@tiptap/core 3.0.0-beta.26 → 3.0.0-beta.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/prosemirror-model@1.24.1/node_modules/prosemirror-model/dist/index.js","../../../node_modules/.pnpm/html@1.0.0/node_modules/html/lib/html.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/empty.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/tslib@2.6.2/node_modules/tslib/tslib.es6.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte@4.2.15/node_modules/svelte/src/runtime/internal/utils.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte@4.2.15/node_modules/svelte/src/runtime/internal/dom.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte@4.2.15/node_modules/svelte/src/runtime/internal/lifecycle.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte@4.2.15/node_modules/svelte/src/runtime/internal/scheduler.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte@4.2.15/node_modules/svelte/src/runtime/internal/transitions.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte@4.2.15/node_modules/svelte/src/runtime/internal/each.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte@4.2.15/node_modules/svelte/src/runtime/internal/Component.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte@4.2.15/node_modules/svelte/src/shared/version.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte@4.2.15/node_modules/svelte/src/runtime/internal/disclose-version/index.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/context.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte@4.2.15/node_modules/svelte/src/runtime/store/index.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/stores/snapshots.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/components/clickOutside.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/diff-match-patch@1.0.5/node_modules/diff-match-patch/index.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/jsondiffpatch@0.4.1/node_modules/jsondiffpatch/dist/jsondiffpatch.esm.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/history-and-diff/diff.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/history-and-diff/transaction.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/history-and-diff/createHistoryEntry.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/stores/stateHistory.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/tabs/state/getActiveMarks.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/tabs/state/selection.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte-tree-view@1.4.2_svelte@4.2.15/node_modules/svelte-tree-view/pkg/tree-utils.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte-tree-view@1.4.2_svelte@4.2.15/node_modules/svelte-tree-view/pkg/stores/props.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte-tree-view@1.4.2_svelte@4.2.15/node_modules/svelte-tree-view/pkg/stores/root-element.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/.pnpm/svelte-tree-view@1.4.2_svelte@4.2.15/node_modules/svelte-tree-view/pkg/stores/tree.js","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/tabs/history/mapDeltas.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/tabs/structure/colors.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/history-and-diff/subscribeToTransactions.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/createOrFindPlace.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/ProseMirrorDevToolkit.ts","../../../node_modules/.pnpm/prosemirror-dev-toolkit@1.1.8_svelte@4.2.19/node_modules/prosemirror-dev-toolkit/src/applyDevTools.ts","../src/index.ts","../src/helpers/createChainableState.ts","../src/CommandManager.ts","../src/Editor.ts","../src/EventEmitter.ts","../src/ExtensionManager.ts","../src/helpers/combineTransactionSteps.ts","../src/helpers/createNodeFromContent.ts","../src/utilities/elementFromString.ts","../src/helpers/createDocument.ts","../src/helpers/defaultBlockAt.ts","../src/helpers/findChildren.ts","../src/helpers/findChildrenInRange.ts","../src/helpers/findParentNodeClosestToPos.ts","../src/helpers/findParentNode.ts","../src/helpers/getExtensionField.ts","../src/helpers/flattenExtensions.ts","../src/helpers/generateHTML.ts","../src/helpers/getHTMLFromFragment.ts","../src/helpers/getSchemaByResolvedExtensions.ts","../src/utilities/isFunction.ts","../src/utilities/callOrReturn.ts","../src/utilities/isEmptyObject.ts","../src/helpers/splitExtensions.ts","../src/helpers/getAttributesFromExtensions.ts","../src/utilities/mergeAttributes.ts","../src/helpers/getRenderedAttributes.ts","../src/utilities/fromString.ts","../src/helpers/injectExtensionAttributesToParseRule.ts","../src/utilities/findDuplicates.ts","../src/helpers/sortExtensions.ts","../src/helpers/resolveExtensions.ts","../src/helpers/getSchema.ts","../src/helpers/generateJSON.ts","../src/helpers/generateText.ts","../src/helpers/getTextBetween.ts","../src/helpers/getText.ts","../src/helpers/getTextSerializersFromSchema.ts","../src/helpers/getMarkType.ts","../src/helpers/getMarkAttributes.ts","../src/helpers/getNodeType.ts","../src/helpers/getNodeAttributes.ts","../src/helpers/getSchemaTypeNameByName.ts","../src/helpers/getAttributes.ts","../src/utilities/removeDuplicates.ts","../src/helpers/getChangedRanges.ts","../src/helpers/getDebugJSON.ts","../src/utilities/isRegExp.ts","../src/utilities/objectIncludes.ts","../src/helpers/getMarkRange.ts","../src/helpers/getMarksBetween.ts","../src/helpers/getNodeAtPosition.ts","../src/helpers/getSchemaTypeByName.ts","../src/helpers/getSplittedAttributes.ts","../src/helpers/getTextContentFromNodes.ts","../src/helpers/isMarkActive.ts","../src/helpers/isNodeActive.ts","../src/helpers/isActive.ts","../src/helpers/isAtEndOfNode.ts","../src/helpers/isAtStartOfNode.ts","../src/helpers/isExtensionRulesEnabled.ts","../src/helpers/isList.ts","../src/helpers/isNodeEmpty.ts","../src/helpers/isNodeSelection.ts","../src/helpers/isTextSelection.ts","../src/utilities/minMax.ts","../src/helpers/posToDOMRect.ts","../src/helpers/resolveFocusPosition.ts","../src/helpers/rewriteUnknownContent.ts","../src/helpers/selectionToInsertionEnd.ts","../src/InputRule.ts","../src/utilities/isPlainObject.ts","../src/utilities/mergeDeep.ts","../src/Extendable.ts","../src/Mark.ts","../src/PasteRule.ts","../src/utilities/isNumber.ts","../src/extensions/index.ts","../src/extensions/clipboardTextSerializer.ts","../src/Extension.ts","../src/commands/index.ts","../src/commands/blur.ts","../src/commands/clearContent.ts","../src/commands/clearNodes.ts","../src/commands/command.ts","../src/commands/createParagraphNear.ts","../src/commands/cut.ts","../src/commands/deleteCurrentNode.ts","../src/commands/deleteNode.ts","../src/commands/deleteRange.ts","../src/commands/deleteSelection.ts","../src/commands/enter.ts","../src/commands/exitCode.ts","../src/commands/extendMarkRange.ts","../src/commands/first.ts","../src/utilities/isAndroid.ts","../src/utilities/isiOS.ts","../src/commands/focus.ts","../src/commands/forEach.ts","../src/commands/insertContent.ts","../src/commands/insertContentAt.ts","../src/commands/join.ts","../src/commands/joinItemBackward.ts","../src/commands/joinItemForward.ts","../src/commands/joinTextblockBackward.ts","../src/commands/joinTextblockForward.ts","../src/utilities/isMacOS.ts","../src/commands/keyboardShortcut.ts","../src/commands/lift.ts","../src/commands/liftEmptyBlock.ts","../src/commands/liftListItem.ts","../src/commands/newlineInCode.ts","../src/utilities/deleteProps.ts","../src/commands/resetAttributes.ts","../src/commands/scrollIntoView.ts","../src/commands/selectAll.ts","../src/commands/selectNodeBackward.ts","../src/commands/selectNodeForward.ts","../src/commands/selectParentNode.ts","../src/commands/selectTextblockEnd.ts","../src/commands/selectTextblockStart.ts","../src/commands/setContent.ts","../src/commands/setMark.ts","../src/commands/setMeta.ts","../src/commands/setNode.ts","../src/commands/setNodeSelection.ts","../src/commands/setTextSelection.ts","../src/commands/sinkListItem.ts","../src/commands/splitBlock.ts","../src/commands/splitListItem.ts","../src/commands/toggleList.ts","../src/commands/toggleMark.ts","../src/commands/toggleNode.ts","../src/commands/toggleWrap.ts","../src/commands/undoInputRule.ts","../src/commands/unsetAllMarks.ts","../src/commands/unsetMark.ts","../src/commands/updateAttributes.ts","../src/commands/wrapIn.ts","../src/commands/wrapInList.ts","../src/extensions/commands.ts","../src/extensions/delete.ts","../src/extensions/drop.ts","../src/extensions/editable.ts","../src/extensions/focusEvents.ts","../src/extensions/keymap.ts","../src/extensions/paste.ts","../src/extensions/tabindex.ts","../src/NodePos.ts","../src/style.ts","../src/utilities/createStyleTag.ts","../src/inputRules/markInputRule.ts","../src/inputRules/nodeInputRule.ts","../src/inputRules/textblockTypeInputRule.ts","../src/inputRules/textInputRule.ts","../src/inputRules/wrappingInputRule.ts","../src/jsx-runtime.ts","../src/utilities/canInsertNode.ts","../src/utilities/escapeForRegEx.ts","../src/utilities/isString.ts","../src/MarkView.ts","../src/Node.ts","../src/NodeView.ts","../src/pasteRules/markPasteRule.ts","../src/pasteRules/nodePasteRule.ts","../src/pasteRules/textPasteRule.ts","../src/Tracker.ts"],"sourcesContent":["import OrderedMap from 'orderedmap';\n\nfunction findDiffStart(a, b, pos) {\n for (let i = 0;; i++) {\n if (i == a.childCount || i == b.childCount)\n return a.childCount == b.childCount ? null : pos;\n let childA = a.child(i), childB = b.child(i);\n if (childA == childB) {\n pos += childA.nodeSize;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return pos;\n if (childA.isText && childA.text != childB.text) {\n for (let j = 0; childA.text[j] == childB.text[j]; j++)\n pos++;\n return pos;\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffStart(childA.content, childB.content, pos + 1);\n if (inner != null)\n return inner;\n }\n pos += childA.nodeSize;\n }\n}\nfunction findDiffEnd(a, b, posA, posB) {\n for (let iA = a.childCount, iB = b.childCount;;) {\n if (iA == 0 || iB == 0)\n return iA == iB ? null : { a: posA, b: posB };\n let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;\n if (childA == childB) {\n posA -= size;\n posB -= size;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return { a: posA, b: posB };\n if (childA.isText && childA.text != childB.text) {\n let same = 0, minSize = Math.min(childA.text.length, childB.text.length);\n while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {\n same++;\n posA--;\n posB--;\n }\n return { a: posA, b: posB };\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n if (inner)\n return inner;\n }\n posA -= size;\n posB -= size;\n }\n}\n\n/**\nA fragment represents a node's collection of child nodes.\n\nLike nodes, fragments are persistent data structures, and you\nshould not mutate them or their content. Rather, you create new\ninstances whenever needed. The API tries to make this easy.\n*/\nclass Fragment {\n /**\n @internal\n */\n constructor(\n /**\n The child nodes in this fragment.\n */\n content, size) {\n this.content = content;\n this.size = size || 0;\n if (size == null)\n for (let i = 0; i < content.length; i++)\n this.size += content[i].nodeSize;\n }\n /**\n Invoke a callback for all descendant nodes between the given two\n positions (relative to start of this fragment). Doesn't descend\n into a node when the callback returns `false`.\n */\n nodesBetween(from, to, f, nodeStart = 0, parent) {\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {\n let start = pos + 1;\n child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);\n }\n pos = end;\n }\n }\n /**\n Call the given callback for every descendant node. `pos` will be\n relative to the start of the fragment. The callback may return\n `false` to prevent traversal of a given node's children.\n */\n descendants(f) {\n this.nodesBetween(0, this.size, f);\n }\n /**\n Extract the text between `from` and `to`. See the same method on\n [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).\n */\n textBetween(from, to, blockSeparator, leafText) {\n let text = \"\", first = true;\n this.nodesBetween(from, to, (node, pos) => {\n let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos)\n : !node.isLeaf ? \"\"\n : leafText ? (typeof leafText === \"function\" ? leafText(node) : leafText)\n : node.type.spec.leafText ? node.type.spec.leafText(node)\n : \"\";\n if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {\n if (first)\n first = false;\n else\n text += blockSeparator;\n }\n text += nodeText;\n }, 0);\n return text;\n }\n /**\n Create a new fragment containing the combined content of this\n fragment and the other.\n */\n append(other) {\n if (!other.size)\n return this;\n if (!this.size)\n return other;\n let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;\n if (last.isText && last.sameMarkup(first)) {\n content[content.length - 1] = last.withText(last.text + first.text);\n i = 1;\n }\n for (; i < other.content.length; i++)\n content.push(other.content[i]);\n return new Fragment(content, this.size + other.size);\n }\n /**\n Cut out the sub-fragment between the two given positions.\n */\n cut(from, to = this.size) {\n if (from == 0 && to == this.size)\n return this;\n let result = [], size = 0;\n if (to > from)\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from) {\n if (pos < from || end > to) {\n if (child.isText)\n child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));\n else\n child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));\n }\n result.push(child);\n size += child.nodeSize;\n }\n pos = end;\n }\n return new Fragment(result, size);\n }\n /**\n @internal\n */\n cutByIndex(from, to) {\n if (from == to)\n return Fragment.empty;\n if (from == 0 && to == this.content.length)\n return this;\n return new Fragment(this.content.slice(from, to));\n }\n /**\n Create a new fragment in which the node at the given index is\n replaced by the given node.\n */\n replaceChild(index, node) {\n let current = this.content[index];\n if (current == node)\n return this;\n let copy = this.content.slice();\n let size = this.size + node.nodeSize - current.nodeSize;\n copy[index] = node;\n return new Fragment(copy, size);\n }\n /**\n Create a new fragment by prepending the given node to this\n fragment.\n */\n addToStart(node) {\n return new Fragment([node].concat(this.content), this.size + node.nodeSize);\n }\n /**\n Create a new fragment by appending the given node to this\n fragment.\n */\n addToEnd(node) {\n return new Fragment(this.content.concat(node), this.size + node.nodeSize);\n }\n /**\n Compare this fragment to another one.\n */\n eq(other) {\n if (this.content.length != other.content.length)\n return false;\n for (let i = 0; i < this.content.length; i++)\n if (!this.content[i].eq(other.content[i]))\n return false;\n return true;\n }\n /**\n The first child of the fragment, or `null` if it is empty.\n */\n get firstChild() { return this.content.length ? this.content[0] : null; }\n /**\n The last child of the fragment, or `null` if it is empty.\n */\n get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }\n /**\n The number of child nodes in this fragment.\n */\n get childCount() { return this.content.length; }\n /**\n Get the child node at the given index. Raise an error when the\n index is out of range.\n */\n child(index) {\n let found = this.content[index];\n if (!found)\n throw new RangeError(\"Index \" + index + \" out of range for \" + this);\n return found;\n }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) {\n return this.content[index] || null;\n }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) {\n for (let i = 0, p = 0; i < this.content.length; i++) {\n let child = this.content[i];\n f(child, p, i);\n p += child.nodeSize;\n }\n }\n /**\n Find the first position at which this fragment and another\n fragment differ, or `null` if they are the same.\n */\n findDiffStart(other, pos = 0) {\n return findDiffStart(this, other, pos);\n }\n /**\n Find the first position, searching from the end, at which this\n fragment and the given fragment differ, or `null` if they are\n the same. Since this position will not be the same in both\n nodes, an object with two separate positions is returned.\n */\n findDiffEnd(other, pos = this.size, otherPos = other.size) {\n return findDiffEnd(this, other, pos, otherPos);\n }\n /**\n Find the index and inner offset corresponding to a given relative\n position in this fragment. The result object will be reused\n (overwritten) the next time the function is called. @internal\n */\n findIndex(pos, round = -1) {\n if (pos == 0)\n return retIndex(0, pos);\n if (pos == this.size)\n return retIndex(this.content.length, pos);\n if (pos > this.size || pos < 0)\n throw new RangeError(`Position ${pos} outside of fragment (${this})`);\n for (let i = 0, curPos = 0;; i++) {\n let cur = this.child(i), end = curPos + cur.nodeSize;\n if (end >= pos) {\n if (end == pos || round > 0)\n return retIndex(i + 1, end);\n return retIndex(i, curPos);\n }\n curPos = end;\n }\n }\n /**\n Return a debugging string that describes this fragment.\n */\n toString() { return \"<\" + this.toStringInner() + \">\"; }\n /**\n @internal\n */\n toStringInner() { return this.content.join(\", \"); }\n /**\n Create a JSON-serializeable representation of this fragment.\n */\n toJSON() {\n return this.content.length ? this.content.map(n => n.toJSON()) : null;\n }\n /**\n Deserialize a fragment from its JSON representation.\n */\n static fromJSON(schema, value) {\n if (!value)\n return Fragment.empty;\n if (!Array.isArray(value))\n throw new RangeError(\"Invalid input for Fragment.fromJSON\");\n return new Fragment(value.map(schema.nodeFromJSON));\n }\n /**\n Build a fragment from an array of nodes. Ensures that adjacent\n text nodes with the same marks are joined together.\n */\n static fromArray(array) {\n if (!array.length)\n return Fragment.empty;\n let joined, size = 0;\n for (let i = 0; i < array.length; i++) {\n let node = array[i];\n size += node.nodeSize;\n if (i && node.isText && array[i - 1].sameMarkup(node)) {\n if (!joined)\n joined = array.slice(0, i);\n joined[joined.length - 1] = node\n .withText(joined[joined.length - 1].text + node.text);\n }\n else if (joined) {\n joined.push(node);\n }\n }\n return new Fragment(joined || array, size);\n }\n /**\n Create a fragment from something that can be interpreted as a\n set of nodes. For `null`, it returns the empty fragment. For a\n fragment, the fragment itself. For a node or array of nodes, a\n fragment containing those nodes.\n */\n static from(nodes) {\n if (!nodes)\n return Fragment.empty;\n if (nodes instanceof Fragment)\n return nodes;\n if (Array.isArray(nodes))\n return this.fromArray(nodes);\n if (nodes.attrs)\n return new Fragment([nodes], nodes.nodeSize);\n throw new RangeError(\"Can not convert \" + nodes + \" to a Fragment\" +\n (nodes.nodesBetween ? \" (looks like multiple versions of prosemirror-model were loaded)\" : \"\"));\n }\n}\n/**\nAn empty fragment. Intended to be reused whenever a node doesn't\ncontain anything (rather than allocating a new empty fragment for\neach leaf node).\n*/\nFragment.empty = new Fragment([], 0);\nconst found = { index: 0, offset: 0 };\nfunction retIndex(index, offset) {\n found.index = index;\n found.offset = offset;\n return found;\n}\n\nfunction compareDeep(a, b) {\n if (a === b)\n return true;\n if (!(a && typeof a == \"object\") ||\n !(b && typeof b == \"object\"))\n return false;\n let array = Array.isArray(a);\n if (Array.isArray(b) != array)\n return false;\n if (array) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!compareDeep(a[i], b[i]))\n return false;\n }\n else {\n for (let p in a)\n if (!(p in b) || !compareDeep(a[p], b[p]))\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n }\n return true;\n}\n\n/**\nA mark is a piece of information that can be attached to a node,\nsuch as it being emphasized, in code font, or a link. It has a\ntype and optionally a set of attributes that provide further\ninformation (such as the target of the link). Marks are created\nthrough a `Schema`, which controls which types exist and which\nattributes they have.\n*/\nclass Mark {\n /**\n @internal\n */\n constructor(\n /**\n The type of this mark.\n */\n type, \n /**\n The attributes associated with this mark.\n */\n attrs) {\n this.type = type;\n this.attrs = attrs;\n }\n /**\n Given a set of marks, create a new set which contains this one as\n well, in the right position. If this mark is already in the set,\n the set itself is returned. If any marks that are set to be\n [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,\n those are replaced by this one.\n */\n addToSet(set) {\n let copy, placed = false;\n for (let i = 0; i < set.length; i++) {\n let other = set[i];\n if (this.eq(other))\n return set;\n if (this.type.excludes(other.type)) {\n if (!copy)\n copy = set.slice(0, i);\n }\n else if (other.type.excludes(this.type)) {\n return set;\n }\n else {\n if (!placed && other.type.rank > this.type.rank) {\n if (!copy)\n copy = set.slice(0, i);\n copy.push(this);\n placed = true;\n }\n if (copy)\n copy.push(other);\n }\n }\n if (!copy)\n copy = set.slice();\n if (!placed)\n copy.push(this);\n return copy;\n }\n /**\n Remove this mark from the given set, returning a new set. If this\n mark is not in the set, the set itself is returned.\n */\n removeFromSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return set.slice(0, i).concat(set.slice(i + 1));\n return set;\n }\n /**\n Test whether this mark is in the given set of marks.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return true;\n return false;\n }\n /**\n Test whether this mark has the same type and attributes as\n another mark.\n */\n eq(other) {\n return this == other ||\n (this.type == other.type && compareDeep(this.attrs, other.attrs));\n }\n /**\n Convert this mark to a JSON-serializeable representation.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n return obj;\n }\n /**\n Deserialize a mark from JSON.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Mark.fromJSON\");\n let type = schema.marks[json.type];\n if (!type)\n throw new RangeError(`There is no mark type ${json.type} in this schema`);\n let mark = type.create(json.attrs);\n type.checkAttrs(mark.attrs);\n return mark;\n }\n /**\n Test whether two sets of marks are identical.\n */\n static sameSet(a, b) {\n if (a == b)\n return true;\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].eq(b[i]))\n return false;\n return true;\n }\n /**\n Create a properly sorted mark set from null, a single mark, or an\n unsorted array of marks.\n */\n static setFrom(marks) {\n if (!marks || Array.isArray(marks) && marks.length == 0)\n return Mark.none;\n if (marks instanceof Mark)\n return [marks];\n let copy = marks.slice();\n copy.sort((a, b) => a.type.rank - b.type.rank);\n return copy;\n }\n}\n/**\nThe empty set of marks.\n*/\nMark.none = [];\n\n/**\nError type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when\ngiven an invalid replacement.\n*/\nclass ReplaceError extends Error {\n}\n/*\nReplaceError = function(this: any, message: string) {\n let err = Error.call(this, message)\n ;(err as any).__proto__ = ReplaceError.prototype\n return err\n} as any\n\nReplaceError.prototype = Object.create(Error.prototype)\nReplaceError.prototype.constructor = ReplaceError\nReplaceError.prototype.name = \"ReplaceError\"\n*/\n/**\nA slice represents a piece cut out of a larger document. It\nstores not only a fragment, but also the depth up to which nodes on\nboth side are ‘open’ (cut through).\n*/\nclass Slice {\n /**\n Create a slice. When specifying a non-zero open depth, you must\n make sure that there are nodes of at least that depth at the\n appropriate side of the fragment—i.e. if the fragment is an\n empty paragraph node, `openStart` and `openEnd` can't be greater\n than 1.\n \n It is not necessary for the content of open nodes to conform to\n the schema's content constraints, though it should be a valid\n start/end/middle for such a node, depending on which sides are\n open.\n */\n constructor(\n /**\n The slice's content.\n */\n content, \n /**\n The open depth at the start of the fragment.\n */\n openStart, \n /**\n The open depth at the end.\n */\n openEnd) {\n this.content = content;\n this.openStart = openStart;\n this.openEnd = openEnd;\n }\n /**\n The size this slice would add when inserted into a document.\n */\n get size() {\n return this.content.size - this.openStart - this.openEnd;\n }\n /**\n @internal\n */\n insertAt(pos, fragment) {\n let content = insertInto(this.content, pos + this.openStart, fragment);\n return content && new Slice(content, this.openStart, this.openEnd);\n }\n /**\n @internal\n */\n removeBetween(from, to) {\n return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);\n }\n /**\n Tests whether this slice is equal to another slice.\n */\n eq(other) {\n return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;\n }\n /**\n @internal\n */\n toString() {\n return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\";\n }\n /**\n Convert a slice to a JSON-serializable representation.\n */\n toJSON() {\n if (!this.content.size)\n return null;\n let json = { content: this.content.toJSON() };\n if (this.openStart > 0)\n json.openStart = this.openStart;\n if (this.openEnd > 0)\n json.openEnd = this.openEnd;\n return json;\n }\n /**\n Deserialize a slice from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n return Slice.empty;\n let openStart = json.openStart || 0, openEnd = json.openEnd || 0;\n if (typeof openStart != \"number\" || typeof openEnd != \"number\")\n throw new RangeError(\"Invalid input for Slice.fromJSON\");\n return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);\n }\n /**\n Create a slice from a fragment by taking the maximum possible\n open value on both side of the fragment.\n */\n static maxOpen(fragment, openIsolating = true) {\n let openStart = 0, openEnd = 0;\n for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)\n openStart++;\n for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)\n openEnd++;\n return new Slice(fragment, openStart, openEnd);\n }\n}\n/**\nThe empty slice.\n*/\nSlice.empty = new Slice(Fragment.empty, 0, 0);\nfunction removeRange(content, from, to) {\n let { index, offset } = content.findIndex(from), child = content.maybeChild(index);\n let { index: indexTo, offset: offsetTo } = content.findIndex(to);\n if (offset == from || child.isText) {\n if (offsetTo != to && !content.child(indexTo).isText)\n throw new RangeError(\"Removing non-flat range\");\n return content.cut(0, from).append(content.cut(to));\n }\n if (index != indexTo)\n throw new RangeError(\"Removing non-flat range\");\n return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));\n}\nfunction insertInto(content, dist, insert, parent) {\n let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);\n if (offset == dist || child.isText) {\n if (parent && !parent.canReplace(index, index, insert))\n return null;\n return content.cut(0, dist).append(insert).append(content.cut(dist));\n }\n let inner = insertInto(child.content, dist - offset - 1, insert);\n return inner && content.replaceChild(index, child.copy(inner));\n}\nfunction replace($from, $to, slice) {\n if (slice.openStart > $from.depth)\n throw new ReplaceError(\"Inserted content deeper than insertion position\");\n if ($from.depth - slice.openStart != $to.depth - slice.openEnd)\n throw new ReplaceError(\"Inconsistent open depths\");\n return replaceOuter($from, $to, slice, 0);\n}\nfunction replaceOuter($from, $to, slice, depth) {\n let index = $from.index(depth), node = $from.node(depth);\n if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n let inner = replaceOuter($from, $to, slice, depth + 1);\n return node.copy(node.content.replaceChild(index, inner));\n }\n else if (!slice.content.size) {\n return close(node, replaceTwoWay($from, $to, depth));\n }\n else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case\n let parent = $from.parent, content = parent.content;\n return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));\n }\n else {\n let { start, end } = prepareSliceForReplace(slice, $from);\n return close(node, replaceThreeWay($from, start, end, $to, depth));\n }\n}\nfunction checkJoin(main, sub) {\n if (!sub.type.compatibleContent(main.type))\n throw new ReplaceError(\"Cannot join \" + sub.type.name + \" onto \" + main.type.name);\n}\nfunction joinable($before, $after, depth) {\n let node = $before.node(depth);\n checkJoin(node, $after.node(depth));\n return node;\n}\nfunction addNode(child, target) {\n let last = target.length - 1;\n if (last >= 0 && child.isText && child.sameMarkup(target[last]))\n target[last] = child.withText(target[last].text + child.text);\n else\n target.push(child);\n}\nfunction addRange($start, $end, depth, target) {\n let node = ($end || $start).node(depth);\n let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;\n if ($start) {\n startIndex = $start.index(depth);\n if ($start.depth > depth) {\n startIndex++;\n }\n else if ($start.textOffset) {\n addNode($start.nodeAfter, target);\n startIndex++;\n }\n }\n for (let i = startIndex; i < endIndex; i++)\n addNode(node.child(i), target);\n if ($end && $end.depth == depth && $end.textOffset)\n addNode($end.nodeBefore, target);\n}\nfunction close(node, content) {\n node.type.checkContent(content);\n return node.copy(content);\n}\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n let openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n let content = [];\n addRange(null, $from, depth, content);\n if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {\n checkJoin(openStart, openEnd);\n addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);\n }\n else {\n if (openStart)\n addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);\n addRange($start, $end, depth, content);\n if (openEnd)\n addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction replaceTwoWay($from, $to, depth) {\n let content = [];\n addRange(null, $from, depth, content);\n if ($from.depth > depth) {\n let type = joinable($from, $to, depth + 1);\n addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction prepareSliceForReplace(slice, $along) {\n let extra = $along.depth - slice.openStart, parent = $along.node(extra);\n let node = parent.copy(slice.content);\n for (let i = extra - 1; i >= 0; i--)\n node = $along.node(i).copy(Fragment.from(node));\n return { start: node.resolveNoCache(slice.openStart + extra),\n end: node.resolveNoCache(node.content.size - slice.openEnd - extra) };\n}\n\n/**\nYou can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more\ninformation about it. Objects of this class represent such a\nresolved position, providing various pieces of context\ninformation, and some helper methods.\n\nThroughout this interface, methods that take an optional `depth`\nparameter will interpret undefined as `this.depth` and negative\nnumbers as `this.depth + value`.\n*/\nclass ResolvedPos {\n /**\n @internal\n */\n constructor(\n /**\n The position that was resolved.\n */\n pos, \n /**\n @internal\n */\n path, \n /**\n The offset this position has into its parent node.\n */\n parentOffset) {\n this.pos = pos;\n this.path = path;\n this.parentOffset = parentOffset;\n this.depth = path.length / 3 - 1;\n }\n /**\n @internal\n */\n resolveDepth(val) {\n if (val == null)\n return this.depth;\n if (val < 0)\n return this.depth + val;\n return val;\n }\n /**\n The parent node that the position points into. Note that even if\n a position points into a text node, that node is not considered\n the parent—text nodes are ‘flat’ in this model, and have no content.\n */\n get parent() { return this.node(this.depth); }\n /**\n The root node in which the position was resolved.\n */\n get doc() { return this.node(0); }\n /**\n The ancestor node at the given level. `p.node(p.depth)` is the\n same as `p.parent`.\n */\n node(depth) { return this.path[this.resolveDepth(depth) * 3]; }\n /**\n The index into the ancestor at the given level. If this points\n at the 3rd node in the 2nd paragraph on the top level, for\n example, `p.index(0)` is 1 and `p.index(1)` is 2.\n */\n index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; }\n /**\n The index pointing after this position into the ancestor at the\n given level.\n */\n indexAfter(depth) {\n depth = this.resolveDepth(depth);\n return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);\n }\n /**\n The (absolute) position at the start of the node at the given\n level.\n */\n start(depth) {\n depth = this.resolveDepth(depth);\n return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n }\n /**\n The (absolute) position at the end of the node at the given\n level.\n */\n end(depth) {\n depth = this.resolveDepth(depth);\n return this.start(depth) + this.node(depth).content.size;\n }\n /**\n The (absolute) position directly before the wrapping node at the\n given level, or, when `depth` is `this.depth + 1`, the original\n position.\n */\n before(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position before the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];\n }\n /**\n The (absolute) position directly after the wrapping node at the\n given level, or the original position when `depth` is `this.depth + 1`.\n */\n after(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position after the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;\n }\n /**\n When this position points into a text node, this returns the\n distance between the position and the start of the text node.\n Will be zero for positions that point between nodes.\n */\n get textOffset() { return this.pos - this.path[this.path.length - 1]; }\n /**\n Get the node directly after the position, if any. If the position\n points into a text node, only the part of that node after the\n position is returned.\n */\n get nodeAfter() {\n let parent = this.parent, index = this.index(this.depth);\n if (index == parent.childCount)\n return null;\n let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);\n return dOff ? parent.child(index).cut(dOff) : child;\n }\n /**\n Get the node directly before the position, if any. If the\n position points into a text node, only the part of that node\n before the position is returned.\n */\n get nodeBefore() {\n let index = this.index(this.depth);\n let dOff = this.pos - this.path[this.path.length - 1];\n if (dOff)\n return this.parent.child(index).cut(0, dOff);\n return index == 0 ? null : this.parent.child(index - 1);\n }\n /**\n Get the position at the given index in the parent node at the\n given depth (which defaults to `this.depth`).\n */\n posAtIndex(index, depth) {\n depth = this.resolveDepth(depth);\n let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n for (let i = 0; i < index; i++)\n pos += node.child(i).nodeSize;\n return pos;\n }\n /**\n Get the marks at this position, factoring in the surrounding\n marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the\n position is at the start of a non-empty node, the marks of the\n node after it (if any) are returned.\n */\n marks() {\n let parent = this.parent, index = this.index();\n // In an empty parent, return the empty array\n if (parent.content.size == 0)\n return Mark.none;\n // When inside a text node, just return the text node's marks\n if (this.textOffset)\n return parent.child(index).marks;\n let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);\n // If the `after` flag is true of there is no node before, make\n // the node after this position the main reference.\n if (!main) {\n let tmp = main;\n main = other;\n other = tmp;\n }\n // Use all marks in the main node, except those that have\n // `inclusive` set to false and are not present in the other node.\n let marks = main.marks;\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n Get the marks after the current position, if any, except those\n that are non-inclusive and not present at position `$end`. This\n is mostly useful for getting the set of marks to preserve after a\n deletion. Will return `null` if this position is at the end of\n its parent node or its parent node isn't a textblock (in which\n case no marks should be preserved).\n */\n marksAcross($end) {\n let after = this.parent.maybeChild(this.index());\n if (!after || !after.isInline)\n return null;\n let marks = after.marks, next = $end.parent.maybeChild($end.index());\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n The depth up to which this position and the given (non-resolved)\n position share the same parent nodes.\n */\n sharedDepth(pos) {\n for (let depth = this.depth; depth > 0; depth--)\n if (this.start(depth) <= pos && this.end(depth) >= pos)\n return depth;\n return 0;\n }\n /**\n Returns a range based on the place where this position and the\n given position diverge around block content. If both point into\n the same textblock, for example, a range around that textblock\n will be returned. If they point into different blocks, the range\n around those blocks in their shared ancestor is returned. You can\n pass in an optional predicate that will be called with a parent\n node to see if a range into that parent is acceptable.\n */\n blockRange(other = this, pred) {\n if (other.pos < this.pos)\n return other.blockRange(this);\n for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)\n if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))\n return new NodeRange(this, other, d);\n return null;\n }\n /**\n Query whether the given position shares the same parent node.\n */\n sameParent(other) {\n return this.pos - this.parentOffset == other.pos - other.parentOffset;\n }\n /**\n Return the greater of this and the given position.\n */\n max(other) {\n return other.pos > this.pos ? other : this;\n }\n /**\n Return the smaller of this and the given position.\n */\n min(other) {\n return other.pos < this.pos ? other : this;\n }\n /**\n @internal\n */\n toString() {\n let str = \"\";\n for (let i = 1; i <= this.depth; i++)\n str += (str ? \"/\" : \"\") + this.node(i).type.name + \"_\" + this.index(i - 1);\n return str + \":\" + this.parentOffset;\n }\n /**\n @internal\n */\n static resolve(doc, pos) {\n if (!(pos >= 0 && pos <= doc.content.size))\n throw new RangeError(\"Position \" + pos + \" out of range\");\n let path = [];\n let start = 0, parentOffset = pos;\n for (let node = doc;;) {\n let { index, offset } = node.content.findIndex(parentOffset);\n let rem = parentOffset - offset;\n path.push(node, index, start + offset);\n if (!rem)\n break;\n node = node.child(index);\n if (node.isText)\n break;\n parentOffset = rem - 1;\n start += offset + 1;\n }\n return new ResolvedPos(pos, path, parentOffset);\n }\n /**\n @internal\n */\n static resolveCached(doc, pos) {\n let cache = resolveCache.get(doc);\n if (cache) {\n for (let i = 0; i < cache.elts.length; i++) {\n let elt = cache.elts[i];\n if (elt.pos == pos)\n return elt;\n }\n }\n else {\n resolveCache.set(doc, cache = new ResolveCache);\n }\n let result = cache.elts[cache.i] = ResolvedPos.resolve(doc, pos);\n cache.i = (cache.i + 1) % resolveCacheSize;\n return result;\n }\n}\nclass ResolveCache {\n constructor() {\n this.elts = [];\n this.i = 0;\n }\n}\nconst resolveCacheSize = 12, resolveCache = new WeakMap();\n/**\nRepresents a flat range of content, i.e. one that starts and\nends in the same node.\n*/\nclass NodeRange {\n /**\n Construct a node range. `$from` and `$to` should point into the\n same node until at least the given `depth`, since a node range\n denotes an adjacent set of nodes in a single parent node.\n */\n constructor(\n /**\n A resolved position along the start of the content. May have a\n `depth` greater than this object's `depth` property, since\n these are the positions that were used to compute the range,\n not re-resolved positions directly at its boundaries.\n */\n $from, \n /**\n A position along the end of the content. See\n caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).\n */\n $to, \n /**\n The depth of the node that this range points into.\n */\n depth) {\n this.$from = $from;\n this.$to = $to;\n this.depth = depth;\n }\n /**\n The position at the start of the range.\n */\n get start() { return this.$from.before(this.depth + 1); }\n /**\n The position at the end of the range.\n */\n get end() { return this.$to.after(this.depth + 1); }\n /**\n The parent node that the range points into.\n */\n get parent() { return this.$from.node(this.depth); }\n /**\n The start index of the range in the parent node.\n */\n get startIndex() { return this.$from.index(this.depth); }\n /**\n The end index of the range in the parent node.\n */\n get endIndex() { return this.$to.indexAfter(this.depth); }\n}\n\nconst emptyAttrs = Object.create(null);\n/**\nThis class represents a node in the tree that makes up a\nProseMirror document. So a document is an instance of `Node`, with\nchildren that are also instances of `Node`.\n\nNodes are persistent data structures. Instead of changing them, you\ncreate new ones with the content you want. Old ones keep pointing\nat the old document shape. This is made cheaper by sharing\nstructure between the old and new data as much as possible, which a\ntree shape like this (without back pointers) makes easy.\n\n**Do not** directly mutate the properties of a `Node` object. See\n[the guide](/docs/guide/#doc) for more information.\n*/\nclass Node {\n /**\n @internal\n */\n constructor(\n /**\n The type of node that this is.\n */\n type, \n /**\n An object mapping attribute names to values. The kind of\n attributes allowed and required are\n [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.\n */\n attrs, \n // A fragment holding the node's children.\n content, \n /**\n The marks (things like whether it is emphasized or part of a\n link) applied to this node.\n */\n marks = Mark.none) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.content = content || Fragment.empty;\n }\n /**\n The array of this node's child nodes.\n */\n get children() { return this.content.content; }\n /**\n The size of this node, as defined by the integer-based [indexing\n scheme](/docs/guide/#doc.indexing). For text nodes, this is the\n amount of characters. For other leaf nodes, it is one. For\n non-leaf nodes, it is the size of the content plus two (the\n start and end token).\n */\n get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; }\n /**\n The number of children that the node has.\n */\n get childCount() { return this.content.childCount; }\n /**\n Get the child node at the given index. Raises an error when the\n index is out of range.\n */\n child(index) { return this.content.child(index); }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) { return this.content.maybeChild(index); }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) { this.content.forEach(f); }\n /**\n Invoke a callback for all descendant nodes recursively between\n the given two positions that are relative to start of this\n node's content. The callback is invoked with the node, its\n position relative to the original node (method receiver),\n its parent node, and its child index. When the callback returns\n false for a given node, that node's children will not be\n recursed over. The last parameter can be used to specify a\n starting position to count from.\n */\n nodesBetween(from, to, f, startPos = 0) {\n this.content.nodesBetween(from, to, f, startPos, this);\n }\n /**\n Call the given callback for every descendant node. Doesn't\n descend into a node when the callback returns `false`.\n */\n descendants(f) {\n this.nodesBetween(0, this.content.size, f);\n }\n /**\n Concatenates all the text nodes found in this fragment and its\n children.\n */\n get textContent() {\n return (this.isLeaf && this.type.spec.leafText)\n ? this.type.spec.leafText(this)\n : this.textBetween(0, this.content.size, \"\");\n }\n /**\n Get all text between positions `from` and `to`. When\n `blockSeparator` is given, it will be inserted to separate text\n from different block nodes. If `leafText` is given, it'll be\n inserted for every non-text leaf node encountered, otherwise\n [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec^leafText) will be used.\n */\n textBetween(from, to, blockSeparator, leafText) {\n return this.content.textBetween(from, to, blockSeparator, leafText);\n }\n /**\n Returns this node's first child, or `null` if there are no\n children.\n */\n get firstChild() { return this.content.firstChild; }\n /**\n Returns this node's last child, or `null` if there are no\n children.\n */\n get lastChild() { return this.content.lastChild; }\n /**\n Test whether two nodes represent the same piece of document.\n */\n eq(other) {\n return this == other || (this.sameMarkup(other) && this.content.eq(other.content));\n }\n /**\n Compare the markup (type, attributes, and marks) of this node to\n those of another. Returns `true` if both have the same markup.\n */\n sameMarkup(other) {\n return this.hasMarkup(other.type, other.attrs, other.marks);\n }\n /**\n Check whether this node's markup correspond to the given type,\n attributes, and marks.\n */\n hasMarkup(type, attrs, marks) {\n return this.type == type &&\n compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&\n Mark.sameSet(this.marks, marks || Mark.none);\n }\n /**\n Create a new node with the same markup as this node, containing\n the given content (or empty, if no content is given).\n */\n copy(content = null) {\n if (content == this.content)\n return this;\n return new Node(this.type, this.attrs, content, this.marks);\n }\n /**\n Create a copy of this node, with the given set of marks instead\n of the node's own marks.\n */\n mark(marks) {\n return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);\n }\n /**\n Create a copy of this node with only the content between the\n given positions. If `to` is not given, it defaults to the end of\n the node.\n */\n cut(from, to = this.content.size) {\n if (from == 0 && to == this.content.size)\n return this;\n return this.copy(this.content.cut(from, to));\n }\n /**\n Cut out the part of the document between the given positions, and\n return it as a `Slice` object.\n */\n slice(from, to = this.content.size, includeParents = false) {\n if (from == to)\n return Slice.empty;\n let $from = this.resolve(from), $to = this.resolve(to);\n let depth = includeParents ? 0 : $from.sharedDepth(to);\n let start = $from.start(depth), node = $from.node(depth);\n let content = node.content.cut($from.pos - start, $to.pos - start);\n return new Slice(content, $from.depth - depth, $to.depth - depth);\n }\n /**\n Replace the part of the document between the given positions with\n the given slice. The slice must 'fit', meaning its open sides\n must be able to connect to the surrounding content, and its\n content nodes must be valid children for the node they are placed\n into. If any of this is violated, an error of type\n [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.\n */\n replace(from, to, slice) {\n return replace(this.resolve(from), this.resolve(to), slice);\n }\n /**\n Find the node directly after the given position.\n */\n nodeAt(pos) {\n for (let node = this;;) {\n let { index, offset } = node.content.findIndex(pos);\n node = node.maybeChild(index);\n if (!node)\n return null;\n if (offset == pos || node.isText)\n return node;\n pos -= offset + 1;\n }\n }\n /**\n Find the (direct) child node after the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childAfter(pos) {\n let { index, offset } = this.content.findIndex(pos);\n return { node: this.content.maybeChild(index), index, offset };\n }\n /**\n Find the (direct) child node before the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childBefore(pos) {\n if (pos == 0)\n return { node: null, index: 0, offset: 0 };\n let { index, offset } = this.content.findIndex(pos);\n if (offset < pos)\n return { node: this.content.child(index), index, offset };\n let node = this.content.child(index - 1);\n return { node, index: index - 1, offset: offset - node.nodeSize };\n }\n /**\n Resolve the given position in the document, returning an\n [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.\n */\n resolve(pos) { return ResolvedPos.resolveCached(this, pos); }\n /**\n @internal\n */\n resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); }\n /**\n Test whether a given mark or mark type occurs in this document\n between the two given positions.\n */\n rangeHasMark(from, to, type) {\n let found = false;\n if (to > from)\n this.nodesBetween(from, to, node => {\n if (type.isInSet(node.marks))\n found = true;\n return !found;\n });\n return found;\n }\n /**\n True when this is a block (non-inline node)\n */\n get isBlock() { return this.type.isBlock; }\n /**\n True when this is a textblock node, a block node with inline\n content.\n */\n get isTextblock() { return this.type.isTextblock; }\n /**\n True when this node allows inline content.\n */\n get inlineContent() { return this.type.inlineContent; }\n /**\n True when this is an inline node (a text node or a node that can\n appear among text).\n */\n get isInline() { return this.type.isInline; }\n /**\n True when this is a text node.\n */\n get isText() { return this.type.isText; }\n /**\n True when this is a leaf node.\n */\n get isLeaf() { return this.type.isLeaf; }\n /**\n True when this is an atom, i.e. when it does not have directly\n editable content. This is usually the same as `isLeaf`, but can\n be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)\n on a node's spec (typically used when the node is displayed as\n an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).\n */\n get isAtom() { return this.type.isAtom; }\n /**\n Return a string representation of this node for debugging\n purposes.\n */\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n let name = this.type.name;\n if (this.content.size)\n name += \"(\" + this.content.toStringInner() + \")\";\n return wrapMarks(this.marks, name);\n }\n /**\n Get the content match in this node at the given index.\n */\n contentMatchAt(index) {\n let match = this.type.contentMatch.matchFragment(this.content, 0, index);\n if (!match)\n throw new Error(\"Called contentMatchAt on a node with invalid content\");\n return match;\n }\n /**\n Test whether replacing the range between `from` and `to` (by\n child index) with the given replacement fragment (which defaults\n to the empty fragment) would leave the node's content valid. You\n can optionally pass `start` and `end` indices into the\n replacement fragment.\n */\n canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {\n let one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n let two = one && one.matchFragment(this.content, to);\n if (!two || !two.validEnd)\n return false;\n for (let i = start; i < end; i++)\n if (!this.type.allowsMarks(replacement.child(i).marks))\n return false;\n return true;\n }\n /**\n Test whether replacing the range `from` to `to` (by index) with\n a node of the given type would leave the node's content valid.\n */\n canReplaceWith(from, to, type, marks) {\n if (marks && !this.type.allowsMarks(marks))\n return false;\n let start = this.contentMatchAt(from).matchType(type);\n let end = start && start.matchFragment(this.content, to);\n return end ? end.validEnd : false;\n }\n /**\n Test whether the given node's content could be appended to this\n node. If that node is empty, this will only return true if there\n is at least one node type that can appear in both nodes (to avoid\n merging completely incompatible nodes).\n */\n canAppend(other) {\n if (other.content.size)\n return this.canReplace(this.childCount, this.childCount, other.content);\n else\n return this.type.compatibleContent(other.type);\n }\n /**\n Check whether this node and its descendants conform to the\n schema, and raise an exception when they do not.\n */\n check() {\n this.type.checkContent(this.content);\n this.type.checkAttrs(this.attrs);\n let copy = Mark.none;\n for (let i = 0; i < this.marks.length; i++) {\n let mark = this.marks[i];\n mark.type.checkAttrs(mark.attrs);\n copy = mark.addToSet(copy);\n }\n if (!Mark.sameSet(copy, this.marks))\n throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);\n this.content.forEach(node => node.check());\n }\n /**\n Return a JSON-serializeable representation of this node.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n if (this.content.size)\n obj.content = this.content.toJSON();\n if (this.marks.length)\n obj.marks = this.marks.map(n => n.toJSON());\n return obj;\n }\n /**\n Deserialize a node from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Node.fromJSON\");\n let marks = undefined;\n if (json.marks) {\n if (!Array.isArray(json.marks))\n throw new RangeError(\"Invalid mark data for Node.fromJSON\");\n marks = json.marks.map(schema.markFromJSON);\n }\n if (json.type == \"text\") {\n if (typeof json.text != \"string\")\n throw new RangeError(\"Invalid text node in JSON\");\n return schema.text(json.text, marks);\n }\n let content = Fragment.fromJSON(schema, json.content);\n let node = schema.nodeType(json.type).create(json.attrs, content, marks);\n node.type.checkAttrs(node.attrs);\n return node;\n }\n}\nNode.prototype.text = undefined;\nclass TextNode extends Node {\n /**\n @internal\n */\n constructor(type, attrs, content, marks) {\n super(type, attrs, null, marks);\n if (!content)\n throw new RangeError(\"Empty text nodes are not allowed\");\n this.text = content;\n }\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n return wrapMarks(this.marks, JSON.stringify(this.text));\n }\n get textContent() { return this.text; }\n textBetween(from, to) { return this.text.slice(from, to); }\n get nodeSize() { return this.text.length; }\n mark(marks) {\n return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);\n }\n withText(text) {\n if (text == this.text)\n return this;\n return new TextNode(this.type, this.attrs, text, this.marks);\n }\n cut(from = 0, to = this.text.length) {\n if (from == 0 && to == this.text.length)\n return this;\n return this.withText(this.text.slice(from, to));\n }\n eq(other) {\n return this.sameMarkup(other) && this.text == other.text;\n }\n toJSON() {\n let base = super.toJSON();\n base.text = this.text;\n return base;\n }\n}\nfunction wrapMarks(marks, str) {\n for (let i = marks.length - 1; i >= 0; i--)\n str = marks[i].type.name + \"(\" + str + \")\";\n return str;\n}\n\n/**\nInstances of this class represent a match state of a node type's\n[content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to\nfind out whether further content matches here, and whether a given\nposition is a valid end of the node.\n*/\nclass ContentMatch {\n /**\n @internal\n */\n constructor(\n /**\n True when this match state represents a valid end of the node.\n */\n validEnd) {\n this.validEnd = validEnd;\n /**\n @internal\n */\n this.next = [];\n /**\n @internal\n */\n this.wrapCache = [];\n }\n /**\n @internal\n */\n static parse(string, nodeTypes) {\n let stream = new TokenStream(string, nodeTypes);\n if (stream.next == null)\n return ContentMatch.empty;\n let expr = parseExpr(stream);\n if (stream.next)\n stream.err(\"Unexpected trailing text\");\n let match = dfa(nfa(expr));\n checkForDeadEnds(match, stream);\n return match;\n }\n /**\n Match a node type, returning a match after that node if\n successful.\n */\n matchType(type) {\n for (let i = 0; i < this.next.length; i++)\n if (this.next[i].type == type)\n return this.next[i].next;\n return null;\n }\n /**\n Try to match a fragment. Returns the resulting match when\n successful.\n */\n matchFragment(frag, start = 0, end = frag.childCount) {\n let cur = this;\n for (let i = start; cur && i < end; i++)\n cur = cur.matchType(frag.child(i).type);\n return cur;\n }\n /**\n @internal\n */\n get inlineContent() {\n return this.next.length != 0 && this.next[0].type.isInline;\n }\n /**\n Get the first matching node type at this match position that can\n be generated.\n */\n get defaultType() {\n for (let i = 0; i < this.next.length; i++) {\n let { type } = this.next[i];\n if (!(type.isText || type.hasRequiredAttrs()))\n return type;\n }\n return null;\n }\n /**\n @internal\n */\n compatible(other) {\n for (let i = 0; i < this.next.length; i++)\n for (let j = 0; j < other.next.length; j++)\n if (this.next[i].type == other.next[j].type)\n return true;\n return false;\n }\n /**\n Try to match the given fragment, and if that fails, see if it can\n be made to match by inserting nodes in front of it. When\n successful, return a fragment of inserted nodes (which may be\n empty if nothing had to be inserted). When `toEnd` is true, only\n return a fragment if the resulting match goes to the end of the\n content expression.\n */\n fillBefore(after, toEnd = false, startIndex = 0) {\n let seen = [this];\n function search(match, types) {\n let finished = match.matchFragment(after, startIndex);\n if (finished && (!toEnd || finished.validEnd))\n return Fragment.from(types.map(tp => tp.createAndFill()));\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n seen.push(next);\n let found = search(next, types.concat(type));\n if (found)\n return found;\n }\n }\n return null;\n }\n return search(this, []);\n }\n /**\n Find a set of wrapping node types that would allow a node of the\n given type to appear at this position. The result may be empty\n (when it fits directly) and will be null when no such wrapping\n exists.\n */\n findWrapping(target) {\n for (let i = 0; i < this.wrapCache.length; i += 2)\n if (this.wrapCache[i] == target)\n return this.wrapCache[i + 1];\n let computed = this.computeWrapping(target);\n this.wrapCache.push(target, computed);\n return computed;\n }\n /**\n @internal\n */\n computeWrapping(target) {\n let seen = Object.create(null), active = [{ match: this, type: null, via: null }];\n while (active.length) {\n let current = active.shift(), match = current.match;\n if (match.matchType(target)) {\n let result = [];\n for (let obj = current; obj.type; obj = obj.via)\n result.push(obj.type);\n return result.reverse();\n }\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {\n active.push({ match: type.contentMatch, type, via: current });\n seen[type.name] = true;\n }\n }\n }\n return null;\n }\n /**\n The number of outgoing edges this node has in the finite\n automaton that describes the content expression.\n */\n get edgeCount() {\n return this.next.length;\n }\n /**\n Get the _n_​th outgoing edge from this node in the finite\n automaton that describes the content expression.\n */\n edge(n) {\n if (n >= this.next.length)\n throw new RangeError(`There's no ${n}th edge in this content match`);\n return this.next[n];\n }\n /**\n @internal\n */\n toString() {\n let seen = [];\n function scan(m) {\n seen.push(m);\n for (let i = 0; i < m.next.length; i++)\n if (seen.indexOf(m.next[i].next) == -1)\n scan(m.next[i].next);\n }\n scan(this);\n return seen.map((m, i) => {\n let out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n for (let i = 0; i < m.next.length; i++)\n out += (i ? \", \" : \"\") + m.next[i].type.name + \"->\" + seen.indexOf(m.next[i].next);\n return out;\n }).join(\"\\n\");\n }\n}\n/**\n@internal\n*/\nContentMatch.empty = new ContentMatch(true);\nclass TokenStream {\n constructor(string, nodeTypes) {\n this.string = string;\n this.nodeTypes = nodeTypes;\n this.inline = null;\n this.pos = 0;\n this.tokens = string.split(/\\s*(?=\\b|\\W|$)/);\n if (this.tokens[this.tokens.length - 1] == \"\")\n this.tokens.pop();\n if (this.tokens[0] == \"\")\n this.tokens.shift();\n }\n get next() { return this.tokens[this.pos]; }\n eat(tok) { return this.next == tok && (this.pos++ || true); }\n err(str) { throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\"); }\n}\nfunction parseExpr(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSeq(stream));\n } while (stream.eat(\"|\"));\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n}\nfunction parseExprSeq(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSubscript(stream));\n } while (stream.next && stream.next != \")\" && stream.next != \"|\");\n return exprs.length == 1 ? exprs[0] : { type: \"seq\", exprs };\n}\nfunction parseExprSubscript(stream) {\n let expr = parseExprAtom(stream);\n for (;;) {\n if (stream.eat(\"+\"))\n expr = { type: \"plus\", expr };\n else if (stream.eat(\"*\"))\n expr = { type: \"star\", expr };\n else if (stream.eat(\"?\"))\n expr = { type: \"opt\", expr };\n else if (stream.eat(\"{\"))\n expr = parseExprRange(stream, expr);\n else\n break;\n }\n return expr;\n}\nfunction parseNum(stream) {\n if (/\\D/.test(stream.next))\n stream.err(\"Expected number, got '\" + stream.next + \"'\");\n let result = Number(stream.next);\n stream.pos++;\n return result;\n}\nfunction parseExprRange(stream, expr) {\n let min = parseNum(stream), max = min;\n if (stream.eat(\",\")) {\n if (stream.next != \"}\")\n max = parseNum(stream);\n else\n max = -1;\n }\n if (!stream.eat(\"}\"))\n stream.err(\"Unclosed braced range\");\n return { type: \"range\", min, max, expr };\n}\nfunction resolveName(stream, name) {\n let types = stream.nodeTypes, type = types[name];\n if (type)\n return [type];\n let result = [];\n for (let typeName in types) {\n let type = types[typeName];\n if (type.isInGroup(name))\n result.push(type);\n }\n if (result.length == 0)\n stream.err(\"No node type or group '\" + name + \"' found\");\n return result;\n}\nfunction parseExprAtom(stream) {\n if (stream.eat(\"(\")) {\n let expr = parseExpr(stream);\n if (!stream.eat(\")\"))\n stream.err(\"Missing closing paren\");\n return expr;\n }\n else if (!/\\W/.test(stream.next)) {\n let exprs = resolveName(stream, stream.next).map(type => {\n if (stream.inline == null)\n stream.inline = type.isInline;\n else if (stream.inline != type.isInline)\n stream.err(\"Mixing inline and block content\");\n return { type: \"name\", value: type };\n });\n stream.pos++;\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n }\n else {\n stream.err(\"Unexpected token '\" + stream.next + \"'\");\n }\n}\n// Construct an NFA from an expression as returned by the parser. The\n// NFA is represented as an array of states, which are themselves\n// arrays of edges, which are `{term, to}` objects. The first state is\n// the entry state and the last node is the success state.\n//\n// Note that unlike typical NFAs, the edge ordering in this one is\n// significant, in that it is used to contruct filler content when\n// necessary.\nfunction nfa(expr) {\n let nfa = [[]];\n connect(compile(expr, 0), node());\n return nfa;\n function node() { return nfa.push([]) - 1; }\n function edge(from, to, term) {\n let edge = { term, to };\n nfa[from].push(edge);\n return edge;\n }\n function connect(edges, to) {\n edges.forEach(edge => edge.to = to);\n }\n function compile(expr, from) {\n if (expr.type == \"choice\") {\n return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);\n }\n else if (expr.type == \"seq\") {\n for (let i = 0;; i++) {\n let next = compile(expr.exprs[i], from);\n if (i == expr.exprs.length - 1)\n return next;\n connect(next, from = node());\n }\n }\n else if (expr.type == \"star\") {\n let loop = node();\n edge(from, loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"plus\") {\n let loop = node();\n connect(compile(expr.expr, from), loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"opt\") {\n return [edge(from)].concat(compile(expr.expr, from));\n }\n else if (expr.type == \"range\") {\n let cur = from;\n for (let i = 0; i < expr.min; i++) {\n let next = node();\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n if (expr.max == -1) {\n connect(compile(expr.expr, cur), cur);\n }\n else {\n for (let i = expr.min; i < expr.max; i++) {\n let next = node();\n edge(cur, next);\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n }\n return [edge(cur)];\n }\n else if (expr.type == \"name\") {\n return [edge(from, undefined, expr.value)];\n }\n else {\n throw new Error(\"Unknown expr type\");\n }\n }\n}\nfunction cmp(a, b) { return b - a; }\n// Get the set of nodes reachable by null edges from `node`. Omit\n// nodes with only a single null-out-edge, since they may lead to\n// needless duplicated nodes.\nfunction nullFrom(nfa, node) {\n let result = [];\n scan(node);\n return result.sort(cmp);\n function scan(node) {\n let edges = nfa[node];\n if (edges.length == 1 && !edges[0].term)\n return scan(edges[0].to);\n result.push(node);\n for (let i = 0; i < edges.length; i++) {\n let { term, to } = edges[i];\n if (!term && result.indexOf(to) == -1)\n scan(to);\n }\n }\n}\n// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set\n// of state objects (`ContentMatch` instances) with transitions\n// between them.\nfunction dfa(nfa) {\n let labeled = Object.create(null);\n return explore(nullFrom(nfa, 0));\n function explore(states) {\n let out = [];\n states.forEach(node => {\n nfa[node].forEach(({ term, to }) => {\n if (!term)\n return;\n let set;\n for (let i = 0; i < out.length; i++)\n if (out[i][0] == term)\n set = out[i][1];\n nullFrom(nfa, to).forEach(node => {\n if (!set)\n out.push([term, set = []]);\n if (set.indexOf(node) == -1)\n set.push(node);\n });\n });\n });\n let state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n for (let i = 0; i < out.length; i++) {\n let states = out[i][1].sort(cmp);\n state.next.push({ type: out[i][0], next: labeled[states.join(\",\")] || explore(states) });\n }\n return state;\n }\n}\nfunction checkForDeadEnds(match, stream) {\n for (let i = 0, work = [match]; i < work.length; i++) {\n let state = work[i], dead = !state.validEnd, nodes = [];\n for (let j = 0; j < state.next.length; j++) {\n let { type, next } = state.next[j];\n nodes.push(type.name);\n if (dead && !(type.isText || type.hasRequiredAttrs()))\n dead = false;\n if (work.indexOf(next) == -1)\n work.push(next);\n }\n if (dead)\n stream.err(\"Only non-generatable nodes (\" + nodes.join(\", \") + \") in a required position (see https://prosemirror.net/docs/guide/#generatable)\");\n }\n}\n\n// For node types where all attrs have a default value (or which don't\n// have any attributes), build up a single reusable default attribute\n// object, and use it for all nodes that don't specify specific\n// attributes.\nfunction defaultAttrs(attrs) {\n let defaults = Object.create(null);\n for (let attrName in attrs) {\n let attr = attrs[attrName];\n if (!attr.hasDefault)\n return null;\n defaults[attrName] = attr.default;\n }\n return defaults;\n}\nfunction computeAttrs(attrs, value) {\n let built = Object.create(null);\n for (let name in attrs) {\n let given = value && value[name];\n if (given === undefined) {\n let attr = attrs[name];\n if (attr.hasDefault)\n given = attr.default;\n else\n throw new RangeError(\"No value supplied for attribute \" + name);\n }\n built[name] = given;\n }\n return built;\n}\nfunction checkAttrs(attrs, values, type, name) {\n for (let name in values)\n if (!(name in attrs))\n throw new RangeError(`Unsupported attribute ${name} for ${type} of type ${name}`);\n for (let name in attrs) {\n let attr = attrs[name];\n if (attr.validate)\n attr.validate(values[name]);\n }\n}\nfunction initAttrs(typeName, attrs) {\n let result = Object.create(null);\n if (attrs)\n for (let name in attrs)\n result[name] = new Attribute(typeName, name, attrs[name]);\n return result;\n}\n/**\nNode types are objects allocated once per `Schema` and used to\n[tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information\nabout the node type, such as its name and what kind of node it\nrepresents.\n*/\nclass NodeType {\n /**\n @internal\n */\n constructor(\n /**\n The name the node type has in this schema.\n */\n name, \n /**\n A link back to the `Schema` the node type belongs to.\n */\n schema, \n /**\n The spec that this type is based on\n */\n spec) {\n this.name = name;\n this.schema = schema;\n this.spec = spec;\n /**\n The set of marks allowed in this node. `null` means all marks\n are allowed.\n */\n this.markSet = null;\n this.groups = spec.group ? spec.group.split(\" \") : [];\n this.attrs = initAttrs(name, spec.attrs);\n this.defaultAttrs = defaultAttrs(this.attrs);\n this.contentMatch = null;\n this.inlineContent = null;\n this.isBlock = !(spec.inline || name == \"text\");\n this.isText = name == \"text\";\n }\n /**\n True if this is an inline type.\n */\n get isInline() { return !this.isBlock; }\n /**\n True if this is a textblock type, a block that contains inline\n content.\n */\n get isTextblock() { return this.isBlock && this.inlineContent; }\n /**\n True for node types that allow no content.\n */\n get isLeaf() { return this.contentMatch == ContentMatch.empty; }\n /**\n True when this node is an atom, i.e. when it does not have\n directly editable content.\n */\n get isAtom() { return this.isLeaf || !!this.spec.atom; }\n /**\n Return true when this node type is part of the given\n [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).\n */\n isInGroup(group) {\n return this.groups.indexOf(group) > -1;\n }\n /**\n The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.\n */\n get whitespace() {\n return this.spec.whitespace || (this.spec.code ? \"pre\" : \"normal\");\n }\n /**\n Tells you whether this node type has any required attributes.\n */\n hasRequiredAttrs() {\n for (let n in this.attrs)\n if (this.attrs[n].isRequired)\n return true;\n return false;\n }\n /**\n Indicates whether this node allows some of the same content as\n the given node type.\n */\n compatibleContent(other) {\n return this == other || this.contentMatch.compatible(other.contentMatch);\n }\n /**\n @internal\n */\n computeAttrs(attrs) {\n if (!attrs && this.defaultAttrs)\n return this.defaultAttrs;\n else\n return computeAttrs(this.attrs, attrs);\n }\n /**\n Create a `Node` of this type. The given attributes are\n checked and defaulted (you can pass `null` to use the type's\n defaults entirely, if no required attributes exist). `content`\n may be a `Fragment`, a node, an array of nodes, or\n `null`. Similarly `marks` may be `null` to default to the empty\n set of marks.\n */\n create(attrs = null, content, marks) {\n if (this.isText)\n throw new Error(\"NodeType.create can't construct text nodes\");\n return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content\n against the node type's content restrictions, and throw an error\n if it doesn't match.\n */\n createChecked(attrs = null, content, marks) {\n content = Fragment.from(content);\n this.checkContent(content);\n return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is\n necessary to add nodes to the start or end of the given fragment\n to make it fit the node. If no fitting wrapping can be found,\n return null. Note that, due to the fact that required nodes can\n always be created, this will always succeed if you pass null or\n `Fragment.empty` as content.\n */\n createAndFill(attrs = null, content, marks) {\n attrs = this.computeAttrs(attrs);\n content = Fragment.from(content);\n if (content.size) {\n let before = this.contentMatch.fillBefore(content);\n if (!before)\n return null;\n content = before.append(content);\n }\n let matched = this.contentMatch.matchFragment(content);\n let after = matched && matched.fillBefore(Fragment.empty, true);\n if (!after)\n return null;\n return new Node(this, attrs, content.append(after), Mark.setFrom(marks));\n }\n /**\n Returns true if the given fragment is valid content for this node\n type.\n */\n validContent(content) {\n let result = this.contentMatch.matchFragment(content);\n if (!result || !result.validEnd)\n return false;\n for (let i = 0; i < content.childCount; i++)\n if (!this.allowsMarks(content.child(i).marks))\n return false;\n return true;\n }\n /**\n Throws a RangeError if the given fragment is not valid content for this\n node type.\n @internal\n */\n checkContent(content) {\n if (!this.validContent(content))\n throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"node\", this.name);\n }\n /**\n Check whether the given mark type is allowed in this node.\n */\n allowsMarkType(markType) {\n return this.markSet == null || this.markSet.indexOf(markType) > -1;\n }\n /**\n Test whether the given set of marks are allowed in this node.\n */\n allowsMarks(marks) {\n if (this.markSet == null)\n return true;\n for (let i = 0; i < marks.length; i++)\n if (!this.allowsMarkType(marks[i].type))\n return false;\n return true;\n }\n /**\n Removes the marks that are not allowed in this node from the given set.\n */\n allowedMarks(marks) {\n if (this.markSet == null)\n return marks;\n let copy;\n for (let i = 0; i < marks.length; i++) {\n if (!this.allowsMarkType(marks[i].type)) {\n if (!copy)\n copy = marks.slice(0, i);\n }\n else if (copy) {\n copy.push(marks[i]);\n }\n }\n return !copy ? marks : copy.length ? copy : Mark.none;\n }\n /**\n @internal\n */\n static compile(nodes, schema) {\n let result = Object.create(null);\n nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));\n let topType = schema.spec.topNode || \"doc\";\n if (!result[topType])\n throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\");\n if (!result.text)\n throw new RangeError(\"Every schema needs a 'text' type\");\n for (let _ in result.text.attrs)\n throw new RangeError(\"The text node type should not have attributes\");\n return result;\n }\n}\nfunction validateType(typeName, attrName, type) {\n let types = type.split(\"|\");\n return (value) => {\n let name = value === null ? \"null\" : typeof value;\n if (types.indexOf(name) < 0)\n throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);\n };\n}\n// Attribute descriptors\nclass Attribute {\n constructor(typeName, attrName, options) {\n this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n this.default = options.default;\n this.validate = typeof options.validate == \"string\" ? validateType(typeName, attrName, options.validate) : options.validate;\n }\n get isRequired() {\n return !this.hasDefault;\n }\n}\n// Marks\n/**\nLike nodes, marks (which are associated with nodes to signify\nthings like emphasis or being part of a link) are\n[tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are\ninstantiated once per `Schema`.\n*/\nclass MarkType {\n /**\n @internal\n */\n constructor(\n /**\n The name of the mark type.\n */\n name, \n /**\n @internal\n */\n rank, \n /**\n The schema that this mark type instance is part of.\n */\n schema, \n /**\n The spec on which the type is based.\n */\n spec) {\n this.name = name;\n this.rank = rank;\n this.schema = schema;\n this.spec = spec;\n this.attrs = initAttrs(name, spec.attrs);\n this.excluded = null;\n let defaults = defaultAttrs(this.attrs);\n this.instance = defaults ? new Mark(this, defaults) : null;\n }\n /**\n Create a mark of this type. `attrs` may be `null` or an object\n containing only some of the mark's attributes. The others, if\n they have defaults, will be added.\n */\n create(attrs = null) {\n if (!attrs && this.instance)\n return this.instance;\n return new Mark(this, computeAttrs(this.attrs, attrs));\n }\n /**\n @internal\n */\n static compile(marks, schema) {\n let result = Object.create(null), rank = 0;\n marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));\n return result;\n }\n /**\n When there is a mark of this type in the given set, a new set\n without it is returned. Otherwise, the input set is returned.\n */\n removeFromSet(set) {\n for (var i = 0; i < set.length; i++)\n if (set[i].type == this) {\n set = set.slice(0, i).concat(set.slice(i + 1));\n i--;\n }\n return set;\n }\n /**\n Tests whether there is a mark of this type in the given set.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (set[i].type == this)\n return set[i];\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"mark\", this.name);\n }\n /**\n Queries whether a given mark type is\n [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.\n */\n excludes(other) {\n return this.excluded.indexOf(other) > -1;\n }\n}\n/**\nA document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark\ntype](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may\noccur in conforming documents, and provides functionality for\ncreating and deserializing such documents.\n\nWhen given, the type parameters provide the names of the nodes and\nmarks in this schema.\n*/\nclass Schema {\n /**\n Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).\n */\n constructor(spec) {\n /**\n The [linebreak\n replacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement) node defined\n in this schema, if any.\n */\n this.linebreakReplacement = null;\n /**\n An object for storing whatever values modules may want to\n compute and cache per schema. (If you want to store something\n in it, try to use property names unlikely to clash.)\n */\n this.cached = Object.create(null);\n let instanceSpec = this.spec = {};\n for (let prop in spec)\n instanceSpec[prop] = spec[prop];\n instanceSpec.nodes = OrderedMap.from(spec.nodes),\n instanceSpec.marks = OrderedMap.from(spec.marks || {}),\n this.nodes = NodeType.compile(this.spec.nodes, this);\n this.marks = MarkType.compile(this.spec.marks, this);\n let contentExprCache = Object.create(null);\n for (let prop in this.nodes) {\n if (prop in this.marks)\n throw new RangeError(prop + \" can not be both a node and a mark\");\n let type = this.nodes[prop], contentExpr = type.spec.content || \"\", markExpr = type.spec.marks;\n type.contentMatch = contentExprCache[contentExpr] ||\n (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));\n type.inlineContent = type.contentMatch.inlineContent;\n if (type.spec.linebreakReplacement) {\n if (this.linebreakReplacement)\n throw new RangeError(\"Multiple linebreak nodes defined\");\n if (!type.isInline || !type.isLeaf)\n throw new RangeError(\"Linebreak replacement nodes must be inline leaf nodes\");\n this.linebreakReplacement = type;\n }\n type.markSet = markExpr == \"_\" ? null :\n markExpr ? gatherMarks(this, markExpr.split(\" \")) :\n markExpr == \"\" || !type.inlineContent ? [] : null;\n }\n for (let prop in this.marks) {\n let type = this.marks[prop], excl = type.spec.excludes;\n type.excluded = excl == null ? [type] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n }\n this.nodeFromJSON = this.nodeFromJSON.bind(this);\n this.markFromJSON = this.markFromJSON.bind(this);\n this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n this.cached.wrappings = Object.create(null);\n }\n /**\n Create a node in this schema. The `type` may be a string or a\n `NodeType` instance. Attributes will be extended with defaults,\n `content` may be a `Fragment`, `null`, a `Node`, or an array of\n nodes.\n */\n node(type, attrs = null, content, marks) {\n if (typeof type == \"string\")\n type = this.nodeType(type);\n else if (!(type instanceof NodeType))\n throw new RangeError(\"Invalid node type: \" + type);\n else if (type.schema != this)\n throw new RangeError(\"Node type from different schema used (\" + type.name + \")\");\n return type.createChecked(attrs, content, marks);\n }\n /**\n Create a text node in the schema. Empty text nodes are not\n allowed.\n */\n text(text, marks) {\n let type = this.nodes.text;\n return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));\n }\n /**\n Create a mark with the given type and attributes.\n */\n mark(type, attrs) {\n if (typeof type == \"string\")\n type = this.marks[type];\n return type.create(attrs);\n }\n /**\n Deserialize a node from its JSON representation. This method is\n bound.\n */\n nodeFromJSON(json) {\n return Node.fromJSON(this, json);\n }\n /**\n Deserialize a mark from its JSON representation. This method is\n bound.\n */\n markFromJSON(json) {\n return Mark.fromJSON(this, json);\n }\n /**\n @internal\n */\n nodeType(name) {\n let found = this.nodes[name];\n if (!found)\n throw new RangeError(\"Unknown node type: \" + name);\n return found;\n }\n}\nfunction gatherMarks(schema, marks) {\n let found = [];\n for (let i = 0; i < marks.length; i++) {\n let name = marks[i], mark = schema.marks[name], ok = mark;\n if (mark) {\n found.push(mark);\n }\n else {\n for (let prop in schema.marks) {\n let mark = schema.marks[prop];\n if (name == \"_\" || (mark.spec.group && mark.spec.group.split(\" \").indexOf(name) > -1))\n found.push(ok = mark);\n }\n }\n if (!ok)\n throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\");\n }\n return found;\n}\n\nfunction isTagRule(rule) { return rule.tag != null; }\nfunction isStyleRule(rule) { return rule.style != null; }\n/**\nA DOM parser represents a strategy for parsing DOM content into a\nProseMirror document conforming to a given schema. Its behavior is\ndefined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).\n*/\nclass DOMParser {\n /**\n Create a parser that targets the given schema, using the given\n parsing rules.\n */\n constructor(\n /**\n The schema into which the parser parses.\n */\n schema, \n /**\n The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser\n uses, in order of precedence.\n */\n rules) {\n this.schema = schema;\n this.rules = rules;\n /**\n @internal\n */\n this.tags = [];\n /**\n @internal\n */\n this.styles = [];\n let matchedStyles = this.matchedStyles = [];\n rules.forEach(rule => {\n if (isTagRule(rule)) {\n this.tags.push(rule);\n }\n else if (isStyleRule(rule)) {\n let prop = /[^=]*/.exec(rule.style)[0];\n if (matchedStyles.indexOf(prop) < 0)\n matchedStyles.push(prop);\n this.styles.push(rule);\n }\n });\n // Only normalize list elements when lists in the schema can't directly contain themselves\n this.normalizeLists = !this.tags.some(r => {\n if (!/^(ul|ol)\\b/.test(r.tag) || !r.node)\n return false;\n let node = schema.nodes[r.node];\n return node.contentMatch.matchType(node);\n });\n }\n /**\n Parse a document from the content of a DOM node.\n */\n parse(dom, options = {}) {\n let context = new ParseContext(this, options, false);\n context.addAll(dom, Mark.none, options.from, options.to);\n return context.finish();\n }\n /**\n Parses the content of the given DOM node, like\n [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of\n options. But unlike that method, which produces a whole node,\n this one returns a slice that is open at the sides, meaning that\n the schema constraints aren't applied to the start of nodes to\n the left of the input and the end of nodes at the end.\n */\n parseSlice(dom, options = {}) {\n let context = new ParseContext(this, options, true);\n context.addAll(dom, Mark.none, options.from, options.to);\n return Slice.maxOpen(context.finish());\n }\n /**\n @internal\n */\n matchTag(dom, context, after) {\n for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {\n let rule = this.tags[i];\n if (matches(dom, rule.tag) &&\n (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&\n (!rule.context || context.matchesContext(rule.context))) {\n if (rule.getAttrs) {\n let result = rule.getAttrs(dom);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n }\n /**\n @internal\n */\n matchStyle(prop, value, context, after) {\n for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {\n let rule = this.styles[i], style = rule.style;\n if (style.indexOf(prop) != 0 ||\n rule.context && !context.matchesContext(rule.context) ||\n // Test that the style string either precisely matches the prop,\n // or has an '=' sign after the prop, followed by the given\n // value.\n style.length > prop.length &&\n (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))\n continue;\n if (rule.getAttrs) {\n let result = rule.getAttrs(value);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n /**\n @internal\n */\n static schemaRules(schema) {\n let result = [];\n function insert(rule) {\n let priority = rule.priority == null ? 50 : rule.priority, i = 0;\n for (; i < result.length; i++) {\n let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;\n if (nextPriority < priority)\n break;\n }\n result.splice(i, 0, rule);\n }\n for (let name in schema.marks) {\n let rules = schema.marks[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.mark || rule.ignore || rule.clearMark))\n rule.mark = name;\n });\n }\n for (let name in schema.nodes) {\n let rules = schema.nodes[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.node || rule.ignore || rule.mark))\n rule.node = name;\n });\n }\n return result;\n }\n /**\n Construct a DOM parser using the parsing rules listed in a\n schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by\n [priority](https://prosemirror.net/docs/ref/#model.ParseRule.priority).\n */\n static fromSchema(schema) {\n return schema.cached.domParser ||\n (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));\n }\n}\nconst blockTags = {\n address: true, article: true, aside: true, blockquote: true, canvas: true,\n dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,\n footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,\n h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,\n output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true\n};\nconst ignoreTags = {\n head: true, noscript: true, object: true, script: true, style: true, title: true\n};\nconst listTags = { ol: true, ul: true };\n// Using a bitfield for node context options\nconst OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;\nfunction wsOptionsFor(type, preserveWhitespace, base) {\n if (preserveWhitespace != null)\n return (preserveWhitespace ? OPT_PRESERVE_WS : 0) |\n (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0);\n return type && type.whitespace == \"pre\" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;\n}\nclass NodeContext {\n constructor(type, attrs, marks, solid, match, options) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.solid = solid;\n this.options = options;\n this.content = [];\n // Marks applied to the node's children\n this.activeMarks = Mark.none;\n this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n }\n findWrapping(node) {\n if (!this.match) {\n if (!this.type)\n return [];\n let fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n if (fill) {\n this.match = this.type.contentMatch.matchFragment(fill);\n }\n else {\n let start = this.type.contentMatch, wrap;\n if (wrap = start.findWrapping(node.type)) {\n this.match = start;\n return wrap;\n }\n else {\n return null;\n }\n }\n }\n return this.match.findWrapping(node.type);\n }\n finish(openEnd) {\n if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace\n let last = this.content[this.content.length - 1], m;\n if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n let text = last;\n if (last.text.length == m[0].length)\n this.content.pop();\n else\n this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));\n }\n }\n let content = Fragment.from(this.content);\n if (!openEnd && this.match)\n content = content.append(this.match.fillBefore(Fragment.empty, true));\n return this.type ? this.type.create(this.attrs, content, this.marks) : content;\n }\n inlineContext(node) {\n if (this.type)\n return this.type.inlineContent;\n if (this.content.length)\n return this.content[0].isInline;\n return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());\n }\n}\nclass ParseContext {\n constructor(\n // The parser we are using.\n parser, \n // The options passed to this parse.\n options, isOpen) {\n this.parser = parser;\n this.options = options;\n this.isOpen = isOpen;\n this.open = 0;\n this.localPreserveWS = false;\n let topNode = options.topNode, topContext;\n let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);\n if (topNode)\n topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);\n else if (isOpen)\n topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);\n else\n topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);\n this.nodes = [topContext];\n this.find = options.findPositions;\n this.needsBlock = false;\n }\n get top() {\n return this.nodes[this.open];\n }\n // Add a DOM node to the content. Text is inserted as text node,\n // otherwise, the node is passed to `addElement` or, if it has a\n // `style` attribute, `addElementWithStyles`.\n addDOM(dom, marks) {\n if (dom.nodeType == 3)\n this.addTextNode(dom, marks);\n else if (dom.nodeType == 1)\n this.addElement(dom, marks);\n }\n addTextNode(dom, marks) {\n let value = dom.nodeValue;\n let top = this.top, preserveWS = (top.options & OPT_PRESERVE_WS_FULL) ? \"full\"\n : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;\n if (preserveWS === \"full\" ||\n top.inlineContext(dom) ||\n /[^ \\t\\r\\n\\u000c]/.test(value)) {\n if (!preserveWS) {\n value = value.replace(/[ \\t\\r\\n\\u000c]+/g, \" \");\n // If this starts with whitespace, and there is no node before it, or\n // a hard break, or a text node that ends with whitespace, strip the\n // leading space.\n if (/^[ \\t\\r\\n\\u000c]/.test(value) && this.open == this.nodes.length - 1) {\n let nodeBefore = top.content[top.content.length - 1];\n let domNodeBefore = dom.previousSibling;\n if (!nodeBefore ||\n (domNodeBefore && domNodeBefore.nodeName == 'BR') ||\n (nodeBefore.isText && /[ \\t\\r\\n\\u000c]$/.test(nodeBefore.text)))\n value = value.slice(1);\n }\n }\n else if (preserveWS !== \"full\") {\n value = value.replace(/\\r?\\n|\\r/g, \" \");\n }\n else {\n value = value.replace(/\\r\\n?/g, \"\\n\");\n }\n if (value)\n this.insertNode(this.parser.schema.text(value), marks);\n this.findInText(dom);\n }\n else {\n this.findInside(dom);\n }\n }\n // Try to find a handler for the given tag and use that to parse. If\n // none is found, the element's content nodes are added directly.\n addElement(dom, marks, matchAfter) {\n let outerWS = this.localPreserveWS, top = this.top;\n if (dom.tagName == \"PRE\" || /pre/.test(dom.style && dom.style.whiteSpace))\n this.localPreserveWS = true;\n let name = dom.nodeName.toLowerCase(), ruleID;\n if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)\n normalizeList(dom);\n let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) ||\n (ruleID = this.parser.matchTag(dom, this, matchAfter));\n out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n this.findInside(dom);\n this.ignoreFallback(dom, marks);\n }\n else if (!rule || rule.skip || rule.closeParent) {\n if (rule && rule.closeParent)\n this.open = Math.max(0, this.open - 1);\n else if (rule && rule.skip.nodeType)\n dom = rule.skip;\n let sync, oldNeedsBlock = this.needsBlock;\n if (blockTags.hasOwnProperty(name)) {\n if (top.content.length && top.content[0].isInline && this.open) {\n this.open--;\n top = this.top;\n }\n sync = true;\n if (!top.type)\n this.needsBlock = true;\n }\n else if (!dom.firstChild) {\n this.leafFallback(dom, marks);\n break out;\n }\n let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);\n if (innerMarks)\n this.addAll(dom, innerMarks);\n if (sync)\n this.sync(top);\n this.needsBlock = oldNeedsBlock;\n }\n else {\n let innerMarks = this.readStyles(dom, marks);\n if (innerMarks)\n this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : undefined);\n }\n this.localPreserveWS = outerWS;\n }\n // Called for leaf DOM nodes that would otherwise be ignored\n leafFallback(dom, marks) {\n if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent)\n this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\"), marks);\n }\n // Called for ignored nodes\n ignoreFallback(dom, marks) {\n // Ignored BR nodes should at least create an inline context\n if (dom.nodeName == \"BR\" && (!this.top.type || !this.top.type.inlineContent))\n this.findPlace(this.parser.schema.text(\"-\"), marks);\n }\n // Run any style parser associated with the node's styles. Either\n // return an updated array of marks, or null to indicate some of the\n // styles had a rule with `ignore` set.\n readStyles(dom, marks) {\n let styles = dom.style;\n // Because many properties will only show up in 'normalized' form\n // in `style.item` (i.e. text-decoration becomes\n // text-decoration-line, text-decoration-color, etc), we directly\n // query the styles mentioned in our rules instead of iterating\n // over the items.\n if (styles && styles.length)\n for (let i = 0; i < this.parser.matchedStyles.length; i++) {\n let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name);\n if (value)\n for (let after = undefined;;) {\n let rule = this.parser.matchStyle(name, value, this, after);\n if (!rule)\n break;\n if (rule.ignore)\n return null;\n if (rule.clearMark)\n marks = marks.filter(m => !rule.clearMark(m));\n else\n marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));\n if (rule.consuming === false)\n after = rule;\n else\n break;\n }\n }\n return marks;\n }\n // Look up a handler for the given node. If none are found, return\n // false. Otherwise, apply it, use its return value to drive the way\n // the node's content is wrapped, and return true.\n addElementByRule(dom, rule, marks, continueAfter) {\n let sync, nodeType;\n if (rule.node) {\n nodeType = this.parser.schema.nodes[rule.node];\n if (!nodeType.isLeaf) {\n let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);\n if (inner) {\n sync = true;\n marks = inner;\n }\n }\n else if (!this.insertNode(nodeType.create(rule.attrs), marks)) {\n this.leafFallback(dom, marks);\n }\n }\n else {\n let markType = this.parser.schema.marks[rule.mark];\n marks = marks.concat(markType.create(rule.attrs));\n }\n let startIn = this.top;\n if (nodeType && nodeType.isLeaf) {\n this.findInside(dom);\n }\n else if (continueAfter) {\n this.addElement(dom, marks, continueAfter);\n }\n else if (rule.getContent) {\n this.findInside(dom);\n rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node, marks));\n }\n else {\n let contentDOM = dom;\n if (typeof rule.contentElement == \"string\")\n contentDOM = dom.querySelector(rule.contentElement);\n else if (typeof rule.contentElement == \"function\")\n contentDOM = rule.contentElement(dom);\n else if (rule.contentElement)\n contentDOM = rule.contentElement;\n this.findAround(dom, contentDOM, true);\n this.addAll(contentDOM, marks);\n this.findAround(dom, contentDOM, false);\n }\n if (sync && this.sync(startIn))\n this.open--;\n }\n // Add all child nodes between `startIndex` and `endIndex` (or the\n // whole node, if not given). If `sync` is passed, use it to\n // synchronize after every block element.\n addAll(parent, marks, startIndex, endIndex) {\n let index = startIndex || 0;\n for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {\n this.findAtPoint(parent, index);\n this.addDOM(dom, marks);\n }\n this.findAtPoint(parent, index);\n }\n // Try to find a way to fit the given node type into the current\n // context. May add intermediate wrappers and/or leave non-solid\n // nodes that we're in.\n findPlace(node, marks) {\n let route, sync;\n for (let depth = this.open; depth >= 0; depth--) {\n let cx = this.nodes[depth];\n let found = cx.findWrapping(node);\n if (found && (!route || route.length > found.length)) {\n route = found;\n sync = cx;\n if (!found.length)\n break;\n }\n if (cx.solid)\n break;\n }\n if (!route)\n return null;\n this.sync(sync);\n for (let i = 0; i < route.length; i++)\n marks = this.enterInner(route[i], null, marks, false);\n return marks;\n }\n // Try to insert the given node, adjusting the context when needed.\n insertNode(node, marks) {\n if (node.isInline && this.needsBlock && !this.top.type) {\n let block = this.textblockFromContext();\n if (block)\n marks = this.enterInner(block, null, marks);\n }\n let innerMarks = this.findPlace(node, marks);\n if (innerMarks) {\n this.closeExtra();\n let top = this.top;\n if (top.match)\n top.match = top.match.matchType(node.type);\n let nodeMarks = Mark.none;\n for (let m of innerMarks.concat(node.marks))\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))\n nodeMarks = m.addToSet(nodeMarks);\n top.content.push(node.mark(nodeMarks));\n return true;\n }\n return false;\n }\n // Try to start a node of the given type, adjusting the context when\n // necessary.\n enter(type, attrs, marks, preserveWS) {\n let innerMarks = this.findPlace(type.create(attrs), marks);\n if (innerMarks)\n innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);\n return innerMarks;\n }\n // Open a node of the given type\n enterInner(type, attrs, marks, solid = false, preserveWS) {\n this.closeExtra();\n let top = this.top;\n top.match = top.match && top.match.matchType(type);\n let options = wsOptionsFor(type, preserveWS, top.options);\n if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0)\n options |= OPT_OPEN_LEFT;\n let applyMarks = Mark.none;\n marks = marks.filter(m => {\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {\n applyMarks = m.addToSet(applyMarks);\n return false;\n }\n return true;\n });\n this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));\n this.open++;\n return marks;\n }\n // Make sure all nodes above this.open are finished and added to\n // their parents\n closeExtra(openEnd = false) {\n let i = this.nodes.length - 1;\n if (i > this.open) {\n for (; i > this.open; i--)\n this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));\n this.nodes.length = this.open + 1;\n }\n }\n finish() {\n this.open = 0;\n this.closeExtra(this.isOpen);\n return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));\n }\n sync(to) {\n for (let i = this.open; i >= 0; i--) {\n if (this.nodes[i] == to) {\n this.open = i;\n return true;\n }\n else if (this.localPreserveWS) {\n this.nodes[i].options |= OPT_PRESERVE_WS;\n }\n }\n return false;\n }\n get currentPos() {\n this.closeExtra();\n let pos = 0;\n for (let i = this.open; i >= 0; i--) {\n let content = this.nodes[i].content;\n for (let j = content.length - 1; j >= 0; j--)\n pos += content[j].nodeSize;\n if (i)\n pos++;\n }\n return pos;\n }\n findAtPoint(parent, offset) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == parent && this.find[i].offset == offset)\n this.find[i].pos = this.currentPos;\n }\n }\n findInside(parent) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))\n this.find[i].pos = this.currentPos;\n }\n }\n findAround(parent, content, before) {\n if (parent != content && this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n let pos = content.compareDocumentPosition(this.find[i].node);\n if (pos & (before ? 2 : 4))\n this.find[i].pos = this.currentPos;\n }\n }\n }\n findInText(textNode) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == textNode)\n this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);\n }\n }\n // Determines whether the given context string matches this context.\n matchesContext(context) {\n if (context.indexOf(\"|\") > -1)\n return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this);\n let parts = context.split(\"/\");\n let option = this.options.context;\n let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n let match = (i, depth) => {\n for (; i >= 0; i--) {\n let part = parts[i];\n if (part == \"\") {\n if (i == parts.length - 1 || i == 0)\n continue;\n for (; depth >= minDepth; depth--)\n if (match(i - 1, depth))\n return true;\n return false;\n }\n else {\n let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type\n : option && depth >= minDepth ? option.node(depth - minDepth).type\n : null;\n if (!next || (next.name != part && !next.isInGroup(part)))\n return false;\n depth--;\n }\n }\n return true;\n };\n return match(parts.length - 1, this.open);\n }\n textblockFromContext() {\n let $context = this.options.context;\n if ($context)\n for (let d = $context.depth; d >= 0; d--) {\n let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n if (deflt && deflt.isTextblock && deflt.defaultAttrs)\n return deflt;\n }\n for (let name in this.parser.schema.nodes) {\n let type = this.parser.schema.nodes[name];\n if (type.isTextblock && type.defaultAttrs)\n return type;\n }\n }\n}\n// Kludge to work around directly nested list nodes produced by some\n// tools and allowed by browsers to mean that the nested list is\n// actually part of the list item above it.\nfunction normalizeList(dom) {\n for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n if (name && listTags.hasOwnProperty(name) && prevItem) {\n prevItem.appendChild(child);\n child = prevItem;\n }\n else if (name == \"li\") {\n prevItem = child;\n }\n else if (name) {\n prevItem = null;\n }\n }\n}\n// Apply a CSS selector.\nfunction matches(dom, selector) {\n return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);\n}\nfunction copy(obj) {\n let copy = {};\n for (let prop in obj)\n copy[prop] = obj[prop];\n return copy;\n}\n// Used when finding a mark at the top level of a fragment parse.\n// Checks whether it would be reasonable to apply a given mark type to\n// a given node, by looking at the way the mark occurs in the schema.\nfunction markMayApply(markType, nodeType) {\n let nodes = nodeType.schema.nodes;\n for (let name in nodes) {\n let parent = nodes[name];\n if (!parent.allowsMarkType(markType))\n continue;\n let seen = [], scan = (match) => {\n seen.push(match);\n for (let i = 0; i < match.edgeCount; i++) {\n let { type, next } = match.edge(i);\n if (type == nodeType)\n return true;\n if (seen.indexOf(next) < 0 && scan(next))\n return true;\n }\n };\n if (scan(parent.contentMatch))\n return true;\n }\n}\n\n/**\nA DOM serializer knows how to convert ProseMirror nodes and\nmarks of various types to DOM nodes.\n*/\nclass DOMSerializer {\n /**\n Create a serializer. `nodes` should map node names to functions\n that take a node and return a description of the corresponding\n DOM. `marks` does the same for mark names, but also gets an\n argument that tells it whether the mark's content is block or\n inline content (for typical use, it'll always be inline). A mark\n serializer may be `null` to indicate that marks of that type\n should not be serialized.\n */\n constructor(\n /**\n The node serialization functions.\n */\n nodes, \n /**\n The mark serialization functions.\n */\n marks) {\n this.nodes = nodes;\n this.marks = marks;\n }\n /**\n Serialize the content of this fragment to a DOM fragment. When\n not in the browser, the `document` option, containing a DOM\n document, should be passed so that the serializer can create\n nodes.\n */\n serializeFragment(fragment, options = {}, target) {\n if (!target)\n target = doc(options).createDocumentFragment();\n let top = target, active = [];\n fragment.forEach(node => {\n if (active.length || node.marks.length) {\n let keep = 0, rendered = 0;\n while (keep < active.length && rendered < node.marks.length) {\n let next = node.marks[rendered];\n if (!this.marks[next.type.name]) {\n rendered++;\n continue;\n }\n if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)\n break;\n keep++;\n rendered++;\n }\n while (keep < active.length)\n top = active.pop()[1];\n while (rendered < node.marks.length) {\n let add = node.marks[rendered++];\n let markDOM = this.serializeMark(add, node.isInline, options);\n if (markDOM) {\n active.push([add, top]);\n top.appendChild(markDOM.dom);\n top = markDOM.contentDOM || markDOM.dom;\n }\n }\n }\n top.appendChild(this.serializeNodeInner(node, options));\n });\n return target;\n }\n /**\n @internal\n */\n serializeNodeInner(node, options) {\n let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);\n if (contentDOM) {\n if (node.isLeaf)\n throw new RangeError(\"Content hole not allowed in a leaf node spec\");\n this.serializeFragment(node.content, options, contentDOM);\n }\n return dom;\n }\n /**\n Serialize this node to a DOM node. This can be useful when you\n need to serialize a part of a document, as opposed to the whole\n document. To serialize a whole document, use\n [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on\n its [content](https://prosemirror.net/docs/ref/#model.Node.content).\n */\n serializeNode(node, options = {}) {\n let dom = this.serializeNodeInner(node, options);\n for (let i = node.marks.length - 1; i >= 0; i--) {\n let wrap = this.serializeMark(node.marks[i], node.isInline, options);\n if (wrap) {\n (wrap.contentDOM || wrap.dom).appendChild(dom);\n dom = wrap.dom;\n }\n }\n return dom;\n }\n /**\n @internal\n */\n serializeMark(mark, inline, options = {}) {\n let toDOM = this.marks[mark.type.name];\n return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);\n }\n static renderSpec(doc, structure, xmlNS = null, blockArraysIn) {\n return renderSpec(doc, structure, xmlNS, blockArraysIn);\n }\n /**\n Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)\n properties in a schema's node and mark specs.\n */\n static fromSchema(schema) {\n return schema.cached.domSerializer ||\n (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));\n }\n /**\n Gather the serializers in a schema's node specs into an object.\n This can be useful as a base to build a custom serializer from.\n */\n static nodesFromSchema(schema) {\n let result = gatherToDOM(schema.nodes);\n if (!result.text)\n result.text = node => node.text;\n return result;\n }\n /**\n Gather the serializers in a schema's mark specs into an object.\n */\n static marksFromSchema(schema) {\n return gatherToDOM(schema.marks);\n }\n}\nfunction gatherToDOM(obj) {\n let result = {};\n for (let name in obj) {\n let toDOM = obj[name].spec.toDOM;\n if (toDOM)\n result[name] = toDOM;\n }\n return result;\n}\nfunction doc(options) {\n return options.document || window.document;\n}\nconst suspiciousAttributeCache = new WeakMap();\nfunction suspiciousAttributes(attrs) {\n let value = suspiciousAttributeCache.get(attrs);\n if (value === undefined)\n suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));\n return value;\n}\nfunction suspiciousAttributesInner(attrs) {\n let result = null;\n function scan(value) {\n if (value && typeof value == \"object\") {\n if (Array.isArray(value)) {\n if (typeof value[0] == \"string\") {\n if (!result)\n result = [];\n result.push(value);\n }\n else {\n for (let i = 0; i < value.length; i++)\n scan(value[i]);\n }\n }\n else {\n for (let prop in value)\n scan(value[prop]);\n }\n }\n }\n scan(attrs);\n return result;\n}\nfunction renderSpec(doc, structure, xmlNS, blockArraysIn) {\n if (typeof structure == \"string\")\n return { dom: doc.createTextNode(structure) };\n if (structure.nodeType != null)\n return { dom: structure };\n if (structure.dom && structure.dom.nodeType != null)\n return structure;\n let tagName = structure[0], suspicious;\n if (typeof tagName != \"string\")\n throw new RangeError(\"Invalid array passed to renderSpec\");\n if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) &&\n suspicious.indexOf(structure) > -1)\n throw new RangeError(\"Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.\");\n let space = tagName.indexOf(\" \");\n if (space > 0) {\n xmlNS = tagName.slice(0, space);\n tagName = tagName.slice(space + 1);\n }\n let contentDOM;\n let dom = (xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName));\n let attrs = structure[1], start = 1;\n if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n start = 2;\n for (let name in attrs)\n if (attrs[name] != null) {\n let space = name.indexOf(\" \");\n if (space > 0)\n dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);\n else\n dom.setAttribute(name, attrs[name]);\n }\n }\n for (let i = start; i < structure.length; i++) {\n let child = structure[i];\n if (child === 0) {\n if (i < structure.length - 1 || i > start)\n throw new RangeError(\"Content hole must be the only child of its parent node\");\n return { dom, contentDOM: dom };\n }\n else {\n let { dom: inner, contentDOM: innerContent } = renderSpec(doc, child, xmlNS, blockArraysIn);\n dom.appendChild(inner);\n if (innerContent) {\n if (contentDOM)\n throw new RangeError(\"Multiple content holes\");\n contentDOM = innerContent;\n }\n }\n }\n return { dom, contentDOM };\n}\n\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };\n","/*\n\n Style HTML\n---------------\n\n Written by Nochum Sossonko, (nsossonko@hotmail.com)\n\n Based on code initially developed by: Einar Lielmanis, <elfz@laacz.lv>\n http://jsbeautifier.org/\n\n\n You are free to use this in any way you want, in case you find this useful or working for you.\n\n Usage:\n style_html(html_source);\n\n style_html(html_source, options);\n\n The options are:\n indent_size (default 4) — indentation size,\n indent_char (default space) — character to indent with,\n max_char (default 70) - maximum amount of characters per line,\n brace_style (default \"collapse\") - \"collapse\" | \"expand\" | \"end-expand\"\n put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line.\n unformatted (defaults to inline tags) - list of tags, that shouldn't be reformatted\n indent_scripts (default normal) - \"keep\"|\"separate\"|\"normal\"\n\n e.g.\n\n style_html(html_source, {\n 'indent_size': 2,\n 'indent_char': ' ',\n 'max_char': 78,\n 'brace_style': 'expand',\n 'unformatted': ['a', 'sub', 'sup', 'b', 'i', 'u']\n });\n*/\n\nfunction style_html(html_source, options) {\n//Wrapper function to invoke all the necessary constructors and deal with the output.\n\n var multi_parser,\n indent_size,\n indent_character,\n max_char,\n brace_style,\n unformatted;\n\n options = options || {};\n indent_size = options.indent_size || 4;\n indent_character = options.indent_char || ' ';\n brace_style = options.brace_style || 'collapse';\n max_char = options.max_char == 0 ? Infinity : options.max_char || 70;\n unformatted = options.unformatted || ['a', 'span', 'bdo', 'em', 'strong', 'dfn', 'code', 'samp', 'kbd', 'var', 'cite', 'abbr', 'acronym', 'q', 'sub', 'sup', 'tt', 'i', 'b', 'big', 'small', 'u', 's', 'strike', 'font', 'ins', 'del', 'pre', 'address', 'dt', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];\n\n function Parser() {\n\n this.pos = 0; //Parser position\n this.token = '';\n this.current_mode = 'CONTENT'; //reflects the current Parser mode: TAG/CONTENT\n this.tags = { //An object to hold tags, their position, and their parent-tags, initiated with default values\n parent: 'parent1',\n parentcount: 1,\n parent1: ''\n };\n this.tag_type = '';\n this.token_text = this.last_token = this.last_text = this.token_type = '';\n\n this.Utils = { //Uilities made available to the various functions\n whitespace: \"\\n\\r\\t \".split(''),\n single_token: 'br,input,link,meta,!doctype,basefont,base,area,hr,wbr,param,img,isindex,?xml,embed,?php,?,?='.split(','), //all the single tags for HTML\n extra_liners: 'head,body,/html'.split(','), //for tags that need a line of whitespace before them\n in_array: function (what, arr) {\n for (var i=0; i<arr.length; i++) {\n if (what === arr[i]) {\n return true;\n }\n }\n return false;\n }\n }\n\n this.get_content = function () { //function to capture regular content between tags\n\n var input_char = '',\n content = [],\n space = false; //if a space is needed\n\n while (this.input.charAt(this.pos) !== '<') {\n if (this.pos >= this.input.length) {\n return content.length?content.join(''):['', 'TK_EOF'];\n }\n\n input_char = this.input.charAt(this.pos);\n this.pos++;\n this.line_char_count++;\n\n if (this.Utils.in_array(input_char, this.Utils.whitespace)) {\n if (content.length) {\n space = true;\n }\n this.line_char_count--;\n continue; //don't want to insert unnecessary space\n }\n else if (space) {\n if (this.line_char_count >= this.max_char) { //insert a line when the max_char is reached\n content.push('\\n');\n for (var i=0; i<this.indent_level; i++) {\n content.push(this.indent_string);\n }\n this.line_char_count = 0;\n }\n else{\n content.push(' ');\n this.line_char_count++;\n }\n space = false;\n }\n content.push(input_char); //letter at-a-time (or string) inserted to an array\n }\n return content.length?content.join(''):'';\n }\n\n this.get_contents_to = function (name) { //get the full content of a script or style to pass to js_beautify\n if (this.pos == this.input.length) {\n return ['', 'TK_EOF'];\n }\n var input_char = '';\n var content = '';\n var reg_match = new RegExp('\\<\\/' + name + '\\\\s*\\>', 'igm');\n reg_match.lastIndex = this.pos;\n var reg_array = reg_match.exec(this.input);\n var end_script = reg_array?reg_array.index:this.input.length; //absolute end of script\n if(this.pos < end_script) { //get everything in between the script tags\n content = this.input.substring(this.pos, end_script);\n this.pos = end_script;\n }\n return content;\n }\n\n this.record_tag = function (tag){ //function to record a tag and its parent in this.tags Object\n if (this.tags[tag + 'count']) { //check for the existence of this tag type\n this.tags[tag + 'count']++;\n this.tags[tag + this.tags[tag + 'count']] = this.indent_level; //and record the present indent level\n }\n else { //otherwise initialize this tag type\n this.tags[tag + 'count'] = 1;\n this.tags[tag + this.tags[tag + 'count']] = this.indent_level; //and record the present indent level\n }\n this.tags[tag + this.tags[tag + 'count'] + 'parent'] = this.tags.parent; //set the parent (i.e. in the case of a div this.tags.div1parent)\n this.tags.parent = tag + this.tags[tag + 'count']; //and make this the current parent (i.e. in the case of a div 'div1')\n }\n\n this.retrieve_tag = function (tag) { //function to retrieve the opening tag to the corresponding closer\n if (this.tags[tag + 'count']) { //if the openener is not in the Object we ignore it\n var temp_parent = this.tags.parent; //check to see if it's a closable tag.\n while (temp_parent) { //till we reach '' (the initial value);\n if (tag + this.tags[tag + 'count'] === temp_parent) { //if this is it use it\n break;\n }\n temp_parent = this.tags[temp_parent + 'parent']; //otherwise keep on climbing up the DOM Tree\n }\n if (temp_parent) { //if we caught something\n this.indent_level = this.tags[tag + this.tags[tag + 'count']]; //set the indent_level accordingly\n this.tags.parent = this.tags[temp_parent + 'parent']; //and set the current parent\n }\n delete this.tags[tag + this.tags[tag + 'count'] + 'parent']; //delete the closed tags parent reference...\n delete this.tags[tag + this.tags[tag + 'count']]; //...and the tag itself\n if (this.tags[tag + 'count'] == 1) {\n delete this.tags[tag + 'count'];\n }\n else {\n this.tags[tag + 'count']--;\n }\n }\n }\n\n this.get_tag = function () { //function to get a full tag and parse its type\n var input_char = '',\n content = [],\n space = false,\n tag_start, tag_end;\n\n do {\n if (this.pos >= this.input.length) {\n return content.length?content.join(''):['', 'TK_EOF'];\n }\n\n input_char = this.input.charAt(this.pos);\n this.pos++;\n this.line_char_count++;\n\n if (this.Utils.in_array(input_char, this.Utils.whitespace)) { //don't want to insert unnecessary space\n space = true;\n this.line_char_count--;\n continue;\n }\n\n if (input_char === \"'\" || input_char === '\"') {\n if (!content[1] || content[1] !== '!') { //if we're in a comment strings don't get treated specially\n input_char += this.get_unformatted(input_char);\n space = true;\n }\n }\n\n if (input_char === '=') { //no space before =\n space = false;\n }\n\n if (content.length && content[content.length-1] !== '=' && input_char !== '>'\n && space) { //no space after = or before >\n if (this.line_char_count >= this.max_char) {\n this.print_newline(false, content);\n this.line_char_count = 0;\n }\n else {\n content.push(' ');\n this.line_char_count++;\n }\n space = false;\n }\n if (input_char === '<') {\n tag_start = this.pos - 1;\n }\n content.push(input_char); //inserts character at-a-time (or string)\n } while (input_char !== '>');\n\n var tag_complete = content.join('');\n var tag_index;\n if (tag_complete.indexOf(' ') != -1) { //if there's whitespace, thats where the tag name ends\n tag_index = tag_complete.indexOf(' ');\n }\n else { //otherwise go with the tag ending\n tag_index = tag_complete.indexOf('>');\n }\n var tag_check = tag_complete.substring(1, tag_index).toLowerCase();\n if (tag_complete.charAt(tag_complete.length-2) === '/' ||\n this.Utils.in_array(tag_check, this.Utils.single_token)) { //if this tag name is a single tag type (either in the list or has a closing /)\n this.tag_type = 'SINGLE';\n }\n else if (tag_check === 'script') { //for later script handling\n this.record_tag(tag_check);\n this.tag_type = 'SCRIPT';\n }\n else if (tag_check === 'style') { //for future style handling (for now it justs uses get_content)\n this.record_tag(tag_check);\n this.tag_type = 'STYLE';\n }\n else if (this.Utils.in_array(tag_check, unformatted)) { // do not reformat the \"unformatted\" tags\n var comment = this.get_unformatted('</'+tag_check+'>', tag_complete); //...delegate to get_unformatted function\n content.push(comment);\n // Preserve collapsed whitespace either before or after this tag.\n if (tag_start > 0 && this.Utils.in_array(this.input.charAt(tag_start - 1), this.Utils.whitespace)){\n content.splice(0, 0, this.input.charAt(tag_start - 1));\n }\n tag_end = this.pos - 1;\n if (this.Utils.in_array(this.input.charAt(tag_end + 1), this.Utils.whitespace)){\n content.push(this.input.charAt(tag_end + 1));\n }\n this.tag_type = 'SINGLE';\n }\n else if (tag_check.charAt(0) === '!') { //peek for <!-- comment\n if (tag_check.indexOf('[if') != -1) { //peek for <!--[if conditional comment\n if (tag_complete.indexOf('!IE') != -1) { //this type needs a closing --> so...\n var comment = this.get_unformatted('-->', tag_complete); //...delegate to get_unformatted\n content.push(comment);\n }\n this.tag_type = 'START';\n }\n else if (tag_check.indexOf('[endif') != -1) {//peek for <!--[endif end conditional comment\n this.tag_type = 'END';\n this.unindent();\n }\n else if (tag_check.indexOf('[cdata[') != -1) { //if it's a <[cdata[ comment...\n var comment = this.get_unformatted(']]>', tag_complete); //...delegate to get_unformatted function\n content.push(comment);\n this.tag_type = 'SINGLE'; //<![CDATA[ comments are treated like single tags\n }\n else {\n var comment = this.get_unformatted('-->', tag_complete);\n content.push(comment);\n this.tag_type = 'SINGLE';\n }\n }\n else {\n if (tag_check.charAt(0) === '/') { //this tag is a double tag so check for tag-ending\n this.retrieve_tag(tag_check.substring(1)); //remove it and all ancestors\n this.tag_type = 'END';\n }\n else { //otherwise it's a start-tag\n this.record_tag(tag_check); //push it on the tag stack\n this.tag_type = 'START';\n }\n if (this.Utils.in_array(tag_check, this.Utils.extra_liners)) { //check if this double needs an extra line\n this.print_newline(true, this.output);\n }\n }\n return content.join(''); //returns fully formatted tag\n }\n\n this.get_unformatted = function (delimiter, orig_tag) { //function to return unformatted content in its entirety\n\n if (orig_tag && orig_tag.toLowerCase().indexOf(delimiter) != -1) {\n return '';\n }\n var input_char = '';\n var content = '';\n var space = true;\n do {\n\n if (this.pos >= this.input.length) {\n return content;\n }\n\n input_char = this.input.charAt(this.pos);\n this.pos++\n\n if (this.Utils.in_array(input_char, this.Utils.whitespace)) {\n if (!space) {\n this.line_char_count--;\n continue;\n }\n if (input_char === '\\n' || input_char === '\\r') {\n content += '\\n';\n /* Don't change tab indention for unformatted blocks. If using code for html editing, this will greatly affect <pre> tags if they are specified in the 'unformatted array'\n for (var i=0; i<this.indent_level; i++) {\n content += this.indent_string;\n }\n space = false; //...and make sure other indentation is erased\n */\n this.line_char_count = 0;\n continue;\n }\n }\n content += input_char;\n this.line_char_count++;\n space = true;\n\n\n } while (content.toLowerCase().indexOf(delimiter) == -1);\n return content;\n }\n\n this.get_token = function () { //initial handler for token-retrieval\n var token;\n\n if (this.last_token === 'TK_TAG_SCRIPT' || this.last_token === 'TK_TAG_STYLE') { //check if we need to format javascript\n var type = this.last_token.substr(7)\n token = this.get_contents_to(type);\n if (typeof token !== 'string') {\n return token;\n }\n return [token, 'TK_' + type];\n }\n if (this.current_mode === 'CONTENT') {\n token = this.get_content();\n if (typeof token !== 'string') {\n return token;\n }\n else {\n return [token, 'TK_CONTENT'];\n }\n }\n\n if (this.current_mode === 'TAG') {\n token = this.get_tag();\n if (typeof token !== 'string') {\n return token;\n }\n else {\n var tag_name_type = 'TK_TAG_' + this.tag_type;\n return [token, tag_name_type];\n }\n }\n }\n\n this.get_full_indent = function (level) {\n level = this.indent_level + level || 0;\n if (level < 1)\n return '';\n\n return Array(level + 1).join(this.indent_string);\n }\n\n\n this.printer = function (js_source, indent_character, indent_size, max_char, brace_style) { //handles input/output and some other printing functions\n\n this.input = js_source || ''; //gets the input for the Parser\n this.output = [];\n this.indent_character = indent_character;\n this.indent_string = '';\n this.indent_size = indent_size;\n this.brace_style = brace_style;\n this.indent_level = 0;\n this.max_char = max_char;\n this.line_char_count = 0; //count to see if max_char was exceeded\n\n for (var i=0; i<this.indent_size; i++) {\n this.indent_string += this.indent_character;\n }\n\n this.print_newline = function (ignore, arr) {\n this.line_char_count = 0;\n if (!arr || !arr.length) {\n return;\n }\n if (!ignore) { //we might want the extra line\n while (this.Utils.in_array(arr[arr.length-1], this.Utils.whitespace)) {\n arr.pop();\n }\n }\n arr.push('\\n');\n for (var i=0; i<this.indent_level; i++) {\n arr.push(this.indent_string);\n }\n }\n\n this.print_token = function (text) {\n this.output.push(text);\n }\n\n this.indent = function () {\n this.indent_level++;\n }\n\n this.unindent = function () {\n if (this.indent_level > 0) {\n this.indent_level--;\n }\n }\n }\n return this;\n }\n\n /*_____________________--------------------_____________________*/\n\n multi_parser = new Parser(); //wrapping functions Parser\n multi_parser.printer(html_source, indent_character, indent_size, max_char, brace_style); //initialize starting values\n\n while (true) {\n var t = multi_parser.get_token();\n multi_parser.token_text = t[0];\n multi_parser.token_type = t[1];\n\n if (multi_parser.token_type === 'TK_EOF') {\n break;\n }\n\n switch (multi_parser.token_type) {\n case 'TK_TAG_START':\n multi_parser.print_newline(false, multi_parser.output);\n multi_parser.print_token(multi_parser.token_text);\n multi_parser.indent();\n multi_parser.current_mode = 'CONTENT';\n break;\n case 'TK_TAG_STYLE':\n case 'TK_TAG_SCRIPT':\n multi_parser.print_newline(false, multi_parser.output);\n multi_parser.print_token(multi_parser.token_text);\n multi_parser.current_mode = 'CONTENT';\n break;\n case 'TK_TAG_END':\n //Print new line only if the tag has no content and has child\n if (multi_parser.last_token === 'TK_CONTENT' && multi_parser.last_text === '') {\n var tag_name = multi_parser.token_text.match(/\\w+/)[0];\n var tag_extracted_from_last_output = multi_parser.output[multi_parser.output.length -1].match(/<\\s*(\\w+)/);\n if (tag_extracted_from_last_output === null || tag_extracted_from_last_output[1] !== tag_name)\n multi_parser.print_newline(true, multi_parser.output);\n }\n multi_parser.print_token(multi_parser.token_text);\n multi_parser.current_mode = 'CONTENT';\n break;\n case 'TK_TAG_SINGLE':\n // Don't add a newline before elements that should remain unformatted.\n var tag_check = multi_parser.token_text.match(/^\\s*<([a-z]+)/i);\n if (!tag_check || !multi_parser.Utils.in_array(tag_check[1], unformatted)){\n multi_parser.print_newline(false, multi_parser.output);\n }\n multi_parser.print_token(multi_parser.token_text);\n multi_parser.current_mode = 'CONTENT';\n break;\n case 'TK_CONTENT':\n if (multi_parser.token_text !== '') {\n multi_parser.print_token(multi_parser.token_text);\n }\n multi_parser.current_mode = 'TAG';\n break;\n case 'TK_STYLE':\n case 'TK_SCRIPT':\n if (multi_parser.token_text !== '') {\n multi_parser.output.push('\\n');\n var text = multi_parser.token_text;\n if (multi_parser.token_type == 'TK_SCRIPT') {\n var _beautifier = typeof js_beautify == 'function' && js_beautify;\n } else if (multi_parser.token_type == 'TK_STYLE') {\n var _beautifier = typeof css_beautify == 'function' && css_beautify;\n }\n\n if (options.indent_scripts == \"keep\") {\n var script_indent_level = 0;\n } else if (options.indent_scripts == \"separate\") {\n var script_indent_level = -multi_parser.indent_level;\n } else {\n var script_indent_level = 1;\n }\n\n var indentation = multi_parser.get_full_indent(script_indent_level);\n if (_beautifier) {\n // call the Beautifier if avaliable\n text = _beautifier(text.replace(/^\\s*/, indentation), options);\n } else {\n // simply indent the string otherwise\n var white = text.match(/^\\s*/)[0];\n var _level = white.match(/[^\\n\\r]*$/)[0].split(multi_parser.indent_string).length - 1;\n var reindent = multi_parser.get_full_indent(script_indent_level -_level);\n text = text.replace(/^\\s*/, indentation)\n .replace(/\\r\\n|\\r|\\n/g, '\\n' + reindent)\n .replace(/\\s*$/, '');\n }\n if (text) {\n multi_parser.print_token(text);\n multi_parser.print_newline(true, multi_parser.output);\n }\n }\n multi_parser.current_mode = 'TAG';\n break;\n }\n multi_parser.last_token = multi_parser.token_type;\n multi_parser.last_text = multi_parser.token_text;\n }\n return multi_parser.output.join('');\n}\n\nmodule.exports = {\n prettyPrint: style_html\n};","// empty export to remove `chalk` from `jsondiffpatch` during bundling.\n\nexport default null\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","/** @returns {void} */\nexport function noop() {}\n\nexport const identity = (x) => x;\n\n/**\n * @template T\n * @template S\n * @param {T} tar\n * @param {S} src\n * @returns {T & S}\n */\nexport function assign(tar, src) {\n\t// @ts-ignore\n\tfor (const k in src) tar[k] = src[k];\n\treturn /** @type {T & S} */ (tar);\n}\n\n// Adapted from https://github.com/then/is-promise/blob/master/index.js\n// Distributed under MIT License https://github.com/then/is-promise/blob/master/LICENSE\n/**\n * @param {any} value\n * @returns {value is PromiseLike<any>}\n */\nexport function is_promise(value) {\n\treturn (\n\t\t!!value &&\n\t\t(typeof value === 'object' || typeof value === 'function') &&\n\t\ttypeof (/** @type {any} */ (value).then) === 'function'\n\t);\n}\n\n/** @returns {void} */\nexport function add_location(element, file, line, column, char) {\n\telement.__svelte_meta = {\n\t\tloc: { file, line, column, char }\n\t};\n}\n\nexport function run(fn) {\n\treturn fn();\n}\n\nexport function blank_object() {\n\treturn Object.create(null);\n}\n\n/**\n * @param {Function[]} fns\n * @returns {void}\n */\nexport function run_all(fns) {\n\tfns.forEach(run);\n}\n\n/**\n * @param {any} thing\n * @returns {thing is Function}\n */\nexport function is_function(thing) {\n\treturn typeof thing === 'function';\n}\n\n/** @returns {boolean} */\nexport function safe_not_equal(a, b) {\n\treturn a != a ? b == b : a !== b || (a && typeof a === 'object') || typeof a === 'function';\n}\n\nlet src_url_equal_anchor;\n\n/**\n * @param {string} element_src\n * @param {string} url\n * @returns {boolean}\n */\nexport function src_url_equal(element_src, url) {\n\tif (element_src === url) return true;\n\tif (!src_url_equal_anchor) {\n\t\tsrc_url_equal_anchor = document.createElement('a');\n\t}\n\t// This is actually faster than doing URL(..).href\n\tsrc_url_equal_anchor.href = url;\n\treturn element_src === src_url_equal_anchor.href;\n}\n\n/** @param {string} srcset */\nfunction split_srcset(srcset) {\n\treturn srcset.split(',').map((src) => src.trim().split(' ').filter(Boolean));\n}\n\n/**\n * @param {HTMLSourceElement | HTMLImageElement} element_srcset\n * @param {string | undefined | null} srcset\n * @returns {boolean}\n */\nexport function srcset_url_equal(element_srcset, srcset) {\n\tconst element_urls = split_srcset(element_srcset.srcset);\n\tconst urls = split_srcset(srcset || '');\n\n\treturn (\n\t\turls.length === element_urls.length &&\n\t\turls.every(\n\t\t\t([url, width], i) =>\n\t\t\t\twidth === element_urls[i][1] &&\n\t\t\t\t// We need to test both ways because Vite will create an a full URL with\n\t\t\t\t// `new URL(asset, import.meta.url).href` for the client when `base: './'`, and the\n\t\t\t\t// relative URLs inside srcset are not automatically resolved to absolute URLs by\n\t\t\t\t// browsers (in contrast to img.src). This means both SSR and DOM code could\n\t\t\t\t// contain relative or absolute URLs.\n\t\t\t\t(src_url_equal(element_urls[i][0], url) || src_url_equal(url, element_urls[i][0]))\n\t\t)\n\t);\n}\n\n/** @returns {boolean} */\nexport function not_equal(a, b) {\n\treturn a != a ? b == b : a !== b;\n}\n\n/** @returns {boolean} */\nexport function is_empty(obj) {\n\treturn Object.keys(obj).length === 0;\n}\n\n/** @returns {void} */\nexport function validate_store(store, name) {\n\tif (store != null && typeof store.subscribe !== 'function') {\n\t\tthrow new Error(`'${name}' is not a store with a 'subscribe' method`);\n\t}\n}\n\nexport function subscribe(store, ...callbacks) {\n\tif (store == null) {\n\t\tfor (const callback of callbacks) {\n\t\t\tcallback(undefined);\n\t\t}\n\t\treturn noop;\n\t}\n\tconst unsub = store.subscribe(...callbacks);\n\treturn unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;\n}\n\n/**\n * Get the current value from a store by subscribing and immediately unsubscribing.\n *\n * https://svelte.dev/docs/svelte-store#get\n * @template T\n * @param {import('../store/public.js').Readable<T>} store\n * @returns {T}\n */\nexport function get_store_value(store) {\n\tlet value;\n\tsubscribe(store, (_) => (value = _))();\n\treturn value;\n}\n\n/** @returns {void} */\nexport function component_subscribe(component, store, callback) {\n\tcomponent.$$.on_destroy.push(subscribe(store, callback));\n}\n\nexport function create_slot(definition, ctx, $$scope, fn) {\n\tif (definition) {\n\t\tconst slot_ctx = get_slot_context(definition, ctx, $$scope, fn);\n\t\treturn definition[0](slot_ctx);\n\t}\n}\n\nfunction get_slot_context(definition, ctx, $$scope, fn) {\n\treturn definition[1] && fn ? assign($$scope.ctx.slice(), definition[1](fn(ctx))) : $$scope.ctx;\n}\n\nexport function get_slot_changes(definition, $$scope, dirty, fn) {\n\tif (definition[2] && fn) {\n\t\tconst lets = definition[2](fn(dirty));\n\t\tif ($$scope.dirty === undefined) {\n\t\t\treturn lets;\n\t\t}\n\t\tif (typeof lets === 'object') {\n\t\t\tconst merged = [];\n\t\t\tconst len = Math.max($$scope.dirty.length, lets.length);\n\t\t\tfor (let i = 0; i < len; i += 1) {\n\t\t\t\tmerged[i] = $$scope.dirty[i] | lets[i];\n\t\t\t}\n\t\t\treturn merged;\n\t\t}\n\t\treturn $$scope.dirty | lets;\n\t}\n\treturn $$scope.dirty;\n}\n\n/** @returns {void} */\nexport function update_slot_base(\n\tslot,\n\tslot_definition,\n\tctx,\n\t$$scope,\n\tslot_changes,\n\tget_slot_context_fn\n) {\n\tif (slot_changes) {\n\t\tconst slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);\n\t\tslot.p(slot_context, slot_changes);\n\t}\n}\n\n/** @returns {void} */\nexport function update_slot(\n\tslot,\n\tslot_definition,\n\tctx,\n\t$$scope,\n\tdirty,\n\tget_slot_changes_fn,\n\tget_slot_context_fn\n) {\n\tconst slot_changes = get_slot_changes(slot_definition, $$scope, dirty, get_slot_changes_fn);\n\tupdate_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn);\n}\n\n/** @returns {any[] | -1} */\nexport function get_all_dirty_from_scope($$scope) {\n\tif ($$scope.ctx.length > 32) {\n\t\tconst dirty = [];\n\t\tconst length = $$scope.ctx.length / 32;\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tdirty[i] = -1;\n\t\t}\n\t\treturn dirty;\n\t}\n\treturn -1;\n}\n\n/** @returns {{}} */\nexport function exclude_internal_props(props) {\n\tconst result = {};\n\tfor (const k in props) if (k[0] !== '$') result[k] = props[k];\n\treturn result;\n}\n\n/** @returns {{}} */\nexport function compute_rest_props(props, keys) {\n\tconst rest = {};\n\tkeys = new Set(keys);\n\tfor (const k in props) if (!keys.has(k) && k[0] !== '$') rest[k] = props[k];\n\treturn rest;\n}\n\n/** @returns {{}} */\nexport function compute_slots(slots) {\n\tconst result = {};\n\tfor (const key in slots) {\n\t\tresult[key] = true;\n\t}\n\treturn result;\n}\n\n/** @returns {(this: any, ...args: any[]) => void} */\nexport function once(fn) {\n\tlet ran = false;\n\treturn function (...args) {\n\t\tif (ran) return;\n\t\tran = true;\n\t\tfn.call(this, ...args);\n\t};\n}\n\nexport function null_to_empty(value) {\n\treturn value == null ? '' : value;\n}\n\nexport function set_store_value(store, ret, value) {\n\tstore.set(value);\n\treturn ret;\n}\n\nexport const has_prop = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);\n\nexport function action_destroyer(action_result) {\n\treturn action_result && is_function(action_result.destroy) ? action_result.destroy : noop;\n}\n\n/** @param {number | string} value\n * @returns {[number, string]}\n */\nexport function split_css_unit(value) {\n\tconst split = typeof value === 'string' && value.match(/^\\s*(-?[\\d.]+)([^\\s]*)\\s*$/);\n\treturn split ? [parseFloat(split[1]), split[2] || 'px'] : [/** @type {number} */ (value), 'px'];\n}\n\nexport const contenteditable_truthy_values = ['', true, 1, 'true', 'contenteditable'];\n","import { contenteditable_truthy_values, has_prop } from './utils.js';\n\nimport { ResizeObserverSingleton } from './ResizeObserverSingleton.js';\n\n// Track which nodes are claimed during hydration. Unclaimed nodes can then be removed from the DOM\n// at the end of hydration without touching the remaining nodes.\nlet is_hydrating = false;\n\n/**\n * @returns {void}\n */\nexport function start_hydrating() {\n\tis_hydrating = true;\n}\n\n/**\n * @returns {void}\n */\nexport function end_hydrating() {\n\tis_hydrating = false;\n}\n\n/**\n * @param {number} low\n * @param {number} high\n * @param {(index: number) => number} key\n * @param {number} value\n * @returns {number}\n */\nfunction upper_bound(low, high, key, value) {\n\t// Return first index of value larger than input value in the range [low, high)\n\twhile (low < high) {\n\t\tconst mid = low + ((high - low) >> 1);\n\t\tif (key(mid) <= value) {\n\t\t\tlow = mid + 1;\n\t\t} else {\n\t\t\thigh = mid;\n\t\t}\n\t}\n\treturn low;\n}\n\n/**\n * @param {NodeEx} target\n * @returns {void}\n */\nfunction init_hydrate(target) {\n\tif (target.hydrate_init) return;\n\ttarget.hydrate_init = true;\n\t// We know that all children have claim_order values since the unclaimed have been detached if target is not <head>\n\n\tlet children = /** @type {ArrayLike<NodeEx2>} */ (target.childNodes);\n\t// If target is <head>, there may be children without claim_order\n\tif (target.nodeName === 'HEAD') {\n\t\tconst my_children = [];\n\t\tfor (let i = 0; i < children.length; i++) {\n\t\t\tconst node = children[i];\n\t\t\tif (node.claim_order !== undefined) {\n\t\t\t\tmy_children.push(node);\n\t\t\t}\n\t\t}\n\t\tchildren = my_children;\n\t}\n\t/*\n\t * Reorder claimed children optimally.\n\t * We can reorder claimed children optimally by finding the longest subsequence of\n\t * nodes that are already claimed in order and only moving the rest. The longest\n\t * subsequence of nodes that are claimed in order can be found by\n\t * computing the longest increasing subsequence of .claim_order values.\n\t *\n\t * This algorithm is optimal in generating the least amount of reorder operations\n\t * possible.\n\t *\n\t * Proof:\n\t * We know that, given a set of reordering operations, the nodes that do not move\n\t * always form an increasing subsequence, since they do not move among each other\n\t * meaning that they must be already ordered among each other. Thus, the maximal\n\t * set of nodes that do not move form a longest increasing subsequence.\n\t */\n\t// Compute longest increasing subsequence\n\t// m: subsequence length j => index k of smallest value that ends an increasing subsequence of length j\n\tconst m = new Int32Array(children.length + 1);\n\t// Predecessor indices + 1\n\tconst p = new Int32Array(children.length);\n\tm[0] = -1;\n\tlet longest = 0;\n\tfor (let i = 0; i < children.length; i++) {\n\t\tconst current = children[i].claim_order;\n\t\t// Find the largest subsequence length such that it ends in a value less than our current value\n\t\t// upper_bound returns first greater value, so we subtract one\n\t\t// with fast path for when we are on the current longest subsequence\n\t\tconst seq_len =\n\t\t\t(longest > 0 && children[m[longest]].claim_order <= current\n\t\t\t\t? longest + 1\n\t\t\t\t: upper_bound(1, longest, (idx) => children[m[idx]].claim_order, current)) - 1;\n\t\tp[i] = m[seq_len] + 1;\n\t\tconst new_len = seq_len + 1;\n\t\t// We can guarantee that current is the smallest value. Otherwise, we would have generated a longer sequence.\n\t\tm[new_len] = i;\n\t\tlongest = Math.max(new_len, longest);\n\t}\n\t// The longest increasing subsequence of nodes (initially reversed)\n\n\t/**\n\t * @type {NodeEx2[]}\n\t */\n\tconst lis = [];\n\t// The rest of the nodes, nodes that will be moved\n\n\t/**\n\t * @type {NodeEx2[]}\n\t */\n\tconst to_move = [];\n\tlet last = children.length - 1;\n\tfor (let cur = m[longest] + 1; cur != 0; cur = p[cur - 1]) {\n\t\tlis.push(children[cur - 1]);\n\t\tfor (; last >= cur; last--) {\n\t\t\tto_move.push(children[last]);\n\t\t}\n\t\tlast--;\n\t}\n\tfor (; last >= 0; last--) {\n\t\tto_move.push(children[last]);\n\t}\n\tlis.reverse();\n\t// We sort the nodes being moved to guarantee that their insertion order matches the claim order\n\tto_move.sort((a, b) => a.claim_order - b.claim_order);\n\t// Finally, we move the nodes\n\tfor (let i = 0, j = 0; i < to_move.length; i++) {\n\t\twhile (j < lis.length && to_move[i].claim_order >= lis[j].claim_order) {\n\t\t\tj++;\n\t\t}\n\t\tconst anchor = j < lis.length ? lis[j] : null;\n\t\ttarget.insertBefore(to_move[i], anchor);\n\t}\n}\n\n/**\n * @param {Node} target\n * @param {Node} node\n * @returns {void}\n */\nexport function append(target, node) {\n\ttarget.appendChild(node);\n}\n\n/**\n * @param {Node} target\n * @param {string} style_sheet_id\n * @param {string} styles\n * @returns {void}\n */\nexport function append_styles(target, style_sheet_id, styles) {\n\tconst append_styles_to = get_root_for_style(target);\n\tif (!append_styles_to.getElementById(style_sheet_id)) {\n\t\tconst style = element('style');\n\t\tstyle.id = style_sheet_id;\n\t\tstyle.textContent = styles;\n\t\tappend_stylesheet(append_styles_to, style);\n\t}\n}\n\n/**\n * @param {Node} node\n * @returns {ShadowRoot | Document}\n */\nexport function get_root_for_style(node) {\n\tif (!node) return document;\n\tconst root = node.getRootNode ? node.getRootNode() : node.ownerDocument;\n\tif (root && /** @type {ShadowRoot} */ (root).host) {\n\t\treturn /** @type {ShadowRoot} */ (root);\n\t}\n\treturn node.ownerDocument;\n}\n\n/**\n * @param {Node} node\n * @returns {CSSStyleSheet}\n */\nexport function append_empty_stylesheet(node) {\n\tconst style_element = element('style');\n\t// For transitions to work without 'style-src: unsafe-inline' Content Security Policy,\n\t// these empty tags need to be allowed with a hash as a workaround until we move to the Web Animations API.\n\t// Using the hash for the empty string (for an empty tag) works in all browsers except Safari.\n\t// So as a workaround for the workaround, when we append empty style tags we set their content to /* empty */.\n\t// The hash 'sha256-9OlNO0DNEeaVzHL4RZwCLsBHA8WBQ8toBp/4F5XV2nc=' will then work even in Safari.\n\tstyle_element.textContent = '/* empty */';\n\tappend_stylesheet(get_root_for_style(node), style_element);\n\treturn style_element.sheet;\n}\n\n/**\n * @param {ShadowRoot | Document} node\n * @param {HTMLStyleElement} style\n * @returns {CSSStyleSheet}\n */\nfunction append_stylesheet(node, style) {\n\tappend(/** @type {Document} */ (node).head || node, style);\n\treturn style.sheet;\n}\n\n/**\n * @param {NodeEx} target\n * @param {NodeEx} node\n * @returns {void}\n */\nexport function append_hydration(target, node) {\n\tif (is_hydrating) {\n\t\tinit_hydrate(target);\n\t\tif (\n\t\t\ttarget.actual_end_child === undefined ||\n\t\t\t(target.actual_end_child !== null && target.actual_end_child.parentNode !== target)\n\t\t) {\n\t\t\ttarget.actual_end_child = target.firstChild;\n\t\t}\n\t\t// Skip nodes of undefined ordering\n\t\twhile (target.actual_end_child !== null && target.actual_end_child.claim_order === undefined) {\n\t\t\ttarget.actual_end_child = target.actual_end_child.nextSibling;\n\t\t}\n\t\tif (node !== target.actual_end_child) {\n\t\t\t// We only insert if the ordering of this node should be modified or the parent node is not target\n\t\t\tif (node.claim_order !== undefined || node.parentNode !== target) {\n\t\t\t\ttarget.insertBefore(node, target.actual_end_child);\n\t\t\t}\n\t\t} else {\n\t\t\ttarget.actual_end_child = node.nextSibling;\n\t\t}\n\t} else if (node.parentNode !== target || node.nextSibling !== null) {\n\t\ttarget.appendChild(node);\n\t}\n}\n\n/**\n * @param {Node} target\n * @param {Node} node\n * @param {Node} [anchor]\n * @returns {void}\n */\nexport function insert(target, node, anchor) {\n\ttarget.insertBefore(node, anchor || null);\n}\n\n/**\n * @param {NodeEx} target\n * @param {NodeEx} node\n * @param {NodeEx} [anchor]\n * @returns {void}\n */\nexport function insert_hydration(target, node, anchor) {\n\tif (is_hydrating && !anchor) {\n\t\tappend_hydration(target, node);\n\t} else if (node.parentNode !== target || node.nextSibling != anchor) {\n\t\ttarget.insertBefore(node, anchor || null);\n\t}\n}\n\n/**\n * @param {Node} node\n * @returns {void}\n */\nexport function detach(node) {\n\tif (node.parentNode) {\n\t\tnode.parentNode.removeChild(node);\n\t}\n}\n\n/**\n * @returns {void} */\nexport function destroy_each(iterations, detaching) {\n\tfor (let i = 0; i < iterations.length; i += 1) {\n\t\tif (iterations[i]) iterations[i].d(detaching);\n\t}\n}\n\n/**\n * @template {keyof HTMLElementTagNameMap} K\n * @param {K} name\n * @returns {HTMLElementTagNameMap[K]}\n */\nexport function element(name) {\n\treturn document.createElement(name);\n}\n\n/**\n * @template {keyof HTMLElementTagNameMap} K\n * @param {K} name\n * @param {string} is\n * @returns {HTMLElementTagNameMap[K]}\n */\nexport function element_is(name, is) {\n\treturn document.createElement(name, { is });\n}\n\n/**\n * @template T\n * @template {keyof T} K\n * @param {T} obj\n * @param {K[]} exclude\n * @returns {Pick<T, Exclude<keyof T, K>>}\n */\nexport function object_without_properties(obj, exclude) {\n\tconst target = /** @type {Pick<T, Exclude<keyof T, K>>} */ ({});\n\tfor (const k in obj) {\n\t\tif (\n\t\t\thas_prop(obj, k) &&\n\t\t\t// @ts-ignore\n\t\t\texclude.indexOf(k) === -1\n\t\t) {\n\t\t\t// @ts-ignore\n\t\t\ttarget[k] = obj[k];\n\t\t}\n\t}\n\treturn target;\n}\n\n/**\n * @template {keyof SVGElementTagNameMap} K\n * @param {K} name\n * @returns {SVGElement}\n */\nexport function svg_element(name) {\n\treturn document.createElementNS('http://www.w3.org/2000/svg', name);\n}\n\n/**\n * @param {string} data\n * @returns {Text}\n */\nexport function text(data) {\n\treturn document.createTextNode(data);\n}\n\n/**\n * @returns {Text} */\nexport function space() {\n\treturn text(' ');\n}\n\n/**\n * @returns {Text} */\nexport function empty() {\n\treturn text('');\n}\n\n/**\n * @param {string} content\n * @returns {Comment}\n */\nexport function comment(content) {\n\treturn document.createComment(content);\n}\n\n/**\n * @param {EventTarget} node\n * @param {string} event\n * @param {EventListenerOrEventListenerObject} handler\n * @param {boolean | AddEventListenerOptions | EventListenerOptions} [options]\n * @returns {() => void}\n */\nexport function listen(node, event, handler, options) {\n\tnode.addEventListener(event, handler, options);\n\treturn () => node.removeEventListener(event, handler, options);\n}\n\n/**\n * @returns {(event: any) => any} */\nexport function prevent_default(fn) {\n\treturn function (event) {\n\t\tevent.preventDefault();\n\t\t// @ts-ignore\n\t\treturn fn.call(this, event);\n\t};\n}\n\n/**\n * @returns {(event: any) => any} */\nexport function stop_propagation(fn) {\n\treturn function (event) {\n\t\tevent.stopPropagation();\n\t\t// @ts-ignore\n\t\treturn fn.call(this, event);\n\t};\n}\n\n/**\n * @returns {(event: any) => any} */\nexport function stop_immediate_propagation(fn) {\n\treturn function (event) {\n\t\tevent.stopImmediatePropagation();\n\t\t// @ts-ignore\n\t\treturn fn.call(this, event);\n\t};\n}\n\n/**\n * @returns {(event: any) => void} */\nexport function self(fn) {\n\treturn function (event) {\n\t\t// @ts-ignore\n\t\tif (event.target === this) fn.call(this, event);\n\t};\n}\n\n/**\n * @returns {(event: any) => void} */\nexport function trusted(fn) {\n\treturn function (event) {\n\t\t// @ts-ignore\n\t\tif (event.isTrusted) fn.call(this, event);\n\t};\n}\n\n/**\n * @param {Element} node\n * @param {string} attribute\n * @param {string} [value]\n * @returns {void}\n */\nexport function attr(node, attribute, value) {\n\tif (value == null) node.removeAttribute(attribute);\n\telse if (node.getAttribute(attribute) !== value) node.setAttribute(attribute, value);\n}\n/**\n * List of attributes that should always be set through the attr method,\n * because updating them through the property setter doesn't work reliably.\n * In the example of `width`/`height`, the problem is that the setter only\n * accepts numeric values, but the attribute can also be set to a string like `50%`.\n * If this list becomes too big, rethink this approach.\n */\nconst always_set_through_set_attribute = ['width', 'height'];\n\n/**\n * @param {Element & ElementCSSInlineStyle} node\n * @param {{ [x: string]: string }} attributes\n * @returns {void}\n */\nexport function set_attributes(node, attributes) {\n\t// @ts-ignore\n\tconst descriptors = Object.getOwnPropertyDescriptors(node.__proto__);\n\tfor (const key in attributes) {\n\t\tif (attributes[key] == null) {\n\t\t\tnode.removeAttribute(key);\n\t\t} else if (key === 'style') {\n\t\t\tnode.style.cssText = attributes[key];\n\t\t} else if (key === '__value') {\n\t\t\t/** @type {any} */ (node).value = node[key] = attributes[key];\n\t\t} else if (\n\t\t\tdescriptors[key] &&\n\t\t\tdescriptors[key].set &&\n\t\t\talways_set_through_set_attribute.indexOf(key) === -1\n\t\t) {\n\t\t\tnode[key] = attributes[key];\n\t\t} else {\n\t\t\tattr(node, key, attributes[key]);\n\t\t}\n\t}\n}\n\n/**\n * @param {Element & ElementCSSInlineStyle} node\n * @param {{ [x: string]: string }} attributes\n * @returns {void}\n */\nexport function set_svg_attributes(node, attributes) {\n\tfor (const key in attributes) {\n\t\tattr(node, key, attributes[key]);\n\t}\n}\n\n/**\n * @param {Record<string, unknown>} data_map\n * @returns {void}\n */\nexport function set_custom_element_data_map(node, data_map) {\n\tObject.keys(data_map).forEach((key) => {\n\t\tset_custom_element_data(node, key, data_map[key]);\n\t});\n}\n\n/**\n * @returns {void} */\nexport function set_custom_element_data(node, prop, value) {\n\tconst lower = prop.toLowerCase(); // for backwards compatibility with existing behavior we do lowercase first\n\tif (lower in node) {\n\t\tnode[lower] = typeof node[lower] === 'boolean' && value === '' ? true : value;\n\t} else if (prop in node) {\n\t\tnode[prop] = typeof node[prop] === 'boolean' && value === '' ? true : value;\n\t} else {\n\t\tattr(node, prop, value);\n\t}\n}\n\n/**\n * @param {string} tag\n */\nexport function set_dynamic_element_data(tag) {\n\treturn /-/.test(tag) ? set_custom_element_data_map : set_attributes;\n}\n\n/**\n * @returns {void}\n */\nexport function xlink_attr(node, attribute, value) {\n\tnode.setAttributeNS('http://www.w3.org/1999/xlink', attribute, value);\n}\n\n/**\n * @param {HTMLElement} node\n * @returns {string}\n */\nexport function get_svelte_dataset(node) {\n\treturn node.dataset.svelteH;\n}\n\n/**\n * @returns {unknown[]} */\nexport function get_binding_group_value(group, __value, checked) {\n\tconst value = new Set();\n\tfor (let i = 0; i < group.length; i += 1) {\n\t\tif (group[i].checked) value.add(group[i].__value);\n\t}\n\tif (!checked) {\n\t\tvalue.delete(__value);\n\t}\n\treturn Array.from(value);\n}\n\n/**\n * @param {HTMLInputElement[]} group\n * @returns {{ p(...inputs: HTMLInputElement[]): void; r(): void; }}\n */\nexport function init_binding_group(group) {\n\t/**\n\t * @type {HTMLInputElement[]} */\n\tlet _inputs;\n\treturn {\n\t\t/* push */ p(...inputs) {\n\t\t\t_inputs = inputs;\n\t\t\t_inputs.forEach((input) => group.push(input));\n\t\t},\n\t\t/* remove */ r() {\n\t\t\t_inputs.forEach((input) => group.splice(group.indexOf(input), 1));\n\t\t}\n\t};\n}\n\n/**\n * @param {number[]} indexes\n * @returns {{ u(new_indexes: number[]): void; p(...inputs: HTMLInputElement[]): void; r: () => void; }}\n */\nexport function init_binding_group_dynamic(group, indexes) {\n\t/**\n\t * @type {HTMLInputElement[]} */\n\tlet _group = get_binding_group(group);\n\n\t/**\n\t * @type {HTMLInputElement[]} */\n\tlet _inputs;\n\n\tfunction get_binding_group(group) {\n\t\tfor (let i = 0; i < indexes.length; i++) {\n\t\t\tgroup = group[indexes[i]] = group[indexes[i]] || [];\n\t\t}\n\t\treturn group;\n\t}\n\n\t/**\n\t * @returns {void} */\n\tfunction push() {\n\t\t_inputs.forEach((input) => _group.push(input));\n\t}\n\n\t/**\n\t * @returns {void} */\n\tfunction remove() {\n\t\t_inputs.forEach((input) => _group.splice(_group.indexOf(input), 1));\n\t}\n\treturn {\n\t\t/* update */ u(new_indexes) {\n\t\t\tindexes = new_indexes;\n\t\t\tconst new_group = get_binding_group(group);\n\t\t\tif (new_group !== _group) {\n\t\t\t\tremove();\n\t\t\t\t_group = new_group;\n\t\t\t\tpush();\n\t\t\t}\n\t\t},\n\t\t/* push */ p(...inputs) {\n\t\t\t_inputs = inputs;\n\t\t\tpush();\n\t\t},\n\t\t/* remove */ r: remove\n\t};\n}\n\n/** @returns {number} */\nexport function to_number(value) {\n\treturn value === '' ? null : +value;\n}\n\n/** @returns {any[]} */\nexport function time_ranges_to_array(ranges) {\n\tconst array = [];\n\tfor (let i = 0; i < ranges.length; i += 1) {\n\t\tarray.push({ start: ranges.start(i), end: ranges.end(i) });\n\t}\n\treturn array;\n}\n\n/**\n * @param {Element} element\n * @returns {ChildNode[]}\n */\nexport function children(element) {\n\treturn Array.from(element.childNodes);\n}\n\n/**\n * @param {ChildNodeArray} nodes\n * @returns {void}\n */\nfunction init_claim_info(nodes) {\n\tif (nodes.claim_info === undefined) {\n\t\tnodes.claim_info = { last_index: 0, total_claimed: 0 };\n\t}\n}\n\n/**\n * @template {ChildNodeEx} R\n * @param {ChildNodeArray} nodes\n * @param {(node: ChildNodeEx) => node is R} predicate\n * @param {(node: ChildNodeEx) => ChildNodeEx | undefined} process_node\n * @param {() => R} create_node\n * @param {boolean} dont_update_last_index\n * @returns {R}\n */\nfunction claim_node(nodes, predicate, process_node, create_node, dont_update_last_index = false) {\n\t// Try to find nodes in an order such that we lengthen the longest increasing subsequence\n\tinit_claim_info(nodes);\n\tconst result_node = (() => {\n\t\t// We first try to find an element after the previous one\n\t\tfor (let i = nodes.claim_info.last_index; i < nodes.length; i++) {\n\t\t\tconst node = nodes[i];\n\t\t\tif (predicate(node)) {\n\t\t\t\tconst replacement = process_node(node);\n\t\t\t\tif (replacement === undefined) {\n\t\t\t\t\tnodes.splice(i, 1);\n\t\t\t\t} else {\n\t\t\t\t\tnodes[i] = replacement;\n\t\t\t\t}\n\t\t\t\tif (!dont_update_last_index) {\n\t\t\t\t\tnodes.claim_info.last_index = i;\n\t\t\t\t}\n\t\t\t\treturn node;\n\t\t\t}\n\t\t}\n\t\t// Otherwise, we try to find one before\n\t\t// We iterate in reverse so that we don't go too far back\n\t\tfor (let i = nodes.claim_info.last_index - 1; i >= 0; i--) {\n\t\t\tconst node = nodes[i];\n\t\t\tif (predicate(node)) {\n\t\t\t\tconst replacement = process_node(node);\n\t\t\t\tif (replacement === undefined) {\n\t\t\t\t\tnodes.splice(i, 1);\n\t\t\t\t} else {\n\t\t\t\t\tnodes[i] = replacement;\n\t\t\t\t}\n\t\t\t\tif (!dont_update_last_index) {\n\t\t\t\t\tnodes.claim_info.last_index = i;\n\t\t\t\t} else if (replacement === undefined) {\n\t\t\t\t\t// Since we spliced before the last_index, we decrease it\n\t\t\t\t\tnodes.claim_info.last_index--;\n\t\t\t\t}\n\t\t\t\treturn node;\n\t\t\t}\n\t\t}\n\t\t// If we can't find any matching node, we create a new one\n\t\treturn create_node();\n\t})();\n\tresult_node.claim_order = nodes.claim_info.total_claimed;\n\tnodes.claim_info.total_claimed += 1;\n\treturn result_node;\n}\n\n/**\n * @param {ChildNodeArray} nodes\n * @param {string} name\n * @param {{ [key: string]: boolean }} attributes\n * @param {(name: string) => Element | SVGElement} create_element\n * @returns {Element | SVGElement}\n */\nfunction claim_element_base(nodes, name, attributes, create_element) {\n\treturn claim_node(\n\t\tnodes,\n\t\t/** @returns {node is Element | SVGElement} */\n\t\t(node) => node.nodeName === name,\n\t\t/** @param {Element} node */\n\t\t(node) => {\n\t\t\tconst remove = [];\n\t\t\tfor (let j = 0; j < node.attributes.length; j++) {\n\t\t\t\tconst attribute = node.attributes[j];\n\t\t\t\tif (!attributes[attribute.name]) {\n\t\t\t\t\tremove.push(attribute.name);\n\t\t\t\t}\n\t\t\t}\n\t\t\tremove.forEach((v) => node.removeAttribute(v));\n\t\t\treturn undefined;\n\t\t},\n\t\t() => create_element(name)\n\t);\n}\n\n/**\n * @param {ChildNodeArray} nodes\n * @param {string} name\n * @param {{ [key: string]: boolean }} attributes\n * @returns {Element | SVGElement}\n */\nexport function claim_element(nodes, name, attributes) {\n\treturn claim_element_base(nodes, name, attributes, element);\n}\n\n/**\n * @param {ChildNodeArray} nodes\n * @param {string} name\n * @param {{ [key: string]: boolean }} attributes\n * @returns {Element | SVGElement}\n */\nexport function claim_svg_element(nodes, name, attributes) {\n\treturn claim_element_base(nodes, name, attributes, svg_element);\n}\n\n/**\n * @param {ChildNodeArray} nodes\n * @returns {Text}\n */\nexport function claim_text(nodes, data) {\n\treturn claim_node(\n\t\tnodes,\n\t\t/** @returns {node is Text} */\n\t\t(node) => node.nodeType === 3,\n\t\t/** @param {Text} node */\n\t\t(node) => {\n\t\t\tconst data_str = '' + data;\n\t\t\tif (node.data.startsWith(data_str)) {\n\t\t\t\tif (node.data.length !== data_str.length) {\n\t\t\t\t\treturn node.splitText(data_str.length);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnode.data = data_str;\n\t\t\t}\n\t\t},\n\t\t() => text(data),\n\t\ttrue // Text nodes should not update last index since it is likely not worth it to eliminate an increasing subsequence of actual elements\n\t);\n}\n\n/**\n * @returns {Text} */\nexport function claim_space(nodes) {\n\treturn claim_text(nodes, ' ');\n}\n\n/**\n * @param {ChildNodeArray} nodes\n * @returns {Comment}\n */\nexport function claim_comment(nodes, data) {\n\treturn claim_node(\n\t\tnodes,\n\t\t/** @returns {node is Comment} */\n\t\t(node) => node.nodeType === 8,\n\t\t/** @param {Comment} node */\n\t\t(node) => {\n\t\t\tnode.data = '' + data;\n\t\t\treturn undefined;\n\t\t},\n\t\t() => comment(data),\n\t\ttrue\n\t);\n}\n\nfunction get_comment_idx(nodes, text, start) {\n\tfor (let i = start; i < nodes.length; i += 1) {\n\t\tconst node = nodes[i];\n\t\tif (node.nodeType === 8 /* comment node */ && node.textContent.trim() === text) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}\n\n/**\n * @param {boolean} is_svg\n * @returns {HtmlTagHydration}\n */\nexport function claim_html_tag(nodes, is_svg) {\n\t// find html opening tag\n\tconst start_index = get_comment_idx(nodes, 'HTML_TAG_START', 0);\n\tconst end_index = get_comment_idx(nodes, 'HTML_TAG_END', start_index + 1);\n\tif (start_index === -1 || end_index === -1) {\n\t\treturn new HtmlTagHydration(is_svg);\n\t}\n\n\tinit_claim_info(nodes);\n\tconst html_tag_nodes = nodes.splice(start_index, end_index - start_index + 1);\n\tdetach(html_tag_nodes[0]);\n\tdetach(html_tag_nodes[html_tag_nodes.length - 1]);\n\tconst claimed_nodes = html_tag_nodes.slice(1, html_tag_nodes.length - 1);\n\tif (claimed_nodes.length === 0) {\n\t\treturn new HtmlTagHydration(is_svg);\n\t}\n\tfor (const n of claimed_nodes) {\n\t\tn.claim_order = nodes.claim_info.total_claimed;\n\t\tnodes.claim_info.total_claimed += 1;\n\t}\n\treturn new HtmlTagHydration(is_svg, claimed_nodes);\n}\n\n/**\n * @param {Text} text\n * @param {unknown} data\n * @returns {void}\n */\nexport function set_data(text, data) {\n\tdata = '' + data;\n\tif (text.data === data) return;\n\ttext.data = /** @type {string} */ (data);\n}\n\n/**\n * @param {Text} text\n * @param {unknown} data\n * @returns {void}\n */\nexport function set_data_contenteditable(text, data) {\n\tdata = '' + data;\n\tif (text.wholeText === data) return;\n\ttext.data = /** @type {string} */ (data);\n}\n\n/**\n * @param {Text} text\n * @param {unknown} data\n * @param {string} attr_value\n * @returns {void}\n */\nexport function set_data_maybe_contenteditable(text, data, attr_value) {\n\tif (~contenteditable_truthy_values.indexOf(attr_value)) {\n\t\tset_data_contenteditable(text, data);\n\t} else {\n\t\tset_data(text, data);\n\t}\n}\n\n/**\n * @returns {void} */\nexport function set_input_value(input, value) {\n\tinput.value = value == null ? '' : value;\n}\n\n/**\n * @returns {void} */\nexport function set_input_type(input, type) {\n\ttry {\n\t\tinput.type = type;\n\t} catch (e) {\n\t\t// do nothing\n\t}\n}\n\n/**\n * @returns {void} */\nexport function set_style(node, key, value, important) {\n\tif (value == null) {\n\t\tnode.style.removeProperty(key);\n\t} else {\n\t\tnode.style.setProperty(key, value, important ? 'important' : '');\n\t}\n}\n\n/**\n * @returns {void} */\nexport function select_option(select, value, mounting) {\n\tfor (let i = 0; i < select.options.length; i += 1) {\n\t\tconst option = select.options[i];\n\t\tif (option.__value === value) {\n\t\t\toption.selected = true;\n\t\t\treturn;\n\t\t}\n\t}\n\tif (!mounting || value !== undefined) {\n\t\tselect.selectedIndex = -1; // no option should be selected\n\t}\n}\n\n/**\n * @returns {void} */\nexport function select_options(select, value) {\n\tfor (let i = 0; i < select.options.length; i += 1) {\n\t\tconst option = select.options[i];\n\t\toption.selected = ~value.indexOf(option.__value);\n\t}\n}\n\nexport function select_value(select) {\n\tconst selected_option = select.querySelector(':checked');\n\treturn selected_option && selected_option.__value;\n}\n\nexport function select_multiple_value(select) {\n\treturn [].map.call(select.querySelectorAll(':checked'), (option) => option.__value);\n}\n// unfortunately this can't be a constant as that wouldn't be tree-shakeable\n// so we cache the result instead\n\n/**\n * @type {boolean} */\nlet crossorigin;\n\n/**\n * @returns {boolean} */\nexport function is_crossorigin() {\n\tif (crossorigin === undefined) {\n\t\tcrossorigin = false;\n\t\ttry {\n\t\t\tif (typeof window !== 'undefined' && window.parent) {\n\t\t\t\tvoid window.parent.document;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tcrossorigin = true;\n\t\t}\n\t}\n\treturn crossorigin;\n}\n\n/**\n * @param {HTMLElement} node\n * @param {() => void} fn\n * @returns {() => void}\n */\nexport function add_iframe_resize_listener(node, fn) {\n\tconst computed_style = getComputedStyle(node);\n\tif (computed_style.position === 'static') {\n\t\tnode.style.position = 'relative';\n\t}\n\tconst iframe = element('iframe');\n\tiframe.setAttribute(\n\t\t'style',\n\t\t'display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; ' +\n\t\t\t'overflow: hidden; border: 0; opacity: 0; pointer-events: none; z-index: -1;'\n\t);\n\tiframe.setAttribute('aria-hidden', 'true');\n\tiframe.tabIndex = -1;\n\tconst crossorigin = is_crossorigin();\n\n\t/**\n\t * @type {() => void}\n\t */\n\tlet unsubscribe;\n\tif (crossorigin) {\n\t\tiframe.src = \"data:text/html,<script>onresize=function(){parent.postMessage(0,'*')}</script>\";\n\t\tunsubscribe = listen(\n\t\t\twindow,\n\t\t\t'message',\n\t\t\t/** @param {MessageEvent} event */ (event) => {\n\t\t\t\tif (event.source === iframe.contentWindow) fn();\n\t\t\t}\n\t\t);\n\t} else {\n\t\tiframe.src = 'about:blank';\n\t\tiframe.onload = () => {\n\t\t\tunsubscribe = listen(iframe.contentWindow, 'resize', fn);\n\t\t\t// make sure an initial resize event is fired _after_ the iframe is loaded (which is asynchronous)\n\t\t\t// see https://github.com/sveltejs/svelte/issues/4233\n\t\t\tfn();\n\t\t};\n\t}\n\tappend(node, iframe);\n\treturn () => {\n\t\tif (crossorigin) {\n\t\t\tunsubscribe();\n\t\t} else if (unsubscribe && iframe.contentWindow) {\n\t\t\tunsubscribe();\n\t\t}\n\t\tdetach(iframe);\n\t};\n}\nexport const resize_observer_content_box = /* @__PURE__ */ new ResizeObserverSingleton({\n\tbox: 'content-box'\n});\nexport const resize_observer_border_box = /* @__PURE__ */ new ResizeObserverSingleton({\n\tbox: 'border-box'\n});\nexport const resize_observer_device_pixel_content_box = /* @__PURE__ */ new ResizeObserverSingleton(\n\t{ box: 'device-pixel-content-box' }\n);\nexport { ResizeObserverSingleton };\n\n/**\n * @returns {void} */\nexport function toggle_class(element, name, toggle) {\n\t// The `!!` is required because an `undefined` flag means flipping the current state.\n\telement.classList.toggle(name, !!toggle);\n}\n\n/**\n * @template T\n * @param {string} type\n * @param {T} [detail]\n * @param {{ bubbles?: boolean, cancelable?: boolean }} [options]\n * @returns {CustomEvent<T>}\n */\nexport function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {\n\treturn new CustomEvent(type, { detail, bubbles, cancelable });\n}\n\n/**\n * @param {string} selector\n * @param {HTMLElement} parent\n * @returns {ChildNodeArray}\n */\nexport function query_selector_all(selector, parent = document.body) {\n\treturn Array.from(parent.querySelectorAll(selector));\n}\n\n/**\n * @param {string} nodeId\n * @param {HTMLElement} head\n * @returns {any[]}\n */\nexport function head_selector(nodeId, head) {\n\tconst result = [];\n\tlet started = 0;\n\tfor (const node of head.childNodes) {\n\t\tif (node.nodeType === 8 /* comment node */) {\n\t\t\tconst comment = node.textContent.trim();\n\t\t\tif (comment === `HEAD_${nodeId}_END`) {\n\t\t\t\tstarted -= 1;\n\t\t\t\tresult.push(node);\n\t\t\t} else if (comment === `HEAD_${nodeId}_START`) {\n\t\t\t\tstarted += 1;\n\t\t\t\tresult.push(node);\n\t\t\t}\n\t\t} else if (started > 0) {\n\t\t\tresult.push(node);\n\t\t}\n\t}\n\treturn result;\n}\n/** */\nexport class HtmlTag {\n\t/**\n\t * @private\n\t * @default false\n\t */\n\tis_svg = false;\n\t/** parent for creating node */\n\te = undefined;\n\t/** html tag nodes */\n\tn = undefined;\n\t/** target */\n\tt = undefined;\n\t/** anchor */\n\ta = undefined;\n\tconstructor(is_svg = false) {\n\t\tthis.is_svg = is_svg;\n\t\tthis.e = this.n = null;\n\t}\n\n\t/**\n\t * @param {string} html\n\t * @returns {void}\n\t */\n\tc(html) {\n\t\tthis.h(html);\n\t}\n\n\t/**\n\t * @param {string} html\n\t * @param {HTMLElement | SVGElement} target\n\t * @param {HTMLElement | SVGElement} anchor\n\t * @returns {void}\n\t */\n\tm(html, target, anchor = null) {\n\t\tif (!this.e) {\n\t\t\tif (this.is_svg)\n\t\t\t\tthis.e = svg_element(/** @type {keyof SVGElementTagNameMap} */ (target.nodeName));\n\t\t\t/** #7364 target for <template> may be provided as #document-fragment(11) */ else\n\t\t\t\tthis.e = element(\n\t\t\t\t\t/** @type {keyof HTMLElementTagNameMap} */ (\n\t\t\t\t\t\ttarget.nodeType === 11 ? 'TEMPLATE' : target.nodeName\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\tthis.t =\n\t\t\t\ttarget.tagName !== 'TEMPLATE'\n\t\t\t\t\t? target\n\t\t\t\t\t: /** @type {HTMLTemplateElement} */ (target).content;\n\t\t\tthis.c(html);\n\t\t}\n\t\tthis.i(anchor);\n\t}\n\n\t/**\n\t * @param {string} html\n\t * @returns {void}\n\t */\n\th(html) {\n\t\tthis.e.innerHTML = html;\n\t\tthis.n = Array.from(\n\t\t\tthis.e.nodeName === 'TEMPLATE' ? this.e.content.childNodes : this.e.childNodes\n\t\t);\n\t}\n\n\t/**\n\t * @returns {void} */\n\ti(anchor) {\n\t\tfor (let i = 0; i < this.n.length; i += 1) {\n\t\t\tinsert(this.t, this.n[i], anchor);\n\t\t}\n\t}\n\n\t/**\n\t * @param {string} html\n\t * @returns {void}\n\t */\n\tp(html) {\n\t\tthis.d();\n\t\tthis.h(html);\n\t\tthis.i(this.a);\n\t}\n\n\t/**\n\t * @returns {void} */\n\td() {\n\t\tthis.n.forEach(detach);\n\t}\n}\n\nexport class HtmlTagHydration extends HtmlTag {\n\t/** @type {Element[]} hydration claimed nodes */\n\tl = undefined;\n\n\tconstructor(is_svg = false, claimed_nodes) {\n\t\tsuper(is_svg);\n\t\tthis.e = this.n = null;\n\t\tthis.l = claimed_nodes;\n\t}\n\n\t/**\n\t * @param {string} html\n\t * @returns {void}\n\t */\n\tc(html) {\n\t\tif (this.l) {\n\t\t\tthis.n = this.l;\n\t\t} else {\n\t\t\tsuper.c(html);\n\t\t}\n\t}\n\n\t/**\n\t * @returns {void} */\n\ti(anchor) {\n\t\tfor (let i = 0; i < this.n.length; i += 1) {\n\t\t\tinsert_hydration(this.t, this.n[i], anchor);\n\t\t}\n\t}\n}\n\n/**\n * @param {NamedNodeMap} attributes\n * @returns {{}}\n */\nexport function attribute_to_object(attributes) {\n\tconst result = {};\n\tfor (const attribute of attributes) {\n\t\tresult[attribute.name] = attribute.value;\n\t}\n\treturn result;\n}\n\nconst escaped = {\n\t'\"': '&quot;',\n\t'&': '&amp;',\n\t'<': '&lt;'\n};\n\nconst regex_attribute_characters_to_escape = /[\"&<]/g;\n\n/**\n * Note that the attribute itself should be surrounded in double quotes\n * @param {any} attribute\n */\nfunction escape_attribute(attribute) {\n\treturn String(attribute).replace(regex_attribute_characters_to_escape, (match) => escaped[match]);\n}\n\n/**\n * @param {Record<string, string>} attributes\n */\nexport function stringify_spread(attributes) {\n\tlet str = ' ';\n\tfor (const key in attributes) {\n\t\tif (attributes[key] != null) {\n\t\t\tstr += `${key}=\"${escape_attribute(attributes[key])}\" `;\n\t\t}\n\t}\n\n\treturn str;\n}\n\n/**\n * @param {HTMLElement} element\n * @returns {{}}\n */\nexport function get_custom_elements_slots(element) {\n\tconst result = {};\n\telement.childNodes.forEach(\n\t\t/** @param {Element} node */ (node) => {\n\t\t\tresult[node.slot || 'default'] = true;\n\t\t}\n\t);\n\treturn result;\n}\n\nexport function construct_svelte_component(component, props) {\n\treturn new component(props);\n}\n\n/**\n * @typedef {Node & {\n * \tclaim_order?: number;\n * \thydrate_init?: true;\n * \tactual_end_child?: NodeEx;\n * \tchildNodes: NodeListOf<NodeEx>;\n * }} NodeEx\n */\n\n/** @typedef {ChildNode & NodeEx} ChildNodeEx */\n\n/** @typedef {NodeEx & { claim_order: number }} NodeEx2 */\n\n/**\n * @typedef {ChildNodeEx[] & {\n * \tclaim_info?: {\n * \t\tlast_index: number;\n * \t\ttotal_claimed: number;\n * \t};\n * }} ChildNodeArray\n */\n","import { custom_event } from './dom.js';\n\nexport let current_component;\n\n/** @returns {void} */\nexport function set_current_component(component) {\n\tcurrent_component = component;\n}\n\nexport function get_current_component() {\n\tif (!current_component) throw new Error('Function called outside component initialization');\n\treturn current_component;\n}\n\n/**\n * Schedules a callback to run immediately before the component is updated after any state change.\n *\n * The first time the callback runs will be before the initial `onMount`\n *\n * https://svelte.dev/docs/svelte#beforeupdate\n * @param {() => any} fn\n * @returns {void}\n */\nexport function beforeUpdate(fn) {\n\tget_current_component().$$.before_update.push(fn);\n}\n\n/**\n * The `onMount` function schedules a callback to run as soon as the component has been mounted to the DOM.\n * It must be called during the component's initialisation (but doesn't need to live *inside* the component;\n * it can be called from an external module).\n *\n * If a function is returned _synchronously_ from `onMount`, it will be called when the component is unmounted.\n *\n * `onMount` does not run inside a [server-side component](https://svelte.dev/docs#run-time-server-side-component-api).\n *\n * https://svelte.dev/docs/svelte#onmount\n * @template T\n * @param {() => import('./private.js').NotFunction<T> | Promise<import('./private.js').NotFunction<T>> | (() => any)} fn\n * @returns {void}\n */\nexport function onMount(fn) {\n\tget_current_component().$$.on_mount.push(fn);\n}\n\n/**\n * Schedules a callback to run immediately after the component has been updated.\n *\n * The first time the callback runs will be after the initial `onMount`\n *\n * https://svelte.dev/docs/svelte#afterupdate\n * @param {() => any} fn\n * @returns {void}\n */\nexport function afterUpdate(fn) {\n\tget_current_component().$$.after_update.push(fn);\n}\n\n/**\n * Schedules a callback to run immediately before the component is unmounted.\n *\n * Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the\n * only one that runs inside a server-side component.\n *\n * https://svelte.dev/docs/svelte#ondestroy\n * @param {() => any} fn\n * @returns {void}\n */\nexport function onDestroy(fn) {\n\tget_current_component().$$.on_destroy.push(fn);\n}\n\n/**\n * Creates an event dispatcher that can be used to dispatch [component events](https://svelte.dev/docs#template-syntax-component-directives-on-eventname).\n * Event dispatchers are functions that can take two arguments: `name` and `detail`.\n *\n * Component events created with `createEventDispatcher` create a\n * [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent).\n * These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture).\n * The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail)\n * property and can contain any type of data.\n *\n * The event dispatcher can be typed to narrow the allowed event names and the type of the `detail` argument:\n * ```ts\n * const dispatch = createEventDispatcher<{\n * loaded: never; // does not take a detail argument\n * change: string; // takes a detail argument of type string, which is required\n * optional: number | null; // takes an optional detail argument of type number\n * }>();\n * ```\n *\n * https://svelte.dev/docs/svelte#createeventdispatcher\n * @template {Record<string, any>} [EventMap=any]\n * @returns {import('./public.js').EventDispatcher<EventMap>}\n */\nexport function createEventDispatcher() {\n\tconst component = get_current_component();\n\treturn (type, detail, { cancelable = false } = {}) => {\n\t\tconst callbacks = component.$$.callbacks[type];\n\t\tif (callbacks) {\n\t\t\t// TODO are there situations where events could be dispatched\n\t\t\t// in a server (non-DOM) environment?\n\t\t\tconst event = custom_event(/** @type {string} */ (type), detail, { cancelable });\n\t\t\tcallbacks.slice().forEach((fn) => {\n\t\t\t\tfn.call(component, event);\n\t\t\t});\n\t\t\treturn !event.defaultPrevented;\n\t\t}\n\t\treturn true;\n\t};\n}\n\n/**\n * Associates an arbitrary `context` object with the current component and the specified `key`\n * and returns that object. The context is then available to children of the component\n * (including slotted content) with `getContext`.\n *\n * Like lifecycle functions, this must be called during component initialisation.\n *\n * https://svelte.dev/docs/svelte#setcontext\n * @template T\n * @param {any} key\n * @param {T} context\n * @returns {T}\n */\nexport function setContext(key, context) {\n\tget_current_component().$$.context.set(key, context);\n\treturn context;\n}\n\n/**\n * Retrieves the context that belongs to the closest parent component with the specified `key`.\n * Must be called during component initialisation.\n *\n * https://svelte.dev/docs/svelte#getcontext\n * @template T\n * @param {any} key\n * @returns {T}\n */\nexport function getContext(key) {\n\treturn get_current_component().$$.context.get(key);\n}\n\n/**\n * Retrieves the whole context map that belongs to the closest parent component.\n * Must be called during component initialisation. Useful, for example, if you\n * programmatically create a component and want to pass the existing context to it.\n *\n * https://svelte.dev/docs/svelte#getallcontexts\n * @template {Map<any, any>} [T=Map<any, any>]\n * @returns {T}\n */\nexport function getAllContexts() {\n\treturn get_current_component().$$.context;\n}\n\n/**\n * Checks whether a given `key` has been set in the context of a parent component.\n * Must be called during component initialisation.\n *\n * https://svelte.dev/docs/svelte#hascontext\n * @param {any} key\n * @returns {boolean}\n */\nexport function hasContext(key) {\n\treturn get_current_component().$$.context.has(key);\n}\n\n// TODO figure out if we still want to support\n// shorthand events, or if we want to implement\n// a real bubbling mechanism\n/**\n * @param component\n * @param event\n * @returns {void}\n */\nexport function bubble(component, event) {\n\tconst callbacks = component.$$.callbacks[event.type];\n\tif (callbacks) {\n\t\t// @ts-ignore\n\t\tcallbacks.slice().forEach((fn) => fn.call(this, event));\n\t}\n}\n","import { run_all } from './utils.js';\nimport { current_component, set_current_component } from './lifecycle.js';\n\nexport const dirty_components = [];\nexport const intros = { enabled: false };\nexport const binding_callbacks = [];\n\nlet render_callbacks = [];\n\nconst flush_callbacks = [];\n\nconst resolved_promise = /* @__PURE__ */ Promise.resolve();\n\nlet update_scheduled = false;\n\n/** @returns {void} */\nexport function schedule_update() {\n\tif (!update_scheduled) {\n\t\tupdate_scheduled = true;\n\t\tresolved_promise.then(flush);\n\t}\n}\n\n/** @returns {Promise<void>} */\nexport function tick() {\n\tschedule_update();\n\treturn resolved_promise;\n}\n\n/** @returns {void} */\nexport function add_render_callback(fn) {\n\trender_callbacks.push(fn);\n}\n\n/** @returns {void} */\nexport function add_flush_callback(fn) {\n\tflush_callbacks.push(fn);\n}\n\n// flush() calls callbacks in this order:\n// 1. All beforeUpdate callbacks, in order: parents before children\n// 2. All bind:this callbacks, in reverse order: children before parents.\n// 3. All afterUpdate callbacks, in order: parents before children. EXCEPT\n// for afterUpdates called during the initial onMount, which are called in\n// reverse order: children before parents.\n// Since callbacks might update component values, which could trigger another\n// call to flush(), the following steps guard against this:\n// 1. During beforeUpdate, any updated components will be added to the\n// dirty_components array and will cause a reentrant call to flush(). Because\n// the flush index is kept outside the function, the reentrant call will pick\n// up where the earlier call left off and go through all dirty components. The\n// current_component value is saved and restored so that the reentrant call will\n// not interfere with the \"parent\" flush() call.\n// 2. bind:this callbacks cannot trigger new flush() calls.\n// 3. During afterUpdate, any updated components will NOT have their afterUpdate\n// callback called a second time; the seen_callbacks set, outside the flush()\n// function, guarantees this behavior.\nconst seen_callbacks = new Set();\n\nlet flushidx = 0; // Do *not* move this inside the flush() function\n\n/** @returns {void} */\nexport function flush() {\n\t// Do not reenter flush while dirty components are updated, as this can\n\t// result in an infinite loop. Instead, let the inner flush handle it.\n\t// Reentrancy is ok afterwards for bindings etc.\n\tif (flushidx !== 0) {\n\t\treturn;\n\t}\n\tconst saved_component = current_component;\n\tdo {\n\t\t// first, call beforeUpdate functions\n\t\t// and update components\n\t\ttry {\n\t\t\twhile (flushidx < dirty_components.length) {\n\t\t\t\tconst component = dirty_components[flushidx];\n\t\t\t\tflushidx++;\n\t\t\t\tset_current_component(component);\n\t\t\t\tupdate(component.$$);\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// reset dirty state to not end up in a deadlocked state and then rethrow\n\t\t\tdirty_components.length = 0;\n\t\t\tflushidx = 0;\n\t\t\tthrow e;\n\t\t}\n\t\tset_current_component(null);\n\t\tdirty_components.length = 0;\n\t\tflushidx = 0;\n\t\twhile (binding_callbacks.length) binding_callbacks.pop()();\n\t\t// then, once components are updated, call\n\t\t// afterUpdate functions. This may cause\n\t\t// subsequent updates...\n\t\tfor (let i = 0; i < render_callbacks.length; i += 1) {\n\t\t\tconst callback = render_callbacks[i];\n\t\t\tif (!seen_callbacks.has(callback)) {\n\t\t\t\t// ...so guard against infinite loops\n\t\t\t\tseen_callbacks.add(callback);\n\t\t\t\tcallback();\n\t\t\t}\n\t\t}\n\t\trender_callbacks.length = 0;\n\t} while (dirty_components.length);\n\twhile (flush_callbacks.length) {\n\t\tflush_callbacks.pop()();\n\t}\n\tupdate_scheduled = false;\n\tseen_callbacks.clear();\n\tset_current_component(saved_component);\n}\n\n/** @returns {void} */\nfunction update($$) {\n\tif ($$.fragment !== null) {\n\t\t$$.update();\n\t\trun_all($$.before_update);\n\t\tconst dirty = $$.dirty;\n\t\t$$.dirty = [-1];\n\t\t$$.fragment && $$.fragment.p($$.ctx, dirty);\n\t\t$$.after_update.forEach(add_render_callback);\n\t}\n}\n\n/**\n * Useful for example to execute remaining `afterUpdate` callbacks before executing `destroy`.\n * @param {Function[]} fns\n * @returns {void}\n */\nexport function flush_render_callbacks(fns) {\n\tconst filtered = [];\n\tconst targets = [];\n\trender_callbacks.forEach((c) => (fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c)));\n\ttargets.forEach((c) => c());\n\trender_callbacks = filtered;\n}\n","import { identity as linear, is_function, noop, run_all } from './utils.js';\nimport { now } from './environment.js';\nimport { loop } from './loop.js';\nimport { create_rule, delete_rule } from './style_manager.js';\nimport { custom_event } from './dom.js';\nimport { add_render_callback } from './scheduler.js';\n\n/**\n * @type {Promise<void> | null}\n */\nlet promise;\n\n/**\n * @returns {Promise<void>}\n */\nfunction wait() {\n\tif (!promise) {\n\t\tpromise = Promise.resolve();\n\t\tpromise.then(() => {\n\t\t\tpromise = null;\n\t\t});\n\t}\n\treturn promise;\n}\n\n/**\n * @param {Element} node\n * @param {INTRO | OUTRO | boolean} direction\n * @param {'start' | 'end'} kind\n * @returns {void}\n */\nfunction dispatch(node, direction, kind) {\n\tnode.dispatchEvent(custom_event(`${direction ? 'intro' : 'outro'}${kind}`));\n}\n\nconst outroing = new Set();\n\n/**\n * @type {Outro}\n */\nlet outros;\n\n/**\n * @returns {void} */\nexport function group_outros() {\n\toutros = {\n\t\tr: 0,\n\t\tc: [],\n\t\tp: outros // parent group\n\t};\n}\n\n/**\n * @returns {void} */\nexport function check_outros() {\n\tif (!outros.r) {\n\t\trun_all(outros.c);\n\t}\n\toutros = outros.p;\n}\n\n/**\n * @param {import('./private.js').Fragment} block\n * @param {0 | 1} [local]\n * @returns {void}\n */\nexport function transition_in(block, local) {\n\tif (block && block.i) {\n\t\toutroing.delete(block);\n\t\tblock.i(local);\n\t}\n}\n\n/**\n * @param {import('./private.js').Fragment} block\n * @param {0 | 1} local\n * @param {0 | 1} [detach]\n * @param {() => void} [callback]\n * @returns {void}\n */\nexport function transition_out(block, local, detach, callback) {\n\tif (block && block.o) {\n\t\tif (outroing.has(block)) return;\n\t\toutroing.add(block);\n\t\toutros.c.push(() => {\n\t\t\toutroing.delete(block);\n\t\t\tif (callback) {\n\t\t\t\tif (detach) block.d(1);\n\t\t\t\tcallback();\n\t\t\t}\n\t\t});\n\t\tblock.o(local);\n\t} else if (callback) {\n\t\tcallback();\n\t}\n}\n\n/**\n * @type {import('../transition/public.js').TransitionConfig}\n */\nconst null_transition = { duration: 0 };\n\n/**\n * @param {Element & ElementCSSInlineStyle} node\n * @param {TransitionFn} fn\n * @param {any} params\n * @returns {{ start(): void; invalidate(): void; end(): void; }}\n */\nexport function create_in_transition(node, fn, params) {\n\t/**\n\t * @type {TransitionOptions} */\n\tconst options = { direction: 'in' };\n\tlet config = fn(node, params, options);\n\tlet running = false;\n\tlet animation_name;\n\tlet task;\n\tlet uid = 0;\n\n\t/**\n\t * @returns {void} */\n\tfunction cleanup() {\n\t\tif (animation_name) delete_rule(node, animation_name);\n\t}\n\n\t/**\n\t * @returns {void} */\n\tfunction go() {\n\t\tconst {\n\t\t\tdelay = 0,\n\t\t\tduration = 300,\n\t\t\teasing = linear,\n\t\t\ttick = noop,\n\t\t\tcss\n\t\t} = config || null_transition;\n\t\tif (css) animation_name = create_rule(node, 0, 1, duration, delay, easing, css, uid++);\n\t\ttick(0, 1);\n\t\tconst start_time = now() + delay;\n\t\tconst end_time = start_time + duration;\n\t\tif (task) task.abort();\n\t\trunning = true;\n\t\tadd_render_callback(() => dispatch(node, true, 'start'));\n\t\ttask = loop((now) => {\n\t\t\tif (running) {\n\t\t\t\tif (now >= end_time) {\n\t\t\t\t\ttick(1, 0);\n\t\t\t\t\tdispatch(node, true, 'end');\n\t\t\t\t\tcleanup();\n\t\t\t\t\treturn (running = false);\n\t\t\t\t}\n\t\t\t\tif (now >= start_time) {\n\t\t\t\t\tconst t = easing((now - start_time) / duration);\n\t\t\t\t\ttick(t, 1 - t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn running;\n\t\t});\n\t}\n\tlet started = false;\n\treturn {\n\t\tstart() {\n\t\t\tif (started) return;\n\t\t\tstarted = true;\n\t\t\tdelete_rule(node);\n\t\t\tif (is_function(config)) {\n\t\t\t\tconfig = config(options);\n\t\t\t\twait().then(go);\n\t\t\t} else {\n\t\t\t\tgo();\n\t\t\t}\n\t\t},\n\t\tinvalidate() {\n\t\t\tstarted = false;\n\t\t},\n\t\tend() {\n\t\t\tif (running) {\n\t\t\t\tcleanup();\n\t\t\t\trunning = false;\n\t\t\t}\n\t\t}\n\t};\n}\n\n/**\n * @param {Element & ElementCSSInlineStyle} node\n * @param {TransitionFn} fn\n * @param {any} params\n * @returns {{ end(reset: any): void; }}\n */\nexport function create_out_transition(node, fn, params) {\n\t/** @type {TransitionOptions} */\n\tconst options = { direction: 'out' };\n\tlet config = fn(node, params, options);\n\tlet running = true;\n\tlet animation_name;\n\tconst group = outros;\n\tgroup.r += 1;\n\t/** @type {boolean} */\n\tlet original_inert_value;\n\n\t/**\n\t * @returns {void} */\n\tfunction go() {\n\t\tconst {\n\t\t\tdelay = 0,\n\t\t\tduration = 300,\n\t\t\teasing = linear,\n\t\t\ttick = noop,\n\t\t\tcss\n\t\t} = config || null_transition;\n\n\t\tif (css) animation_name = create_rule(node, 1, 0, duration, delay, easing, css);\n\n\t\tconst start_time = now() + delay;\n\t\tconst end_time = start_time + duration;\n\t\tadd_render_callback(() => dispatch(node, false, 'start'));\n\n\t\tif ('inert' in node) {\n\t\t\toriginal_inert_value = /** @type {HTMLElement} */ (node).inert;\n\t\t\tnode.inert = true;\n\t\t}\n\n\t\tloop((now) => {\n\t\t\tif (running) {\n\t\t\t\tif (now >= end_time) {\n\t\t\t\t\ttick(0, 1);\n\t\t\t\t\tdispatch(node, false, 'end');\n\t\t\t\t\tif (!--group.r) {\n\t\t\t\t\t\t// this will result in `end()` being called,\n\t\t\t\t\t\t// so we don't need to clean up here\n\t\t\t\t\t\trun_all(group.c);\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (now >= start_time) {\n\t\t\t\t\tconst t = easing((now - start_time) / duration);\n\t\t\t\t\ttick(1 - t, t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn running;\n\t\t});\n\t}\n\n\tif (is_function(config)) {\n\t\twait().then(() => {\n\t\t\t// @ts-ignore\n\t\t\tconfig = config(options);\n\t\t\tgo();\n\t\t});\n\t} else {\n\t\tgo();\n\t}\n\n\treturn {\n\t\tend(reset) {\n\t\t\tif (reset && 'inert' in node) {\n\t\t\t\tnode.inert = original_inert_value;\n\t\t\t}\n\t\t\tif (reset && config.tick) {\n\t\t\t\tconfig.tick(1, 0);\n\t\t\t}\n\t\t\tif (running) {\n\t\t\t\tif (animation_name) delete_rule(node, animation_name);\n\t\t\t\trunning = false;\n\t\t\t}\n\t\t}\n\t};\n}\n\n/**\n * @param {Element & ElementCSSInlineStyle} node\n * @param {TransitionFn} fn\n * @param {any} params\n * @param {boolean} intro\n * @returns {{ run(b: 0 | 1): void; end(): void; }}\n */\nexport function create_bidirectional_transition(node, fn, params, intro) {\n\t/**\n\t * @type {TransitionOptions} */\n\tconst options = { direction: 'both' };\n\tlet config = fn(node, params, options);\n\tlet t = intro ? 0 : 1;\n\n\t/**\n\t * @type {Program | null} */\n\tlet running_program = null;\n\n\t/**\n\t * @type {PendingProgram | null} */\n\tlet pending_program = null;\n\tlet animation_name = null;\n\n\t/** @type {boolean} */\n\tlet original_inert_value;\n\n\t/**\n\t * @returns {void} */\n\tfunction clear_animation() {\n\t\tif (animation_name) delete_rule(node, animation_name);\n\t}\n\n\t/**\n\t * @param {PendingProgram} program\n\t * @param {number} duration\n\t * @returns {Program}\n\t */\n\tfunction init(program, duration) {\n\t\tconst d = /** @type {Program['d']} */ (program.b - t);\n\t\tduration *= Math.abs(d);\n\t\treturn {\n\t\t\ta: t,\n\t\t\tb: program.b,\n\t\t\td,\n\t\t\tduration,\n\t\t\tstart: program.start,\n\t\t\tend: program.start + duration,\n\t\t\tgroup: program.group\n\t\t};\n\t}\n\n\t/**\n\t * @param {INTRO | OUTRO} b\n\t * @returns {void}\n\t */\n\tfunction go(b) {\n\t\tconst {\n\t\t\tdelay = 0,\n\t\t\tduration = 300,\n\t\t\teasing = linear,\n\t\t\ttick = noop,\n\t\t\tcss\n\t\t} = config || null_transition;\n\n\t\t/**\n\t\t * @type {PendingProgram} */\n\t\tconst program = {\n\t\t\tstart: now() + delay,\n\t\t\tb\n\t\t};\n\n\t\tif (!b) {\n\t\t\t// @ts-ignore todo: improve typings\n\t\t\tprogram.group = outros;\n\t\t\toutros.r += 1;\n\t\t}\n\n\t\tif ('inert' in node) {\n\t\t\tif (b) {\n\t\t\t\tif (original_inert_value !== undefined) {\n\t\t\t\t\t// aborted/reversed outro — restore previous inert value\n\t\t\t\t\tnode.inert = original_inert_value;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toriginal_inert_value = /** @type {HTMLElement} */ (node).inert;\n\t\t\t\tnode.inert = true;\n\t\t\t}\n\t\t}\n\n\t\tif (running_program || pending_program) {\n\t\t\tpending_program = program;\n\t\t} else {\n\t\t\t// if this is an intro, and there's a delay, we need to do\n\t\t\t// an initial tick and/or apply CSS animation immediately\n\t\t\tif (css) {\n\t\t\t\tclear_animation();\n\t\t\t\tanimation_name = create_rule(node, t, b, duration, delay, easing, css);\n\t\t\t}\n\t\t\tif (b) tick(0, 1);\n\t\t\trunning_program = init(program, duration);\n\t\t\tadd_render_callback(() => dispatch(node, b, 'start'));\n\t\t\tloop((now) => {\n\t\t\t\tif (pending_program && now > pending_program.start) {\n\t\t\t\t\trunning_program = init(pending_program, duration);\n\t\t\t\t\tpending_program = null;\n\t\t\t\t\tdispatch(node, running_program.b, 'start');\n\t\t\t\t\tif (css) {\n\t\t\t\t\t\tclear_animation();\n\t\t\t\t\t\tanimation_name = create_rule(\n\t\t\t\t\t\t\tnode,\n\t\t\t\t\t\t\tt,\n\t\t\t\t\t\t\trunning_program.b,\n\t\t\t\t\t\t\trunning_program.duration,\n\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\teasing,\n\t\t\t\t\t\t\tconfig.css\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (running_program) {\n\t\t\t\t\tif (now >= running_program.end) {\n\t\t\t\t\t\ttick((t = running_program.b), 1 - t);\n\t\t\t\t\t\tdispatch(node, running_program.b, 'end');\n\t\t\t\t\t\tif (!pending_program) {\n\t\t\t\t\t\t\t// we're done\n\t\t\t\t\t\t\tif (running_program.b) {\n\t\t\t\t\t\t\t\t// intro — we can tidy up immediately\n\t\t\t\t\t\t\t\tclear_animation();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// outro — needs to be coordinated\n\t\t\t\t\t\t\t\tif (!--running_program.group.r) run_all(running_program.group.c);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\trunning_program = null;\n\t\t\t\t\t} else if (now >= running_program.start) {\n\t\t\t\t\t\tconst p = now - running_program.start;\n\t\t\t\t\t\tt = running_program.a + running_program.d * easing(p / running_program.duration);\n\t\t\t\t\t\ttick(t, 1 - t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn !!(running_program || pending_program);\n\t\t\t});\n\t\t}\n\t}\n\treturn {\n\t\trun(b) {\n\t\t\tif (is_function(config)) {\n\t\t\t\twait().then(() => {\n\t\t\t\t\tconst opts = { direction: b ? 'in' : 'out' };\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tconfig = config(opts);\n\t\t\t\t\tgo(b);\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tgo(b);\n\t\t\t}\n\t\t},\n\t\tend() {\n\t\t\tclear_animation();\n\t\t\trunning_program = pending_program = null;\n\t\t}\n\t};\n}\n\n/** @typedef {1} INTRO */\n/** @typedef {0} OUTRO */\n/** @typedef {{ direction: 'in' | 'out' | 'both' }} TransitionOptions */\n/** @typedef {(node: Element, params: any, options: TransitionOptions) => import('../transition/public.js').TransitionConfig} TransitionFn */\n\n/**\n * @typedef {Object} Outro\n * @property {number} r\n * @property {Function[]} c\n * @property {Object} p\n */\n\n/**\n * @typedef {Object} PendingProgram\n * @property {number} start\n * @property {INTRO|OUTRO} b\n * @property {Outro} [group]\n */\n\n/**\n * @typedef {Object} Program\n * @property {number} a\n * @property {INTRO|OUTRO} b\n * @property {1|-1} d\n * @property {number} duration\n * @property {number} start\n * @property {number} end\n * @property {Outro} [group]\n */\n","import { transition_in, transition_out } from './transitions.js';\nimport { run_all } from './utils.js';\n\n// general each functions:\n\nexport function ensure_array_like(array_like_or_iterator) {\n\treturn array_like_or_iterator?.length !== undefined\n\t\t? array_like_or_iterator\n\t\t: Array.from(array_like_or_iterator);\n}\n\n// keyed each functions:\n\n/** @returns {void} */\nexport function destroy_block(block, lookup) {\n\tblock.d(1);\n\tlookup.delete(block.key);\n}\n\n/** @returns {void} */\nexport function outro_and_destroy_block(block, lookup) {\n\ttransition_out(block, 1, 1, () => {\n\t\tlookup.delete(block.key);\n\t});\n}\n\n/** @returns {void} */\nexport function fix_and_destroy_block(block, lookup) {\n\tblock.f();\n\tdestroy_block(block, lookup);\n}\n\n/** @returns {void} */\nexport function fix_and_outro_and_destroy_block(block, lookup) {\n\tblock.f();\n\toutro_and_destroy_block(block, lookup);\n}\n\n/** @returns {any[]} */\nexport function update_keyed_each(\n\told_blocks,\n\tdirty,\n\tget_key,\n\tdynamic,\n\tctx,\n\tlist,\n\tlookup,\n\tnode,\n\tdestroy,\n\tcreate_each_block,\n\tnext,\n\tget_context\n) {\n\tlet o = old_blocks.length;\n\tlet n = list.length;\n\tlet i = o;\n\tconst old_indexes = {};\n\twhile (i--) old_indexes[old_blocks[i].key] = i;\n\tconst new_blocks = [];\n\tconst new_lookup = new Map();\n\tconst deltas = new Map();\n\tconst updates = [];\n\ti = n;\n\twhile (i--) {\n\t\tconst child_ctx = get_context(ctx, list, i);\n\t\tconst key = get_key(child_ctx);\n\t\tlet block = lookup.get(key);\n\t\tif (!block) {\n\t\t\tblock = create_each_block(key, child_ctx);\n\t\t\tblock.c();\n\t\t} else if (dynamic) {\n\t\t\t// defer updates until all the DOM shuffling is done\n\t\t\tupdates.push(() => block.p(child_ctx, dirty));\n\t\t}\n\t\tnew_lookup.set(key, (new_blocks[i] = block));\n\t\tif (key in old_indexes) deltas.set(key, Math.abs(i - old_indexes[key]));\n\t}\n\tconst will_move = new Set();\n\tconst did_move = new Set();\n\t/** @returns {void} */\n\tfunction insert(block) {\n\t\ttransition_in(block, 1);\n\t\tblock.m(node, next);\n\t\tlookup.set(block.key, block);\n\t\tnext = block.first;\n\t\tn--;\n\t}\n\twhile (o && n) {\n\t\tconst new_block = new_blocks[n - 1];\n\t\tconst old_block = old_blocks[o - 1];\n\t\tconst new_key = new_block.key;\n\t\tconst old_key = old_block.key;\n\t\tif (new_block === old_block) {\n\t\t\t// do nothing\n\t\t\tnext = new_block.first;\n\t\t\to--;\n\t\t\tn--;\n\t\t} else if (!new_lookup.has(old_key)) {\n\t\t\t// remove old block\n\t\t\tdestroy(old_block, lookup);\n\t\t\to--;\n\t\t} else if (!lookup.has(new_key) || will_move.has(new_key)) {\n\t\t\tinsert(new_block);\n\t\t} else if (did_move.has(old_key)) {\n\t\t\to--;\n\t\t} else if (deltas.get(new_key) > deltas.get(old_key)) {\n\t\t\tdid_move.add(new_key);\n\t\t\tinsert(new_block);\n\t\t} else {\n\t\t\twill_move.add(old_key);\n\t\t\to--;\n\t\t}\n\t}\n\twhile (o--) {\n\t\tconst old_block = old_blocks[o];\n\t\tif (!new_lookup.has(old_block.key)) destroy(old_block, lookup);\n\t}\n\twhile (n) insert(new_blocks[n - 1]);\n\trun_all(updates);\n\treturn new_blocks;\n}\n\n/** @returns {void} */\nexport function validate_each_keys(ctx, list, get_context, get_key) {\n\tconst keys = new Map();\n\tfor (let i = 0; i < list.length; i++) {\n\t\tconst key = get_key(get_context(ctx, list, i));\n\t\tif (keys.has(key)) {\n\t\t\tlet value = '';\n\t\t\ttry {\n\t\t\t\tvalue = `with value '${String(key)}' `;\n\t\t\t} catch (e) {\n\t\t\t\t// can't stringify\n\t\t\t}\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot have duplicate keys in a keyed each: Keys at index ${keys.get(\n\t\t\t\t\tkey\n\t\t\t\t)} and ${i} ${value}are duplicates`\n\t\t\t);\n\t\t}\n\t\tkeys.set(key, i);\n\t}\n}\n","import {\n\tadd_render_callback,\n\tflush,\n\tflush_render_callbacks,\n\tschedule_update,\n\tdirty_components\n} from './scheduler.js';\nimport { current_component, set_current_component } from './lifecycle.js';\nimport { blank_object, is_empty, is_function, run, run_all, noop } from './utils.js';\nimport {\n\tchildren,\n\tdetach,\n\tstart_hydrating,\n\tend_hydrating,\n\tget_custom_elements_slots,\n\tinsert,\n\telement,\n\tattr\n} from './dom.js';\nimport { transition_in } from './transitions.js';\n\n/** @returns {void} */\nexport function bind(component, name, callback) {\n\tconst index = component.$$.props[name];\n\tif (index !== undefined) {\n\t\tcomponent.$$.bound[index] = callback;\n\t\tcallback(component.$$.ctx[index]);\n\t}\n}\n\n/** @returns {void} */\nexport function create_component(block) {\n\tblock && block.c();\n}\n\n/** @returns {void} */\nexport function claim_component(block, parent_nodes) {\n\tblock && block.l(parent_nodes);\n}\n\n/** @returns {void} */\nexport function mount_component(component, target, anchor) {\n\tconst { fragment, after_update } = component.$$;\n\tfragment && fragment.m(target, anchor);\n\t// onMount happens before the initial afterUpdate\n\tadd_render_callback(() => {\n\t\tconst new_on_destroy = component.$$.on_mount.map(run).filter(is_function);\n\t\t// if the component was destroyed immediately\n\t\t// it will update the `$$.on_destroy` reference to `null`.\n\t\t// the destructured on_destroy may still reference to the old array\n\t\tif (component.$$.on_destroy) {\n\t\t\tcomponent.$$.on_destroy.push(...new_on_destroy);\n\t\t} else {\n\t\t\t// Edge case - component was destroyed immediately,\n\t\t\t// most likely as a result of a binding initialising\n\t\t\trun_all(new_on_destroy);\n\t\t}\n\t\tcomponent.$$.on_mount = [];\n\t});\n\tafter_update.forEach(add_render_callback);\n}\n\n/** @returns {void} */\nexport function destroy_component(component, detaching) {\n\tconst $$ = component.$$;\n\tif ($$.fragment !== null) {\n\t\tflush_render_callbacks($$.after_update);\n\t\trun_all($$.on_destroy);\n\t\t$$.fragment && $$.fragment.d(detaching);\n\t\t// TODO null out other refs, including component.$$ (but need to\n\t\t// preserve final state?)\n\t\t$$.on_destroy = $$.fragment = null;\n\t\t$$.ctx = [];\n\t}\n}\n\n/** @returns {void} */\nfunction make_dirty(component, i) {\n\tif (component.$$.dirty[0] === -1) {\n\t\tdirty_components.push(component);\n\t\tschedule_update();\n\t\tcomponent.$$.dirty.fill(0);\n\t}\n\tcomponent.$$.dirty[(i / 31) | 0] |= 1 << i % 31;\n}\n\n// TODO: Document the other params\n/**\n * @param {SvelteComponent} component\n * @param {import('./public.js').ComponentConstructorOptions} options\n *\n * @param {import('./utils.js')['not_equal']} not_equal Used to compare props and state values.\n * @param {(target: Element | ShadowRoot) => void} [append_styles] Function that appends styles to the DOM when the component is first initialised.\n * This will be the `add_css` function from the compiled component.\n *\n * @returns {void}\n */\nexport function init(\n\tcomponent,\n\toptions,\n\tinstance,\n\tcreate_fragment,\n\tnot_equal,\n\tprops,\n\tappend_styles = null,\n\tdirty = [-1]\n) {\n\tconst parent_component = current_component;\n\tset_current_component(component);\n\t/** @type {import('./private.js').T$$} */\n\tconst $$ = (component.$$ = {\n\t\tfragment: null,\n\t\tctx: [],\n\t\t// state\n\t\tprops,\n\t\tupdate: noop,\n\t\tnot_equal,\n\t\tbound: blank_object(),\n\t\t// lifecycle\n\t\ton_mount: [],\n\t\ton_destroy: [],\n\t\ton_disconnect: [],\n\t\tbefore_update: [],\n\t\tafter_update: [],\n\t\tcontext: new Map(options.context || (parent_component ? parent_component.$$.context : [])),\n\t\t// everything else\n\t\tcallbacks: blank_object(),\n\t\tdirty,\n\t\tskip_bound: false,\n\t\troot: options.target || parent_component.$$.root\n\t});\n\tappend_styles && append_styles($$.root);\n\tlet ready = false;\n\t$$.ctx = instance\n\t\t? instance(component, options.props || {}, (i, ret, ...rest) => {\n\t\t\t\tconst value = rest.length ? rest[0] : ret;\n\t\t\t\tif ($$.ctx && not_equal($$.ctx[i], ($$.ctx[i] = value))) {\n\t\t\t\t\tif (!$$.skip_bound && $$.bound[i]) $$.bound[i](value);\n\t\t\t\t\tif (ready) make_dirty(component, i);\n\t\t\t\t}\n\t\t\t\treturn ret;\n\t\t })\n\t\t: [];\n\t$$.update();\n\tready = true;\n\trun_all($$.before_update);\n\t// `false` as a special case of no DOM component\n\t$$.fragment = create_fragment ? create_fragment($$.ctx) : false;\n\tif (options.target) {\n\t\tif (options.hydrate) {\n\t\t\tstart_hydrating();\n\t\t\t// TODO: what is the correct type here?\n\t\t\t// @ts-expect-error\n\t\t\tconst nodes = children(options.target);\n\t\t\t$$.fragment && $$.fragment.l(nodes);\n\t\t\tnodes.forEach(detach);\n\t\t} else {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\t\t\t$$.fragment && $$.fragment.c();\n\t\t}\n\t\tif (options.intro) transition_in(component.$$.fragment);\n\t\tmount_component(component, options.target, options.anchor);\n\t\tend_hydrating();\n\t\tflush();\n\t}\n\tset_current_component(parent_component);\n}\n\nexport let SvelteElement;\n\nif (typeof HTMLElement === 'function') {\n\tSvelteElement = class extends HTMLElement {\n\t\t/** The Svelte component constructor */\n\t\t$$ctor;\n\t\t/** Slots */\n\t\t$$s;\n\t\t/** The Svelte component instance */\n\t\t$$c;\n\t\t/** Whether or not the custom element is connected */\n\t\t$$cn = false;\n\t\t/** Component props data */\n\t\t$$d = {};\n\t\t/** `true` if currently in the process of reflecting component props back to attributes */\n\t\t$$r = false;\n\t\t/** @type {Record<string, CustomElementPropDefinition>} Props definition (name, reflected, type etc) */\n\t\t$$p_d = {};\n\t\t/** @type {Record<string, Function[]>} Event listeners */\n\t\t$$l = {};\n\t\t/** @type {Map<Function, Function>} Event listener unsubscribe functions */\n\t\t$$l_u = new Map();\n\n\t\tconstructor($$componentCtor, $$slots, use_shadow_dom) {\n\t\t\tsuper();\n\t\t\tthis.$$ctor = $$componentCtor;\n\t\t\tthis.$$s = $$slots;\n\t\t\tif (use_shadow_dom) {\n\t\t\t\tthis.attachShadow({ mode: 'open' });\n\t\t\t}\n\t\t}\n\n\t\taddEventListener(type, listener, options) {\n\t\t\t// We can't determine upfront if the event is a custom event or not, so we have to\n\t\t\t// listen to both. If someone uses a custom event with the same name as a regular\n\t\t\t// browser event, this fires twice - we can't avoid that.\n\t\t\tthis.$$l[type] = this.$$l[type] || [];\n\t\t\tthis.$$l[type].push(listener);\n\t\t\tif (this.$$c) {\n\t\t\t\tconst unsub = this.$$c.$on(type, listener);\n\t\t\t\tthis.$$l_u.set(listener, unsub);\n\t\t\t}\n\t\t\tsuper.addEventListener(type, listener, options);\n\t\t}\n\n\t\tremoveEventListener(type, listener, options) {\n\t\t\tsuper.removeEventListener(type, listener, options);\n\t\t\tif (this.$$c) {\n\t\t\t\tconst unsub = this.$$l_u.get(listener);\n\t\t\t\tif (unsub) {\n\t\t\t\t\tunsub();\n\t\t\t\t\tthis.$$l_u.delete(listener);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tasync connectedCallback() {\n\t\t\tthis.$$cn = true;\n\t\t\tif (!this.$$c) {\n\t\t\t\t// We wait one tick to let possible child slot elements be created/mounted\n\t\t\t\tawait Promise.resolve();\n\t\t\t\tif (!this.$$cn || this.$$c) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfunction create_slot(name) {\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tlet node;\n\t\t\t\t\t\tconst obj = {\n\t\t\t\t\t\t\tc: function create() {\n\t\t\t\t\t\t\t\tnode = element('slot');\n\t\t\t\t\t\t\t\tif (name !== 'default') {\n\t\t\t\t\t\t\t\t\tattr(node, 'name', name);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t/**\n\t\t\t\t\t\t\t * @param {HTMLElement} target\n\t\t\t\t\t\t\t * @param {HTMLElement} [anchor]\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tm: function mount(target, anchor) {\n\t\t\t\t\t\t\t\tinsert(target, node, anchor);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\td: function destroy(detaching) {\n\t\t\t\t\t\t\t\tif (detaching) {\n\t\t\t\t\t\t\t\t\tdetach(node);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn obj;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst $$slots = {};\n\t\t\t\tconst existing_slots = get_custom_elements_slots(this);\n\t\t\t\tfor (const name of this.$$s) {\n\t\t\t\t\tif (name in existing_slots) {\n\t\t\t\t\t\t$$slots[name] = [create_slot(name)];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const attribute of this.attributes) {\n\t\t\t\t\t// this.$$data takes precedence over this.attributes\n\t\t\t\t\tconst name = this.$$g_p(attribute.name);\n\t\t\t\t\tif (!(name in this.$$d)) {\n\t\t\t\t\t\tthis.$$d[name] = get_custom_element_value(name, attribute.value, this.$$p_d, 'toProp');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Port over props that were set programmatically before ce was initialized\n\t\t\t\tfor (const key in this.$$p_d) {\n\t\t\t\t\tif (!(key in this.$$d) && this[key] !== undefined) {\n\t\t\t\t\t\tthis.$$d[key] = this[key]; // don't transform, these were set through JavaScript\n\t\t\t\t\t\tdelete this[key]; // remove the property that shadows the getter/setter\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.$$c = new this.$$ctor({\n\t\t\t\t\ttarget: this.shadowRoot || this,\n\t\t\t\t\tprops: {\n\t\t\t\t\t\t...this.$$d,\n\t\t\t\t\t\t$$slots,\n\t\t\t\t\t\t$$scope: {\n\t\t\t\t\t\t\tctx: []\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Reflect component props as attributes\n\t\t\t\tconst reflect_attributes = () => {\n\t\t\t\t\tthis.$$r = true;\n\t\t\t\t\tfor (const key in this.$$p_d) {\n\t\t\t\t\t\tthis.$$d[key] = this.$$c.$$.ctx[this.$$c.$$.props[key]];\n\t\t\t\t\t\tif (this.$$p_d[key].reflect) {\n\t\t\t\t\t\t\tconst attribute_value = get_custom_element_value(\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tthis.$$d[key],\n\t\t\t\t\t\t\t\tthis.$$p_d,\n\t\t\t\t\t\t\t\t'toAttribute'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (attribute_value == null) {\n\t\t\t\t\t\t\t\tthis.removeAttribute(this.$$p_d[key].attribute || key);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthis.setAttribute(this.$$p_d[key].attribute || key, attribute_value);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthis.$$r = false;\n\t\t\t\t};\n\t\t\t\tthis.$$c.$$.after_update.push(reflect_attributes);\n\t\t\t\treflect_attributes(); // once initially because after_update is added too late for first render\n\n\t\t\t\tfor (const type in this.$$l) {\n\t\t\t\t\tfor (const listener of this.$$l[type]) {\n\t\t\t\t\t\tconst unsub = this.$$c.$on(type, listener);\n\t\t\t\t\t\tthis.$$l_u.set(listener, unsub);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.$$l = {};\n\t\t\t}\n\t\t}\n\n\t\t// We don't need this when working within Svelte code, but for compatibility of people using this outside of Svelte\n\t\t// and setting attributes through setAttribute etc, this is helpful\n\t\tattributeChangedCallback(attr, _oldValue, newValue) {\n\t\t\tif (this.$$r) return;\n\t\t\tattr = this.$$g_p(attr);\n\t\t\tthis.$$d[attr] = get_custom_element_value(attr, newValue, this.$$p_d, 'toProp');\n\t\t\tthis.$$c?.$set({ [attr]: this.$$d[attr] });\n\t\t}\n\n\t\tdisconnectedCallback() {\n\t\t\tthis.$$cn = false;\n\t\t\t// In a microtask, because this could be a move within the DOM\n\t\t\tPromise.resolve().then(() => {\n\t\t\t\tif (!this.$$cn) {\n\t\t\t\t\tthis.$$c.$destroy();\n\t\t\t\t\tthis.$$c = undefined;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t$$g_p(attribute_name) {\n\t\t\treturn (\n\t\t\t\tObject.keys(this.$$p_d).find(\n\t\t\t\t\t(key) =>\n\t\t\t\t\t\tthis.$$p_d[key].attribute === attribute_name ||\n\t\t\t\t\t\t(!this.$$p_d[key].attribute && key.toLowerCase() === attribute_name)\n\t\t\t\t) || attribute_name\n\t\t\t);\n\t\t}\n\t};\n}\n\n/**\n * @param {string} prop\n * @param {any} value\n * @param {Record<string, CustomElementPropDefinition>} props_definition\n * @param {'toAttribute' | 'toProp'} [transform]\n */\nfunction get_custom_element_value(prop, value, props_definition, transform) {\n\tconst type = props_definition[prop]?.type;\n\tvalue = type === 'Boolean' && typeof value !== 'boolean' ? value != null : value;\n\tif (!transform || !props_definition[prop]) {\n\t\treturn value;\n\t} else if (transform === 'toAttribute') {\n\t\tswitch (type) {\n\t\t\tcase 'Object':\n\t\t\tcase 'Array':\n\t\t\t\treturn value == null ? null : JSON.stringify(value);\n\t\t\tcase 'Boolean':\n\t\t\t\treturn value ? '' : null;\n\t\t\tcase 'Number':\n\t\t\t\treturn value == null ? null : value;\n\t\t\tdefault:\n\t\t\t\treturn value;\n\t\t}\n\t} else {\n\t\tswitch (type) {\n\t\t\tcase 'Object':\n\t\t\tcase 'Array':\n\t\t\t\treturn value && JSON.parse(value);\n\t\t\tcase 'Boolean':\n\t\t\t\treturn value; // conversion already handled above\n\t\t\tcase 'Number':\n\t\t\t\treturn value != null ? +value : value;\n\t\t\tdefault:\n\t\t\t\treturn value;\n\t\t}\n\t}\n}\n\n/**\n * @internal\n *\n * Turn a Svelte component into a custom element.\n * @param {import('./public.js').ComponentType} Component A Svelte component constructor\n * @param {Record<string, CustomElementPropDefinition>} props_definition The props to observe\n * @param {string[]} slots The slots to create\n * @param {string[]} accessors Other accessors besides the ones for props the component has\n * @param {boolean} use_shadow_dom Whether to use shadow DOM\n * @param {(ce: new () => HTMLElement) => new () => HTMLElement} [extend]\n */\nexport function create_custom_element(\n\tComponent,\n\tprops_definition,\n\tslots,\n\taccessors,\n\tuse_shadow_dom,\n\textend\n) {\n\tlet Class = class extends SvelteElement {\n\t\tconstructor() {\n\t\t\tsuper(Component, slots, use_shadow_dom);\n\t\t\tthis.$$p_d = props_definition;\n\t\t}\n\t\tstatic get observedAttributes() {\n\t\t\treturn Object.keys(props_definition).map((key) =>\n\t\t\t\t(props_definition[key].attribute || key).toLowerCase()\n\t\t\t);\n\t\t}\n\t};\n\tObject.keys(props_definition).forEach((prop) => {\n\t\tObject.defineProperty(Class.prototype, prop, {\n\t\t\tget() {\n\t\t\t\treturn this.$$c && prop in this.$$c ? this.$$c[prop] : this.$$d[prop];\n\t\t\t},\n\t\t\tset(value) {\n\t\t\t\tvalue = get_custom_element_value(prop, value, props_definition);\n\t\t\t\tthis.$$d[prop] = value;\n\t\t\t\tthis.$$c?.$set({ [prop]: value });\n\t\t\t}\n\t\t});\n\t});\n\taccessors.forEach((accessor) => {\n\t\tObject.defineProperty(Class.prototype, accessor, {\n\t\t\tget() {\n\t\t\t\treturn this.$$c?.[accessor];\n\t\t\t}\n\t\t});\n\t});\n\tif (extend) {\n\t\t// @ts-expect-error - assigning here is fine\n\t\tClass = extend(Class);\n\t}\n\tComponent.element = /** @type {any} */ (Class);\n\treturn Class;\n}\n\n/**\n * Base class for Svelte components. Used when dev=false.\n *\n * @template {Record<string, any>} [Props=any]\n * @template {Record<string, any>} [Events=any]\n */\nexport class SvelteComponent {\n\t/**\n\t * ### PRIVATE API\n\t *\n\t * Do not use, may change at any time\n\t *\n\t * @type {any}\n\t */\n\t$$ = undefined;\n\t/**\n\t * ### PRIVATE API\n\t *\n\t * Do not use, may change at any time\n\t *\n\t * @type {any}\n\t */\n\t$$set = undefined;\n\n\t/** @returns {void} */\n\t$destroy() {\n\t\tdestroy_component(this, 1);\n\t\tthis.$destroy = noop;\n\t}\n\n\t/**\n\t * @template {Extract<keyof Events, string>} K\n\t * @param {K} type\n\t * @param {((e: Events[K]) => void) | null | undefined} callback\n\t * @returns {() => void}\n\t */\n\t$on(type, callback) {\n\t\tif (!is_function(callback)) {\n\t\t\treturn noop;\n\t\t}\n\t\tconst callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []);\n\t\tcallbacks.push(callback);\n\t\treturn () => {\n\t\t\tconst index = callbacks.indexOf(callback);\n\t\t\tif (index !== -1) callbacks.splice(index, 1);\n\t\t};\n\t}\n\n\t/**\n\t * @param {Partial<Props>} props\n\t * @returns {void}\n\t */\n\t$set(props) {\n\t\tif (this.$$set && !is_empty(props)) {\n\t\t\tthis.$$.skip_bound = true;\n\t\t\tthis.$$set(props);\n\t\t\tthis.$$.skip_bound = false;\n\t\t}\n\t}\n}\n\n/**\n * @typedef {Object} CustomElementPropDefinition\n * @property {string} [attribute]\n * @property {boolean} [reflect]\n * @property {'String'|'Boolean'|'Number'|'Array'|'Object'} [type]\n */\n","// generated during release, do not modify\n\n/**\n * The current version, as set in package.json.\n *\n * https://svelte.dev/docs/svelte-compiler#svelte-version\n * @type {string}\n */\nexport const VERSION = '4.2.15';\nexport const PUBLIC_VERSION = '4';\n","import { PUBLIC_VERSION } from '../../../shared/version.js';\n\nif (typeof window !== 'undefined')\n\t// @ts-ignore\n\t(window.__svelte || (window.__svelte = { v: new Set() })).v.add(PUBLIC_VERSION);\n","import { EditorView } from 'prosemirror-view'\nimport type { EditorState, Transaction } from 'prosemirror-state'\nimport type { Node as PMNode } from 'prosemirror-model'\nimport { getContext as getCtx, setContext as setCtx } from 'svelte'\n\nimport { buildColors } from './tabs/structure/colors'\n\nexport type Contexts = {\n 'editor-view': {\n view: EditorView\n replaceEditorContent: (state: EditorState) => void\n execCmd: (cmd: (state: EditorState, dispatch?: (tr: Transaction) => void) => void) => void\n }\n 'doc-view': {\n selected: {\n type: string\n start: number\n end: number\n }\n colors: ReturnType<typeof buildColors>\n handleNodeClick: (n: PMNode, startPos: number, scrollInto?: boolean) => void\n }\n}\n\nexport const setContext = <K extends keyof Contexts & string>(ctx: K, val: Contexts[K]) =>\n setCtx<Contexts[K]>(ctx, val)\n\nexport const getContext = <K extends keyof Contexts & string>(ctx: K) => getCtx<Contexts[K]>(ctx)\n","import {\n\trun_all,\n\tsubscribe,\n\tnoop,\n\tsafe_not_equal,\n\tis_function,\n\tget_store_value\n} from '../internal/index.js';\n\nconst subscriber_queue = [];\n\n/**\n * Creates a `Readable` store that allows reading by subscription.\n *\n * https://svelte.dev/docs/svelte-store#readable\n * @template T\n * @param {T} [value] initial value\n * @param {import('./public.js').StartStopNotifier<T>} [start]\n * @returns {import('./public.js').Readable<T>}\n */\nexport function readable(value, start) {\n\treturn {\n\t\tsubscribe: writable(value, start).subscribe\n\t};\n}\n\n/**\n * Create a `Writable` store that allows both updating and reading by subscription.\n *\n * https://svelte.dev/docs/svelte-store#writable\n * @template T\n * @param {T} [value] initial value\n * @param {import('./public.js').StartStopNotifier<T>} [start]\n * @returns {import('./public.js').Writable<T>}\n */\nexport function writable(value, start = noop) {\n\t/** @type {import('./public.js').Unsubscriber} */\n\tlet stop;\n\t/** @type {Set<import('./private.js').SubscribeInvalidateTuple<T>>} */\n\tconst subscribers = new Set();\n\t/** @param {T} new_value\n\t * @returns {void}\n\t */\n\tfunction set(new_value) {\n\t\tif (safe_not_equal(value, new_value)) {\n\t\t\tvalue = new_value;\n\t\t\tif (stop) {\n\t\t\t\t// store is ready\n\t\t\t\tconst run_queue = !subscriber_queue.length;\n\t\t\t\tfor (const subscriber of subscribers) {\n\t\t\t\t\tsubscriber[1]();\n\t\t\t\t\tsubscriber_queue.push(subscriber, value);\n\t\t\t\t}\n\t\t\t\tif (run_queue) {\n\t\t\t\t\tfor (let i = 0; i < subscriber_queue.length; i += 2) {\n\t\t\t\t\t\tsubscriber_queue[i][0](subscriber_queue[i + 1]);\n\t\t\t\t\t}\n\t\t\t\t\tsubscriber_queue.length = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {import('./public.js').Updater<T>} fn\n\t * @returns {void}\n\t */\n\tfunction update(fn) {\n\t\tset(fn(value));\n\t}\n\n\t/**\n\t * @param {import('./public.js').Subscriber<T>} run\n\t * @param {import('./private.js').Invalidator<T>} [invalidate]\n\t * @returns {import('./public.js').Unsubscriber}\n\t */\n\tfunction subscribe(run, invalidate = noop) {\n\t\t/** @type {import('./private.js').SubscribeInvalidateTuple<T>} */\n\t\tconst subscriber = [run, invalidate];\n\t\tsubscribers.add(subscriber);\n\t\tif (subscribers.size === 1) {\n\t\t\tstop = start(set, update) || noop;\n\t\t}\n\t\trun(value);\n\t\treturn () => {\n\t\t\tsubscribers.delete(subscriber);\n\t\t\tif (subscribers.size === 0 && stop) {\n\t\t\t\tstop();\n\t\t\t\tstop = null;\n\t\t\t}\n\t\t};\n\t}\n\treturn { set, update, subscribe };\n}\n\n/**\n * Derived value store by synchronizing one or more readable stores and\n * applying an aggregation function over its input values.\n *\n * https://svelte.dev/docs/svelte-store#derived\n * @template {import('./private.js').Stores} S\n * @template T\n * @overload\n * @param {S} stores - input stores\n * @param {(values: import('./private.js').StoresValues<S>, set: (value: T) => void, update: (fn: import('./public.js').Updater<T>) => void) => import('./public.js').Unsubscriber | void} fn - function callback that aggregates the values\n * @param {T} [initial_value] - initial value\n * @returns {import('./public.js').Readable<T>}\n */\n\n/**\n * Derived value store by synchronizing one or more readable stores and\n * applying an aggregation function over its input values.\n *\n * https://svelte.dev/docs/svelte-store#derived\n * @template {import('./private.js').Stores} S\n * @template T\n * @overload\n * @param {S} stores - input stores\n * @param {(values: import('./private.js').StoresValues<S>) => T} fn - function callback that aggregates the values\n * @param {T} [initial_value] - initial value\n * @returns {import('./public.js').Readable<T>}\n */\n\n/**\n * @template {import('./private.js').Stores} S\n * @template T\n * @param {S} stores\n * @param {Function} fn\n * @param {T} [initial_value]\n * @returns {import('./public.js').Readable<T>}\n */\nexport function derived(stores, fn, initial_value) {\n\tconst single = !Array.isArray(stores);\n\t/** @type {Array<import('./public.js').Readable<any>>} */\n\tconst stores_array = single ? [stores] : stores;\n\tif (!stores_array.every(Boolean)) {\n\t\tthrow new Error('derived() expects stores as input, got a falsy value');\n\t}\n\tconst auto = fn.length < 2;\n\treturn readable(initial_value, (set, update) => {\n\t\tlet started = false;\n\t\tconst values = [];\n\t\tlet pending = 0;\n\t\tlet cleanup = noop;\n\t\tconst sync = () => {\n\t\t\tif (pending) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcleanup();\n\t\t\tconst result = fn(single ? values[0] : values, set, update);\n\t\t\tif (auto) {\n\t\t\t\tset(result);\n\t\t\t} else {\n\t\t\t\tcleanup = is_function(result) ? result : noop;\n\t\t\t}\n\t\t};\n\t\tconst unsubscribers = stores_array.map((store, i) =>\n\t\t\tsubscribe(\n\t\t\t\tstore,\n\t\t\t\t(value) => {\n\t\t\t\t\tvalues[i] = value;\n\t\t\t\t\tpending &= ~(1 << i);\n\t\t\t\t\tif (started) {\n\t\t\t\t\t\tsync();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tpending |= 1 << i;\n\t\t\t\t}\n\t\t\t)\n\t\t);\n\t\tstarted = true;\n\t\tsync();\n\t\treturn function stop() {\n\t\t\trun_all(unsubscribers);\n\t\t\tcleanup();\n\t\t\t// We need to set this to false because callbacks can still happen despite having unsubscribed:\n\t\t\t// Callbacks might already be placed in the queue which doesn't know it should no longer\n\t\t\t// invoke this derived store.\n\t\t\tstarted = false;\n\t\t};\n\t});\n}\n\n/**\n * Takes a store and returns a new one derived from the old one that is readable.\n *\n * https://svelte.dev/docs/svelte-store#readonly\n * @template T\n * @param {import('./public.js').Readable<T>} store - store to make readonly\n * @returns {import('./public.js').Readable<T>}\n */\nexport function readonly(store) {\n\treturn {\n\t\tsubscribe: store.subscribe.bind(store)\n\t};\n}\n\nexport { get_store_value as get };\n","import type { EditorView } from 'prosemirror-view'\nimport type { EditorState } from 'prosemirror-state'\nimport type { Node as PMNode } from 'prosemirror-model'\nimport { get, writable } from 'svelte/store'\n\nimport type { Snapshot } from '$typings/snapshots'\nimport { Schema } from 'prosemirror-model'\n\nconst SNAPSHOTS_KEY = '__prosemirror-dev-toolkit__snapshots'\n\nexport const snapshots = writable<Snapshot[]>([])\nexport const selectedSnapshot = writable<Snapshot | undefined>()\nexport const previousEditorState = writable<EditorState | undefined>()\nlet canAccessLocalStorage = true\n\nfunction hydrate() {\n let persisted = null\n try {\n persisted = localStorage.getItem(SNAPSHOTS_KEY)\n } catch (err) {\n // Will crash when window is undefined, eg in server-side rendering\n // but also in a codesandbox where you are denied access to localStorage\n canAccessLocalStorage = false\n }\n if (persisted && persisted.length > 0) {\n try {\n const parsed = JSON.parse(persisted)\n snapshots.set(parsed)\n } catch (err) {\n console.error('Corrupted snapshots values in localStorage', err)\n }\n }\n}\n\nhydrate()\n\nsnapshots.subscribe(val => {\n if (canAccessLocalStorage) {\n localStorage.setItem(SNAPSHOTS_KEY, JSON.stringify(val))\n }\n})\n\nfunction setEditorDoc(view: EditorView, doc: { [key: string]: any }) {\n const node: PMNode = view.state.schema.nodeFromJSON(doc)\n const tr = view.state.tr\n tr.replaceWith(0, view.state.doc.nodeSize - 2, node.content)\n view.dispatch(tr)\n}\n\nexport function saveSnapshot(snapshotName: string, doc: { [key: string]: any }) {\n const snap: Snapshot = {\n name: snapshotName,\n timestamp: Date.now(),\n doc\n }\n snapshots.update(val => [snap, ...val])\n return snap\n}\n\nexport function importSnapshot(\n snapshotName: string,\n json: { [key: string]: unknown },\n schema: Schema\n) {\n const doc = schema.nodeFromJSON(json)\n const snap: Snapshot = {\n name: snapshotName,\n timestamp: Date.now(),\n doc: doc.toJSON()\n }\n snapshots.update(val => [snap, ...val])\n return snap\n}\n\nexport function updateSnapshot(snapshot: Snapshot) {\n snapshots.update(val =>\n val.map(s => {\n if (s.timestamp === snapshot.timestamp) {\n return snapshot\n }\n return s\n })\n )\n}\n\nexport function toggleViewSnapshot(view: EditorView, snap?: Snapshot) {\n if (snap) {\n const prevState = get(previousEditorState)\n if (!prevState) previousEditorState.set(view.state)\n setEditorDoc(view, snap.doc)\n } else {\n const prevState = get(previousEditorState)\n if (!prevState) {\n console.error('No previous state to restore!')\n } else {\n view.updateState(prevState)\n }\n previousEditorState.set(undefined)\n }\n selectedSnapshot.set(snap)\n}\n\nexport function restoreSnapshot(view: EditorView, snap: Snapshot) {\n setEditorDoc(view, snap.doc)\n previousEditorState.set(undefined)\n selectedSnapshot.set(undefined)\n}\n\nexport function exportSnapshot(snapshot: Snapshot) {\n const a = document.createElement('a')\n const file = new Blob([JSON.stringify(snapshot.doc)], { type: 'application/json' })\n a.href = URL.createObjectURL(file)\n a.download = `${snapshot.name}.json`\n a.click()\n}\n\nexport function deleteSnapshot(snapshot: Snapshot) {\n snapshots.update(val => val.filter(s => s.timestamp !== snapshot.timestamp))\n const selected = get(selectedSnapshot)\n if (selected?.timestamp === snapshot.timestamp) {\n selectedSnapshot.set(undefined)\n }\n}\n","export function clickOutside(el: HTMLElement, onClickOutside: () => void) {\n const onClick = (event: MouseEvent) => {\n el && !event.composedPath().includes(el) && !event.defaultPrevented && onClickOutside()\n }\n\n document.addEventListener('click', onClick, true)\n\n return {\n destroy() {\n document.removeEventListener('click', onClick, true)\n }\n }\n}\n","/**\n * Diff Match and Patch\n * Copyright 2018 The diff-match-patch Authors.\n * https://github.com/google/diff-match-patch\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Computes the difference between two texts to create a patch.\n * Applies the patch onto another text, allowing for errors.\n * @author fraser@google.com (Neil Fraser)\n */\n\n/**\n * Class containing the diff, match and patch methods.\n * @constructor\n */\nvar diff_match_patch = function() {\n\n // Defaults.\n // Redefine these in your program to override the defaults.\n\n // Number of seconds to map a diff before giving up (0 for infinity).\n this.Diff_Timeout = 1.0;\n // Cost of an empty edit operation in terms of edit characters.\n this.Diff_EditCost = 4;\n // At what point is no match declared (0.0 = perfection, 1.0 = very loose).\n this.Match_Threshold = 0.5;\n // How far to search for a match (0 = exact location, 1000+ = broad match).\n // A match this many characters away from the expected location will add\n // 1.0 to the score (0.0 is a perfect match).\n this.Match_Distance = 1000;\n // When deleting a large block of text (over ~64 characters), how close do\n // the contents have to be to match the expected contents. (0.0 = perfection,\n // 1.0 = very loose). Note that Match_Threshold controls how closely the\n // end points of a delete need to match.\n this.Patch_DeleteThreshold = 0.5;\n // Chunk size for context length.\n this.Patch_Margin = 4;\n\n // The number of bits in an int.\n this.Match_MaxBits = 32;\n};\n\n\n// DIFF FUNCTIONS\n\n\n/**\n * The data structure representing a diff is an array of tuples:\n * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]\n * which means: delete 'Hello', add 'Goodbye' and keep ' world.'\n */\nvar DIFF_DELETE = -1;\nvar DIFF_INSERT = 1;\nvar DIFF_EQUAL = 0;\n\n/**\n * Class representing one diff tuple.\n * ~Attempts to look like a two-element array (which is what this used to be).~\n * Constructor returns an actual two-element array, to allow destructing @JackuB\n * See https://github.com/JackuB/diff-match-patch/issues/14 for details\n * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL.\n * @param {string} text Text to be deleted, inserted, or retained.\n * @constructor\n */\ndiff_match_patch.Diff = function(op, text) {\n return [op, text];\n};\n\n/**\n * Find the differences between two texts. Simplifies the problem by stripping\n * any common prefix or suffix off the texts before diffing.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {boolean=} opt_checklines Optional speedup flag. If present and false,\n * then don't run a line-level diff first to identify the changed areas.\n * Defaults to true, which does a faster, slightly less optimal diff.\n * @param {number=} opt_deadline Optional time when the diff should be complete\n * by. Used internally for recursive calls. Users should set DiffTimeout\n * instead.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines,\n opt_deadline) {\n // Set a deadline by which time the diff must be complete.\n if (typeof opt_deadline == 'undefined') {\n if (this.Diff_Timeout <= 0) {\n opt_deadline = Number.MAX_VALUE;\n } else {\n opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000;\n }\n }\n var deadline = opt_deadline;\n\n // Check for null inputs.\n if (text1 == null || text2 == null) {\n throw new Error('Null input. (diff_main)');\n }\n\n // Check for equality (speedup).\n if (text1 == text2) {\n if (text1) {\n return [new diff_match_patch.Diff(DIFF_EQUAL, text1)];\n }\n return [];\n }\n\n if (typeof opt_checklines == 'undefined') {\n opt_checklines = true;\n }\n var checklines = opt_checklines;\n\n // Trim off common prefix (speedup).\n var commonlength = this.diff_commonPrefix(text1, text2);\n var commonprefix = text1.substring(0, commonlength);\n text1 = text1.substring(commonlength);\n text2 = text2.substring(commonlength);\n\n // Trim off common suffix (speedup).\n commonlength = this.diff_commonSuffix(text1, text2);\n var commonsuffix = text1.substring(text1.length - commonlength);\n text1 = text1.substring(0, text1.length - commonlength);\n text2 = text2.substring(0, text2.length - commonlength);\n\n // Compute the diff on the middle block.\n var diffs = this.diff_compute_(text1, text2, checklines, deadline);\n\n // Restore the prefix and suffix.\n if (commonprefix) {\n diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, commonprefix));\n }\n if (commonsuffix) {\n diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, commonsuffix));\n }\n this.diff_cleanupMerge(diffs);\n return diffs;\n};\n\n\n/**\n * Find the differences between two texts. Assumes that the texts do not\n * have any common prefix or suffix.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {boolean} checklines Speedup flag. If false, then don't run a\n * line-level diff first to identify the changed areas.\n * If true, then run a faster, slightly less optimal diff.\n * @param {number} deadline Time when the diff should be complete by.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines,\n deadline) {\n var diffs;\n\n if (!text1) {\n // Just add some text (speedup).\n return [new diff_match_patch.Diff(DIFF_INSERT, text2)];\n }\n\n if (!text2) {\n // Just delete some text (speedup).\n return [new diff_match_patch.Diff(DIFF_DELETE, text1)];\n }\n\n var longtext = text1.length > text2.length ? text1 : text2;\n var shorttext = text1.length > text2.length ? text2 : text1;\n var i = longtext.indexOf(shorttext);\n if (i != -1) {\n // Shorter text is inside the longer text (speedup).\n diffs = [new diff_match_patch.Diff(DIFF_INSERT, longtext.substring(0, i)),\n new diff_match_patch.Diff(DIFF_EQUAL, shorttext),\n new diff_match_patch.Diff(DIFF_INSERT,\n longtext.substring(i + shorttext.length))];\n // Swap insertions for deletions if diff is reversed.\n if (text1.length > text2.length) {\n diffs[0][0] = diffs[2][0] = DIFF_DELETE;\n }\n return diffs;\n }\n\n if (shorttext.length == 1) {\n // Single character string.\n // After the previous speedup, the character can't be an equality.\n return [new diff_match_patch.Diff(DIFF_DELETE, text1),\n new diff_match_patch.Diff(DIFF_INSERT, text2)];\n }\n\n // Check to see if the problem can be split in two.\n var hm = this.diff_halfMatch_(text1, text2);\n if (hm) {\n // A half-match was found, sort out the return data.\n var text1_a = hm[0];\n var text1_b = hm[1];\n var text2_a = hm[2];\n var text2_b = hm[3];\n var mid_common = hm[4];\n // Send both pairs off for separate processing.\n var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline);\n var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline);\n // Merge the results.\n return diffs_a.concat([new diff_match_patch.Diff(DIFF_EQUAL, mid_common)],\n diffs_b);\n }\n\n if (checklines && text1.length > 100 && text2.length > 100) {\n return this.diff_lineMode_(text1, text2, deadline);\n }\n\n return this.diff_bisect_(text1, text2, deadline);\n};\n\n\n/**\n * Do a quick line-level diff on both strings, then rediff the parts for\n * greater accuracy.\n * This speedup can produce non-minimal diffs.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {number} deadline Time when the diff should be complete by.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) {\n // Scan the text on a line-by-line basis first.\n var a = this.diff_linesToChars_(text1, text2);\n text1 = a.chars1;\n text2 = a.chars2;\n var linearray = a.lineArray;\n\n var diffs = this.diff_main(text1, text2, false, deadline);\n\n // Convert the diff back to original text.\n this.diff_charsToLines_(diffs, linearray);\n // Eliminate freak matches (e.g. blank lines)\n this.diff_cleanupSemantic(diffs);\n\n // Rediff any replacement blocks, this time character-by-character.\n // Add a dummy entry at the end.\n diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, ''));\n var pointer = 0;\n var count_delete = 0;\n var count_insert = 0;\n var text_delete = '';\n var text_insert = '';\n while (pointer < diffs.length) {\n switch (diffs[pointer][0]) {\n case DIFF_INSERT:\n count_insert++;\n text_insert += diffs[pointer][1];\n break;\n case DIFF_DELETE:\n count_delete++;\n text_delete += diffs[pointer][1];\n break;\n case DIFF_EQUAL:\n // Upon reaching an equality, check for prior redundancies.\n if (count_delete >= 1 && count_insert >= 1) {\n // Delete the offending records and add the merged ones.\n diffs.splice(pointer - count_delete - count_insert,\n count_delete + count_insert);\n pointer = pointer - count_delete - count_insert;\n var subDiff =\n this.diff_main(text_delete, text_insert, false, deadline);\n for (var j = subDiff.length - 1; j >= 0; j--) {\n diffs.splice(pointer, 0, subDiff[j]);\n }\n pointer = pointer + subDiff.length;\n }\n count_insert = 0;\n count_delete = 0;\n text_delete = '';\n text_insert = '';\n break;\n }\n pointer++;\n }\n diffs.pop(); // Remove the dummy entry at the end.\n\n return diffs;\n};\n\n\n/**\n * Find the 'middle snake' of a diff, split the problem in two\n * and return the recursively constructed diff.\n * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {number} deadline Time at which to bail if not yet complete.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) {\n // Cache the text lengths to prevent multiple calls.\n var text1_length = text1.length;\n var text2_length = text2.length;\n var max_d = Math.ceil((text1_length + text2_length) / 2);\n var v_offset = max_d;\n var v_length = 2 * max_d;\n var v1 = new Array(v_length);\n var v2 = new Array(v_length);\n // Setting all elements to -1 is faster in Chrome & Firefox than mixing\n // integers and undefined.\n for (var x = 0; x < v_length; x++) {\n v1[x] = -1;\n v2[x] = -1;\n }\n v1[v_offset + 1] = 0;\n v2[v_offset + 1] = 0;\n var delta = text1_length - text2_length;\n // If the total number of characters is odd, then the front path will collide\n // with the reverse path.\n var front = (delta % 2 != 0);\n // Offsets for start and end of k loop.\n // Prevents mapping of space beyond the grid.\n var k1start = 0;\n var k1end = 0;\n var k2start = 0;\n var k2end = 0;\n for (var d = 0; d < max_d; d++) {\n // Bail out if deadline is reached.\n if ((new Date()).getTime() > deadline) {\n break;\n }\n\n // Walk the front path one step.\n for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {\n var k1_offset = v_offset + k1;\n var x1;\n if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {\n x1 = v1[k1_offset + 1];\n } else {\n x1 = v1[k1_offset - 1] + 1;\n }\n var y1 = x1 - k1;\n while (x1 < text1_length && y1 < text2_length &&\n text1.charAt(x1) == text2.charAt(y1)) {\n x1++;\n y1++;\n }\n v1[k1_offset] = x1;\n if (x1 > text1_length) {\n // Ran off the right of the graph.\n k1end += 2;\n } else if (y1 > text2_length) {\n // Ran off the bottom of the graph.\n k1start += 2;\n } else if (front) {\n var k2_offset = v_offset + delta - k1;\n if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {\n // Mirror x2 onto top-left coordinate system.\n var x2 = text1_length - v2[k2_offset];\n if (x1 >= x2) {\n // Overlap detected.\n return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);\n }\n }\n }\n }\n\n // Walk the reverse path one step.\n for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {\n var k2_offset = v_offset + k2;\n var x2;\n if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {\n x2 = v2[k2_offset + 1];\n } else {\n x2 = v2[k2_offset - 1] + 1;\n }\n var y2 = x2 - k2;\n while (x2 < text1_length && y2 < text2_length &&\n text1.charAt(text1_length - x2 - 1) ==\n text2.charAt(text2_length - y2 - 1)) {\n x2++;\n y2++;\n }\n v2[k2_offset] = x2;\n if (x2 > text1_length) {\n // Ran off the left of the graph.\n k2end += 2;\n } else if (y2 > text2_length) {\n // Ran off the top of the graph.\n k2start += 2;\n } else if (!front) {\n var k1_offset = v_offset + delta - k2;\n if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {\n var x1 = v1[k1_offset];\n var y1 = v_offset + x1 - k1_offset;\n // Mirror x2 onto top-left coordinate system.\n x2 = text1_length - x2;\n if (x1 >= x2) {\n // Overlap detected.\n return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);\n }\n }\n }\n }\n }\n // Diff took too long and hit the deadline or\n // number of diffs equals number of characters, no commonality at all.\n return [new diff_match_patch.Diff(DIFF_DELETE, text1),\n new diff_match_patch.Diff(DIFF_INSERT, text2)];\n};\n\n\n/**\n * Given the location of the 'middle snake', split the diff in two parts\n * and recurse.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {number} x Index of split point in text1.\n * @param {number} y Index of split point in text2.\n * @param {number} deadline Time at which to bail if not yet complete.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y,\n deadline) {\n var text1a = text1.substring(0, x);\n var text2a = text2.substring(0, y);\n var text1b = text1.substring(x);\n var text2b = text2.substring(y);\n\n // Compute both diffs serially.\n var diffs = this.diff_main(text1a, text2a, false, deadline);\n var diffsb = this.diff_main(text1b, text2b, false, deadline);\n\n return diffs.concat(diffsb);\n};\n\n\n/**\n * Split two texts into an array of strings. Reduce the texts to a string of\n * hashes where each Unicode character represents one line.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}\n * An object containing the encoded text1, the encoded text2 and\n * the array of unique strings.\n * The zeroth element of the array of unique strings is intentionally blank.\n * @private\n */\ndiff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) {\n var lineArray = []; // e.g. lineArray[4] == 'Hello\\n'\n var lineHash = {}; // e.g. lineHash['Hello\\n'] == 4\n\n // '\\x00' is a valid character, but various debuggers don't like it.\n // So we'll insert a junk entry to avoid generating a null character.\n lineArray[0] = '';\n\n /**\n * Split a text into an array of strings. Reduce the texts to a string of\n * hashes where each Unicode character represents one line.\n * Modifies linearray and linehash through being a closure.\n * @param {string} text String to encode.\n * @return {string} Encoded string.\n * @private\n */\n function diff_linesToCharsMunge_(text) {\n var chars = '';\n // Walk the text, pulling out a substring for each line.\n // text.split('\\n') would would temporarily double our memory footprint.\n // Modifying text would create many large strings to garbage collect.\n var lineStart = 0;\n var lineEnd = -1;\n // Keeping our own length variable is faster than looking it up.\n var lineArrayLength = lineArray.length;\n while (lineEnd < text.length - 1) {\n lineEnd = text.indexOf('\\n', lineStart);\n if (lineEnd == -1) {\n lineEnd = text.length - 1;\n }\n var line = text.substring(lineStart, lineEnd + 1);\n\n if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :\n (lineHash[line] !== undefined)) {\n chars += String.fromCharCode(lineHash[line]);\n } else {\n if (lineArrayLength == maxLines) {\n // Bail out at 65535 because\n // String.fromCharCode(65536) == String.fromCharCode(0)\n line = text.substring(lineStart);\n lineEnd = text.length;\n }\n chars += String.fromCharCode(lineArrayLength);\n lineHash[line] = lineArrayLength;\n lineArray[lineArrayLength++] = line;\n }\n lineStart = lineEnd + 1;\n }\n return chars;\n }\n // Allocate 2/3rds of the space for text1, the rest for text2.\n var maxLines = 40000;\n var chars1 = diff_linesToCharsMunge_(text1);\n maxLines = 65535;\n var chars2 = diff_linesToCharsMunge_(text2);\n return {chars1: chars1, chars2: chars2, lineArray: lineArray};\n};\n\n\n/**\n * Rehydrate the text in a diff from a string of line hashes to real lines of\n * text.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @param {!Array.<string>} lineArray Array of unique strings.\n * @private\n */\ndiff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) {\n for (var i = 0; i < diffs.length; i++) {\n var chars = diffs[i][1];\n var text = [];\n for (var j = 0; j < chars.length; j++) {\n text[j] = lineArray[chars.charCodeAt(j)];\n }\n diffs[i][1] = text.join('');\n }\n};\n\n\n/**\n * Determine the common prefix of two strings.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the start of each\n * string.\n */\ndiff_match_patch.prototype.diff_commonPrefix = function(text1, text2) {\n // Quick check for common null cases.\n if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {\n return 0;\n }\n // Binary search.\n // Performance analysis: https://neil.fraser.name/news/2007/10/09/\n var pointermin = 0;\n var pointermax = Math.min(text1.length, text2.length);\n var pointermid = pointermax;\n var pointerstart = 0;\n while (pointermin < pointermid) {\n if (text1.substring(pointerstart, pointermid) ==\n text2.substring(pointerstart, pointermid)) {\n pointermin = pointermid;\n pointerstart = pointermin;\n } else {\n pointermax = pointermid;\n }\n pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);\n }\n return pointermid;\n};\n\n\n/**\n * Determine the common suffix of two strings.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the end of each string.\n */\ndiff_match_patch.prototype.diff_commonSuffix = function(text1, text2) {\n // Quick check for common null cases.\n if (!text1 || !text2 ||\n text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) {\n return 0;\n }\n // Binary search.\n // Performance analysis: https://neil.fraser.name/news/2007/10/09/\n var pointermin = 0;\n var pointermax = Math.min(text1.length, text2.length);\n var pointermid = pointermax;\n var pointerend = 0;\n while (pointermin < pointermid) {\n if (text1.substring(text1.length - pointermid, text1.length - pointerend) ==\n text2.substring(text2.length - pointermid, text2.length - pointerend)) {\n pointermin = pointermid;\n pointerend = pointermin;\n } else {\n pointermax = pointermid;\n }\n pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);\n }\n return pointermid;\n};\n\n\n/**\n * Determine if the suffix of one string is the prefix of another.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the end of the first\n * string and the start of the second string.\n * @private\n */\ndiff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) {\n // Cache the text lengths to prevent multiple calls.\n var text1_length = text1.length;\n var text2_length = text2.length;\n // Eliminate the null case.\n if (text1_length == 0 || text2_length == 0) {\n return 0;\n }\n // Truncate the longer string.\n if (text1_length > text2_length) {\n text1 = text1.substring(text1_length - text2_length);\n } else if (text1_length < text2_length) {\n text2 = text2.substring(0, text1_length);\n }\n var text_length = Math.min(text1_length, text2_length);\n // Quick check for the worst case.\n if (text1 == text2) {\n return text_length;\n }\n\n // Start by looking for a single character match\n // and increase length until no match is found.\n // Performance analysis: https://neil.fraser.name/news/2010/11/04/\n var best = 0;\n var length = 1;\n while (true) {\n var pattern = text1.substring(text_length - length);\n var found = text2.indexOf(pattern);\n if (found == -1) {\n return best;\n }\n length += found;\n if (found == 0 || text1.substring(text_length - length) ==\n text2.substring(0, length)) {\n best = length;\n length++;\n }\n }\n};\n\n\n/**\n * Do the two texts share a substring which is at least half the length of the\n * longer text?\n * This speedup can produce non-minimal diffs.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {Array.<string>} Five element Array, containing the prefix of\n * text1, the suffix of text1, the prefix of text2, the suffix of\n * text2 and the common middle. Or null if there was no match.\n * @private\n */\ndiff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) {\n if (this.Diff_Timeout <= 0) {\n // Don't risk returning a non-optimal diff if we have unlimited time.\n return null;\n }\n var longtext = text1.length > text2.length ? text1 : text2;\n var shorttext = text1.length > text2.length ? text2 : text1;\n if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {\n return null; // Pointless.\n }\n var dmp = this; // 'this' becomes 'window' in a closure.\n\n /**\n * Does a substring of shorttext exist within longtext such that the substring\n * is at least half the length of longtext?\n * Closure, but does not reference any external variables.\n * @param {string} longtext Longer string.\n * @param {string} shorttext Shorter string.\n * @param {number} i Start index of quarter length substring within longtext.\n * @return {Array.<string>} Five element Array, containing the prefix of\n * longtext, the suffix of longtext, the prefix of shorttext, the suffix\n * of shorttext and the common middle. Or null if there was no match.\n * @private\n */\n function diff_halfMatchI_(longtext, shorttext, i) {\n // Start with a 1/4 length substring at position i as a seed.\n var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));\n var j = -1;\n var best_common = '';\n var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;\n while ((j = shorttext.indexOf(seed, j + 1)) != -1) {\n var prefixLength = dmp.diff_commonPrefix(longtext.substring(i),\n shorttext.substring(j));\n var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i),\n shorttext.substring(0, j));\n if (best_common.length < suffixLength + prefixLength) {\n best_common = shorttext.substring(j - suffixLength, j) +\n shorttext.substring(j, j + prefixLength);\n best_longtext_a = longtext.substring(0, i - suffixLength);\n best_longtext_b = longtext.substring(i + prefixLength);\n best_shorttext_a = shorttext.substring(0, j - suffixLength);\n best_shorttext_b = shorttext.substring(j + prefixLength);\n }\n }\n if (best_common.length * 2 >= longtext.length) {\n return [best_longtext_a, best_longtext_b,\n best_shorttext_a, best_shorttext_b, best_common];\n } else {\n return null;\n }\n }\n\n // First check if the second quarter is the seed for a half-match.\n var hm1 = diff_halfMatchI_(longtext, shorttext,\n Math.ceil(longtext.length / 4));\n // Check again based on the third quarter.\n var hm2 = diff_halfMatchI_(longtext, shorttext,\n Math.ceil(longtext.length / 2));\n var hm;\n if (!hm1 && !hm2) {\n return null;\n } else if (!hm2) {\n hm = hm1;\n } else if (!hm1) {\n hm = hm2;\n } else {\n // Both matched. Select the longest.\n hm = hm1[4].length > hm2[4].length ? hm1 : hm2;\n }\n\n // A half-match was found, sort out the return data.\n var text1_a, text1_b, text2_a, text2_b;\n if (text1.length > text2.length) {\n text1_a = hm[0];\n text1_b = hm[1];\n text2_a = hm[2];\n text2_b = hm[3];\n } else {\n text2_a = hm[0];\n text2_b = hm[1];\n text1_a = hm[2];\n text1_b = hm[3];\n }\n var mid_common = hm[4];\n return [text1_a, text1_b, text2_a, text2_b, mid_common];\n};\n\n\n/**\n * Reduce the number of edits by eliminating semantically trivial equalities.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupSemantic = function(diffs) {\n var changes = false;\n var equalities = []; // Stack of indices where equalities are found.\n var equalitiesLength = 0; // Keeping our own length var is faster in JS.\n /** @type {?string} */\n var lastEquality = null;\n // Always equal to diffs[equalities[equalitiesLength - 1]][1]\n var pointer = 0; // Index of current position.\n // Number of characters that changed prior to the equality.\n var length_insertions1 = 0;\n var length_deletions1 = 0;\n // Number of characters that changed after the equality.\n var length_insertions2 = 0;\n var length_deletions2 = 0;\n while (pointer < diffs.length) {\n if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.\n equalities[equalitiesLength++] = pointer;\n length_insertions1 = length_insertions2;\n length_deletions1 = length_deletions2;\n length_insertions2 = 0;\n length_deletions2 = 0;\n lastEquality = diffs[pointer][1];\n } else { // An insertion or deletion.\n if (diffs[pointer][0] == DIFF_INSERT) {\n length_insertions2 += diffs[pointer][1].length;\n } else {\n length_deletions2 += diffs[pointer][1].length;\n }\n // Eliminate an equality that is smaller or equal to the edits on both\n // sides of it.\n if (lastEquality && (lastEquality.length <=\n Math.max(length_insertions1, length_deletions1)) &&\n (lastEquality.length <= Math.max(length_insertions2,\n length_deletions2))) {\n // Duplicate record.\n diffs.splice(equalities[equalitiesLength - 1], 0,\n new diff_match_patch.Diff(DIFF_DELETE, lastEquality));\n // Change second copy to insert.\n diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n // Throw away the equality we just deleted.\n equalitiesLength--;\n // Throw away the previous equality (it needs to be reevaluated).\n equalitiesLength--;\n pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;\n length_insertions1 = 0; // Reset the counters.\n length_deletions1 = 0;\n length_insertions2 = 0;\n length_deletions2 = 0;\n lastEquality = null;\n changes = true;\n }\n }\n pointer++;\n }\n\n // Normalize the diff.\n if (changes) {\n this.diff_cleanupMerge(diffs);\n }\n this.diff_cleanupSemanticLossless(diffs);\n\n // Find any overlaps between deletions and insertions.\n // e.g: <del>abcxxx</del><ins>xxxdef</ins>\n // -> <del>abc</del>xxx<ins>def</ins>\n // e.g: <del>xxxabc</del><ins>defxxx</ins>\n // -> <ins>def</ins>xxx<del>abc</del>\n // Only extract an overlap if it is as big as the edit ahead or behind it.\n pointer = 1;\n while (pointer < diffs.length) {\n if (diffs[pointer - 1][0] == DIFF_DELETE &&\n diffs[pointer][0] == DIFF_INSERT) {\n var deletion = diffs[pointer - 1][1];\n var insertion = diffs[pointer][1];\n var overlap_length1 = this.diff_commonOverlap_(deletion, insertion);\n var overlap_length2 = this.diff_commonOverlap_(insertion, deletion);\n if (overlap_length1 >= overlap_length2) {\n if (overlap_length1 >= deletion.length / 2 ||\n overlap_length1 >= insertion.length / 2) {\n // Overlap found. Insert an equality and trim the surrounding edits.\n diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL,\n insertion.substring(0, overlap_length1)));\n diffs[pointer - 1][1] =\n deletion.substring(0, deletion.length - overlap_length1);\n diffs[pointer + 1][1] = insertion.substring(overlap_length1);\n pointer++;\n }\n } else {\n if (overlap_length2 >= deletion.length / 2 ||\n overlap_length2 >= insertion.length / 2) {\n // Reverse overlap found.\n // Insert an equality and swap and trim the surrounding edits.\n diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL,\n deletion.substring(0, overlap_length2)));\n diffs[pointer - 1][0] = DIFF_INSERT;\n diffs[pointer - 1][1] =\n insertion.substring(0, insertion.length - overlap_length2);\n diffs[pointer + 1][0] = DIFF_DELETE;\n diffs[pointer + 1][1] =\n deletion.substring(overlap_length2);\n pointer++;\n }\n }\n pointer++;\n }\n pointer++;\n }\n};\n\n\n/**\n * Look for single edits surrounded on both sides by equalities\n * which can be shifted sideways to align the edit to a word boundary.\n * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) {\n /**\n * Given two strings, compute a score representing whether the internal\n * boundary falls on logical boundaries.\n * Scores range from 6 (best) to 0 (worst).\n * Closure, but does not reference any external variables.\n * @param {string} one First string.\n * @param {string} two Second string.\n * @return {number} The score.\n * @private\n */\n function diff_cleanupSemanticScore_(one, two) {\n if (!one || !two) {\n // Edges are the best.\n return 6;\n }\n\n // Each port of this function behaves slightly differently due to\n // subtle differences in each language's definition of things like\n // 'whitespace'. Since this function's purpose is largely cosmetic,\n // the choice has been made to use each language's native features\n // rather than force total conformity.\n var char1 = one.charAt(one.length - 1);\n var char2 = two.charAt(0);\n var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_);\n var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_);\n var whitespace1 = nonAlphaNumeric1 &&\n char1.match(diff_match_patch.whitespaceRegex_);\n var whitespace2 = nonAlphaNumeric2 &&\n char2.match(diff_match_patch.whitespaceRegex_);\n var lineBreak1 = whitespace1 &&\n char1.match(diff_match_patch.linebreakRegex_);\n var lineBreak2 = whitespace2 &&\n char2.match(diff_match_patch.linebreakRegex_);\n var blankLine1 = lineBreak1 &&\n one.match(diff_match_patch.blanklineEndRegex_);\n var blankLine2 = lineBreak2 &&\n two.match(diff_match_patch.blanklineStartRegex_);\n\n if (blankLine1 || blankLine2) {\n // Five points for blank lines.\n return 5;\n } else if (lineBreak1 || lineBreak2) {\n // Four points for line breaks.\n return 4;\n } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {\n // Three points for end of sentences.\n return 3;\n } else if (whitespace1 || whitespace2) {\n // Two points for whitespace.\n return 2;\n } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {\n // One point for non-alphanumeric.\n return 1;\n }\n return 0;\n }\n\n var pointer = 1;\n // Intentionally ignore the first and last element (don't need checking).\n while (pointer < diffs.length - 1) {\n if (diffs[pointer - 1][0] == DIFF_EQUAL &&\n diffs[pointer + 1][0] == DIFF_EQUAL) {\n // This is a single edit surrounded by equalities.\n var equality1 = diffs[pointer - 1][1];\n var edit = diffs[pointer][1];\n var equality2 = diffs[pointer + 1][1];\n\n // First, shift the edit as far left as possible.\n var commonOffset = this.diff_commonSuffix(equality1, edit);\n if (commonOffset) {\n var commonString = edit.substring(edit.length - commonOffset);\n equality1 = equality1.substring(0, equality1.length - commonOffset);\n edit = commonString + edit.substring(0, edit.length - commonOffset);\n equality2 = commonString + equality2;\n }\n\n // Second, step character by character right, looking for the best fit.\n var bestEquality1 = equality1;\n var bestEdit = edit;\n var bestEquality2 = equality2;\n var bestScore = diff_cleanupSemanticScore_(equality1, edit) +\n diff_cleanupSemanticScore_(edit, equality2);\n while (edit.charAt(0) === equality2.charAt(0)) {\n equality1 += edit.charAt(0);\n edit = edit.substring(1) + equality2.charAt(0);\n equality2 = equality2.substring(1);\n var score = diff_cleanupSemanticScore_(equality1, edit) +\n diff_cleanupSemanticScore_(edit, equality2);\n // The >= encourages trailing rather than leading whitespace on edits.\n if (score >= bestScore) {\n bestScore = score;\n bestEquality1 = equality1;\n bestEdit = edit;\n bestEquality2 = equality2;\n }\n }\n\n if (diffs[pointer - 1][1] != bestEquality1) {\n // We have an improvement, save it back to the diff.\n if (bestEquality1) {\n diffs[pointer - 1][1] = bestEquality1;\n } else {\n diffs.splice(pointer - 1, 1);\n pointer--;\n }\n diffs[pointer][1] = bestEdit;\n if (bestEquality2) {\n diffs[pointer + 1][1] = bestEquality2;\n } else {\n diffs.splice(pointer + 1, 1);\n pointer--;\n }\n }\n }\n pointer++;\n }\n};\n\n// Define some regex patterns for matching boundaries.\ndiff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;\ndiff_match_patch.whitespaceRegex_ = /\\s/;\ndiff_match_patch.linebreakRegex_ = /[\\r\\n]/;\ndiff_match_patch.blanklineEndRegex_ = /\\n\\r?\\n$/;\ndiff_match_patch.blanklineStartRegex_ = /^\\r?\\n\\r?\\n/;\n\n/**\n * Reduce the number of edits by eliminating operationally trivial equalities.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) {\n var changes = false;\n var equalities = []; // Stack of indices where equalities are found.\n var equalitiesLength = 0; // Keeping our own length var is faster in JS.\n /** @type {?string} */\n var lastEquality = null;\n // Always equal to diffs[equalities[equalitiesLength - 1]][1]\n var pointer = 0; // Index of current position.\n // Is there an insertion operation before the last equality.\n var pre_ins = false;\n // Is there a deletion operation before the last equality.\n var pre_del = false;\n // Is there an insertion operation after the last equality.\n var post_ins = false;\n // Is there a deletion operation after the last equality.\n var post_del = false;\n while (pointer < diffs.length) {\n if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.\n if (diffs[pointer][1].length < this.Diff_EditCost &&\n (post_ins || post_del)) {\n // Candidate found.\n equalities[equalitiesLength++] = pointer;\n pre_ins = post_ins;\n pre_del = post_del;\n lastEquality = diffs[pointer][1];\n } else {\n // Not a candidate, and can never become one.\n equalitiesLength = 0;\n lastEquality = null;\n }\n post_ins = post_del = false;\n } else { // An insertion or deletion.\n if (diffs[pointer][0] == DIFF_DELETE) {\n post_del = true;\n } else {\n post_ins = true;\n }\n /*\n * Five types to be split:\n * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>\n * <ins>A</ins>X<ins>C</ins><del>D</del>\n * <ins>A</ins><del>B</del>X<ins>C</ins>\n * <ins>A</del>X<ins>C</ins><del>D</del>\n * <ins>A</ins><del>B</del>X<del>C</del>\n */\n if (lastEquality && ((pre_ins && pre_del && post_ins && post_del) ||\n ((lastEquality.length < this.Diff_EditCost / 2) &&\n (pre_ins + pre_del + post_ins + post_del) == 3))) {\n // Duplicate record.\n diffs.splice(equalities[equalitiesLength - 1], 0,\n new diff_match_patch.Diff(DIFF_DELETE, lastEquality));\n // Change second copy to insert.\n diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n equalitiesLength--; // Throw away the equality we just deleted;\n lastEquality = null;\n if (pre_ins && pre_del) {\n // No changes made which could affect previous entry, keep going.\n post_ins = post_del = true;\n equalitiesLength = 0;\n } else {\n equalitiesLength--; // Throw away the previous equality.\n pointer = equalitiesLength > 0 ?\n equalities[equalitiesLength - 1] : -1;\n post_ins = post_del = false;\n }\n changes = true;\n }\n }\n pointer++;\n }\n\n if (changes) {\n this.diff_cleanupMerge(diffs);\n }\n};\n\n\n/**\n * Reorder and merge like edit sections. Merge equalities.\n * Any edit section can move as long as it doesn't cross an equality.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupMerge = function(diffs) {\n // Add a dummy entry at the end.\n diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, ''));\n var pointer = 0;\n var count_delete = 0;\n var count_insert = 0;\n var text_delete = '';\n var text_insert = '';\n var commonlength;\n while (pointer < diffs.length) {\n switch (diffs[pointer][0]) {\n case DIFF_INSERT:\n count_insert++;\n text_insert += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_DELETE:\n count_delete++;\n text_delete += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_EQUAL:\n // Upon reaching an equality, check for prior redundancies.\n if (count_delete + count_insert > 1) {\n if (count_delete !== 0 && count_insert !== 0) {\n // Factor out any common prefixies.\n commonlength = this.diff_commonPrefix(text_insert, text_delete);\n if (commonlength !== 0) {\n if ((pointer - count_delete - count_insert) > 0 &&\n diffs[pointer - count_delete - count_insert - 1][0] ==\n DIFF_EQUAL) {\n diffs[pointer - count_delete - count_insert - 1][1] +=\n text_insert.substring(0, commonlength);\n } else {\n diffs.splice(0, 0, new diff_match_patch.Diff(DIFF_EQUAL,\n text_insert.substring(0, commonlength)));\n pointer++;\n }\n text_insert = text_insert.substring(commonlength);\n text_delete = text_delete.substring(commonlength);\n }\n // Factor out any common suffixies.\n commonlength = this.diff_commonSuffix(text_insert, text_delete);\n if (commonlength !== 0) {\n diffs[pointer][1] = text_insert.substring(text_insert.length -\n commonlength) + diffs[pointer][1];\n text_insert = text_insert.substring(0, text_insert.length -\n commonlength);\n text_delete = text_delete.substring(0, text_delete.length -\n commonlength);\n }\n }\n // Delete the offending records and add the merged ones.\n pointer -= count_delete + count_insert;\n diffs.splice(pointer, count_delete + count_insert);\n if (text_delete.length) {\n diffs.splice(pointer, 0,\n new diff_match_patch.Diff(DIFF_DELETE, text_delete));\n pointer++;\n }\n if (text_insert.length) {\n diffs.splice(pointer, 0,\n new diff_match_patch.Diff(DIFF_INSERT, text_insert));\n pointer++;\n }\n pointer++;\n } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) {\n // Merge this equality with the previous one.\n diffs[pointer - 1][1] += diffs[pointer][1];\n diffs.splice(pointer, 1);\n } else {\n pointer++;\n }\n count_insert = 0;\n count_delete = 0;\n text_delete = '';\n text_insert = '';\n break;\n }\n }\n if (diffs[diffs.length - 1][1] === '') {\n diffs.pop(); // Remove the dummy entry at the end.\n }\n\n // Second pass: look for single edits surrounded on both sides by equalities\n // which can be shifted sideways to eliminate an equality.\n // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC\n var changes = false;\n pointer = 1;\n // Intentionally ignore the first and last element (don't need checking).\n while (pointer < diffs.length - 1) {\n if (diffs[pointer - 1][0] == DIFF_EQUAL &&\n diffs[pointer + 1][0] == DIFF_EQUAL) {\n // This is a single edit surrounded by equalities.\n if (diffs[pointer][1].substring(diffs[pointer][1].length -\n diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) {\n // Shift the edit over the previous equality.\n diffs[pointer][1] = diffs[pointer - 1][1] +\n diffs[pointer][1].substring(0, diffs[pointer][1].length -\n diffs[pointer - 1][1].length);\n diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];\n diffs.splice(pointer - 1, 1);\n changes = true;\n } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==\n diffs[pointer + 1][1]) {\n // Shift the edit over the next equality.\n diffs[pointer - 1][1] += diffs[pointer + 1][1];\n diffs[pointer][1] =\n diffs[pointer][1].substring(diffs[pointer + 1][1].length) +\n diffs[pointer + 1][1];\n diffs.splice(pointer + 1, 1);\n changes = true;\n }\n }\n pointer++;\n }\n // If shifts were made, the diff needs reordering and another shift sweep.\n if (changes) {\n this.diff_cleanupMerge(diffs);\n }\n};\n\n\n/**\n * loc is a location in text1, compute and return the equivalent location in\n * text2.\n * e.g. 'The cat' vs 'The big cat', 1->1, 5->8\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @param {number} loc Location within text1.\n * @return {number} Location within text2.\n */\ndiff_match_patch.prototype.diff_xIndex = function(diffs, loc) {\n var chars1 = 0;\n var chars2 = 0;\n var last_chars1 = 0;\n var last_chars2 = 0;\n var x;\n for (x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion.\n chars1 += diffs[x][1].length;\n }\n if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion.\n chars2 += diffs[x][1].length;\n }\n if (chars1 > loc) { // Overshot the location.\n break;\n }\n last_chars1 = chars1;\n last_chars2 = chars2;\n }\n // Was the location was deleted?\n if (diffs.length != x && diffs[x][0] === DIFF_DELETE) {\n return last_chars2;\n }\n // Add the remaining character length.\n return last_chars2 + (loc - last_chars1);\n};\n\n\n/**\n * Convert a diff array into a pretty HTML report.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @return {string} HTML representation.\n */\ndiff_match_patch.prototype.diff_prettyHtml = function(diffs) {\n var html = [];\n var pattern_amp = /&/g;\n var pattern_lt = /</g;\n var pattern_gt = />/g;\n var pattern_para = /\\n/g;\n for (var x = 0; x < diffs.length; x++) {\n var op = diffs[x][0]; // Operation (insert, delete, equal)\n var data = diffs[x][1]; // Text of change.\n var text = data.replace(pattern_amp, '&amp;').replace(pattern_lt, '&lt;')\n .replace(pattern_gt, '&gt;').replace(pattern_para, '&para;<br>');\n switch (op) {\n case DIFF_INSERT:\n html[x] = '<ins style=\"background:#e6ffe6;\">' + text + '</ins>';\n break;\n case DIFF_DELETE:\n html[x] = '<del style=\"background:#ffe6e6;\">' + text + '</del>';\n break;\n case DIFF_EQUAL:\n html[x] = '<span>' + text + '</span>';\n break;\n }\n }\n return html.join('');\n};\n\n\n/**\n * Compute and return the source text (all equalities and deletions).\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @return {string} Source text.\n */\ndiff_match_patch.prototype.diff_text1 = function(diffs) {\n var text = [];\n for (var x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_INSERT) {\n text[x] = diffs[x][1];\n }\n }\n return text.join('');\n};\n\n\n/**\n * Compute and return the destination text (all equalities and insertions).\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @return {string} Destination text.\n */\ndiff_match_patch.prototype.diff_text2 = function(diffs) {\n var text = [];\n for (var x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_DELETE) {\n text[x] = diffs[x][1];\n }\n }\n return text.join('');\n};\n\n\n/**\n * Compute the Levenshtein distance; the number of inserted, deleted or\n * substituted characters.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @return {number} Number of changes.\n */\ndiff_match_patch.prototype.diff_levenshtein = function(diffs) {\n var levenshtein = 0;\n var insertions = 0;\n var deletions = 0;\n for (var x = 0; x < diffs.length; x++) {\n var op = diffs[x][0];\n var data = diffs[x][1];\n switch (op) {\n case DIFF_INSERT:\n insertions += data.length;\n break;\n case DIFF_DELETE:\n deletions += data.length;\n break;\n case DIFF_EQUAL:\n // A deletion and an insertion is one substitution.\n levenshtein += Math.max(insertions, deletions);\n insertions = 0;\n deletions = 0;\n break;\n }\n }\n levenshtein += Math.max(insertions, deletions);\n return levenshtein;\n};\n\n\n/**\n * Crush the diff into an encoded string which describes the operations\n * required to transform text1 into text2.\n * E.g. =3\\t-2\\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.\n * Operations are tab-separated. Inserted text is escaped using %xx notation.\n * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.\n * @return {string} Delta text.\n */\ndiff_match_patch.prototype.diff_toDelta = function(diffs) {\n var text = [];\n for (var x = 0; x < diffs.length; x++) {\n switch (diffs[x][0]) {\n case DIFF_INSERT:\n text[x] = '+' + encodeURI(diffs[x][1]);\n break;\n case DIFF_DELETE:\n text[x] = '-' + diffs[x][1].length;\n break;\n case DIFF_EQUAL:\n text[x] = '=' + diffs[x][1].length;\n break;\n }\n }\n return text.join('\\t').replace(/%20/g, ' ');\n};\n\n\n/**\n * Given the original text1, and an encoded string which describes the\n * operations required to transform text1 into text2, compute the full diff.\n * @param {string} text1 Source string for the diff.\n * @param {string} delta Delta text.\n * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.\n * @throws {!Error} If invalid input.\n */\ndiff_match_patch.prototype.diff_fromDelta = function(text1, delta) {\n var diffs = [];\n var diffsLength = 0; // Keeping our own length var is faster in JS.\n var pointer = 0; // Cursor in text1\n var tokens = delta.split(/\\t/g);\n for (var x = 0; x < tokens.length; x++) {\n // Each token begins with a one character parameter which specifies the\n // operation of this token (delete, insert, equality).\n var param = tokens[x].substring(1);\n switch (tokens[x].charAt(0)) {\n case '+':\n try {\n diffs[diffsLength++] =\n new diff_match_patch.Diff(DIFF_INSERT, decodeURI(param));\n } catch (ex) {\n // Malformed URI sequence.\n throw new Error('Illegal escape in diff_fromDelta: ' + param);\n }\n break;\n case '-':\n // Fall through.\n case '=':\n var n = parseInt(param, 10);\n if (isNaN(n) || n < 0) {\n throw new Error('Invalid number in diff_fromDelta: ' + param);\n }\n var text = text1.substring(pointer, pointer += n);\n if (tokens[x].charAt(0) == '=') {\n diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_EQUAL, text);\n } else {\n diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_DELETE, text);\n }\n break;\n default:\n // Blank tokens are ok (from a trailing \\t).\n // Anything else is an error.\n if (tokens[x]) {\n throw new Error('Invalid diff operation in diff_fromDelta: ' +\n tokens[x]);\n }\n }\n }\n if (pointer != text1.length) {\n throw new Error('Delta length (' + pointer +\n ') does not equal source text length (' + text1.length + ').');\n }\n return diffs;\n};\n\n\n// MATCH FUNCTIONS\n\n\n/**\n * Locate the best instance of 'pattern' in 'text' near 'loc'.\n * @param {string} text The text to search.\n * @param {string} pattern The pattern to search for.\n * @param {number} loc The location to search around.\n * @return {number} Best match index or -1.\n */\ndiff_match_patch.prototype.match_main = function(text, pattern, loc) {\n // Check for null inputs.\n if (text == null || pattern == null || loc == null) {\n throw new Error('Null input. (match_main)');\n }\n\n loc = Math.max(0, Math.min(loc, text.length));\n if (text == pattern) {\n // Shortcut (potentially not guaranteed by the algorithm)\n return 0;\n } else if (!text.length) {\n // Nothing to match.\n return -1;\n } else if (text.substring(loc, loc + pattern.length) == pattern) {\n // Perfect match at the perfect spot! (Includes case of null pattern)\n return loc;\n } else {\n // Do a fuzzy compare.\n return this.match_bitap_(text, pattern, loc);\n }\n};\n\n\n/**\n * Locate the best instance of 'pattern' in 'text' near 'loc' using the\n * Bitap algorithm.\n * @param {string} text The text to search.\n * @param {string} pattern The pattern to search for.\n * @param {number} loc The location to search around.\n * @return {number} Best match index or -1.\n * @private\n */\ndiff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) {\n if (pattern.length > this.Match_MaxBits) {\n throw new Error('Pattern too long for this browser.');\n }\n\n // Initialise the alphabet.\n var s = this.match_alphabet_(pattern);\n\n var dmp = this; // 'this' becomes 'window' in a closure.\n\n /**\n * Compute and return the score for a match with e errors and x location.\n * Accesses loc and pattern through being a closure.\n * @param {number} e Number of errors in match.\n * @param {number} x Location of match.\n * @return {number} Overall score for match (0.0 = good, 1.0 = bad).\n * @private\n */\n function match_bitapScore_(e, x) {\n var accuracy = e / pattern.length;\n var proximity = Math.abs(loc - x);\n if (!dmp.Match_Distance) {\n // Dodge divide by zero error.\n return proximity ? 1.0 : accuracy;\n }\n return accuracy + (proximity / dmp.Match_Distance);\n }\n\n // Highest score beyond which we give up.\n var score_threshold = this.Match_Threshold;\n // Is there a nearby exact match? (speedup)\n var best_loc = text.indexOf(pattern, loc);\n if (best_loc != -1) {\n score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold);\n // What about in the other direction? (speedup)\n best_loc = text.lastIndexOf(pattern, loc + pattern.length);\n if (best_loc != -1) {\n score_threshold =\n Math.min(match_bitapScore_(0, best_loc), score_threshold);\n }\n }\n\n // Initialise the bit arrays.\n var matchmask = 1 << (pattern.length - 1);\n best_loc = -1;\n\n var bin_min, bin_mid;\n var bin_max = pattern.length + text.length;\n var last_rd;\n for (var d = 0; d < pattern.length; d++) {\n // Scan for the best match; each iteration allows for one more error.\n // Run a binary search to determine how far from 'loc' we can stray at this\n // error level.\n bin_min = 0;\n bin_mid = bin_max;\n while (bin_min < bin_mid) {\n if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {\n bin_min = bin_mid;\n } else {\n bin_max = bin_mid;\n }\n bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min);\n }\n // Use the result from this iteration as the maximum for the next.\n bin_max = bin_mid;\n var start = Math.max(1, loc - bin_mid + 1);\n var finish = Math.min(loc + bin_mid, text.length) + pattern.length;\n\n var rd = Array(finish + 2);\n rd[finish + 1] = (1 << d) - 1;\n for (var j = finish; j >= start; j--) {\n // The alphabet (s) is a sparse hash, so the following line generates\n // warnings.\n var charMatch = s[text.charAt(j - 1)];\n if (d === 0) { // First pass: exact match.\n rd[j] = ((rd[j + 1] << 1) | 1) & charMatch;\n } else { // Subsequent passes: fuzzy match.\n rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) |\n (((last_rd[j + 1] | last_rd[j]) << 1) | 1) |\n last_rd[j + 1];\n }\n if (rd[j] & matchmask) {\n var score = match_bitapScore_(d, j - 1);\n // This match will almost certainly be better than any existing match.\n // But check anyway.\n if (score <= score_threshold) {\n // Told you so.\n score_threshold = score;\n best_loc = j - 1;\n if (best_loc > loc) {\n // When passing loc, don't exceed our current distance from loc.\n start = Math.max(1, 2 * loc - best_loc);\n } else {\n // Already passed loc, downhill from here on in.\n break;\n }\n }\n }\n }\n // No hope for a (better) match at greater error levels.\n if (match_bitapScore_(d + 1, loc) > score_threshold) {\n break;\n }\n last_rd = rd;\n }\n return best_loc;\n};\n\n\n/**\n * Initialise the alphabet for the Bitap algorithm.\n * @param {string} pattern The text to encode.\n * @return {!Object} Hash of character locations.\n * @private\n */\ndiff_match_patch.prototype.match_alphabet_ = function(pattern) {\n var s = {};\n for (var i = 0; i < pattern.length; i++) {\n s[pattern.charAt(i)] = 0;\n }\n for (var i = 0; i < pattern.length; i++) {\n s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1);\n }\n return s;\n};\n\n\n// PATCH FUNCTIONS\n\n\n/**\n * Increase the context until it is unique,\n * but don't let the pattern expand beyond Match_MaxBits.\n * @param {!diff_match_patch.patch_obj} patch The patch to grow.\n * @param {string} text Source text.\n * @private\n */\ndiff_match_patch.prototype.patch_addContext_ = function(patch, text) {\n if (text.length == 0) {\n return;\n }\n if (patch.start2 === null) {\n throw Error('patch not initialized');\n }\n var pattern = text.substring(patch.start2, patch.start2 + patch.length1);\n var padding = 0;\n\n // Look for the first and last matches of pattern in text. If two different\n // matches are found, increase the pattern length.\n while (text.indexOf(pattern) != text.lastIndexOf(pattern) &&\n pattern.length < this.Match_MaxBits - this.Patch_Margin -\n this.Patch_Margin) {\n padding += this.Patch_Margin;\n pattern = text.substring(patch.start2 - padding,\n patch.start2 + patch.length1 + padding);\n }\n // Add one chunk for good luck.\n padding += this.Patch_Margin;\n\n // Add the prefix.\n var prefix = text.substring(patch.start2 - padding, patch.start2);\n if (prefix) {\n patch.diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, prefix));\n }\n // Add the suffix.\n var suffix = text.substring(patch.start2 + patch.length1,\n patch.start2 + patch.length1 + padding);\n if (suffix) {\n patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, suffix));\n }\n\n // Roll back the start points.\n patch.start1 -= prefix.length;\n patch.start2 -= prefix.length;\n // Extend the lengths.\n patch.length1 += prefix.length + suffix.length;\n patch.length2 += prefix.length + suffix.length;\n};\n\n\n/**\n * Compute a list of patches to turn text1 into text2.\n * Use diffs if provided, otherwise compute it ourselves.\n * There are four ways to call this function, depending on what data is\n * available to the caller:\n * Method 1:\n * a = text1, b = text2\n * Method 2:\n * a = diffs\n * Method 3 (optimal):\n * a = text1, b = diffs\n * Method 4 (deprecated, use method 3):\n * a = text1, b = text2, c = diffs\n *\n * @param {string|!Array.<!diff_match_patch.Diff>} a text1 (methods 1,3,4) or\n * Array of diff tuples for text1 to text2 (method 2).\n * @param {string|!Array.<!diff_match_patch.Diff>=} opt_b text2 (methods 1,4) or\n * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).\n * @param {string|!Array.<!diff_match_patch.Diff>=} opt_c Array of diff tuples\n * for text1 to text2 (method 4) or undefined (methods 1,2,3).\n * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.\n */\ndiff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) {\n var text1, diffs;\n if (typeof a == 'string' && typeof opt_b == 'string' &&\n typeof opt_c == 'undefined') {\n // Method 1: text1, text2\n // Compute diffs from text1 and text2.\n text1 = /** @type {string} */(a);\n diffs = this.diff_main(text1, /** @type {string} */(opt_b), true);\n if (diffs.length > 2) {\n this.diff_cleanupSemantic(diffs);\n this.diff_cleanupEfficiency(diffs);\n }\n } else if (a && typeof a == 'object' && typeof opt_b == 'undefined' &&\n typeof opt_c == 'undefined') {\n // Method 2: diffs\n // Compute text1 from diffs.\n diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(a);\n text1 = this.diff_text1(diffs);\n } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' &&\n typeof opt_c == 'undefined') {\n // Method 3: text1, diffs\n text1 = /** @type {string} */(a);\n diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_b);\n } else if (typeof a == 'string' && typeof opt_b == 'string' &&\n opt_c && typeof opt_c == 'object') {\n // Method 4: text1, text2, diffs\n // text2 is not used.\n text1 = /** @type {string} */(a);\n diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_c);\n } else {\n throw new Error('Unknown call format to patch_make.');\n }\n\n if (diffs.length === 0) {\n return []; // Get rid of the null case.\n }\n var patches = [];\n var patch = new diff_match_patch.patch_obj();\n var patchDiffLength = 0; // Keeping our own length var is faster in JS.\n var char_count1 = 0; // Number of characters into the text1 string.\n var char_count2 = 0; // Number of characters into the text2 string.\n // Start with text1 (prepatch_text) and apply the diffs until we arrive at\n // text2 (postpatch_text). We recreate the patches one by one to determine\n // context info.\n var prepatch_text = text1;\n var postpatch_text = text1;\n for (var x = 0; x < diffs.length; x++) {\n var diff_type = diffs[x][0];\n var diff_text = diffs[x][1];\n\n if (!patchDiffLength && diff_type !== DIFF_EQUAL) {\n // A new patch starts here.\n patch.start1 = char_count1;\n patch.start2 = char_count2;\n }\n\n switch (diff_type) {\n case DIFF_INSERT:\n patch.diffs[patchDiffLength++] = diffs[x];\n patch.length2 += diff_text.length;\n postpatch_text = postpatch_text.substring(0, char_count2) + diff_text +\n postpatch_text.substring(char_count2);\n break;\n case DIFF_DELETE:\n patch.length1 += diff_text.length;\n patch.diffs[patchDiffLength++] = diffs[x];\n postpatch_text = postpatch_text.substring(0, char_count2) +\n postpatch_text.substring(char_count2 +\n diff_text.length);\n break;\n case DIFF_EQUAL:\n if (diff_text.length <= 2 * this.Patch_Margin &&\n patchDiffLength && diffs.length != x + 1) {\n // Small equality inside a patch.\n patch.diffs[patchDiffLength++] = diffs[x];\n patch.length1 += diff_text.length;\n patch.length2 += diff_text.length;\n } else if (diff_text.length >= 2 * this.Patch_Margin) {\n // Time for a new patch.\n if (patchDiffLength) {\n this.patch_addContext_(patch, prepatch_text);\n patches.push(patch);\n patch = new diff_match_patch.patch_obj();\n patchDiffLength = 0;\n // Unlike Unidiff, our patch lists have a rolling context.\n // https://github.com/google/diff-match-patch/wiki/Unidiff\n // Update prepatch text & pos to reflect the application of the\n // just completed patch.\n prepatch_text = postpatch_text;\n char_count1 = char_count2;\n }\n }\n break;\n }\n\n // Update the current character count.\n if (diff_type !== DIFF_INSERT) {\n char_count1 += diff_text.length;\n }\n if (diff_type !== DIFF_DELETE) {\n char_count2 += diff_text.length;\n }\n }\n // Pick up the leftover patch if not empty.\n if (patchDiffLength) {\n this.patch_addContext_(patch, prepatch_text);\n patches.push(patch);\n }\n\n return patches;\n};\n\n\n/**\n * Given an array of patches, return another array that is identical.\n * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.\n * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.\n */\ndiff_match_patch.prototype.patch_deepCopy = function(patches) {\n // Making deep copies is hard in JavaScript.\n var patchesCopy = [];\n for (var x = 0; x < patches.length; x++) {\n var patch = patches[x];\n var patchCopy = new diff_match_patch.patch_obj();\n patchCopy.diffs = [];\n for (var y = 0; y < patch.diffs.length; y++) {\n patchCopy.diffs[y] =\n new diff_match_patch.Diff(patch.diffs[y][0], patch.diffs[y][1]);\n }\n patchCopy.start1 = patch.start1;\n patchCopy.start2 = patch.start2;\n patchCopy.length1 = patch.length1;\n patchCopy.length2 = patch.length2;\n patchesCopy[x] = patchCopy;\n }\n return patchesCopy;\n};\n\n\n/**\n * Merge a set of patches onto the text. Return a patched text, as well\n * as a list of true/false values indicating which patches were applied.\n * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.\n * @param {string} text Old text.\n * @return {!Array.<string|!Array.<boolean>>} Two element Array, containing the\n * new text and an array of boolean values.\n */\ndiff_match_patch.prototype.patch_apply = function(patches, text) {\n if (patches.length == 0) {\n return [text, []];\n }\n\n // Deep copy the patches so that no changes are made to originals.\n patches = this.patch_deepCopy(patches);\n\n var nullPadding = this.patch_addPadding(patches);\n text = nullPadding + text + nullPadding;\n\n this.patch_splitMax(patches);\n // delta keeps track of the offset between the expected and actual location\n // of the previous patch. If there are patches expected at positions 10 and\n // 20, but the first patch was found at 12, delta is 2 and the second patch\n // has an effective expected position of 22.\n var delta = 0;\n var results = [];\n for (var x = 0; x < patches.length; x++) {\n var expected_loc = patches[x].start2 + delta;\n var text1 = this.diff_text1(patches[x].diffs);\n var start_loc;\n var end_loc = -1;\n if (text1.length > this.Match_MaxBits) {\n // patch_splitMax will only provide an oversized pattern in the case of\n // a monster delete.\n start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits),\n expected_loc);\n if (start_loc != -1) {\n end_loc = this.match_main(text,\n text1.substring(text1.length - this.Match_MaxBits),\n expected_loc + text1.length - this.Match_MaxBits);\n if (end_loc == -1 || start_loc >= end_loc) {\n // Can't find valid trailing context. Drop this patch.\n start_loc = -1;\n }\n }\n } else {\n start_loc = this.match_main(text, text1, expected_loc);\n }\n if (start_loc == -1) {\n // No match found. :(\n results[x] = false;\n // Subtract the delta for this failed patch from subsequent patches.\n delta -= patches[x].length2 - patches[x].length1;\n } else {\n // Found a match. :)\n results[x] = true;\n delta = start_loc - expected_loc;\n var text2;\n if (end_loc == -1) {\n text2 = text.substring(start_loc, start_loc + text1.length);\n } else {\n text2 = text.substring(start_loc, end_loc + this.Match_MaxBits);\n }\n if (text1 == text2) {\n // Perfect match, just shove the replacement text in.\n text = text.substring(0, start_loc) +\n this.diff_text2(patches[x].diffs) +\n text.substring(start_loc + text1.length);\n } else {\n // Imperfect match. Run a diff to get a framework of equivalent\n // indices.\n var diffs = this.diff_main(text1, text2, false);\n if (text1.length > this.Match_MaxBits &&\n this.diff_levenshtein(diffs) / text1.length >\n this.Patch_DeleteThreshold) {\n // The end points match, but the content is unacceptably bad.\n results[x] = false;\n } else {\n this.diff_cleanupSemanticLossless(diffs);\n var index1 = 0;\n var index2;\n for (var y = 0; y < patches[x].diffs.length; y++) {\n var mod = patches[x].diffs[y];\n if (mod[0] !== DIFF_EQUAL) {\n index2 = this.diff_xIndex(diffs, index1);\n }\n if (mod[0] === DIFF_INSERT) { // Insertion\n text = text.substring(0, start_loc + index2) + mod[1] +\n text.substring(start_loc + index2);\n } else if (mod[0] === DIFF_DELETE) { // Deletion\n text = text.substring(0, start_loc + index2) +\n text.substring(start_loc + this.diff_xIndex(diffs,\n index1 + mod[1].length));\n }\n if (mod[0] !== DIFF_DELETE) {\n index1 += mod[1].length;\n }\n }\n }\n }\n }\n }\n // Strip the padding off.\n text = text.substring(nullPadding.length, text.length - nullPadding.length);\n return [text, results];\n};\n\n\n/**\n * Add some padding on text start and end so that edges can match something.\n * Intended to be called only from within patch_apply.\n * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.\n * @return {string} The padding string added to each side.\n */\ndiff_match_patch.prototype.patch_addPadding = function(patches) {\n var paddingLength = this.Patch_Margin;\n var nullPadding = '';\n for (var x = 1; x <= paddingLength; x++) {\n nullPadding += String.fromCharCode(x);\n }\n\n // Bump all the patches forward.\n for (var x = 0; x < patches.length; x++) {\n patches[x].start1 += paddingLength;\n patches[x].start2 += paddingLength;\n }\n\n // Add some padding on start of first diff.\n var patch = patches[0];\n var diffs = patch.diffs;\n if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) {\n // Add nullPadding equality.\n diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding));\n patch.start1 -= paddingLength; // Should be 0.\n patch.start2 -= paddingLength; // Should be 0.\n patch.length1 += paddingLength;\n patch.length2 += paddingLength;\n } else if (paddingLength > diffs[0][1].length) {\n // Grow first equality.\n var extraLength = paddingLength - diffs[0][1].length;\n diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1];\n patch.start1 -= extraLength;\n patch.start2 -= extraLength;\n patch.length1 += extraLength;\n patch.length2 += extraLength;\n }\n\n // Add some padding on end of last diff.\n patch = patches[patches.length - 1];\n diffs = patch.diffs;\n if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) {\n // Add nullPadding equality.\n diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding));\n patch.length1 += paddingLength;\n patch.length2 += paddingLength;\n } else if (paddingLength > diffs[diffs.length - 1][1].length) {\n // Grow last equality.\n var extraLength = paddingLength - diffs[diffs.length - 1][1].length;\n diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength);\n patch.length1 += extraLength;\n patch.length2 += extraLength;\n }\n\n return nullPadding;\n};\n\n\n/**\n * Look through the patches and break up any which are longer than the maximum\n * limit of the match algorithm.\n * Intended to be called only from within patch_apply.\n * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.\n */\ndiff_match_patch.prototype.patch_splitMax = function(patches) {\n var patch_size = this.Match_MaxBits;\n for (var x = 0; x < patches.length; x++) {\n if (patches[x].length1 <= patch_size) {\n continue;\n }\n var bigpatch = patches[x];\n // Remove the big old patch.\n patches.splice(x--, 1);\n var start1 = bigpatch.start1;\n var start2 = bigpatch.start2;\n var precontext = '';\n while (bigpatch.diffs.length !== 0) {\n // Create one of several smaller patches.\n var patch = new diff_match_patch.patch_obj();\n var empty = true;\n patch.start1 = start1 - precontext.length;\n patch.start2 = start2 - precontext.length;\n if (precontext !== '') {\n patch.length1 = patch.length2 = precontext.length;\n patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, precontext));\n }\n while (bigpatch.diffs.length !== 0 &&\n patch.length1 < patch_size - this.Patch_Margin) {\n var diff_type = bigpatch.diffs[0][0];\n var diff_text = bigpatch.diffs[0][1];\n if (diff_type === DIFF_INSERT) {\n // Insertions are harmless.\n patch.length2 += diff_text.length;\n start2 += diff_text.length;\n patch.diffs.push(bigpatch.diffs.shift());\n empty = false;\n } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 &&\n patch.diffs[0][0] == DIFF_EQUAL &&\n diff_text.length > 2 * patch_size) {\n // This is a large deletion. Let it pass in one chunk.\n patch.length1 += diff_text.length;\n start1 += diff_text.length;\n empty = false;\n patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text));\n bigpatch.diffs.shift();\n } else {\n // Deletion or equality. Only take as much as we can stomach.\n diff_text = diff_text.substring(0,\n patch_size - patch.length1 - this.Patch_Margin);\n patch.length1 += diff_text.length;\n start1 += diff_text.length;\n if (diff_type === DIFF_EQUAL) {\n patch.length2 += diff_text.length;\n start2 += diff_text.length;\n } else {\n empty = false;\n }\n patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text));\n if (diff_text == bigpatch.diffs[0][1]) {\n bigpatch.diffs.shift();\n } else {\n bigpatch.diffs[0][1] =\n bigpatch.diffs[0][1].substring(diff_text.length);\n }\n }\n }\n // Compute the head context for the next patch.\n precontext = this.diff_text2(patch.diffs);\n precontext =\n precontext.substring(precontext.length - this.Patch_Margin);\n // Append the end context for this patch.\n var postcontext = this.diff_text1(bigpatch.diffs)\n .substring(0, this.Patch_Margin);\n if (postcontext !== '') {\n patch.length1 += postcontext.length;\n patch.length2 += postcontext.length;\n if (patch.diffs.length !== 0 &&\n patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) {\n patch.diffs[patch.diffs.length - 1][1] += postcontext;\n } else {\n patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, postcontext));\n }\n }\n if (!empty) {\n patches.splice(++x, 0, patch);\n }\n }\n }\n};\n\n\n/**\n * Take a list of patches and return a textual representation.\n * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.\n * @return {string} Text representation of patches.\n */\ndiff_match_patch.prototype.patch_toText = function(patches) {\n var text = [];\n for (var x = 0; x < patches.length; x++) {\n text[x] = patches[x];\n }\n return text.join('');\n};\n\n\n/**\n * Parse a textual representation of patches and return a list of Patch objects.\n * @param {string} textline Text representation of patches.\n * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.\n * @throws {!Error} If invalid input.\n */\ndiff_match_patch.prototype.patch_fromText = function(textline) {\n var patches = [];\n if (!textline) {\n return patches;\n }\n var text = textline.split('\\n');\n var textPointer = 0;\n var patchHeader = /^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$/;\n while (textPointer < text.length) {\n var m = text[textPointer].match(patchHeader);\n if (!m) {\n throw new Error('Invalid patch string: ' + text[textPointer]);\n }\n var patch = new diff_match_patch.patch_obj();\n patches.push(patch);\n patch.start1 = parseInt(m[1], 10);\n if (m[2] === '') {\n patch.start1--;\n patch.length1 = 1;\n } else if (m[2] == '0') {\n patch.length1 = 0;\n } else {\n patch.start1--;\n patch.length1 = parseInt(m[2], 10);\n }\n\n patch.start2 = parseInt(m[3], 10);\n if (m[4] === '') {\n patch.start2--;\n patch.length2 = 1;\n } else if (m[4] == '0') {\n patch.length2 = 0;\n } else {\n patch.start2--;\n patch.length2 = parseInt(m[4], 10);\n }\n textPointer++;\n\n while (textPointer < text.length) {\n var sign = text[textPointer].charAt(0);\n try {\n var line = decodeURI(text[textPointer].substring(1));\n } catch (ex) {\n // Malformed URI sequence.\n throw new Error('Illegal escape in patch_fromText: ' + line);\n }\n if (sign == '-') {\n // Deletion.\n patch.diffs.push(new diff_match_patch.Diff(DIFF_DELETE, line));\n } else if (sign == '+') {\n // Insertion.\n patch.diffs.push(new diff_match_patch.Diff(DIFF_INSERT, line));\n } else if (sign == ' ') {\n // Minor equality.\n patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, line));\n } else if (sign == '@') {\n // Start of next patch.\n break;\n } else if (sign === '') {\n // Blank line? Whatever.\n } else {\n // WTF?\n throw new Error('Invalid patch mode \"' + sign + '\" in: ' + line);\n }\n textPointer++;\n }\n }\n return patches;\n};\n\n\n/**\n * Class representing one patch operation.\n * @constructor\n */\ndiff_match_patch.patch_obj = function() {\n /** @type {!Array.<!diff_match_patch.Diff>} */\n this.diffs = [];\n /** @type {?number} */\n this.start1 = null;\n /** @type {?number} */\n this.start2 = null;\n /** @type {number} */\n this.length1 = 0;\n /** @type {number} */\n this.length2 = 0;\n};\n\n\n/**\n * Emulate GNU diff's format.\n * Header: @@ -382,8 +481,9 @@\n * Indices are printed as 1-based, not 0-based.\n * @return {string} The GNU diff string.\n */\ndiff_match_patch.patch_obj.prototype.toString = function() {\n var coords1, coords2;\n if (this.length1 === 0) {\n coords1 = this.start1 + ',0';\n } else if (this.length1 == 1) {\n coords1 = this.start1 + 1;\n } else {\n coords1 = (this.start1 + 1) + ',' + this.length1;\n }\n if (this.length2 === 0) {\n coords2 = this.start2 + ',0';\n } else if (this.length2 == 1) {\n coords2 = this.start2 + 1;\n } else {\n coords2 = (this.start2 + 1) + ',' + this.length2;\n }\n var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\\n'];\n var op;\n // Escape the body of the patch with %xx notation.\n for (var x = 0; x < this.diffs.length; x++) {\n switch (this.diffs[x][0]) {\n case DIFF_INSERT:\n op = '+';\n break;\n case DIFF_DELETE:\n op = '-';\n break;\n case DIFF_EQUAL:\n op = ' ';\n break;\n }\n text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\\n';\n }\n return text.join('').replace(/%20/g, ' ');\n};\n\n\n// The following export code was added by @ForbesLindesay\nmodule.exports = diff_match_patch;\nmodule.exports['diff_match_patch'] = diff_match_patch;\nmodule.exports['DIFF_DELETE'] = DIFF_DELETE;\nmodule.exports['DIFF_INSERT'] = DIFF_INSERT;\nmodule.exports['DIFF_EQUAL'] = DIFF_EQUAL;","import dmp from 'diff-match-patch';\nimport chalk from 'chalk';\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) {\n return typeof obj;\n} : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n};\n\n\n\n\n\n\n\n\n\n\n\nvar classCallCheck = function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n};\n\nvar createClass = function () {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n}();\n\n\n\n\n\n\n\nvar get = function get(object, property, receiver) {\n if (object === null) object = Function.prototype;\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent === null) {\n return undefined;\n } else {\n return get(parent, property, receiver);\n }\n } else if (\"value\" in desc) {\n return desc.value;\n } else {\n var getter = desc.get;\n\n if (getter === undefined) {\n return undefined;\n }\n\n return getter.call(receiver);\n }\n};\n\nvar inherits = function (subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n};\n\n\n\n\n\n\n\n\n\n\n\nvar possibleConstructorReturn = function (self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n};\n\n\n\n\n\nvar slicedToArray = function () {\n function sliceIterator(arr, i) {\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"]) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n }\n\n return function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n return sliceIterator(arr, i);\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n };\n}();\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar toConsumableArray = function (arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n\n return arr2;\n } else {\n return Array.from(arr);\n }\n};\n\nvar Processor = function () {\n function Processor(options) {\n classCallCheck(this, Processor);\n\n this.selfOptions = options || {};\n this.pipes = {};\n }\n\n createClass(Processor, [{\n key: 'options',\n value: function options(_options) {\n if (_options) {\n this.selfOptions = _options;\n }\n return this.selfOptions;\n }\n }, {\n key: 'pipe',\n value: function pipe(name, pipeArg) {\n var pipe = pipeArg;\n if (typeof name === 'string') {\n if (typeof pipe === 'undefined') {\n return this.pipes[name];\n } else {\n this.pipes[name] = pipe;\n }\n }\n if (name && name.name) {\n pipe = name;\n if (pipe.processor === this) {\n return pipe;\n }\n this.pipes[pipe.name] = pipe;\n }\n pipe.processor = this;\n return pipe;\n }\n }, {\n key: 'process',\n value: function process(input, pipe) {\n var context = input;\n context.options = this.options();\n var nextPipe = pipe || input.pipe || 'default';\n var lastPipe = void 0;\n var lastContext = void 0;\n while (nextPipe) {\n if (typeof context.nextAfterChildren !== 'undefined') {\n // children processed and coming back to parent\n context.next = context.nextAfterChildren;\n context.nextAfterChildren = null;\n }\n\n if (typeof nextPipe === 'string') {\n nextPipe = this.pipe(nextPipe);\n }\n nextPipe.process(context);\n lastContext = context;\n lastPipe = nextPipe;\n nextPipe = null;\n if (context) {\n if (context.next) {\n context = context.next;\n nextPipe = lastContext.nextPipe || context.pipe || lastPipe;\n }\n }\n }\n return context.hasResult ? context.result : undefined;\n }\n }]);\n return Processor;\n}();\n\nvar Pipe = function () {\n function Pipe(name) {\n classCallCheck(this, Pipe);\n\n this.name = name;\n this.filters = [];\n }\n\n createClass(Pipe, [{\n key: 'process',\n value: function process(input) {\n if (!this.processor) {\n throw new Error('add this pipe to a processor before using it');\n }\n var debug = this.debug;\n var length = this.filters.length;\n var context = input;\n for (var index = 0; index < length; index++) {\n var filter = this.filters[index];\n if (debug) {\n this.log('filter: ' + filter.filterName);\n }\n filter(context);\n if ((typeof context === 'undefined' ? 'undefined' : _typeof(context)) === 'object' && context.exiting) {\n context.exiting = false;\n break;\n }\n }\n if (!context.next && this.resultCheck) {\n this.resultCheck(context);\n }\n }\n }, {\n key: 'log',\n value: function log(msg) {\n console.log('[jsondiffpatch] ' + this.name + ' pipe, ' + msg);\n }\n }, {\n key: 'append',\n value: function append() {\n var _filters;\n\n (_filters = this.filters).push.apply(_filters, arguments);\n return this;\n }\n }, {\n key: 'prepend',\n value: function prepend() {\n var _filters2;\n\n (_filters2 = this.filters).unshift.apply(_filters2, arguments);\n return this;\n }\n }, {\n key: 'indexOf',\n value: function indexOf(filterName) {\n if (!filterName) {\n throw new Error('a filter name is required');\n }\n for (var index = 0; index < this.filters.length; index++) {\n var filter = this.filters[index];\n if (filter.filterName === filterName) {\n return index;\n }\n }\n throw new Error('filter not found: ' + filterName);\n }\n }, {\n key: 'list',\n value: function list() {\n return this.filters.map(function (f) {\n return f.filterName;\n });\n }\n }, {\n key: 'after',\n value: function after(filterName) {\n var index = this.indexOf(filterName);\n var params = Array.prototype.slice.call(arguments, 1);\n if (!params.length) {\n throw new Error('a filter is required');\n }\n params.unshift(index + 1, 0);\n Array.prototype.splice.apply(this.filters, params);\n return this;\n }\n }, {\n key: 'before',\n value: function before(filterName) {\n var index = this.indexOf(filterName);\n var params = Array.prototype.slice.call(arguments, 1);\n if (!params.length) {\n throw new Error('a filter is required');\n }\n params.unshift(index, 0);\n Array.prototype.splice.apply(this.filters, params);\n return this;\n }\n }, {\n key: 'replace',\n value: function replace(filterName) {\n var index = this.indexOf(filterName);\n var params = Array.prototype.slice.call(arguments, 1);\n if (!params.length) {\n throw new Error('a filter is required');\n }\n params.unshift(index, 1);\n Array.prototype.splice.apply(this.filters, params);\n return this;\n }\n }, {\n key: 'remove',\n value: function remove(filterName) {\n var index = this.indexOf(filterName);\n this.filters.splice(index, 1);\n return this;\n }\n }, {\n key: 'clear',\n value: function clear() {\n this.filters.length = 0;\n return this;\n }\n }, {\n key: 'shouldHaveResult',\n value: function shouldHaveResult(should) {\n if (should === false) {\n this.resultCheck = null;\n return;\n }\n if (this.resultCheck) {\n return;\n }\n var pipe = this;\n this.resultCheck = function (context) {\n if (!context.hasResult) {\n console.log(context);\n var error = new Error(pipe.name + ' failed');\n error.noResult = true;\n throw error;\n }\n };\n return this;\n }\n }]);\n return Pipe;\n}();\n\nvar Context = function () {\n function Context() {\n classCallCheck(this, Context);\n }\n\n createClass(Context, [{\n key: 'setResult',\n value: function setResult(result) {\n this.result = result;\n this.hasResult = true;\n return this;\n }\n }, {\n key: 'exit',\n value: function exit() {\n this.exiting = true;\n return this;\n }\n }, {\n key: 'switchTo',\n value: function switchTo(next, pipe) {\n if (typeof next === 'string' || next instanceof Pipe) {\n this.nextPipe = next;\n } else {\n this.next = next;\n if (pipe) {\n this.nextPipe = pipe;\n }\n }\n return this;\n }\n }, {\n key: 'push',\n value: function push(child, name) {\n child.parent = this;\n if (typeof name !== 'undefined') {\n child.childName = name;\n }\n child.root = this.root || this;\n child.options = child.options || this.options;\n if (!this.children) {\n this.children = [child];\n this.nextAfterChildren = this.next || null;\n this.next = child;\n } else {\n this.children[this.children.length - 1].next = child;\n this.children.push(child);\n }\n child.next = this;\n return this;\n }\n }]);\n return Context;\n}();\n\nvar isArray = typeof Array.isArray === 'function' ? Array.isArray : function (a) {\n return a instanceof Array;\n};\n\nfunction cloneRegExp(re) {\n var regexMatch = /^\\/(.*)\\/([gimyu]*)$/.exec(re.toString());\n return new RegExp(regexMatch[1], regexMatch[2]);\n}\n\nfunction clone(arg) {\n if ((typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) !== 'object') {\n return arg;\n }\n if (arg === null) {\n return null;\n }\n if (isArray(arg)) {\n return arg.map(clone);\n }\n if (arg instanceof Date) {\n return new Date(arg.getTime());\n }\n if (arg instanceof RegExp) {\n return cloneRegExp(arg);\n }\n var cloned = {};\n for (var name in arg) {\n if (Object.prototype.hasOwnProperty.call(arg, name)) {\n cloned[name] = clone(arg[name]);\n }\n }\n return cloned;\n}\n\nvar DiffContext = function (_Context) {\n inherits(DiffContext, _Context);\n\n function DiffContext(left, right) {\n classCallCheck(this, DiffContext);\n\n var _this = possibleConstructorReturn(this, (DiffContext.__proto__ || Object.getPrototypeOf(DiffContext)).call(this));\n\n _this.left = left;\n _this.right = right;\n _this.pipe = 'diff';\n return _this;\n }\n\n createClass(DiffContext, [{\n key: 'setResult',\n value: function setResult(result) {\n if (this.options.cloneDiffValues && (typeof result === 'undefined' ? 'undefined' : _typeof(result)) === 'object') {\n var clone$$1 = typeof this.options.cloneDiffValues === 'function' ? this.options.cloneDiffValues : clone;\n if (_typeof(result[0]) === 'object') {\n result[0] = clone$$1(result[0]);\n }\n if (_typeof(result[1]) === 'object') {\n result[1] = clone$$1(result[1]);\n }\n }\n return Context.prototype.setResult.apply(this, arguments);\n }\n }]);\n return DiffContext;\n}(Context);\n\nvar PatchContext = function (_Context) {\n inherits(PatchContext, _Context);\n\n function PatchContext(left, delta) {\n classCallCheck(this, PatchContext);\n\n var _this = possibleConstructorReturn(this, (PatchContext.__proto__ || Object.getPrototypeOf(PatchContext)).call(this));\n\n _this.left = left;\n _this.delta = delta;\n _this.pipe = 'patch';\n return _this;\n }\n\n return PatchContext;\n}(Context);\n\nvar ReverseContext = function (_Context) {\n inherits(ReverseContext, _Context);\n\n function ReverseContext(delta) {\n classCallCheck(this, ReverseContext);\n\n var _this = possibleConstructorReturn(this, (ReverseContext.__proto__ || Object.getPrototypeOf(ReverseContext)).call(this));\n\n _this.delta = delta;\n _this.pipe = 'reverse';\n return _this;\n }\n\n return ReverseContext;\n}(Context);\n\nvar isArray$1 = typeof Array.isArray === 'function' ? Array.isArray : function (a) {\n return a instanceof Array;\n};\n\nvar diffFilter = function trivialMatchesDiffFilter(context) {\n if (context.left === context.right) {\n context.setResult(undefined).exit();\n return;\n }\n if (typeof context.left === 'undefined') {\n if (typeof context.right === 'function') {\n throw new Error('functions are not supported');\n }\n context.setResult([context.right]).exit();\n return;\n }\n if (typeof context.right === 'undefined') {\n context.setResult([context.left, 0, 0]).exit();\n return;\n }\n if (typeof context.left === 'function' || typeof context.right === 'function') {\n throw new Error('functions are not supported');\n }\n context.leftType = context.left === null ? 'null' : _typeof(context.left);\n context.rightType = context.right === null ? 'null' : _typeof(context.right);\n if (context.leftType !== context.rightType) {\n context.setResult([context.left, context.right]).exit();\n return;\n }\n if (context.leftType === 'boolean' || context.leftType === 'number') {\n context.setResult([context.left, context.right]).exit();\n return;\n }\n if (context.leftType === 'object') {\n context.leftIsArray = isArray$1(context.left);\n }\n if (context.rightType === 'object') {\n context.rightIsArray = isArray$1(context.right);\n }\n if (context.leftIsArray !== context.rightIsArray) {\n context.setResult([context.left, context.right]).exit();\n return;\n }\n\n if (context.left instanceof RegExp) {\n if (context.right instanceof RegExp) {\n context.setResult([context.left.toString(), context.right.toString()]).exit();\n } else {\n context.setResult([context.left, context.right]).exit();\n }\n }\n};\ndiffFilter.filterName = 'trivial';\n\nvar patchFilter = function trivialMatchesPatchFilter(context) {\n if (typeof context.delta === 'undefined') {\n context.setResult(context.left).exit();\n return;\n }\n context.nested = !isArray$1(context.delta);\n if (context.nested) {\n return;\n }\n if (context.delta.length === 1) {\n context.setResult(context.delta[0]).exit();\n return;\n }\n if (context.delta.length === 2) {\n if (context.left instanceof RegExp) {\n var regexArgs = /^\\/(.*)\\/([gimyu]+)$/.exec(context.delta[1]);\n if (regexArgs) {\n context.setResult(new RegExp(regexArgs[1], regexArgs[2])).exit();\n return;\n }\n }\n context.setResult(context.delta[1]).exit();\n return;\n }\n if (context.delta.length === 3 && context.delta[2] === 0) {\n context.setResult(undefined).exit();\n }\n};\npatchFilter.filterName = 'trivial';\n\nvar reverseFilter = function trivialReferseFilter(context) {\n if (typeof context.delta === 'undefined') {\n context.setResult(context.delta).exit();\n return;\n }\n context.nested = !isArray$1(context.delta);\n if (context.nested) {\n return;\n }\n if (context.delta.length === 1) {\n context.setResult([context.delta[0], 0, 0]).exit();\n return;\n }\n if (context.delta.length === 2) {\n context.setResult([context.delta[1], context.delta[0]]).exit();\n return;\n }\n if (context.delta.length === 3 && context.delta[2] === 0) {\n context.setResult([context.delta[0]]).exit();\n }\n};\nreverseFilter.filterName = 'trivial';\n\nfunction collectChildrenDiffFilter(context) {\n if (!context || !context.children) {\n return;\n }\n var length = context.children.length;\n var child = void 0;\n var result = context.result;\n for (var index = 0; index < length; index++) {\n child = context.children[index];\n if (typeof child.result === 'undefined') {\n continue;\n }\n result = result || {};\n result[child.childName] = child.result;\n }\n if (result && context.leftIsArray) {\n result._t = 'a';\n }\n context.setResult(result).exit();\n}\ncollectChildrenDiffFilter.filterName = 'collectChildren';\n\nfunction objectsDiffFilter(context) {\n if (context.leftIsArray || context.leftType !== 'object') {\n return;\n }\n\n var name = void 0;\n var child = void 0;\n var propertyFilter = context.options.propertyFilter;\n for (name in context.left) {\n if (!Object.prototype.hasOwnProperty.call(context.left, name)) {\n continue;\n }\n if (propertyFilter && !propertyFilter(name, context)) {\n continue;\n }\n child = new DiffContext(context.left[name], context.right[name]);\n context.push(child, name);\n }\n for (name in context.right) {\n if (!Object.prototype.hasOwnProperty.call(context.right, name)) {\n continue;\n }\n if (propertyFilter && !propertyFilter(name, context)) {\n continue;\n }\n if (typeof context.left[name] === 'undefined') {\n child = new DiffContext(undefined, context.right[name]);\n context.push(child, name);\n }\n }\n\n if (!context.children || context.children.length === 0) {\n context.setResult(undefined).exit();\n return;\n }\n context.exit();\n}\nobjectsDiffFilter.filterName = 'objects';\n\nvar patchFilter$1 = function nestedPatchFilter(context) {\n if (!context.nested) {\n return;\n }\n if (context.delta._t) {\n return;\n }\n var name = void 0;\n var child = void 0;\n for (name in context.delta) {\n child = new PatchContext(context.left[name], context.delta[name]);\n context.push(child, name);\n }\n context.exit();\n};\npatchFilter$1.filterName = 'objects';\n\nvar collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {\n if (!context || !context.children) {\n return;\n }\n if (context.delta._t) {\n return;\n }\n var length = context.children.length;\n var child = void 0;\n for (var index = 0; index < length; index++) {\n child = context.children[index];\n if (Object.prototype.hasOwnProperty.call(context.left, child.childName) && child.result === undefined) {\n delete context.left[child.childName];\n } else if (context.left[child.childName] !== child.result) {\n context.left[child.childName] = child.result;\n }\n }\n context.setResult(context.left).exit();\n};\ncollectChildrenPatchFilter.filterName = 'collectChildren';\n\nvar reverseFilter$1 = function nestedReverseFilter(context) {\n if (!context.nested) {\n return;\n }\n if (context.delta._t) {\n return;\n }\n var name = void 0;\n var child = void 0;\n for (name in context.delta) {\n child = new ReverseContext(context.delta[name]);\n context.push(child, name);\n }\n context.exit();\n};\nreverseFilter$1.filterName = 'objects';\n\nfunction collectChildrenReverseFilter(context) {\n if (!context || !context.children) {\n return;\n }\n if (context.delta._t) {\n return;\n }\n var length = context.children.length;\n var child = void 0;\n var delta = {};\n for (var index = 0; index < length; index++) {\n child = context.children[index];\n if (delta[child.childName] !== child.result) {\n delta[child.childName] = child.result;\n }\n }\n context.setResult(delta).exit();\n}\ncollectChildrenReverseFilter.filterName = 'collectChildren';\n\n/*\n\nLCS implementation that supports arrays or strings\n\nreference: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem\n\n*/\n\nvar defaultMatch = function defaultMatch(array1, array2, index1, index2) {\n return array1[index1] === array2[index2];\n};\n\nvar lengthMatrix = function lengthMatrix(array1, array2, match, context) {\n var len1 = array1.length;\n var len2 = array2.length;\n var x = void 0,\n y = void 0;\n\n // initialize empty matrix of len1+1 x len2+1\n var matrix = [len1 + 1];\n for (x = 0; x < len1 + 1; x++) {\n matrix[x] = [len2 + 1];\n for (y = 0; y < len2 + 1; y++) {\n matrix[x][y] = 0;\n }\n }\n matrix.match = match;\n // save sequence lengths for each coordinate\n for (x = 1; x < len1 + 1; x++) {\n for (y = 1; y < len2 + 1; y++) {\n if (match(array1, array2, x - 1, y - 1, context)) {\n matrix[x][y] = matrix[x - 1][y - 1] + 1;\n } else {\n matrix[x][y] = Math.max(matrix[x - 1][y], matrix[x][y - 1]);\n }\n }\n }\n return matrix;\n};\n\nvar backtrack = function backtrack(matrix, array1, array2, context) {\n var index1 = array1.length;\n var index2 = array2.length;\n var subsequence = {\n sequence: [],\n indices1: [],\n indices2: []\n };\n\n while (index1 !== 0 && index2 !== 0) {\n var sameLetter = matrix.match(array1, array2, index1 - 1, index2 - 1, context);\n if (sameLetter) {\n subsequence.sequence.unshift(array1[index1 - 1]);\n subsequence.indices1.unshift(index1 - 1);\n subsequence.indices2.unshift(index2 - 1);\n --index1;\n --index2;\n } else {\n var valueAtMatrixAbove = matrix[index1][index2 - 1];\n var valueAtMatrixLeft = matrix[index1 - 1][index2];\n if (valueAtMatrixAbove > valueAtMatrixLeft) {\n --index2;\n } else {\n --index1;\n }\n }\n }\n return subsequence;\n};\n\nvar get$1 = function get(array1, array2, match, context) {\n var innerContext = context || {};\n var matrix = lengthMatrix(array1, array2, match || defaultMatch, innerContext);\n var result = backtrack(matrix, array1, array2, innerContext);\n if (typeof array1 === 'string' && typeof array2 === 'string') {\n result.sequence = result.sequence.join('');\n }\n return result;\n};\n\nvar lcs = {\n get: get$1\n};\n\nvar ARRAY_MOVE = 3;\n\nvar isArray$2 = typeof Array.isArray === 'function' ? Array.isArray : function (a) {\n return a instanceof Array;\n};\n\nvar arrayIndexOf = typeof Array.prototype.indexOf === 'function' ? function (array, item) {\n return array.indexOf(item);\n} : function (array, item) {\n var length = array.length;\n for (var i = 0; i < length; i++) {\n if (array[i] === item) {\n return i;\n }\n }\n return -1;\n};\n\nfunction arraysHaveMatchByRef(array1, array2, len1, len2) {\n for (var index1 = 0; index1 < len1; index1++) {\n var val1 = array1[index1];\n for (var index2 = 0; index2 < len2; index2++) {\n var val2 = array2[index2];\n if (index1 !== index2 && val1 === val2) {\n return true;\n }\n }\n }\n}\n\nfunction matchItems(array1, array2, index1, index2, context) {\n var value1 = array1[index1];\n var value2 = array2[index2];\n if (value1 === value2) {\n return true;\n }\n if ((typeof value1 === 'undefined' ? 'undefined' : _typeof(value1)) !== 'object' || (typeof value2 === 'undefined' ? 'undefined' : _typeof(value2)) !== 'object') {\n return false;\n }\n var objectHash = context.objectHash;\n if (!objectHash) {\n // no way to match objects was provided, try match by position\n return context.matchByPosition && index1 === index2;\n }\n var hash1 = void 0;\n var hash2 = void 0;\n if (typeof index1 === 'number') {\n context.hashCache1 = context.hashCache1 || [];\n hash1 = context.hashCache1[index1];\n if (typeof hash1 === 'undefined') {\n context.hashCache1[index1] = hash1 = objectHash(value1, index1);\n }\n } else {\n hash1 = objectHash(value1);\n }\n if (typeof hash1 === 'undefined') {\n return false;\n }\n if (typeof index2 === 'number') {\n context.hashCache2 = context.hashCache2 || [];\n hash2 = context.hashCache2[index2];\n if (typeof hash2 === 'undefined') {\n context.hashCache2[index2] = hash2 = objectHash(value2, index2);\n }\n } else {\n hash2 = objectHash(value2);\n }\n if (typeof hash2 === 'undefined') {\n return false;\n }\n return hash1 === hash2;\n}\n\nvar diffFilter$1 = function arraysDiffFilter(context) {\n if (!context.leftIsArray) {\n return;\n }\n\n var matchContext = {\n objectHash: context.options && context.options.objectHash,\n matchByPosition: context.options && context.options.matchByPosition\n };\n var commonHead = 0;\n var commonTail = 0;\n var index = void 0;\n var index1 = void 0;\n var index2 = void 0;\n var array1 = context.left;\n var array2 = context.right;\n var len1 = array1.length;\n var len2 = array2.length;\n\n var child = void 0;\n\n if (len1 > 0 && len2 > 0 && !matchContext.objectHash && typeof matchContext.matchByPosition !== 'boolean') {\n matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2);\n }\n\n // separate common head\n while (commonHead < len1 && commonHead < len2 && matchItems(array1, array2, commonHead, commonHead, matchContext)) {\n index = commonHead;\n child = new DiffContext(context.left[index], context.right[index]);\n context.push(child, index);\n commonHead++;\n }\n // separate common tail\n while (commonTail + commonHead < len1 && commonTail + commonHead < len2 && matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {\n index1 = len1 - 1 - commonTail;\n index2 = len2 - 1 - commonTail;\n child = new DiffContext(context.left[index1], context.right[index2]);\n context.push(child, index2);\n commonTail++;\n }\n var result = void 0;\n if (commonHead + commonTail === len1) {\n if (len1 === len2) {\n // arrays are identical\n context.setResult(undefined).exit();\n return;\n }\n // trivial case, a block (1 or more consecutive items) was added\n result = result || {\n _t: 'a'\n };\n for (index = commonHead; index < len2 - commonTail; index++) {\n result[index] = [array2[index]];\n }\n context.setResult(result).exit();\n return;\n }\n if (commonHead + commonTail === len2) {\n // trivial case, a block (1 or more consecutive items) was removed\n result = result || {\n _t: 'a'\n };\n for (index = commonHead; index < len1 - commonTail; index++) {\n result['_' + index] = [array1[index], 0, 0];\n }\n context.setResult(result).exit();\n return;\n }\n // reset hash cache\n delete matchContext.hashCache1;\n delete matchContext.hashCache2;\n\n // diff is not trivial, find the LCS (Longest Common Subsequence)\n var trimmed1 = array1.slice(commonHead, len1 - commonTail);\n var trimmed2 = array2.slice(commonHead, len2 - commonTail);\n var seq = lcs.get(trimmed1, trimmed2, matchItems, matchContext);\n var removedItems = [];\n result = result || {\n _t: 'a'\n };\n for (index = commonHead; index < len1 - commonTail; index++) {\n if (arrayIndexOf(seq.indices1, index - commonHead) < 0) {\n // removed\n result['_' + index] = [array1[index], 0, 0];\n removedItems.push(index);\n }\n }\n\n var detectMove = true;\n if (context.options && context.options.arrays && context.options.arrays.detectMove === false) {\n detectMove = false;\n }\n var includeValueOnMove = false;\n if (context.options && context.options.arrays && context.options.arrays.includeValueOnMove) {\n includeValueOnMove = true;\n }\n\n var removedItemsLength = removedItems.length;\n for (index = commonHead; index < len2 - commonTail; index++) {\n var indexOnArray2 = arrayIndexOf(seq.indices2, index - commonHead);\n if (indexOnArray2 < 0) {\n // added, try to match with a removed item and register as position move\n var isMove = false;\n if (detectMove && removedItemsLength > 0) {\n for (var removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {\n index1 = removedItems[removeItemIndex1];\n if (matchItems(trimmed1, trimmed2, index1 - commonHead, index - commonHead, matchContext)) {\n // store position move as: [originalValue, newPosition, ARRAY_MOVE]\n result['_' + index1].splice(1, 2, index, ARRAY_MOVE);\n if (!includeValueOnMove) {\n // don't include moved value on diff, to save bytes\n result['_' + index1][0] = '';\n }\n\n index2 = index;\n child = new DiffContext(context.left[index1], context.right[index2]);\n context.push(child, index2);\n removedItems.splice(removeItemIndex1, 1);\n isMove = true;\n break;\n }\n }\n }\n if (!isMove) {\n // added\n result[index] = [array2[index]];\n }\n } else {\n // match, do inner diff\n index1 = seq.indices1[indexOnArray2] + commonHead;\n index2 = seq.indices2[indexOnArray2] + commonHead;\n child = new DiffContext(context.left[index1], context.right[index2]);\n context.push(child, index2);\n }\n }\n\n context.setResult(result).exit();\n};\ndiffFilter$1.filterName = 'arrays';\n\nvar compare = {\n numerically: function numerically(a, b) {\n return a - b;\n },\n numericallyBy: function numericallyBy(name) {\n return function (a, b) {\n return a[name] - b[name];\n };\n }\n};\n\nvar patchFilter$2 = function nestedPatchFilter(context) {\n if (!context.nested) {\n return;\n }\n if (context.delta._t !== 'a') {\n return;\n }\n var index = void 0;\n var index1 = void 0;\n\n var delta = context.delta;\n var array = context.left;\n\n // first, separate removals, insertions and modifications\n var toRemove = [];\n var toInsert = [];\n var toModify = [];\n for (index in delta) {\n if (index !== '_t') {\n if (index[0] === '_') {\n // removed item from original array\n if (delta[index][2] === 0 || delta[index][2] === ARRAY_MOVE) {\n toRemove.push(parseInt(index.slice(1), 10));\n } else {\n throw new Error('only removal or move can be applied at original array indices,' + (' invalid diff type: ' + delta[index][2]));\n }\n } else {\n if (delta[index].length === 1) {\n // added item at new array\n toInsert.push({\n index: parseInt(index, 10),\n value: delta[index][0]\n });\n } else {\n // modified item at new array\n toModify.push({\n index: parseInt(index, 10),\n delta: delta[index]\n });\n }\n }\n }\n }\n\n // remove items, in reverse order to avoid sawing our own floor\n toRemove = toRemove.sort(compare.numerically);\n for (index = toRemove.length - 1; index >= 0; index--) {\n index1 = toRemove[index];\n var indexDiff = delta['_' + index1];\n var removedValue = array.splice(index1, 1)[0];\n if (indexDiff[2] === ARRAY_MOVE) {\n // reinsert later\n toInsert.push({\n index: indexDiff[1],\n value: removedValue\n });\n }\n }\n\n // insert items, in reverse order to avoid moving our own floor\n toInsert = toInsert.sort(compare.numericallyBy('index'));\n var toInsertLength = toInsert.length;\n for (index = 0; index < toInsertLength; index++) {\n var insertion = toInsert[index];\n array.splice(insertion.index, 0, insertion.value);\n }\n\n // apply modifications\n var toModifyLength = toModify.length;\n var child = void 0;\n if (toModifyLength > 0) {\n for (index = 0; index < toModifyLength; index++) {\n var modification = toModify[index];\n child = new PatchContext(context.left[modification.index], modification.delta);\n context.push(child, modification.index);\n }\n }\n\n if (!context.children) {\n context.setResult(context.left).exit();\n return;\n }\n context.exit();\n};\npatchFilter$2.filterName = 'arrays';\n\nvar collectChildrenPatchFilter$1 = function collectChildrenPatchFilter(context) {\n if (!context || !context.children) {\n return;\n }\n if (context.delta._t !== 'a') {\n return;\n }\n var length = context.children.length;\n var child = void 0;\n for (var index = 0; index < length; index++) {\n child = context.children[index];\n context.left[child.childName] = child.result;\n }\n context.setResult(context.left).exit();\n};\ncollectChildrenPatchFilter$1.filterName = 'arraysCollectChildren';\n\nvar reverseFilter$2 = function arraysReverseFilter(context) {\n if (!context.nested) {\n if (context.delta[2] === ARRAY_MOVE) {\n context.newName = '_' + context.delta[1];\n context.setResult([context.delta[0], parseInt(context.childName.substr(1), 10), ARRAY_MOVE]).exit();\n }\n return;\n }\n if (context.delta._t !== 'a') {\n return;\n }\n var name = void 0;\n var child = void 0;\n for (name in context.delta) {\n if (name === '_t') {\n continue;\n }\n child = new ReverseContext(context.delta[name]);\n context.push(child, name);\n }\n context.exit();\n};\nreverseFilter$2.filterName = 'arrays';\n\nvar reverseArrayDeltaIndex = function reverseArrayDeltaIndex(delta, index, itemDelta) {\n if (typeof index === 'string' && index[0] === '_') {\n return parseInt(index.substr(1), 10);\n } else if (isArray$2(itemDelta) && itemDelta[2] === 0) {\n return '_' + index;\n }\n\n var reverseIndex = +index;\n for (var deltaIndex in delta) {\n var deltaItem = delta[deltaIndex];\n if (isArray$2(deltaItem)) {\n if (deltaItem[2] === ARRAY_MOVE) {\n var moveFromIndex = parseInt(deltaIndex.substr(1), 10);\n var moveToIndex = deltaItem[1];\n if (moveToIndex === +index) {\n return moveFromIndex;\n }\n if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) {\n reverseIndex++;\n } else if (moveFromIndex >= reverseIndex && moveToIndex < reverseIndex) {\n reverseIndex--;\n }\n } else if (deltaItem[2] === 0) {\n var deleteIndex = parseInt(deltaIndex.substr(1), 10);\n if (deleteIndex <= reverseIndex) {\n reverseIndex++;\n }\n } else if (deltaItem.length === 1 && deltaIndex <= reverseIndex) {\n reverseIndex--;\n }\n }\n }\n\n return reverseIndex;\n};\n\nfunction collectChildrenReverseFilter$1(context) {\n if (!context || !context.children) {\n return;\n }\n if (context.delta._t !== 'a') {\n return;\n }\n var length = context.children.length;\n var child = void 0;\n var delta = {\n _t: 'a'\n };\n\n for (var index = 0; index < length; index++) {\n child = context.children[index];\n var name = child.newName;\n if (typeof name === 'undefined') {\n name = reverseArrayDeltaIndex(context.delta, child.childName, child.result);\n }\n if (delta[name] !== child.result) {\n delta[name] = child.result;\n }\n }\n context.setResult(delta).exit();\n}\ncollectChildrenReverseFilter$1.filterName = 'arraysCollectChildren';\n\nvar diffFilter$2 = function datesDiffFilter(context) {\n if (context.left instanceof Date) {\n if (context.right instanceof Date) {\n if (context.left.getTime() !== context.right.getTime()) {\n context.setResult([context.left, context.right]);\n } else {\n context.setResult(undefined);\n }\n } else {\n context.setResult([context.left, context.right]);\n }\n context.exit();\n } else if (context.right instanceof Date) {\n context.setResult([context.left, context.right]).exit();\n }\n};\ndiffFilter$2.filterName = 'dates';\n\n/* global diff_match_patch */\nvar TEXT_DIFF = 2;\nvar DEFAULT_MIN_LENGTH = 60;\nvar cachedDiffPatch = null;\n\nvar getDiffMatchPatch = function getDiffMatchPatch(required) {\n /* jshint camelcase: false */\n\n if (!cachedDiffPatch) {\n var instance = void 0;\n /* eslint-disable camelcase, new-cap */\n if (typeof diff_match_patch !== 'undefined') {\n // already loaded, probably a browser\n instance = typeof diff_match_patch === 'function' ? new diff_match_patch() : new diff_match_patch.diff_match_patch();\n } else if (dmp) {\n try {\n instance = dmp && new dmp();\n } catch (err) {\n instance = null;\n }\n }\n /* eslint-enable camelcase, new-cap */\n if (!instance) {\n if (!required) {\n return null;\n }\n var error = new Error('text diff_match_patch library not found');\n // eslint-disable-next-line camelcase\n error.diff_match_patch_not_found = true;\n throw error;\n }\n cachedDiffPatch = {\n diff: function diff(txt1, txt2) {\n return instance.patch_toText(instance.patch_make(txt1, txt2));\n },\n patch: function patch(txt1, _patch) {\n var results = instance.patch_apply(instance.patch_fromText(_patch), txt1);\n for (var i = 0; i < results[1].length; i++) {\n if (!results[1][i]) {\n var _error = new Error('text patch failed');\n _error.textPatchFailed = true;\n }\n }\n return results[0];\n }\n };\n }\n return cachedDiffPatch;\n};\n\nvar diffFilter$3 = function textsDiffFilter(context) {\n if (context.leftType !== 'string') {\n return;\n }\n var minLength = context.options && context.options.textDiff && context.options.textDiff.minLength || DEFAULT_MIN_LENGTH;\n if (context.left.length < minLength || context.right.length < minLength) {\n context.setResult([context.left, context.right]).exit();\n return;\n }\n // large text, try to use a text-diff algorithm\n var diffMatchPatch = getDiffMatchPatch();\n if (!diffMatchPatch) {\n // diff-match-patch library not available,\n // fallback to regular string replace\n context.setResult([context.left, context.right]).exit();\n return;\n }\n var diff = diffMatchPatch.diff;\n context.setResult([diff(context.left, context.right), 0, TEXT_DIFF]).exit();\n};\ndiffFilter$3.filterName = 'texts';\n\nvar patchFilter$3 = function textsPatchFilter(context) {\n if (context.nested) {\n return;\n }\n if (context.delta[2] !== TEXT_DIFF) {\n return;\n }\n\n // text-diff, use a text-patch algorithm\n var patch = getDiffMatchPatch(true).patch;\n context.setResult(patch(context.left, context.delta[0])).exit();\n};\npatchFilter$3.filterName = 'texts';\n\nvar textDeltaReverse = function textDeltaReverse(delta) {\n var i = void 0;\n var l = void 0;\n var lines = void 0;\n var line = void 0;\n var lineTmp = void 0;\n var header = null;\n var headerRegex = /^@@ +-(\\d+),(\\d+) +\\+(\\d+),(\\d+) +@@$/;\n var lineHeader = void 0;\n lines = delta.split('\\n');\n for (i = 0, l = lines.length; i < l; i++) {\n line = lines[i];\n var lineStart = line.slice(0, 1);\n if (lineStart === '@') {\n header = headerRegex.exec(line);\n lineHeader = i;\n\n // fix header\n lines[lineHeader] = '@@ -' + header[3] + ',' + header[4] + ' +' + header[1] + ',' + header[2] + ' @@';\n } else if (lineStart === '+') {\n lines[i] = '-' + lines[i].slice(1);\n if (lines[i - 1].slice(0, 1) === '+') {\n // swap lines to keep default order (-+)\n lineTmp = lines[i];\n lines[i] = lines[i - 1];\n lines[i - 1] = lineTmp;\n }\n } else if (lineStart === '-') {\n lines[i] = '+' + lines[i].slice(1);\n }\n }\n return lines.join('\\n');\n};\n\nvar reverseFilter$3 = function textsReverseFilter(context) {\n if (context.nested) {\n return;\n }\n if (context.delta[2] !== TEXT_DIFF) {\n return;\n }\n\n // text-diff, use a text-diff algorithm\n context.setResult([textDeltaReverse(context.delta[0]), 0, TEXT_DIFF]).exit();\n};\nreverseFilter$3.filterName = 'texts';\n\nvar DiffPatcher = function () {\n function DiffPatcher(options) {\n classCallCheck(this, DiffPatcher);\n\n this.processor = new Processor(options);\n this.processor.pipe(new Pipe('diff').append(collectChildrenDiffFilter, diffFilter, diffFilter$2, diffFilter$3, objectsDiffFilter, diffFilter$1).shouldHaveResult());\n this.processor.pipe(new Pipe('patch').append(collectChildrenPatchFilter, collectChildrenPatchFilter$1, patchFilter, patchFilter$3, patchFilter$1, patchFilter$2).shouldHaveResult());\n this.processor.pipe(new Pipe('reverse').append(collectChildrenReverseFilter, collectChildrenReverseFilter$1, reverseFilter, reverseFilter$3, reverseFilter$1, reverseFilter$2).shouldHaveResult());\n }\n\n createClass(DiffPatcher, [{\n key: 'options',\n value: function options() {\n var _processor;\n\n return (_processor = this.processor).options.apply(_processor, arguments);\n }\n }, {\n key: 'diff',\n value: function diff(left, right) {\n return this.processor.process(new DiffContext(left, right));\n }\n }, {\n key: 'patch',\n value: function patch(left, delta) {\n return this.processor.process(new PatchContext(left, delta));\n }\n }, {\n key: 'reverse',\n value: function reverse(delta) {\n return this.processor.process(new ReverseContext(delta));\n }\n }, {\n key: 'unpatch',\n value: function unpatch(right, delta) {\n return this.patch(right, this.reverse(delta));\n }\n }, {\n key: 'clone',\n value: function clone$$1(value) {\n return clone(value);\n }\n }]);\n return DiffPatcher;\n}();\n\nvar isArray$3 = typeof Array.isArray === 'function' ? Array.isArray : function (a) {\n return a instanceof Array;\n};\n\nvar getObjectKeys = typeof Object.keys === 'function' ? function (obj) {\n return Object.keys(obj);\n} : function (obj) {\n var names = [];\n for (var property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n names.push(property);\n }\n }\n return names;\n};\n\nvar trimUnderscore = function trimUnderscore(str) {\n if (str.substr(0, 1) === '_') {\n return str.slice(1);\n }\n return str;\n};\n\nvar arrayKeyToSortNumber = function arrayKeyToSortNumber(key) {\n if (key === '_t') {\n return -1;\n } else {\n if (key.substr(0, 1) === '_') {\n return parseInt(key.slice(1), 10);\n } else {\n return parseInt(key, 10) + 0.1;\n }\n }\n};\n\nvar arrayKeyComparer = function arrayKeyComparer(key1, key2) {\n return arrayKeyToSortNumber(key1) - arrayKeyToSortNumber(key2);\n};\n\nvar BaseFormatter = function () {\n function BaseFormatter() {\n classCallCheck(this, BaseFormatter);\n }\n\n createClass(BaseFormatter, [{\n key: 'format',\n value: function format(delta, left) {\n var context = {};\n this.prepareContext(context);\n this.recurse(context, delta, left);\n return this.finalize(context);\n }\n }, {\n key: 'prepareContext',\n value: function prepareContext(context) {\n context.buffer = [];\n context.out = function () {\n var _buffer;\n\n (_buffer = this.buffer).push.apply(_buffer, arguments);\n };\n }\n }, {\n key: 'typeFormattterNotFound',\n value: function typeFormattterNotFound(context, deltaType) {\n throw new Error('cannot format delta type: ' + deltaType);\n }\n }, {\n key: 'typeFormattterErrorFormatter',\n value: function typeFormattterErrorFormatter(context, err) {\n return err.toString();\n }\n }, {\n key: 'finalize',\n value: function finalize(_ref) {\n var buffer = _ref.buffer;\n\n if (isArray$3(buffer)) {\n return buffer.join('');\n }\n }\n }, {\n key: 'recurse',\n value: function recurse(context, delta, left, key, leftKey, movedFrom, isLast) {\n var useMoveOriginHere = delta && movedFrom;\n var leftValue = useMoveOriginHere ? movedFrom.value : left;\n\n if (typeof delta === 'undefined' && typeof key === 'undefined') {\n return undefined;\n }\n\n var type = this.getDeltaType(delta, movedFrom);\n var nodeType = type === 'node' ? delta._t === 'a' ? 'array' : 'object' : '';\n\n if (typeof key !== 'undefined') {\n this.nodeBegin(context, key, leftKey, type, nodeType, isLast);\n } else {\n this.rootBegin(context, type, nodeType);\n }\n\n var typeFormattter = void 0;\n try {\n typeFormattter = this['format_' + type] || this.typeFormattterNotFound(context, type);\n typeFormattter.call(this, context, delta, leftValue, key, leftKey, movedFrom);\n } catch (err) {\n this.typeFormattterErrorFormatter(context, err, delta, leftValue, key, leftKey, movedFrom);\n if (typeof console !== 'undefined' && console.error) {\n console.error(err.stack);\n }\n }\n\n if (typeof key !== 'undefined') {\n this.nodeEnd(context, key, leftKey, type, nodeType, isLast);\n } else {\n this.rootEnd(context, type, nodeType);\n }\n }\n }, {\n key: 'formatDeltaChildren',\n value: function formatDeltaChildren(context, delta, left) {\n var self = this;\n this.forEachDeltaKey(delta, left, function (key, leftKey, movedFrom, isLast) {\n self.recurse(context, delta[key], left ? left[leftKey] : undefined, key, leftKey, movedFrom, isLast);\n });\n }\n }, {\n key: 'forEachDeltaKey',\n value: function forEachDeltaKey(delta, left, fn) {\n var keys = getObjectKeys(delta);\n var arrayKeys = delta._t === 'a';\n var moveDestinations = {};\n var name = void 0;\n if (typeof left !== 'undefined') {\n for (name in left) {\n if (Object.prototype.hasOwnProperty.call(left, name)) {\n if (typeof delta[name] === 'undefined' && (!arrayKeys || typeof delta['_' + name] === 'undefined')) {\n keys.push(name);\n }\n }\n }\n }\n // look for move destinations\n for (name in delta) {\n if (Object.prototype.hasOwnProperty.call(delta, name)) {\n var value = delta[name];\n if (isArray$3(value) && value[2] === 3) {\n moveDestinations[value[1].toString()] = {\n key: name,\n value: left && left[parseInt(name.substr(1))]\n };\n if (this.includeMoveDestinations !== false) {\n if (typeof left === 'undefined' && typeof delta[value[1]] === 'undefined') {\n keys.push(value[1].toString());\n }\n }\n }\n }\n }\n if (arrayKeys) {\n keys.sort(arrayKeyComparer);\n } else {\n keys.sort();\n }\n for (var index = 0, length = keys.length; index < length; index++) {\n var key = keys[index];\n if (arrayKeys && key === '_t') {\n continue;\n }\n var leftKey = arrayKeys ? typeof key === 'number' ? key : parseInt(trimUnderscore(key), 10) : key;\n var isLast = index === length - 1;\n fn(key, leftKey, moveDestinations[leftKey], isLast);\n }\n }\n }, {\n key: 'getDeltaType',\n value: function getDeltaType(delta, movedFrom) {\n if (typeof delta === 'undefined') {\n if (typeof movedFrom !== 'undefined') {\n return 'movedestination';\n }\n return 'unchanged';\n }\n if (isArray$3(delta)) {\n if (delta.length === 1) {\n return 'added';\n }\n if (delta.length === 2) {\n return 'modified';\n }\n if (delta.length === 3 && delta[2] === 0) {\n return 'deleted';\n }\n if (delta.length === 3 && delta[2] === 2) {\n return 'textdiff';\n }\n if (delta.length === 3 && delta[2] === 3) {\n return 'moved';\n }\n } else if ((typeof delta === 'undefined' ? 'undefined' : _typeof(delta)) === 'object') {\n return 'node';\n }\n return 'unknown';\n }\n }, {\n key: 'parseTextDiff',\n value: function parseTextDiff(value) {\n var output = [];\n var lines = value.split('\\n@@ ');\n for (var i = 0, l = lines.length; i < l; i++) {\n var line = lines[i];\n var lineOutput = {\n pieces: []\n };\n var location = /^(?:@@ )?[-+]?(\\d+),(\\d+)/.exec(line).slice(1);\n lineOutput.location = {\n line: location[0],\n chr: location[1]\n };\n var pieces = line.split('\\n').slice(1);\n for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {\n var piece = pieces[pieceIndex];\n if (!piece.length) {\n continue;\n }\n var pieceOutput = {\n type: 'context'\n };\n if (piece.substr(0, 1) === '+') {\n pieceOutput.type = 'added';\n } else if (piece.substr(0, 1) === '-') {\n pieceOutput.type = 'deleted';\n }\n pieceOutput.text = piece.slice(1);\n lineOutput.pieces.push(pieceOutput);\n }\n output.push(lineOutput);\n }\n return output;\n }\n }]);\n return BaseFormatter;\n}();\n\n\n\nvar base = Object.freeze({\n\tdefault: BaseFormatter\n});\n\nvar HtmlFormatter = function (_BaseFormatter) {\n inherits(HtmlFormatter, _BaseFormatter);\n\n function HtmlFormatter() {\n classCallCheck(this, HtmlFormatter);\n return possibleConstructorReturn(this, (HtmlFormatter.__proto__ || Object.getPrototypeOf(HtmlFormatter)).apply(this, arguments));\n }\n\n createClass(HtmlFormatter, [{\n key: 'typeFormattterErrorFormatter',\n value: function typeFormattterErrorFormatter(context, err) {\n context.out('<pre class=\"jsondiffpatch-error\">' + err + '</pre>');\n }\n }, {\n key: 'formatValue',\n value: function formatValue(context, value) {\n context.out('<pre>' + htmlEscape(JSON.stringify(value, null, 2)) + '</pre>');\n }\n }, {\n key: 'formatTextDiffString',\n value: function formatTextDiffString(context, value) {\n var lines = this.parseTextDiff(value);\n context.out('<ul class=\"jsondiffpatch-textdiff\">');\n for (var i = 0, l = lines.length; i < l; i++) {\n var line = lines[i];\n context.out('<li><div class=\"jsondiffpatch-textdiff-location\">' + ('<span class=\"jsondiffpatch-textdiff-line-number\">' + line.location.line + '</span><span class=\"jsondiffpatch-textdiff-char\">' + line.location.chr + '</span></div><div class=\"jsondiffpatch-textdiff-line\">'));\n var pieces = line.pieces;\n for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {\n /* global decodeURI */\n var piece = pieces[pieceIndex];\n context.out('<span class=\"jsondiffpatch-textdiff-' + piece.type + '\">' + htmlEscape(decodeURI(piece.text)) + '</span>');\n }\n context.out('</div></li>');\n }\n context.out('</ul>');\n }\n }, {\n key: 'rootBegin',\n value: function rootBegin(context, type, nodeType) {\n var nodeClass = 'jsondiffpatch-' + type + (nodeType ? ' jsondiffpatch-child-node-type-' + nodeType : '');\n context.out('<div class=\"jsondiffpatch-delta ' + nodeClass + '\">');\n }\n }, {\n key: 'rootEnd',\n value: function rootEnd(context) {\n context.out('</div>' + (context.hasArrows ? '<script type=\"text/javascript\">setTimeout(' + (adjustArrows.toString() + ',10);</script>') : ''));\n }\n }, {\n key: 'nodeBegin',\n value: function nodeBegin(context, key, leftKey, type, nodeType) {\n var nodeClass = 'jsondiffpatch-' + type + (nodeType ? ' jsondiffpatch-child-node-type-' + nodeType : '');\n context.out('<li class=\"' + nodeClass + '\" data-key=\"' + leftKey + '\">' + ('<div class=\"jsondiffpatch-property-name\">' + leftKey + '</div>'));\n }\n }, {\n key: 'nodeEnd',\n value: function nodeEnd(context) {\n context.out('</li>');\n }\n\n /* jshint camelcase: false */\n /* eslint-disable camelcase */\n\n }, {\n key: 'format_unchanged',\n value: function format_unchanged(context, delta, left) {\n if (typeof left === 'undefined') {\n return;\n }\n context.out('<div class=\"jsondiffpatch-value\">');\n this.formatValue(context, left);\n context.out('</div>');\n }\n }, {\n key: 'format_movedestination',\n value: function format_movedestination(context, delta, left) {\n if (typeof left === 'undefined') {\n return;\n }\n context.out('<div class=\"jsondiffpatch-value\">');\n this.formatValue(context, left);\n context.out('</div>');\n }\n }, {\n key: 'format_node',\n value: function format_node(context, delta, left) {\n // recurse\n var nodeType = delta._t === 'a' ? 'array' : 'object';\n context.out('<ul class=\"jsondiffpatch-node jsondiffpatch-node-type-' + nodeType + '\">');\n this.formatDeltaChildren(context, delta, left);\n context.out('</ul>');\n }\n }, {\n key: 'format_added',\n value: function format_added(context, delta) {\n context.out('<div class=\"jsondiffpatch-value\">');\n this.formatValue(context, delta[0]);\n context.out('</div>');\n }\n }, {\n key: 'format_modified',\n value: function format_modified(context, delta) {\n context.out('<div class=\"jsondiffpatch-value jsondiffpatch-left-value\">');\n this.formatValue(context, delta[0]);\n context.out('</div>' + '<div class=\"jsondiffpatch-value jsondiffpatch-right-value\">');\n this.formatValue(context, delta[1]);\n context.out('</div>');\n }\n }, {\n key: 'format_deleted',\n value: function format_deleted(context, delta) {\n context.out('<div class=\"jsondiffpatch-value\">');\n this.formatValue(context, delta[0]);\n context.out('</div>');\n }\n }, {\n key: 'format_moved',\n value: function format_moved(context, delta) {\n context.out('<div class=\"jsondiffpatch-value\">');\n this.formatValue(context, delta[0]);\n context.out('</div><div class=\"jsondiffpatch-moved-destination\">' + delta[1] + '</div>');\n\n // draw an SVG arrow from here to move destination\n context.out(\n /* jshint multistr: true */\n '<div class=\"jsondiffpatch-arrow\" ' + 'style=\"position: relative; left: -34px;\">\\n <svg width=\"30\" height=\"60\" ' + 'style=\"position: absolute; display: none;\">\\n <defs>\\n <marker id=\"markerArrow\" markerWidth=\"8\" markerHeight=\"8\"\\n refx=\"2\" refy=\"4\"\\n orient=\"auto\" markerUnits=\"userSpaceOnUse\">\\n <path d=\"M1,1 L1,7 L7,4 L1,1\" style=\"fill: #339;\" />\\n </marker>\\n </defs>\\n <path d=\"M30,0 Q-10,25 26,50\"\\n style=\"stroke: #88f; stroke-width: 2px; fill: none; ' + 'stroke-opacity: 0.5; marker-end: url(#markerArrow);\"\\n ></path>\\n </svg>\\n </div>');\n context.hasArrows = true;\n }\n }, {\n key: 'format_textdiff',\n value: function format_textdiff(context, delta) {\n context.out('<div class=\"jsondiffpatch-value\">');\n this.formatTextDiffString(context, delta[0]);\n context.out('</div>');\n }\n }]);\n return HtmlFormatter;\n}(BaseFormatter);\n\nfunction htmlEscape(text) {\n var html = text;\n var replacements = [[/&/g, '&amp;'], [/</g, '&lt;'], [/>/g, '&gt;'], [/'/g, '&apos;'], [/\"/g, '&quot;']];\n for (var i = 0; i < replacements.length; i++) {\n html = html.replace(replacements[i][0], replacements[i][1]);\n }\n return html;\n}\n\nvar adjustArrows = function jsondiffpatchHtmlFormatterAdjustArrows(nodeArg) {\n var node = nodeArg || document;\n var getElementText = function getElementText(_ref) {\n var textContent = _ref.textContent,\n innerText = _ref.innerText;\n return textContent || innerText;\n };\n var eachByQuery = function eachByQuery(el, query, fn) {\n var elems = el.querySelectorAll(query);\n for (var i = 0, l = elems.length; i < l; i++) {\n fn(elems[i]);\n }\n };\n var eachChildren = function eachChildren(_ref2, fn) {\n var children = _ref2.children;\n\n for (var i = 0, l = children.length; i < l; i++) {\n fn(children[i], i);\n }\n };\n eachByQuery(node, '.jsondiffpatch-arrow', function (_ref3) {\n var parentNode = _ref3.parentNode,\n children = _ref3.children,\n style = _ref3.style;\n\n var arrowParent = parentNode;\n var svg = children[0];\n var path = svg.children[1];\n svg.style.display = 'none';\n var destination = getElementText(arrowParent.querySelector('.jsondiffpatch-moved-destination'));\n var container = arrowParent.parentNode;\n var destinationElem = void 0;\n eachChildren(container, function (child) {\n if (child.getAttribute('data-key') === destination) {\n destinationElem = child;\n }\n });\n if (!destinationElem) {\n return;\n }\n try {\n var distance = destinationElem.offsetTop - arrowParent.offsetTop;\n svg.setAttribute('height', Math.abs(distance) + 6);\n style.top = -8 + (distance > 0 ? 0 : distance) + 'px';\n var curve = distance > 0 ? 'M30,0 Q-10,' + Math.round(distance / 2) + ' 26,' + (distance - 4) : 'M30,' + -distance + ' Q-10,' + Math.round(-distance / 2) + ' 26,4';\n path.setAttribute('d', curve);\n svg.style.display = '';\n } catch (err) {}\n });\n};\n\n/* jshint camelcase: true */\n/* eslint-enable camelcase */\n\nvar showUnchanged = function showUnchanged(show, node, delay) {\n var el = node || document.body;\n var prefix = 'jsondiffpatch-unchanged-';\n var classes = {\n showing: prefix + 'showing',\n hiding: prefix + 'hiding',\n visible: prefix + 'visible',\n hidden: prefix + 'hidden'\n };\n var list = el.classList;\n if (!list) {\n return;\n }\n if (!delay) {\n list.remove(classes.showing);\n list.remove(classes.hiding);\n list.remove(classes.visible);\n list.remove(classes.hidden);\n if (show === false) {\n list.add(classes.hidden);\n }\n return;\n }\n if (show === false) {\n list.remove(classes.showing);\n list.add(classes.visible);\n setTimeout(function () {\n list.add(classes.hiding);\n }, 10);\n } else {\n list.remove(classes.hiding);\n list.add(classes.showing);\n list.remove(classes.hidden);\n }\n var intervalId = setInterval(function () {\n adjustArrows(el);\n }, 100);\n setTimeout(function () {\n list.remove(classes.showing);\n list.remove(classes.hiding);\n if (show === false) {\n list.add(classes.hidden);\n list.remove(classes.visible);\n } else {\n list.add(classes.visible);\n list.remove(classes.hidden);\n }\n setTimeout(function () {\n list.remove(classes.visible);\n clearInterval(intervalId);\n }, delay + 400);\n }, delay);\n};\n\nvar hideUnchanged = function hideUnchanged(node, delay) {\n return showUnchanged(false, node, delay);\n};\n\nvar defaultInstance = void 0;\n\nfunction format(delta, left) {\n if (!defaultInstance) {\n defaultInstance = new HtmlFormatter();\n }\n return defaultInstance.format(delta, left);\n}\n\n\n\nvar html = Object.freeze({\n\tshowUnchanged: showUnchanged,\n\thideUnchanged: hideUnchanged,\n\tdefault: HtmlFormatter,\n\tformat: format\n});\n\nvar AnnotatedFormatter = function (_BaseFormatter) {\n inherits(AnnotatedFormatter, _BaseFormatter);\n\n function AnnotatedFormatter() {\n classCallCheck(this, AnnotatedFormatter);\n\n var _this = possibleConstructorReturn(this, (AnnotatedFormatter.__proto__ || Object.getPrototypeOf(AnnotatedFormatter)).call(this));\n\n _this.includeMoveDestinations = false;\n return _this;\n }\n\n createClass(AnnotatedFormatter, [{\n key: 'prepareContext',\n value: function prepareContext(context) {\n get(AnnotatedFormatter.prototype.__proto__ || Object.getPrototypeOf(AnnotatedFormatter.prototype), 'prepareContext', this).call(this, context);\n context.indent = function (levels) {\n this.indentLevel = (this.indentLevel || 0) + (typeof levels === 'undefined' ? 1 : levels);\n this.indentPad = new Array(this.indentLevel + 1).join('&nbsp;&nbsp;');\n };\n context.row = function (json, htmlNote) {\n context.out('<tr><td style=\"white-space: nowrap;\">' + '<pre class=\"jsondiffpatch-annotated-indent\"' + ' style=\"display: inline-block\">');\n context.out(context.indentPad);\n context.out('</pre><pre style=\"display: inline-block\">');\n context.out(json);\n context.out('</pre></td><td class=\"jsondiffpatch-delta-note\"><div>');\n context.out(htmlNote);\n context.out('</div></td></tr>');\n };\n }\n }, {\n key: 'typeFormattterErrorFormatter',\n value: function typeFormattterErrorFormatter(context, err) {\n context.row('', '<pre class=\"jsondiffpatch-error\">' + err + '</pre>');\n }\n }, {\n key: 'formatTextDiffString',\n value: function formatTextDiffString(context, value) {\n var lines = this.parseTextDiff(value);\n context.out('<ul class=\"jsondiffpatch-textdiff\">');\n for (var i = 0, l = lines.length; i < l; i++) {\n var line = lines[i];\n context.out('<li><div class=\"jsondiffpatch-textdiff-location\">' + ('<span class=\"jsondiffpatch-textdiff-line-number\">' + line.location.line + '</span><span class=\"jsondiffpatch-textdiff-char\">' + line.location.chr + '</span></div><div class=\"jsondiffpatch-textdiff-line\">'));\n var pieces = line.pieces;\n for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {\n var piece = pieces[pieceIndex];\n context.out('<span class=\"jsondiffpatch-textdiff-' + piece.type + '\">' + piece.text + '</span>');\n }\n context.out('</div></li>');\n }\n context.out('</ul>');\n }\n }, {\n key: 'rootBegin',\n value: function rootBegin(context, type, nodeType) {\n context.out('<table class=\"jsondiffpatch-annotated-delta\">');\n if (type === 'node') {\n context.row('{');\n context.indent();\n }\n if (nodeType === 'array') {\n context.row('\"_t\": \"a\",', 'Array delta (member names indicate array indices)');\n }\n }\n }, {\n key: 'rootEnd',\n value: function rootEnd(context, type) {\n if (type === 'node') {\n context.indent(-1);\n context.row('}');\n }\n context.out('</table>');\n }\n }, {\n key: 'nodeBegin',\n value: function nodeBegin(context, key, leftKey, type, nodeType) {\n context.row('&quot;' + key + '&quot;: {');\n if (type === 'node') {\n context.indent();\n }\n if (nodeType === 'array') {\n context.row('\"_t\": \"a\",', 'Array delta (member names indicate array indices)');\n }\n }\n }, {\n key: 'nodeEnd',\n value: function nodeEnd(context, key, leftKey, type, nodeType, isLast) {\n if (type === 'node') {\n context.indent(-1);\n }\n context.row('}' + (isLast ? '' : ','));\n }\n\n /* jshint camelcase: false */\n\n /* eslint-disable camelcase */\n\n }, {\n key: 'format_unchanged',\n value: function format_unchanged() {}\n }, {\n key: 'format_movedestination',\n value: function format_movedestination() {}\n }, {\n key: 'format_node',\n value: function format_node(context, delta, left) {\n // recurse\n this.formatDeltaChildren(context, delta, left);\n }\n }]);\n return AnnotatedFormatter;\n}(BaseFormatter);\n\n/* eslint-enable camelcase */\n\nvar wrapPropertyName = function wrapPropertyName(name) {\n return '<pre style=\"display:inline-block\">&quot;' + name + '&quot;</pre>';\n};\n\nvar deltaAnnotations = {\n added: function added(delta, left, key, leftKey) {\n var formatLegend = ' <pre>([newValue])</pre>';\n if (typeof leftKey === 'undefined') {\n return 'new value' + formatLegend;\n }\n if (typeof leftKey === 'number') {\n return 'insert at index ' + leftKey + formatLegend;\n }\n return 'add property ' + wrapPropertyName(leftKey) + formatLegend;\n },\n modified: function modified(delta, left, key, leftKey) {\n var formatLegend = ' <pre>([previousValue, newValue])</pre>';\n if (typeof leftKey === 'undefined') {\n return 'modify value' + formatLegend;\n }\n if (typeof leftKey === 'number') {\n return 'modify at index ' + leftKey + formatLegend;\n }\n return 'modify property ' + wrapPropertyName(leftKey) + formatLegend;\n },\n deleted: function deleted(delta, left, key, leftKey) {\n var formatLegend = ' <pre>([previousValue, 0, 0])</pre>';\n if (typeof leftKey === 'undefined') {\n return 'delete value' + formatLegend;\n }\n if (typeof leftKey === 'number') {\n return 'remove index ' + leftKey + formatLegend;\n }\n return 'delete property ' + wrapPropertyName(leftKey) + formatLegend;\n },\n moved: function moved(delta, left, key, leftKey) {\n return 'move from <span title=\"(position to remove at original state)\">' + ('index ' + leftKey + '</span> to <span title=\"(position to insert at final') + (' state)\">index ' + delta[1] + '</span>');\n },\n textdiff: function textdiff(delta, left, key, leftKey) {\n var location = typeof leftKey === 'undefined' ? '' : typeof leftKey === 'number' ? ' at index ' + leftKey : ' at property ' + wrapPropertyName(leftKey);\n return 'text diff' + location + ', format is <a href=\"https://code.google.com/' + 'p/google-diff-match-patch/wiki/Unidiff\">a variation of Unidiff</a>';\n }\n};\n\nvar formatAnyChange = function formatAnyChange(context, delta) {\n var deltaType = this.getDeltaType(delta);\n var annotator = deltaAnnotations[deltaType];\n var htmlNote = annotator && annotator.apply(annotator, Array.prototype.slice.call(arguments, 1));\n var json = JSON.stringify(delta, null, 2);\n if (deltaType === 'textdiff') {\n // split text diffs lines\n json = json.split('\\\\n').join('\\\\n\"+\\n \"');\n }\n context.indent();\n context.row(json, htmlNote);\n context.indent(-1);\n};\n\n/* eslint-disable camelcase */\nAnnotatedFormatter.prototype.format_added = formatAnyChange;\nAnnotatedFormatter.prototype.format_modified = formatAnyChange;\nAnnotatedFormatter.prototype.format_deleted = formatAnyChange;\nAnnotatedFormatter.prototype.format_moved = formatAnyChange;\nAnnotatedFormatter.prototype.format_textdiff = formatAnyChange;\nvar defaultInstance$1 = void 0;\n\nfunction format$1(delta, left) {\n if (!defaultInstance$1) {\n defaultInstance$1 = new AnnotatedFormatter();\n }\n return defaultInstance$1.format(delta, left);\n}\n\n\n\nvar annotated = Object.freeze({\n\tdefault: AnnotatedFormatter,\n\tformat: format$1\n});\n\nvar OPERATIONS = {\n add: 'add',\n remove: 'remove',\n replace: 'replace',\n move: 'move'\n};\n\nvar JSONFormatter = function (_BaseFormatter) {\n inherits(JSONFormatter, _BaseFormatter);\n\n function JSONFormatter() {\n classCallCheck(this, JSONFormatter);\n\n var _this = possibleConstructorReturn(this, (JSONFormatter.__proto__ || Object.getPrototypeOf(JSONFormatter)).call(this));\n\n _this.includeMoveDestinations = true;\n return _this;\n }\n\n createClass(JSONFormatter, [{\n key: 'prepareContext',\n value: function prepareContext(context) {\n get(JSONFormatter.prototype.__proto__ || Object.getPrototypeOf(JSONFormatter.prototype), 'prepareContext', this).call(this, context);\n context.result = [];\n context.path = [];\n context.pushCurrentOp = function (obj) {\n var op = obj.op,\n value = obj.value;\n\n var val = {\n op: op,\n path: this.currentPath()\n };\n if (typeof value !== 'undefined') {\n val.value = value;\n }\n this.result.push(val);\n };\n\n context.pushMoveOp = function (to) {\n var from = this.currentPath();\n this.result.push({\n op: OPERATIONS.move,\n from: from,\n path: this.toPath(to)\n });\n };\n\n context.currentPath = function () {\n return '/' + this.path.join('/');\n };\n\n context.toPath = function (toPath) {\n var to = this.path.slice();\n to[to.length - 1] = toPath;\n return '/' + to.join('/');\n };\n }\n }, {\n key: 'typeFormattterErrorFormatter',\n value: function typeFormattterErrorFormatter(context, err) {\n context.out('[ERROR] ' + err);\n }\n }, {\n key: 'rootBegin',\n value: function rootBegin() {}\n }, {\n key: 'rootEnd',\n value: function rootEnd() {}\n }, {\n key: 'nodeBegin',\n value: function nodeBegin(_ref, key, leftKey) {\n var path = _ref.path;\n\n path.push(leftKey);\n }\n }, {\n key: 'nodeEnd',\n value: function nodeEnd(_ref2) {\n var path = _ref2.path;\n\n path.pop();\n }\n\n /* jshint camelcase: false */\n /* eslint-disable camelcase */\n\n }, {\n key: 'format_unchanged',\n value: function format_unchanged() {}\n }, {\n key: 'format_movedestination',\n value: function format_movedestination() {}\n }, {\n key: 'format_node',\n value: function format_node(context, delta, left) {\n this.formatDeltaChildren(context, delta, left);\n }\n }, {\n key: 'format_added',\n value: function format_added(context, delta) {\n context.pushCurrentOp({ op: OPERATIONS.add, value: delta[0] });\n }\n }, {\n key: 'format_modified',\n value: function format_modified(context, delta) {\n context.pushCurrentOp({ op: OPERATIONS.replace, value: delta[1] });\n }\n }, {\n key: 'format_deleted',\n value: function format_deleted(context) {\n context.pushCurrentOp({ op: OPERATIONS.remove });\n }\n }, {\n key: 'format_moved',\n value: function format_moved(context, delta) {\n var to = delta[1];\n context.pushMoveOp(to);\n }\n }, {\n key: 'format_textdiff',\n value: function format_textdiff() {\n throw new Error('Not implemented');\n }\n }, {\n key: 'format',\n value: function format(delta, left) {\n var context = {};\n this.prepareContext(context);\n this.recurse(context, delta, left);\n return context.result;\n }\n }]);\n return JSONFormatter;\n}(BaseFormatter);\n\nvar last = function last(arr) {\n return arr[arr.length - 1];\n};\n\nvar sortBy = function sortBy(arr, pred) {\n arr.sort(pred);\n return arr;\n};\n\nvar compareByIndexDesc = function compareByIndexDesc(indexA, indexB) {\n var lastA = parseInt(indexA, 10);\n var lastB = parseInt(indexB, 10);\n if (!(isNaN(lastA) || isNaN(lastB))) {\n return lastB - lastA;\n } else {\n return 0;\n }\n};\n\nvar opsByDescendingOrder = function opsByDescendingOrder(removeOps) {\n return sortBy(removeOps, function (a, b) {\n var splitA = a.path.split('/');\n var splitB = b.path.split('/');\n if (splitA.length !== splitB.length) {\n return splitA.length - splitB.length;\n } else {\n return compareByIndexDesc(last(splitA), last(splitB));\n }\n });\n};\n\nvar partitionOps = function partitionOps(arr, fns) {\n var initArr = Array(fns.length + 1).fill().map(function () {\n return [];\n });\n return arr.map(function (item) {\n var position = fns.map(function (fn) {\n return fn(item);\n }).indexOf(true);\n if (position < 0) {\n position = fns.length;\n }\n return { item: item, position: position };\n }).reduce(function (acc, item) {\n acc[item.position].push(item.item);\n return acc;\n }, initArr);\n};\nvar isMoveOp = function isMoveOp(_ref3) {\n var op = _ref3.op;\n return op === 'move';\n};\nvar isRemoveOp = function isRemoveOp(_ref4) {\n var op = _ref4.op;\n return op === 'remove';\n};\n\nvar reorderOps = function reorderOps(diff) {\n var _partitionOps = partitionOps(diff, [isMoveOp, isRemoveOp]),\n _partitionOps2 = slicedToArray(_partitionOps, 3),\n moveOps = _partitionOps2[0],\n removedOps = _partitionOps2[1],\n restOps = _partitionOps2[2];\n\n var removeOpsReverse = opsByDescendingOrder(removedOps);\n return [].concat(toConsumableArray(removeOpsReverse), toConsumableArray(moveOps), toConsumableArray(restOps));\n};\n\nvar defaultInstance$2 = void 0;\n\nvar format$2 = function format(delta, left) {\n if (!defaultInstance$2) {\n defaultInstance$2 = new JSONFormatter();\n }\n return reorderOps(defaultInstance$2.format(delta, left));\n};\n\nvar log = function log(delta, left) {\n console.log(format$2(delta, left));\n};\n\n\n\nvar jsonpatch = Object.freeze({\n\tdefault: JSONFormatter,\n\tpartitionOps: partitionOps,\n\tformat: format$2,\n\tlog: log\n});\n\nfunction chalkColor(name) {\n return chalk && chalk[name] || function () {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return args;\n };\n}\n\nvar colors = {\n added: chalkColor('green'),\n deleted: chalkColor('red'),\n movedestination: chalkColor('gray'),\n moved: chalkColor('yellow'),\n unchanged: chalkColor('gray'),\n error: chalkColor('white.bgRed'),\n textDiffLine: chalkColor('gray')\n};\n\nvar ConsoleFormatter = function (_BaseFormatter) {\n inherits(ConsoleFormatter, _BaseFormatter);\n\n function ConsoleFormatter() {\n classCallCheck(this, ConsoleFormatter);\n\n var _this = possibleConstructorReturn(this, (ConsoleFormatter.__proto__ || Object.getPrototypeOf(ConsoleFormatter)).call(this));\n\n _this.includeMoveDestinations = false;\n return _this;\n }\n\n createClass(ConsoleFormatter, [{\n key: 'prepareContext',\n value: function prepareContext(context) {\n get(ConsoleFormatter.prototype.__proto__ || Object.getPrototypeOf(ConsoleFormatter.prototype), 'prepareContext', this).call(this, context);\n context.indent = function (levels) {\n this.indentLevel = (this.indentLevel || 0) + (typeof levels === 'undefined' ? 1 : levels);\n this.indentPad = new Array(this.indentLevel + 1).join(' ');\n this.outLine();\n };\n context.outLine = function () {\n this.buffer.push('\\n' + (this.indentPad || ''));\n };\n context.out = function () {\n for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n for (var i = 0, l = args.length; i < l; i++) {\n var lines = args[i].split('\\n');\n var text = lines.join('\\n' + (this.indentPad || ''));\n if (this.color && this.color[0]) {\n text = this.color[0](text);\n }\n this.buffer.push(text);\n }\n };\n context.pushColor = function (color) {\n this.color = this.color || [];\n this.color.unshift(color);\n };\n context.popColor = function () {\n this.color = this.color || [];\n this.color.shift();\n };\n }\n }, {\n key: 'typeFormattterErrorFormatter',\n value: function typeFormattterErrorFormatter(context, err) {\n context.pushColor(colors.error);\n context.out('[ERROR]' + err);\n context.popColor();\n }\n }, {\n key: 'formatValue',\n value: function formatValue(context, value) {\n context.out(JSON.stringify(value, null, 2));\n }\n }, {\n key: 'formatTextDiffString',\n value: function formatTextDiffString(context, value) {\n var lines = this.parseTextDiff(value);\n context.indent();\n for (var i = 0, l = lines.length; i < l; i++) {\n var line = lines[i];\n context.pushColor(colors.textDiffLine);\n context.out(line.location.line + ',' + line.location.chr + ' ');\n context.popColor();\n var pieces = line.pieces;\n for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {\n var piece = pieces[pieceIndex];\n context.pushColor(colors[piece.type]);\n context.out(piece.text);\n context.popColor();\n }\n if (i < l - 1) {\n context.outLine();\n }\n }\n context.indent(-1);\n }\n }, {\n key: 'rootBegin',\n value: function rootBegin(context, type, nodeType) {\n context.pushColor(colors[type]);\n if (type === 'node') {\n context.out(nodeType === 'array' ? '[' : '{');\n context.indent();\n }\n }\n }, {\n key: 'rootEnd',\n value: function rootEnd(context, type, nodeType) {\n if (type === 'node') {\n context.indent(-1);\n context.out(nodeType === 'array' ? ']' : '}');\n }\n context.popColor();\n }\n }, {\n key: 'nodeBegin',\n value: function nodeBegin(context, key, leftKey, type, nodeType) {\n context.pushColor(colors[type]);\n context.out(leftKey + ': ');\n if (type === 'node') {\n context.out(nodeType === 'array' ? '[' : '{');\n context.indent();\n }\n }\n }, {\n key: 'nodeEnd',\n value: function nodeEnd(context, key, leftKey, type, nodeType, isLast) {\n if (type === 'node') {\n context.indent(-1);\n context.out(nodeType === 'array' ? ']' : '}' + (isLast ? '' : ','));\n }\n if (!isLast) {\n context.outLine();\n }\n context.popColor();\n }\n\n /* jshint camelcase: false */\n /* eslint-disable camelcase */\n\n }, {\n key: 'format_unchanged',\n value: function format_unchanged(context, delta, left) {\n if (typeof left === 'undefined') {\n return;\n }\n this.formatValue(context, left);\n }\n }, {\n key: 'format_movedestination',\n value: function format_movedestination(context, delta, left) {\n if (typeof left === 'undefined') {\n return;\n }\n this.formatValue(context, left);\n }\n }, {\n key: 'format_node',\n value: function format_node(context, delta, left) {\n // recurse\n this.formatDeltaChildren(context, delta, left);\n }\n }, {\n key: 'format_added',\n value: function format_added(context, delta) {\n this.formatValue(context, delta[0]);\n }\n }, {\n key: 'format_modified',\n value: function format_modified(context, delta) {\n context.pushColor(colors.deleted);\n this.formatValue(context, delta[0]);\n context.popColor();\n context.out(' => ');\n context.pushColor(colors.added);\n this.formatValue(context, delta[1]);\n context.popColor();\n }\n }, {\n key: 'format_deleted',\n value: function format_deleted(context, delta) {\n this.formatValue(context, delta[0]);\n }\n }, {\n key: 'format_moved',\n value: function format_moved(context, delta) {\n context.out('==> ' + delta[1]);\n }\n }, {\n key: 'format_textdiff',\n value: function format_textdiff(context, delta) {\n this.formatTextDiffString(context, delta[0]);\n }\n }]);\n return ConsoleFormatter;\n}(BaseFormatter);\n\nvar defaultInstance$3 = void 0;\n\nvar format$3 = function format(delta, left) {\n if (!defaultInstance$3) {\n defaultInstance$3 = new ConsoleFormatter();\n }\n return defaultInstance$3.format(delta, left);\n};\n\nfunction log$1(delta, left) {\n console.log(format$3(delta, left));\n}\n\n\n\nvar console$1 = Object.freeze({\n\tdefault: ConsoleFormatter,\n\tformat: format$3,\n\tlog: log$1\n});\n\n\n\nvar index = Object.freeze({\n\tbase: base,\n\thtml: html,\n\tannotated: annotated,\n\tjsonpatch: jsonpatch,\n\tconsole: console$1\n});\n\n// use as 2nd parameter for JSON.parse to revive Date instances\nfunction dateReviver(key, value) {\n var parts = void 0;\n if (typeof value === 'string') {\n // eslint-disable-next-line max-len\n parts = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d*))?(Z|([+-])(\\d{2}):(\\d{2}))$/.exec(value);\n if (parts) {\n return new Date(Date.UTC(+parts[1], +parts[2] - 1, +parts[3], +parts[4], +parts[5], +parts[6], +(parts[7] || 0)));\n }\n }\n return value;\n}\n\nfunction create(options) {\n return new DiffPatcher(options);\n}\n\nvar defaultInstance$4 = void 0;\n\nfunction diff() {\n if (!defaultInstance$4) {\n defaultInstance$4 = new DiffPatcher();\n }\n return defaultInstance$4.diff.apply(defaultInstance$4, arguments);\n}\n\nfunction patch() {\n if (!defaultInstance$4) {\n defaultInstance$4 = new DiffPatcher();\n }\n return defaultInstance$4.patch.apply(defaultInstance$4, arguments);\n}\n\nfunction unpatch() {\n if (!defaultInstance$4) {\n defaultInstance$4 = new DiffPatcher();\n }\n return defaultInstance$4.unpatch.apply(defaultInstance$4, arguments);\n}\n\nfunction reverse() {\n if (!defaultInstance$4) {\n defaultInstance$4 = new DiffPatcher();\n }\n return defaultInstance$4.reverse.apply(defaultInstance$4, arguments);\n}\n\nfunction clone$1() {\n if (!defaultInstance$4) {\n defaultInstance$4 = new DiffPatcher();\n }\n return defaultInstance$4.clone.apply(defaultInstance$4, arguments);\n}\n\nexport { DiffPatcher, index as formatters, console$1 as console, create, dateReviver, diff, patch, unpatch, reverse, clone$1 as clone };\n//# sourceMappingURL=jsondiffpatch.esm.js.map\n","import { DiffPatcher } from 'jsondiffpatch'\n\nconst diffPatcher = new DiffPatcher({\n arrays: { detectMove: false, includeValueOnMove: false },\n textDiff: { minLength: 1 }\n})\n\nexport function diff(inputA: any, inputB: any) {\n return diffPatcher.diff(inputA, inputB)\n}\n","import type { Transaction } from 'prosemirror-state'\n\nconst addedProperties = [\n 'docChanged',\n 'isGeneric',\n 'scrolledIntoView',\n 'selectionSet',\n 'storedMarksSet'\n]\n\nexport function addPropertiesToTransaction(tr: Transaction) {\n return Object.keys(tr)\n .concat(addedProperties)\n .reduce((acc, key) => {\n // @ts-ignore\n acc[key] = tr[key]\n return acc\n }, {} as Transaction)\n}\n","import type { EditorState, Selection, Transaction } from 'prosemirror-state'\nimport { DOMSerializer } from 'prosemirror-model'\nimport { prettyPrint } from 'html'\n\nimport { diff } from './diff'\nimport { addPropertiesToTransaction } from './transaction'\nimport type { HistoryEntry } from '$typings/history'\n\nfunction buildSelection(selection: Selection) {\n return {\n // @ts-ignore\n type: selection.type,\n empty: selection.empty,\n anchor: selection.anchor,\n head: selection.head,\n from: selection.from,\n to: selection.to\n }\n}\n\nfunction pad(num: number) {\n return ('00' + num).slice(-2)\n}\n\nfunction pad3(num: number) {\n return ('000' + num).slice(-3)\n}\n\nconst formatTimestamp = (timestamp: number) => {\n const date = new Date(timestamp)\n return [\n pad(date.getHours()),\n pad(date.getMinutes()),\n pad(date.getSeconds()),\n pad3(date.getMilliseconds())\n ].join(':')\n}\n\n// Matches any src attribute containing base64 data due to bug in html package and legibility\n// https://github.com/TeemuKoivisto/prosemirror-dev-toolkit/issues/81\nconst srcAttr = /src=[\\\"|\\']data:(.*);base64,(.*)[\\\"|\\']/g\n\nconst wrappingCarets = /(&lt;\\/?[\\w\\d\\s=\"']+&gt;)/gim\nconst highlightHtmlString = (html: string) =>\n html\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(wrappingCarets, \"<span style='color: cadetblue;'>$&</span>\")\n\nexport function createHistoryEntry(\n trs: readonly Transaction[],\n state: EditorState,\n stateBeforeDispatch: EditorState,\n oldEntry?: HistoryEntry\n): HistoryEntry {\n const serializer = DOMSerializer.fromSchema(state.schema)\n const selection = state.selection\n const domFragment = serializer.serializeFragment(selection.content().content)\n\n const selectedElementsAsHtml = []\n if (domFragment) {\n let child = domFragment.firstChild as HTMLElement | null\n while (child) {\n selectedElementsAsHtml.push(child.outerHTML.replaceAll(srcAttr, 'src=\"...\"'))\n child = child.nextSibling as HTMLElement | null\n }\n }\n\n // As described in stateHistory.ts the first entry is a special exception\n const prevState = oldEntry ? oldEntry.state : stateBeforeDispatch\n const contentDiff = diff(prevState.doc.toJSON(), state.doc.toJSON())\n const selectionDiff = diff(buildSelection(prevState.selection), buildSelection(state.selection))\n\n return {\n id: Math.random().toString() + Math.random().toString(),\n state,\n trs: trs.map(tr => addPropertiesToTransaction(tr)),\n timestamp: trs[0].time,\n timeStr: formatTimestamp(trs[0].time),\n contentDiff,\n selectionDiff,\n selectionHtml: highlightHtmlString(\n prettyPrint(selectedElementsAsHtml.join('\\n'), {\n max_char: 60,\n indent_size: 2\n })\n )\n }\n}\n","import { get, writable } from 'svelte/store'\nimport { EditorState, Transaction } from 'prosemirror-state'\n\nimport { createHistoryEntry } from '../history-and-diff/createHistoryEntry'\n\nimport type { HistoryEntry, HistoryGroup } from '$typings/history'\n\nexport const stateHistory = writable<Map<string, HistoryEntry>>(new Map())\nexport const shownHistoryGroups = writable<HistoryGroup[]>([])\nexport const latestEntry = writable<HistoryEntry | undefined>(undefined)\nexport const nextId = writable(0)\n\nexport function appendNewHistoryEntry(\n trs: readonly Transaction[],\n state: EditorState,\n stateBeforeDispatch: EditorState\n) {\n const entryMap = get(stateHistory)\n const prevGroup = get(shownHistoryGroups)[0]\n const oldEntry = entryMap.get(prevGroup?.topEntryId || '')\n // In the case of first entry there aren't oldEntries to diff against, therefore we have to use the state\n // before the transaction. We can't use it for the next entries because it will always be one state behind,\n // as the current state is the one _after_ the dispatch. You can observe this in the old dev-tools.\n const newEntry = createHistoryEntry(trs, state, stateBeforeDispatch, oldEntry)\n\n stateHistory.update(val => new Map(val.set(newEntry.id, newEntry)))\n latestEntry.set(newEntry)\n\n // Groups are subsequent transactions where the doc hasn't changed (eg selection was set) OR the diff was equal\n // Haven't seen necessary to differentiate between selection-only vs equal diffs\n const isGroup = !newEntry.contentDiff\n if (prevGroup?.isGroup && isGroup) {\n const newGroup = {\n id: prevGroup.id,\n isGroup,\n entryIds: [newEntry.id, ...prevGroup.entryIds],\n topEntryId: newEntry.id,\n expanded: prevGroup.expanded\n }\n shownHistoryGroups.update(val => [newGroup, ...val.slice(1)])\n } else {\n const id = get(nextId) + 1\n const newGroup = {\n id,\n isGroup,\n entryIds: [newEntry.id],\n topEntryId: newEntry.id,\n expanded: false\n }\n shownHistoryGroups.update(val => [newGroup, ...val])\n nextId.set(id)\n }\n}\n\nexport function resetHistory() {\n stateHistory.set(new Map())\n shownHistoryGroups.set([])\n latestEntry.set(undefined)\n}\n","import { EditorState } from 'prosemirror-state'\n\n// From https://github.com/PierBover/prosemirror-cookbook\nexport function getActiveMarks(state: EditorState): string[] {\n if (state.selection.empty) {\n const $from = state.selection.$from\n const storedMarks = state.storedMarks\n\n // Return either the stored marks, or the marks at the cursor position.\n // Stored marks are the marks that are going to be applied to the next input\n // if you dispatched a mark toggle with an empty cursor.\n if (storedMarks) {\n return storedMarks.map(mark => mark.type.name)\n } else {\n return $from.marks().map(mark => mark.type.name)\n }\n } else {\n const $head = state.selection.$head\n const $anchor = state.selection.$anchor\n\n // We're using a Set to not get duplicate values\n const activeMarks = new Set<string>()\n\n // Here we're getting the marks at the head and anchor of the selection\n $head.marks().forEach(mark => activeMarks.add(mark.type.name))\n $anchor.marks().forEach(mark => activeMarks.add(mark.type.name))\n\n return Array.from(activeMarks)\n }\n}\n","import { Selection } from 'prosemirror-state'\n\nconst defaultProperties = ['jsonID', 'empty', 'anchor', 'from', 'head', 'to']\nconst resolvedPosProperties = ['$anchor', '$head', '$cursor', '$to', '$from']\nconst resolvedPosSubProperties = ['nodeAfter', 'nodeBefore', 'textOffset']\n\nexport function createSelection(selection: Selection) {\n return defaultProperties.reduce(\n (acc, key) => {\n // @ts-ignore\n acc[key] = selection[key]\n return acc\n },\n {} as { [key: string]: any }\n )\n}\n\nexport function createFullSelection(selection: Selection) {\n return defaultProperties.concat(resolvedPosProperties).reduce(\n (acc, key) => {\n // @ts-ignore\n let val = selection[key]\n if (val && resolvedPosProperties.includes(key)) {\n const additionalProperties = {}\n resolvedPosSubProperties.forEach(subKey => {\n // @ts-ignore\n additionalProperties[subKey] = val[subKey]\n })\n val = { ...val, ...additionalProperties }\n }\n acc[key] = val\n return acc\n },\n {} as { [key: string]: any }\n )\n}\n","export function createNode(index, key, value, depth, parent) {\n const path = parent ? [...parent.path, index] : [];\n return {\n id: `[${path.join(',')}]`,\n index,\n key,\n value,\n depth,\n collapsed: true,\n type: getValueType(value),\n path,\n parentId: parent ? parent.id : null,\n circularOfId: null,\n children: []\n };\n}\nexport function getValueType(value) {\n if (Array.isArray(value)) {\n return 'array';\n }\n else if (value instanceof Map) {\n return 'map';\n }\n else if (value instanceof Set) {\n return 'set';\n }\n else if (value instanceof Date) {\n return 'date';\n }\n else if (value === null) {\n return 'null';\n }\n else {\n return typeof value;\n }\n}\n// From redux-dev-tools\n// case 'Object':\n// case 'Error':\n// case 'Array':\n// case 'Iterable':\n// case 'Map':\n// case 'Set':\n// case 'MapEntry':\n// case 'Number':\n// return undefined;\n// case 'String':\n// return raw => `\"${raw}\"`;\n// case 'Boolean':\n// return raw => (raw ? 'true' : 'false');\n// case 'Date':\n// return raw => raw.toISOString();\n// case 'Null':\n// return () => 'null';\n// case 'Undefined':\n// return () => 'undefined';\n// case 'Function':\n// case 'Symbol':\n// export function objType(obj: any) {\n// const type = Object.prototype.toString.call(obj).slice(8, -1)\n// if (type === 'Object') {\n// if (typeof obj[Symbol.iterator] === 'function') {\n// return 'Iterable'\n// }\n// return obj.constructor.name\n// }\n// return type\n// }\nfunction getChildren(value, type) {\n switch (type) {\n case 'array':\n return value.map((v, i) => [i.toString(), v]);\n case 'map':\n // eslint-disable-next-line no-case-declarations\n const entries = Array.from(value.entries());\n return entries.map(([key, value], i) => [\n `[map entry ${i}]`,\n {\n '[key]': key,\n '[value]': value\n }\n ]);\n case 'set':\n return Array.from(value.values()).map((v, i) => [`[set entry ${i}]`, v]);\n case 'object':\n return Object.entries(value);\n default:\n return [];\n }\n}\nfunction shouldRecurseChildren(node, parent, iteratedValues, opts) {\n if (!parent) {\n // The root node's children should always be recursed\n return true;\n }\n else if (node.collapsed && (parent === null || parent === void 0 ? void 0 : parent.collapsed)) {\n // If the node's parent is uncollapsed the node's children should still be recursed\n // in order to compute its value properly eg \"{} 4 keys\" and to place clickable arrow caret.\n // Only when the node is completely hidden it should not be recursed\n return false;\n }\n else if (!opts.stopCircularRecursion) {\n return true;\n }\n else if (opts.isCircularNode) {\n return opts.isCircularNode(node, iteratedValues);\n }\n else if (node.type === 'object' || node.type === 'array') {\n const existingNodeWithValue = iteratedValues.get(node.value);\n if (existingNodeWithValue && node.id !== existingNodeWithValue.id) {\n node.circularOfId = existingNodeWithValue.id;\n return false;\n }\n iteratedValues.set(node.value, node);\n }\n return true;\n}\nexport function recurseObjectProperties(index, key, value, depth, ensureNotCollapsed, parent, treeMap, oldTreeMap, iteratedValues, recomputeExpandNode, opts) {\n var _a;\n if (((_a = opts.omitKeys) === null || _a === void 0 ? void 0 : _a.includes(key)) || (opts.maxDepth && depth > opts.maxDepth)) {\n return null;\n }\n const node = createNode(index, key, value, depth, parent);\n const oldNode = oldTreeMap.get(node.id);\n if (ensureNotCollapsed) {\n // Used to ensure that either root node is always uncollapsed or when uncollapsing new nodes\n // with expandNodeChildren the node children are recursed (if applicable) with mapChildren\n node.collapsed = false;\n }\n else if (oldNode && !recomputeExpandNode) {\n // Maintain the same expanded/collapsed toggle for a node in this path/id\n // EXCEPT when the shouldExpandNode prop is changed...\n node.collapsed = oldNode.collapsed;\n }\n else if (opts.shouldExpandNode) {\n node.collapsed = !opts.shouldExpandNode(node);\n }\n treeMap.set(node.id, node);\n if (shouldRecurseChildren(node, parent, iteratedValues, opts)) {\n const mappedChildren = opts.mapChildren && opts.mapChildren(value, getValueType(value), node);\n const children = mappedChildren !== null && mappedChildren !== void 0 ? mappedChildren : getChildren(value, getValueType(value));\n node.children = children\n .map(([key, val], idx) => recurseObjectProperties(idx, key, val, depth + 1, false, node, treeMap, oldTreeMap, iteratedValues, recomputeExpandNode, opts))\n .filter(n => n !== null);\n }\n return node;\n}\nexport function recomputeTree(data, oldTreeMap, recursionOpts, recomputeExpandNode) {\n const treeMap = new Map();\n const iteratedValues = new Map();\n const newTree = recurseObjectProperties(-1, 'root', data, 0, true, null, treeMap, oldTreeMap, iteratedValues, recomputeExpandNode, recursionOpts);\n return { treeMap, tree: newTree, iteratedValues };\n}\n","import { derived, get, writable } from 'svelte/store';\nexport const createPropsStore = (initialProps) => {\n const props = writable(initialProps);\n const recursionOpts = derived(props, p => p.recursionOpts);\n return {\n props,\n recursionOpts,\n setProps(newProps) {\n props.set(newProps);\n },\n formatValue(val, node) {\n const { valueFormatter } = get(props);\n const customFormat = valueFormatter ? valueFormatter(val, node) : undefined;\n if (customFormat) {\n return customFormat;\n }\n switch (node.type) {\n case 'array':\n return `${node.circularOfId ? 'circular' : ''} [] ${val.length} items`;\n case 'object':\n return `${node.circularOfId ? 'circular' : ''} {} ${Object.keys(val).length} keys`;\n case 'map':\n case 'set':\n return `${node.circularOfId ? 'circular' : ''} () ${val.size} entries`;\n case 'date':\n return `${val.toISOString()}`;\n case 'string':\n return `\"${val}\"`;\n case 'boolean':\n return val ? 'true' : 'false';\n case 'symbol':\n return String(val);\n default:\n return val;\n }\n }\n };\n};\n","import { writable } from 'svelte/store';\nexport const createRootElementStore = () => {\n const rootElementStore = writable(null);\n return {\n set: rootElementStore.set,\n subscribe: rootElementStore.subscribe\n };\n};\n","import { get, writable } from 'svelte/store';\nimport { createNode, recurseObjectProperties } from '../tree-utils';\nexport const createTreeStore = (propsStore) => {\n const defaultRootNode = createNode(0, 'root', [], 0, null);\n const tree = writable(defaultRootNode);\n const treeMap = writable(new Map());\n const iteratedValues = writable(new Map());\n return {\n tree,\n treeMap,\n defaultRootNode,\n init(newTree, newTreeMap, iterated) {\n if (newTree) {\n tree.set(newTree);\n }\n else {\n tree.set(defaultRootNode);\n }\n treeMap.set(newTreeMap);\n iteratedValues.set(iterated);\n },\n getNode(id) {\n return get(treeMap).get(id);\n },\n toggleCollapse(id) {\n const node = get(treeMap).get(id);\n if (!node) {\n console.warn(`Attempted to collapse non-existent node: ${id}`);\n return;\n }\n const updatedNode = { ...node, collapsed: !node.collapsed };\n treeMap.update(m => new Map(m.set(node.id, updatedNode)));\n const recursionOpts = get(propsStore.recursionOpts);\n if (recursionOpts) {\n this.expandNodeChildren(updatedNode, recursionOpts);\n }\n },\n expandNodeChildren(node, recursionOpts) {\n const parent = this.getNode((node === null || node === void 0 ? void 0 : node.parentId) || '') || null;\n if (!parent) {\n // Only root node has no parent and it should not be expandable\n throw Error('No parent in expandNodeChildren for node: ' + node);\n }\n const newTreeMap = new Map(get(treeMap));\n const oldTreeMap = get(treeMap);\n const previouslyIterated = get(iteratedValues);\n const nodeWithUpdatedChildren = recurseObjectProperties(node.index, node.key, node.value, node.depth, !node.collapsed, // Ensure that when uncollapsed the node's children are always recursed\n parent, newTreeMap, oldTreeMap, previouslyIterated, false, // Never recompute shouldExpandNode since it may override the collapsing of this node\n recursionOpts);\n if (!nodeWithUpdatedChildren)\n return;\n parent.children = parent.children.map(c => c.id === nodeWithUpdatedChildren.id ? nodeWithUpdatedChildren : c);\n newTreeMap.set(nodeWithUpdatedChildren.id, nodeWithUpdatedChildren);\n newTreeMap.set(parent.id, parent);\n treeMap.set(newTreeMap);\n iteratedValues.set(previouslyIterated);\n },\n expandAllNodesToNode(id) {\n function recurseNodeUpwards(updated, node) {\n if (!node)\n return;\n updated.set(node.id, { ...node, collapsed: false });\n if (node.parentId) {\n recurseNodeUpwards(updated, updated.get(node.parentId));\n }\n }\n const updated = new Map(get(treeMap));\n recurseNodeUpwards(updated, updated.get(id));\n treeMap.set(updated);\n }\n };\n};\n","import type { Delta } from 'jsondiffpatch'\nimport type { TreeNode, ValueType } from 'svelte-tree-view'\n\n// function postprocessValue(value: any) {\n// if (value && value._t === 'a') {\n// const res: { [key: string]: string | string[] } = {}\n// for (const key in value) {\n// if (key !== '_t') {\n// if (key[0] === '_' && !value[key.substr(1)]) {\n// res[key.substr(1)] = value[key]\n// } else if (value['_' + key]) {\n// res[key] = [value['_' + key][0], value[key][0]]\n// } else if (!value['_' + key] && key[0] !== '_') {\n// res[key] = value[key]\n// }\n// }\n// }\n// return res\n// }\n// return value\n// }\n\nexport function mapSelectionDeltaChildren(\n _val: any,\n type: ValueType,\n _parent: TreeNode\n): [string, any][] | undefined {\n if (type !== 'array') return\n return []\n}\n\n/**\n * Magic function to transform jsondiffpatch array deltas\n * https://github.com/benjamine/jsondiffpatch/blob/master/docs/deltas.md\n * https://benjamine.github.io/jsondiffpatch/demo/index.html\n */\nexport function mapDocDeltaChildren(delta: Delta, type: ValueType) {\n // So due to the way the tree-view works, it will automatically map the children of an array\n // to their own nodes. For diff deltas, however, we want to omit those children and just show\n // a value wrapped with <span> to show either deleted or inserted content\n if (type === 'array' && delta[1] === 0 && delta[2] === 0) {\n // Remove operation is defined by two 0s in its delta [{ <deleted> }, 0, 0]\n return []\n // } else if (type === 'array' && typeof delta[0] === 'string' && typeof delta[1] === 'number' && delta[2] === 3) {\n // Move operation is almost the same as remove, except its value is empty and the second number\n // points to the moved index eg [\"\", 6, 3] AND the third value is always '3'\n // But since these seem to never occur (and they weren't handled in the previous version) we are not doing anything\n // with them for now.\n } else if (type === 'array' && typeof delta[0] === 'string' && delta[1] === 0 && delta[2] === 2) {\n // If a diff between two strings gets too long, a text diff algorithm is used which produces an array\n // with unidiff as the first value, 0 as the second and 2 as third.\n // Eg [\"@@ -1,4 +1,9 @@\\n-text\\n+paragraph\\n\", 0, 2]\n return []\n } else if (type === 'array' && delta.length === 1 && typeof delta[0] === 'object') {\n // Insert operations do not have indexes (it's already indexed in the array) and carry\n // only an object payload eg [{ <inserted> }]\n return []\n }\n\n // The main delta objects are objects denoted by key '_t' with 'a' value which we shall omit.\n // DiffValue component handles the text diffs otherwise.\n if (type !== 'object' || delta._t !== 'a') return\n\n // We shall remap the values to omit '_t' and remove underscores from the keys\n const transformed: [string, any][] = []\n for (const key in delta) {\n if (key === '_t') continue\n // Remove or move operation is indicated by an underscore before the index eg '_2'\n if (key.charAt(0) === '_') {\n transformed.push([key.substr(1), delta[key]])\n } else {\n transformed.push([key, delta[key]])\n }\n }\n return transformed\n}\n","import { Schema } from 'prosemirror-model'\n\nconst nodeColors = <const>[\n '#EA7C7F', // red\n '#67B0C6', // cyan 400\n '#94BB7F', // green\n '#CA9EDB', // deep purple\n '#DCDC5D', // lime\n '#B9CC7C', // light green\n '#DD97D8', // purple\n '#FFB761', // orange\n '#4D8FD1', // light blue\n '#F36E98', // pink\n '#E45F44', // deep orange\n '#A6A4AE', // blue grey\n '#FCC047', // yellow\n '#FFC129', // amber\n '#D3929C', // can can\n '#4CBCD4', // cyan\n '#8D7BC0' // indigo\n]\n\nexport function calculateSafeIndex(index: number, total: number) {\n const quotient = index / total\n return Math.round(total * (quotient - Math.floor(quotient)))\n}\n\nexport function buildColors(schema: Schema) {\n return Object.keys(schema.nodes).reduce(\n (acc, node, index) => {\n const safeIndex =\n index >= nodeColors.length ? calculateSafeIndex(index, nodeColors.length) : index\n\n acc[node] = nodeColors[safeIndex]\n return acc\n },\n {} as { [key: string]: (typeof nodeColors)[number] }\n )\n}\n","import type { EditorView } from 'prosemirror-view'\nimport type { Transaction } from 'prosemirror-state'\n\nimport { appendNewHistoryEntry } from '$stores/stateHistory'\n\nlet active = false,\n resetDispatch: (() => void) | undefined = undefined\n\n/**\n * Handler for dispatchTransaction that pushes trs to history and monkey patches applyTransaction\n *\n * Incase the editor already has a `dispatchTransaction` prop, oldDispatchFn is called but because\n * that function would also call state.apply we'd run apply multiple times, causing plugins to see\n * transactions often twice. So we monkey patch the `applyTransaction` method and apply some reflection\n * magic to maintain this-context as well as remove the patch if the transaction is somehow different\n * from the original.\n *\n * Why we have to monkey patch the method here and not once globally, is because the method is reset\n * to the original by ProseMirror at times so the function would not get called. Proxying `view.state.applyTransaction`\n * didn't also work.\n *\n * The other option is to use Plugins to store the transactions https://github.com/TeemuKoivisto/prosemirror-dev-toolkit/pull/15\n * which we'll revert to incase this one doesn't cover all the cases.\n * @param view\n * @param oldDispatchFn\n * @returns\n */\nconst handleDispatch =\n (view: EditorView, oldDispatchFn?: (tr: Transaction) => void) => (tr: Transaction) => {\n const stateBeforeDispatch = view.state\n const applied = view.state.applyTransaction(tr)\n if (oldDispatchFn) {\n const oldFn = view.state.applyTransaction.bind(view.state)\n view.state.applyTransaction = function (trr) {\n if (trr !== tr) {\n view.state.applyTransaction = oldFn\n return Reflect.apply(oldFn, view.state, arguments)\n }\n return applied\n }\n oldDispatchFn(tr)\n } else {\n view.updateState(applied.state)\n }\n // If a plugin filtered a transaction, this would be an empty array\n if (active && applied.transactions.length > 0) {\n appendNewHistoryEntry(applied.transactions, view.state, stateBeforeDispatch)\n }\n }\n\nexport function subscribeToDispatchTransaction(view: EditorView) {\n active = true\n // People at times do all kinds of crazy things with EditorView eg extending it with a custom class.\n // This can cause various bugs, for example it can override props setter. Because I don't get points from\n // being right I'll just save them from their own silliness by checking also private _props\n // @ts-ignore\n const oldDispatchFn = (view.props || view._props).dispatchTransaction?.bind(view)\n view.setProps({\n dispatchTransaction: handleDispatch(view, oldDispatchFn)\n })\n resetDispatch = () => view.setProps({ dispatchTransaction: oldDispatchFn })\n}\n\nexport function unsubscribeDispatchTransaction() {\n active = false\n resetDispatch && resetDispatch()\n resetDispatch = undefined\n}\n","const DEVTOOLS_CSS_CLASS = '__prosemirror-dev-toolkit__'\n\nexport function createOrFindPlace() {\n let place: HTMLElement | null = document.querySelector(`.${DEVTOOLS_CSS_CLASS}`)\n\n if (!place) {\n place = document.createElement('div')\n place.className = DEVTOOLS_CSS_CLASS\n document.body.appendChild(place)\n }\n\n return place\n}\n","import type { EditorView } from 'prosemirror-view'\nimport DevTools from './components/DevTools.svelte'\nimport type { SvelteComponent } from 'svelte'\n\nimport { DevToolsOpts } from './types'\n\n// Inspired by https://www.colorglare.com/svelte-components-as-web-components-b400d1253504\n// Using a web component allows toolkit to encapsulate its DOM and CSS styles without affecting\n// the site or being affected by its global stylesheets\nexport class ProseMirrorDevToolkit extends HTMLElement {\n private component?: SvelteComponent\n\n constructor() {\n super()\n const shadowRoot = this.attachShadow({ mode: 'open' })\n\n this.addEventListener('init-dev-toolkit', (event: Event) => {\n const {\n detail: { view, opts }\n } = event as CustomEvent<{ view: EditorView; opts: DevToolsOpts }>\n this.component = new DevTools({\n target: shadowRoot,\n props: {\n view,\n ...opts\n }\n })\n })\n }\n\n disconnectedCallback(): void {\n this.component?.$destroy()\n }\n}\n","import DevTools from './components/DevTools.svelte'\nimport {\n subscribeToDispatchTransaction,\n unsubscribeDispatchTransaction\n} from './history-and-diff/subscribeToTransactions'\nimport { resetHistory } from './stores/stateHistory'\n\nimport { createOrFindPlace } from './createOrFindPlace'\nimport { ProseMirrorDevToolkit } from './ProseMirrorDevToolkit'\n\nimport type { DevToolsOpts } from './types'\nimport type { Command } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\n\n// Register the fancy web component wrapper but don't crash if it's already defined\nif (!customElements.get('prosemirror-dev-toolkit')) {\n customElements.define('prosemirror-dev-toolkit', ProseMirrorDevToolkit)\n}\n\n// Make the dev tools available globally for testing and other use\nif (typeof window !== 'undefined') window.applyDevTools = applyDevTools\n\nlet removeCallback: (() => void) | undefined\n\n/**\n * Applies devTools to the given EditorView.\n *\n * Will remove previous devTools instance first, then subscribes to the view's\n * transactions by adding a dispatchTransaction prop. If previous dispatchTransaction\n * prop exists, passes the transaction to it. Otherwise updates the state as normal.\n * Will destroy itself whenever view is destroyed or removeDevTools() is called.\n * @param view\n * @param opts\n */\nexport function applyDevTools(view: EditorView, opts: DevToolsOpts = {}) {\n const place = createOrFindPlace()\n\n removeDevTools()\n\n // Sometimes when applyDevTools is run with hot module reload, it's accidentally executed on already destroyed EditorViews\n if (view.isDestroyed) return\n\n let comp: DevTools | undefined\n const { disableWebComponent, ...filteredOpts } = opts\n if (disableWebComponent) {\n // Mainly for testing purposes since shadow DOM quite annoyingly hides all of its contents in the test snapshots\n comp = new DevTools({\n target: place,\n props: {\n view,\n ...filteredOpts\n }\n })\n } else {\n const newTools = document.createElement('prosemirror-dev-toolkit')\n newTools.dispatchEvent(\n new CustomEvent('init-dev-toolkit', {\n detail: { view, opts: filteredOpts }\n })\n )\n place.appendChild(newTools)\n }\n\n if (typeof window !== 'undefined') {\n // Add editorView to the window for testing and debugging purposes\n window.editorView = view\n // Also a helper method to execute commands\n window.pmCmd = (cmd: Command) => {\n const state = view.state\n return cmd(state, view.dispatch, view)\n }\n }\n\n // Bind the component's life-cycle to the editorView to automatically unmount the devTools\n const oldDestroyFn = view.destroy.bind(view)\n view.destroy = () => {\n // DevTools must always be removed before view as the resetDispatch requires view to be still present\n removeDevTools()\n oldDestroyFn()\n }\n\n subscribeToDispatchTransaction(view)\n\n removeCallback = () => {\n resetHistory()\n unsubscribeDispatchTransaction()\n comp?.$destroy()\n const el = place.firstChild\n el && place.removeChild(el)\n }\n}\n\nexport function removeDevTools() {\n removeCallback && removeCallback()\n removeCallback = undefined\n}\n","export * from './CommandManager.js'\nexport * from './Editor.js'\nexport * from './Extension.js'\nexport * as extensions from './extensions/index.js'\nexport * from './helpers/index.js'\nexport * from './InputRule.js'\nexport * from './inputRules/index.js'\nexport { createElement, Fragment, createElement as h } from './jsx-runtime.js'\nexport * from './Mark.js'\nexport * from './MarkView.js'\nexport * from './Node.js'\nexport * from './NodePos.js'\nexport * from './NodeView.js'\nexport * from './PasteRule.js'\nexport * from './pasteRules/index.js'\nexport * from './Tracker.js'\nexport * from './types.js'\nexport * from './utilities/index.js'\n\n// eslint-disable-next-line\nexport interface Commands<ReturnType = any> {}\n\n// eslint-disable-next-line\nexport interface Storage {}\n","import type { EditorState, Transaction } from '@tiptap/pm/state'\n\n/**\n * Takes a Transaction & Editor State and turns it into a chainable state object\n * @param config The transaction and state to create the chainable state from\n * @returns A chainable Editor state object\n */\nexport function createChainableState(config: { transaction: Transaction; state: EditorState }): EditorState {\n const { state, transaction } = config\n let { selection } = transaction\n let { doc } = transaction\n let { storedMarks } = transaction\n\n return {\n ...state,\n apply: state.apply.bind(state),\n applyTransaction: state.applyTransaction.bind(state),\n plugins: state.plugins,\n schema: state.schema,\n reconfigure: state.reconfigure.bind(state),\n toJSON: state.toJSON.bind(state),\n get storedMarks() {\n return storedMarks\n },\n get selection() {\n return selection\n },\n get doc() {\n return doc\n },\n get tr() {\n selection = transaction.selection\n doc = transaction.doc\n storedMarks = transaction.storedMarks\n\n return transaction\n },\n }\n}\n","import type { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport type { AnyCommands, CanCommands, ChainedCommands, CommandProps, SingleCommands } from './types.js'\n\nexport class CommandManager {\n editor: Editor\n\n rawCommands: AnyCommands\n\n customState?: EditorState\n\n constructor(props: { editor: Editor; state?: EditorState }) {\n this.editor = props.editor\n this.rawCommands = this.editor.extensionManager.commands\n this.customState = props.state\n }\n\n get hasCustomState(): boolean {\n return !!this.customState\n }\n\n get state(): EditorState {\n return this.customState || this.editor.state\n }\n\n get commands(): SingleCommands {\n const { rawCommands, editor, state } = this\n const { view } = editor\n const { tr } = state\n const props = this.buildProps(tr)\n\n return Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n const method = (...args: any[]) => {\n const callback = command(...args)(props)\n\n if (!tr.getMeta('preventDispatch') && !this.hasCustomState) {\n view.dispatch(tr)\n }\n\n return callback\n }\n\n return [name, method]\n }),\n ) as unknown as SingleCommands\n }\n\n get chain(): () => ChainedCommands {\n return () => this.createChain()\n }\n\n get can(): () => CanCommands {\n return () => this.createCan()\n }\n\n public createChain(startTr?: Transaction, shouldDispatch = true): ChainedCommands {\n const { rawCommands, editor, state } = this\n const { view } = editor\n const callbacks: boolean[] = []\n const hasStartTransaction = !!startTr\n const tr = startTr || state.tr\n\n const run = () => {\n if (!hasStartTransaction && shouldDispatch && !tr.getMeta('preventDispatch') && !this.hasCustomState) {\n view.dispatch(tr)\n }\n\n return callbacks.every(callback => callback === true)\n }\n\n const chain = {\n ...Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n const chainedCommand = (...args: never[]) => {\n const props = this.buildProps(tr, shouldDispatch)\n const callback = command(...args)(props)\n\n callbacks.push(callback)\n\n return chain\n }\n\n return [name, chainedCommand]\n }),\n ),\n run,\n } as unknown as ChainedCommands\n\n return chain\n }\n\n public createCan(startTr?: Transaction): CanCommands {\n const { rawCommands, state } = this\n const dispatch = false\n const tr = startTr || state.tr\n const props = this.buildProps(tr, dispatch)\n const formattedCommands = Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n return [name, (...args: never[]) => command(...args)({ ...props, dispatch: undefined })]\n }),\n ) as unknown as SingleCommands\n\n return {\n ...formattedCommands,\n chain: () => this.createChain(tr, dispatch),\n } as CanCommands\n }\n\n public buildProps(tr: Transaction, shouldDispatch = true): CommandProps {\n const { rawCommands, editor, state } = this\n const { view } = editor\n\n const props: CommandProps = {\n tr,\n editor,\n view,\n state: createChainableState({\n state,\n transaction: tr,\n }),\n dispatch: shouldDispatch ? () => undefined : undefined,\n chain: () => this.createChain(tr, shouldDispatch),\n can: () => this.createCan(tr),\n get commands() {\n return Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n return [name, (...args: never[]) => command(...args)(props)]\n }),\n ) as unknown as SingleCommands\n },\n }\n\n return props\n }\n}\n","/* eslint-disable @typescript-eslint/no-empty-object-type */\nimport type { MarkType, Node as ProseMirrorNode, NodeType, Schema } from '@tiptap/pm/model'\nimport type { Plugin, PluginKey, Transaction } from '@tiptap/pm/state'\nimport { EditorState } from '@tiptap/pm/state'\nimport { EditorView } from '@tiptap/pm/view'\n\nimport { CommandManager } from './CommandManager.js'\nimport { EventEmitter } from './EventEmitter.js'\nimport { ExtensionManager } from './ExtensionManager.js'\nimport {\n ClipboardTextSerializer,\n Commands,\n Delete,\n Drop,\n Editable,\n FocusEvents,\n Keymap,\n Paste,\n Tabindex,\n} from './extensions/index.js'\nimport { createDocument } from './helpers/createDocument.js'\nimport { getAttributes } from './helpers/getAttributes.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport { getText } from './helpers/getText.js'\nimport { getTextSerializersFromSchema } from './helpers/getTextSerializersFromSchema.js'\nimport { isActive } from './helpers/isActive.js'\nimport { isNodeEmpty } from './helpers/isNodeEmpty.js'\nimport { resolveFocusPosition } from './helpers/resolveFocusPosition.js'\nimport type { Storage } from './index.js'\nimport { NodePos } from './NodePos.js'\nimport { style } from './style.js'\nimport type {\n CanCommands,\n ChainedCommands,\n DocumentType,\n EditorEvents,\n EditorOptions,\n NodeType as TNodeType,\n SingleCommands,\n TextSerializer,\n TextType as TTextType,\n} from './types.js'\nimport { createStyleTag } from './utilities/createStyleTag.js'\nimport { isFunction } from './utilities/isFunction.js'\n\nexport * as extensions from './extensions/index.js'\n\n// @ts-ignore\nexport interface TiptapEditorHTMLElement extends HTMLElement {\n editor?: Editor\n}\n\nexport class Editor extends EventEmitter<EditorEvents> {\n private commandManager!: CommandManager\n\n public extensionManager!: ExtensionManager\n\n private css: HTMLStyleElement | null = null\n\n public schema!: Schema\n\n private editorView: EditorView | null = null\n\n public isFocused = false\n\n private editorState!: EditorState\n\n /**\n * The editor is considered initialized after the `create` event has been emitted.\n */\n public isInitialized = false\n\n public extensionStorage: Storage = {} as Storage\n\n /**\n * A unique ID for this editor instance.\n */\n public instanceId = Math.random().toString(36).slice(2, 9)\n\n public options: EditorOptions = {\n element: typeof document !== 'undefined' ? document.createElement('div') : null,\n content: '',\n injectCSS: true,\n injectNonce: undefined,\n extensions: [],\n autofocus: false,\n editable: true,\n editorProps: {},\n parseOptions: {},\n coreExtensionOptions: {},\n enableInputRules: true,\n enablePasteRules: true,\n enableCoreExtensions: true,\n enableContentCheck: false,\n enableDevTools: false,\n emitContentError: false,\n onBeforeCreate: () => null,\n onCreate: () => null,\n onUpdate: () => null,\n onSelectionUpdate: () => null,\n onTransaction: () => null,\n onFocus: () => null,\n onBlur: () => null,\n onDestroy: () => null,\n onContentError: ({ error }) => {\n throw error\n },\n onPaste: () => null,\n onDrop: () => null,\n onDelete: () => null,\n }\n\n constructor(options: Partial<EditorOptions> = {}) {\n super()\n this.setOptions(options)\n this.createExtensionManager()\n this.createCommandManager()\n this.createSchema()\n this.on('beforeCreate', this.options.onBeforeCreate)\n this.emit('beforeCreate', { editor: this })\n this.on('contentError', this.options.onContentError)\n this.on('create', this.options.onCreate)\n this.on('update', this.options.onUpdate)\n this.on('selectionUpdate', this.options.onSelectionUpdate)\n this.on('transaction', this.options.onTransaction)\n this.on('focus', this.options.onFocus)\n this.on('blur', this.options.onBlur)\n this.on('destroy', this.options.onDestroy)\n this.on('drop', ({ event, slice, moved }) => this.options.onDrop(event, slice, moved))\n this.on('paste', ({ event, slice }) => this.options.onPaste(event, slice))\n this.on('delete', this.options.onDelete)\n\n const initialDoc = this.createDoc()\n const selection = resolveFocusPosition(initialDoc, this.options.autofocus)\n\n // Set editor state immediately, so that it's available independently from the view\n this.editorState = EditorState.create({\n doc: initialDoc,\n schema: this.schema,\n selection: selection || undefined,\n })\n\n if (this.options.element) {\n this.mount(this.options.element)\n }\n }\n\n /**\n * Attach the editor to the DOM, creating a new editor view.\n */\n public mount(el: NonNullable<EditorOptions['element']> & {}) {\n if (typeof document === 'undefined') {\n throw new Error(\n `[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.`,\n )\n }\n this.createView(el)\n\n window.setTimeout(() => {\n if (this.isDestroyed) {\n return\n }\n\n this.commands.focus(this.options.autofocus)\n this.emit('create', { editor: this })\n this.isInitialized = true\n }, 0)\n }\n\n /**\n * Remove the editor from the DOM, but still allow remounting at a different point in time\n */\n public unmount() {\n if (this.editorView) {\n // Cleanup our reference to prevent circular references which caused memory leaks\n // @ts-ignore\n const dom = this.editorView.dom as TiptapEditorHTMLElement\n\n if (dom?.editor) {\n delete dom.editor\n }\n this.editorView.destroy()\n }\n this.editorView = null\n this.isInitialized = false\n this.css?.remove()\n this.css = null\n }\n\n /**\n *\n * @returns\n */\n /**\n * Applies ProseMirror dev tools to the editor instance if enabled and running in a browser environment.\n *\n * This method dynamically imports the `prosemirror-dev-toolkit` package and applies it to the current\n * editor view. If the dev tools are not installed, a warning is logged to the console.\n *\n * @private\n * @remarks\n * - Dev tools are only applied if `this.options.enableDevTools` is `true` and the code is running in a browser.\n * - If the editor view is not available, the dev tools are not applied.\n * - If the `prosemirror-dev-toolkit` package is missing, a warning is shown in the console.\n *\n * @returns {void}\n */\n private applyDevTools(): void {\n if (typeof window === 'undefined' || !this.options.enableDevTools) {\n return\n }\n\n import('prosemirror-dev-toolkit')\n .then(({ applyDevTools }) => {\n if (!this.editorView) {\n return\n }\n\n applyDevTools(this.editorView)\n })\n .catch(() => {\n console.warn('[Tiptap warning]: Devtools are enabled but `prosemirror-dev-toolkit` is not installed.')\n console.warn(\"Install 'prosemirror-dev-toolkit' as a dev dependency to use the dev tools.\")\n })\n }\n\n /**\n * Returns the editor storage.\n */\n public get storage(): Storage {\n return this.extensionStorage\n }\n\n /**\n * An object of all registered commands.\n */\n public get commands(): SingleCommands {\n return this.commandManager.commands\n }\n\n /**\n * Create a command chain to call multiple commands at once.\n */\n public chain(): ChainedCommands {\n return this.commandManager.chain()\n }\n\n /**\n * Check if a command or a command chain can be executed. Without executing it.\n */\n public can(): CanCommands {\n return this.commandManager.can()\n }\n\n /**\n * Inject CSS styles.\n */\n private injectCSS(): void {\n if (this.options.injectCSS && typeof document !== 'undefined') {\n this.css = createStyleTag(style, this.options.injectNonce)\n }\n }\n\n /**\n * Update editor options.\n *\n * @param options A list of options\n */\n public setOptions(options: Partial<EditorOptions> = {}): void {\n this.options = {\n ...this.options,\n ...options,\n }\n\n if (!this.editorView || !this.state || this.isDestroyed) {\n return\n }\n\n if (this.options.editorProps) {\n this.view.setProps(this.options.editorProps)\n }\n\n this.view.updateState(this.state)\n }\n\n /**\n * Update editable state of the editor.\n */\n public setEditable(editable: boolean, emitUpdate = true): void {\n this.setOptions({ editable })\n\n if (emitUpdate) {\n this.emit('update', { editor: this, transaction: this.state.tr, appendedTransactions: [] })\n }\n }\n\n /**\n * Returns whether the editor is editable.\n */\n public get isEditable(): boolean {\n // since plugins are applied after creating the view\n // `editable` is always `true` for one tick.\n // that’s why we also have to check for `options.editable`\n return this.options.editable && this.view && this.view.editable\n }\n\n /**\n * Returns the editor state.\n */\n public get view(): EditorView {\n if (this.editorView) {\n return this.editorView\n }\n\n return new Proxy(\n {\n state: this.editorState,\n updateState: (state: EditorState): ReturnType<EditorView['updateState']> => {\n this.editorState = state\n },\n dispatch: (tr: Transaction): ReturnType<EditorView['dispatch']> => {\n this.editorState = this.state.apply(tr)\n },\n\n // Stub some commonly accessed properties to prevent errors\n composing: false,\n dragging: null,\n editable: true,\n isDestroyed: false,\n } as EditorView,\n {\n get: (obj, key) => {\n // Specifically always return the most recent editorState\n if (key === 'state') {\n return this.editorState\n }\n if (key in obj) {\n return Reflect.get(obj, key)\n }\n\n // We throw an error here, because we know the view is not available\n throw new Error(\n `[tiptap error]: The editor view is not available. Cannot access view['${key as string}']. The editor may not be mounted yet.`,\n )\n },\n },\n ) as EditorView\n }\n\n /**\n * Returns the editor state.\n */\n public get state(): EditorState {\n if (this.editorView) {\n this.editorState = this.view.state\n }\n\n return this.editorState\n }\n\n /**\n * Register a ProseMirror plugin.\n *\n * @param plugin A ProseMirror plugin\n * @param handlePlugins Control how to merge the plugin into the existing plugins.\n * @returns The new editor state\n */\n public registerPlugin(\n plugin: Plugin,\n handlePlugins?: (newPlugin: Plugin, plugins: Plugin[]) => Plugin[],\n ): EditorState {\n const plugins = isFunction(handlePlugins)\n ? handlePlugins(plugin, [...this.state.plugins])\n : [...this.state.plugins, plugin]\n\n const state = this.state.reconfigure({ plugins })\n\n this.view.updateState(state)\n\n return state\n }\n\n /**\n * Unregister a ProseMirror plugin.\n *\n * @param nameOrPluginKeyToRemove The plugins name\n * @returns The new editor state or undefined if the editor is destroyed\n */\n public unregisterPlugin(\n nameOrPluginKeyToRemove: string | PluginKey | (string | PluginKey)[],\n ): EditorState | undefined {\n if (this.isDestroyed) {\n return undefined\n }\n\n const prevPlugins = this.state.plugins\n let plugins = prevPlugins\n\n ;([] as (string | PluginKey)[]).concat(nameOrPluginKeyToRemove).forEach(nameOrPluginKey => {\n // @ts-ignore\n const name = typeof nameOrPluginKey === 'string' ? `${nameOrPluginKey}$` : nameOrPluginKey.key\n\n // @ts-ignore\n plugins = plugins.filter(plugin => !plugin.key.startsWith(name))\n })\n\n if (prevPlugins.length === plugins.length) {\n // No plugin was removed, so we don’t need to update the state\n return undefined\n }\n\n const state = this.state.reconfigure({\n plugins,\n })\n\n this.view.updateState(state)\n\n return state\n }\n\n /**\n * Creates an extension manager.\n */\n private createExtensionManager(): void {\n const coreExtensions = this.options.enableCoreExtensions\n ? [\n Editable,\n ClipboardTextSerializer.configure({\n blockSeparator: this.options.coreExtensionOptions?.clipboardTextSerializer?.blockSeparator,\n }),\n Commands,\n FocusEvents,\n Keymap,\n Tabindex,\n Drop,\n Paste,\n Delete,\n ].filter(ext => {\n if (typeof this.options.enableCoreExtensions === 'object') {\n return (\n this.options.enableCoreExtensions[ext.name as keyof typeof this.options.enableCoreExtensions] !== false\n )\n }\n return true\n })\n : []\n const allExtensions = [...coreExtensions, ...this.options.extensions].filter(extension => {\n return ['extension', 'node', 'mark'].includes(extension?.type)\n })\n\n this.extensionManager = new ExtensionManager(allExtensions, this)\n }\n\n /**\n * Creates an command manager.\n */\n private createCommandManager(): void {\n this.commandManager = new CommandManager({\n editor: this,\n })\n }\n\n /**\n * Creates a ProseMirror schema.\n */\n private createSchema(): void {\n this.schema = this.extensionManager.schema\n }\n\n /**\n * Creates the initial document.\n */\n private createDoc(): ProseMirrorNode {\n let doc: ProseMirrorNode\n\n try {\n doc = createDocument(this.options.content, this.schema, this.options.parseOptions, {\n errorOnInvalidContent: this.options.enableContentCheck,\n })\n } catch (e) {\n if (\n !(e instanceof Error) ||\n !['[tiptap error]: Invalid JSON content', '[tiptap error]: Invalid HTML content'].includes(e.message)\n ) {\n // Not the content error we were expecting\n throw e\n }\n this.emit('contentError', {\n editor: this,\n error: e as Error,\n disableCollaboration: () => {\n if (\n 'collaboration' in this.storage &&\n typeof this.storage.collaboration === 'object' &&\n this.storage.collaboration\n ) {\n ;(this.storage.collaboration as any).isDisabled = true\n }\n // To avoid syncing back invalid content, reinitialize the extensions without the collaboration extension\n this.options.extensions = this.options.extensions.filter(extension => extension.name !== 'collaboration')\n\n // Restart the initialization process by recreating the extension manager with the new set of extensions\n this.createExtensionManager()\n },\n })\n\n // Content is invalid, but attempt to create it anyway, stripping out the invalid parts\n doc = createDocument(this.options.content, this.schema, this.options.parseOptions, {\n errorOnInvalidContent: false,\n })\n }\n return doc\n }\n\n /**\n * Creates a ProseMirror view.\n */\n private createView(element: NonNullable<EditorOptions['element']> & {}): void {\n this.editorView = new EditorView(element, {\n ...this.options.editorProps,\n attributes: {\n // add `role=\"textbox\"` to the editor element\n role: 'textbox',\n ...this.options.editorProps?.attributes,\n },\n dispatchTransaction: this.dispatchTransaction.bind(this),\n state: this.editorState,\n })\n\n // Apply dev tools if enabled\n if (this.options.enableDevTools) {\n this.applyDevTools()\n }\n\n // `editor.view` is not yet available at this time.\n // Therefore we will add all plugins and node views directly afterwards.\n const newState = this.state.reconfigure({\n plugins: this.extensionManager.plugins,\n })\n\n this.view.updateState(newState)\n\n this.createNodeViews()\n this.prependClass()\n this.injectCSS()\n\n // Let’s store the editor instance in the DOM element.\n // So we’ll have access to it for tests.\n // @ts-ignore\n const dom = this.view.dom as TiptapEditorHTMLElement\n\n dom.editor = this\n }\n\n /**\n * Creates all node and mark views.\n */\n public createNodeViews(): void {\n if (this.view.isDestroyed) {\n return\n }\n\n this.view.setProps({\n markViews: this.extensionManager.markViews,\n nodeViews: this.extensionManager.nodeViews,\n })\n }\n\n /**\n * Prepend class name to element.\n */\n public prependClass(): void {\n this.view.dom.className = `tiptap ${this.view.dom.className}`\n }\n\n public isCapturingTransaction = false\n\n private capturedTransaction: Transaction | null = null\n\n public captureTransaction(fn: () => void) {\n this.isCapturingTransaction = true\n fn()\n this.isCapturingTransaction = false\n\n const tr = this.capturedTransaction\n\n this.capturedTransaction = null\n\n return tr\n }\n\n /**\n * The callback over which to send transactions (state updates) produced by the view.\n *\n * @param transaction An editor state transaction\n */\n private dispatchTransaction(transaction: Transaction): void {\n // if the editor / the view of the editor was destroyed\n // the transaction should not be dispatched as there is no view anymore.\n if (this.view.isDestroyed) {\n return\n }\n\n if (this.isCapturingTransaction) {\n if (!this.capturedTransaction) {\n this.capturedTransaction = transaction\n\n return\n }\n\n transaction.steps.forEach(step => this.capturedTransaction?.step(step))\n\n return\n }\n\n // Apply transaction and get resulting state and transactions\n const { state, transactions } = this.state.applyTransaction(transaction)\n const selectionHasChanged = !this.state.selection.eq(state.selection)\n const rootTrWasApplied = transactions.includes(transaction)\n const prevState = this.state\n\n this.emit('beforeTransaction', {\n editor: this,\n transaction,\n nextState: state,\n })\n\n // If transaction was filtered out, we can return early\n if (!rootTrWasApplied) {\n return\n }\n\n this.view.updateState(state)\n\n // Emit transaction event with appended transactions info\n this.emit('transaction', {\n editor: this,\n transaction,\n appendedTransactions: transactions.slice(1),\n })\n\n if (selectionHasChanged) {\n this.emit('selectionUpdate', {\n editor: this,\n transaction,\n })\n }\n\n // Only emit the latest between focus and blur events\n const mostRecentFocusTr = transactions.findLast(tr => tr.getMeta('focus') || tr.getMeta('blur'))\n const focus = mostRecentFocusTr?.getMeta('focus')\n const blur = mostRecentFocusTr?.getMeta('blur')\n\n if (focus) {\n this.emit('focus', {\n editor: this,\n event: focus.event,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n transaction: mostRecentFocusTr!,\n })\n }\n\n if (blur) {\n this.emit('blur', {\n editor: this,\n event: blur.event,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n transaction: mostRecentFocusTr!,\n })\n }\n\n // Compare states for update event\n if (\n transaction.getMeta('preventUpdate') ||\n !transactions.some(tr => tr.docChanged) ||\n prevState.doc.eq(state.doc)\n ) {\n return\n }\n\n this.emit('update', {\n editor: this,\n transaction,\n appendedTransactions: transactions.slice(1),\n })\n }\n\n /**\n * Get attributes of the currently selected node or mark.\n */\n public getAttributes(nameOrType: string | NodeType | MarkType): Record<string, any> {\n return getAttributes(this.state, nameOrType)\n }\n\n /**\n * Returns if the currently selected node or mark is active.\n *\n * @param name Name of the node or mark\n * @param attributes Attributes of the node or mark\n */\n public isActive(name: string, attributes?: {}): boolean\n public isActive(attributes: {}): boolean\n public isActive(nameOrAttributes: string, attributesOrUndefined?: {}): boolean {\n const name = typeof nameOrAttributes === 'string' ? nameOrAttributes : null\n\n const attributes = typeof nameOrAttributes === 'string' ? attributesOrUndefined : nameOrAttributes\n\n return isActive(this.state, name, attributes)\n }\n\n /**\n * Get the document as JSON.\n */\n public getJSON(): DocumentType<\n Record<string, any> | undefined,\n TNodeType<string, undefined | Record<string, any>, any, (TNodeType | TTextType)[]>[]\n > {\n return this.state.doc.toJSON()\n }\n\n /**\n * Get the document as HTML.\n */\n public getHTML(): string {\n return getHTMLFromFragment(this.state.doc.content, this.schema)\n }\n\n /**\n * Get the document as text.\n */\n public getText(options?: { blockSeparator?: string; textSerializers?: Record<string, TextSerializer> }): string {\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n\n return getText(this.state.doc, {\n blockSeparator,\n textSerializers: {\n ...getTextSerializersFromSchema(this.schema),\n ...textSerializers,\n },\n })\n }\n\n /**\n * Check if there is no content.\n */\n public get isEmpty(): boolean {\n return isNodeEmpty(this.state.doc)\n }\n\n /**\n * Destroy the editor.\n */\n public destroy(): void {\n this.emit('destroy')\n\n this.unmount()\n\n this.removeAllListeners()\n }\n\n /**\n * Check if the editor is already destroyed.\n */\n public get isDestroyed(): boolean {\n return this.editorView?.isDestroyed ?? true\n }\n\n public $node(selector: string, attributes?: { [key: string]: any }): NodePos | null {\n return this.$doc?.querySelector(selector, attributes) || null\n }\n\n public $nodes(selector: string, attributes?: { [key: string]: any }): NodePos[] | null {\n return this.$doc?.querySelectorAll(selector, attributes) || null\n }\n\n public $pos(pos: number) {\n const $pos = this.state.doc.resolve(pos)\n\n return new NodePos($pos, this)\n }\n\n get $doc() {\n return this.$pos(0)\n }\n}\n","type StringKeyOf<T> = Extract<keyof T, string>\ntype CallbackType<T extends Record<string, any>, EventName extends StringKeyOf<T>> = T[EventName] extends any[]\n ? T[EventName]\n : [T[EventName]]\ntype CallbackFunction<T extends Record<string, any>, EventName extends StringKeyOf<T>> = (\n ...props: CallbackType<T, EventName>\n) => any\n\nexport class EventEmitter<T extends Record<string, any>> {\n private callbacks: { [key: string]: Array<(...args: any[]) => void> } = {}\n\n public on<EventName extends StringKeyOf<T>>(event: EventName, fn: CallbackFunction<T, EventName>): this {\n if (!this.callbacks[event]) {\n this.callbacks[event] = []\n }\n\n this.callbacks[event].push(fn)\n\n return this\n }\n\n public emit<EventName extends StringKeyOf<T>>(event: EventName, ...args: CallbackType<T, EventName>): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n callbacks.forEach(callback => callback.apply(this, args))\n }\n\n return this\n }\n\n public off<EventName extends StringKeyOf<T>>(event: EventName, fn?: CallbackFunction<T, EventName>): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n if (fn) {\n this.callbacks[event] = callbacks.filter(callback => callback !== fn)\n } else {\n delete this.callbacks[event]\n }\n }\n\n return this\n }\n\n public once<EventName extends StringKeyOf<T>>(event: EventName, fn: CallbackFunction<T, EventName>): this {\n const onceFn = (...args: CallbackType<T, EventName>) => {\n this.off(event, onceFn)\n fn.apply(this, args)\n }\n\n return this.on(event, onceFn)\n }\n\n public removeAllListeners(): void {\n this.callbacks = {}\n }\n}\n","import { keymap } from '@tiptap/pm/keymap'\nimport type { Schema } from '@tiptap/pm/model'\nimport type { Plugin } from '@tiptap/pm/state'\nimport type { MarkViewConstructor, NodeViewConstructor } from '@tiptap/pm/view'\n\nimport type { Editor } from './Editor.js'\nimport {\n flattenExtensions,\n getAttributesFromExtensions,\n getExtensionField,\n getNodeType,\n getRenderedAttributes,\n getSchemaByResolvedExtensions,\n getSchemaTypeByName,\n isExtensionRulesEnabled,\n resolveExtensions,\n sortExtensions,\n splitExtensions,\n} from './helpers/index.js'\nimport { type MarkConfig, type NodeConfig, type Storage, getMarkType, updateMarkViewAttributes } from './index.js'\nimport type { InputRule } from './InputRule.js'\nimport { inputRulesPlugin } from './InputRule.js'\nimport { Mark } from './Mark.js'\nimport type { PasteRule } from './PasteRule.js'\nimport { pasteRulesPlugin } from './PasteRule.js'\nimport type { AnyConfig, Extensions, RawCommands } from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\n\nexport class ExtensionManager {\n editor: Editor\n\n schema: Schema\n\n extensions: Extensions\n\n splittableMarks: string[] = []\n\n constructor(extensions: Extensions, editor: Editor) {\n this.editor = editor\n this.extensions = resolveExtensions(extensions)\n this.schema = getSchemaByResolvedExtensions(this.extensions, editor)\n this.setupExtensions()\n }\n\n static resolve = resolveExtensions\n\n static sort = sortExtensions\n\n static flatten = flattenExtensions\n\n /**\n * Get all commands from the extensions.\n * @returns An object with all commands where the key is the command name and the value is the command function\n */\n get commands(): RawCommands {\n return this.extensions.reduce((commands, extension) => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor: this.editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n const addCommands = getExtensionField<AnyConfig['addCommands']>(extension, 'addCommands', context)\n\n if (!addCommands) {\n return commands\n }\n\n return {\n ...commands,\n ...addCommands(),\n }\n }, {} as RawCommands)\n }\n\n /**\n * Get all registered Prosemirror plugins from the extensions.\n * @returns An array of Prosemirror plugins\n */\n get plugins(): Plugin[] {\n const { editor } = this\n\n // With ProseMirror, first plugins within an array are executed first.\n // In Tiptap, we provide the ability to override plugins,\n // so it feels more natural to run plugins at the end of an array first.\n // That’s why we have to reverse the `extensions` array and sort again\n // based on the `priority` option.\n const extensions = sortExtensions([...this.extensions].reverse())\n\n const inputRules: InputRule[] = []\n const pasteRules: PasteRule[] = []\n\n const allPlugins = extensions\n .map(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n const plugins: Plugin[] = []\n\n const addKeyboardShortcuts = getExtensionField<AnyConfig['addKeyboardShortcuts']>(\n extension,\n 'addKeyboardShortcuts',\n context,\n )\n\n let defaultBindings: Record<string, () => boolean> = {}\n\n // bind exit handling\n if (extension.type === 'mark' && getExtensionField<MarkConfig['exitable']>(extension, 'exitable', context)) {\n defaultBindings.ArrowRight = () => Mark.handleExit({ editor, mark: extension as Mark })\n }\n\n if (addKeyboardShortcuts) {\n const bindings = Object.fromEntries(\n Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => {\n return [shortcut, () => method({ editor })]\n }),\n )\n\n defaultBindings = { ...defaultBindings, ...bindings }\n }\n\n const keyMapPlugin = keymap(defaultBindings)\n\n plugins.push(keyMapPlugin)\n\n const addInputRules = getExtensionField<AnyConfig['addInputRules']>(extension, 'addInputRules', context)\n\n if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) {\n inputRules.push(...addInputRules())\n }\n\n const addPasteRules = getExtensionField<AnyConfig['addPasteRules']>(extension, 'addPasteRules', context)\n\n if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) {\n pasteRules.push(...addPasteRules())\n }\n\n const addProseMirrorPlugins = getExtensionField<AnyConfig['addProseMirrorPlugins']>(\n extension,\n 'addProseMirrorPlugins',\n context,\n )\n\n if (addProseMirrorPlugins) {\n const proseMirrorPlugins = addProseMirrorPlugins()\n\n plugins.push(...proseMirrorPlugins)\n }\n\n return plugins\n })\n .flat()\n\n return [\n inputRulesPlugin({\n editor,\n rules: inputRules,\n }),\n ...pasteRulesPlugin({\n editor,\n rules: pasteRules,\n }),\n ...allPlugins,\n ]\n }\n\n /**\n * Get all attributes from the extensions.\n * @returns An array of attributes\n */\n get attributes() {\n return getAttributesFromExtensions(this.extensions)\n }\n\n /**\n * Get all node views from the extensions.\n * @returns An object with all node views where the key is the node name and the value is the node view function\n */\n get nodeViews(): Record<string, NodeViewConstructor> {\n const { editor } = this\n const { nodeExtensions } = splitExtensions(this.extensions)\n\n return Object.fromEntries(\n nodeExtensions\n .filter(extension => !!getExtensionField(extension, 'addNodeView'))\n .map(extension => {\n const extensionAttributes = this.attributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getNodeType(extension.name, this.schema),\n }\n const addNodeView = getExtensionField<NodeConfig['addNodeView']>(extension, 'addNodeView', context)\n\n if (!addNodeView) {\n return []\n }\n\n const nodeview: NodeViewConstructor = (node, view, getPos, decorations, innerDecorations) => {\n const HTMLAttributes = getRenderedAttributes(node, extensionAttributes)\n\n return addNodeView()({\n // pass-through\n node,\n view,\n getPos: getPos as () => number,\n decorations,\n innerDecorations,\n // tiptap-specific\n editor,\n extension,\n HTMLAttributes,\n })\n }\n\n return [extension.name, nodeview]\n }),\n )\n }\n\n get markViews(): Record<string, MarkViewConstructor> {\n const { editor } = this\n const { markExtensions } = splitExtensions(this.extensions)\n\n return Object.fromEntries(\n markExtensions\n .filter(extension => !!getExtensionField(extension, 'addMarkView'))\n .map(extension => {\n const extensionAttributes = this.attributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getMarkType(extension.name, this.schema),\n }\n const addMarkView = getExtensionField<MarkConfig['addMarkView']>(extension, 'addMarkView', context)\n\n if (!addMarkView) {\n return []\n }\n\n const markView: MarkViewConstructor = (mark, view, inline) => {\n const HTMLAttributes = getRenderedAttributes(mark, extensionAttributes)\n\n return addMarkView()({\n // pass-through\n mark,\n view,\n inline,\n // tiptap-specific\n editor,\n extension,\n HTMLAttributes,\n updateAttributes: (attrs: Record<string, any>) => {\n updateMarkViewAttributes(mark, editor, attrs)\n },\n })\n }\n\n return [extension.name, markView]\n }),\n )\n }\n\n /**\n * Go through all extensions, create extension storages & setup marks\n * & bind editor event listener.\n */\n private setupExtensions() {\n const extensions = this.extensions\n // re-initialize the extension storage object instance\n this.editor.extensionStorage = Object.fromEntries(\n extensions.map(extension => [extension.name, extension.storage]),\n ) as unknown as Storage\n\n extensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor: this.editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n if (extension.type === 'mark') {\n const keepOnSplit = callOrReturn(getExtensionField(extension, 'keepOnSplit', context)) ?? true\n\n if (keepOnSplit) {\n this.splittableMarks.push(extension.name)\n }\n }\n\n const onBeforeCreate = getExtensionField<AnyConfig['onBeforeCreate']>(extension, 'onBeforeCreate', context)\n const onCreate = getExtensionField<AnyConfig['onCreate']>(extension, 'onCreate', context)\n const onUpdate = getExtensionField<AnyConfig['onUpdate']>(extension, 'onUpdate', context)\n const onSelectionUpdate = getExtensionField<AnyConfig['onSelectionUpdate']>(\n extension,\n 'onSelectionUpdate',\n context,\n )\n const onTransaction = getExtensionField<AnyConfig['onTransaction']>(extension, 'onTransaction', context)\n const onFocus = getExtensionField<AnyConfig['onFocus']>(extension, 'onFocus', context)\n const onBlur = getExtensionField<AnyConfig['onBlur']>(extension, 'onBlur', context)\n const onDestroy = getExtensionField<AnyConfig['onDestroy']>(extension, 'onDestroy', context)\n\n if (onBeforeCreate) {\n this.editor.on('beforeCreate', onBeforeCreate)\n }\n\n if (onCreate) {\n this.editor.on('create', onCreate)\n }\n\n if (onUpdate) {\n this.editor.on('update', onUpdate)\n }\n\n if (onSelectionUpdate) {\n this.editor.on('selectionUpdate', onSelectionUpdate)\n }\n\n if (onTransaction) {\n this.editor.on('transaction', onTransaction)\n }\n\n if (onFocus) {\n this.editor.on('focus', onFocus)\n }\n\n if (onBlur) {\n this.editor.on('blur', onBlur)\n }\n\n if (onDestroy) {\n this.editor.on('destroy', onDestroy)\n }\n })\n }\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport type { Transaction } from '@tiptap/pm/state'\nimport { Transform } from '@tiptap/pm/transform'\n\n/**\n * Returns a new `Transform` based on all steps of the passed transactions.\n * @param oldDoc The Prosemirror node to start from\n * @param transactions The transactions to combine\n * @returns A new `Transform` with all steps of the passed transactions\n */\nexport function combineTransactionSteps(oldDoc: ProseMirrorNode, transactions: Transaction[]): Transform {\n const transform = new Transform(oldDoc)\n\n transactions.forEach(transaction => {\n transaction.steps.forEach(step => {\n transform.step(step)\n })\n })\n\n return transform\n}\n","import type { ParseOptions } from '@tiptap/pm/model'\nimport { DOMParser, Fragment, Node as ProseMirrorNode, Schema } from '@tiptap/pm/model'\n\nimport type { Content } from '../types.js'\nimport { elementFromString } from '../utilities/elementFromString.js'\n\nexport type CreateNodeFromContentOptions = {\n slice?: boolean\n parseOptions?: ParseOptions\n errorOnInvalidContent?: boolean\n}\n\n/**\n * Takes a JSON or HTML content and creates a Prosemirror node or fragment from it.\n * @param content The JSON or HTML content to create the node from\n * @param schema The Prosemirror schema to use for the node\n * @param options Options for the parser\n * @returns The created Prosemirror node or fragment\n */\nexport function createNodeFromContent(\n content: Content | ProseMirrorNode | Fragment,\n schema: Schema,\n options?: CreateNodeFromContentOptions,\n): ProseMirrorNode | Fragment {\n if (content instanceof ProseMirrorNode || content instanceof Fragment) {\n return content\n }\n options = {\n slice: true,\n parseOptions: {},\n ...options,\n }\n\n const isJSONContent = typeof content === 'object' && content !== null\n const isTextContent = typeof content === 'string'\n\n if (isJSONContent) {\n try {\n const isArrayContent = Array.isArray(content) && content.length > 0\n\n // if the JSON Content is an array of nodes, create a fragment for each node\n if (isArrayContent) {\n return Fragment.fromArray(content.map(item => schema.nodeFromJSON(item)))\n }\n\n const node = schema.nodeFromJSON(content)\n\n if (options.errorOnInvalidContent) {\n node.check()\n }\n\n return node\n } catch (error) {\n if (options.errorOnInvalidContent) {\n throw new Error('[tiptap error]: Invalid JSON content', { cause: error as Error })\n }\n\n console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error)\n\n return createNodeFromContent('', schema, options)\n }\n }\n\n if (isTextContent) {\n // Check for invalid content\n if (options.errorOnInvalidContent) {\n let hasInvalidContent = false\n let invalidContent = ''\n\n // A copy of the current schema with a catch-all node at the end\n const contentCheckSchema = new Schema({\n topNode: schema.spec.topNode,\n marks: schema.spec.marks,\n // Prosemirror's schemas are executed such that: the last to execute, matches last\n // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle\n nodes: schema.spec.nodes.append({\n __tiptap__private__unknown__catch__all__node: {\n content: 'inline*',\n group: 'block',\n parseDOM: [\n {\n tag: '*',\n getAttrs: e => {\n // If this is ever called, we know that the content has something that we don't know how to handle in the schema\n hasInvalidContent = true\n // Try to stringify the element for a more helpful error message\n invalidContent = typeof e === 'string' ? e : e.outerHTML\n return null\n },\n },\n ],\n },\n }),\n })\n\n if (options.slice) {\n DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions)\n } else {\n DOMParser.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions)\n }\n\n if (options.errorOnInvalidContent && hasInvalidContent) {\n throw new Error('[tiptap error]: Invalid HTML content', {\n cause: new Error(`Invalid element found: ${invalidContent}`),\n })\n }\n }\n\n const parser = DOMParser.fromSchema(schema)\n\n if (options.slice) {\n return parser.parseSlice(elementFromString(content), options.parseOptions).content\n }\n\n return parser.parse(elementFromString(content), options.parseOptions)\n }\n\n return createNodeFromContent('', schema, options)\n}\n","const removeWhitespaces = (node: HTMLElement) => {\n const children = node.childNodes\n\n for (let i = children.length - 1; i >= 0; i -= 1) {\n const child = children[i]\n\n if (child.nodeType === 3 && child.nodeValue && /^(\\n\\s\\s|\\n)$/.test(child.nodeValue)) {\n node.removeChild(child)\n } else if (child.nodeType === 1) {\n removeWhitespaces(child as HTMLElement)\n }\n }\n\n return node\n}\n\nexport function elementFromString(value: string): HTMLElement {\n if (typeof window === 'undefined') {\n throw new Error('[tiptap error]: there is no window object available, so this function cannot be used')\n }\n // add a wrapper to preserve leading and trailing whitespace\n const wrappedValue = `<body>${value}</body>`\n\n const html = new window.DOMParser().parseFromString(wrappedValue, 'text/html').body\n\n return removeWhitespaces(html)\n}\n","import type { Fragment, Node as ProseMirrorNode, ParseOptions, Schema } from '@tiptap/pm/model'\n\nimport type { Content } from '../types.js'\nimport { createNodeFromContent } from './createNodeFromContent.js'\n\n/**\n * Create a new Prosemirror document node from content.\n * @param content The JSON or HTML content to create the document from\n * @param schema The Prosemirror schema to use for the document\n * @param parseOptions Options for the parser\n * @returns The created Prosemirror document node\n */\nexport function createDocument(\n content: Content | ProseMirrorNode | Fragment,\n schema: Schema,\n parseOptions: ParseOptions = {},\n options: { errorOnInvalidContent?: boolean } = {},\n): ProseMirrorNode {\n return createNodeFromContent(content, schema, {\n slice: false,\n parseOptions,\n errorOnInvalidContent: options.errorOnInvalidContent,\n }) as ProseMirrorNode\n}\n","import type { ContentMatch, NodeType } from '@tiptap/pm/model'\n\n/**\n * Gets the default block type at a given match\n * @param match The content match to get the default block type from\n * @returns The default block type or null\n */\nexport function defaultBlockAt(match: ContentMatch): NodeType | null {\n for (let i = 0; i < match.edgeCount; i += 1) {\n const { type } = match.edge(i)\n\n if (type.isTextblock && !type.hasRequiredAttrs()) {\n return type\n }\n }\n\n return null\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { NodeWithPos, Predicate } from '../types.js'\n\n/**\n * Find children inside a Prosemirror node that match a predicate.\n * @param node The Prosemirror node to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nexport function findChildren(node: ProseMirrorNode, predicate: Predicate): NodeWithPos[] {\n const nodesWithPos: NodeWithPos[] = []\n\n node.descendants((child, pos) => {\n if (predicate(child)) {\n nodesWithPos.push({\n node: child,\n pos,\n })\n }\n })\n\n return nodesWithPos\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { NodeWithPos, Predicate, Range } from '../types.js'\n\n/**\n * Same as `findChildren` but searches only within a `range`.\n * @param node The Prosemirror node to search in\n * @param range The range to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nexport function findChildrenInRange(node: ProseMirrorNode, range: Range, predicate: Predicate): NodeWithPos[] {\n const nodesWithPos: NodeWithPos[] = []\n\n // if (range.from === range.to) {\n // const nodeAt = node.nodeAt(range.from)\n\n // if (nodeAt) {\n // nodesWithPos.push({\n // node: nodeAt,\n // pos: range.from,\n // })\n // }\n // }\n\n node.nodesBetween(range.from, range.to, (child, pos) => {\n if (predicate(child)) {\n nodesWithPos.push({\n node: child,\n pos,\n })\n }\n })\n\n return nodesWithPos\n}\n","import type { Node as ProseMirrorNode, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Predicate } from '../types.js'\n\n/**\n * Finds the closest parent node to a resolved position that matches a predicate.\n * @param $pos The resolved position to search from\n * @param predicate The predicate to match\n * @returns The closest parent node to the resolved position that matches the predicate\n * @example ```js\n * findParentNodeClosestToPos($from, node => node.type.name === 'paragraph')\n * ```\n */\nexport function findParentNodeClosestToPos(\n $pos: ResolvedPos,\n predicate: Predicate,\n):\n | {\n pos: number\n start: number\n depth: number\n node: ProseMirrorNode\n }\n | undefined {\n for (let i = $pos.depth; i > 0; i -= 1) {\n const node = $pos.node(i)\n\n if (predicate(node)) {\n return {\n pos: i > 0 ? $pos.before(i) : 0,\n start: $pos.start(i),\n depth: i,\n node,\n }\n }\n }\n}\n","import type { Selection } from '@tiptap/pm/state'\n\nimport type { Predicate } from '../types.js'\nimport { findParentNodeClosestToPos } from './findParentNodeClosestToPos.js'\n\n/**\n * Finds the closest parent node to the current selection that matches a predicate.\n * @param predicate The predicate to match\n * @returns A command that finds the closest parent node to the current selection that matches the predicate\n * @example ```js\n * findParentNode(node => node.type.name === 'paragraph')\n * ```\n */\nexport function findParentNode(\n predicate: Predicate,\n): (selection: Selection) => ReturnType<typeof findParentNodeClosestToPos> {\n return (selection: Selection) => findParentNodeClosestToPos(selection.$from, predicate)\n}\n","import type { ExtensionConfig } from '../Extension.js'\nimport type { MarkConfig } from '../Mark.js'\nimport type { NodeConfig } from '../Node.js'\nimport type { AnyExtension, MaybeThisParameterType, RemoveThis } from '../types.js'\n\n/**\n * Returns a field from an extension\n * @param extension The Tiptap extension\n * @param field The field, for example `renderHTML` or `priority`\n * @param context The context object that should be passed as `this` into the function\n * @returns The field value\n */\nexport function getExtensionField<T = any, E extends AnyExtension = any>(\n extension: E,\n field: keyof ExtensionConfig | keyof MarkConfig | keyof NodeConfig,\n context?: Omit<MaybeThisParameterType<T>, 'parent'>,\n): RemoveThis<T> {\n if (extension.config[field as keyof typeof extension.config] === undefined && extension.parent) {\n return getExtensionField(extension.parent, field, context)\n }\n\n if (typeof extension.config[field as keyof typeof extension.config] === 'function') {\n const value = (extension.config[field as keyof typeof extension.config] as any).bind({\n ...context,\n parent: extension.parent ? getExtensionField(extension.parent, field, context) : null,\n })\n\n return value\n }\n\n return extension.config[field as keyof typeof extension.config] as RemoveThis<T>\n}\n","import type { AnyConfig, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\n\n/**\n * Create a flattened array of extensions by traversing the `addExtensions` field.\n * @param extensions An array of Tiptap extensions\n * @returns A flattened array of Tiptap extensions\n */\nexport function flattenExtensions(extensions: Extensions): Extensions {\n return (\n extensions\n .map(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n }\n\n const addExtensions = getExtensionField<AnyConfig['addExtensions']>(extension, 'addExtensions', context)\n\n if (addExtensions) {\n return [extension, ...flattenExtensions(addExtensions())]\n }\n\n return extension\n })\n // `Infinity` will break TypeScript so we set a number that is probably high enough\n .flat(10)\n )\n}\n","import { Node } from '@tiptap/pm/model'\n\nimport type { Extensions, JSONContent } from '../types.js'\nimport { getHTMLFromFragment } from './getHTMLFromFragment.js'\nimport { getSchema } from './getSchema.js'\n\n/**\n * Generate HTML from a JSONContent\n * @param doc The JSONContent to generate HTML from\n * @param extensions The extensions to use for the schema\n * @returns The generated HTML\n */\nexport function generateHTML(doc: JSONContent, extensions: Extensions): string {\n const schema = getSchema(extensions)\n const contentNode = Node.fromJSON(schema, doc)\n\n return getHTMLFromFragment(contentNode.content, schema)\n}\n","import type { Fragment, Schema } from '@tiptap/pm/model'\nimport { DOMSerializer } from '@tiptap/pm/model'\n\nexport function getHTMLFromFragment(fragment: Fragment, schema: Schema): string {\n const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment)\n\n const temporaryDocument = document.implementation.createHTMLDocument()\n const container = temporaryDocument.createElement('div')\n\n container.appendChild(documentFragment)\n\n return container.innerHTML\n}\n","import type { MarkSpec, NodeSpec, TagParseRule } from '@tiptap/pm/model'\nimport { Schema } from '@tiptap/pm/model'\n\nimport type { Editor, MarkConfig, NodeConfig } from '../index.js'\nimport type { AnyConfig, Extensions } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\nimport { isEmptyObject } from '../utilities/isEmptyObject.js'\nimport { getAttributesFromExtensions } from './getAttributesFromExtensions.js'\nimport { getExtensionField } from './getExtensionField.js'\nimport { getRenderedAttributes } from './getRenderedAttributes.js'\nimport { injectExtensionAttributesToParseRule } from './injectExtensionAttributesToParseRule.js'\nimport { splitExtensions } from './splitExtensions.js'\n\nfunction cleanUpSchemaItem<T>(data: T) {\n return Object.fromEntries(\n // @ts-ignore\n Object.entries(data).filter(([key, value]) => {\n if (key === 'attrs' && isEmptyObject(value as object | undefined)) {\n return false\n }\n\n return value !== null && value !== undefined\n }),\n ) as T\n}\n\n/**\n * Creates a new Prosemirror schema based on the given extensions.\n * @param extensions An array of Tiptap extensions\n * @param editor The editor instance\n * @returns A Prosemirror schema\n */\nexport function getSchemaByResolvedExtensions(extensions: Extensions, editor?: Editor): Schema {\n const allAttributes = getAttributesFromExtensions(extensions)\n const { nodeExtensions, markExtensions } = splitExtensions(extensions)\n const topNode = nodeExtensions.find(extension => getExtensionField(extension, 'topNode'))?.name\n\n const nodes = Object.fromEntries(\n nodeExtensions.map(extension => {\n const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor,\n }\n\n const extraNodeFields = extensions.reduce((fields, e) => {\n const extendNodeSchema = getExtensionField<AnyConfig['extendNodeSchema']>(e, 'extendNodeSchema', context)\n\n return {\n ...fields,\n ...(extendNodeSchema ? extendNodeSchema(extension) : {}),\n }\n }, {})\n\n const schema: NodeSpec = cleanUpSchemaItem({\n ...extraNodeFields,\n content: callOrReturn(getExtensionField<NodeConfig['content']>(extension, 'content', context)),\n marks: callOrReturn(getExtensionField<NodeConfig['marks']>(extension, 'marks', context)),\n group: callOrReturn(getExtensionField<NodeConfig['group']>(extension, 'group', context)),\n inline: callOrReturn(getExtensionField<NodeConfig['inline']>(extension, 'inline', context)),\n atom: callOrReturn(getExtensionField<NodeConfig['atom']>(extension, 'atom', context)),\n selectable: callOrReturn(getExtensionField<NodeConfig['selectable']>(extension, 'selectable', context)),\n draggable: callOrReturn(getExtensionField<NodeConfig['draggable']>(extension, 'draggable', context)),\n code: callOrReturn(getExtensionField<NodeConfig['code']>(extension, 'code', context)),\n whitespace: callOrReturn(getExtensionField<NodeConfig['whitespace']>(extension, 'whitespace', context)),\n linebreakReplacement: callOrReturn(\n getExtensionField<NodeConfig['linebreakReplacement']>(extension, 'linebreakReplacement', context),\n ),\n defining: callOrReturn(getExtensionField<NodeConfig['defining']>(extension, 'defining', context)),\n isolating: callOrReturn(getExtensionField<NodeConfig['isolating']>(extension, 'isolating', context)),\n attrs: Object.fromEntries(\n extensionAttributes.map(extensionAttribute => {\n return [\n extensionAttribute.name,\n { default: extensionAttribute?.attribute?.default, validate: extensionAttribute?.attribute?.validate },\n ]\n }),\n ),\n })\n\n const parseHTML = callOrReturn(getExtensionField<NodeConfig['parseHTML']>(extension, 'parseHTML', context))\n\n if (parseHTML) {\n schema.parseDOM = parseHTML.map(parseRule =>\n injectExtensionAttributesToParseRule(parseRule, extensionAttributes),\n ) as TagParseRule[]\n }\n\n const renderHTML = getExtensionField<NodeConfig['renderHTML']>(extension, 'renderHTML', context)\n\n if (renderHTML) {\n schema.toDOM = node =>\n renderHTML({\n node,\n HTMLAttributes: getRenderedAttributes(node, extensionAttributes),\n })\n }\n\n const renderText = getExtensionField<NodeConfig['renderText']>(extension, 'renderText', context)\n\n if (renderText) {\n schema.toText = renderText\n }\n\n return [extension.name, schema]\n }),\n )\n\n const marks = Object.fromEntries(\n markExtensions.map(extension => {\n const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor,\n }\n\n const extraMarkFields = extensions.reduce((fields, e) => {\n const extendMarkSchema = getExtensionField<AnyConfig['extendMarkSchema']>(e, 'extendMarkSchema', context)\n\n return {\n ...fields,\n ...(extendMarkSchema ? extendMarkSchema(extension as any) : {}),\n }\n }, {})\n\n const schema: MarkSpec = cleanUpSchemaItem({\n ...extraMarkFields,\n inclusive: callOrReturn(getExtensionField<MarkConfig['inclusive']>(extension, 'inclusive', context)),\n excludes: callOrReturn(getExtensionField<MarkConfig['excludes']>(extension, 'excludes', context)),\n group: callOrReturn(getExtensionField<MarkConfig['group']>(extension, 'group', context)),\n spanning: callOrReturn(getExtensionField<MarkConfig['spanning']>(extension, 'spanning', context)),\n code: callOrReturn(getExtensionField<MarkConfig['code']>(extension, 'code', context)),\n attrs: Object.fromEntries(\n extensionAttributes.map(extensionAttribute => {\n return [\n extensionAttribute.name,\n { default: extensionAttribute?.attribute?.default, validate: extensionAttribute?.attribute?.validate },\n ]\n }),\n ),\n })\n\n const parseHTML = callOrReturn(getExtensionField<MarkConfig['parseHTML']>(extension, 'parseHTML', context))\n\n if (parseHTML) {\n schema.parseDOM = parseHTML.map(parseRule =>\n injectExtensionAttributesToParseRule(parseRule, extensionAttributes),\n )\n }\n\n const renderHTML = getExtensionField<MarkConfig['renderHTML']>(extension, 'renderHTML', context)\n\n if (renderHTML) {\n schema.toDOM = mark =>\n renderHTML({\n mark,\n HTMLAttributes: getRenderedAttributes(mark, extensionAttributes),\n })\n }\n\n return [extension.name, schema]\n }),\n )\n\n return new Schema({\n topNode,\n nodes,\n marks,\n })\n}\n","// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport function isFunction(value: any): value is Function {\n return typeof value === 'function'\n}\n","import type { MaybeReturnType } from '../types.js'\nimport { isFunction } from './isFunction.js'\n\n/**\n * Optionally calls `value` as a function.\n * Otherwise it is returned directly.\n * @param value Function or any value.\n * @param context Optional context to bind to function.\n * @param props Optional props to pass to function.\n */\nexport function callOrReturn<T>(value: T, context: any = undefined, ...props: any[]): MaybeReturnType<T> {\n if (isFunction(value)) {\n if (context) {\n return value.bind(context)(...props)\n }\n\n return value(...props)\n }\n\n return value as MaybeReturnType<T>\n}\n","export function isEmptyObject(value = {}): boolean {\n return Object.keys(value).length === 0 && value.constructor === Object\n}\n","import type { Extension } from '../Extension.js'\nimport type { Mark } from '../Mark.js'\nimport type { Node } from '../Node.js'\nimport type { Extensions } from '../types.js'\n\nexport function splitExtensions(extensions: Extensions) {\n const baseExtensions = extensions.filter(extension => extension.type === 'extension') as Extension[]\n const nodeExtensions = extensions.filter(extension => extension.type === 'node') as Node[]\n const markExtensions = extensions.filter(extension => extension.type === 'mark') as Mark[]\n\n return {\n baseExtensions,\n nodeExtensions,\n markExtensions,\n }\n}\n","import type { MarkConfig, NodeConfig } from '../index.js'\nimport type { AnyConfig, Attribute, Attributes, ExtensionAttribute, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\nimport { splitExtensions } from './splitExtensions.js'\n\n/**\n * Get a list of all extension attributes defined in `addAttribute` and `addGlobalAttribute`.\n * @param extensions List of extensions\n */\nexport function getAttributesFromExtensions(extensions: Extensions): ExtensionAttribute[] {\n const extensionAttributes: ExtensionAttribute[] = []\n const { nodeExtensions, markExtensions } = splitExtensions(extensions)\n const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions]\n const defaultAttribute: Required<Omit<Attribute, 'validate'>> & Pick<Attribute, 'validate'> = {\n default: null,\n validate: undefined,\n rendered: true,\n renderHTML: null,\n parseHTML: null,\n keepOnSplit: true,\n isRequired: false,\n }\n\n extensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n extensions: nodeAndMarkExtensions,\n }\n\n const addGlobalAttributes = getExtensionField<AnyConfig['addGlobalAttributes']>(\n extension,\n 'addGlobalAttributes',\n context,\n )\n\n if (!addGlobalAttributes) {\n return\n }\n\n const globalAttributes = addGlobalAttributes()\n\n globalAttributes.forEach(globalAttribute => {\n globalAttribute.types.forEach(type => {\n Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => {\n extensionAttributes.push({\n type,\n name,\n attribute: {\n ...defaultAttribute,\n ...attribute,\n },\n })\n })\n })\n })\n })\n\n nodeAndMarkExtensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n }\n\n const addAttributes = getExtensionField<NodeConfig['addAttributes'] | MarkConfig['addAttributes']>(\n extension,\n 'addAttributes',\n context,\n )\n\n if (!addAttributes) {\n return\n }\n\n // TODO: remove `as Attributes`\n const attributes = addAttributes() as Attributes\n\n Object.entries(attributes).forEach(([name, attribute]) => {\n const mergedAttr = {\n ...defaultAttribute,\n ...attribute,\n }\n\n if (typeof mergedAttr?.default === 'function') {\n mergedAttr.default = mergedAttr.default()\n }\n\n if (mergedAttr?.isRequired && mergedAttr?.default === undefined) {\n delete mergedAttr.default\n }\n\n extensionAttributes.push({\n type: extension.name,\n name,\n attribute: mergedAttr,\n })\n })\n })\n\n return extensionAttributes\n}\n","export function mergeAttributes(...objects: Record<string, any>[]): Record<string, any> {\n return objects\n .filter(item => !!item)\n .reduce((items, item) => {\n const mergedAttributes = { ...items }\n\n Object.entries(item).forEach(([key, value]) => {\n const exists = mergedAttributes[key]\n\n if (!exists) {\n mergedAttributes[key] = value\n\n return\n }\n\n if (key === 'class') {\n const valueClasses: string[] = value ? String(value).split(' ') : []\n const existingClasses: string[] = mergedAttributes[key] ? mergedAttributes[key].split(' ') : []\n\n const insertClasses = valueClasses.filter(valueClass => !existingClasses.includes(valueClass))\n\n mergedAttributes[key] = [...existingClasses, ...insertClasses].join(' ')\n } else if (key === 'style') {\n const newStyles: string[] = value\n ? value\n .split(';')\n .map((style: string) => style.trim())\n .filter(Boolean)\n : []\n const existingStyles: string[] = mergedAttributes[key]\n ? mergedAttributes[key]\n .split(';')\n .map((style: string) => style.trim())\n .filter(Boolean)\n : []\n\n const styleMap = new Map<string, string>()\n\n existingStyles.forEach(style => {\n const [property, val] = style.split(':').map(part => part.trim())\n\n styleMap.set(property, val)\n })\n\n newStyles.forEach(style => {\n const [property, val] = style.split(':').map(part => part.trim())\n\n styleMap.set(property, val)\n })\n\n mergedAttributes[key] = Array.from(styleMap.entries())\n .map(([property, val]) => `${property}: ${val}`)\n .join('; ')\n } else {\n mergedAttributes[key] = value\n }\n })\n\n return mergedAttributes\n }, {})\n}\n","import type { Mark, Node } from '@tiptap/pm/model'\n\nimport type { ExtensionAttribute } from '../types.js'\nimport { mergeAttributes } from '../utilities/mergeAttributes.js'\n\nexport function getRenderedAttributes(\n nodeOrMark: Node | Mark,\n extensionAttributes: ExtensionAttribute[],\n): Record<string, any> {\n return extensionAttributes\n .filter(attribute => attribute.type === nodeOrMark.type.name)\n .filter(item => item.attribute.rendered)\n .map(item => {\n if (!item.attribute.renderHTML) {\n return {\n [item.name]: nodeOrMark.attrs[item.name],\n }\n }\n\n return item.attribute.renderHTML(nodeOrMark.attrs) || {}\n })\n .reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {})\n}\n","export function fromString(value: any): any {\n if (typeof value !== 'string') {\n return value\n }\n\n if (value.match(/^[+-]?(?:\\d*\\.)?\\d+$/)) {\n return Number(value)\n }\n\n if (value === 'true') {\n return true\n }\n\n if (value === 'false') {\n return false\n }\n\n return value\n}\n","import type { ParseRule } from '@tiptap/pm/model'\n\nimport type { ExtensionAttribute } from '../types.js'\nimport { fromString } from '../utilities/fromString.js'\n\n/**\n * This function merges extension attributes into parserule attributes (`attrs` or `getAttrs`).\n * Cancels when `getAttrs` returned `false`.\n * @param parseRule ProseMirror ParseRule\n * @param extensionAttributes List of attributes to inject\n */\nexport function injectExtensionAttributesToParseRule(\n parseRule: ParseRule,\n extensionAttributes: ExtensionAttribute[],\n): ParseRule {\n if ('style' in parseRule) {\n return parseRule\n }\n\n return {\n ...parseRule,\n getAttrs: (node: HTMLElement) => {\n const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs\n\n if (oldAttributes === false) {\n return false\n }\n\n const newAttributes = extensionAttributes.reduce((items, item) => {\n const value = item.attribute.parseHTML\n ? item.attribute.parseHTML(node)\n : fromString(node.getAttribute(item.name))\n\n if (value === null || value === undefined) {\n return items\n }\n\n return {\n ...items,\n [item.name]: value,\n }\n }, {})\n\n return { ...oldAttributes, ...newAttributes }\n },\n }\n}\n","/**\n * Find duplicates in an array.\n */\nexport function findDuplicates<T>(items: T[]): T[] {\n const filtered = items.filter((el, index) => items.indexOf(el) !== index)\n\n return Array.from(new Set(filtered))\n}\n","import type { AnyConfig, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\n\n/**\n * Sort extensions by priority.\n * @param extensions An array of Tiptap extensions\n * @returns A sorted array of Tiptap extensions by priority\n */\nexport function sortExtensions(extensions: Extensions): Extensions {\n const defaultPriority = 100\n\n return extensions.sort((a, b) => {\n const priorityA = getExtensionField<AnyConfig['priority']>(a, 'priority') || defaultPriority\n const priorityB = getExtensionField<AnyConfig['priority']>(b, 'priority') || defaultPriority\n\n if (priorityA > priorityB) {\n return -1\n }\n\n if (priorityA < priorityB) {\n return 1\n }\n\n return 0\n })\n}\n","import type { Extensions } from '../types.js'\nimport { findDuplicates } from '../utilities/findDuplicates.js'\nimport { flattenExtensions } from './flattenExtensions.js'\nimport { sortExtensions } from './sortExtensions.js'\n\n/**\n * Returns a flattened and sorted extension list while\n * also checking for duplicated extensions and warns the user.\n * @param extensions An array of Tiptap extensions\n * @returns An flattened and sorted array of Tiptap extensions\n */\nexport function resolveExtensions(extensions: Extensions): Extensions {\n const resolvedExtensions = sortExtensions(flattenExtensions(extensions))\n const duplicatedNames = findDuplicates(resolvedExtensions.map(extension => extension.name))\n\n if (duplicatedNames.length) {\n console.warn(\n `[tiptap warn]: Duplicate extension names found: [${duplicatedNames\n .map(item => `'${item}'`)\n .join(', ')}]. This can lead to issues.`,\n )\n }\n\n return resolvedExtensions\n}\n","import type { Schema } from '@tiptap/pm/model'\n\nimport type { Editor } from '../Editor.js'\nimport type { Extensions } from '../types.js'\nimport { getSchemaByResolvedExtensions } from './getSchemaByResolvedExtensions.js'\nimport { resolveExtensions } from './resolveExtensions.js'\n\nexport function getSchema(extensions: Extensions, editor?: Editor): Schema {\n const resolvedExtensions = resolveExtensions(extensions)\n\n return getSchemaByResolvedExtensions(resolvedExtensions, editor)\n}\n","import { DOMParser } from '@tiptap/pm/model'\n\nimport type { Extensions } from '../types.js'\nimport { elementFromString } from '../utilities/elementFromString.js'\nimport { getSchema } from './getSchema.js'\n\n/**\n * Generate JSONContent from HTML\n * @param html The HTML to generate JSONContent from\n * @param extensions The extensions to use for the schema\n * @returns The generated JSONContent\n */\nexport function generateJSON(html: string, extensions: Extensions): Record<string, any> {\n const schema = getSchema(extensions)\n const dom = elementFromString(html)\n\n return DOMParser.fromSchema(schema).parse(dom).toJSON()\n}\n","import { Node } from '@tiptap/pm/model'\n\nimport type { Extensions, JSONContent, TextSerializer } from '../types.js'\nimport { getSchema } from './getSchema.js'\nimport { getText } from './getText.js'\nimport { getTextSerializersFromSchema } from './getTextSerializersFromSchema.js'\n\n/**\n * Generate raw text from a JSONContent\n * @param doc The JSONContent to generate text from\n * @param extensions The extensions to use for the schema\n * @param options Options for the text generation f.e. blockSeparator or textSerializers\n * @returns The generated text\n */\nexport function generateText(\n doc: JSONContent,\n extensions: Extensions,\n options?: {\n blockSeparator?: string\n textSerializers?: Record<string, TextSerializer>\n },\n): string {\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n const schema = getSchema(extensions)\n const contentNode = Node.fromJSON(schema, doc)\n\n return getText(contentNode, {\n blockSeparator,\n textSerializers: {\n ...getTextSerializersFromSchema(schema),\n ...textSerializers,\n },\n })\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { Range, TextSerializer } from '../types.js'\n\n/**\n * Gets the text between two positions in a Prosemirror node\n * and serializes it using the given text serializers and block separator (see getText)\n * @param startNode The Prosemirror node to start from\n * @param range The range of the text to get\n * @param options Options for the text serializer & block separator\n * @returns The text between the two positions\n */\nexport function getTextBetween(\n startNode: ProseMirrorNode,\n range: Range,\n options?: {\n blockSeparator?: string\n textSerializers?: Record<string, TextSerializer>\n },\n): string {\n const { from, to } = range\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n let text = ''\n\n startNode.nodesBetween(from, to, (node, pos, parent, index) => {\n if (node.isBlock && pos > from) {\n text += blockSeparator\n }\n\n const textSerializer = textSerializers?.[node.type.name]\n\n if (textSerializer) {\n if (parent) {\n text += textSerializer({\n node,\n pos,\n parent,\n index,\n range,\n })\n }\n // do not descend into child nodes when there exists a serializer\n return false\n }\n\n if (node.isText) {\n text += node?.text?.slice(Math.max(from, pos) - pos, to - pos) // eslint-disable-line\n }\n })\n\n return text\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { TextSerializer } from '../types.js'\nimport { getTextBetween } from './getTextBetween.js'\n\n/**\n * Gets the text of a Prosemirror node\n * @param node The Prosemirror node\n * @param options Options for the text serializer & block separator\n * @returns The text of the node\n * @example ```js\n * const text = getText(node, { blockSeparator: '\\n' })\n * ```\n */\nexport function getText(\n node: ProseMirrorNode,\n options?: {\n blockSeparator?: string\n textSerializers?: Record<string, TextSerializer>\n },\n) {\n const range = {\n from: 0,\n to: node.content.size,\n }\n\n return getTextBetween(node, range, options)\n}\n","import type { Schema } from '@tiptap/pm/model'\n\nimport type { TextSerializer } from '../types.js'\n\n/**\n * Find text serializers `toText` in a Prosemirror schema\n * @param schema The Prosemirror schema to search in\n * @returns A record of text serializers by node name\n */\nexport function getTextSerializersFromSchema(schema: Schema): Record<string, TextSerializer> {\n return Object.fromEntries(\n Object.entries(schema.nodes)\n .filter(([, node]) => node.spec.toText)\n .map(([name, node]) => [name, node.spec.toText]),\n )\n}\n","import type { MarkType, Schema } from '@tiptap/pm/model'\n\nexport function getMarkType(nameOrType: string | MarkType, schema: Schema): MarkType {\n if (typeof nameOrType === 'string') {\n if (!schema.marks[nameOrType]) {\n throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`)\n }\n\n return schema.marks[nameOrType]\n }\n\n return nameOrType\n}\n","import type { Mark, MarkType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getMarkType } from './getMarkType.js'\n\nexport function getMarkAttributes(state: EditorState, typeOrName: string | MarkType): Record<string, any> {\n const type = getMarkType(typeOrName, state.schema)\n const { from, to, empty } = state.selection\n const marks: Mark[] = []\n\n if (empty) {\n if (state.storedMarks) {\n marks.push(...state.storedMarks)\n }\n\n marks.push(...state.selection.$head.marks())\n } else {\n state.doc.nodesBetween(from, to, node => {\n marks.push(...node.marks)\n })\n }\n\n const mark = marks.find(markItem => markItem.type.name === type.name)\n\n if (!mark) {\n return {}\n }\n\n return { ...mark.attrs }\n}\n","import type { NodeType, Schema } from '@tiptap/pm/model'\n\nexport function getNodeType(nameOrType: string | NodeType, schema: Schema): NodeType {\n if (typeof nameOrType === 'string') {\n if (!schema.nodes[nameOrType]) {\n throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`)\n }\n\n return schema.nodes[nameOrType]\n }\n\n return nameOrType\n}\n","import type { Node, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getNodeType } from './getNodeType.js'\n\nexport function getNodeAttributes(state: EditorState, typeOrName: string | NodeType): Record<string, any> {\n const type = getNodeType(typeOrName, state.schema)\n const { from, to } = state.selection\n const nodes: Node[] = []\n\n state.doc.nodesBetween(from, to, node => {\n nodes.push(node)\n })\n\n const node = nodes.reverse().find(nodeItem => nodeItem.type.name === type.name)\n\n if (!node) {\n return {}\n }\n\n return { ...node.attrs }\n}\n","import type { Schema } from '@tiptap/pm/model'\n\n/**\n * Get the type of a schema item by its name.\n * @param name The name of the schema item\n * @param schema The Prosemiror schema to search in\n * @returns The type of the schema item (`node` or `mark`), or null if it doesn't exist\n */\nexport function getSchemaTypeNameByName(name: string, schema: Schema): 'node' | 'mark' | null {\n if (schema.nodes[name]) {\n return 'node'\n }\n\n if (schema.marks[name]) {\n return 'mark'\n }\n\n return null\n}\n","import type { MarkType, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getMarkAttributes } from './getMarkAttributes.js'\nimport { getNodeAttributes } from './getNodeAttributes.js'\nimport { getSchemaTypeNameByName } from './getSchemaTypeNameByName.js'\n\n/**\n * Get node or mark attributes by type or name on the current editor state\n * @param state The current editor state\n * @param typeOrName The node or mark type or name\n * @returns The attributes of the node or mark or an empty object\n */\nexport function getAttributes(state: EditorState, typeOrName: string | NodeType | MarkType): Record<string, any> {\n const schemaType = getSchemaTypeNameByName(\n typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n state.schema,\n )\n\n if (schemaType === 'node') {\n return getNodeAttributes(state, typeOrName as NodeType)\n }\n\n if (schemaType === 'mark') {\n return getMarkAttributes(state, typeOrName as MarkType)\n }\n\n return {}\n}\n","/**\n * Removes duplicated values within an array.\n * Supports numbers, strings and objects.\n */\nexport function removeDuplicates<T>(array: T[], by = JSON.stringify): T[] {\n const seen: Record<any, any> = {}\n\n return array.filter(item => {\n const key = by(item)\n\n return Object.prototype.hasOwnProperty.call(seen, key) ? false : (seen[key] = true)\n })\n}\n","import type { Step, Transform } from '@tiptap/pm/transform'\n\nimport type { Range } from '../types.js'\nimport { removeDuplicates } from '../utilities/removeDuplicates.js'\n\nexport type ChangedRange = {\n oldRange: Range\n newRange: Range\n}\n\n/**\n * Removes duplicated ranges and ranges that are\n * fully captured by other ranges.\n */\nfunction simplifyChangedRanges(changes: ChangedRange[]): ChangedRange[] {\n const uniqueChanges = removeDuplicates(changes)\n\n return uniqueChanges.length === 1\n ? uniqueChanges\n : uniqueChanges.filter((change, index) => {\n const rest = uniqueChanges.filter((_, i) => i !== index)\n\n return !rest.some(otherChange => {\n return (\n change.oldRange.from >= otherChange.oldRange.from &&\n change.oldRange.to <= otherChange.oldRange.to &&\n change.newRange.from >= otherChange.newRange.from &&\n change.newRange.to <= otherChange.newRange.to\n )\n })\n })\n}\n\n/**\n * Returns a list of changed ranges\n * based on the first and last state of all steps.\n */\nexport function getChangedRanges(transform: Transform): ChangedRange[] {\n const { mapping, steps } = transform\n const changes: ChangedRange[] = []\n\n mapping.maps.forEach((stepMap, index) => {\n const ranges: Range[] = []\n\n // This accounts for step changes where no range was actually altered\n // e.g. when setting a mark, node attribute, etc.\n // @ts-ignore\n if (!stepMap.ranges.length) {\n const { from, to } = steps[index] as Step & {\n from?: number\n to?: number\n }\n\n if (from === undefined || to === undefined) {\n return\n }\n\n ranges.push({ from, to })\n } else {\n stepMap.forEach((from, to) => {\n ranges.push({ from, to })\n })\n }\n\n ranges.forEach(({ from, to }) => {\n const newStart = mapping.slice(index).map(from, -1)\n const newEnd = mapping.slice(index).map(to)\n const oldStart = mapping.invert().map(newStart, -1)\n const oldEnd = mapping.invert().map(newEnd)\n\n changes.push({\n oldRange: {\n from: oldStart,\n to: oldEnd,\n },\n newRange: {\n from: newStart,\n to: newEnd,\n },\n })\n })\n })\n\n return simplifyChangedRanges(changes)\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { JSONContent } from '../types.js'\n\ninterface DebugJSONContent extends JSONContent {\n from: number\n to: number\n}\n\nexport function getDebugJSON(node: ProseMirrorNode, startOffset = 0): DebugJSONContent {\n const isTopNode = node.type === node.type.schema.topNodeType\n const increment = isTopNode ? 0 : 1\n const from = startOffset\n const to = from + node.nodeSize\n const marks = node.marks.map(mark => {\n const output: { type: string; attrs?: Record<string, any> } = {\n type: mark.type.name,\n }\n\n if (Object.keys(mark.attrs).length) {\n output.attrs = { ...mark.attrs }\n }\n\n return output\n })\n const attrs = { ...node.attrs }\n const output: DebugJSONContent = {\n type: node.type.name,\n from,\n to,\n }\n\n if (Object.keys(attrs).length) {\n output.attrs = attrs\n }\n\n if (marks.length) {\n output.marks = marks\n }\n\n if (node.content.childCount) {\n output.content = []\n\n node.forEach((child, offset) => {\n output.content?.push(getDebugJSON(child, startOffset + offset + increment))\n })\n }\n\n if (node.text) {\n output.text = node.text\n }\n\n return output\n}\n","export function isRegExp(value: any): value is RegExp {\n return Object.prototype.toString.call(value) === '[object RegExp]'\n}\n","import { isRegExp } from './isRegExp.js'\n\n/**\n * Check if object1 includes object2\n * @param object1 Object\n * @param object2 Object\n */\nexport function objectIncludes(\n object1: Record<string, any>,\n object2: Record<string, any>,\n options: { strict: boolean } = { strict: true },\n): boolean {\n const keys = Object.keys(object2)\n\n if (!keys.length) {\n return true\n }\n\n return keys.every(key => {\n if (options.strict) {\n return object2[key] === object1[key]\n }\n\n if (isRegExp(object2[key])) {\n return object2[key].test(object1[key])\n }\n\n return object2[key] === object1[key]\n })\n}\n","import type { Mark as ProseMirrorMark, MarkType, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Range } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\n\nfunction findMarkInSet(\n marks: ProseMirrorMark[],\n type: MarkType,\n attributes: Record<string, any> = {},\n): ProseMirrorMark | undefined {\n return marks.find(item => {\n return (\n item.type === type &&\n objectIncludes(\n // Only check equality for the attributes that are provided\n Object.fromEntries(Object.keys(attributes).map(k => [k, item.attrs[k]])),\n attributes,\n )\n )\n })\n}\n\nfunction isMarkInSet(marks: ProseMirrorMark[], type: MarkType, attributes: Record<string, any> = {}): boolean {\n return !!findMarkInSet(marks, type, attributes)\n}\n\n/**\n * Get the range of a mark at a resolved position.\n */\nexport function getMarkRange(\n /**\n * The position to get the mark range for.\n */\n $pos: ResolvedPos,\n /**\n * The mark type to get the range for.\n */\n type: MarkType,\n /**\n * The attributes to match against.\n * If not provided, only the first mark at the position will be matched.\n */\n attributes?: Record<string, any>,\n): Range | void {\n if (!$pos || !type) {\n return\n }\n let start = $pos.parent.childAfter($pos.parentOffset)\n\n // If the cursor is at the start of a text node that does not have the mark, look backward\n if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n start = $pos.parent.childBefore($pos.parentOffset)\n }\n\n // If there is no text node with the mark even backward, return undefined\n if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n return\n }\n\n // Default to only matching against the first mark's attributes\n attributes = attributes || start.node.marks[0]?.attrs\n\n // We now know that the cursor is either at the start, middle or end of a text node with the specified mark\n // so we can look it up on the targeted mark\n const mark = findMarkInSet([...start.node.marks], type, attributes)\n\n if (!mark) {\n return\n }\n\n let startIndex = start.index\n let startPos = $pos.start() + start.offset\n let endIndex = startIndex + 1\n let endPos = startPos + start.node.nodeSize\n\n while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) {\n startIndex -= 1\n startPos -= $pos.parent.child(startIndex).nodeSize\n }\n\n while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) {\n endPos += $pos.parent.child(endIndex).nodeSize\n endIndex += 1\n }\n\n return {\n from: startPos,\n to: endPos,\n }\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { MarkRange } from '../types.js'\nimport { getMarkRange } from './getMarkRange.js'\n\nexport function getMarksBetween(from: number, to: number, doc: ProseMirrorNode): MarkRange[] {\n const marks: MarkRange[] = []\n\n // get all inclusive marks on empty selection\n if (from === to) {\n doc\n .resolve(from)\n .marks()\n .forEach(mark => {\n const $pos = doc.resolve(from)\n const range = getMarkRange($pos, mark.type)\n\n if (!range) {\n return\n }\n\n marks.push({\n mark,\n ...range,\n })\n })\n } else {\n doc.nodesBetween(from, to, (node, pos) => {\n if (!node || node?.nodeSize === undefined) {\n return\n }\n\n marks.push(\n ...node.marks.map(mark => ({\n from: pos,\n to: pos + node.nodeSize,\n mark,\n })),\n )\n })\n }\n\n return marks\n}\n","import type { Node, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\n/**\n * Finds the first node of a given type or name in the current selection.\n * @param state The editor state.\n * @param typeOrName The node type or name.\n * @param pos The position to start searching from.\n * @param maxDepth The maximum depth to search.\n * @returns The node and the depth as an array.\n */\nexport const getNodeAtPosition = (state: EditorState, typeOrName: string | NodeType, pos: number, maxDepth = 20) => {\n const $pos = state.doc.resolve(pos)\n\n let currentDepth = maxDepth\n let node: Node | null = null\n\n while (currentDepth > 0 && node === null) {\n const currentNode = $pos.node(currentDepth)\n\n if (currentNode?.type.name === typeOrName) {\n node = currentNode\n } else {\n currentDepth -= 1\n }\n }\n\n return [node, currentDepth] as [Node | null, number]\n}\n","import type { MarkType, NodeType, Schema } from '@tiptap/pm/model'\n\n/**\n * Tries to get a node or mark type by its name.\n * @param name The name of the node or mark type\n * @param schema The Prosemiror schema to search in\n * @returns The node or mark type, or null if it doesn't exist\n */\nexport function getSchemaTypeByName(name: string, schema: Schema): NodeType | MarkType | null {\n return schema.nodes[name] || schema.marks[name] || null\n}\n","import type { ExtensionAttribute } from '../types.js'\n\n/**\n * Return attributes of an extension that should be splitted by keepOnSplit flag\n * @param extensionAttributes Array of extension attributes\n * @param typeName The type of the extension\n * @param attributes The attributes of the extension\n * @returns The splitted attributes\n */\nexport function getSplittedAttributes(\n extensionAttributes: ExtensionAttribute[],\n typeName: string,\n attributes: Record<string, any>,\n): Record<string, any> {\n return Object.fromEntries(\n Object.entries(attributes).filter(([name]) => {\n const extensionAttribute = extensionAttributes.find(item => {\n return item.type === typeName && item.name === name\n })\n\n if (!extensionAttribute) {\n return false\n }\n\n return extensionAttribute.attribute.keepOnSplit\n }),\n )\n}\n","import type { ResolvedPos } from '@tiptap/pm/model'\n\n/**\n * Returns the text content of a resolved prosemirror position\n * @param $from The resolved position to get the text content from\n * @param maxMatch The maximum number of characters to match\n * @returns The text content\n */\nexport const getTextContentFromNodes = ($from: ResolvedPos, maxMatch = 500) => {\n let textBefore = ''\n\n const sliceEndPos = $from.parentOffset\n\n $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node, pos, parent, index) => {\n const chunk =\n node.type.spec.toText?.({\n node,\n pos,\n parent,\n index,\n }) ||\n node.textContent ||\n '%leaf%'\n\n textBefore += node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos))\n })\n\n return textBefore\n}\n","import type { MarkType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport type { MarkRange } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\nimport { getMarkType } from './getMarkType.js'\n\nexport function isMarkActive(\n state: EditorState,\n typeOrName: MarkType | string | null,\n attributes: Record<string, any> = {},\n): boolean {\n const { empty, ranges } = state.selection\n const type = typeOrName ? getMarkType(typeOrName, state.schema) : null\n\n if (empty) {\n return !!(state.storedMarks || state.selection.$from.marks())\n .filter(mark => {\n if (!type) {\n return true\n }\n\n return type.name === mark.type.name\n })\n .find(mark => objectIncludes(mark.attrs, attributes, { strict: false }))\n }\n\n let selectionRange = 0\n const markRanges: MarkRange[] = []\n\n ranges.forEach(({ $from, $to }) => {\n const from = $from.pos\n const to = $to.pos\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isText && !node.marks.length) {\n return\n }\n\n const relativeFrom = Math.max(from, pos)\n const relativeTo = Math.min(to, pos + node.nodeSize)\n const range = relativeTo - relativeFrom\n\n selectionRange += range\n\n markRanges.push(\n ...node.marks.map(mark => ({\n mark,\n from: relativeFrom,\n to: relativeTo,\n })),\n )\n })\n })\n\n if (selectionRange === 0) {\n return false\n }\n\n // calculate range of matched mark\n const matchedRange = markRanges\n .filter(markRange => {\n if (!type) {\n return true\n }\n\n return type.name === markRange.mark.type.name\n })\n .filter(markRange => objectIncludes(markRange.mark.attrs, attributes, { strict: false }))\n .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0)\n\n // calculate range of marks that excludes the searched mark\n // for example `code` doesn’t allow any other marks\n const excludedRange = markRanges\n .filter(markRange => {\n if (!type) {\n return true\n }\n\n return markRange.mark.type !== type && markRange.mark.type.excludes(type)\n })\n .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0)\n\n // we only include the result of `excludedRange`\n // if there is a match at all\n const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange\n\n return range >= selectionRange\n}\n","import type { NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport type { NodeRange } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\nimport { getNodeType } from './getNodeType.js'\n\nexport function isNodeActive(\n state: EditorState,\n typeOrName: NodeType | string | null,\n attributes: Record<string, any> = {},\n): boolean {\n const { from, to, empty } = state.selection\n const type = typeOrName ? getNodeType(typeOrName, state.schema) : null\n\n const nodeRanges: NodeRange[] = []\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (node.isText) {\n return\n }\n\n const relativeFrom = Math.max(from, pos)\n const relativeTo = Math.min(to, pos + node.nodeSize)\n\n nodeRanges.push({\n node,\n from: relativeFrom,\n to: relativeTo,\n })\n })\n\n const selectionRange = to - from\n const matchedNodeRanges = nodeRanges\n .filter(nodeRange => {\n if (!type) {\n return true\n }\n\n return type.name === nodeRange.node.type.name\n })\n .filter(nodeRange => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }))\n\n if (empty) {\n return !!matchedNodeRanges.length\n }\n\n const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0)\n\n return range >= selectionRange\n}\n","import type { EditorState } from '@tiptap/pm/state'\n\nimport { getSchemaTypeNameByName } from './getSchemaTypeNameByName.js'\nimport { isMarkActive } from './isMarkActive.js'\nimport { isNodeActive } from './isNodeActive.js'\n\nexport function isActive(state: EditorState, name: string | null, attributes: Record<string, any> = {}): boolean {\n if (!name) {\n return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes)\n }\n\n const schemaType = getSchemaTypeNameByName(name, state.schema)\n\n if (schemaType === 'node') {\n return isNodeActive(state, name, attributes)\n }\n\n if (schemaType === 'mark') {\n return isMarkActive(state, name, attributes)\n }\n\n return false\n}\n","import type { EditorState } from '@tiptap/pm/state'\n\nimport { findParentNode } from './findParentNode.js'\n\nexport const isAtEndOfNode = (state: EditorState, nodeType?: string) => {\n const { $from, $to, $anchor } = state.selection\n\n if (nodeType) {\n const parentNode = findParentNode(node => node.type.name === nodeType)(state.selection)\n\n if (!parentNode) {\n return false\n }\n\n const $parentPos = state.doc.resolve(parentNode.pos + 1)\n\n if ($anchor.pos + 1 === $parentPos.end()) {\n return true\n }\n\n return false\n }\n\n if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) {\n return false\n }\n\n return true\n}\n","import type { EditorState } from '@tiptap/pm/state'\n\nexport const isAtStartOfNode = (state: EditorState) => {\n const { $from, $to } = state.selection\n\n if ($from.parentOffset > 0 || $from.pos !== $to.pos) {\n return false\n }\n\n return true\n}\n","import type { AnyExtension, EnableRules } from '../types.js'\n\nexport function isExtensionRulesEnabled(extension: AnyExtension, enabled: EnableRules): boolean {\n if (Array.isArray(enabled)) {\n return enabled.some(enabledExtension => {\n const name = typeof enabledExtension === 'string' ? enabledExtension : enabledExtension.name\n\n return name === extension.name\n })\n }\n\n return enabled\n}\n","import { getExtensionField } from '../helpers/getExtensionField.js'\nimport type { NodeConfig } from '../index.js'\nimport type { Extensions } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\nimport { splitExtensions } from './splitExtensions.js'\n\nexport function isList(name: string, extensions: Extensions): boolean {\n const { nodeExtensions } = splitExtensions(extensions)\n const extension = nodeExtensions.find(item => item.name === name)\n\n if (!extension) {\n return false\n }\n\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n }\n const group = callOrReturn(getExtensionField<NodeConfig['group']>(extension, 'group', context))\n\n if (typeof group !== 'string') {\n return false\n }\n\n return group.split(' ').includes('list')\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\n/**\n * Returns true if the given prosemirror node is empty.\n */\nexport function isNodeEmpty(\n node: ProseMirrorNode,\n {\n checkChildren = true,\n ignoreWhitespace = false,\n }: {\n /**\n * When true (default), it will also check if all children are empty.\n */\n checkChildren?: boolean\n /**\n * When true, it will ignore whitespace when checking for emptiness.\n */\n ignoreWhitespace?: boolean\n } = {},\n): boolean {\n if (ignoreWhitespace) {\n if (node.type.name === 'hardBreak') {\n // Hard breaks are considered empty\n return true\n }\n if (node.isText) {\n return /^\\s*$/m.test(node.text ?? '')\n }\n }\n\n if (node.isText) {\n return !node.text\n }\n\n if (node.isAtom || node.isLeaf) {\n return false\n }\n\n if (node.content.childCount === 0) {\n return true\n }\n\n if (checkChildren) {\n let isContentEmpty = true\n\n node.content.forEach(childNode => {\n if (isContentEmpty === false) {\n // Exit early for perf\n return\n }\n\n if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {\n isContentEmpty = false\n }\n })\n\n return isContentEmpty\n }\n\n return false\n}\n","import { NodeSelection } from '@tiptap/pm/state'\n\nexport function isNodeSelection(value: unknown): value is NodeSelection {\n return value instanceof NodeSelection\n}\n","import { TextSelection } from '@tiptap/pm/state'\n\nexport function isTextSelection(value: unknown): value is TextSelection {\n return value instanceof TextSelection\n}\n","export function minMax(value = 0, min = 0, max = 0): number {\n return Math.min(Math.max(value, min), max)\n}\n","import type { EditorView } from '@tiptap/pm/view'\n\nimport { minMax } from '../utilities/minMax.js'\n\nexport function posToDOMRect(view: EditorView, from: number, to: number): DOMRect {\n const minPos = 0\n const maxPos = view.state.doc.content.size\n const resolvedFrom = minMax(from, minPos, maxPos)\n const resolvedEnd = minMax(to, minPos, maxPos)\n const start = view.coordsAtPos(resolvedFrom)\n const end = view.coordsAtPos(resolvedEnd, -1)\n const top = Math.min(start.top, end.top)\n const bottom = Math.max(start.bottom, end.bottom)\n const left = Math.min(start.left, end.left)\n const right = Math.max(start.right, end.right)\n const width = right - left\n const height = bottom - top\n const x = left\n const y = top\n const data = {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x,\n y,\n }\n\n return {\n ...data,\n toJSON: () => data,\n }\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Selection, TextSelection } from '@tiptap/pm/state'\n\nimport type { FocusPosition } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\nexport function resolveFocusPosition(doc: ProseMirrorNode, position: FocusPosition = null): Selection | null {\n if (!position) {\n return null\n }\n\n const selectionAtStart = Selection.atStart(doc)\n const selectionAtEnd = Selection.atEnd(doc)\n\n if (position === 'start' || position === true) {\n return selectionAtStart\n }\n\n if (position === 'end') {\n return selectionAtEnd\n }\n\n const minPos = selectionAtStart.from\n const maxPos = selectionAtEnd.to\n\n if (position === 'all') {\n return TextSelection.create(doc, minMax(0, minPos, maxPos), minMax(doc.content.size, minPos, maxPos))\n }\n\n return TextSelection.create(doc, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos))\n}\n","import type { Schema } from '@tiptap/pm/model'\n\nimport type { JSONContent } from '../types.js'\n\ntype RewriteUnknownContentOptions = {\n /**\n * If true, unknown nodes will be treated as paragraphs\n * @default true\n */\n fallbackToParagraph?: boolean\n}\n\ntype RewrittenContent = {\n /**\n * The original JSON content that was rewritten\n */\n original: JSONContent\n /**\n * The name of the node or mark that was unsupported\n */\n unsupported: string\n}[]\n\n/**\n * The actual implementation of the rewriteUnknownContent function\n */\nfunction rewriteUnknownContentInner({\n json,\n validMarks,\n validNodes,\n options,\n rewrittenContent = [],\n}: {\n json: JSONContent\n validMarks: Set<string>\n validNodes: Set<string>\n options?: RewriteUnknownContentOptions\n rewrittenContent?: RewrittenContent\n}): {\n /**\n * The cleaned JSON content\n */\n json: JSONContent | null\n /**\n * The array of nodes and marks that were rewritten\n */\n rewrittenContent: RewrittenContent\n} {\n if (json.marks && Array.isArray(json.marks)) {\n json.marks = json.marks.filter(mark => {\n const name = typeof mark === 'string' ? mark : mark.type\n\n if (validMarks.has(name)) {\n return true\n }\n\n rewrittenContent.push({\n original: JSON.parse(JSON.stringify(mark)),\n unsupported: name,\n })\n // Just ignore any unknown marks\n return false\n })\n }\n\n if (json.content && Array.isArray(json.content)) {\n json.content = json.content\n .map(\n value =>\n rewriteUnknownContentInner({\n json: value,\n validMarks,\n validNodes,\n options,\n rewrittenContent,\n }).json,\n )\n .filter(a => a !== null && a !== undefined)\n }\n\n if (json.type && !validNodes.has(json.type)) {\n rewrittenContent.push({\n original: JSON.parse(JSON.stringify(json)),\n unsupported: json.type,\n })\n\n if (json.content && Array.isArray(json.content) && options?.fallbackToParagraph !== false) {\n // Just treat it like a paragraph and hope for the best\n json.type = 'paragraph'\n\n return {\n json,\n rewrittenContent,\n }\n }\n\n // or just omit it entirely\n return {\n json: null,\n rewrittenContent,\n }\n }\n\n return { json, rewrittenContent }\n}\n\n/**\n * Rewrite unknown nodes and marks within JSON content\n * Allowing for user within the editor\n */\nexport function rewriteUnknownContent(\n /**\n * The JSON content to clean of unknown nodes and marks\n */\n json: JSONContent,\n /**\n * The schema to use for validation\n */\n schema: Schema,\n /**\n * Options for the cleaning process\n */\n options?: RewriteUnknownContentOptions,\n): {\n /**\n * The cleaned JSON content\n */\n json: JSONContent | null\n /**\n * The array of nodes and marks that were rewritten\n */\n rewrittenContent: {\n /**\n * The original JSON content that was rewritten\n */\n original: JSONContent\n /**\n * The name of the node or mark that was unsupported\n */\n unsupported: string\n }[]\n} {\n return rewriteUnknownContentInner({\n json,\n validNodes: new Set(Object.keys(schema.nodes)),\n validMarks: new Set(Object.keys(schema.marks)),\n options,\n })\n}\n","import type { Transaction } from '@tiptap/pm/state'\nimport { Selection } from '@tiptap/pm/state'\nimport { ReplaceAroundStep, ReplaceStep } from '@tiptap/pm/transform'\n\n// source: https://github.com/ProseMirror/prosemirror-state/blob/master/src/selection.js#L466\nexport function selectionToInsertionEnd(tr: Transaction, startLen: number, bias: number) {\n const last = tr.steps.length - 1\n\n if (last < startLen) {\n return\n }\n\n const step = tr.steps[last]\n\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {\n return\n }\n\n const map = tr.mapping.maps[last]\n let end = 0\n\n map.forEach((_from, _to, _newFrom, newTo) => {\n if (end === 0) {\n end = newTo\n }\n })\n\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias))\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\nimport type { EditorState, TextSelection } from '@tiptap/pm/state'\nimport { Plugin } from '@tiptap/pm/state'\n\nimport { CommandManager } from './CommandManager.js'\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport { getTextContentFromNodes } from './helpers/getTextContentFromNodes.js'\nimport type { CanCommands, ChainedCommands, ExtendedRegExpMatchArray, Range, SingleCommands } from './types.js'\nimport { isRegExp } from './utilities/isRegExp.js'\n\nexport type InputRuleMatch = {\n index: number\n text: string\n replaceWith?: string\n match?: RegExpMatchArray\n data?: Record<string, any>\n}\n\nexport type InputRuleFinder = RegExp | ((text: string) => InputRuleMatch | null)\n\nexport class InputRule {\n find: InputRuleFinder\n\n handler: (props: {\n state: EditorState\n range: Range\n match: ExtendedRegExpMatchArray\n commands: SingleCommands\n chain: () => ChainedCommands\n can: () => CanCommands\n }) => void | null\n\n constructor(config: {\n find: InputRuleFinder\n handler: (props: {\n state: EditorState\n range: Range\n match: ExtendedRegExpMatchArray\n commands: SingleCommands\n chain: () => ChainedCommands\n can: () => CanCommands\n }) => void | null\n }) {\n this.find = config.find\n this.handler = config.handler\n }\n}\n\nconst inputRuleMatcherHandler = (text: string, find: InputRuleFinder): ExtendedRegExpMatchArray | null => {\n if (isRegExp(find)) {\n return find.exec(text)\n }\n\n const inputRuleMatch = find(text)\n\n if (!inputRuleMatch) {\n return null\n }\n\n const result: ExtendedRegExpMatchArray = [inputRuleMatch.text]\n\n result.index = inputRuleMatch.index\n result.input = text\n result.data = inputRuleMatch.data\n\n if (inputRuleMatch.replaceWith) {\n if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {\n console.warn('[tiptap warn]: \"inputRuleMatch.replaceWith\" must be part of \"inputRuleMatch.text\".')\n }\n\n result.push(inputRuleMatch.replaceWith)\n }\n\n return result\n}\n\nfunction run(config: {\n editor: Editor\n from: number\n to: number\n text: string\n rules: InputRule[]\n plugin: Plugin\n}): boolean {\n const { editor, from, to, text, rules, plugin } = config\n const { view } = editor\n\n if (view.composing) {\n return false\n }\n\n const $from = view.state.doc.resolve(from)\n\n if (\n // check for code node\n $from.parent.type.spec.code ||\n // check for code mark\n !!($from.nodeBefore || $from.nodeAfter)?.marks.find(mark => mark.type.spec.code)\n ) {\n return false\n }\n\n let matched = false\n\n const textBefore = getTextContentFromNodes($from) + text\n\n rules.forEach(rule => {\n if (matched) {\n return\n }\n\n const match = inputRuleMatcherHandler(textBefore, rule.find)\n\n if (!match) {\n return\n }\n\n const tr = view.state.tr\n const state = createChainableState({\n state: view.state,\n transaction: tr,\n })\n const range = {\n from: from - (match[0].length - text.length),\n to,\n }\n\n const { commands, chain, can } = new CommandManager({\n editor,\n state,\n })\n\n const handler = rule.handler({\n state,\n range,\n match,\n commands,\n chain,\n can,\n })\n\n // stop if there are no changes\n if (handler === null || !tr.steps.length) {\n return\n }\n\n // store transform as meta data\n // so we can undo input rules within the `undoInputRules` command\n tr.setMeta(plugin, {\n transform: tr,\n from,\n to,\n text,\n })\n\n view.dispatch(tr)\n matched = true\n })\n\n return matched\n}\n\n/**\n * Create an input rules plugin. When enabled, it will cause text\n * input that matches any of the given rules to trigger the rule’s\n * action.\n */\nexport function inputRulesPlugin(props: { editor: Editor; rules: InputRule[] }): Plugin {\n const { editor, rules } = props\n const plugin = new Plugin({\n state: {\n init() {\n return null\n },\n apply(tr, prev, state) {\n const stored = tr.getMeta(plugin)\n\n if (stored) {\n return stored\n }\n\n // if InputRule is triggered by insertContent()\n const simulatedInputMeta = tr.getMeta('applyInputRules') as\n | undefined\n | {\n from: number\n text: string | ProseMirrorNode | Fragment\n }\n const isSimulatedInput = !!simulatedInputMeta\n\n if (isSimulatedInput) {\n setTimeout(() => {\n let { text } = simulatedInputMeta\n\n if (typeof text === 'string') {\n text = text as string\n } else {\n text = getHTMLFromFragment(Fragment.from(text), state.schema)\n }\n\n const { from } = simulatedInputMeta\n const to = from + text.length\n\n run({\n editor,\n from,\n to,\n text,\n rules,\n plugin,\n })\n })\n }\n\n return tr.selectionSet || tr.docChanged ? null : prev\n },\n },\n\n props: {\n handleTextInput(view, from, to, text) {\n return run({\n editor,\n from,\n to,\n text,\n rules,\n plugin,\n })\n },\n\n handleDOMEvents: {\n compositionend: view => {\n setTimeout(() => {\n const { $cursor } = view.state.selection as TextSelection\n\n if ($cursor) {\n run({\n editor,\n from: $cursor.pos,\n to: $cursor.pos,\n text: '',\n rules,\n plugin,\n })\n }\n })\n\n return false\n },\n },\n\n // add support for input rules to trigger on enter\n // this is useful for example for code blocks\n handleKeyDown(view, event) {\n if (event.key !== 'Enter') {\n return false\n }\n\n const { $cursor } = view.state.selection as TextSelection\n\n if ($cursor) {\n return run({\n editor,\n from: $cursor.pos,\n to: $cursor.pos,\n text: '\\n',\n rules,\n plugin,\n })\n }\n\n return false\n },\n },\n\n // @ts-ignore\n isInputRules: true,\n }) as Plugin\n\n return plugin\n}\n","// see: https://github.com/mesqueeb/is-what/blob/88d6e4ca92fb2baab6003c54e02eedf4e729e5ab/src/index.ts\n\nfunction getType(value: any): string {\n return Object.prototype.toString.call(value).slice(8, -1)\n}\n\nexport function isPlainObject(value: any): value is Record<string, any> {\n if (getType(value) !== 'Object') {\n return false\n }\n\n return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype\n}\n","import { isPlainObject } from './isPlainObject.js'\n\nexport function mergeDeep(target: Record<string, any>, source: Record<string, any>): Record<string, any> {\n const output = { ...target }\n\n if (isPlainObject(target) && isPlainObject(source)) {\n Object.keys(source).forEach(key => {\n if (isPlainObject(source[key]) && isPlainObject(target[key])) {\n output[key] = mergeDeep(target[key], source[key])\n } else {\n output[key] = source[key]\n }\n })\n }\n\n return output\n}\n","import type { Plugin } from '@tiptap/pm/state'\n\nimport type { Editor } from './Editor.js'\nimport { getExtensionField } from './helpers/getExtensionField.js'\nimport type { ExtensionConfig, MarkConfig, NodeConfig } from './index.js'\nimport type { InputRule } from './InputRule.js'\nimport type { Mark } from './Mark.js'\nimport type { Node } from './Node.js'\nimport type { PasteRule } from './PasteRule.js'\nimport type {\n AnyConfig,\n EditorEvents,\n Extensions,\n GlobalAttributes,\n KeyboardShortcutCommand,\n ParentConfig,\n RawCommands,\n} from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\nimport { mergeDeep } from './utilities/mergeDeep.js'\n\nexport interface ExtendableConfig<\n Options = any,\n Storage = any,\n Config extends\n | ExtensionConfig<Options, Storage>\n | NodeConfig<Options, Storage>\n | MarkConfig<Options, Storage>\n | ExtendableConfig<Options, Storage> = ExtendableConfig<Options, Storage, any, any>,\n PMType = any,\n> {\n /**\n * The extension name - this must be unique.\n * It will be used to identify the extension.\n *\n * @example 'myExtension'\n */\n name: string\n\n /**\n * The priority of your extension. The higher, the earlier it will be called\n * and will take precedence over other extensions with a lower priority.\n * @default 100\n * @example 101\n */\n priority?: number\n\n /**\n * This method will add options to this extension\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#settings\n * @example\n * addOptions() {\n * return {\n * myOption: 'foo',\n * myOtherOption: 10,\n * }\n */\n addOptions?: (this: { name: string; parent: ParentConfig<Config>['addOptions'] }) => Options\n\n /**\n * The default storage this extension can save data to.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#storage\n * @example\n * defaultStorage: {\n * prefetchedUsers: [],\n * loading: false,\n * }\n */\n addStorage?: (this: { name: string; options: Options; parent: ParentConfig<Config>['addStorage'] }) => Storage\n\n /**\n * This function adds globalAttributes to specific nodes.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#global-attributes\n * @example\n * addGlobalAttributes() {\n * return [\n * {\n // Extend the following extensions\n * types: [\n * 'heading',\n * 'paragraph',\n * ],\n * // … with those attributes\n * attributes: {\n * textAlign: {\n * default: 'left',\n * renderHTML: attributes => ({\n * style: `text-align: ${attributes.textAlign}`,\n * }),\n * parseHTML: element => element.style.textAlign || 'left',\n * },\n * },\n * },\n * ]\n * }\n */\n addGlobalAttributes?: (this: {\n name: string\n options: Options\n storage: Storage\n extensions: (Node | Mark)[]\n parent: ParentConfig<Config>['addGlobalAttributes']\n }) => GlobalAttributes\n\n /**\n * This function adds commands to the editor\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#commands\n * @example\n * addCommands() {\n * return {\n * myCommand: () => ({ chain }) => chain().setMark('type', 'foo').run(),\n * }\n * }\n */\n addCommands?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['addCommands']\n }) => Partial<RawCommands>\n\n /**\n * This function registers keyboard shortcuts.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#keyboard-shortcuts\n * @example\n * addKeyboardShortcuts() {\n * return {\n * 'Mod-l': () => this.editor.commands.toggleBulletList(),\n * }\n * },\n */\n addKeyboardShortcuts?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['addKeyboardShortcuts']\n }) => {\n [key: string]: KeyboardShortcutCommand\n }\n\n /**\n * This function adds input rules to the editor.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#input-rules\n * @example\n * addInputRules() {\n * return [\n * markInputRule({\n * find: inputRegex,\n * type: this.type,\n * }),\n * ]\n * },\n */\n addInputRules?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['addInputRules']\n }) => InputRule[]\n\n /**\n * This function adds paste rules to the editor.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#paste-rules\n * @example\n * addPasteRules() {\n * return [\n * markPasteRule({\n * find: pasteRegex,\n * type: this.type,\n * }),\n * ]\n * },\n */\n addPasteRules?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['addPasteRules']\n }) => PasteRule[]\n\n /**\n * This function adds Prosemirror plugins to the editor\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#prosemirror-plugins\n * @example\n * addProseMirrorPlugins() {\n * return [\n * customPlugin(),\n * ]\n * }\n */\n addProseMirrorPlugins?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['addProseMirrorPlugins']\n }) => Plugin[]\n\n /**\n * This function adds additional extensions to the editor. This is useful for\n * building extension kits.\n * @example\n * addExtensions() {\n * return [\n * BulletList,\n * OrderedList,\n * ListItem\n * ]\n * }\n */\n addExtensions?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<Config>['addExtensions']\n }) => Extensions\n\n /**\n * This function extends the schema of the node.\n * @example\n * extendNodeSchema() {\n * return {\n * group: 'inline',\n * selectable: false,\n * }\n * }\n */\n extendNodeSchema?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<Config>['extendNodeSchema']\n },\n extension: Node,\n ) => Record<string, any>)\n | null\n\n /**\n * This function extends the schema of the mark.\n * @example\n * extendMarkSchema() {\n * return {\n * group: 'inline',\n * selectable: false,\n * }\n * }\n */\n extendMarkSchema?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<Config>['extendMarkSchema']\n },\n extension: Mark,\n ) => Record<string, any>)\n | null\n\n /**\n * The editor is not ready yet.\n */\n onBeforeCreate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onBeforeCreate']\n },\n event: EditorEvents['beforeCreate'],\n ) => void)\n | null\n\n /**\n * The editor is ready.\n */\n onCreate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onCreate']\n },\n event: EditorEvents['create'],\n ) => void)\n | null\n\n /**\n * The content has changed.\n */\n onUpdate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onUpdate']\n },\n event: EditorEvents['update'],\n ) => void)\n | null\n\n /**\n * The selection has changed.\n */\n onSelectionUpdate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onSelectionUpdate']\n },\n event: EditorEvents['selectionUpdate'],\n ) => void)\n | null\n\n /**\n * The editor state has changed.\n */\n onTransaction?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onTransaction']\n },\n event: EditorEvents['transaction'],\n ) => void)\n | null\n\n /**\n * The editor is focused.\n */\n onFocus?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onFocus']\n },\n event: EditorEvents['focus'],\n ) => void)\n | null\n\n /**\n * The editor isn’t focused anymore.\n */\n onBlur?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onBlur']\n },\n event: EditorEvents['blur'],\n ) => void)\n | null\n\n /**\n * The editor is destroyed.\n */\n onDestroy?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onDestroy']\n },\n event: EditorEvents['destroy'],\n ) => void)\n | null\n}\n\nexport class Extendable<\n Options = any,\n Storage = any,\n Config = ExtensionConfig<Options, Storage> | NodeConfig<Options, Storage> | MarkConfig<Options, Storage>,\n> {\n type = 'extendable'\n parent: Extendable | null = null\n\n child: Extendable | null = null\n\n name = ''\n\n config: Config = {\n name: this.name,\n } as Config\n\n constructor(config: Partial<Config> = {}) {\n this.config = {\n ...this.config,\n ...config,\n }\n\n this.name = (this.config as any).name\n }\n\n get options(): Options {\n return {\n ...(callOrReturn(\n getExtensionField<AnyConfig['addOptions']>(this as any, 'addOptions', {\n name: this.name,\n }),\n ) || {}),\n }\n }\n\n get storage(): Readonly<Storage> {\n return {\n ...(callOrReturn(\n getExtensionField<AnyConfig['addStorage']>(this as any, 'addStorage', {\n name: this.name,\n options: this.options,\n }),\n ) || {}),\n }\n }\n\n configure(options: Partial<Options> = {}) {\n const extension = this.extend<Options, Storage, Config>({\n ...this.config,\n addOptions: () => {\n return mergeDeep(this.options as Record<string, any>, options) as Options\n },\n })\n\n extension.name = this.name\n extension.parent = this.parent\n\n return extension\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig =\n | ExtensionConfig<ExtendedOptions, ExtendedStorage>\n | NodeConfig<ExtendedOptions, ExtendedStorage>\n | MarkConfig<ExtendedOptions, ExtendedStorage>,\n >(extendedConfig: Partial<ExtendedConfig> = {}): Extendable<ExtendedOptions, ExtendedStorage> {\n const extension = new (this.constructor as any)({ ...this.config, ...extendedConfig })\n\n extension.parent = this\n this.child = extension\n extension.name = 'name' in extendedConfig ? extendedConfig.name : extension.parent.name\n\n return extension\n }\n}\n","import type { DOMOutputSpec, Mark as ProseMirrorMark, MarkSpec, MarkType } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { ExtendableConfig } from './Extendable.js'\nimport { Extendable } from './Extendable.js'\nimport type { Attributes, MarkViewRenderer, ParentConfig } from './types.js'\n\nexport interface MarkConfig<Options = any, Storage = any>\n extends ExtendableConfig<Options, Storage, MarkConfig<Options, Storage>, MarkType> {\n /**\n * Mark View\n */\n addMarkView?:\n | ((this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: MarkType\n parent: ParentConfig<MarkConfig<Options, Storage>>['addMarkView']\n }) => MarkViewRenderer)\n | null\n\n /**\n * Keep mark after split node\n */\n keepOnSplit?: boolean | (() => boolean)\n\n /**\n * Inclusive\n */\n inclusive?:\n | MarkSpec['inclusive']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['inclusive']\n editor?: Editor\n }) => MarkSpec['inclusive'])\n\n /**\n * Excludes\n */\n excludes?:\n | MarkSpec['excludes']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['excludes']\n editor?: Editor\n }) => MarkSpec['excludes'])\n\n /**\n * Marks this Mark as exitable\n */\n exitable?: boolean | (() => boolean)\n\n /**\n * Group\n */\n group?:\n | MarkSpec['group']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['group']\n editor?: Editor\n }) => MarkSpec['group'])\n\n /**\n * Spanning\n */\n spanning?:\n | MarkSpec['spanning']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['spanning']\n editor?: Editor\n }) => MarkSpec['spanning'])\n\n /**\n * Code\n */\n code?:\n | boolean\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['code']\n editor?: Editor\n }) => boolean)\n\n /**\n * Parse HTML\n */\n parseHTML?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['parseHTML']\n editor?: Editor\n }) => MarkSpec['parseDOM']\n\n /**\n * Render HTML\n */\n renderHTML?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['renderHTML']\n editor?: Editor\n },\n props: {\n mark: ProseMirrorMark\n HTMLAttributes: Record<string, any>\n },\n ) => DOMOutputSpec)\n | null\n\n /**\n * Attributes\n */\n addAttributes?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['addAttributes']\n editor?: Editor\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n }) => Attributes | {}\n}\n\n/**\n * The Mark class is used to create custom mark extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Mark<Options = any, Storage = any> extends Extendable<Options, Storage, MarkConfig<Options, Storage>> {\n type = 'mark'\n\n /**\n * Create a new Mark instance\n * @param config - Mark configuration object or a function that returns a configuration object\n */\n static create<O = any, S = any>(config: Partial<MarkConfig<O, S>> | (() => Partial<MarkConfig<O, S>>) = {}) {\n // If the config is a function, execute it to get the configuration object\n const resolvedConfig = typeof config === 'function' ? config() : config\n return new Mark<O, S>(resolvedConfig)\n }\n\n static handleExit({ editor, mark }: { editor: Editor; mark: Mark }) {\n const { tr } = editor.state\n const currentPos = editor.state.selection.$from\n const isAtEnd = currentPos.pos === currentPos.end()\n\n if (isAtEnd) {\n const currentMarks = currentPos.marks()\n const isInMark = !!currentMarks.find(m => m?.type.name === mark.name)\n\n if (!isInMark) {\n return false\n }\n\n const removeMark = currentMarks.find(m => m?.type.name === mark.name)\n\n if (removeMark) {\n tr.removeStoredMark(removeMark)\n }\n tr.insertText(' ', currentPos.pos)\n\n editor.view.dispatch(tr)\n\n return true\n }\n\n return false\n }\n\n configure(options?: Partial<Options>) {\n return super.configure(options) as Mark<Options, Storage>\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig = MarkConfig<ExtendedOptions, ExtendedStorage>,\n >(extendedConfig?: Partial<ExtendedConfig> | (() => Partial<ExtendedConfig>)) {\n // If the extended config is a function, execute it to get the configuration object\n const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n return super.extend(resolvedConfig) as Mark<ExtendedOptions, ExtendedStorage>\n }\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\nimport { Plugin } from '@tiptap/pm/state'\n\nimport { CommandManager } from './CommandManager.js'\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport type { CanCommands, ChainedCommands, ExtendedRegExpMatchArray, Range, SingleCommands } from './types.js'\nimport { isNumber } from './utilities/isNumber.js'\nimport { isRegExp } from './utilities/isRegExp.js'\n\nexport type PasteRuleMatch = {\n index: number\n text: string\n replaceWith?: string\n match?: RegExpMatchArray\n data?: Record<string, any>\n}\n\nexport type PasteRuleFinder =\n | RegExp\n | ((text: string, event?: ClipboardEvent | null) => PasteRuleMatch[] | null | undefined)\n\n/**\n * Paste rules are used to react to pasted content.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport class PasteRule {\n find: PasteRuleFinder\n\n handler: (props: {\n state: EditorState\n range: Range\n match: ExtendedRegExpMatchArray\n commands: SingleCommands\n chain: () => ChainedCommands\n can: () => CanCommands\n pasteEvent: ClipboardEvent | null\n dropEvent: DragEvent | null\n }) => void | null\n\n constructor(config: {\n find: PasteRuleFinder\n handler: (props: {\n can: () => CanCommands\n chain: () => ChainedCommands\n commands: SingleCommands\n dropEvent: DragEvent | null\n match: ExtendedRegExpMatchArray\n pasteEvent: ClipboardEvent | null\n range: Range\n state: EditorState\n }) => void | null\n }) {\n this.find = config.find\n this.handler = config.handler\n }\n}\n\nconst pasteRuleMatcherHandler = (\n text: string,\n find: PasteRuleFinder,\n event?: ClipboardEvent | null,\n): ExtendedRegExpMatchArray[] => {\n if (isRegExp(find)) {\n return [...text.matchAll(find)]\n }\n\n const matches = find(text, event)\n\n if (!matches) {\n return []\n }\n\n return matches.map(pasteRuleMatch => {\n const result: ExtendedRegExpMatchArray = [pasteRuleMatch.text]\n\n result.index = pasteRuleMatch.index\n result.input = text\n result.data = pasteRuleMatch.data\n\n if (pasteRuleMatch.replaceWith) {\n if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) {\n console.warn('[tiptap warn]: \"pasteRuleMatch.replaceWith\" must be part of \"pasteRuleMatch.text\".')\n }\n\n result.push(pasteRuleMatch.replaceWith)\n }\n\n return result\n })\n}\n\nfunction run(config: {\n editor: Editor\n state: EditorState\n from: number\n to: number\n rule: PasteRule\n pasteEvent: ClipboardEvent | null\n dropEvent: DragEvent | null\n}): boolean {\n const { editor, state, from, to, rule, pasteEvent, dropEvent } = config\n\n const { commands, chain, can } = new CommandManager({\n editor,\n state,\n })\n\n const handlers: (void | null)[] = []\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isTextblock || node.type.spec.code) {\n return\n }\n\n const resolvedFrom = Math.max(from, pos)\n const resolvedTo = Math.min(to, pos + node.content.size)\n const textToMatch = node.textBetween(resolvedFrom - pos, resolvedTo - pos, undefined, '\\ufffc')\n\n const matches = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent)\n\n matches.forEach(match => {\n if (match.index === undefined) {\n return\n }\n\n const start = resolvedFrom + match.index + 1\n const end = start + match[0].length\n const range = {\n from: state.tr.mapping.map(start),\n to: state.tr.mapping.map(end),\n }\n\n const handler = rule.handler({\n state,\n range,\n match,\n commands,\n chain,\n can,\n pasteEvent,\n dropEvent,\n })\n\n handlers.push(handler)\n })\n })\n\n const success = handlers.every(handler => handler !== null)\n\n return success\n}\n\n// When dragging across editors, must get another editor instance to delete selection content.\nlet tiptapDragFromOtherEditor: Editor | null = null\n\nconst createClipboardPasteEvent = (text: string) => {\n const event = new ClipboardEvent('paste', {\n clipboardData: new DataTransfer(),\n })\n\n event.clipboardData?.setData('text/html', text)\n\n return event\n}\n\n/**\n * Create an paste rules plugin. When enabled, it will cause pasted\n * text that matches any of the given rules to trigger the rule’s\n * action.\n */\nexport function pasteRulesPlugin(props: { editor: Editor; rules: PasteRule[] }): Plugin[] {\n const { editor, rules } = props\n let dragSourceElement: Element | null = null\n let isPastedFromProseMirror = false\n let isDroppedFromProseMirror = false\n let pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null\n let dropEvent: DragEvent | null\n\n try {\n dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null\n } catch {\n dropEvent = null\n }\n\n const processEvent = ({\n state,\n from,\n to,\n rule,\n pasteEvt,\n }: {\n state: EditorState\n from: number\n to: { b: number }\n rule: PasteRule\n pasteEvt: ClipboardEvent | null\n }) => {\n const tr = state.tr\n const chainableState = createChainableState({\n state,\n transaction: tr,\n })\n\n const handler = run({\n editor,\n state: chainableState,\n from: Math.max(from - 1, 0),\n to: to.b - 1,\n rule,\n pasteEvent: pasteEvt,\n dropEvent,\n })\n\n if (!handler || !tr.steps.length) {\n return\n }\n\n try {\n dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null\n } catch {\n dropEvent = null\n }\n pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null\n\n return tr\n }\n\n const plugins = rules.map(rule => {\n return new Plugin({\n // we register a global drag handler to track the current drag source element\n view(view) {\n const handleDragstart = (event: DragEvent) => {\n dragSourceElement = view.dom.parentElement?.contains(event.target as Element) ? view.dom.parentElement : null\n\n if (dragSourceElement) {\n tiptapDragFromOtherEditor = editor\n }\n }\n\n const handleDragend = () => {\n if (tiptapDragFromOtherEditor) {\n tiptapDragFromOtherEditor = null\n }\n }\n\n window.addEventListener('dragstart', handleDragstart)\n window.addEventListener('dragend', handleDragend)\n\n return {\n destroy() {\n window.removeEventListener('dragstart', handleDragstart)\n window.removeEventListener('dragend', handleDragend)\n },\n }\n },\n\n props: {\n handleDOMEvents: {\n drop: (view, event: Event) => {\n isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement\n dropEvent = event as DragEvent\n\n if (!isDroppedFromProseMirror) {\n const dragFromOtherEditor = tiptapDragFromOtherEditor\n\n if (dragFromOtherEditor?.isEditable) {\n // setTimeout to avoid the wrong content after drop, timeout arg can't be empty or 0\n setTimeout(() => {\n const selection = dragFromOtherEditor.state.selection\n\n if (selection) {\n dragFromOtherEditor.commands.deleteRange({ from: selection.from, to: selection.to })\n }\n }, 10)\n }\n }\n return false\n },\n\n paste: (_view, event: Event) => {\n const html = (event as ClipboardEvent).clipboardData?.getData('text/html')\n\n pasteEvent = event as ClipboardEvent\n\n isPastedFromProseMirror = !!html?.includes('data-pm-slice')\n\n return false\n },\n },\n },\n\n appendTransaction: (transactions, oldState, state) => {\n const transaction = transactions[0]\n const isPaste = transaction.getMeta('uiEvent') === 'paste' && !isPastedFromProseMirror\n const isDrop = transaction.getMeta('uiEvent') === 'drop' && !isDroppedFromProseMirror\n\n // if PasteRule is triggered by insertContent()\n const simulatedPasteMeta = transaction.getMeta('applyPasteRules') as\n | undefined\n | { from: number; text: string | ProseMirrorNode | Fragment }\n const isSimulatedPaste = !!simulatedPasteMeta\n\n if (!isPaste && !isDrop && !isSimulatedPaste) {\n return\n }\n\n // Handle simulated paste\n if (isSimulatedPaste) {\n let { text } = simulatedPasteMeta\n\n if (typeof text === 'string') {\n text = text as string\n } else {\n text = getHTMLFromFragment(Fragment.from(text), state.schema)\n }\n\n const { from } = simulatedPasteMeta\n const to = from + text.length\n\n const pasteEvt = createClipboardPasteEvent(text)\n\n return processEvent({\n rule,\n state,\n from,\n to: { b: to },\n pasteEvt,\n })\n }\n\n // handle actual paste/drop\n const from = oldState.doc.content.findDiffStart(state.doc.content)\n const to = oldState.doc.content.findDiffEnd(state.doc.content)\n\n // stop if there is no changed range\n if (!isNumber(from) || !to || from === to.b) {\n return\n }\n\n return processEvent({\n rule,\n state,\n from,\n to,\n pasteEvt: pasteEvent,\n })\n },\n })\n })\n\n return plugins\n}\n","export function isNumber(value: any): value is number {\n return typeof value === 'number'\n}\n","export { ClipboardTextSerializer } from './clipboardTextSerializer.js'\nexport { Commands } from './commands.js'\nexport { Delete } from './delete.js'\nexport { Drop } from './drop.js'\nexport { Editable } from './editable.js'\nexport { FocusEvents, focusEventsPluginKey } from './focusEvents.js'\nexport { Keymap } from './keymap.js'\nexport { Paste } from './paste.js'\nexport { Tabindex } from './tabindex.js'\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\nimport { getTextBetween } from '../helpers/getTextBetween.js'\nimport { getTextSerializersFromSchema } from '../helpers/getTextSerializersFromSchema.js'\n\nexport type ClipboardTextSerializerOptions = {\n blockSeparator?: string\n}\n\nexport const ClipboardTextSerializer = Extension.create<ClipboardTextSerializerOptions>({\n name: 'clipboardTextSerializer',\n\n addOptions() {\n return {\n blockSeparator: undefined,\n }\n },\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('clipboardTextSerializer'),\n props: {\n clipboardTextSerializer: () => {\n const { editor } = this\n const { state, schema } = editor\n const { doc, selection } = state\n const { ranges } = selection\n const from = Math.min(...ranges.map(range => range.$from.pos))\n const to = Math.max(...ranges.map(range => range.$to.pos))\n const textSerializers = getTextSerializersFromSchema(schema)\n const range = { from, to }\n\n return getTextBetween(doc, range, {\n ...(this.options.blockSeparator !== undefined ? { blockSeparator: this.options.blockSeparator } : {}),\n textSerializers,\n })\n },\n },\n }),\n ]\n },\n})\n","import { type ExtendableConfig, Extendable } from './Extendable.js'\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface ExtensionConfig<Options = any, Storage = any>\n extends ExtendableConfig<Options, Storage, ExtensionConfig<Options, Storage>, null> {}\n\n/**\n * The Extension class is the base class for all extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Extension<Options = any, Storage = any> extends Extendable<\n Options,\n Storage,\n ExtensionConfig<Options, Storage>\n> {\n type = 'extension'\n\n /**\n * Create a new Extension instance\n * @param config - Extension configuration object or a function that returns a configuration object\n */\n static create<O = any, S = any>(\n config: Partial<ExtensionConfig<O, S>> | (() => Partial<ExtensionConfig<O, S>>) = {},\n ) {\n // If the config is a function, execute it to get the configuration object\n const resolvedConfig = typeof config === 'function' ? config() : config\n return new Extension<O, S>(resolvedConfig)\n }\n\n configure(options?: Partial<Options>) {\n return super.configure(options) as Extension<Options, Storage>\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig = ExtensionConfig<ExtendedOptions, ExtendedStorage>,\n >(extendedConfig?: Partial<ExtendedConfig> | (() => Partial<ExtendedConfig>)) {\n // If the extended config is a function, execute it to get the configuration object\n const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n return super.extend(resolvedConfig) as Extension<ExtendedOptions, ExtendedStorage>\n }\n}\n","export * from './blur.js'\nexport * from './clearContent.js'\nexport * from './clearNodes.js'\nexport * from './command.js'\nexport * from './createParagraphNear.js'\nexport * from './cut.js'\nexport * from './deleteCurrentNode.js'\nexport * from './deleteNode.js'\nexport * from './deleteRange.js'\nexport * from './deleteSelection.js'\nexport * from './enter.js'\nexport * from './exitCode.js'\nexport * from './extendMarkRange.js'\nexport * from './first.js'\nexport * from './focus.js'\nexport * from './forEach.js'\nexport * from './insertContent.js'\nexport * from './insertContentAt.js'\nexport * from './join.js'\nexport * from './joinItemBackward.js'\nexport * from './joinItemForward.js'\nexport * from './joinTextblockBackward.js'\nexport * from './joinTextblockForward.js'\nexport * from './keyboardShortcut.js'\nexport * from './lift.js'\nexport * from './liftEmptyBlock.js'\nexport * from './liftListItem.js'\nexport * from './newlineInCode.js'\nexport * from './resetAttributes.js'\nexport * from './scrollIntoView.js'\nexport * from './selectAll.js'\nexport * from './selectNodeBackward.js'\nexport * from './selectNodeForward.js'\nexport * from './selectParentNode.js'\nexport * from './selectTextblockEnd.js'\nexport * from './selectTextblockStart.js'\nexport * from './setContent.js'\nexport * from './setMark.js'\nexport * from './setMeta.js'\nexport * from './setNode.js'\nexport * from './setNodeSelection.js'\nexport * from './setTextSelection.js'\nexport * from './sinkListItem.js'\nexport * from './splitBlock.js'\nexport * from './splitListItem.js'\nexport * from './toggleList.js'\nexport * from './toggleMark.js'\nexport * from './toggleNode.js'\nexport * from './toggleWrap.js'\nexport * from './undoInputRule.js'\nexport * from './unsetAllMarks.js'\nexport * from './unsetMark.js'\nexport * from './updateAttributes.js'\nexport * from './wrapIn.js'\nexport * from './wrapInList.js'\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n blur: {\n /**\n * Removes focus from the editor.\n * @example editor.commands.blur()\n */\n blur: () => ReturnType\n }\n }\n}\n\nexport const blur: RawCommands['blur'] =\n () =>\n ({ editor, view }) => {\n requestAnimationFrame(() => {\n if (!editor.isDestroyed) {\n ;(view.dom as HTMLElement).blur()\n\n // Browsers should remove the caret on blur but safari does not.\n // See: https://github.com/ueberdosis/tiptap/issues/2405\n window?.getSelection()?.removeAllRanges()\n }\n })\n\n return true\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n clearContent: {\n /**\n * Clear the whole document.\n * @example editor.commands.clearContent()\n */\n clearContent: (\n /**\n * Whether to emit an update event.\n * @default true\n */\n emitUpdate?: boolean,\n ) => ReturnType\n }\n }\n}\n\nexport const clearContent: RawCommands['clearContent'] =\n (emitUpdate = true) =>\n ({ commands }) => {\n return commands.setContent('', { emitUpdate })\n }\n","import { liftTarget } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n clearNodes: {\n /**\n * Normalize nodes to a simple paragraph.\n * @example editor.commands.clearNodes()\n */\n clearNodes: () => ReturnType\n }\n }\n}\n\nexport const clearNodes: RawCommands['clearNodes'] =\n () =>\n ({ state, tr, dispatch }) => {\n const { selection } = tr\n const { ranges } = selection\n\n if (!dispatch) {\n return true\n }\n\n ranges.forEach(({ $from, $to }) => {\n state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (node.type.isText) {\n return\n }\n\n const { doc, mapping } = tr\n const $mappedFrom = doc.resolve(mapping.map(pos))\n const $mappedTo = doc.resolve(mapping.map(pos + node.nodeSize))\n const nodeRange = $mappedFrom.blockRange($mappedTo)\n\n if (!nodeRange) {\n return\n }\n\n const targetLiftDepth = liftTarget(nodeRange)\n\n if (node.type.isTextblock) {\n const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index())\n\n tr.setNodeMarkup(nodeRange.start, defaultType)\n }\n\n if (targetLiftDepth || targetLiftDepth === 0) {\n tr.lift(nodeRange, targetLiftDepth)\n }\n })\n })\n\n return true\n }\n","import type { Command, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n command: {\n /**\n * Define a command inline.\n * @param fn The command function.\n * @example\n * editor.commands.command(({ tr, state }) => {\n * ...\n * return true\n * })\n */\n command: (fn: (props: Parameters<Command>[0]) => boolean) => ReturnType\n }\n }\n}\n\nexport const command: RawCommands['command'] = fn => props => {\n return fn(props)\n}\n","import { createParagraphNear as originalCreateParagraphNear } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n createParagraphNear: {\n /**\n * Create a paragraph nearby.\n * @example editor.commands.createParagraphNear()\n */\n createParagraphNear: () => ReturnType\n }\n }\n}\n\nexport const createParagraphNear: RawCommands['createParagraphNear'] =\n () =>\n ({ state, dispatch }) => {\n return originalCreateParagraphNear(state, dispatch)\n }\n","import { TextSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n cut: {\n /**\n * Cuts content from a range and inserts it at a given position.\n * @param range The range to cut.\n * @param range.from The start position of the range.\n * @param range.to The end position of the range.\n * @param targetPos The position to insert the content at.\n * @example editor.commands.cut({ from: 1, to: 3 }, 5)\n */\n cut: ({ from, to }: { from: number; to: number }, targetPos: number) => ReturnType\n }\n }\n}\n\nexport const cut: RawCommands['cut'] =\n (originRange, targetPos) =>\n ({ editor, tr }) => {\n const { state } = editor\n\n const contentSlice = state.doc.slice(originRange.from, originRange.to)\n\n tr.deleteRange(originRange.from, originRange.to)\n const newPos = tr.mapping.map(targetPos)\n\n tr.insert(newPos, contentSlice.content)\n\n tr.setSelection(new TextSelection(tr.doc.resolve(Math.max(newPos - 1, 0))))\n\n return true\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n deleteCurrentNode: {\n /**\n * Delete the node that currently has the selection anchor.\n * @example editor.commands.deleteCurrentNode()\n */\n deleteCurrentNode: () => ReturnType\n }\n }\n}\n\nexport const deleteCurrentNode: RawCommands['deleteCurrentNode'] =\n () =>\n ({ tr, dispatch }) => {\n const { selection } = tr\n const currentNode = selection.$anchor.node()\n\n // if there is content inside the current node, break out of this command\n if (currentNode.content.size > 0) {\n return false\n }\n\n const $pos = tr.selection.$anchor\n\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth)\n\n if (node.type === currentNode.type) {\n if (dispatch) {\n const from = $pos.before(depth)\n const to = $pos.after(depth)\n\n tr.delete(from, to).scrollIntoView()\n }\n\n return true\n }\n }\n\n return false\n }\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n deleteNode: {\n /**\n * Delete a node with a given type or name.\n * @param typeOrName The type or name of the node.\n * @example editor.commands.deleteNode('paragraph')\n */\n deleteNode: (typeOrName: string | NodeType) => ReturnType\n }\n }\n}\n\nexport const deleteNode: RawCommands['deleteNode'] =\n typeOrName =>\n ({ tr, state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n const $pos = tr.selection.$anchor\n\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth)\n\n if (node.type === type) {\n if (dispatch) {\n const from = $pos.before(depth)\n const to = $pos.after(depth)\n\n tr.delete(from, to).scrollIntoView()\n }\n\n return true\n }\n }\n\n return false\n }\n","import type { Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n deleteRange: {\n /**\n * Delete a given range.\n * @param range The range to delete.\n * @example editor.commands.deleteRange({ from: 1, to: 3 })\n */\n deleteRange: (range: Range) => ReturnType\n }\n }\n}\n\nexport const deleteRange: RawCommands['deleteRange'] =\n range =>\n ({ tr, dispatch }) => {\n const { from, to } = range\n\n if (dispatch) {\n tr.delete(from, to)\n }\n\n return true\n }\n","import { deleteSelection as originalDeleteSelection } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n deleteSelection: {\n /**\n * Delete the selection, if there is one.\n * @example editor.commands.deleteSelection()\n */\n deleteSelection: () => ReturnType\n }\n }\n}\n\nexport const deleteSelection: RawCommands['deleteSelection'] =\n () =>\n ({ state, dispatch }) => {\n return originalDeleteSelection(state, dispatch)\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n enter: {\n /**\n * Trigger enter.\n * @example editor.commands.enter()\n */\n enter: () => ReturnType\n }\n }\n}\n\nexport const enter: RawCommands['enter'] =\n () =>\n ({ commands }) => {\n return commands.keyboardShortcut('Enter')\n }\n","import { exitCode as originalExitCode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n exitCode: {\n /**\n * Exit from a code block.\n * @example editor.commands.exitCode()\n */\n exitCode: () => ReturnType\n }\n }\n}\n\nexport const exitCode: RawCommands['exitCode'] =\n () =>\n ({ state, dispatch }) => {\n return originalExitCode(state, dispatch)\n }\n","import type { MarkType } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\n\nimport { getMarkRange } from '../helpers/getMarkRange.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n extendMarkRange: {\n /**\n * Extends the text selection to the current mark by type or name.\n * @param typeOrName The type or name of the mark.\n * @param attributes The attributes of the mark.\n * @example editor.commands.extendMarkRange('bold')\n * @example editor.commands.extendMarkRange('mention', { userId: \"1\" })\n */\n extendMarkRange: (\n /**\n * The type or name of the mark.\n */\n typeOrName: string | MarkType,\n\n /**\n * The attributes of the mark.\n */\n attributes?: Record<string, any>,\n ) => ReturnType\n }\n }\n}\n\nexport const extendMarkRange: RawCommands['extendMarkRange'] =\n (typeOrName, attributes = {}) =>\n ({ tr, state, dispatch }) => {\n const type = getMarkType(typeOrName, state.schema)\n const { doc, selection } = tr\n const { $from, from, to } = selection\n\n if (dispatch) {\n const range = getMarkRange($from, type, attributes)\n\n if (range && range.from <= from && range.to >= to) {\n const newSelection = TextSelection.create(doc, range.from, range.to)\n\n tr.setSelection(newSelection)\n }\n }\n\n return true\n }\n","import type { Command, CommandProps, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n first: {\n /**\n * Runs one command after the other and stops at the first which returns true.\n * @param commands The commands to run.\n * @example editor.commands.first([command1, command2])\n */\n first: (commands: Command[] | ((props: CommandProps) => Command[])) => ReturnType\n }\n }\n}\n\nexport const first: RawCommands['first'] = commands => props => {\n const items = typeof commands === 'function' ? commands(props) : commands\n\n for (let i = 0; i < items.length; i += 1) {\n if (items[i](props)) {\n return true\n }\n }\n\n return false\n}\n","export function isAndroid(): boolean {\n return navigator.platform === 'Android' || /android/i.test(navigator.userAgent)\n}\n","export function isiOS(): boolean {\n return (\n ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator.platform) ||\n // iPad on iOS 13 detection\n (navigator.userAgent.includes('Mac') && 'ontouchend' in document)\n )\n}\n","import { isTextSelection } from '../helpers/isTextSelection.js'\nimport { resolveFocusPosition } from '../helpers/resolveFocusPosition.js'\nimport type { FocusPosition, RawCommands } from '../types.js'\nimport { isAndroid } from '../utilities/isAndroid.js'\nimport { isiOS } from '../utilities/isiOS.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n focus: {\n /**\n * Focus the editor at the given position.\n * @param position The position to focus at.\n * @param options.scrollIntoView Scroll the focused position into view after focusing\n * @example editor.commands.focus()\n * @example editor.commands.focus(32, { scrollIntoView: false })\n */\n focus: (\n /**\n * The position to focus at.\n */\n position?: FocusPosition,\n\n /**\n * Optional options\n * @default { scrollIntoView: true }\n */\n options?: {\n scrollIntoView?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const focus: RawCommands['focus'] =\n (position = null, options = {}) =>\n ({ editor, view, tr, dispatch }) => {\n options = {\n scrollIntoView: true,\n ...options,\n }\n\n const delayedFocus = () => {\n // focus within `requestAnimationFrame` breaks focus on iOS and Android\n // so we have to call this\n if (isiOS() || isAndroid()) {\n ;(view.dom as HTMLElement).focus()\n }\n\n // For React we have to focus asynchronously. Otherwise wild things happen.\n // see: https://github.com/ueberdosis/tiptap/issues/1520\n requestAnimationFrame(() => {\n if (!editor.isDestroyed) {\n view.focus()\n\n if (options?.scrollIntoView) {\n editor.commands.scrollIntoView()\n }\n }\n })\n }\n\n if ((view.hasFocus() && position === null) || position === false) {\n return true\n }\n\n // we don’t try to resolve a NodeSelection or CellSelection\n if (dispatch && position === null && !isTextSelection(editor.state.selection)) {\n delayedFocus()\n return true\n }\n\n // pass through tr.doc instead of editor.state.doc\n // since transactions could change the editors state before this command has been run\n const selection = resolveFocusPosition(tr.doc, position) || editor.state.selection\n const isSameSelection = editor.state.selection.eq(selection)\n\n if (dispatch) {\n if (!isSameSelection) {\n tr.setSelection(selection)\n }\n\n // `tr.setSelection` resets the stored marks\n // so we’ll restore them if the selection is the same as before\n if (isSameSelection && tr.storedMarks) {\n tr.setStoredMarks(tr.storedMarks)\n }\n\n delayedFocus()\n }\n\n return true\n }\n","import type { CommandProps, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n forEach: {\n /**\n * Loop through an array of items.\n */\n forEach: <T>(\n items: T[],\n fn: (\n item: T,\n props: CommandProps & {\n index: number\n },\n ) => boolean,\n ) => ReturnType\n }\n }\n}\n\nexport const forEach: RawCommands['forEach'] = (items, fn) => props => {\n return items.every((item, index) => fn(item, { ...props, index }))\n}\n","import type { Fragment, Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\n\nimport type { Content, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n insertContent: {\n /**\n * Insert a node or string of HTML at the current position.\n * @example editor.commands.insertContent('<h1>Example</h1>')\n * @example editor.commands.insertContent('<h1>Example</h1>', { updateSelection: false })\n */\n insertContent: (\n /**\n * The ProseMirror content to insert.\n */\n value: Content | ProseMirrorNode | Fragment,\n\n /**\n * Optional options\n */\n options?: {\n /**\n * Options for parsing the content.\n */\n parseOptions?: ParseOptions\n\n /**\n * Whether to update the selection after inserting the content.\n */\n updateSelection?: boolean\n applyInputRules?: boolean\n applyPasteRules?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const insertContent: RawCommands['insertContent'] =\n (value, options) =>\n ({ tr, commands }) => {\n return commands.insertContentAt({ from: tr.selection.from, to: tr.selection.to }, value, options)\n }\n","import type { Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\n\nimport { createNodeFromContent } from '../helpers/createNodeFromContent.js'\nimport { selectionToInsertionEnd } from '../helpers/selectionToInsertionEnd.js'\nimport type { Content, Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n insertContentAt: {\n /**\n * Insert a node or string of HTML at a specific position.\n * @example editor.commands.insertContentAt(0, '<h1>Example</h1>')\n */\n insertContentAt: (\n /**\n * The position to insert the content at.\n */\n position: number | Range,\n\n /**\n * The ProseMirror content to insert.\n */\n value: Content | ProseMirrorNode | Fragment,\n\n /**\n * Optional options\n */\n options?: {\n /**\n * Options for parsing the content.\n */\n parseOptions?: ParseOptions\n\n /**\n * Whether to update the selection after inserting the content.\n */\n updateSelection?: boolean\n\n /**\n * Whether to apply input rules after inserting the content.\n */\n applyInputRules?: boolean\n\n /**\n * Whether to apply paste rules after inserting the content.\n */\n applyPasteRules?: boolean\n\n /**\n * Whether to throw an error if the content is invalid.\n */\n errorOnInvalidContent?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nconst isFragment = (nodeOrFragment: ProseMirrorNode | Fragment): nodeOrFragment is Fragment => {\n return !('type' in nodeOrFragment)\n}\n\nexport const insertContentAt: RawCommands['insertContentAt'] =\n (position, value, options) =>\n ({ tr, dispatch, editor }) => {\n if (dispatch) {\n options = {\n parseOptions: editor.options.parseOptions,\n updateSelection: true,\n applyInputRules: false,\n applyPasteRules: false,\n ...options,\n }\n\n let content: Fragment | ProseMirrorNode\n const { selection } = editor.state\n\n const emitContentError = (error: Error) => {\n editor.emit('contentError', {\n editor,\n error,\n disableCollaboration: () => {\n if (\n 'collaboration' in editor.storage &&\n typeof editor.storage.collaboration === 'object' &&\n editor.storage.collaboration\n ) {\n ;(editor.storage.collaboration as any).isDisabled = true\n }\n },\n })\n }\n\n const parseOptions: ParseOptions = {\n preserveWhitespace: 'full',\n ...options.parseOptions,\n }\n\n // If `emitContentError` is enabled, we want to check the content for errors\n // but ignore them (do not remove the invalid content from the document)\n if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) {\n try {\n createNodeFromContent(value, editor.schema, {\n parseOptions,\n errorOnInvalidContent: true,\n })\n } catch (e) {\n emitContentError(e as Error)\n }\n }\n\n try {\n content = createNodeFromContent(value, editor.schema, {\n parseOptions,\n errorOnInvalidContent: options.errorOnInvalidContent ?? editor.options.enableContentCheck,\n })\n } catch (e) {\n emitContentError(e as Error)\n return false\n }\n\n let { from, to } =\n typeof position === 'number' ? { from: position, to: position } : { from: position.from, to: position.to }\n\n let isOnlyTextContent = true\n let isOnlyBlockContent = true\n const nodes = isFragment(content) ? content : [content]\n\n nodes.forEach(node => {\n // check if added node is valid\n node.check()\n\n isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false\n\n isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false\n })\n\n // check if we can replace the wrapping node by\n // the newly inserted content\n // example:\n // replace an empty paragraph by an inserted image\n // instead of inserting the image below the paragraph\n if (from === to && isOnlyBlockContent) {\n const { parent } = tr.doc.resolve(from)\n const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount\n\n if (isEmptyTextBlock) {\n from -= 1\n to += 1\n }\n }\n\n let newContent\n\n // if there is only plain text we have to use `insertText`\n // because this will keep the current marks\n if (isOnlyTextContent) {\n // if value is string, we can use it directly\n // otherwise if it is an array, we have to join it\n if (Array.isArray(value)) {\n newContent = value.map(v => v.text || '').join('')\n } else if (value instanceof Fragment) {\n let text = ''\n\n value.forEach(node => {\n if (node.text) {\n text += node.text\n }\n })\n\n newContent = text\n } else if (typeof value === 'object' && !!value && !!value.text) {\n newContent = value.text\n } else {\n newContent = value as string\n }\n\n tr.insertText(newContent, from, to)\n } else {\n newContent = content\n\n const fromSelectionAtStart = selection.$from.parentOffset === 0\n const isTextSelection = selection.$from.node().isText || selection.$from.node().isTextblock\n const hasContent = selection.$from.node().content.size > 0\n\n if (fromSelectionAtStart && isTextSelection && hasContent) {\n from = Math.max(0, from - 1)\n }\n\n tr.replaceWith(from, to, newContent)\n }\n\n // set cursor at end of inserted content\n if (options.updateSelection) {\n selectionToInsertionEnd(tr, tr.steps.length - 1, -1)\n }\n\n if (options.applyInputRules) {\n tr.setMeta('applyInputRules', { from, text: newContent })\n }\n\n if (options.applyPasteRules) {\n tr.setMeta('applyPasteRules', { from, text: newContent })\n }\n }\n\n return true\n }\n","import {\n joinBackward as originalJoinBackward,\n joinDown as originalJoinDown,\n joinForward as originalJoinForward,\n joinUp as originalJoinUp,\n} from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n joinUp: {\n /**\n * Join the selected block or, if there is a text selection, the closest ancestor block of the selection that can be joined, with the sibling above it.\n * @example editor.commands.joinUp()\n */\n joinUp: () => ReturnType\n }\n joinDown: {\n /**\n * Join the selected block, or the closest ancestor of the selection that can be joined, with the sibling after it.\n * @example editor.commands.joinDown()\n */\n joinDown: () => ReturnType\n }\n joinBackward: {\n /**\n * If the selection is empty and at the start of a textblock, try to reduce the distance between that block and the one before it—if there's a block directly before it that can be joined, join them.\n * If not, try to move the selected block closer to the next one in the document structure by lifting it out of its\n * parent or moving it into a parent of the previous block. Will use the view for accurate (bidi-aware) start-of-textblock detection if given.\n * @example editor.commands.joinBackward()\n */\n joinBackward: () => ReturnType\n }\n joinForward: {\n /**\n * If the selection is empty and the cursor is at the end of a textblock, try to reduce or remove the boundary between that block and the one after it,\n * either by joining them or by moving the other block closer to this one in the tree structure.\n * Will use the view for accurate start-of-textblock detection if given.\n * @example editor.commands.joinForward()\n */\n joinForward: () => ReturnType\n }\n }\n}\n\nexport const joinUp: RawCommands['joinUp'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinUp(state, dispatch)\n }\n\nexport const joinDown: RawCommands['joinDown'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinDown(state, dispatch)\n }\n\nexport const joinBackward: RawCommands['joinBackward'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinBackward(state, dispatch)\n }\n\nexport const joinForward: RawCommands['joinForward'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinForward(state, dispatch)\n }\n","import { joinPoint } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n joinItemBackward: {\n /**\n * Join two items backward.\n * @example editor.commands.joinItemBackward()\n */\n joinItemBackward: () => ReturnType\n }\n }\n}\n\nexport const joinItemBackward: RawCommands['joinItemBackward'] =\n () =>\n ({ state, dispatch, tr }) => {\n try {\n const point = joinPoint(state.doc, state.selection.$from.pos, -1)\n\n if (point === null || point === undefined) {\n return false\n }\n\n tr.join(point, 2)\n\n if (dispatch) {\n dispatch(tr)\n }\n\n return true\n } catch {\n return false\n }\n }\n","import { joinPoint } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n joinItemForward: {\n /**\n * Join two items Forwards.\n * @example editor.commands.joinItemForward()\n */\n joinItemForward: () => ReturnType\n }\n }\n}\n\nexport const joinItemForward: RawCommands['joinItemForward'] =\n () =>\n ({ state, dispatch, tr }) => {\n try {\n const point = joinPoint(state.doc, state.selection.$from.pos, +1)\n\n if (point === null || point === undefined) {\n return false\n }\n\n tr.join(point, 2)\n\n if (dispatch) {\n dispatch(tr)\n }\n\n return true\n } catch {\n return false\n }\n }\n","import { joinTextblockBackward as originalCommand } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n joinTextblockBackward: {\n /**\n * A more limited form of joinBackward that only tries to join the current textblock to the one before it, if the cursor is at the start of a textblock.\n */\n joinTextblockBackward: () => ReturnType\n }\n }\n}\n\nexport const joinTextblockBackward: RawCommands['joinTextblockBackward'] =\n () =>\n ({ state, dispatch }) => {\n return originalCommand(state, dispatch)\n }\n","import { joinTextblockForward as originalCommand } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n joinTextblockForward: {\n /**\n * A more limited form of joinForward that only tries to join the current textblock to the one after it, if the cursor is at the end of a textblock.\n */\n joinTextblockForward: () => ReturnType\n }\n }\n}\n\nexport const joinTextblockForward: RawCommands['joinTextblockForward'] =\n () =>\n ({ state, dispatch }) => {\n return originalCommand(state, dispatch)\n }\n","export function isMacOS(): boolean {\n return typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false\n}\n","import type { RawCommands } from '../types.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isMacOS } from '../utilities/isMacOS.js'\n\nfunction normalizeKeyName(name: string) {\n const parts = name.split(/-(?!$)/)\n let result = parts[parts.length - 1]\n\n if (result === 'Space') {\n result = ' '\n }\n\n let alt\n let ctrl\n let shift\n let meta\n\n for (let i = 0; i < parts.length - 1; i += 1) {\n const mod = parts[i]\n\n if (/^(cmd|meta|m)$/i.test(mod)) {\n meta = true\n } else if (/^a(lt)?$/i.test(mod)) {\n alt = true\n } else if (/^(c|ctrl|control)$/i.test(mod)) {\n ctrl = true\n } else if (/^s(hift)?$/i.test(mod)) {\n shift = true\n } else if (/^mod$/i.test(mod)) {\n if (isiOS() || isMacOS()) {\n meta = true\n } else {\n ctrl = true\n }\n } else {\n throw new Error(`Unrecognized modifier name: ${mod}`)\n }\n }\n\n if (alt) {\n result = `Alt-${result}`\n }\n\n if (ctrl) {\n result = `Ctrl-${result}`\n }\n\n if (meta) {\n result = `Meta-${result}`\n }\n\n if (shift) {\n result = `Shift-${result}`\n }\n\n return result\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n keyboardShortcut: {\n /**\n * Trigger a keyboard shortcut.\n * @param name The name of the keyboard shortcut.\n * @example editor.commands.keyboardShortcut('Mod-b')\n */\n keyboardShortcut: (name: string) => ReturnType\n }\n }\n}\n\nexport const keyboardShortcut: RawCommands['keyboardShortcut'] =\n name =>\n ({ editor, view, tr, dispatch }) => {\n const keys = normalizeKeyName(name).split(/-(?!$)/)\n const key = keys.find(item => !['Alt', 'Ctrl', 'Meta', 'Shift'].includes(item))\n const event = new KeyboardEvent('keydown', {\n key: key === 'Space' ? ' ' : key,\n altKey: keys.includes('Alt'),\n ctrlKey: keys.includes('Ctrl'),\n metaKey: keys.includes('Meta'),\n shiftKey: keys.includes('Shift'),\n bubbles: true,\n cancelable: true,\n })\n\n const capturedTransaction = editor.captureTransaction(() => {\n view.someProp('handleKeyDown', f => f(view, event))\n })\n\n capturedTransaction?.steps.forEach(step => {\n const newStep = step.map(tr.mapping)\n\n if (newStep && dispatch) {\n tr.maybeStep(newStep)\n }\n })\n\n return true\n }\n","import { lift as originalLift } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n lift: {\n /**\n * Removes an existing wrap if possible lifting the node out of it\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.lift('paragraph')\n * @example editor.commands.lift('heading', { level: 1 })\n */\n lift: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const lift: RawCommands['lift'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n const isActive = isNodeActive(state, type, attributes)\n\n if (!isActive) {\n return false\n }\n\n return originalLift(state, dispatch)\n }\n","import { liftEmptyBlock as originalLiftEmptyBlock } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n liftEmptyBlock: {\n /**\n * If the cursor is in an empty textblock that can be lifted, lift the block.\n * @example editor.commands.liftEmptyBlock()\n */\n liftEmptyBlock: () => ReturnType\n }\n }\n}\n\nexport const liftEmptyBlock: RawCommands['liftEmptyBlock'] =\n () =>\n ({ state, dispatch }) => {\n return originalLiftEmptyBlock(state, dispatch)\n }\n","import type { NodeType } from '@tiptap/pm/model'\nimport { liftListItem as originalLiftListItem } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n liftListItem: {\n /**\n * Create a command to lift the list item around the selection up into a wrapping list.\n * @param typeOrName The type or name of the node.\n * @example editor.commands.liftListItem('listItem')\n */\n liftListItem: (typeOrName: string | NodeType) => ReturnType\n }\n }\n}\n\nexport const liftListItem: RawCommands['liftListItem'] =\n typeOrName =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalLiftListItem(type)(state, dispatch)\n }\n","import { newlineInCode as originalNewlineInCode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n newlineInCode: {\n /**\n * Add a newline character in code.\n * @example editor.commands.newlineInCode()\n */\n newlineInCode: () => ReturnType\n }\n }\n}\n\nexport const newlineInCode: RawCommands['newlineInCode'] =\n () =>\n ({ state, dispatch }) => {\n return originalNewlineInCode(state, dispatch)\n }\n","/**\n * Remove a property or an array of properties from an object\n * @param obj Object\n * @param key Key to remove\n */\nexport function deleteProps(obj: Record<string, any>, propOrProps: string | string[]): Record<string, any> {\n const props = typeof propOrProps === 'string' ? [propOrProps] : propOrProps\n\n return Object.keys(obj).reduce((newObj: Record<string, any>, prop) => {\n if (!props.includes(prop)) {\n newObj[prop] = obj[prop]\n }\n\n return newObj\n }, {})\n}\n","import type { MarkType, NodeType } from '@tiptap/pm/model'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSchemaTypeNameByName } from '../helpers/getSchemaTypeNameByName.js'\nimport type { RawCommands } from '../types.js'\nimport { deleteProps } from '../utilities/deleteProps.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n resetAttributes: {\n /**\n * Resets some node attributes to the default value.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node to reset.\n * @example editor.commands.resetAttributes('heading', 'level')\n */\n resetAttributes: (typeOrName: string | NodeType | MarkType, attributes: string | string[]) => ReturnType\n }\n }\n}\n\nexport const resetAttributes: RawCommands['resetAttributes'] =\n (typeOrName, attributes) =>\n ({ tr, state, dispatch }) => {\n let nodeType: NodeType | null = null\n let markType: MarkType | null = null\n\n const schemaType = getSchemaTypeNameByName(\n typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n state.schema,\n )\n\n if (!schemaType) {\n return false\n }\n\n if (schemaType === 'node') {\n nodeType = getNodeType(typeOrName as NodeType, state.schema)\n }\n\n if (schemaType === 'mark') {\n markType = getMarkType(typeOrName as MarkType, state.schema)\n }\n\n if (dispatch) {\n tr.selection.ranges.forEach(range => {\n state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {\n if (nodeType && nodeType === node.type) {\n tr.setNodeMarkup(pos, undefined, deleteProps(node.attrs, attributes))\n }\n\n if (markType && node.marks.length) {\n node.marks.forEach(mark => {\n if (markType === mark.type) {\n tr.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes)))\n }\n })\n }\n })\n })\n }\n\n return true\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n scrollIntoView: {\n /**\n * Scroll the selection into view.\n * @example editor.commands.scrollIntoView()\n */\n scrollIntoView: () => ReturnType\n }\n }\n}\n\nexport const scrollIntoView: RawCommands['scrollIntoView'] =\n () =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n tr.scrollIntoView()\n }\n\n return true\n }\n","import { AllSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectAll: {\n /**\n * Select the whole document.\n * @example editor.commands.selectAll()\n */\n selectAll: () => ReturnType\n }\n }\n}\n\nexport const selectAll: RawCommands['selectAll'] =\n () =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n const selection = new AllSelection(tr.doc)\n\n tr.setSelection(selection)\n }\n\n return true\n }\n","import { selectNodeBackward as originalSelectNodeBackward } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectNodeBackward: {\n /**\n * Select a node backward.\n * @example editor.commands.selectNodeBackward()\n */\n selectNodeBackward: () => ReturnType\n }\n }\n}\n\nexport const selectNodeBackward: RawCommands['selectNodeBackward'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectNodeBackward(state, dispatch)\n }\n","import { selectNodeForward as originalSelectNodeForward } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectNodeForward: {\n /**\n * Select a node forward.\n * @example editor.commands.selectNodeForward()\n */\n selectNodeForward: () => ReturnType\n }\n }\n}\n\nexport const selectNodeForward: RawCommands['selectNodeForward'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectNodeForward(state, dispatch)\n }\n","import { selectParentNode as originalSelectParentNode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectParentNode: {\n /**\n * Select the parent node.\n * @example editor.commands.selectParentNode()\n */\n selectParentNode: () => ReturnType\n }\n }\n}\n\nexport const selectParentNode: RawCommands['selectParentNode'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectParentNode(state, dispatch)\n }\n","// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nimport { selectTextblockEnd as originalSelectTextblockEnd } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectTextblockEnd: {\n /**\n * Moves the cursor to the end of current text block.\n * @example editor.commands.selectTextblockEnd()\n */\n selectTextblockEnd: () => ReturnType\n }\n }\n}\n\nexport const selectTextblockEnd: RawCommands['selectTextblockEnd'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectTextblockEnd(state, dispatch)\n }\n","// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nimport { selectTextblockStart as originalSelectTextblockStart } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectTextblockStart: {\n /**\n * Moves the cursor to the start of current text block.\n * @example editor.commands.selectTextblockStart()\n */\n selectTextblockStart: () => ReturnType\n }\n }\n}\n\nexport const selectTextblockStart: RawCommands['selectTextblockStart'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectTextblockStart(state, dispatch)\n }\n","import type { Fragment, Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\n\nimport { createDocument } from '../helpers/createDocument.js'\nimport type { Content, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setContent: {\n /**\n * Replace the whole document with new content.\n * @param content The new content.\n * @param emitUpdate Whether to emit an update event.\n * @param parseOptions Options for parsing the content.\n * @example editor.commands.setContent('<p>Example text</p>')\n */\n setContent: (\n /**\n * The new content.\n */\n content: Content | Fragment | ProseMirrorNode,\n\n /**\n * Options for `setContent`.\n */\n options?: {\n /**\n * Options for parsing the content.\n * @default {}\n */\n parseOptions?: ParseOptions\n\n /**\n * Whether to throw an error if the content is invalid.\n */\n errorOnInvalidContent?: boolean\n\n /**\n * Whether to emit an update event.\n * @default true\n */\n emitUpdate?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const setContent: RawCommands['setContent'] =\n (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) =>\n ({ editor, tr, dispatch, commands }) => {\n const { doc } = tr\n\n // This is to keep backward compatibility with the previous behavior\n // TODO remove this in the next major version\n if (parseOptions.preserveWhitespace !== 'full') {\n const document = createDocument(content, editor.schema, parseOptions, {\n errorOnInvalidContent: errorOnInvalidContent ?? editor.options.enableContentCheck,\n })\n\n if (dispatch) {\n tr.replaceWith(0, doc.content.size, document).setMeta('preventUpdate', !emitUpdate)\n }\n return true\n }\n\n if (dispatch) {\n tr.setMeta('preventUpdate', !emitUpdate)\n }\n\n return commands.insertContentAt({ from: 0, to: doc.content.size }, content, {\n parseOptions,\n errorOnInvalidContent: errorOnInvalidContent ?? editor.options.enableContentCheck,\n })\n }\n","import type { MarkType, ResolvedPos } from '@tiptap/pm/model'\nimport type { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport { getMarkAttributes } from '../helpers/getMarkAttributes.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { isTextSelection } from '../helpers/index.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setMark: {\n /**\n * Add a mark with new attributes.\n * @param typeOrName The mark type or name.\n * @example editor.commands.setMark('bold', { level: 1 })\n */\n setMark: (typeOrName: string | MarkType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nfunction canSetMark(state: EditorState, tr: Transaction, newMarkType: MarkType) {\n const { selection } = tr\n let cursor: ResolvedPos | null = null\n\n if (isTextSelection(selection)) {\n cursor = selection.$cursor\n }\n\n if (cursor) {\n const currentMarks = state.storedMarks ?? cursor.marks()\n\n // There can be no current marks that exclude the new mark\n return !!newMarkType.isInSet(currentMarks) || !currentMarks.some(mark => mark.type.excludes(newMarkType))\n }\n\n const { ranges } = selection\n\n return ranges.some(({ $from, $to }) => {\n let someNodeSupportsMark =\n $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false\n\n state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => {\n // If we already found a mark that we can enable, return false to bypass the remaining search\n if (someNodeSupportsMark) {\n return false\n }\n\n if (node.isInline) {\n const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType)\n const currentMarksAllowMarkType =\n !!newMarkType.isInSet(node.marks) || !node.marks.some(otherMark => otherMark.type.excludes(newMarkType))\n\n someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType\n }\n return !someNodeSupportsMark\n })\n\n return someNodeSupportsMark\n })\n}\nexport const setMark: RawCommands['setMark'] =\n (typeOrName, attributes = {}) =>\n ({ tr, state, dispatch }) => {\n const { selection } = tr\n const { empty, ranges } = selection\n const type = getMarkType(typeOrName, state.schema)\n\n if (dispatch) {\n if (empty) {\n const oldAttributes = getMarkAttributes(state, type)\n\n tr.addStoredMark(\n type.create({\n ...oldAttributes,\n ...attributes,\n }),\n )\n } else {\n ranges.forEach(range => {\n const from = range.$from.pos\n const to = range.$to.pos\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n const trimmedFrom = Math.max(pos, from)\n const trimmedTo = Math.min(pos + node.nodeSize, to)\n const someHasMark = node.marks.find(mark => mark.type === type)\n\n // if there is already a mark of this type\n // we know that we have to merge its attributes\n // otherwise we add a fresh new mark\n if (someHasMark) {\n node.marks.forEach(mark => {\n if (type === mark.type) {\n tr.addMark(\n trimmedFrom,\n trimmedTo,\n type.create({\n ...mark.attrs,\n ...attributes,\n }),\n )\n }\n })\n } else {\n tr.addMark(trimmedFrom, trimmedTo, type.create(attributes))\n }\n })\n })\n }\n }\n\n return canSetMark(state, tr, type)\n }\n","import type { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setMeta: {\n /**\n * Store a metadata property in the current transaction.\n * @param key The key of the metadata property.\n * @param value The value to store.\n * @example editor.commands.setMeta('foo', 'bar')\n */\n setMeta: (key: string | Plugin | PluginKey, value: any) => ReturnType\n }\n }\n}\n\nexport const setMeta: RawCommands['setMeta'] =\n (key, value) =>\n ({ tr }) => {\n tr.setMeta(key, value)\n\n return true\n }\n","import { setBlockType } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setNode: {\n /**\n * Replace a given range with a node.\n * @param typeOrName The type or name of the node\n * @param attributes The attributes of the node\n * @example editor.commands.setNode('paragraph')\n */\n setNode: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const setNode: RawCommands['setNode'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch, chain }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n let attributesToCopy: Record<string, any> | undefined\n\n if (state.selection.$anchor.sameParent(state.selection.$head)) {\n // only copy attributes if the selection is pointing to a node of the same type\n attributesToCopy = state.selection.$anchor.parent.attrs\n }\n\n // TODO: use a fallback like insertContent?\n if (!type.isTextblock) {\n console.warn('[tiptap warn]: Currently \"setNode()\" only supports text block nodes.')\n\n return false\n }\n\n return (\n chain()\n // try to convert node to default node if needed\n .command(({ commands }) => {\n const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state)\n\n if (canSetBlock) {\n return true\n }\n\n return commands.clearNodes()\n })\n .command(({ state: updatedState }) => {\n return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch)\n })\n .run()\n )\n }\n","import { NodeSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setNodeSelection: {\n /**\n * Creates a NodeSelection.\n * @param position - Position of the node.\n * @example editor.commands.setNodeSelection(10)\n */\n setNodeSelection: (position: number) => ReturnType\n }\n }\n}\n\nexport const setNodeSelection: RawCommands['setNodeSelection'] =\n position =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n const { doc } = tr\n const from = minMax(position, 0, doc.content.size)\n const selection = NodeSelection.create(doc, from)\n\n tr.setSelection(selection)\n }\n\n return true\n }\n","import { TextSelection } from '@tiptap/pm/state'\n\nimport type { Range, RawCommands } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setTextSelection: {\n /**\n * Creates a TextSelection.\n * @param position The position of the selection.\n * @example editor.commands.setTextSelection(10)\n */\n setTextSelection: (position: number | Range) => ReturnType\n }\n }\n}\n\nexport const setTextSelection: RawCommands['setTextSelection'] =\n position =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n const { doc } = tr\n const { from, to } = typeof position === 'number' ? { from: position, to: position } : position\n const minPos = TextSelection.atStart(doc).from\n const maxPos = TextSelection.atEnd(doc).to\n const resolvedFrom = minMax(from, minPos, maxPos)\n const resolvedEnd = minMax(to, minPos, maxPos)\n const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd)\n\n tr.setSelection(selection)\n }\n\n return true\n }\n","import type { NodeType } from '@tiptap/pm/model'\nimport { sinkListItem as originalSinkListItem } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n sinkListItem: {\n /**\n * Sink the list item down into an inner list.\n * @param typeOrName The type or name of the node.\n * @example editor.commands.sinkListItem('listItem')\n */\n sinkListItem: (typeOrName: string | NodeType) => ReturnType\n }\n }\n}\n\nexport const sinkListItem: RawCommands['sinkListItem'] =\n typeOrName =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalSinkListItem(type)(state, dispatch)\n }\n","import type { EditorState } from '@tiptap/pm/state'\nimport { NodeSelection, TextSelection } from '@tiptap/pm/state'\nimport { canSplit } from '@tiptap/pm/transform'\n\nimport { defaultBlockAt } from '../helpers/defaultBlockAt.js'\nimport { getSplittedAttributes } from '../helpers/getSplittedAttributes.js'\nimport type { RawCommands } from '../types.js'\n\nfunction ensureMarks(state: EditorState, splittableMarks?: string[]) {\n const marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks())\n\n if (marks) {\n const filteredMarks = marks.filter(mark => splittableMarks?.includes(mark.type.name))\n\n state.tr.ensureMarks(filteredMarks)\n }\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n splitBlock: {\n /**\n * Forks a new node from an existing node.\n * @param options.keepMarks Keep marks from the previous node.\n * @example editor.commands.splitBlock()\n * @example editor.commands.splitBlock({ keepMarks: true })\n */\n splitBlock: (options?: { keepMarks?: boolean }) => ReturnType\n }\n }\n}\n\nexport const splitBlock: RawCommands['splitBlock'] =\n ({ keepMarks = true } = {}) =>\n ({ tr, state, dispatch, editor }) => {\n const { selection, doc } = tr\n const { $from, $to } = selection\n const extensionAttributes = editor.extensionManager.attributes\n const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs)\n\n if (selection instanceof NodeSelection && selection.node.isBlock) {\n if (!$from.parentOffset || !canSplit(doc, $from.pos)) {\n return false\n }\n\n if (dispatch) {\n if (keepMarks) {\n ensureMarks(state, editor.extensionManager.splittableMarks)\n }\n\n tr.split($from.pos).scrollIntoView()\n }\n\n return true\n }\n\n if (!$from.parent.isBlock) {\n return false\n }\n\n const atEnd = $to.parentOffset === $to.parent.content.size\n\n const deflt = $from.depth === 0 ? undefined : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)))\n\n let types =\n atEnd && deflt\n ? [\n {\n type: deflt,\n attrs: newAttributes,\n },\n ]\n : undefined\n\n let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types)\n\n if (!types && !can && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : undefined)) {\n can = true\n types = deflt\n ? [\n {\n type: deflt,\n attrs: newAttributes,\n },\n ]\n : undefined\n }\n\n if (dispatch) {\n if (can) {\n if (selection instanceof TextSelection) {\n tr.deleteSelection()\n }\n\n tr.split(tr.mapping.map($from.pos), 1, types)\n\n if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {\n const first = tr.mapping.map($from.before())\n const $first = tr.doc.resolve(first)\n\n if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {\n tr.setNodeMarkup(tr.mapping.map($from.before()), deflt)\n }\n }\n }\n\n if (keepMarks) {\n ensureMarks(state, editor.extensionManager.splittableMarks)\n }\n\n tr.scrollIntoView()\n }\n\n return can\n }\n","import type { Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\nimport { Fragment, Slice } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { canSplit } from '@tiptap/pm/transform'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSplittedAttributes } from '../helpers/getSplittedAttributes.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n splitListItem: {\n /**\n * Splits one list item into two list items.\n * @param typeOrName The type or name of the node.\n * @param overrideAttrs The attributes to ensure on the new node.\n * @example editor.commands.splitListItem('listItem')\n */\n splitListItem: (typeOrName: string | NodeType, overrideAttrs?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const splitListItem: RawCommands['splitListItem'] =\n (typeOrName, overrideAttrs = {}) =>\n ({ tr, state, dispatch, editor }) => {\n const type = getNodeType(typeOrName, state.schema)\n const { $from, $to } = state.selection\n\n // @ts-ignore\n // eslint-disable-next-line\n const node: ProseMirrorNode = state.selection.node\n\n if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to)) {\n return false\n }\n\n const grandParent = $from.node(-1)\n\n if (grandParent.type !== type) {\n return false\n }\n\n const extensionAttributes = editor.extensionManager.attributes\n\n if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {\n // In an empty block. If this is a nested list, the wrapping\n // list item should be split. Otherwise, bail out and let next\n // command handle lifting.\n if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) {\n return false\n }\n\n if (dispatch) {\n let wrap = Fragment.empty\n // eslint-disable-next-line\n const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3\n\n // Build a fragment containing empty versions of the structure\n // from the outer list item to the parent node of the cursor\n for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {\n wrap = Fragment.from($from.node(d).copy(wrap))\n }\n\n const depthAfter =\n // eslint-disable-next-line no-nested-ternary\n $from.indexAfter(-1) < $from.node(-2).childCount\n ? 1\n : $from.indexAfter(-2) < $from.node(-3).childCount\n ? 2\n : 3\n\n // Add a second list item with an empty default start node\n const newNextTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),\n ...overrideAttrs,\n }\n const nextType = type.contentMatch.defaultType?.createAndFill(newNextTypeAttributes) || undefined\n\n wrap = wrap.append(Fragment.from(type.createAndFill(null, nextType) || undefined))\n\n const start = $from.before($from.depth - (depthBefore - 1))\n\n tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0))\n\n let sel = -1\n\n tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {\n if (sel > -1) {\n return false\n }\n\n if (n.isTextblock && n.content.size === 0) {\n sel = pos + 1\n }\n })\n\n if (sel > -1) {\n tr.setSelection(TextSelection.near(tr.doc.resolve(sel)))\n }\n\n tr.scrollIntoView()\n }\n\n return true\n }\n\n const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null\n\n const newTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),\n ...overrideAttrs,\n }\n const newNextTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),\n ...overrideAttrs,\n }\n\n tr.delete($from.pos, $to.pos)\n\n const types = nextType\n ? [\n { type, attrs: newTypeAttributes },\n { type: nextType, attrs: newNextTypeAttributes },\n ]\n : [{ type, attrs: newTypeAttributes }]\n\n if (!canSplit(tr.doc, $from.pos, 2)) {\n return false\n }\n\n if (dispatch) {\n const { selection, storedMarks } = state\n const { splittableMarks } = editor.extensionManager\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n tr.split($from.pos, 2, types).scrollIntoView()\n\n if (!marks || !dispatch) {\n return true\n }\n\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n tr.ensureMarks(filteredMarks)\n }\n\n return true\n }\n","import type { NodeType } from '@tiptap/pm/model'\nimport type { Transaction } from '@tiptap/pm/state'\nimport { canJoin } from '@tiptap/pm/transform'\n\nimport { findParentNode } from '../helpers/findParentNode.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isList } from '../helpers/isList.js'\nimport type { RawCommands } from '../types.js'\n\nconst joinListBackwards = (tr: Transaction, listType: NodeType): boolean => {\n const list = findParentNode(node => node.type === listType)(tr.selection)\n\n if (!list) {\n return true\n }\n\n const before = tr.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth)\n\n if (before === undefined) {\n return true\n }\n\n const nodeBefore = tr.doc.nodeAt(before)\n const canJoinBackwards = list.node.type === nodeBefore?.type && canJoin(tr.doc, list.pos)\n\n if (!canJoinBackwards) {\n return true\n }\n\n tr.join(list.pos)\n\n return true\n}\n\nconst joinListForwards = (tr: Transaction, listType: NodeType): boolean => {\n const list = findParentNode(node => node.type === listType)(tr.selection)\n\n if (!list) {\n return true\n }\n\n const after = tr.doc.resolve(list.start).after(list.depth)\n\n if (after === undefined) {\n return true\n }\n\n const nodeAfter = tr.doc.nodeAt(after)\n const canJoinForwards = list.node.type === nodeAfter?.type && canJoin(tr.doc, after)\n\n if (!canJoinForwards) {\n return true\n }\n\n tr.join(after)\n\n return true\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n toggleList: {\n /**\n * Toggle between different list types.\n * @param listTypeOrName The type or name of the list.\n * @param itemTypeOrName The type or name of the list item.\n * @param keepMarks Keep marks when toggling.\n * @param attributes Attributes for the new list.\n * @example editor.commands.toggleList('bulletList', 'listItem')\n */\n toggleList: (\n listTypeOrName: string | NodeType,\n itemTypeOrName: string | NodeType,\n keepMarks?: boolean,\n attributes?: Record<string, any>,\n ) => ReturnType\n }\n }\n}\n\nexport const toggleList: RawCommands['toggleList'] =\n (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) =>\n ({ editor, tr, state, dispatch, chain, commands, can }) => {\n const { extensions, splittableMarks } = editor.extensionManager\n const listType = getNodeType(listTypeOrName, state.schema)\n const itemType = getNodeType(itemTypeOrName, state.schema)\n const { selection, storedMarks } = state\n const { $from, $to } = selection\n const range = $from.blockRange($to)\n\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n if (!range) {\n return false\n }\n\n const parentList = findParentNode(node => isList(node.type.name, extensions))(selection)\n\n if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {\n // remove list\n if (parentList.node.type === listType) {\n return commands.liftListItem(itemType)\n }\n\n // change list type\n if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content) && dispatch) {\n return chain()\n .command(() => {\n tr.setNodeMarkup(parentList.pos, listType)\n\n return true\n })\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run()\n }\n }\n if (!keepMarks || !marks || !dispatch) {\n return (\n chain()\n // try to convert node to default node if needed\n .command(() => {\n const canWrapInList = can().wrapInList(listType, attributes)\n\n if (canWrapInList) {\n return true\n }\n\n return commands.clearNodes()\n })\n .wrapInList(listType, attributes)\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run()\n )\n }\n\n return (\n chain()\n // try to convert node to default node if needed\n .command(() => {\n const canWrapInList = can().wrapInList(listType, attributes)\n\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n tr.ensureMarks(filteredMarks)\n\n if (canWrapInList) {\n return true\n }\n\n return commands.clearNodes()\n })\n .wrapInList(listType, attributes)\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run()\n )\n }\n","import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { isMarkActive } from '../helpers/isMarkActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n toggleMark: {\n /**\n * Toggle a mark on and off.\n * @param typeOrName The mark type or name.\n * @param attributes The attributes of the mark.\n * @param options.extendEmptyMarkRange Removes the mark even across the current selection. Defaults to `false`.\n * @example editor.commands.toggleMark('bold')\n */\n toggleMark: (\n /**\n * The mark type or name.\n */\n typeOrName: string | MarkType,\n\n /**\n * The attributes of the mark.\n */\n attributes?: Record<string, any>,\n\n options?: {\n /**\n * Removes the mark even across the current selection. Defaults to `false`.\n */\n extendEmptyMarkRange?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const toggleMark: RawCommands['toggleMark'] =\n (typeOrName, attributes = {}, options = {}) =>\n ({ state, commands }) => {\n const { extendEmptyMarkRange = false } = options\n const type = getMarkType(typeOrName, state.schema)\n const isActive = isMarkActive(state, type, attributes)\n\n if (isActive) {\n return commands.unsetMark(type, { extendEmptyMarkRange })\n }\n\n return commands.setMark(type, attributes)\n }\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n toggleNode: {\n /**\n * Toggle a node with another node.\n * @param typeOrName The type or name of the node.\n * @param toggleTypeOrName The type or name of the node to toggle.\n * @param attributes The attributes of the node.\n * @example editor.commands.toggleNode('heading', 'paragraph')\n */\n toggleNode: (\n typeOrName: string | NodeType,\n toggleTypeOrName: string | NodeType,\n attributes?: Record<string, any>,\n ) => ReturnType\n }\n }\n}\n\nexport const toggleNode: RawCommands['toggleNode'] =\n (typeOrName, toggleTypeOrName, attributes = {}) =>\n ({ state, commands }) => {\n const type = getNodeType(typeOrName, state.schema)\n const toggleType = getNodeType(toggleTypeOrName, state.schema)\n const isActive = isNodeActive(state, type, attributes)\n\n let attributesToCopy: Record<string, any> | undefined\n\n if (state.selection.$anchor.sameParent(state.selection.$head)) {\n // only copy attributes if the selection is pointing to a node of the same type\n attributesToCopy = state.selection.$anchor.parent.attrs\n }\n\n if (isActive) {\n return commands.setNode(toggleType, attributesToCopy)\n }\n\n // If the node is not active, we want to set the new node type with the given attributes\n // Copying over the attributes from the current node if the selection is pointing to a node of the same type\n return commands.setNode(type, { ...attributesToCopy, ...attributes })\n }\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n toggleWrap: {\n /**\n * Wraps nodes in another node, or removes an existing wrap.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.toggleWrap('blockquote')\n */\n toggleWrap: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const toggleWrap: RawCommands['toggleWrap'] =\n (typeOrName, attributes = {}) =>\n ({ state, commands }) => {\n const type = getNodeType(typeOrName, state.schema)\n const isActive = isNodeActive(state, type, attributes)\n\n if (isActive) {\n return commands.lift(type)\n }\n\n return commands.wrapIn(type, attributes)\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n undoInputRule: {\n /**\n * Undo an input rule.\n * @example editor.commands.undoInputRule()\n */\n undoInputRule: () => ReturnType\n }\n }\n}\n\nexport const undoInputRule: RawCommands['undoInputRule'] =\n () =>\n ({ state, dispatch }) => {\n const plugins = state.plugins\n\n for (let i = 0; i < plugins.length; i += 1) {\n const plugin = plugins[i]\n let undoable\n\n // @ts-ignore\n // eslint-disable-next-line\n if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {\n if (dispatch) {\n const tr = state.tr\n const toUndo = undoable.transform\n\n for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {\n tr.step(toUndo.steps[j].invert(toUndo.docs[j]))\n }\n\n if (undoable.text) {\n const marks = tr.doc.resolve(undoable.from).marks()\n\n tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks))\n } else {\n tr.delete(undoable.from, undoable.to)\n }\n }\n\n return true\n }\n }\n\n return false\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n unsetAllMarks: {\n /**\n * Remove all marks in the current selection.\n * @example editor.commands.unsetAllMarks()\n */\n unsetAllMarks: () => ReturnType\n }\n }\n}\n\nexport const unsetAllMarks: RawCommands['unsetAllMarks'] =\n () =>\n ({ tr, dispatch }) => {\n const { selection } = tr\n const { empty, ranges } = selection\n\n if (empty) {\n return true\n }\n\n if (dispatch) {\n ranges.forEach(range => {\n tr.removeMark(range.$from.pos, range.$to.pos)\n })\n }\n\n return true\n }\n","import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarkRange } from '../helpers/getMarkRange.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n unsetMark: {\n /**\n * Remove all marks in the current selection.\n * @param typeOrName The mark type or name.\n * @param options.extendEmptyMarkRange Removes the mark even across the current selection. Defaults to `false`.\n * @example editor.commands.unsetMark('bold')\n */\n unsetMark: (\n /**\n * The mark type or name.\n */\n typeOrName: string | MarkType,\n\n options?: {\n /**\n * Removes the mark even across the current selection. Defaults to `false`.\n */\n extendEmptyMarkRange?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const unsetMark: RawCommands['unsetMark'] =\n (typeOrName, options = {}) =>\n ({ tr, state, dispatch }) => {\n const { extendEmptyMarkRange = false } = options\n const { selection } = tr\n const type = getMarkType(typeOrName, state.schema)\n const { $from, empty, ranges } = selection\n\n if (!dispatch) {\n return true\n }\n\n if (empty && extendEmptyMarkRange) {\n let { from, to } = selection\n const attrs = $from.marks().find(mark => mark.type === type)?.attrs\n const range = getMarkRange($from, type, attrs)\n\n if (range) {\n from = range.from\n to = range.to\n }\n\n tr.removeMark(from, to, type)\n } else {\n ranges.forEach(range => {\n tr.removeMark(range.$from.pos, range.$to.pos, type)\n })\n }\n\n tr.removeStoredMark(type)\n\n return true\n }\n","import type { Mark, MarkType, Node, NodeType } from '@tiptap/pm/model'\nimport type { SelectionRange } from '@tiptap/pm/state'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSchemaTypeNameByName } from '../helpers/getSchemaTypeNameByName.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n updateAttributes: {\n /**\n * Update attributes of a node or mark.\n * @param typeOrName The type or name of the node or mark.\n * @param attributes The attributes of the node or mark.\n * @example editor.commands.updateAttributes('mention', { userId: \"2\" })\n */\n updateAttributes: (\n /**\n * The type or name of the node or mark.\n */\n typeOrName: string | NodeType | MarkType,\n\n /**\n * The attributes of the node or mark.\n */\n attributes: Record<string, any>,\n ) => ReturnType\n }\n }\n}\n\nexport const updateAttributes: RawCommands['updateAttributes'] =\n (typeOrName, attributes = {}) =>\n ({ tr, state, dispatch }) => {\n let nodeType: NodeType | null = null\n let markType: MarkType | null = null\n\n const schemaType = getSchemaTypeNameByName(\n typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n state.schema,\n )\n\n if (!schemaType) {\n return false\n }\n\n if (schemaType === 'node') {\n nodeType = getNodeType(typeOrName as NodeType, state.schema)\n }\n\n if (schemaType === 'mark') {\n markType = getMarkType(typeOrName as MarkType, state.schema)\n }\n\n if (dispatch) {\n tr.selection.ranges.forEach((range: SelectionRange) => {\n const from = range.$from.pos\n const to = range.$to.pos\n\n let lastPos: number | undefined\n let lastNode: Node | undefined\n let trimmedFrom: number\n let trimmedTo: number\n\n if (tr.selection.empty) {\n state.doc.nodesBetween(from, to, (node: Node, pos: number) => {\n if (nodeType && nodeType === node.type) {\n trimmedFrom = Math.max(pos, from)\n trimmedTo = Math.min(pos + node.nodeSize, to)\n lastPos = pos\n lastNode = node\n }\n })\n } else {\n state.doc.nodesBetween(from, to, (node: Node, pos: number) => {\n if (pos < from && nodeType && nodeType === node.type) {\n trimmedFrom = Math.max(pos, from)\n trimmedTo = Math.min(pos + node.nodeSize, to)\n lastPos = pos\n lastNode = node\n }\n\n if (pos >= from && pos <= to) {\n if (nodeType && nodeType === node.type) {\n tr.setNodeMarkup(pos, undefined, {\n ...node.attrs,\n ...attributes,\n })\n }\n\n if (markType && node.marks.length) {\n node.marks.forEach((mark: Mark) => {\n if (markType === mark.type) {\n const trimmedFrom2 = Math.max(pos, from)\n const trimmedTo2 = Math.min(pos + node.nodeSize, to)\n\n tr.addMark(\n trimmedFrom2,\n trimmedTo2,\n markType.create({\n ...mark.attrs,\n ...attributes,\n }),\n )\n }\n })\n }\n }\n })\n }\n\n if (lastNode) {\n if (lastPos !== undefined) {\n tr.setNodeMarkup(lastPos, undefined, {\n ...lastNode.attrs,\n ...attributes,\n })\n }\n\n if (markType && lastNode.marks.length) {\n lastNode.marks.forEach((mark: Mark) => {\n if (markType === mark.type) {\n tr.addMark(\n trimmedFrom,\n trimmedTo,\n markType.create({\n ...mark.attrs,\n ...attributes,\n }),\n )\n }\n })\n }\n }\n })\n }\n\n return true\n }\n","import { wrapIn as originalWrapIn } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n wrapIn: {\n /**\n * Wraps nodes in another node.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.wrapIn('blockquote')\n */\n wrapIn: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const wrapIn: RawCommands['wrapIn'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalWrapIn(type, attributes)(state, dispatch)\n }\n","import type { NodeType } from '@tiptap/pm/model'\nimport { wrapInList as originalWrapInList } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n wrapInList: {\n /**\n * Wrap a node in a list.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.wrapInList('bulletList')\n */\n wrapInList: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const wrapInList: RawCommands['wrapInList'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalWrapInList(type, attributes)(state, dispatch)\n }\n","import * as commands from '../commands/index.js'\nimport { Extension } from '../Extension.js'\n\nexport * from '../commands/index.js'\n\nexport const Commands = Extension.create({\n name: 'commands',\n\n addCommands() {\n return {\n ...commands,\n }\n },\n})\n","import { RemoveMarkStep } from '@tiptap/pm/transform'\n\nimport { Extension } from '../Extension.js'\nimport { combineTransactionSteps, getChangedRanges } from '../helpers/index.js'\n\n/**\n * This extension allows you to be notified when the user deletes content you are interested in.\n */\nexport const Delete = Extension.create({\n name: 'delete',\n\n onUpdate({ transaction, appendedTransactions }) {\n const callback = () => {\n if (\n this.editor.options.coreExtensionOptions?.delete?.filterTransaction?.(transaction) ??\n transaction.getMeta('y-sync$')\n ) {\n return\n }\n const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions])\n const changes = getChangedRanges(nextTransaction)\n\n changes.forEach(change => {\n if (\n nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter &&\n nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore\n ) {\n nextTransaction.before.nodesBetween(change.oldRange.from, change.oldRange.to, (node, from) => {\n const to = from + node.nodeSize - 2\n const isFullyWithinRange = change.oldRange.from <= from && to <= change.oldRange.to\n\n this.editor.emit('delete', {\n type: 'node',\n node,\n from,\n to,\n newFrom: nextTransaction.mapping.map(from),\n newTo: nextTransaction.mapping.map(to),\n deletedRange: change.oldRange,\n newRange: change.newRange,\n partial: !isFullyWithinRange,\n editor: this.editor,\n transaction,\n combinedTransform: nextTransaction,\n })\n })\n }\n })\n\n const mapping = nextTransaction.mapping\n nextTransaction.steps.forEach((step, index) => {\n if (step instanceof RemoveMarkStep) {\n const newStart = mapping.slice(index).map(step.from, -1)\n const newEnd = mapping.slice(index).map(step.to)\n const oldStart = mapping.invert().map(newStart, -1)\n const oldEnd = mapping.invert().map(newEnd)\n\n const foundBeforeMark = nextTransaction.doc.nodeAt(newStart - 1)?.marks.some(mark => mark.eq(step.mark))\n const foundAfterMark = nextTransaction.doc.nodeAt(newEnd)?.marks.some(mark => mark.eq(step.mark))\n\n this.editor.emit('delete', {\n type: 'mark',\n mark: step.mark,\n from: step.from,\n to: step.to,\n deletedRange: {\n from: oldStart,\n to: oldEnd,\n },\n newRange: {\n from: newStart,\n to: newEnd,\n },\n partial: Boolean(foundAfterMark || foundBeforeMark),\n editor: this.editor,\n transaction,\n combinedTransform: nextTransaction,\n })\n }\n })\n }\n\n if (this.editor.options.coreExtensionOptions?.delete?.async ?? true) {\n setTimeout(callback, 0)\n } else {\n callback()\n }\n },\n})\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Drop = Extension.create({\n name: 'drop',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tiptapDrop'),\n\n props: {\n handleDrop: (_, e, slice, moved) => {\n this.editor.emit('drop', {\n editor: this.editor,\n event: e,\n slice,\n moved,\n })\n },\n },\n }),\n ]\n },\n})\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Editable = Extension.create({\n name: 'editable',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('editable'),\n props: {\n editable: () => this.editor.options.editable,\n },\n }),\n ]\n },\n})\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const focusEventsPluginKey = new PluginKey('focusEvents')\n\nexport const FocusEvents = Extension.create({\n name: 'focusEvents',\n\n addProseMirrorPlugins() {\n const { editor } = this\n\n return [\n new Plugin({\n key: focusEventsPluginKey,\n props: {\n handleDOMEvents: {\n focus: (view, event: Event) => {\n editor.isFocused = true\n\n const transaction = editor.state.tr.setMeta('focus', { event }).setMeta('addToHistory', false)\n\n view.dispatch(transaction)\n\n return false\n },\n blur: (view, event: Event) => {\n editor.isFocused = false\n\n const transaction = editor.state.tr.setMeta('blur', { event }).setMeta('addToHistory', false)\n\n view.dispatch(transaction)\n\n return false\n },\n },\n },\n }),\n ]\n },\n})\n","import { Plugin, PluginKey, Selection } from '@tiptap/pm/state'\n\nimport { CommandManager } from '../CommandManager.js'\nimport { Extension } from '../Extension.js'\nimport { createChainableState } from '../helpers/createChainableState.js'\nimport { isNodeEmpty } from '../helpers/isNodeEmpty.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isMacOS } from '../utilities/isMacOS.js'\n\nexport const Keymap = Extension.create({\n name: 'keymap',\n\n addKeyboardShortcuts() {\n const handleBackspace = () =>\n this.editor.commands.first(({ commands }) => [\n () => commands.undoInputRule(),\n\n // maybe convert first text block node to default node\n () =>\n commands.command(({ tr }) => {\n const { selection, doc } = tr\n const { empty, $anchor } = selection\n const { pos, parent } = $anchor\n const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr.doc.resolve(pos - 1) : $anchor\n const parentIsIsolating = $parentPos.parent.type.spec.isolating\n\n const parentPos = $anchor.pos - $anchor.parentOffset\n\n const isAtStart =\n parentIsIsolating && $parentPos.parent.childCount === 1\n ? parentPos === $anchor.pos\n : Selection.atStart(doc).from === pos\n\n if (\n !empty ||\n !parent.type.isTextblock ||\n parent.textContent.length ||\n !isAtStart ||\n (isAtStart && $anchor.parent.type.name === 'paragraph') // prevent clearNodes when no nodes to clear, otherwise history stack is appended\n ) {\n return false\n }\n\n return commands.clearNodes()\n }),\n\n () => commands.deleteSelection(),\n () => commands.joinBackward(),\n () => commands.selectNodeBackward(),\n ])\n\n const handleDelete = () =>\n this.editor.commands.first(({ commands }) => [\n () => commands.deleteSelection(),\n () => commands.deleteCurrentNode(),\n () => commands.joinForward(),\n () => commands.selectNodeForward(),\n ])\n\n const handleEnter = () =>\n this.editor.commands.first(({ commands }) => [\n () => commands.newlineInCode(),\n () => commands.createParagraphNear(),\n () => commands.liftEmptyBlock(),\n () => commands.splitBlock(),\n ])\n\n const baseKeymap = {\n Enter: handleEnter,\n 'Mod-Enter': () => this.editor.commands.exitCode(),\n Backspace: handleBackspace,\n 'Mod-Backspace': handleBackspace,\n 'Shift-Backspace': handleBackspace,\n Delete: handleDelete,\n 'Mod-Delete': handleDelete,\n 'Mod-a': () => this.editor.commands.selectAll(),\n }\n\n const pcKeymap = {\n ...baseKeymap,\n }\n\n const macKeymap = {\n ...baseKeymap,\n 'Ctrl-h': handleBackspace,\n 'Alt-Backspace': handleBackspace,\n 'Ctrl-d': handleDelete,\n 'Ctrl-Alt-Backspace': handleDelete,\n 'Alt-Delete': handleDelete,\n 'Alt-d': handleDelete,\n 'Ctrl-a': () => this.editor.commands.selectTextblockStart(),\n 'Ctrl-e': () => this.editor.commands.selectTextblockEnd(),\n }\n\n if (isiOS() || isMacOS()) {\n return macKeymap\n }\n\n return pcKeymap\n },\n\n addProseMirrorPlugins() {\n return [\n // With this plugin we check if the whole document was selected and deleted.\n // In this case we will additionally call `clearNodes()` to convert e.g. a heading\n // to a paragraph if necessary.\n // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well\n // with many other commands.\n new Plugin({\n key: new PluginKey('clearDocument'),\n appendTransaction: (transactions, oldState, newState) => {\n if (transactions.some(tr => tr.getMeta('composition'))) {\n return\n }\n\n const docChanges = transactions.some(transaction => transaction.docChanged) && !oldState.doc.eq(newState.doc)\n\n const ignoreTr = transactions.some(transaction => transaction.getMeta('preventClearDocument'))\n\n if (!docChanges || ignoreTr) {\n return\n }\n\n const { empty, from, to } = oldState.selection\n const allFrom = Selection.atStart(oldState.doc).from\n const allEnd = Selection.atEnd(oldState.doc).to\n const allWasSelected = from === allFrom && to === allEnd\n\n if (empty || !allWasSelected) {\n return\n }\n\n const isEmpty = isNodeEmpty(newState.doc)\n\n if (!isEmpty) {\n return\n }\n\n const tr = newState.tr\n const state = createChainableState({\n state: newState,\n transaction: tr,\n })\n const { commands } = new CommandManager({\n editor: this.editor,\n state,\n })\n\n commands.clearNodes()\n\n if (!tr.steps.length) {\n return\n }\n\n return tr\n },\n }),\n ]\n },\n})\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Paste = Extension.create({\n name: 'paste',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tiptapPaste'),\n\n props: {\n handlePaste: (_view, e, slice) => {\n this.editor.emit('paste', {\n editor: this.editor,\n event: e,\n slice,\n })\n },\n },\n }),\n ]\n },\n})\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Tabindex = Extension.create({\n name: 'tabindex',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tabindex'),\n props: {\n attributes: (): { [name: string]: string } => (this.editor.isEditable ? { tabindex: '0' } : {}),\n },\n }),\n ]\n },\n})\n","import type { Fragment, Node, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { Content, Range } from './types.js'\n\nexport class NodePos {\n private resolvedPos: ResolvedPos\n\n private isBlock: boolean\n\n private editor: Editor\n\n private get name(): string {\n return this.node.type.name\n }\n\n constructor(pos: ResolvedPos, editor: Editor, isBlock = false, node: Node | null = null) {\n this.isBlock = isBlock\n this.resolvedPos = pos\n this.editor = editor\n this.currentNode = node\n }\n\n private currentNode: Node | null = null\n\n get node(): Node {\n return this.currentNode || this.resolvedPos.node()\n }\n\n get element(): HTMLElement {\n return this.editor.view.domAtPos(this.pos).node as HTMLElement\n }\n\n public actualDepth: number | null = null\n\n get depth(): number {\n return this.actualDepth ?? this.resolvedPos.depth\n }\n\n get pos(): number {\n return this.resolvedPos.pos\n }\n\n get content(): Fragment {\n return this.node.content\n }\n\n set content(content: Content) {\n let from = this.from\n let to = this.to\n\n if (this.isBlock) {\n if (this.content.size === 0) {\n console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`)\n return\n }\n\n from = this.from + 1\n to = this.to - 1\n }\n\n this.editor.commands.insertContentAt({ from, to }, content)\n }\n\n get attributes(): { [key: string]: any } {\n return this.node.attrs\n }\n\n get textContent(): string {\n return this.node.textContent\n }\n\n get size(): number {\n return this.node.nodeSize\n }\n\n get from(): number {\n if (this.isBlock) {\n return this.pos\n }\n\n return this.resolvedPos.start(this.resolvedPos.depth)\n }\n\n get range(): Range {\n return {\n from: this.from,\n to: this.to,\n }\n }\n\n get to(): number {\n if (this.isBlock) {\n return this.pos + this.size\n }\n\n return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1)\n }\n\n get parent(): NodePos | null {\n if (this.depth === 0) {\n return null\n }\n\n const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1)\n const $pos = this.resolvedPos.doc.resolve(parentPos)\n\n return new NodePos($pos, this.editor)\n }\n\n get before(): NodePos | null {\n let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2))\n\n if ($pos.depth !== this.depth) {\n $pos = this.resolvedPos.doc.resolve(this.from - 3)\n }\n\n return new NodePos($pos, this.editor)\n }\n\n get after(): NodePos | null {\n let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1))\n\n if ($pos.depth !== this.depth) {\n $pos = this.resolvedPos.doc.resolve(this.to + 3)\n }\n\n return new NodePos($pos, this.editor)\n }\n\n get children(): NodePos[] {\n const children: NodePos[] = []\n\n this.node.content.forEach((node, offset) => {\n const isBlock = node.isBlock && !node.isTextblock\n const isNonTextAtom = node.isAtom && !node.isText\n\n const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1)\n\n // Check if targetPos is within valid document range\n if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) {\n return\n }\n\n const $pos = this.resolvedPos.doc.resolve(targetPos)\n\n if (!isBlock && $pos.depth <= this.depth) {\n return\n }\n\n const childNodePos = new NodePos($pos, this.editor, isBlock, isBlock ? node : null)\n\n if (isBlock) {\n childNodePos.actualDepth = this.depth + 1\n }\n\n children.push(new NodePos($pos, this.editor, isBlock, isBlock ? node : null))\n })\n\n return children\n }\n\n get firstChild(): NodePos | null {\n return this.children[0] || null\n }\n\n get lastChild(): NodePos | null {\n const children = this.children\n\n return children[children.length - 1] || null\n }\n\n closest(selector: string, attributes: { [key: string]: any } = {}): NodePos | null {\n let node: NodePos | null = null\n let currentNode = this.parent\n\n while (currentNode && !node) {\n if (currentNode.node.type.name === selector) {\n if (Object.keys(attributes).length > 0) {\n const nodeAttributes = currentNode.node.attrs\n const attrKeys = Object.keys(attributes)\n\n for (let index = 0; index < attrKeys.length; index += 1) {\n const key = attrKeys[index]\n\n if (nodeAttributes[key] !== attributes[key]) {\n break\n }\n }\n } else {\n node = currentNode\n }\n }\n\n currentNode = currentNode.parent\n }\n\n return node\n }\n\n querySelector(selector: string, attributes: { [key: string]: any } = {}): NodePos | null {\n return this.querySelectorAll(selector, attributes, true)[0] || null\n }\n\n querySelectorAll(selector: string, attributes: { [key: string]: any } = {}, firstItemOnly = false): NodePos[] {\n let nodes: NodePos[] = []\n\n if (!this.children || this.children.length === 0) {\n return nodes\n }\n const attrKeys = Object.keys(attributes)\n\n /**\n * Finds all children recursively that match the selector and attributes\n * If firstItemOnly is true, it will return the first item found\n */\n this.children.forEach(childPos => {\n // If we already found a node and we only want the first item, we dont need to keep going\n if (firstItemOnly && nodes.length > 0) {\n return\n }\n\n if (childPos.node.type.name === selector) {\n const doesAllAttributesMatch = attrKeys.every(key => attributes[key] === childPos.node.attrs[key])\n\n if (doesAllAttributesMatch) {\n nodes.push(childPos)\n }\n }\n\n // If we already found a node and we only want the first item, we can stop here and skip the recursion\n if (firstItemOnly && nodes.length > 0) {\n return\n }\n\n nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly))\n })\n\n return nodes\n }\n\n setAttribute(attributes: { [key: string]: any }) {\n const { tr } = this.editor.state\n\n tr.setNodeMarkup(this.from, undefined, {\n ...this.node.attrs,\n ...attributes,\n })\n\n this.editor.view.dispatch(tr)\n }\n}\n","export const style = `.ProseMirror {\n position: relative;\n}\n\n.ProseMirror {\n word-wrap: break-word;\n white-space: pre-wrap;\n white-space: break-spaces;\n -webkit-font-variant-ligatures: none;\n font-variant-ligatures: none;\n font-feature-settings: \"liga\" 0; /* the above doesn't seem to work in Edge */\n}\n\n.ProseMirror [contenteditable=\"false\"] {\n white-space: normal;\n}\n\n.ProseMirror [contenteditable=\"false\"] [contenteditable=\"true\"] {\n white-space: pre-wrap;\n}\n\n.ProseMirror pre {\n white-space: pre-wrap;\n}\n\nimg.ProseMirror-separator {\n display: inline !important;\n border: none !important;\n margin: 0 !important;\n width: 0 !important;\n height: 0 !important;\n}\n\n.ProseMirror-gapcursor {\n display: none;\n pointer-events: none;\n position: absolute;\n margin: 0;\n}\n\n.ProseMirror-gapcursor:after {\n content: \"\";\n display: block;\n position: absolute;\n top: -2px;\n width: 20px;\n border-top: 1px solid black;\n animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;\n}\n\n@keyframes ProseMirror-cursor-blink {\n to {\n visibility: hidden;\n }\n}\n\n.ProseMirror-hideselection *::selection {\n background: transparent;\n}\n\n.ProseMirror-hideselection *::-moz-selection {\n background: transparent;\n}\n\n.ProseMirror-hideselection * {\n caret-color: transparent;\n}\n\n.ProseMirror-focused .ProseMirror-gapcursor {\n display: block;\n}`\n","export function createStyleTag(style: string, nonce?: string, suffix?: string): HTMLStyleElement {\n const tiptapStyleTag = <HTMLStyleElement>(\n document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ''}]`)\n )\n\n if (tiptapStyleTag !== null) {\n return tiptapStyleTag\n }\n\n const styleNode = document.createElement('style')\n\n if (nonce) {\n styleNode.setAttribute('nonce', nonce)\n }\n\n styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ''}`, '')\n styleNode.innerHTML = style\n document.getElementsByTagName('head')[0].appendChild(styleNode)\n\n return styleNode\n}\n","import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarksBetween } from '../helpers/getMarksBetween.js'\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that adds a mark when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function markInputRule(config: {\n find: InputRuleFinder\n type: MarkType\n getAttributes?: Record<string, any> | ((match: ExtendedRegExpMatchArray) => Record<string, any>) | false | null\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match)\n\n if (attributes === false || attributes === null) {\n return null\n }\n\n const { tr } = state\n const captureGroup = match[match.length - 1]\n const fullMatch = match[0]\n\n if (captureGroup) {\n const startSpaces = fullMatch.search(/\\S/)\n const textStart = range.from + fullMatch.indexOf(captureGroup)\n const textEnd = textStart + captureGroup.length\n\n const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n .filter(item => {\n // @ts-ignore\n const excluded = item.mark.type.excluded as MarkType[]\n\n return excluded.find(type => type === config.type && type !== item.mark.type)\n })\n .filter(item => item.to > textStart)\n\n if (excludedMarks.length) {\n return null\n }\n\n if (textEnd < range.to) {\n tr.delete(textEnd, range.to)\n }\n\n if (textStart > range.from) {\n tr.delete(range.from + startSpaces, textStart)\n }\n\n const markEnd = range.from + startSpaces + captureGroup.length\n\n tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))\n\n tr.removeStoredMark(config.type)\n }\n },\n })\n}\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that adds a node when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function nodeInputRule(config: {\n /**\n * The regex to match.\n */\n find: InputRuleFinder\n\n /**\n * The node type to add.\n */\n type: NodeType\n\n /**\n * A function that returns the attributes for the node\n * can also be an object of attributes\n */\n getAttributes?: Record<string, any> | ((match: ExtendedRegExpMatchArray) => Record<string, any>) | false | null\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n const { tr } = state\n const start = range.from\n let end = range.to\n\n const newNode = config.type.create(attributes)\n\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1])\n let matchStart = start + offset\n\n if (matchStart > end) {\n matchStart = end\n } else {\n end = matchStart + match[1].length\n }\n\n // insert last typed character\n const lastChar = match[0][match[0].length - 1]\n\n tr.insertText(lastChar, start + match[0].length - 1)\n\n // insert node from input rule\n tr.replaceWith(matchStart, end, newNode)\n } else if (match[0]) {\n const insertionStart = config.type.isInline ? start : start - 1\n\n tr.insert(insertionStart, config.type.create(attributes)).delete(tr.mapping.map(start), tr.mapping.map(end))\n }\n\n tr.scrollIntoView()\n },\n })\n}\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that changes the type of a textblock when the\n * matched text is typed into it. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function textblockTypeInputRule(config: {\n find: InputRuleFinder\n type: NodeType\n getAttributes?: Record<string, any> | ((match: ExtendedRegExpMatchArray) => Record<string, any>) | false | null\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const $start = state.doc.resolve(range.from)\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n\n if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) {\n return null\n }\n\n state.tr.delete(range.from, range.to).setBlockType(range.from, range.from, config.type, attributes)\n },\n })\n}\n","import type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\n\n/**\n * Build an input rule that replaces text when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function textInputRule(config: { find: InputRuleFinder; replace: string }) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n let insert = config.replace\n let start = range.from\n const end = range.to\n\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1])\n\n insert += match[0].slice(offset + match[1].length)\n start += offset\n\n const cutOff = start - end\n\n if (cutOff > 0) {\n insert = match[0].slice(offset - cutOff, offset) + insert\n start = end\n }\n }\n\n state.tr.insertText(insert, start, end)\n },\n })\n}\n","import type { Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\nimport { canJoin, findWrapping } from '@tiptap/pm/transform'\n\nimport type { Editor } from '../Editor.js'\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule for automatically wrapping a textblock when a\n * given string is typed. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n *\n * `type` is the type of node to wrap in.\n *\n * By default, if there’s a node with the same type above the newly\n * wrapped node, the rule will try to join those\n * two nodes. You can pass a join predicate, which takes a regular\n * expression match and the node before the wrapped node, and can\n * return a boolean to indicate whether a join should happen.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function wrappingInputRule(config: {\n find: InputRuleFinder\n type: NodeType\n keepMarks?: boolean\n keepAttributes?: boolean\n editor?: Editor\n getAttributes?: Record<string, any> | ((match: ExtendedRegExpMatchArray) => Record<string, any>) | false | null\n joinPredicate?: (match: ExtendedRegExpMatchArray, node: ProseMirrorNode) => boolean\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match, chain }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n const tr = state.tr.delete(range.from, range.to)\n const $start = tr.doc.resolve(range.from)\n const blockRange = $start.blockRange()\n const wrapping = blockRange && findWrapping(blockRange, config.type, attributes)\n\n if (!wrapping) {\n return null\n }\n\n tr.wrap(blockRange, wrapping)\n\n if (config.keepMarks && config.editor) {\n const { selection, storedMarks } = state\n const { splittableMarks } = config.editor.extensionManager\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n if (marks) {\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n tr.ensureMarks(filteredMarks)\n }\n }\n if (config.keepAttributes) {\n /** If the nodeType is `bulletList` or `orderedList` set the `nodeType` as `listItem` */\n const nodeType =\n config.type.name === 'bulletList' || config.type.name === 'orderedList' ? 'listItem' : 'taskList'\n\n chain().updateAttributes(nodeType, attributes).run()\n }\n\n const before = tr.doc.resolve(range.from - 1).nodeBefore\n\n if (\n before &&\n before.type === config.type &&\n canJoin(tr.doc, range.from - 1) &&\n (!config.joinPredicate || config.joinPredicate(match, before))\n ) {\n tr.join(range.from - 1)\n }\n },\n })\n}\n","export type Attributes = Record<string, any>\n\nexport type DOMOutputSpecElement = 0 | Attributes | DOMOutputSpecArray\n/**\n * Better describes the output of a `renderHTML` function in prosemirror\n * @see https://prosemirror.net/docs/ref/#model.DOMOutputSpec\n */\nexport type DOMOutputSpecArray =\n | [string]\n | [string, Attributes]\n | [string, 0]\n | [string, Attributes, 0]\n | [string, Attributes, DOMOutputSpecArray | 0]\n | [string, DOMOutputSpecArray]\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n // @ts-ignore - conflict with React typings\n type Element = [string, ...any[]]\n // @ts-ignore - conflict with React typings\n interface IntrinsicElements {\n // @ts-ignore - conflict with React typings\n [key: string]: any\n }\n }\n}\n\nexport type JSXRenderer = (\n tag: 'slot' | string | ((props?: Attributes) => DOMOutputSpecArray | DOMOutputSpecElement),\n props?: Attributes,\n ...children: JSXRenderer[]\n) => DOMOutputSpecArray | DOMOutputSpecElement\n\nexport function Fragment(props: { children: JSXRenderer[] }) {\n return props.children\n}\n\nexport const h: JSXRenderer = (tag, attributes) => {\n // Treat the slot tag as the Prosemirror hole to render content into\n if (tag === 'slot') {\n return 0\n }\n\n // If the tag is a function, call it with the props\n if (tag instanceof Function) {\n return tag(attributes)\n }\n\n const { children, ...rest } = attributes ?? {}\n\n if (tag === 'svg') {\n throw new Error('SVG elements are not supported in the JSX syntax, use the array syntax instead')\n }\n\n // Otherwise, return the tag, attributes, and children\n return [tag, rest, children]\n}\n\n// See\n// https://esbuild.github.io/api/#jsx-import-source\n// https://www.typescriptlang.org/tsconfig/#jsxImportSource\n\nexport { h as createElement, h as jsx, h as jsxDEV, h as jsxs }\n","import type { NodeType } from '@tiptap/pm/model'\nimport { type EditorState, NodeSelection } from '@tiptap/pm/state'\n\nexport function canInsertNode(state: EditorState, nodeType: NodeType): boolean {\n const { selection } = state\n const { $from } = selection\n\n // Special handling for NodeSelection\n if (selection instanceof NodeSelection) {\n const index = $from.index()\n const parent = $from.parent\n\n // Can we replace the selected node with the horizontal rule?\n return parent.canReplaceWith(index, index + 1, nodeType)\n }\n\n // Default: check if we can insert at the current position\n let depth = $from.depth\n\n while (depth >= 0) {\n const index = $from.index(depth)\n const parent = $from.node(depth)\n const match = parent.contentMatchAt(index)\n if (match.matchType(nodeType)) {\n return true\n }\n depth -= 1\n }\n return false\n}\n","// source: https://stackoverflow.com/a/6969486\nexport function escapeForRegEx(string: string): string {\n return string.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&')\n}\n","export function isString(value: any): value is string {\n return typeof value === 'string'\n}\n","import type { Mark } from '@tiptap/pm/model'\nimport type { ViewMutationRecord } from '@tiptap/pm/view'\n\nimport type { Editor } from './Editor.js'\nimport type { MarkViewProps, MarkViewRendererOptions } from './types.js'\nimport { isAndroid, isiOS } from './utilities/index.js'\n\nexport function updateMarkViewAttributes(checkMark: Mark, editor: Editor, attrs: Record<string, any> = {}): void {\n const { state } = editor\n const { doc, tr } = state\n const thisMark = checkMark\n\n doc.descendants((node, pos) => {\n const from = tr.mapping.map(pos)\n const to = tr.mapping.map(pos) + node.nodeSize\n let foundMark: Mark | null = null\n\n // find the mark on the current node\n node.marks.forEach(mark => {\n if (mark !== thisMark) {\n return false\n }\n\n foundMark = mark\n })\n\n if (!foundMark) {\n return\n }\n\n // check if we need to update given the attributes\n let needsUpdate = false\n Object.keys(attrs).forEach(k => {\n if (attrs[k] !== foundMark!.attrs[k]) {\n needsUpdate = true\n }\n })\n\n if (needsUpdate) {\n const updatedMark = checkMark.type.create({\n ...checkMark.attrs,\n ...attrs,\n })\n\n tr.removeMark(from, to, checkMark.type)\n tr.addMark(from, to, updatedMark)\n }\n })\n\n if (tr.docChanged) {\n editor.view.dispatch(tr)\n }\n}\n\nexport class MarkView<Component, Options extends MarkViewRendererOptions = MarkViewRendererOptions> {\n component: Component\n editor: Editor\n options: Options\n mark: MarkViewProps['mark']\n HTMLAttributes: MarkViewProps['HTMLAttributes']\n\n constructor(component: Component, props: MarkViewProps, options?: Partial<Options>) {\n this.component = component\n this.editor = props.editor\n this.options = { ...options } as Options\n this.mark = props.mark\n this.HTMLAttributes = props.HTMLAttributes\n }\n\n get dom(): HTMLElement {\n return this.editor.view.dom\n }\n\n get contentDOM(): HTMLElement | null {\n return null\n }\n\n /**\n * Update the attributes of the mark in the document.\n * @param attrs The attributes to update.\n */\n updateAttributes(attrs: Record<string, any>, checkMark?: Mark): void {\n updateMarkViewAttributes(checkMark || this.mark, this.editor, attrs)\n }\n\n ignoreMutation(mutation: ViewMutationRecord): boolean {\n if (!this.dom || !this.contentDOM) {\n return true\n }\n\n if (typeof this.options.ignoreMutation === 'function') {\n return this.options.ignoreMutation({ mutation })\n }\n\n if (mutation.type === 'selection') {\n return false\n }\n\n if (\n this.dom.contains(mutation.target) &&\n mutation.type === 'childList' &&\n (isiOS() || isAndroid()) &&\n this.editor.isFocused\n ) {\n const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)] as HTMLElement[]\n\n if (changedNodes.every(node => node.isContentEditable)) {\n return false\n }\n }\n\n if (this.contentDOM === mutation.target && mutation.type === 'attributes') {\n return true\n }\n\n if (this.contentDOM.contains(mutation.target)) {\n return false\n }\n\n return true\n }\n}\n","import type { DOMOutputSpec, Node as ProseMirrorNode, NodeSpec, NodeType } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { ExtendableConfig } from './Extendable.js'\nimport { Extendable } from './Extendable.js'\nimport type { Attributes, NodeViewRenderer, ParentConfig } from './types.js'\n\nexport interface NodeConfig<Options = any, Storage = any>\n extends ExtendableConfig<Options, Storage, NodeConfig<Options, Storage>, NodeType> {\n /**\n * Node View\n */\n addNodeView?:\n | ((this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: NodeType\n parent: ParentConfig<NodeConfig<Options, Storage>>['addNodeView']\n }) => NodeViewRenderer)\n | null\n\n /**\n * Defines if this node should be a top level node (doc)\n * @default false\n * @example true\n */\n topNode?: boolean\n\n /**\n * The content expression for this node, as described in the [schema\n * guide](/docs/guide/#schema.content_expressions). When not given,\n * the node does not allow any content.\n *\n * You can read more about it on the Prosemirror documentation here\n * @see https://prosemirror.net/docs/guide/#schema.content_expressions\n * @default undefined\n * @example content: 'block+'\n * @example content: 'headline paragraph block*'\n */\n content?:\n | NodeSpec['content']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['content']\n editor?: Editor\n }) => NodeSpec['content'])\n\n /**\n * The marks that are allowed inside of this node. May be a\n * space-separated string referring to mark names or groups, `\"_\"`\n * to explicitly allow all marks, or `\"\"` to disallow marks. When\n * not given, nodes with inline content default to allowing all\n * marks, other nodes default to not allowing marks.\n *\n * @example marks: 'strong em'\n */\n marks?:\n | NodeSpec['marks']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['marks']\n editor?: Editor\n }) => NodeSpec['marks'])\n\n /**\n * The group or space-separated groups to which this node belongs,\n * which can be referred to in the content expressions for the\n * schema.\n *\n * By default Tiptap uses the groups 'block' and 'inline' for nodes. You\n * can also use custom groups if you want to group specific nodes together\n * and handle them in your schema.\n * @example group: 'block'\n * @example group: 'inline'\n * @example group: 'customBlock' // this uses a custom group\n */\n group?:\n | NodeSpec['group']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['group']\n editor?: Editor\n }) => NodeSpec['group'])\n\n /**\n * Should be set to true for inline nodes. (Implied for text nodes.)\n */\n inline?:\n | NodeSpec['inline']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['inline']\n editor?: Editor\n }) => NodeSpec['inline'])\n\n /**\n * Can be set to true to indicate that, though this isn't a [leaf\n * node](https://prosemirror.net/docs/ref/#model.NodeType.isLeaf), it doesn't have directly editable\n * content and should be treated as a single unit in the view.\n *\n * @example atom: true\n */\n atom?:\n | NodeSpec['atom']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['atom']\n editor?: Editor\n }) => NodeSpec['atom'])\n\n /**\n * Controls whether nodes of this type can be selected as a [node\n * selection](https://prosemirror.net/docs/ref/#state.NodeSelection). Defaults to true for non-text\n * nodes.\n *\n * @default true\n * @example selectable: false\n */\n selectable?:\n | NodeSpec['selectable']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['selectable']\n editor?: Editor\n }) => NodeSpec['selectable'])\n\n /**\n * Determines whether nodes of this type can be dragged without\n * being selected. Defaults to false.\n *\n * @default: false\n * @example: draggable: true\n */\n draggable?:\n | NodeSpec['draggable']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['draggable']\n editor?: Editor\n }) => NodeSpec['draggable'])\n\n /**\n * Can be used to indicate that this node contains code, which\n * causes some commands to behave differently.\n */\n code?:\n | NodeSpec['code']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['code']\n editor?: Editor\n }) => NodeSpec['code'])\n\n /**\n * Controls way whitespace in this a node is parsed. The default is\n * `\"normal\"`, which causes the [DOM parser](https://prosemirror.net/docs/ref/#model.DOMParser) to\n * collapse whitespace in normal mode, and normalize it (replacing\n * newlines and such with spaces) otherwise. `\"pre\"` causes the\n * parser to preserve spaces inside the node. When this option isn't\n * given, but [`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) is true, `whitespace`\n * will default to `\"pre\"`. Note that this option doesn't influence\n * the way the node is rendered—that should be handled by `toDOM`\n * and/or styling.\n */\n whitespace?:\n | NodeSpec['whitespace']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['whitespace']\n editor?: Editor\n }) => NodeSpec['whitespace'])\n\n /**\n * Allows a **single** node to be set as linebreak equivalent (e.g. hardBreak).\n * When converting between block types that have whitespace set to \"pre\"\n * and don't support the linebreak node (e.g. codeBlock) and other block types\n * that do support the linebreak node (e.g. paragraphs) - this node will be used\n * as the linebreak instead of stripping the newline.\n *\n * See [linebreakReplacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement).\n */\n linebreakReplacement?:\n | NodeSpec['linebreakReplacement']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['linebreakReplacement']\n editor?: Editor\n }) => NodeSpec['linebreakReplacement'])\n\n /**\n * When enabled, enables both\n * [`definingAsContext`](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext) and\n * [`definingForContent`](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n *\n * @default false\n * @example isolating: true\n */\n defining?:\n | NodeSpec['defining']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['defining']\n editor?: Editor\n }) => NodeSpec['defining'])\n\n /**\n * When enabled (default is false), the sides of nodes of this type\n * count as boundaries that regular editing operations, like\n * backspacing or lifting, won't cross. An example of a node that\n * should probably have this enabled is a table cell.\n */\n isolating?:\n | NodeSpec['isolating']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['isolating']\n editor?: Editor\n }) => NodeSpec['isolating'])\n\n /**\n * Associates DOM parser information with this node, which can be\n * used by [`DOMParser.fromSchema`](https://prosemirror.net/docs/ref/#model.DOMParser^fromSchema) to\n * automatically derive a parser. The `node` field in the rules is\n * implied (the name of this node will be filled in automatically).\n * If you supply your own parser, you do not need to also specify\n * parsing rules in your schema.\n *\n * @example parseHTML: [{ tag: 'div', attrs: { 'data-id': 'my-block' } }]\n */\n parseHTML?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['parseHTML']\n editor?: Editor\n }) => NodeSpec['parseDOM']\n\n /**\n * A description of a DOM structure. Can be either a string, which is\n * interpreted as a text node, a DOM node, which is interpreted as\n * itself, a `{dom, contentDOM}` object, or an array.\n *\n * An array describes a DOM element. The first value in the array\n * should be a string—the name of the DOM element, optionally prefixed\n * by a namespace URL and a space. If the second element is plain\n * object, it is interpreted as a set of attributes for the element.\n * Any elements after that (including the 2nd if it's not an attribute\n * object) are interpreted as children of the DOM elements, and must\n * either be valid `DOMOutputSpec` values, or the number zero.\n *\n * The number zero (pronounced “hole”) is used to indicate the place\n * where a node's child nodes should be inserted. If it occurs in an\n * output spec, it should be the only child element in its parent\n * node.\n *\n * @example toDOM: ['div[data-id=\"my-block\"]', { class: 'my-block' }, 0]\n */\n renderHTML?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['renderHTML']\n editor?: Editor\n },\n props: {\n node: ProseMirrorNode\n HTMLAttributes: Record<string, any>\n },\n ) => DOMOutputSpec)\n | null\n\n /**\n * renders the node as text\n * @example renderText: () => 'foo\n */\n renderText?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['renderText']\n editor?: Editor\n },\n props: {\n node: ProseMirrorNode\n pos: number\n parent: ProseMirrorNode\n index: number\n },\n ) => string)\n | null\n\n /**\n * Add attributes to the node\n * @example addAttributes: () => ({ class: 'foo' })\n */\n addAttributes?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['addAttributes']\n editor?: Editor\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n }) => Attributes | {}\n}\n\n/**\n * The Node class is used to create custom node extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Node<Options = any, Storage = any> extends Extendable<Options, Storage, NodeConfig<Options, Storage>> {\n type = 'node'\n\n /**\n * Create a new Node instance\n * @param config - Node configuration object or a function that returns a configuration object\n */\n static create<O = any, S = any>(config: Partial<NodeConfig<O, S>> | (() => Partial<NodeConfig<O, S>>) = {}) {\n // If the config is a function, execute it to get the configuration object\n const resolvedConfig = typeof config === 'function' ? config() : config\n return new Node<O, S>(resolvedConfig)\n }\n\n configure(options?: Partial<Options>) {\n return super.configure(options) as Node<Options, Storage>\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig = NodeConfig<ExtendedOptions, ExtendedStorage>,\n >(extendedConfig?: Partial<ExtendedConfig> | (() => Partial<ExtendedConfig>)) {\n // If the extended config is a function, execute it to get the configuration object\n const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n return super.extend(resolvedConfig) as Node<ExtendedOptions, ExtendedStorage>\n }\n}\n","import { NodeSelection } from '@tiptap/pm/state'\nimport type { NodeView as ProseMirrorNodeView, ViewMutationRecord } from '@tiptap/pm/view'\n\nimport type { Editor as CoreEditor } from './Editor.js'\nimport type { DecorationWithType, NodeViewRendererOptions, NodeViewRendererProps } from './types.js'\nimport { isAndroid } from './utilities/isAndroid.js'\nimport { isiOS } from './utilities/isiOS.js'\n\n/**\n * Node views are used to customize the rendered DOM structure of a node.\n * @see https://tiptap.dev/guide/node-views\n */\nexport class NodeView<\n Component,\n NodeEditor extends CoreEditor = CoreEditor,\n Options extends NodeViewRendererOptions = NodeViewRendererOptions,\n> implements ProseMirrorNodeView\n{\n component: Component\n\n editor: NodeEditor\n\n options: Options\n\n extension: NodeViewRendererProps['extension']\n\n node: NodeViewRendererProps['node']\n\n decorations: NodeViewRendererProps['decorations']\n\n innerDecorations: NodeViewRendererProps['innerDecorations']\n\n view: NodeViewRendererProps['view']\n\n getPos: NodeViewRendererProps['getPos']\n\n HTMLAttributes: NodeViewRendererProps['HTMLAttributes']\n\n isDragging = false\n\n constructor(component: Component, props: NodeViewRendererProps, options?: Partial<Options>) {\n this.component = component\n this.editor = props.editor as NodeEditor\n this.options = {\n stopEvent: null,\n ignoreMutation: null,\n ...options,\n } as Options\n this.extension = props.extension\n this.node = props.node\n this.decorations = props.decorations as DecorationWithType[]\n this.innerDecorations = props.innerDecorations\n this.view = props.view\n this.HTMLAttributes = props.HTMLAttributes\n this.getPos = props.getPos\n this.mount()\n }\n\n mount() {\n // eslint-disable-next-line\n return\n }\n\n get dom(): HTMLElement {\n return this.editor.view.dom as HTMLElement\n }\n\n get contentDOM(): HTMLElement | null {\n return null\n }\n\n onDragStart(event: DragEvent) {\n const { view } = this.editor\n const target = event.target as HTMLElement\n\n // get the drag handle element\n // `closest` is not available for text nodes so we may have to use its parent\n const dragHandle =\n target.nodeType === 3 ? target.parentElement?.closest('[data-drag-handle]') : target.closest('[data-drag-handle]')\n\n if (!this.dom || this.contentDOM?.contains(target) || !dragHandle) {\n return\n }\n\n let x = 0\n let y = 0\n\n // calculate offset for drag element if we use a different drag handle element\n if (this.dom !== dragHandle) {\n const domBox = this.dom.getBoundingClientRect()\n const handleBox = dragHandle.getBoundingClientRect()\n\n // In React, we have to go through nativeEvent to reach offsetX/offsetY.\n const offsetX = event.offsetX ?? (event as any).nativeEvent?.offsetX\n const offsetY = event.offsetY ?? (event as any).nativeEvent?.offsetY\n\n x = handleBox.x - domBox.x + offsetX\n y = handleBox.y - domBox.y + offsetY\n }\n\n const clonedNode = this.dom.cloneNode(true) as HTMLElement\n\n event.dataTransfer?.setDragImage(clonedNode, x, y)\n\n const pos = this.getPos()\n\n if (typeof pos !== 'number') {\n return\n }\n // we need to tell ProseMirror that we want to move the whole node\n // so we create a NodeSelection\n const selection = NodeSelection.create(view.state.doc, pos)\n const transaction = view.state.tr.setSelection(selection)\n\n view.dispatch(transaction)\n }\n\n stopEvent(event: Event) {\n if (!this.dom) {\n return false\n }\n\n if (typeof this.options.stopEvent === 'function') {\n return this.options.stopEvent({ event })\n }\n\n const target = event.target as HTMLElement\n const isInElement = this.dom.contains(target) && !this.contentDOM?.contains(target)\n\n // any event from child nodes should be handled by ProseMirror\n if (!isInElement) {\n return false\n }\n\n const isDragEvent = event.type.startsWith('drag')\n const isDropEvent = event.type === 'drop'\n const isInput = ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA'].includes(target.tagName) || target.isContentEditable\n\n // any input event within node views should be ignored by ProseMirror\n if (isInput && !isDropEvent && !isDragEvent) {\n return true\n }\n\n const { isEditable } = this.editor\n const { isDragging } = this\n const isDraggable = !!this.node.type.spec.draggable\n const isSelectable = NodeSelection.isSelectable(this.node)\n const isCopyEvent = event.type === 'copy'\n const isPasteEvent = event.type === 'paste'\n const isCutEvent = event.type === 'cut'\n const isClickEvent = event.type === 'mousedown'\n\n // ProseMirror tries to drag selectable nodes\n // even if `draggable` is set to `false`\n // this fix prevents that\n if (!isDraggable && isSelectable && isDragEvent && event.target === this.dom) {\n event.preventDefault()\n }\n\n if (isDraggable && isDragEvent && !isDragging && event.target === this.dom) {\n event.preventDefault()\n return false\n }\n\n // we have to store that dragging started\n if (isDraggable && isEditable && !isDragging && isClickEvent) {\n const dragHandle = target.closest('[data-drag-handle]')\n const isValidDragHandle = dragHandle && (this.dom === dragHandle || this.dom.contains(dragHandle))\n\n if (isValidDragHandle) {\n this.isDragging = true\n\n document.addEventListener(\n 'dragend',\n () => {\n this.isDragging = false\n },\n { once: true },\n )\n\n document.addEventListener(\n 'drop',\n () => {\n this.isDragging = false\n },\n { once: true },\n )\n\n document.addEventListener(\n 'mouseup',\n () => {\n this.isDragging = false\n },\n { once: true },\n )\n }\n }\n\n // these events are handled by prosemirror\n if (isDragging || isDropEvent || isCopyEvent || isPasteEvent || isCutEvent || (isClickEvent && isSelectable)) {\n return false\n }\n\n return true\n }\n\n /**\n * Called when a DOM [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) or a selection change happens within the view.\n * @return `false` if the editor should re-read the selection or re-parse the range around the mutation\n * @return `true` if it can safely be ignored.\n */\n ignoreMutation(mutation: ViewMutationRecord) {\n if (!this.dom || !this.contentDOM) {\n return true\n }\n\n if (typeof this.options.ignoreMutation === 'function') {\n return this.options.ignoreMutation({ mutation })\n }\n\n // a leaf/atom node is like a black box for ProseMirror\n // and should be fully handled by the node view\n if (this.node.isLeaf || this.node.isAtom) {\n return true\n }\n\n // ProseMirror should handle any selections\n if (mutation.type === 'selection') {\n return false\n }\n\n // try to prevent a bug on iOS and Android that will break node views on enter\n // this is because ProseMirror can’t preventDispatch on enter\n // this will lead to a re-render of the node view on enter\n // see: https://github.com/ueberdosis/tiptap/issues/1214\n // see: https://github.com/ueberdosis/tiptap/issues/2534\n if (\n this.dom.contains(mutation.target) &&\n mutation.type === 'childList' &&\n (isiOS() || isAndroid()) &&\n this.editor.isFocused\n ) {\n const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)] as HTMLElement[]\n\n // we’ll check if every changed node is contentEditable\n // to make sure it’s probably mutated by ProseMirror\n if (changedNodes.every(node => node.isContentEditable)) {\n return false\n }\n }\n\n // we will allow mutation contentDOM with attributes\n // so we can for example adding classes within our node view\n if (this.contentDOM === mutation.target && mutation.type === 'attributes') {\n return true\n }\n\n // ProseMirror should handle any changes within contentDOM\n if (this.contentDOM.contains(mutation.target)) {\n return false\n }\n\n return true\n }\n\n /**\n * Update the attributes of the prosemirror node.\n */\n updateAttributes(attributes: Record<string, any>): void {\n this.editor.commands.command(({ tr }) => {\n const pos = this.getPos()\n\n if (typeof pos !== 'number') {\n return false\n }\n\n tr.setNodeMarkup(pos, undefined, {\n ...this.node.attrs,\n ...attributes,\n })\n\n return true\n })\n }\n\n /**\n * Delete the node.\n */\n deleteNode(): void {\n const from = this.getPos()\n\n if (typeof from !== 'number') {\n return\n }\n const to = from + this.node.nodeSize\n\n this.editor.commands.deleteRange({ from, to })\n }\n}\n","import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarksBetween } from '../helpers/getMarksBetween.js'\nimport type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an paste rule that adds a mark when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function markPasteRule(config: {\n find: PasteRuleFinder\n type: MarkType\n getAttributes?:\n | Record<string, any>\n | ((match: ExtendedRegExpMatchArray, event: ClipboardEvent) => Record<string, any>)\n | false\n | null\n}) {\n return new PasteRule({\n find: config.find,\n handler: ({ state, range, match, pasteEvent }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent)\n\n if (attributes === false || attributes === null) {\n return null\n }\n\n const { tr } = state\n const captureGroup = match[match.length - 1]\n const fullMatch = match[0]\n let markEnd = range.to\n\n if (captureGroup) {\n const startSpaces = fullMatch.search(/\\S/)\n const textStart = range.from + fullMatch.indexOf(captureGroup)\n const textEnd = textStart + captureGroup.length\n\n const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n .filter(item => {\n // @ts-ignore\n const excluded = item.mark.type.excluded as MarkType[]\n\n return excluded.find(type => type === config.type && type !== item.mark.type)\n })\n .filter(item => item.to > textStart)\n\n if (excludedMarks.length) {\n return null\n }\n\n if (textEnd < range.to) {\n tr.delete(textEnd, range.to)\n }\n\n if (textStart > range.from) {\n tr.delete(range.from + startSpaces, textStart)\n }\n\n markEnd = range.from + startSpaces + captureGroup.length\n\n tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))\n\n tr.removeStoredMark(config.type)\n }\n },\n })\n}\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\nimport type { ExtendedRegExpMatchArray, JSONContent } from '../types.js'\nimport { callOrReturn } from '../utilities/index.js'\n\n/**\n * Build an paste rule that adds a node when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function nodePasteRule(config: {\n find: PasteRuleFinder\n type: NodeType\n getAttributes?:\n | Record<string, any>\n | ((match: ExtendedRegExpMatchArray, event: ClipboardEvent) => Record<string, any>)\n | false\n | null\n getContent?: JSONContent[] | ((attrs: Record<string, any>) => JSONContent[]) | false | null\n}) {\n return new PasteRule({\n find: config.find,\n handler({ match, chain, range, pasteEvent }) {\n const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent)\n const content = callOrReturn(config.getContent, undefined, attributes)\n\n if (attributes === false || attributes === null) {\n return null\n }\n\n const node = { type: config.type.name, attrs: attributes } as JSONContent\n\n if (content) {\n node.content = content\n }\n\n if (match.input) {\n chain().deleteRange(range).insertContentAt(range.from, node)\n }\n },\n })\n}\n","import type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\n\n/**\n * Build an paste rule that replaces text when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function textPasteRule(config: { find: PasteRuleFinder; replace: string }) {\n return new PasteRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n let insert = config.replace\n let start = range.from\n const end = range.to\n\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1])\n\n insert += match[0].slice(offset + match[1].length)\n start += offset\n\n const cutOff = start - end\n\n if (cutOff > 0) {\n insert = match[0].slice(offset - cutOff, offset) + insert\n start = end\n }\n }\n\n state.tr.insertText(insert, start, end)\n },\n })\n}\n","import type { Transaction } from '@tiptap/pm/state'\n\nexport interface TrackerResult {\n position: number\n deleted: boolean\n}\n\nexport class Tracker {\n transaction: Transaction\n\n currentStep: number\n\n constructor(transaction: Transaction) {\n this.transaction = transaction\n this.currentStep = this.transaction.steps.length\n }\n\n map(position: number): TrackerResult {\n let deleted = false\n\n const mappedPosition = this.transaction.steps.slice(this.currentStep).reduce((newPosition, step) => {\n const mapResult = step.getMap().mapResult(newPosition)\n\n if (mapResult.deleted) {\n deleted = true\n }\n\n return mapResult.pos\n }, position)\n\n return {\n position: mappedPosition,\n deleted,\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,cAAc,GAAG,GAAG,KAAK;AAC9B,WAAS,IAAI,KAAI,KAAK;AAClB,QAAI,KAAK,EAAE,cAAc,KAAK,EAAE;AAC5B,aAAO,EAAE,cAAc,EAAE,aAAa,OAAO;AACjD,QAAI,SAAS,EAAE,MAAM,CAAC,GAAG,SAAS,EAAE,MAAM,CAAC;AAC3C,QAAI,UAAU,QAAQ;AAClB,aAAO,OAAO;AACd;AAAA,IACJ;AACA,QAAI,CAAC,OA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AM,OAAO;AAAA,IACb,SAAS,CAAC,EAAE,OAAO,OAAO,MAAM,MAAM;AACpC,UAAIC,UAAS,OAAO;AACpB,UAAI,QAAQ,MAAM;AAClB,YAAM,MAAM,MAAM;AAElB,UAAI,MAAM,CAAC,GAAG;AACZ,cAAM,SAAS,MAAM,CAAC,EAAE,YAAY,MAAM,CAAC,CAAC;AAE5C,QAAAA,WAAU,MAAM,CAAC,EAAE,MAAM,SAAS,MAAM,CAAC,EAAE,MAAM;AACjD,iBAAS;AAET,cAAM,SAAS,QAAQ;AAEvB,YAAI,SAAS,GAAG;AACd,UAAAA,UAAS,MAAM,CAAC,EAAE,MAAM,SAAS,QAAQ,MAAM,IAAIA;AACnD,kBAAQ;AAAA,QACV;AAAA,MACF;AAEA,YAAM,GAAG,WAAWA,SAAQ,OAAO,GAAG;AAAA,IACxC;AAAA,EACF,CAAC;AACH;;;AC1BO,IAAM,UAAN,MAAc;AAAA,EAKnB,YAAY,aAA0B;AACpC,SAAK,cAAc;AACnB,SAAK,cAAc,KAAK,YAAY,MAAM;AAAA,EAC5C;AAAA,EAEA,IAAI,UAAiC;AACnC,QAAIC,WAAU;AAEd,UAAM,iBAAiB,KAAK,YAAY,MAAM,MAAM,KAAK,WAAW,EAAE,OAAO,CAAC,aAAa,SAAS;AAClG,YAAM,YAAY,KAAK,OAAO,EAAE,UAAU,WAAW;AAErD,UAAI,UAAU,SAAS;AACrB,QAAAA,WAAU;AAAA,MACZ;AAEA,aAAO,UAAU;AAAA,IACnB,GAAG,QAAQ;AAEX,WAAO;AAAA,MACL,UAAU;AAAA,MACV,SAAAA;AAAA,IACF;AAAA,EACF;AACF;","names":["insert","Fragment","type","nfa","edge","expr","node","states","doc","space","Mark","Slice","Node","DOMSerializer","text","first","found","active","i","exports","module","space","tag_check","indent_character","indent_size","max_char","brace_style","i","text","__rest","s","e","t","p","Object","prototype","hasOwnProperty","call","indexOf","getOwnPropertySymbols","i","length","propertyIsEnumerable","noop","assign","tar","src","k","run","fn","blank_object","create","run_all","fns","forEach","is_function","thing","safe_not_equal","a","b","is_empty","obj","keys","subscribe","store","_len","arguments","callbacks","Array","_key","callback","undefined","unsub","unsubscribe","get_store_value","value","_","component_subscribe","component","$$","on_destroy","push","create_slot","definition","ctx","$$scope","slot_ctx","get_slot_context","slice","get_slot_changes","dirty","lets","merged","len","Math","max","update_slot_base","slot","slot_definition","slot_changes","get_slot_context_fn","slot_context","get_all_dirty_from_scope","exclude_internal_props","props","result","null_to_empty","action_destroyer","action_result","destroy","append","target","node","appendChild","append_styles","style_sheet_id","styles","append_styles_to","get_root_for_style","getElementById","style","element","id","textContent","append_stylesheet","document","root","getRootNode","ownerDocument","host","head","sheet","insert","anchor","insertBefore","detach","parentNode","removeChild","destroy_each","iterations","detaching","d","name","createElement","svg_element","createElementNS","text","data","createTextNode","space","empty","listen","event","handler","options","addEventListener","removeEventListener","prevent_default","preventDefault","attr","attribute","removeAttribute","getAttribute","setAttribute","xlink_attr","setAttributeNS","children","from","childNodes","set_data","set_input_value","input","set_style","key","important","setProperty","toggle_class","toggle","classList","custom_event","type","detail","bubbles","cancelable","CustomEvent","construct_svelte_component","set_current_component","current_component","get_current_component","Error","onMount","on_mount","onDestroy","createEventDispatcher","defaultPrevented","setContext","context","set","getContext","get","bubble","schedule_update","update_scheduled","resolved_promise","then","flush","add_render_callback","render_callbacks","flushidx","saved_component","dirty_components","update","binding_callbacks","pop","seen_callbacks","has","add","flush_callbacks","clear","fragment","before_update","after_update","flush_render_callbacks","filtered","targets","c","group_outros","outros","r","check_outros","transition_in","block","local","outroing","delete","transition_out","o","ensure_array_like","array_like_or_iterator","destroy_block","lookup","update_keyed_each","old_blocks","get_key","dynamic","list","create_each_block","next","get_context","n","old_indexes","new_blocks","new_lookup","Map","deltas","updates","child_ctx","abs","will_move","Set","did_move","m","first","new_block","old_block","new_key","old_key","create_component","mount_component","new_on_destroy","map","filter","destroy_component","make_dirty","fill","init","instance","create_fragment","not_equal","parent_component","bound","on_disconnect","skip_bound","ready","ret","hydrate","nodes","l","intro","readable","start","writable","stop","subscribers","new_value","run_queue","subscriber_queue","subscriber","invalidate","size","derived","stores","initial_value","single","isArray","stores_array","every","Boolean","auto","started","values","pending","cleanup","sync","unsubscribers","doc","cloneRegExp","re","regexMatch","exec","toString","RegExp","clone","arg","_typeof","Date","getTime","cloned","collectChildrenDiffFilter","child","index","childName","leftIsArray","_t","setResult","exit","objectsDiffFilter","leftType","propertyFilter","left","DiffContext","right","collectChildrenReverseFilter","delta","arraysHaveMatchByRef","array1","array2","len1","len2","index1","val1","index2","val2","matchItems","value1","value2","objectHash","matchByPosition","hash1","hash2","hashCache1","hashCache2","collectChildrenReverseFilter$1","newName","reverseArrayDeltaIndex","htmlEscape","html","replacements","replace","chalkColor","chalk","args","DOMSerializer","createNode","depth","parent","path","concat","join","collapsed","getValueType","parentId","circularOfId","getChildren","v","entries","_ref","shouldRecurseChildren","iteratedValues","opts","stopCircularRecursion","isCircularNode","existingNodeWithValue","recurseObjectProperties","ensureNotCollapsed","treeMap","oldTreeMap","recomputeExpandNode","_a","omitKeys","includes","maxDepth","oldNode","shouldExpandNode","mappedChildren","mapChildren","_ref2","idx","val","recomputeTree","recursionOpts","newTree","tree","SvelteComponent","PUBLIC_VERSION","classCallCheck","createClass","inherits","possibleConstructorReturn","Processor","Pipe","Context","PatchContext","ReverseContext","isArray$1","diffFilter","patchFilter","reverseFilter","patchFilter$1","collectChildrenPatchFilter","reverseFilter$1","defaultMatch","lengthMatrix","backtrack","get$1","lcs","ARRAY_MOVE","isArray$2","arrayIndexOf","diffFilter$1","compare","patchFilter$2","collectChildrenPatchFilter$1","reverseFilter$2","diffFilter$2","TEXT_DIFF","DEFAULT_MIN_LENGTH","cachedDiffPatch","getDiffMatchPatch","diffFilter$3","patchFilter$3","textDeltaReverse","reverseFilter$3","DiffPatcher","isArray$3","getObjectKeys","trimUnderscore","arrayKeyToSortNumber","arrayKeyComparer","BaseFormatter","adjustArrows","AnnotatedFormatter","wrapPropertyName","deltaAnnotations","formatAnyChange","OPERATIONS","colors","createPropsStore","createRootElementStore","createTreeStore","Promise","resolve","constructor","$$set","$destroy","$on","splice","$set","window","__svelte","setCtx","getCtx","diff_match_patch","Diff_Timeout","Diff_EditCost","Match_Threshold","Match_Distance","Patch_DeleteThreshold","Patch_Margin","Match_MaxBits","DIFF_DELETE","DIFF_INSERT","DIFF_EQUAL","Diff","op","diff_main","text1","text2","opt_checklines","opt_deadline","Number","MAX_VALUE","deadline","checklines","commonlength","diff_commonPrefix","commonprefix","substring","diff_commonSuffix","commonsuffix","diffs","diff_compute_","unshift","diff_cleanupMerge","longtext","shorttext","hm","diff_halfMatch_","text1_a","text1_b","text2_a","text2_b","mid_common","diffs_a","diffs_b","diff_lineMode_","diff_bisect_","diff_linesToChars_","chars1","chars2","linearray","lineArray","diff_charsToLines_","diff_cleanupSemantic","pointer","count_delete","count_insert","text_delete","text_insert","subDiff","j","text1_length","text2_length","max_d","ceil","v_offset","v_length","v1","v2","x","front","k1start","k1end","k2start","k2end","k1","k1_offset","x1","y1","charAt","k2_offset","x2","diff_bisectSplit_","k2","y2","y","text1a","text2a","text1b","text2b","diffsb","lineHash","diff_linesToCharsMunge_","chars","lineStart","lineEnd","lineArrayLength","line","String","fromCharCode","maxLines","charCodeAt","pointermin","pointermax","min","pointermid","pointerstart","floor","pointerend","diff_commonOverlap_","text_length","best","pattern","found","dmp","diff_halfMatchI_","seed","best_common","best_longtext_a","best_longtext_b","best_shorttext_a","best_shorttext_b","prefixLength","suffixLength","hm1","hm2","changes","equalities","equalitiesLength","lastEquality","length_insertions1","length_deletions1","length_insertions2","length_deletions2","diff_cleanupSemanticLossless","deletion","insertion","overlap_length1","overlap_length2","diff_cleanupSemanticScore_","one","two","char1","char2","nonAlphaNumeric1","match","nonAlphaNumericRegex_","nonAlphaNumeric2","whitespace1","whitespaceRegex_","whitespace2","lineBreak1","linebreakRegex_","lineBreak2","blankLine1","blanklineEndRegex_","blankLine2","blanklineStartRegex_","equality1","edit","equality2","commonOffset","commonString","bestEquality1","bestEdit","bestEquality2","bestScore","score","diff_cleanupEfficiency","pre_ins","pre_del","post_ins","post_del","diff_xIndex","loc","last_chars1","last_chars2","diff_prettyHtml","pattern_amp","pattern_lt","pattern_gt","pattern_para","diff_text1","diff_text2","diff_levenshtein","levenshtein","insertions","deletions","diff_toDelta","encodeURI","diff_fromDelta","diffsLength","tokens","split","param","decodeURI","ex","parseInt","isNaN","match_main","match_bitap_","match_alphabet_","match_bitapScore_","accuracy","proximity","score_threshold","best_loc","lastIndexOf","matchmask","bin_min","bin_mid","bin_max","last_rd","finish","rd","charMatch","patch_addContext_","patch","start2","length1","padding","prefix","suffix","start1","length2","patch_make","opt_b","opt_c","patches","patch_obj","patchDiffLength","char_count1","char_count2","prepatch_text","postpatch_text","diff_type","diff_text","patch_deepCopy","patchesCopy","patchCopy","patch_apply","nullPadding","patch_addPadding","patch_splitMax","results","expected_loc","start_loc","end_loc","mod","paddingLength","extraLength","patch_size","bigpatch","precontext","shift","postcontext","patch_toText","patch_fromText","textline","textPointer","patchHeader","sign","coords1","coords2","module","exports","Symbol","iterator","Constructor","TypeError","defineProperties","descriptor","enumerable","configurable","defineProperty","protoProps","staticProps","object","property","receiver","Function","desc","getOwnPropertyDescriptor","getPrototypeOf","getter","subClass","superClass","setPrototypeOf","__proto__","self","ReferenceError","selfOptions","pipes","_options","pipe","pipeArg","processor","process","nextPipe","lastPipe","lastContext","nextAfterChildren","hasResult","filters","debug","log","filterName","exiting","resultCheck","msg","console","_filters","apply","prepend","_filters2","f","after","params","before","remove","shouldHaveResult","should","error","noResult","switchTo","_Context","_this","cloneDiffValues","clone$$1","trivialMatchesDiffFilter","rightType","rightIsArray","trivialMatchesPatchFilter","nested","regexArgs","trivialReferseFilter","nestedPatchFilter","nestedReverseFilter","matrix","subsequence","sequence","indices1","indices2","sameLetter","valueAtMatrixAbove","valueAtMatrixLeft","innerContext","array","item","arraysDiffFilter","matchContext","commonHead","commonTail","trimmed1","trimmed2","seq","removedItems","detectMove","arrays","includeValueOnMove","removedItemsLength","indexOnArray2","isMove","removeItemIndex1","numerically","numericallyBy","toRemove","toInsert","toModify","sort","indexDiff","removedValue","toInsertLength","toModifyLength","modification","arraysReverseFilter","substr","itemDelta","reverseIndex","deltaIndex","deltaItem","moveFromIndex","moveToIndex","deleteIndex","datesDiffFilter","required","err","diff_match_patch_not_found","diff","txt1","txt2","_patch","_error","textPatchFailed","textsDiffFilter","minLength","textDiff","diffMatchPatch","textsPatchFilter","lines","lineTmp","header","headerRegex","lineHeader","textsReverseFilter","_processor","reverse","unpatch","names","str","key1","key2","format","prepareContext","recurse","finalize","buffer","out","_buffer","typeFormattterNotFound","deltaType","typeFormattterErrorFormatter","leftKey","movedFrom","isLast","useMoveOriginHere","leftValue","getDeltaType","nodeType","nodeBegin","rootBegin","typeFormattter","stack","nodeEnd","rootEnd","formatDeltaChildren","forEachDeltaKey","arrayKeys","moveDestinations","includeMoveDestinations","parseTextDiff","output","lineOutput","pieces","location","chr","pieceIndex","piecesLength","piece","pieceOutput","_BaseFormatter","HtmlFormatter","formatValue","JSON","stringify","formatTextDiffString","nodeClass","hasArrows","format_unchanged","format_movedestination","format_node","format_added","format_modified","format_deleted","format_moved","format_textdiff","jsondiffpatchHtmlFormatterAdjustArrows","nodeArg","getElementText","innerText","eachByQuery","el","query","elems","querySelectorAll","eachChildren","_ref3","arrowParent","svg","display","destination","querySelector","container","destinationElem","distance","offsetTop","top","curve","round","indent","levels","indentLevel","indentPad","row","json","htmlNote","added","formatLegend","modified","deleted","moved","textdiff","annotator","move","JSONFormatter","pushCurrentOp","currentPath","pushMoveOp","to","toPath","movedestination","unchanged","textDiffLine","ConsoleFormatter","outLine","_len2","_key2","color","pushColor","popColor","initialProps","setProps","newProps","valueFormatter","customFormat","toISOString","rootElementStore","propsStore","defaultRootNode","newTreeMap","iterated","getNode","toggleCollapse","warn","updatedNode","expandNodeChildren","previouslyIterated","nodeWithUpdatedChildren","expandAllNodesToNode","recurseNodeUpwards","updated","Fragment","Node","doc","command","run","import_state","children","ProseMirrorNode","import_model","import_model","import_model","style","_a","doc","import_model","import_model","text","doc","empty","node","output","mark","doc","empty","range","empty","import_state","import_state","doc","import_state","import_transform","import_model","import_state","text","import_model","import_state","text","run","from","to","onDestroy","import_state","doc","range","import_transform","doc","originalCreateParagraphNear","import_state","import_commands","originalDeleteSelection","import_commands","originalExitCode","import_state","doc","import_model","text","isTextSelection","import_commands","originalJoinUp","originalJoinDown","originalJoinBackward","originalJoinForward","import_transform","import_transform","import_commands","originalCommand","import_commands","originalCommand","import_commands","isActive","originalLift","import_commands","originalLiftEmptyBlock","originalLiftListItem","import_commands","originalNewlineInCode","import_state","import_commands","originalSelectNodeBackward","import_commands","originalSelectNodeForward","import_commands","originalSelectParentNode","import_commands","originalSelectTextblockEnd","import_commands","originalSelectTextblockStart","doc","document","empty","import_commands","import_state","doc","import_state","doc","import_schema_list","originalSinkListItem","import_state","import_transform","doc","first","import_model","import_state","import_transform","newNextTypeAttributes","nextType","import_transform","isActive","isActive","isActive","empty","empty","import_commands","originalWrapIn","import_schema_list","originalWrapInList","import_transform","_a","_b","_c","import_state","moved","import_state","import_state","import_state","doc","empty","tr","import_state","import_state","children","style","moved","applyDevTools","doc","element","focus","blur","insert","import_transform","Fragment","children","import_state","doc","Node","import_state","insert","deleted"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/helpers/createChainableState.ts","../src/CommandManager.ts","../src/Editor.ts","../src/EventEmitter.ts","../src/ExtensionManager.ts","../src/helpers/combineTransactionSteps.ts","../src/helpers/createNodeFromContent.ts","../src/utilities/elementFromString.ts","../src/helpers/createDocument.ts","../src/helpers/defaultBlockAt.ts","../src/helpers/findChildren.ts","../src/helpers/findChildrenInRange.ts","../src/helpers/findParentNodeClosestToPos.ts","../src/helpers/findParentNode.ts","../src/helpers/getExtensionField.ts","../src/helpers/flattenExtensions.ts","../src/helpers/generateHTML.ts","../src/helpers/getHTMLFromFragment.ts","../src/helpers/getSchemaByResolvedExtensions.ts","../src/utilities/isFunction.ts","../src/utilities/callOrReturn.ts","../src/utilities/isEmptyObject.ts","../src/helpers/splitExtensions.ts","../src/helpers/getAttributesFromExtensions.ts","../src/utilities/mergeAttributes.ts","../src/helpers/getRenderedAttributes.ts","../src/utilities/fromString.ts","../src/helpers/injectExtensionAttributesToParseRule.ts","../src/utilities/findDuplicates.ts","../src/helpers/sortExtensions.ts","../src/helpers/resolveExtensions.ts","../src/helpers/getSchema.ts","../src/helpers/generateJSON.ts","../src/helpers/generateText.ts","../src/helpers/getTextBetween.ts","../src/helpers/getText.ts","../src/helpers/getTextSerializersFromSchema.ts","../src/helpers/getMarkType.ts","../src/helpers/getMarkAttributes.ts","../src/helpers/getNodeType.ts","../src/helpers/getNodeAttributes.ts","../src/helpers/getSchemaTypeNameByName.ts","../src/helpers/getAttributes.ts","../src/utilities/removeDuplicates.ts","../src/helpers/getChangedRanges.ts","../src/helpers/getDebugJSON.ts","../src/utilities/isRegExp.ts","../src/utilities/objectIncludes.ts","../src/helpers/getMarkRange.ts","../src/helpers/getMarksBetween.ts","../src/helpers/getNodeAtPosition.ts","../src/helpers/getSchemaTypeByName.ts","../src/helpers/getSplittedAttributes.ts","../src/helpers/getTextContentFromNodes.ts","../src/helpers/isMarkActive.ts","../src/helpers/isNodeActive.ts","../src/helpers/isActive.ts","../src/helpers/isAtEndOfNode.ts","../src/helpers/isAtStartOfNode.ts","../src/helpers/isExtensionRulesEnabled.ts","../src/helpers/isList.ts","../src/helpers/isNodeEmpty.ts","../src/helpers/isNodeSelection.ts","../src/helpers/isTextSelection.ts","../src/utilities/minMax.ts","../src/helpers/posToDOMRect.ts","../src/helpers/resolveFocusPosition.ts","../src/helpers/rewriteUnknownContent.ts","../src/helpers/selectionToInsertionEnd.ts","../src/InputRule.ts","../src/utilities/isPlainObject.ts","../src/utilities/mergeDeep.ts","../src/Extendable.ts","../src/Mark.ts","../src/PasteRule.ts","../src/utilities/isNumber.ts","../src/extensions/index.ts","../src/extensions/clipboardTextSerializer.ts","../src/Extension.ts","../src/commands/index.ts","../src/commands/blur.ts","../src/commands/clearContent.ts","../src/commands/clearNodes.ts","../src/commands/command.ts","../src/commands/createParagraphNear.ts","../src/commands/cut.ts","../src/commands/deleteCurrentNode.ts","../src/commands/deleteNode.ts","../src/commands/deleteRange.ts","../src/commands/deleteSelection.ts","../src/commands/enter.ts","../src/commands/exitCode.ts","../src/commands/extendMarkRange.ts","../src/commands/first.ts","../src/utilities/isAndroid.ts","../src/utilities/isiOS.ts","../src/commands/focus.ts","../src/commands/forEach.ts","../src/commands/insertContent.ts","../src/commands/insertContentAt.ts","../src/commands/join.ts","../src/commands/joinItemBackward.ts","../src/commands/joinItemForward.ts","../src/commands/joinTextblockBackward.ts","../src/commands/joinTextblockForward.ts","../src/utilities/isMacOS.ts","../src/commands/keyboardShortcut.ts","../src/commands/lift.ts","../src/commands/liftEmptyBlock.ts","../src/commands/liftListItem.ts","../src/commands/newlineInCode.ts","../src/utilities/deleteProps.ts","../src/commands/resetAttributes.ts","../src/commands/scrollIntoView.ts","../src/commands/selectAll.ts","../src/commands/selectNodeBackward.ts","../src/commands/selectNodeForward.ts","../src/commands/selectParentNode.ts","../src/commands/selectTextblockEnd.ts","../src/commands/selectTextblockStart.ts","../src/commands/setContent.ts","../src/commands/setMark.ts","../src/commands/setMeta.ts","../src/commands/setNode.ts","../src/commands/setNodeSelection.ts","../src/commands/setTextSelection.ts","../src/commands/sinkListItem.ts","../src/commands/splitBlock.ts","../src/commands/splitListItem.ts","../src/commands/toggleList.ts","../src/commands/toggleMark.ts","../src/commands/toggleNode.ts","../src/commands/toggleWrap.ts","../src/commands/undoInputRule.ts","../src/commands/unsetAllMarks.ts","../src/commands/unsetMark.ts","../src/commands/updateAttributes.ts","../src/commands/wrapIn.ts","../src/commands/wrapInList.ts","../src/extensions/commands.ts","../src/extensions/delete.ts","../src/extensions/drop.ts","../src/extensions/editable.ts","../src/extensions/focusEvents.ts","../src/extensions/keymap.ts","../src/extensions/paste.ts","../src/extensions/tabindex.ts","../src/NodePos.ts","../src/style.ts","../src/utilities/createStyleTag.ts","../src/inputRules/markInputRule.ts","../src/inputRules/nodeInputRule.ts","../src/inputRules/textblockTypeInputRule.ts","../src/inputRules/textInputRule.ts","../src/inputRules/wrappingInputRule.ts","../src/jsx-runtime.ts","../src/utilities/canInsertNode.ts","../src/utilities/escapeForRegEx.ts","../src/utilities/isString.ts","../src/MarkView.ts","../src/Node.ts","../src/NodeView.ts","../src/pasteRules/markPasteRule.ts","../src/pasteRules/nodePasteRule.ts","../src/pasteRules/textPasteRule.ts","../src/Tracker.ts"],"sourcesContent":["export * from './CommandManager.js'\nexport * from './Editor.js'\nexport * from './Extension.js'\nexport * as extensions from './extensions/index.js'\nexport * from './helpers/index.js'\nexport * from './InputRule.js'\nexport * from './inputRules/index.js'\nexport { createElement, Fragment, createElement as h } from './jsx-runtime.js'\nexport * from './Mark.js'\nexport * from './MarkView.js'\nexport * from './Node.js'\nexport * from './NodePos.js'\nexport * from './NodeView.js'\nexport * from './PasteRule.js'\nexport * from './pasteRules/index.js'\nexport * from './Tracker.js'\nexport * from './types.js'\nexport * from './utilities/index.js'\n\n// eslint-disable-next-line\nexport interface Commands<ReturnType = any> {}\n\n// eslint-disable-next-line\nexport interface Storage {}\n","import type { EditorState, Transaction } from '@tiptap/pm/state'\n\n/**\n * Takes a Transaction & Editor State and turns it into a chainable state object\n * @param config The transaction and state to create the chainable state from\n * @returns A chainable Editor state object\n */\nexport function createChainableState(config: { transaction: Transaction; state: EditorState }): EditorState {\n const { state, transaction } = config\n let { selection } = transaction\n let { doc } = transaction\n let { storedMarks } = transaction\n\n return {\n ...state,\n apply: state.apply.bind(state),\n applyTransaction: state.applyTransaction.bind(state),\n plugins: state.plugins,\n schema: state.schema,\n reconfigure: state.reconfigure.bind(state),\n toJSON: state.toJSON.bind(state),\n get storedMarks() {\n return storedMarks\n },\n get selection() {\n return selection\n },\n get doc() {\n return doc\n },\n get tr() {\n selection = transaction.selection\n doc = transaction.doc\n storedMarks = transaction.storedMarks\n\n return transaction\n },\n }\n}\n","import type { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport type { AnyCommands, CanCommands, ChainedCommands, CommandProps, SingleCommands } from './types.js'\n\nexport class CommandManager {\n editor: Editor\n\n rawCommands: AnyCommands\n\n customState?: EditorState\n\n constructor(props: { editor: Editor; state?: EditorState }) {\n this.editor = props.editor\n this.rawCommands = this.editor.extensionManager.commands\n this.customState = props.state\n }\n\n get hasCustomState(): boolean {\n return !!this.customState\n }\n\n get state(): EditorState {\n return this.customState || this.editor.state\n }\n\n get commands(): SingleCommands {\n const { rawCommands, editor, state } = this\n const { view } = editor\n const { tr } = state\n const props = this.buildProps(tr)\n\n return Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n const method = (...args: any[]) => {\n const callback = command(...args)(props)\n\n if (!tr.getMeta('preventDispatch') && !this.hasCustomState) {\n view.dispatch(tr)\n }\n\n return callback\n }\n\n return [name, method]\n }),\n ) as unknown as SingleCommands\n }\n\n get chain(): () => ChainedCommands {\n return () => this.createChain()\n }\n\n get can(): () => CanCommands {\n return () => this.createCan()\n }\n\n public createChain(startTr?: Transaction, shouldDispatch = true): ChainedCommands {\n const { rawCommands, editor, state } = this\n const { view } = editor\n const callbacks: boolean[] = []\n const hasStartTransaction = !!startTr\n const tr = startTr || state.tr\n\n const run = () => {\n if (!hasStartTransaction && shouldDispatch && !tr.getMeta('preventDispatch') && !this.hasCustomState) {\n view.dispatch(tr)\n }\n\n return callbacks.every(callback => callback === true)\n }\n\n const chain = {\n ...Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n const chainedCommand = (...args: never[]) => {\n const props = this.buildProps(tr, shouldDispatch)\n const callback = command(...args)(props)\n\n callbacks.push(callback)\n\n return chain\n }\n\n return [name, chainedCommand]\n }),\n ),\n run,\n } as unknown as ChainedCommands\n\n return chain\n }\n\n public createCan(startTr?: Transaction): CanCommands {\n const { rawCommands, state } = this\n const dispatch = false\n const tr = startTr || state.tr\n const props = this.buildProps(tr, dispatch)\n const formattedCommands = Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n return [name, (...args: never[]) => command(...args)({ ...props, dispatch: undefined })]\n }),\n ) as unknown as SingleCommands\n\n return {\n ...formattedCommands,\n chain: () => this.createChain(tr, dispatch),\n } as CanCommands\n }\n\n public buildProps(tr: Transaction, shouldDispatch = true): CommandProps {\n const { rawCommands, editor, state } = this\n const { view } = editor\n\n const props: CommandProps = {\n tr,\n editor,\n view,\n state: createChainableState({\n state,\n transaction: tr,\n }),\n dispatch: shouldDispatch ? () => undefined : undefined,\n chain: () => this.createChain(tr, shouldDispatch),\n can: () => this.createCan(tr),\n get commands() {\n return Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n return [name, (...args: never[]) => command(...args)(props)]\n }),\n ) as unknown as SingleCommands\n },\n }\n\n return props\n }\n}\n","/* eslint-disable @typescript-eslint/no-empty-object-type */\nimport type { MarkType, Node as ProseMirrorNode, NodeType, Schema } from '@tiptap/pm/model'\nimport type { Plugin, PluginKey, Transaction } from '@tiptap/pm/state'\nimport { EditorState } from '@tiptap/pm/state'\nimport { EditorView } from '@tiptap/pm/view'\n\nimport { CommandManager } from './CommandManager.js'\nimport { EventEmitter } from './EventEmitter.js'\nimport { ExtensionManager } from './ExtensionManager.js'\nimport {\n ClipboardTextSerializer,\n Commands,\n Delete,\n Drop,\n Editable,\n FocusEvents,\n Keymap,\n Paste,\n Tabindex,\n} from './extensions/index.js'\nimport { createDocument } from './helpers/createDocument.js'\nimport { getAttributes } from './helpers/getAttributes.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport { getText } from './helpers/getText.js'\nimport { getTextSerializersFromSchema } from './helpers/getTextSerializersFromSchema.js'\nimport { isActive } from './helpers/isActive.js'\nimport { isNodeEmpty } from './helpers/isNodeEmpty.js'\nimport { resolveFocusPosition } from './helpers/resolveFocusPosition.js'\nimport type { Storage } from './index.js'\nimport { NodePos } from './NodePos.js'\nimport { style } from './style.js'\nimport type {\n CanCommands,\n ChainedCommands,\n DocumentType,\n EditorEvents,\n EditorOptions,\n NodeType as TNodeType,\n SingleCommands,\n TextSerializer,\n TextType as TTextType,\n} from './types.js'\nimport { createStyleTag } from './utilities/createStyleTag.js'\nimport { isFunction } from './utilities/isFunction.js'\n\nexport * as extensions from './extensions/index.js'\n\n// @ts-ignore\nexport interface TiptapEditorHTMLElement extends HTMLElement {\n editor?: Editor\n}\n\nexport class Editor extends EventEmitter<EditorEvents> {\n private commandManager!: CommandManager\n\n public extensionManager!: ExtensionManager\n\n private css: HTMLStyleElement | null = null\n\n public schema!: Schema\n\n private editorView: EditorView | null = null\n\n public isFocused = false\n\n private editorState!: EditorState\n\n /**\n * The editor is considered initialized after the `create` event has been emitted.\n */\n public isInitialized = false\n\n public extensionStorage: Storage = {} as Storage\n\n /**\n * A unique ID for this editor instance.\n */\n public instanceId = Math.random().toString(36).slice(2, 9)\n\n public options: EditorOptions = {\n element: typeof document !== 'undefined' ? document.createElement('div') : null,\n content: '',\n injectCSS: true,\n injectNonce: undefined,\n extensions: [],\n autofocus: false,\n editable: true,\n editorProps: {},\n parseOptions: {},\n coreExtensionOptions: {},\n enableInputRules: true,\n enablePasteRules: true,\n enableCoreExtensions: true,\n enableContentCheck: false,\n emitContentError: false,\n onBeforeCreate: () => null,\n onCreate: () => null,\n onUpdate: () => null,\n onSelectionUpdate: () => null,\n onTransaction: () => null,\n onFocus: () => null,\n onBlur: () => null,\n onDestroy: () => null,\n onContentError: ({ error }) => {\n throw error\n },\n onPaste: () => null,\n onDrop: () => null,\n onDelete: () => null,\n }\n\n constructor(options: Partial<EditorOptions> = {}) {\n super()\n this.setOptions(options)\n this.createExtensionManager()\n this.createCommandManager()\n this.createSchema()\n this.on('beforeCreate', this.options.onBeforeCreate)\n this.emit('beforeCreate', { editor: this })\n this.on('contentError', this.options.onContentError)\n this.on('create', this.options.onCreate)\n this.on('update', this.options.onUpdate)\n this.on('selectionUpdate', this.options.onSelectionUpdate)\n this.on('transaction', this.options.onTransaction)\n this.on('focus', this.options.onFocus)\n this.on('blur', this.options.onBlur)\n this.on('destroy', this.options.onDestroy)\n this.on('drop', ({ event, slice, moved }) => this.options.onDrop(event, slice, moved))\n this.on('paste', ({ event, slice }) => this.options.onPaste(event, slice))\n this.on('delete', this.options.onDelete)\n\n const initialDoc = this.createDoc()\n const selection = resolveFocusPosition(initialDoc, this.options.autofocus)\n\n // Set editor state immediately, so that it's available independently from the view\n this.editorState = EditorState.create({\n doc: initialDoc,\n schema: this.schema,\n selection: selection || undefined,\n })\n\n if (this.options.element) {\n this.mount(this.options.element)\n }\n }\n\n /**\n * Attach the editor to the DOM, creating a new editor view.\n */\n public mount(el: NonNullable<EditorOptions['element']> & {}) {\n if (typeof document === 'undefined') {\n throw new Error(\n `[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.`,\n )\n }\n this.createView(el)\n\n window.setTimeout(() => {\n if (this.isDestroyed) {\n return\n }\n\n this.commands.focus(this.options.autofocus)\n this.emit('create', { editor: this })\n this.isInitialized = true\n }, 0)\n }\n\n /**\n * Remove the editor from the DOM, but still allow remounting at a different point in time\n */\n public unmount() {\n if (this.editorView) {\n // Cleanup our reference to prevent circular references which caused memory leaks\n // @ts-ignore\n const dom = this.editorView.dom as TiptapEditorHTMLElement\n\n if (dom?.editor) {\n delete dom.editor\n }\n this.editorView.destroy()\n }\n this.editorView = null\n this.isInitialized = false\n this.css?.remove()\n this.css = null\n }\n\n /**\n * Returns the editor storage.\n */\n public get storage(): Storage {\n return this.extensionStorage\n }\n\n /**\n * An object of all registered commands.\n */\n public get commands(): SingleCommands {\n return this.commandManager.commands\n }\n\n /**\n * Create a command chain to call multiple commands at once.\n */\n public chain(): ChainedCommands {\n return this.commandManager.chain()\n }\n\n /**\n * Check if a command or a command chain can be executed. Without executing it.\n */\n public can(): CanCommands {\n return this.commandManager.can()\n }\n\n /**\n * Inject CSS styles.\n */\n private injectCSS(): void {\n if (this.options.injectCSS && typeof document !== 'undefined') {\n this.css = createStyleTag(style, this.options.injectNonce)\n }\n }\n\n /**\n * Update editor options.\n *\n * @param options A list of options\n */\n public setOptions(options: Partial<EditorOptions> = {}): void {\n this.options = {\n ...this.options,\n ...options,\n }\n\n if (!this.editorView || !this.state || this.isDestroyed) {\n return\n }\n\n if (this.options.editorProps) {\n this.view.setProps(this.options.editorProps)\n }\n\n this.view.updateState(this.state)\n }\n\n /**\n * Update editable state of the editor.\n */\n public setEditable(editable: boolean, emitUpdate = true): void {\n this.setOptions({ editable })\n\n if (emitUpdate) {\n this.emit('update', { editor: this, transaction: this.state.tr, appendedTransactions: [] })\n }\n }\n\n /**\n * Returns whether the editor is editable.\n */\n public get isEditable(): boolean {\n // since plugins are applied after creating the view\n // `editable` is always `true` for one tick.\n // that’s why we also have to check for `options.editable`\n return this.options.editable && this.view && this.view.editable\n }\n\n /**\n * Returns the editor state.\n */\n public get view(): EditorView {\n if (this.editorView) {\n return this.editorView\n }\n\n return new Proxy(\n {\n state: this.editorState,\n updateState: (state: EditorState): ReturnType<EditorView['updateState']> => {\n this.editorState = state\n },\n dispatch: (tr: Transaction): ReturnType<EditorView['dispatch']> => {\n this.editorState = this.state.apply(tr)\n },\n\n // Stub some commonly accessed properties to prevent errors\n composing: false,\n dragging: null,\n editable: true,\n isDestroyed: false,\n } as EditorView,\n {\n get: (obj, key) => {\n // Specifically always return the most recent editorState\n if (key === 'state') {\n return this.editorState\n }\n if (key in obj) {\n return Reflect.get(obj, key)\n }\n\n // We throw an error here, because we know the view is not available\n throw new Error(\n `[tiptap error]: The editor view is not available. Cannot access view['${key as string}']. The editor may not be mounted yet.`,\n )\n },\n },\n ) as EditorView\n }\n\n /**\n * Returns the editor state.\n */\n public get state(): EditorState {\n if (this.editorView) {\n this.editorState = this.view.state\n }\n\n return this.editorState\n }\n\n /**\n * Register a ProseMirror plugin.\n *\n * @param plugin A ProseMirror plugin\n * @param handlePlugins Control how to merge the plugin into the existing plugins.\n * @returns The new editor state\n */\n public registerPlugin(\n plugin: Plugin,\n handlePlugins?: (newPlugin: Plugin, plugins: Plugin[]) => Plugin[],\n ): EditorState {\n const plugins = isFunction(handlePlugins)\n ? handlePlugins(plugin, [...this.state.plugins])\n : [...this.state.plugins, plugin]\n\n const state = this.state.reconfigure({ plugins })\n\n this.view.updateState(state)\n\n return state\n }\n\n /**\n * Unregister a ProseMirror plugin.\n *\n * @param nameOrPluginKeyToRemove The plugins name\n * @returns The new editor state or undefined if the editor is destroyed\n */\n public unregisterPlugin(\n nameOrPluginKeyToRemove: string | PluginKey | (string | PluginKey)[],\n ): EditorState | undefined {\n if (this.isDestroyed) {\n return undefined\n }\n\n const prevPlugins = this.state.plugins\n let plugins = prevPlugins\n\n ;([] as (string | PluginKey)[]).concat(nameOrPluginKeyToRemove).forEach(nameOrPluginKey => {\n // @ts-ignore\n const name = typeof nameOrPluginKey === 'string' ? `${nameOrPluginKey}$` : nameOrPluginKey.key\n\n // @ts-ignore\n plugins = plugins.filter(plugin => !plugin.key.startsWith(name))\n })\n\n if (prevPlugins.length === plugins.length) {\n // No plugin was removed, so we don’t need to update the state\n return undefined\n }\n\n const state = this.state.reconfigure({\n plugins,\n })\n\n this.view.updateState(state)\n\n return state\n }\n\n /**\n * Creates an extension manager.\n */\n private createExtensionManager(): void {\n const coreExtensions = this.options.enableCoreExtensions\n ? [\n Editable,\n ClipboardTextSerializer.configure({\n blockSeparator: this.options.coreExtensionOptions?.clipboardTextSerializer?.blockSeparator,\n }),\n Commands,\n FocusEvents,\n Keymap,\n Tabindex,\n Drop,\n Paste,\n Delete,\n ].filter(ext => {\n if (typeof this.options.enableCoreExtensions === 'object') {\n return (\n this.options.enableCoreExtensions[ext.name as keyof typeof this.options.enableCoreExtensions] !== false\n )\n }\n return true\n })\n : []\n const allExtensions = [...coreExtensions, ...this.options.extensions].filter(extension => {\n return ['extension', 'node', 'mark'].includes(extension?.type)\n })\n\n this.extensionManager = new ExtensionManager(allExtensions, this)\n }\n\n /**\n * Creates an command manager.\n */\n private createCommandManager(): void {\n this.commandManager = new CommandManager({\n editor: this,\n })\n }\n\n /**\n * Creates a ProseMirror schema.\n */\n private createSchema(): void {\n this.schema = this.extensionManager.schema\n }\n\n /**\n * Creates the initial document.\n */\n private createDoc(): ProseMirrorNode {\n let doc: ProseMirrorNode\n\n try {\n doc = createDocument(this.options.content, this.schema, this.options.parseOptions, {\n errorOnInvalidContent: this.options.enableContentCheck,\n })\n } catch (e) {\n if (\n !(e instanceof Error) ||\n !['[tiptap error]: Invalid JSON content', '[tiptap error]: Invalid HTML content'].includes(e.message)\n ) {\n // Not the content error we were expecting\n throw e\n }\n this.emit('contentError', {\n editor: this,\n error: e as Error,\n disableCollaboration: () => {\n if (\n 'collaboration' in this.storage &&\n typeof this.storage.collaboration === 'object' &&\n this.storage.collaboration\n ) {\n ;(this.storage.collaboration as any).isDisabled = true\n }\n // To avoid syncing back invalid content, reinitialize the extensions without the collaboration extension\n this.options.extensions = this.options.extensions.filter(extension => extension.name !== 'collaboration')\n\n // Restart the initialization process by recreating the extension manager with the new set of extensions\n this.createExtensionManager()\n },\n })\n\n // Content is invalid, but attempt to create it anyway, stripping out the invalid parts\n doc = createDocument(this.options.content, this.schema, this.options.parseOptions, {\n errorOnInvalidContent: false,\n })\n }\n return doc\n }\n\n /**\n * Creates a ProseMirror view.\n */\n private createView(element: NonNullable<EditorOptions['element']> & {}): void {\n this.editorView = new EditorView(element, {\n ...this.options.editorProps,\n attributes: {\n // add `role=\"textbox\"` to the editor element\n role: 'textbox',\n ...this.options.editorProps?.attributes,\n },\n dispatchTransaction: this.dispatchTransaction.bind(this),\n state: this.editorState,\n })\n\n // `editor.view` is not yet available at this time.\n // Therefore we will add all plugins and node views directly afterwards.\n const newState = this.state.reconfigure({\n plugins: this.extensionManager.plugins,\n })\n\n this.view.updateState(newState)\n\n this.createNodeViews()\n this.prependClass()\n this.injectCSS()\n\n // Let’s store the editor instance in the DOM element.\n // So we’ll have access to it for tests.\n // @ts-ignore\n const dom = this.view.dom as TiptapEditorHTMLElement\n\n dom.editor = this\n }\n\n /**\n * Creates all node and mark views.\n */\n public createNodeViews(): void {\n if (this.view.isDestroyed) {\n return\n }\n\n this.view.setProps({\n markViews: this.extensionManager.markViews,\n nodeViews: this.extensionManager.nodeViews,\n })\n }\n\n /**\n * Prepend class name to element.\n */\n public prependClass(): void {\n this.view.dom.className = `tiptap ${this.view.dom.className}`\n }\n\n public isCapturingTransaction = false\n\n private capturedTransaction: Transaction | null = null\n\n public captureTransaction(fn: () => void) {\n this.isCapturingTransaction = true\n fn()\n this.isCapturingTransaction = false\n\n const tr = this.capturedTransaction\n\n this.capturedTransaction = null\n\n return tr\n }\n\n /**\n * The callback over which to send transactions (state updates) produced by the view.\n *\n * @param transaction An editor state transaction\n */\n private dispatchTransaction(transaction: Transaction): void {\n // if the editor / the view of the editor was destroyed\n // the transaction should not be dispatched as there is no view anymore.\n if (this.view.isDestroyed) {\n return\n }\n\n if (this.isCapturingTransaction) {\n if (!this.capturedTransaction) {\n this.capturedTransaction = transaction\n\n return\n }\n\n transaction.steps.forEach(step => this.capturedTransaction?.step(step))\n\n return\n }\n\n // Apply transaction and get resulting state and transactions\n const { state, transactions } = this.state.applyTransaction(transaction)\n const selectionHasChanged = !this.state.selection.eq(state.selection)\n const rootTrWasApplied = transactions.includes(transaction)\n const prevState = this.state\n\n this.emit('beforeTransaction', {\n editor: this,\n transaction,\n nextState: state,\n })\n\n // If transaction was filtered out, we can return early\n if (!rootTrWasApplied) {\n return\n }\n\n this.view.updateState(state)\n\n // Emit transaction event with appended transactions info\n this.emit('transaction', {\n editor: this,\n transaction,\n appendedTransactions: transactions.slice(1),\n })\n\n if (selectionHasChanged) {\n this.emit('selectionUpdate', {\n editor: this,\n transaction,\n })\n }\n\n // Only emit the latest between focus and blur events\n const mostRecentFocusTr = transactions.findLast(tr => tr.getMeta('focus') || tr.getMeta('blur'))\n const focus = mostRecentFocusTr?.getMeta('focus')\n const blur = mostRecentFocusTr?.getMeta('blur')\n\n if (focus) {\n this.emit('focus', {\n editor: this,\n event: focus.event,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n transaction: mostRecentFocusTr!,\n })\n }\n\n if (blur) {\n this.emit('blur', {\n editor: this,\n event: blur.event,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n transaction: mostRecentFocusTr!,\n })\n }\n\n // Compare states for update event\n if (\n transaction.getMeta('preventUpdate') ||\n !transactions.some(tr => tr.docChanged) ||\n prevState.doc.eq(state.doc)\n ) {\n return\n }\n\n this.emit('update', {\n editor: this,\n transaction,\n appendedTransactions: transactions.slice(1),\n })\n }\n\n /**\n * Get attributes of the currently selected node or mark.\n */\n public getAttributes(nameOrType: string | NodeType | MarkType): Record<string, any> {\n return getAttributes(this.state, nameOrType)\n }\n\n /**\n * Returns if the currently selected node or mark is active.\n *\n * @param name Name of the node or mark\n * @param attributes Attributes of the node or mark\n */\n public isActive(name: string, attributes?: {}): boolean\n public isActive(attributes: {}): boolean\n public isActive(nameOrAttributes: string, attributesOrUndefined?: {}): boolean {\n const name = typeof nameOrAttributes === 'string' ? nameOrAttributes : null\n\n const attributes = typeof nameOrAttributes === 'string' ? attributesOrUndefined : nameOrAttributes\n\n return isActive(this.state, name, attributes)\n }\n\n /**\n * Get the document as JSON.\n */\n public getJSON(): DocumentType<\n Record<string, any> | undefined,\n TNodeType<string, undefined | Record<string, any>, any, (TNodeType | TTextType)[]>[]\n > {\n return this.state.doc.toJSON()\n }\n\n /**\n * Get the document as HTML.\n */\n public getHTML(): string {\n return getHTMLFromFragment(this.state.doc.content, this.schema)\n }\n\n /**\n * Get the document as text.\n */\n public getText(options?: { blockSeparator?: string; textSerializers?: Record<string, TextSerializer> }): string {\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n\n return getText(this.state.doc, {\n blockSeparator,\n textSerializers: {\n ...getTextSerializersFromSchema(this.schema),\n ...textSerializers,\n },\n })\n }\n\n /**\n * Check if there is no content.\n */\n public get isEmpty(): boolean {\n return isNodeEmpty(this.state.doc)\n }\n\n /**\n * Destroy the editor.\n */\n public destroy(): void {\n this.emit('destroy')\n\n this.unmount()\n\n this.removeAllListeners()\n }\n\n /**\n * Check if the editor is already destroyed.\n */\n public get isDestroyed(): boolean {\n return this.editorView?.isDestroyed ?? true\n }\n\n public $node(selector: string, attributes?: { [key: string]: any }): NodePos | null {\n return this.$doc?.querySelector(selector, attributes) || null\n }\n\n public $nodes(selector: string, attributes?: { [key: string]: any }): NodePos[] | null {\n return this.$doc?.querySelectorAll(selector, attributes) || null\n }\n\n public $pos(pos: number) {\n const $pos = this.state.doc.resolve(pos)\n\n return new NodePos($pos, this)\n }\n\n get $doc() {\n return this.$pos(0)\n }\n}\n","type StringKeyOf<T> = Extract<keyof T, string>\ntype CallbackType<T extends Record<string, any>, EventName extends StringKeyOf<T>> = T[EventName] extends any[]\n ? T[EventName]\n : [T[EventName]]\ntype CallbackFunction<T extends Record<string, any>, EventName extends StringKeyOf<T>> = (\n ...props: CallbackType<T, EventName>\n) => any\n\nexport class EventEmitter<T extends Record<string, any>> {\n private callbacks: { [key: string]: Array<(...args: any[]) => void> } = {}\n\n public on<EventName extends StringKeyOf<T>>(event: EventName, fn: CallbackFunction<T, EventName>): this {\n if (!this.callbacks[event]) {\n this.callbacks[event] = []\n }\n\n this.callbacks[event].push(fn)\n\n return this\n }\n\n public emit<EventName extends StringKeyOf<T>>(event: EventName, ...args: CallbackType<T, EventName>): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n callbacks.forEach(callback => callback.apply(this, args))\n }\n\n return this\n }\n\n public off<EventName extends StringKeyOf<T>>(event: EventName, fn?: CallbackFunction<T, EventName>): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n if (fn) {\n this.callbacks[event] = callbacks.filter(callback => callback !== fn)\n } else {\n delete this.callbacks[event]\n }\n }\n\n return this\n }\n\n public once<EventName extends StringKeyOf<T>>(event: EventName, fn: CallbackFunction<T, EventName>): this {\n const onceFn = (...args: CallbackType<T, EventName>) => {\n this.off(event, onceFn)\n fn.apply(this, args)\n }\n\n return this.on(event, onceFn)\n }\n\n public removeAllListeners(): void {\n this.callbacks = {}\n }\n}\n","import { keymap } from '@tiptap/pm/keymap'\nimport type { Schema } from '@tiptap/pm/model'\nimport type { Plugin } from '@tiptap/pm/state'\nimport type { MarkViewConstructor, NodeViewConstructor } from '@tiptap/pm/view'\n\nimport type { Editor } from './Editor.js'\nimport {\n flattenExtensions,\n getAttributesFromExtensions,\n getExtensionField,\n getNodeType,\n getRenderedAttributes,\n getSchemaByResolvedExtensions,\n getSchemaTypeByName,\n isExtensionRulesEnabled,\n resolveExtensions,\n sortExtensions,\n splitExtensions,\n} from './helpers/index.js'\nimport { type MarkConfig, type NodeConfig, type Storage, getMarkType, updateMarkViewAttributes } from './index.js'\nimport type { InputRule } from './InputRule.js'\nimport { inputRulesPlugin } from './InputRule.js'\nimport { Mark } from './Mark.js'\nimport type { PasteRule } from './PasteRule.js'\nimport { pasteRulesPlugin } from './PasteRule.js'\nimport type { AnyConfig, Extensions, RawCommands } from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\n\nexport class ExtensionManager {\n editor: Editor\n\n schema: Schema\n\n extensions: Extensions\n\n splittableMarks: string[] = []\n\n constructor(extensions: Extensions, editor: Editor) {\n this.editor = editor\n this.extensions = resolveExtensions(extensions)\n this.schema = getSchemaByResolvedExtensions(this.extensions, editor)\n this.setupExtensions()\n }\n\n static resolve = resolveExtensions\n\n static sort = sortExtensions\n\n static flatten = flattenExtensions\n\n /**\n * Get all commands from the extensions.\n * @returns An object with all commands where the key is the command name and the value is the command function\n */\n get commands(): RawCommands {\n return this.extensions.reduce((commands, extension) => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor: this.editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n const addCommands = getExtensionField<AnyConfig['addCommands']>(extension, 'addCommands', context)\n\n if (!addCommands) {\n return commands\n }\n\n return {\n ...commands,\n ...addCommands(),\n }\n }, {} as RawCommands)\n }\n\n /**\n * Get all registered Prosemirror plugins from the extensions.\n * @returns An array of Prosemirror plugins\n */\n get plugins(): Plugin[] {\n const { editor } = this\n\n // With ProseMirror, first plugins within an array are executed first.\n // In Tiptap, we provide the ability to override plugins,\n // so it feels more natural to run plugins at the end of an array first.\n // That’s why we have to reverse the `extensions` array and sort again\n // based on the `priority` option.\n const extensions = sortExtensions([...this.extensions].reverse())\n\n const inputRules: InputRule[] = []\n const pasteRules: PasteRule[] = []\n\n const allPlugins = extensions\n .map(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n const plugins: Plugin[] = []\n\n const addKeyboardShortcuts = getExtensionField<AnyConfig['addKeyboardShortcuts']>(\n extension,\n 'addKeyboardShortcuts',\n context,\n )\n\n let defaultBindings: Record<string, () => boolean> = {}\n\n // bind exit handling\n if (extension.type === 'mark' && getExtensionField<MarkConfig['exitable']>(extension, 'exitable', context)) {\n defaultBindings.ArrowRight = () => Mark.handleExit({ editor, mark: extension as Mark })\n }\n\n if (addKeyboardShortcuts) {\n const bindings = Object.fromEntries(\n Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => {\n return [shortcut, () => method({ editor })]\n }),\n )\n\n defaultBindings = { ...defaultBindings, ...bindings }\n }\n\n const keyMapPlugin = keymap(defaultBindings)\n\n plugins.push(keyMapPlugin)\n\n const addInputRules = getExtensionField<AnyConfig['addInputRules']>(extension, 'addInputRules', context)\n\n if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) {\n inputRules.push(...addInputRules())\n }\n\n const addPasteRules = getExtensionField<AnyConfig['addPasteRules']>(extension, 'addPasteRules', context)\n\n if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) {\n pasteRules.push(...addPasteRules())\n }\n\n const addProseMirrorPlugins = getExtensionField<AnyConfig['addProseMirrorPlugins']>(\n extension,\n 'addProseMirrorPlugins',\n context,\n )\n\n if (addProseMirrorPlugins) {\n const proseMirrorPlugins = addProseMirrorPlugins()\n\n plugins.push(...proseMirrorPlugins)\n }\n\n return plugins\n })\n .flat()\n\n return [\n inputRulesPlugin({\n editor,\n rules: inputRules,\n }),\n ...pasteRulesPlugin({\n editor,\n rules: pasteRules,\n }),\n ...allPlugins,\n ]\n }\n\n /**\n * Get all attributes from the extensions.\n * @returns An array of attributes\n */\n get attributes() {\n return getAttributesFromExtensions(this.extensions)\n }\n\n /**\n * Get all node views from the extensions.\n * @returns An object with all node views where the key is the node name and the value is the node view function\n */\n get nodeViews(): Record<string, NodeViewConstructor> {\n const { editor } = this\n const { nodeExtensions } = splitExtensions(this.extensions)\n\n return Object.fromEntries(\n nodeExtensions\n .filter(extension => !!getExtensionField(extension, 'addNodeView'))\n .map(extension => {\n const extensionAttributes = this.attributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getNodeType(extension.name, this.schema),\n }\n const addNodeView = getExtensionField<NodeConfig['addNodeView']>(extension, 'addNodeView', context)\n\n if (!addNodeView) {\n return []\n }\n\n const nodeview: NodeViewConstructor = (node, view, getPos, decorations, innerDecorations) => {\n const HTMLAttributes = getRenderedAttributes(node, extensionAttributes)\n\n return addNodeView()({\n // pass-through\n node,\n view,\n getPos: getPos as () => number,\n decorations,\n innerDecorations,\n // tiptap-specific\n editor,\n extension,\n HTMLAttributes,\n })\n }\n\n return [extension.name, nodeview]\n }),\n )\n }\n\n get markViews(): Record<string, MarkViewConstructor> {\n const { editor } = this\n const { markExtensions } = splitExtensions(this.extensions)\n\n return Object.fromEntries(\n markExtensions\n .filter(extension => !!getExtensionField(extension, 'addMarkView'))\n .map(extension => {\n const extensionAttributes = this.attributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getMarkType(extension.name, this.schema),\n }\n const addMarkView = getExtensionField<MarkConfig['addMarkView']>(extension, 'addMarkView', context)\n\n if (!addMarkView) {\n return []\n }\n\n const markView: MarkViewConstructor = (mark, view, inline) => {\n const HTMLAttributes = getRenderedAttributes(mark, extensionAttributes)\n\n return addMarkView()({\n // pass-through\n mark,\n view,\n inline,\n // tiptap-specific\n editor,\n extension,\n HTMLAttributes,\n updateAttributes: (attrs: Record<string, any>) => {\n updateMarkViewAttributes(mark, editor, attrs)\n },\n })\n }\n\n return [extension.name, markView]\n }),\n )\n }\n\n /**\n * Go through all extensions, create extension storages & setup marks\n * & bind editor event listener.\n */\n private setupExtensions() {\n const extensions = this.extensions\n // re-initialize the extension storage object instance\n this.editor.extensionStorage = Object.fromEntries(\n extensions.map(extension => [extension.name, extension.storage]),\n ) as unknown as Storage\n\n extensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor: this.editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n if (extension.type === 'mark') {\n const keepOnSplit = callOrReturn(getExtensionField(extension, 'keepOnSplit', context)) ?? true\n\n if (keepOnSplit) {\n this.splittableMarks.push(extension.name)\n }\n }\n\n const onBeforeCreate = getExtensionField<AnyConfig['onBeforeCreate']>(extension, 'onBeforeCreate', context)\n const onCreate = getExtensionField<AnyConfig['onCreate']>(extension, 'onCreate', context)\n const onUpdate = getExtensionField<AnyConfig['onUpdate']>(extension, 'onUpdate', context)\n const onSelectionUpdate = getExtensionField<AnyConfig['onSelectionUpdate']>(\n extension,\n 'onSelectionUpdate',\n context,\n )\n const onTransaction = getExtensionField<AnyConfig['onTransaction']>(extension, 'onTransaction', context)\n const onFocus = getExtensionField<AnyConfig['onFocus']>(extension, 'onFocus', context)\n const onBlur = getExtensionField<AnyConfig['onBlur']>(extension, 'onBlur', context)\n const onDestroy = getExtensionField<AnyConfig['onDestroy']>(extension, 'onDestroy', context)\n\n if (onBeforeCreate) {\n this.editor.on('beforeCreate', onBeforeCreate)\n }\n\n if (onCreate) {\n this.editor.on('create', onCreate)\n }\n\n if (onUpdate) {\n this.editor.on('update', onUpdate)\n }\n\n if (onSelectionUpdate) {\n this.editor.on('selectionUpdate', onSelectionUpdate)\n }\n\n if (onTransaction) {\n this.editor.on('transaction', onTransaction)\n }\n\n if (onFocus) {\n this.editor.on('focus', onFocus)\n }\n\n if (onBlur) {\n this.editor.on('blur', onBlur)\n }\n\n if (onDestroy) {\n this.editor.on('destroy', onDestroy)\n }\n })\n }\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport type { Transaction } from '@tiptap/pm/state'\nimport { Transform } from '@tiptap/pm/transform'\n\n/**\n * Returns a new `Transform` based on all steps of the passed transactions.\n * @param oldDoc The Prosemirror node to start from\n * @param transactions The transactions to combine\n * @returns A new `Transform` with all steps of the passed transactions\n */\nexport function combineTransactionSteps(oldDoc: ProseMirrorNode, transactions: Transaction[]): Transform {\n const transform = new Transform(oldDoc)\n\n transactions.forEach(transaction => {\n transaction.steps.forEach(step => {\n transform.step(step)\n })\n })\n\n return transform\n}\n","import type { ParseOptions } from '@tiptap/pm/model'\nimport { DOMParser, Fragment, Node as ProseMirrorNode, Schema } from '@tiptap/pm/model'\n\nimport type { Content } from '../types.js'\nimport { elementFromString } from '../utilities/elementFromString.js'\n\nexport type CreateNodeFromContentOptions = {\n slice?: boolean\n parseOptions?: ParseOptions\n errorOnInvalidContent?: boolean\n}\n\n/**\n * Takes a JSON or HTML content and creates a Prosemirror node or fragment from it.\n * @param content The JSON or HTML content to create the node from\n * @param schema The Prosemirror schema to use for the node\n * @param options Options for the parser\n * @returns The created Prosemirror node or fragment\n */\nexport function createNodeFromContent(\n content: Content | ProseMirrorNode | Fragment,\n schema: Schema,\n options?: CreateNodeFromContentOptions,\n): ProseMirrorNode | Fragment {\n if (content instanceof ProseMirrorNode || content instanceof Fragment) {\n return content\n }\n options = {\n slice: true,\n parseOptions: {},\n ...options,\n }\n\n const isJSONContent = typeof content === 'object' && content !== null\n const isTextContent = typeof content === 'string'\n\n if (isJSONContent) {\n try {\n const isArrayContent = Array.isArray(content) && content.length > 0\n\n // if the JSON Content is an array of nodes, create a fragment for each node\n if (isArrayContent) {\n return Fragment.fromArray(content.map(item => schema.nodeFromJSON(item)))\n }\n\n const node = schema.nodeFromJSON(content)\n\n if (options.errorOnInvalidContent) {\n node.check()\n }\n\n return node\n } catch (error) {\n if (options.errorOnInvalidContent) {\n throw new Error('[tiptap error]: Invalid JSON content', { cause: error as Error })\n }\n\n console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error)\n\n return createNodeFromContent('', schema, options)\n }\n }\n\n if (isTextContent) {\n // Check for invalid content\n if (options.errorOnInvalidContent) {\n let hasInvalidContent = false\n let invalidContent = ''\n\n // A copy of the current schema with a catch-all node at the end\n const contentCheckSchema = new Schema({\n topNode: schema.spec.topNode,\n marks: schema.spec.marks,\n // Prosemirror's schemas are executed such that: the last to execute, matches last\n // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle\n nodes: schema.spec.nodes.append({\n __tiptap__private__unknown__catch__all__node: {\n content: 'inline*',\n group: 'block',\n parseDOM: [\n {\n tag: '*',\n getAttrs: e => {\n // If this is ever called, we know that the content has something that we don't know how to handle in the schema\n hasInvalidContent = true\n // Try to stringify the element for a more helpful error message\n invalidContent = typeof e === 'string' ? e : e.outerHTML\n return null\n },\n },\n ],\n },\n }),\n })\n\n if (options.slice) {\n DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions)\n } else {\n DOMParser.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions)\n }\n\n if (options.errorOnInvalidContent && hasInvalidContent) {\n throw new Error('[tiptap error]: Invalid HTML content', {\n cause: new Error(`Invalid element found: ${invalidContent}`),\n })\n }\n }\n\n const parser = DOMParser.fromSchema(schema)\n\n if (options.slice) {\n return parser.parseSlice(elementFromString(content), options.parseOptions).content\n }\n\n return parser.parse(elementFromString(content), options.parseOptions)\n }\n\n return createNodeFromContent('', schema, options)\n}\n","const removeWhitespaces = (node: HTMLElement) => {\n const children = node.childNodes\n\n for (let i = children.length - 1; i >= 0; i -= 1) {\n const child = children[i]\n\n if (child.nodeType === 3 && child.nodeValue && /^(\\n\\s\\s|\\n)$/.test(child.nodeValue)) {\n node.removeChild(child)\n } else if (child.nodeType === 1) {\n removeWhitespaces(child as HTMLElement)\n }\n }\n\n return node\n}\n\nexport function elementFromString(value: string): HTMLElement {\n if (typeof window === 'undefined') {\n throw new Error('[tiptap error]: there is no window object available, so this function cannot be used')\n }\n // add a wrapper to preserve leading and trailing whitespace\n const wrappedValue = `<body>${value}</body>`\n\n const html = new window.DOMParser().parseFromString(wrappedValue, 'text/html').body\n\n return removeWhitespaces(html)\n}\n","import type { Fragment, Node as ProseMirrorNode, ParseOptions, Schema } from '@tiptap/pm/model'\n\nimport type { Content } from '../types.js'\nimport { createNodeFromContent } from './createNodeFromContent.js'\n\n/**\n * Create a new Prosemirror document node from content.\n * @param content The JSON or HTML content to create the document from\n * @param schema The Prosemirror schema to use for the document\n * @param parseOptions Options for the parser\n * @returns The created Prosemirror document node\n */\nexport function createDocument(\n content: Content | ProseMirrorNode | Fragment,\n schema: Schema,\n parseOptions: ParseOptions = {},\n options: { errorOnInvalidContent?: boolean } = {},\n): ProseMirrorNode {\n return createNodeFromContent(content, schema, {\n slice: false,\n parseOptions,\n errorOnInvalidContent: options.errorOnInvalidContent,\n }) as ProseMirrorNode\n}\n","import type { ContentMatch, NodeType } from '@tiptap/pm/model'\n\n/**\n * Gets the default block type at a given match\n * @param match The content match to get the default block type from\n * @returns The default block type or null\n */\nexport function defaultBlockAt(match: ContentMatch): NodeType | null {\n for (let i = 0; i < match.edgeCount; i += 1) {\n const { type } = match.edge(i)\n\n if (type.isTextblock && !type.hasRequiredAttrs()) {\n return type\n }\n }\n\n return null\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { NodeWithPos, Predicate } from '../types.js'\n\n/**\n * Find children inside a Prosemirror node that match a predicate.\n * @param node The Prosemirror node to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nexport function findChildren(node: ProseMirrorNode, predicate: Predicate): NodeWithPos[] {\n const nodesWithPos: NodeWithPos[] = []\n\n node.descendants((child, pos) => {\n if (predicate(child)) {\n nodesWithPos.push({\n node: child,\n pos,\n })\n }\n })\n\n return nodesWithPos\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { NodeWithPos, Predicate, Range } from '../types.js'\n\n/**\n * Same as `findChildren` but searches only within a `range`.\n * @param node The Prosemirror node to search in\n * @param range The range to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nexport function findChildrenInRange(node: ProseMirrorNode, range: Range, predicate: Predicate): NodeWithPos[] {\n const nodesWithPos: NodeWithPos[] = []\n\n // if (range.from === range.to) {\n // const nodeAt = node.nodeAt(range.from)\n\n // if (nodeAt) {\n // nodesWithPos.push({\n // node: nodeAt,\n // pos: range.from,\n // })\n // }\n // }\n\n node.nodesBetween(range.from, range.to, (child, pos) => {\n if (predicate(child)) {\n nodesWithPos.push({\n node: child,\n pos,\n })\n }\n })\n\n return nodesWithPos\n}\n","import type { Node as ProseMirrorNode, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Predicate } from '../types.js'\n\n/**\n * Finds the closest parent node to a resolved position that matches a predicate.\n * @param $pos The resolved position to search from\n * @param predicate The predicate to match\n * @returns The closest parent node to the resolved position that matches the predicate\n * @example ```js\n * findParentNodeClosestToPos($from, node => node.type.name === 'paragraph')\n * ```\n */\nexport function findParentNodeClosestToPos(\n $pos: ResolvedPos,\n predicate: Predicate,\n):\n | {\n pos: number\n start: number\n depth: number\n node: ProseMirrorNode\n }\n | undefined {\n for (let i = $pos.depth; i > 0; i -= 1) {\n const node = $pos.node(i)\n\n if (predicate(node)) {\n return {\n pos: i > 0 ? $pos.before(i) : 0,\n start: $pos.start(i),\n depth: i,\n node,\n }\n }\n }\n}\n","import type { Selection } from '@tiptap/pm/state'\n\nimport type { Predicate } from '../types.js'\nimport { findParentNodeClosestToPos } from './findParentNodeClosestToPos.js'\n\n/**\n * Finds the closest parent node to the current selection that matches a predicate.\n * @param predicate The predicate to match\n * @returns A command that finds the closest parent node to the current selection that matches the predicate\n * @example ```js\n * findParentNode(node => node.type.name === 'paragraph')\n * ```\n */\nexport function findParentNode(\n predicate: Predicate,\n): (selection: Selection) => ReturnType<typeof findParentNodeClosestToPos> {\n return (selection: Selection) => findParentNodeClosestToPos(selection.$from, predicate)\n}\n","import type { ExtensionConfig } from '../Extension.js'\nimport type { MarkConfig } from '../Mark.js'\nimport type { NodeConfig } from '../Node.js'\nimport type { AnyExtension, MaybeThisParameterType, RemoveThis } from '../types.js'\n\n/**\n * Returns a field from an extension\n * @param extension The Tiptap extension\n * @param field The field, for example `renderHTML` or `priority`\n * @param context The context object that should be passed as `this` into the function\n * @returns The field value\n */\nexport function getExtensionField<T = any, E extends AnyExtension = any>(\n extension: E,\n field: keyof ExtensionConfig | keyof MarkConfig | keyof NodeConfig,\n context?: Omit<MaybeThisParameterType<T>, 'parent'>,\n): RemoveThis<T> {\n if (extension.config[field as keyof typeof extension.config] === undefined && extension.parent) {\n return getExtensionField(extension.parent, field, context)\n }\n\n if (typeof extension.config[field as keyof typeof extension.config] === 'function') {\n const value = (extension.config[field as keyof typeof extension.config] as any).bind({\n ...context,\n parent: extension.parent ? getExtensionField(extension.parent, field, context) : null,\n })\n\n return value\n }\n\n return extension.config[field as keyof typeof extension.config] as RemoveThis<T>\n}\n","import type { AnyConfig, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\n\n/**\n * Create a flattened array of extensions by traversing the `addExtensions` field.\n * @param extensions An array of Tiptap extensions\n * @returns A flattened array of Tiptap extensions\n */\nexport function flattenExtensions(extensions: Extensions): Extensions {\n return (\n extensions\n .map(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n }\n\n const addExtensions = getExtensionField<AnyConfig['addExtensions']>(extension, 'addExtensions', context)\n\n if (addExtensions) {\n return [extension, ...flattenExtensions(addExtensions())]\n }\n\n return extension\n })\n // `Infinity` will break TypeScript so we set a number that is probably high enough\n .flat(10)\n )\n}\n","import { Node } from '@tiptap/pm/model'\n\nimport type { Extensions, JSONContent } from '../types.js'\nimport { getHTMLFromFragment } from './getHTMLFromFragment.js'\nimport { getSchema } from './getSchema.js'\n\n/**\n * Generate HTML from a JSONContent\n * @param doc The JSONContent to generate HTML from\n * @param extensions The extensions to use for the schema\n * @returns The generated HTML\n */\nexport function generateHTML(doc: JSONContent, extensions: Extensions): string {\n const schema = getSchema(extensions)\n const contentNode = Node.fromJSON(schema, doc)\n\n return getHTMLFromFragment(contentNode.content, schema)\n}\n","import type { Fragment, Schema } from '@tiptap/pm/model'\nimport { DOMSerializer } from '@tiptap/pm/model'\n\nexport function getHTMLFromFragment(fragment: Fragment, schema: Schema): string {\n const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment)\n\n const temporaryDocument = document.implementation.createHTMLDocument()\n const container = temporaryDocument.createElement('div')\n\n container.appendChild(documentFragment)\n\n return container.innerHTML\n}\n","import type { MarkSpec, NodeSpec, TagParseRule } from '@tiptap/pm/model'\nimport { Schema } from '@tiptap/pm/model'\n\nimport type { Editor, MarkConfig, NodeConfig } from '../index.js'\nimport type { AnyConfig, Extensions } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\nimport { isEmptyObject } from '../utilities/isEmptyObject.js'\nimport { getAttributesFromExtensions } from './getAttributesFromExtensions.js'\nimport { getExtensionField } from './getExtensionField.js'\nimport { getRenderedAttributes } from './getRenderedAttributes.js'\nimport { injectExtensionAttributesToParseRule } from './injectExtensionAttributesToParseRule.js'\nimport { splitExtensions } from './splitExtensions.js'\n\nfunction cleanUpSchemaItem<T>(data: T) {\n return Object.fromEntries(\n // @ts-ignore\n Object.entries(data).filter(([key, value]) => {\n if (key === 'attrs' && isEmptyObject(value as object | undefined)) {\n return false\n }\n\n return value !== null && value !== undefined\n }),\n ) as T\n}\n\n/**\n * Creates a new Prosemirror schema based on the given extensions.\n * @param extensions An array of Tiptap extensions\n * @param editor The editor instance\n * @returns A Prosemirror schema\n */\nexport function getSchemaByResolvedExtensions(extensions: Extensions, editor?: Editor): Schema {\n const allAttributes = getAttributesFromExtensions(extensions)\n const { nodeExtensions, markExtensions } = splitExtensions(extensions)\n const topNode = nodeExtensions.find(extension => getExtensionField(extension, 'topNode'))?.name\n\n const nodes = Object.fromEntries(\n nodeExtensions.map(extension => {\n const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor,\n }\n\n const extraNodeFields = extensions.reduce((fields, e) => {\n const extendNodeSchema = getExtensionField<AnyConfig['extendNodeSchema']>(e, 'extendNodeSchema', context)\n\n return {\n ...fields,\n ...(extendNodeSchema ? extendNodeSchema(extension) : {}),\n }\n }, {})\n\n const schema: NodeSpec = cleanUpSchemaItem({\n ...extraNodeFields,\n content: callOrReturn(getExtensionField<NodeConfig['content']>(extension, 'content', context)),\n marks: callOrReturn(getExtensionField<NodeConfig['marks']>(extension, 'marks', context)),\n group: callOrReturn(getExtensionField<NodeConfig['group']>(extension, 'group', context)),\n inline: callOrReturn(getExtensionField<NodeConfig['inline']>(extension, 'inline', context)),\n atom: callOrReturn(getExtensionField<NodeConfig['atom']>(extension, 'atom', context)),\n selectable: callOrReturn(getExtensionField<NodeConfig['selectable']>(extension, 'selectable', context)),\n draggable: callOrReturn(getExtensionField<NodeConfig['draggable']>(extension, 'draggable', context)),\n code: callOrReturn(getExtensionField<NodeConfig['code']>(extension, 'code', context)),\n whitespace: callOrReturn(getExtensionField<NodeConfig['whitespace']>(extension, 'whitespace', context)),\n linebreakReplacement: callOrReturn(\n getExtensionField<NodeConfig['linebreakReplacement']>(extension, 'linebreakReplacement', context),\n ),\n defining: callOrReturn(getExtensionField<NodeConfig['defining']>(extension, 'defining', context)),\n isolating: callOrReturn(getExtensionField<NodeConfig['isolating']>(extension, 'isolating', context)),\n attrs: Object.fromEntries(\n extensionAttributes.map(extensionAttribute => {\n return [\n extensionAttribute.name,\n { default: extensionAttribute?.attribute?.default, validate: extensionAttribute?.attribute?.validate },\n ]\n }),\n ),\n })\n\n const parseHTML = callOrReturn(getExtensionField<NodeConfig['parseHTML']>(extension, 'parseHTML', context))\n\n if (parseHTML) {\n schema.parseDOM = parseHTML.map(parseRule =>\n injectExtensionAttributesToParseRule(parseRule, extensionAttributes),\n ) as TagParseRule[]\n }\n\n const renderHTML = getExtensionField<NodeConfig['renderHTML']>(extension, 'renderHTML', context)\n\n if (renderHTML) {\n schema.toDOM = node =>\n renderHTML({\n node,\n HTMLAttributes: getRenderedAttributes(node, extensionAttributes),\n })\n }\n\n const renderText = getExtensionField<NodeConfig['renderText']>(extension, 'renderText', context)\n\n if (renderText) {\n schema.toText = renderText\n }\n\n return [extension.name, schema]\n }),\n )\n\n const marks = Object.fromEntries(\n markExtensions.map(extension => {\n const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor,\n }\n\n const extraMarkFields = extensions.reduce((fields, e) => {\n const extendMarkSchema = getExtensionField<AnyConfig['extendMarkSchema']>(e, 'extendMarkSchema', context)\n\n return {\n ...fields,\n ...(extendMarkSchema ? extendMarkSchema(extension as any) : {}),\n }\n }, {})\n\n const schema: MarkSpec = cleanUpSchemaItem({\n ...extraMarkFields,\n inclusive: callOrReturn(getExtensionField<MarkConfig['inclusive']>(extension, 'inclusive', context)),\n excludes: callOrReturn(getExtensionField<MarkConfig['excludes']>(extension, 'excludes', context)),\n group: callOrReturn(getExtensionField<MarkConfig['group']>(extension, 'group', context)),\n spanning: callOrReturn(getExtensionField<MarkConfig['spanning']>(extension, 'spanning', context)),\n code: callOrReturn(getExtensionField<MarkConfig['code']>(extension, 'code', context)),\n attrs: Object.fromEntries(\n extensionAttributes.map(extensionAttribute => {\n return [\n extensionAttribute.name,\n { default: extensionAttribute?.attribute?.default, validate: extensionAttribute?.attribute?.validate },\n ]\n }),\n ),\n })\n\n const parseHTML = callOrReturn(getExtensionField<MarkConfig['parseHTML']>(extension, 'parseHTML', context))\n\n if (parseHTML) {\n schema.parseDOM = parseHTML.map(parseRule =>\n injectExtensionAttributesToParseRule(parseRule, extensionAttributes),\n )\n }\n\n const renderHTML = getExtensionField<MarkConfig['renderHTML']>(extension, 'renderHTML', context)\n\n if (renderHTML) {\n schema.toDOM = mark =>\n renderHTML({\n mark,\n HTMLAttributes: getRenderedAttributes(mark, extensionAttributes),\n })\n }\n\n return [extension.name, schema]\n }),\n )\n\n return new Schema({\n topNode,\n nodes,\n marks,\n })\n}\n","// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport function isFunction(value: any): value is Function {\n return typeof value === 'function'\n}\n","import type { MaybeReturnType } from '../types.js'\nimport { isFunction } from './isFunction.js'\n\n/**\n * Optionally calls `value` as a function.\n * Otherwise it is returned directly.\n * @param value Function or any value.\n * @param context Optional context to bind to function.\n * @param props Optional props to pass to function.\n */\nexport function callOrReturn<T>(value: T, context: any = undefined, ...props: any[]): MaybeReturnType<T> {\n if (isFunction(value)) {\n if (context) {\n return value.bind(context)(...props)\n }\n\n return value(...props)\n }\n\n return value as MaybeReturnType<T>\n}\n","export function isEmptyObject(value = {}): boolean {\n return Object.keys(value).length === 0 && value.constructor === Object\n}\n","import type { Extension } from '../Extension.js'\nimport type { Mark } from '../Mark.js'\nimport type { Node } from '../Node.js'\nimport type { Extensions } from '../types.js'\n\nexport function splitExtensions(extensions: Extensions) {\n const baseExtensions = extensions.filter(extension => extension.type === 'extension') as Extension[]\n const nodeExtensions = extensions.filter(extension => extension.type === 'node') as Node[]\n const markExtensions = extensions.filter(extension => extension.type === 'mark') as Mark[]\n\n return {\n baseExtensions,\n nodeExtensions,\n markExtensions,\n }\n}\n","import type { MarkConfig, NodeConfig } from '../index.js'\nimport type { AnyConfig, Attribute, Attributes, ExtensionAttribute, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\nimport { splitExtensions } from './splitExtensions.js'\n\n/**\n * Get a list of all extension attributes defined in `addAttribute` and `addGlobalAttribute`.\n * @param extensions List of extensions\n */\nexport function getAttributesFromExtensions(extensions: Extensions): ExtensionAttribute[] {\n const extensionAttributes: ExtensionAttribute[] = []\n const { nodeExtensions, markExtensions } = splitExtensions(extensions)\n const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions]\n const defaultAttribute: Required<Omit<Attribute, 'validate'>> & Pick<Attribute, 'validate'> = {\n default: null,\n validate: undefined,\n rendered: true,\n renderHTML: null,\n parseHTML: null,\n keepOnSplit: true,\n isRequired: false,\n }\n\n extensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n extensions: nodeAndMarkExtensions,\n }\n\n const addGlobalAttributes = getExtensionField<AnyConfig['addGlobalAttributes']>(\n extension,\n 'addGlobalAttributes',\n context,\n )\n\n if (!addGlobalAttributes) {\n return\n }\n\n const globalAttributes = addGlobalAttributes()\n\n globalAttributes.forEach(globalAttribute => {\n globalAttribute.types.forEach(type => {\n Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => {\n extensionAttributes.push({\n type,\n name,\n attribute: {\n ...defaultAttribute,\n ...attribute,\n },\n })\n })\n })\n })\n })\n\n nodeAndMarkExtensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n }\n\n const addAttributes = getExtensionField<NodeConfig['addAttributes'] | MarkConfig['addAttributes']>(\n extension,\n 'addAttributes',\n context,\n )\n\n if (!addAttributes) {\n return\n }\n\n // TODO: remove `as Attributes`\n const attributes = addAttributes() as Attributes\n\n Object.entries(attributes).forEach(([name, attribute]) => {\n const mergedAttr = {\n ...defaultAttribute,\n ...attribute,\n }\n\n if (typeof mergedAttr?.default === 'function') {\n mergedAttr.default = mergedAttr.default()\n }\n\n if (mergedAttr?.isRequired && mergedAttr?.default === undefined) {\n delete mergedAttr.default\n }\n\n extensionAttributes.push({\n type: extension.name,\n name,\n attribute: mergedAttr,\n })\n })\n })\n\n return extensionAttributes\n}\n","export function mergeAttributes(...objects: Record<string, any>[]): Record<string, any> {\n return objects\n .filter(item => !!item)\n .reduce((items, item) => {\n const mergedAttributes = { ...items }\n\n Object.entries(item).forEach(([key, value]) => {\n const exists = mergedAttributes[key]\n\n if (!exists) {\n mergedAttributes[key] = value\n\n return\n }\n\n if (key === 'class') {\n const valueClasses: string[] = value ? String(value).split(' ') : []\n const existingClasses: string[] = mergedAttributes[key] ? mergedAttributes[key].split(' ') : []\n\n const insertClasses = valueClasses.filter(valueClass => !existingClasses.includes(valueClass))\n\n mergedAttributes[key] = [...existingClasses, ...insertClasses].join(' ')\n } else if (key === 'style') {\n const newStyles: string[] = value\n ? value\n .split(';')\n .map((style: string) => style.trim())\n .filter(Boolean)\n : []\n const existingStyles: string[] = mergedAttributes[key]\n ? mergedAttributes[key]\n .split(';')\n .map((style: string) => style.trim())\n .filter(Boolean)\n : []\n\n const styleMap = new Map<string, string>()\n\n existingStyles.forEach(style => {\n const [property, val] = style.split(':').map(part => part.trim())\n\n styleMap.set(property, val)\n })\n\n newStyles.forEach(style => {\n const [property, val] = style.split(':').map(part => part.trim())\n\n styleMap.set(property, val)\n })\n\n mergedAttributes[key] = Array.from(styleMap.entries())\n .map(([property, val]) => `${property}: ${val}`)\n .join('; ')\n } else {\n mergedAttributes[key] = value\n }\n })\n\n return mergedAttributes\n }, {})\n}\n","import type { Mark, Node } from '@tiptap/pm/model'\n\nimport type { ExtensionAttribute } from '../types.js'\nimport { mergeAttributes } from '../utilities/mergeAttributes.js'\n\nexport function getRenderedAttributes(\n nodeOrMark: Node | Mark,\n extensionAttributes: ExtensionAttribute[],\n): Record<string, any> {\n return extensionAttributes\n .filter(attribute => attribute.type === nodeOrMark.type.name)\n .filter(item => item.attribute.rendered)\n .map(item => {\n if (!item.attribute.renderHTML) {\n return {\n [item.name]: nodeOrMark.attrs[item.name],\n }\n }\n\n return item.attribute.renderHTML(nodeOrMark.attrs) || {}\n })\n .reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {})\n}\n","export function fromString(value: any): any {\n if (typeof value !== 'string') {\n return value\n }\n\n if (value.match(/^[+-]?(?:\\d*\\.)?\\d+$/)) {\n return Number(value)\n }\n\n if (value === 'true') {\n return true\n }\n\n if (value === 'false') {\n return false\n }\n\n return value\n}\n","import type { ParseRule } from '@tiptap/pm/model'\n\nimport type { ExtensionAttribute } from '../types.js'\nimport { fromString } from '../utilities/fromString.js'\n\n/**\n * This function merges extension attributes into parserule attributes (`attrs` or `getAttrs`).\n * Cancels when `getAttrs` returned `false`.\n * @param parseRule ProseMirror ParseRule\n * @param extensionAttributes List of attributes to inject\n */\nexport function injectExtensionAttributesToParseRule(\n parseRule: ParseRule,\n extensionAttributes: ExtensionAttribute[],\n): ParseRule {\n if ('style' in parseRule) {\n return parseRule\n }\n\n return {\n ...parseRule,\n getAttrs: (node: HTMLElement) => {\n const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs\n\n if (oldAttributes === false) {\n return false\n }\n\n const newAttributes = extensionAttributes.reduce((items, item) => {\n const value = item.attribute.parseHTML\n ? item.attribute.parseHTML(node)\n : fromString(node.getAttribute(item.name))\n\n if (value === null || value === undefined) {\n return items\n }\n\n return {\n ...items,\n [item.name]: value,\n }\n }, {})\n\n return { ...oldAttributes, ...newAttributes }\n },\n }\n}\n","/**\n * Find duplicates in an array.\n */\nexport function findDuplicates<T>(items: T[]): T[] {\n const filtered = items.filter((el, index) => items.indexOf(el) !== index)\n\n return Array.from(new Set(filtered))\n}\n","import type { AnyConfig, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\n\n/**\n * Sort extensions by priority.\n * @param extensions An array of Tiptap extensions\n * @returns A sorted array of Tiptap extensions by priority\n */\nexport function sortExtensions(extensions: Extensions): Extensions {\n const defaultPriority = 100\n\n return extensions.sort((a, b) => {\n const priorityA = getExtensionField<AnyConfig['priority']>(a, 'priority') || defaultPriority\n const priorityB = getExtensionField<AnyConfig['priority']>(b, 'priority') || defaultPriority\n\n if (priorityA > priorityB) {\n return -1\n }\n\n if (priorityA < priorityB) {\n return 1\n }\n\n return 0\n })\n}\n","import type { Extensions } from '../types.js'\nimport { findDuplicates } from '../utilities/findDuplicates.js'\nimport { flattenExtensions } from './flattenExtensions.js'\nimport { sortExtensions } from './sortExtensions.js'\n\n/**\n * Returns a flattened and sorted extension list while\n * also checking for duplicated extensions and warns the user.\n * @param extensions An array of Tiptap extensions\n * @returns An flattened and sorted array of Tiptap extensions\n */\nexport function resolveExtensions(extensions: Extensions): Extensions {\n const resolvedExtensions = sortExtensions(flattenExtensions(extensions))\n const duplicatedNames = findDuplicates(resolvedExtensions.map(extension => extension.name))\n\n if (duplicatedNames.length) {\n console.warn(\n `[tiptap warn]: Duplicate extension names found: [${duplicatedNames\n .map(item => `'${item}'`)\n .join(', ')}]. This can lead to issues.`,\n )\n }\n\n return resolvedExtensions\n}\n","import type { Schema } from '@tiptap/pm/model'\n\nimport type { Editor } from '../Editor.js'\nimport type { Extensions } from '../types.js'\nimport { getSchemaByResolvedExtensions } from './getSchemaByResolvedExtensions.js'\nimport { resolveExtensions } from './resolveExtensions.js'\n\nexport function getSchema(extensions: Extensions, editor?: Editor): Schema {\n const resolvedExtensions = resolveExtensions(extensions)\n\n return getSchemaByResolvedExtensions(resolvedExtensions, editor)\n}\n","import { DOMParser } from '@tiptap/pm/model'\n\nimport type { Extensions } from '../types.js'\nimport { elementFromString } from '../utilities/elementFromString.js'\nimport { getSchema } from './getSchema.js'\n\n/**\n * Generate JSONContent from HTML\n * @param html The HTML to generate JSONContent from\n * @param extensions The extensions to use for the schema\n * @returns The generated JSONContent\n */\nexport function generateJSON(html: string, extensions: Extensions): Record<string, any> {\n const schema = getSchema(extensions)\n const dom = elementFromString(html)\n\n return DOMParser.fromSchema(schema).parse(dom).toJSON()\n}\n","import { Node } from '@tiptap/pm/model'\n\nimport type { Extensions, JSONContent, TextSerializer } from '../types.js'\nimport { getSchema } from './getSchema.js'\nimport { getText } from './getText.js'\nimport { getTextSerializersFromSchema } from './getTextSerializersFromSchema.js'\n\n/**\n * Generate raw text from a JSONContent\n * @param doc The JSONContent to generate text from\n * @param extensions The extensions to use for the schema\n * @param options Options for the text generation f.e. blockSeparator or textSerializers\n * @returns The generated text\n */\nexport function generateText(\n doc: JSONContent,\n extensions: Extensions,\n options?: {\n blockSeparator?: string\n textSerializers?: Record<string, TextSerializer>\n },\n): string {\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n const schema = getSchema(extensions)\n const contentNode = Node.fromJSON(schema, doc)\n\n return getText(contentNode, {\n blockSeparator,\n textSerializers: {\n ...getTextSerializersFromSchema(schema),\n ...textSerializers,\n },\n })\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { Range, TextSerializer } from '../types.js'\n\n/**\n * Gets the text between two positions in a Prosemirror node\n * and serializes it using the given text serializers and block separator (see getText)\n * @param startNode The Prosemirror node to start from\n * @param range The range of the text to get\n * @param options Options for the text serializer & block separator\n * @returns The text between the two positions\n */\nexport function getTextBetween(\n startNode: ProseMirrorNode,\n range: Range,\n options?: {\n blockSeparator?: string\n textSerializers?: Record<string, TextSerializer>\n },\n): string {\n const { from, to } = range\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n let text = ''\n\n startNode.nodesBetween(from, to, (node, pos, parent, index) => {\n if (node.isBlock && pos > from) {\n text += blockSeparator\n }\n\n const textSerializer = textSerializers?.[node.type.name]\n\n if (textSerializer) {\n if (parent) {\n text += textSerializer({\n node,\n pos,\n parent,\n index,\n range,\n })\n }\n // do not descend into child nodes when there exists a serializer\n return false\n }\n\n if (node.isText) {\n text += node?.text?.slice(Math.max(from, pos) - pos, to - pos) // eslint-disable-line\n }\n })\n\n return text\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { TextSerializer } from '../types.js'\nimport { getTextBetween } from './getTextBetween.js'\n\n/**\n * Gets the text of a Prosemirror node\n * @param node The Prosemirror node\n * @param options Options for the text serializer & block separator\n * @returns The text of the node\n * @example ```js\n * const text = getText(node, { blockSeparator: '\\n' })\n * ```\n */\nexport function getText(\n node: ProseMirrorNode,\n options?: {\n blockSeparator?: string\n textSerializers?: Record<string, TextSerializer>\n },\n) {\n const range = {\n from: 0,\n to: node.content.size,\n }\n\n return getTextBetween(node, range, options)\n}\n","import type { Schema } from '@tiptap/pm/model'\n\nimport type { TextSerializer } from '../types.js'\n\n/**\n * Find text serializers `toText` in a Prosemirror schema\n * @param schema The Prosemirror schema to search in\n * @returns A record of text serializers by node name\n */\nexport function getTextSerializersFromSchema(schema: Schema): Record<string, TextSerializer> {\n return Object.fromEntries(\n Object.entries(schema.nodes)\n .filter(([, node]) => node.spec.toText)\n .map(([name, node]) => [name, node.spec.toText]),\n )\n}\n","import type { MarkType, Schema } from '@tiptap/pm/model'\n\nexport function getMarkType(nameOrType: string | MarkType, schema: Schema): MarkType {\n if (typeof nameOrType === 'string') {\n if (!schema.marks[nameOrType]) {\n throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`)\n }\n\n return schema.marks[nameOrType]\n }\n\n return nameOrType\n}\n","import type { Mark, MarkType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getMarkType } from './getMarkType.js'\n\nexport function getMarkAttributes(state: EditorState, typeOrName: string | MarkType): Record<string, any> {\n const type = getMarkType(typeOrName, state.schema)\n const { from, to, empty } = state.selection\n const marks: Mark[] = []\n\n if (empty) {\n if (state.storedMarks) {\n marks.push(...state.storedMarks)\n }\n\n marks.push(...state.selection.$head.marks())\n } else {\n state.doc.nodesBetween(from, to, node => {\n marks.push(...node.marks)\n })\n }\n\n const mark = marks.find(markItem => markItem.type.name === type.name)\n\n if (!mark) {\n return {}\n }\n\n return { ...mark.attrs }\n}\n","import type { NodeType, Schema } from '@tiptap/pm/model'\n\nexport function getNodeType(nameOrType: string | NodeType, schema: Schema): NodeType {\n if (typeof nameOrType === 'string') {\n if (!schema.nodes[nameOrType]) {\n throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`)\n }\n\n return schema.nodes[nameOrType]\n }\n\n return nameOrType\n}\n","import type { Node, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getNodeType } from './getNodeType.js'\n\nexport function getNodeAttributes(state: EditorState, typeOrName: string | NodeType): Record<string, any> {\n const type = getNodeType(typeOrName, state.schema)\n const { from, to } = state.selection\n const nodes: Node[] = []\n\n state.doc.nodesBetween(from, to, node => {\n nodes.push(node)\n })\n\n const node = nodes.reverse().find(nodeItem => nodeItem.type.name === type.name)\n\n if (!node) {\n return {}\n }\n\n return { ...node.attrs }\n}\n","import type { Schema } from '@tiptap/pm/model'\n\n/**\n * Get the type of a schema item by its name.\n * @param name The name of the schema item\n * @param schema The Prosemiror schema to search in\n * @returns The type of the schema item (`node` or `mark`), or null if it doesn't exist\n */\nexport function getSchemaTypeNameByName(name: string, schema: Schema): 'node' | 'mark' | null {\n if (schema.nodes[name]) {\n return 'node'\n }\n\n if (schema.marks[name]) {\n return 'mark'\n }\n\n return null\n}\n","import type { MarkType, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getMarkAttributes } from './getMarkAttributes.js'\nimport { getNodeAttributes } from './getNodeAttributes.js'\nimport { getSchemaTypeNameByName } from './getSchemaTypeNameByName.js'\n\n/**\n * Get node or mark attributes by type or name on the current editor state\n * @param state The current editor state\n * @param typeOrName The node or mark type or name\n * @returns The attributes of the node or mark or an empty object\n */\nexport function getAttributes(state: EditorState, typeOrName: string | NodeType | MarkType): Record<string, any> {\n const schemaType = getSchemaTypeNameByName(\n typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n state.schema,\n )\n\n if (schemaType === 'node') {\n return getNodeAttributes(state, typeOrName as NodeType)\n }\n\n if (schemaType === 'mark') {\n return getMarkAttributes(state, typeOrName as MarkType)\n }\n\n return {}\n}\n","/**\n * Removes duplicated values within an array.\n * Supports numbers, strings and objects.\n */\nexport function removeDuplicates<T>(array: T[], by = JSON.stringify): T[] {\n const seen: Record<any, any> = {}\n\n return array.filter(item => {\n const key = by(item)\n\n return Object.prototype.hasOwnProperty.call(seen, key) ? false : (seen[key] = true)\n })\n}\n","import type { Step, Transform } from '@tiptap/pm/transform'\n\nimport type { Range } from '../types.js'\nimport { removeDuplicates } from '../utilities/removeDuplicates.js'\n\nexport type ChangedRange = {\n oldRange: Range\n newRange: Range\n}\n\n/**\n * Removes duplicated ranges and ranges that are\n * fully captured by other ranges.\n */\nfunction simplifyChangedRanges(changes: ChangedRange[]): ChangedRange[] {\n const uniqueChanges = removeDuplicates(changes)\n\n return uniqueChanges.length === 1\n ? uniqueChanges\n : uniqueChanges.filter((change, index) => {\n const rest = uniqueChanges.filter((_, i) => i !== index)\n\n return !rest.some(otherChange => {\n return (\n change.oldRange.from >= otherChange.oldRange.from &&\n change.oldRange.to <= otherChange.oldRange.to &&\n change.newRange.from >= otherChange.newRange.from &&\n change.newRange.to <= otherChange.newRange.to\n )\n })\n })\n}\n\n/**\n * Returns a list of changed ranges\n * based on the first and last state of all steps.\n */\nexport function getChangedRanges(transform: Transform): ChangedRange[] {\n const { mapping, steps } = transform\n const changes: ChangedRange[] = []\n\n mapping.maps.forEach((stepMap, index) => {\n const ranges: Range[] = []\n\n // This accounts for step changes where no range was actually altered\n // e.g. when setting a mark, node attribute, etc.\n // @ts-ignore\n if (!stepMap.ranges.length) {\n const { from, to } = steps[index] as Step & {\n from?: number\n to?: number\n }\n\n if (from === undefined || to === undefined) {\n return\n }\n\n ranges.push({ from, to })\n } else {\n stepMap.forEach((from, to) => {\n ranges.push({ from, to })\n })\n }\n\n ranges.forEach(({ from, to }) => {\n const newStart = mapping.slice(index).map(from, -1)\n const newEnd = mapping.slice(index).map(to)\n const oldStart = mapping.invert().map(newStart, -1)\n const oldEnd = mapping.invert().map(newEnd)\n\n changes.push({\n oldRange: {\n from: oldStart,\n to: oldEnd,\n },\n newRange: {\n from: newStart,\n to: newEnd,\n },\n })\n })\n })\n\n return simplifyChangedRanges(changes)\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { JSONContent } from '../types.js'\n\ninterface DebugJSONContent extends JSONContent {\n from: number\n to: number\n}\n\nexport function getDebugJSON(node: ProseMirrorNode, startOffset = 0): DebugJSONContent {\n const isTopNode = node.type === node.type.schema.topNodeType\n const increment = isTopNode ? 0 : 1\n const from = startOffset\n const to = from + node.nodeSize\n const marks = node.marks.map(mark => {\n const output: { type: string; attrs?: Record<string, any> } = {\n type: mark.type.name,\n }\n\n if (Object.keys(mark.attrs).length) {\n output.attrs = { ...mark.attrs }\n }\n\n return output\n })\n const attrs = { ...node.attrs }\n const output: DebugJSONContent = {\n type: node.type.name,\n from,\n to,\n }\n\n if (Object.keys(attrs).length) {\n output.attrs = attrs\n }\n\n if (marks.length) {\n output.marks = marks\n }\n\n if (node.content.childCount) {\n output.content = []\n\n node.forEach((child, offset) => {\n output.content?.push(getDebugJSON(child, startOffset + offset + increment))\n })\n }\n\n if (node.text) {\n output.text = node.text\n }\n\n return output\n}\n","export function isRegExp(value: any): value is RegExp {\n return Object.prototype.toString.call(value) === '[object RegExp]'\n}\n","import { isRegExp } from './isRegExp.js'\n\n/**\n * Check if object1 includes object2\n * @param object1 Object\n * @param object2 Object\n */\nexport function objectIncludes(\n object1: Record<string, any>,\n object2: Record<string, any>,\n options: { strict: boolean } = { strict: true },\n): boolean {\n const keys = Object.keys(object2)\n\n if (!keys.length) {\n return true\n }\n\n return keys.every(key => {\n if (options.strict) {\n return object2[key] === object1[key]\n }\n\n if (isRegExp(object2[key])) {\n return object2[key].test(object1[key])\n }\n\n return object2[key] === object1[key]\n })\n}\n","import type { Mark as ProseMirrorMark, MarkType, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Range } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\n\nfunction findMarkInSet(\n marks: ProseMirrorMark[],\n type: MarkType,\n attributes: Record<string, any> = {},\n): ProseMirrorMark | undefined {\n return marks.find(item => {\n return (\n item.type === type &&\n objectIncludes(\n // Only check equality for the attributes that are provided\n Object.fromEntries(Object.keys(attributes).map(k => [k, item.attrs[k]])),\n attributes,\n )\n )\n })\n}\n\nfunction isMarkInSet(marks: ProseMirrorMark[], type: MarkType, attributes: Record<string, any> = {}): boolean {\n return !!findMarkInSet(marks, type, attributes)\n}\n\n/**\n * Get the range of a mark at a resolved position.\n */\nexport function getMarkRange(\n /**\n * The position to get the mark range for.\n */\n $pos: ResolvedPos,\n /**\n * The mark type to get the range for.\n */\n type: MarkType,\n /**\n * The attributes to match against.\n * If not provided, only the first mark at the position will be matched.\n */\n attributes?: Record<string, any>,\n): Range | void {\n if (!$pos || !type) {\n return\n }\n let start = $pos.parent.childAfter($pos.parentOffset)\n\n // If the cursor is at the start of a text node that does not have the mark, look backward\n if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n start = $pos.parent.childBefore($pos.parentOffset)\n }\n\n // If there is no text node with the mark even backward, return undefined\n if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n return\n }\n\n // Default to only matching against the first mark's attributes\n attributes = attributes || start.node.marks[0]?.attrs\n\n // We now know that the cursor is either at the start, middle or end of a text node with the specified mark\n // so we can look it up on the targeted mark\n const mark = findMarkInSet([...start.node.marks], type, attributes)\n\n if (!mark) {\n return\n }\n\n let startIndex = start.index\n let startPos = $pos.start() + start.offset\n let endIndex = startIndex + 1\n let endPos = startPos + start.node.nodeSize\n\n while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) {\n startIndex -= 1\n startPos -= $pos.parent.child(startIndex).nodeSize\n }\n\n while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) {\n endPos += $pos.parent.child(endIndex).nodeSize\n endIndex += 1\n }\n\n return {\n from: startPos,\n to: endPos,\n }\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { MarkRange } from '../types.js'\nimport { getMarkRange } from './getMarkRange.js'\n\nexport function getMarksBetween(from: number, to: number, doc: ProseMirrorNode): MarkRange[] {\n const marks: MarkRange[] = []\n\n // get all inclusive marks on empty selection\n if (from === to) {\n doc\n .resolve(from)\n .marks()\n .forEach(mark => {\n const $pos = doc.resolve(from)\n const range = getMarkRange($pos, mark.type)\n\n if (!range) {\n return\n }\n\n marks.push({\n mark,\n ...range,\n })\n })\n } else {\n doc.nodesBetween(from, to, (node, pos) => {\n if (!node || node?.nodeSize === undefined) {\n return\n }\n\n marks.push(\n ...node.marks.map(mark => ({\n from: pos,\n to: pos + node.nodeSize,\n mark,\n })),\n )\n })\n }\n\n return marks\n}\n","import type { Node, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\n/**\n * Finds the first node of a given type or name in the current selection.\n * @param state The editor state.\n * @param typeOrName The node type or name.\n * @param pos The position to start searching from.\n * @param maxDepth The maximum depth to search.\n * @returns The node and the depth as an array.\n */\nexport const getNodeAtPosition = (state: EditorState, typeOrName: string | NodeType, pos: number, maxDepth = 20) => {\n const $pos = state.doc.resolve(pos)\n\n let currentDepth = maxDepth\n let node: Node | null = null\n\n while (currentDepth > 0 && node === null) {\n const currentNode = $pos.node(currentDepth)\n\n if (currentNode?.type.name === typeOrName) {\n node = currentNode\n } else {\n currentDepth -= 1\n }\n }\n\n return [node, currentDepth] as [Node | null, number]\n}\n","import type { MarkType, NodeType, Schema } from '@tiptap/pm/model'\n\n/**\n * Tries to get a node or mark type by its name.\n * @param name The name of the node or mark type\n * @param schema The Prosemiror schema to search in\n * @returns The node or mark type, or null if it doesn't exist\n */\nexport function getSchemaTypeByName(name: string, schema: Schema): NodeType | MarkType | null {\n return schema.nodes[name] || schema.marks[name] || null\n}\n","import type { ExtensionAttribute } from '../types.js'\n\n/**\n * Return attributes of an extension that should be splitted by keepOnSplit flag\n * @param extensionAttributes Array of extension attributes\n * @param typeName The type of the extension\n * @param attributes The attributes of the extension\n * @returns The splitted attributes\n */\nexport function getSplittedAttributes(\n extensionAttributes: ExtensionAttribute[],\n typeName: string,\n attributes: Record<string, any>,\n): Record<string, any> {\n return Object.fromEntries(\n Object.entries(attributes).filter(([name]) => {\n const extensionAttribute = extensionAttributes.find(item => {\n return item.type === typeName && item.name === name\n })\n\n if (!extensionAttribute) {\n return false\n }\n\n return extensionAttribute.attribute.keepOnSplit\n }),\n )\n}\n","import type { ResolvedPos } from '@tiptap/pm/model'\n\n/**\n * Returns the text content of a resolved prosemirror position\n * @param $from The resolved position to get the text content from\n * @param maxMatch The maximum number of characters to match\n * @returns The text content\n */\nexport const getTextContentFromNodes = ($from: ResolvedPos, maxMatch = 500) => {\n let textBefore = ''\n\n const sliceEndPos = $from.parentOffset\n\n $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node, pos, parent, index) => {\n const chunk =\n node.type.spec.toText?.({\n node,\n pos,\n parent,\n index,\n }) ||\n node.textContent ||\n '%leaf%'\n\n textBefore += node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos))\n })\n\n return textBefore\n}\n","import type { MarkType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport type { MarkRange } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\nimport { getMarkType } from './getMarkType.js'\n\nexport function isMarkActive(\n state: EditorState,\n typeOrName: MarkType | string | null,\n attributes: Record<string, any> = {},\n): boolean {\n const { empty, ranges } = state.selection\n const type = typeOrName ? getMarkType(typeOrName, state.schema) : null\n\n if (empty) {\n return !!(state.storedMarks || state.selection.$from.marks())\n .filter(mark => {\n if (!type) {\n return true\n }\n\n return type.name === mark.type.name\n })\n .find(mark => objectIncludes(mark.attrs, attributes, { strict: false }))\n }\n\n let selectionRange = 0\n const markRanges: MarkRange[] = []\n\n ranges.forEach(({ $from, $to }) => {\n const from = $from.pos\n const to = $to.pos\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isText && !node.marks.length) {\n return\n }\n\n const relativeFrom = Math.max(from, pos)\n const relativeTo = Math.min(to, pos + node.nodeSize)\n const range = relativeTo - relativeFrom\n\n selectionRange += range\n\n markRanges.push(\n ...node.marks.map(mark => ({\n mark,\n from: relativeFrom,\n to: relativeTo,\n })),\n )\n })\n })\n\n if (selectionRange === 0) {\n return false\n }\n\n // calculate range of matched mark\n const matchedRange = markRanges\n .filter(markRange => {\n if (!type) {\n return true\n }\n\n return type.name === markRange.mark.type.name\n })\n .filter(markRange => objectIncludes(markRange.mark.attrs, attributes, { strict: false }))\n .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0)\n\n // calculate range of marks that excludes the searched mark\n // for example `code` doesn’t allow any other marks\n const excludedRange = markRanges\n .filter(markRange => {\n if (!type) {\n return true\n }\n\n return markRange.mark.type !== type && markRange.mark.type.excludes(type)\n })\n .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0)\n\n // we only include the result of `excludedRange`\n // if there is a match at all\n const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange\n\n return range >= selectionRange\n}\n","import type { NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport type { NodeRange } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\nimport { getNodeType } from './getNodeType.js'\n\nexport function isNodeActive(\n state: EditorState,\n typeOrName: NodeType | string | null,\n attributes: Record<string, any> = {},\n): boolean {\n const { from, to, empty } = state.selection\n const type = typeOrName ? getNodeType(typeOrName, state.schema) : null\n\n const nodeRanges: NodeRange[] = []\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (node.isText) {\n return\n }\n\n const relativeFrom = Math.max(from, pos)\n const relativeTo = Math.min(to, pos + node.nodeSize)\n\n nodeRanges.push({\n node,\n from: relativeFrom,\n to: relativeTo,\n })\n })\n\n const selectionRange = to - from\n const matchedNodeRanges = nodeRanges\n .filter(nodeRange => {\n if (!type) {\n return true\n }\n\n return type.name === nodeRange.node.type.name\n })\n .filter(nodeRange => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }))\n\n if (empty) {\n return !!matchedNodeRanges.length\n }\n\n const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0)\n\n return range >= selectionRange\n}\n","import type { EditorState } from '@tiptap/pm/state'\n\nimport { getSchemaTypeNameByName } from './getSchemaTypeNameByName.js'\nimport { isMarkActive } from './isMarkActive.js'\nimport { isNodeActive } from './isNodeActive.js'\n\nexport function isActive(state: EditorState, name: string | null, attributes: Record<string, any> = {}): boolean {\n if (!name) {\n return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes)\n }\n\n const schemaType = getSchemaTypeNameByName(name, state.schema)\n\n if (schemaType === 'node') {\n return isNodeActive(state, name, attributes)\n }\n\n if (schemaType === 'mark') {\n return isMarkActive(state, name, attributes)\n }\n\n return false\n}\n","import type { EditorState } from '@tiptap/pm/state'\n\nimport { findParentNode } from './findParentNode.js'\n\nexport const isAtEndOfNode = (state: EditorState, nodeType?: string) => {\n const { $from, $to, $anchor } = state.selection\n\n if (nodeType) {\n const parentNode = findParentNode(node => node.type.name === nodeType)(state.selection)\n\n if (!parentNode) {\n return false\n }\n\n const $parentPos = state.doc.resolve(parentNode.pos + 1)\n\n if ($anchor.pos + 1 === $parentPos.end()) {\n return true\n }\n\n return false\n }\n\n if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) {\n return false\n }\n\n return true\n}\n","import type { EditorState } from '@tiptap/pm/state'\n\nexport const isAtStartOfNode = (state: EditorState) => {\n const { $from, $to } = state.selection\n\n if ($from.parentOffset > 0 || $from.pos !== $to.pos) {\n return false\n }\n\n return true\n}\n","import type { AnyExtension, EnableRules } from '../types.js'\n\nexport function isExtensionRulesEnabled(extension: AnyExtension, enabled: EnableRules): boolean {\n if (Array.isArray(enabled)) {\n return enabled.some(enabledExtension => {\n const name = typeof enabledExtension === 'string' ? enabledExtension : enabledExtension.name\n\n return name === extension.name\n })\n }\n\n return enabled\n}\n","import { getExtensionField } from '../helpers/getExtensionField.js'\nimport type { NodeConfig } from '../index.js'\nimport type { Extensions } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\nimport { splitExtensions } from './splitExtensions.js'\n\nexport function isList(name: string, extensions: Extensions): boolean {\n const { nodeExtensions } = splitExtensions(extensions)\n const extension = nodeExtensions.find(item => item.name === name)\n\n if (!extension) {\n return false\n }\n\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n }\n const group = callOrReturn(getExtensionField<NodeConfig['group']>(extension, 'group', context))\n\n if (typeof group !== 'string') {\n return false\n }\n\n return group.split(' ').includes('list')\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\n/**\n * Returns true if the given prosemirror node is empty.\n */\nexport function isNodeEmpty(\n node: ProseMirrorNode,\n {\n checkChildren = true,\n ignoreWhitespace = false,\n }: {\n /**\n * When true (default), it will also check if all children are empty.\n */\n checkChildren?: boolean\n /**\n * When true, it will ignore whitespace when checking for emptiness.\n */\n ignoreWhitespace?: boolean\n } = {},\n): boolean {\n if (ignoreWhitespace) {\n if (node.type.name === 'hardBreak') {\n // Hard breaks are considered empty\n return true\n }\n if (node.isText) {\n return /^\\s*$/m.test(node.text ?? '')\n }\n }\n\n if (node.isText) {\n return !node.text\n }\n\n if (node.isAtom || node.isLeaf) {\n return false\n }\n\n if (node.content.childCount === 0) {\n return true\n }\n\n if (checkChildren) {\n let isContentEmpty = true\n\n node.content.forEach(childNode => {\n if (isContentEmpty === false) {\n // Exit early for perf\n return\n }\n\n if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {\n isContentEmpty = false\n }\n })\n\n return isContentEmpty\n }\n\n return false\n}\n","import { NodeSelection } from '@tiptap/pm/state'\n\nexport function isNodeSelection(value: unknown): value is NodeSelection {\n return value instanceof NodeSelection\n}\n","import { TextSelection } from '@tiptap/pm/state'\n\nexport function isTextSelection(value: unknown): value is TextSelection {\n return value instanceof TextSelection\n}\n","export function minMax(value = 0, min = 0, max = 0): number {\n return Math.min(Math.max(value, min), max)\n}\n","import type { EditorView } from '@tiptap/pm/view'\n\nimport { minMax } from '../utilities/minMax.js'\n\nexport function posToDOMRect(view: EditorView, from: number, to: number): DOMRect {\n const minPos = 0\n const maxPos = view.state.doc.content.size\n const resolvedFrom = minMax(from, minPos, maxPos)\n const resolvedEnd = minMax(to, minPos, maxPos)\n const start = view.coordsAtPos(resolvedFrom)\n const end = view.coordsAtPos(resolvedEnd, -1)\n const top = Math.min(start.top, end.top)\n const bottom = Math.max(start.bottom, end.bottom)\n const left = Math.min(start.left, end.left)\n const right = Math.max(start.right, end.right)\n const width = right - left\n const height = bottom - top\n const x = left\n const y = top\n const data = {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x,\n y,\n }\n\n return {\n ...data,\n toJSON: () => data,\n }\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Selection, TextSelection } from '@tiptap/pm/state'\n\nimport type { FocusPosition } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\nexport function resolveFocusPosition(doc: ProseMirrorNode, position: FocusPosition = null): Selection | null {\n if (!position) {\n return null\n }\n\n const selectionAtStart = Selection.atStart(doc)\n const selectionAtEnd = Selection.atEnd(doc)\n\n if (position === 'start' || position === true) {\n return selectionAtStart\n }\n\n if (position === 'end') {\n return selectionAtEnd\n }\n\n const minPos = selectionAtStart.from\n const maxPos = selectionAtEnd.to\n\n if (position === 'all') {\n return TextSelection.create(doc, minMax(0, minPos, maxPos), minMax(doc.content.size, minPos, maxPos))\n }\n\n return TextSelection.create(doc, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos))\n}\n","import type { Schema } from '@tiptap/pm/model'\n\nimport type { JSONContent } from '../types.js'\n\ntype RewriteUnknownContentOptions = {\n /**\n * If true, unknown nodes will be treated as paragraphs\n * @default true\n */\n fallbackToParagraph?: boolean\n}\n\ntype RewrittenContent = {\n /**\n * The original JSON content that was rewritten\n */\n original: JSONContent\n /**\n * The name of the node or mark that was unsupported\n */\n unsupported: string\n}[]\n\n/**\n * The actual implementation of the rewriteUnknownContent function\n */\nfunction rewriteUnknownContentInner({\n json,\n validMarks,\n validNodes,\n options,\n rewrittenContent = [],\n}: {\n json: JSONContent\n validMarks: Set<string>\n validNodes: Set<string>\n options?: RewriteUnknownContentOptions\n rewrittenContent?: RewrittenContent\n}): {\n /**\n * The cleaned JSON content\n */\n json: JSONContent | null\n /**\n * The array of nodes and marks that were rewritten\n */\n rewrittenContent: RewrittenContent\n} {\n if (json.marks && Array.isArray(json.marks)) {\n json.marks = json.marks.filter(mark => {\n const name = typeof mark === 'string' ? mark : mark.type\n\n if (validMarks.has(name)) {\n return true\n }\n\n rewrittenContent.push({\n original: JSON.parse(JSON.stringify(mark)),\n unsupported: name,\n })\n // Just ignore any unknown marks\n return false\n })\n }\n\n if (json.content && Array.isArray(json.content)) {\n json.content = json.content\n .map(\n value =>\n rewriteUnknownContentInner({\n json: value,\n validMarks,\n validNodes,\n options,\n rewrittenContent,\n }).json,\n )\n .filter(a => a !== null && a !== undefined)\n }\n\n if (json.type && !validNodes.has(json.type)) {\n rewrittenContent.push({\n original: JSON.parse(JSON.stringify(json)),\n unsupported: json.type,\n })\n\n if (json.content && Array.isArray(json.content) && options?.fallbackToParagraph !== false) {\n // Just treat it like a paragraph and hope for the best\n json.type = 'paragraph'\n\n return {\n json,\n rewrittenContent,\n }\n }\n\n // or just omit it entirely\n return {\n json: null,\n rewrittenContent,\n }\n }\n\n return { json, rewrittenContent }\n}\n\n/**\n * Rewrite unknown nodes and marks within JSON content\n * Allowing for user within the editor\n */\nexport function rewriteUnknownContent(\n /**\n * The JSON content to clean of unknown nodes and marks\n */\n json: JSONContent,\n /**\n * The schema to use for validation\n */\n schema: Schema,\n /**\n * Options for the cleaning process\n */\n options?: RewriteUnknownContentOptions,\n): {\n /**\n * The cleaned JSON content\n */\n json: JSONContent | null\n /**\n * The array of nodes and marks that were rewritten\n */\n rewrittenContent: {\n /**\n * The original JSON content that was rewritten\n */\n original: JSONContent\n /**\n * The name of the node or mark that was unsupported\n */\n unsupported: string\n }[]\n} {\n return rewriteUnknownContentInner({\n json,\n validNodes: new Set(Object.keys(schema.nodes)),\n validMarks: new Set(Object.keys(schema.marks)),\n options,\n })\n}\n","import type { Transaction } from '@tiptap/pm/state'\nimport { Selection } from '@tiptap/pm/state'\nimport { ReplaceAroundStep, ReplaceStep } from '@tiptap/pm/transform'\n\n// source: https://github.com/ProseMirror/prosemirror-state/blob/master/src/selection.js#L466\nexport function selectionToInsertionEnd(tr: Transaction, startLen: number, bias: number) {\n const last = tr.steps.length - 1\n\n if (last < startLen) {\n return\n }\n\n const step = tr.steps[last]\n\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {\n return\n }\n\n const map = tr.mapping.maps[last]\n let end = 0\n\n map.forEach((_from, _to, _newFrom, newTo) => {\n if (end === 0) {\n end = newTo\n }\n })\n\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias))\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\nimport type { EditorState, TextSelection } from '@tiptap/pm/state'\nimport { Plugin } from '@tiptap/pm/state'\n\nimport { CommandManager } from './CommandManager.js'\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport { getTextContentFromNodes } from './helpers/getTextContentFromNodes.js'\nimport type { CanCommands, ChainedCommands, ExtendedRegExpMatchArray, Range, SingleCommands } from './types.js'\nimport { isRegExp } from './utilities/isRegExp.js'\n\nexport type InputRuleMatch = {\n index: number\n text: string\n replaceWith?: string\n match?: RegExpMatchArray\n data?: Record<string, any>\n}\n\nexport type InputRuleFinder = RegExp | ((text: string) => InputRuleMatch | null)\n\nexport class InputRule {\n find: InputRuleFinder\n\n handler: (props: {\n state: EditorState\n range: Range\n match: ExtendedRegExpMatchArray\n commands: SingleCommands\n chain: () => ChainedCommands\n can: () => CanCommands\n }) => void | null\n\n constructor(config: {\n find: InputRuleFinder\n handler: (props: {\n state: EditorState\n range: Range\n match: ExtendedRegExpMatchArray\n commands: SingleCommands\n chain: () => ChainedCommands\n can: () => CanCommands\n }) => void | null\n }) {\n this.find = config.find\n this.handler = config.handler\n }\n}\n\nconst inputRuleMatcherHandler = (text: string, find: InputRuleFinder): ExtendedRegExpMatchArray | null => {\n if (isRegExp(find)) {\n return find.exec(text)\n }\n\n const inputRuleMatch = find(text)\n\n if (!inputRuleMatch) {\n return null\n }\n\n const result: ExtendedRegExpMatchArray = [inputRuleMatch.text]\n\n result.index = inputRuleMatch.index\n result.input = text\n result.data = inputRuleMatch.data\n\n if (inputRuleMatch.replaceWith) {\n if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {\n console.warn('[tiptap warn]: \"inputRuleMatch.replaceWith\" must be part of \"inputRuleMatch.text\".')\n }\n\n result.push(inputRuleMatch.replaceWith)\n }\n\n return result\n}\n\nfunction run(config: {\n editor: Editor\n from: number\n to: number\n text: string\n rules: InputRule[]\n plugin: Plugin\n}): boolean {\n const { editor, from, to, text, rules, plugin } = config\n const { view } = editor\n\n if (view.composing) {\n return false\n }\n\n const $from = view.state.doc.resolve(from)\n\n if (\n // check for code node\n $from.parent.type.spec.code ||\n // check for code mark\n !!($from.nodeBefore || $from.nodeAfter)?.marks.find(mark => mark.type.spec.code)\n ) {\n return false\n }\n\n let matched = false\n\n const textBefore = getTextContentFromNodes($from) + text\n\n rules.forEach(rule => {\n if (matched) {\n return\n }\n\n const match = inputRuleMatcherHandler(textBefore, rule.find)\n\n if (!match) {\n return\n }\n\n const tr = view.state.tr\n const state = createChainableState({\n state: view.state,\n transaction: tr,\n })\n const range = {\n from: from - (match[0].length - text.length),\n to,\n }\n\n const { commands, chain, can } = new CommandManager({\n editor,\n state,\n })\n\n const handler = rule.handler({\n state,\n range,\n match,\n commands,\n chain,\n can,\n })\n\n // stop if there are no changes\n if (handler === null || !tr.steps.length) {\n return\n }\n\n // store transform as meta data\n // so we can undo input rules within the `undoInputRules` command\n tr.setMeta(plugin, {\n transform: tr,\n from,\n to,\n text,\n })\n\n view.dispatch(tr)\n matched = true\n })\n\n return matched\n}\n\n/**\n * Create an input rules plugin. When enabled, it will cause text\n * input that matches any of the given rules to trigger the rule’s\n * action.\n */\nexport function inputRulesPlugin(props: { editor: Editor; rules: InputRule[] }): Plugin {\n const { editor, rules } = props\n const plugin = new Plugin({\n state: {\n init() {\n return null\n },\n apply(tr, prev, state) {\n const stored = tr.getMeta(plugin)\n\n if (stored) {\n return stored\n }\n\n // if InputRule is triggered by insertContent()\n const simulatedInputMeta = tr.getMeta('applyInputRules') as\n | undefined\n | {\n from: number\n text: string | ProseMirrorNode | Fragment\n }\n const isSimulatedInput = !!simulatedInputMeta\n\n if (isSimulatedInput) {\n setTimeout(() => {\n let { text } = simulatedInputMeta\n\n if (typeof text === 'string') {\n text = text as string\n } else {\n text = getHTMLFromFragment(Fragment.from(text), state.schema)\n }\n\n const { from } = simulatedInputMeta\n const to = from + text.length\n\n run({\n editor,\n from,\n to,\n text,\n rules,\n plugin,\n })\n })\n }\n\n return tr.selectionSet || tr.docChanged ? null : prev\n },\n },\n\n props: {\n handleTextInput(view, from, to, text) {\n return run({\n editor,\n from,\n to,\n text,\n rules,\n plugin,\n })\n },\n\n handleDOMEvents: {\n compositionend: view => {\n setTimeout(() => {\n const { $cursor } = view.state.selection as TextSelection\n\n if ($cursor) {\n run({\n editor,\n from: $cursor.pos,\n to: $cursor.pos,\n text: '',\n rules,\n plugin,\n })\n }\n })\n\n return false\n },\n },\n\n // add support for input rules to trigger on enter\n // this is useful for example for code blocks\n handleKeyDown(view, event) {\n if (event.key !== 'Enter') {\n return false\n }\n\n const { $cursor } = view.state.selection as TextSelection\n\n if ($cursor) {\n return run({\n editor,\n from: $cursor.pos,\n to: $cursor.pos,\n text: '\\n',\n rules,\n plugin,\n })\n }\n\n return false\n },\n },\n\n // @ts-ignore\n isInputRules: true,\n }) as Plugin\n\n return plugin\n}\n","// see: https://github.com/mesqueeb/is-what/blob/88d6e4ca92fb2baab6003c54e02eedf4e729e5ab/src/index.ts\n\nfunction getType(value: any): string {\n return Object.prototype.toString.call(value).slice(8, -1)\n}\n\nexport function isPlainObject(value: any): value is Record<string, any> {\n if (getType(value) !== 'Object') {\n return false\n }\n\n return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype\n}\n","import { isPlainObject } from './isPlainObject.js'\n\nexport function mergeDeep(target: Record<string, any>, source: Record<string, any>): Record<string, any> {\n const output = { ...target }\n\n if (isPlainObject(target) && isPlainObject(source)) {\n Object.keys(source).forEach(key => {\n if (isPlainObject(source[key]) && isPlainObject(target[key])) {\n output[key] = mergeDeep(target[key], source[key])\n } else {\n output[key] = source[key]\n }\n })\n }\n\n return output\n}\n","import type { Plugin } from '@tiptap/pm/state'\n\nimport type { Editor } from './Editor.js'\nimport { getExtensionField } from './helpers/getExtensionField.js'\nimport type { ExtensionConfig, MarkConfig, NodeConfig } from './index.js'\nimport type { InputRule } from './InputRule.js'\nimport type { Mark } from './Mark.js'\nimport type { Node } from './Node.js'\nimport type { PasteRule } from './PasteRule.js'\nimport type {\n AnyConfig,\n EditorEvents,\n Extensions,\n GlobalAttributes,\n KeyboardShortcutCommand,\n ParentConfig,\n RawCommands,\n} from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\nimport { mergeDeep } from './utilities/mergeDeep.js'\n\nexport interface ExtendableConfig<\n Options = any,\n Storage = any,\n Config extends\n | ExtensionConfig<Options, Storage>\n | NodeConfig<Options, Storage>\n | MarkConfig<Options, Storage>\n | ExtendableConfig<Options, Storage> = ExtendableConfig<Options, Storage, any, any>,\n PMType = any,\n> {\n /**\n * The extension name - this must be unique.\n * It will be used to identify the extension.\n *\n * @example 'myExtension'\n */\n name: string\n\n /**\n * The priority of your extension. The higher, the earlier it will be called\n * and will take precedence over other extensions with a lower priority.\n * @default 100\n * @example 101\n */\n priority?: number\n\n /**\n * This method will add options to this extension\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#settings\n * @example\n * addOptions() {\n * return {\n * myOption: 'foo',\n * myOtherOption: 10,\n * }\n */\n addOptions?: (this: { name: string; parent: ParentConfig<Config>['addOptions'] }) => Options\n\n /**\n * The default storage this extension can save data to.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#storage\n * @example\n * defaultStorage: {\n * prefetchedUsers: [],\n * loading: false,\n * }\n */\n addStorage?: (this: { name: string; options: Options; parent: ParentConfig<Config>['addStorage'] }) => Storage\n\n /**\n * This function adds globalAttributes to specific nodes.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#global-attributes\n * @example\n * addGlobalAttributes() {\n * return [\n * {\n // Extend the following extensions\n * types: [\n * 'heading',\n * 'paragraph',\n * ],\n * // … with those attributes\n * attributes: {\n * textAlign: {\n * default: 'left',\n * renderHTML: attributes => ({\n * style: `text-align: ${attributes.textAlign}`,\n * }),\n * parseHTML: element => element.style.textAlign || 'left',\n * },\n * },\n * },\n * ]\n * }\n */\n addGlobalAttributes?: (this: {\n name: string\n options: Options\n storage: Storage\n extensions: (Node | Mark)[]\n parent: ParentConfig<Config>['addGlobalAttributes']\n }) => GlobalAttributes\n\n /**\n * This function adds commands to the editor\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#commands\n * @example\n * addCommands() {\n * return {\n * myCommand: () => ({ chain }) => chain().setMark('type', 'foo').run(),\n * }\n * }\n */\n addCommands?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['addCommands']\n }) => Partial<RawCommands>\n\n /**\n * This function registers keyboard shortcuts.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#keyboard-shortcuts\n * @example\n * addKeyboardShortcuts() {\n * return {\n * 'Mod-l': () => this.editor.commands.toggleBulletList(),\n * }\n * },\n */\n addKeyboardShortcuts?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['addKeyboardShortcuts']\n }) => {\n [key: string]: KeyboardShortcutCommand\n }\n\n /**\n * This function adds input rules to the editor.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#input-rules\n * @example\n * addInputRules() {\n * return [\n * markInputRule({\n * find: inputRegex,\n * type: this.type,\n * }),\n * ]\n * },\n */\n addInputRules?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['addInputRules']\n }) => InputRule[]\n\n /**\n * This function adds paste rules to the editor.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#paste-rules\n * @example\n * addPasteRules() {\n * return [\n * markPasteRule({\n * find: pasteRegex,\n * type: this.type,\n * }),\n * ]\n * },\n */\n addPasteRules?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['addPasteRules']\n }) => PasteRule[]\n\n /**\n * This function adds Prosemirror plugins to the editor\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#prosemirror-plugins\n * @example\n * addProseMirrorPlugins() {\n * return [\n * customPlugin(),\n * ]\n * }\n */\n addProseMirrorPlugins?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['addProseMirrorPlugins']\n }) => Plugin[]\n\n /**\n * This function adds additional extensions to the editor. This is useful for\n * building extension kits.\n * @example\n * addExtensions() {\n * return [\n * BulletList,\n * OrderedList,\n * ListItem\n * ]\n * }\n */\n addExtensions?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<Config>['addExtensions']\n }) => Extensions\n\n /**\n * This function extends the schema of the node.\n * @example\n * extendNodeSchema() {\n * return {\n * group: 'inline',\n * selectable: false,\n * }\n * }\n */\n extendNodeSchema?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<Config>['extendNodeSchema']\n },\n extension: Node,\n ) => Record<string, any>)\n | null\n\n /**\n * This function extends the schema of the mark.\n * @example\n * extendMarkSchema() {\n * return {\n * group: 'inline',\n * selectable: false,\n * }\n * }\n */\n extendMarkSchema?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<Config>['extendMarkSchema']\n },\n extension: Mark,\n ) => Record<string, any>)\n | null\n\n /**\n * The editor is not ready yet.\n */\n onBeforeCreate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onBeforeCreate']\n },\n event: EditorEvents['beforeCreate'],\n ) => void)\n | null\n\n /**\n * The editor is ready.\n */\n onCreate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onCreate']\n },\n event: EditorEvents['create'],\n ) => void)\n | null\n\n /**\n * The content has changed.\n */\n onUpdate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onUpdate']\n },\n event: EditorEvents['update'],\n ) => void)\n | null\n\n /**\n * The selection has changed.\n */\n onSelectionUpdate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onSelectionUpdate']\n },\n event: EditorEvents['selectionUpdate'],\n ) => void)\n | null\n\n /**\n * The editor state has changed.\n */\n onTransaction?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onTransaction']\n },\n event: EditorEvents['transaction'],\n ) => void)\n | null\n\n /**\n * The editor is focused.\n */\n onFocus?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onFocus']\n },\n event: EditorEvents['focus'],\n ) => void)\n | null\n\n /**\n * The editor isn’t focused anymore.\n */\n onBlur?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onBlur']\n },\n event: EditorEvents['blur'],\n ) => void)\n | null\n\n /**\n * The editor is destroyed.\n */\n onDestroy?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig<Config>['onDestroy']\n },\n event: EditorEvents['destroy'],\n ) => void)\n | null\n}\n\nexport class Extendable<\n Options = any,\n Storage = any,\n Config = ExtensionConfig<Options, Storage> | NodeConfig<Options, Storage> | MarkConfig<Options, Storage>,\n> {\n type = 'extendable'\n parent: Extendable | null = null\n\n child: Extendable | null = null\n\n name = ''\n\n config: Config = {\n name: this.name,\n } as Config\n\n constructor(config: Partial<Config> = {}) {\n this.config = {\n ...this.config,\n ...config,\n }\n\n this.name = (this.config as any).name\n }\n\n get options(): Options {\n return {\n ...(callOrReturn(\n getExtensionField<AnyConfig['addOptions']>(this as any, 'addOptions', {\n name: this.name,\n }),\n ) || {}),\n }\n }\n\n get storage(): Readonly<Storage> {\n return {\n ...(callOrReturn(\n getExtensionField<AnyConfig['addStorage']>(this as any, 'addStorage', {\n name: this.name,\n options: this.options,\n }),\n ) || {}),\n }\n }\n\n configure(options: Partial<Options> = {}) {\n const extension = this.extend<Options, Storage, Config>({\n ...this.config,\n addOptions: () => {\n return mergeDeep(this.options as Record<string, any>, options) as Options\n },\n })\n\n extension.name = this.name\n extension.parent = this.parent\n\n return extension\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig =\n | ExtensionConfig<ExtendedOptions, ExtendedStorage>\n | NodeConfig<ExtendedOptions, ExtendedStorage>\n | MarkConfig<ExtendedOptions, ExtendedStorage>,\n >(extendedConfig: Partial<ExtendedConfig> = {}): Extendable<ExtendedOptions, ExtendedStorage> {\n const extension = new (this.constructor as any)({ ...this.config, ...extendedConfig })\n\n extension.parent = this\n this.child = extension\n extension.name = 'name' in extendedConfig ? extendedConfig.name : extension.parent.name\n\n return extension\n }\n}\n","import type { DOMOutputSpec, Mark as ProseMirrorMark, MarkSpec, MarkType } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { ExtendableConfig } from './Extendable.js'\nimport { Extendable } from './Extendable.js'\nimport type { Attributes, MarkViewRenderer, ParentConfig } from './types.js'\n\nexport interface MarkConfig<Options = any, Storage = any>\n extends ExtendableConfig<Options, Storage, MarkConfig<Options, Storage>, MarkType> {\n /**\n * Mark View\n */\n addMarkView?:\n | ((this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: MarkType\n parent: ParentConfig<MarkConfig<Options, Storage>>['addMarkView']\n }) => MarkViewRenderer)\n | null\n\n /**\n * Keep mark after split node\n */\n keepOnSplit?: boolean | (() => boolean)\n\n /**\n * Inclusive\n */\n inclusive?:\n | MarkSpec['inclusive']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['inclusive']\n editor?: Editor\n }) => MarkSpec['inclusive'])\n\n /**\n * Excludes\n */\n excludes?:\n | MarkSpec['excludes']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['excludes']\n editor?: Editor\n }) => MarkSpec['excludes'])\n\n /**\n * Marks this Mark as exitable\n */\n exitable?: boolean | (() => boolean)\n\n /**\n * Group\n */\n group?:\n | MarkSpec['group']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['group']\n editor?: Editor\n }) => MarkSpec['group'])\n\n /**\n * Spanning\n */\n spanning?:\n | MarkSpec['spanning']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['spanning']\n editor?: Editor\n }) => MarkSpec['spanning'])\n\n /**\n * Code\n */\n code?:\n | boolean\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['code']\n editor?: Editor\n }) => boolean)\n\n /**\n * Parse HTML\n */\n parseHTML?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['parseHTML']\n editor?: Editor\n }) => MarkSpec['parseDOM']\n\n /**\n * Render HTML\n */\n renderHTML?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['renderHTML']\n editor?: Editor\n },\n props: {\n mark: ProseMirrorMark\n HTMLAttributes: Record<string, any>\n },\n ) => DOMOutputSpec)\n | null\n\n /**\n * Attributes\n */\n addAttributes?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<MarkConfig<Options, Storage>>['addAttributes']\n editor?: Editor\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n }) => Attributes | {}\n}\n\n/**\n * The Mark class is used to create custom mark extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Mark<Options = any, Storage = any> extends Extendable<Options, Storage, MarkConfig<Options, Storage>> {\n type = 'mark'\n\n /**\n * Create a new Mark instance\n * @param config - Mark configuration object or a function that returns a configuration object\n */\n static create<O = any, S = any>(config: Partial<MarkConfig<O, S>> | (() => Partial<MarkConfig<O, S>>) = {}) {\n // If the config is a function, execute it to get the configuration object\n const resolvedConfig = typeof config === 'function' ? config() : config\n return new Mark<O, S>(resolvedConfig)\n }\n\n static handleExit({ editor, mark }: { editor: Editor; mark: Mark }) {\n const { tr } = editor.state\n const currentPos = editor.state.selection.$from\n const isAtEnd = currentPos.pos === currentPos.end()\n\n if (isAtEnd) {\n const currentMarks = currentPos.marks()\n const isInMark = !!currentMarks.find(m => m?.type.name === mark.name)\n\n if (!isInMark) {\n return false\n }\n\n const removeMark = currentMarks.find(m => m?.type.name === mark.name)\n\n if (removeMark) {\n tr.removeStoredMark(removeMark)\n }\n tr.insertText(' ', currentPos.pos)\n\n editor.view.dispatch(tr)\n\n return true\n }\n\n return false\n }\n\n configure(options?: Partial<Options>) {\n return super.configure(options) as Mark<Options, Storage>\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig = MarkConfig<ExtendedOptions, ExtendedStorage>,\n >(extendedConfig?: Partial<ExtendedConfig> | (() => Partial<ExtendedConfig>)) {\n // If the extended config is a function, execute it to get the configuration object\n const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n return super.extend(resolvedConfig) as Mark<ExtendedOptions, ExtendedStorage>\n }\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\nimport { Plugin } from '@tiptap/pm/state'\n\nimport { CommandManager } from './CommandManager.js'\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport type { CanCommands, ChainedCommands, ExtendedRegExpMatchArray, Range, SingleCommands } from './types.js'\nimport { isNumber } from './utilities/isNumber.js'\nimport { isRegExp } from './utilities/isRegExp.js'\n\nexport type PasteRuleMatch = {\n index: number\n text: string\n replaceWith?: string\n match?: RegExpMatchArray\n data?: Record<string, any>\n}\n\nexport type PasteRuleFinder =\n | RegExp\n | ((text: string, event?: ClipboardEvent | null) => PasteRuleMatch[] | null | undefined)\n\n/**\n * Paste rules are used to react to pasted content.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport class PasteRule {\n find: PasteRuleFinder\n\n handler: (props: {\n state: EditorState\n range: Range\n match: ExtendedRegExpMatchArray\n commands: SingleCommands\n chain: () => ChainedCommands\n can: () => CanCommands\n pasteEvent: ClipboardEvent | null\n dropEvent: DragEvent | null\n }) => void | null\n\n constructor(config: {\n find: PasteRuleFinder\n handler: (props: {\n can: () => CanCommands\n chain: () => ChainedCommands\n commands: SingleCommands\n dropEvent: DragEvent | null\n match: ExtendedRegExpMatchArray\n pasteEvent: ClipboardEvent | null\n range: Range\n state: EditorState\n }) => void | null\n }) {\n this.find = config.find\n this.handler = config.handler\n }\n}\n\nconst pasteRuleMatcherHandler = (\n text: string,\n find: PasteRuleFinder,\n event?: ClipboardEvent | null,\n): ExtendedRegExpMatchArray[] => {\n if (isRegExp(find)) {\n return [...text.matchAll(find)]\n }\n\n const matches = find(text, event)\n\n if (!matches) {\n return []\n }\n\n return matches.map(pasteRuleMatch => {\n const result: ExtendedRegExpMatchArray = [pasteRuleMatch.text]\n\n result.index = pasteRuleMatch.index\n result.input = text\n result.data = pasteRuleMatch.data\n\n if (pasteRuleMatch.replaceWith) {\n if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) {\n console.warn('[tiptap warn]: \"pasteRuleMatch.replaceWith\" must be part of \"pasteRuleMatch.text\".')\n }\n\n result.push(pasteRuleMatch.replaceWith)\n }\n\n return result\n })\n}\n\nfunction run(config: {\n editor: Editor\n state: EditorState\n from: number\n to: number\n rule: PasteRule\n pasteEvent: ClipboardEvent | null\n dropEvent: DragEvent | null\n}): boolean {\n const { editor, state, from, to, rule, pasteEvent, dropEvent } = config\n\n const { commands, chain, can } = new CommandManager({\n editor,\n state,\n })\n\n const handlers: (void | null)[] = []\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isTextblock || node.type.spec.code) {\n return\n }\n\n const resolvedFrom = Math.max(from, pos)\n const resolvedTo = Math.min(to, pos + node.content.size)\n const textToMatch = node.textBetween(resolvedFrom - pos, resolvedTo - pos, undefined, '\\ufffc')\n\n const matches = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent)\n\n matches.forEach(match => {\n if (match.index === undefined) {\n return\n }\n\n const start = resolvedFrom + match.index + 1\n const end = start + match[0].length\n const range = {\n from: state.tr.mapping.map(start),\n to: state.tr.mapping.map(end),\n }\n\n const handler = rule.handler({\n state,\n range,\n match,\n commands,\n chain,\n can,\n pasteEvent,\n dropEvent,\n })\n\n handlers.push(handler)\n })\n })\n\n const success = handlers.every(handler => handler !== null)\n\n return success\n}\n\n// When dragging across editors, must get another editor instance to delete selection content.\nlet tiptapDragFromOtherEditor: Editor | null = null\n\nconst createClipboardPasteEvent = (text: string) => {\n const event = new ClipboardEvent('paste', {\n clipboardData: new DataTransfer(),\n })\n\n event.clipboardData?.setData('text/html', text)\n\n return event\n}\n\n/**\n * Create an paste rules plugin. When enabled, it will cause pasted\n * text that matches any of the given rules to trigger the rule’s\n * action.\n */\nexport function pasteRulesPlugin(props: { editor: Editor; rules: PasteRule[] }): Plugin[] {\n const { editor, rules } = props\n let dragSourceElement: Element | null = null\n let isPastedFromProseMirror = false\n let isDroppedFromProseMirror = false\n let pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null\n let dropEvent: DragEvent | null\n\n try {\n dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null\n } catch {\n dropEvent = null\n }\n\n const processEvent = ({\n state,\n from,\n to,\n rule,\n pasteEvt,\n }: {\n state: EditorState\n from: number\n to: { b: number }\n rule: PasteRule\n pasteEvt: ClipboardEvent | null\n }) => {\n const tr = state.tr\n const chainableState = createChainableState({\n state,\n transaction: tr,\n })\n\n const handler = run({\n editor,\n state: chainableState,\n from: Math.max(from - 1, 0),\n to: to.b - 1,\n rule,\n pasteEvent: pasteEvt,\n dropEvent,\n })\n\n if (!handler || !tr.steps.length) {\n return\n }\n\n try {\n dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null\n } catch {\n dropEvent = null\n }\n pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null\n\n return tr\n }\n\n const plugins = rules.map(rule => {\n return new Plugin({\n // we register a global drag handler to track the current drag source element\n view(view) {\n const handleDragstart = (event: DragEvent) => {\n dragSourceElement = view.dom.parentElement?.contains(event.target as Element) ? view.dom.parentElement : null\n\n if (dragSourceElement) {\n tiptapDragFromOtherEditor = editor\n }\n }\n\n const handleDragend = () => {\n if (tiptapDragFromOtherEditor) {\n tiptapDragFromOtherEditor = null\n }\n }\n\n window.addEventListener('dragstart', handleDragstart)\n window.addEventListener('dragend', handleDragend)\n\n return {\n destroy() {\n window.removeEventListener('dragstart', handleDragstart)\n window.removeEventListener('dragend', handleDragend)\n },\n }\n },\n\n props: {\n handleDOMEvents: {\n drop: (view, event: Event) => {\n isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement\n dropEvent = event as DragEvent\n\n if (!isDroppedFromProseMirror) {\n const dragFromOtherEditor = tiptapDragFromOtherEditor\n\n if (dragFromOtherEditor?.isEditable) {\n // setTimeout to avoid the wrong content after drop, timeout arg can't be empty or 0\n setTimeout(() => {\n const selection = dragFromOtherEditor.state.selection\n\n if (selection) {\n dragFromOtherEditor.commands.deleteRange({ from: selection.from, to: selection.to })\n }\n }, 10)\n }\n }\n return false\n },\n\n paste: (_view, event: Event) => {\n const html = (event as ClipboardEvent).clipboardData?.getData('text/html')\n\n pasteEvent = event as ClipboardEvent\n\n isPastedFromProseMirror = !!html?.includes('data-pm-slice')\n\n return false\n },\n },\n },\n\n appendTransaction: (transactions, oldState, state) => {\n const transaction = transactions[0]\n const isPaste = transaction.getMeta('uiEvent') === 'paste' && !isPastedFromProseMirror\n const isDrop = transaction.getMeta('uiEvent') === 'drop' && !isDroppedFromProseMirror\n\n // if PasteRule is triggered by insertContent()\n const simulatedPasteMeta = transaction.getMeta('applyPasteRules') as\n | undefined\n | { from: number; text: string | ProseMirrorNode | Fragment }\n const isSimulatedPaste = !!simulatedPasteMeta\n\n if (!isPaste && !isDrop && !isSimulatedPaste) {\n return\n }\n\n // Handle simulated paste\n if (isSimulatedPaste) {\n let { text } = simulatedPasteMeta\n\n if (typeof text === 'string') {\n text = text as string\n } else {\n text = getHTMLFromFragment(Fragment.from(text), state.schema)\n }\n\n const { from } = simulatedPasteMeta\n const to = from + text.length\n\n const pasteEvt = createClipboardPasteEvent(text)\n\n return processEvent({\n rule,\n state,\n from,\n to: { b: to },\n pasteEvt,\n })\n }\n\n // handle actual paste/drop\n const from = oldState.doc.content.findDiffStart(state.doc.content)\n const to = oldState.doc.content.findDiffEnd(state.doc.content)\n\n // stop if there is no changed range\n if (!isNumber(from) || !to || from === to.b) {\n return\n }\n\n return processEvent({\n rule,\n state,\n from,\n to,\n pasteEvt: pasteEvent,\n })\n },\n })\n })\n\n return plugins\n}\n","export function isNumber(value: any): value is number {\n return typeof value === 'number'\n}\n","export { ClipboardTextSerializer } from './clipboardTextSerializer.js'\nexport { Commands } from './commands.js'\nexport { Delete } from './delete.js'\nexport { Drop } from './drop.js'\nexport { Editable } from './editable.js'\nexport { FocusEvents, focusEventsPluginKey } from './focusEvents.js'\nexport { Keymap } from './keymap.js'\nexport { Paste } from './paste.js'\nexport { Tabindex } from './tabindex.js'\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\nimport { getTextBetween } from '../helpers/getTextBetween.js'\nimport { getTextSerializersFromSchema } from '../helpers/getTextSerializersFromSchema.js'\n\nexport type ClipboardTextSerializerOptions = {\n blockSeparator?: string\n}\n\nexport const ClipboardTextSerializer = Extension.create<ClipboardTextSerializerOptions>({\n name: 'clipboardTextSerializer',\n\n addOptions() {\n return {\n blockSeparator: undefined,\n }\n },\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('clipboardTextSerializer'),\n props: {\n clipboardTextSerializer: () => {\n const { editor } = this\n const { state, schema } = editor\n const { doc, selection } = state\n const { ranges } = selection\n const from = Math.min(...ranges.map(range => range.$from.pos))\n const to = Math.max(...ranges.map(range => range.$to.pos))\n const textSerializers = getTextSerializersFromSchema(schema)\n const range = { from, to }\n\n return getTextBetween(doc, range, {\n ...(this.options.blockSeparator !== undefined ? { blockSeparator: this.options.blockSeparator } : {}),\n textSerializers,\n })\n },\n },\n }),\n ]\n },\n})\n","import { type ExtendableConfig, Extendable } from './Extendable.js'\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface ExtensionConfig<Options = any, Storage = any>\n extends ExtendableConfig<Options, Storage, ExtensionConfig<Options, Storage>, null> {}\n\n/**\n * The Extension class is the base class for all extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Extension<Options = any, Storage = any> extends Extendable<\n Options,\n Storage,\n ExtensionConfig<Options, Storage>\n> {\n type = 'extension'\n\n /**\n * Create a new Extension instance\n * @param config - Extension configuration object or a function that returns a configuration object\n */\n static create<O = any, S = any>(\n config: Partial<ExtensionConfig<O, S>> | (() => Partial<ExtensionConfig<O, S>>) = {},\n ) {\n // If the config is a function, execute it to get the configuration object\n const resolvedConfig = typeof config === 'function' ? config() : config\n return new Extension<O, S>(resolvedConfig)\n }\n\n configure(options?: Partial<Options>) {\n return super.configure(options) as Extension<Options, Storage>\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig = ExtensionConfig<ExtendedOptions, ExtendedStorage>,\n >(extendedConfig?: Partial<ExtendedConfig> | (() => Partial<ExtendedConfig>)) {\n // If the extended config is a function, execute it to get the configuration object\n const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n return super.extend(resolvedConfig) as Extension<ExtendedOptions, ExtendedStorage>\n }\n}\n","export * from './blur.js'\nexport * from './clearContent.js'\nexport * from './clearNodes.js'\nexport * from './command.js'\nexport * from './createParagraphNear.js'\nexport * from './cut.js'\nexport * from './deleteCurrentNode.js'\nexport * from './deleteNode.js'\nexport * from './deleteRange.js'\nexport * from './deleteSelection.js'\nexport * from './enter.js'\nexport * from './exitCode.js'\nexport * from './extendMarkRange.js'\nexport * from './first.js'\nexport * from './focus.js'\nexport * from './forEach.js'\nexport * from './insertContent.js'\nexport * from './insertContentAt.js'\nexport * from './join.js'\nexport * from './joinItemBackward.js'\nexport * from './joinItemForward.js'\nexport * from './joinTextblockBackward.js'\nexport * from './joinTextblockForward.js'\nexport * from './keyboardShortcut.js'\nexport * from './lift.js'\nexport * from './liftEmptyBlock.js'\nexport * from './liftListItem.js'\nexport * from './newlineInCode.js'\nexport * from './resetAttributes.js'\nexport * from './scrollIntoView.js'\nexport * from './selectAll.js'\nexport * from './selectNodeBackward.js'\nexport * from './selectNodeForward.js'\nexport * from './selectParentNode.js'\nexport * from './selectTextblockEnd.js'\nexport * from './selectTextblockStart.js'\nexport * from './setContent.js'\nexport * from './setMark.js'\nexport * from './setMeta.js'\nexport * from './setNode.js'\nexport * from './setNodeSelection.js'\nexport * from './setTextSelection.js'\nexport * from './sinkListItem.js'\nexport * from './splitBlock.js'\nexport * from './splitListItem.js'\nexport * from './toggleList.js'\nexport * from './toggleMark.js'\nexport * from './toggleNode.js'\nexport * from './toggleWrap.js'\nexport * from './undoInputRule.js'\nexport * from './unsetAllMarks.js'\nexport * from './unsetMark.js'\nexport * from './updateAttributes.js'\nexport * from './wrapIn.js'\nexport * from './wrapInList.js'\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n blur: {\n /**\n * Removes focus from the editor.\n * @example editor.commands.blur()\n */\n blur: () => ReturnType\n }\n }\n}\n\nexport const blur: RawCommands['blur'] =\n () =>\n ({ editor, view }) => {\n requestAnimationFrame(() => {\n if (!editor.isDestroyed) {\n ;(view.dom as HTMLElement).blur()\n\n // Browsers should remove the caret on blur but safari does not.\n // See: https://github.com/ueberdosis/tiptap/issues/2405\n window?.getSelection()?.removeAllRanges()\n }\n })\n\n return true\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n clearContent: {\n /**\n * Clear the whole document.\n * @example editor.commands.clearContent()\n */\n clearContent: (\n /**\n * Whether to emit an update event.\n * @default true\n */\n emitUpdate?: boolean,\n ) => ReturnType\n }\n }\n}\n\nexport const clearContent: RawCommands['clearContent'] =\n (emitUpdate = true) =>\n ({ commands }) => {\n return commands.setContent('', { emitUpdate })\n }\n","import { liftTarget } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n clearNodes: {\n /**\n * Normalize nodes to a simple paragraph.\n * @example editor.commands.clearNodes()\n */\n clearNodes: () => ReturnType\n }\n }\n}\n\nexport const clearNodes: RawCommands['clearNodes'] =\n () =>\n ({ state, tr, dispatch }) => {\n const { selection } = tr\n const { ranges } = selection\n\n if (!dispatch) {\n return true\n }\n\n ranges.forEach(({ $from, $to }) => {\n state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (node.type.isText) {\n return\n }\n\n const { doc, mapping } = tr\n const $mappedFrom = doc.resolve(mapping.map(pos))\n const $mappedTo = doc.resolve(mapping.map(pos + node.nodeSize))\n const nodeRange = $mappedFrom.blockRange($mappedTo)\n\n if (!nodeRange) {\n return\n }\n\n const targetLiftDepth = liftTarget(nodeRange)\n\n if (node.type.isTextblock) {\n const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index())\n\n tr.setNodeMarkup(nodeRange.start, defaultType)\n }\n\n if (targetLiftDepth || targetLiftDepth === 0) {\n tr.lift(nodeRange, targetLiftDepth)\n }\n })\n })\n\n return true\n }\n","import type { Command, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n command: {\n /**\n * Define a command inline.\n * @param fn The command function.\n * @example\n * editor.commands.command(({ tr, state }) => {\n * ...\n * return true\n * })\n */\n command: (fn: (props: Parameters<Command>[0]) => boolean) => ReturnType\n }\n }\n}\n\nexport const command: RawCommands['command'] = fn => props => {\n return fn(props)\n}\n","import { createParagraphNear as originalCreateParagraphNear } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n createParagraphNear: {\n /**\n * Create a paragraph nearby.\n * @example editor.commands.createParagraphNear()\n */\n createParagraphNear: () => ReturnType\n }\n }\n}\n\nexport const createParagraphNear: RawCommands['createParagraphNear'] =\n () =>\n ({ state, dispatch }) => {\n return originalCreateParagraphNear(state, dispatch)\n }\n","import { TextSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n cut: {\n /**\n * Cuts content from a range and inserts it at a given position.\n * @param range The range to cut.\n * @param range.from The start position of the range.\n * @param range.to The end position of the range.\n * @param targetPos The position to insert the content at.\n * @example editor.commands.cut({ from: 1, to: 3 }, 5)\n */\n cut: ({ from, to }: { from: number; to: number }, targetPos: number) => ReturnType\n }\n }\n}\n\nexport const cut: RawCommands['cut'] =\n (originRange, targetPos) =>\n ({ editor, tr }) => {\n const { state } = editor\n\n const contentSlice = state.doc.slice(originRange.from, originRange.to)\n\n tr.deleteRange(originRange.from, originRange.to)\n const newPos = tr.mapping.map(targetPos)\n\n tr.insert(newPos, contentSlice.content)\n\n tr.setSelection(new TextSelection(tr.doc.resolve(Math.max(newPos - 1, 0))))\n\n return true\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n deleteCurrentNode: {\n /**\n * Delete the node that currently has the selection anchor.\n * @example editor.commands.deleteCurrentNode()\n */\n deleteCurrentNode: () => ReturnType\n }\n }\n}\n\nexport const deleteCurrentNode: RawCommands['deleteCurrentNode'] =\n () =>\n ({ tr, dispatch }) => {\n const { selection } = tr\n const currentNode = selection.$anchor.node()\n\n // if there is content inside the current node, break out of this command\n if (currentNode.content.size > 0) {\n return false\n }\n\n const $pos = tr.selection.$anchor\n\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth)\n\n if (node.type === currentNode.type) {\n if (dispatch) {\n const from = $pos.before(depth)\n const to = $pos.after(depth)\n\n tr.delete(from, to).scrollIntoView()\n }\n\n return true\n }\n }\n\n return false\n }\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n deleteNode: {\n /**\n * Delete a node with a given type or name.\n * @param typeOrName The type or name of the node.\n * @example editor.commands.deleteNode('paragraph')\n */\n deleteNode: (typeOrName: string | NodeType) => ReturnType\n }\n }\n}\n\nexport const deleteNode: RawCommands['deleteNode'] =\n typeOrName =>\n ({ tr, state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n const $pos = tr.selection.$anchor\n\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth)\n\n if (node.type === type) {\n if (dispatch) {\n const from = $pos.before(depth)\n const to = $pos.after(depth)\n\n tr.delete(from, to).scrollIntoView()\n }\n\n return true\n }\n }\n\n return false\n }\n","import type { Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n deleteRange: {\n /**\n * Delete a given range.\n * @param range The range to delete.\n * @example editor.commands.deleteRange({ from: 1, to: 3 })\n */\n deleteRange: (range: Range) => ReturnType\n }\n }\n}\n\nexport const deleteRange: RawCommands['deleteRange'] =\n range =>\n ({ tr, dispatch }) => {\n const { from, to } = range\n\n if (dispatch) {\n tr.delete(from, to)\n }\n\n return true\n }\n","import { deleteSelection as originalDeleteSelection } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n deleteSelection: {\n /**\n * Delete the selection, if there is one.\n * @example editor.commands.deleteSelection()\n */\n deleteSelection: () => ReturnType\n }\n }\n}\n\nexport const deleteSelection: RawCommands['deleteSelection'] =\n () =>\n ({ state, dispatch }) => {\n return originalDeleteSelection(state, dispatch)\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n enter: {\n /**\n * Trigger enter.\n * @example editor.commands.enter()\n */\n enter: () => ReturnType\n }\n }\n}\n\nexport const enter: RawCommands['enter'] =\n () =>\n ({ commands }) => {\n return commands.keyboardShortcut('Enter')\n }\n","import { exitCode as originalExitCode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n exitCode: {\n /**\n * Exit from a code block.\n * @example editor.commands.exitCode()\n */\n exitCode: () => ReturnType\n }\n }\n}\n\nexport const exitCode: RawCommands['exitCode'] =\n () =>\n ({ state, dispatch }) => {\n return originalExitCode(state, dispatch)\n }\n","import type { MarkType } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\n\nimport { getMarkRange } from '../helpers/getMarkRange.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n extendMarkRange: {\n /**\n * Extends the text selection to the current mark by type or name.\n * @param typeOrName The type or name of the mark.\n * @param attributes The attributes of the mark.\n * @example editor.commands.extendMarkRange('bold')\n * @example editor.commands.extendMarkRange('mention', { userId: \"1\" })\n */\n extendMarkRange: (\n /**\n * The type or name of the mark.\n */\n typeOrName: string | MarkType,\n\n /**\n * The attributes of the mark.\n */\n attributes?: Record<string, any>,\n ) => ReturnType\n }\n }\n}\n\nexport const extendMarkRange: RawCommands['extendMarkRange'] =\n (typeOrName, attributes = {}) =>\n ({ tr, state, dispatch }) => {\n const type = getMarkType(typeOrName, state.schema)\n const { doc, selection } = tr\n const { $from, from, to } = selection\n\n if (dispatch) {\n const range = getMarkRange($from, type, attributes)\n\n if (range && range.from <= from && range.to >= to) {\n const newSelection = TextSelection.create(doc, range.from, range.to)\n\n tr.setSelection(newSelection)\n }\n }\n\n return true\n }\n","import type { Command, CommandProps, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n first: {\n /**\n * Runs one command after the other and stops at the first which returns true.\n * @param commands The commands to run.\n * @example editor.commands.first([command1, command2])\n */\n first: (commands: Command[] | ((props: CommandProps) => Command[])) => ReturnType\n }\n }\n}\n\nexport const first: RawCommands['first'] = commands => props => {\n const items = typeof commands === 'function' ? commands(props) : commands\n\n for (let i = 0; i < items.length; i += 1) {\n if (items[i](props)) {\n return true\n }\n }\n\n return false\n}\n","export function isAndroid(): boolean {\n return navigator.platform === 'Android' || /android/i.test(navigator.userAgent)\n}\n","export function isiOS(): boolean {\n return (\n ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator.platform) ||\n // iPad on iOS 13 detection\n (navigator.userAgent.includes('Mac') && 'ontouchend' in document)\n )\n}\n","import { isTextSelection } from '../helpers/isTextSelection.js'\nimport { resolveFocusPosition } from '../helpers/resolveFocusPosition.js'\nimport type { FocusPosition, RawCommands } from '../types.js'\nimport { isAndroid } from '../utilities/isAndroid.js'\nimport { isiOS } from '../utilities/isiOS.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n focus: {\n /**\n * Focus the editor at the given position.\n * @param position The position to focus at.\n * @param options.scrollIntoView Scroll the focused position into view after focusing\n * @example editor.commands.focus()\n * @example editor.commands.focus(32, { scrollIntoView: false })\n */\n focus: (\n /**\n * The position to focus at.\n */\n position?: FocusPosition,\n\n /**\n * Optional options\n * @default { scrollIntoView: true }\n */\n options?: {\n scrollIntoView?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const focus: RawCommands['focus'] =\n (position = null, options = {}) =>\n ({ editor, view, tr, dispatch }) => {\n options = {\n scrollIntoView: true,\n ...options,\n }\n\n const delayedFocus = () => {\n // focus within `requestAnimationFrame` breaks focus on iOS and Android\n // so we have to call this\n if (isiOS() || isAndroid()) {\n ;(view.dom as HTMLElement).focus()\n }\n\n // For React we have to focus asynchronously. Otherwise wild things happen.\n // see: https://github.com/ueberdosis/tiptap/issues/1520\n requestAnimationFrame(() => {\n if (!editor.isDestroyed) {\n view.focus()\n\n if (options?.scrollIntoView) {\n editor.commands.scrollIntoView()\n }\n }\n })\n }\n\n if ((view.hasFocus() && position === null) || position === false) {\n return true\n }\n\n // we don’t try to resolve a NodeSelection or CellSelection\n if (dispatch && position === null && !isTextSelection(editor.state.selection)) {\n delayedFocus()\n return true\n }\n\n // pass through tr.doc instead of editor.state.doc\n // since transactions could change the editors state before this command has been run\n const selection = resolveFocusPosition(tr.doc, position) || editor.state.selection\n const isSameSelection = editor.state.selection.eq(selection)\n\n if (dispatch) {\n if (!isSameSelection) {\n tr.setSelection(selection)\n }\n\n // `tr.setSelection` resets the stored marks\n // so we’ll restore them if the selection is the same as before\n if (isSameSelection && tr.storedMarks) {\n tr.setStoredMarks(tr.storedMarks)\n }\n\n delayedFocus()\n }\n\n return true\n }\n","import type { CommandProps, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n forEach: {\n /**\n * Loop through an array of items.\n */\n forEach: <T>(\n items: T[],\n fn: (\n item: T,\n props: CommandProps & {\n index: number\n },\n ) => boolean,\n ) => ReturnType\n }\n }\n}\n\nexport const forEach: RawCommands['forEach'] = (items, fn) => props => {\n return items.every((item, index) => fn(item, { ...props, index }))\n}\n","import type { Fragment, Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\n\nimport type { Content, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n insertContent: {\n /**\n * Insert a node or string of HTML at the current position.\n * @example editor.commands.insertContent('<h1>Example</h1>')\n * @example editor.commands.insertContent('<h1>Example</h1>', { updateSelection: false })\n */\n insertContent: (\n /**\n * The ProseMirror content to insert.\n */\n value: Content | ProseMirrorNode | Fragment,\n\n /**\n * Optional options\n */\n options?: {\n /**\n * Options for parsing the content.\n */\n parseOptions?: ParseOptions\n\n /**\n * Whether to update the selection after inserting the content.\n */\n updateSelection?: boolean\n applyInputRules?: boolean\n applyPasteRules?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const insertContent: RawCommands['insertContent'] =\n (value, options) =>\n ({ tr, commands }) => {\n return commands.insertContentAt({ from: tr.selection.from, to: tr.selection.to }, value, options)\n }\n","import type { Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\n\nimport { createNodeFromContent } from '../helpers/createNodeFromContent.js'\nimport { selectionToInsertionEnd } from '../helpers/selectionToInsertionEnd.js'\nimport type { Content, Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n insertContentAt: {\n /**\n * Insert a node or string of HTML at a specific position.\n * @example editor.commands.insertContentAt(0, '<h1>Example</h1>')\n */\n insertContentAt: (\n /**\n * The position to insert the content at.\n */\n position: number | Range,\n\n /**\n * The ProseMirror content to insert.\n */\n value: Content | ProseMirrorNode | Fragment,\n\n /**\n * Optional options\n */\n options?: {\n /**\n * Options for parsing the content.\n */\n parseOptions?: ParseOptions\n\n /**\n * Whether to update the selection after inserting the content.\n */\n updateSelection?: boolean\n\n /**\n * Whether to apply input rules after inserting the content.\n */\n applyInputRules?: boolean\n\n /**\n * Whether to apply paste rules after inserting the content.\n */\n applyPasteRules?: boolean\n\n /**\n * Whether to throw an error if the content is invalid.\n */\n errorOnInvalidContent?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nconst isFragment = (nodeOrFragment: ProseMirrorNode | Fragment): nodeOrFragment is Fragment => {\n return !('type' in nodeOrFragment)\n}\n\nexport const insertContentAt: RawCommands['insertContentAt'] =\n (position, value, options) =>\n ({ tr, dispatch, editor }) => {\n if (dispatch) {\n options = {\n parseOptions: editor.options.parseOptions,\n updateSelection: true,\n applyInputRules: false,\n applyPasteRules: false,\n ...options,\n }\n\n let content: Fragment | ProseMirrorNode\n const { selection } = editor.state\n\n const emitContentError = (error: Error) => {\n editor.emit('contentError', {\n editor,\n error,\n disableCollaboration: () => {\n if (\n 'collaboration' in editor.storage &&\n typeof editor.storage.collaboration === 'object' &&\n editor.storage.collaboration\n ) {\n ;(editor.storage.collaboration as any).isDisabled = true\n }\n },\n })\n }\n\n const parseOptions: ParseOptions = {\n preserveWhitespace: 'full',\n ...options.parseOptions,\n }\n\n // If `emitContentError` is enabled, we want to check the content for errors\n // but ignore them (do not remove the invalid content from the document)\n if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) {\n try {\n createNodeFromContent(value, editor.schema, {\n parseOptions,\n errorOnInvalidContent: true,\n })\n } catch (e) {\n emitContentError(e as Error)\n }\n }\n\n try {\n content = createNodeFromContent(value, editor.schema, {\n parseOptions,\n errorOnInvalidContent: options.errorOnInvalidContent ?? editor.options.enableContentCheck,\n })\n } catch (e) {\n emitContentError(e as Error)\n return false\n }\n\n let { from, to } =\n typeof position === 'number' ? { from: position, to: position } : { from: position.from, to: position.to }\n\n let isOnlyTextContent = true\n let isOnlyBlockContent = true\n const nodes = isFragment(content) ? content : [content]\n\n nodes.forEach(node => {\n // check if added node is valid\n node.check()\n\n isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false\n\n isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false\n })\n\n // check if we can replace the wrapping node by\n // the newly inserted content\n // example:\n // replace an empty paragraph by an inserted image\n // instead of inserting the image below the paragraph\n if (from === to && isOnlyBlockContent) {\n const { parent } = tr.doc.resolve(from)\n const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount\n\n if (isEmptyTextBlock) {\n from -= 1\n to += 1\n }\n }\n\n let newContent\n\n // if there is only plain text we have to use `insertText`\n // because this will keep the current marks\n if (isOnlyTextContent) {\n // if value is string, we can use it directly\n // otherwise if it is an array, we have to join it\n if (Array.isArray(value)) {\n newContent = value.map(v => v.text || '').join('')\n } else if (value instanceof Fragment) {\n let text = ''\n\n value.forEach(node => {\n if (node.text) {\n text += node.text\n }\n })\n\n newContent = text\n } else if (typeof value === 'object' && !!value && !!value.text) {\n newContent = value.text\n } else {\n newContent = value as string\n }\n\n tr.insertText(newContent, from, to)\n } else {\n newContent = content\n\n const fromSelectionAtStart = selection.$from.parentOffset === 0\n const isTextSelection = selection.$from.node().isText || selection.$from.node().isTextblock\n const hasContent = selection.$from.node().content.size > 0\n\n if (fromSelectionAtStart && isTextSelection && hasContent) {\n from = Math.max(0, from - 1)\n }\n\n tr.replaceWith(from, to, newContent)\n }\n\n // set cursor at end of inserted content\n if (options.updateSelection) {\n selectionToInsertionEnd(tr, tr.steps.length - 1, -1)\n }\n\n if (options.applyInputRules) {\n tr.setMeta('applyInputRules', { from, text: newContent })\n }\n\n if (options.applyPasteRules) {\n tr.setMeta('applyPasteRules', { from, text: newContent })\n }\n }\n\n return true\n }\n","import {\n joinBackward as originalJoinBackward,\n joinDown as originalJoinDown,\n joinForward as originalJoinForward,\n joinUp as originalJoinUp,\n} from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n joinUp: {\n /**\n * Join the selected block or, if there is a text selection, the closest ancestor block of the selection that can be joined, with the sibling above it.\n * @example editor.commands.joinUp()\n */\n joinUp: () => ReturnType\n }\n joinDown: {\n /**\n * Join the selected block, or the closest ancestor of the selection that can be joined, with the sibling after it.\n * @example editor.commands.joinDown()\n */\n joinDown: () => ReturnType\n }\n joinBackward: {\n /**\n * If the selection is empty and at the start of a textblock, try to reduce the distance between that block and the one before it—if there's a block directly before it that can be joined, join them.\n * If not, try to move the selected block closer to the next one in the document structure by lifting it out of its\n * parent or moving it into a parent of the previous block. Will use the view for accurate (bidi-aware) start-of-textblock detection if given.\n * @example editor.commands.joinBackward()\n */\n joinBackward: () => ReturnType\n }\n joinForward: {\n /**\n * If the selection is empty and the cursor is at the end of a textblock, try to reduce or remove the boundary between that block and the one after it,\n * either by joining them or by moving the other block closer to this one in the tree structure.\n * Will use the view for accurate start-of-textblock detection if given.\n * @example editor.commands.joinForward()\n */\n joinForward: () => ReturnType\n }\n }\n}\n\nexport const joinUp: RawCommands['joinUp'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinUp(state, dispatch)\n }\n\nexport const joinDown: RawCommands['joinDown'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinDown(state, dispatch)\n }\n\nexport const joinBackward: RawCommands['joinBackward'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinBackward(state, dispatch)\n }\n\nexport const joinForward: RawCommands['joinForward'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinForward(state, dispatch)\n }\n","import { joinPoint } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n joinItemBackward: {\n /**\n * Join two items backward.\n * @example editor.commands.joinItemBackward()\n */\n joinItemBackward: () => ReturnType\n }\n }\n}\n\nexport const joinItemBackward: RawCommands['joinItemBackward'] =\n () =>\n ({ state, dispatch, tr }) => {\n try {\n const point = joinPoint(state.doc, state.selection.$from.pos, -1)\n\n if (point === null || point === undefined) {\n return false\n }\n\n tr.join(point, 2)\n\n if (dispatch) {\n dispatch(tr)\n }\n\n return true\n } catch {\n return false\n }\n }\n","import { joinPoint } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n joinItemForward: {\n /**\n * Join two items Forwards.\n * @example editor.commands.joinItemForward()\n */\n joinItemForward: () => ReturnType\n }\n }\n}\n\nexport const joinItemForward: RawCommands['joinItemForward'] =\n () =>\n ({ state, dispatch, tr }) => {\n try {\n const point = joinPoint(state.doc, state.selection.$from.pos, +1)\n\n if (point === null || point === undefined) {\n return false\n }\n\n tr.join(point, 2)\n\n if (dispatch) {\n dispatch(tr)\n }\n\n return true\n } catch {\n return false\n }\n }\n","import { joinTextblockBackward as originalCommand } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n joinTextblockBackward: {\n /**\n * A more limited form of joinBackward that only tries to join the current textblock to the one before it, if the cursor is at the start of a textblock.\n */\n joinTextblockBackward: () => ReturnType\n }\n }\n}\n\nexport const joinTextblockBackward: RawCommands['joinTextblockBackward'] =\n () =>\n ({ state, dispatch }) => {\n return originalCommand(state, dispatch)\n }\n","import { joinTextblockForward as originalCommand } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n joinTextblockForward: {\n /**\n * A more limited form of joinForward that only tries to join the current textblock to the one after it, if the cursor is at the end of a textblock.\n */\n joinTextblockForward: () => ReturnType\n }\n }\n}\n\nexport const joinTextblockForward: RawCommands['joinTextblockForward'] =\n () =>\n ({ state, dispatch }) => {\n return originalCommand(state, dispatch)\n }\n","export function isMacOS(): boolean {\n return typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false\n}\n","import type { RawCommands } from '../types.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isMacOS } from '../utilities/isMacOS.js'\n\nfunction normalizeKeyName(name: string) {\n const parts = name.split(/-(?!$)/)\n let result = parts[parts.length - 1]\n\n if (result === 'Space') {\n result = ' '\n }\n\n let alt\n let ctrl\n let shift\n let meta\n\n for (let i = 0; i < parts.length - 1; i += 1) {\n const mod = parts[i]\n\n if (/^(cmd|meta|m)$/i.test(mod)) {\n meta = true\n } else if (/^a(lt)?$/i.test(mod)) {\n alt = true\n } else if (/^(c|ctrl|control)$/i.test(mod)) {\n ctrl = true\n } else if (/^s(hift)?$/i.test(mod)) {\n shift = true\n } else if (/^mod$/i.test(mod)) {\n if (isiOS() || isMacOS()) {\n meta = true\n } else {\n ctrl = true\n }\n } else {\n throw new Error(`Unrecognized modifier name: ${mod}`)\n }\n }\n\n if (alt) {\n result = `Alt-${result}`\n }\n\n if (ctrl) {\n result = `Ctrl-${result}`\n }\n\n if (meta) {\n result = `Meta-${result}`\n }\n\n if (shift) {\n result = `Shift-${result}`\n }\n\n return result\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n keyboardShortcut: {\n /**\n * Trigger a keyboard shortcut.\n * @param name The name of the keyboard shortcut.\n * @example editor.commands.keyboardShortcut('Mod-b')\n */\n keyboardShortcut: (name: string) => ReturnType\n }\n }\n}\n\nexport const keyboardShortcut: RawCommands['keyboardShortcut'] =\n name =>\n ({ editor, view, tr, dispatch }) => {\n const keys = normalizeKeyName(name).split(/-(?!$)/)\n const key = keys.find(item => !['Alt', 'Ctrl', 'Meta', 'Shift'].includes(item))\n const event = new KeyboardEvent('keydown', {\n key: key === 'Space' ? ' ' : key,\n altKey: keys.includes('Alt'),\n ctrlKey: keys.includes('Ctrl'),\n metaKey: keys.includes('Meta'),\n shiftKey: keys.includes('Shift'),\n bubbles: true,\n cancelable: true,\n })\n\n const capturedTransaction = editor.captureTransaction(() => {\n view.someProp('handleKeyDown', f => f(view, event))\n })\n\n capturedTransaction?.steps.forEach(step => {\n const newStep = step.map(tr.mapping)\n\n if (newStep && dispatch) {\n tr.maybeStep(newStep)\n }\n })\n\n return true\n }\n","import { lift as originalLift } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n lift: {\n /**\n * Removes an existing wrap if possible lifting the node out of it\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.lift('paragraph')\n * @example editor.commands.lift('heading', { level: 1 })\n */\n lift: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const lift: RawCommands['lift'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n const isActive = isNodeActive(state, type, attributes)\n\n if (!isActive) {\n return false\n }\n\n return originalLift(state, dispatch)\n }\n","import { liftEmptyBlock as originalLiftEmptyBlock } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n liftEmptyBlock: {\n /**\n * If the cursor is in an empty textblock that can be lifted, lift the block.\n * @example editor.commands.liftEmptyBlock()\n */\n liftEmptyBlock: () => ReturnType\n }\n }\n}\n\nexport const liftEmptyBlock: RawCommands['liftEmptyBlock'] =\n () =>\n ({ state, dispatch }) => {\n return originalLiftEmptyBlock(state, dispatch)\n }\n","import type { NodeType } from '@tiptap/pm/model'\nimport { liftListItem as originalLiftListItem } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n liftListItem: {\n /**\n * Create a command to lift the list item around the selection up into a wrapping list.\n * @param typeOrName The type or name of the node.\n * @example editor.commands.liftListItem('listItem')\n */\n liftListItem: (typeOrName: string | NodeType) => ReturnType\n }\n }\n}\n\nexport const liftListItem: RawCommands['liftListItem'] =\n typeOrName =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalLiftListItem(type)(state, dispatch)\n }\n","import { newlineInCode as originalNewlineInCode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n newlineInCode: {\n /**\n * Add a newline character in code.\n * @example editor.commands.newlineInCode()\n */\n newlineInCode: () => ReturnType\n }\n }\n}\n\nexport const newlineInCode: RawCommands['newlineInCode'] =\n () =>\n ({ state, dispatch }) => {\n return originalNewlineInCode(state, dispatch)\n }\n","/**\n * Remove a property or an array of properties from an object\n * @param obj Object\n * @param key Key to remove\n */\nexport function deleteProps(obj: Record<string, any>, propOrProps: string | string[]): Record<string, any> {\n const props = typeof propOrProps === 'string' ? [propOrProps] : propOrProps\n\n return Object.keys(obj).reduce((newObj: Record<string, any>, prop) => {\n if (!props.includes(prop)) {\n newObj[prop] = obj[prop]\n }\n\n return newObj\n }, {})\n}\n","import type { MarkType, NodeType } from '@tiptap/pm/model'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSchemaTypeNameByName } from '../helpers/getSchemaTypeNameByName.js'\nimport type { RawCommands } from '../types.js'\nimport { deleteProps } from '../utilities/deleteProps.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n resetAttributes: {\n /**\n * Resets some node attributes to the default value.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node to reset.\n * @example editor.commands.resetAttributes('heading', 'level')\n */\n resetAttributes: (typeOrName: string | NodeType | MarkType, attributes: string | string[]) => ReturnType\n }\n }\n}\n\nexport const resetAttributes: RawCommands['resetAttributes'] =\n (typeOrName, attributes) =>\n ({ tr, state, dispatch }) => {\n let nodeType: NodeType | null = null\n let markType: MarkType | null = null\n\n const schemaType = getSchemaTypeNameByName(\n typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n state.schema,\n )\n\n if (!schemaType) {\n return false\n }\n\n if (schemaType === 'node') {\n nodeType = getNodeType(typeOrName as NodeType, state.schema)\n }\n\n if (schemaType === 'mark') {\n markType = getMarkType(typeOrName as MarkType, state.schema)\n }\n\n if (dispatch) {\n tr.selection.ranges.forEach(range => {\n state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {\n if (nodeType && nodeType === node.type) {\n tr.setNodeMarkup(pos, undefined, deleteProps(node.attrs, attributes))\n }\n\n if (markType && node.marks.length) {\n node.marks.forEach(mark => {\n if (markType === mark.type) {\n tr.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes)))\n }\n })\n }\n })\n })\n }\n\n return true\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n scrollIntoView: {\n /**\n * Scroll the selection into view.\n * @example editor.commands.scrollIntoView()\n */\n scrollIntoView: () => ReturnType\n }\n }\n}\n\nexport const scrollIntoView: RawCommands['scrollIntoView'] =\n () =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n tr.scrollIntoView()\n }\n\n return true\n }\n","import { AllSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectAll: {\n /**\n * Select the whole document.\n * @example editor.commands.selectAll()\n */\n selectAll: () => ReturnType\n }\n }\n}\n\nexport const selectAll: RawCommands['selectAll'] =\n () =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n const selection = new AllSelection(tr.doc)\n\n tr.setSelection(selection)\n }\n\n return true\n }\n","import { selectNodeBackward as originalSelectNodeBackward } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectNodeBackward: {\n /**\n * Select a node backward.\n * @example editor.commands.selectNodeBackward()\n */\n selectNodeBackward: () => ReturnType\n }\n }\n}\n\nexport const selectNodeBackward: RawCommands['selectNodeBackward'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectNodeBackward(state, dispatch)\n }\n","import { selectNodeForward as originalSelectNodeForward } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectNodeForward: {\n /**\n * Select a node forward.\n * @example editor.commands.selectNodeForward()\n */\n selectNodeForward: () => ReturnType\n }\n }\n}\n\nexport const selectNodeForward: RawCommands['selectNodeForward'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectNodeForward(state, dispatch)\n }\n","import { selectParentNode as originalSelectParentNode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectParentNode: {\n /**\n * Select the parent node.\n * @example editor.commands.selectParentNode()\n */\n selectParentNode: () => ReturnType\n }\n }\n}\n\nexport const selectParentNode: RawCommands['selectParentNode'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectParentNode(state, dispatch)\n }\n","// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nimport { selectTextblockEnd as originalSelectTextblockEnd } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectTextblockEnd: {\n /**\n * Moves the cursor to the end of current text block.\n * @example editor.commands.selectTextblockEnd()\n */\n selectTextblockEnd: () => ReturnType\n }\n }\n}\n\nexport const selectTextblockEnd: RawCommands['selectTextblockEnd'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectTextblockEnd(state, dispatch)\n }\n","// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nimport { selectTextblockStart as originalSelectTextblockStart } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n selectTextblockStart: {\n /**\n * Moves the cursor to the start of current text block.\n * @example editor.commands.selectTextblockStart()\n */\n selectTextblockStart: () => ReturnType\n }\n }\n}\n\nexport const selectTextblockStart: RawCommands['selectTextblockStart'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectTextblockStart(state, dispatch)\n }\n","import type { Fragment, Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\n\nimport { createDocument } from '../helpers/createDocument.js'\nimport type { Content, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setContent: {\n /**\n * Replace the whole document with new content.\n * @param content The new content.\n * @param emitUpdate Whether to emit an update event.\n * @param parseOptions Options for parsing the content.\n * @example editor.commands.setContent('<p>Example text</p>')\n */\n setContent: (\n /**\n * The new content.\n */\n content: Content | Fragment | ProseMirrorNode,\n\n /**\n * Options for `setContent`.\n */\n options?: {\n /**\n * Options for parsing the content.\n * @default {}\n */\n parseOptions?: ParseOptions\n\n /**\n * Whether to throw an error if the content is invalid.\n */\n errorOnInvalidContent?: boolean\n\n /**\n * Whether to emit an update event.\n * @default true\n */\n emitUpdate?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const setContent: RawCommands['setContent'] =\n (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) =>\n ({ editor, tr, dispatch, commands }) => {\n const { doc } = tr\n\n // This is to keep backward compatibility with the previous behavior\n // TODO remove this in the next major version\n if (parseOptions.preserveWhitespace !== 'full') {\n const document = createDocument(content, editor.schema, parseOptions, {\n errorOnInvalidContent: errorOnInvalidContent ?? editor.options.enableContentCheck,\n })\n\n if (dispatch) {\n tr.replaceWith(0, doc.content.size, document).setMeta('preventUpdate', !emitUpdate)\n }\n return true\n }\n\n if (dispatch) {\n tr.setMeta('preventUpdate', !emitUpdate)\n }\n\n return commands.insertContentAt({ from: 0, to: doc.content.size }, content, {\n parseOptions,\n errorOnInvalidContent: errorOnInvalidContent ?? editor.options.enableContentCheck,\n })\n }\n","import type { MarkType, ResolvedPos } from '@tiptap/pm/model'\nimport type { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport { getMarkAttributes } from '../helpers/getMarkAttributes.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { isTextSelection } from '../helpers/index.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setMark: {\n /**\n * Add a mark with new attributes.\n * @param typeOrName The mark type or name.\n * @example editor.commands.setMark('bold', { level: 1 })\n */\n setMark: (typeOrName: string | MarkType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nfunction canSetMark(state: EditorState, tr: Transaction, newMarkType: MarkType) {\n const { selection } = tr\n let cursor: ResolvedPos | null = null\n\n if (isTextSelection(selection)) {\n cursor = selection.$cursor\n }\n\n if (cursor) {\n const currentMarks = state.storedMarks ?? cursor.marks()\n\n // There can be no current marks that exclude the new mark\n return !!newMarkType.isInSet(currentMarks) || !currentMarks.some(mark => mark.type.excludes(newMarkType))\n }\n\n const { ranges } = selection\n\n return ranges.some(({ $from, $to }) => {\n let someNodeSupportsMark =\n $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false\n\n state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => {\n // If we already found a mark that we can enable, return false to bypass the remaining search\n if (someNodeSupportsMark) {\n return false\n }\n\n if (node.isInline) {\n const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType)\n const currentMarksAllowMarkType =\n !!newMarkType.isInSet(node.marks) || !node.marks.some(otherMark => otherMark.type.excludes(newMarkType))\n\n someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType\n }\n return !someNodeSupportsMark\n })\n\n return someNodeSupportsMark\n })\n}\nexport const setMark: RawCommands['setMark'] =\n (typeOrName, attributes = {}) =>\n ({ tr, state, dispatch }) => {\n const { selection } = tr\n const { empty, ranges } = selection\n const type = getMarkType(typeOrName, state.schema)\n\n if (dispatch) {\n if (empty) {\n const oldAttributes = getMarkAttributes(state, type)\n\n tr.addStoredMark(\n type.create({\n ...oldAttributes,\n ...attributes,\n }),\n )\n } else {\n ranges.forEach(range => {\n const from = range.$from.pos\n const to = range.$to.pos\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n const trimmedFrom = Math.max(pos, from)\n const trimmedTo = Math.min(pos + node.nodeSize, to)\n const someHasMark = node.marks.find(mark => mark.type === type)\n\n // if there is already a mark of this type\n // we know that we have to merge its attributes\n // otherwise we add a fresh new mark\n if (someHasMark) {\n node.marks.forEach(mark => {\n if (type === mark.type) {\n tr.addMark(\n trimmedFrom,\n trimmedTo,\n type.create({\n ...mark.attrs,\n ...attributes,\n }),\n )\n }\n })\n } else {\n tr.addMark(trimmedFrom, trimmedTo, type.create(attributes))\n }\n })\n })\n }\n }\n\n return canSetMark(state, tr, type)\n }\n","import type { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setMeta: {\n /**\n * Store a metadata property in the current transaction.\n * @param key The key of the metadata property.\n * @param value The value to store.\n * @example editor.commands.setMeta('foo', 'bar')\n */\n setMeta: (key: string | Plugin | PluginKey, value: any) => ReturnType\n }\n }\n}\n\nexport const setMeta: RawCommands['setMeta'] =\n (key, value) =>\n ({ tr }) => {\n tr.setMeta(key, value)\n\n return true\n }\n","import { setBlockType } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setNode: {\n /**\n * Replace a given range with a node.\n * @param typeOrName The type or name of the node\n * @param attributes The attributes of the node\n * @example editor.commands.setNode('paragraph')\n */\n setNode: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const setNode: RawCommands['setNode'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch, chain }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n let attributesToCopy: Record<string, any> | undefined\n\n if (state.selection.$anchor.sameParent(state.selection.$head)) {\n // only copy attributes if the selection is pointing to a node of the same type\n attributesToCopy = state.selection.$anchor.parent.attrs\n }\n\n // TODO: use a fallback like insertContent?\n if (!type.isTextblock) {\n console.warn('[tiptap warn]: Currently \"setNode()\" only supports text block nodes.')\n\n return false\n }\n\n return (\n chain()\n // try to convert node to default node if needed\n .command(({ commands }) => {\n const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state)\n\n if (canSetBlock) {\n return true\n }\n\n return commands.clearNodes()\n })\n .command(({ state: updatedState }) => {\n return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch)\n })\n .run()\n )\n }\n","import { NodeSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setNodeSelection: {\n /**\n * Creates a NodeSelection.\n * @param position - Position of the node.\n * @example editor.commands.setNodeSelection(10)\n */\n setNodeSelection: (position: number) => ReturnType\n }\n }\n}\n\nexport const setNodeSelection: RawCommands['setNodeSelection'] =\n position =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n const { doc } = tr\n const from = minMax(position, 0, doc.content.size)\n const selection = NodeSelection.create(doc, from)\n\n tr.setSelection(selection)\n }\n\n return true\n }\n","import { TextSelection } from '@tiptap/pm/state'\n\nimport type { Range, RawCommands } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n setTextSelection: {\n /**\n * Creates a TextSelection.\n * @param position The position of the selection.\n * @example editor.commands.setTextSelection(10)\n */\n setTextSelection: (position: number | Range) => ReturnType\n }\n }\n}\n\nexport const setTextSelection: RawCommands['setTextSelection'] =\n position =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n const { doc } = tr\n const { from, to } = typeof position === 'number' ? { from: position, to: position } : position\n const minPos = TextSelection.atStart(doc).from\n const maxPos = TextSelection.atEnd(doc).to\n const resolvedFrom = minMax(from, minPos, maxPos)\n const resolvedEnd = minMax(to, minPos, maxPos)\n const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd)\n\n tr.setSelection(selection)\n }\n\n return true\n }\n","import type { NodeType } from '@tiptap/pm/model'\nimport { sinkListItem as originalSinkListItem } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n sinkListItem: {\n /**\n * Sink the list item down into an inner list.\n * @param typeOrName The type or name of the node.\n * @example editor.commands.sinkListItem('listItem')\n */\n sinkListItem: (typeOrName: string | NodeType) => ReturnType\n }\n }\n}\n\nexport const sinkListItem: RawCommands['sinkListItem'] =\n typeOrName =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalSinkListItem(type)(state, dispatch)\n }\n","import type { EditorState } from '@tiptap/pm/state'\nimport { NodeSelection, TextSelection } from '@tiptap/pm/state'\nimport { canSplit } from '@tiptap/pm/transform'\n\nimport { defaultBlockAt } from '../helpers/defaultBlockAt.js'\nimport { getSplittedAttributes } from '../helpers/getSplittedAttributes.js'\nimport type { RawCommands } from '../types.js'\n\nfunction ensureMarks(state: EditorState, splittableMarks?: string[]) {\n const marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks())\n\n if (marks) {\n const filteredMarks = marks.filter(mark => splittableMarks?.includes(mark.type.name))\n\n state.tr.ensureMarks(filteredMarks)\n }\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n splitBlock: {\n /**\n * Forks a new node from an existing node.\n * @param options.keepMarks Keep marks from the previous node.\n * @example editor.commands.splitBlock()\n * @example editor.commands.splitBlock({ keepMarks: true })\n */\n splitBlock: (options?: { keepMarks?: boolean }) => ReturnType\n }\n }\n}\n\nexport const splitBlock: RawCommands['splitBlock'] =\n ({ keepMarks = true } = {}) =>\n ({ tr, state, dispatch, editor }) => {\n const { selection, doc } = tr\n const { $from, $to } = selection\n const extensionAttributes = editor.extensionManager.attributes\n const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs)\n\n if (selection instanceof NodeSelection && selection.node.isBlock) {\n if (!$from.parentOffset || !canSplit(doc, $from.pos)) {\n return false\n }\n\n if (dispatch) {\n if (keepMarks) {\n ensureMarks(state, editor.extensionManager.splittableMarks)\n }\n\n tr.split($from.pos).scrollIntoView()\n }\n\n return true\n }\n\n if (!$from.parent.isBlock) {\n return false\n }\n\n const atEnd = $to.parentOffset === $to.parent.content.size\n\n const deflt = $from.depth === 0 ? undefined : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)))\n\n let types =\n atEnd && deflt\n ? [\n {\n type: deflt,\n attrs: newAttributes,\n },\n ]\n : undefined\n\n let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types)\n\n if (!types && !can && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : undefined)) {\n can = true\n types = deflt\n ? [\n {\n type: deflt,\n attrs: newAttributes,\n },\n ]\n : undefined\n }\n\n if (dispatch) {\n if (can) {\n if (selection instanceof TextSelection) {\n tr.deleteSelection()\n }\n\n tr.split(tr.mapping.map($from.pos), 1, types)\n\n if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {\n const first = tr.mapping.map($from.before())\n const $first = tr.doc.resolve(first)\n\n if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {\n tr.setNodeMarkup(tr.mapping.map($from.before()), deflt)\n }\n }\n }\n\n if (keepMarks) {\n ensureMarks(state, editor.extensionManager.splittableMarks)\n }\n\n tr.scrollIntoView()\n }\n\n return can\n }\n","import type { Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\nimport { Fragment, Slice } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { canSplit } from '@tiptap/pm/transform'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSplittedAttributes } from '../helpers/getSplittedAttributes.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n splitListItem: {\n /**\n * Splits one list item into two list items.\n * @param typeOrName The type or name of the node.\n * @param overrideAttrs The attributes to ensure on the new node.\n * @example editor.commands.splitListItem('listItem')\n */\n splitListItem: (typeOrName: string | NodeType, overrideAttrs?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const splitListItem: RawCommands['splitListItem'] =\n (typeOrName, overrideAttrs = {}) =>\n ({ tr, state, dispatch, editor }) => {\n const type = getNodeType(typeOrName, state.schema)\n const { $from, $to } = state.selection\n\n // @ts-ignore\n // eslint-disable-next-line\n const node: ProseMirrorNode = state.selection.node\n\n if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to)) {\n return false\n }\n\n const grandParent = $from.node(-1)\n\n if (grandParent.type !== type) {\n return false\n }\n\n const extensionAttributes = editor.extensionManager.attributes\n\n if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {\n // In an empty block. If this is a nested list, the wrapping\n // list item should be split. Otherwise, bail out and let next\n // command handle lifting.\n if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) {\n return false\n }\n\n if (dispatch) {\n let wrap = Fragment.empty\n // eslint-disable-next-line\n const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3\n\n // Build a fragment containing empty versions of the structure\n // from the outer list item to the parent node of the cursor\n for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {\n wrap = Fragment.from($from.node(d).copy(wrap))\n }\n\n const depthAfter =\n // eslint-disable-next-line no-nested-ternary\n $from.indexAfter(-1) < $from.node(-2).childCount\n ? 1\n : $from.indexAfter(-2) < $from.node(-3).childCount\n ? 2\n : 3\n\n // Add a second list item with an empty default start node\n const newNextTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),\n ...overrideAttrs,\n }\n const nextType = type.contentMatch.defaultType?.createAndFill(newNextTypeAttributes) || undefined\n\n wrap = wrap.append(Fragment.from(type.createAndFill(null, nextType) || undefined))\n\n const start = $from.before($from.depth - (depthBefore - 1))\n\n tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0))\n\n let sel = -1\n\n tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {\n if (sel > -1) {\n return false\n }\n\n if (n.isTextblock && n.content.size === 0) {\n sel = pos + 1\n }\n })\n\n if (sel > -1) {\n tr.setSelection(TextSelection.near(tr.doc.resolve(sel)))\n }\n\n tr.scrollIntoView()\n }\n\n return true\n }\n\n const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null\n\n const newTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),\n ...overrideAttrs,\n }\n const newNextTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),\n ...overrideAttrs,\n }\n\n tr.delete($from.pos, $to.pos)\n\n const types = nextType\n ? [\n { type, attrs: newTypeAttributes },\n { type: nextType, attrs: newNextTypeAttributes },\n ]\n : [{ type, attrs: newTypeAttributes }]\n\n if (!canSplit(tr.doc, $from.pos, 2)) {\n return false\n }\n\n if (dispatch) {\n const { selection, storedMarks } = state\n const { splittableMarks } = editor.extensionManager\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n tr.split($from.pos, 2, types).scrollIntoView()\n\n if (!marks || !dispatch) {\n return true\n }\n\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n tr.ensureMarks(filteredMarks)\n }\n\n return true\n }\n","import type { NodeType } from '@tiptap/pm/model'\nimport type { Transaction } from '@tiptap/pm/state'\nimport { canJoin } from '@tiptap/pm/transform'\n\nimport { findParentNode } from '../helpers/findParentNode.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isList } from '../helpers/isList.js'\nimport type { RawCommands } from '../types.js'\n\nconst joinListBackwards = (tr: Transaction, listType: NodeType): boolean => {\n const list = findParentNode(node => node.type === listType)(tr.selection)\n\n if (!list) {\n return true\n }\n\n const before = tr.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth)\n\n if (before === undefined) {\n return true\n }\n\n const nodeBefore = tr.doc.nodeAt(before)\n const canJoinBackwards = list.node.type === nodeBefore?.type && canJoin(tr.doc, list.pos)\n\n if (!canJoinBackwards) {\n return true\n }\n\n tr.join(list.pos)\n\n return true\n}\n\nconst joinListForwards = (tr: Transaction, listType: NodeType): boolean => {\n const list = findParentNode(node => node.type === listType)(tr.selection)\n\n if (!list) {\n return true\n }\n\n const after = tr.doc.resolve(list.start).after(list.depth)\n\n if (after === undefined) {\n return true\n }\n\n const nodeAfter = tr.doc.nodeAt(after)\n const canJoinForwards = list.node.type === nodeAfter?.type && canJoin(tr.doc, after)\n\n if (!canJoinForwards) {\n return true\n }\n\n tr.join(after)\n\n return true\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n toggleList: {\n /**\n * Toggle between different list types.\n * @param listTypeOrName The type or name of the list.\n * @param itemTypeOrName The type or name of the list item.\n * @param keepMarks Keep marks when toggling.\n * @param attributes Attributes for the new list.\n * @example editor.commands.toggleList('bulletList', 'listItem')\n */\n toggleList: (\n listTypeOrName: string | NodeType,\n itemTypeOrName: string | NodeType,\n keepMarks?: boolean,\n attributes?: Record<string, any>,\n ) => ReturnType\n }\n }\n}\n\nexport const toggleList: RawCommands['toggleList'] =\n (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) =>\n ({ editor, tr, state, dispatch, chain, commands, can }) => {\n const { extensions, splittableMarks } = editor.extensionManager\n const listType = getNodeType(listTypeOrName, state.schema)\n const itemType = getNodeType(itemTypeOrName, state.schema)\n const { selection, storedMarks } = state\n const { $from, $to } = selection\n const range = $from.blockRange($to)\n\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n if (!range) {\n return false\n }\n\n const parentList = findParentNode(node => isList(node.type.name, extensions))(selection)\n\n if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {\n // remove list\n if (parentList.node.type === listType) {\n return commands.liftListItem(itemType)\n }\n\n // change list type\n if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content) && dispatch) {\n return chain()\n .command(() => {\n tr.setNodeMarkup(parentList.pos, listType)\n\n return true\n })\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run()\n }\n }\n if (!keepMarks || !marks || !dispatch) {\n return (\n chain()\n // try to convert node to default node if needed\n .command(() => {\n const canWrapInList = can().wrapInList(listType, attributes)\n\n if (canWrapInList) {\n return true\n }\n\n return commands.clearNodes()\n })\n .wrapInList(listType, attributes)\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run()\n )\n }\n\n return (\n chain()\n // try to convert node to default node if needed\n .command(() => {\n const canWrapInList = can().wrapInList(listType, attributes)\n\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n tr.ensureMarks(filteredMarks)\n\n if (canWrapInList) {\n return true\n }\n\n return commands.clearNodes()\n })\n .wrapInList(listType, attributes)\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run()\n )\n }\n","import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { isMarkActive } from '../helpers/isMarkActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n toggleMark: {\n /**\n * Toggle a mark on and off.\n * @param typeOrName The mark type or name.\n * @param attributes The attributes of the mark.\n * @param options.extendEmptyMarkRange Removes the mark even across the current selection. Defaults to `false`.\n * @example editor.commands.toggleMark('bold')\n */\n toggleMark: (\n /**\n * The mark type or name.\n */\n typeOrName: string | MarkType,\n\n /**\n * The attributes of the mark.\n */\n attributes?: Record<string, any>,\n\n options?: {\n /**\n * Removes the mark even across the current selection. Defaults to `false`.\n */\n extendEmptyMarkRange?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const toggleMark: RawCommands['toggleMark'] =\n (typeOrName, attributes = {}, options = {}) =>\n ({ state, commands }) => {\n const { extendEmptyMarkRange = false } = options\n const type = getMarkType(typeOrName, state.schema)\n const isActive = isMarkActive(state, type, attributes)\n\n if (isActive) {\n return commands.unsetMark(type, { extendEmptyMarkRange })\n }\n\n return commands.setMark(type, attributes)\n }\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n toggleNode: {\n /**\n * Toggle a node with another node.\n * @param typeOrName The type or name of the node.\n * @param toggleTypeOrName The type or name of the node to toggle.\n * @param attributes The attributes of the node.\n * @example editor.commands.toggleNode('heading', 'paragraph')\n */\n toggleNode: (\n typeOrName: string | NodeType,\n toggleTypeOrName: string | NodeType,\n attributes?: Record<string, any>,\n ) => ReturnType\n }\n }\n}\n\nexport const toggleNode: RawCommands['toggleNode'] =\n (typeOrName, toggleTypeOrName, attributes = {}) =>\n ({ state, commands }) => {\n const type = getNodeType(typeOrName, state.schema)\n const toggleType = getNodeType(toggleTypeOrName, state.schema)\n const isActive = isNodeActive(state, type, attributes)\n\n let attributesToCopy: Record<string, any> | undefined\n\n if (state.selection.$anchor.sameParent(state.selection.$head)) {\n // only copy attributes if the selection is pointing to a node of the same type\n attributesToCopy = state.selection.$anchor.parent.attrs\n }\n\n if (isActive) {\n return commands.setNode(toggleType, attributesToCopy)\n }\n\n // If the node is not active, we want to set the new node type with the given attributes\n // Copying over the attributes from the current node if the selection is pointing to a node of the same type\n return commands.setNode(type, { ...attributesToCopy, ...attributes })\n }\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n toggleWrap: {\n /**\n * Wraps nodes in another node, or removes an existing wrap.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.toggleWrap('blockquote')\n */\n toggleWrap: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const toggleWrap: RawCommands['toggleWrap'] =\n (typeOrName, attributes = {}) =>\n ({ state, commands }) => {\n const type = getNodeType(typeOrName, state.schema)\n const isActive = isNodeActive(state, type, attributes)\n\n if (isActive) {\n return commands.lift(type)\n }\n\n return commands.wrapIn(type, attributes)\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n undoInputRule: {\n /**\n * Undo an input rule.\n * @example editor.commands.undoInputRule()\n */\n undoInputRule: () => ReturnType\n }\n }\n}\n\nexport const undoInputRule: RawCommands['undoInputRule'] =\n () =>\n ({ state, dispatch }) => {\n const plugins = state.plugins\n\n for (let i = 0; i < plugins.length; i += 1) {\n const plugin = plugins[i]\n let undoable\n\n // @ts-ignore\n // eslint-disable-next-line\n if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {\n if (dispatch) {\n const tr = state.tr\n const toUndo = undoable.transform\n\n for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {\n tr.step(toUndo.steps[j].invert(toUndo.docs[j]))\n }\n\n if (undoable.text) {\n const marks = tr.doc.resolve(undoable.from).marks()\n\n tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks))\n } else {\n tr.delete(undoable.from, undoable.to)\n }\n }\n\n return true\n }\n }\n\n return false\n }\n","import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n unsetAllMarks: {\n /**\n * Remove all marks in the current selection.\n * @example editor.commands.unsetAllMarks()\n */\n unsetAllMarks: () => ReturnType\n }\n }\n}\n\nexport const unsetAllMarks: RawCommands['unsetAllMarks'] =\n () =>\n ({ tr, dispatch }) => {\n const { selection } = tr\n const { empty, ranges } = selection\n\n if (empty) {\n return true\n }\n\n if (dispatch) {\n ranges.forEach(range => {\n tr.removeMark(range.$from.pos, range.$to.pos)\n })\n }\n\n return true\n }\n","import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarkRange } from '../helpers/getMarkRange.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n unsetMark: {\n /**\n * Remove all marks in the current selection.\n * @param typeOrName The mark type or name.\n * @param options.extendEmptyMarkRange Removes the mark even across the current selection. Defaults to `false`.\n * @example editor.commands.unsetMark('bold')\n */\n unsetMark: (\n /**\n * The mark type or name.\n */\n typeOrName: string | MarkType,\n\n options?: {\n /**\n * Removes the mark even across the current selection. Defaults to `false`.\n */\n extendEmptyMarkRange?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const unsetMark: RawCommands['unsetMark'] =\n (typeOrName, options = {}) =>\n ({ tr, state, dispatch }) => {\n const { extendEmptyMarkRange = false } = options\n const { selection } = tr\n const type = getMarkType(typeOrName, state.schema)\n const { $from, empty, ranges } = selection\n\n if (!dispatch) {\n return true\n }\n\n if (empty && extendEmptyMarkRange) {\n let { from, to } = selection\n const attrs = $from.marks().find(mark => mark.type === type)?.attrs\n const range = getMarkRange($from, type, attrs)\n\n if (range) {\n from = range.from\n to = range.to\n }\n\n tr.removeMark(from, to, type)\n } else {\n ranges.forEach(range => {\n tr.removeMark(range.$from.pos, range.$to.pos, type)\n })\n }\n\n tr.removeStoredMark(type)\n\n return true\n }\n","import type { Mark, MarkType, Node, NodeType } from '@tiptap/pm/model'\nimport type { SelectionRange } from '@tiptap/pm/state'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSchemaTypeNameByName } from '../helpers/getSchemaTypeNameByName.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n updateAttributes: {\n /**\n * Update attributes of a node or mark.\n * @param typeOrName The type or name of the node or mark.\n * @param attributes The attributes of the node or mark.\n * @example editor.commands.updateAttributes('mention', { userId: \"2\" })\n */\n updateAttributes: (\n /**\n * The type or name of the node or mark.\n */\n typeOrName: string | NodeType | MarkType,\n\n /**\n * The attributes of the node or mark.\n */\n attributes: Record<string, any>,\n ) => ReturnType\n }\n }\n}\n\nexport const updateAttributes: RawCommands['updateAttributes'] =\n (typeOrName, attributes = {}) =>\n ({ tr, state, dispatch }) => {\n let nodeType: NodeType | null = null\n let markType: MarkType | null = null\n\n const schemaType = getSchemaTypeNameByName(\n typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n state.schema,\n )\n\n if (!schemaType) {\n return false\n }\n\n if (schemaType === 'node') {\n nodeType = getNodeType(typeOrName as NodeType, state.schema)\n }\n\n if (schemaType === 'mark') {\n markType = getMarkType(typeOrName as MarkType, state.schema)\n }\n\n if (dispatch) {\n tr.selection.ranges.forEach((range: SelectionRange) => {\n const from = range.$from.pos\n const to = range.$to.pos\n\n let lastPos: number | undefined\n let lastNode: Node | undefined\n let trimmedFrom: number\n let trimmedTo: number\n\n if (tr.selection.empty) {\n state.doc.nodesBetween(from, to, (node: Node, pos: number) => {\n if (nodeType && nodeType === node.type) {\n trimmedFrom = Math.max(pos, from)\n trimmedTo = Math.min(pos + node.nodeSize, to)\n lastPos = pos\n lastNode = node\n }\n })\n } else {\n state.doc.nodesBetween(from, to, (node: Node, pos: number) => {\n if (pos < from && nodeType && nodeType === node.type) {\n trimmedFrom = Math.max(pos, from)\n trimmedTo = Math.min(pos + node.nodeSize, to)\n lastPos = pos\n lastNode = node\n }\n\n if (pos >= from && pos <= to) {\n if (nodeType && nodeType === node.type) {\n tr.setNodeMarkup(pos, undefined, {\n ...node.attrs,\n ...attributes,\n })\n }\n\n if (markType && node.marks.length) {\n node.marks.forEach((mark: Mark) => {\n if (markType === mark.type) {\n const trimmedFrom2 = Math.max(pos, from)\n const trimmedTo2 = Math.min(pos + node.nodeSize, to)\n\n tr.addMark(\n trimmedFrom2,\n trimmedTo2,\n markType.create({\n ...mark.attrs,\n ...attributes,\n }),\n )\n }\n })\n }\n }\n })\n }\n\n if (lastNode) {\n if (lastPos !== undefined) {\n tr.setNodeMarkup(lastPos, undefined, {\n ...lastNode.attrs,\n ...attributes,\n })\n }\n\n if (markType && lastNode.marks.length) {\n lastNode.marks.forEach((mark: Mark) => {\n if (markType === mark.type) {\n tr.addMark(\n trimmedFrom,\n trimmedTo,\n markType.create({\n ...mark.attrs,\n ...attributes,\n }),\n )\n }\n })\n }\n }\n })\n }\n\n return true\n }\n","import { wrapIn as originalWrapIn } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n wrapIn: {\n /**\n * Wraps nodes in another node.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.wrapIn('blockquote')\n */\n wrapIn: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const wrapIn: RawCommands['wrapIn'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalWrapIn(type, attributes)(state, dispatch)\n }\n","import type { NodeType } from '@tiptap/pm/model'\nimport { wrapInList as originalWrapInList } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n wrapInList: {\n /**\n * Wrap a node in a list.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.wrapInList('bulletList')\n */\n wrapInList: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n }\n }\n}\n\nexport const wrapInList: RawCommands['wrapInList'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalWrapInList(type, attributes)(state, dispatch)\n }\n","import * as commands from '../commands/index.js'\nimport { Extension } from '../Extension.js'\n\nexport * from '../commands/index.js'\n\nexport const Commands = Extension.create({\n name: 'commands',\n\n addCommands() {\n return {\n ...commands,\n }\n },\n})\n","import { RemoveMarkStep } from '@tiptap/pm/transform'\n\nimport { Extension } from '../Extension.js'\nimport { combineTransactionSteps, getChangedRanges } from '../helpers/index.js'\n\n/**\n * This extension allows you to be notified when the user deletes content you are interested in.\n */\nexport const Delete = Extension.create({\n name: 'delete',\n\n onUpdate({ transaction, appendedTransactions }) {\n const callback = () => {\n if (\n this.editor.options.coreExtensionOptions?.delete?.filterTransaction?.(transaction) ??\n transaction.getMeta('y-sync$')\n ) {\n return\n }\n const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions])\n const changes = getChangedRanges(nextTransaction)\n\n changes.forEach(change => {\n if (\n nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter &&\n nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore\n ) {\n nextTransaction.before.nodesBetween(change.oldRange.from, change.oldRange.to, (node, from) => {\n const to = from + node.nodeSize - 2\n const isFullyWithinRange = change.oldRange.from <= from && to <= change.oldRange.to\n\n this.editor.emit('delete', {\n type: 'node',\n node,\n from,\n to,\n newFrom: nextTransaction.mapping.map(from),\n newTo: nextTransaction.mapping.map(to),\n deletedRange: change.oldRange,\n newRange: change.newRange,\n partial: !isFullyWithinRange,\n editor: this.editor,\n transaction,\n combinedTransform: nextTransaction,\n })\n })\n }\n })\n\n const mapping = nextTransaction.mapping\n nextTransaction.steps.forEach((step, index) => {\n if (step instanceof RemoveMarkStep) {\n const newStart = mapping.slice(index).map(step.from, -1)\n const newEnd = mapping.slice(index).map(step.to)\n const oldStart = mapping.invert().map(newStart, -1)\n const oldEnd = mapping.invert().map(newEnd)\n\n const foundBeforeMark = nextTransaction.doc.nodeAt(newStart - 1)?.marks.some(mark => mark.eq(step.mark))\n const foundAfterMark = nextTransaction.doc.nodeAt(newEnd)?.marks.some(mark => mark.eq(step.mark))\n\n this.editor.emit('delete', {\n type: 'mark',\n mark: step.mark,\n from: step.from,\n to: step.to,\n deletedRange: {\n from: oldStart,\n to: oldEnd,\n },\n newRange: {\n from: newStart,\n to: newEnd,\n },\n partial: Boolean(foundAfterMark || foundBeforeMark),\n editor: this.editor,\n transaction,\n combinedTransform: nextTransaction,\n })\n }\n })\n }\n\n if (this.editor.options.coreExtensionOptions?.delete?.async ?? true) {\n setTimeout(callback, 0)\n } else {\n callback()\n }\n },\n})\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Drop = Extension.create({\n name: 'drop',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tiptapDrop'),\n\n props: {\n handleDrop: (_, e, slice, moved) => {\n this.editor.emit('drop', {\n editor: this.editor,\n event: e,\n slice,\n moved,\n })\n },\n },\n }),\n ]\n },\n})\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Editable = Extension.create({\n name: 'editable',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('editable'),\n props: {\n editable: () => this.editor.options.editable,\n },\n }),\n ]\n },\n})\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const focusEventsPluginKey = new PluginKey('focusEvents')\n\nexport const FocusEvents = Extension.create({\n name: 'focusEvents',\n\n addProseMirrorPlugins() {\n const { editor } = this\n\n return [\n new Plugin({\n key: focusEventsPluginKey,\n props: {\n handleDOMEvents: {\n focus: (view, event: Event) => {\n editor.isFocused = true\n\n const transaction = editor.state.tr.setMeta('focus', { event }).setMeta('addToHistory', false)\n\n view.dispatch(transaction)\n\n return false\n },\n blur: (view, event: Event) => {\n editor.isFocused = false\n\n const transaction = editor.state.tr.setMeta('blur', { event }).setMeta('addToHistory', false)\n\n view.dispatch(transaction)\n\n return false\n },\n },\n },\n }),\n ]\n },\n})\n","import { Plugin, PluginKey, Selection } from '@tiptap/pm/state'\n\nimport { CommandManager } from '../CommandManager.js'\nimport { Extension } from '../Extension.js'\nimport { createChainableState } from '../helpers/createChainableState.js'\nimport { isNodeEmpty } from '../helpers/isNodeEmpty.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isMacOS } from '../utilities/isMacOS.js'\n\nexport const Keymap = Extension.create({\n name: 'keymap',\n\n addKeyboardShortcuts() {\n const handleBackspace = () =>\n this.editor.commands.first(({ commands }) => [\n () => commands.undoInputRule(),\n\n // maybe convert first text block node to default node\n () =>\n commands.command(({ tr }) => {\n const { selection, doc } = tr\n const { empty, $anchor } = selection\n const { pos, parent } = $anchor\n const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr.doc.resolve(pos - 1) : $anchor\n const parentIsIsolating = $parentPos.parent.type.spec.isolating\n\n const parentPos = $anchor.pos - $anchor.parentOffset\n\n const isAtStart =\n parentIsIsolating && $parentPos.parent.childCount === 1\n ? parentPos === $anchor.pos\n : Selection.atStart(doc).from === pos\n\n if (\n !empty ||\n !parent.type.isTextblock ||\n parent.textContent.length ||\n !isAtStart ||\n (isAtStart && $anchor.parent.type.name === 'paragraph') // prevent clearNodes when no nodes to clear, otherwise history stack is appended\n ) {\n return false\n }\n\n return commands.clearNodes()\n }),\n\n () => commands.deleteSelection(),\n () => commands.joinBackward(),\n () => commands.selectNodeBackward(),\n ])\n\n const handleDelete = () =>\n this.editor.commands.first(({ commands }) => [\n () => commands.deleteSelection(),\n () => commands.deleteCurrentNode(),\n () => commands.joinForward(),\n () => commands.selectNodeForward(),\n ])\n\n const handleEnter = () =>\n this.editor.commands.first(({ commands }) => [\n () => commands.newlineInCode(),\n () => commands.createParagraphNear(),\n () => commands.liftEmptyBlock(),\n () => commands.splitBlock(),\n ])\n\n const baseKeymap = {\n Enter: handleEnter,\n 'Mod-Enter': () => this.editor.commands.exitCode(),\n Backspace: handleBackspace,\n 'Mod-Backspace': handleBackspace,\n 'Shift-Backspace': handleBackspace,\n Delete: handleDelete,\n 'Mod-Delete': handleDelete,\n 'Mod-a': () => this.editor.commands.selectAll(),\n }\n\n const pcKeymap = {\n ...baseKeymap,\n }\n\n const macKeymap = {\n ...baseKeymap,\n 'Ctrl-h': handleBackspace,\n 'Alt-Backspace': handleBackspace,\n 'Ctrl-d': handleDelete,\n 'Ctrl-Alt-Backspace': handleDelete,\n 'Alt-Delete': handleDelete,\n 'Alt-d': handleDelete,\n 'Ctrl-a': () => this.editor.commands.selectTextblockStart(),\n 'Ctrl-e': () => this.editor.commands.selectTextblockEnd(),\n }\n\n if (isiOS() || isMacOS()) {\n return macKeymap\n }\n\n return pcKeymap\n },\n\n addProseMirrorPlugins() {\n return [\n // With this plugin we check if the whole document was selected and deleted.\n // In this case we will additionally call `clearNodes()` to convert e.g. a heading\n // to a paragraph if necessary.\n // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well\n // with many other commands.\n new Plugin({\n key: new PluginKey('clearDocument'),\n appendTransaction: (transactions, oldState, newState) => {\n if (transactions.some(tr => tr.getMeta('composition'))) {\n return\n }\n\n const docChanges = transactions.some(transaction => transaction.docChanged) && !oldState.doc.eq(newState.doc)\n\n const ignoreTr = transactions.some(transaction => transaction.getMeta('preventClearDocument'))\n\n if (!docChanges || ignoreTr) {\n return\n }\n\n const { empty, from, to } = oldState.selection\n const allFrom = Selection.atStart(oldState.doc).from\n const allEnd = Selection.atEnd(oldState.doc).to\n const allWasSelected = from === allFrom && to === allEnd\n\n if (empty || !allWasSelected) {\n return\n }\n\n const isEmpty = isNodeEmpty(newState.doc)\n\n if (!isEmpty) {\n return\n }\n\n const tr = newState.tr\n const state = createChainableState({\n state: newState,\n transaction: tr,\n })\n const { commands } = new CommandManager({\n editor: this.editor,\n state,\n })\n\n commands.clearNodes()\n\n if (!tr.steps.length) {\n return\n }\n\n return tr\n },\n }),\n ]\n },\n})\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Paste = Extension.create({\n name: 'paste',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tiptapPaste'),\n\n props: {\n handlePaste: (_view, e, slice) => {\n this.editor.emit('paste', {\n editor: this.editor,\n event: e,\n slice,\n })\n },\n },\n }),\n ]\n },\n})\n","import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Tabindex = Extension.create({\n name: 'tabindex',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tabindex'),\n props: {\n attributes: (): { [name: string]: string } => (this.editor.isEditable ? { tabindex: '0' } : {}),\n },\n }),\n ]\n },\n})\n","import type { Fragment, Node, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { Content, Range } from './types.js'\n\nexport class NodePos {\n private resolvedPos: ResolvedPos\n\n private isBlock: boolean\n\n private editor: Editor\n\n private get name(): string {\n return this.node.type.name\n }\n\n constructor(pos: ResolvedPos, editor: Editor, isBlock = false, node: Node | null = null) {\n this.isBlock = isBlock\n this.resolvedPos = pos\n this.editor = editor\n this.currentNode = node\n }\n\n private currentNode: Node | null = null\n\n get node(): Node {\n return this.currentNode || this.resolvedPos.node()\n }\n\n get element(): HTMLElement {\n return this.editor.view.domAtPos(this.pos).node as HTMLElement\n }\n\n public actualDepth: number | null = null\n\n get depth(): number {\n return this.actualDepth ?? this.resolvedPos.depth\n }\n\n get pos(): number {\n return this.resolvedPos.pos\n }\n\n get content(): Fragment {\n return this.node.content\n }\n\n set content(content: Content) {\n let from = this.from\n let to = this.to\n\n if (this.isBlock) {\n if (this.content.size === 0) {\n console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`)\n return\n }\n\n from = this.from + 1\n to = this.to - 1\n }\n\n this.editor.commands.insertContentAt({ from, to }, content)\n }\n\n get attributes(): { [key: string]: any } {\n return this.node.attrs\n }\n\n get textContent(): string {\n return this.node.textContent\n }\n\n get size(): number {\n return this.node.nodeSize\n }\n\n get from(): number {\n if (this.isBlock) {\n return this.pos\n }\n\n return this.resolvedPos.start(this.resolvedPos.depth)\n }\n\n get range(): Range {\n return {\n from: this.from,\n to: this.to,\n }\n }\n\n get to(): number {\n if (this.isBlock) {\n return this.pos + this.size\n }\n\n return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1)\n }\n\n get parent(): NodePos | null {\n if (this.depth === 0) {\n return null\n }\n\n const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1)\n const $pos = this.resolvedPos.doc.resolve(parentPos)\n\n return new NodePos($pos, this.editor)\n }\n\n get before(): NodePos | null {\n let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2))\n\n if ($pos.depth !== this.depth) {\n $pos = this.resolvedPos.doc.resolve(this.from - 3)\n }\n\n return new NodePos($pos, this.editor)\n }\n\n get after(): NodePos | null {\n let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1))\n\n if ($pos.depth !== this.depth) {\n $pos = this.resolvedPos.doc.resolve(this.to + 3)\n }\n\n return new NodePos($pos, this.editor)\n }\n\n get children(): NodePos[] {\n const children: NodePos[] = []\n\n this.node.content.forEach((node, offset) => {\n const isBlock = node.isBlock && !node.isTextblock\n const isNonTextAtom = node.isAtom && !node.isText\n\n const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1)\n\n // Check if targetPos is within valid document range\n if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) {\n return\n }\n\n const $pos = this.resolvedPos.doc.resolve(targetPos)\n\n if (!isBlock && $pos.depth <= this.depth) {\n return\n }\n\n const childNodePos = new NodePos($pos, this.editor, isBlock, isBlock ? node : null)\n\n if (isBlock) {\n childNodePos.actualDepth = this.depth + 1\n }\n\n children.push(new NodePos($pos, this.editor, isBlock, isBlock ? node : null))\n })\n\n return children\n }\n\n get firstChild(): NodePos | null {\n return this.children[0] || null\n }\n\n get lastChild(): NodePos | null {\n const children = this.children\n\n return children[children.length - 1] || null\n }\n\n closest(selector: string, attributes: { [key: string]: any } = {}): NodePos | null {\n let node: NodePos | null = null\n let currentNode = this.parent\n\n while (currentNode && !node) {\n if (currentNode.node.type.name === selector) {\n if (Object.keys(attributes).length > 0) {\n const nodeAttributes = currentNode.node.attrs\n const attrKeys = Object.keys(attributes)\n\n for (let index = 0; index < attrKeys.length; index += 1) {\n const key = attrKeys[index]\n\n if (nodeAttributes[key] !== attributes[key]) {\n break\n }\n }\n } else {\n node = currentNode\n }\n }\n\n currentNode = currentNode.parent\n }\n\n return node\n }\n\n querySelector(selector: string, attributes: { [key: string]: any } = {}): NodePos | null {\n return this.querySelectorAll(selector, attributes, true)[0] || null\n }\n\n querySelectorAll(selector: string, attributes: { [key: string]: any } = {}, firstItemOnly = false): NodePos[] {\n let nodes: NodePos[] = []\n\n if (!this.children || this.children.length === 0) {\n return nodes\n }\n const attrKeys = Object.keys(attributes)\n\n /**\n * Finds all children recursively that match the selector and attributes\n * If firstItemOnly is true, it will return the first item found\n */\n this.children.forEach(childPos => {\n // If we already found a node and we only want the first item, we dont need to keep going\n if (firstItemOnly && nodes.length > 0) {\n return\n }\n\n if (childPos.node.type.name === selector) {\n const doesAllAttributesMatch = attrKeys.every(key => attributes[key] === childPos.node.attrs[key])\n\n if (doesAllAttributesMatch) {\n nodes.push(childPos)\n }\n }\n\n // If we already found a node and we only want the first item, we can stop here and skip the recursion\n if (firstItemOnly && nodes.length > 0) {\n return\n }\n\n nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly))\n })\n\n return nodes\n }\n\n setAttribute(attributes: { [key: string]: any }) {\n const { tr } = this.editor.state\n\n tr.setNodeMarkup(this.from, undefined, {\n ...this.node.attrs,\n ...attributes,\n })\n\n this.editor.view.dispatch(tr)\n }\n}\n","export const style = `.ProseMirror {\n position: relative;\n}\n\n.ProseMirror {\n word-wrap: break-word;\n white-space: pre-wrap;\n white-space: break-spaces;\n -webkit-font-variant-ligatures: none;\n font-variant-ligatures: none;\n font-feature-settings: \"liga\" 0; /* the above doesn't seem to work in Edge */\n}\n\n.ProseMirror [contenteditable=\"false\"] {\n white-space: normal;\n}\n\n.ProseMirror [contenteditable=\"false\"] [contenteditable=\"true\"] {\n white-space: pre-wrap;\n}\n\n.ProseMirror pre {\n white-space: pre-wrap;\n}\n\nimg.ProseMirror-separator {\n display: inline !important;\n border: none !important;\n margin: 0 !important;\n width: 0 !important;\n height: 0 !important;\n}\n\n.ProseMirror-gapcursor {\n display: none;\n pointer-events: none;\n position: absolute;\n margin: 0;\n}\n\n.ProseMirror-gapcursor:after {\n content: \"\";\n display: block;\n position: absolute;\n top: -2px;\n width: 20px;\n border-top: 1px solid black;\n animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;\n}\n\n@keyframes ProseMirror-cursor-blink {\n to {\n visibility: hidden;\n }\n}\n\n.ProseMirror-hideselection *::selection {\n background: transparent;\n}\n\n.ProseMirror-hideselection *::-moz-selection {\n background: transparent;\n}\n\n.ProseMirror-hideselection * {\n caret-color: transparent;\n}\n\n.ProseMirror-focused .ProseMirror-gapcursor {\n display: block;\n}`\n","export function createStyleTag(style: string, nonce?: string, suffix?: string): HTMLStyleElement {\n const tiptapStyleTag = <HTMLStyleElement>(\n document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ''}]`)\n )\n\n if (tiptapStyleTag !== null) {\n return tiptapStyleTag\n }\n\n const styleNode = document.createElement('style')\n\n if (nonce) {\n styleNode.setAttribute('nonce', nonce)\n }\n\n styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ''}`, '')\n styleNode.innerHTML = style\n document.getElementsByTagName('head')[0].appendChild(styleNode)\n\n return styleNode\n}\n","import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarksBetween } from '../helpers/getMarksBetween.js'\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that adds a mark when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function markInputRule(config: {\n find: InputRuleFinder\n type: MarkType\n getAttributes?: Record<string, any> | ((match: ExtendedRegExpMatchArray) => Record<string, any>) | false | null\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match)\n\n if (attributes === false || attributes === null) {\n return null\n }\n\n const { tr } = state\n const captureGroup = match[match.length - 1]\n const fullMatch = match[0]\n\n if (captureGroup) {\n const startSpaces = fullMatch.search(/\\S/)\n const textStart = range.from + fullMatch.indexOf(captureGroup)\n const textEnd = textStart + captureGroup.length\n\n const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n .filter(item => {\n // @ts-ignore\n const excluded = item.mark.type.excluded as MarkType[]\n\n return excluded.find(type => type === config.type && type !== item.mark.type)\n })\n .filter(item => item.to > textStart)\n\n if (excludedMarks.length) {\n return null\n }\n\n if (textEnd < range.to) {\n tr.delete(textEnd, range.to)\n }\n\n if (textStart > range.from) {\n tr.delete(range.from + startSpaces, textStart)\n }\n\n const markEnd = range.from + startSpaces + captureGroup.length\n\n tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))\n\n tr.removeStoredMark(config.type)\n }\n },\n })\n}\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that adds a node when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function nodeInputRule(config: {\n /**\n * The regex to match.\n */\n find: InputRuleFinder\n\n /**\n * The node type to add.\n */\n type: NodeType\n\n /**\n * A function that returns the attributes for the node\n * can also be an object of attributes\n */\n getAttributes?: Record<string, any> | ((match: ExtendedRegExpMatchArray) => Record<string, any>) | false | null\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n const { tr } = state\n const start = range.from\n let end = range.to\n\n const newNode = config.type.create(attributes)\n\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1])\n let matchStart = start + offset\n\n if (matchStart > end) {\n matchStart = end\n } else {\n end = matchStart + match[1].length\n }\n\n // insert last typed character\n const lastChar = match[0][match[0].length - 1]\n\n tr.insertText(lastChar, start + match[0].length - 1)\n\n // insert node from input rule\n tr.replaceWith(matchStart, end, newNode)\n } else if (match[0]) {\n const insertionStart = config.type.isInline ? start : start - 1\n\n tr.insert(insertionStart, config.type.create(attributes)).delete(tr.mapping.map(start), tr.mapping.map(end))\n }\n\n tr.scrollIntoView()\n },\n })\n}\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that changes the type of a textblock when the\n * matched text is typed into it. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function textblockTypeInputRule(config: {\n find: InputRuleFinder\n type: NodeType\n getAttributes?: Record<string, any> | ((match: ExtendedRegExpMatchArray) => Record<string, any>) | false | null\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const $start = state.doc.resolve(range.from)\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n\n if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) {\n return null\n }\n\n state.tr.delete(range.from, range.to).setBlockType(range.from, range.from, config.type, attributes)\n },\n })\n}\n","import type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\n\n/**\n * Build an input rule that replaces text when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function textInputRule(config: { find: InputRuleFinder; replace: string }) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n let insert = config.replace\n let start = range.from\n const end = range.to\n\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1])\n\n insert += match[0].slice(offset + match[1].length)\n start += offset\n\n const cutOff = start - end\n\n if (cutOff > 0) {\n insert = match[0].slice(offset - cutOff, offset) + insert\n start = end\n }\n }\n\n state.tr.insertText(insert, start, end)\n },\n })\n}\n","import type { Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\nimport { canJoin, findWrapping } from '@tiptap/pm/transform'\n\nimport type { Editor } from '../Editor.js'\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule for automatically wrapping a textblock when a\n * given string is typed. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n *\n * `type` is the type of node to wrap in.\n *\n * By default, if there’s a node with the same type above the newly\n * wrapped node, the rule will try to join those\n * two nodes. You can pass a join predicate, which takes a regular\n * expression match and the node before the wrapped node, and can\n * return a boolean to indicate whether a join should happen.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function wrappingInputRule(config: {\n find: InputRuleFinder\n type: NodeType\n keepMarks?: boolean\n keepAttributes?: boolean\n editor?: Editor\n getAttributes?: Record<string, any> | ((match: ExtendedRegExpMatchArray) => Record<string, any>) | false | null\n joinPredicate?: (match: ExtendedRegExpMatchArray, node: ProseMirrorNode) => boolean\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match, chain }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n const tr = state.tr.delete(range.from, range.to)\n const $start = tr.doc.resolve(range.from)\n const blockRange = $start.blockRange()\n const wrapping = blockRange && findWrapping(blockRange, config.type, attributes)\n\n if (!wrapping) {\n return null\n }\n\n tr.wrap(blockRange, wrapping)\n\n if (config.keepMarks && config.editor) {\n const { selection, storedMarks } = state\n const { splittableMarks } = config.editor.extensionManager\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n if (marks) {\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n tr.ensureMarks(filteredMarks)\n }\n }\n if (config.keepAttributes) {\n /** If the nodeType is `bulletList` or `orderedList` set the `nodeType` as `listItem` */\n const nodeType =\n config.type.name === 'bulletList' || config.type.name === 'orderedList' ? 'listItem' : 'taskList'\n\n chain().updateAttributes(nodeType, attributes).run()\n }\n\n const before = tr.doc.resolve(range.from - 1).nodeBefore\n\n if (\n before &&\n before.type === config.type &&\n canJoin(tr.doc, range.from - 1) &&\n (!config.joinPredicate || config.joinPredicate(match, before))\n ) {\n tr.join(range.from - 1)\n }\n },\n })\n}\n","export type Attributes = Record<string, any>\n\nexport type DOMOutputSpecElement = 0 | Attributes | DOMOutputSpecArray\n/**\n * Better describes the output of a `renderHTML` function in prosemirror\n * @see https://prosemirror.net/docs/ref/#model.DOMOutputSpec\n */\nexport type DOMOutputSpecArray =\n | [string]\n | [string, Attributes]\n | [string, 0]\n | [string, Attributes, 0]\n | [string, Attributes, DOMOutputSpecArray | 0]\n | [string, DOMOutputSpecArray]\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n // @ts-ignore - conflict with React typings\n type Element = [string, ...any[]]\n // @ts-ignore - conflict with React typings\n interface IntrinsicElements {\n // @ts-ignore - conflict with React typings\n [key: string]: any\n }\n }\n}\n\nexport type JSXRenderer = (\n tag: 'slot' | string | ((props?: Attributes) => DOMOutputSpecArray | DOMOutputSpecElement),\n props?: Attributes,\n ...children: JSXRenderer[]\n) => DOMOutputSpecArray | DOMOutputSpecElement\n\nexport function Fragment(props: { children: JSXRenderer[] }) {\n return props.children\n}\n\nexport const h: JSXRenderer = (tag, attributes) => {\n // Treat the slot tag as the Prosemirror hole to render content into\n if (tag === 'slot') {\n return 0\n }\n\n // If the tag is a function, call it with the props\n if (tag instanceof Function) {\n return tag(attributes)\n }\n\n const { children, ...rest } = attributes ?? {}\n\n if (tag === 'svg') {\n throw new Error('SVG elements are not supported in the JSX syntax, use the array syntax instead')\n }\n\n // Otherwise, return the tag, attributes, and children\n return [tag, rest, children]\n}\n\n// See\n// https://esbuild.github.io/api/#jsx-import-source\n// https://www.typescriptlang.org/tsconfig/#jsxImportSource\n\nexport { h as createElement, h as jsx, h as jsxDEV, h as jsxs }\n","import type { NodeType } from '@tiptap/pm/model'\nimport { type EditorState, NodeSelection } from '@tiptap/pm/state'\n\nexport function canInsertNode(state: EditorState, nodeType: NodeType): boolean {\n const { selection } = state\n const { $from } = selection\n\n // Special handling for NodeSelection\n if (selection instanceof NodeSelection) {\n const index = $from.index()\n const parent = $from.parent\n\n // Can we replace the selected node with the horizontal rule?\n return parent.canReplaceWith(index, index + 1, nodeType)\n }\n\n // Default: check if we can insert at the current position\n let depth = $from.depth\n\n while (depth >= 0) {\n const index = $from.index(depth)\n const parent = $from.node(depth)\n const match = parent.contentMatchAt(index)\n if (match.matchType(nodeType)) {\n return true\n }\n depth -= 1\n }\n return false\n}\n","// source: https://stackoverflow.com/a/6969486\nexport function escapeForRegEx(string: string): string {\n return string.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&')\n}\n","export function isString(value: any): value is string {\n return typeof value === 'string'\n}\n","import type { Mark } from '@tiptap/pm/model'\nimport type { ViewMutationRecord } from '@tiptap/pm/view'\n\nimport type { Editor } from './Editor.js'\nimport type { MarkViewProps, MarkViewRendererOptions } from './types.js'\nimport { isAndroid, isiOS } from './utilities/index.js'\n\nexport function updateMarkViewAttributes(checkMark: Mark, editor: Editor, attrs: Record<string, any> = {}): void {\n const { state } = editor\n const { doc, tr } = state\n const thisMark = checkMark\n\n doc.descendants((node, pos) => {\n const from = tr.mapping.map(pos)\n const to = tr.mapping.map(pos) + node.nodeSize\n let foundMark: Mark | null = null\n\n // find the mark on the current node\n node.marks.forEach(mark => {\n if (mark !== thisMark) {\n return false\n }\n\n foundMark = mark\n })\n\n if (!foundMark) {\n return\n }\n\n // check if we need to update given the attributes\n let needsUpdate = false\n Object.keys(attrs).forEach(k => {\n if (attrs[k] !== foundMark!.attrs[k]) {\n needsUpdate = true\n }\n })\n\n if (needsUpdate) {\n const updatedMark = checkMark.type.create({\n ...checkMark.attrs,\n ...attrs,\n })\n\n tr.removeMark(from, to, checkMark.type)\n tr.addMark(from, to, updatedMark)\n }\n })\n\n if (tr.docChanged) {\n editor.view.dispatch(tr)\n }\n}\n\nexport class MarkView<Component, Options extends MarkViewRendererOptions = MarkViewRendererOptions> {\n component: Component\n editor: Editor\n options: Options\n mark: MarkViewProps['mark']\n HTMLAttributes: MarkViewProps['HTMLAttributes']\n\n constructor(component: Component, props: MarkViewProps, options?: Partial<Options>) {\n this.component = component\n this.editor = props.editor\n this.options = { ...options } as Options\n this.mark = props.mark\n this.HTMLAttributes = props.HTMLAttributes\n }\n\n get dom(): HTMLElement {\n return this.editor.view.dom\n }\n\n get contentDOM(): HTMLElement | null {\n return null\n }\n\n /**\n * Update the attributes of the mark in the document.\n * @param attrs The attributes to update.\n */\n updateAttributes(attrs: Record<string, any>, checkMark?: Mark): void {\n updateMarkViewAttributes(checkMark || this.mark, this.editor, attrs)\n }\n\n ignoreMutation(mutation: ViewMutationRecord): boolean {\n if (!this.dom || !this.contentDOM) {\n return true\n }\n\n if (typeof this.options.ignoreMutation === 'function') {\n return this.options.ignoreMutation({ mutation })\n }\n\n if (mutation.type === 'selection') {\n return false\n }\n\n if (\n this.dom.contains(mutation.target) &&\n mutation.type === 'childList' &&\n (isiOS() || isAndroid()) &&\n this.editor.isFocused\n ) {\n const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)] as HTMLElement[]\n\n if (changedNodes.every(node => node.isContentEditable)) {\n return false\n }\n }\n\n if (this.contentDOM === mutation.target && mutation.type === 'attributes') {\n return true\n }\n\n if (this.contentDOM.contains(mutation.target)) {\n return false\n }\n\n return true\n }\n}\n","import type { DOMOutputSpec, Node as ProseMirrorNode, NodeSpec, NodeType } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { ExtendableConfig } from './Extendable.js'\nimport { Extendable } from './Extendable.js'\nimport type { Attributes, NodeViewRenderer, ParentConfig } from './types.js'\n\nexport interface NodeConfig<Options = any, Storage = any>\n extends ExtendableConfig<Options, Storage, NodeConfig<Options, Storage>, NodeType> {\n /**\n * Node View\n */\n addNodeView?:\n | ((this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: NodeType\n parent: ParentConfig<NodeConfig<Options, Storage>>['addNodeView']\n }) => NodeViewRenderer)\n | null\n\n /**\n * Defines if this node should be a top level node (doc)\n * @default false\n * @example true\n */\n topNode?: boolean\n\n /**\n * The content expression for this node, as described in the [schema\n * guide](/docs/guide/#schema.content_expressions). When not given,\n * the node does not allow any content.\n *\n * You can read more about it on the Prosemirror documentation here\n * @see https://prosemirror.net/docs/guide/#schema.content_expressions\n * @default undefined\n * @example content: 'block+'\n * @example content: 'headline paragraph block*'\n */\n content?:\n | NodeSpec['content']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['content']\n editor?: Editor\n }) => NodeSpec['content'])\n\n /**\n * The marks that are allowed inside of this node. May be a\n * space-separated string referring to mark names or groups, `\"_\"`\n * to explicitly allow all marks, or `\"\"` to disallow marks. When\n * not given, nodes with inline content default to allowing all\n * marks, other nodes default to not allowing marks.\n *\n * @example marks: 'strong em'\n */\n marks?:\n | NodeSpec['marks']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['marks']\n editor?: Editor\n }) => NodeSpec['marks'])\n\n /**\n * The group or space-separated groups to which this node belongs,\n * which can be referred to in the content expressions for the\n * schema.\n *\n * By default Tiptap uses the groups 'block' and 'inline' for nodes. You\n * can also use custom groups if you want to group specific nodes together\n * and handle them in your schema.\n * @example group: 'block'\n * @example group: 'inline'\n * @example group: 'customBlock' // this uses a custom group\n */\n group?:\n | NodeSpec['group']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['group']\n editor?: Editor\n }) => NodeSpec['group'])\n\n /**\n * Should be set to true for inline nodes. (Implied for text nodes.)\n */\n inline?:\n | NodeSpec['inline']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['inline']\n editor?: Editor\n }) => NodeSpec['inline'])\n\n /**\n * Can be set to true to indicate that, though this isn't a [leaf\n * node](https://prosemirror.net/docs/ref/#model.NodeType.isLeaf), it doesn't have directly editable\n * content and should be treated as a single unit in the view.\n *\n * @example atom: true\n */\n atom?:\n | NodeSpec['atom']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['atom']\n editor?: Editor\n }) => NodeSpec['atom'])\n\n /**\n * Controls whether nodes of this type can be selected as a [node\n * selection](https://prosemirror.net/docs/ref/#state.NodeSelection). Defaults to true for non-text\n * nodes.\n *\n * @default true\n * @example selectable: false\n */\n selectable?:\n | NodeSpec['selectable']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['selectable']\n editor?: Editor\n }) => NodeSpec['selectable'])\n\n /**\n * Determines whether nodes of this type can be dragged without\n * being selected. Defaults to false.\n *\n * @default: false\n * @example: draggable: true\n */\n draggable?:\n | NodeSpec['draggable']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['draggable']\n editor?: Editor\n }) => NodeSpec['draggable'])\n\n /**\n * Can be used to indicate that this node contains code, which\n * causes some commands to behave differently.\n */\n code?:\n | NodeSpec['code']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['code']\n editor?: Editor\n }) => NodeSpec['code'])\n\n /**\n * Controls way whitespace in this a node is parsed. The default is\n * `\"normal\"`, which causes the [DOM parser](https://prosemirror.net/docs/ref/#model.DOMParser) to\n * collapse whitespace in normal mode, and normalize it (replacing\n * newlines and such with spaces) otherwise. `\"pre\"` causes the\n * parser to preserve spaces inside the node. When this option isn't\n * given, but [`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) is true, `whitespace`\n * will default to `\"pre\"`. Note that this option doesn't influence\n * the way the node is rendered—that should be handled by `toDOM`\n * and/or styling.\n */\n whitespace?:\n | NodeSpec['whitespace']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['whitespace']\n editor?: Editor\n }) => NodeSpec['whitespace'])\n\n /**\n * Allows a **single** node to be set as linebreak equivalent (e.g. hardBreak).\n * When converting between block types that have whitespace set to \"pre\"\n * and don't support the linebreak node (e.g. codeBlock) and other block types\n * that do support the linebreak node (e.g. paragraphs) - this node will be used\n * as the linebreak instead of stripping the newline.\n *\n * See [linebreakReplacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement).\n */\n linebreakReplacement?:\n | NodeSpec['linebreakReplacement']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['linebreakReplacement']\n editor?: Editor\n }) => NodeSpec['linebreakReplacement'])\n\n /**\n * When enabled, enables both\n * [`definingAsContext`](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext) and\n * [`definingForContent`](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n *\n * @default false\n * @example isolating: true\n */\n defining?:\n | NodeSpec['defining']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['defining']\n editor?: Editor\n }) => NodeSpec['defining'])\n\n /**\n * When enabled (default is false), the sides of nodes of this type\n * count as boundaries that regular editing operations, like\n * backspacing or lifting, won't cross. An example of a node that\n * should probably have this enabled is a table cell.\n */\n isolating?:\n | NodeSpec['isolating']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['isolating']\n editor?: Editor\n }) => NodeSpec['isolating'])\n\n /**\n * Associates DOM parser information with this node, which can be\n * used by [`DOMParser.fromSchema`](https://prosemirror.net/docs/ref/#model.DOMParser^fromSchema) to\n * automatically derive a parser. The `node` field in the rules is\n * implied (the name of this node will be filled in automatically).\n * If you supply your own parser, you do not need to also specify\n * parsing rules in your schema.\n *\n * @example parseHTML: [{ tag: 'div', attrs: { 'data-id': 'my-block' } }]\n */\n parseHTML?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['parseHTML']\n editor?: Editor\n }) => NodeSpec['parseDOM']\n\n /**\n * A description of a DOM structure. Can be either a string, which is\n * interpreted as a text node, a DOM node, which is interpreted as\n * itself, a `{dom, contentDOM}` object, or an array.\n *\n * An array describes a DOM element. The first value in the array\n * should be a string—the name of the DOM element, optionally prefixed\n * by a namespace URL and a space. If the second element is plain\n * object, it is interpreted as a set of attributes for the element.\n * Any elements after that (including the 2nd if it's not an attribute\n * object) are interpreted as children of the DOM elements, and must\n * either be valid `DOMOutputSpec` values, or the number zero.\n *\n * The number zero (pronounced “hole”) is used to indicate the place\n * where a node's child nodes should be inserted. If it occurs in an\n * output spec, it should be the only child element in its parent\n * node.\n *\n * @example toDOM: ['div[data-id=\"my-block\"]', { class: 'my-block' }, 0]\n */\n renderHTML?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['renderHTML']\n editor?: Editor\n },\n props: {\n node: ProseMirrorNode\n HTMLAttributes: Record<string, any>\n },\n ) => DOMOutputSpec)\n | null\n\n /**\n * renders the node as text\n * @example renderText: () => 'foo\n */\n renderText?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['renderText']\n editor?: Editor\n },\n props: {\n node: ProseMirrorNode\n pos: number\n parent: ProseMirrorNode\n index: number\n },\n ) => string)\n | null\n\n /**\n * Add attributes to the node\n * @example addAttributes: () => ({ class: 'foo' })\n */\n addAttributes?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig<NodeConfig<Options, Storage>>['addAttributes']\n editor?: Editor\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n }) => Attributes | {}\n}\n\n/**\n * The Node class is used to create custom node extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Node<Options = any, Storage = any> extends Extendable<Options, Storage, NodeConfig<Options, Storage>> {\n type = 'node'\n\n /**\n * Create a new Node instance\n * @param config - Node configuration object or a function that returns a configuration object\n */\n static create<O = any, S = any>(config: Partial<NodeConfig<O, S>> | (() => Partial<NodeConfig<O, S>>) = {}) {\n // If the config is a function, execute it to get the configuration object\n const resolvedConfig = typeof config === 'function' ? config() : config\n return new Node<O, S>(resolvedConfig)\n }\n\n configure(options?: Partial<Options>) {\n return super.configure(options) as Node<Options, Storage>\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig = NodeConfig<ExtendedOptions, ExtendedStorage>,\n >(extendedConfig?: Partial<ExtendedConfig> | (() => Partial<ExtendedConfig>)) {\n // If the extended config is a function, execute it to get the configuration object\n const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n return super.extend(resolvedConfig) as Node<ExtendedOptions, ExtendedStorage>\n }\n}\n","import { NodeSelection } from '@tiptap/pm/state'\nimport type { NodeView as ProseMirrorNodeView, ViewMutationRecord } from '@tiptap/pm/view'\n\nimport type { Editor as CoreEditor } from './Editor.js'\nimport type { DecorationWithType, NodeViewRendererOptions, NodeViewRendererProps } from './types.js'\nimport { isAndroid } from './utilities/isAndroid.js'\nimport { isiOS } from './utilities/isiOS.js'\n\n/**\n * Node views are used to customize the rendered DOM structure of a node.\n * @see https://tiptap.dev/guide/node-views\n */\nexport class NodeView<\n Component,\n NodeEditor extends CoreEditor = CoreEditor,\n Options extends NodeViewRendererOptions = NodeViewRendererOptions,\n> implements ProseMirrorNodeView\n{\n component: Component\n\n editor: NodeEditor\n\n options: Options\n\n extension: NodeViewRendererProps['extension']\n\n node: NodeViewRendererProps['node']\n\n decorations: NodeViewRendererProps['decorations']\n\n innerDecorations: NodeViewRendererProps['innerDecorations']\n\n view: NodeViewRendererProps['view']\n\n getPos: NodeViewRendererProps['getPos']\n\n HTMLAttributes: NodeViewRendererProps['HTMLAttributes']\n\n isDragging = false\n\n constructor(component: Component, props: NodeViewRendererProps, options?: Partial<Options>) {\n this.component = component\n this.editor = props.editor as NodeEditor\n this.options = {\n stopEvent: null,\n ignoreMutation: null,\n ...options,\n } as Options\n this.extension = props.extension\n this.node = props.node\n this.decorations = props.decorations as DecorationWithType[]\n this.innerDecorations = props.innerDecorations\n this.view = props.view\n this.HTMLAttributes = props.HTMLAttributes\n this.getPos = props.getPos\n this.mount()\n }\n\n mount() {\n // eslint-disable-next-line\n return\n }\n\n get dom(): HTMLElement {\n return this.editor.view.dom as HTMLElement\n }\n\n get contentDOM(): HTMLElement | null {\n return null\n }\n\n onDragStart(event: DragEvent) {\n const { view } = this.editor\n const target = event.target as HTMLElement\n\n // get the drag handle element\n // `closest` is not available for text nodes so we may have to use its parent\n const dragHandle =\n target.nodeType === 3 ? target.parentElement?.closest('[data-drag-handle]') : target.closest('[data-drag-handle]')\n\n if (!this.dom || this.contentDOM?.contains(target) || !dragHandle) {\n return\n }\n\n let x = 0\n let y = 0\n\n // calculate offset for drag element if we use a different drag handle element\n if (this.dom !== dragHandle) {\n const domBox = this.dom.getBoundingClientRect()\n const handleBox = dragHandle.getBoundingClientRect()\n\n // In React, we have to go through nativeEvent to reach offsetX/offsetY.\n const offsetX = event.offsetX ?? (event as any).nativeEvent?.offsetX\n const offsetY = event.offsetY ?? (event as any).nativeEvent?.offsetY\n\n x = handleBox.x - domBox.x + offsetX\n y = handleBox.y - domBox.y + offsetY\n }\n\n const clonedNode = this.dom.cloneNode(true) as HTMLElement\n\n event.dataTransfer?.setDragImage(clonedNode, x, y)\n\n const pos = this.getPos()\n\n if (typeof pos !== 'number') {\n return\n }\n // we need to tell ProseMirror that we want to move the whole node\n // so we create a NodeSelection\n const selection = NodeSelection.create(view.state.doc, pos)\n const transaction = view.state.tr.setSelection(selection)\n\n view.dispatch(transaction)\n }\n\n stopEvent(event: Event) {\n if (!this.dom) {\n return false\n }\n\n if (typeof this.options.stopEvent === 'function') {\n return this.options.stopEvent({ event })\n }\n\n const target = event.target as HTMLElement\n const isInElement = this.dom.contains(target) && !this.contentDOM?.contains(target)\n\n // any event from child nodes should be handled by ProseMirror\n if (!isInElement) {\n return false\n }\n\n const isDragEvent = event.type.startsWith('drag')\n const isDropEvent = event.type === 'drop'\n const isInput = ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA'].includes(target.tagName) || target.isContentEditable\n\n // any input event within node views should be ignored by ProseMirror\n if (isInput && !isDropEvent && !isDragEvent) {\n return true\n }\n\n const { isEditable } = this.editor\n const { isDragging } = this\n const isDraggable = !!this.node.type.spec.draggable\n const isSelectable = NodeSelection.isSelectable(this.node)\n const isCopyEvent = event.type === 'copy'\n const isPasteEvent = event.type === 'paste'\n const isCutEvent = event.type === 'cut'\n const isClickEvent = event.type === 'mousedown'\n\n // ProseMirror tries to drag selectable nodes\n // even if `draggable` is set to `false`\n // this fix prevents that\n if (!isDraggable && isSelectable && isDragEvent && event.target === this.dom) {\n event.preventDefault()\n }\n\n if (isDraggable && isDragEvent && !isDragging && event.target === this.dom) {\n event.preventDefault()\n return false\n }\n\n // we have to store that dragging started\n if (isDraggable && isEditable && !isDragging && isClickEvent) {\n const dragHandle = target.closest('[data-drag-handle]')\n const isValidDragHandle = dragHandle && (this.dom === dragHandle || this.dom.contains(dragHandle))\n\n if (isValidDragHandle) {\n this.isDragging = true\n\n document.addEventListener(\n 'dragend',\n () => {\n this.isDragging = false\n },\n { once: true },\n )\n\n document.addEventListener(\n 'drop',\n () => {\n this.isDragging = false\n },\n { once: true },\n )\n\n document.addEventListener(\n 'mouseup',\n () => {\n this.isDragging = false\n },\n { once: true },\n )\n }\n }\n\n // these events are handled by prosemirror\n if (isDragging || isDropEvent || isCopyEvent || isPasteEvent || isCutEvent || (isClickEvent && isSelectable)) {\n return false\n }\n\n return true\n }\n\n /**\n * Called when a DOM [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) or a selection change happens within the view.\n * @return `false` if the editor should re-read the selection or re-parse the range around the mutation\n * @return `true` if it can safely be ignored.\n */\n ignoreMutation(mutation: ViewMutationRecord) {\n if (!this.dom || !this.contentDOM) {\n return true\n }\n\n if (typeof this.options.ignoreMutation === 'function') {\n return this.options.ignoreMutation({ mutation })\n }\n\n // a leaf/atom node is like a black box for ProseMirror\n // and should be fully handled by the node view\n if (this.node.isLeaf || this.node.isAtom) {\n return true\n }\n\n // ProseMirror should handle any selections\n if (mutation.type === 'selection') {\n return false\n }\n\n // try to prevent a bug on iOS and Android that will break node views on enter\n // this is because ProseMirror can’t preventDispatch on enter\n // this will lead to a re-render of the node view on enter\n // see: https://github.com/ueberdosis/tiptap/issues/1214\n // see: https://github.com/ueberdosis/tiptap/issues/2534\n if (\n this.dom.contains(mutation.target) &&\n mutation.type === 'childList' &&\n (isiOS() || isAndroid()) &&\n this.editor.isFocused\n ) {\n const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)] as HTMLElement[]\n\n // we’ll check if every changed node is contentEditable\n // to make sure it’s probably mutated by ProseMirror\n if (changedNodes.every(node => node.isContentEditable)) {\n return false\n }\n }\n\n // we will allow mutation contentDOM with attributes\n // so we can for example adding classes within our node view\n if (this.contentDOM === mutation.target && mutation.type === 'attributes') {\n return true\n }\n\n // ProseMirror should handle any changes within contentDOM\n if (this.contentDOM.contains(mutation.target)) {\n return false\n }\n\n return true\n }\n\n /**\n * Update the attributes of the prosemirror node.\n */\n updateAttributes(attributes: Record<string, any>): void {\n this.editor.commands.command(({ tr }) => {\n const pos = this.getPos()\n\n if (typeof pos !== 'number') {\n return false\n }\n\n tr.setNodeMarkup(pos, undefined, {\n ...this.node.attrs,\n ...attributes,\n })\n\n return true\n })\n }\n\n /**\n * Delete the node.\n */\n deleteNode(): void {\n const from = this.getPos()\n\n if (typeof from !== 'number') {\n return\n }\n const to = from + this.node.nodeSize\n\n this.editor.commands.deleteRange({ from, to })\n }\n}\n","import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarksBetween } from '../helpers/getMarksBetween.js'\nimport type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an paste rule that adds a mark when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function markPasteRule(config: {\n find: PasteRuleFinder\n type: MarkType\n getAttributes?:\n | Record<string, any>\n | ((match: ExtendedRegExpMatchArray, event: ClipboardEvent) => Record<string, any>)\n | false\n | null\n}) {\n return new PasteRule({\n find: config.find,\n handler: ({ state, range, match, pasteEvent }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent)\n\n if (attributes === false || attributes === null) {\n return null\n }\n\n const { tr } = state\n const captureGroup = match[match.length - 1]\n const fullMatch = match[0]\n let markEnd = range.to\n\n if (captureGroup) {\n const startSpaces = fullMatch.search(/\\S/)\n const textStart = range.from + fullMatch.indexOf(captureGroup)\n const textEnd = textStart + captureGroup.length\n\n const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n .filter(item => {\n // @ts-ignore\n const excluded = item.mark.type.excluded as MarkType[]\n\n return excluded.find(type => type === config.type && type !== item.mark.type)\n })\n .filter(item => item.to > textStart)\n\n if (excludedMarks.length) {\n return null\n }\n\n if (textEnd < range.to) {\n tr.delete(textEnd, range.to)\n }\n\n if (textStart > range.from) {\n tr.delete(range.from + startSpaces, textStart)\n }\n\n markEnd = range.from + startSpaces + captureGroup.length\n\n tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))\n\n tr.removeStoredMark(config.type)\n }\n },\n })\n}\n","import type { NodeType } from '@tiptap/pm/model'\n\nimport type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\nimport type { ExtendedRegExpMatchArray, JSONContent } from '../types.js'\nimport { callOrReturn } from '../utilities/index.js'\n\n/**\n * Build an paste rule that adds a node when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function nodePasteRule(config: {\n find: PasteRuleFinder\n type: NodeType\n getAttributes?:\n | Record<string, any>\n | ((match: ExtendedRegExpMatchArray, event: ClipboardEvent) => Record<string, any>)\n | false\n | null\n getContent?: JSONContent[] | ((attrs: Record<string, any>) => JSONContent[]) | false | null\n}) {\n return new PasteRule({\n find: config.find,\n handler({ match, chain, range, pasteEvent }) {\n const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent)\n const content = callOrReturn(config.getContent, undefined, attributes)\n\n if (attributes === false || attributes === null) {\n return null\n }\n\n const node = { type: config.type.name, attrs: attributes } as JSONContent\n\n if (content) {\n node.content = content\n }\n\n if (match.input) {\n chain().deleteRange(range).insertContentAt(range.from, node)\n }\n },\n })\n}\n","import type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\n\n/**\n * Build an paste rule that replaces text when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function textPasteRule(config: { find: PasteRuleFinder; replace: string }) {\n return new PasteRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n let insert = config.replace\n let start = range.from\n const end = range.to\n\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1])\n\n insert += match[0].slice(offset + match[1].length)\n start += offset\n\n const cutOff = start - end\n\n if (cutOff > 0) {\n insert = match[0].slice(offset - cutOff, offset) + insert\n start = end\n }\n }\n\n state.tr.insertText(insert, start, end)\n },\n })\n}\n","import type { Transaction } from '@tiptap/pm/state'\n\nexport interface TrackerResult {\n position: number\n deleted: boolean\n}\n\nexport class Tracker {\n transaction: Transaction\n\n currentStep: number\n\n constructor(transaction: Transaction) {\n this.transaction = transaction\n this.currentStep = this.transaction.steps.length\n }\n\n map(position: number): TrackerResult {\n let deleted = false\n\n const mappedPosition = this.transaction.steps.slice(this.currentStep).reduce((newPosition, step) => {\n const mapResult = step.getMap().mapResult(newPosition)\n\n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AEvB,YAAI,SAAS,GAAG;AACd,mBAAS,MAAM,CAAC,EAAE,MAAM,SAAS,QAAQ,MAAM,IAAI;AACnD,kBAAQ;AAAA,QACV;AAAA,MACF;AAEA,YAAM,GAAG,WAAW,QAAQ,OAAO,GAAG;AAAA,IACxC;AAAA,EACF,CAAC;AACH;;;AC1BO,IAAM,UAAN,MAAc;AAAA,EAKnB,YAAY,aAA0B;AACpC,SAAK,cAAc;AACnB,SAAK,cAAc,KAAK,YAAY,MAAM;AAAA,EAC5C;AAAA,EAEA,IAAI,UAAiC;AACnC,QAAI,UAAU;AAEd,UAAM,iBAAiB,KAAK,YAAY,MAAM,MAAM,KAAK,WAAW,EAAE,OAAO,CAAC,aAAa,SAAS;AAClG,YAAM,YAAY,KAAK,OAAO,EAAE,UAAU,WAAW;AAErD,UAAI,UAAU,SAAS;AACrB,kBAAU;AAAA,MACZ;AAEA,aAAO,UAAU;AAAA,IACnB,GAAG,QAAQ;AAEX,WAAO;AAAA,MACL,UAAU;AAAA,MACV;AAAA,IACF;AAAA,EACF;AACF;","names":["Fragment","Node","command","run","import_state","ProseMirrorNode","import_model","import_model","import_model","style","_a","import_model","import_model","node","output","mark","range","import_state","import_state","import_state","import_transform","import_model","import_state","import_model","import_state","run","from","to","import_state","range","import_transform","originalCreateParagraphNear","import_state","import_commands","originalDeleteSelection","import_commands","originalExitCode","import_state","import_model","isTextSelection","import_commands","originalJoinUp","originalJoinDown","originalJoinBackward","originalJoinForward","import_transform","import_transform","import_commands","originalCommand","import_commands","originalCommand","import_commands","isActive","originalLift","import_commands","originalLiftEmptyBlock","originalLiftListItem","import_commands","originalNewlineInCode","import_state","import_commands","originalSelectNodeBackward","import_commands","originalSelectNodeForward","import_commands","originalSelectParentNode","import_commands","originalSelectTextblockEnd","import_commands","originalSelectTextblockStart","document","import_commands","import_state","import_state","import_schema_list","originalSinkListItem","import_state","import_transform","first","import_model","import_state","import_transform","newNextTypeAttributes","nextType","import_transform","isActive","isActive","isActive","import_commands","originalWrapIn","import_schema_list","originalWrapInList","import_transform","_a","_b","_c","import_state","import_state","import_state","import_state","tr","import_state","import_state","style","focus","blur","import_transform","Fragment","import_state","Node","import_state"]}