) → OrderedMap\n// Return a map with the given content. If null, create an empty\n// map. If given an ordered map, return that map itself. If given an\n// object, create a map from the object's properties.\nOrderedMap.from = function(value) {\n if (value instanceof OrderedMap) return value\n var content = [];\n if (value) for (var prop in value) content.push(prop, value[prop]);\n return new OrderedMap(content)\n};\n\nexport default OrderedMap;\n","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","import { ReplaceError, Slice, Fragment, MarkType, Mark } from 'prosemirror-model';\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\nconst lower16 = 0xffff;\nconst factor16 = Math.pow(2, 16);\nfunction makeRecover(index, offset) { return index + offset * factor16; }\nfunction recoverIndex(value) { return value & lower16; }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16; }\nconst DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;\n/**\nAn object representing a mapped position with extra\ninformation.\n*/\nclass MapResult {\n /**\n @internal\n */\n constructor(\n /**\n The mapped version of the position.\n */\n pos, \n /**\n @internal\n */\n delInfo, \n /**\n @internal\n */\n recover) {\n this.pos = pos;\n this.delInfo = delInfo;\n this.recover = recover;\n }\n /**\n Tells you whether the position was deleted, that is, whether the\n step removed the token on the side queried (via the `assoc`)\n argument from the document.\n */\n get deleted() { return (this.delInfo & DEL_SIDE) > 0; }\n /**\n Tells you whether the token before the mapped position was deleted.\n */\n get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }\n /**\n True when the token after the mapped position was deleted.\n */\n get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }\n /**\n Tells whether any of the steps mapped through deletes across the\n position (including both the token before and after the\n position).\n */\n get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }\n}\n/**\nA map describing the deletions and insertions made by a step, which\ncan be used to find the correspondence between positions in the\npre-step version of a document and the same position in the\npost-step version.\n*/\nclass StepMap {\n /**\n Create a position map. The modifications to the document are\n represented as an array of numbers, in which each group of three\n represents a modified chunk as `[start, oldSize, newSize]`.\n */\n constructor(\n /**\n @internal\n */\n ranges, \n /**\n @internal\n */\n inverted = false) {\n this.ranges = ranges;\n this.inverted = inverted;\n if (!ranges.length && StepMap.empty)\n return StepMap.empty;\n }\n /**\n @internal\n */\n recover(value) {\n let diff = 0, index = recoverIndex(value);\n if (!this.inverted)\n for (let i = 0; i < index; i++)\n diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];\n return this.ranges[index * 3] + diff + recoverOffset(value);\n }\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n map(pos, assoc = 1) { return this._map(pos, assoc, true); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n if (pos <= end) {\n let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n let result = start + diff + (side < 0 ? 0 : newSize);\n if (simple)\n return result;\n let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;\n if (assoc < 0 ? pos != start : pos != end)\n del |= DEL_SIDE;\n return new MapResult(result, del, recover);\n }\n diff += newSize - oldSize;\n }\n return simple ? pos + diff : new MapResult(pos + diff, 0, null);\n }\n /**\n @internal\n */\n touches(pos, recover) {\n let diff = 0, index = recoverIndex(recover);\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n if (pos <= end && i == index * 3)\n return true;\n diff += this.ranges[i + newIndex] - oldSize;\n }\n return false;\n }\n /**\n Calls the given function on each of the changed ranges included in\n this map.\n */\n forEach(f) {\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];\n f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n diff += newSize - oldSize;\n }\n }\n /**\n Create an inverted version of this map. The result can be used to\n map positions in the post-step document to the pre-step document.\n */\n invert() {\n return new StepMap(this.ranges, !this.inverted);\n }\n /**\n @internal\n */\n toString() {\n return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges);\n }\n /**\n Create a map that moves all positions by offset `n` (which may be\n negative). This can be useful when applying steps meant for a\n sub-document to a larger document, or vice-versa.\n */\n static offset(n) {\n return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);\n }\n}\n/**\nA StepMap that contains no changed ranges.\n*/\nStepMap.empty = new StepMap([]);\n/**\nA mapping represents a pipeline of zero or more [step\nmaps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly\nhandling mapping positions through a series of steps in which some\nsteps are inverted versions of earlier steps. (This comes up when\n‘[rebasing](/docs/guide/#transform.rebasing)’ steps for\ncollaboration or history management.)\n*/\nclass Mapping {\n /**\n Create a new mapping with the given position maps.\n */\n constructor(\n /**\n The step maps in this mapping.\n */\n maps = [], \n /**\n @internal\n */\n mirror, \n /**\n The starting position in the `maps` array, used when `map` or\n `mapResult` is called.\n */\n from = 0, \n /**\n The end position in the `maps` array.\n */\n to = maps.length) {\n this.maps = maps;\n this.mirror = mirror;\n this.from = from;\n this.to = to;\n }\n /**\n Create a mapping that maps only through a part of this one.\n */\n slice(from = 0, to = this.maps.length) {\n return new Mapping(this.maps, this.mirror, from, to);\n }\n /**\n @internal\n */\n copy() {\n return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to);\n }\n /**\n Add a step map to the end of this mapping. If `mirrors` is\n given, it should be the index of the step map that is the mirror\n image of this one.\n */\n appendMap(map, mirrors) {\n this.to = this.maps.push(map);\n if (mirrors != null)\n this.setMirror(this.maps.length - 1, mirrors);\n }\n /**\n Add all the step maps in a given mapping to this one (preserving\n mirroring information).\n */\n appendMapping(mapping) {\n for (let i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);\n }\n }\n /**\n Finds the offset of the step map that mirrors the map at the\n given offset, in this mapping (as per the second argument to\n `appendMap`).\n */\n getMirror(n) {\n if (this.mirror)\n for (let i = 0; i < this.mirror.length; i++)\n if (this.mirror[i] == n)\n return this.mirror[i + (i % 2 ? -1 : 1)];\n }\n /**\n @internal\n */\n setMirror(n, m) {\n if (!this.mirror)\n this.mirror = [];\n this.mirror.push(n, m);\n }\n /**\n Append the inverse of the given mapping to this one.\n */\n appendMappingInverted(mapping) {\n for (let i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);\n }\n }\n /**\n Create an inverted version of this mapping.\n */\n invert() {\n let inverse = new Mapping;\n inverse.appendMappingInverted(this);\n return inverse;\n }\n /**\n Map a position through this mapping.\n */\n map(pos, assoc = 1) {\n if (this.mirror)\n return this._map(pos, assoc, true);\n for (let i = this.from; i < this.to; i++)\n pos = this.maps[i].map(pos, assoc);\n return pos;\n }\n /**\n Map a position through this mapping, returning a mapping\n result.\n */\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let delInfo = 0;\n for (let i = this.from; i < this.to; i++) {\n let map = this.maps[i], result = map.mapResult(pos, assoc);\n if (result.recover != null) {\n let corr = this.getMirror(i);\n if (corr != null && corr > i && corr < this.to) {\n i = corr;\n pos = this.maps[corr].recover(result.recover);\n continue;\n }\n }\n delInfo |= result.delInfo;\n pos = result.pos;\n }\n return simple ? pos : new MapResult(pos, delInfo, null);\n }\n}\n\nconst stepsByID = Object.create(null);\n/**\nA step object represents an atomic change. It generally applies\nonly to the document it was created for, since the positions\nstored in it will only make sense for that document.\n\nNew steps are defined by creating classes that extend `Step`,\noverriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\nmethods, and registering your class with a unique\nJSON-serialization identifier using\n[`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).\n*/\nclass Step {\n /**\n Get the step map that represents the changes made by this step,\n and which can be used to transform between positions in the old\n and the new document.\n */\n getMap() { return StepMap.empty; }\n /**\n Try to merge this step with another one, to be applied directly\n after it. Returns the merged step when possible, null if the\n steps can't be merged.\n */\n merge(other) { return null; }\n /**\n Deserialize a step from its JSON representation. Will call\n through to the step class' own implementation of this method.\n */\n static fromJSON(schema, json) {\n if (!json || !json.stepType)\n throw new RangeError(\"Invalid input for Step.fromJSON\");\n let type = stepsByID[json.stepType];\n if (!type)\n throw new RangeError(`No step type ${json.stepType} defined`);\n return type.fromJSON(schema, json);\n }\n /**\n To be able to serialize steps to JSON, each step needs a string\n ID to attach to its JSON representation. Use this method to\n register an ID for your step classes. Try to pick something\n that's unlikely to clash with steps from other modules.\n */\n static jsonID(id, stepClass) {\n if (id in stepsByID)\n throw new RangeError(\"Duplicate use of step JSON ID \" + id);\n stepsByID[id] = stepClass;\n stepClass.prototype.jsonID = id;\n return stepClass;\n }\n}\n/**\nThe result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a\nnew document or a failure value.\n*/\nclass StepResult {\n /**\n @internal\n */\n constructor(\n /**\n The transformed document, if successful.\n */\n doc, \n /**\n The failure message, if unsuccessful.\n */\n failed) {\n this.doc = doc;\n this.failed = failed;\n }\n /**\n Create a successful step result.\n */\n static ok(doc) { return new StepResult(doc, null); }\n /**\n Create a failed step result.\n */\n static fail(message) { return new StepResult(null, message); }\n /**\n Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given\n arguments. Create a successful result if it succeeds, and a\n failed one if it throws a `ReplaceError`.\n */\n static fromReplace(doc, from, to, slice) {\n try {\n return StepResult.ok(doc.replace(from, to, slice));\n }\n catch (e) {\n if (e instanceof ReplaceError)\n return StepResult.fail(e.message);\n throw e;\n }\n }\n}\n\nfunction mapFragment(fragment, f, parent) {\n let mapped = [];\n for (let i = 0; i < fragment.childCount; i++) {\n let child = fragment.child(i);\n if (child.content.size)\n child = child.copy(mapFragment(child.content, f, child));\n if (child.isInline)\n child = f(child, parent, i);\n mapped.push(child);\n }\n return Fragment.fromArray(mapped);\n}\n/**\nAdd a mark to all inline content between two positions.\n*/\nclass AddMarkStep extends Step {\n /**\n Create a mark step.\n */\n constructor(\n /**\n The start of the marked range.\n */\n from, \n /**\n The end of the marked range.\n */\n to, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n let parent = $from.node($from.sharedDepth(this.to));\n let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {\n if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))\n return node;\n return node.mark(this.mark.addToSet(node.marks));\n }, parent), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new RemoveMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new AddMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof AddMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"addMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\");\n return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addMark\", AddMarkStep);\n/**\nRemove a mark from all inline content between two positions.\n*/\nclass RemoveMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The start of the unmarked range.\n */\n from, \n /**\n The end of the unmarked range.\n */\n to, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to);\n let slice = new Slice(mapFragment(oldSlice.content, node => {\n return node.mark(this.mark.removeFromSet(node.marks));\n }, doc), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new AddMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new RemoveMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof RemoveMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"removeMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\");\n return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeMark\", RemoveMarkStep);\n/**\nAdd a mark to a specific node.\n*/\nclass AddNodeMarkStep extends Step {\n /**\n Create a node mark step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (node) {\n let newSet = this.mark.addToSet(node.marks);\n if (newSet.length == node.marks.length) {\n for (let i = 0; i < node.marks.length; i++)\n if (!node.marks[i].isInSet(newSet))\n return new AddNodeMarkStep(this.pos, node.marks[i]);\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n }\n return new RemoveNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"addNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for AddNodeMarkStep.fromJSON\");\n return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addNodeMark\", AddNodeMarkStep);\n/**\nRemove a mark from a specific node.\n*/\nclass RemoveNodeMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node || !this.mark.isInSet(node.marks))\n return this;\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"removeNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for RemoveNodeMarkStep.fromJSON\");\n return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeNodeMark\", RemoveNodeMarkStep);\n\n/**\nReplace a part of the document with a slice of new content.\n*/\nclass ReplaceStep extends Step {\n /**\n The given `slice` should fit the 'gap' between `from` and\n `to`—the depths must line up, and the surrounding nodes must be\n able to be joined with the open sides of the slice. When\n `structure` is true, the step will fail if the content between\n from and to is not just a sequence of closing and then opening\n tokens (this is to guard against rebased replace steps\n overwriting something they weren't supposed to).\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The slice to insert.\n */\n slice, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.slice = slice;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && contentBetween(doc, this.from, this.to))\n return StepResult.fail(\"Structure replace would overwrite content\");\n return StepResult.fromReplace(doc, this.from, this.to, this.slice);\n }\n getMap() {\n return new StepMap([this.from, this.to - this.from, this.slice.size]);\n }\n invert(doc) {\n return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deletedAcross && to.deletedAcross)\n return null;\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice);\n }\n merge(other) {\n if (!(other instanceof ReplaceStep) || other.structure || this.structure)\n return null;\n if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);\n }\n else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n return new ReplaceStep(other.from, this.to, slice, this.structure);\n }\n else {\n return null;\n }\n }\n toJSON() {\n let json = { stepType: \"replace\", from: this.from, to: this.to };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\");\n return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);\n }\n}\nStep.jsonID(\"replace\", ReplaceStep);\n/**\nReplace a part of the document with a slice of content, but\npreserve a range of the replaced content by moving it into the\nslice.\n*/\nclass ReplaceAroundStep extends Step {\n /**\n Create a replace-around step with the given range and gap.\n `insert` should be the point in the slice into which the content\n of the gap should be moved. `structure` has the same meaning as\n it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The start of preserved range.\n */\n gapFrom, \n /**\n The end of preserved range.\n */\n gapTo, \n /**\n The slice to insert.\n */\n slice, \n /**\n The position in the slice where the preserved range should be\n inserted.\n */\n insert, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.gapFrom = gapFrom;\n this.gapTo = gapTo;\n this.slice = slice;\n this.insert = insert;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||\n contentBetween(doc, this.gapTo, this.to)))\n return StepResult.fail(\"Structure gap-replace would overwrite content\");\n let gap = doc.slice(this.gapFrom, this.gapTo);\n if (gap.openStart || gap.openEnd)\n return StepResult.fail(\"Gap is not a flat range\");\n let inserted = this.slice.insertAt(this.insert, gap.content);\n if (!inserted)\n return StepResult.fail(\"Content does not fit in gap\");\n return StepResult.fromReplace(doc, this.from, this.to, inserted);\n }\n getMap() {\n return new StepMap([this.from, this.gapFrom - this.from, this.insert,\n this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);\n }\n invert(doc) {\n let gap = this.gapTo - this.gapFrom;\n return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);\n let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);\n if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos)\n return null;\n return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);\n }\n toJSON() {\n let json = { stepType: \"replaceAround\", from: this.from, to: this.to,\n gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\" ||\n typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\")\n throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\");\n return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);\n }\n}\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\nfunction contentBetween(doc, from, to) {\n let $from = doc.resolve(from), dist = to - from, depth = $from.depth;\n while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n depth--;\n dist--;\n }\n if (dist > 0) {\n let next = $from.node(depth).maybeChild($from.indexAfter(depth));\n while (dist > 0) {\n if (!next || next.isLeaf)\n return true;\n next = next.firstChild;\n dist--;\n }\n }\n return false;\n}\n\nfunction addMark(tr, from, to, mark) {\n let removed = [], added = [];\n let removing, adding;\n tr.doc.nodesBetween(from, to, (node, pos, parent) => {\n if (!node.isInline)\n return;\n let marks = node.marks;\n if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n let newSet = mark.addToSet(marks);\n for (let i = 0; i < marks.length; i++) {\n if (!marks[i].isInSet(newSet)) {\n if (removing && removing.to == start && removing.mark.eq(marks[i]))\n removing.to = end;\n else\n removed.push(removing = new RemoveMarkStep(start, end, marks[i]));\n }\n }\n if (adding && adding.to == start)\n adding.to = end;\n else\n added.push(adding = new AddMarkStep(start, end, mark));\n }\n });\n removed.forEach(s => tr.step(s));\n added.forEach(s => tr.step(s));\n}\nfunction removeMark(tr, from, to, mark) {\n let matched = [], step = 0;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isInline)\n return;\n step++;\n let toRemove = null;\n if (mark instanceof MarkType) {\n let set = node.marks, found;\n while (found = mark.isInSet(set)) {\n (toRemove || (toRemove = [])).push(found);\n set = found.removeFromSet(set);\n }\n }\n else if (mark) {\n if (mark.isInSet(node.marks))\n toRemove = [mark];\n }\n else {\n toRemove = node.marks;\n }\n if (toRemove && toRemove.length) {\n let end = Math.min(pos + node.nodeSize, to);\n for (let i = 0; i < toRemove.length; i++) {\n let style = toRemove[i], found;\n for (let j = 0; j < matched.length; j++) {\n let m = matched[j];\n if (m.step == step - 1 && style.eq(matched[j].style))\n found = m;\n }\n if (found) {\n found.to = end;\n found.step = step;\n }\n else {\n matched.push({ style, from: Math.max(pos, from), to: end, step });\n }\n }\n }\n });\n matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));\n}\nfunction clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {\n let node = tr.doc.nodeAt(pos);\n let replSteps = [], cur = pos + 1;\n for (let i = 0; i < node.childCount; i++) {\n let child = node.child(i), end = cur + child.nodeSize;\n let allowed = match.matchType(child.type);\n if (!allowed) {\n replSteps.push(new ReplaceStep(cur, end, Slice.empty));\n }\n else {\n match = allowed;\n for (let j = 0; j < child.marks.length; j++)\n if (!parentType.allowsMarkType(child.marks[j].type))\n tr.step(new RemoveMarkStep(cur, end, child.marks[j]));\n if (clearNewlines && child.isText && parentType.whitespace != \"pre\") {\n let m, newline = /\\r?\\n|\\r/g, slice;\n while (m = newline.exec(child.text)) {\n if (!slice)\n slice = new Slice(Fragment.from(parentType.schema.text(\" \", parentType.allowedMarks(child.marks))), 0, 0);\n replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));\n }\n }\n }\n cur = end;\n }\n if (!match.validEnd) {\n let fill = match.fillBefore(Fragment.empty, true);\n tr.replace(cur, cur, new Slice(fill, 0, 0));\n }\n for (let i = replSteps.length - 1; i >= 0; i--)\n tr.step(replSteps[i]);\n}\n\nfunction canCut(node, start, end) {\n return (start == 0 || node.canReplace(start, node.childCount)) &&\n (end == node.childCount || node.canReplace(0, end));\n}\n/**\nTry to find a target depth to which the content in the given range\ncan be lifted. Will not go across\n[isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.\n*/\nfunction liftTarget(range) {\n let parent = range.parent;\n let content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n for (let depth = range.depth;; --depth) {\n let node = range.$from.node(depth);\n let index = range.$from.index(depth), endIndex = range.$to.indexAfter(depth);\n if (depth < range.depth && node.canReplace(index, endIndex, content))\n return depth;\n if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))\n break;\n }\n return null;\n}\nfunction lift(tr, range, target) {\n let { $from, $to, depth } = range;\n let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n let start = gapStart, end = gapEnd;\n let before = Fragment.empty, openStart = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $from.index(d) > 0) {\n splitting = true;\n before = Fragment.from($from.node(d).copy(before));\n openStart++;\n }\n else {\n start--;\n }\n let after = Fragment.empty, openEnd = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $to.after(d + 1) < $to.end(d)) {\n splitting = true;\n after = Fragment.from($to.node(d).copy(after));\n openEnd++;\n }\n else {\n end++;\n }\n tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));\n}\n/**\nTry to find a valid way to wrap the content in the given range in a\nnode of the given type. May introduce extra nodes around and inside\nthe wrapper node, if necessary. Returns null if no valid wrapping\ncould be found. When `innerRange` is given, that range's content is\nused as the content to fit into the wrapping, instead of the\ncontent of `range`.\n*/\nfunction findWrapping(range, nodeType, attrs = null, innerRange = range) {\n let around = findWrappingOutside(range, nodeType);\n let inner = around && findWrappingInside(innerRange, nodeType);\n if (!inner)\n return null;\n return around.map(withAttrs)\n .concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));\n}\nfunction withAttrs(type) { return { type, attrs: null }; }\nfunction findWrappingOutside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let around = parent.contentMatchAt(startIndex).findWrapping(type);\n if (!around)\n return null;\n let outer = around.length ? around[0] : type;\n return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;\n}\nfunction findWrappingInside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let inner = parent.child(startIndex);\n let inside = type.contentMatch.findWrapping(inner.type);\n if (!inside)\n return null;\n let lastType = inside.length ? inside[inside.length - 1] : type;\n let innerMatch = lastType.contentMatch;\n for (let i = startIndex; innerMatch && i < endIndex; i++)\n innerMatch = innerMatch.matchType(parent.child(i).type);\n if (!innerMatch || !innerMatch.validEnd)\n return null;\n return inside;\n}\nfunction wrap(tr, range, wrappers) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--) {\n if (content.size) {\n let match = wrappers[i].type.contentMatch.matchFragment(content);\n if (!match || !match.validEnd)\n throw new RangeError(\"Wrapper type given to Transform.wrap does not form valid content of its parent wrapper\");\n }\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n }\n let start = range.start, end = range.end;\n tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));\n}\nfunction setBlockType(tr, from, to, type, attrs) {\n if (!type.isTextblock)\n throw new RangeError(\"Type given to setBlockType should be a textblock\");\n let mapFrom = tr.steps.length;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n let attrsHere = typeof attrs == \"function\" ? attrs(node) : attrs;\n if (node.isTextblock && !node.hasMarkup(type, attrsHere) &&\n canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {\n let convertNewlines = null;\n if (type.schema.linebreakReplacement) {\n let pre = type.whitespace == \"pre\", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n // Ensure all markup that isn't allowed in the new node type is cleared\n if (convertNewlines === false)\n replaceLinebreaks(tr, node, pos, mapFrom);\n clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, undefined, convertNewlines === null);\n let mapping = tr.mapping.slice(mapFrom);\n let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));\n if (convertNewlines === true)\n replaceNewlines(tr, node, pos, mapFrom);\n return false;\n }\n });\n}\nfunction replaceNewlines(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.isText) {\n let m, newline = /\\r?\\n|\\r/g;\n while (m = newline.exec(child.text)) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);\n tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());\n }\n }\n });\n}\nfunction replaceLinebreaks(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.type == child.type.schema.linebreakReplacement) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);\n tr.replaceWith(start, start + 1, node.type.schema.text(\"\\n\"));\n }\n });\n}\nfunction canChangeType(doc, pos, type) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return $pos.parent.canReplaceWith(index, index + 1, type);\n}\n/**\nChange the type, attributes, and/or marks of the node at `pos`.\nWhen `type` isn't given, the existing node type is preserved,\n*/\nfunction setNodeMarkup(tr, pos, type, attrs, marks) {\n let node = tr.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at given position\");\n if (!type)\n type = node.type;\n let newNode = type.create(attrs, null, marks || node.marks);\n if (node.isLeaf)\n return tr.replaceWith(pos, pos + node.nodeSize, newNode);\n if (!type.validContent(node.content))\n throw new RangeError(\"Invalid content for node type \" + type.name);\n tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));\n}\n/**\nCheck whether splitting at the given position is allowed.\n*/\nfunction canSplit(doc, pos, depth = 1, typesAfter) {\n let $pos = doc.resolve(pos), base = $pos.depth - depth;\n let innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;\n if (base < 0 || $pos.parent.type.spec.isolating ||\n !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||\n !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))\n return false;\n for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n let node = $pos.node(d), index = $pos.index(d);\n if (node.type.spec.isolating)\n return false;\n let rest = node.content.cutByIndex(index, node.childCount);\n let overrideChild = typesAfter && typesAfter[i + 1];\n if (overrideChild)\n rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));\n let after = (typesAfter && typesAfter[i]) || node;\n if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest))\n return false;\n }\n let index = $pos.indexAfter(base);\n let baseType = typesAfter && typesAfter[0];\n return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);\n}\nfunction split(tr, pos, depth = 1, typesAfter) {\n let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n before = Fragment.from($pos.node(d).copy(before));\n let typeAfter = typesAfter && typesAfter[i];\n after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n }\n tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));\n}\n/**\nTest whether the blocks before and after a given position can be\njoined.\n*/\nfunction canJoin(doc, pos) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n $pos.parent.canReplace(index, index + 1);\n}\nfunction canAppendWithSubstitutedLinebreaks(a, b) {\n if (!b.content.size)\n a.type.compatibleContent(b.type);\n let match = a.contentMatchAt(a.childCount);\n let { linebreakReplacement } = a.type.schema;\n for (let i = 0; i < b.childCount; i++) {\n let child = b.child(i);\n let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;\n match = match.matchType(type);\n if (!match)\n return false;\n if (!a.type.allowsMarks(child.marks))\n return false;\n }\n return match.validEnd;\n}\nfunction joinable(a, b) {\n return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));\n}\n/**\nFind an ancestor of the given position that can be joined to the\nblock before (or after if `dir` is positive). Returns the joinable\npoint, if any.\n*/\nfunction joinPoint(doc, pos, dir = -1) {\n let $pos = doc.resolve(pos);\n for (let d = $pos.depth;; d--) {\n let before, after, index = $pos.index(d);\n if (d == $pos.depth) {\n before = $pos.nodeBefore;\n after = $pos.nodeAfter;\n }\n else if (dir > 0) {\n before = $pos.node(d + 1);\n index++;\n after = $pos.node(d).maybeChild(index);\n }\n else {\n before = $pos.node(d).maybeChild(index - 1);\n after = $pos.node(d + 1);\n }\n if (before && !before.isTextblock && joinable(before, after) &&\n $pos.node(d).canReplace(index, index + 1))\n return pos;\n if (d == 0)\n break;\n pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n }\n}\nfunction join(tr, pos, depth) {\n let convertNewlines = null;\n let { linebreakReplacement } = tr.doc.type.schema;\n let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;\n if (linebreakReplacement && beforeType.inlineContent) {\n let pre = beforeType.whitespace == \"pre\";\n let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n let mapFrom = tr.steps.length;\n if (convertNewlines === false) {\n let $after = tr.doc.resolve(pos + depth);\n replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);\n }\n if (beforeType.inlineContent)\n clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);\n let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);\n tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));\n if (convertNewlines === true) {\n let $full = tr.doc.resolve(start);\n replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);\n }\n return tr;\n}\n/**\nTry to find a point where a node of the given type can be inserted\nnear `pos`, by searching up the node hierarchy when `pos` itself\nisn't a valid place but is at the start or end of a node. Return\nnull if no position was found.\n*/\nfunction insertPoint(doc, pos, nodeType) {\n let $pos = doc.resolve(pos);\n if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))\n return pos;\n if ($pos.parentOffset == 0)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.index(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.before(d + 1);\n if (index > 0)\n return null;\n }\n if ($pos.parentOffset == $pos.parent.content.size)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.indexAfter(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.after(d + 1);\n if (index < $pos.node(d).childCount)\n return null;\n }\n return null;\n}\n/**\nFinds a position at or around the given position where the given\nslice can be inserted. Will look at parent nodes' nearest boundary\nand try there, even if the original position wasn't directly at the\nstart or end of that node. Returns null when no position was found.\n*/\nfunction dropPoint(doc, pos, slice) {\n let $pos = doc.resolve(pos);\n if (!slice.content.size)\n return pos;\n let content = slice.content;\n for (let i = 0; i < slice.openStart; i++)\n content = content.firstChild.content;\n for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n for (let d = $pos.depth; d >= 0; d--) {\n let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n let parent = $pos.node(d), fits = false;\n if (pass == 1) {\n fits = parent.canReplace(insertPos, insertPos, content);\n }\n else {\n let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);\n fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);\n }\n if (fits)\n return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);\n }\n }\n return null;\n}\n\n/**\n‘Fit’ a slice into a given position in the document, producing a\n[step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if\nthere's no meaningful way to insert the slice here, or inserting it\nwould be a no-op (an empty slice over an empty range).\n*/\nfunction replaceStep(doc, from, to = from, slice = Slice.empty) {\n if (from == to && !slice.size)\n return null;\n let $from = doc.resolve(from), $to = doc.resolve(to);\n // Optimization -- avoid work if it's obvious that it's not needed.\n if (fitsTrivially($from, $to, slice))\n return new ReplaceStep(from, to, slice);\n return new Fitter($from, $to, slice).fit();\n}\nfunction fitsTrivially($from, $to, slice) {\n return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&\n $from.parent.canReplace($from.index(), $to.index(), slice.content);\n}\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in , when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n// - `frontier` holds a stack of `{type, match}` objects that\n// represent the open side of the replacement. It starts at\n// `$from`, then moves forward as content is placed, and is finally\n// reconciled with `$to`.\n//\n// - `unplaced` is a slice that represents the content that hasn't\n// been placed yet.\n//\n// - `placed` is a fragment of placed content. Its open-start value\n// is implicit in `$from`, and its open-end value in `frontier`.\nclass Fitter {\n constructor($from, $to, unplaced) {\n this.$from = $from;\n this.$to = $to;\n this.unplaced = unplaced;\n this.frontier = [];\n this.placed = Fragment.empty;\n for (let i = 0; i <= $from.depth; i++) {\n let node = $from.node(i);\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt($from.indexAfter(i))\n });\n }\n for (let i = $from.depth; i > 0; i--)\n this.placed = Fragment.from($from.node(i).copy(this.placed));\n }\n get depth() { return this.frontier.length - 1; }\n fit() {\n // As long as there's unplaced content, try to place some of it.\n // If that fails, either increase the open score of the unplaced\n // slice, or drop nodes from it, and then try again.\n while (this.unplaced.size) {\n let fit = this.findFittable();\n if (fit)\n this.placeNodes(fit);\n else\n this.openMore() || this.dropNode();\n }\n // When there's inline content directly after the frontier _and_\n // directly after `this.$to`, we must generate a `ReplaceAround`\n // step that pulls that content into the node after the frontier.\n // That means the fitting must be done to the end of the textblock\n // node after `this.$to`, not `this.$to` itself.\n let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n if (!$to)\n return null;\n // If closing to `$to` succeeded, create a step\n let content = this.placed, openStart = $from.depth, openEnd = $to.depth;\n while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes\n content = content.firstChild.content;\n openStart--;\n openEnd--;\n }\n let slice = new Slice(content, openStart, openEnd);\n if (moveInline > -1)\n return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);\n if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps\n return new ReplaceStep($from.pos, $to.pos, slice);\n return null;\n }\n // Find a position on the start spine of `this.unplaced` that has\n // content that can be moved somewhere on the frontier. Returns two\n // depths, one for the slice and one for the frontier.\n findFittable() {\n let startDepth = this.unplaced.openStart;\n for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {\n let node = cur.firstChild;\n if (cur.childCount > 1)\n openEnd = 0;\n if (node.type.spec.isolating && openEnd <= d) {\n startDepth = d;\n break;\n }\n cur = node.content;\n }\n // Only try wrapping nodes (pass 2) after finding a place without\n // wrapping failed.\n for (let pass = 1; pass <= 2; pass++) {\n for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n let fragment, parent = null;\n if (sliceDepth) {\n parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n fragment = parent.content;\n }\n else {\n fragment = this.unplaced.content;\n }\n let first = fragment.firstChild;\n for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n let { type, match } = this.frontier[frontierDepth], wrap, inject = null;\n // In pass 1, if the next node matches, or there is no next\n // node but the parents look compatible, we've found a\n // place.\n if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))\n : parent && type.compatibleContent(parent.type)))\n return { sliceDepth, frontierDepth, parent, inject };\n // In pass 2, look for a set of wrapping nodes that make\n // `first` fit here.\n else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))\n return { sliceDepth, frontierDepth, parent, wrap };\n // Don't continue looking further up if the parent node\n // would fit here.\n if (parent && match.matchType(parent.type))\n break;\n }\n }\n }\n }\n openMore() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (!inner.childCount || inner.firstChild.isLeaf)\n return false;\n this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));\n return true;\n }\n dropNode() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (inner.childCount <= 1 && openStart > 0) {\n let openAtEnd = content.size - openStart <= openStart + inner.size;\n this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);\n }\n else {\n this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n }\n }\n // Move content from the unplaced slice at `sliceDepth` to the\n // frontier node at `frontierDepth`. Close that frontier node when\n // applicable.\n placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {\n while (this.depth > frontierDepth)\n this.closeFrontierNode();\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n this.openFrontierNode(wrap[i]);\n let slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n let openStart = slice.openStart - sliceDepth;\n let taken = 0, add = [];\n let { match, type } = this.frontier[frontierDepth];\n if (inject) {\n for (let i = 0; i < inject.childCount; i++)\n add.push(inject.child(i));\n match = match.matchFragment(inject);\n }\n // Computes the amount of (end) open nodes at the end of the\n // fragment. When 0, the parent is open, but no more. When\n // negative, nothing is open.\n let openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);\n // Scan over the fragment, fitting as many child nodes as\n // possible.\n while (taken < fragment.childCount) {\n let next = fragment.child(taken), matches = match.matchType(next.type);\n if (!matches)\n break;\n taken++;\n if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes\n match = matches;\n add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));\n }\n }\n let toEnd = taken == fragment.childCount;\n if (!toEnd)\n openEndCount = -1;\n this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n this.frontier[frontierDepth].match = match;\n // If the parent types match, and the entire node was moved, and\n // it's not open, close this frontier node right away.\n if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)\n this.closeFrontierNode();\n // Add new frontier nodes for any open nodes at the end.\n for (let i = 0, cur = fragment; i < openEndCount; i++) {\n let node = cur.lastChild;\n this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });\n cur = node.content;\n }\n // Update `this.unplaced`. Drop the entire node from which we\n // placed it we got to its end, otherwise just drop the placed\n // nodes.\n this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd)\n : sliceDepth == 0 ? Slice.empty\n : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n }\n mustMoveInline() {\n if (!this.$to.parent.isTextblock)\n return -1;\n let top = this.frontier[this.depth], level;\n if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||\n (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth))\n return -1;\n let { depth } = this.$to, after = this.$to.after(depth);\n while (depth > 1 && after == this.$to.end(--depth))\n ++after;\n return after;\n }\n findCloseLevel($to) {\n scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n let { match, type } = this.frontier[i];\n let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n let fit = contentAfterFits($to, i, type, match, dropInner);\n if (!fit)\n continue;\n for (let d = i - 1; d >= 0; d--) {\n let { match, type } = this.frontier[d];\n let matches = contentAfterFits($to, d, type, match, true);\n if (!matches || matches.childCount)\n continue scan;\n }\n return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };\n }\n }\n close($to) {\n let close = this.findCloseLevel($to);\n if (!close)\n return null;\n while (this.depth > close.depth)\n this.closeFrontierNode();\n if (close.fit.childCount)\n this.placed = addToFragment(this.placed, close.depth, close.fit);\n $to = close.move;\n for (let d = close.depth + 1; d <= $to.depth; d++) {\n let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n this.openFrontierNode(node.type, node.attrs, add);\n }\n return $to;\n }\n openFrontierNode(type, attrs = null, content) {\n let top = this.frontier[this.depth];\n top.match = top.match.matchType(type);\n this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n this.frontier.push({ type, match: type.contentMatch });\n }\n closeFrontierNode() {\n let open = this.frontier.pop();\n let add = open.match.fillBefore(Fragment.empty, true);\n if (add.childCount)\n this.placed = addToFragment(this.placed, this.frontier.length, add);\n }\n}\nfunction dropFromFragment(fragment, depth, count) {\n if (depth == 0)\n return fragment.cutByIndex(count, fragment.childCount);\n return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));\n}\nfunction addToFragment(fragment, depth, content) {\n if (depth == 0)\n return fragment.append(content);\n return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));\n}\nfunction contentAt(fragment, depth) {\n for (let i = 0; i < depth; i++)\n fragment = fragment.firstChild.content;\n return fragment;\n}\nfunction closeNodeStart(node, openStart, openEnd) {\n if (openStart <= 0)\n return node;\n let frag = node.content;\n if (openStart > 1)\n frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));\n if (openStart > 0) {\n frag = node.type.contentMatch.fillBefore(frag).append(frag);\n if (openEnd <= 0)\n frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));\n }\n return node.copy(frag);\n}\nfunction contentAfterFits($to, depth, type, match, open) {\n let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n if (index == node.childCount && !type.compatibleContent(node.type))\n return null;\n let fit = match.fillBefore(node.content, true, index);\n return fit && !invalidMarks(type, node.content, index) ? fit : null;\n}\nfunction invalidMarks(type, fragment, start) {\n for (let i = start; i < fragment.childCount; i++)\n if (!type.allowsMarks(fragment.child(i).marks))\n return true;\n return false;\n}\nfunction definesContent(type) {\n return type.spec.defining || type.spec.definingForContent;\n}\nfunction replaceRange(tr, from, to, slice) {\n if (!slice.size)\n return tr.deleteRange(from, to);\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n if (fitsTrivially($from, $to, slice))\n return tr.step(new ReplaceStep(from, to, slice));\n let targetDepths = coveredDepths($from, tr.doc.resolve(to));\n // Can't replace the whole document, so remove 0 if it's present\n if (targetDepths[targetDepths.length - 1] == 0)\n targetDepths.pop();\n // Negative numbers represent not expansion over the whole node at\n // that depth, but replacing from $from.before(-D) to $to.pos.\n let preferredTarget = -($from.depth + 1);\n targetDepths.unshift(preferredTarget);\n // This loop picks a preferred target depth, if one of the covering\n // depths is not outside of a defining node, and adds negative\n // depths for any depth that has $from at its start and does not\n // cross a defining node.\n for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n let spec = $from.node(d).type.spec;\n if (spec.defining || spec.definingAsContext || spec.isolating)\n break;\n if (targetDepths.indexOf(d) > -1)\n preferredTarget = d;\n else if ($from.before(d) == pos)\n targetDepths.splice(1, 0, -d);\n }\n // Try to fit each possible depth of the slice into each possible\n // target depth, starting with the preferred depths.\n let preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n let leftNodes = [], preferredDepth = slice.openStart;\n for (let content = slice.content, i = 0;; i++) {\n let node = content.firstChild;\n leftNodes.push(node);\n if (i == slice.openStart)\n break;\n content = node.content;\n }\n // Back up preferredDepth to cover defining textblocks directly\n // above it, possibly skipping a non-defining textblock.\n for (let d = preferredDepth - 1; d >= 0; d--) {\n let leftNode = leftNodes[d], def = definesContent(leftNode.type);\n if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))\n preferredDepth = d;\n else if (def || !leftNode.type.isTextblock)\n break;\n }\n for (let j = slice.openStart; j >= 0; j--) {\n let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n let insert = leftNodes[openDepth];\n if (!insert)\n continue;\n for (let i = 0; i < targetDepths.length; i++) {\n // Loop over possible expansion levels, starting with the\n // preferred one\n let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;\n if (targetDepth < 0) {\n expand = false;\n targetDepth = -targetDepth;\n }\n let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));\n }\n }\n let startSteps = tr.steps.length;\n for (let i = targetDepths.length - 1; i >= 0; i--) {\n tr.replace(from, to, slice);\n if (tr.steps.length > startSteps)\n break;\n let depth = targetDepths[i];\n if (depth < 0)\n continue;\n from = $from.before(depth);\n to = $to.after(depth);\n }\n}\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n if (depth < oldOpen) {\n let first = fragment.firstChild;\n fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n }\n if (depth > newOpen) {\n let match = parent.contentMatchAt(0);\n let start = match.fillBefore(fragment).append(fragment);\n fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n }\n return fragment;\n}\nfunction replaceRangeWith(tr, from, to, node) {\n if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {\n let point = insertPoint(tr.doc, from, node.type);\n if (point != null)\n from = to = point;\n }\n tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));\n}\nfunction deleteRange(tr, from, to) {\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n let covered = coveredDepths($from, $to);\n for (let i = 0; i < covered.length; i++) {\n let depth = covered[i], last = i == covered.length - 1;\n if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n return tr.delete($from.start(depth), $to.end(depth));\n if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))\n return tr.delete($from.before(depth), $to.after(depth));\n }\n for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {\n if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d &&\n $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))\n return tr.delete($from.before(d), to);\n }\n tr.delete(from, to);\n}\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n let result = [], minDepth = Math.min($from.depth, $to.depth);\n for (let d = minDepth; d >= 0; d--) {\n let start = $from.start(d);\n if (start < $from.pos - ($from.depth - d) ||\n $to.end(d) > $to.pos + ($to.depth - d) ||\n $from.node(d).type.spec.isolating ||\n $to.node(d).type.spec.isolating)\n break;\n if (start == $to.start(d) ||\n (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&\n d && $to.start(d - 1) == start - 1))\n result.push(d);\n }\n return result;\n}\n\n/**\nUpdate an attribute in a specific node.\n*/\nclass AttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.pos = pos;\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at attribute step's position\");\n let attrs = Object.create(null);\n for (let name in node.attrs)\n attrs[name] = node.attrs[name];\n attrs[this.attr] = this.value;\n let updated = node.type.create(attrs, null, node.marks);\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);\n }\n toJSON() {\n return { stepType: \"attr\", pos: this.pos, attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\" || typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for AttrStep.fromJSON\");\n return new AttrStep(json.pos, json.attr, json.value);\n }\n}\nStep.jsonID(\"attr\", AttrStep);\n/**\nUpdate an attribute in the doc node.\n*/\nclass DocAttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let attrs = Object.create(null);\n for (let name in doc.attrs)\n attrs[name] = doc.attrs[name];\n attrs[this.attr] = this.value;\n let updated = doc.type.create(attrs, doc.content, doc.marks);\n return StepResult.ok(updated);\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new DocAttrStep(this.attr, doc.attrs[this.attr]);\n }\n map(mapping) {\n return this;\n }\n toJSON() {\n return { stepType: \"docAttr\", attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for DocAttrStep.fromJSON\");\n return new DocAttrStep(json.attr, json.value);\n }\n}\nStep.jsonID(\"docAttr\", DocAttrStep);\n\n/**\n@internal\n*/\nlet TransformError = class extends Error {\n};\nTransformError = function TransformError(message) {\n let err = Error.call(this, message);\n err.__proto__ = TransformError.prototype;\n return err;\n};\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n/**\nAbstraction to build up and track an array of\n[steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.\n\nMost transforming methods return the `Transform` object itself, so\nthat they can be chained.\n*/\nclass Transform {\n /**\n Create a transform that starts with the given document.\n */\n constructor(\n /**\n The current document (the result of applying the steps in the\n transform).\n */\n doc) {\n this.doc = doc;\n /**\n The steps in this transform.\n */\n this.steps = [];\n /**\n The documents before each of the steps.\n */\n this.docs = [];\n /**\n A mapping with the maps for each of the steps in this transform.\n */\n this.mapping = new Mapping;\n }\n /**\n The starting document.\n */\n get before() { return this.docs.length ? this.docs[0] : this.doc; }\n /**\n Apply a new step in this transform, saving the result. Throws an\n error when the step fails.\n */\n step(step) {\n let result = this.maybeStep(step);\n if (result.failed)\n throw new TransformError(result.failed);\n return this;\n }\n /**\n Try to apply a step in this transformation, ignoring it if it\n fails. Returns the step result.\n */\n maybeStep(step) {\n let result = step.apply(this.doc);\n if (!result.failed)\n this.addStep(step, result.doc);\n return result;\n }\n /**\n True when the document has been changed (when there are any\n steps).\n */\n get docChanged() {\n return this.steps.length > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n this.docs.push(this.doc);\n this.steps.push(step);\n this.mapping.appendMap(step.getMap());\n this.doc = doc;\n }\n /**\n Replace the part of the document between `from` and `to` with the\n given `slice`.\n */\n replace(from, to = from, slice = Slice.empty) {\n let step = replaceStep(this.doc, from, to, slice);\n if (step)\n this.step(step);\n return this;\n }\n /**\n Replace the given range with the given content, which may be a\n fragment, node, or array of nodes.\n */\n replaceWith(from, to, content) {\n return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));\n }\n /**\n Delete the content between the given positions.\n */\n delete(from, to) {\n return this.replace(from, to, Slice.empty);\n }\n /**\n Insert the given content at the given position.\n */\n insert(pos, content) {\n return this.replaceWith(pos, pos, content);\n }\n /**\n Replace a range of the document with a given slice, using\n `from`, `to`, and the slice's\n [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather\n than fixed start and end points. This method may grow the\n replaced area or close open nodes in the slice in order to get a\n fit that is more in line with WYSIWYG expectations, by dropping\n fully covered parent nodes of the replaced region when they are\n marked [non-defining as\n context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an\n open parent node from the slice that _is_ marked as [defining\n its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n \n This is the method, for example, to handle paste. The similar\n [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more\n primitive tool which will _not_ move the start and end of its given\n range, and is useful in situations where you need more precise\n control over what happens.\n */\n replaceRange(from, to, slice) {\n replaceRange(this, from, to, slice);\n return this;\n }\n /**\n Replace the given range with a node, but use `from` and `to` as\n hints, rather than precise positions. When from and to are the same\n and are at the start or end of a parent node in which the given\n node doesn't fit, this method may _move_ them out towards a parent\n that does allow the given node to be placed. When the given range\n completely covers a parent node, this method may completely replace\n that parent node.\n */\n replaceRangeWith(from, to, node) {\n replaceRangeWith(this, from, to, node);\n return this;\n }\n /**\n Delete the given range, expanding it to cover fully covered\n parent nodes until a valid replace is found.\n */\n deleteRange(from, to) {\n deleteRange(this, from, to);\n return this;\n }\n /**\n Split the content in the given range off from its parent, if there\n is sibling content before or after it, and move it up the tree to\n the depth specified by `target`. You'll probably want to use\n [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make\n sure the lift is valid.\n */\n lift(range, target) {\n lift(this, range, target);\n return this;\n }\n /**\n Join the blocks around the given position. If depth is 2, their\n last and first siblings are also joined, and so on.\n */\n join(pos, depth = 1) {\n join(this, pos, depth);\n return this;\n }\n /**\n Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.\n The wrappers are assumed to be valid in this position, and should\n probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).\n */\n wrap(range, wrappers) {\n wrap(this, range, wrappers);\n return this;\n }\n /**\n Set the type of all textblocks (partly) between `from` and `to` to\n the given node type with the given attributes.\n */\n setBlockType(from, to = from, type, attrs = null) {\n setBlockType(this, from, to, type, attrs);\n return this;\n }\n /**\n Change the type, attributes, and/or marks of the node at `pos`.\n When `type` isn't given, the existing node type is preserved,\n */\n setNodeMarkup(pos, type, attrs = null, marks) {\n setNodeMarkup(this, pos, type, attrs, marks);\n return this;\n }\n /**\n Set a single attribute on a given node to a new value.\n The `pos` addresses the document content. Use `setDocAttribute`\n to set attributes on the document itself.\n */\n setNodeAttribute(pos, attr, value) {\n this.step(new AttrStep(pos, attr, value));\n return this;\n }\n /**\n Set a single attribute on the document to a new value.\n */\n setDocAttribute(attr, value) {\n this.step(new DocAttrStep(attr, value));\n return this;\n }\n /**\n Add a mark to the node at position `pos`.\n */\n addNodeMark(pos, mark) {\n this.step(new AddNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Remove a mark (or a mark of the given type) from the node at\n position `pos`.\n */\n removeNodeMark(pos, mark) {\n if (!(mark instanceof Mark)) {\n let node = this.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at position \" + pos);\n mark = mark.isInSet(node.marks);\n if (!mark)\n return this;\n }\n this.step(new RemoveNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Split the node at the given position, and optionally, if `depth` is\n greater than one, any number of nodes above that. By default, the\n parts split off will inherit the node type of the original node.\n This can be changed by passing an array of types and attributes to\n use after the split.\n */\n split(pos, depth = 1, typesAfter) {\n split(this, pos, depth, typesAfter);\n return this;\n }\n /**\n Add the given mark to the inline content between `from` and `to`.\n */\n addMark(from, to, mark) {\n addMark(this, from, to, mark);\n return this;\n }\n /**\n Remove marks from inline nodes between `from` and `to`. When\n `mark` is a single mark, remove precisely that mark. When it is\n a mark type, remove all marks of that type. When it is null,\n remove all marks of any type.\n */\n removeMark(from, to, mark) {\n removeMark(this, from, to, mark);\n return this;\n }\n /**\n Removes all marks and nodes from the content of the node at\n `pos` that don't match the given new parent node type. Accepts\n an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as\n third argument.\n */\n clearIncompatible(pos, parentType, match) {\n clearIncompatible(this, pos, parentType, match);\n return this;\n }\n}\n\nexport { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n","import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nconst classesById = Object.create(null);\n/**\nSuperclass for editor selections. Every selection type should\nextend this. Should not be instantiated directly.\n*/\nclass Selection {\n /**\n Initialize a selection with the head and anchor and ranges. If no\n ranges are given, constructs a single range across `$anchor` and\n `$head`.\n */\n constructor(\n /**\n The resolved anchor of the selection (the side that stays in\n place when the selection is modified).\n */\n $anchor, \n /**\n The resolved head of the selection (the side that moves when\n the selection is modified).\n */\n $head, ranges) {\n this.$anchor = $anchor;\n this.$head = $head;\n this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n }\n /**\n The selection's anchor, as an unresolved position.\n */\n get anchor() { return this.$anchor.pos; }\n /**\n The selection's head.\n */\n get head() { return this.$head.pos; }\n /**\n The lower bound of the selection's main range.\n */\n get from() { return this.$from.pos; }\n /**\n The upper bound of the selection's main range.\n */\n get to() { return this.$to.pos; }\n /**\n The resolved lower bound of the selection's main range.\n */\n get $from() {\n return this.ranges[0].$from;\n }\n /**\n The resolved upper bound of the selection's main range.\n */\n get $to() {\n return this.ranges[0].$to;\n }\n /**\n Indicates whether the selection contains any content.\n */\n get empty() {\n let ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++)\n if (ranges[i].$from.pos != ranges[i].$to.pos)\n return false;\n return true;\n }\n /**\n Get the content of this selection as a slice.\n */\n content() {\n return this.$from.doc.slice(this.from, this.to, true);\n }\n /**\n Replace the selection with a slice or, if no slice is given,\n delete the selection. Will append to the given transaction.\n */\n replace(tr, content = Slice.empty) {\n // Put the new selection at the position after the inserted\n // content. When that ended in an inline node, search backwards,\n // to get the position after that node. If not, search forward.\n let lastNode = content.content.lastChild, lastParent = null;\n for (let i = 0; i < content.openEnd; i++) {\n lastParent = lastNode;\n lastNode = lastNode.lastChild;\n }\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);\n if (i == 0)\n selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);\n }\n }\n /**\n Replace the selection with the given node, appending the changes\n to the given transaction.\n */\n replaceWith(tr, node) {\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n let from = mapping.map($from.pos), to = mapping.map($to.pos);\n if (i) {\n tr.deleteRange(from, to);\n }\n else {\n tr.replaceRangeWith(from, to, node);\n selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n }\n }\n }\n /**\n Find a valid cursor or leaf node selection starting at the given\n position and searching back if `dir` is negative, and forward if\n positive. When `textOnly` is true, only consider cursor\n selections. Will return null when no valid selection position is\n found.\n */\n static findFrom($pos, dir, textOnly = false) {\n let inner = $pos.parent.inlineContent ? new TextSelection($pos)\n : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n if (inner)\n return inner;\n for (let depth = $pos.depth - 1; depth >= 0; depth--) {\n let found = dir < 0\n ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)\n : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n if (found)\n return found;\n }\n return null;\n }\n /**\n Find a valid cursor or leaf node selection near the given\n position. Searches forward first by default, but if `bias` is\n negative, it will search backwards first.\n */\n static near($pos, bias = 1) {\n return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));\n }\n /**\n Find the cursor or leaf node selection closest to the start of\n the given document. Will return an\n [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position\n exists.\n */\n static atStart(doc) {\n return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);\n }\n /**\n Find the cursor or leaf node selection closest to the end of the\n given document.\n */\n static atEnd(doc) {\n return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);\n }\n /**\n Deserialize the JSON representation of a selection. Must be\n implemented for custom classes (as a static class method).\n */\n static fromJSON(doc, json) {\n if (!json || !json.type)\n throw new RangeError(\"Invalid input for Selection.fromJSON\");\n let cls = classesById[json.type];\n if (!cls)\n throw new RangeError(`No selection type ${json.type} defined`);\n return cls.fromJSON(doc, json);\n }\n /**\n To be able to deserialize selections from JSON, custom selection\n classes must register themselves with an ID string, so that they\n can be disambiguated. Try to pick something that's unlikely to\n clash with classes from other modules.\n */\n static jsonID(id, selectionClass) {\n if (id in classesById)\n throw new RangeError(\"Duplicate use of selection JSON ID \" + id);\n classesById[id] = selectionClass;\n selectionClass.prototype.jsonID = id;\n return selectionClass;\n }\n /**\n Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,\n which is a value that can be mapped without having access to a\n current document, and later resolved to a real selection for a\n given document again. (This is used mostly by the history to\n track and restore old selections.) The default implementation of\n this method just converts the selection to a text selection and\n returns the bookmark for that.\n */\n getBookmark() {\n return TextSelection.between(this.$anchor, this.$head).getBookmark();\n }\n}\nSelection.prototype.visible = true;\n/**\nRepresents a selected range in a document.\n*/\nclass SelectionRange {\n /**\n Create a range.\n */\n constructor(\n /**\n The lower bound of the range.\n */\n $from, \n /**\n The upper bound of the range.\n */\n $to) {\n this.$from = $from;\n this.$to = $to;\n }\n}\nlet warnedAboutTextSelection = false;\nfunction checkTextSelection($pos) {\n if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {\n warnedAboutTextSelection = true;\n console[\"warn\"](\"TextSelection endpoint not pointing into a node with inline content (\" + $pos.parent.type.name + \")\");\n }\n}\n/**\nA text selection represents a classical editor selection, with a\nhead (the moving side) and anchor (immobile side), both of which\npoint into textblock nodes. It can be empty (a regular cursor\nposition).\n*/\nclass TextSelection extends Selection {\n /**\n Construct a text selection between the given points.\n */\n constructor($anchor, $head = $anchor) {\n checkTextSelection($anchor);\n checkTextSelection($head);\n super($anchor, $head);\n }\n /**\n Returns a resolved position if this is a cursor selection (an\n empty text selection), and null otherwise.\n */\n get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }\n map(doc, mapping) {\n let $head = doc.resolve(mapping.map(this.head));\n if (!$head.parent.inlineContent)\n return Selection.near($head);\n let $anchor = doc.resolve(mapping.map(this.anchor));\n return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);\n }\n replace(tr, content = Slice.empty) {\n super.replace(tr, content);\n if (content == Slice.empty) {\n let marks = this.$from.marksAcross(this.$to);\n if (marks)\n tr.ensureMarks(marks);\n }\n }\n eq(other) {\n return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;\n }\n getBookmark() {\n return new TextBookmark(this.anchor, this.head);\n }\n toJSON() {\n return { type: \"text\", anchor: this.anchor, head: this.head };\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\" || typeof json.head != \"number\")\n throw new RangeError(\"Invalid input for TextSelection.fromJSON\");\n return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n }\n /**\n Create a text selection from non-resolved positions.\n */\n static create(doc, anchor, head = anchor) {\n let $anchor = doc.resolve(anchor);\n return new this($anchor, head == anchor ? $anchor : doc.resolve(head));\n }\n /**\n Return a text selection that spans the given positions or, if\n they aren't text positions, find a text selection near them.\n `bias` determines whether the method searches forward (default)\n or backwards (negative number) first. Will fall back to calling\n [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document\n doesn't contain a valid text position.\n */\n static between($anchor, $head, bias) {\n let dPos = $anchor.pos - $head.pos;\n if (!bias || dPos)\n bias = dPos >= 0 ? 1 : -1;\n if (!$head.parent.inlineContent) {\n let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n if (found)\n $head = found.$head;\n else\n return Selection.near($head, bias);\n }\n if (!$anchor.parent.inlineContent) {\n if (dPos == 0) {\n $anchor = $head;\n }\n else {\n $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n if (($anchor.pos < $head.pos) != (dPos < 0))\n $anchor = $head;\n }\n }\n return new TextSelection($anchor, $head);\n }\n}\nSelection.jsonID(\"text\", TextSelection);\nclass TextBookmark {\n constructor(anchor, head) {\n this.anchor = anchor;\n this.head = head;\n }\n map(mapping) {\n return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));\n }\n resolve(doc) {\n return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));\n }\n}\n/**\nA node selection is a selection that points at a single node. All\nnodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the\ntarget of a node selection. In such a selection, `from` and `to`\npoint directly before and after the selected node, `anchor` equals\n`from`, and `head` equals `to`..\n*/\nclass NodeSelection extends Selection {\n /**\n Create a node selection. Does not verify the validity of its\n argument.\n */\n constructor($pos) {\n let node = $pos.nodeAfter;\n let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n super($pos, $end);\n this.node = node;\n }\n map(doc, mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n let $pos = doc.resolve(pos);\n if (deleted)\n return Selection.near($pos);\n return new NodeSelection($pos);\n }\n content() {\n return new Slice(Fragment.from(this.node), 0, 0);\n }\n eq(other) {\n return other instanceof NodeSelection && other.anchor == this.anchor;\n }\n toJSON() {\n return { type: \"node\", anchor: this.anchor };\n }\n getBookmark() { return new NodeBookmark(this.anchor); }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\")\n throw new RangeError(\"Invalid input for NodeSelection.fromJSON\");\n return new NodeSelection(doc.resolve(json.anchor));\n }\n /**\n Create a node selection from non-resolved positions.\n */\n static create(doc, from) {\n return new NodeSelection(doc.resolve(from));\n }\n /**\n Determines whether the given node may be selected as a node\n selection.\n */\n static isSelectable(node) {\n return !node.isText && node.type.spec.selectable !== false;\n }\n}\nNodeSelection.prototype.visible = false;\nSelection.jsonID(\"node\", NodeSelection);\nclass NodeBookmark {\n constructor(anchor) {\n this.anchor = anchor;\n }\n map(mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);\n }\n resolve(doc) {\n let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n if (node && NodeSelection.isSelectable(node))\n return new NodeSelection($pos);\n return Selection.near($pos);\n }\n}\n/**\nA selection type that represents selecting the whole document\n(which can not necessarily be expressed with a text selection, when\nthere are for example leaf block nodes at the start or end of the\ndocument).\n*/\nclass AllSelection extends Selection {\n /**\n Create an all-selection over the given document.\n */\n constructor(doc) {\n super(doc.resolve(0), doc.resolve(doc.content.size));\n }\n replace(tr, content = Slice.empty) {\n if (content == Slice.empty) {\n tr.delete(0, tr.doc.content.size);\n let sel = Selection.atStart(tr.doc);\n if (!sel.eq(tr.selection))\n tr.setSelection(sel);\n }\n else {\n super.replace(tr, content);\n }\n }\n toJSON() { return { type: \"all\" }; }\n /**\n @internal\n */\n static fromJSON(doc) { return new AllSelection(doc); }\n map(doc) { return new AllSelection(doc); }\n eq(other) { return other instanceof AllSelection; }\n getBookmark() { return AllBookmark; }\n}\nSelection.jsonID(\"all\", AllSelection);\nconst AllBookmark = {\n map() { return this; },\n resolve(doc) { return new AllSelection(doc); }\n};\n// FIXME we'll need some awareness of text direction when scanning for selections\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text = false) {\n if (node.inlineContent)\n return TextSelection.create(doc, pos);\n for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n let child = node.child(i);\n if (!child.isAtom) {\n let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n if (inner)\n return inner;\n }\n else if (!text && NodeSelection.isSelectable(child)) {\n return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));\n }\n pos += child.nodeSize * dir;\n }\n return null;\n}\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n let last = tr.steps.length - 1;\n if (last < startLen)\n return;\n let step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))\n return;\n let map = tr.mapping.maps[last], end;\n map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)\n end = newTo; });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nconst UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n/**\nAn editor state transaction, which can be applied to a state to\ncreate an updated state. Use\n[`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.\n\nTransactions track changes to the document (they are a subclass of\n[`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,\nlike selection updates and adjustments of the set of [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store\nmetadata properties in a transaction, which are extra pieces of\ninformation that client code or plugins can use to describe what a\ntransaction represents, so that they can update their [own\nstate](https://prosemirror.net/docs/ref/#state.StateField) accordingly.\n\nThe [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata\nproperties: it will attach a property `\"pointer\"` with the value\n`true` to selection transactions directly caused by mouse or touch\ninput, a `\"composition\"` property holding an ID identifying the\ncomposition that caused it to transactions caused by composed DOM\ninput, and a `\"uiEvent\"` property of that may be `\"paste\"`,\n`\"cut\"`, or `\"drop\"`.\n*/\nclass Transaction extends Transform {\n /**\n @internal\n */\n constructor(state) {\n super(state.doc);\n // The step count for which the current selection is valid.\n this.curSelectionFor = 0;\n // Bitfield to track which aspects of the state were updated by\n // this transaction.\n this.updated = 0;\n // Object used to store metadata properties for the transaction.\n this.meta = Object.create(null);\n this.time = Date.now();\n this.curSelection = state.selection;\n this.storedMarks = state.storedMarks;\n }\n /**\n The transaction's current selection. This defaults to the editor\n selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the\n transaction, but can be overwritten with\n [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).\n */\n get selection() {\n if (this.curSelectionFor < this.steps.length) {\n this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n this.curSelectionFor = this.steps.length;\n }\n return this.curSelection;\n }\n /**\n Update the transaction's current selection. Will determine the\n selection that the editor gets when the transaction is applied.\n */\n setSelection(selection) {\n if (selection.$from.doc != this.doc)\n throw new RangeError(\"Selection passed to setSelection must point at the current document\");\n this.curSelection = selection;\n this.curSelectionFor = this.steps.length;\n this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n this.storedMarks = null;\n return this;\n }\n /**\n Whether the selection was explicitly updated by this transaction.\n */\n get selectionSet() {\n return (this.updated & UPDATED_SEL) > 0;\n }\n /**\n Set the current stored marks.\n */\n setStoredMarks(marks) {\n this.storedMarks = marks;\n this.updated |= UPDATED_MARKS;\n return this;\n }\n /**\n Make sure the current stored marks or, if that is null, the marks\n at the selection, match the given set of marks. Does nothing if\n this is already the case.\n */\n ensureMarks(marks) {\n if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n this.setStoredMarks(marks);\n return this;\n }\n /**\n Add a mark to the set of stored marks.\n */\n addStoredMark(mark) {\n return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Remove a mark or mark type from the set of stored marks.\n */\n removeStoredMark(mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Whether the stored marks were explicitly set for this transaction.\n */\n get storedMarksSet() {\n return (this.updated & UPDATED_MARKS) > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n super.addStep(step, doc);\n this.updated = this.updated & ~UPDATED_MARKS;\n this.storedMarks = null;\n }\n /**\n Update the timestamp for the transaction.\n */\n setTime(time) {\n this.time = time;\n return this;\n }\n /**\n Replace the current selection with the given slice.\n */\n replaceSelection(slice) {\n this.selection.replace(this, slice);\n return this;\n }\n /**\n Replace the selection with the given node. When `inheritMarks` is\n true and the content is inline, it inherits the marks from the\n place where it is inserted.\n */\n replaceSelectionWith(node, inheritMarks = true) {\n let selection = this.selection;\n if (inheritMarks)\n node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none)));\n selection.replaceWith(this, node);\n return this;\n }\n /**\n Delete the selection.\n */\n deleteSelection() {\n this.selection.replace(this);\n return this;\n }\n /**\n Replace the given range, or the selection if no range is given,\n with a text node containing the given string.\n */\n insertText(text, from, to) {\n let schema = this.doc.type.schema;\n if (from == null) {\n if (!text)\n return this.deleteSelection();\n return this.replaceSelectionWith(schema.text(text), true);\n }\n else {\n if (to == null)\n to = from;\n to = to == null ? from : to;\n if (!text)\n return this.deleteRange(from, to);\n let marks = this.storedMarks;\n if (!marks) {\n let $from = this.doc.resolve(from);\n marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n }\n this.replaceRangeWith(from, to, schema.text(text, marks));\n if (!this.selection.empty)\n this.setSelection(Selection.near(this.selection.$to));\n return this;\n }\n }\n /**\n Store a metadata property in this transaction, keyed either by\n name or by plugin.\n */\n setMeta(key, value) {\n this.meta[typeof key == \"string\" ? key : key.key] = value;\n return this;\n }\n /**\n Retrieve a metadata property for a given name or plugin.\n */\n getMeta(key) {\n return this.meta[typeof key == \"string\" ? key : key.key];\n }\n /**\n Returns true if this transaction doesn't contain any metadata,\n and can thus safely be extended.\n */\n get isGeneric() {\n for (let _ in this.meta)\n return false;\n return true;\n }\n /**\n Indicate that the editor should scroll the selection into view\n when updated to the state produced by this transaction.\n */\n scrollIntoView() {\n this.updated |= UPDATED_SCROLL;\n return this;\n }\n /**\n True when this transaction has had `scrollIntoView` called on it.\n */\n get scrolledIntoView() {\n return (this.updated & UPDATED_SCROLL) > 0;\n }\n}\n\nfunction bind(f, self) {\n return !self || !f ? f : f.bind(self);\n}\nclass FieldDesc {\n constructor(name, desc, self) {\n this.name = name;\n this.init = bind(desc.init, self);\n this.apply = bind(desc.apply, self);\n }\n}\nconst baseFields = [\n new FieldDesc(\"doc\", {\n init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },\n apply(tr) { return tr.doc; }\n }),\n new FieldDesc(\"selection\", {\n init(config, instance) { return config.selection || Selection.atStart(instance.doc); },\n apply(tr) { return tr.selection; }\n }),\n new FieldDesc(\"storedMarks\", {\n init(config) { return config.storedMarks || null; },\n apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }\n }),\n new FieldDesc(\"scrollToSelection\", {\n init() { return 0; },\n apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }\n })\n];\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nclass Configuration {\n constructor(schema, plugins) {\n this.schema = schema;\n this.plugins = [];\n this.pluginsByKey = Object.create(null);\n this.fields = baseFields.slice();\n if (plugins)\n plugins.forEach(plugin => {\n if (this.pluginsByKey[plugin.key])\n throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\");\n this.plugins.push(plugin);\n this.pluginsByKey[plugin.key] = plugin;\n if (plugin.spec.state)\n this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));\n });\n }\n}\n/**\nThe state of a ProseMirror editor is represented by an object of\nthis type. A state is a persistent data structure—it isn't\nupdated, but rather a new state value is computed from an old one\nusing the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.\n\nA state holds a number of built-in fields, and plugins can\n[define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.\n*/\nclass EditorState {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n config) {\n this.config = config;\n }\n /**\n The schema of the state's document.\n */\n get schema() {\n return this.config.schema;\n }\n /**\n The plugins that are active in this state.\n */\n get plugins() {\n return this.config.plugins;\n }\n /**\n Apply the given transaction to produce a new state.\n */\n apply(tr) {\n return this.applyTransaction(tr).state;\n }\n /**\n @internal\n */\n filterTransaction(tr, ignore = -1) {\n for (let i = 0; i < this.config.plugins.length; i++)\n if (i != ignore) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))\n return false;\n }\n return true;\n }\n /**\n Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that\n returns the precise transactions that were applied (which might\n be influenced by the [transaction\n hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of\n plugins) along with the new state.\n */\n applyTransaction(rootTr) {\n if (!this.filterTransaction(rootTr))\n return { state: this, transactions: [] };\n let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;\n // This loop repeatedly gives plugins a chance to respond to\n // transactions as new transactions are added, making sure to only\n // pass the transactions the plugin did not see before.\n for (;;) {\n let haveNew = false;\n for (let i = 0; i < this.config.plugins.length; i++) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.appendTransaction) {\n let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n let tr = n < trs.length &&\n plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n if (tr && newState.filterTransaction(tr, i)) {\n tr.setMeta(\"appendedTransaction\", rootTr);\n if (!seen) {\n seen = [];\n for (let j = 0; j < this.config.plugins.length; j++)\n seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });\n }\n trs.push(tr);\n newState = newState.applyInner(tr);\n haveNew = true;\n }\n if (seen)\n seen[i] = { state: newState, n: trs.length };\n }\n }\n if (!haveNew)\n return { state: newState, transactions: trs };\n }\n }\n /**\n @internal\n */\n applyInner(tr) {\n if (!tr.before.eq(this.doc))\n throw new RangeError(\"Applying a mismatched transaction\");\n let newInstance = new EditorState(this.config), fields = this.config.fields;\n for (let i = 0; i < fields.length; i++) {\n let field = fields[i];\n newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n }\n return newInstance;\n }\n /**\n Start a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.\n */\n get tr() { return new Transaction(this); }\n /**\n Create a new state.\n */\n static create(config) {\n let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);\n let instance = new EditorState($config);\n for (let i = 0; i < $config.fields.length; i++)\n instance[$config.fields[i].name] = $config.fields[i].init(config, instance);\n return instance;\n }\n /**\n Create a new state based on this one, but with an adjusted set\n of active plugins. State fields that exist in both sets of\n plugins are kept unchanged. Those that no longer exist are\n dropped, and those that are new are initialized using their\n [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new\n configuration object..\n */\n reconfigure(config) {\n let $config = new Configuration(this.schema, config.plugins);\n let fields = $config.fields, instance = new EditorState($config);\n for (let i = 0; i < fields.length; i++) {\n let name = fields[i].name;\n instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n }\n return instance;\n }\n /**\n Serialize this state to JSON. If you want to serialize the state\n of plugins, pass an object mapping property names to use in the\n resulting JSON object to plugin objects. The argument may also be\n a string or number, in which case it is ignored, to support the\n way `JSON.stringify` calls `toString` methods.\n */\n toJSON(pluginFields) {\n let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };\n if (this.storedMarks)\n result.storedMarks = this.storedMarks.map(m => m.toJSON());\n if (pluginFields && typeof pluginFields == 'object')\n for (let prop in pluginFields) {\n if (prop == \"doc\" || prop == \"selection\")\n throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\");\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (state && state.toJSON)\n result[prop] = state.toJSON.call(plugin, this[plugin.key]);\n }\n return result;\n }\n /**\n Deserialize a JSON representation of a state. `config` should\n have at least a `schema` field, and should contain array of\n plugins to initialize the state with. `pluginFields` can be used\n to deserialize the state of plugins, by associating plugin\n instances with the property names they use in the JSON object.\n */\n static fromJSON(config, json, pluginFields) {\n if (!json)\n throw new RangeError(\"Invalid input for EditorState.fromJSON\");\n if (!config.schema)\n throw new RangeError(\"Required config field 'schema' missing\");\n let $config = new Configuration(config.schema, config.plugins);\n let instance = new EditorState($config);\n $config.fields.forEach(field => {\n if (field.name == \"doc\") {\n instance.doc = Node.fromJSON(config.schema, json.doc);\n }\n else if (field.name == \"selection\") {\n instance.selection = Selection.fromJSON(instance.doc, json.selection);\n }\n else if (field.name == \"storedMarks\") {\n if (json.storedMarks)\n instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);\n }\n else {\n if (pluginFields)\n for (let prop in pluginFields) {\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (plugin.key == field.name && state && state.fromJSON &&\n Object.prototype.hasOwnProperty.call(json, prop)) {\n instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n return;\n }\n }\n instance[field.name] = field.init(config, instance);\n }\n });\n return instance;\n }\n}\n\nfunction bindProps(obj, self, target) {\n for (let prop in obj) {\n let val = obj[prop];\n if (val instanceof Function)\n val = val.bind(self);\n else if (prop == \"handleDOMEvents\")\n val = bindProps(val, self, {});\n target[prop] = val;\n }\n return target;\n}\n/**\nPlugins bundle functionality that can be added to an editor.\nThey are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and\nmay influence that state and the view that contains it.\n*/\nclass Plugin {\n /**\n Create a plugin.\n */\n constructor(\n /**\n The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).\n */\n spec) {\n this.spec = spec;\n /**\n The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.\n */\n this.props = {};\n if (spec.props)\n bindProps(spec.props, this, this.props);\n this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n }\n /**\n Extract the plugin's state field from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\nconst keys = Object.create(null);\nfunction createKey(name) {\n if (name in keys)\n return name + \"$\" + ++keys[name];\n keys[name] = 0;\n return name + \"$\";\n}\n/**\nA key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way\nthat makes it possible to find them, given an editor state.\nAssigning a key does mean only one plugin of that type can be\nactive in a state.\n*/\nclass PluginKey {\n /**\n Create a plugin key.\n */\n constructor(name = \"key\") { this.key = createKey(name); }\n /**\n Get the active plugin with this key, if any, from an editor\n state.\n */\n get(state) { return state.config.pluginsByKey[this.key]; }\n /**\n Get the plugin's state from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n","import { TextSelection, NodeSelection, AllSelection, Selection } from 'prosemirror-state';\nimport { DOMSerializer, Fragment, Mark, Slice, DOMParser } from 'prosemirror-model';\nimport { dropPoint } from 'prosemirror-transform';\n\nconst domIndex = function (node) {\n for (var index = 0;; index++) {\n node = node.previousSibling;\n if (!node)\n return index;\n }\n};\nconst parentNode = function (node) {\n let parent = node.assignedSlot || node.parentNode;\n return parent && parent.nodeType == 11 ? parent.host : parent;\n};\nlet reusedRange = null;\n// Note that this will always return the same range, because DOM range\n// objects are every expensive, and keep slowing down subsequent DOM\n// updates, for some reason.\nconst textRange = function (node, from, to) {\n let range = reusedRange || (reusedRange = document.createRange());\n range.setEnd(node, to == null ? node.nodeValue.length : to);\n range.setStart(node, from || 0);\n return range;\n};\nconst clearReusedRange = function () {\n reusedRange = null;\n};\n// Scans forward and backward through DOM positions equivalent to the\n// given one to see if the two are in the same place (i.e. after a\n// text node vs at the end of that text node)\nconst isEquivalentPosition = function (node, off, targetNode, targetOff) {\n return targetNode && (scanFor(node, off, targetNode, targetOff, -1) ||\n scanFor(node, off, targetNode, targetOff, 1));\n};\nconst atomElements = /^(img|br|input|textarea|hr)$/i;\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n for (;;) {\n if (node == targetNode && off == targetOff)\n return true;\n if (off == (dir < 0 ? 0 : nodeSize(node))) {\n let parent = node.parentNode;\n if (!parent || parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) ||\n node.contentEditable == \"false\")\n return false;\n off = domIndex(node) + (dir < 0 ? 0 : 1);\n node = parent;\n }\n else if (node.nodeType == 1) {\n node = node.childNodes[off + (dir < 0 ? -1 : 0)];\n if (node.contentEditable == \"false\")\n return false;\n off = dir < 0 ? nodeSize(node) : 0;\n }\n else {\n return false;\n }\n }\n}\nfunction nodeSize(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction textNodeBefore$1(node, offset) {\n for (;;) {\n if (node.nodeType == 3 && offset)\n return node;\n if (node.nodeType == 1 && offset > 0) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset - 1];\n offset = nodeSize(node);\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction textNodeAfter$1(node, offset) {\n for (;;) {\n if (node.nodeType == 3 && offset < node.nodeValue.length)\n return node;\n if (node.nodeType == 1 && offset < node.childNodes.length) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset];\n offset = 0;\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction isOnEdge(node, offset, parent) {\n for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) {\n if (node == parent)\n return true;\n let index = domIndex(node);\n node = node.parentNode;\n if (!node)\n return false;\n atStart = atStart && index == 0;\n atEnd = atEnd && index == nodeSize(node);\n }\n}\nfunction hasBlockDesc(dom) {\n let desc;\n for (let cur = dom; cur; cur = cur.parentNode)\n if (desc = cur.pmViewDesc)\n break;\n return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);\n}\n// Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523\n// (isCollapsed inappropriately returns true in shadow dom)\nconst selectionCollapsed = function (domSel) {\n return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);\n};\nfunction keyEvent(keyCode, key) {\n let event = document.createEvent(\"Event\");\n event.initEvent(\"keydown\", true, true);\n event.keyCode = keyCode;\n event.key = event.code = key;\n return event;\n}\nfunction deepActiveElement(doc) {\n let elt = doc.activeElement;\n while (elt && elt.shadowRoot)\n elt = elt.shadowRoot.activeElement;\n return elt;\n}\nfunction caretFromPoint(doc, x, y) {\n if (doc.caretPositionFromPoint) {\n try { // Firefox throws for this call in hard-to-predict circumstances (#994)\n let pos = doc.caretPositionFromPoint(x, y);\n // Clip the offset, because Chrome will return a text offset\n // into nodes, which can't be treated as a regular DOM\n // offset\n if (pos)\n return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };\n }\n catch (_) { }\n }\n if (doc.caretRangeFromPoint) {\n let range = doc.caretRangeFromPoint(x, y);\n if (range)\n return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };\n }\n}\n\nconst nav = typeof navigator != \"undefined\" ? navigator : null;\nconst doc = typeof document != \"undefined\" ? document : null;\nconst agent = (nav && nav.userAgent) || \"\";\nconst ie_edge = /Edge\\/(\\d+)/.exec(agent);\nconst ie_upto10 = /MSIE \\d/.exec(agent);\nconst ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(agent);\nconst ie = !!(ie_upto10 || ie_11up || ie_edge);\nconst ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;\nconst gecko = !ie && /gecko\\/(\\d+)/i.test(agent);\ngecko && +(/Firefox\\/(\\d+)/.exec(agent) || [0, 0])[1];\nconst _chrome = !ie && /Chrome\\/(\\d+)/.exec(agent);\nconst chrome = !!_chrome;\nconst chrome_version = _chrome ? +_chrome[1] : 0;\nconst safari = !ie && !!nav && /Apple Computer/.test(nav.vendor);\n// Is true for both iOS and iPadOS for convenience\nconst ios = safari && (/Mobile\\/\\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);\nconst mac = ios || (nav ? /Mac/.test(nav.platform) : false);\nconst windows = nav ? /Win/.test(nav.platform) : false;\nconst android = /Android \\d/.test(agent);\nconst webkit = !!doc && \"webkitFontSmoothing\" in doc.documentElement.style;\nconst webkit_version = webkit ? +(/\\bAppleWebKit\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;\n\nfunction windowRect(doc) {\n let vp = doc.defaultView && doc.defaultView.visualViewport;\n if (vp)\n return {\n left: 0, right: vp.width,\n top: 0, bottom: vp.height\n };\n return { left: 0, right: doc.documentElement.clientWidth,\n top: 0, bottom: doc.documentElement.clientHeight };\n}\nfunction getSide(value, side) {\n return typeof value == \"number\" ? value : value[side];\n}\nfunction clientRect(node) {\n let rect = node.getBoundingClientRect();\n // Adjust for elements with style \"transform: scale()\"\n let scaleX = (rect.width / node.offsetWidth) || 1;\n let scaleY = (rect.height / node.offsetHeight) || 1;\n // Make sure scrollbar width isn't included in the rectangle\n return { left: rect.left, right: rect.left + node.clientWidth * scaleX,\n top: rect.top, bottom: rect.top + node.clientHeight * scaleY };\n}\nfunction scrollRectIntoView(view, rect, startDOM) {\n let scrollThreshold = view.someProp(\"scrollThreshold\") || 0, scrollMargin = view.someProp(\"scrollMargin\") || 5;\n let doc = view.dom.ownerDocument;\n for (let parent = startDOM || view.dom;; parent = parentNode(parent)) {\n if (!parent)\n break;\n if (parent.nodeType != 1)\n continue;\n let elt = parent;\n let atTop = elt == doc.body;\n let bounding = atTop ? windowRect(doc) : clientRect(elt);\n let moveX = 0, moveY = 0;\n if (rect.top < bounding.top + getSide(scrollThreshold, \"top\"))\n moveY = -(bounding.top - rect.top + getSide(scrollMargin, \"top\"));\n else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, \"bottom\"))\n moveY = rect.bottom - rect.top > bounding.bottom - bounding.top\n ? rect.top + getSide(scrollMargin, \"top\") - bounding.top\n : rect.bottom - bounding.bottom + getSide(scrollMargin, \"bottom\");\n if (rect.left < bounding.left + getSide(scrollThreshold, \"left\"))\n moveX = -(bounding.left - rect.left + getSide(scrollMargin, \"left\"));\n else if (rect.right > bounding.right - getSide(scrollThreshold, \"right\"))\n moveX = rect.right - bounding.right + getSide(scrollMargin, \"right\");\n if (moveX || moveY) {\n if (atTop) {\n doc.defaultView.scrollBy(moveX, moveY);\n }\n else {\n let startX = elt.scrollLeft, startY = elt.scrollTop;\n if (moveY)\n elt.scrollTop += moveY;\n if (moveX)\n elt.scrollLeft += moveX;\n let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY;\n rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };\n }\n }\n if (atTop || /^(fixed|sticky)$/.test(getComputedStyle(parent).position))\n break;\n }\n}\n// Store the scroll position of the editor's parent nodes, along with\n// the top position of an element near the top of the editor, which\n// will be used to make sure the visible viewport remains stable even\n// when the size of the content above changes.\nfunction storeScrollPos(view) {\n let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);\n let refDOM, refTop;\n for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) {\n let dom = view.root.elementFromPoint(x, y);\n if (!dom || dom == view.dom || !view.dom.contains(dom))\n continue;\n let localRect = dom.getBoundingClientRect();\n if (localRect.top >= startY - 20) {\n refDOM = dom;\n refTop = localRect.top;\n break;\n }\n }\n return { refDOM: refDOM, refTop: refTop, stack: scrollStack(view.dom) };\n}\nfunction scrollStack(dom) {\n let stack = [], doc = dom.ownerDocument;\n for (let cur = dom; cur; cur = parentNode(cur)) {\n stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });\n if (dom == doc)\n break;\n }\n return stack;\n}\n// Reset the scroll position of the editor's parent nodes to that what\n// it was before, when storeScrollPos was called.\nfunction resetScrollPos({ refDOM, refTop, stack }) {\n let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;\n restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);\n}\nfunction restoreScrollStack(stack, dTop) {\n for (let i = 0; i < stack.length; i++) {\n let { dom, top, left } = stack[i];\n if (dom.scrollTop != top + dTop)\n dom.scrollTop = top + dTop;\n if (dom.scrollLeft != left)\n dom.scrollLeft = left;\n }\n}\nlet preventScrollSupported = null;\n// Feature-detects support for .focus({preventScroll: true}), and uses\n// a fallback kludge when not supported.\nfunction focusPreventScroll(dom) {\n if (dom.setActive)\n return dom.setActive(); // in IE\n if (preventScrollSupported)\n return dom.focus(preventScrollSupported);\n let stored = scrollStack(dom);\n dom.focus(preventScrollSupported == null ? {\n get preventScroll() {\n preventScrollSupported = { preventScroll: true };\n return true;\n }\n } : undefined);\n if (!preventScrollSupported) {\n preventScrollSupported = false;\n restoreScrollStack(stored, 0);\n }\n}\nfunction findOffsetInNode(node, coords) {\n let closest, dxClosest = 2e8, coordsClosest, offset = 0;\n let rowBot = coords.top, rowTop = coords.top;\n let firstBelow, coordsBelow;\n for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {\n let rects;\n if (child.nodeType == 1)\n rects = child.getClientRects();\n else if (child.nodeType == 3)\n rects = textRange(child).getClientRects();\n else\n continue;\n for (let i = 0; i < rects.length; i++) {\n let rect = rects[i];\n if (rect.top <= rowBot && rect.bottom >= rowTop) {\n rowBot = Math.max(rect.bottom, rowBot);\n rowTop = Math.min(rect.top, rowTop);\n let dx = rect.left > coords.left ? rect.left - coords.left\n : rect.right < coords.left ? coords.left - rect.right : 0;\n if (dx < dxClosest) {\n closest = child;\n dxClosest = dx;\n coordsClosest = dx && closest.nodeType == 3 ? {\n left: rect.right < coords.left ? rect.right : rect.left,\n top: coords.top\n } : coords;\n if (child.nodeType == 1 && dx)\n offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);\n continue;\n }\n }\n else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {\n firstBelow = child;\n coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };\n }\n if (!closest && (coords.left >= rect.right && coords.top >= rect.top ||\n coords.left >= rect.left && coords.top >= rect.bottom))\n offset = childIndex + 1;\n }\n }\n if (!closest && firstBelow) {\n closest = firstBelow;\n coordsClosest = coordsBelow;\n dxClosest = 0;\n }\n if (closest && closest.nodeType == 3)\n return findOffsetInText(closest, coordsClosest);\n if (!closest || (dxClosest && closest.nodeType == 1))\n return { node, offset };\n return findOffsetInNode(closest, coordsClosest);\n}\nfunction findOffsetInText(node, coords) {\n let len = node.nodeValue.length;\n let range = document.createRange();\n for (let i = 0; i < len; i++) {\n range.setEnd(node, i + 1);\n range.setStart(node, i);\n let rect = singleRect(range, 1);\n if (rect.top == rect.bottom)\n continue;\n if (inRect(coords, rect))\n return { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };\n }\n return { node, offset: 0 };\n}\nfunction inRect(coords, rect) {\n return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 &&\n coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;\n}\nfunction targetKludge(dom, coords) {\n let parent = dom.parentNode;\n if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)\n return parent;\n return dom;\n}\nfunction posFromElement(view, elt, coords) {\n let { node, offset } = findOffsetInNode(elt, coords), bias = -1;\n if (node.nodeType == 1 && !node.firstChild) {\n let rect = node.getBoundingClientRect();\n bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;\n }\n return view.docView.posFromDOM(node, offset, bias);\n}\nfunction posFromCaret(view, node, offset, coords) {\n // Browser (in caretPosition/RangeFromPoint) will agressively\n // normalize towards nearby inline nodes. Since we are interested in\n // positions between block nodes too, we first walk up the hierarchy\n // of nodes to see if there are block nodes that the coordinates\n // fall outside of. If so, we take the position before/after that\n // block. If not, we call `posFromDOM` on the raw node/offset.\n let outsideBlock = -1;\n for (let cur = node, sawBlock = false;;) {\n if (cur == view.dom)\n break;\n let desc = view.docView.nearestDesc(cur, true), rect;\n if (!desc)\n return null;\n if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) &&\n // Ignore elements with zero-size bounding rectangles\n ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {\n if (desc.node.isBlock && desc.parent) {\n // Only apply the horizontal test to the innermost block. Vertical for any parent.\n if (!sawBlock && rect.left > coords.left || rect.top > coords.top)\n outsideBlock = desc.posBefore;\n else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top)\n outsideBlock = desc.posAfter;\n sawBlock = true;\n }\n if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {\n // If we are inside a leaf, return the side of the leaf closer to the coords\n let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2\n : coords.left < (rect.left + rect.right) / 2;\n return before ? desc.posBefore : desc.posAfter;\n }\n }\n cur = desc.dom.parentNode;\n }\n return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1);\n}\nfunction elementFromPoint(element, coords, box) {\n let len = element.childNodes.length;\n if (len && box.top < box.bottom) {\n for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) {\n let child = element.childNodes[i];\n if (child.nodeType == 1) {\n let rects = child.getClientRects();\n for (let j = 0; j < rects.length; j++) {\n let rect = rects[j];\n if (inRect(coords, rect))\n return elementFromPoint(child, coords, rect);\n }\n }\n if ((i = (i + 1) % len) == startI)\n break;\n }\n }\n return element;\n}\n// Given an x,y position on the editor, get the position in the document.\nfunction posAtCoords(view, coords) {\n let doc = view.dom.ownerDocument, node, offset = 0;\n let caret = caretFromPoint(doc, coords.left, coords.top);\n if (caret)\n ({ node, offset } = caret);\n let elt = (view.root.elementFromPoint ? view.root : doc)\n .elementFromPoint(coords.left, coords.top);\n let pos;\n if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {\n let box = view.dom.getBoundingClientRect();\n if (!inRect(coords, box))\n return null;\n elt = elementFromPoint(view.dom, coords, box);\n if (!elt)\n return null;\n }\n // Safari's caretRangeFromPoint returns nonsense when on a draggable element\n if (safari) {\n for (let p = elt; node && p; p = parentNode(p))\n if (p.draggable)\n node = undefined;\n }\n elt = targetKludge(elt, coords);\n if (node) {\n if (gecko && node.nodeType == 1) {\n // Firefox will sometimes return offsets into nodes, which\n // have no actual children, from caretPositionFromPoint (#953)\n offset = Math.min(offset, node.childNodes.length);\n // It'll also move the returned position before image nodes,\n // even if those are behind it.\n if (offset < node.childNodes.length) {\n let next = node.childNodes[offset], box;\n if (next.nodeName == \"IMG\" && (box = next.getBoundingClientRect()).right <= coords.left &&\n box.bottom > coords.top)\n offset++;\n }\n }\n let prev;\n // When clicking above the right side of an uneditable node, Chrome will report a cursor position after that node.\n if (webkit && offset && node.nodeType == 1 && (prev = node.childNodes[offset - 1]).nodeType == 1 &&\n prev.contentEditable == \"false\" && prev.getBoundingClientRect().top >= coords.top)\n offset--;\n // Suspiciously specific kludge to work around caret*FromPoint\n // never returning a position at the end of the document\n if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 &&\n coords.top > node.lastChild.getBoundingClientRect().bottom)\n pos = view.state.doc.content.size;\n // Ignore positions directly after a BR, since caret*FromPoint\n // 'round up' positions that would be more accurately placed\n // before the BR node.\n else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != \"BR\")\n pos = posFromCaret(view, node, offset, coords);\n }\n if (pos == null)\n pos = posFromElement(view, elt, coords);\n let desc = view.docView.nearestDesc(elt, true);\n return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };\n}\nfunction nonZero(rect) {\n return rect.top < rect.bottom || rect.left < rect.right;\n}\nfunction singleRect(target, bias) {\n let rects = target.getClientRects();\n if (rects.length) {\n let first = rects[bias < 0 ? 0 : rects.length - 1];\n if (nonZero(first))\n return first;\n }\n return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();\n}\nconst BIDI = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n// Given a position in the document model, get a bounding box of the\n// character at that position, relative to the window.\nfunction coordsAtPos(view, pos, side) {\n let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);\n let supportEmptyRange = webkit || gecko;\n if (node.nodeType == 3) {\n // These browsers support querying empty text ranges. Prefer that in\n // bidi context or when at the end of a node.\n if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {\n let rect = singleRect(textRange(node, offset, offset), side);\n // Firefox returns bad results (the position before the space)\n // when querying a position directly after line-broken\n // whitespace. Detect this situation and and kludge around it\n if (gecko && offset && /\\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {\n let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);\n if (rectBefore.top == rect.top) {\n let rectAfter = singleRect(textRange(node, offset, offset + 1), -1);\n if (rectAfter.top != rect.top)\n return flattenV(rectAfter, rectAfter.left < rectBefore.left);\n }\n }\n return rect;\n }\n else {\n let from = offset, to = offset, takeSide = side < 0 ? 1 : -1;\n if (side < 0 && !offset) {\n to++;\n takeSide = -1;\n }\n else if (side >= 0 && offset == node.nodeValue.length) {\n from--;\n takeSide = 1;\n }\n else if (side < 0) {\n from--;\n }\n else {\n to++;\n }\n return flattenV(singleRect(textRange(node, from, to), takeSide), takeSide < 0);\n }\n }\n let $dom = view.state.doc.resolve(pos - (atom || 0));\n // Return a horizontal line in block context\n if (!$dom.parent.inlineContent) {\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n if (before.nodeType == 1)\n return flattenH(before.getBoundingClientRect(), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n if (after.nodeType == 1)\n return flattenH(after.getBoundingClientRect(), true);\n }\n return flattenH(node.getBoundingClientRect(), side >= 0);\n }\n // Inline, not in text node (this is not Bidi-safe)\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n let target = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1))\n // BR nodes tend to only return the rectangle before them.\n // Only use them if they are the last element in their parent\n : before.nodeType == 1 && (before.nodeName != \"BR\" || !before.nextSibling) ? before : null;\n if (target)\n return flattenV(singleRect(target, 1), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)\n after = after.nextSibling;\n let target = !after ? null : after.nodeType == 3 ? textRange(after, 0, (supportEmptyRange ? 0 : 1))\n : after.nodeType == 1 ? after : null;\n if (target)\n return flattenV(singleRect(target, -1), true);\n }\n // All else failed, just try to get a rectangle for the target node\n return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0);\n}\nfunction flattenV(rect, left) {\n if (rect.width == 0)\n return rect;\n let x = left ? rect.left : rect.right;\n return { top: rect.top, bottom: rect.bottom, left: x, right: x };\n}\nfunction flattenH(rect, top) {\n if (rect.height == 0)\n return rect;\n let y = top ? rect.top : rect.bottom;\n return { top: y, bottom: y, left: rect.left, right: rect.right };\n}\nfunction withFlushedState(view, state, f) {\n let viewState = view.state, active = view.root.activeElement;\n if (viewState != state)\n view.updateState(state);\n if (active != view.dom)\n view.focus();\n try {\n return f();\n }\n finally {\n if (viewState != state)\n view.updateState(viewState);\n if (active != view.dom && active)\n active.focus();\n }\n}\n// Whether vertical position motion in a given direction\n// from a position would leave a text block.\nfunction endOfTextblockVertical(view, state, dir) {\n let sel = state.selection;\n let $pos = dir == \"up\" ? sel.$from : sel.$to;\n return withFlushedState(view, state, () => {\n let { node: dom } = view.docView.domFromPos($pos.pos, dir == \"up\" ? -1 : 1);\n for (;;) {\n let nearest = view.docView.nearestDesc(dom, true);\n if (!nearest)\n break;\n if (nearest.node.isBlock) {\n dom = nearest.contentDOM || nearest.dom;\n break;\n }\n dom = nearest.dom.parentNode;\n }\n let coords = coordsAtPos(view, $pos.pos, 1);\n for (let child = dom.firstChild; child; child = child.nextSibling) {\n let boxes;\n if (child.nodeType == 1)\n boxes = child.getClientRects();\n else if (child.nodeType == 3)\n boxes = textRange(child, 0, child.nodeValue.length).getClientRects();\n else\n continue;\n for (let i = 0; i < boxes.length; i++) {\n let box = boxes[i];\n if (box.bottom > box.top + 1 &&\n (dir == \"up\" ? coords.top - box.top > (box.bottom - coords.top) * 2\n : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))\n return false;\n }\n }\n return true;\n });\n}\nconst maybeRTL = /[\\u0590-\\u08ac]/;\nfunction endOfTextblockHorizontal(view, state, dir) {\n let { $head } = state.selection;\n if (!$head.parent.isTextblock)\n return false;\n let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;\n let sel = view.domSelection();\n if (!sel)\n return $head.pos == $head.start() || $head.pos == $head.end();\n // If the textblock is all LTR, or the browser doesn't support\n // Selection.modify (Edge), fall back to a primitive approach\n if (!maybeRTL.test($head.parent.textContent) || !sel.modify)\n return dir == \"left\" || dir == \"backward\" ? atStart : atEnd;\n return withFlushedState(view, state, () => {\n // This is a huge hack, but appears to be the best we can\n // currently do: use `Selection.modify` to move the selection by\n // one character, and see if that moves the cursor out of the\n // textblock (or doesn't move it at all, when at the start/end of\n // the document).\n let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();\n let oldBidiLevel = sel.caretBidiLevel // Only for Firefox\n ;\n sel.modify(\"move\", dir, \"character\");\n let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;\n let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();\n let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) ||\n (oldNode == newNode && oldOff == newOff);\n // Restore the previous selection\n try {\n sel.collapse(anchorNode, anchorOffset);\n if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)\n sel.extend(oldNode, oldOff);\n }\n catch (_) { }\n if (oldBidiLevel != null)\n sel.caretBidiLevel = oldBidiLevel;\n return result;\n });\n}\nlet cachedState = null;\nlet cachedDir = null;\nlet cachedResult = false;\nfunction endOfTextblock(view, state, dir) {\n if (cachedState == state && cachedDir == dir)\n return cachedResult;\n cachedState = state;\n cachedDir = dir;\n return cachedResult = dir == \"up\" || dir == \"down\"\n ? endOfTextblockVertical(view, state, dir)\n : endOfTextblockHorizontal(view, state, dir);\n}\n\n// View descriptions are data structures that describe the DOM that is\n// used to represent the editor's content. They are used for:\n//\n// - Incremental redrawing when the document changes\n//\n// - Figuring out what part of the document a given DOM position\n// corresponds to\n//\n// - Wiring in custom implementations of the editing interface for a\n// given node\n//\n// They form a doubly-linked mutable tree, starting at `view.docView`.\nconst NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3;\n// Superclass for the various kinds of descriptions. Defines their\n// basic structure and shared methods.\nclass ViewDesc {\n constructor(parent, children, dom, \n // This is the node that holds the child views. It may be null for\n // descs that don't have children.\n contentDOM) {\n this.parent = parent;\n this.children = children;\n this.dom = dom;\n this.contentDOM = contentDOM;\n this.dirty = NOT_DIRTY;\n // An expando property on the DOM node provides a link back to its\n // description.\n dom.pmViewDesc = this;\n }\n // Used to check whether a given description corresponds to a\n // widget/mark/node.\n matchesWidget(widget) { return false; }\n matchesMark(mark) { return false; }\n matchesNode(node, outerDeco, innerDeco) { return false; }\n matchesHack(nodeName) { return false; }\n // When parsing in-editor content (in domchange.js), we allow\n // descriptions to determine the parse rules that should be used to\n // parse them.\n parseRule() { return null; }\n // Used by the editor's event handler to ignore events that come\n // from certain descs.\n stopEvent(event) { return false; }\n // The size of the content represented by this desc.\n get size() {\n let size = 0;\n for (let i = 0; i < this.children.length; i++)\n size += this.children[i].size;\n return size;\n }\n // For block nodes, this represents the space taken up by their\n // start/end tokens.\n get border() { return 0; }\n destroy() {\n this.parent = undefined;\n if (this.dom.pmViewDesc == this)\n this.dom.pmViewDesc = undefined;\n for (let i = 0; i < this.children.length; i++)\n this.children[i].destroy();\n }\n posBeforeChild(child) {\n for (let i = 0, pos = this.posAtStart;; i++) {\n let cur = this.children[i];\n if (cur == child)\n return pos;\n pos += cur.size;\n }\n }\n get posBefore() {\n return this.parent.posBeforeChild(this);\n }\n get posAtStart() {\n return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;\n }\n get posAfter() {\n return this.posBefore + this.size;\n }\n get posAtEnd() {\n return this.posAtStart + this.size - 2 * this.border;\n }\n localPosFromDOM(dom, offset, bias) {\n // If the DOM position is in the content, use the child desc after\n // it to figure out a position.\n if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {\n if (bias < 0) {\n let domBefore, desc;\n if (dom == this.contentDOM) {\n domBefore = dom.childNodes[offset - 1];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domBefore = dom.previousSibling;\n }\n while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))\n domBefore = domBefore.previousSibling;\n return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;\n }\n else {\n let domAfter, desc;\n if (dom == this.contentDOM) {\n domAfter = dom.childNodes[offset];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domAfter = dom.nextSibling;\n }\n while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))\n domAfter = domAfter.nextSibling;\n return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;\n }\n }\n // Otherwise, use various heuristics, falling back on the bias\n // parameter, to determine whether to return the position at the\n // start or at the end of this view desc.\n let atEnd;\n if (dom == this.dom && this.contentDOM) {\n atEnd = offset > domIndex(this.contentDOM);\n }\n else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {\n atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;\n }\n else if (this.dom.firstChild) {\n if (offset == 0)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = false;\n break;\n }\n if (search.previousSibling)\n break;\n }\n if (atEnd == null && offset == dom.childNodes.length)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = true;\n break;\n }\n if (search.nextSibling)\n break;\n }\n }\n return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;\n }\n nearestDesc(dom, onlyNodes = false) {\n for (let first = true, cur = dom; cur; cur = cur.parentNode) {\n let desc = this.getDesc(cur), nodeDOM;\n if (desc && (!onlyNodes || desc.node)) {\n // If dom is outside of this desc's nodeDOM, don't count it.\n if (first && (nodeDOM = desc.nodeDOM) &&\n !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom))\n first = false;\n else\n return desc;\n }\n }\n }\n getDesc(dom) {\n let desc = dom.pmViewDesc;\n for (let cur = desc; cur; cur = cur.parent)\n if (cur == this)\n return desc;\n }\n posFromDOM(dom, offset, bias) {\n for (let scan = dom; scan; scan = scan.parentNode) {\n let desc = this.getDesc(scan);\n if (desc)\n return desc.localPosFromDOM(dom, offset, bias);\n }\n return -1;\n }\n // Find the desc for the node after the given pos, if any. (When a\n // parent node overrode rendering, there might not be one.)\n descAt(pos) {\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == pos && end != offset) {\n while (!child.border && child.children.length)\n child = child.children[0];\n return child;\n }\n if (pos < end)\n return child.descAt(pos - offset - child.border);\n offset = end;\n }\n }\n domFromPos(pos, side) {\n if (!this.contentDOM)\n return { node: this.dom, offset: 0, atom: pos + 1 };\n // First find the position in the child array\n let i = 0, offset = 0;\n for (let curPos = 0; i < this.children.length; i++) {\n let child = this.children[i], end = curPos + child.size;\n if (end > pos || child instanceof TrailingHackViewDesc) {\n offset = pos - curPos;\n break;\n }\n curPos = end;\n }\n // If this points into the middle of a child, call through\n if (offset)\n return this.children[i].domFromPos(offset - this.children[i].border, side);\n // Go back if there were any zero-length widgets with side >= 0 before this point\n for (let prev; i && !(prev = this.children[i - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i--) { }\n // Scan towards the first useable node\n if (side <= 0) {\n let prev, enter = true;\n for (;; i--, enter = false) {\n prev = i ? this.children[i - 1] : null;\n if (!prev || prev.dom.parentNode == this.contentDOM)\n break;\n }\n if (prev && side && enter && !prev.border && !prev.domAtom)\n return prev.domFromPos(prev.size, side);\n return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };\n }\n else {\n let next, enter = true;\n for (;; i++, enter = false) {\n next = i < this.children.length ? this.children[i] : null;\n if (!next || next.dom.parentNode == this.contentDOM)\n break;\n }\n if (next && enter && !next.border && !next.domAtom)\n return next.domFromPos(0, side);\n return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };\n }\n }\n // Used to find a DOM range in a single parent for a given changed\n // range.\n parseRange(from, to, base = 0) {\n if (this.children.length == 0)\n return { node: this.contentDOM, from, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };\n let fromOffset = -1, toOffset = -1;\n for (let offset = base, i = 0;; i++) {\n let child = this.children[i], end = offset + child.size;\n if (fromOffset == -1 && from <= end) {\n let childBase = offset + child.border;\n // FIXME maybe descend mark views to parse a narrower range?\n if (from >= childBase && to <= end - child.border && child.node &&\n child.contentDOM && this.contentDOM.contains(child.contentDOM))\n return child.parseRange(from, to, childBase);\n from = offset;\n for (let j = i; j > 0; j--) {\n let prev = this.children[j - 1];\n if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {\n fromOffset = domIndex(prev.dom) + 1;\n break;\n }\n from -= prev.size;\n }\n if (fromOffset == -1)\n fromOffset = 0;\n }\n if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {\n to = end;\n for (let j = i + 1; j < this.children.length; j++) {\n let next = this.children[j];\n if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {\n toOffset = domIndex(next.dom);\n break;\n }\n to += next.size;\n }\n if (toOffset == -1)\n toOffset = this.contentDOM.childNodes.length;\n break;\n }\n offset = end;\n }\n return { node: this.contentDOM, from, to, fromOffset, toOffset };\n }\n emptyChildAt(side) {\n if (this.border || !this.contentDOM || !this.children.length)\n return false;\n let child = this.children[side < 0 ? 0 : this.children.length - 1];\n return child.size == 0 || child.emptyChildAt(side);\n }\n domAfterPos(pos) {\n let { node, offset } = this.domFromPos(pos, 0);\n if (node.nodeType != 1 || offset == node.childNodes.length)\n throw new RangeError(\"No node after pos \" + pos);\n return node.childNodes[offset];\n }\n // View descs are responsible for setting any selection that falls\n // entirely inside of them, so that custom implementations can do\n // custom things with the selection. Note that this falls apart when\n // a selection starts in such a node and ends in another, in which\n // case we just use whatever domFromPos produces as a best effort.\n setSelection(anchor, head, view, force = false) {\n // If the selection falls entirely in a child, give it to that child\n let from = Math.min(anchor, head), to = Math.max(anchor, head);\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (from > offset && to < end)\n return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force);\n offset = end;\n }\n let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);\n let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1);\n let domSel = view.root.getSelection();\n let selRange = view.domSelectionRange();\n let brKludge = false;\n // On Firefox, using Selection.collapse to put the cursor after a\n // BR node for some reason doesn't always work (#1073). On Safari,\n // the cursor sometimes inexplicable visually lags behind its\n // reported position in such situations (#1092).\n if ((gecko || safari) && anchor == head) {\n let { node, offset } = anchorDOM;\n if (node.nodeType == 3) {\n brKludge = !!(offset && node.nodeValue[offset - 1] == \"\\n\");\n // Issue #1128\n if (brKludge && offset == node.nodeValue.length) {\n for (let scan = node, after; scan; scan = scan.parentNode) {\n if (after = scan.nextSibling) {\n if (after.nodeName == \"BR\")\n anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };\n break;\n }\n let desc = scan.pmViewDesc;\n if (desc && desc.node && desc.node.isBlock)\n break;\n }\n }\n }\n else {\n let prev = node.childNodes[offset - 1];\n brKludge = prev && (prev.nodeName == \"BR\" || prev.contentEditable == \"false\");\n }\n }\n // Firefox can act strangely when the selection is in front of an\n // uneditable node. See #1163 and https://bugzilla.mozilla.org/show_bug.cgi?id=1709536\n if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) {\n let after = selRange.focusNode.childNodes[selRange.focusOffset];\n if (after && after.contentEditable == \"false\")\n force = true;\n }\n if (!(force || brKludge && safari) &&\n isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) &&\n isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))\n return;\n // Selection.extend can be used to create an 'inverted' selection\n // (one where the focus is before the anchor), but not all\n // browsers support it yet.\n let domSelExtended = false;\n if ((domSel.extend || anchor == head) && !brKludge) {\n domSel.collapse(anchorDOM.node, anchorDOM.offset);\n try {\n if (anchor != head)\n domSel.extend(headDOM.node, headDOM.offset);\n domSelExtended = true;\n }\n catch (_) {\n // In some cases with Chrome the selection is empty after calling\n // collapse, even when it should be valid. This appears to be a bug, but\n // it is difficult to isolate. If this happens fallback to the old path\n // without using extend.\n // Similarly, this could crash on Safari if the editor is hidden, and\n // there was no selection.\n }\n }\n if (!domSelExtended) {\n if (anchor > head) {\n let tmp = anchorDOM;\n anchorDOM = headDOM;\n headDOM = tmp;\n }\n let range = document.createRange();\n range.setEnd(headDOM.node, headDOM.offset);\n range.setStart(anchorDOM.node, anchorDOM.offset);\n domSel.removeAllRanges();\n domSel.addRange(range);\n }\n }\n ignoreMutation(mutation) {\n return !this.contentDOM && mutation.type != \"selection\";\n }\n get contentLost() {\n return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);\n }\n // Remove a subtree of the element tree that has been touched\n // by a DOM change, so that the next update will redraw it.\n markDirty(from, to) {\n for (let offset = 0, i = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == end ? from <= end && to >= offset : from < end && to > offset) {\n let startInside = offset + child.border, endInside = end - child.border;\n if (from >= startInside && to <= endInside) {\n this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;\n if (from == startInside && to == endInside &&\n (child.contentLost || child.dom.parentNode != this.contentDOM))\n child.dirty = NODE_DIRTY;\n else\n child.markDirty(from - startInside, to - startInside);\n return;\n }\n else {\n child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length\n ? CONTENT_DIRTY : NODE_DIRTY;\n }\n }\n offset = end;\n }\n this.dirty = CONTENT_DIRTY;\n }\n markParentsDirty() {\n let level = 1;\n for (let node = this.parent; node; node = node.parent, level++) {\n let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;\n if (node.dirty < dirty)\n node.dirty = dirty;\n }\n }\n get domAtom() { return false; }\n get ignoreForCoords() { return false; }\n isText(text) { return false; }\n}\n// A widget desc represents a widget decoration, which is a DOM node\n// drawn between the document nodes.\nclass WidgetViewDesc extends ViewDesc {\n constructor(parent, widget, view, pos) {\n let self, dom = widget.type.toDOM;\n if (typeof dom == \"function\")\n dom = dom(view, () => {\n if (!self)\n return pos;\n if (self.parent)\n return self.parent.posBeforeChild(self);\n });\n if (!widget.type.spec.raw) {\n if (dom.nodeType != 1) {\n let wrap = document.createElement(\"span\");\n wrap.appendChild(dom);\n dom = wrap;\n }\n dom.contentEditable = \"false\";\n dom.classList.add(\"ProseMirror-widget\");\n }\n super(parent, [], dom, null);\n this.widget = widget;\n this.widget = widget;\n self = this;\n }\n matchesWidget(widget) {\n return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);\n }\n parseRule() { return { ignore: true }; }\n stopEvent(event) {\n let stop = this.widget.spec.stopEvent;\n return stop ? stop(event) : false;\n }\n ignoreMutation(mutation) {\n return mutation.type != \"selection\" || this.widget.spec.ignoreSelection;\n }\n destroy() {\n this.widget.type.destroy(this.dom);\n super.destroy();\n }\n get domAtom() { return true; }\n get side() { return this.widget.type.side; }\n}\nclass CompositionViewDesc extends ViewDesc {\n constructor(parent, dom, textDOM, text) {\n super(parent, [], dom, null);\n this.textDOM = textDOM;\n this.text = text;\n }\n get size() { return this.text.length; }\n localPosFromDOM(dom, offset) {\n if (dom != this.textDOM)\n return this.posAtStart + (offset ? this.size : 0);\n return this.posAtStart + offset;\n }\n domFromPos(pos) {\n return { node: this.textDOM, offset: pos };\n }\n ignoreMutation(mut) {\n return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue;\n }\n}\n// A mark desc represents a mark. May have multiple children,\n// depending on how the mark is split. Note that marks are drawn using\n// a fixed nesting order, for simplicity and predictability, so in\n// some cases they will be split more often than would appear\n// necessary.\nclass MarkViewDesc extends ViewDesc {\n constructor(parent, mark, dom, contentDOM, spec) {\n super(parent, [], dom, contentDOM);\n this.mark = mark;\n this.spec = spec;\n }\n static create(parent, mark, inline, view) {\n let custom = view.nodeViews[mark.type.name];\n let spec = custom && custom(mark, view, inline);\n if (!spec || !spec.dom)\n spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs);\n return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec);\n }\n parseRule() {\n if ((this.dirty & NODE_DIRTY) || this.mark.type.spec.reparseInView)\n return null;\n return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };\n }\n matchesMark(mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark); }\n markDirty(from, to) {\n super.markDirty(from, to);\n // Move dirty info to nearest node view\n if (this.dirty != NOT_DIRTY) {\n let parent = this.parent;\n while (!parent.node)\n parent = parent.parent;\n if (parent.dirty < this.dirty)\n parent.dirty = this.dirty;\n this.dirty = NOT_DIRTY;\n }\n }\n slice(from, to, view) {\n let copy = MarkViewDesc.create(this.parent, this.mark, true, view);\n let nodes = this.children, size = this.size;\n if (to < size)\n nodes = replaceNodes(nodes, to, size, view);\n if (from > 0)\n nodes = replaceNodes(nodes, 0, from, view);\n for (let i = 0; i < nodes.length; i++)\n nodes[i].parent = copy;\n copy.children = nodes;\n return copy;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\n}\n// Node view descs are the main, most common type of view desc, and\n// correspond to an actual node in the document. Unlike mark descs,\n// they populate their child array themselves.\nclass NodeViewDesc extends ViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {\n super(parent, [], dom, contentDOM);\n this.node = node;\n this.outerDeco = outerDeco;\n this.innerDeco = innerDeco;\n this.nodeDOM = nodeDOM;\n }\n // By default, a node is rendered using the `toDOM` method from the\n // node type spec. But client code can use the `nodeViews` spec to\n // supply a custom node view, which can influence various aspects of\n // the way the node works.\n //\n // (Using subclassing for this was intentionally decided against,\n // since it'd require exposing a whole slew of finicky\n // implementation details to the user code that they probably will\n // never need.)\n static create(parent, node, outerDeco, innerDeco, view, pos) {\n let custom = view.nodeViews[node.type.name], descObj;\n let spec = custom && custom(node, view, () => {\n // (This is a function that allows the custom view to find its\n // own position)\n if (!descObj)\n return pos;\n if (descObj.parent)\n return descObj.parent.posBeforeChild(descObj);\n }, outerDeco, innerDeco);\n let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;\n if (node.isText) {\n if (!dom)\n dom = document.createTextNode(node.text);\n else if (dom.nodeType != 3)\n throw new RangeError(\"Text must be rendered as a DOM text node\");\n }\n else if (!dom) {\n let spec = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);\n ({ dom, contentDOM } = spec);\n }\n if (!contentDOM && !node.isText && dom.nodeName != \"BR\") { // Chrome gets confused by \n if (!dom.hasAttribute(\"contenteditable\"))\n dom.contentEditable = \"false\";\n if (node.type.spec.draggable)\n dom.draggable = true;\n }\n let nodeDOM = dom;\n dom = applyOuterDeco(dom, outerDeco, node);\n if (spec)\n return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1);\n else if (node.isText)\n return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view);\n else\n return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1);\n }\n parseRule() {\n // Experimental kludge to allow opt-in re-parsing of nodes\n if (this.node.type.spec.reparseInView)\n return null;\n // FIXME the assumption that this can always return the current\n // attrs means that if the user somehow manages to change the\n // attrs in the dom, that won't be picked up. Not entirely sure\n // whether this is a problem\n let rule = { node: this.node.type.name, attrs: this.node.attrs };\n if (this.node.type.whitespace == \"pre\")\n rule.preserveWhitespace = \"full\";\n if (!this.contentDOM) {\n rule.getContent = () => this.node.content;\n }\n else if (!this.contentLost) {\n rule.contentElement = this.contentDOM;\n }\n else {\n // Chrome likes to randomly recreate parent nodes when\n // backspacing things. When that happens, this tries to find the\n // new parent.\n for (let i = this.children.length - 1; i >= 0; i--) {\n let child = this.children[i];\n if (this.dom.contains(child.dom.parentNode)) {\n rule.contentElement = child.dom.parentNode;\n break;\n }\n }\n if (!rule.contentElement)\n rule.getContent = () => Fragment.empty;\n }\n return rule;\n }\n matchesNode(node, outerDeco, innerDeco) {\n return this.dirty == NOT_DIRTY && node.eq(this.node) &&\n sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);\n }\n get size() { return this.node.nodeSize; }\n get border() { return this.node.isLeaf ? 0 : 1; }\n // Syncs `this.children` to match `this.node.content` and the local\n // decorations, possibly introducing nesting for marks. Then, in a\n // separate step, syncs the DOM inside `this.contentDOM` to\n // `this.children`.\n updateChildren(view, pos) {\n let inline = this.node.inlineContent, off = pos;\n let composition = view.composing ? this.localCompositionInfo(view, pos) : null;\n let localComposition = composition && composition.pos > -1 ? composition : null;\n let compositionInChild = composition && composition.pos < 0;\n let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);\n iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {\n if (widget.spec.marks)\n updater.syncToMarks(widget.spec.marks, inline, view);\n else if (widget.type.side >= 0 && !insideNode)\n updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view);\n // If the next node is a desc matching this widget, reuse it,\n // otherwise insert the widget as a new view desc.\n updater.placeWidget(widget, view, off);\n }, (child, outerDeco, innerDeco, i) => {\n // Make sure the wrapping mark descs match the node's marks.\n updater.syncToMarks(child.marks, inline, view);\n // Try several strategies for drawing this node\n let compIndex;\n if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ;\n else if (compositionInChild && view.state.selection.from > off &&\n view.state.selection.to < off + child.nodeSize &&\n (compIndex = updater.findIndexWithChild(composition.node)) > -1 &&\n updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ;\n else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ;\n else {\n // Add it as a new view\n updater.addNode(child, outerDeco, innerDeco, view, off);\n }\n off += child.nodeSize;\n });\n // Drop all remaining descs after the current position.\n updater.syncToMarks([], inline, view);\n if (this.node.isTextblock)\n updater.addTextblockHacks();\n updater.destroyRest();\n // Sync the DOM if anything changed\n if (updater.changed || this.dirty == CONTENT_DIRTY) {\n // May have to protect focused DOM from being changed if a composition is active\n if (localComposition)\n this.protectLocalComposition(view, localComposition);\n renderDescs(this.contentDOM, this.children, view);\n if (ios)\n iosHacks(this.dom);\n }\n }\n localCompositionInfo(view, pos) {\n // Only do something if both the selection and a focused text node\n // are inside of this node\n let { from, to } = view.state.selection;\n if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size)\n return null;\n let textNode = view.input.compositionNode;\n if (!textNode || !this.dom.contains(textNode.parentNode))\n return null;\n if (this.node.inlineContent) {\n // Find the text in the focused node in the node, stop if it's not\n // there (may have been modified through other means, in which\n // case it should overwritten)\n let text = textNode.nodeValue;\n let textPos = findTextInFragment(this.node.content, text, from - pos, to - pos);\n return textPos < 0 ? null : { node: textNode, pos: textPos, text };\n }\n else {\n return { node: textNode, pos: -1, text: \"\" };\n }\n }\n protectLocalComposition(view, { node, pos, text }) {\n // The node is already part of a local view desc, leave it there\n if (this.getDesc(node))\n return;\n // Create a composition view for the orphaned nodes\n let topNode = node;\n for (;; topNode = topNode.parentNode) {\n if (topNode.parentNode == this.contentDOM)\n break;\n while (topNode.previousSibling)\n topNode.parentNode.removeChild(topNode.previousSibling);\n while (topNode.nextSibling)\n topNode.parentNode.removeChild(topNode.nextSibling);\n if (topNode.pmViewDesc)\n topNode.pmViewDesc = undefined;\n }\n let desc = new CompositionViewDesc(this, topNode, node, text);\n view.input.compositionNodes.push(desc);\n // Patch up this.children to contain the composition view\n this.children = replaceNodes(this.children, pos, pos + text.length, view, desc);\n }\n // If this desc must be updated to match the given node decoration,\n // do so and return true.\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY ||\n !node.sameMarkup(this.node))\n return false;\n this.updateInner(node, outerDeco, innerDeco, view);\n return true;\n }\n updateInner(node, outerDeco, innerDeco, view) {\n this.updateOuterDeco(outerDeco);\n this.node = node;\n this.innerDeco = innerDeco;\n if (this.contentDOM)\n this.updateChildren(view, this.posAtStart);\n this.dirty = NOT_DIRTY;\n }\n updateOuterDeco(outerDeco) {\n if (sameOuterDeco(outerDeco, this.outerDeco))\n return;\n let needsWrap = this.nodeDOM.nodeType != 1;\n let oldDOM = this.dom;\n this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));\n if (this.dom != oldDOM) {\n oldDOM.pmViewDesc = undefined;\n this.dom.pmViewDesc = this;\n }\n this.outerDeco = outerDeco;\n }\n // Mark this node as being the selected node.\n selectNode() {\n if (this.nodeDOM.nodeType == 1)\n this.nodeDOM.classList.add(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.dom.draggable = true;\n }\n // Remove selected node marking from this node.\n deselectNode() {\n if (this.nodeDOM.nodeType == 1) {\n this.nodeDOM.classList.remove(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.dom.removeAttribute(\"draggable\");\n }\n }\n get domAtom() { return this.node.isAtom; }\n}\n// Create a view desc for the top-level document node, to be exported\n// and used by the view class.\nfunction docViewDesc(doc, outerDeco, innerDeco, dom, view) {\n applyOuterDeco(dom, outerDeco, doc);\n let docView = new NodeViewDesc(undefined, doc, outerDeco, innerDeco, dom, dom, dom, view, 0);\n if (docView.contentDOM)\n docView.updateChildren(view, 0);\n return docView;\n}\nclass TextViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) {\n super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view, 0);\n }\n parseRule() {\n let skip = this.nodeDOM.parentNode;\n while (skip && skip != this.dom && !skip.pmIsDeco)\n skip = skip.parentNode;\n return { skip: (skip || true) };\n }\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) ||\n !node.sameMarkup(this.node))\n return false;\n this.updateOuterDeco(outerDeco);\n if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {\n this.nodeDOM.nodeValue = node.text;\n if (view.trackWrites == this.nodeDOM)\n view.trackWrites = null;\n }\n this.node = node;\n this.dirty = NOT_DIRTY;\n return true;\n }\n inParent() {\n let parentDOM = this.parent.contentDOM;\n for (let n = this.nodeDOM; n; n = n.parentNode)\n if (n == parentDOM)\n return true;\n return false;\n }\n domFromPos(pos) {\n return { node: this.nodeDOM, offset: pos };\n }\n localPosFromDOM(dom, offset, bias) {\n if (dom == this.nodeDOM)\n return this.posAtStart + Math.min(offset, this.node.text.length);\n return super.localPosFromDOM(dom, offset, bias);\n }\n ignoreMutation(mutation) {\n return mutation.type != \"characterData\" && mutation.type != \"selection\";\n }\n slice(from, to, view) {\n let node = this.node.cut(from, to), dom = document.createTextNode(node.text);\n return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view);\n }\n markDirty(from, to) {\n super.markDirty(from, to);\n if (this.dom != this.nodeDOM && (from == 0 || to == this.nodeDOM.nodeValue.length))\n this.dirty = NODE_DIRTY;\n }\n get domAtom() { return false; }\n isText(text) { return this.node.text == text; }\n}\n// A dummy desc used to tag trailing BR or IMG nodes created to work\n// around contentEditable terribleness.\nclass TrailingHackViewDesc extends ViewDesc {\n parseRule() { return { ignore: true }; }\n matchesHack(nodeName) { return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; }\n get domAtom() { return true; }\n get ignoreForCoords() { return this.dom.nodeName == \"IMG\"; }\n}\n// A separate subclass is used for customized node views, so that the\n// extra checks only have to be made for nodes that are actually\n// customized.\nclass CustomNodeViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {\n super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);\n this.spec = spec;\n }\n // A custom `update` method gets to decide whether the update goes\n // through. If it does, and there's a `contentDOM` node, our logic\n // updates the children.\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY)\n return false;\n if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {\n let result = this.spec.update(node, outerDeco, innerDeco);\n if (result)\n this.updateInner(node, outerDeco, innerDeco, view);\n return result;\n }\n else if (!this.contentDOM && !node.isLeaf) {\n return false;\n }\n else {\n return super.update(node, outerDeco, innerDeco, view);\n }\n }\n selectNode() {\n this.spec.selectNode ? this.spec.selectNode() : super.selectNode();\n }\n deselectNode() {\n this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();\n }\n setSelection(anchor, head, view, force) {\n this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root)\n : super.setSelection(anchor, head, view, force);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\n stopEvent(event) {\n return this.spec.stopEvent ? this.spec.stopEvent(event) : false;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n}\n// Sync the content of the given DOM node with the nodes associated\n// with the given array of view descs, recursing into mark descs\n// because this should sync the subtree for a whole node at a time.\nfunction renderDescs(parentDOM, descs, view) {\n let dom = parentDOM.firstChild, written = false;\n for (let i = 0; i < descs.length; i++) {\n let desc = descs[i], childDOM = desc.dom;\n if (childDOM.parentNode == parentDOM) {\n while (childDOM != dom) {\n dom = rm(dom);\n written = true;\n }\n dom = dom.nextSibling;\n }\n else {\n written = true;\n parentDOM.insertBefore(childDOM, dom);\n }\n if (desc instanceof MarkViewDesc) {\n let pos = dom ? dom.previousSibling : parentDOM.lastChild;\n renderDescs(desc.contentDOM, desc.children, view);\n dom = pos ? pos.nextSibling : parentDOM.firstChild;\n }\n }\n while (dom) {\n dom = rm(dom);\n written = true;\n }\n if (written && view.trackWrites == parentDOM)\n view.trackWrites = null;\n}\nconst OuterDecoLevel = function (nodeName) {\n if (nodeName)\n this.nodeName = nodeName;\n};\nOuterDecoLevel.prototype = Object.create(null);\nconst noDeco = [new OuterDecoLevel];\nfunction computeOuterDeco(outerDeco, node, needsWrap) {\n if (outerDeco.length == 0)\n return noDeco;\n let top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top];\n for (let i = 0; i < outerDeco.length; i++) {\n let attrs = outerDeco[i].type.attrs;\n if (!attrs)\n continue;\n if (attrs.nodeName)\n result.push(top = new OuterDecoLevel(attrs.nodeName));\n for (let name in attrs) {\n let val = attrs[name];\n if (val == null)\n continue;\n if (needsWrap && result.length == 1)\n result.push(top = new OuterDecoLevel(node.isInline ? \"span\" : \"div\"));\n if (name == \"class\")\n top.class = (top.class ? top.class + \" \" : \"\") + val;\n else if (name == \"style\")\n top.style = (top.style ? top.style + \";\" : \"\") + val;\n else if (name != \"nodeName\")\n top[name] = val;\n }\n }\n return result;\n}\nfunction patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {\n // Shortcut for trivial case\n if (prevComputed == noDeco && curComputed == noDeco)\n return nodeDOM;\n let curDOM = nodeDOM;\n for (let i = 0; i < curComputed.length; i++) {\n let deco = curComputed[i], prev = prevComputed[i];\n if (i) {\n let parent;\n if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM &&\n (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {\n curDOM = parent;\n }\n else {\n parent = document.createElement(deco.nodeName);\n parent.pmIsDeco = true;\n parent.appendChild(curDOM);\n prev = noDeco[0];\n curDOM = parent;\n }\n }\n patchAttributes(curDOM, prev || noDeco[0], deco);\n }\n return curDOM;\n}\nfunction patchAttributes(dom, prev, cur) {\n for (let name in prev)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && !(name in cur))\n dom.removeAttribute(name);\n for (let name in cur)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && cur[name] != prev[name])\n dom.setAttribute(name, cur[name]);\n if (prev.class != cur.class) {\n let prevList = prev.class ? prev.class.split(\" \").filter(Boolean) : [];\n let curList = cur.class ? cur.class.split(\" \").filter(Boolean) : [];\n for (let i = 0; i < prevList.length; i++)\n if (curList.indexOf(prevList[i]) == -1)\n dom.classList.remove(prevList[i]);\n for (let i = 0; i < curList.length; i++)\n if (prevList.indexOf(curList[i]) == -1)\n dom.classList.add(curList[i]);\n if (dom.classList.length == 0)\n dom.removeAttribute(\"class\");\n }\n if (prev.style != cur.style) {\n if (prev.style) {\n let prop = /\\s*([\\w\\-\\xa1-\\uffff]+)\\s*:(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|\\(.*?\\)|[^;])*/g, m;\n while (m = prop.exec(prev.style))\n dom.style.removeProperty(m[1]);\n }\n if (cur.style)\n dom.style.cssText += cur.style;\n }\n}\nfunction applyOuterDeco(dom, deco, node) {\n return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1));\n}\nfunction sameOuterDeco(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].type.eq(b[i].type))\n return false;\n return true;\n}\n// Remove a DOM node and return its next sibling.\nfunction rm(dom) {\n let next = dom.nextSibling;\n dom.parentNode.removeChild(dom);\n return next;\n}\n// Helper class for incrementally updating a tree of mark descs and\n// the widget and node descs inside of them.\nclass ViewTreeUpdater {\n constructor(top, lock, view) {\n this.lock = lock;\n this.view = view;\n // Index into `this.top`'s child array, represents the current\n // update position.\n this.index = 0;\n // When entering a mark, the current top and index are pushed\n // onto this.\n this.stack = [];\n // Tracks whether anything was changed\n this.changed = false;\n this.top = top;\n this.preMatch = preMatch(top.node.content, top);\n }\n // Destroy and remove the children between the given indices in\n // `this.top`.\n destroyBetween(start, end) {\n if (start == end)\n return;\n for (let i = start; i < end; i++)\n this.top.children[i].destroy();\n this.top.children.splice(start, end - start);\n this.changed = true;\n }\n // Destroy all remaining children in `this.top`.\n destroyRest() {\n this.destroyBetween(this.index, this.top.children.length);\n }\n // Sync the current stack of mark descs with the given array of\n // marks, reusing existing mark descs when possible.\n syncToMarks(marks, inline, view) {\n let keep = 0, depth = this.stack.length >> 1;\n let maxKeep = Math.min(depth, marks.length);\n while (keep < maxKeep &&\n (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1])\n .matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)\n keep++;\n while (keep < depth) {\n this.destroyRest();\n this.top.dirty = NOT_DIRTY;\n this.index = this.stack.pop();\n this.top = this.stack.pop();\n depth--;\n }\n while (depth < marks.length) {\n this.stack.push(this.top, this.index + 1);\n let found = -1;\n for (let i = this.index; i < Math.min(this.index + 3, this.top.children.length); i++) {\n let next = this.top.children[i];\n if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {\n found = i;\n break;\n }\n }\n if (found > -1) {\n if (found > this.index) {\n this.changed = true;\n this.destroyBetween(this.index, found);\n }\n this.top = this.top.children[this.index];\n }\n else {\n let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);\n this.top.children.splice(this.index, 0, markDesc);\n this.top = markDesc;\n this.changed = true;\n }\n this.index = 0;\n depth++;\n }\n }\n // Try to find a node desc matching the given data. Skip over it and\n // return true when successful.\n findNodeMatch(node, outerDeco, innerDeco, index) {\n let found = -1, targetDesc;\n if (index >= this.preMatch.index &&\n (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top &&\n targetDesc.matchesNode(node, outerDeco, innerDeco)) {\n found = this.top.children.indexOf(targetDesc, this.index);\n }\n else {\n for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) {\n let child = this.top.children[i];\n if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {\n found = i;\n break;\n }\n }\n }\n if (found < 0)\n return false;\n this.destroyBetween(this.index, found);\n this.index++;\n return true;\n }\n updateNodeAt(node, outerDeco, innerDeco, index, view) {\n let child = this.top.children[index];\n if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM)\n child.dirty = CONTENT_DIRTY;\n if (!child.update(node, outerDeco, innerDeco, view))\n return false;\n this.destroyBetween(this.index, index);\n this.index++;\n return true;\n }\n findIndexWithChild(domNode) {\n for (;;) {\n let parent = domNode.parentNode;\n if (!parent)\n return -1;\n if (parent == this.top.contentDOM) {\n let desc = domNode.pmViewDesc;\n if (desc)\n for (let i = this.index; i < this.top.children.length; i++) {\n if (this.top.children[i] == desc)\n return i;\n }\n return -1;\n }\n domNode = parent;\n }\n }\n // Try to update the next node, if any, to the given data. Checks\n // pre-matches to avoid overwriting nodes that could still be used.\n updateNextNode(node, outerDeco, innerDeco, view, index, pos) {\n for (let i = this.index; i < this.top.children.length; i++) {\n let next = this.top.children[i];\n if (next instanceof NodeViewDesc) {\n let preMatch = this.preMatch.matched.get(next);\n if (preMatch != null && preMatch != index)\n return false;\n let nextDOM = next.dom, updated;\n // Can't update if nextDOM is or contains this.lock, except if\n // it's a text node whose content already matches the new text\n // and whose decorations match the new ones.\n let locked = this.isLocked(nextDOM) &&\n !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text &&\n next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));\n if (!locked && next.update(node, outerDeco, innerDeco, view)) {\n this.destroyBetween(this.index, i);\n if (next.dom != nextDOM)\n this.changed = true;\n this.index++;\n return true;\n }\n else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {\n this.destroyBetween(this.index, i);\n this.top.children[this.index] = updated;\n if (updated.contentDOM) {\n updated.dirty = CONTENT_DIRTY;\n updated.updateChildren(view, pos + 1);\n updated.dirty = NOT_DIRTY;\n }\n this.changed = true;\n this.index++;\n return true;\n }\n break;\n }\n }\n return false;\n }\n // When a node with content is replaced by a different node with\n // identical content, move over its children.\n recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {\n if (next.dirty || node.isAtom || !next.children.length ||\n !next.node.content.eq(node.content) ||\n !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))\n return null;\n let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (wrapper.contentDOM) {\n wrapper.children = next.children;\n next.children = [];\n for (let ch of wrapper.children)\n ch.parent = wrapper;\n }\n next.destroy();\n return wrapper;\n }\n // Insert the node as a newly created node desc.\n addNode(node, outerDeco, innerDeco, view, pos) {\n let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (desc.contentDOM)\n desc.updateChildren(view, pos + 1);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n placeWidget(widget, view, pos) {\n let next = this.index < this.top.children.length ? this.top.children[this.index] : null;\n if (next && next.matchesWidget(widget) &&\n (widget == next.widget || !next.widget.type.toDOM.parentNode)) {\n this.index++;\n }\n else {\n let desc = new WidgetViewDesc(this.top, widget, view, pos);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n }\n // Make sure a textblock looks and behaves correctly in\n // contentEditable.\n addTextblockHacks() {\n let lastChild = this.top.children[this.index - 1], parent = this.top;\n while (lastChild instanceof MarkViewDesc) {\n parent = lastChild;\n lastChild = parent.children[parent.children.length - 1];\n }\n if (!lastChild || // Empty textblock\n !(lastChild instanceof TextViewDesc) ||\n /\\n$/.test(lastChild.node.text) ||\n (this.view.requiresGeckoHackNode && /\\s$/.test(lastChild.node.text))) {\n // Avoid bugs in Safari's cursor drawing (#1165) and Chrome's mouse selection (#1152)\n if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == \"false\")\n this.addHackNode(\"IMG\", parent);\n this.addHackNode(\"BR\", this.top);\n }\n }\n addHackNode(nodeName, parent) {\n if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {\n this.index++;\n }\n else {\n let dom = document.createElement(nodeName);\n if (nodeName == \"IMG\") {\n dom.className = \"ProseMirror-separator\";\n dom.alt = \"\";\n }\n if (nodeName == \"BR\")\n dom.className = \"ProseMirror-trailingBreak\";\n let hack = new TrailingHackViewDesc(this.top, [], dom, null);\n if (parent != this.top)\n parent.children.push(hack);\n else\n parent.children.splice(this.index++, 0, hack);\n this.changed = true;\n }\n }\n isLocked(node) {\n return this.lock && (node == this.lock || node.nodeType == 1 && node.contains(this.lock.parentNode));\n }\n}\n// Iterate from the end of the fragment and array of descs to find\n// directly matching ones, in order to avoid overeagerly reusing those\n// for other nodes. Returns the fragment index of the first node that\n// is part of the sequence of matched nodes at the end of the\n// fragment.\nfunction preMatch(frag, parentDesc) {\n let curDesc = parentDesc, descI = curDesc.children.length;\n let fI = frag.childCount, matched = new Map, matches = [];\n outer: while (fI > 0) {\n let desc;\n for (;;) {\n if (descI) {\n let next = curDesc.children[descI - 1];\n if (next instanceof MarkViewDesc) {\n curDesc = next;\n descI = next.children.length;\n }\n else {\n desc = next;\n descI--;\n break;\n }\n }\n else if (curDesc == parentDesc) {\n break outer;\n }\n else {\n // FIXME\n descI = curDesc.parent.children.indexOf(curDesc);\n curDesc = curDesc.parent;\n }\n }\n let node = desc.node;\n if (!node)\n continue;\n if (node != frag.child(fI - 1))\n break;\n --fI;\n matched.set(desc, fI);\n matches.push(desc);\n }\n return { index: fI, matched, matches: matches.reverse() };\n}\nfunction compareSide(a, b) {\n return a.type.side - b.type.side;\n}\n// This function abstracts iterating over the nodes and decorations in\n// a fragment. Calls `onNode` for each node, with its local and child\n// decorations. Splits text nodes when there is a decoration starting\n// or ending inside of them. Calls `onWidget` for each widget.\nfunction iterDeco(parent, deco, onWidget, onNode) {\n let locals = deco.locals(parent), offset = 0;\n // Simple, cheap variant for when there are no local decorations\n if (locals.length == 0) {\n for (let i = 0; i < parent.childCount; i++) {\n let child = parent.child(i);\n onNode(child, locals, deco.forChild(offset, child), i);\n offset += child.nodeSize;\n }\n return;\n }\n let decoIndex = 0, active = [], restNode = null;\n for (let parentIndex = 0;;) {\n let widget, widgets;\n while (decoIndex < locals.length && locals[decoIndex].to == offset) {\n let next = locals[decoIndex++];\n if (next.widget) {\n if (!widget)\n widget = next;\n else\n (widgets || (widgets = [widget])).push(next);\n }\n }\n if (widget) {\n if (widgets) {\n widgets.sort(compareSide);\n for (let i = 0; i < widgets.length; i++)\n onWidget(widgets[i], parentIndex, !!restNode);\n }\n else {\n onWidget(widget, parentIndex, !!restNode);\n }\n }\n let child, index;\n if (restNode) {\n index = -1;\n child = restNode;\n restNode = null;\n }\n else if (parentIndex < parent.childCount) {\n index = parentIndex;\n child = parent.child(parentIndex++);\n }\n else {\n break;\n }\n for (let i = 0; i < active.length; i++)\n if (active[i].to <= offset)\n active.splice(i--, 1);\n while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)\n active.push(locals[decoIndex++]);\n let end = offset + child.nodeSize;\n if (child.isText) {\n let cutAt = end;\n if (decoIndex < locals.length && locals[decoIndex].from < cutAt)\n cutAt = locals[decoIndex].from;\n for (let i = 0; i < active.length; i++)\n if (active[i].to < cutAt)\n cutAt = active[i].to;\n if (cutAt < end) {\n restNode = child.cut(cutAt - offset);\n child = child.cut(0, cutAt - offset);\n end = cutAt;\n index = -1;\n }\n }\n else {\n while (decoIndex < locals.length && locals[decoIndex].to < end)\n decoIndex++;\n }\n let outerDeco = child.isInline && !child.isLeaf ? active.filter(d => !d.inline) : active.slice();\n onNode(child, outerDeco, deco.forChild(offset, child), index);\n offset = end;\n }\n}\n// List markers in Mobile Safari will mysteriously disappear\n// sometimes. This works around that.\nfunction iosHacks(dom) {\n if (dom.nodeName == \"UL\" || dom.nodeName == \"OL\") {\n let oldCSS = dom.style.cssText;\n dom.style.cssText = oldCSS + \"; list-style: square !important\";\n window.getComputedStyle(dom).listStyle;\n dom.style.cssText = oldCSS;\n }\n}\n// Find a piece of text in an inline fragment, overlapping from-to\nfunction findTextInFragment(frag, text, from, to) {\n for (let i = 0, pos = 0; i < frag.childCount && pos <= to;) {\n let child = frag.child(i++), childStart = pos;\n pos += child.nodeSize;\n if (!child.isText)\n continue;\n let str = child.text;\n while (i < frag.childCount) {\n let next = frag.child(i++);\n pos += next.nodeSize;\n if (!next.isText)\n break;\n str += next.text;\n }\n if (pos >= from) {\n if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text)\n return to - text.length;\n let found = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1;\n if (found >= 0 && found + text.length + childStart >= from)\n return childStart + found;\n if (from == to && str.length >= (to + text.length) - childStart &&\n str.slice(to - childStart, to - childStart + text.length) == text)\n return to;\n }\n }\n return -1;\n}\n// Replace range from-to in an array of view descs with replacement\n// (may be null to just delete). This goes very much against the grain\n// of the rest of this code, which tends to create nodes with the\n// right shape in one go, rather than messing with them after\n// creation, but is necessary in the composition hack.\nfunction replaceNodes(nodes, from, to, view, replacement) {\n let result = [];\n for (let i = 0, off = 0; i < nodes.length; i++) {\n let child = nodes[i], start = off, end = off += child.size;\n if (start >= to || end <= from) {\n result.push(child);\n }\n else {\n if (start < from)\n result.push(child.slice(0, from - start, view));\n if (replacement) {\n result.push(replacement);\n replacement = undefined;\n }\n if (end > to)\n result.push(child.slice(to - start, child.size, view));\n }\n }\n return result;\n}\n\nfunction selectionFromDOM(view, origin = null) {\n let domSel = view.domSelectionRange(), doc = view.state.doc;\n if (!domSel.focusNode)\n return null;\n let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;\n let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);\n if (head < 0)\n return null;\n let $head = doc.resolve(head), anchor, selection;\n if (selectionCollapsed(domSel)) {\n anchor = head;\n while (nearestDesc && !nearestDesc.node)\n nearestDesc = nearestDesc.parent;\n let nearestDescNode = nearestDesc.node;\n if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent\n && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {\n let pos = nearestDesc.posBefore;\n selection = new NodeSelection(head == pos ? $head : doc.resolve(pos));\n }\n }\n else {\n if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {\n let min = head, max = head;\n for (let i = 0; i < domSel.rangeCount; i++) {\n let range = domSel.getRangeAt(i);\n min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));\n max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));\n }\n if (min < 0)\n return null;\n [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];\n $head = doc.resolve(head);\n }\n else {\n anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);\n }\n if (anchor < 0)\n return null;\n }\n let $anchor = doc.resolve(anchor);\n if (!selection) {\n let bias = origin == \"pointer\" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1;\n selection = selectionBetween(view, $anchor, $head, bias);\n }\n return selection;\n}\nfunction editorOwnsSelection(view) {\n return view.editable ? view.hasFocus() :\n hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);\n}\nfunction selectionToDOM(view, force = false) {\n let sel = view.state.selection;\n syncNodeSelection(view, sel);\n if (!editorOwnsSelection(view))\n return;\n // The delayed drag selection causes issues with Cell Selections\n // in Safari. And the drag selection delay is to workarond issues\n // which only present in Chrome.\n if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome) {\n let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;\n if (domSel.anchorNode && curSel.anchorNode &&\n isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) {\n view.input.mouseDown.delayedSelectionSync = true;\n view.domObserver.setCurSelection();\n return;\n }\n }\n view.domObserver.disconnectSelection();\n if (view.cursorWrapper) {\n selectCursorWrapper(view);\n }\n else {\n let { anchor, head } = sel, resetEditableFrom, resetEditableTo;\n if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {\n if (!sel.$from.parent.inlineContent)\n resetEditableFrom = temporarilyEditableNear(view, sel.from);\n if (!sel.empty && !sel.$from.parent.inlineContent)\n resetEditableTo = temporarilyEditableNear(view, sel.to);\n }\n view.docView.setSelection(anchor, head, view, force);\n if (brokenSelectBetweenUneditable) {\n if (resetEditableFrom)\n resetEditable(resetEditableFrom);\n if (resetEditableTo)\n resetEditable(resetEditableTo);\n }\n if (sel.visible) {\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }\n else {\n view.dom.classList.add(\"ProseMirror-hideselection\");\n if (\"onselectionchange\" in document)\n removeClassOnSelectionChange(view);\n }\n }\n view.domObserver.setCurSelection();\n view.domObserver.connectSelection();\n}\n// Kludge to work around Webkit not allowing a selection to start/end\n// between non-editable block nodes. We briefly make something\n// editable, set the selection, then set it uneditable again.\nconst brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;\nfunction temporarilyEditableNear(view, pos) {\n let { node, offset } = view.docView.domFromPos(pos, 0);\n let after = offset < node.childNodes.length ? node.childNodes[offset] : null;\n let before = offset ? node.childNodes[offset - 1] : null;\n if (safari && after && after.contentEditable == \"false\")\n return setEditable(after);\n if ((!after || after.contentEditable == \"false\") &&\n (!before || before.contentEditable == \"false\")) {\n if (after)\n return setEditable(after);\n else if (before)\n return setEditable(before);\n }\n}\nfunction setEditable(element) {\n element.contentEditable = \"true\";\n if (safari && element.draggable) {\n element.draggable = false;\n element.wasDraggable = true;\n }\n return element;\n}\nfunction resetEditable(element) {\n element.contentEditable = \"false\";\n if (element.wasDraggable) {\n element.draggable = true;\n element.wasDraggable = null;\n }\n}\nfunction removeClassOnSelectionChange(view) {\n let doc = view.dom.ownerDocument;\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n let domSel = view.domSelectionRange();\n let node = domSel.anchorNode, offset = domSel.anchorOffset;\n doc.addEventListener(\"selectionchange\", view.input.hideSelectionGuard = () => {\n if (domSel.anchorNode != node || domSel.anchorOffset != offset) {\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n setTimeout(() => {\n if (!editorOwnsSelection(view) || view.state.selection.visible)\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }, 20);\n }\n });\n}\nfunction selectCursorWrapper(view) {\n let domSel = view.domSelection(), range = document.createRange();\n if (!domSel)\n return;\n let node = view.cursorWrapper.dom, img = node.nodeName == \"IMG\";\n if (img)\n range.setStart(node.parentNode, domIndex(node) + 1);\n else\n range.setStart(node, 0);\n range.collapse(true);\n domSel.removeAllRanges();\n domSel.addRange(range);\n // Kludge to kill 'control selection' in IE11 when selecting an\n // invisible cursor wrapper, since that would result in those weird\n // resize handles and a selection that considers the absolutely\n // positioned wrapper, rather than the root editable node, the\n // focused element.\n if (!img && !view.state.selection.visible && ie && ie_version <= 11) {\n node.disabled = true;\n node.disabled = false;\n }\n}\nfunction syncNodeSelection(view, sel) {\n if (sel instanceof NodeSelection) {\n let desc = view.docView.descAt(sel.from);\n if (desc != view.lastSelectedViewDesc) {\n clearNodeSelection(view);\n if (desc)\n desc.selectNode();\n view.lastSelectedViewDesc = desc;\n }\n }\n else {\n clearNodeSelection(view);\n }\n}\n// Clear all DOM statefulness of the last node selection.\nfunction clearNodeSelection(view) {\n if (view.lastSelectedViewDesc) {\n if (view.lastSelectedViewDesc.parent)\n view.lastSelectedViewDesc.deselectNode();\n view.lastSelectedViewDesc = undefined;\n }\n}\nfunction selectionBetween(view, $anchor, $head, bias) {\n return view.someProp(\"createSelectionBetween\", f => f(view, $anchor, $head))\n || TextSelection.between($anchor, $head, bias);\n}\nfunction hasFocusAndSelection(view) {\n if (view.editable && !view.hasFocus())\n return false;\n return hasSelection(view);\n}\nfunction hasSelection(view) {\n let sel = view.domSelectionRange();\n if (!sel.anchorNode)\n return false;\n try {\n // Firefox will raise 'permission denied' errors when accessing\n // properties of `sel.anchorNode` when it's in a generated CSS\n // element.\n return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) &&\n (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode));\n }\n catch (_) {\n return false;\n }\n}\nfunction anchorInRightPlace(view) {\n let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);\n let domSel = view.domSelectionRange();\n return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);\n}\n\nfunction moveSelectionBlock(state, dir) {\n let { $anchor, $head } = state.selection;\n let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);\n let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;\n return $start && Selection.findFrom($start, dir);\n}\nfunction apply(view, sel) {\n view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());\n return true;\n}\nfunction selectHorizontally(view, dir, mods) {\n let sel = view.state.selection;\n if (sel instanceof TextSelection) {\n if (mods.indexOf(\"s\") > -1) {\n let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;\n if (!node || node.isText || !node.isLeaf)\n return false;\n let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));\n return apply(view, new TextSelection(sel.$anchor, $newHead));\n }\n else if (!sel.empty) {\n return false;\n }\n else if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n return false;\n }\n else if (!(mac && mods.indexOf(\"m\") > -1)) {\n let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;\n if (!node || node.isText)\n return false;\n let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;\n if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))\n return false;\n if (NodeSelection.isSelectable(node)) {\n return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));\n }\n else if (webkit) {\n // Chrome and Safari will introduce extra pointless cursor\n // positions around inline uneditable nodes, so we have to\n // take over and move the cursor past them (#937)\n return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));\n }\n else {\n return false;\n }\n }\n }\n else if (sel instanceof NodeSelection && sel.node.isInline) {\n return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));\n }\n else {\n let next = moveSelectionBlock(view.state, dir);\n if (next)\n return apply(view, next);\n return false;\n }\n}\nfunction nodeLen(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction isIgnorable(dom, dir) {\n let desc = dom.pmViewDesc;\n return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != \"BR\");\n}\nfunction skipIgnoredNodes(view, dir) {\n return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);\n}\n// Make sure the cursor isn't directly after one or more ignored\n// nodes, which will confuse the browser's cursor motion logic.\nfunction skipIgnoredNodesBefore(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let moveNode, moveOffset, force = false;\n // Gecko will do odd things when the selection is directly in front\n // of a non-editable node, so in that case, move it into the next\n // node if possible. Issue prosemirror/prosemirror#832.\n if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1))\n force = true;\n for (;;) {\n if (offset > 0) {\n if (node.nodeType != 1) {\n break;\n }\n else {\n let before = node.childNodes[offset - 1];\n if (isIgnorable(before, -1)) {\n moveNode = node;\n moveOffset = --offset;\n }\n else if (before.nodeType == 3) {\n node = before;\n offset = node.nodeValue.length;\n }\n else\n break;\n }\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let prev = node.previousSibling;\n while (prev && isIgnorable(prev, -1)) {\n moveNode = node.parentNode;\n moveOffset = domIndex(prev);\n prev = prev.previousSibling;\n }\n if (!prev) {\n node = node.parentNode;\n if (node == view.dom)\n break;\n offset = 0;\n }\n else {\n node = prev;\n offset = nodeLen(node);\n }\n }\n }\n if (force)\n setSelFocus(view, node, offset);\n else if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\n// Make sure the cursor isn't directly before one or more ignored\n// nodes.\nfunction skipIgnoredNodesAfter(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let len = nodeLen(node);\n let moveNode, moveOffset;\n for (;;) {\n if (offset < len) {\n if (node.nodeType != 1)\n break;\n let after = node.childNodes[offset];\n if (isIgnorable(after, 1)) {\n moveNode = node;\n moveOffset = ++offset;\n }\n else\n break;\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let next = node.nextSibling;\n while (next && isIgnorable(next, 1)) {\n moveNode = next.parentNode;\n moveOffset = domIndex(next) + 1;\n next = next.nextSibling;\n }\n if (!next) {\n node = node.parentNode;\n if (node == view.dom)\n break;\n offset = len = 0;\n }\n else {\n node = next;\n offset = 0;\n len = nodeLen(node);\n }\n }\n }\n if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\nfunction isBlockNode(dom) {\n let desc = dom.pmViewDesc;\n return desc && desc.node && desc.node.isBlock;\n}\nfunction textNodeAfter(node, offset) {\n while (node && offset == node.childNodes.length && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n while (node && offset < node.childNodes.length) {\n let next = node.childNodes[offset];\n if (next.nodeType == 3)\n return next;\n if (next.nodeType == 1 && next.contentEditable == \"false\")\n break;\n node = next;\n offset = 0;\n }\n}\nfunction textNodeBefore(node, offset) {\n while (node && !offset && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n while (node && offset) {\n let next = node.childNodes[offset - 1];\n if (next.nodeType == 3)\n return next;\n if (next.nodeType == 1 && next.contentEditable == \"false\")\n break;\n node = next;\n offset = node.childNodes.length;\n }\n}\nfunction setSelFocus(view, node, offset) {\n if (node.nodeType != 3) {\n let before, after;\n if (after = textNodeAfter(node, offset)) {\n node = after;\n offset = 0;\n }\n else if (before = textNodeBefore(node, offset)) {\n node = before;\n offset = before.nodeValue.length;\n }\n }\n let sel = view.domSelection();\n if (!sel)\n return;\n if (selectionCollapsed(sel)) {\n let range = document.createRange();\n range.setEnd(node, offset);\n range.setStart(node, offset);\n sel.removeAllRanges();\n sel.addRange(range);\n }\n else if (sel.extend) {\n sel.extend(node, offset);\n }\n view.domObserver.setCurSelection();\n let { state } = view;\n // If no state update ends up happening, reset the selection.\n setTimeout(() => {\n if (view.state == state)\n selectionToDOM(view);\n }, 50);\n}\nfunction findDirection(view, pos) {\n let $pos = view.state.doc.resolve(pos);\n if (!(chrome || windows) && $pos.parent.inlineContent) {\n let coords = view.coordsAtPos(pos);\n if (pos > $pos.start()) {\n let before = view.coordsAtPos(pos - 1);\n let mid = (before.top + before.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)\n return before.left < coords.left ? \"ltr\" : \"rtl\";\n }\n if (pos < $pos.end()) {\n let after = view.coordsAtPos(pos + 1);\n let mid = (after.top + after.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)\n return after.left > coords.left ? \"ltr\" : \"rtl\";\n }\n }\n let computed = getComputedStyle(view.dom).direction;\n return computed == \"rtl\" ? \"rtl\" : \"ltr\";\n}\n// Check whether vertical selection motion would involve node\n// selections. If so, apply it (if not, the result is left to the\n// browser)\nfunction selectVertically(view, dir, mods) {\n let sel = view.state.selection;\n if (sel instanceof TextSelection && !sel.empty || mods.indexOf(\"s\") > -1)\n return false;\n if (mac && mods.indexOf(\"m\") > -1)\n return false;\n let { $from, $to } = sel;\n if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? \"up\" : \"down\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n }\n if (!$from.parent.inlineContent) {\n let side = dir < 0 ? $from : $to;\n let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);\n return beyond ? apply(view, beyond) : false;\n }\n return false;\n}\nfunction stopNativeHorizontalDelete(view, dir) {\n if (!(view.state.selection instanceof TextSelection))\n return true;\n let { $head, $anchor, empty } = view.state.selection;\n if (!$head.sameParent($anchor))\n return true;\n if (!empty)\n return false;\n if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\"))\n return true;\n let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);\n if (nextNode && !nextNode.isText) {\n let tr = view.state.tr;\n if (dir < 0)\n tr.delete($head.pos - nextNode.nodeSize, $head.pos);\n else\n tr.delete($head.pos, $head.pos + nextNode.nodeSize);\n view.dispatch(tr);\n return true;\n }\n return false;\n}\nfunction switchEditable(view, node, state) {\n view.domObserver.stop();\n node.contentEditable = state;\n view.domObserver.start();\n}\n// Issue #867 / #1090 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821\n// In which Safari (and at some point in the past, Chrome) does really\n// wrong things when the down arrow is pressed when the cursor is\n// directly at the start of a textblock and has an uneditable node\n// after it\nfunction safariDownArrowBug(view) {\n if (!safari || view.state.selection.$head.parentOffset > 0)\n return false;\n let { focusNode, focusOffset } = view.domSelectionRange();\n if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 &&\n focusNode.firstChild && focusNode.firstChild.contentEditable == \"false\") {\n let child = focusNode.firstChild;\n switchEditable(view, child, \"true\");\n setTimeout(() => switchEditable(view, child, \"false\"), 20);\n }\n return false;\n}\n// A backdrop key mapping used to make sure we always suppress keys\n// that have a dangerous default effect, even if the commands they are\n// bound to return false, and to make sure that cursor-motion keys\n// find a cursor (as opposed to a node selection) when pressed. For\n// cursor-motion keys, the code in the handlers also takes care of\n// block selections.\nfunction getMods(event) {\n let result = \"\";\n if (event.ctrlKey)\n result += \"c\";\n if (event.metaKey)\n result += \"m\";\n if (event.altKey)\n result += \"a\";\n if (event.shiftKey)\n result += \"s\";\n return result;\n}\nfunction captureKeyDown(view, event) {\n let code = event.keyCode, mods = getMods(event);\n if (code == 8 || (mac && code == 72 && mods == \"c\")) { // Backspace, Ctrl-h on Mac\n return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);\n }\n else if ((code == 46 && !event.shiftKey) || (mac && code == 68 && mods == \"c\")) { // Delete, Ctrl-d on Mac\n return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);\n }\n else if (code == 13 || code == 27) { // Enter, Esc\n return true;\n }\n else if (code == 37 || (mac && code == 66 && mods == \"c\")) { // Left arrow, Ctrl-b on Mac\n let dir = code == 37 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? -1 : 1) : -1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 39 || (mac && code == 70 && mods == \"c\")) { // Right arrow, Ctrl-f on Mac\n let dir = code == 39 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? 1 : -1) : 1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 38 || (mac && code == 80 && mods == \"c\")) { // Up arrow, Ctrl-p on Mac\n return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);\n }\n else if (code == 40 || (mac && code == 78 && mods == \"c\")) { // Down arrow, Ctrl-n on Mac\n return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);\n }\n else if (mods == (mac ? \"m\" : \"c\") &&\n (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz]\n return true;\n }\n return false;\n}\n\nfunction serializeForClipboard(view, slice) {\n view.someProp(\"transformCopied\", f => { slice = f(slice, view); });\n let context = [], { content, openStart, openEnd } = slice;\n while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {\n openStart--;\n openEnd--;\n let node = content.firstChild;\n context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);\n content = node.content;\n }\n let serializer = view.someProp(\"clipboardSerializer\") || DOMSerializer.fromSchema(view.state.schema);\n let doc = detachedDoc(), wrap = doc.createElement(\"div\");\n wrap.appendChild(serializer.serializeFragment(content, { document: doc }));\n let firstChild = wrap.firstChild, needsWrap, wrappers = 0;\n while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {\n for (let i = needsWrap.length - 1; i >= 0; i--) {\n let wrapper = doc.createElement(needsWrap[i]);\n while (wrap.firstChild)\n wrapper.appendChild(wrap.firstChild);\n wrap.appendChild(wrapper);\n wrappers++;\n }\n firstChild = wrap.firstChild;\n }\n if (firstChild && firstChild.nodeType == 1)\n firstChild.setAttribute(\"data-pm-slice\", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : \"\"} ${JSON.stringify(context)}`);\n let text = view.someProp(\"clipboardTextSerializer\", f => f(slice, view)) ||\n slice.content.textBetween(0, slice.content.size, \"\\n\\n\");\n return { dom: wrap, text, slice };\n}\n// Read a slice of content from the clipboard (or drop data).\nfunction parseFromClipboard(view, text, html, plainText, $context) {\n let inCode = $context.parent.type.spec.code;\n let dom, slice;\n if (!html && !text)\n return null;\n let asText = text && (plainText || inCode || !html);\n if (asText) {\n view.someProp(\"transformPastedText\", f => { text = f(text, inCode || plainText, view); });\n if (inCode)\n return text ? new Slice(Fragment.from(view.state.schema.text(text.replace(/\\r\\n?/g, \"\\n\"))), 0, 0) : Slice.empty;\n let parsed = view.someProp(\"clipboardTextParser\", f => f(text, $context, plainText, view));\n if (parsed) {\n slice = parsed;\n }\n else {\n let marks = $context.marks();\n let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema);\n dom = document.createElement(\"div\");\n text.split(/(?:\\r\\n?|\\n)+/).forEach(block => {\n let p = dom.appendChild(document.createElement(\"p\"));\n if (block)\n p.appendChild(serializer.serializeNode(schema.text(block, marks)));\n });\n }\n }\n else {\n view.someProp(\"transformPastedHTML\", f => { html = f(html, view); });\n dom = readHTML(html);\n if (webkit)\n restoreReplacedSpaces(dom);\n }\n let contextNode = dom && dom.querySelector(\"[data-pm-slice]\");\n let sliceData = contextNode && /^(\\d+) (\\d+)(?: -(\\d+))? (.*)/.exec(contextNode.getAttribute(\"data-pm-slice\") || \"\");\n if (sliceData && sliceData[3])\n for (let i = +sliceData[3]; i > 0; i--) {\n let child = dom.firstChild;\n while (child && child.nodeType != 1)\n child = child.nextSibling;\n if (!child)\n break;\n dom = child;\n }\n if (!slice) {\n let parser = view.someProp(\"clipboardParser\") || view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n slice = parser.parseSlice(dom, {\n preserveWhitespace: !!(asText || sliceData),\n context: $context,\n ruleFromNode(dom) {\n if (dom.nodeName == \"BR\" && !dom.nextSibling &&\n dom.parentNode && !inlineParents.test(dom.parentNode.nodeName))\n return { ignore: true };\n return null;\n }\n });\n }\n if (sliceData) {\n slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4]);\n }\n else { // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent\n slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true);\n if (slice.openStart || slice.openEnd) {\n let openStart = 0, openEnd = 0;\n for (let node = slice.content.firstChild; openStart < slice.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { }\n for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { }\n slice = closeSlice(slice, openStart, openEnd);\n }\n }\n view.someProp(\"transformPasted\", f => { slice = f(slice, view); });\n return slice;\n}\nconst inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;\n// Takes a slice parsed with parseSlice, which means there hasn't been\n// any content-expression checking done on the top nodes, tries to\n// find a parent node in the current context that might fit the nodes,\n// and if successful, rebuilds the slice so that it fits into that parent.\n//\n// This addresses the problem that Transform.replace expects a\n// coherent slice, and will fail to place a set of siblings that don't\n// fit anywhere in the schema.\nfunction normalizeSiblings(fragment, $context) {\n if (fragment.childCount < 2)\n return fragment;\n for (let d = $context.depth; d >= 0; d--) {\n let parent = $context.node(d);\n let match = parent.contentMatchAt($context.index(d));\n let lastWrap, result = [];\n fragment.forEach(node => {\n if (!result)\n return;\n let wrap = match.findWrapping(node.type), inLast;\n if (!wrap)\n return result = null;\n if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) {\n result[result.length - 1] = inLast;\n }\n else {\n if (result.length)\n result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);\n let wrapped = withWrappers(node, wrap);\n result.push(wrapped);\n match = match.matchType(wrapped.type);\n lastWrap = wrap;\n }\n });\n if (result)\n return Fragment.from(result);\n }\n return fragment;\n}\nfunction withWrappers(node, wrap, from = 0) {\n for (let i = wrap.length - 1; i >= from; i--)\n node = wrap[i].create(null, Fragment.from(node));\n return node;\n}\n// Used to group adjacent nodes wrapped in similar parents by\n// normalizeSiblings into the same parent node\nfunction addToSibling(wrap, lastWrap, node, sibling, depth) {\n if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) {\n let inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1);\n if (inner)\n return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));\n let match = sibling.contentMatchAt(sibling.childCount);\n if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1]))\n return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1))));\n }\n}\nfunction closeRight(node, depth) {\n if (depth == 0)\n return node;\n let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));\n let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);\n return node.copy(fragment.append(fill));\n}\nfunction closeRange(fragment, side, from, to, depth, openEnd) {\n let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;\n if (fragment.childCount > 1)\n openEnd = 0;\n if (depth < to - 1)\n inner = closeRange(inner, side, from, to, depth + 1, openEnd);\n if (depth >= from)\n inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner)\n : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true));\n return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner));\n}\nfunction closeSlice(slice, openStart, openEnd) {\n if (openStart < slice.openStart)\n slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd);\n if (openEnd < slice.openEnd)\n slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd);\n return slice;\n}\n// Trick from jQuery -- some elements must be wrapped in other\n// elements for innerHTML to work. I.e. if you do `div.innerHTML =\n// \"
.. \"` the table cells are ignored.\nconst wrapMap = {\n thead: [\"table\"],\n tbody: [\"table\"],\n tfoot: [\"table\"],\n caption: [\"table\"],\n colgroup: [\"table\"],\n col: [\"table\", \"colgroup\"],\n tr: [\"table\", \"tbody\"],\n td: [\"table\", \"tbody\", \"tr\"],\n th: [\"table\", \"tbody\", \"tr\"]\n};\nlet _detachedDoc = null;\nfunction detachedDoc() {\n return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument(\"title\"));\n}\nlet _policy = null;\nfunction maybeWrapTrusted(html) {\n let trustedTypes = window.trustedTypes;\n if (!trustedTypes)\n return html;\n // With the require-trusted-types-for CSP, Chrome will block\n // innerHTML, even on a detached document. This wraps the string in\n // a way that makes the browser allow us to use its parser again.\n if (!_policy)\n _policy = trustedTypes.createPolicy(\"ProseMirrorClipboard\", { createHTML: (s) => s });\n return _policy.createHTML(html);\n}\nfunction readHTML(html) {\n let metas = /^(\\s* ]*>)*/.exec(html);\n if (metas)\n html = html.slice(metas[0].length);\n let elt = detachedDoc().createElement(\"div\");\n let firstTag = /<([a-z][^>\\s]+)/i.exec(html), wrap;\n if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()])\n html = wrap.map(n => \"<\" + n + \">\").join(\"\") + html + wrap.map(n => \"\" + n + \">\").reverse().join(\"\");\n elt.innerHTML = maybeWrapTrusted(html);\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n elt = elt.querySelector(wrap[i]) || elt;\n return elt;\n}\n// Webkit browsers do some hard-to-predict replacement of regular\n// spaces with non-breaking spaces when putting content on the\n// clipboard. This tries to convert such non-breaking spaces (which\n// will be wrapped in a plain span on Chrome, a span with class\n// Apple-converted-space on Safari) back to regular spaces.\nfunction restoreReplacedSpaces(dom) {\n let nodes = dom.querySelectorAll(chrome ? \"span:not([class]):not([style])\" : \"span.Apple-converted-space\");\n for (let i = 0; i < nodes.length; i++) {\n let node = nodes[i];\n if (node.childNodes.length == 1 && node.textContent == \"\\u00a0\" && node.parentNode)\n node.parentNode.replaceChild(dom.ownerDocument.createTextNode(\" \"), node);\n }\n}\nfunction addContext(slice, context) {\n if (!slice.size)\n return slice;\n let schema = slice.content.firstChild.type.schema, array;\n try {\n array = JSON.parse(context);\n }\n catch (e) {\n return slice;\n }\n let { content, openStart, openEnd } = slice;\n for (let i = array.length - 2; i >= 0; i -= 2) {\n let type = schema.nodes[array[i]];\n if (!type || type.hasRequiredAttrs())\n break;\n content = Fragment.from(type.create(array[i + 1], content));\n openStart++;\n openEnd++;\n }\n return new Slice(content, openStart, openEnd);\n}\n\n// A collection of DOM events that occur within the editor, and callback functions\n// to invoke when the event fires.\nconst handlers = {};\nconst editHandlers = {};\nconst passiveHandlers = { touchstart: true, touchmove: true };\nclass InputState {\n constructor() {\n this.shiftKey = false;\n this.mouseDown = null;\n this.lastKeyCode = null;\n this.lastKeyCodeTime = 0;\n this.lastClick = { time: 0, x: 0, y: 0, type: \"\" };\n this.lastSelectionOrigin = null;\n this.lastSelectionTime = 0;\n this.lastIOSEnter = 0;\n this.lastIOSEnterFallbackTimeout = -1;\n this.lastFocus = 0;\n this.lastTouch = 0;\n this.lastChromeDelete = 0;\n this.composing = false;\n this.compositionNode = null;\n this.composingTimeout = -1;\n this.compositionNodes = [];\n this.compositionEndedAt = -2e8;\n this.compositionID = 1;\n // Set to a composition ID when there are pending changes at compositionend\n this.compositionPendingChanges = 0;\n this.domChangeCount = 0;\n this.eventHandlers = Object.create(null);\n this.hideSelectionGuard = null;\n }\n}\nfunction initInput(view) {\n for (let event in handlers) {\n let handler = handlers[event];\n view.dom.addEventListener(event, view.input.eventHandlers[event] = (event) => {\n if (eventBelongsToView(view, event) && !runCustomHandler(view, event) &&\n (view.editable || !(event.type in editHandlers)))\n handler(view, event);\n }, passiveHandlers[event] ? { passive: true } : undefined);\n }\n // On Safari, for reasons beyond my understanding, adding an input\n // event handler makes an issue where the composition vanishes when\n // you press enter go away.\n if (safari)\n view.dom.addEventListener(\"input\", () => null);\n ensureListeners(view);\n}\nfunction setSelectionOrigin(view, origin) {\n view.input.lastSelectionOrigin = origin;\n view.input.lastSelectionTime = Date.now();\n}\nfunction destroyInput(view) {\n view.domObserver.stop();\n for (let type in view.input.eventHandlers)\n view.dom.removeEventListener(type, view.input.eventHandlers[type]);\n clearTimeout(view.input.composingTimeout);\n clearTimeout(view.input.lastIOSEnterFallbackTimeout);\n}\nfunction ensureListeners(view) {\n view.someProp(\"handleDOMEvents\", currentHandlers => {\n for (let type in currentHandlers)\n if (!view.input.eventHandlers[type])\n view.dom.addEventListener(type, view.input.eventHandlers[type] = event => runCustomHandler(view, event));\n });\n}\nfunction runCustomHandler(view, event) {\n return view.someProp(\"handleDOMEvents\", handlers => {\n let handler = handlers[event.type];\n return handler ? handler(view, event) || event.defaultPrevented : false;\n });\n}\nfunction eventBelongsToView(view, event) {\n if (!event.bubbles)\n return true;\n if (event.defaultPrevented)\n return false;\n for (let node = event.target; node != view.dom; node = node.parentNode)\n if (!node || node.nodeType == 11 ||\n (node.pmViewDesc && node.pmViewDesc.stopEvent(event)))\n return false;\n return true;\n}\nfunction dispatchEvent(view, event) {\n if (!runCustomHandler(view, event) && handlers[event.type] &&\n (view.editable || !(event.type in editHandlers)))\n handlers[event.type](view, event);\n}\neditHandlers.keydown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.keyCode == 16 || event.shiftKey;\n if (inOrNearComposition(view, event))\n return;\n view.input.lastKeyCode = event.keyCode;\n view.input.lastKeyCodeTime = Date.now();\n // Suppress enter key events on Chrome Android, because those tend\n // to be part of a confused sequence of composition events fired,\n // and handling them eagerly tends to corrupt the input.\n if (android && chrome && event.keyCode == 13)\n return;\n if (event.keyCode != 229)\n view.domObserver.forceFlush();\n // On iOS, if we preventDefault enter key presses, the virtual\n // keyboard gets confused. So the hack here is to set a flag that\n // makes the DOM change code recognize that what just happens should\n // be replaced by whatever the Enter key handlers do.\n if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {\n let now = Date.now();\n view.input.lastIOSEnter = now;\n view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {\n if (view.input.lastIOSEnter == now) {\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")));\n view.input.lastIOSEnter = 0;\n }\n }, 200);\n }\n else if (view.someProp(\"handleKeyDown\", f => f(view, event)) || captureKeyDown(view, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"key\");\n }\n};\neditHandlers.keyup = (view, event) => {\n if (event.keyCode == 16)\n view.input.shiftKey = false;\n};\neditHandlers.keypress = (view, _event) => {\n let event = _event;\n if (inOrNearComposition(view, event) || !event.charCode ||\n event.ctrlKey && !event.altKey || mac && event.metaKey)\n return;\n if (view.someProp(\"handleKeyPress\", f => f(view, event))) {\n event.preventDefault();\n return;\n }\n let sel = view.state.selection;\n if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {\n let text = String.fromCharCode(event.charCode);\n if (!/[\\r\\n]/.test(text) && !view.someProp(\"handleTextInput\", f => f(view, sel.$from.pos, sel.$to.pos, text)))\n view.dispatch(view.state.tr.insertText(text).scrollIntoView());\n event.preventDefault();\n }\n};\nfunction eventCoords(event) { return { left: event.clientX, top: event.clientY }; }\nfunction isNear(event, click) {\n let dx = click.x - event.clientX, dy = click.y - event.clientY;\n return dx * dx + dy * dy < 100;\n}\nfunction runHandlerOnContext(view, propName, pos, inside, event) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n if (view.someProp(propName, f => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true)\n : f(view, pos, $pos.node(i), $pos.before(i), event, false)))\n return true;\n }\n return false;\n}\nfunction updateSelection(view, selection, origin) {\n if (!view.focused)\n view.focus();\n if (view.state.selection.eq(selection))\n return;\n let tr = view.state.tr.setSelection(selection);\n if (origin == \"pointer\")\n tr.setMeta(\"pointer\", true);\n view.dispatch(tr);\n}\nfunction selectClickedLeaf(view, inside) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;\n if (node && node.isAtom && NodeSelection.isSelectable(node)) {\n updateSelection(view, new NodeSelection($pos), \"pointer\");\n return true;\n }\n return false;\n}\nfunction selectClickedNode(view, inside) {\n if (inside == -1)\n return false;\n let sel = view.state.selection, selectedNode, selectAt;\n if (sel instanceof NodeSelection)\n selectedNode = sel.node;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n if (NodeSelection.isSelectable(node)) {\n if (selectedNode && sel.$from.depth > 0 &&\n i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)\n selectAt = $pos.before(sel.$from.depth);\n else\n selectAt = $pos.before(i);\n break;\n }\n }\n if (selectAt != null) {\n updateSelection(view, NodeSelection.create(view.state.doc, selectAt), \"pointer\");\n return true;\n }\n else {\n return false;\n }\n}\nfunction handleSingleClick(view, pos, inside, event, selectNode) {\n return runHandlerOnContext(view, \"handleClickOn\", pos, inside, event) ||\n view.someProp(\"handleClick\", f => f(view, pos, event)) ||\n (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));\n}\nfunction handleDoubleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleDoubleClickOn\", pos, inside, event) ||\n view.someProp(\"handleDoubleClick\", f => f(view, pos, event));\n}\nfunction handleTripleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleTripleClickOn\", pos, inside, event) ||\n view.someProp(\"handleTripleClick\", f => f(view, pos, event)) ||\n defaultTripleClick(view, inside, event);\n}\nfunction defaultTripleClick(view, inside, event) {\n if (event.button != 0)\n return false;\n let doc = view.state.doc;\n if (inside == -1) {\n if (doc.inlineContent) {\n updateSelection(view, TextSelection.create(doc, 0, doc.content.size), \"pointer\");\n return true;\n }\n return false;\n }\n let $pos = doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n let nodePos = $pos.before(i);\n if (node.inlineContent)\n updateSelection(view, TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size), \"pointer\");\n else if (NodeSelection.isSelectable(node))\n updateSelection(view, NodeSelection.create(doc, nodePos), \"pointer\");\n else\n continue;\n return true;\n }\n}\nfunction forceDOMFlush(view) {\n return endComposition(view);\n}\nconst selectNodeModifier = mac ? \"metaKey\" : \"ctrlKey\";\nhandlers.mousedown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.shiftKey;\n let flushed = forceDOMFlush(view);\n let now = Date.now(), type = \"singleClick\";\n if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier]) {\n if (view.input.lastClick.type == \"singleClick\")\n type = \"doubleClick\";\n else if (view.input.lastClick.type == \"doubleClick\")\n type = \"tripleClick\";\n }\n view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type };\n let pos = view.posAtCoords(eventCoords(event));\n if (!pos)\n return;\n if (type == \"singleClick\") {\n if (view.input.mouseDown)\n view.input.mouseDown.done();\n view.input.mouseDown = new MouseDown(view, pos, event, !!flushed);\n }\n else if ((type == \"doubleClick\" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"pointer\");\n }\n};\nclass MouseDown {\n constructor(view, pos, event, flushed) {\n this.view = view;\n this.pos = pos;\n this.event = event;\n this.flushed = flushed;\n this.delayedSelectionSync = false;\n this.mightDrag = null;\n this.startDoc = view.state.doc;\n this.selectNode = !!event[selectNodeModifier];\n this.allowDefault = event.shiftKey;\n let targetNode, targetPos;\n if (pos.inside > -1) {\n targetNode = view.state.doc.nodeAt(pos.inside);\n targetPos = pos.inside;\n }\n else {\n let $pos = view.state.doc.resolve(pos.pos);\n targetNode = $pos.parent;\n targetPos = $pos.depth ? $pos.before() : 0;\n }\n const target = flushed ? null : event.target;\n const targetDesc = target ? view.docView.nearestDesc(target, true) : null;\n this.target = targetDesc && targetDesc.dom.nodeType == 1 ? targetDesc.dom : null;\n let { selection } = view.state;\n if (event.button == 0 &&\n targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false ||\n selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)\n this.mightDrag = {\n node: targetNode,\n pos: targetPos,\n addAttr: !!(this.target && !this.target.draggable),\n setUneditable: !!(this.target && gecko && !this.target.hasAttribute(\"contentEditable\"))\n };\n if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr)\n this.target.draggable = true;\n if (this.mightDrag.setUneditable)\n setTimeout(() => {\n if (this.view.input.mouseDown == this)\n this.target.setAttribute(\"contentEditable\", \"false\");\n }, 20);\n this.view.domObserver.start();\n }\n view.root.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n view.root.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n setSelectionOrigin(view, \"pointer\");\n }\n done() {\n this.view.root.removeEventListener(\"mouseup\", this.up);\n this.view.root.removeEventListener(\"mousemove\", this.move);\n if (this.mightDrag && this.target) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr)\n this.target.removeAttribute(\"draggable\");\n if (this.mightDrag.setUneditable)\n this.target.removeAttribute(\"contentEditable\");\n this.view.domObserver.start();\n }\n if (this.delayedSelectionSync)\n setTimeout(() => selectionToDOM(this.view));\n this.view.input.mouseDown = null;\n }\n up(event) {\n this.done();\n if (!this.view.dom.contains(event.target))\n return;\n let pos = this.pos;\n if (this.view.state.doc != this.startDoc)\n pos = this.view.posAtCoords(eventCoords(event));\n this.updateAllowDefault(event);\n if (this.allowDefault || !pos) {\n setSelectionOrigin(this.view, \"pointer\");\n }\n else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {\n event.preventDefault();\n }\n else if (event.button == 0 &&\n (this.flushed ||\n // Safari ignores clicks on draggable elements\n (safari && this.mightDrag && !this.mightDrag.node.isAtom) ||\n // Chrome will sometimes treat a node selection as a\n // cursor, but still report that the node is selected\n // when asked through getSelection. You'll then get a\n // situation where clicking at the point where that\n // (hidden) cursor is doesn't change the selection, and\n // thus doesn't get a reaction from ProseMirror. This\n // works around that.\n (chrome && !this.view.state.selection.visible &&\n Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2))) {\n updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), \"pointer\");\n event.preventDefault();\n }\n else {\n setSelectionOrigin(this.view, \"pointer\");\n }\n }\n move(event) {\n this.updateAllowDefault(event);\n setSelectionOrigin(this.view, \"pointer\");\n if (event.buttons == 0)\n this.done();\n }\n updateAllowDefault(event) {\n if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 ||\n Math.abs(this.event.y - event.clientY) > 4))\n this.allowDefault = true;\n }\n}\nhandlers.touchstart = view => {\n view.input.lastTouch = Date.now();\n forceDOMFlush(view);\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.touchmove = view => {\n view.input.lastTouch = Date.now();\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.contextmenu = view => forceDOMFlush(view);\nfunction inOrNearComposition(view, event) {\n if (view.composing)\n return true;\n // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.\n // On Japanese input method editors (IMEs), the Enter key is used to confirm character\n // selection. On Safari, when Enter is pressed, compositionend and keydown events are\n // emitted. The keydown event triggers newline insertion, which we don't want.\n // This method returns true if the keydown event should be ignored.\n // We only ignore it once, as pressing Enter a second time *should* insert a newline.\n // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp.\n // This guards against the case where compositionend is triggered without the keyboard\n // (e.g. character confirmation may be done with the mouse), and keydown is triggered\n // afterwards- we wouldn't want to ignore the keydown event in this case.\n if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) {\n view.input.compositionEndedAt = -2e8;\n return true;\n }\n return false;\n}\n// Drop active composition after 5 seconds of inactivity on Android\nconst timeoutComposition = android ? 5000 : -1;\neditHandlers.compositionstart = editHandlers.compositionupdate = view => {\n if (!view.composing) {\n view.domObserver.flush();\n let { state } = view, $pos = state.selection.$to;\n if (state.selection instanceof TextSelection &&\n (state.storedMarks ||\n (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(m => m.type.spec.inclusive === false)))) {\n // Need to wrap the cursor in mark nodes different from the ones in the DOM context\n view.markCursor = view.state.storedMarks || $pos.marks();\n endComposition(view, true);\n view.markCursor = null;\n }\n else {\n endComposition(view, !state.selection.empty);\n // In firefox, if the cursor is after but outside a marked node,\n // the inserted text won't inherit the marks. So this moves it\n // inside if necessary.\n if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {\n let sel = view.domSelectionRange();\n for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0;) {\n let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];\n if (!before)\n break;\n if (before.nodeType == 3) {\n let sel = view.domSelection();\n if (sel)\n sel.collapse(before, before.nodeValue.length);\n break;\n }\n else {\n node = before;\n offset = -1;\n }\n }\n }\n }\n view.input.composing = true;\n }\n scheduleComposeEnd(view, timeoutComposition);\n};\neditHandlers.compositionend = (view, event) => {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = event.timeStamp;\n view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;\n view.input.compositionNode = null;\n if (view.input.compositionPendingChanges)\n Promise.resolve().then(() => view.domObserver.flush());\n view.input.compositionID++;\n scheduleComposeEnd(view, 20);\n }\n};\nfunction scheduleComposeEnd(view, delay) {\n clearTimeout(view.input.composingTimeout);\n if (delay > -1)\n view.input.composingTimeout = setTimeout(() => endComposition(view), delay);\n}\nfunction clearComposition(view) {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = timestampFromCustomEvent();\n }\n while (view.input.compositionNodes.length > 0)\n view.input.compositionNodes.pop().markParentsDirty();\n}\nfunction findCompositionNode(view) {\n let sel = view.domSelectionRange();\n if (!sel.focusNode)\n return null;\n let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);\n let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);\n if (textBefore && textAfter && textBefore != textAfter) {\n let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;\n if (textBefore == lastChanged || textAfter == lastChanged)\n return lastChanged;\n if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {\n return textAfter;\n }\n else if (view.input.compositionNode == textAfter) {\n let descBefore = textBefore.pmViewDesc;\n if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))\n return textAfter;\n }\n }\n return textBefore || textAfter;\n}\nfunction timestampFromCustomEvent() {\n let event = document.createEvent(\"Event\");\n event.initEvent(\"event\", true, true);\n return event.timeStamp;\n}\n/**\n@internal\n*/\nfunction endComposition(view, restarting = false) {\n if (android && view.domObserver.flushingSoon >= 0)\n return;\n view.domObserver.forceFlush();\n clearComposition(view);\n if (restarting || view.docView && view.docView.dirty) {\n let sel = selectionFromDOM(view);\n if (sel && !sel.eq(view.state.selection))\n view.dispatch(view.state.tr.setSelection(sel));\n else if ((view.markCursor || restarting) && !view.state.selection.empty)\n view.dispatch(view.state.tr.deleteSelection());\n else\n view.updateState(view.state);\n return true;\n }\n return false;\n}\nfunction captureCopy(view, dom) {\n // The extra wrapper is somehow necessary on IE/Edge to prevent the\n // content from being mangled when it is put onto the clipboard\n if (!view.dom.parentNode)\n return;\n let wrap = view.dom.parentNode.appendChild(document.createElement(\"div\"));\n wrap.appendChild(dom);\n wrap.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n let sel = getSelection(), range = document.createRange();\n range.selectNodeContents(dom);\n // Done because IE will fire a selectionchange moving the selection\n // to its start when removeAllRanges is called and the editor still\n // has focus (which will mess up the editor's selection state).\n view.dom.blur();\n sel.removeAllRanges();\n sel.addRange(range);\n setTimeout(() => {\n if (wrap.parentNode)\n wrap.parentNode.removeChild(wrap);\n view.focus();\n }, 50);\n}\n// This is very crude, but unfortunately both these browsers _pretend_\n// that they have a clipboard API—all the objects and methods are\n// there, they just don't work, and they are hard to test.\nconst brokenClipboardAPI = (ie && ie_version < 15) ||\n (ios && webkit_version < 604);\nhandlers.copy = editHandlers.cut = (view, _event) => {\n let event = _event;\n let sel = view.state.selection, cut = event.type == \"cut\";\n if (sel.empty)\n return;\n // IE and Edge's clipboard interface is completely broken\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let slice = sel.content(), { dom, text } = serializeForClipboard(view, slice);\n if (data) {\n event.preventDefault();\n data.clearData();\n data.setData(\"text/html\", dom.innerHTML);\n data.setData(\"text/plain\", text);\n }\n else {\n captureCopy(view, dom);\n }\n if (cut)\n view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta(\"uiEvent\", \"cut\"));\n};\nfunction sliceSingleNode(slice) {\n return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null;\n}\nfunction capturePaste(view, event) {\n if (!view.dom.parentNode)\n return;\n let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;\n let target = view.dom.parentNode.appendChild(document.createElement(plainText ? \"textarea\" : \"div\"));\n if (!plainText)\n target.contentEditable = \"true\";\n target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n target.focus();\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n setTimeout(() => {\n view.focus();\n if (target.parentNode)\n target.parentNode.removeChild(target);\n if (plainText)\n doPaste(view, target.value, null, plain, event);\n else\n doPaste(view, target.textContent, target.innerHTML, plain, event);\n }, 50);\n}\nfunction doPaste(view, text, html, preferPlain, event) {\n let slice = parseFromClipboard(view, text, html, preferPlain, view.state.selection.$from);\n if (view.someProp(\"handlePaste\", f => f(view, event, slice || Slice.empty)))\n return true;\n if (!slice)\n return false;\n let singleNode = sliceSingleNode(slice);\n let tr = singleNode\n ? view.state.tr.replaceSelectionWith(singleNode, preferPlain)\n : view.state.tr.replaceSelection(slice);\n view.dispatch(tr.scrollIntoView().setMeta(\"paste\", true).setMeta(\"uiEvent\", \"paste\"));\n return true;\n}\nfunction getText(clipboardData) {\n let text = clipboardData.getData(\"text/plain\") || clipboardData.getData(\"Text\");\n if (text)\n return text;\n let uris = clipboardData.getData(\"text/uri-list\");\n return uris ? uris.replace(/\\r?\\n/g, \" \") : \"\";\n}\neditHandlers.paste = (view, _event) => {\n let event = _event;\n // Handling paste from JavaScript during composition is very poorly\n // handled by browsers, so as a dodgy but preferable kludge, we just\n // let the browser do its native thing there, except on Android,\n // where the editor is almost always composing.\n if (view.composing && !android)\n return;\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n if (data && doPaste(view, getText(data), data.getData(\"text/html\"), plain, event))\n event.preventDefault();\n else\n capturePaste(view, event);\n};\nclass Dragging {\n constructor(slice, move, node) {\n this.slice = slice;\n this.move = move;\n this.node = node;\n }\n}\nconst dragCopyModifier = mac ? \"altKey\" : \"ctrlKey\";\nhandlers.dragstart = (view, _event) => {\n let event = _event;\n let mouseDown = view.input.mouseDown;\n if (mouseDown)\n mouseDown.done();\n if (!event.dataTransfer)\n return;\n let sel = view.state.selection;\n let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));\n let node;\n if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;\n else if (mouseDown && mouseDown.mightDrag) {\n node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);\n }\n else if (event.target && event.target.nodeType == 1) {\n let desc = view.docView.nearestDesc(event.target, true);\n if (desc && desc.node.type.spec.draggable && desc != view.docView)\n node = NodeSelection.create(view.state.doc, desc.posBefore);\n }\n let draggedSlice = (node || view.state.selection).content();\n let { dom, text, slice } = serializeForClipboard(view, draggedSlice);\n // Pre-120 Chrome versions clear files when calling `clearData` (#1472)\n if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)\n event.dataTransfer.clearData();\n event.dataTransfer.setData(brokenClipboardAPI ? \"Text\" : \"text/html\", dom.innerHTML);\n // See https://github.com/ProseMirror/prosemirror/issues/1156\n event.dataTransfer.effectAllowed = \"copyMove\";\n if (!brokenClipboardAPI)\n event.dataTransfer.setData(\"text/plain\", text);\n view.dragging = new Dragging(slice, !event[dragCopyModifier], node);\n};\nhandlers.dragend = view => {\n let dragging = view.dragging;\n window.setTimeout(() => {\n if (view.dragging == dragging)\n view.dragging = null;\n }, 50);\n};\neditHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault();\neditHandlers.drop = (view, _event) => {\n let event = _event;\n let dragging = view.dragging;\n view.dragging = null;\n if (!event.dataTransfer)\n return;\n let eventPos = view.posAtCoords(eventCoords(event));\n if (!eventPos)\n return;\n let $mouse = view.state.doc.resolve(eventPos.pos);\n let slice = dragging && dragging.slice;\n if (slice) {\n view.someProp(\"transformPasted\", f => { slice = f(slice, view); });\n }\n else {\n slice = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData(\"text/html\"), false, $mouse);\n }\n let move = !!(dragging && !event[dragCopyModifier]);\n if (view.someProp(\"handleDrop\", f => f(view, event, slice || Slice.empty, move))) {\n event.preventDefault();\n return;\n }\n if (!slice)\n return;\n event.preventDefault();\n let insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos;\n if (insertPos == null)\n insertPos = $mouse.pos;\n let tr = view.state.tr;\n if (move) {\n let { node } = dragging;\n if (node)\n node.replace(tr);\n else\n tr.deleteSelection();\n }\n let pos = tr.mapping.map(insertPos);\n let isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;\n let beforeInsert = tr.doc;\n if (isNode)\n tr.replaceRangeWith(pos, pos, slice.content.firstChild);\n else\n tr.replaceRange(pos, pos, slice);\n if (tr.doc.eq(beforeInsert))\n return;\n let $pos = tr.doc.resolve(pos);\n if (isNode && NodeSelection.isSelectable(slice.content.firstChild) &&\n $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) {\n tr.setSelection(new NodeSelection($pos));\n }\n else {\n let end = tr.mapping.map(insertPos);\n tr.mapping.maps[tr.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);\n tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));\n }\n view.focus();\n view.dispatch(tr.setMeta(\"uiEvent\", \"drop\"));\n};\nhandlers.focus = view => {\n view.input.lastFocus = Date.now();\n if (!view.focused) {\n view.domObserver.stop();\n view.dom.classList.add(\"ProseMirror-focused\");\n view.domObserver.start();\n view.focused = true;\n setTimeout(() => {\n if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))\n selectionToDOM(view);\n }, 20);\n }\n};\nhandlers.blur = (view, _event) => {\n let event = _event;\n if (view.focused) {\n view.domObserver.stop();\n view.dom.classList.remove(\"ProseMirror-focused\");\n view.domObserver.start();\n if (event.relatedTarget && view.dom.contains(event.relatedTarget))\n view.domObserver.currentSelection.clear();\n view.focused = false;\n }\n};\nhandlers.beforeinput = (view, _event) => {\n let event = _event;\n // We should probably do more with beforeinput events, but support\n // is so spotty that I'm still waiting to see where they are going.\n // Very specific hack to deal with backspace sometimes failing on\n // Chrome Android when after an uneditable node.\n if (chrome && android && event.inputType == \"deleteContentBackward\") {\n view.domObserver.flushSoon();\n let { domChangeCount } = view.input;\n setTimeout(() => {\n if (view.input.domChangeCount != domChangeCount)\n return; // Event already had some effect\n // This bug tends to close the virtual keyboard, so we refocus\n view.dom.blur();\n view.focus();\n if (view.someProp(\"handleKeyDown\", f => f(view, keyEvent(8, \"Backspace\"))))\n return;\n let { $cursor } = view.state.selection;\n // Crude approximation of backspace behavior when no command handled it\n if ($cursor && $cursor.pos > 0)\n view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());\n }, 50);\n }\n};\n// Make sure all handlers get registered\nfor (let prop in editHandlers)\n handlers[prop] = editHandlers[prop];\n\nfunction compareObjs(a, b) {\n if (a == b)\n return true;\n for (let p in a)\n if (a[p] !== b[p])\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n return true;\n}\nclass WidgetType {\n constructor(toDOM, spec) {\n this.toDOM = toDOM;\n this.spec = spec || noSpec;\n this.side = this.spec.side || 0;\n }\n map(mapping, span, offset, oldOffset) {\n let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);\n return deleted ? null : new Decoration(pos - offset, pos - offset, this);\n }\n valid() { return true; }\n eq(other) {\n return this == other ||\n (other instanceof WidgetType &&\n (this.spec.key && this.spec.key == other.spec.key ||\n this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)));\n }\n destroy(node) {\n if (this.spec.destroy)\n this.spec.destroy(node);\n }\n}\nclass InlineType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;\n let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;\n return from >= to ? null : new Decoration(from, to, this);\n }\n valid(_, span) { return span.from < span.to; }\n eq(other) {\n return this == other ||\n (other instanceof InlineType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n static is(span) { return span.type instanceof InlineType; }\n destroy() { }\n}\nclass NodeType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.mapResult(span.from + oldOffset, 1);\n if (from.deleted)\n return null;\n let to = mapping.mapResult(span.to + oldOffset, -1);\n if (to.deleted || to.pos <= from.pos)\n return null;\n return new Decoration(from.pos - offset, to.pos - offset, this);\n }\n valid(node, span) {\n let { index, offset } = node.content.findIndex(span.from), child;\n return offset == span.from && !(child = node.child(index)).isText && offset + child.nodeSize == span.to;\n }\n eq(other) {\n return this == other ||\n (other instanceof NodeType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n destroy() { }\n}\n/**\nDecoration objects can be provided to the view through the\n[`decorations` prop](https://prosemirror.net/docs/ref/#view.EditorProps.decorations). They come in\nseveral variants—see the static members of this class for details.\n*/\nclass Decoration {\n /**\n @internal\n */\n constructor(\n /**\n The start position of the decoration.\n */\n from, \n /**\n The end position. Will be the same as `from` for [widget\n decorations](https://prosemirror.net/docs/ref/#view.Decoration^widget).\n */\n to, \n /**\n @internal\n */\n type) {\n this.from = from;\n this.to = to;\n this.type = type;\n }\n /**\n @internal\n */\n copy(from, to) {\n return new Decoration(from, to, this.type);\n }\n /**\n @internal\n */\n eq(other, offset = 0) {\n return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;\n }\n /**\n @internal\n */\n map(mapping, offset, oldOffset) {\n return this.type.map(mapping, this, offset, oldOffset);\n }\n /**\n Creates a widget decoration, which is a DOM node that's shown in\n the document at the given position. It is recommended that you\n delay rendering the widget by passing a function that will be\n called when the widget is actually drawn in a view, but you can\n also directly pass a DOM node. `getPos` can be used to find the\n widget's current document position.\n */\n static widget(pos, toDOM, spec) {\n return new Decoration(pos, pos, new WidgetType(toDOM, spec));\n }\n /**\n Creates an inline decoration, which adds the given attributes to\n each inline node between `from` and `to`.\n */\n static inline(from, to, attrs, spec) {\n return new Decoration(from, to, new InlineType(attrs, spec));\n }\n /**\n Creates a node decoration. `from` and `to` should point precisely\n before and after a node in the document. That node, and only that\n node, will receive the given attributes.\n */\n static node(from, to, attrs, spec) {\n return new Decoration(from, to, new NodeType(attrs, spec));\n }\n /**\n The spec provided when creating this decoration. Can be useful\n if you've stored extra information in that object.\n */\n get spec() { return this.type.spec; }\n /**\n @internal\n */\n get inline() { return this.type instanceof InlineType; }\n /**\n @internal\n */\n get widget() { return this.type instanceof WidgetType; }\n}\nconst none = [], noSpec = {};\n/**\nA collection of [decorations](https://prosemirror.net/docs/ref/#view.Decoration), organized in such\na way that the drawing algorithm can efficiently use and compare\nthem. This is a persistent data structure—it is not modified,\nupdates create a new value.\n*/\nclass DecorationSet {\n /**\n @internal\n */\n constructor(local, children) {\n this.local = local.length ? local : none;\n this.children = children.length ? children : none;\n }\n /**\n Create a set of decorations, using the structure of the given\n document. This will consume (modify) the `decorations` array, so\n you must make a copy if you want need to preserve that.\n */\n static create(doc, decorations) {\n return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty;\n }\n /**\n Find all decorations in this set which touch the given range\n (including decorations that start or end directly at the\n boundaries) and match the given predicate on their spec. When\n `start` and `end` are omitted, all decorations in the set are\n considered. When `predicate` isn't given, all decorations are\n assumed to match.\n */\n find(start, end, predicate) {\n let result = [];\n this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);\n return result;\n }\n findInner(start, end, result, offset, predicate) {\n for (let i = 0; i < this.local.length; i++) {\n let span = this.local[i];\n if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec)))\n result.push(span.copy(span.from + offset, span.to + offset));\n }\n for (let i = 0; i < this.children.length; i += 3) {\n if (this.children[i] < end && this.children[i + 1] > start) {\n let childOff = this.children[i] + 1;\n this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);\n }\n }\n }\n /**\n Map the set of decorations in response to a change in the\n document.\n */\n map(mapping, doc, options) {\n if (this == empty || mapping.maps.length == 0)\n return this;\n return this.mapInner(mapping, doc, 0, 0, options || noSpec);\n }\n /**\n @internal\n */\n mapInner(mapping, node, offset, oldOffset, options) {\n let newLocal;\n for (let i = 0; i < this.local.length; i++) {\n let mapped = this.local[i].map(mapping, offset, oldOffset);\n if (mapped && mapped.type.valid(node, mapped))\n (newLocal || (newLocal = [])).push(mapped);\n else if (options.onRemove)\n options.onRemove(this.local[i].spec);\n }\n if (this.children.length)\n return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options);\n else\n return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty;\n }\n /**\n Add the given array of decorations to the ones in the set,\n producing a new set. Consumes the `decorations` array. Needs\n access to the current document to create the appropriate tree\n structure.\n */\n add(doc, decorations) {\n if (!decorations.length)\n return this;\n if (this == empty)\n return DecorationSet.create(doc, decorations);\n return this.addInner(doc, decorations, 0);\n }\n addInner(doc, decorations, offset) {\n let children, childIndex = 0;\n doc.forEach((childNode, childOffset) => {\n let baseOffset = childOffset + offset, found;\n if (!(found = takeSpansForNode(decorations, childNode, baseOffset)))\n return;\n if (!children)\n children = this.children.slice();\n while (childIndex < children.length && children[childIndex] < childOffset)\n childIndex += 3;\n if (children[childIndex] == childOffset)\n children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1);\n else\n children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec));\n childIndex += 3;\n });\n let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);\n for (let i = 0; i < local.length; i++)\n if (!local[i].type.valid(doc, local[i]))\n local.splice(i--, 1);\n return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);\n }\n /**\n Create a new set that contains the decorations in this set, minus\n the ones in the given array.\n */\n remove(decorations) {\n if (decorations.length == 0 || this == empty)\n return this;\n return this.removeInner(decorations, 0);\n }\n removeInner(decorations, offset) {\n let children = this.children, local = this.local;\n for (let i = 0; i < children.length; i += 3) {\n let found;\n let from = children[i] + offset, to = children[i + 1] + offset;\n for (let j = 0, span; j < decorations.length; j++)\n if (span = decorations[j]) {\n if (span.from > from && span.to < to) {\n decorations[j] = null;\n (found || (found = [])).push(span);\n }\n }\n if (!found)\n continue;\n if (children == this.children)\n children = this.children.slice();\n let removed = children[i + 2].removeInner(found, from + 1);\n if (removed != empty) {\n children[i + 2] = removed;\n }\n else {\n children.splice(i, 3);\n i -= 3;\n }\n }\n if (local.length)\n for (let i = 0, span; i < decorations.length; i++)\n if (span = decorations[i]) {\n for (let j = 0; j < local.length; j++)\n if (local[j].eq(span, offset)) {\n if (local == this.local)\n local = this.local.slice();\n local.splice(j--, 1);\n }\n }\n if (children == this.children && local == this.local)\n return this;\n return local.length || children.length ? new DecorationSet(local, children) : empty;\n }\n forChild(offset, node) {\n if (this == empty)\n return this;\n if (node.isLeaf)\n return DecorationSet.empty;\n let child, local;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] >= offset) {\n if (this.children[i] == offset)\n child = this.children[i + 2];\n break;\n }\n let start = offset + 1, end = start + node.content.size;\n for (let i = 0; i < this.local.length; i++) {\n let dec = this.local[i];\n if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) {\n let from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;\n if (from < to)\n (local || (local = [])).push(dec.copy(from, to));\n }\n }\n if (local) {\n let localSet = new DecorationSet(local.sort(byPos), none);\n return child ? new DecorationGroup([localSet, child]) : localSet;\n }\n return child || empty;\n }\n /**\n @internal\n */\n eq(other) {\n if (this == other)\n return true;\n if (!(other instanceof DecorationSet) ||\n this.local.length != other.local.length ||\n this.children.length != other.children.length)\n return false;\n for (let i = 0; i < this.local.length; i++)\n if (!this.local[i].eq(other.local[i]))\n return false;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] != other.children[i] ||\n this.children[i + 1] != other.children[i + 1] ||\n !this.children[i + 2].eq(other.children[i + 2]))\n return false;\n return true;\n }\n /**\n @internal\n */\n locals(node) {\n return removeOverlap(this.localsInner(node));\n }\n /**\n @internal\n */\n localsInner(node) {\n if (this == empty)\n return none;\n if (node.inlineContent || !this.local.some(InlineType.is))\n return this.local;\n let result = [];\n for (let i = 0; i < this.local.length; i++) {\n if (!(this.local[i].type instanceof InlineType))\n result.push(this.local[i]);\n }\n return result;\n }\n forEachSet(f) { f(this); }\n}\n/**\nThe empty set of decorations.\n*/\nDecorationSet.empty = new DecorationSet([], []);\n/**\n@internal\n*/\nDecorationSet.removeOverlap = removeOverlap;\nconst empty = DecorationSet.empty;\n// An abstraction that allows the code dealing with decorations to\n// treat multiple DecorationSet objects as if it were a single object\n// with (a subset of) the same interface.\nclass DecorationGroup {\n constructor(members) {\n this.members = members;\n }\n map(mapping, doc) {\n const mappedDecos = this.members.map(member => member.map(mapping, doc, noSpec));\n return DecorationGroup.from(mappedDecos);\n }\n forChild(offset, child) {\n if (child.isLeaf)\n return DecorationSet.empty;\n let found = [];\n for (let i = 0; i < this.members.length; i++) {\n let result = this.members[i].forChild(offset, child);\n if (result == empty)\n continue;\n if (result instanceof DecorationGroup)\n found = found.concat(result.members);\n else\n found.push(result);\n }\n return DecorationGroup.from(found);\n }\n eq(other) {\n if (!(other instanceof DecorationGroup) ||\n other.members.length != this.members.length)\n return false;\n for (let i = 0; i < this.members.length; i++)\n if (!this.members[i].eq(other.members[i]))\n return false;\n return true;\n }\n locals(node) {\n let result, sorted = true;\n for (let i = 0; i < this.members.length; i++) {\n let locals = this.members[i].localsInner(node);\n if (!locals.length)\n continue;\n if (!result) {\n result = locals;\n }\n else {\n if (sorted) {\n result = result.slice();\n sorted = false;\n }\n for (let j = 0; j < locals.length; j++)\n result.push(locals[j]);\n }\n }\n return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;\n }\n // Create a group for the given array of decoration sets, or return\n // a single set when possible.\n static from(members) {\n switch (members.length) {\n case 0: return empty;\n case 1: return members[0];\n default: return new DecorationGroup(members.every(m => m instanceof DecorationSet) ? members :\n members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), []));\n }\n }\n forEachSet(f) {\n for (let i = 0; i < this.members.length; i++)\n this.members[i].forEachSet(f);\n }\n}\nfunction mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {\n let children = oldChildren.slice();\n // Mark the children that are directly touched by changes, and\n // move those that are after the changes.\n for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) {\n let moved = 0;\n mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => {\n let dSize = (newEnd - newStart) - (oldEnd - oldStart);\n for (let i = 0; i < children.length; i += 3) {\n let end = children[i + 1];\n if (end < 0 || oldStart > end + baseOffset - moved)\n continue;\n let start = children[i] + baseOffset - moved;\n if (oldEnd >= start) {\n children[i + 1] = oldStart <= start ? -2 : -1;\n }\n else if (oldStart >= baseOffset && dSize) {\n children[i] += dSize;\n children[i + 1] += dSize;\n }\n }\n moved += dSize;\n });\n baseOffset = mapping.maps[i].map(baseOffset, -1);\n }\n // Find the child nodes that still correspond to a single node,\n // recursively call mapInner on them and update their positions.\n let mustRebuild = false;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) { // Touched nodes\n if (children[i + 1] == -2) {\n mustRebuild = true;\n children[i + 1] = -1;\n continue;\n }\n let from = mapping.map(oldChildren[i] + oldOffset), fromLocal = from - offset;\n if (fromLocal < 0 || fromLocal >= node.content.size) {\n mustRebuild = true;\n continue;\n }\n // Must read oldChildren because children was tagged with -1\n let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset;\n let { index, offset: childOffset } = node.content.findIndex(fromLocal);\n let childNode = node.maybeChild(index);\n if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {\n let mapped = children[i + 2]\n .mapInner(mapping, childNode, from + 1, oldChildren[i] + oldOffset + 1, options);\n if (mapped != empty) {\n children[i] = fromLocal;\n children[i + 1] = toLocal;\n children[i + 2] = mapped;\n }\n else {\n children[i + 1] = -2;\n mustRebuild = true;\n }\n }\n else {\n mustRebuild = true;\n }\n }\n // Remaining children must be collected and rebuilt into the appropriate structure\n if (mustRebuild) {\n let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options);\n let built = buildTree(decorations, node, 0, options);\n newLocal = built.local;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) {\n children.splice(i, 3);\n i -= 3;\n }\n for (let i = 0, j = 0; i < built.children.length; i += 3) {\n let from = built.children[i];\n while (j < children.length && children[j] < from)\n j += 3;\n children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]);\n }\n }\n return new DecorationSet(newLocal.sort(byPos), children);\n}\nfunction moveSpans(spans, offset) {\n if (!offset || !spans.length)\n return spans;\n let result = [];\n for (let i = 0; i < spans.length; i++) {\n let span = spans[i];\n result.push(new Decoration(span.from + offset, span.to + offset, span.type));\n }\n return result;\n}\nfunction mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {\n // Gather all decorations from the remaining marked children\n function gather(set, oldOffset) {\n for (let i = 0; i < set.local.length; i++) {\n let mapped = set.local[i].map(mapping, offset, oldOffset);\n if (mapped)\n decorations.push(mapped);\n else if (options.onRemove)\n options.onRemove(set.local[i].spec);\n }\n for (let i = 0; i < set.children.length; i += 3)\n gather(set.children[i + 2], set.children[i] + oldOffset + 1);\n }\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] == -1)\n gather(children[i + 2], oldChildren[i] + oldOffset + 1);\n return decorations;\n}\nfunction takeSpansForNode(spans, node, offset) {\n if (node.isLeaf)\n return null;\n let end = offset + node.nodeSize, found = null;\n for (let i = 0, span; i < spans.length; i++) {\n if ((span = spans[i]) && span.from > offset && span.to < end) {\n (found || (found = [])).push(span);\n spans[i] = null;\n }\n }\n return found;\n}\nfunction withoutNulls(array) {\n let result = [];\n for (let i = 0; i < array.length; i++)\n if (array[i] != null)\n result.push(array[i]);\n return result;\n}\n// Build up a tree that corresponds to a set of decorations. `offset`\n// is a base offset that should be subtracted from the `from` and `to`\n// positions in the spans (so that we don't have to allocate new spans\n// for recursive calls).\nfunction buildTree(spans, node, offset, options) {\n let children = [], hasNulls = false;\n node.forEach((childNode, localStart) => {\n let found = takeSpansForNode(spans, childNode, localStart + offset);\n if (found) {\n hasNulls = true;\n let subtree = buildTree(found, childNode, offset + localStart + 1, options);\n if (subtree != empty)\n children.push(localStart, localStart + childNode.nodeSize, subtree);\n }\n });\n let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);\n for (let i = 0; i < locals.length; i++)\n if (!locals[i].type.valid(node, locals[i])) {\n if (options.onRemove)\n options.onRemove(locals[i].spec);\n locals.splice(i--, 1);\n }\n return locals.length || children.length ? new DecorationSet(locals, children) : empty;\n}\n// Used to sort decorations so that ones with a low start position\n// come first, and within a set with the same start position, those\n// with an smaller end position come first.\nfunction byPos(a, b) {\n return a.from - b.from || a.to - b.to;\n}\n// Scan a sorted array of decorations for partially overlapping spans,\n// and split those so that only fully overlapping spans are left (to\n// make subsequent rendering easier). Will return the input array if\n// no partially overlapping spans are found (the common case).\nfunction removeOverlap(spans) {\n let working = spans;\n for (let i = 0; i < working.length - 1; i++) {\n let span = working[i];\n if (span.from != span.to)\n for (let j = i + 1; j < working.length; j++) {\n let next = working[j];\n if (next.from == span.from) {\n if (next.to != span.to) {\n if (working == spans)\n working = spans.slice();\n // Followed by a partially overlapping larger span. Split that\n // span.\n working[j] = next.copy(next.from, span.to);\n insertAhead(working, j + 1, next.copy(span.to, next.to));\n }\n continue;\n }\n else {\n if (next.from < span.to) {\n if (working == spans)\n working = spans.slice();\n // The end of this one overlaps with a subsequent span. Split\n // this one.\n working[i] = span.copy(span.from, next.from);\n insertAhead(working, j, span.copy(next.from, span.to));\n }\n break;\n }\n }\n }\n return working;\n}\nfunction insertAhead(array, i, deco) {\n while (i < array.length && byPos(deco, array[i]) > 0)\n i++;\n array.splice(i, 0, deco);\n}\n// Get the decorations associated with the current props of a view.\nfunction viewDecorations(view) {\n let found = [];\n view.someProp(\"decorations\", f => {\n let result = f(view.state);\n if (result && result != empty)\n found.push(result);\n });\n if (view.cursorWrapper)\n found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));\n return DecorationGroup.from(found);\n}\n\nconst observeOptions = {\n childList: true,\n characterData: true,\n characterDataOldValue: true,\n attributes: true,\n attributeOldValue: true,\n subtree: true\n};\n// IE11 has very broken mutation observers, so we also listen to DOMCharacterDataModified\nconst useCharData = ie && ie_version <= 11;\nclass SelectionState {\n constructor() {\n this.anchorNode = null;\n this.anchorOffset = 0;\n this.focusNode = null;\n this.focusOffset = 0;\n }\n set(sel) {\n this.anchorNode = sel.anchorNode;\n this.anchorOffset = sel.anchorOffset;\n this.focusNode = sel.focusNode;\n this.focusOffset = sel.focusOffset;\n }\n clear() {\n this.anchorNode = this.focusNode = null;\n }\n eq(sel) {\n return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset &&\n sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;\n }\n}\nclass DOMObserver {\n constructor(view, handleDOMChange) {\n this.view = view;\n this.handleDOMChange = handleDOMChange;\n this.queue = [];\n this.flushingSoon = -1;\n this.observer = null;\n this.currentSelection = new SelectionState;\n this.onCharData = null;\n this.suppressingSelectionUpdates = false;\n this.lastChangedTextNode = null;\n this.observer = window.MutationObserver &&\n new window.MutationObserver(mutations => {\n for (let i = 0; i < mutations.length; i++)\n this.queue.push(mutations[i]);\n // IE11 will sometimes (on backspacing out a single character\n // text node after a BR node) call the observer callback\n // before actually updating the DOM, which will cause\n // ProseMirror to miss the change (see #930)\n if (ie && ie_version <= 11 && mutations.some(m => m.type == \"childList\" && m.removedNodes.length ||\n m.type == \"characterData\" && m.oldValue.length > m.target.nodeValue.length))\n this.flushSoon();\n else\n this.flush();\n });\n if (useCharData) {\n this.onCharData = e => {\n this.queue.push({ target: e.target, type: \"characterData\", oldValue: e.prevValue });\n this.flushSoon();\n };\n }\n this.onSelectionChange = this.onSelectionChange.bind(this);\n }\n flushSoon() {\n if (this.flushingSoon < 0)\n this.flushingSoon = window.setTimeout(() => { this.flushingSoon = -1; this.flush(); }, 20);\n }\n forceFlush() {\n if (this.flushingSoon > -1) {\n window.clearTimeout(this.flushingSoon);\n this.flushingSoon = -1;\n this.flush();\n }\n }\n start() {\n if (this.observer) {\n this.observer.takeRecords();\n this.observer.observe(this.view.dom, observeOptions);\n }\n if (this.onCharData)\n this.view.dom.addEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.connectSelection();\n }\n stop() {\n if (this.observer) {\n let take = this.observer.takeRecords();\n if (take.length) {\n for (let i = 0; i < take.length; i++)\n this.queue.push(take[i]);\n window.setTimeout(() => this.flush(), 20);\n }\n this.observer.disconnect();\n }\n if (this.onCharData)\n this.view.dom.removeEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.disconnectSelection();\n }\n connectSelection() {\n this.view.dom.ownerDocument.addEventListener(\"selectionchange\", this.onSelectionChange);\n }\n disconnectSelection() {\n this.view.dom.ownerDocument.removeEventListener(\"selectionchange\", this.onSelectionChange);\n }\n suppressSelectionUpdates() {\n this.suppressingSelectionUpdates = true;\n setTimeout(() => this.suppressingSelectionUpdates = false, 50);\n }\n onSelectionChange() {\n if (!hasFocusAndSelection(this.view))\n return;\n if (this.suppressingSelectionUpdates)\n return selectionToDOM(this.view);\n // Deletions on IE11 fire their events in the wrong order, giving\n // us a selection change event before the DOM changes are\n // reported.\n if (ie && ie_version <= 11 && !this.view.state.selection.empty) {\n let sel = this.view.domSelectionRange();\n // Selection.isCollapsed isn't reliable on IE\n if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))\n return this.flushSoon();\n }\n this.flush();\n }\n setCurSelection() {\n this.currentSelection.set(this.view.domSelectionRange());\n }\n ignoreSelectionChange(sel) {\n if (!sel.focusNode)\n return true;\n let ancestors = new Set, container;\n for (let scan = sel.focusNode; scan; scan = parentNode(scan))\n ancestors.add(scan);\n for (let scan = sel.anchorNode; scan; scan = parentNode(scan))\n if (ancestors.has(scan)) {\n container = scan;\n break;\n }\n let desc = container && this.view.docView.nearestDesc(container);\n if (desc && desc.ignoreMutation({\n type: \"selection\",\n target: container.nodeType == 3 ? container.parentNode : container\n })) {\n this.setCurSelection();\n return true;\n }\n }\n pendingRecords() {\n if (this.observer)\n for (let mut of this.observer.takeRecords())\n this.queue.push(mut);\n return this.queue;\n }\n flush() {\n let { view } = this;\n if (!view.docView || this.flushingSoon > -1)\n return;\n let mutations = this.pendingRecords();\n if (mutations.length)\n this.queue = [];\n let sel = view.domSelectionRange();\n let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel);\n let from = -1, to = -1, typeOver = false, added = [];\n if (view.editable) {\n for (let i = 0; i < mutations.length; i++) {\n let result = this.registerMutation(mutations[i], added);\n if (result) {\n from = from < 0 ? result.from : Math.min(result.from, from);\n to = to < 0 ? result.to : Math.max(result.to, to);\n if (result.typeOver)\n typeOver = true;\n }\n }\n }\n if (gecko && added.length) {\n let brs = added.filter(n => n.nodeName == \"BR\");\n if (brs.length == 2) {\n let [a, b] = brs;\n if (a.parentNode && a.parentNode.parentNode == b.parentNode)\n b.remove();\n else\n a.remove();\n }\n else {\n let { focusNode } = this.currentSelection;\n for (let br of brs) {\n let parent = br.parentNode;\n if (parent && parent.nodeName == \"LI\" && (!focusNode || blockParent(view, focusNode) != parent))\n br.remove();\n }\n }\n }\n let readSel = null;\n // If it looks like the browser has reset the selection to the\n // start of the document after focus, restore the selection from\n // the state\n if (from < 0 && newSel && view.input.lastFocus > Date.now() - 200 &&\n Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 &&\n selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) &&\n readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {\n view.input.lastFocus = 0;\n selectionToDOM(view);\n this.currentSelection.set(sel);\n view.scrollToSelection();\n }\n else if (from > -1 || newSel) {\n if (from > -1) {\n view.docView.markDirty(from, to);\n checkCSS(view);\n }\n this.handleDOMChange(from, to, typeOver, added);\n if (view.docView && view.docView.dirty)\n view.updateState(view.state);\n else if (!this.currentSelection.eq(sel))\n selectionToDOM(view);\n this.currentSelection.set(sel);\n }\n }\n registerMutation(mut, added) {\n // Ignore mutations inside nodes that were already noted as inserted\n if (added.indexOf(mut.target) > -1)\n return null;\n let desc = this.view.docView.nearestDesc(mut.target);\n if (mut.type == \"attributes\" &&\n (desc == this.view.docView || mut.attributeName == \"contenteditable\" ||\n // Firefox sometimes fires spurious events for null/empty styles\n (mut.attributeName == \"style\" && !mut.oldValue && !mut.target.getAttribute(\"style\"))))\n return null;\n if (!desc || desc.ignoreMutation(mut))\n return null;\n if (mut.type == \"childList\") {\n for (let i = 0; i < mut.addedNodes.length; i++) {\n let node = mut.addedNodes[i];\n added.push(node);\n if (node.nodeType == 3)\n this.lastChangedTextNode = node;\n }\n if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))\n return { from: desc.posBefore, to: desc.posAfter };\n let prev = mut.previousSibling, next = mut.nextSibling;\n if (ie && ie_version <= 11 && mut.addedNodes.length) {\n // IE11 gives us incorrect next/prev siblings for some\n // insertions, so if there are added nodes, recompute those\n for (let i = 0; i < mut.addedNodes.length; i++) {\n let { previousSibling, nextSibling } = mut.addedNodes[i];\n if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)\n prev = previousSibling;\n if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)\n next = nextSibling;\n }\n }\n let fromOffset = prev && prev.parentNode == mut.target\n ? domIndex(prev) + 1 : 0;\n let from = desc.localPosFromDOM(mut.target, fromOffset, -1);\n let toOffset = next && next.parentNode == mut.target\n ? domIndex(next) : mut.target.childNodes.length;\n let to = desc.localPosFromDOM(mut.target, toOffset, 1);\n return { from, to };\n }\n else if (mut.type == \"attributes\") {\n return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };\n }\n else { // \"characterData\"\n this.lastChangedTextNode = mut.target;\n return {\n from: desc.posAtStart,\n to: desc.posAtEnd,\n // An event was generated for a text change that didn't change\n // any text. Mark the dom change to fall back to assuming the\n // selection was typed over with an identical value if it can't\n // find another change.\n typeOver: mut.target.nodeValue == mut.oldValue\n };\n }\n }\n}\nlet cssChecked = new WeakMap();\nlet cssCheckWarned = false;\nfunction checkCSS(view) {\n if (cssChecked.has(view))\n return;\n cssChecked.set(view, null);\n if (['normal', 'nowrap', 'pre-line'].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {\n view.requiresGeckoHackNode = gecko;\n if (cssCheckWarned)\n return;\n console[\"warn\"](\"ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.\");\n cssCheckWarned = true;\n }\n}\nfunction rangeToSelectionRange(view, range) {\n let anchorNode = range.startContainer, anchorOffset = range.startOffset;\n let focusNode = range.endContainer, focusOffset = range.endOffset;\n let currentAnchor = view.domAtPos(view.state.selection.anchor);\n // Since such a range doesn't distinguish between anchor and head,\n // use a heuristic that flips it around if its end matches the\n // current anchor.\n if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))\n [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];\n return { anchorNode, anchorOffset, focusNode, focusOffset };\n}\n// Used to work around a Safari Selection/shadow DOM bug\n// Based on https://github.com/codemirror/dev/issues/414 fix\nfunction safariShadowSelectionRange(view, selection) {\n if (selection.getComposedRanges) {\n let range = selection.getComposedRanges(view.root)[0];\n if (range)\n return rangeToSelectionRange(view, range);\n }\n let found;\n function read(event) {\n event.preventDefault();\n event.stopImmediatePropagation();\n found = event.getTargetRanges()[0];\n }\n // Because Safari (at least in 2018-2022) doesn't provide regular\n // access to the selection inside a shadowRoot, we have to perform a\n // ridiculous hack to get at it—using `execCommand` to trigger a\n // `beforeInput` event so that we can read the target range from the\n // event.\n view.dom.addEventListener(\"beforeinput\", read, true);\n document.execCommand(\"indent\");\n view.dom.removeEventListener(\"beforeinput\", read, true);\n return found ? rangeToSelectionRange(view, found) : null;\n}\nfunction blockParent(view, node) {\n for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) {\n let desc = view.docView.nearestDesc(p, true);\n if (desc && desc.node.isBlock)\n return p;\n }\n return null;\n}\n\n// Note that all referencing and parsing is done with the\n// start-of-operation selection and document, since that's the one\n// that the DOM represents. If any changes came in in the meantime,\n// the modification is mapped over those before it is applied, in\n// readDOMChange.\nfunction parseBetween(view, from_, to_) {\n let { node: parent, fromOffset, toOffset, from, to } = view.docView.parseRange(from_, to_);\n let domSel = view.domSelectionRange();\n let find;\n let anchor = domSel.anchorNode;\n if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {\n find = [{ node: anchor, offset: domSel.anchorOffset }];\n if (!selectionCollapsed(domSel))\n find.push({ node: domSel.focusNode, offset: domSel.focusOffset });\n }\n // Work around issue in Chrome where backspacing sometimes replaces\n // the deleted content with a random BR node (issues #799, #831)\n if (chrome && view.input.lastKeyCode === 8) {\n for (let off = toOffset; off > fromOffset; off--) {\n let node = parent.childNodes[off - 1], desc = node.pmViewDesc;\n if (node.nodeName == \"BR\" && !desc) {\n toOffset = off;\n break;\n }\n if (!desc || desc.size)\n break;\n }\n }\n let startDoc = view.state.doc;\n let parser = view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n let $from = startDoc.resolve(from);\n let sel = null, doc = parser.parse(parent, {\n topNode: $from.parent,\n topMatch: $from.parent.contentMatchAt($from.index()),\n topOpen: true,\n from: fromOffset,\n to: toOffset,\n preserveWhitespace: $from.parent.type.whitespace == \"pre\" ? \"full\" : true,\n findPositions: find,\n ruleFromNode,\n context: $from\n });\n if (find && find[0].pos != null) {\n let anchor = find[0].pos, head = find[1] && find[1].pos;\n if (head == null)\n head = anchor;\n sel = { anchor: anchor + from, head: head + from };\n }\n return { doc, sel, from, to };\n}\nfunction ruleFromNode(dom) {\n let desc = dom.pmViewDesc;\n if (desc) {\n return desc.parseRule();\n }\n else if (dom.nodeName == \"BR\" && dom.parentNode) {\n // Safari replaces the list item or table cell with a BR\n // directly in the list node (?!) if you delete the last\n // character in a list item or table cell (#708, #862)\n if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {\n let skip = document.createElement(\"div\");\n skip.appendChild(document.createElement(\"li\"));\n return { skip };\n }\n else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {\n return { ignore: true };\n }\n }\n else if (dom.nodeName == \"IMG\" && dom.getAttribute(\"mark-placeholder\")) {\n return { ignore: true };\n }\n return null;\n}\nconst isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;\nfunction readDOMChange(view, from, to, typeOver, addedNodes) {\n let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);\n view.input.compositionPendingChanges = 0;\n if (from < 0) {\n let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;\n let newSel = selectionFromDOM(view, origin);\n if (newSel && !view.state.selection.eq(newSel)) {\n if (chrome && android &&\n view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\"))))\n return;\n let tr = view.state.tr.setSelection(newSel);\n if (origin == \"pointer\")\n tr.setMeta(\"pointer\", true);\n else if (origin == \"key\")\n tr.scrollIntoView();\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n return;\n }\n let $before = view.state.doc.resolve(from);\n let shared = $before.sharedDepth(to);\n from = $before.before(shared + 1);\n to = view.state.doc.resolve(to).after(shared + 1);\n let sel = view.state.selection;\n let parse = parseBetween(view, from, to);\n let doc = view.state.doc, compare = doc.slice(parse.from, parse.to);\n let preferredPos, preferredSide;\n // Prefer anchoring to end when Backspace is pressed\n if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {\n preferredPos = view.state.selection.to;\n preferredSide = \"end\";\n }\n else {\n preferredPos = view.state.selection.from;\n preferredSide = \"start\";\n }\n view.input.lastKeyCode = null;\n let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);\n if (change)\n view.input.domChangeCount++;\n if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) &&\n addedNodes.some(n => n.nodeType == 1 && !isInline.test(n.nodeName)) &&\n (!change || change.endA >= change.endB) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\n if (!change) {\n if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) &&\n !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {\n change = { start: sel.from, endA: sel.to, endB: sel.to };\n }\n else {\n if (parse.sel) {\n let sel = resolveSelection(view, view.state.doc, parse.sel);\n if (sel && !sel.eq(view.state.selection)) {\n let tr = view.state.tr.setSelection(sel);\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n }\n return;\n }\n }\n // Handle the case where overwriting a selection by typing matches\n // the start or end of the selected content, creating a change\n // that's smaller than what was actually overwritten.\n if (view.state.selection.from < view.state.selection.to &&\n change.start == change.endB &&\n view.state.selection instanceof TextSelection) {\n if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 &&\n view.state.selection.from >= parse.from) {\n change.start = view.state.selection.from;\n }\n else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 &&\n view.state.selection.to <= parse.to) {\n change.endB += (view.state.selection.to - change.endA);\n change.endA = view.state.selection.to;\n }\n }\n // IE11 will insert a non-breaking space _ahead_ of the space after\n // the cursor space when adding a space before another space. When\n // that happened, adjust the change to cover the space instead.\n if (ie && ie_version <= 11 && change.endB == change.start + 1 &&\n change.endA == change.start && change.start > parse.from &&\n parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == \" \\u00a0\") {\n change.start--;\n change.endA--;\n change.endB--;\n }\n let $from = parse.doc.resolveNoCache(change.start - parse.from);\n let $to = parse.doc.resolveNoCache(change.endB - parse.from);\n let $fromA = doc.resolve(change.start);\n let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;\n let nextSel;\n // If this looks like the effect of pressing Enter (or was recorded\n // as being an iOS enter press), just dispatch an Enter key instead.\n if (((ios && view.input.lastIOSEnter > Date.now() - 225 &&\n (!inlineChange || addedNodes.some(n => n.nodeName == \"DIV\" || n.nodeName == \"P\"))) ||\n (!inlineChange && $from.pos < parse.doc.content.size && !$from.sameParent($to) &&\n (nextSel = Selection.findFrom(parse.doc.resolve($from.pos + 1), 1, true)) &&\n nextSel.head == $to.pos)) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\n // Same for backspace\n if (view.state.selection.anchor > change.start &&\n looksLikeBackspace(doc, change.start, change.endA, $from, $to) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(8, \"Backspace\")))) {\n if (android && chrome)\n view.domObserver.suppressSelectionUpdates(); // #820\n return;\n }\n // Chrome will occasionally, during composition, delete the\n // entire composition and then immediately insert it again. This is\n // used to detect that situation.\n if (chrome && change.endB == change.start)\n view.input.lastChromeDelete = Date.now();\n // This tries to detect Android virtual keyboard\n // enter-and-pick-suggestion action. That sometimes (see issue\n // #1059) first fires a DOM mutation, before moving the selection to\n // the newly created block. And then, because ProseMirror cleans up\n // the DOM selection, it gives up moving the selection entirely,\n // leaving the cursor in the wrong place. When that happens, we drop\n // the new paragraph from the initial change, and fire a simulated\n // enter key afterwards.\n if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth &&\n parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) {\n change.endB -= 2;\n $to = parse.doc.resolveNoCache(change.endB - parse.from);\n setTimeout(() => {\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); });\n }, 20);\n }\n let chFrom = change.start, chTo = change.endA;\n let tr, storedMarks, markChange;\n if (inlineChange) {\n if ($from.pos == $to.pos) { // Deletion\n // IE11 sometimes weirdly moves the DOM selection around after\n // backspacing out the first element in a textblock\n if (ie && ie_version <= 11 && $from.parentOffset == 0) {\n view.domObserver.suppressSelectionUpdates();\n setTimeout(() => selectionToDOM(view), 20);\n }\n tr = view.state.tr.delete(chFrom, chTo);\n storedMarks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA));\n }\n else if ( // Adding or removing a mark\n change.endA == change.endB &&\n (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))) {\n tr = view.state.tr;\n if (markChange.type == \"add\")\n tr.addMark(chFrom, chTo, markChange.mark);\n else\n tr.removeMark(chFrom, chTo, markChange.mark);\n }\n else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {\n // Both positions in the same text node -- simply insert text\n let text = $from.parent.textBetween($from.parentOffset, $to.parentOffset);\n if (view.someProp(\"handleTextInput\", f => f(view, chFrom, chTo, text)))\n return;\n tr = view.state.tr.insertText(text, chFrom, chTo);\n }\n }\n if (!tr)\n tr = view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from));\n if (parse.sel) {\n let sel = resolveSelection(view, tr.doc, parse.sel);\n // Chrome will sometimes, during composition, report the\n // selection in the wrong place. If it looks like that is\n // happening, don't update the selection.\n // Edge just doesn't move the cursor forward when you start typing\n // in an empty block or between br nodes.\n if (sel && !(chrome && view.composing && sel.empty &&\n (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) &&\n (sel.head == chFrom || sel.head == tr.mapping.map(chTo) - 1) ||\n ie && sel.empty && sel.head == chFrom))\n tr.setSelection(sel);\n }\n if (storedMarks)\n tr.ensureMarks(storedMarks);\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr.scrollIntoView());\n}\nfunction resolveSelection(view, doc, parsedSel) {\n if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size)\n return null;\n return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head));\n}\n// Given two same-length, non-empty fragments of inline content,\n// determine whether the first could be created from the second by\n// removing or adding a single mark type.\nfunction isMarkChange(cur, prev) {\n let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;\n let added = curMarks, removed = prevMarks, type, mark, update;\n for (let i = 0; i < prevMarks.length; i++)\n added = prevMarks[i].removeFromSet(added);\n for (let i = 0; i < curMarks.length; i++)\n removed = curMarks[i].removeFromSet(removed);\n if (added.length == 1 && removed.length == 0) {\n mark = added[0];\n type = \"add\";\n update = (node) => node.mark(mark.addToSet(node.marks));\n }\n else if (added.length == 0 && removed.length == 1) {\n mark = removed[0];\n type = \"remove\";\n update = (node) => node.mark(mark.removeFromSet(node.marks));\n }\n else {\n return null;\n }\n let updated = [];\n for (let i = 0; i < prev.childCount; i++)\n updated.push(update(prev.child(i)));\n if (Fragment.from(updated).eq(cur))\n return { mark, type };\n}\nfunction looksLikeBackspace(old, start, end, $newStart, $newEnd) {\n if ( // The content must have shrunk\n end - start <= $newEnd.pos - $newStart.pos ||\n // newEnd must point directly at or after the end of the block that newStart points into\n skipClosingAndOpening($newStart, true, false) < $newEnd.pos)\n return false;\n let $start = old.resolve(start);\n // Handle the case where, rather than joining blocks, the change just removed an entire block\n if (!$newStart.parent.isTextblock) {\n let after = $start.nodeAfter;\n return after != null && end == start + after.nodeSize;\n }\n // Start must be at the end of a block\n if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)\n return false;\n let $next = old.resolve(skipClosingAndOpening($start, true, true));\n // The next textblock must start before end and end near it\n if (!$next.parent.isTextblock || $next.pos > end ||\n skipClosingAndOpening($next, true, false) < end)\n return false;\n // The fragments after the join point must match\n return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);\n}\nfunction skipClosingAndOpening($pos, fromEnd, mayOpen) {\n let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;\n while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {\n depth--;\n end++;\n fromEnd = false;\n }\n if (mayOpen) {\n let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));\n while (next && !next.isLeaf) {\n next = next.firstChild;\n end++;\n }\n }\n return end;\n}\nfunction findDiff(a, b, pos, preferredPos, preferredSide) {\n let start = a.findDiffStart(b, pos);\n if (start == null)\n return null;\n let { a: endA, b: endB } = a.findDiffEnd(b, pos + a.size, pos + b.size);\n if (preferredSide == \"end\") {\n let adjust = Math.max(0, start - Math.min(endA, endB));\n preferredPos -= endA + adjust - start;\n }\n if (endA < start && a.size < b.size) {\n let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;\n start -= move;\n if (start && start < b.size && isSurrogatePair(b.textBetween(start - 1, start + 1)))\n start += move ? 1 : -1;\n endB = start + (endB - endA);\n endA = start;\n }\n else if (endB < start) {\n let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;\n start -= move;\n if (start && start < a.size && isSurrogatePair(a.textBetween(start - 1, start + 1)))\n start += move ? 1 : -1;\n endA = start + (endA - endB);\n endB = start;\n }\n return { start, endA, endB };\n}\nfunction isSurrogatePair(str) {\n if (str.length != 2)\n return false;\n let a = str.charCodeAt(0), b = str.charCodeAt(1);\n return a >= 0xDC00 && a <= 0xDFFF && b >= 0xD800 && b <= 0xDBFF;\n}\n\n/**\n@internal\n*/\nconst __serializeForClipboard = serializeForClipboard;\n/**\n@internal\n*/\nconst __parseFromClipboard = parseFromClipboard;\n/**\n@internal\n*/\nconst __endComposition = endComposition;\n/**\nAn editor view manages the DOM structure that represents an\neditable document. Its state and behavior are determined by its\n[props](https://prosemirror.net/docs/ref/#view.DirectEditorProps).\n*/\nclass EditorView {\n /**\n Create a view. `place` may be a DOM node that the editor should\n be appended to, a function that will place it into the document,\n or an object whose `mount` property holds the node to use as the\n document container. If it is `null`, the editor will not be\n added to the document.\n */\n constructor(place, props) {\n this._root = null;\n /**\n @internal\n */\n this.focused = false;\n /**\n Kludge used to work around a Chrome bug @internal\n */\n this.trackWrites = null;\n this.mounted = false;\n /**\n @internal\n */\n this.markCursor = null;\n /**\n @internal\n */\n this.cursorWrapper = null;\n /**\n @internal\n */\n this.lastSelectedViewDesc = undefined;\n /**\n @internal\n */\n this.input = new InputState;\n this.prevDirectPlugins = [];\n this.pluginViews = [];\n /**\n Holds `true` when a hack node is needed in Firefox to prevent the\n [space is eaten issue](https://github.com/ProseMirror/prosemirror/issues/651)\n @internal\n */\n this.requiresGeckoHackNode = false;\n /**\n When editor content is being dragged, this object contains\n information about the dragged slice and whether it is being\n copied or moved. At any other time, it is null.\n */\n this.dragging = null;\n this._props = props;\n this.state = props.state;\n this.directPlugins = props.plugins || [];\n this.directPlugins.forEach(checkStateComponent);\n this.dispatch = this.dispatch.bind(this);\n this.dom = (place && place.mount) || document.createElement(\"div\");\n if (place) {\n if (place.appendChild)\n place.appendChild(this.dom);\n else if (typeof place == \"function\")\n place(this.dom);\n else if (place.mount)\n this.mounted = true;\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n this.nodeViews = buildNodeViews(this);\n this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);\n this.domObserver = new DOMObserver(this, (from, to, typeOver, added) => readDOMChange(this, from, to, typeOver, added));\n this.domObserver.start();\n initInput(this);\n this.updatePluginViews();\n }\n /**\n Holds `true` when a\n [composition](https://w3c.github.io/uievents/#events-compositionevents)\n is active.\n */\n get composing() { return this.input.composing; }\n /**\n The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).\n */\n get props() {\n if (this._props.state != this.state) {\n let prev = this._props;\n this._props = {};\n for (let name in prev)\n this._props[name] = prev[name];\n this._props.state = this.state;\n }\n return this._props;\n }\n /**\n Update the view's props. Will immediately cause an update to\n the DOM.\n */\n update(props) {\n if (props.handleDOMEvents != this._props.handleDOMEvents)\n ensureListeners(this);\n let prevProps = this._props;\n this._props = props;\n if (props.plugins) {\n props.plugins.forEach(checkStateComponent);\n this.directPlugins = props.plugins;\n }\n this.updateStateInner(props.state, prevProps);\n }\n /**\n Update the view by updating existing props object with the object\n given as argument. Equivalent to `view.update(Object.assign({},\n view.props, props))`.\n */\n setProps(props) {\n let updated = {};\n for (let name in this._props)\n updated[name] = this._props[name];\n updated.state = this.state;\n for (let name in props)\n updated[name] = props[name];\n this.update(updated);\n }\n /**\n Update the editor's `state` prop, without touching any of the\n other props.\n */\n updateState(state) {\n this.updateStateInner(state, this._props);\n }\n updateStateInner(state, prevProps) {\n var _a;\n let prev = this.state, redraw = false, updateSel = false;\n // When stored marks are added, stop composition, so that they can\n // be displayed.\n if (state.storedMarks && this.composing) {\n clearComposition(this);\n updateSel = true;\n }\n this.state = state;\n let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;\n if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {\n let nodeViews = buildNodeViews(this);\n if (changedNodeViews(nodeViews, this.nodeViews)) {\n this.nodeViews = nodeViews;\n redraw = true;\n }\n }\n if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {\n ensureListeners(this);\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);\n let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? \"reset\"\n : state.scrollToSelection > prev.scrollToSelection ? \"to selection\" : \"preserve\";\n let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);\n if (updateDoc || !state.selection.eq(prev.selection))\n updateSel = true;\n let oldScrollPos = scroll == \"preserve\" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);\n if (updateSel) {\n this.domObserver.stop();\n // Work around an issue in Chrome, IE, and Edge where changing\n // the DOM around an active selection puts it into a broken\n // state where the thing the user sees differs from the\n // selection reported by the Selection object (#710, #973,\n // #1011, #1013, #1035).\n let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing &&\n !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);\n if (updateDoc) {\n // If the node that the selection points into is written to,\n // Chrome sometimes starts misreporting the selection, so this\n // tracks that and forces a selection reset when our update\n // did write to the node.\n let chromeKludge = chrome ? (this.trackWrites = this.domSelectionRange().focusNode) : null;\n if (this.composing)\n this.input.compositionNode = findCompositionNode(this);\n if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {\n this.docView.updateOuterDeco(outerDeco);\n this.docView.destroy();\n this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);\n }\n if (chromeKludge && !this.trackWrites)\n forceSelUpdate = true;\n }\n // Work around for an issue where an update arriving right between\n // a DOM selection change and the \"selectionchange\" event for it\n // can cause a spurious DOM selection update, disrupting mouse\n // drag selection.\n if (forceSelUpdate ||\n !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) &&\n anchorInRightPlace(this))) {\n selectionToDOM(this, forceSelUpdate);\n }\n else {\n syncNodeSelection(this, state.selection);\n this.domObserver.setCurSelection();\n }\n this.domObserver.start();\n }\n this.updatePluginViews(prev);\n if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc))\n this.updateDraggedNode(this.dragging, prev);\n if (scroll == \"reset\") {\n this.dom.scrollTop = 0;\n }\n else if (scroll == \"to selection\") {\n this.scrollToSelection();\n }\n else if (oldScrollPos) {\n resetScrollPos(oldScrollPos);\n }\n }\n /**\n @internal\n */\n scrollToSelection() {\n let startDOM = this.domSelectionRange().focusNode;\n if (this.someProp(\"handleScrollToSelection\", f => f(this))) ;\n else if (this.state.selection instanceof NodeSelection) {\n let target = this.docView.domAfterPos(this.state.selection.from);\n if (target.nodeType == 1)\n scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);\n }\n else {\n scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);\n }\n }\n destroyPluginViews() {\n let view;\n while (view = this.pluginViews.pop())\n if (view.destroy)\n view.destroy();\n }\n updatePluginViews(prevState) {\n if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {\n this.prevDirectPlugins = this.directPlugins;\n this.destroyPluginViews();\n for (let i = 0; i < this.directPlugins.length; i++) {\n let plugin = this.directPlugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n for (let i = 0; i < this.state.plugins.length; i++) {\n let plugin = this.state.plugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n }\n else {\n for (let i = 0; i < this.pluginViews.length; i++) {\n let pluginView = this.pluginViews[i];\n if (pluginView.update)\n pluginView.update(this, prevState);\n }\n }\n }\n updateDraggedNode(dragging, prev) {\n let sel = dragging.node, found = -1;\n if (this.state.doc.nodeAt(sel.from) == sel.node) {\n found = sel.from;\n }\n else {\n let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);\n let moved = movedPos > 0 && this.state.doc.nodeAt(movedPos);\n if (moved == sel.node)\n found = movedPos;\n }\n this.dragging = new Dragging(dragging.slice, dragging.move, found < 0 ? undefined : NodeSelection.create(this.state.doc, found));\n }\n someProp(propName, f) {\n let prop = this._props && this._props[propName], value;\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n for (let i = 0; i < this.directPlugins.length; i++) {\n let prop = this.directPlugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n let plugins = this.state.plugins;\n if (plugins)\n for (let i = 0; i < plugins.length; i++) {\n let prop = plugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n }\n /**\n Query whether the view has focus.\n */\n hasFocus() {\n // Work around IE not handling focus correctly if resize handles are shown.\n // If the cursor is inside an element with resize handles, activeElement\n // will be that element instead of this.dom.\n if (ie) {\n // If activeElement is within this.dom, and there are no other elements\n // setting `contenteditable` to false in between, treat it as focused.\n let node = this.root.activeElement;\n if (node == this.dom)\n return true;\n if (!node || !this.dom.contains(node))\n return false;\n while (node && this.dom != node && this.dom.contains(node)) {\n if (node.contentEditable == 'false')\n return false;\n node = node.parentElement;\n }\n return true;\n }\n return this.root.activeElement == this.dom;\n }\n /**\n Focus the editor.\n */\n focus() {\n this.domObserver.stop();\n if (this.editable)\n focusPreventScroll(this.dom);\n selectionToDOM(this);\n this.domObserver.start();\n }\n /**\n Get the document root in which the editor exists. This will\n usually be the top-level `document`, but might be a [shadow\n DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)\n root if the editor is inside one.\n */\n get root() {\n let cached = this._root;\n if (cached == null)\n for (let search = this.dom.parentNode; search; search = search.parentNode) {\n if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) {\n if (!search.getSelection)\n Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection();\n return this._root = search;\n }\n }\n return cached || document;\n }\n /**\n When an existing editor view is moved to a new document or\n shadow tree, call this to make it recompute its root.\n */\n updateRoot() {\n this._root = null;\n }\n /**\n Given a pair of viewport coordinates, return the document\n position that corresponds to them. May return null if the given\n coordinates aren't inside of the editor. When an object is\n returned, its `pos` property is the position nearest to the\n coordinates, and its `inside` property holds the position of the\n inner node that the position falls inside of, or -1 if it is at\n the top level, not in any node.\n */\n posAtCoords(coords) {\n return posAtCoords(this, coords);\n }\n /**\n Returns the viewport rectangle at a given document position.\n `left` and `right` will be the same number, as this returns a\n flat cursor-ish rectangle. If the position is between two things\n that aren't directly adjacent, `side` determines which element\n is used. When < 0, the element before the position is used,\n otherwise the element after.\n */\n coordsAtPos(pos, side = 1) {\n return coordsAtPos(this, pos, side);\n }\n /**\n Find the DOM position that corresponds to the given document\n position. When `side` is negative, find the position as close as\n possible to the content before the position. When positive,\n prefer positions close to the content after the position. When\n zero, prefer as shallow a position as possible.\n \n Note that you should **not** mutate the editor's internal DOM,\n only inspect it (and even that is usually not necessary).\n */\n domAtPos(pos, side = 0) {\n return this.docView.domFromPos(pos, side);\n }\n /**\n Find the DOM node that represents the document node after the\n given position. May return `null` when the position doesn't point\n in front of a node or if the node is inside an opaque node view.\n \n This is intended to be able to call things like\n `getBoundingClientRect` on that DOM node. Do **not** mutate the\n editor DOM directly, or add styling this way, since that will be\n immediately overriden by the editor as it redraws the node.\n */\n nodeDOM(pos) {\n let desc = this.docView.descAt(pos);\n return desc ? desc.nodeDOM : null;\n }\n /**\n Find the document position that corresponds to a given DOM\n position. (Whenever possible, it is preferable to inspect the\n document structure directly, rather than poking around in the\n DOM, but sometimes—for example when interpreting an event\n target—you don't have a choice.)\n \n The `bias` parameter can be used to influence which side of a DOM\n node to use when the position is inside a leaf node.\n */\n posAtDOM(node, offset, bias = -1) {\n let pos = this.docView.posFromDOM(node, offset, bias);\n if (pos == null)\n throw new RangeError(\"DOM position not inside the editor\");\n return pos;\n }\n /**\n Find out whether the selection is at the end of a textblock when\n moving in a given direction. When, for example, given `\"left\"`,\n it will return true if moving left from the current cursor\n position would leave that position's parent textblock. Will apply\n to the view's current state by default, but it is possible to\n pass a different state.\n */\n endOfTextblock(dir, state) {\n return endOfTextblock(this, state || this.state, dir);\n }\n /**\n Run the editor's paste logic with the given HTML string. The\n `event`, if given, will be passed to the\n [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.\n */\n pasteHTML(html, event) {\n return doPaste(this, \"\", html, false, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Run the editor's paste logic with the given plain-text input.\n */\n pasteText(text, event) {\n return doPaste(this, text, null, true, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Removes the editor from the DOM and destroys all [node\n views](https://prosemirror.net/docs/ref/#view.NodeView).\n */\n destroy() {\n if (!this.docView)\n return;\n destroyInput(this);\n this.destroyPluginViews();\n if (this.mounted) {\n this.docView.update(this.state.doc, [], viewDecorations(this), this);\n this.dom.textContent = \"\";\n }\n else if (this.dom.parentNode) {\n this.dom.parentNode.removeChild(this.dom);\n }\n this.docView.destroy();\n this.docView = null;\n clearReusedRange();\n }\n /**\n This is true when the view has been\n [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be\n used anymore).\n */\n get isDestroyed() {\n return this.docView == null;\n }\n /**\n Used for testing.\n */\n dispatchEvent(event) {\n return dispatchEvent(this, event);\n }\n /**\n Dispatch a transaction. Will call\n [`dispatchTransaction`](https://prosemirror.net/docs/ref/#view.DirectEditorProps.dispatchTransaction)\n when given, and otherwise defaults to applying the transaction to\n the current state and calling\n [`updateState`](https://prosemirror.net/docs/ref/#view.EditorView.updateState) with the result.\n This method is bound to the view instance, so that it can be\n easily passed around.\n */\n dispatch(tr) {\n let dispatchTransaction = this._props.dispatchTransaction;\n if (dispatchTransaction)\n dispatchTransaction.call(this, tr);\n else\n this.updateState(this.state.apply(tr));\n }\n /**\n @internal\n */\n domSelectionRange() {\n let sel = this.domSelection();\n if (!sel)\n return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };\n return safari && this.root.nodeType === 11 &&\n deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;\n }\n /**\n @internal\n */\n domSelection() {\n return this.root.getSelection();\n }\n}\nfunction computeDocDeco(view) {\n let attrs = Object.create(null);\n attrs.class = \"ProseMirror\";\n attrs.contenteditable = String(view.editable);\n view.someProp(\"attributes\", value => {\n if (typeof value == \"function\")\n value = value(view.state);\n if (value)\n for (let attr in value) {\n if (attr == \"class\")\n attrs.class += \" \" + value[attr];\n else if (attr == \"style\")\n attrs.style = (attrs.style ? attrs.style + \";\" : \"\") + value[attr];\n else if (!attrs[attr] && attr != \"contenteditable\" && attr != \"nodeName\")\n attrs[attr] = String(value[attr]);\n }\n });\n if (!attrs.translate)\n attrs.translate = \"no\";\n return [Decoration.node(0, view.state.doc.content.size, attrs)];\n}\nfunction updateCursorWrapper(view) {\n if (view.markCursor) {\n let dom = document.createElement(\"img\");\n dom.className = \"ProseMirror-separator\";\n dom.setAttribute(\"mark-placeholder\", \"true\");\n dom.setAttribute(\"alt\", \"\");\n view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };\n }\n else {\n view.cursorWrapper = null;\n }\n}\nfunction getEditable(view) {\n return !view.someProp(\"editable\", value => value(view.state) === false);\n}\nfunction selectionContextChanged(sel1, sel2) {\n let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));\n return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);\n}\nfunction buildNodeViews(view) {\n let result = Object.create(null);\n function add(obj) {\n for (let prop in obj)\n if (!Object.prototype.hasOwnProperty.call(result, prop))\n result[prop] = obj[prop];\n }\n view.someProp(\"nodeViews\", add);\n view.someProp(\"markViews\", add);\n return result;\n}\nfunction changedNodeViews(a, b) {\n let nA = 0, nB = 0;\n for (let prop in a) {\n if (a[prop] != b[prop])\n return true;\n nA++;\n }\n for (let _ in b)\n nB++;\n return nA != nB;\n}\nfunction checkStateComponent(plugin) {\n if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)\n throw new RangeError(\"Plugins passed directly to the view must not have a state component\");\n}\n\nexport { Decoration, DecorationSet, EditorView, __endComposition, __parseFromClipboard, __serializeForClipboard };\n","export var base = {\n 8: \"Backspace\",\n 9: \"Tab\",\n 10: \"Enter\",\n 12: \"NumLock\",\n 13: \"Enter\",\n 16: \"Shift\",\n 17: \"Control\",\n 18: \"Alt\",\n 20: \"CapsLock\",\n 27: \"Escape\",\n 32: \" \",\n 33: \"PageUp\",\n 34: \"PageDown\",\n 35: \"End\",\n 36: \"Home\",\n 37: \"ArrowLeft\",\n 38: \"ArrowUp\",\n 39: \"ArrowRight\",\n 40: \"ArrowDown\",\n 44: \"PrintScreen\",\n 45: \"Insert\",\n 46: \"Delete\",\n 59: \";\",\n 61: \"=\",\n 91: \"Meta\",\n 92: \"Meta\",\n 106: \"*\",\n 107: \"+\",\n 108: \",\",\n 109: \"-\",\n 110: \".\",\n 111: \"/\",\n 144: \"NumLock\",\n 145: \"ScrollLock\",\n 160: \"Shift\",\n 161: \"Shift\",\n 162: \"Control\",\n 163: \"Control\",\n 164: \"Alt\",\n 165: \"Alt\",\n 173: \"-\",\n 186: \";\",\n 187: \"=\",\n 188: \",\",\n 189: \"-\",\n 190: \".\",\n 191: \"/\",\n 192: \"`\",\n 219: \"[\",\n 220: \"\\\\\",\n 221: \"]\",\n 222: \"'\"\n}\n\nexport var shift = {\n 48: \")\",\n 49: \"!\",\n 50: \"@\",\n 51: \"#\",\n 52: \"$\",\n 53: \"%\",\n 54: \"^\",\n 55: \"&\",\n 56: \"*\",\n 57: \"(\",\n 59: \":\",\n 61: \"+\",\n 173: \"_\",\n 186: \":\",\n 187: \"+\",\n 188: \"<\",\n 189: \"_\",\n 190: \">\",\n 191: \"?\",\n 192: \"~\",\n 219: \"{\",\n 220: \"|\",\n 221: \"}\",\n 222: \"\\\"\"\n}\n\nvar mac = typeof navigator != \"undefined\" && /Mac/.test(navigator.platform)\nvar ie = typeof navigator != \"undefined\" && /MSIE \\d|Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent)\n\n// Fill in the digit keys\nfor (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i)\n\n// The function keys\nfor (var i = 1; i <= 24; i++) base[i + 111] = \"F\" + i\n\n// And the alphabetic keys\nfor (var i = 65; i <= 90; i++) {\n base[i] = String.fromCharCode(i + 32)\n shift[i] = String.fromCharCode(i)\n}\n\n// For each code that doesn't have a shift-equivalent, copy the base name\nfor (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]\n\nexport function keyName(event) {\n // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.\n // On IE, shift effect is never included in `.key`.\n var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||\n ie && event.shiftKey && event.key && event.key.length == 1 ||\n event.key == \"Unidentified\"\n var name = (!ignoreKey && event.key) ||\n (event.shiftKey ? shift : base)[event.keyCode] ||\n event.key || \"Unidentified\"\n // Edge sometimes produces wrong names (Issue #3)\n if (name == \"Esc\") name = \"Escape\"\n if (name == \"Del\") name = \"Delete\"\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/\n if (name == \"Left\") name = \"ArrowLeft\"\n if (name == \"Up\") name = \"ArrowUp\"\n if (name == \"Right\") name = \"ArrowRight\"\n if (name == \"Down\") name = \"ArrowDown\"\n return name\n}\n","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","import { ReplaceError, Slice, Fragment, MarkType, Mark } from 'prosemirror-model';\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\nconst lower16 = 0xffff;\nconst factor16 = Math.pow(2, 16);\nfunction makeRecover(index, offset) { return index + offset * factor16; }\nfunction recoverIndex(value) { return value & lower16; }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16; }\nconst DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;\n/**\nAn object representing a mapped position with extra\ninformation.\n*/\nclass MapResult {\n /**\n @internal\n */\n constructor(\n /**\n The mapped version of the position.\n */\n pos, \n /**\n @internal\n */\n delInfo, \n /**\n @internal\n */\n recover) {\n this.pos = pos;\n this.delInfo = delInfo;\n this.recover = recover;\n }\n /**\n Tells you whether the position was deleted, that is, whether the\n step removed the token on the side queried (via the `assoc`)\n argument from the document.\n */\n get deleted() { return (this.delInfo & DEL_SIDE) > 0; }\n /**\n Tells you whether the token before the mapped position was deleted.\n */\n get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }\n /**\n True when the token after the mapped position was deleted.\n */\n get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }\n /**\n Tells whether any of the steps mapped through deletes across the\n position (including both the token before and after the\n position).\n */\n get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }\n}\n/**\nA map describing the deletions and insertions made by a step, which\ncan be used to find the correspondence between positions in the\npre-step version of a document and the same position in the\npost-step version.\n*/\nclass StepMap {\n /**\n Create a position map. The modifications to the document are\n represented as an array of numbers, in which each group of three\n represents a modified chunk as `[start, oldSize, newSize]`.\n */\n constructor(\n /**\n @internal\n */\n ranges, \n /**\n @internal\n */\n inverted = false) {\n this.ranges = ranges;\n this.inverted = inverted;\n if (!ranges.length && StepMap.empty)\n return StepMap.empty;\n }\n /**\n @internal\n */\n recover(value) {\n let diff = 0, index = recoverIndex(value);\n if (!this.inverted)\n for (let i = 0; i < index; i++)\n diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];\n return this.ranges[index * 3] + diff + recoverOffset(value);\n }\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n map(pos, assoc = 1) { return this._map(pos, assoc, true); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n if (pos <= end) {\n let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n let result = start + diff + (side < 0 ? 0 : newSize);\n if (simple)\n return result;\n let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;\n if (assoc < 0 ? pos != start : pos != end)\n del |= DEL_SIDE;\n return new MapResult(result, del, recover);\n }\n diff += newSize - oldSize;\n }\n return simple ? pos + diff : new MapResult(pos + diff, 0, null);\n }\n /**\n @internal\n */\n touches(pos, recover) {\n let diff = 0, index = recoverIndex(recover);\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n if (pos <= end && i == index * 3)\n return true;\n diff += this.ranges[i + newIndex] - oldSize;\n }\n return false;\n }\n /**\n Calls the given function on each of the changed ranges included in\n this map.\n */\n forEach(f) {\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];\n f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n diff += newSize - oldSize;\n }\n }\n /**\n Create an inverted version of this map. The result can be used to\n map positions in the post-step document to the pre-step document.\n */\n invert() {\n return new StepMap(this.ranges, !this.inverted);\n }\n /**\n @internal\n */\n toString() {\n return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges);\n }\n /**\n Create a map that moves all positions by offset `n` (which may be\n negative). This can be useful when applying steps meant for a\n sub-document to a larger document, or vice-versa.\n */\n static offset(n) {\n return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);\n }\n}\n/**\nA StepMap that contains no changed ranges.\n*/\nStepMap.empty = new StepMap([]);\n/**\nA mapping represents a pipeline of zero or more [step\nmaps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly\nhandling mapping positions through a series of steps in which some\nsteps are inverted versions of earlier steps. (This comes up when\n‘[rebasing](/docs/guide/#transform.rebasing)’ steps for\ncollaboration or history management.)\n*/\nclass Mapping {\n /**\n Create a new mapping with the given position maps.\n */\n constructor(\n /**\n The step maps in this mapping.\n */\n maps = [], \n /**\n @internal\n */\n mirror, \n /**\n The starting position in the `maps` array, used when `map` or\n `mapResult` is called.\n */\n from = 0, \n /**\n The end position in the `maps` array.\n */\n to = maps.length) {\n this.maps = maps;\n this.mirror = mirror;\n this.from = from;\n this.to = to;\n }\n /**\n Create a mapping that maps only through a part of this one.\n */\n slice(from = 0, to = this.maps.length) {\n return new Mapping(this.maps, this.mirror, from, to);\n }\n /**\n @internal\n */\n copy() {\n return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to);\n }\n /**\n Add a step map to the end of this mapping. If `mirrors` is\n given, it should be the index of the step map that is the mirror\n image of this one.\n */\n appendMap(map, mirrors) {\n this.to = this.maps.push(map);\n if (mirrors != null)\n this.setMirror(this.maps.length - 1, mirrors);\n }\n /**\n Add all the step maps in a given mapping to this one (preserving\n mirroring information).\n */\n appendMapping(mapping) {\n for (let i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);\n }\n }\n /**\n Finds the offset of the step map that mirrors the map at the\n given offset, in this mapping (as per the second argument to\n `appendMap`).\n */\n getMirror(n) {\n if (this.mirror)\n for (let i = 0; i < this.mirror.length; i++)\n if (this.mirror[i] == n)\n return this.mirror[i + (i % 2 ? -1 : 1)];\n }\n /**\n @internal\n */\n setMirror(n, m) {\n if (!this.mirror)\n this.mirror = [];\n this.mirror.push(n, m);\n }\n /**\n Append the inverse of the given mapping to this one.\n */\n appendMappingInverted(mapping) {\n for (let i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);\n }\n }\n /**\n Create an inverted version of this mapping.\n */\n invert() {\n let inverse = new Mapping;\n inverse.appendMappingInverted(this);\n return inverse;\n }\n /**\n Map a position through this mapping.\n */\n map(pos, assoc = 1) {\n if (this.mirror)\n return this._map(pos, assoc, true);\n for (let i = this.from; i < this.to; i++)\n pos = this.maps[i].map(pos, assoc);\n return pos;\n }\n /**\n Map a position through this mapping, returning a mapping\n result.\n */\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let delInfo = 0;\n for (let i = this.from; i < this.to; i++) {\n let map = this.maps[i], result = map.mapResult(pos, assoc);\n if (result.recover != null) {\n let corr = this.getMirror(i);\n if (corr != null && corr > i && corr < this.to) {\n i = corr;\n pos = this.maps[corr].recover(result.recover);\n continue;\n }\n }\n delInfo |= result.delInfo;\n pos = result.pos;\n }\n return simple ? pos : new MapResult(pos, delInfo, null);\n }\n}\n\nconst stepsByID = Object.create(null);\n/**\nA step object represents an atomic change. It generally applies\nonly to the document it was created for, since the positions\nstored in it will only make sense for that document.\n\nNew steps are defined by creating classes that extend `Step`,\noverriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\nmethods, and registering your class with a unique\nJSON-serialization identifier using\n[`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).\n*/\nclass Step {\n /**\n Get the step map that represents the changes made by this step,\n and which can be used to transform between positions in the old\n and the new document.\n */\n getMap() { return StepMap.empty; }\n /**\n Try to merge this step with another one, to be applied directly\n after it. Returns the merged step when possible, null if the\n steps can't be merged.\n */\n merge(other) { return null; }\n /**\n Deserialize a step from its JSON representation. Will call\n through to the step class' own implementation of this method.\n */\n static fromJSON(schema, json) {\n if (!json || !json.stepType)\n throw new RangeError(\"Invalid input for Step.fromJSON\");\n let type = stepsByID[json.stepType];\n if (!type)\n throw new RangeError(`No step type ${json.stepType} defined`);\n return type.fromJSON(schema, json);\n }\n /**\n To be able to serialize steps to JSON, each step needs a string\n ID to attach to its JSON representation. Use this method to\n register an ID for your step classes. Try to pick something\n that's unlikely to clash with steps from other modules.\n */\n static jsonID(id, stepClass) {\n if (id in stepsByID)\n throw new RangeError(\"Duplicate use of step JSON ID \" + id);\n stepsByID[id] = stepClass;\n stepClass.prototype.jsonID = id;\n return stepClass;\n }\n}\n/**\nThe result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a\nnew document or a failure value.\n*/\nclass StepResult {\n /**\n @internal\n */\n constructor(\n /**\n The transformed document, if successful.\n */\n doc, \n /**\n The failure message, if unsuccessful.\n */\n failed) {\n this.doc = doc;\n this.failed = failed;\n }\n /**\n Create a successful step result.\n */\n static ok(doc) { return new StepResult(doc, null); }\n /**\n Create a failed step result.\n */\n static fail(message) { return new StepResult(null, message); }\n /**\n Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given\n arguments. Create a successful result if it succeeds, and a\n failed one if it throws a `ReplaceError`.\n */\n static fromReplace(doc, from, to, slice) {\n try {\n return StepResult.ok(doc.replace(from, to, slice));\n }\n catch (e) {\n if (e instanceof ReplaceError)\n return StepResult.fail(e.message);\n throw e;\n }\n }\n}\n\nfunction mapFragment(fragment, f, parent) {\n let mapped = [];\n for (let i = 0; i < fragment.childCount; i++) {\n let child = fragment.child(i);\n if (child.content.size)\n child = child.copy(mapFragment(child.content, f, child));\n if (child.isInline)\n child = f(child, parent, i);\n mapped.push(child);\n }\n return Fragment.fromArray(mapped);\n}\n/**\nAdd a mark to all inline content between two positions.\n*/\nclass AddMarkStep extends Step {\n /**\n Create a mark step.\n */\n constructor(\n /**\n The start of the marked range.\n */\n from, \n /**\n The end of the marked range.\n */\n to, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n let parent = $from.node($from.sharedDepth(this.to));\n let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {\n if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))\n return node;\n return node.mark(this.mark.addToSet(node.marks));\n }, parent), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new RemoveMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new AddMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof AddMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"addMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\");\n return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addMark\", AddMarkStep);\n/**\nRemove a mark from all inline content between two positions.\n*/\nclass RemoveMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The start of the unmarked range.\n */\n from, \n /**\n The end of the unmarked range.\n */\n to, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to);\n let slice = new Slice(mapFragment(oldSlice.content, node => {\n return node.mark(this.mark.removeFromSet(node.marks));\n }, doc), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new AddMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new RemoveMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof RemoveMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"removeMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\");\n return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeMark\", RemoveMarkStep);\n/**\nAdd a mark to a specific node.\n*/\nclass AddNodeMarkStep extends Step {\n /**\n Create a node mark step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (node) {\n let newSet = this.mark.addToSet(node.marks);\n if (newSet.length == node.marks.length) {\n for (let i = 0; i < node.marks.length; i++)\n if (!node.marks[i].isInSet(newSet))\n return new AddNodeMarkStep(this.pos, node.marks[i]);\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n }\n return new RemoveNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"addNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for AddNodeMarkStep.fromJSON\");\n return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addNodeMark\", AddNodeMarkStep);\n/**\nRemove a mark from a specific node.\n*/\nclass RemoveNodeMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node || !this.mark.isInSet(node.marks))\n return this;\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"removeNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for RemoveNodeMarkStep.fromJSON\");\n return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeNodeMark\", RemoveNodeMarkStep);\n\n/**\nReplace a part of the document with a slice of new content.\n*/\nclass ReplaceStep extends Step {\n /**\n The given `slice` should fit the 'gap' between `from` and\n `to`—the depths must line up, and the surrounding nodes must be\n able to be joined with the open sides of the slice. When\n `structure` is true, the step will fail if the content between\n from and to is not just a sequence of closing and then opening\n tokens (this is to guard against rebased replace steps\n overwriting something they weren't supposed to).\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The slice to insert.\n */\n slice, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.slice = slice;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && contentBetween(doc, this.from, this.to))\n return StepResult.fail(\"Structure replace would overwrite content\");\n return StepResult.fromReplace(doc, this.from, this.to, this.slice);\n }\n getMap() {\n return new StepMap([this.from, this.to - this.from, this.slice.size]);\n }\n invert(doc) {\n return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deletedAcross && to.deletedAcross)\n return null;\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice);\n }\n merge(other) {\n if (!(other instanceof ReplaceStep) || other.structure || this.structure)\n return null;\n if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);\n }\n else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n return new ReplaceStep(other.from, this.to, slice, this.structure);\n }\n else {\n return null;\n }\n }\n toJSON() {\n let json = { stepType: \"replace\", from: this.from, to: this.to };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\");\n return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);\n }\n}\nStep.jsonID(\"replace\", ReplaceStep);\n/**\nReplace a part of the document with a slice of content, but\npreserve a range of the replaced content by moving it into the\nslice.\n*/\nclass ReplaceAroundStep extends Step {\n /**\n Create a replace-around step with the given range and gap.\n `insert` should be the point in the slice into which the content\n of the gap should be moved. `structure` has the same meaning as\n it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The start of preserved range.\n */\n gapFrom, \n /**\n The end of preserved range.\n */\n gapTo, \n /**\n The slice to insert.\n */\n slice, \n /**\n The position in the slice where the preserved range should be\n inserted.\n */\n insert, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.gapFrom = gapFrom;\n this.gapTo = gapTo;\n this.slice = slice;\n this.insert = insert;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||\n contentBetween(doc, this.gapTo, this.to)))\n return StepResult.fail(\"Structure gap-replace would overwrite content\");\n let gap = doc.slice(this.gapFrom, this.gapTo);\n if (gap.openStart || gap.openEnd)\n return StepResult.fail(\"Gap is not a flat range\");\n let inserted = this.slice.insertAt(this.insert, gap.content);\n if (!inserted)\n return StepResult.fail(\"Content does not fit in gap\");\n return StepResult.fromReplace(doc, this.from, this.to, inserted);\n }\n getMap() {\n return new StepMap([this.from, this.gapFrom - this.from, this.insert,\n this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);\n }\n invert(doc) {\n let gap = this.gapTo - this.gapFrom;\n return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);\n let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);\n if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos)\n return null;\n return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);\n }\n toJSON() {\n let json = { stepType: \"replaceAround\", from: this.from, to: this.to,\n gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\" ||\n typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\")\n throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\");\n return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);\n }\n}\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\nfunction contentBetween(doc, from, to) {\n let $from = doc.resolve(from), dist = to - from, depth = $from.depth;\n while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n depth--;\n dist--;\n }\n if (dist > 0) {\n let next = $from.node(depth).maybeChild($from.indexAfter(depth));\n while (dist > 0) {\n if (!next || next.isLeaf)\n return true;\n next = next.firstChild;\n dist--;\n }\n }\n return false;\n}\n\nfunction addMark(tr, from, to, mark) {\n let removed = [], added = [];\n let removing, adding;\n tr.doc.nodesBetween(from, to, (node, pos, parent) => {\n if (!node.isInline)\n return;\n let marks = node.marks;\n if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n let newSet = mark.addToSet(marks);\n for (let i = 0; i < marks.length; i++) {\n if (!marks[i].isInSet(newSet)) {\n if (removing && removing.to == start && removing.mark.eq(marks[i]))\n removing.to = end;\n else\n removed.push(removing = new RemoveMarkStep(start, end, marks[i]));\n }\n }\n if (adding && adding.to == start)\n adding.to = end;\n else\n added.push(adding = new AddMarkStep(start, end, mark));\n }\n });\n removed.forEach(s => tr.step(s));\n added.forEach(s => tr.step(s));\n}\nfunction removeMark(tr, from, to, mark) {\n let matched = [], step = 0;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isInline)\n return;\n step++;\n let toRemove = null;\n if (mark instanceof MarkType) {\n let set = node.marks, found;\n while (found = mark.isInSet(set)) {\n (toRemove || (toRemove = [])).push(found);\n set = found.removeFromSet(set);\n }\n }\n else if (mark) {\n if (mark.isInSet(node.marks))\n toRemove = [mark];\n }\n else {\n toRemove = node.marks;\n }\n if (toRemove && toRemove.length) {\n let end = Math.min(pos + node.nodeSize, to);\n for (let i = 0; i < toRemove.length; i++) {\n let style = toRemove[i], found;\n for (let j = 0; j < matched.length; j++) {\n let m = matched[j];\n if (m.step == step - 1 && style.eq(matched[j].style))\n found = m;\n }\n if (found) {\n found.to = end;\n found.step = step;\n }\n else {\n matched.push({ style, from: Math.max(pos, from), to: end, step });\n }\n }\n }\n });\n matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));\n}\nfunction clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {\n let node = tr.doc.nodeAt(pos);\n let replSteps = [], cur = pos + 1;\n for (let i = 0; i < node.childCount; i++) {\n let child = node.child(i), end = cur + child.nodeSize;\n let allowed = match.matchType(child.type);\n if (!allowed) {\n replSteps.push(new ReplaceStep(cur, end, Slice.empty));\n }\n else {\n match = allowed;\n for (let j = 0; j < child.marks.length; j++)\n if (!parentType.allowsMarkType(child.marks[j].type))\n tr.step(new RemoveMarkStep(cur, end, child.marks[j]));\n if (clearNewlines && child.isText && parentType.whitespace != \"pre\") {\n let m, newline = /\\r?\\n|\\r/g, slice;\n while (m = newline.exec(child.text)) {\n if (!slice)\n slice = new Slice(Fragment.from(parentType.schema.text(\" \", parentType.allowedMarks(child.marks))), 0, 0);\n replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));\n }\n }\n }\n cur = end;\n }\n if (!match.validEnd) {\n let fill = match.fillBefore(Fragment.empty, true);\n tr.replace(cur, cur, new Slice(fill, 0, 0));\n }\n for (let i = replSteps.length - 1; i >= 0; i--)\n tr.step(replSteps[i]);\n}\n\nfunction canCut(node, start, end) {\n return (start == 0 || node.canReplace(start, node.childCount)) &&\n (end == node.childCount || node.canReplace(0, end));\n}\n/**\nTry to find a target depth to which the content in the given range\ncan be lifted. Will not go across\n[isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.\n*/\nfunction liftTarget(range) {\n let parent = range.parent;\n let content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n for (let depth = range.depth;; --depth) {\n let node = range.$from.node(depth);\n let index = range.$from.index(depth), endIndex = range.$to.indexAfter(depth);\n if (depth < range.depth && node.canReplace(index, endIndex, content))\n return depth;\n if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))\n break;\n }\n return null;\n}\nfunction lift(tr, range, target) {\n let { $from, $to, depth } = range;\n let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n let start = gapStart, end = gapEnd;\n let before = Fragment.empty, openStart = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $from.index(d) > 0) {\n splitting = true;\n before = Fragment.from($from.node(d).copy(before));\n openStart++;\n }\n else {\n start--;\n }\n let after = Fragment.empty, openEnd = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $to.after(d + 1) < $to.end(d)) {\n splitting = true;\n after = Fragment.from($to.node(d).copy(after));\n openEnd++;\n }\n else {\n end++;\n }\n tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));\n}\n/**\nTry to find a valid way to wrap the content in the given range in a\nnode of the given type. May introduce extra nodes around and inside\nthe wrapper node, if necessary. Returns null if no valid wrapping\ncould be found. When `innerRange` is given, that range's content is\nused as the content to fit into the wrapping, instead of the\ncontent of `range`.\n*/\nfunction findWrapping(range, nodeType, attrs = null, innerRange = range) {\n let around = findWrappingOutside(range, nodeType);\n let inner = around && findWrappingInside(innerRange, nodeType);\n if (!inner)\n return null;\n return around.map(withAttrs)\n .concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));\n}\nfunction withAttrs(type) { return { type, attrs: null }; }\nfunction findWrappingOutside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let around = parent.contentMatchAt(startIndex).findWrapping(type);\n if (!around)\n return null;\n let outer = around.length ? around[0] : type;\n return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;\n}\nfunction findWrappingInside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let inner = parent.child(startIndex);\n let inside = type.contentMatch.findWrapping(inner.type);\n if (!inside)\n return null;\n let lastType = inside.length ? inside[inside.length - 1] : type;\n let innerMatch = lastType.contentMatch;\n for (let i = startIndex; innerMatch && i < endIndex; i++)\n innerMatch = innerMatch.matchType(parent.child(i).type);\n if (!innerMatch || !innerMatch.validEnd)\n return null;\n return inside;\n}\nfunction wrap(tr, range, wrappers) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--) {\n if (content.size) {\n let match = wrappers[i].type.contentMatch.matchFragment(content);\n if (!match || !match.validEnd)\n throw new RangeError(\"Wrapper type given to Transform.wrap does not form valid content of its parent wrapper\");\n }\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n }\n let start = range.start, end = range.end;\n tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));\n}\nfunction setBlockType(tr, from, to, type, attrs) {\n if (!type.isTextblock)\n throw new RangeError(\"Type given to setBlockType should be a textblock\");\n let mapFrom = tr.steps.length;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n let attrsHere = typeof attrs == \"function\" ? attrs(node) : attrs;\n if (node.isTextblock && !node.hasMarkup(type, attrsHere) &&\n canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {\n let convertNewlines = null;\n if (type.schema.linebreakReplacement) {\n let pre = type.whitespace == \"pre\", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n // Ensure all markup that isn't allowed in the new node type is cleared\n if (convertNewlines === false)\n replaceLinebreaks(tr, node, pos, mapFrom);\n clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, undefined, convertNewlines === null);\n let mapping = tr.mapping.slice(mapFrom);\n let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));\n if (convertNewlines === true)\n replaceNewlines(tr, node, pos, mapFrom);\n return false;\n }\n });\n}\nfunction replaceNewlines(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.isText) {\n let m, newline = /\\r?\\n|\\r/g;\n while (m = newline.exec(child.text)) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);\n tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());\n }\n }\n });\n}\nfunction replaceLinebreaks(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.type == child.type.schema.linebreakReplacement) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);\n tr.replaceWith(start, start + 1, node.type.schema.text(\"\\n\"));\n }\n });\n}\nfunction canChangeType(doc, pos, type) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return $pos.parent.canReplaceWith(index, index + 1, type);\n}\n/**\nChange the type, attributes, and/or marks of the node at `pos`.\nWhen `type` isn't given, the existing node type is preserved,\n*/\nfunction setNodeMarkup(tr, pos, type, attrs, marks) {\n let node = tr.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at given position\");\n if (!type)\n type = node.type;\n let newNode = type.create(attrs, null, marks || node.marks);\n if (node.isLeaf)\n return tr.replaceWith(pos, pos + node.nodeSize, newNode);\n if (!type.validContent(node.content))\n throw new RangeError(\"Invalid content for node type \" + type.name);\n tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));\n}\n/**\nCheck whether splitting at the given position is allowed.\n*/\nfunction canSplit(doc, pos, depth = 1, typesAfter) {\n let $pos = doc.resolve(pos), base = $pos.depth - depth;\n let innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;\n if (base < 0 || $pos.parent.type.spec.isolating ||\n !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||\n !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))\n return false;\n for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n let node = $pos.node(d), index = $pos.index(d);\n if (node.type.spec.isolating)\n return false;\n let rest = node.content.cutByIndex(index, node.childCount);\n let overrideChild = typesAfter && typesAfter[i + 1];\n if (overrideChild)\n rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));\n let after = (typesAfter && typesAfter[i]) || node;\n if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest))\n return false;\n }\n let index = $pos.indexAfter(base);\n let baseType = typesAfter && typesAfter[0];\n return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);\n}\nfunction split(tr, pos, depth = 1, typesAfter) {\n let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n before = Fragment.from($pos.node(d).copy(before));\n let typeAfter = typesAfter && typesAfter[i];\n after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n }\n tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));\n}\n/**\nTest whether the blocks before and after a given position can be\njoined.\n*/\nfunction canJoin(doc, pos) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n $pos.parent.canReplace(index, index + 1);\n}\nfunction canAppendWithSubstitutedLinebreaks(a, b) {\n if (!b.content.size)\n a.type.compatibleContent(b.type);\n let match = a.contentMatchAt(a.childCount);\n let { linebreakReplacement } = a.type.schema;\n for (let i = 0; i < b.childCount; i++) {\n let child = b.child(i);\n let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;\n match = match.matchType(type);\n if (!match)\n return false;\n if (!a.type.allowsMarks(child.marks))\n return false;\n }\n return match.validEnd;\n}\nfunction joinable(a, b) {\n return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));\n}\n/**\nFind an ancestor of the given position that can be joined to the\nblock before (or after if `dir` is positive). Returns the joinable\npoint, if any.\n*/\nfunction joinPoint(doc, pos, dir = -1) {\n let $pos = doc.resolve(pos);\n for (let d = $pos.depth;; d--) {\n let before, after, index = $pos.index(d);\n if (d == $pos.depth) {\n before = $pos.nodeBefore;\n after = $pos.nodeAfter;\n }\n else if (dir > 0) {\n before = $pos.node(d + 1);\n index++;\n after = $pos.node(d).maybeChild(index);\n }\n else {\n before = $pos.node(d).maybeChild(index - 1);\n after = $pos.node(d + 1);\n }\n if (before && !before.isTextblock && joinable(before, after) &&\n $pos.node(d).canReplace(index, index + 1))\n return pos;\n if (d == 0)\n break;\n pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n }\n}\nfunction join(tr, pos, depth) {\n let convertNewlines = null;\n let { linebreakReplacement } = tr.doc.type.schema;\n let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;\n if (linebreakReplacement && beforeType.inlineContent) {\n let pre = beforeType.whitespace == \"pre\";\n let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n let mapFrom = tr.steps.length;\n if (convertNewlines === false) {\n let $after = tr.doc.resolve(pos + depth);\n replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);\n }\n if (beforeType.inlineContent)\n clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);\n let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);\n tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));\n if (convertNewlines === true) {\n let $full = tr.doc.resolve(start);\n replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);\n }\n return tr;\n}\n/**\nTry to find a point where a node of the given type can be inserted\nnear `pos`, by searching up the node hierarchy when `pos` itself\nisn't a valid place but is at the start or end of a node. Return\nnull if no position was found.\n*/\nfunction insertPoint(doc, pos, nodeType) {\n let $pos = doc.resolve(pos);\n if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))\n return pos;\n if ($pos.parentOffset == 0)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.index(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.before(d + 1);\n if (index > 0)\n return null;\n }\n if ($pos.parentOffset == $pos.parent.content.size)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.indexAfter(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.after(d + 1);\n if (index < $pos.node(d).childCount)\n return null;\n }\n return null;\n}\n/**\nFinds a position at or around the given position where the given\nslice can be inserted. Will look at parent nodes' nearest boundary\nand try there, even if the original position wasn't directly at the\nstart or end of that node. Returns null when no position was found.\n*/\nfunction dropPoint(doc, pos, slice) {\n let $pos = doc.resolve(pos);\n if (!slice.content.size)\n return pos;\n let content = slice.content;\n for (let i = 0; i < slice.openStart; i++)\n content = content.firstChild.content;\n for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n for (let d = $pos.depth; d >= 0; d--) {\n let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n let parent = $pos.node(d), fits = false;\n if (pass == 1) {\n fits = parent.canReplace(insertPos, insertPos, content);\n }\n else {\n let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);\n fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);\n }\n if (fits)\n return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);\n }\n }\n return null;\n}\n\n/**\n‘Fit’ a slice into a given position in the document, producing a\n[step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if\nthere's no meaningful way to insert the slice here, or inserting it\nwould be a no-op (an empty slice over an empty range).\n*/\nfunction replaceStep(doc, from, to = from, slice = Slice.empty) {\n if (from == to && !slice.size)\n return null;\n let $from = doc.resolve(from), $to = doc.resolve(to);\n // Optimization -- avoid work if it's obvious that it's not needed.\n if (fitsTrivially($from, $to, slice))\n return new ReplaceStep(from, to, slice);\n return new Fitter($from, $to, slice).fit();\n}\nfunction fitsTrivially($from, $to, slice) {\n return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&\n $from.parent.canReplace($from.index(), $to.index(), slice.content);\n}\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in , when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n// - `frontier` holds a stack of `{type, match}` objects that\n// represent the open side of the replacement. It starts at\n// `$from`, then moves forward as content is placed, and is finally\n// reconciled with `$to`.\n//\n// - `unplaced` is a slice that represents the content that hasn't\n// been placed yet.\n//\n// - `placed` is a fragment of placed content. Its open-start value\n// is implicit in `$from`, and its open-end value in `frontier`.\nclass Fitter {\n constructor($from, $to, unplaced) {\n this.$from = $from;\n this.$to = $to;\n this.unplaced = unplaced;\n this.frontier = [];\n this.placed = Fragment.empty;\n for (let i = 0; i <= $from.depth; i++) {\n let node = $from.node(i);\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt($from.indexAfter(i))\n });\n }\n for (let i = $from.depth; i > 0; i--)\n this.placed = Fragment.from($from.node(i).copy(this.placed));\n }\n get depth() { return this.frontier.length - 1; }\n fit() {\n // As long as there's unplaced content, try to place some of it.\n // If that fails, either increase the open score of the unplaced\n // slice, or drop nodes from it, and then try again.\n while (this.unplaced.size) {\n let fit = this.findFittable();\n if (fit)\n this.placeNodes(fit);\n else\n this.openMore() || this.dropNode();\n }\n // When there's inline content directly after the frontier _and_\n // directly after `this.$to`, we must generate a `ReplaceAround`\n // step that pulls that content into the node after the frontier.\n // That means the fitting must be done to the end of the textblock\n // node after `this.$to`, not `this.$to` itself.\n let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n if (!$to)\n return null;\n // If closing to `$to` succeeded, create a step\n let content = this.placed, openStart = $from.depth, openEnd = $to.depth;\n while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes\n content = content.firstChild.content;\n openStart--;\n openEnd--;\n }\n let slice = new Slice(content, openStart, openEnd);\n if (moveInline > -1)\n return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);\n if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps\n return new ReplaceStep($from.pos, $to.pos, slice);\n return null;\n }\n // Find a position on the start spine of `this.unplaced` that has\n // content that can be moved somewhere on the frontier. Returns two\n // depths, one for the slice and one for the frontier.\n findFittable() {\n let startDepth = this.unplaced.openStart;\n for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {\n let node = cur.firstChild;\n if (cur.childCount > 1)\n openEnd = 0;\n if (node.type.spec.isolating && openEnd <= d) {\n startDepth = d;\n break;\n }\n cur = node.content;\n }\n // Only try wrapping nodes (pass 2) after finding a place without\n // wrapping failed.\n for (let pass = 1; pass <= 2; pass++) {\n for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n let fragment, parent = null;\n if (sliceDepth) {\n parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n fragment = parent.content;\n }\n else {\n fragment = this.unplaced.content;\n }\n let first = fragment.firstChild;\n for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n let { type, match } = this.frontier[frontierDepth], wrap, inject = null;\n // In pass 1, if the next node matches, or there is no next\n // node but the parents look compatible, we've found a\n // place.\n if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))\n : parent && type.compatibleContent(parent.type)))\n return { sliceDepth, frontierDepth, parent, inject };\n // In pass 2, look for a set of wrapping nodes that make\n // `first` fit here.\n else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))\n return { sliceDepth, frontierDepth, parent, wrap };\n // Don't continue looking further up if the parent node\n // would fit here.\n if (parent && match.matchType(parent.type))\n break;\n }\n }\n }\n }\n openMore() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (!inner.childCount || inner.firstChild.isLeaf)\n return false;\n this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));\n return true;\n }\n dropNode() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (inner.childCount <= 1 && openStart > 0) {\n let openAtEnd = content.size - openStart <= openStart + inner.size;\n this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);\n }\n else {\n this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n }\n }\n // Move content from the unplaced slice at `sliceDepth` to the\n // frontier node at `frontierDepth`. Close that frontier node when\n // applicable.\n placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {\n while (this.depth > frontierDepth)\n this.closeFrontierNode();\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n this.openFrontierNode(wrap[i]);\n let slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n let openStart = slice.openStart - sliceDepth;\n let taken = 0, add = [];\n let { match, type } = this.frontier[frontierDepth];\n if (inject) {\n for (let i = 0; i < inject.childCount; i++)\n add.push(inject.child(i));\n match = match.matchFragment(inject);\n }\n // Computes the amount of (end) open nodes at the end of the\n // fragment. When 0, the parent is open, but no more. When\n // negative, nothing is open.\n let openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);\n // Scan over the fragment, fitting as many child nodes as\n // possible.\n while (taken < fragment.childCount) {\n let next = fragment.child(taken), matches = match.matchType(next.type);\n if (!matches)\n break;\n taken++;\n if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes\n match = matches;\n add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));\n }\n }\n let toEnd = taken == fragment.childCount;\n if (!toEnd)\n openEndCount = -1;\n this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n this.frontier[frontierDepth].match = match;\n // If the parent types match, and the entire node was moved, and\n // it's not open, close this frontier node right away.\n if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)\n this.closeFrontierNode();\n // Add new frontier nodes for any open nodes at the end.\n for (let i = 0, cur = fragment; i < openEndCount; i++) {\n let node = cur.lastChild;\n this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });\n cur = node.content;\n }\n // Update `this.unplaced`. Drop the entire node from which we\n // placed it we got to its end, otherwise just drop the placed\n // nodes.\n this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd)\n : sliceDepth == 0 ? Slice.empty\n : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n }\n mustMoveInline() {\n if (!this.$to.parent.isTextblock)\n return -1;\n let top = this.frontier[this.depth], level;\n if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||\n (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth))\n return -1;\n let { depth } = this.$to, after = this.$to.after(depth);\n while (depth > 1 && after == this.$to.end(--depth))\n ++after;\n return after;\n }\n findCloseLevel($to) {\n scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n let { match, type } = this.frontier[i];\n let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n let fit = contentAfterFits($to, i, type, match, dropInner);\n if (!fit)\n continue;\n for (let d = i - 1; d >= 0; d--) {\n let { match, type } = this.frontier[d];\n let matches = contentAfterFits($to, d, type, match, true);\n if (!matches || matches.childCount)\n continue scan;\n }\n return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };\n }\n }\n close($to) {\n let close = this.findCloseLevel($to);\n if (!close)\n return null;\n while (this.depth > close.depth)\n this.closeFrontierNode();\n if (close.fit.childCount)\n this.placed = addToFragment(this.placed, close.depth, close.fit);\n $to = close.move;\n for (let d = close.depth + 1; d <= $to.depth; d++) {\n let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n this.openFrontierNode(node.type, node.attrs, add);\n }\n return $to;\n }\n openFrontierNode(type, attrs = null, content) {\n let top = this.frontier[this.depth];\n top.match = top.match.matchType(type);\n this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n this.frontier.push({ type, match: type.contentMatch });\n }\n closeFrontierNode() {\n let open = this.frontier.pop();\n let add = open.match.fillBefore(Fragment.empty, true);\n if (add.childCount)\n this.placed = addToFragment(this.placed, this.frontier.length, add);\n }\n}\nfunction dropFromFragment(fragment, depth, count) {\n if (depth == 0)\n return fragment.cutByIndex(count, fragment.childCount);\n return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));\n}\nfunction addToFragment(fragment, depth, content) {\n if (depth == 0)\n return fragment.append(content);\n return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));\n}\nfunction contentAt(fragment, depth) {\n for (let i = 0; i < depth; i++)\n fragment = fragment.firstChild.content;\n return fragment;\n}\nfunction closeNodeStart(node, openStart, openEnd) {\n if (openStart <= 0)\n return node;\n let frag = node.content;\n if (openStart > 1)\n frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));\n if (openStart > 0) {\n frag = node.type.contentMatch.fillBefore(frag).append(frag);\n if (openEnd <= 0)\n frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));\n }\n return node.copy(frag);\n}\nfunction contentAfterFits($to, depth, type, match, open) {\n let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n if (index == node.childCount && !type.compatibleContent(node.type))\n return null;\n let fit = match.fillBefore(node.content, true, index);\n return fit && !invalidMarks(type, node.content, index) ? fit : null;\n}\nfunction invalidMarks(type, fragment, start) {\n for (let i = start; i < fragment.childCount; i++)\n if (!type.allowsMarks(fragment.child(i).marks))\n return true;\n return false;\n}\nfunction definesContent(type) {\n return type.spec.defining || type.spec.definingForContent;\n}\nfunction replaceRange(tr, from, to, slice) {\n if (!slice.size)\n return tr.deleteRange(from, to);\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n if (fitsTrivially($from, $to, slice))\n return tr.step(new ReplaceStep(from, to, slice));\n let targetDepths = coveredDepths($from, tr.doc.resolve(to));\n // Can't replace the whole document, so remove 0 if it's present\n if (targetDepths[targetDepths.length - 1] == 0)\n targetDepths.pop();\n // Negative numbers represent not expansion over the whole node at\n // that depth, but replacing from $from.before(-D) to $to.pos.\n let preferredTarget = -($from.depth + 1);\n targetDepths.unshift(preferredTarget);\n // This loop picks a preferred target depth, if one of the covering\n // depths is not outside of a defining node, and adds negative\n // depths for any depth that has $from at its start and does not\n // cross a defining node.\n for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n let spec = $from.node(d).type.spec;\n if (spec.defining || spec.definingAsContext || spec.isolating)\n break;\n if (targetDepths.indexOf(d) > -1)\n preferredTarget = d;\n else if ($from.before(d) == pos)\n targetDepths.splice(1, 0, -d);\n }\n // Try to fit each possible depth of the slice into each possible\n // target depth, starting with the preferred depths.\n let preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n let leftNodes = [], preferredDepth = slice.openStart;\n for (let content = slice.content, i = 0;; i++) {\n let node = content.firstChild;\n leftNodes.push(node);\n if (i == slice.openStart)\n break;\n content = node.content;\n }\n // Back up preferredDepth to cover defining textblocks directly\n // above it, possibly skipping a non-defining textblock.\n for (let d = preferredDepth - 1; d >= 0; d--) {\n let leftNode = leftNodes[d], def = definesContent(leftNode.type);\n if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))\n preferredDepth = d;\n else if (def || !leftNode.type.isTextblock)\n break;\n }\n for (let j = slice.openStart; j >= 0; j--) {\n let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n let insert = leftNodes[openDepth];\n if (!insert)\n continue;\n for (let i = 0; i < targetDepths.length; i++) {\n // Loop over possible expansion levels, starting with the\n // preferred one\n let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;\n if (targetDepth < 0) {\n expand = false;\n targetDepth = -targetDepth;\n }\n let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));\n }\n }\n let startSteps = tr.steps.length;\n for (let i = targetDepths.length - 1; i >= 0; i--) {\n tr.replace(from, to, slice);\n if (tr.steps.length > startSteps)\n break;\n let depth = targetDepths[i];\n if (depth < 0)\n continue;\n from = $from.before(depth);\n to = $to.after(depth);\n }\n}\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n if (depth < oldOpen) {\n let first = fragment.firstChild;\n fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n }\n if (depth > newOpen) {\n let match = parent.contentMatchAt(0);\n let start = match.fillBefore(fragment).append(fragment);\n fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n }\n return fragment;\n}\nfunction replaceRangeWith(tr, from, to, node) {\n if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {\n let point = insertPoint(tr.doc, from, node.type);\n if (point != null)\n from = to = point;\n }\n tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));\n}\nfunction deleteRange(tr, from, to) {\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n let covered = coveredDepths($from, $to);\n for (let i = 0; i < covered.length; i++) {\n let depth = covered[i], last = i == covered.length - 1;\n if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n return tr.delete($from.start(depth), $to.end(depth));\n if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))\n return tr.delete($from.before(depth), $to.after(depth));\n }\n for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {\n if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d &&\n $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))\n return tr.delete($from.before(d), to);\n }\n tr.delete(from, to);\n}\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n let result = [], minDepth = Math.min($from.depth, $to.depth);\n for (let d = minDepth; d >= 0; d--) {\n let start = $from.start(d);\n if (start < $from.pos - ($from.depth - d) ||\n $to.end(d) > $to.pos + ($to.depth - d) ||\n $from.node(d).type.spec.isolating ||\n $to.node(d).type.spec.isolating)\n break;\n if (start == $to.start(d) ||\n (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&\n d && $to.start(d - 1) == start - 1))\n result.push(d);\n }\n return result;\n}\n\n/**\nUpdate an attribute in a specific node.\n*/\nclass AttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.pos = pos;\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at attribute step's position\");\n let attrs = Object.create(null);\n for (let name in node.attrs)\n attrs[name] = node.attrs[name];\n attrs[this.attr] = this.value;\n let updated = node.type.create(attrs, null, node.marks);\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);\n }\n toJSON() {\n return { stepType: \"attr\", pos: this.pos, attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\" || typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for AttrStep.fromJSON\");\n return new AttrStep(json.pos, json.attr, json.value);\n }\n}\nStep.jsonID(\"attr\", AttrStep);\n/**\nUpdate an attribute in the doc node.\n*/\nclass DocAttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let attrs = Object.create(null);\n for (let name in doc.attrs)\n attrs[name] = doc.attrs[name];\n attrs[this.attr] = this.value;\n let updated = doc.type.create(attrs, doc.content, doc.marks);\n return StepResult.ok(updated);\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new DocAttrStep(this.attr, doc.attrs[this.attr]);\n }\n map(mapping) {\n return this;\n }\n toJSON() {\n return { stepType: \"docAttr\", attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for DocAttrStep.fromJSON\");\n return new DocAttrStep(json.attr, json.value);\n }\n}\nStep.jsonID(\"docAttr\", DocAttrStep);\n\n/**\n@internal\n*/\nlet TransformError = class extends Error {\n};\nTransformError = function TransformError(message) {\n let err = Error.call(this, message);\n err.__proto__ = TransformError.prototype;\n return err;\n};\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n/**\nAbstraction to build up and track an array of\n[steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.\n\nMost transforming methods return the `Transform` object itself, so\nthat they can be chained.\n*/\nclass Transform {\n /**\n Create a transform that starts with the given document.\n */\n constructor(\n /**\n The current document (the result of applying the steps in the\n transform).\n */\n doc) {\n this.doc = doc;\n /**\n The steps in this transform.\n */\n this.steps = [];\n /**\n The documents before each of the steps.\n */\n this.docs = [];\n /**\n A mapping with the maps for each of the steps in this transform.\n */\n this.mapping = new Mapping;\n }\n /**\n The starting document.\n */\n get before() { return this.docs.length ? this.docs[0] : this.doc; }\n /**\n Apply a new step in this transform, saving the result. Throws an\n error when the step fails.\n */\n step(step) {\n let result = this.maybeStep(step);\n if (result.failed)\n throw new TransformError(result.failed);\n return this;\n }\n /**\n Try to apply a step in this transformation, ignoring it if it\n fails. Returns the step result.\n */\n maybeStep(step) {\n let result = step.apply(this.doc);\n if (!result.failed)\n this.addStep(step, result.doc);\n return result;\n }\n /**\n True when the document has been changed (when there are any\n steps).\n */\n get docChanged() {\n return this.steps.length > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n this.docs.push(this.doc);\n this.steps.push(step);\n this.mapping.appendMap(step.getMap());\n this.doc = doc;\n }\n /**\n Replace the part of the document between `from` and `to` with the\n given `slice`.\n */\n replace(from, to = from, slice = Slice.empty) {\n let step = replaceStep(this.doc, from, to, slice);\n if (step)\n this.step(step);\n return this;\n }\n /**\n Replace the given range with the given content, which may be a\n fragment, node, or array of nodes.\n */\n replaceWith(from, to, content) {\n return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));\n }\n /**\n Delete the content between the given positions.\n */\n delete(from, to) {\n return this.replace(from, to, Slice.empty);\n }\n /**\n Insert the given content at the given position.\n */\n insert(pos, content) {\n return this.replaceWith(pos, pos, content);\n }\n /**\n Replace a range of the document with a given slice, using\n `from`, `to`, and the slice's\n [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather\n than fixed start and end points. This method may grow the\n replaced area or close open nodes in the slice in order to get a\n fit that is more in line with WYSIWYG expectations, by dropping\n fully covered parent nodes of the replaced region when they are\n marked [non-defining as\n context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an\n open parent node from the slice that _is_ marked as [defining\n its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n \n This is the method, for example, to handle paste. The similar\n [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more\n primitive tool which will _not_ move the start and end of its given\n range, and is useful in situations where you need more precise\n control over what happens.\n */\n replaceRange(from, to, slice) {\n replaceRange(this, from, to, slice);\n return this;\n }\n /**\n Replace the given range with a node, but use `from` and `to` as\n hints, rather than precise positions. When from and to are the same\n and are at the start or end of a parent node in which the given\n node doesn't fit, this method may _move_ them out towards a parent\n that does allow the given node to be placed. When the given range\n completely covers a parent node, this method may completely replace\n that parent node.\n */\n replaceRangeWith(from, to, node) {\n replaceRangeWith(this, from, to, node);\n return this;\n }\n /**\n Delete the given range, expanding it to cover fully covered\n parent nodes until a valid replace is found.\n */\n deleteRange(from, to) {\n deleteRange(this, from, to);\n return this;\n }\n /**\n Split the content in the given range off from its parent, if there\n is sibling content before or after it, and move it up the tree to\n the depth specified by `target`. You'll probably want to use\n [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make\n sure the lift is valid.\n */\n lift(range, target) {\n lift(this, range, target);\n return this;\n }\n /**\n Join the blocks around the given position. If depth is 2, their\n last and first siblings are also joined, and so on.\n */\n join(pos, depth = 1) {\n join(this, pos, depth);\n return this;\n }\n /**\n Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.\n The wrappers are assumed to be valid in this position, and should\n probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).\n */\n wrap(range, wrappers) {\n wrap(this, range, wrappers);\n return this;\n }\n /**\n Set the type of all textblocks (partly) between `from` and `to` to\n the given node type with the given attributes.\n */\n setBlockType(from, to = from, type, attrs = null) {\n setBlockType(this, from, to, type, attrs);\n return this;\n }\n /**\n Change the type, attributes, and/or marks of the node at `pos`.\n When `type` isn't given, the existing node type is preserved,\n */\n setNodeMarkup(pos, type, attrs = null, marks) {\n setNodeMarkup(this, pos, type, attrs, marks);\n return this;\n }\n /**\n Set a single attribute on a given node to a new value.\n The `pos` addresses the document content. Use `setDocAttribute`\n to set attributes on the document itself.\n */\n setNodeAttribute(pos, attr, value) {\n this.step(new AttrStep(pos, attr, value));\n return this;\n }\n /**\n Set a single attribute on the document to a new value.\n */\n setDocAttribute(attr, value) {\n this.step(new DocAttrStep(attr, value));\n return this;\n }\n /**\n Add a mark to the node at position `pos`.\n */\n addNodeMark(pos, mark) {\n this.step(new AddNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Remove a mark (or a mark of the given type) from the node at\n position `pos`.\n */\n removeNodeMark(pos, mark) {\n if (!(mark instanceof Mark)) {\n let node = this.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at position \" + pos);\n mark = mark.isInSet(node.marks);\n if (!mark)\n return this;\n }\n this.step(new RemoveNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Split the node at the given position, and optionally, if `depth` is\n greater than one, any number of nodes above that. By default, the\n parts split off will inherit the node type of the original node.\n This can be changed by passing an array of types and attributes to\n use after the split.\n */\n split(pos, depth = 1, typesAfter) {\n split(this, pos, depth, typesAfter);\n return this;\n }\n /**\n Add the given mark to the inline content between `from` and `to`.\n */\n addMark(from, to, mark) {\n addMark(this, from, to, mark);\n return this;\n }\n /**\n Remove marks from inline nodes between `from` and `to`. When\n `mark` is a single mark, remove precisely that mark. When it is\n a mark type, remove all marks of that type. When it is null,\n remove all marks of any type.\n */\n removeMark(from, to, mark) {\n removeMark(this, from, to, mark);\n return this;\n }\n /**\n Removes all marks and nodes from the content of the node at\n `pos` that don't match the given new parent node type. Accepts\n an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as\n third argument.\n */\n clearIncompatible(pos, parentType, match) {\n clearIncompatible(this, pos, parentType, match);\n return this;\n }\n}\n\nexport { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n","import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nconst classesById = Object.create(null);\n/**\nSuperclass for editor selections. Every selection type should\nextend this. Should not be instantiated directly.\n*/\nclass Selection {\n /**\n Initialize a selection with the head and anchor and ranges. If no\n ranges are given, constructs a single range across `$anchor` and\n `$head`.\n */\n constructor(\n /**\n The resolved anchor of the selection (the side that stays in\n place when the selection is modified).\n */\n $anchor, \n /**\n The resolved head of the selection (the side that moves when\n the selection is modified).\n */\n $head, ranges) {\n this.$anchor = $anchor;\n this.$head = $head;\n this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n }\n /**\n The selection's anchor, as an unresolved position.\n */\n get anchor() { return this.$anchor.pos; }\n /**\n The selection's head.\n */\n get head() { return this.$head.pos; }\n /**\n The lower bound of the selection's main range.\n */\n get from() { return this.$from.pos; }\n /**\n The upper bound of the selection's main range.\n */\n get to() { return this.$to.pos; }\n /**\n The resolved lower bound of the selection's main range.\n */\n get $from() {\n return this.ranges[0].$from;\n }\n /**\n The resolved upper bound of the selection's main range.\n */\n get $to() {\n return this.ranges[0].$to;\n }\n /**\n Indicates whether the selection contains any content.\n */\n get empty() {\n let ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++)\n if (ranges[i].$from.pos != ranges[i].$to.pos)\n return false;\n return true;\n }\n /**\n Get the content of this selection as a slice.\n */\n content() {\n return this.$from.doc.slice(this.from, this.to, true);\n }\n /**\n Replace the selection with a slice or, if no slice is given,\n delete the selection. Will append to the given transaction.\n */\n replace(tr, content = Slice.empty) {\n // Put the new selection at the position after the inserted\n // content. When that ended in an inline node, search backwards,\n // to get the position after that node. If not, search forward.\n let lastNode = content.content.lastChild, lastParent = null;\n for (let i = 0; i < content.openEnd; i++) {\n lastParent = lastNode;\n lastNode = lastNode.lastChild;\n }\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);\n if (i == 0)\n selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);\n }\n }\n /**\n Replace the selection with the given node, appending the changes\n to the given transaction.\n */\n replaceWith(tr, node) {\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n let from = mapping.map($from.pos), to = mapping.map($to.pos);\n if (i) {\n tr.deleteRange(from, to);\n }\n else {\n tr.replaceRangeWith(from, to, node);\n selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n }\n }\n }\n /**\n Find a valid cursor or leaf node selection starting at the given\n position and searching back if `dir` is negative, and forward if\n positive. When `textOnly` is true, only consider cursor\n selections. Will return null when no valid selection position is\n found.\n */\n static findFrom($pos, dir, textOnly = false) {\n let inner = $pos.parent.inlineContent ? new TextSelection($pos)\n : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n if (inner)\n return inner;\n for (let depth = $pos.depth - 1; depth >= 0; depth--) {\n let found = dir < 0\n ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)\n : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n if (found)\n return found;\n }\n return null;\n }\n /**\n Find a valid cursor or leaf node selection near the given\n position. Searches forward first by default, but if `bias` is\n negative, it will search backwards first.\n */\n static near($pos, bias = 1) {\n return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));\n }\n /**\n Find the cursor or leaf node selection closest to the start of\n the given document. Will return an\n [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position\n exists.\n */\n static atStart(doc) {\n return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);\n }\n /**\n Find the cursor or leaf node selection closest to the end of the\n given document.\n */\n static atEnd(doc) {\n return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);\n }\n /**\n Deserialize the JSON representation of a selection. Must be\n implemented for custom classes (as a static class method).\n */\n static fromJSON(doc, json) {\n if (!json || !json.type)\n throw new RangeError(\"Invalid input for Selection.fromJSON\");\n let cls = classesById[json.type];\n if (!cls)\n throw new RangeError(`No selection type ${json.type} defined`);\n return cls.fromJSON(doc, json);\n }\n /**\n To be able to deserialize selections from JSON, custom selection\n classes must register themselves with an ID string, so that they\n can be disambiguated. Try to pick something that's unlikely to\n clash with classes from other modules.\n */\n static jsonID(id, selectionClass) {\n if (id in classesById)\n throw new RangeError(\"Duplicate use of selection JSON ID \" + id);\n classesById[id] = selectionClass;\n selectionClass.prototype.jsonID = id;\n return selectionClass;\n }\n /**\n Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,\n which is a value that can be mapped without having access to a\n current document, and later resolved to a real selection for a\n given document again. (This is used mostly by the history to\n track and restore old selections.) The default implementation of\n this method just converts the selection to a text selection and\n returns the bookmark for that.\n */\n getBookmark() {\n return TextSelection.between(this.$anchor, this.$head).getBookmark();\n }\n}\nSelection.prototype.visible = true;\n/**\nRepresents a selected range in a document.\n*/\nclass SelectionRange {\n /**\n Create a range.\n */\n constructor(\n /**\n The lower bound of the range.\n */\n $from, \n /**\n The upper bound of the range.\n */\n $to) {\n this.$from = $from;\n this.$to = $to;\n }\n}\nlet warnedAboutTextSelection = false;\nfunction checkTextSelection($pos) {\n if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {\n warnedAboutTextSelection = true;\n console[\"warn\"](\"TextSelection endpoint not pointing into a node with inline content (\" + $pos.parent.type.name + \")\");\n }\n}\n/**\nA text selection represents a classical editor selection, with a\nhead (the moving side) and anchor (immobile side), both of which\npoint into textblock nodes. It can be empty (a regular cursor\nposition).\n*/\nclass TextSelection extends Selection {\n /**\n Construct a text selection between the given points.\n */\n constructor($anchor, $head = $anchor) {\n checkTextSelection($anchor);\n checkTextSelection($head);\n super($anchor, $head);\n }\n /**\n Returns a resolved position if this is a cursor selection (an\n empty text selection), and null otherwise.\n */\n get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }\n map(doc, mapping) {\n let $head = doc.resolve(mapping.map(this.head));\n if (!$head.parent.inlineContent)\n return Selection.near($head);\n let $anchor = doc.resolve(mapping.map(this.anchor));\n return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);\n }\n replace(tr, content = Slice.empty) {\n super.replace(tr, content);\n if (content == Slice.empty) {\n let marks = this.$from.marksAcross(this.$to);\n if (marks)\n tr.ensureMarks(marks);\n }\n }\n eq(other) {\n return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;\n }\n getBookmark() {\n return new TextBookmark(this.anchor, this.head);\n }\n toJSON() {\n return { type: \"text\", anchor: this.anchor, head: this.head };\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\" || typeof json.head != \"number\")\n throw new RangeError(\"Invalid input for TextSelection.fromJSON\");\n return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n }\n /**\n Create a text selection from non-resolved positions.\n */\n static create(doc, anchor, head = anchor) {\n let $anchor = doc.resolve(anchor);\n return new this($anchor, head == anchor ? $anchor : doc.resolve(head));\n }\n /**\n Return a text selection that spans the given positions or, if\n they aren't text positions, find a text selection near them.\n `bias` determines whether the method searches forward (default)\n or backwards (negative number) first. Will fall back to calling\n [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document\n doesn't contain a valid text position.\n */\n static between($anchor, $head, bias) {\n let dPos = $anchor.pos - $head.pos;\n if (!bias || dPos)\n bias = dPos >= 0 ? 1 : -1;\n if (!$head.parent.inlineContent) {\n let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n if (found)\n $head = found.$head;\n else\n return Selection.near($head, bias);\n }\n if (!$anchor.parent.inlineContent) {\n if (dPos == 0) {\n $anchor = $head;\n }\n else {\n $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n if (($anchor.pos < $head.pos) != (dPos < 0))\n $anchor = $head;\n }\n }\n return new TextSelection($anchor, $head);\n }\n}\nSelection.jsonID(\"text\", TextSelection);\nclass TextBookmark {\n constructor(anchor, head) {\n this.anchor = anchor;\n this.head = head;\n }\n map(mapping) {\n return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));\n }\n resolve(doc) {\n return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));\n }\n}\n/**\nA node selection is a selection that points at a single node. All\nnodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the\ntarget of a node selection. In such a selection, `from` and `to`\npoint directly before and after the selected node, `anchor` equals\n`from`, and `head` equals `to`..\n*/\nclass NodeSelection extends Selection {\n /**\n Create a node selection. Does not verify the validity of its\n argument.\n */\n constructor($pos) {\n let node = $pos.nodeAfter;\n let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n super($pos, $end);\n this.node = node;\n }\n map(doc, mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n let $pos = doc.resolve(pos);\n if (deleted)\n return Selection.near($pos);\n return new NodeSelection($pos);\n }\n content() {\n return new Slice(Fragment.from(this.node), 0, 0);\n }\n eq(other) {\n return other instanceof NodeSelection && other.anchor == this.anchor;\n }\n toJSON() {\n return { type: \"node\", anchor: this.anchor };\n }\n getBookmark() { return new NodeBookmark(this.anchor); }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\")\n throw new RangeError(\"Invalid input for NodeSelection.fromJSON\");\n return new NodeSelection(doc.resolve(json.anchor));\n }\n /**\n Create a node selection from non-resolved positions.\n */\n static create(doc, from) {\n return new NodeSelection(doc.resolve(from));\n }\n /**\n Determines whether the given node may be selected as a node\n selection.\n */\n static isSelectable(node) {\n return !node.isText && node.type.spec.selectable !== false;\n }\n}\nNodeSelection.prototype.visible = false;\nSelection.jsonID(\"node\", NodeSelection);\nclass NodeBookmark {\n constructor(anchor) {\n this.anchor = anchor;\n }\n map(mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);\n }\n resolve(doc) {\n let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n if (node && NodeSelection.isSelectable(node))\n return new NodeSelection($pos);\n return Selection.near($pos);\n }\n}\n/**\nA selection type that represents selecting the whole document\n(which can not necessarily be expressed with a text selection, when\nthere are for example leaf block nodes at the start or end of the\ndocument).\n*/\nclass AllSelection extends Selection {\n /**\n Create an all-selection over the given document.\n */\n constructor(doc) {\n super(doc.resolve(0), doc.resolve(doc.content.size));\n }\n replace(tr, content = Slice.empty) {\n if (content == Slice.empty) {\n tr.delete(0, tr.doc.content.size);\n let sel = Selection.atStart(tr.doc);\n if (!sel.eq(tr.selection))\n tr.setSelection(sel);\n }\n else {\n super.replace(tr, content);\n }\n }\n toJSON() { return { type: \"all\" }; }\n /**\n @internal\n */\n static fromJSON(doc) { return new AllSelection(doc); }\n map(doc) { return new AllSelection(doc); }\n eq(other) { return other instanceof AllSelection; }\n getBookmark() { return AllBookmark; }\n}\nSelection.jsonID(\"all\", AllSelection);\nconst AllBookmark = {\n map() { return this; },\n resolve(doc) { return new AllSelection(doc); }\n};\n// FIXME we'll need some awareness of text direction when scanning for selections\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text = false) {\n if (node.inlineContent)\n return TextSelection.create(doc, pos);\n for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n let child = node.child(i);\n if (!child.isAtom) {\n let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n if (inner)\n return inner;\n }\n else if (!text && NodeSelection.isSelectable(child)) {\n return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));\n }\n pos += child.nodeSize * dir;\n }\n return null;\n}\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n let last = tr.steps.length - 1;\n if (last < startLen)\n return;\n let step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))\n return;\n let map = tr.mapping.maps[last], end;\n map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)\n end = newTo; });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nconst UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n/**\nAn editor state transaction, which can be applied to a state to\ncreate an updated state. Use\n[`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.\n\nTransactions track changes to the document (they are a subclass of\n[`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,\nlike selection updates and adjustments of the set of [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store\nmetadata properties in a transaction, which are extra pieces of\ninformation that client code or plugins can use to describe what a\ntransaction represents, so that they can update their [own\nstate](https://prosemirror.net/docs/ref/#state.StateField) accordingly.\n\nThe [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata\nproperties: it will attach a property `\"pointer\"` with the value\n`true` to selection transactions directly caused by mouse or touch\ninput, a `\"composition\"` property holding an ID identifying the\ncomposition that caused it to transactions caused by composed DOM\ninput, and a `\"uiEvent\"` property of that may be `\"paste\"`,\n`\"cut\"`, or `\"drop\"`.\n*/\nclass Transaction extends Transform {\n /**\n @internal\n */\n constructor(state) {\n super(state.doc);\n // The step count for which the current selection is valid.\n this.curSelectionFor = 0;\n // Bitfield to track which aspects of the state were updated by\n // this transaction.\n this.updated = 0;\n // Object used to store metadata properties for the transaction.\n this.meta = Object.create(null);\n this.time = Date.now();\n this.curSelection = state.selection;\n this.storedMarks = state.storedMarks;\n }\n /**\n The transaction's current selection. This defaults to the editor\n selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the\n transaction, but can be overwritten with\n [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).\n */\n get selection() {\n if (this.curSelectionFor < this.steps.length) {\n this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n this.curSelectionFor = this.steps.length;\n }\n return this.curSelection;\n }\n /**\n Update the transaction's current selection. Will determine the\n selection that the editor gets when the transaction is applied.\n */\n setSelection(selection) {\n if (selection.$from.doc != this.doc)\n throw new RangeError(\"Selection passed to setSelection must point at the current document\");\n this.curSelection = selection;\n this.curSelectionFor = this.steps.length;\n this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n this.storedMarks = null;\n return this;\n }\n /**\n Whether the selection was explicitly updated by this transaction.\n */\n get selectionSet() {\n return (this.updated & UPDATED_SEL) > 0;\n }\n /**\n Set the current stored marks.\n */\n setStoredMarks(marks) {\n this.storedMarks = marks;\n this.updated |= UPDATED_MARKS;\n return this;\n }\n /**\n Make sure the current stored marks or, if that is null, the marks\n at the selection, match the given set of marks. Does nothing if\n this is already the case.\n */\n ensureMarks(marks) {\n if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n this.setStoredMarks(marks);\n return this;\n }\n /**\n Add a mark to the set of stored marks.\n */\n addStoredMark(mark) {\n return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Remove a mark or mark type from the set of stored marks.\n */\n removeStoredMark(mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Whether the stored marks were explicitly set for this transaction.\n */\n get storedMarksSet() {\n return (this.updated & UPDATED_MARKS) > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n super.addStep(step, doc);\n this.updated = this.updated & ~UPDATED_MARKS;\n this.storedMarks = null;\n }\n /**\n Update the timestamp for the transaction.\n */\n setTime(time) {\n this.time = time;\n return this;\n }\n /**\n Replace the current selection with the given slice.\n */\n replaceSelection(slice) {\n this.selection.replace(this, slice);\n return this;\n }\n /**\n Replace the selection with the given node. When `inheritMarks` is\n true and the content is inline, it inherits the marks from the\n place where it is inserted.\n */\n replaceSelectionWith(node, inheritMarks = true) {\n let selection = this.selection;\n if (inheritMarks)\n node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none)));\n selection.replaceWith(this, node);\n return this;\n }\n /**\n Delete the selection.\n */\n deleteSelection() {\n this.selection.replace(this);\n return this;\n }\n /**\n Replace the given range, or the selection if no range is given,\n with a text node containing the given string.\n */\n insertText(text, from, to) {\n let schema = this.doc.type.schema;\n if (from == null) {\n if (!text)\n return this.deleteSelection();\n return this.replaceSelectionWith(schema.text(text), true);\n }\n else {\n if (to == null)\n to = from;\n to = to == null ? from : to;\n if (!text)\n return this.deleteRange(from, to);\n let marks = this.storedMarks;\n if (!marks) {\n let $from = this.doc.resolve(from);\n marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n }\n this.replaceRangeWith(from, to, schema.text(text, marks));\n if (!this.selection.empty)\n this.setSelection(Selection.near(this.selection.$to));\n return this;\n }\n }\n /**\n Store a metadata property in this transaction, keyed either by\n name or by plugin.\n */\n setMeta(key, value) {\n this.meta[typeof key == \"string\" ? key : key.key] = value;\n return this;\n }\n /**\n Retrieve a metadata property for a given name or plugin.\n */\n getMeta(key) {\n return this.meta[typeof key == \"string\" ? key : key.key];\n }\n /**\n Returns true if this transaction doesn't contain any metadata,\n and can thus safely be extended.\n */\n get isGeneric() {\n for (let _ in this.meta)\n return false;\n return true;\n }\n /**\n Indicate that the editor should scroll the selection into view\n when updated to the state produced by this transaction.\n */\n scrollIntoView() {\n this.updated |= UPDATED_SCROLL;\n return this;\n }\n /**\n True when this transaction has had `scrollIntoView` called on it.\n */\n get scrolledIntoView() {\n return (this.updated & UPDATED_SCROLL) > 0;\n }\n}\n\nfunction bind(f, self) {\n return !self || !f ? f : f.bind(self);\n}\nclass FieldDesc {\n constructor(name, desc, self) {\n this.name = name;\n this.init = bind(desc.init, self);\n this.apply = bind(desc.apply, self);\n }\n}\nconst baseFields = [\n new FieldDesc(\"doc\", {\n init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },\n apply(tr) { return tr.doc; }\n }),\n new FieldDesc(\"selection\", {\n init(config, instance) { return config.selection || Selection.atStart(instance.doc); },\n apply(tr) { return tr.selection; }\n }),\n new FieldDesc(\"storedMarks\", {\n init(config) { return config.storedMarks || null; },\n apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }\n }),\n new FieldDesc(\"scrollToSelection\", {\n init() { return 0; },\n apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }\n })\n];\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nclass Configuration {\n constructor(schema, plugins) {\n this.schema = schema;\n this.plugins = [];\n this.pluginsByKey = Object.create(null);\n this.fields = baseFields.slice();\n if (plugins)\n plugins.forEach(plugin => {\n if (this.pluginsByKey[plugin.key])\n throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\");\n this.plugins.push(plugin);\n this.pluginsByKey[plugin.key] = plugin;\n if (plugin.spec.state)\n this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));\n });\n }\n}\n/**\nThe state of a ProseMirror editor is represented by an object of\nthis type. A state is a persistent data structure—it isn't\nupdated, but rather a new state value is computed from an old one\nusing the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.\n\nA state holds a number of built-in fields, and plugins can\n[define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.\n*/\nclass EditorState {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n config) {\n this.config = config;\n }\n /**\n The schema of the state's document.\n */\n get schema() {\n return this.config.schema;\n }\n /**\n The plugins that are active in this state.\n */\n get plugins() {\n return this.config.plugins;\n }\n /**\n Apply the given transaction to produce a new state.\n */\n apply(tr) {\n return this.applyTransaction(tr).state;\n }\n /**\n @internal\n */\n filterTransaction(tr, ignore = -1) {\n for (let i = 0; i < this.config.plugins.length; i++)\n if (i != ignore) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))\n return false;\n }\n return true;\n }\n /**\n Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that\n returns the precise transactions that were applied (which might\n be influenced by the [transaction\n hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of\n plugins) along with the new state.\n */\n applyTransaction(rootTr) {\n if (!this.filterTransaction(rootTr))\n return { state: this, transactions: [] };\n let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;\n // This loop repeatedly gives plugins a chance to respond to\n // transactions as new transactions are added, making sure to only\n // pass the transactions the plugin did not see before.\n for (;;) {\n let haveNew = false;\n for (let i = 0; i < this.config.plugins.length; i++) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.appendTransaction) {\n let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n let tr = n < trs.length &&\n plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n if (tr && newState.filterTransaction(tr, i)) {\n tr.setMeta(\"appendedTransaction\", rootTr);\n if (!seen) {\n seen = [];\n for (let j = 0; j < this.config.plugins.length; j++)\n seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });\n }\n trs.push(tr);\n newState = newState.applyInner(tr);\n haveNew = true;\n }\n if (seen)\n seen[i] = { state: newState, n: trs.length };\n }\n }\n if (!haveNew)\n return { state: newState, transactions: trs };\n }\n }\n /**\n @internal\n */\n applyInner(tr) {\n if (!tr.before.eq(this.doc))\n throw new RangeError(\"Applying a mismatched transaction\");\n let newInstance = new EditorState(this.config), fields = this.config.fields;\n for (let i = 0; i < fields.length; i++) {\n let field = fields[i];\n newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n }\n return newInstance;\n }\n /**\n Start a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.\n */\n get tr() { return new Transaction(this); }\n /**\n Create a new state.\n */\n static create(config) {\n let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);\n let instance = new EditorState($config);\n for (let i = 0; i < $config.fields.length; i++)\n instance[$config.fields[i].name] = $config.fields[i].init(config, instance);\n return instance;\n }\n /**\n Create a new state based on this one, but with an adjusted set\n of active plugins. State fields that exist in both sets of\n plugins are kept unchanged. Those that no longer exist are\n dropped, and those that are new are initialized using their\n [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new\n configuration object..\n */\n reconfigure(config) {\n let $config = new Configuration(this.schema, config.plugins);\n let fields = $config.fields, instance = new EditorState($config);\n for (let i = 0; i < fields.length; i++) {\n let name = fields[i].name;\n instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n }\n return instance;\n }\n /**\n Serialize this state to JSON. If you want to serialize the state\n of plugins, pass an object mapping property names to use in the\n resulting JSON object to plugin objects. The argument may also be\n a string or number, in which case it is ignored, to support the\n way `JSON.stringify` calls `toString` methods.\n */\n toJSON(pluginFields) {\n let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };\n if (this.storedMarks)\n result.storedMarks = this.storedMarks.map(m => m.toJSON());\n if (pluginFields && typeof pluginFields == 'object')\n for (let prop in pluginFields) {\n if (prop == \"doc\" || prop == \"selection\")\n throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\");\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (state && state.toJSON)\n result[prop] = state.toJSON.call(plugin, this[plugin.key]);\n }\n return result;\n }\n /**\n Deserialize a JSON representation of a state. `config` should\n have at least a `schema` field, and should contain array of\n plugins to initialize the state with. `pluginFields` can be used\n to deserialize the state of plugins, by associating plugin\n instances with the property names they use in the JSON object.\n */\n static fromJSON(config, json, pluginFields) {\n if (!json)\n throw new RangeError(\"Invalid input for EditorState.fromJSON\");\n if (!config.schema)\n throw new RangeError(\"Required config field 'schema' missing\");\n let $config = new Configuration(config.schema, config.plugins);\n let instance = new EditorState($config);\n $config.fields.forEach(field => {\n if (field.name == \"doc\") {\n instance.doc = Node.fromJSON(config.schema, json.doc);\n }\n else if (field.name == \"selection\") {\n instance.selection = Selection.fromJSON(instance.doc, json.selection);\n }\n else if (field.name == \"storedMarks\") {\n if (json.storedMarks)\n instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);\n }\n else {\n if (pluginFields)\n for (let prop in pluginFields) {\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (plugin.key == field.name && state && state.fromJSON &&\n Object.prototype.hasOwnProperty.call(json, prop)) {\n instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n return;\n }\n }\n instance[field.name] = field.init(config, instance);\n }\n });\n return instance;\n }\n}\n\nfunction bindProps(obj, self, target) {\n for (let prop in obj) {\n let val = obj[prop];\n if (val instanceof Function)\n val = val.bind(self);\n else if (prop == \"handleDOMEvents\")\n val = bindProps(val, self, {});\n target[prop] = val;\n }\n return target;\n}\n/**\nPlugins bundle functionality that can be added to an editor.\nThey are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and\nmay influence that state and the view that contains it.\n*/\nclass Plugin {\n /**\n Create a plugin.\n */\n constructor(\n /**\n The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).\n */\n spec) {\n this.spec = spec;\n /**\n The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.\n */\n this.props = {};\n if (spec.props)\n bindProps(spec.props, this, this.props);\n this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n }\n /**\n Extract the plugin's state field from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\nconst keys = Object.create(null);\nfunction createKey(name) {\n if (name in keys)\n return name + \"$\" + ++keys[name];\n keys[name] = 0;\n return name + \"$\";\n}\n/**\nA key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way\nthat makes it possible to find them, given an editor state.\nAssigning a key does mean only one plugin of that type can be\nactive in a state.\n*/\nclass PluginKey {\n /**\n Create a plugin key.\n */\n constructor(name = \"key\") { this.key = createKey(name); }\n /**\n Get the active plugin with this key, if any, from an editor\n state.\n */\n get(state) { return state.config.pluginsByKey[this.key]; }\n /**\n Get the plugin's state from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n","import { keyName, base } from 'w3c-keyname';\nimport { Plugin } from 'prosemirror-state';\n\nconst mac = typeof navigator != \"undefined\" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : false;\nfunction normalizeKeyName(name) {\n let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];\n if (result == \"Space\")\n result = \" \";\n let alt, ctrl, shift, meta;\n for (let i = 0; i < parts.length - 1; i++) {\n let mod = parts[i];\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 (mac)\n meta = true;\n else\n ctrl = true;\n }\n else\n throw new Error(\"Unrecognized modifier name: \" + mod);\n }\n if (alt)\n result = \"Alt-\" + result;\n if (ctrl)\n result = \"Ctrl-\" + result;\n if (meta)\n result = \"Meta-\" + result;\n if (shift)\n result = \"Shift-\" + result;\n return result;\n}\nfunction normalize(map) {\n let copy = Object.create(null);\n for (let prop in map)\n copy[normalizeKeyName(prop)] = map[prop];\n return copy;\n}\nfunction modifiers(name, event, shift = true) {\n if (event.altKey)\n name = \"Alt-\" + name;\n if (event.ctrlKey)\n name = \"Ctrl-\" + name;\n if (event.metaKey)\n name = \"Meta-\" + name;\n if (shift && event.shiftKey)\n name = \"Shift-\" + name;\n return name;\n}\n/**\nCreate a keymap plugin for the given set of bindings.\n\nBindings should map key names to [command](https://prosemirror.net/docs/ref/#commands)-style\nfunctions, which will be called with `(EditorState, dispatch,\nEditorView)` arguments, and should return true when they've handled\nthe key. Note that the view argument isn't part of the command\nprotocol, but can be used as an escape hatch if a binding needs to\ndirectly interact with the UI.\n\nKey names may be strings like `\"Shift-Ctrl-Enter\"`—a key\nidentifier prefixed with zero or more modifiers. Key identifiers\nare based on the strings that can appear in\n[`KeyEvent.key`](https:developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key).\nUse lowercase letters to refer to letter keys (or uppercase letters\nif you want shift to be held). You may use `\"Space\"` as an alias\nfor the `\" \"` name.\n\nModifiers can be given in any order. `Shift-` (or `s-`), `Alt-` (or\n`a-`), `Ctrl-` (or `c-` or `Control-`) and `Cmd-` (or `m-` or\n`Meta-`) are recognized. For characters that are created by holding\nshift, the `Shift-` prefix is implied, and should not be added\nexplicitly.\n\nYou can use `Mod-` as a shorthand for `Cmd-` on Mac and `Ctrl-` on\nother platforms.\n\nYou can add multiple keymap plugins to an editor. The order in\nwhich they appear determines their precedence (the ones early in\nthe array get to dispatch first).\n*/\nfunction keymap(bindings) {\n return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });\n}\n/**\nGiven a set of bindings (using the same format as\n[`keymap`](https://prosemirror.net/docs/ref/#keymap.keymap)), return a [keydown\nhandler](https://prosemirror.net/docs/ref/#view.EditorProps.handleKeyDown) that handles them.\n*/\nfunction keydownHandler(bindings) {\n let map = normalize(bindings);\n return function (view, event) {\n let name = keyName(event), baseName, direct = map[modifiers(name, event)];\n if (direct && direct(view.state, view.dispatch, view))\n return true;\n // A character key\n if (name.length == 1 && name != \" \") {\n if (event.shiftKey) {\n // In case the name was already modified by shift, try looking\n // it up without its shift modifier\n let noShift = map[modifiers(name, event, false)];\n if (noShift && noShift(view.state, view.dispatch, view))\n return true;\n }\n if ((event.shiftKey || event.altKey || event.metaKey || name.charCodeAt(0) > 127) &&\n (baseName = base[event.keyCode]) && baseName != name) {\n // Try falling back to the keyCode when there's a modifier\n // active or the character produced isn't ASCII, and our table\n // produces a different name from the the keyCode. See #668,\n // #1060\n let fromCode = map[modifiers(baseName, event)];\n if (fromCode && fromCode(view.state, view.dispatch, view))\n return true;\n }\n }\n return false;\n };\n}\n\nexport { keydownHandler, keymap };\n","import { liftTarget, replaceStep, ReplaceStep, canJoin, joinPoint, canSplit, ReplaceAroundStep, findWrapping } from 'prosemirror-transform';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { NodeSelection, Selection, TextSelection, AllSelection, SelectionRange } from 'prosemirror-state';\n\n/**\nDelete the selection, if there is one.\n*/\nconst deleteSelection = (state, dispatch) => {\n if (state.selection.empty)\n return false;\n if (dispatch)\n dispatch(state.tr.deleteSelection().scrollIntoView());\n return true;\n};\nfunction atBlockStart(state, view) {\n let { $cursor } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"backward\", state)\n : $cursor.parentOffset > 0))\n return null;\n return $cursor;\n}\n/**\nIf the selection is empty and at the start of a textblock, try to\nreduce the distance between that block and the one before it—if\nthere's a block directly before it that can be joined, join them.\nIf not, try to move the selected block closer to the next one in\nthe document structure by lifting it out of its parent or moving it\ninto a parent of the previous block. Will use the view for accurate\n(bidi-aware) start-of-textblock detection if given.\n*/\nconst joinBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutBefore($cursor);\n // If there is no node before this, try to lift\n if (!$cut) {\n let range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n let before = $cut.nodeBefore;\n // Apply the joining algorithm\n if (deleteBarrier(state, $cut, dispatch, -1))\n return true;\n // If the node below has no content and the node above is\n // selectable, delete the node below and select the one above.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(before, \"end\") || NodeSelection.isSelectable(before))) {\n for (let depth = $cursor.depth;; depth--) {\n let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(before, \"end\")\n ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1)\n : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n if (depth == 1 || $cursor.node(depth - 1).childCount > 1)\n break;\n }\n }\n // If the node before is an atom, delete it\n if (before.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch)\n dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nA more limited form of [`joinBackward`]($commands.joinBackward)\nthat only tries to join the current textblock to the one before\nit, if the cursor is at the start of a textblock.\n*/\nconst joinTextblockBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutBefore($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\n/**\nA more limited form of [`joinForward`]($commands.joinForward)\nthat only tries to join the current textblock to the one after\nit, if the cursor is at the end of a textblock.\n*/\nconst joinTextblockForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutAfter($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\nfunction joinTextblocksAround(state, $cut, dispatch) {\n let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1;\n for (; !beforeText.isTextblock; beforePos--) {\n if (beforeText.type.spec.isolating)\n return false;\n let child = beforeText.lastChild;\n if (!child)\n return false;\n beforeText = child;\n }\n let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1;\n for (; !afterText.isTextblock; afterPos++) {\n if (afterText.type.spec.isolating)\n return false;\n let child = afterText.firstChild;\n if (!child)\n return false;\n afterText = child;\n }\n let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);\n if (!step || step.from != beforePos ||\n step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)\n return false;\n if (dispatch) {\n let tr = state.tr.step(step);\n tr.setSelection(TextSelection.create(tr.doc, beforePos));\n dispatch(tr.scrollIntoView());\n }\n return true;\n}\nfunction textblockAt(node, side, only = false) {\n for (let scan = node; scan; scan = (side == \"start\" ? scan.firstChild : scan.lastChild)) {\n if (scan.isTextblock)\n return true;\n if (only && scan.childCount != 1)\n return false;\n }\n return false;\n}\n/**\nWhen the selection is empty and at the start of a textblock, select\nthe node before that textblock, if possible. This is intended to be\nbound to keys like backspace, after\n[`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward) or other deleting\ncommands, as a fall-back behavior when the schema doesn't allow\ndeletion at the selected point.\n*/\nconst selectNodeBackward = (state, dispatch, view) => {\n let { $head, empty } = state.selection, $cut = $head;\n if (!empty)\n return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"backward\", state) : $head.parentOffset > 0)\n return false;\n $cut = findCutBefore($head);\n }\n let node = $cut && $cut.nodeBefore;\n if (!node || !NodeSelection.isSelectable(node))\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());\n return true;\n};\nfunction findCutBefore($pos) {\n if (!$pos.parent.type.spec.isolating)\n for (let i = $pos.depth - 1; i >= 0; i--) {\n if ($pos.index(i) > 0)\n return $pos.doc.resolve($pos.before(i + 1));\n if ($pos.node(i).type.spec.isolating)\n break;\n }\n return null;\n}\nfunction atBlockEnd(state, view) {\n let { $cursor } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"forward\", state)\n : $cursor.parentOffset < $cursor.parent.content.size))\n return null;\n return $cursor;\n}\n/**\nIf the selection is empty and the cursor is at the end of a\ntextblock, try to reduce or remove the boundary between that block\nand the one after it, either by joining them or by moving the other\nblock closer to this one in the tree structure. Will use the view\nfor accurate start-of-textblock detection if given.\n*/\nconst joinForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutAfter($cursor);\n // If there is no node after this, there's nothing to do\n if (!$cut)\n return false;\n let after = $cut.nodeAfter;\n // Try the joining algorithm\n if (deleteBarrier(state, $cut, dispatch, 1))\n return true;\n // If the node above has no content and the node below is\n // selectable, delete the node above and select the one below.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(after, \"start\") || NodeSelection.isSelectable(after))) {\n let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(after, \"start\") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1)\n : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n // If the next node is an atom, delete it\n if (after.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch)\n dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nWhen the selection is empty and at the end of a textblock, select\nthe node coming after that textblock, if possible. This is intended\nto be bound to keys like delete, after\n[`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward) and similar deleting\ncommands, to provide a fall-back behavior when the schema doesn't\nallow deletion at the selected point.\n*/\nconst selectNodeForward = (state, dispatch, view) => {\n let { $head, empty } = state.selection, $cut = $head;\n if (!empty)\n return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"forward\", state) : $head.parentOffset < $head.parent.content.size)\n return false;\n $cut = findCutAfter($head);\n }\n let node = $cut && $cut.nodeAfter;\n if (!node || !NodeSelection.isSelectable(node))\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());\n return true;\n};\nfunction findCutAfter($pos) {\n if (!$pos.parent.type.spec.isolating)\n for (let i = $pos.depth - 1; i >= 0; i--) {\n let parent = $pos.node(i);\n if ($pos.index(i) + 1 < parent.childCount)\n return $pos.doc.resolve($pos.after(i + 1));\n if (parent.type.spec.isolating)\n break;\n }\n return null;\n}\n/**\nJoin the selected block or, if there is a text selection, the\nclosest ancestor block of the selection that can be joined, with\nthe sibling above it.\n*/\nconst joinUp = (state, dispatch) => {\n let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;\n if (nodeSel) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.from))\n return false;\n point = sel.from;\n }\n else {\n point = joinPoint(state.doc, sel.from, -1);\n if (point == null)\n return false;\n }\n if (dispatch) {\n let tr = state.tr.join(point);\n if (nodeSel)\n tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nJoin the selected block, or the closest ancestor of the selection\nthat can be joined, with the sibling after it.\n*/\nconst joinDown = (state, dispatch) => {\n let sel = state.selection, point;\n if (sel instanceof NodeSelection) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.to))\n return false;\n point = sel.to;\n }\n else {\n point = joinPoint(state.doc, sel.to, 1);\n if (point == null)\n return false;\n }\n if (dispatch)\n dispatch(state.tr.join(point).scrollIntoView());\n return true;\n};\n/**\nLift the selected block, or the closest ancestor block of the\nselection that can be lifted, out of its parent node.\n*/\nconst lift = (state, dispatch) => {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nIf the selection is in a node whose type has a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, replace the\nselection with a newline character.\n*/\nconst newlineInCode = (state, dispatch) => {\n let { $head, $anchor } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n return false;\n if (dispatch)\n dispatch(state.tr.insertText(\"\\n\").scrollIntoView());\n return true;\n};\nfunction defaultBlockAt(match) {\n for (let i = 0; i < match.edgeCount; i++) {\n let { type } = match.edge(i);\n if (type.isTextblock && !type.hasRequiredAttrs())\n return type;\n }\n return null;\n}\n/**\nWhen the selection is in a node with a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, create a\ndefault block after the code block, and move the cursor there.\n*/\nconst exitCode = (state, dispatch) => {\n let { $head, $anchor } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n return false;\n let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));\n if (!type || !above.canReplaceWith(after, after, type))\n return false;\n if (dispatch) {\n let pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill());\n tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf a block node is selected, create an empty paragraph before (if\nit is its parent's first child) or after it.\n*/\nconst createParagraphNear = (state, dispatch) => {\n let sel = state.selection, { $from, $to } = sel;\n if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)\n return false;\n let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));\n if (!type || !type.isTextblock)\n return false;\n if (dispatch) {\n let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;\n let tr = state.tr.insert(side, type.createAndFill());\n tr.setSelection(TextSelection.create(tr.doc, side + 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf the cursor is in an empty textblock that can be lifted, lift the\nblock.\n*/\nconst liftEmptyBlock = (state, dispatch) => {\n let { $cursor } = state.selection;\n if (!$cursor || $cursor.parent.content.size)\n return false;\n if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {\n let before = $cursor.before();\n if (canSplit(state.doc, before)) {\n if (dispatch)\n dispatch(state.tr.split(before).scrollIntoView());\n return true;\n }\n }\n let range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nCreate a variant of [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock) that uses\na custom function to determine the type of the newly split off block.\n*/\nfunction splitBlockAs(splitNode) {\n return (state, dispatch) => {\n let { $from, $to } = state.selection;\n if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {\n if (!$from.parentOffset || !canSplit(state.doc, $from.pos))\n return false;\n if (dispatch)\n dispatch(state.tr.split($from.pos).scrollIntoView());\n return true;\n }\n if (!$from.depth)\n return false;\n let types = [];\n let splitDepth, deflt, atEnd = false, atStart = false;\n for (let d = $from.depth;; d--) {\n let node = $from.node(d);\n if (node.isBlock) {\n atEnd = $from.end(d) == $from.pos + ($from.depth - d);\n atStart = $from.start(d) == $from.pos - ($from.depth - d);\n deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1)));\n let splitType = splitNode && splitNode($to.parent, atEnd, $from);\n types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null));\n splitDepth = d;\n break;\n }\n else {\n if (d == 1)\n return false;\n types.unshift(null);\n }\n }\n let tr = state.tr;\n if (state.selection instanceof TextSelection || state.selection instanceof AllSelection)\n tr.deleteSelection();\n let splitPos = tr.mapping.map($from.pos);\n let can = canSplit(tr.doc, splitPos, types.length, types);\n if (!can) {\n types[0] = deflt ? { type: deflt } : null;\n can = canSplit(tr.doc, splitPos, types.length, types);\n }\n tr.split(splitPos, types.length, types);\n if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {\n let first = tr.mapping.map($from.before(splitDepth)), $first = tr.doc.resolve(first);\n if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))\n tr.setNodeMarkup(tr.mapping.map($from.before(splitDepth)), deflt);\n }\n if (dispatch)\n dispatch(tr.scrollIntoView());\n return true;\n };\n}\n/**\nSplit the parent block of the selection. If the selection is a text\nselection, also delete its content.\n*/\nconst splitBlock = splitBlockAs();\n/**\nActs like [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock), but without\nresetting the set of active marks at the cursor.\n*/\nconst splitBlockKeepMarks = (state, dispatch) => {\n return splitBlock(state, dispatch && (tr => {\n let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n if (marks)\n tr.ensureMarks(marks);\n dispatch(tr);\n }));\n};\n/**\nMove the selection to the node wrapping the current selection, if\nany. (Will not select the document node.)\n*/\nconst selectParentNode = (state, dispatch) => {\n let { $from, to } = state.selection, pos;\n let same = $from.sharedDepth(to);\n if (same == 0)\n return false;\n pos = $from.before(same);\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));\n return true;\n};\n/**\nSelect the whole document.\n*/\nconst selectAll = (state, dispatch) => {\n if (dispatch)\n dispatch(state.tr.setSelection(new AllSelection(state.doc)));\n return true;\n};\nfunction joinMaybeClear(state, $pos, dispatch) {\n let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index();\n if (!before || !after || !before.type.compatibleContent(after.type))\n return false;\n if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {\n if (dispatch)\n dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());\n return true;\n }\n if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))\n return false;\n if (dispatch)\n dispatch(state.tr.join($pos.pos).scrollIntoView());\n return true;\n}\nfunction deleteBarrier(state, $cut, dispatch, dir) {\n let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match;\n let isolated = before.type.spec.isolating || after.type.spec.isolating;\n if (!isolated && joinMaybeClear(state, $cut, dispatch))\n return true;\n let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);\n if (canDelAfter &&\n (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) &&\n match.matchType(conn[0] || after.type).validEnd) {\n if (dispatch) {\n let end = $cut.pos + after.nodeSize, wrap = Fragment.empty;\n for (let i = conn.length - 1; i >= 0; i--)\n wrap = Fragment.from(conn[i].create(null, wrap));\n wrap = Fragment.from(before.copy(wrap));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap, 1, 0), conn.length, true));\n let $joinAt = tr.doc.resolve(end + 2 * conn.length);\n if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type &&\n canJoin(tr.doc, $joinAt.pos))\n tr.join($joinAt.pos);\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n let selAfter = after.type.spec.isolating || (dir > 0 && isolated) ? null : Selection.findFrom($cut, 1);\n let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);\n if (target != null && target >= $cut.depth) {\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n if (canDelAfter && textblockAt(after, \"start\", true) && textblockAt(before, \"end\")) {\n let at = before, wrap = [];\n for (;;) {\n wrap.push(at);\n if (at.isTextblock)\n break;\n at = at.lastChild;\n }\n let afterText = after, afterDepth = 1;\n for (; !afterText.isTextblock; afterText = afterText.firstChild)\n afterDepth++;\n if (at.canReplace(at.childCount, at.childCount, afterText.content)) {\n if (dispatch) {\n let end = Fragment.empty;\n for (let i = wrap.length - 1; i >= 0; i--)\n end = Fragment.from(wrap[i].copy(end));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap.length, 0), 0, true));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n return false;\n}\nfunction selectTextblockSide(side) {\n return function (state, dispatch) {\n let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;\n let depth = $pos.depth;\n while ($pos.node(depth).isInline) {\n if (!depth)\n return false;\n depth--;\n }\n if (!$pos.node(depth).isTextblock)\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));\n return true;\n };\n}\n/**\nMoves the cursor to the start of current text block.\n*/\nconst selectTextblockStart = selectTextblockSide(-1);\n/**\nMoves the cursor to the end of current text block.\n*/\nconst selectTextblockEnd = selectTextblockSide(1);\n// Parameterized commands\n/**\nWrap the selection in a node of the given type with the given\nattributes.\n*/\nfunction wrapIn(nodeType, attrs = null) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs);\n if (!wrapping)\n return false;\n if (dispatch)\n dispatch(state.tr.wrap(range, wrapping).scrollIntoView());\n return true;\n };\n}\n/**\nReturns a command that tries to set the selected textblocks to the\ngiven node type with the given attributes.\n*/\nfunction setBlockType(nodeType, attrs = null) {\n return function (state, dispatch) {\n let applicable = false;\n for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {\n let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (applicable)\n return false;\n if (!node.isTextblock || node.hasMarkup(nodeType, attrs))\n return;\n if (node.type == nodeType) {\n applicable = true;\n }\n else {\n let $pos = state.doc.resolve(pos), index = $pos.index();\n applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);\n }\n });\n }\n if (!applicable)\n return false;\n if (dispatch) {\n let tr = state.tr;\n for (let i = 0; i < state.selection.ranges.length; i++) {\n let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n tr.setBlockType(from, to, nodeType, attrs);\n }\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\nfunction markApplies(doc, ranges, type, enterAtoms) {\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n let can = $from.depth == 0 ? doc.inlineContent && doc.type.allowsMarkType(type) : false;\n doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (can || !enterAtoms && node.isAtom && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos)\n return false;\n can = node.inlineContent && node.type.allowsMarkType(type);\n });\n if (can)\n return true;\n }\n return false;\n}\nfunction removeInlineAtoms(ranges) {\n let result = [];\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n $from.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (node.isAtom && node.content.size && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos) {\n if (pos + 1 > $from.pos)\n result.push(new SelectionRange($from, $from.doc.resolve(pos + 1)));\n $from = $from.doc.resolve(pos + 1 + node.content.size);\n return false;\n }\n });\n if ($from.pos < $to.pos)\n result.push(new SelectionRange($from, $to));\n }\n return result;\n}\n/**\nCreate a command function that toggles the given mark with the\ngiven attributes. Will return `false` when the current selection\ndoesn't support that mark. This will remove the mark if any marks\nof that type exist in the selection, or add it otherwise. If the\nselection is empty, this applies to the [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks) instead of a range of the\ndocument.\n*/\nfunction toggleMark(markType, attrs = null, options) {\n let removeWhenPresent = (options && options.removeWhenPresent) !== false;\n let enterAtoms = (options && options.enterInlineAtoms) !== false;\n return function (state, dispatch) {\n let { empty, $cursor, ranges } = state.selection;\n if ((empty && !$cursor) || !markApplies(state.doc, ranges, markType, enterAtoms))\n return false;\n if (dispatch) {\n if ($cursor) {\n if (markType.isInSet(state.storedMarks || $cursor.marks()))\n dispatch(state.tr.removeStoredMark(markType));\n else\n dispatch(state.tr.addStoredMark(markType.create(attrs)));\n }\n else {\n let add, tr = state.tr;\n if (!enterAtoms)\n ranges = removeInlineAtoms(ranges);\n if (removeWhenPresent) {\n add = !ranges.some(r => state.doc.rangeHasMark(r.$from.pos, r.$to.pos, markType));\n }\n else {\n add = !ranges.every(r => {\n let missing = false;\n tr.doc.nodesBetween(r.$from.pos, r.$to.pos, (node, pos, parent) => {\n if (missing)\n return false;\n missing = !markType.isInSet(node.marks) && !!parent && parent.type.allowsMarkType(markType) &&\n !(node.isText && /^\\s*$/.test(node.textBetween(Math.max(0, r.$from.pos - pos), Math.min(node.nodeSize, r.$to.pos - pos))));\n });\n return !missing;\n });\n }\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n if (!add) {\n tr.removeMark($from.pos, $to.pos, markType);\n }\n else {\n let from = $from.pos, to = $to.pos, start = $from.nodeAfter, end = $to.nodeBefore;\n let spaceStart = start && start.isText ? /^\\s*/.exec(start.text)[0].length : 0;\n let spaceEnd = end && end.isText ? /\\s*$/.exec(end.text)[0].length : 0;\n if (from + spaceStart < to) {\n from += spaceStart;\n to -= spaceEnd;\n }\n tr.addMark(from, to, markType.create(attrs));\n }\n }\n dispatch(tr.scrollIntoView());\n }\n }\n return true;\n };\n}\nfunction wrapDispatchForJoin(dispatch, isJoinable) {\n return (tr) => {\n if (!tr.isGeneric)\n return dispatch(tr);\n let ranges = [];\n for (let i = 0; i < tr.mapping.maps.length; i++) {\n let map = tr.mapping.maps[i];\n for (let j = 0; j < ranges.length; j++)\n ranges[j] = map.map(ranges[j]);\n map.forEach((_s, _e, from, to) => ranges.push(from, to));\n }\n // Figure out which joinable points exist inside those ranges,\n // by checking all node boundaries in their parent nodes.\n let joinable = [];\n for (let i = 0; i < ranges.length; i += 2) {\n let from = ranges[i], to = ranges[i + 1];\n let $from = tr.doc.resolve(from), depth = $from.sharedDepth(to), parent = $from.node(depth);\n for (let index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {\n let after = parent.maybeChild(index);\n if (!after)\n break;\n if (index && joinable.indexOf(pos) == -1) {\n let before = parent.child(index - 1);\n if (before.type == after.type && isJoinable(before, after))\n joinable.push(pos);\n }\n pos += after.nodeSize;\n }\n }\n // Join the joinable points\n joinable.sort((a, b) => a - b);\n for (let i = joinable.length - 1; i >= 0; i--) {\n if (canJoin(tr.doc, joinable[i]))\n tr.join(joinable[i]);\n }\n dispatch(tr);\n };\n}\n/**\nWrap a command so that, when it produces a transform that causes\ntwo joinable nodes to end up next to each other, those are joined.\nNodes are considered joinable when they are of the same type and\nwhen the `isJoinable` predicate returns true for them or, if an\narray of strings was passed, if their node type name is in that\narray.\n*/\nfunction autoJoin(command, isJoinable) {\n let canJoin = Array.isArray(isJoinable) ? (node) => isJoinable.indexOf(node.type.name) > -1\n : isJoinable;\n return (state, dispatch, view) => command(state, dispatch && wrapDispatchForJoin(dispatch, canJoin), view);\n}\n/**\nCombine a number of command functions into a single function (which\ncalls them one by one until one returns true).\n*/\nfunction chainCommands(...commands) {\n return function (state, dispatch, view) {\n for (let i = 0; i < commands.length; i++)\n if (commands[i](state, dispatch, view))\n return true;\n return false;\n };\n}\nlet backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);\nlet del = chainCommands(deleteSelection, joinForward, selectNodeForward);\n/**\nA basic keymap containing bindings not specific to any schema.\nBinds the following keys (when multiple commands are listed, they\nare chained with [`chainCommands`](https://prosemirror.net/docs/ref/#commands.chainCommands)):\n\n* **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock`\n* **Mod-Enter** to `exitCode`\n* **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward`\n* **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-a** to `selectAll`\n*/\nconst pcBaseKeymap = {\n \"Enter\": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),\n \"Mod-Enter\": exitCode,\n \"Backspace\": backspace,\n \"Mod-Backspace\": backspace,\n \"Shift-Backspace\": backspace,\n \"Delete\": del,\n \"Mod-Delete\": del,\n \"Mod-a\": selectAll\n};\n/**\nA copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace,\n**Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and\n**Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like\nCtrl-Delete.\n*/\nconst macBaseKeymap = {\n \"Ctrl-h\": pcBaseKeymap[\"Backspace\"],\n \"Alt-Backspace\": pcBaseKeymap[\"Mod-Backspace\"],\n \"Ctrl-d\": pcBaseKeymap[\"Delete\"],\n \"Ctrl-Alt-Backspace\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-Delete\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-d\": pcBaseKeymap[\"Mod-Delete\"],\n \"Ctrl-a\": selectTextblockStart,\n \"Ctrl-e\": selectTextblockEnd\n};\nfor (let key in pcBaseKeymap)\n macBaseKeymap[key] = pcBaseKeymap[key];\nconst mac = typeof navigator != \"undefined\" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform)\n // @ts-ignore\n : typeof os != \"undefined\" && os.platform ? os.platform() == \"darwin\" : false;\n/**\nDepending on the detected platform, this will hold\n[`pcBasekeymap`](https://prosemirror.net/docs/ref/#commands.pcBaseKeymap) or\n[`macBaseKeymap`](https://prosemirror.net/docs/ref/#commands.macBaseKeymap).\n*/\nconst baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;\n\nexport { autoJoin, baseKeymap, chainCommands, createParagraphNear, deleteSelection, exitCode, joinBackward, joinDown, joinForward, joinTextblockBackward, joinTextblockForward, joinUp, lift, liftEmptyBlock, macBaseKeymap, newlineInCode, pcBaseKeymap, selectAll, selectNodeBackward, selectNodeForward, selectParentNode, selectTextblockEnd, selectTextblockStart, setBlockType, splitBlock, splitBlockAs, splitBlockKeepMarks, toggleMark, wrapIn };\n","var GOOD_LEAF_SIZE = 200;\n\n// :: class A rope sequence is a persistent sequence data structure\n// that supports appending, prepending, and slicing without doing a\n// full copy. It is represented as a mostly-balanced tree.\nvar RopeSequence = function RopeSequence () {};\n\nRopeSequence.prototype.append = function append (other) {\n if (!other.length) { return this }\n other = RopeSequence.from(other);\n\n return (!this.length && other) ||\n (other.length < GOOD_LEAF_SIZE && this.leafAppend(other)) ||\n (this.length < GOOD_LEAF_SIZE && other.leafPrepend(this)) ||\n this.appendInner(other)\n};\n\n// :: (union<[T], RopeSequence>) → RopeSequence\n// Prepend an array or other rope to this one, returning a new rope.\nRopeSequence.prototype.prepend = function prepend (other) {\n if (!other.length) { return this }\n return RopeSequence.from(other).append(this)\n};\n\nRopeSequence.prototype.appendInner = function appendInner (other) {\n return new Append(this, other)\n};\n\n// :: (?number, ?number) → RopeSequence\n// Create a rope repesenting a sub-sequence of this rope.\nRopeSequence.prototype.slice = function slice (from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n if (from >= to) { return RopeSequence.empty }\n return this.sliceInner(Math.max(0, from), Math.min(this.length, to))\n};\n\n// :: (number) → T\n// Retrieve the element at the given position from this rope.\nRopeSequence.prototype.get = function get (i) {\n if (i < 0 || i >= this.length) { return undefined }\n return this.getInner(i)\n};\n\n// :: ((element: T, index: number) → ?bool, ?number, ?number)\n// Call the given function for each element between the given\n// indices. This tends to be more efficient than looping over the\n// indices and calling `get`, because it doesn't have to descend the\n// tree for every element.\nRopeSequence.prototype.forEach = function forEach (f, from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n if (from <= to)\n { this.forEachInner(f, from, to, 0); }\n else\n { this.forEachInvertedInner(f, from, to, 0); }\n};\n\n// :: ((element: T, index: number) → U, ?number, ?number) → [U]\n// Map the given functions over the elements of the rope, producing\n// a flat array.\nRopeSequence.prototype.map = function map (f, from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n var result = [];\n this.forEach(function (elt, i) { return result.push(f(elt, i)); }, from, to);\n return result\n};\n\n// :: (?union<[T], RopeSequence>) → RopeSequence\n// Create a rope representing the given array, or return the rope\n// itself if a rope was given.\nRopeSequence.from = function from (values) {\n if (values instanceof RopeSequence) { return values }\n return values && values.length ? new Leaf(values) : RopeSequence.empty\n};\n\nvar Leaf = /*@__PURE__*/(function (RopeSequence) {\n function Leaf(values) {\n RopeSequence.call(this);\n this.values = values;\n }\n\n if ( RopeSequence ) Leaf.__proto__ = RopeSequence;\n Leaf.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n Leaf.prototype.constructor = Leaf;\n\n var prototypeAccessors = { length: { configurable: true },depth: { configurable: true } };\n\n Leaf.prototype.flatten = function flatten () {\n return this.values\n };\n\n Leaf.prototype.sliceInner = function sliceInner (from, to) {\n if (from == 0 && to == this.length) { return this }\n return new Leaf(this.values.slice(from, to))\n };\n\n Leaf.prototype.getInner = function getInner (i) {\n return this.values[i]\n };\n\n Leaf.prototype.forEachInner = function forEachInner (f, from, to, start) {\n for (var i = from; i < to; i++)\n { if (f(this.values[i], start + i) === false) { return false } }\n };\n\n Leaf.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n for (var i = from - 1; i >= to; i--)\n { if (f(this.values[i], start + i) === false) { return false } }\n };\n\n Leaf.prototype.leafAppend = function leafAppend (other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE)\n { return new Leaf(this.values.concat(other.flatten())) }\n };\n\n Leaf.prototype.leafPrepend = function leafPrepend (other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE)\n { return new Leaf(other.flatten().concat(this.values)) }\n };\n\n prototypeAccessors.length.get = function () { return this.values.length };\n\n prototypeAccessors.depth.get = function () { return 0 };\n\n Object.defineProperties( Leaf.prototype, prototypeAccessors );\n\n return Leaf;\n}(RopeSequence));\n\n// :: RopeSequence\n// The empty rope sequence.\nRopeSequence.empty = new Leaf([]);\n\nvar Append = /*@__PURE__*/(function (RopeSequence) {\n function Append(left, right) {\n RopeSequence.call(this);\n this.left = left;\n this.right = right;\n this.length = left.length + right.length;\n this.depth = Math.max(left.depth, right.depth) + 1;\n }\n\n if ( RopeSequence ) Append.__proto__ = RopeSequence;\n Append.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n Append.prototype.constructor = Append;\n\n Append.prototype.flatten = function flatten () {\n return this.left.flatten().concat(this.right.flatten())\n };\n\n Append.prototype.getInner = function getInner (i) {\n return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length)\n };\n\n Append.prototype.forEachInner = function forEachInner (f, from, to, start) {\n var leftLen = this.left.length;\n if (from < leftLen &&\n this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false)\n { return false }\n if (to > leftLen &&\n this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false)\n { return false }\n };\n\n Append.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n var leftLen = this.left.length;\n if (from > leftLen &&\n this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false)\n { return false }\n if (to < leftLen &&\n this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false)\n { return false }\n };\n\n Append.prototype.sliceInner = function sliceInner (from, to) {\n if (from == 0 && to == this.length) { return this }\n var leftLen = this.left.length;\n if (to <= leftLen) { return this.left.slice(from, to) }\n if (from >= leftLen) { return this.right.slice(from - leftLen, to - leftLen) }\n return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen))\n };\n\n Append.prototype.leafAppend = function leafAppend (other) {\n var inner = this.right.leafAppend(other);\n if (inner) { return new Append(this.left, inner) }\n };\n\n Append.prototype.leafPrepend = function leafPrepend (other) {\n var inner = this.left.leafPrepend(other);\n if (inner) { return new Append(inner, this.right) }\n };\n\n Append.prototype.appendInner = function appendInner (other) {\n if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1)\n { return new Append(this.left, new Append(this.right, other)) }\n return new Append(this, other)\n };\n\n return Append;\n}(RopeSequence));\n\nexport default RopeSequence;\n","import RopeSequence from 'rope-sequence';\nimport { Mapping } from 'prosemirror-transform';\nimport { PluginKey, Plugin } from 'prosemirror-state';\n\n// ProseMirror's history isn't simply a way to roll back to a previous\n// state, because ProseMirror supports applying changes without adding\n// them to the history (for example during collaboration).\n//\n// To this end, each 'Branch' (one for the undo history and one for\n// the redo history) keeps an array of 'Items', which can optionally\n// hold a step (an actual undoable change), and always hold a position\n// map (which is needed to move changes below them to apply to the\n// current document).\n//\n// An item that has both a step and a selection bookmark is the start\n// of an 'event' — a group of changes that will be undone or redone at\n// once. (It stores only the bookmark, since that way we don't have to\n// provide a document until the selection is actually applied, which\n// is useful when compressing.)\n// Used to schedule history compression\nconst max_empty_items = 500;\nclass Branch {\n constructor(items, eventCount) {\n this.items = items;\n this.eventCount = eventCount;\n }\n // Pop the latest event off the branch's history and apply it\n // to a document transform.\n popEvent(state, preserveItems) {\n if (this.eventCount == 0)\n return null;\n let end = this.items.length;\n for (;; end--) {\n let next = this.items.get(end - 1);\n if (next.selection) {\n --end;\n break;\n }\n }\n let remap, mapFrom;\n if (preserveItems) {\n remap = this.remapping(end, this.items.length);\n mapFrom = remap.maps.length;\n }\n let transform = state.tr;\n let selection, remaining;\n let addAfter = [], addBefore = [];\n this.items.forEach((item, i) => {\n if (!item.step) {\n if (!remap) {\n remap = this.remapping(end, i + 1);\n mapFrom = remap.maps.length;\n }\n mapFrom--;\n addBefore.push(item);\n return;\n }\n if (remap) {\n addBefore.push(new Item(item.map));\n let step = item.step.map(remap.slice(mapFrom)), map;\n if (step && transform.maybeStep(step).doc) {\n map = transform.mapping.maps[transform.mapping.maps.length - 1];\n addAfter.push(new Item(map, undefined, undefined, addAfter.length + addBefore.length));\n }\n mapFrom--;\n if (map)\n remap.appendMap(map, mapFrom);\n }\n else {\n transform.maybeStep(item.step);\n }\n if (item.selection) {\n selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;\n remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);\n return false;\n }\n }, this.items.length, 0);\n return { remaining: remaining, transform, selection: selection };\n }\n // Create a new branch with the given transform added.\n addTransform(transform, selection, histOptions, preserveItems) {\n let newItems = [], eventCount = this.eventCount;\n let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;\n for (let i = 0; i < transform.steps.length; i++) {\n let step = transform.steps[i].invert(transform.docs[i]);\n let item = new Item(transform.mapping.maps[i], step, selection), merged;\n if (merged = lastItem && lastItem.merge(item)) {\n item = merged;\n if (i)\n newItems.pop();\n else\n oldItems = oldItems.slice(0, oldItems.length - 1);\n }\n newItems.push(item);\n if (selection) {\n eventCount++;\n selection = undefined;\n }\n if (!preserveItems)\n lastItem = item;\n }\n let overflow = eventCount - histOptions.depth;\n if (overflow > DEPTH_OVERFLOW) {\n oldItems = cutOffEvents(oldItems, overflow);\n eventCount -= overflow;\n }\n return new Branch(oldItems.append(newItems), eventCount);\n }\n remapping(from, to) {\n let maps = new Mapping;\n this.items.forEach((item, i) => {\n let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from\n ? maps.maps.length - item.mirrorOffset : undefined;\n maps.appendMap(item.map, mirrorPos);\n }, from, to);\n return maps;\n }\n addMaps(array) {\n if (this.eventCount == 0)\n return this;\n return new Branch(this.items.append(array.map(map => new Item(map))), this.eventCount);\n }\n // When the collab module receives remote changes, the history has\n // to know about those, so that it can adjust the steps that were\n // rebased on top of the remote changes, and include the position\n // maps for the remote changes in its array of items.\n rebased(rebasedTransform, rebasedCount) {\n if (!this.eventCount)\n return this;\n let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount);\n let mapping = rebasedTransform.mapping;\n let newUntil = rebasedTransform.steps.length;\n let eventCount = this.eventCount;\n this.items.forEach(item => { if (item.selection)\n eventCount--; }, start);\n let iRebased = rebasedCount;\n this.items.forEach(item => {\n let pos = mapping.getMirror(--iRebased);\n if (pos == null)\n return;\n newUntil = Math.min(newUntil, pos);\n let map = mapping.maps[pos];\n if (item.step) {\n let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);\n let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));\n if (selection)\n eventCount++;\n rebasedItems.push(new Item(map, step, selection));\n }\n else {\n rebasedItems.push(new Item(map));\n }\n }, start);\n let newMaps = [];\n for (let i = rebasedCount; i < newUntil; i++)\n newMaps.push(new Item(mapping.maps[i]));\n let items = this.items.slice(0, start).append(newMaps).append(rebasedItems);\n let branch = new Branch(items, eventCount);\n if (branch.emptyItemCount() > max_empty_items)\n branch = branch.compress(this.items.length - rebasedItems.length);\n return branch;\n }\n emptyItemCount() {\n let count = 0;\n this.items.forEach(item => { if (!item.step)\n count++; });\n return count;\n }\n // Compressing a branch means rewriting it to push the air (map-only\n // items) out. During collaboration, these naturally accumulate\n // because each remote change adds one. The `upto` argument is used\n // to ensure that only the items below a given level are compressed,\n // because `rebased` relies on a clean, untouched set of items in\n // order to associate old items with rebased steps.\n compress(upto = this.items.length) {\n let remap = this.remapping(0, upto), mapFrom = remap.maps.length;\n let items = [], events = 0;\n this.items.forEach((item, i) => {\n if (i >= upto) {\n items.push(item);\n if (item.selection)\n events++;\n }\n else if (item.step) {\n let step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap();\n mapFrom--;\n if (map)\n remap.appendMap(map, mapFrom);\n if (step) {\n let selection = item.selection && item.selection.map(remap.slice(mapFrom));\n if (selection)\n events++;\n let newItem = new Item(map.invert(), step, selection), merged, last = items.length - 1;\n if (merged = items.length && items[last].merge(newItem))\n items[last] = merged;\n else\n items.push(newItem);\n }\n }\n else if (item.map) {\n mapFrom--;\n }\n }, this.items.length, 0);\n return new Branch(RopeSequence.from(items.reverse()), events);\n }\n}\nBranch.empty = new Branch(RopeSequence.empty, 0);\nfunction cutOffEvents(items, n) {\n let cutPoint;\n items.forEach((item, i) => {\n if (item.selection && (n-- == 0)) {\n cutPoint = i;\n return false;\n }\n });\n return items.slice(cutPoint);\n}\nclass Item {\n constructor(\n // The (forward) step map for this item.\n map, \n // The inverted step\n step, \n // If this is non-null, this item is the start of a group, and\n // this selection is the starting selection for the group (the one\n // that was active before the first step was applied)\n selection, \n // If this item is the inverse of a previous mapping on the stack,\n // this points at the inverse's offset\n mirrorOffset) {\n this.map = map;\n this.step = step;\n this.selection = selection;\n this.mirrorOffset = mirrorOffset;\n }\n merge(other) {\n if (this.step && other.step && !other.selection) {\n let step = other.step.merge(this.step);\n if (step)\n return new Item(step.getMap().invert(), step, this.selection);\n }\n }\n}\n// The value of the state field that tracks undo/redo history for that\n// state. Will be stored in the plugin state when the history plugin\n// is active.\nclass HistoryState {\n constructor(done, undone, prevRanges, prevTime, prevComposition) {\n this.done = done;\n this.undone = undone;\n this.prevRanges = prevRanges;\n this.prevTime = prevTime;\n this.prevComposition = prevComposition;\n }\n}\nconst DEPTH_OVERFLOW = 20;\n// Record a transformation in undo history.\nfunction applyTransaction(history, state, tr, options) {\n let historyTr = tr.getMeta(historyKey), rebased;\n if (historyTr)\n return historyTr.historyState;\n if (tr.getMeta(closeHistoryKey))\n history = new HistoryState(history.done, history.undone, null, 0, -1);\n let appended = tr.getMeta(\"appendedTransaction\");\n if (tr.steps.length == 0) {\n return history;\n }\n else if (appended && appended.getMeta(historyKey)) {\n if (appended.getMeta(historyKey).redo)\n return new HistoryState(history.done.addTransform(tr, undefined, options, mustPreserveItems(state)), history.undone, rangesFor(tr.mapping.maps), history.prevTime, history.prevComposition);\n else\n return new HistoryState(history.done, history.undone.addTransform(tr, undefined, options, mustPreserveItems(state)), null, history.prevTime, history.prevComposition);\n }\n else if (tr.getMeta(\"addToHistory\") !== false && !(appended && appended.getMeta(\"addToHistory\") === false)) {\n // Group transforms that occur in quick succession into one event.\n let composition = tr.getMeta(\"composition\");\n let newGroup = history.prevTime == 0 ||\n (!appended && history.prevComposition != composition &&\n (history.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history.prevRanges)));\n let prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps);\n return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : undefined, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time, composition == null ? history.prevComposition : composition);\n }\n else if (rebased = tr.getMeta(\"rebased\")) {\n // Used by the collab module to tell the history that some of its\n // content has been rebased.\n return new HistoryState(history.done.rebased(tr, rebased), history.undone.rebased(tr, rebased), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n }\n else {\n return new HistoryState(history.done.addMaps(tr.mapping.maps), history.undone.addMaps(tr.mapping.maps), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n }\n}\nfunction isAdjacentTo(transform, prevRanges) {\n if (!prevRanges)\n return false;\n if (!transform.docChanged)\n return true;\n let adjacent = false;\n transform.mapping.maps[0].forEach((start, end) => {\n for (let i = 0; i < prevRanges.length; i += 2)\n if (start <= prevRanges[i + 1] && end >= prevRanges[i])\n adjacent = true;\n });\n return adjacent;\n}\nfunction rangesFor(maps) {\n let result = [];\n for (let i = maps.length - 1; i >= 0 && result.length == 0; i--)\n maps[i].forEach((_from, _to, from, to) => result.push(from, to));\n return result;\n}\nfunction mapRanges(ranges, mapping) {\n if (!ranges)\n return null;\n let result = [];\n for (let i = 0; i < ranges.length; i += 2) {\n let from = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1);\n if (from <= to)\n result.push(from, to);\n }\n return result;\n}\n// Apply the latest event from one branch to the document and shift the event\n// onto the other branch.\nfunction histTransaction(history, state, redo) {\n let preserveItems = mustPreserveItems(state);\n let histOptions = historyKey.get(state).spec.config;\n let pop = (redo ? history.undone : history.done).popEvent(state, preserveItems);\n if (!pop)\n return null;\n let selection = pop.selection.resolve(pop.transform.doc);\n let added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);\n let newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0, -1);\n return pop.transform.setSelection(selection).setMeta(historyKey, { redo, historyState: newHist });\n}\nlet cachedPreserveItems = false, cachedPreserveItemsPlugins = null;\n// Check whether any plugin in the given state has a\n// `historyPreserveItems` property in its spec, in which case we must\n// preserve steps exactly as they came in, so that they can be\n// rebased.\nfunction mustPreserveItems(state) {\n let plugins = state.plugins;\n if (cachedPreserveItemsPlugins != plugins) {\n cachedPreserveItems = false;\n cachedPreserveItemsPlugins = plugins;\n for (let i = 0; i < plugins.length; i++)\n if (plugins[i].spec.historyPreserveItems) {\n cachedPreserveItems = true;\n break;\n }\n }\n return cachedPreserveItems;\n}\n/**\nSet a flag on the given transaction that will prevent further steps\nfrom being appended to an existing history event (so that they\nrequire a separate undo command to undo).\n*/\nfunction closeHistory(tr) {\n return tr.setMeta(closeHistoryKey, true);\n}\nconst historyKey = new PluginKey(\"history\");\nconst closeHistoryKey = new PluginKey(\"closeHistory\");\n/**\nReturns a plugin that enables the undo history for an editor. The\nplugin will track undo and redo stacks, which can be used with the\n[`undo`](https://prosemirror.net/docs/ref/#history.undo) and [`redo`](https://prosemirror.net/docs/ref/#history.redo) commands.\n\nYou can set an `\"addToHistory\"` [metadata\nproperty](https://prosemirror.net/docs/ref/#state.Transaction.setMeta) of `false` on a transaction\nto prevent it from being rolled back by undo.\n*/\nfunction history(config = {}) {\n config = { depth: config.depth || 100,\n newGroupDelay: config.newGroupDelay || 500 };\n return new Plugin({\n key: historyKey,\n state: {\n init() {\n return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);\n },\n apply(tr, hist, state) {\n return applyTransaction(hist, state, tr, config);\n }\n },\n config,\n props: {\n handleDOMEvents: {\n beforeinput(view, e) {\n let inputType = e.inputType;\n let command = inputType == \"historyUndo\" ? undo : inputType == \"historyRedo\" ? redo : null;\n if (!command)\n return false;\n e.preventDefault();\n return command(view.state, view.dispatch);\n }\n }\n }\n });\n}\nfunction buildCommand(redo, scroll) {\n return (state, dispatch) => {\n let hist = historyKey.getState(state);\n if (!hist || (redo ? hist.undone : hist.done).eventCount == 0)\n return false;\n if (dispatch) {\n let tr = histTransaction(hist, state, redo);\n if (tr)\n dispatch(scroll ? tr.scrollIntoView() : tr);\n }\n return true;\n };\n}\n/**\nA command function that undoes the last change, if any.\n*/\nconst undo = buildCommand(false, true);\n/**\nA command function that redoes the last undone change, if any.\n*/\nconst redo = buildCommand(true, true);\n/**\nA command function that undoes the last change. Don't scroll the\nselection into view.\n*/\nconst undoNoScroll = buildCommand(false, false);\n/**\nA command function that redoes the last undone change. Don't\nscroll the selection into view.\n*/\nconst redoNoScroll = buildCommand(true, false);\n/**\nThe amount of undoable events available in a given state.\n*/\nfunction undoDepth(state) {\n let hist = historyKey.getState(state);\n return hist ? hist.done.eventCount : 0;\n}\n/**\nThe amount of redoable events available in a given editor state.\n*/\nfunction redoDepth(state) {\n let hist = historyKey.getState(state);\n return hist ? hist.undone.eventCount : 0;\n}\n\nexport { closeHistory, history, redo, redoDepth, redoNoScroll, undo, undoDepth, undoNoScroll };\n","export default function crelt() {\n var elt = arguments[0]\n if (typeof elt == \"string\") elt = document.createElement(elt)\n var i = 1, next = arguments[1]\n if (next && typeof next == \"object\" && next.nodeType == null && !Array.isArray(next)) {\n for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) {\n var value = next[name]\n if (typeof value == \"string\") elt.setAttribute(name, value)\n else if (value != null) elt[name] = value\n }\n i++\n }\n for (; i < arguments.length; i++) add(elt, arguments[i])\n return elt\n}\n\nfunction add(elt, child) {\n if (typeof child == \"string\") {\n elt.appendChild(document.createTextNode(child))\n } else if (child == null) {\n } else if (child.nodeType != null) {\n elt.appendChild(child)\n } else if (Array.isArray(child)) {\n for (var i = 0; i < child.length; i++) add(elt, child[i])\n } else {\n throw new RangeError(\"Unsupported child node: \" + child)\n }\n}\n","import crel from 'crelt';\nimport { joinUp, lift, selectParentNode, setBlockType, wrapIn } from 'prosemirror-commands';\nimport { undo, redo } from 'prosemirror-history';\nimport { Plugin } from 'prosemirror-state';\n\nconst SVG = \"http://www.w3.org/2000/svg\";\nconst XLINK = \"http://www.w3.org/1999/xlink\";\nconst prefix$2 = \"ProseMirror-icon\";\nfunction hashPath(path) {\n let hash = 0;\n for (let i = 0; i < path.length; i++)\n hash = (((hash << 5) - hash) + path.charCodeAt(i)) | 0;\n return hash;\n}\nfunction getIcon(root, icon) {\n let doc = (root.nodeType == 9 ? root : root.ownerDocument) || document;\n let node = doc.createElement(\"div\");\n node.className = prefix$2;\n if (icon.path) {\n let { path, width, height } = icon;\n let name = \"pm-icon-\" + hashPath(path).toString(16);\n if (!doc.getElementById(name))\n buildSVG(root, name, icon);\n let svg = node.appendChild(doc.createElementNS(SVG, \"svg\"));\n svg.style.width = (width / height) + \"em\";\n let use = svg.appendChild(doc.createElementNS(SVG, \"use\"));\n use.setAttributeNS(XLINK, \"href\", /([^#]*)/.exec(doc.location.toString())[1] + \"#\" + name);\n }\n else if (icon.dom) {\n node.appendChild(icon.dom.cloneNode(true));\n }\n else {\n let { text, css } = icon;\n node.appendChild(doc.createElement(\"span\")).textContent = text || '';\n if (css)\n node.firstChild.style.cssText = css;\n }\n return node;\n}\nfunction buildSVG(root, name, data) {\n let [doc, top] = root.nodeType == 9 ? [root, root.body] : [root.ownerDocument || document, root];\n let collection = doc.getElementById(prefix$2 + \"-collection\");\n if (!collection) {\n collection = doc.createElementNS(SVG, \"svg\");\n collection.id = prefix$2 + \"-collection\";\n collection.style.display = \"none\";\n top.insertBefore(collection, top.firstChild);\n }\n let sym = doc.createElementNS(SVG, \"symbol\");\n sym.id = name;\n sym.setAttribute(\"viewBox\", \"0 0 \" + data.width + \" \" + data.height);\n let path = sym.appendChild(doc.createElementNS(SVG, \"path\"));\n path.setAttribute(\"d\", data.path);\n collection.appendChild(sym);\n}\n\nconst prefix$1 = \"ProseMirror-menu\";\n/**\nAn icon or label that, when clicked, executes a command.\n*/\nclass MenuItem {\n /**\n Create a menu item.\n */\n constructor(\n /**\n The spec used to create this item.\n */\n spec) {\n this.spec = spec;\n }\n /**\n Renders the icon according to its [display\n spec](https://prosemirror.net/docs/ref/#menu.MenuItemSpec.display), and adds an event handler which\n executes the command when the representation is clicked.\n */\n render(view) {\n let spec = this.spec;\n let dom = spec.render ? spec.render(view)\n : spec.icon ? getIcon(view.root, spec.icon)\n : spec.label ? crel(\"div\", null, translate(view, spec.label))\n : null;\n if (!dom)\n throw new RangeError(\"MenuItem without icon or label property\");\n if (spec.title) {\n const title = (typeof spec.title === \"function\" ? spec.title(view.state) : spec.title);\n dom.setAttribute(\"title\", translate(view, title));\n }\n if (spec.class)\n dom.classList.add(spec.class);\n if (spec.css)\n dom.style.cssText += spec.css;\n dom.addEventListener(\"mousedown\", e => {\n e.preventDefault();\n if (!dom.classList.contains(prefix$1 + \"-disabled\"))\n spec.run(view.state, view.dispatch, view, e);\n });\n function update(state) {\n if (spec.select) {\n let selected = spec.select(state);\n dom.style.display = selected ? \"\" : \"none\";\n if (!selected)\n return false;\n }\n let enabled = true;\n if (spec.enable) {\n enabled = spec.enable(state) || false;\n setClass(dom, prefix$1 + \"-disabled\", !enabled);\n }\n if (spec.active) {\n let active = enabled && spec.active(state) || false;\n setClass(dom, prefix$1 + \"-active\", active);\n }\n return true;\n }\n return { dom, update };\n }\n}\nfunction translate(view, text) {\n return view._props.translate ? view._props.translate(text) : text;\n}\nlet lastMenuEvent = { time: 0, node: null };\nfunction markMenuEvent(e) {\n lastMenuEvent.time = Date.now();\n lastMenuEvent.node = e.target;\n}\nfunction isMenuEvent(wrapper) {\n return Date.now() - 100 < lastMenuEvent.time &&\n lastMenuEvent.node && wrapper.contains(lastMenuEvent.node);\n}\n/**\nA drop-down menu, displayed as a label with a downwards-pointing\ntriangle to the right of it.\n*/\nclass Dropdown {\n /**\n Create a dropdown wrapping the elements.\n */\n constructor(content, \n /**\n @internal\n */\n options = {}) {\n this.options = options;\n this.options = options || {};\n this.content = Array.isArray(content) ? content : [content];\n }\n /**\n Render the dropdown menu and sub-items.\n */\n render(view) {\n let content = renderDropdownItems(this.content, view);\n let win = view.dom.ownerDocument.defaultView || window;\n let label = crel(\"div\", { class: prefix$1 + \"-dropdown \" + (this.options.class || \"\"),\n style: this.options.css }, translate(view, this.options.label || \"\"));\n if (this.options.title)\n label.setAttribute(\"title\", translate(view, this.options.title));\n let wrap = crel(\"div\", { class: prefix$1 + \"-dropdown-wrap\" }, label);\n let open = null;\n let listeningOnClose = null;\n let close = () => {\n if (open && open.close()) {\n open = null;\n win.removeEventListener(\"mousedown\", listeningOnClose);\n }\n };\n label.addEventListener(\"mousedown\", e => {\n e.preventDefault();\n markMenuEvent(e);\n if (open) {\n close();\n }\n else {\n open = this.expand(wrap, content.dom);\n win.addEventListener(\"mousedown\", listeningOnClose = () => {\n if (!isMenuEvent(wrap))\n close();\n });\n }\n });\n function update(state) {\n let inner = content.update(state);\n wrap.style.display = inner ? \"\" : \"none\";\n return inner;\n }\n return { dom: wrap, update };\n }\n /**\n @internal\n */\n expand(dom, items) {\n let menuDOM = crel(\"div\", { class: prefix$1 + \"-dropdown-menu \" + (this.options.class || \"\") }, items);\n let done = false;\n function close() {\n if (done)\n return false;\n done = true;\n dom.removeChild(menuDOM);\n return true;\n }\n dom.appendChild(menuDOM);\n return { close, node: menuDOM };\n }\n}\nfunction renderDropdownItems(items, view) {\n let rendered = [], updates = [];\n for (let i = 0; i < items.length; i++) {\n let { dom, update } = items[i].render(view);\n rendered.push(crel(\"div\", { class: prefix$1 + \"-dropdown-item\" }, dom));\n updates.push(update);\n }\n return { dom: rendered, update: combineUpdates(updates, rendered) };\n}\nfunction combineUpdates(updates, nodes) {\n return (state) => {\n let something = false;\n for (let i = 0; i < updates.length; i++) {\n let up = updates[i](state);\n nodes[i].style.display = up ? \"\" : \"none\";\n if (up)\n something = true;\n }\n return something;\n };\n}\n/**\nRepresents a submenu wrapping a group of elements that start\nhidden and expand to the right when hovered over or tapped.\n*/\nclass DropdownSubmenu {\n /**\n Creates a submenu for the given group of menu elements. The\n following options are recognized:\n */\n constructor(content, \n /**\n @internal\n */\n options = {}) {\n this.options = options;\n this.content = Array.isArray(content) ? content : [content];\n }\n /**\n Renders the submenu.\n */\n render(view) {\n let items = renderDropdownItems(this.content, view);\n let win = view.dom.ownerDocument.defaultView || window;\n let label = crel(\"div\", { class: prefix$1 + \"-submenu-label\" }, translate(view, this.options.label || \"\"));\n let wrap = crel(\"div\", { class: prefix$1 + \"-submenu-wrap\" }, label, crel(\"div\", { class: prefix$1 + \"-submenu\" }, items.dom));\n let listeningOnClose = null;\n label.addEventListener(\"mousedown\", e => {\n e.preventDefault();\n markMenuEvent(e);\n setClass(wrap, prefix$1 + \"-submenu-wrap-active\", false);\n if (!listeningOnClose)\n win.addEventListener(\"mousedown\", listeningOnClose = () => {\n if (!isMenuEvent(wrap)) {\n wrap.classList.remove(prefix$1 + \"-submenu-wrap-active\");\n win.removeEventListener(\"mousedown\", listeningOnClose);\n listeningOnClose = null;\n }\n });\n });\n function update(state) {\n let inner = items.update(state);\n wrap.style.display = inner ? \"\" : \"none\";\n return inner;\n }\n return { dom: wrap, update };\n }\n}\n/**\nRender the given, possibly nested, array of menu elements into a\ndocument fragment, placing separators between them (and ensuring no\nsuperfluous separators appear when some of the groups turn out to\nbe empty).\n*/\nfunction renderGrouped(view, content) {\n let result = document.createDocumentFragment();\n let updates = [], separators = [];\n for (let i = 0; i < content.length; i++) {\n let items = content[i], localUpdates = [], localNodes = [];\n for (let j = 0; j < items.length; j++) {\n let { dom, update } = items[j].render(view);\n let span = crel(\"span\", { class: prefix$1 + \"item\" }, dom);\n result.appendChild(span);\n localNodes.push(span);\n localUpdates.push(update);\n }\n if (localUpdates.length) {\n updates.push(combineUpdates(localUpdates, localNodes));\n if (i < content.length - 1)\n separators.push(result.appendChild(separator()));\n }\n }\n function update(state) {\n let something = false, needSep = false;\n for (let i = 0; i < updates.length; i++) {\n let hasContent = updates[i](state);\n if (i)\n separators[i - 1].style.display = needSep && hasContent ? \"\" : \"none\";\n needSep = hasContent;\n if (hasContent)\n something = true;\n }\n return something;\n }\n return { dom: result, update };\n}\nfunction separator() {\n return crel(\"span\", { class: prefix$1 + \"separator\" });\n}\n/**\nA set of basic editor-related icons. Contains the properties\n`join`, `lift`, `selectParentNode`, `undo`, `redo`, `strong`, `em`,\n`code`, `link`, `bulletList`, `orderedList`, and `blockquote`, each\nholding an object that can be used as the `icon` option to\n`MenuItem`.\n*/\nconst icons = {\n join: {\n width: 800, height: 900,\n path: \"M0 75h800v125h-800z M0 825h800v-125h-800z M250 400h100v-100h100v100h100v100h-100v100h-100v-100h-100z\"\n },\n lift: {\n width: 1024, height: 1024,\n path: \"M219 310v329q0 7-5 12t-12 5q-8 0-13-5l-164-164q-5-5-5-13t5-13l164-164q5-5 13-5 7 0 12 5t5 12zM1024 749v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12zM1024 530v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 310v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 91v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12z\"\n },\n selectParentNode: { text: \"\\u2b1a\", css: \"font-weight: bold\" },\n undo: {\n width: 1024, height: 1024,\n path: \"M761 1024c113-206 132-520-313-509v253l-384-384 384-384v248c534-13 594 472 313 775z\"\n },\n redo: {\n width: 1024, height: 1024,\n path: \"M576 248v-248l384 384-384 384v-253c-446-10-427 303-313 509-280-303-221-789 313-775z\"\n },\n strong: {\n width: 805, height: 1024,\n path: \"M317 869q42 18 80 18 214 0 214-191 0-65-23-102-15-25-35-42t-38-26-46-14-48-6-54-1q-41 0-57 5 0 30-0 90t-0 90q0 4-0 38t-0 55 2 47 6 38zM309 442q24 4 62 4 46 0 81-7t62-25 42-51 14-81q0-40-16-70t-45-46-61-24-70-8q-28 0-74 7 0 28 2 86t2 86q0 15-0 45t-0 45q0 26 0 39zM0 950l1-53q8-2 48-9t60-15q4-6 7-15t4-19 3-18 1-21 0-19v-37q0-561-12-585-2-4-12-8t-25-6-28-4-27-2-17-1l-2-47q56-1 194-6t213-5q13 0 39 0t38 0q40 0 78 7t73 24 61 40 42 59 16 78q0 29-9 54t-22 41-36 32-41 25-48 22q88 20 146 76t58 141q0 57-20 102t-53 74-78 48-93 27-100 8q-25 0-75-1t-75-1q-60 0-175 6t-132 6z\"\n },\n em: {\n width: 585, height: 1024,\n path: \"M0 949l9-48q3-1 46-12t63-21q16-20 23-57 0-4 35-165t65-310 29-169v-14q-13-7-31-10t-39-4-33-3l10-58q18 1 68 3t85 4 68 1q27 0 56-1t69-4 56-3q-2 22-10 50-17 5-58 16t-62 19q-4 10-8 24t-5 22-4 26-3 24q-15 84-50 239t-44 203q-1 5-7 33t-11 51-9 47-3 32l0 10q9 2 105 17-1 25-9 56-6 0-18 0t-18 0q-16 0-49-5t-49-5q-78-1-117-1-29 0-81 5t-69 6z\"\n },\n code: {\n width: 896, height: 1024,\n path: \"M608 192l-96 96 224 224-224 224 96 96 288-320-288-320zM288 192l-288 320 288 320 96-96-224-224 224-224-96-96z\"\n },\n link: {\n width: 951, height: 1024,\n path: \"M832 694q0-22-16-38l-118-118q-16-16-38-16-24 0-41 18 1 1 10 10t12 12 8 10 7 14 2 15q0 22-16 38t-38 16q-8 0-15-2t-14-7-10-8-12-12-10-10q-18 17-18 41 0 22 16 38l117 118q15 15 38 15 22 0 38-14l84-83q16-16 16-38zM430 292q0-22-16-38l-117-118q-16-16-38-16-22 0-38 15l-84 83q-16 16-16 38 0 22 16 38l118 118q15 15 38 15 24 0 41-17-1-1-10-10t-12-12-8-10-7-14-2-15q0-22 16-38t38-16q8 0 15 2t14 7 10 8 12 12 10 10q18-17 18-41zM941 694q0 68-48 116l-84 83q-47 47-116 47-69 0-116-48l-117-118q-47-47-47-116 0-70 50-119l-50-50q-49 50-118 50-68 0-116-48l-118-118q-48-48-48-116t48-116l84-83q47-47 116-47 69 0 116 48l117 118q47 47 47 116 0 70-50 119l50 50q49-50 118-50 68 0 116 48l118 118q48 48 48 116z\"\n },\n bulletList: {\n width: 768, height: 896,\n path: \"M0 512h128v-128h-128v128zM0 256h128v-128h-128v128zM0 768h128v-128h-128v128zM256 512h512v-128h-512v128zM256 256h512v-128h-512v128zM256 768h512v-128h-512v128z\"\n },\n orderedList: {\n width: 768, height: 896,\n path: \"M320 512h448v-128h-448v128zM320 768h448v-128h-448v128zM320 128v128h448v-128h-448zM79 384h78v-256h-36l-85 23v50l43-2v185zM189 590c0-36-12-78-96-78-33 0-64 6-83 16l1 66c21-10 42-15 67-15s32 11 32 28c0 26-30 58-110 112v50h192v-67l-91 2c49-30 87-66 87-113l1-1z\"\n },\n blockquote: {\n width: 640, height: 896,\n path: \"M0 448v256h256v-256h-128c0 0 0-128 128-128v-128c0 0-256 0-256 256zM640 320v-128c0 0-256 0-256 256v256h256v-256h-128c0 0 0-128 128-128z\"\n }\n};\n/**\nMenu item for the `joinUp` command.\n*/\nconst joinUpItem = new MenuItem({\n title: \"Join with above block\",\n run: joinUp,\n select: state => joinUp(state),\n icon: icons.join\n});\n/**\nMenu item for the `lift` command.\n*/\nconst liftItem = new MenuItem({\n title: \"Lift out of enclosing block\",\n run: lift,\n select: state => lift(state),\n icon: icons.lift\n});\n/**\nMenu item for the `selectParentNode` command.\n*/\nconst selectParentNodeItem = new MenuItem({\n title: \"Select parent node\",\n run: selectParentNode,\n select: state => selectParentNode(state),\n icon: icons.selectParentNode\n});\n/**\nMenu item for the `undo` command.\n*/\nlet undoItem = new MenuItem({\n title: \"Undo last change\",\n run: undo,\n enable: state => undo(state),\n icon: icons.undo\n});\n/**\nMenu item for the `redo` command.\n*/\nlet redoItem = new MenuItem({\n title: \"Redo last undone change\",\n run: redo,\n enable: state => redo(state),\n icon: icons.redo\n});\n/**\nBuild a menu item for wrapping the selection in a given node type.\nAdds `run` and `select` properties to the ones present in\n`options`. `options.attrs` may be an object that provides\nattributes for the wrapping node.\n*/\nfunction wrapItem(nodeType, options) {\n let passedOptions = {\n run(state, dispatch) {\n return wrapIn(nodeType, options.attrs)(state, dispatch);\n },\n select(state) {\n return wrapIn(nodeType, options.attrs)(state);\n }\n };\n for (let prop in options)\n passedOptions[prop] = options[prop];\n return new MenuItem(passedOptions);\n}\n/**\nBuild a menu item for changing the type of the textblock around the\nselection to the given type. Provides `run`, `active`, and `select`\nproperties. Others must be given in `options`. `options.attrs` may\nbe an object to provide the attributes for the textblock node.\n*/\nfunction blockTypeItem(nodeType, options) {\n let command = setBlockType(nodeType, options.attrs);\n let passedOptions = {\n run: command,\n enable(state) { return command(state); },\n active(state) {\n let { $from, to, node } = state.selection;\n if (node)\n return node.hasMarkup(nodeType, options.attrs);\n return to <= $from.end() && $from.parent.hasMarkup(nodeType, options.attrs);\n }\n };\n for (let prop in options)\n passedOptions[prop] = options[prop];\n return new MenuItem(passedOptions);\n}\n// Work around classList.toggle being broken in IE11\nfunction setClass(dom, cls, on) {\n if (on)\n dom.classList.add(cls);\n else\n dom.classList.remove(cls);\n}\n\nconst prefix = \"ProseMirror-menubar\";\nfunction isIOS() {\n if (typeof navigator == \"undefined\")\n return false;\n let agent = navigator.userAgent;\n return !/Edge\\/\\d/.test(agent) && /AppleWebKit/.test(agent) && /Mobile\\/\\w+/.test(agent);\n}\n/**\nA plugin that will place a menu bar above the editor. Note that\nthis involves wrapping the editor in an additional ``.\n*/\nfunction menuBar(options) {\n return new Plugin({\n view(editorView) { return new MenuBarView(editorView, options); }\n });\n}\nclass MenuBarView {\n constructor(editorView, options) {\n this.editorView = editorView;\n this.options = options;\n this.spacer = null;\n this.maxHeight = 0;\n this.widthForMaxHeight = 0;\n this.floating = false;\n this.scrollHandler = null;\n this.wrapper = crel(\"div\", { class: prefix + \"-wrapper\" });\n this.menu = this.wrapper.appendChild(crel(\"div\", { class: prefix }));\n this.menu.className = prefix;\n if (editorView.dom.parentNode)\n editorView.dom.parentNode.replaceChild(this.wrapper, editorView.dom);\n this.wrapper.appendChild(editorView.dom);\n let { dom, update } = renderGrouped(this.editorView, this.options.content);\n this.contentUpdate = update;\n this.menu.appendChild(dom);\n this.update();\n if (options.floating && !isIOS()) {\n this.updateFloat();\n let potentialScrollers = getAllWrapping(this.wrapper);\n this.scrollHandler = (e) => {\n let root = this.editorView.root;\n if (!(root.body || root).contains(this.wrapper))\n potentialScrollers.forEach(el => el.removeEventListener(\"scroll\", this.scrollHandler));\n else\n this.updateFloat(e.target.getBoundingClientRect ? e.target : undefined);\n };\n potentialScrollers.forEach(el => el.addEventListener('scroll', this.scrollHandler));\n }\n }\n update() {\n this.contentUpdate(this.editorView.state);\n if (this.floating) {\n this.updateScrollCursor();\n }\n else {\n if (this.menu.offsetWidth != this.widthForMaxHeight) {\n this.widthForMaxHeight = this.menu.offsetWidth;\n this.maxHeight = 0;\n }\n if (this.menu.offsetHeight > this.maxHeight) {\n this.maxHeight = this.menu.offsetHeight;\n this.menu.style.minHeight = this.maxHeight + \"px\";\n }\n }\n }\n updateScrollCursor() {\n let selection = this.editorView.root.getSelection();\n if (!selection.focusNode)\n return;\n let rects = selection.getRangeAt(0).getClientRects();\n let selRect = rects[selectionIsInverted(selection) ? 0 : rects.length - 1];\n if (!selRect)\n return;\n let menuRect = this.menu.getBoundingClientRect();\n if (selRect.top < menuRect.bottom && selRect.bottom > menuRect.top) {\n let scrollable = findWrappingScrollable(this.wrapper);\n if (scrollable)\n scrollable.scrollTop -= (menuRect.bottom - selRect.top);\n }\n }\n updateFloat(scrollAncestor) {\n let parent = this.wrapper, editorRect = parent.getBoundingClientRect(), top = scrollAncestor ? Math.max(0, scrollAncestor.getBoundingClientRect().top) : 0;\n if (this.floating) {\n if (editorRect.top >= top || editorRect.bottom < this.menu.offsetHeight + 10) {\n this.floating = false;\n this.menu.style.position = this.menu.style.left = this.menu.style.top = this.menu.style.width = \"\";\n this.menu.style.display = \"\";\n this.spacer.parentNode.removeChild(this.spacer);\n this.spacer = null;\n }\n else {\n let border = (parent.offsetWidth - parent.clientWidth) / 2;\n this.menu.style.left = (editorRect.left + border) + \"px\";\n this.menu.style.display = editorRect.top > (this.editorView.dom.ownerDocument.defaultView || window).innerHeight\n ? \"none\" : \"\";\n if (scrollAncestor)\n this.menu.style.top = top + \"px\";\n }\n }\n else {\n if (editorRect.top < top && editorRect.bottom >= this.menu.offsetHeight + 10) {\n this.floating = true;\n let menuRect = this.menu.getBoundingClientRect();\n this.menu.style.left = menuRect.left + \"px\";\n this.menu.style.width = menuRect.width + \"px\";\n if (scrollAncestor)\n this.menu.style.top = top + \"px\";\n this.menu.style.position = \"fixed\";\n this.spacer = crel(\"div\", { class: prefix + \"-spacer\", style: `height: ${menuRect.height}px` });\n parent.insertBefore(this.spacer, this.menu);\n }\n }\n }\n destroy() {\n if (this.wrapper.parentNode)\n this.wrapper.parentNode.replaceChild(this.editorView.dom, this.wrapper);\n }\n}\n// Not precise, but close enough\nfunction selectionIsInverted(selection) {\n if (selection.anchorNode == selection.focusNode)\n return selection.anchorOffset > selection.focusOffset;\n return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING;\n}\nfunction findWrappingScrollable(node) {\n for (let cur = node.parentNode; cur; cur = cur.parentNode)\n if (cur.scrollHeight > cur.clientHeight)\n return cur;\n}\nfunction getAllWrapping(node) {\n let res = [node.ownerDocument.defaultView || window];\n for (let cur = node.parentNode; cur; cur = cur.parentNode)\n res.push(cur);\n return res;\n}\n\nexport { Dropdown, DropdownSubmenu, MenuItem, blockTypeItem, icons, joinUpItem, liftItem, menuBar, redoItem, renderGrouped, selectParentNodeItem, undoItem, wrapItem };\n","// menu-plugin.ts\nimport { MenuItem } from \"prosemirror-menu\";\nimport { menuBar } from \"prosemirror-menu\";\nimport { toggleMark } from \"prosemirror-commands\";\nimport { Plugin, PluginKey } from \"prosemirror-state\";\n\n\nconst menuPluginKey = new PluginKey('menuPlugin')\n// Modify the menuBar function to accept customSchema as a parameter\nexport function createMenuPlugin(customSchema: any) {\n const boldButton = new MenuItem({\n title: \"Bold\",\n run: toggleMark(customSchema.marks.bold),\n active: (state) => state.selection.$head.marks().some(mark => mark.type === customSchema.marks.bold),\n });\n\n const italicButton = new MenuItem({\n title: \"Italic\",\n run: toggleMark(customSchema.marks.italic),\n active: (state) => state.selection.$head.marks().some(mark => mark.type === customSchema.marks.italic),\n });\n\n const menuContent = [\n [boldButton, italicButton] // Array of buttons or other menu items\n ];\n\n menuBar({\n content: menuContent,\n floating: true,\n });\n console.log('Creating menu plugin');\n\n return new Plugin({\n key: menuPluginKey\n })\n\n}\n","import { LitElement, css, html } from 'lit';\nimport { property, customElement, query } from 'lit/decorators.js';\n\nimport '@shoelace-style/shoelace/dist/components/card/card.js';\n\nimport '@shoelace-style/shoelace/dist/components/button/button.js';\n\nimport { styles } from '../../styles/shared-styles';\n\nimport {EditorState} from 'prosemirror-state'\nimport { Transaction } from 'prosemirror-state';\nimport { EditorView } from 'prosemirror-view';\nimport { Schema } from 'prosemirror-model';\n\n\nimport { keymap } from 'prosemirror-keymap';\nimport { toggleMark } from 'prosemirror-commands';\nimport {undo, redo, history} from 'prosemirror-history'\nimport { baseKeymap } from 'prosemirror-commands';\n\nimport {createMenuPlugin} from '../../components/menu-plugin'\n\n\nexport const customSchema = new Schema({\n\tnodes: {\n\t text: {\n\t\tgroup: 'inline',\n\t },\n\t star: {\n\t\tinline: true,\n\t\tgroup: 'inline',\n\t\ttoDOM() {\n\t\t return ['star', '⭐'];\n\t\t},\n\t\tparseDOM: [{ tag: 'star' }],\n\t },\n\t paragraph: {\n\t\tgroup: 'block',\n\t\tcontent: 'inline*',\n\t\ttoDOM() {\n\t\t return ['p', 0];\n\t\t},\n\t\tparseDOM: [{ tag: 'p' }],\n\t },\n\t boring_paragraph: {\n\t\tgroup: 'block',\n\t\tcontent: 'text*',\n\t\tmarks: '',\n\t\ttoDOM() {\n\t\t return ['p', { class: 'boring' }, 0];\n\t\t},\n\t\tparseDOM: [{ tag: 'p.boring', priority: 60 }],\n\t },\n\t doc: {\n\t\tcontent: 'block+',\n\t },\n\t},\n\tmarks: {\n\t shouting: {\n\t\ttoDOM() {\n\t\t return ['shouting', 0];\n\t\t},\n\t\tparseDOM: [{ tag: 'shouting' }],\n\t },\n\t link: {\n\t\tattrs: { href: {} },\n\t\ttoDOM(node) {\n\t\t return ['a', { href: node.attrs.href }, 0];\n\t\t},\n\t\tparseDOM: [\n\t\t {\n\t\t\ttag: 'a',\n\t\t\tgetAttrs(dom) {\n\t\t\t return { href: dom };\n\t\t\t},\n\t\t },\n\t\t],\n\t\tinclusive: false,\n\t },\n\t},\n });\n\n// Create the menu plugin\nconst menuPlugin = createMenuPlugin(customSchema);\n\n // Commands\nfunction insertStar(state: EditorState, dispatch?: (tr: Transaction) => void): boolean {\n\tconst type = customSchema.nodes.star;\n\tconst { $from } = state.selection;\n\n\t// If the parent cannot replace with the 'star' node, return false\n\tif (!$from.parent.canReplaceWith($from.index(), $from.index(), type)) {\n\t return false;\n\t}\n\n\t// If dispatch is provided, apply the transaction\n\tif (dispatch) {\n\t dispatch(state.tr.replaceSelectionWith(type.create()));\n\t}\n\n\t// Always return true if insertion conditions are met\n\treturn true;\n }\n\nfunction toggleLink(state: EditorState, dispatch?: (tr: Transaction) => void): boolean {\n\tlet {doc, selection} = state\n\tif (selection.empty) return false\n\tlet attrs = null\n\tif (!doc.rangeHasMark(selection.from, selection.to, customSchema.marks.link)) {\n\t attrs = {href: prompt(\"Link to where?\", \"\")}\n\t if (!attrs.href) return false\n\t}\n\treturn toggleMark(customSchema.marks.link, attrs)(state, dispatch)\n }\n\n\n // Keymap\nconst customKeymap = keymap({\n\t'Ctrl-Space': insertStar,\n\t\"Ctrl-b\": (state, dispatch) => {\n console.log(\"Ctrl-b pressed, toggling shouting mark...\");\n return toggleMark(customSchema.marks.shouting)(state, dispatch);\n },\n \t'Ctrl-q': (state, dispatch) => {\n\t\tconsole.log(\"you should have just gotten an alert\");\n\t\treturn toggleLink(state, dispatch);\n\t},\n\n });\n\n\n\n\n@customElement('app-write')\nexport class AppWrite extends LitElement {\n\t@property({ type: String }) placeholder: string = 'Compose your note...';\n\t@property({ type: String }) public value?: string;\n\n\t// Reference to the ProseMirror container\n\t@query('#editor') editorContainer!: HTMLElement;\n\n\tprivate editorView!: EditorView\n\n\n\n\n static styles = [\n styles, css`\n\t\t:host {\n\t\tdisplay: block;\n\t\t}\n\n\t\tshouting {\n all: unset; /* Remove inherited or conflicting styles */\n font-weight: bold;\n text-transform: uppercase;\n color: red; /* Add a visible color for debugging */\n}\n\n\t\t`\n\n ];\n\n protected async firstUpdated() {\n\t\tconsole.log(\"Welcome to the compose page\");\n\t\tawait this.updateComplete;\n\t\tthis.initializeEditor()\n\n}\nprivate initializeEditor() {\n\t\tif (!this.editorContainer) {\n\t\t\tconsole.error('Editor container not here');\n\t\t\treturn\n\t\t}\n \tconst doc = customSchema.nodes.doc.createAndFill();\n\t if (!doc) {\n\t\tconsole.error(\"failed to create initial document\")\n\t\treturn;\n\t}\n\n\tconst state = EditorState.create({\n \tdoc,\n \tplugins: [\n\t\t\tmenuPlugin,\n\t\t\thistory(),\n \t\tkeymap({\n \t'Mod-z': undo,\n \t'Mod-y': redo,\n \t\t}),\n \t\tkeymap(baseKeymap),\n \t // Add the plus-button plugin here\n\t\t\tcustomKeymap\n \t\t],\n\t \t});\n\n\n\n\t\tlet view = new EditorView(this.editorContainer, {\n\t\t\tstate,\n\t\t\tdispatchTransaction(transaction) {\n\t\t\t\tconsole.log('Document size went from', transaction.before.content.size, \"to\",\n\t\t\t\t\ttransaction.doc.content.size\n\t\t\t\t)\n\t\t\t\tlet newState = view.state.apply(transaction)\n\t\t\t\tview.updateState(newState)\n\t\t\t}\n\t\t});\n\t\tthis.editorView = view;\n\t\tconsole.log(state.plugins);\n\n\t\tconsole.log('editor initialized')\n\n\t}\n\n\t/* connectedCallback(): void {\n\t\tsuper.connectedCallback();\n\t\tif(!this.editorView) {\n\t\t\tthis.editorView;\n\t\t}\n\t} */\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n\t\tif (this.editorView) {\n\t\t\tthis.editorView.destroy();\n\t\t\tthis.editorView = null!\n\t\t}\n }\n\n\n\n protected render() {\n return html`\n
\n\n\t\t
\n\t\t\n\n
\n \n
Editor Demo \n \n\n\n\n\t\t\tInstructions \n\t\t\tClick inside the white text area to highlight with your cursor.\n\t\t\tYou can type and press enter to insert a new block below.
\n\t\t\t \n\t\t\tTry to highlight a piece of text, then CTRL+X to cut and\n\t\t\tCTRL+V to paste.
\n\t\t\tPress Ctrl+Space to add a yellow star to the document.
\n\t\t\tPress Ctrl+B over a highlighted selection to add a \"shouting\"\n\t\t\tmark and format it all caps and red.
\n\n \n
\n
\n \n \n `}\n\t}"],"names":["OrderedMap","content","key","i","found","value","newKey","self","place","without","f","map","result","prop","findDiffStart","a","b","pos","childA","childB","j","inner","findDiffEnd","posA","posB","iA","iB","size","same","minSize","Fragment$1","Fragment","from","to","nodeStart","parent","child","end","start","blockSeparator","leafText","text","first","node","nodeText","other","last","index","current","copy","p","otherPos","round","retIndex","curPos","cur","n","schema","array","joined","nodes","offset","compareDeep","Mark","type","attrs","set","placed","obj","_","json","mark","marks","Slice$1","Slice","openStart","openEnd","fragment","insertInto","removeRange","openIsolating","indexTo","offsetTo","dist","insert","replace","$from","$to","slice","ReplaceError","replaceOuter","depth","close","prepareSliceForReplace","replaceThreeWay","replaceTwoWay","checkJoin","main","sub","joinable","$before","$after","addNode","target","addRange","$start","$end","startIndex","endIndex","$along","extra","ResolvedPos","path","parentOffset","val","dOff","tmp","after","next","pred","d","NodeRange","str","doc","rem","cache","resolveCache","elt","ResolveCache","resolveCacheSize","emptyAttrs","Node$1","Node","startPos","includeParents","name","wrapMarks","match","replacement","one","two","m","TextNode","base","ContentMatch","validEnd","string","nodeTypes","stream","TokenStream","expr","parseExpr","dfa","nfa","checkForDeadEnds","frag","toEnd","seen","search","types","finished","tp","computed","active","scan","out","tok","exprs","parseExprSeq","parseExprSubscript","parseExprAtom","parseExprRange","parseNum","min","max","resolveName","typeName","connect","compile","edge","term","edges","loop","cmp","nullFrom","labeled","explore","states","state","work","dead","defaultAttrs","defaults","attrName","attr","computeAttrs","built","given","checkAttrs","values","initAttrs","Attribute","NodeType$1","NodeType","spec","group","before","matched","markType","topType","validateType","options","MarkType","rank","Schema","instanceSpec","contentExprCache","contentExpr","markExpr","gatherMarks","excl","ok","isTagRule","rule","isStyleRule","DOMParser","rules","matchedStyles","r","dom","context","ParseContext","matches","style","priority","blockTags","ignoreTags","listTags","OPT_PRESERVE_WS","OPT_PRESERVE_WS_FULL","OPT_OPEN_LEFT","wsOptionsFor","preserveWhitespace","NodeContext","solid","fill","wrap","parser","isOpen","topNode","topContext","topOptions","top","preserveWS","nodeBefore","domNodeBefore","matchAfter","outerWS","ruleID","normalizeList","sync","oldNeedsBlock","innerMarks","styles","continueAfter","nodeType","startIn","contentDOM","route","cx","block","nodeMarks","markMayApply","applyMarks","textNode","parts","option","useRoot","minDepth","part","$context","deflt","prevItem","selector","DOMSerializer","keep","rendered","add","markDOM","renderSpec","inline","toDOM","structure","xmlNS","blockArraysIn","gatherToDOM","suspiciousAttributeCache","suspiciousAttributes","suspiciousAttributesInner","tagName","suspicious","space","innerContent","lower16","factor16","makeRecover","recoverIndex","recoverOffset","DEL_BEFORE","DEL_AFTER","DEL_ACROSS","DEL_SIDE","MapResult$1","delInfo","recover","StepMap$1","StepMap","ranges","inverted","diff","assoc","simple","oldIndex","newIndex","oldSize","newSize","side","del","MapResult","oldStart","newStart","Mapping","maps","mirror","mirrors","mapping","startSize","mirr","totalSize","inverse","corr","stepsByID","Step$1","id","stepClass","StepResult$1","StepResult","failed","message","e","mapFragment","mapped","AddMarkStep","Step","oldSlice","RemoveMarkStep","AddNodeMarkStep","updated","newSet","RemoveNodeMarkStep","ReplaceStep","contentBetween","ReplaceAroundStep","gapFrom","gapTo","gap","inserted","addMark","tr","removed","added","removing","adding","s","removeMark","step","toRemove","clearIncompatible","parentType","clearNewlines","replSteps","allowed","newline","canCut","liftTarget","range","lift","gapStart","gapEnd","splitting","wrappers","setBlockType","mapFrom","attrsHere","canChangeType","convertNewlines","pre","supportLinebreak","replaceLinebreaks","startM","endM","replaceNewlines","$pos","setNodeMarkup","newNode","canSplit","typesAfter","innerType","rest","overrideChild","baseType","split","typeAfter","canJoin","canAppendWithSubstitutedLinebreaks","linebreakReplacement","join","beforeType","$full","insertPoint","dropPoint","pass","bias","insertPos","fits","wrapping","replaceStep","fitsTrivially","Fitter","unplaced","fit","moveInline","placedSize","startDepth","sliceDepth","contentAt","frontierDepth","inject","openAtEnd","dropFromFragment","taken","openEndCount","closeNodeStart","addToFragment","level","contentAfterFits","dropInner","count","open","invalidMarks","definesContent","replaceRange","targetDepths","coveredDepths","preferredTarget","preferredTargetIndex","leftNodes","preferredDepth","leftNode","def","openDepth","targetDepth","expand","closeFragment","startSteps","oldOpen","newOpen","replaceRangeWith","point","deleteRange","covered","AttrStep","DocAttrStep","TransformError","err","Transform","classesById","Selection$1","$anchor","$head","SelectionRange","lastNode","lastParent","selectionToInsertionEnd","dir","textOnly","TextSelection","findSelectionIn","AllSelection","cls","selectionClass","Selection","SelectionRange$1","warnedAboutTextSelection","checkTextSelection","TextBookmark","anchor","head","dPos","TextBookmark$1","NodeSelection","deleted","NodeBookmark","NodeBookmark$1","sel","AllBookmark","startLen","_from","_to","_newFrom","newTo","UPDATED_SEL","UPDATED_MARKS","UPDATED_SCROLL","Transaction","selection","time","inheritMarks","bind","FieldDesc$1","desc","baseFields","FieldDesc","config","instance","_marks","_old","prev","Configuration","plugins","plugin","EditorState","ignore","rootTr","trs","newState","haveNew","oldState","newInstance","fields","field","$config","pluginFields","bindProps","Plugin$1","createKey","keys","PluginKey","domIndex","parentNode","reusedRange","textRange","clearReusedRange","isEquivalentPosition","off","targetNode","targetOff","scanFor","atomElements","nodeSize","hasBlockDesc","textNodeBefore$1","textNodeAfter$1","isOnEdge","atStart","atEnd","selectionCollapsed","domSel","keyEvent","keyCode","event","deepActiveElement","caretFromPoint","x","y","nav","agent","ie_edge","ie_upto10","ie_11up","ie","ie_version","gecko","_chrome","chrome","chrome_version","safari","ios","mac","windows","android","webkit","webkit_version","windowRect","vp","getSide","clientRect","rect","scaleX","scaleY","scrollRectIntoView","view","startDOM","scrollThreshold","scrollMargin","atTop","bounding","moveX","moveY","startX","startY","dX","dY","storeScrollPos","refDOM","refTop","localRect","scrollStack","stack","resetScrollPos","newRefTop","restoreScrollStack","dTop","left","preventScrollSupported","focusPreventScroll","stored","findOffsetInNode","coords","closest","dxClosest","coordsClosest","rowBot","rowTop","firstBelow","coordsBelow","childIndex","rects","dx","findOffsetInText","len","singleRect","inRect","targetKludge","posFromElement","posFromCaret","outsideBlock","sawBlock","elementFromPoint","element","box","startI","posAtCoords","caret","nonZero","BIDI","coordsAtPos","atom","supportEmptyRange","rectBefore","rectAfter","flattenV","takeSide","flattenH","withFlushedState","viewState","endOfTextblockVertical","nearest","boxes","maybeRTL","endOfTextblockHorizontal","oldNode","oldOff","anchorNode","anchorOffset","oldBidiLevel","parentDOM","newOff","cachedState","cachedDir","cachedResult","endOfTextblock","NOT_DIRTY","CHILD_DIRTY","CONTENT_DIRTY","NODE_DIRTY","ViewDesc","children","widget","outerDeco","innerDeco","nodeName","domBefore","domAfter","onlyNodes","nodeDOM","TrailingHackViewDesc","WidgetViewDesc","enter","fromOffset","toOffset","childBase","force","anchorDOM","headDOM","selRange","brKludge","domSelExtended","mutation","startInside","endInside","dirty","stop","CompositionViewDesc","textDOM","mut","MarkViewDesc","custom","replaceNodes","NodeViewDesc","descObj","applyOuterDeco","CustomNodeViewDesc","TextViewDesc","sameOuterDeco","composition","localComposition","compositionInChild","updater","ViewTreeUpdater","iterDeco","insideNode","compIndex","renderDescs","iosHacks","textPos","findTextInFragment","needsWrap","oldDOM","patchOuterDeco","computeOuterDeco","docViewDesc","docView","skip","descs","written","childDOM","rm","OuterDecoLevel","noDeco","outerDOM","prevComputed","curComputed","curDOM","deco","patchAttributes","prevList","curList","lock","preMatch","maxKeep","markDesc","targetDesc","domNode","nextDOM","locked","wrapper","ch","lastChild","hack","parentDesc","curDesc","descI","fI","outer","compareSide","onWidget","onNode","locals","decoIndex","restNode","parentIndex","widgets","cutAt","oldCSS","childStart","selectionFromDOM","origin","nearestDesc","inWidget","nearestDescNode","selectionBetween","editorOwnsSelection","hasSelection","selectionToDOM","syncNodeSelection","curSel","selectCursorWrapper","resetEditableFrom","resetEditableTo","brokenSelectBetweenUneditable","temporarilyEditableNear","resetEditable","removeClassOnSelectionChange","setEditable","img","clearNodeSelection","hasFocusAndSelection","anchorInRightPlace","moveSelectionBlock","$side","apply","selectHorizontally","mods","$newHead","nodePos","nodeLen","isIgnorable","skipIgnoredNodes","skipIgnoredNodesBefore","skipIgnoredNodesAfter","moveNode","moveOffset","isBlockNode","setSelFocus","textNodeAfter","textNodeBefore","findDirection","mid","selectVertically","beyond","stopNativeHorizontalDelete","empty","nextNode","switchEditable","safariDownArrowBug","focusNode","focusOffset","getMods","captureKeyDown","code","serializeForClipboard","serializer","detachedDoc","firstChild","wrapMap","parseFromClipboard","html","plainText","inCode","asText","parsed","readHTML","restoreReplacedSpaces","contextNode","sliceData","inlineParents","addContext","closeSlice","normalizeSiblings","lastWrap","inLast","addToSibling","closeRight","wrapped","withWrappers","sibling","closeRange","_detachedDoc","_policy","maybeWrapTrusted","trustedTypes","metas","firstTag","handlers","editHandlers","passiveHandlers","InputState","initInput","handler","eventBelongsToView","runCustomHandler","ensureListeners","setSelectionOrigin","destroyInput","currentHandlers","dispatchEvent","_event","inOrNearComposition","now","eventCoords","isNear","click","dy","runHandlerOnContext","propName","inside","updateSelection","selectClickedLeaf","selectClickedNode","selectedNode","selectAt","handleSingleClick","selectNode","handleDoubleClick","handleTripleClick","defaultTripleClick","forceDOMFlush","endComposition","selectNodeModifier","flushed","MouseDown","targetPos","timeoutComposition","scheduleComposeEnd","delay","clearComposition","timestampFromCustomEvent","findCompositionNode","textBefore","textAfter","descAfter","lastChanged","descBefore","restarting","captureCopy","brokenClipboardAPI","cut","data","sliceSingleNode","capturePaste","plain","doPaste","preferPlain","singleNode","getText","clipboardData","uris","Dragging","move","dragCopyModifier","mouseDown","draggedSlice","dragging","eventPos","$mouse","isNode","beforeInsert","domChangeCount","$cursor","compareObjs","WidgetType","noSpec","span","oldOffset","Decoration","InlineType","none","DecorationSet","local","decorations","buildTree","predicate","childOff","newLocal","mapChildren","byPos","childNode","childOffset","baseOffset","takeSpansForNode","moveSpans","withoutNulls","dec","localSet","DecorationGroup","removeOverlap","members","mappedDecos","member","sorted","oldChildren","moved","oldEnd","newEnd","dSize","mustRebuild","fromLocal","toLocal","mapAndGatherRemainingDecorations","spans","gather","hasNulls","localStart","subtree","working","insertAhead","viewDecorations","observeOptions","useCharData","SelectionState","DOMObserver","handleDOMChange","mutations","take","ancestors","container","newSel","typeOver","brs","br","blockParent","readSel","checkCSS","previousSibling","nextSibling","cssChecked","cssCheckWarned","rangeToSelectionRange","currentAnchor","safariShadowSelectionRange","read","parseBetween","from_","to_","find","startDoc","ruleFromNode","isInline","readDOMChange","addedNodes","compositionID","shared","parse","compare","preferredPos","preferredSide","change","findDiff","resolveSelection","$fromA","inlineChange","nextSel","looksLikeBackspace","chFrom","chTo","storedMarks","markChange","isMarkChange","parsedSel","curMarks","prevMarks","update","old","$newStart","$newEnd","skipClosingAndOpening","$next","fromEnd","mayOpen","endA","endB","adjust","isSurrogatePair","EditorView","props","checkStateComponent","getEditable","updateCursorWrapper","buildNodeViews","computeDocDeco","prevProps","_a","redraw","updateSel","pluginsChanged","nodeViews","changedNodeViews","scroll","updateDoc","oldScrollPos","forceSelUpdate","selectionContextChanged","chromeKludge","prevState","pluginView","movedPos","cached","dispatchTransaction","sel1","sel2","nA","nB","shift","keyName","ignoreKey","Plugin","normalizeKeyName","alt","ctrl","meta","mod","normalize","modifiers","keymap","bindings","keydownHandler","baseName","direct","noShift","fromCode","deleteSelection","dispatch","atBlockStart","joinBackward","$cut","findCutBefore","deleteBarrier","textblockAt","delStep","only","selectNodeBackward","atBlockEnd","joinForward","findCutAfter","selectNodeForward","newlineInCode","defaultBlockAt","exitCode","above","createParagraphNear","liftEmptyBlock","splitBlockAs","splitNode","splitDepth","splitPos","can","$first","splitBlock","selectAll","joinMaybeClear","conn","isolated","canDelAfter","$joinAt","selAfter","at","afterText","afterDepth","selectTextblockSide","selectTextblockStart","selectTextblockEnd","markApplies","enterAtoms","toggleMark","spaceStart","spaceEnd","chainCommands","commands","backspace","pcBaseKeymap","macBaseKeymap","baseKeymap","GOOD_LEAF_SIZE","RopeSequence","Append","Leaf","prototypeAccessors","right","leftLen","max_empty_items","Branch","items","eventCount","preserveItems","remap","transform","remaining","addAfter","addBefore","item","Item","histOptions","newItems","oldItems","lastItem","merged","overflow","DEPTH_OVERFLOW","cutOffEvents","mirrorPos","rebasedTransform","rebasedCount","rebasedItems","newUntil","iRebased","newMaps","branch","upto","events","newItem","cutPoint","mirrorOffset","HistoryState","done","undone","prevRanges","prevTime","prevComposition","applyTransaction","history","historyTr","historyKey","rebased","closeHistoryKey","appended","mustPreserveItems","rangesFor","newGroup","isAdjacentTo","mapRanges","adjacent","histTransaction","redo","pop","newHist","cachedPreserveItems","cachedPreserveItemsPlugins","hist","inputType","command","undo","buildCommand","crelt","SVG","XLINK","prefix$2","hashPath","hash","getIcon","root","icon","width","height","buildSVG","svg","css","collection","sym","prefix$1","MenuItem","crel","translate","title","selected","enabled","setClass","combineUpdates","updates","something","up","renderGrouped","separators","localUpdates","localNodes","separator","needSep","hasContent","on","prefix","isIOS","menuBar","editorView","MenuBarView","potentialScrollers","getAllWrapping","el","selRect","selectionIsInverted","menuRect","scrollable","findWrappingScrollable","scrollAncestor","editorRect","border","res","menuPluginKey","createMenuPlugin","customSchema","boldButton","italicButton","menuPlugin","insertStar","toggleLink","customKeymap","AppWrite","LitElement","transaction","__decorateClass","property","query","customElement"],"mappings":"yFAEA,SAASA,EAAWC,EAAS,CAC3B,KAAK,QAAUA,CACjB,CAEAD,EAAW,UAAY,CACrB,YAAaA,EAEb,KAAM,SAASE,EAAK,CAClB,QAASC,EAAI,EAAGA,EAAI,KAAK,QAAQ,OAAQA,GAAK,EAC5C,GAAI,KAAK,QAAQA,CAAC,IAAMD,EAAK,OAAOC,EACtC,MAAO,EACR,EAKD,IAAK,SAASD,EAAK,CACjB,IAAIE,EAAQ,KAAK,KAAKF,CAAG,EACzB,OAAOE,GAAS,GAAK,OAAY,KAAK,QAAQA,EAAQ,CAAC,CACxD,EAMD,OAAQ,SAASF,EAAKG,EAAOC,EAAQ,CACnC,IAAIC,EAAOD,GAAUA,GAAUJ,EAAM,KAAK,OAAOI,CAAM,EAAI,KACvDF,EAAQG,EAAK,KAAKL,CAAG,EAAGD,EAAUM,EAAK,QAAQ,MAAO,EAC1D,OAAIH,GAAS,GACXH,EAAQ,KAAKK,GAAUJ,EAAKG,CAAK,GAEjCJ,EAAQG,EAAQ,CAAC,EAAIC,EACjBC,IAAQL,EAAQG,CAAK,EAA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CACR,OAAAmpB;AAAAA,mCACoB,EAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAA,CA4BtC,EA/HYgc,GAYF,OAAS,CACZxgC,GAAQu9B;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA,GAcZ,EA1ByBoD,GAAA,CAA3BC,GAAS,CAAE,KAAM,MAAQ,CAAA,CAAA,EADdJ,GACgB,UAAA,cAAA,CAAA,EACOG,GAAA,CAAlCC,GAAS,CAAE,KAAM,MAAQ,CAAA,CAAA,EAFdJ,GAEuB,UAAA,QAAA,CAAA,EAGjBG,GAAA,CAAjBE,GAAM,SAAS,CAAA,EALJL,GAKM,UAAA,kBAAA,CAAA,EALNA,GAANG,GAAA,CADNG,GAAc,WAAW,CAAA,EACbN,EAAA","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]}
\ No newline at end of file
diff --git a/dist2/code/index-CBloBB_n.js b/dist2/code/index-CBloBB_n.js
deleted file mode 100644
index d889aad..0000000
--- a/dist2/code/index-CBloBB_n.js
+++ /dev/null
@@ -1,2 +0,0 @@
-var P=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,e,s,r,h,u){this.type=t,this.name=e,this.prefix=s,this.value=r,this.suffix=h,this.modifier=u}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},J=/[$_\p{ID_Start}]/u,Q=/[$_\u200C\u200D\p{ID_Continue}]/u,D=".*";function Y(t,e){return/^[\x00-\x7F]*$/.test(t)}function M(t,e=!1){let s=[],r=0;for(;r
{if(on("OTHER_MODIFIER")??n("ASTERISK"),f=p=>{let c=n(p);if(c!==void 0)return c;let{type:l,index:E}=s[o];throw new TypeError(`Unexpected ${l} at ${E}, expected ${p}`)},w=()=>{let p="",c;for(;c=n("CHAR")??n("ESCAPED_CHAR");)p+=c;return p},k=p=>p,T=e.encodePart||k,O="",U=p=>{O+=p},I=()=>{O.length&&(h.push(new P(3,"","",T(O),"",3)),O="")},_=(p,c,l,E,v)=>{let g=3;switch(v){case"?":g=1;break;case"*":g=0;break;case"+":g=2;break}if(!c&&!l&&g===3){U(p);return}if(I(),!c&&!l){if(!p)return;h.push(new P(3,"","",T(p),"",g));return}let m;l?l==="*"?m=D:m=l:m=r;let C=2;m===r?(C=1,m=""):m===D&&(C=0,m="");let b;if(c?b=c:l&&(b=u++),i.has(b))throw new TypeError(`Duplicate name '${b}'.`);i.add(b),h.push(new P(C,b,T(p),m,T(E),g))};for(;o-1)}return o||(r+=`(?=${u}|${h})`),new RegExp(r,j(s))}var $={delimiter:"",prefixes:"",sensitive:!0,strict:!0},et={delimiter:".",prefixes:"",sensitive:!0,strict:!0},st={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function it(t,e){return t.length?t[0]==="/"?!0:!e||t.length<2?!1:(t[0]=="\\"||t[0]=="{")&&t[1]=="/":!1}function G(t,e){return t.startsWith(e)?t.substring(e.length,t.length):t}function rt(t,e){return t.endsWith(e)?t.substr(0,t.length-e.length):t}function K(t){return!t||t.length<2?!1:t[0]==="["||(t[0]==="\\"||t[0]==="{")&&t[1]==="["}var X=["ftp","file","http","https","ws","wss"];function V(t){if(!t)return!0;for(let e of X)if(t.test(e))return!0;return!1}function nt(t,e){if(t=G(t,"#"),e||t==="")return t;let s=new URL("https://example.com");return s.hash=t,s.hash?s.hash.substring(1,s.hash.length):""}function ot(t,e){if(t=G(t,"?"),e||t==="")return t;let s=new URL("https://example.com");return s.search=t,s.search?s.search.substring(1,s.search.length):""}function ht(t,e){return e||t===""?t:K(t)?q(t):Z(t)}function at(t,e){if(e||t==="")return t;let s=new URL("https://example.com");return s.password=t,s.password}function ut(t,e){if(e||t==="")return t;let s=new URL("https://example.com");return s.username=t,s.username}function pt(t,e,s){if(s||t==="")return t;if(e&&!X.includes(e))return new URL(`${e}:${t}`).pathname;let r=t[0]=="/";return t=new URL(r?t:"/-"+t,"https://example.com").pathname,r||(t=t.substring(2,t.length)),t}function ct(t,e,s){return z(e)===t&&(t=""),s||t===""?t:B(t)}function ft(t,e){return t=rt(t,":"),e||t===""?t:N(t)}function z(t){switch(t){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}function N(t){if(t==="")return t;if(/^[-+.A-Za-z0-9]*$/.test(t))return t.toLowerCase();throw new TypeError(`Invalid protocol '${t}'.`)}function lt(t){if(t==="")return t;let e=new URL("https://example.com");return e.username=t,e.username}function mt(t){if(t==="")return t;let e=new URL("https://example.com");return e.password=t,e.password}function Z(t){if(t==="")return t;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(t))throw new TypeError(`Invalid hostname '${t}'`);let e=new URL("https://example.com");return e.hostname=t,e.hostname}function q(t){if(t==="")return t;if(/[^0-9a-fA-F[\]:]/g.test(t))throw new TypeError(`Invalid IPv6 hostname '${t}'`);return t.toLowerCase()}function B(t){if(t===""||/^[0-9]*$/.test(t)&&parseInt(t)<=65535)return t;throw new TypeError(`Invalid port '${t}'.`)}function dt(t){if(t==="")return t;let e=new URL("https://example.com");return e.pathname=t[0]!=="/"?"/-"+t:t,t[0]!=="/"?e.pathname.substring(2,e.pathname.length):e.pathname}function gt(t){return t===""?t:new URL(`data:${t}`).pathname}function wt(t){if(t==="")return t;let e=new URL("https://example.com");return e.search=t,e.search.substring(1,e.search.length)}function yt(t){if(t==="")return t;let e=new URL("https://example.com");return e.hash=t,e.hash.substring(1,e.hash.length)}var vt=class{#n;#i=[];#e={};#t=0;#r=1;#u=0;#h=0;#l=0;#m=0;#d=!1;constructor(t){this.#n=t}get result(){return this.#e}parse(){for(this.#i=M(this.#n,!0);this.#t0)if(this.#C())this.#l-=1;else continue;if(this.#k()){this.#l+=1;continue}switch(this.#h){case 0:this.#b()&&this.#f(1);break;case 1:if(this.#b()){this.#P();let t=7,e=1;this.#$()?(t=2,e=3):this.#d&&(t=2),this.#s(t,e)}break;case 2:this.#w()?this.#f(3):(this.#y()||this.#c()||this.#p())&&this.#f(5);break;case 3:this.#E()?this.#s(4,1):this.#w()&&this.#s(5,1);break;case 4:this.#w()&&this.#s(5,1);break;case 5:this.#L()?this.#m+=1:this.#A()&&(this.#m-=1),this.#R()&&!this.#m?this.#s(6,1):this.#y()?this.#s(7,0):this.#c()?this.#s(8,1):this.#p()&&this.#s(9,1);break;case 6:this.#y()?this.#s(7,0):this.#c()?this.#s(8,1):this.#p()&&this.#s(9,1);break;case 7:this.#c()?this.#s(8,1):this.#p()&&this.#s(9,1);break;case 8:this.#p()&&this.#s(9,1);break}}this.#e.hostname!==void 0&&this.#e.port===void 0&&(this.#e.port="")}#s(t,e){switch(this.#h){case 0:break;case 1:this.#e.protocol=this.#a();break;case 2:break;case 3:this.#e.username=this.#a();break;case 4:this.#e.password=this.#a();break;case 5:this.#e.hostname=this.#a();break;case 6:this.#e.port=this.#a();break;case 7:this.#e.pathname=this.#a();break;case 8:this.#e.search=this.#a();break;case 9:this.#e.hash=this.#a();break}this.#h!==0&&t!==10&&([1,2,3,4].includes(this.#h)&&[6,7,8,9].includes(t)&&(this.#e.hostname??=""),[1,2,3,4,5,6].includes(this.#h)&&[8,9].includes(t)&&(this.#e.pathname??=this.#d?"/":""),[1,2,3,4,5,6,7].includes(this.#h)&&t===9&&(this.#e.search??="")),this.#x(t,e)}#x(t,e){this.#h=t,this.#u=this.#t+e,this.#t+=e,this.#r=0}#v(){this.#t=this.#u,this.#r=0}#f(t){this.#v(),this.#h=t}#g(t){return t<0&&(t=this.#i.length-t),t=0&&(t.pathname=y(r.pathname.substring(0,h+1),s)+t.pathname)}t.pathname=pt(t.pathname,t.protocol,s)}return typeof e.search=="string"&&(t.search=ot(e.search,s)),typeof e.hash=="string"&&(t.hash=nt(e.hash,s)),t}function A(t){return t.replace(/([+*?:{}()\\])/g,"\\$1")}function bt(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function xt(t,e){e.delimiter??="/#?",e.prefixes??="./",e.sensitive??=!1,e.strict??=!1,e.end??=!0,e.start??=!0,e.endsWith="";let s=".*",r=`[^${bt(e.delimiter)}]+?`,h=/[$_\u200C\u200D\p{ID_Continue}]/u,u="";for(let o=0;o0?t[o-1]:null,w=o0?w.value[0]:"";a=h.test(k)}else a=!w.hasCustomName();if(!a&&!i.prefix.length&&f&&f.type===3){let k=f.value[f.value.length-1];a=e.prefixes.includes(k)}a&&(u+="{"),u+=A(i.prefix),n&&(u+=`:${i.name}`),i.type===2?u+=`(${i.value})`:i.type===1?n||(u+=`(${r})`):i.type===0&&(!n&&(!f||f.type===3||f.modifier!==3||a||i.prefix!=="")?u+="*":u+=`(${s})`),i.type===1&&n&&i.suffix.length&&h.test(i.suffix[0])&&(u+="\\"),u+=A(i.suffix),a&&(u+="}"),i.modifier!==3&&(u+=R(i.modifier))}return u}var $t=class{#n;#i={};#e={};#t={};#r={};#u=!1;constructor(t={},e,s){try{let r;if(typeof e=="string"?r=e:s=e,typeof t=="string"){let i=new vt(t);if(i.parse(),t=i.result,r===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=r}else{if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(r)throw new TypeError("parameter 1 is not of type 'string'.")}typeof s>"u"&&(s={ignoreCase:!1});let h={ignoreCase:s.ignoreCase===!0},u={pathname:x,protocol:x,username:x,password:x,hostname:x,port:x,search:x,hash:x};this.#n=L(u,t,!0),z(this.#n.protocol)===this.#n.port&&(this.#n.port="");let o;for(o of S){if(!(o in this.#n))continue;let i={},n=this.#n[o];switch(this.#e[o]=[],o){case"protocol":Object.assign(i,$),i.encodePart=N;break;case"username":Object.assign(i,$),i.encodePart=lt;break;case"password":Object.assign(i,$),i.encodePart=mt;break;case"hostname":Object.assign(i,et),K(n)?i.encodePart=q:i.encodePart=Z;break;case"port":Object.assign(i,$),i.encodePart=B;break;case"pathname":V(this.#i.protocol)?(Object.assign(i,st,h),i.encodePart=dt):(Object.assign(i,$,h),i.encodePart=gt);break;case"search":Object.assign(i,$,h),i.encodePart=wt;break;case"hash":Object.assign(i,$,h),i.encodePart=yt;break}try{this.#r[o]=W(n,i),this.#i[o]=F(this.#r[o],this.#e[o],i),this.#t[o]=xt(this.#r[o],i),this.#u=this.#u||this.#r[o].some(a=>a.type===2)}catch{throw new TypeError(`invalid ${o} pattern '${this.#n[o]}'.`)}}}catch(r){throw new TypeError(`Failed to construct 'URLPattern': ${r.message}`)}}test(t={},e){let s={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return!1;try{typeof t=="object"?s=L(s,t,!1):s=L(s,H(t,e),!1)}catch{return!1}let r;for(r of S)if(!this.#i[r].exec(s[r]))return!1;return!0}exec(t={},e){let s={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?s=L(s,t,!1):s=L(s,H(t,e),!1)}catch{return null}let r={};e?r.inputs=[t,e]:r.inputs=[t];let h;for(h of S){let u=this.#i[h].exec(s[h]);if(!u)return null;let o={};for(let[i,n]of this.#e[h].entries())if(typeof n=="string"||typeof n=="number"){let a=u[i+1];o[n]=a}r[h]={input:s[h]??"",groups:o}}return r}static compareComponent(t,e,s){let r=(i,n)=>{for(let a of["type","modifier","prefix","value","suffix"]){if(i[a]{let a=0;for(;a{if(la(\"OTHER_MODIFIER\")??a(\"ASTERISK\"),d=h=>{let u=a(h);if(u!==void 0)return u;let{type:p,index:A}=r[l];throw new TypeError(`Unexpected ${p} at ${A}, expected ${h}`)},T=()=>{let h=\"\",u;for(;u=a(\"CHAR\")??a(\"ESCAPED_CHAR\");)h+=u;return h},Se=h=>h,L=t.encodePart||Se,I=\"\",U=h=>{I+=h},$=()=>{I.length&&(o.push(new R(3,\"\",\"\",L(I),\"\",3)),I=\"\")},V=(h,u,p,A,Y)=>{let g=3;switch(Y){case\"?\":g=1;break;case\"*\":g=0;break;case\"+\":g=2;break}if(!u&&!p&&g===3){U(h);return}if($(),!u&&!p){if(!h)return;o.push(new R(3,\"\",\"\",L(h),\"\",g));return}let m;p?p===\"*\"?m=M:m=p:m=n;let O=2;m===n?(O=1,m=\"\"):m===M&&(O=0,m=\"\");let P;if(u?P=u:p&&(P=c++),i.has(P))throw new TypeError(`Duplicate name '${P}'.`);i.add(P),o.push(new R(O,P,L(h),m,L(A),g))};for(;l-1)}return l||(n+=`(?=${c}|${o})`),new RegExp(n,X(r))}var x={delimiter:\"\",prefixes:\"\",sensitive:!0,strict:!0},B={delimiter:\".\",prefixes:\"\",sensitive:!0,strict:!0},q={delimiter:\"/\",prefixes:\"/\",sensitive:!0,strict:!0};function J(e,t){return e.length?e[0]===\"/\"?!0:!t||e.length<2?!1:(e[0]==\"\\\\\"||e[0]==\"{\")&&e[1]==\"/\":!1}function Q(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function Ee(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function W(e){return!e||e.length<2?!1:e[0]===\"[\"||(e[0]===\"\\\\\"||e[0]===\"{\")&&e[1]===\"[\"}var ee=[\"ftp\",\"file\",\"http\",\"https\",\"ws\",\"wss\"];function N(e){if(!e)return!0;for(let t of ee)if(e.test(t))return!0;return!1}function te(e,t){if(e=Q(e,\"#\"),t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):\"\"}function re(e,t){if(e=Q(e,\"?\"),t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.search=e,r.search?r.search.substring(1,r.search.length):\"\"}function ne(e,t){return t||e===\"\"?e:W(e)?j(e):z(e)}function se(e,t){if(t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.password=e,r.password}function ie(e,t){if(t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.username=e,r.username}function ae(e,t,r){if(r||e===\"\")return e;if(t&&!ee.includes(t))return new URL(`${t}:${e}`).pathname;let n=e[0]==\"/\";return e=new URL(n?e:\"/-\"+e,\"https://example.com\").pathname,n||(e=e.substring(2,e.length)),e}function oe(e,t,r){return _(t)===e&&(e=\"\"),r||e===\"\"?e:K(e)}function ce(e,t){return e=Ee(e,\":\"),t||e===\"\"?e:y(e)}function _(e){switch(e){case\"ws\":case\"http\":return\"80\";case\"wws\":case\"https\":return\"443\";case\"ftp\":return\"21\";default:return\"\"}}function y(e){if(e===\"\")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}function le(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.username=e,t.username}function fe(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.password=e,t.password}function z(e){if(e===\"\")return e;if(/[\\t\\n\\r #%/:<>?@[\\]^\\\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL(\"https://example.com\");return t.hostname=e,t.hostname}function j(e){if(e===\"\")return e;if(/[^0-9a-fA-F[\\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function K(e){if(e===\"\"||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}function he(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.pathname=e[0]!==\"/\"?\"/-\"+e:e,e[0]!==\"/\"?t.pathname.substring(2,t.pathname.length):t.pathname}function ue(e){return e===\"\"?e:new URL(`data:${e}`).pathname}function de(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.search=e,t.search.substring(1,t.search.length)}function pe(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.hash=e,t.hash.substring(1,t.hash.length)}var H=class{#i;#n=[];#t={};#e=0;#s=1;#l=0;#o=0;#d=0;#p=0;#g=!1;constructor(t){this.#i=t}get result(){return this.#t}parse(){for(this.#n=v(this.#i,!0);this.#e0)if(this.#A())this.#d-=1;else continue;if(this.#T()){this.#d+=1;continue}switch(this.#o){case 0:this.#P()&&this.#u(1);break;case 1:if(this.#P()){this.#C();let t=7,r=1;this.#E()?(t=2,r=3):this.#g&&(t=2),this.#r(t,r)}break;case 2:this.#S()?this.#u(3):(this.#x()||this.#h()||this.#f())&&this.#u(5);break;case 3:this.#O()?this.#r(4,1):this.#S()&&this.#r(5,1);break;case 4:this.#S()&&this.#r(5,1);break;case 5:this.#y()?this.#p+=1:this.#w()&&(this.#p-=1),this.#k()&&!this.#p?this.#r(6,1):this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 6:this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 8:this.#f()&&this.#r(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port=\"\")}#r(t,r){switch(this.#o){case 0:break;case 1:this.#t.protocol=this.#c();break;case 2:break;case 3:this.#t.username=this.#c();break;case 4:this.#t.password=this.#c();break;case 5:this.#t.hostname=this.#c();break;case 6:this.#t.port=this.#c();break;case 7:this.#t.pathname=this.#c();break;case 8:this.#t.search=this.#c();break;case 9:this.#t.hash=this.#c();break;case 10:break}this.#o!==0&&t!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(t)&&(this.#t.hostname??=\"\"),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(t)&&(this.#t.pathname??=this.#g?\"/\":\"\"),[1,2,3,4,5,6,7].includes(this.#o)&&t===9&&(this.#t.search??=\"\")),this.#R(t,r)}#R(t,r){this.#o=t,this.#l=this.#e+r,this.#e+=r,this.#s=0}#b(){this.#e=this.#l,this.#s=0}#u(t){this.#b(),this.#o=t}#m(t){return t<0&&(t=this.#n.length-t),t=0&&(e.pathname=b(n.pathname.substring(0,o+1),r)+e.pathname)}e.pathname=ae(e.pathname,e.protocol,r)}return typeof t.search==\"string\"&&(e.search=re(t.search,r)),typeof t.hash==\"string\"&&(e.hash=te(t.hash,r)),e}function C(e){return e.replace(/([+*?:{}()\\\\])/g,\"\\\\$1\")}function Oe(e){return e.replace(/([.+*?^${}()[\\]|/\\\\])/g,\"\\\\$1\")}function ke(e,t){t.delimiter??=\"/#?\",t.prefixes??=\"./\",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith=\"\";let r=\".*\",n=`[^${Oe(t.delimiter)}]+?`,o=/[$_\\u200C\\u200D\\p{ID_Continue}]/u,c=\"\";for(let l=0;l0?e[l-1]:null,d=l0?d.value[0]:\"\";a=o.test(T)}else a=!d.hasCustomName();if(!a&&!s.prefix.length&&f&&f.type===3){let T=f.value[f.value.length-1];a=t.prefixes.includes(T)}a&&(c+=\"{\"),c+=C(s.prefix),i&&(c+=`:${s.name}`),s.type===2?c+=`(${s.value})`:s.type===1?i||(c+=`(${n})`):s.type===0&&(!i&&(!f||f.type===3||f.modifier!==3||a||s.prefix!==\"\")?c+=\"*\":c+=`(${r})`),s.type===1&&i&&s.suffix.length&&o.test(s.suffix[0])&&(c+=\"\\\\\"),c+=C(s.suffix),a&&(c+=\"}\"),s.modifier!==3&&(c+=k(s.modifier))}return c}var me=class{#i;#n={};#t={};#e={};#s={};#l=!1;constructor(t={},r,n){try{let o;if(typeof r==\"string\"?o=r:n=r,typeof t==\"string\"){let i=new H(t);if(i.parse(),t=i.result,o===void 0&&typeof t.protocol!=\"string\")throw new TypeError(\"A base URL must be provided for a relative constructor string.\");t.baseURL=o}else{if(!t||typeof t!=\"object\")throw new TypeError(\"parameter 1 is not of type 'string' and cannot convert to dictionary.\");if(o)throw new TypeError(\"parameter 1 is not of type 'string'.\")}typeof n>\"u\"&&(n={ignoreCase:!1});let c={ignoreCase:n.ignoreCase===!0},l={pathname:E,protocol:E,username:E,password:E,hostname:E,port:E,search:E,hash:E};this.#i=w(l,t,!0),_(this.#i.protocol)===this.#i.port&&(this.#i.port=\"\");let s;for(s of G){if(!(s in this.#i))continue;let i={},a=this.#i[s];switch(this.#t[s]=[],s){case\"protocol\":Object.assign(i,x),i.encodePart=y;break;case\"username\":Object.assign(i,x),i.encodePart=le;break;case\"password\":Object.assign(i,x),i.encodePart=fe;break;case\"hostname\":Object.assign(i,B),W(a)?i.encodePart=j:i.encodePart=z;break;case\"port\":Object.assign(i,x),i.encodePart=K;break;case\"pathname\":N(this.#n.protocol)?(Object.assign(i,q,c),i.encodePart=he):(Object.assign(i,x,c),i.encodePart=ue);break;case\"search\":Object.assign(i,x,c),i.encodePart=de;break;case\"hash\":Object.assign(i,x,c),i.encodePart=pe;break}try{this.#s[s]=D(a,i),this.#n[s]=F(this.#s[s],this.#t[s],i),this.#e[s]=ke(this.#s[s],i),this.#l=this.#l||this.#s[s].some(f=>f.type===2)}catch{throw new TypeError(`invalid ${s} pattern '${this.#i[s]}'.`)}}}catch(o){throw new TypeError(`Failed to construct 'URLPattern': ${o.message}`)}}test(t={},r){let n={pathname:\"\",protocol:\"\",username:\"\",password:\"\",hostname:\"\",port:\"\",search:\"\",hash:\"\"};if(typeof t!=\"string\"&&r)throw new TypeError(\"parameter 1 is not of type 'string'.\");if(typeof t>\"u\")return!1;try{typeof t==\"object\"?n=w(n,t,!1):n=w(n,ge(t,r),!1)}catch{return!1}let o;for(o of G)if(!this.#n[o].exec(n[o]))return!1;return!0}exec(t={},r){let n={pathname:\"\",protocol:\"\",username:\"\",password:\"\",hostname:\"\",port:\"\",search:\"\",hash:\"\"};if(typeof t!=\"string\"&&r)throw new TypeError(\"parameter 1 is not of type 'string'.\");if(typeof t>\"u\")return;try{typeof t==\"object\"?n=w(n,t,!1):n=w(n,ge(t,r),!1)}catch{return null}let o={};r?o.inputs=[t,r]:o.inputs=[t];let c;for(c of G){let l=this.#n[c].exec(n[c]);if(!l)return null;let s={};for(let[i,a]of this.#t[c].entries())if(typeof a==\"string\"||typeof a==\"number\"){let f=l[i+1];s[a]=f}o[c]={input:n[c]??\"\",groups:s}}return o}static compareComponent(t,r,n){let o=(i,a)=>{for(let f of[\"type\",\"modifier\",\"prefix\",\"value\",\"suffix\"]){if(i[f]{let f=0;for(;f{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function r(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(o){if(o.ep)return;o.ep=!0;const i=r(o);fetch(o.href,i)}})();var Ar="";function Sr(e){Ar=e}function ps(e=""){if(!Ar){const t=[...document.getElementsByTagName("script")],r=t.find(n=>n.hasAttribute("data-shoelace"));if(r)Sr(r.getAttribute("data-shoelace"));else{const n=t.find(i=>/shoelace(\.min)?\.js($|\?)/.test(i.src)||/shoelace-autoloader(\.min)?\.js($|\?)/.test(i.src));let o="";n&&(o=n.getAttribute("src")),Sr(o.split("/").slice(0,-1).join("/"))}}return Ar.replace(/\/$/,"")+(e?`/${e.replace(/^\//,"")}`:"")}var go=Object.defineProperty,gs=Object.defineProperties,bs=Object.getOwnPropertyDescriptor,ms=Object.getOwnPropertyDescriptors,Tn=Object.getOwnPropertySymbols,ys=Object.prototype.hasOwnProperty,ws=Object.prototype.propertyIsEnumerable,In=(e,t,r)=>t in e?go(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,_e=(e,t)=>{for(var r in t||(t={}))ys.call(t,r)&&In(e,r,t[r]);if(Tn)for(var r of Tn(t))ws.call(t,r)&&In(e,r,t[r]);return e},bo=(e,t)=>gs(e,ms(t)),T=(e,t,r,n)=>{for(var o=n>1?void 0:n?bs(t,r):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(o=(n?s(t,r,o):s(o))||o);return n&&o&&go(t,r,o),o},mo=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},vs=(e,t,r)=>(mo(e,t,"read from private field"),t.get(e)),xs=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},Es=(e,t,r,n)=>(mo(e,t,"write to private field"),t.set(e,r),r);Sr("https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.16.0/cdn/");/**
- * @license
- * Copyright 2019 Google LLC
- * SPDX-License-Identifier: BSD-3-Clause
- */const Be=globalThis,qr=Be.ShadowRoot&&(Be.ShadyCSS===void 0||Be.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,jr=Symbol(),Mn=new WeakMap;let yo=class{constructor(t,r,n){if(this._$cssResult$=!0,n!==jr)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=r}get styleSheet(){let t=this.o;const r=this.t;if(qr&&t===void 0){const n=r!==void 0&&r.length===1;n&&(t=Mn.get(r)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&Mn.set(r,t))}return t}toString(){return this.cssText}};const _s=e=>new yo(typeof e=="string"?e:e+"",void 0,jr),ct=(e,...t)=>{const r=e.length===1?e[0]:t.reduce((n,o,i)=>n+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[i+1],e[0]);return new yo(r,e,jr)},$s=(e,t)=>{if(qr)e.adoptedStyleSheets=t.map(r=>r instanceof CSSStyleSheet?r:r.styleSheet);else for(const r of t){const n=document.createElement("style"),o=Be.litNonce;o!==void 0&&n.setAttribute("nonce",o),n.textContent=r.cssText,e.appendChild(n)}},Rn=qr?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let r="";for(const n of t.cssRules)r+=n.cssText;return _s(r)})(e):e;/**
- * @license
- * Copyright 2017 Google LLC
- * SPDX-License-Identifier: BSD-3-Clause
- */const{is:As,defineProperty:Ss,getOwnPropertyDescriptor:ks,getOwnPropertyNames:Ps,getOwnPropertySymbols:Cs,getPrototypeOf:Bs}=Object,Ve=globalThis,Nn=Ve.trustedTypes,Ls=Nn?Nn.emptyScript:"",Us=Ve.reactiveElementPolyfillSupport,me=(e,t)=>e,Ie={toAttribute(e,t){switch(t){case Boolean:e=e?Ls:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let r=e;switch(t){case Boolean:r=e!==null;break;case Number:r=e===null?null:Number(e);break;case Object:case Array:try{r=JSON.parse(e)}catch{r=null}}return r}},Fr=(e,t)=>!As(e,t),On={attribute:!0,type:String,converter:Ie,reflect:!1,hasChanged:Fr};Symbol.metadata??=Symbol("metadata"),Ve.litPropertyMetadata??=new WeakMap;class Yt extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,r=On){if(r.state&&(r.attribute=!1),this._$Ei(),this.elementProperties.set(t,r),!r.noAccessor){const n=Symbol(),o=this.getPropertyDescriptor(t,n,r);o!==void 0&&Ss(this.prototype,t,o)}}static getPropertyDescriptor(t,r,n){const{get:o,set:i}=ks(this.prototype,t)??{get(){return this[r]},set(s){this[r]=s}};return{get(){return o?.call(this)},set(s){const l=o?.call(this);i.call(this,s),this.requestUpdate(t,l,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??On}static _$Ei(){if(this.hasOwnProperty(me("elementProperties")))return;const t=Bs(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(me("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(me("properties"))){const r=this.properties,n=[...Ps(r),...Cs(r)];for(const o of n)this.createProperty(o,r[o])}const t=this[Symbol.metadata];if(t!==null){const r=litPropertyMetadata.get(t);if(r!==void 0)for(const[n,o]of r)this.elementProperties.set(n,o)}this._$Eh=new Map;for(const[r,n]of this.elementProperties){const o=this._$Eu(r,n);o!==void 0&&this._$Eh.set(o,r)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const r=[];if(Array.isArray(t)){const n=new Set(t.flat(1/0).reverse());for(const o of n)r.unshift(Rn(o))}else t!==void 0&&r.push(Rn(t));return r}static _$Eu(t,r){const n=r.attribute;return n===!1?void 0:typeof n=="string"?n:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,r=this.constructor.elementProperties;for(const n of r.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return $s(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,r,n){this._$AK(t,n)}_$EC(t,r){const n=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,n);if(o!==void 0&&n.reflect===!0){const i=(n.converter?.toAttribute!==void 0?n.converter:Ie).toAttribute(r,n.type);this._$Em=t,i==null?this.removeAttribute(o):this.setAttribute(o,i),this._$Em=null}}_$AK(t,r){const n=this.constructor,o=n._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const i=n.getPropertyOptions(o),s=typeof i.converter=="function"?{fromAttribute:i.converter}:i.converter?.fromAttribute!==void 0?i.converter:Ie;this._$Em=o,this[o]=s.fromAttribute(r,i.type),this._$Em=null}}requestUpdate(t,r,n){if(t!==void 0){if(n??=this.constructor.getPropertyOptions(t),!(n.hasChanged??Fr)(this[t],r))return;this.P(t,r,n)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,r,n){this._$AL.has(t)||this._$AL.set(t,r),n.reflect===!0&&this._$Em!==t&&(this._$Ej??=new Set).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(r){Promise.reject(r)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[o,i]of this._$Ep)this[o]=i;this._$Ep=void 0}const n=this.constructor.elementProperties;if(n.size>0)for(const[o,i]of n)i.wrapped!==!0||this._$AL.has(o)||this[o]===void 0||this.P(o,this[o],i)}let t=!1;const r=this._$AL;try{t=this.shouldUpdate(r),t?(this.willUpdate(r),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(r)):this._$EU()}catch(n){throw t=!1,this._$EU(),n}t&&this._$AE(r)}willUpdate(t){}_$AE(t){this._$EO?.forEach(r=>r.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&=this._$Ej.forEach(r=>this._$EC(r,this[r])),this._$EU()}updated(t){}firstUpdated(t){}}Yt.elementStyles=[],Yt.shadowRootOptions={mode:"open"},Yt[me("elementProperties")]=new Map,Yt[me("finalized")]=new Map,Us?.({ReactiveElement:Yt}),(Ve.reactiveElementVersions??=[]).push("2.0.4");/**
- * @license
- * Copyright 2017 Google LLC
- * SPDX-License-Identifier: BSD-3-Clause
- */const Wr=globalThis,Me=Wr.trustedTypes,Hn=Me?Me.createPolicy("lit-html",{createHTML:e=>e}):void 0,wo="$lit$",Ct=`lit$${Math.random().toFixed(9).slice(2)}$`,vo="?"+Ct,Ts=`<${vo}>`,qt=document,ye=()=>qt.createComment(""),we=e=>e===null||typeof e!="object"&&typeof e!="function",Kr=Array.isArray,Is=e=>Kr(e)||typeof e?.[Symbol.iterator]=="function",lr=`[
-\f\r]`,de=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,zn=/-->/g,Vn=/>/g,Ot=RegExp(`>|${lr}(?:([^\\s"'>=/]+)(${lr}*=${lr}*(?:[^
-\f\r"'\`<>=]|("|')|))|$)`,"g"),Dn=/'/g,qn=/"/g,xo=/^(?:script|style|textarea|title)$/i,Ms=e=>(t,...r)=>({_$litType$:e,strings:t,values:r}),G=Ms(1),jt=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),jn=new WeakMap,Vt=qt.createTreeWalker(qt,129);function Eo(e,t){if(!Kr(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Hn!==void 0?Hn.createHTML(t):t}const Rs=(e,t)=>{const r=e.length-1,n=[];let o,i=t===2?"":t===3?"":"",s=de;for(let l=0;l"?(s=o??de,d=-1):u[1]===void 0?d=-2:(d=s.lastIndex-u[2].length,c=u[1],s=u[3]===void 0?Ot:u[3]==='"'?qn:Dn):s===qn||s===Dn?s=Ot:s===zn||s===Vn?s=de:(s=Ot,o=void 0);const g=s===Ot&&e[l+1].startsWith("/>")?" ":"";i+=s===de?a+Ts:d>=0?(n.push(c),a.slice(0,d)+wo+a.slice(d)+Ct+g):a+Ct+(d===-2?l:g)}return[Eo(e,i+(e[r]||">")+(t===2?" ":t===3?"":"")),n]};class ve{constructor({strings:t,_$litType$:r},n){let o;this.parts=[];let i=0,s=0;const l=t.length-1,a=this.parts,[c,u]=Rs(t,r);if(this.el=ve.createElement(c,n),Vt.currentNode=this.el.content,r===2||r===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(o=Vt.nextNode())!==null&&a.length0){o.textContent=Me?Me.emptyScript:"";for(let g=0;g2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=F}_$AI(t,r=this,n,o){const i=this.strings;let s=!1;if(i===void 0)t=te(this,t,r,0),s=!we(t)||t!==this._$AH&&t!==jt,s&&(this._$AH=t);else{const l=t;let a,c;for(t=i[0],a=0;a{const n=r?.renderBefore??t;let o=n._$litPart$;if(o===void 0){const i=r?.renderBefore??null;n._$litPart$=o=new $e(t.insertBefore(ye(),i),i,void 0,r??{})}return o._$AI(e),o};/**
- * @license
- * Copyright 2017 Google LLC
- * SPDX-License-Identifier: BSD-3-Clause
- */let gt=class extends Yt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const r=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=qs(r,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return jt}};gt._$litElement$=!0,gt.finalized=!0,globalThis.litElementHydrateSupport?.({LitElement:gt});const js=globalThis.litElementPolyfillSupport;js?.({LitElement:gt});(globalThis.litElementVersions??=[]).push("4.1.1");/**
- * @license
- * Copyright 2017 Google LLC
- * SPDX-License-Identifier: BSD-3-Clause
- */const qe=e=>(t,r)=>{r!==void 0?r.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};/**
- * @license
- * Copyright 2017 Google LLC
- * SPDX-License-Identifier: BSD-3-Clause
- */const Fs={attribute:!0,type:String,converter:Ie,reflect:!1,hasChanged:Fr},Ws=(e=Fs,t,r)=>{const{kind:n,metadata:o}=r;let i=globalThis.litPropertyMetadata.get(o);if(i===void 0&&globalThis.litPropertyMetadata.set(o,i=new Map),i.set(r.name,e),n==="accessor"){const{name:s}=r;return{set(l){const a=t.get.call(this);t.set.call(this,l),this.requestUpdate(s,a,e)},init(l){return l!==void 0&&this.P(s,void 0,e),l}}}if(n==="setter"){const{name:s}=r;return function(l){const a=this[s];t.call(this,l),this.requestUpdate(s,a,e)}}throw Error("Unsupported decorator location: "+n)};function S(e){return(t,r)=>typeof r=="object"?Ws(e,t,r):((n,o,i)=>{const s=o.hasOwnProperty(i);return o.constructor.createProperty(i,s?{...n,wrapped:!0}:n),s?Object.getOwnPropertyDescriptor(o,i):void 0})(e,t,r)}/**
- * @license
- * Copyright 2017 Google LLC
- * SPDX-License-Identifier: BSD-3-Clause
- */function Zr(e){return S({...e,state:!0,attribute:!1})}/**
- * @license
- * Copyright 2017 Google LLC
- * SPDX-License-Identifier: BSD-3-Clause
- */const Ks=(e,t,r)=>(r.configurable=!0,r.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,r),r);/**
- * @license
- * Copyright 2017 Google LLC
- * SPDX-License-Identifier: BSD-3-Clause
- */function Zs(e,t){return(r,n,o)=>{const i=s=>s.renderRoot?.querySelector(e)??null;return Ks(r,n,{get(){return i(this)}})}}function Fn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function _o(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function Gs(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Fn(e.outputLen),Fn(e.blockLen)}function Re(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Js(e,t){_o(e);const r=t.outputLen;if(e.lengthe instanceof Uint8Array,dr=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),ot=(e,t)=>e<<32-t|e>>>t,Ys=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ys)throw new Error("Non little-endian hardware is not supported");function Xs(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Gr(e){if(typeof e=="string"&&(e=Xs(e)),!$o(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function Qs(...e){const t=new Uint8Array(e.reduce((n,o)=>n+o.length,0));let r=0;return e.forEach(n=>{if(!$o(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}let Ao=class{clone(){return this._cloneInto()}};function ta(e){const t=n=>e().update(Gr(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function So(e=32){if(cr&&typeof cr.getRandomValues=="function")return cr.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function ea(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),l=Number(r&i),a=n?4:0,c=n?0:4;e.setUint32(t+a,s,n),e.setUint32(t+c,l,n)}let ra=class extends Ao{constructor(t,r,n,o){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=dr(this.buffer)}update(t){Re(this);const{view:r,buffer:n,blockLen:o}=this;t=Gr(t);const i=t.length;for(let s=0;so-s&&(this.process(n,0),s=0);for(let d=s;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;de&t^~e&r,oa=(e,t,r)=>e&t^e&r^t&r,ia=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),At=new Uint32Array(64);let sa=class extends ra{constructor(){super(64,32,8,!1),this.A=$t[0]|0,this.B=$t[1]|0,this.C=$t[2]|0,this.D=$t[3]|0,this.E=$t[4]|0,this.F=$t[5]|0,this.G=$t[6]|0,this.H=$t[7]|0}get(){const{A:t,B:r,C:n,D:o,E:i,F:s,G:l,H:a}=this;return[t,r,n,o,i,s,l,a]}set(t,r,n,o,i,s,l,a){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=l|0,this.H=a|0}process(t,r){for(let d=0;d<16;d++,r+=4)At[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){const m=At[d-15],g=At[d-2],p=ot(m,7)^ot(m,18)^m>>>3,h=ot(g,17)^ot(g,19)^g>>>10;At[d]=h+At[d-7]+p+At[d-16]|0}let{A:n,B:o,C:i,D:s,E:l,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){const m=ot(l,6)^ot(l,11)^ot(l,25),g=u+m+na(l,a,c)+ia[d]+At[d]|0,h=(ot(n,2)^ot(n,13)^ot(n,22))+oa(n,o,i)|0;u=c,c=a,a=l,l=s+g|0,s=i,i=o,o=n,n=g+h|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,l=l+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,o,i,s,l,a,c,u)}roundClean(){At.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const kr=ta(()=>new sa);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ko=BigInt(0),je=BigInt(1),aa=BigInt(2),Fe=e=>e instanceof Uint8Array,la=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ee(e){if(!Fe(e))throw new Error("Uint8Array expected");let t="";for(let r=0;rn+o.length,0));let r=0;return e.forEach(n=>{if(!Fe(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}function da(e,t){if(e.length!==t.length)return!1;for(let r=0;rko;e>>=je,t+=1);return t}function fa(e,t){return e>>BigInt(t)&je}const pa=(e,t,r)=>e|(r?je:ko)<(aa<new Uint8Array(e),Wn=e=>Uint8Array.from(e);function Co(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=ur(e),o=ur(e),i=0;const s=()=>{n.fill(1),o.fill(0),i=0},l=(...d)=>r(o,n,...d),a=(d=ur())=>{o=l(Wn([0]),d),n=l(),d.length!==0&&(o=l(Wn([1]),d),n=l())},c=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const m=[];for(;d{s(),a(d);let g;for(;!(g=m(c()));)a();return s(),g}}const ga={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function Ae(e,t,r={}){const n=(o,i,s)=>{const l=ga[i];if(typeof l!="function")throw new Error(`Invalid validator "${i}", expected function`);const a=e[o];if(!(s&&a===void 0)&&!l(a,e))throw new Error(`Invalid param ${String(o)}=${a} (${typeof a}), expected ${i}`)};for(const[o,i]of Object.entries(t))n(o,i,!1);for(const[o,i]of Object.entries(r))n(o,i,!0);return e}const ba=Object.freeze(Object.defineProperty({__proto__:null,bitGet:fa,bitLen:ha,bitMask:Qr,bitSet:pa,bytesToHex:ee,bytesToNumberBE:X,bytesToNumberLE:Yr,concatBytes:Ft,createHmacDrbg:Co,ensureBytes:Z,equalBytes:da,hexToBytes:re,hexToNumber:Jr,numberToBytesBE:Tt,numberToBytesLE:Xr,numberToHexUnpadded:Po,numberToVarBytesBE:ca,utf8ToBytes:ua,validateObject:Ae},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const W=BigInt(0),j=BigInt(1),Ht=BigInt(2),ma=BigInt(3),Pr=BigInt(4),Kn=BigInt(5),Zn=BigInt(8);BigInt(9);BigInt(16);function K(e,t){const r=e%t;return r>=W?r:t+r}function ya(e,t,r){if(r<=W||t 0");if(r===j)return W;let n=j;for(;t>W;)t&j&&(n=n*e%r),e=e*e%r,t>>=j;return n}function Q(e,t,r){let n=e;for(;t-- >W;)n*=n,n%=r;return n}function Cr(e,t){if(e===W||t<=W)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=K(e,t),n=t,o=W,i=j;for(;r!==W;){const l=n/r,a=n%r,c=o-i*l;n=r,r=a,o=i,i=c}if(n!==j)throw new Error("invert: does not exist");return K(o,t)}function wa(e){const t=(e-j)/Ht;let r,n,o;for(r=e-j,n=0;r%Ht===W;r/=Ht,n++);for(o=Ht;o(n[o]="function",n),t);return Ae(e,r)}function _a(e,t,r){if(r 0");if(r===W)return e.ONE;if(r===j)return t;let n=e.ONE,o=t;for(;r>W;)r&j&&(n=e.mul(n,o)),o=e.sqr(o),r>>=j;return n}function $a(e,t){const r=new Array(t.length),n=t.reduce((i,s,l)=>e.is0(s)?i:(r[l]=i,e.mul(i,s)),e.ONE),o=e.inv(n);return t.reduceRight((i,s,l)=>e.is0(s)?i:(r[l]=e.mul(i,r[l]),e.mul(i,s)),o),r}function Bo(e,t){const r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Aa(e,t,r=!1,n={}){if(e<=W)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:o,nByteLength:i}=Bo(e,t);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const s=va(e),l=Object.freeze({ORDER:e,BITS:o,BYTES:i,MASK:Qr(o),ZERO:W,ONE:j,create:a=>K(a,e),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return W<=a&&aa===W,isOdd:a=>(a&j)===j,neg:a=>K(-a,e),eql:(a,c)=>a===c,sqr:a=>K(a*a,e),add:(a,c)=>K(a+c,e),sub:(a,c)=>K(a-c,e),mul:(a,c)=>K(a*c,e),pow:(a,c)=>_a(l,a,c),div:(a,c)=>K(a*Cr(c,e),e),sqrN:a=>a*a,addN:(a,c)=>a+c,subN:(a,c)=>a-c,mulN:(a,c)=>a*c,inv:a=>Cr(a,e),sqrt:n.sqrt||(a=>s(l,a)),invertBatch:a=>$a(l,a),cmov:(a,c,u)=>u?c:a,toBytes:a=>r?Xr(a,i):Tt(a,i),fromBytes:a=>{if(a.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${a.length}`);return r?Yr(a):X(a)}});return Object.freeze(l)}function Lo(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Uo(e){const t=Lo(e);return t+Math.ceil(t/2)}function Sa(e,t,r=!1){const n=e.length,o=Lo(t),i=Uo(t);if(n<16||n1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);const s=r?X(e):Yr(e),l=K(s,t-j)+j;return r?Xr(l,o):Tt(l,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ka=BigInt(0),hr=BigInt(1);function Pa(e,t){const r=(o,i)=>{const s=i.negate();return o?s:i},n=o=>{const i=Math.ceil(t/o)+1,s=2**(o-1);return{windows:i,windowSize:s}};return{constTimeNegate:r,unsafeLadder(o,i){let s=e.ZERO,l=o;for(;i>ka;)i&hr&&(s=s.add(l)),l=l.double(),i>>=hr;return s},precomputeWindow(o,i){const{windows:s,windowSize:l}=n(i),a=[];let c=o,u=c;for(let d=0;d>=g,f>a&&(f-=m,s+=hr);const b=h,x=h+Math.abs(f)-1,A=p%2!==0,U=f<0;f===0?u=u.add(r(A,i[b])):c=c.add(r(U,i[x]))}return{p:c,f:u}},wNAFCached(o,i,s,l){const a=o._WINDOW_SIZE||1;let c=i.get(o);return c||(c=this.precomputeWindow(o,a),a!==1&&i.set(o,l(c))),this.wNAF(a,c,s)}}}function To(e){return Ea(e.Fp),Ae(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Bo(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ca(e){const t=To(e);Ae(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:Ba,hexToBytes:La}=ba,Dt={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=Dt;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");const r=e[1],n=e.subarray(2,r+2);if(!r||n.length!==r)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:Ba(n),l:e.subarray(r+2)}},toSig(e){const{Err:t}=Dt,r=typeof e=="string"?La(e):e;if(!(r instanceof Uint8Array))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new t("Invalid signature tag");if(r[1]!==n-2)throw new t("Invalid signature: incorrect length");const{d:o,l:i}=Dt._parseInt(r.subarray(2)),{d:s,l}=Dt._parseInt(i);if(l.length)throw new t("Invalid signature: left bytes after parsing");return{r:o,s}},hexFromSig(e){const t=c=>Number.parseInt(c[0],16)&8?"00"+c:c,r=c=>{const u=c.toString(16);return u.length&1?`0${u}`:u},n=t(r(e.s)),o=t(r(e.r)),i=n.length/2,s=o.length/2,l=r(i),a=r(s);return`30${r(s+i+4)}02${a}${o}02${l}${n}`}},ht=BigInt(0),tt=BigInt(1);BigInt(2);const Gn=BigInt(3);BigInt(4);function Ua(e){const t=Ca(e),{Fp:r}=t,n=t.toBytes||((p,h,f)=>{const b=h.toAffine();return Ft(Uint8Array.from([4]),r.toBytes(b.x),r.toBytes(b.y))}),o=t.fromBytes||(p=>{const h=p.subarray(1),f=r.fromBytes(h.subarray(0,r.BYTES)),b=r.fromBytes(h.subarray(r.BYTES,2*r.BYTES));return{x:f,y:b}});function i(p){const{a:h,b:f}=t,b=r.sqr(p),x=r.mul(b,p);return r.add(r.add(x,r.mul(p,h)),f)}if(!r.eql(r.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function s(p){return typeof p=="bigint"&&ht r.eql(A,r.ZERO);return x(f)&&x(b)?d.ZERO:new d(f,b,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){const f=r.invertBatch(h.map(b=>b.pz));return h.map((b,x)=>b.toAffine(f[x])).map(d.fromAffine)}static fromHex(h){const f=d.fromAffine(o(Z("pointHex",h)));return f.assertValidity(),f}static fromPrivateKey(h){return d.BASE.multiply(a(h))}_setWindowSize(h){this._WINDOW_SIZE=h,c.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:h,y:f}=this.toAffine();if(!r.isValid(h)||!r.isValid(f))throw new Error("bad point: x or y not FE");const b=r.sqr(f),x=i(h);if(!r.eql(b,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:h}=this.toAffine();if(r.isOdd)return!r.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){u(h);const{px:f,py:b,pz:x}=this,{px:A,py:U,pz:C}=h,v=r.eql(r.mul(f,C),r.mul(A,x)),E=r.eql(r.mul(b,C),r.mul(U,x));return v&&E}negate(){return new d(this.px,r.neg(this.py),this.pz)}double(){const{a:h,b:f}=t,b=r.mul(f,Gn),{px:x,py:A,pz:U}=this;let C=r.ZERO,v=r.ZERO,E=r.ZERO,_=r.mul(x,x),V=r.mul(A,A),L=r.mul(U,U),k=r.mul(x,A);return k=r.add(k,k),E=r.mul(x,U),E=r.add(E,E),C=r.mul(h,E),v=r.mul(b,L),v=r.add(C,v),C=r.sub(V,v),v=r.add(V,v),v=r.mul(C,v),C=r.mul(k,C),E=r.mul(b,E),L=r.mul(h,L),k=r.sub(_,L),k=r.mul(h,k),k=r.add(k,E),E=r.add(_,_),_=r.add(E,_),_=r.add(_,L),_=r.mul(_,k),v=r.add(v,_),L=r.mul(A,U),L=r.add(L,L),_=r.mul(L,k),C=r.sub(C,_),E=r.mul(L,V),E=r.add(E,E),E=r.add(E,E),new d(C,v,E)}add(h){u(h);const{px:f,py:b,pz:x}=this,{px:A,py:U,pz:C}=h;let v=r.ZERO,E=r.ZERO,_=r.ZERO;const V=t.a,L=r.mul(t.b,Gn);let k=r.mul(f,A),O=r.mul(b,U),H=r.mul(x,C),D=r.add(f,b),y=r.add(A,U);D=r.mul(D,y),y=r.add(k,O),D=r.sub(D,y),y=r.add(f,x);let w=r.add(A,C);return y=r.mul(y,w),w=r.add(k,H),y=r.sub(y,w),w=r.add(b,x),v=r.add(U,C),w=r.mul(w,v),v=r.add(O,H),w=r.sub(w,v),_=r.mul(V,y),v=r.mul(L,H),_=r.add(v,_),v=r.sub(O,_),_=r.add(O,_),E=r.mul(v,_),O=r.add(k,k),O=r.add(O,k),H=r.mul(V,H),y=r.mul(L,y),O=r.add(O,H),H=r.sub(k,H),H=r.mul(V,H),y=r.add(y,H),k=r.mul(O,y),E=r.add(E,k),k=r.mul(w,y),v=r.mul(D,v),v=r.sub(v,k),k=r.mul(D,O),_=r.mul(w,_),_=r.add(_,k),new d(v,E,_)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return g.wNAFCached(this,c,h,f=>{const b=r.invertBatch(f.map(x=>x.pz));return f.map((x,A)=>x.toAffine(b[A])).map(d.fromAffine)})}multiplyUnsafe(h){const f=d.ZERO;if(h===ht)return f;if(l(h),h===tt)return this;const{endo:b}=t;if(!b)return g.unsafeLadder(this,h);let{k1neg:x,k1:A,k2neg:U,k2:C}=b.splitScalar(h),v=f,E=f,_=this;for(;A>ht||C>ht;)A&tt&&(v=v.add(_)),C&tt&&(E=E.add(_)),_=_.double(),A>>=tt,C>>=tt;return x&&(v=v.negate()),U&&(E=E.negate()),E=new d(r.mul(E.px,b.beta),E.py,E.pz),v.add(E)}multiply(h){l(h);let f=h,b,x;const{endo:A}=t;if(A){const{k1neg:U,k1:C,k2neg:v,k2:E}=A.splitScalar(f);let{p:_,f:V}=this.wNAF(C),{p:L,f:k}=this.wNAF(E);_=g.constTimeNegate(U,_),L=g.constTimeNegate(v,L),L=new d(r.mul(L.px,A.beta),L.py,L.pz),b=_.add(L),x=V.add(k)}else{const{p:U,f:C}=this.wNAF(f);b=U,x=C}return d.normalizeZ([b,x])[0]}multiplyAndAddUnsafe(h,f,b){const x=d.BASE,A=(C,v)=>v===ht||v===tt||!C.equals(x)?C.multiplyUnsafe(v):C.multiply(v),U=A(this,f).add(A(h,b));return U.is0()?void 0:U}toAffine(h){const{px:f,py:b,pz:x}=this,A=this.is0();h==null&&(h=A?r.ONE:r.inv(x));const U=r.mul(f,h),C=r.mul(b,h),v=r.mul(x,h);if(A)return{x:r.ZERO,y:r.ZERO};if(!r.eql(v,r.ONE))throw new Error("invZ was invalid");return{x:U,y:C}}isTorsionFree(){const{h,isTorsionFree:f}=t;if(h===tt)return!0;if(f)return f(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h,clearCofactor:f}=t;return h===tt?this:f?f(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return this.assertValidity(),n(d,this,h)}toHex(h=!0){return ee(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,r.ONE),d.ZERO=new d(r.ZERO,r.ONE,r.ZERO);const m=t.nBitLength,g=Pa(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:a,weierstrassEquation:i,isWithinCurveOrder:s}}function Ta(e){const t=To(e);return Ae(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Ia(e){const t=Ta(e),{Fp:r,n}=t,o=r.BYTES+1,i=2*r.BYTES+1;function s(y){return htee(Tt(y,t.nByteLength));function p(y){const w=n>>tt;return y>w}function h(y){return p(y)?l(-y):y}const f=(y,w,$)=>X(y.slice(w,$));class b{constructor(w,$,B){this.r=w,this.s=$,this.recovery=B,this.assertValidity()}static fromCompact(w){const $=t.nByteLength;return w=Z("compactSignature",w,$*2),new b(f(w,0,$),f(w,$,2*$))}static fromDER(w){const{r:$,s:B}=Dt.toSig(Z("DER",w));return new b($,B)}assertValidity(){if(!m(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!m(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(w){return new b(this.r,this.s,w)}recoverPublicKey(w){const{r:$,s:B,recovery:P}=this,I=E(Z("msgHash",w));if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");const z=P===2||P===3?$+t.n:$;if(z>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const R=P&1?"03":"02",et=c.fromHex(R+g(z)),Et=a(z),Kt=l(-I*Et),ce=l(B*Et),_t=c.BASE.multiplyAndAddUnsafe(et,Kt,ce);if(!_t)throw new Error("point at infinify");return _t.assertValidity(),_t}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new b(this.r,l(-this.s),this.recovery):this}toDERRawBytes(){return re(this.toDERHex())}toDERHex(){return Dt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return re(this.toCompactHex())}toCompactHex(){return g(this.r)+g(this.s)}}const x={isValidPrivateKey(y){try{return u(y),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const y=Uo(t.n);return Sa(t.randomBytes(y),t.n)},precompute(y=8,w=c.BASE){return w._setWindowSize(y),w.multiply(BigInt(3)),w}};function A(y,w=!0){return c.fromPrivateKey(y).toRawBytes(w)}function U(y){const w=y instanceof Uint8Array,$=typeof y=="string",B=(w||$)&&y.length;return w?B===o||B===i:$?B===2*o||B===2*i:y instanceof c}function C(y,w,$=!0){if(U(y))throw new Error("first arg must be private key");if(!U(w))throw new Error("second arg must be public key");return c.fromHex(w).multiply(u(y)).toRawBytes($)}const v=t.bits2int||function(y){const w=X(y),$=y.length*8-t.nBitLength;return $>0?w>>BigInt($):w},E=t.bits2int_modN||function(y){return l(v(y))},_=Qr(t.nBitLength);function V(y){if(typeof y!="bigint")throw new Error("bigint expected");if(!(ht<=y&&y<_))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Tt(y,t.nByteLength)}function L(y,w,$=k){if(["recovered","canonical"].some(Nt=>Nt in $))throw new Error("sign() legacy options not supported");const{hash:B,randomBytes:P}=t;let{lowS:I,prehash:z,extraEntropy:R}=$;I==null&&(I=!0),y=Z("msgHash",y),z&&(y=Z("prehashed msgHash",B(y)));const et=E(y),Et=u(w),Kt=[V(Et),V(et)];if(R!=null){const Nt=R===!0?P(r.BYTES):R;Kt.push(Z("extraEntropy",Nt))}const ce=Ft(...Kt),_t=et;function ar(Nt){const Zt=v(Nt);if(!m(Zt))return;const Bn=a(Zt),nt=c.BASE.multiply(Zt).toAffine(),Gt=l(nt.x);if(Gt===ht)return;const Se=l(Bn*l(_t+Gt*Et));if(Se===ht)return;let Ln=(nt.x===Gt?0:2)|Number(nt.y&tt),Un=Se;return I&&p(Se)&&(Un=h(Se),Ln^=1),new b(Gt,Un,Ln)}return{seed:ce,k2sig:ar}}const k={lowS:t.lowS,prehash:!1},O={lowS:t.lowS,prehash:!1};function H(y,w,$=k){const{seed:B,k2sig:P}=L(y,w,$),I=t;return Co(I.hash.outputLen,I.nByteLength,I.hmac)(B,P)}c.BASE._setWindowSize(8);function D(y,w,$,B=O){const P=y;if(w=Z("msgHash",w),$=Z("publicKey",$),"strict"in B)throw new Error("options.strict was renamed to lowS");const{lowS:I,prehash:z}=B;let R,et;try{if(typeof P=="string"||P instanceof Uint8Array)try{R=b.fromDER(P)}catch(nt){if(!(nt instanceof Dt.Err))throw nt;R=b.fromCompact(P)}else if(typeof P=="object"&&typeof P.r=="bigint"&&typeof P.s=="bigint"){const{r:nt,s:Gt}=P;R=new b(nt,Gt)}else throw new Error("PARSE");et=c.fromHex($)}catch(nt){if(nt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(I&&R.hasHighS())return!1;z&&(w=t.hash(w));const{r:Et,s:Kt}=R,ce=E(w),_t=a(Kt),ar=l(ce*_t),Nt=l(Et*_t),Zt=c.BASE.multiplyAndAddUnsafe(et,ar,Nt)?.toAffine();return Zt?l(Zt.x)===Et:!1}return{CURVE:t,getPublicKey:A,getSharedSecret:C,sign:H,verify:D,ProjectivePoint:c,Signature:b,utils:x}}let Io=class extends Ao{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,Gs(t);const n=Gr(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?t.create().update(n).digest():n);for(let s=0;snew Io(e,t).update(r).digest();Mo.create=(e,t)=>new Io(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ma(e){return{hash:e,hmac:(t,...r)=>Mo(e,t,Qs(...r)),randomBytes:So}}function Ra(e,t){const r=n=>Ia({...e,...Ma(n)});return Object.freeze({...r(t),create:r})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const We=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Ne=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ro=BigInt(1),Oe=BigInt(2),Jn=(e,t)=>(e+t/Oe)/t;function No(e){const t=We,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),l=BigInt(44),a=BigInt(88),c=e*e*e%t,u=c*c*e%t,d=Q(u,r,t)*u%t,m=Q(d,r,t)*u%t,g=Q(m,Oe,t)*c%t,p=Q(g,o,t)*g%t,h=Q(p,i,t)*p%t,f=Q(h,l,t)*h%t,b=Q(f,a,t)*f%t,x=Q(b,l,t)*h%t,A=Q(x,r,t)*u%t,U=Q(A,s,t)*p%t,C=Q(U,n,t)*c%t,v=Q(C,Oe,t);if(!Br.eql(Br.sqr(v),e))throw new Error("Cannot find square root");return v}const Br=Aa(We,void 0,void 0,{sqrt:No}),se=Ra({a:BigInt(0),b:BigInt(7),Fp:Br,n:Ne,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Ne,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Ro*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,s=BigInt("0x100000000000000000000000000000000"),l=Jn(i*e,t),a=Jn(-n*e,t);let c=K(e-l*r-a*o,t),u=K(-l*n-a*i,t);const d=c>s,m=u>s;if(d&&(c=t-c),m&&(u=t-u),c>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:c,k2neg:m,k2:u}}}},kr),Ke=BigInt(0),Oo=e=>typeof e=="bigint"&&Ketypeof e=="bigint"&&Keo.charCodeAt(0)));r=Ft(n,n),Yn[e]=r}return kr(Ft(r,...t))}const tn=e=>e.toRawBytes(!0).slice(1),Lr=e=>Tt(e,32),fr=e=>K(e,We),xe=e=>K(e,Ne),en=se.ProjectivePoint,Oa=(e,t,r)=>en.BASE.multiplyAndAddUnsafe(e,t,r);function Ur(e){let t=se.utils.normPrivateKeyToScalar(e),r=en.fromPrivateKey(t);return{scalar:r.hasEvenY()?t:xe(-t),bytes:tn(r)}}function Ho(e){if(!Oo(e))throw new Error("bad x: need 0 < x < p");const t=fr(e*e),r=fr(t*e+BigInt(7));let n=No(r);n%Oe!==Ke&&(n=fr(-n));const o=new en(e,n,Ro);return o.assertValidity(),o}function zo(...e){return xe(X(He("BIP0340/challenge",...e)))}function Ha(e){return Ur(e).bytes}function za(e,t,r=So(32)){const n=Z("message",e),{bytes:o,scalar:i}=Ur(t),s=Z("auxRand",r,32),l=Lr(i^X(He("BIP0340/aux",s))),a=He("BIP0340/nonce",l,o,n),c=xe(X(a));if(c===Ke)throw new Error("sign failed: k is zero");const{bytes:u,scalar:d}=Ur(c),m=zo(u,o,n),g=new Uint8Array(64);if(g.set(u,0),g.set(Lr(xe(d+m*i)),32),!Vo(g,n,o))throw new Error("sign: Invalid signature produced");return g}function Vo(e,t,r){const n=Z("signature",e,64),o=Z("message",t),i=Z("publicKey",r,32);try{const s=Ho(X(i)),l=X(n.subarray(0,32));if(!Oo(l))return!1;const a=X(n.subarray(32,64));if(!Na(a))return!1;const c=zo(Lr(l),tn(s),o),u=Oa(s,a,xe(-c));return!(!u||!u.hasEvenY()||u.toAffine().x!==l)}catch{return!1}}const ue={getPublicKey:Ha,sign:za,verify:Vo,utils:{randomPrivateKey:se.utils.randomPrivateKey,lift_x:Ho,pointToBytes:tn,numberToBytesBE:Tt,bytesToNumberBE:X,taggedHash:He,mod:K}},pr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const rn=e=>e instanceof Uint8Array,gr=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),it=(e,t)=>e<<32-t|e>>>t,Va=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Va)throw new Error("Non little-endian hardware is not supported");const Da=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Y(e){if(!rn(e))throw new Error("Uint8Array expected");let t="";for(let r=0;rn+o.length,0));let r=0;return e.forEach(n=>{if(!rn(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}class Do{clone(){return this._cloneInto()}}function qo(e){const t=n=>e().update(Ee(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function jo(e=32){if(pr&&typeof pr.getRandomValues=="function")return pr.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function Tr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function ja(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function Fo(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function Fa(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Tr(e.outputLen),Tr(e.blockLen)}function Wa(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ka(e,t){Fo(e);const r=t.outputLen;if(e.length>o&i),l=Number(r&i),a=n?4:0,c=n?0:4;e.setUint32(t+a,s,n),e.setUint32(t+c,l,n)}class Ga extends Do{constructor(t,r,n,o){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=gr(this.buffer)}update(t){st.exists(this);const{view:r,buffer:n,blockLen:o}=this;t=Ee(t);const i=t.length;for(let s=0;so-s&&(this.process(n,0),s=0);for(let d=s;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;de&t^~e&r,Ya=(e,t,r)=>e&t^e&r^t&r,Xa=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),St=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),kt=new Uint32Array(64);class Wo extends Ga{constructor(){super(64,32,8,!1),this.A=St[0]|0,this.B=St[1]|0,this.C=St[2]|0,this.D=St[3]|0,this.E=St[4]|0,this.F=St[5]|0,this.G=St[6]|0,this.H=St[7]|0}get(){const{A:t,B:r,C:n,D:o,E:i,F:s,G:l,H:a}=this;return[t,r,n,o,i,s,l,a]}set(t,r,n,o,i,s,l,a){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=l|0,this.H=a|0}process(t,r){for(let d=0;d<16;d++,r+=4)kt[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){const m=kt[d-15],g=kt[d-2],p=it(m,7)^it(m,18)^m>>>3,h=it(g,17)^it(g,19)^g>>>10;kt[d]=h+kt[d-7]+p+kt[d-16]|0}let{A:n,B:o,C:i,D:s,E:l,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){const m=it(l,6)^it(l,11)^it(l,25),g=u+m+Ja(l,a,c)+Xa[d]+kt[d]|0,h=(it(n,2)^it(n,13)^it(n,22))+Ya(n,o,i)|0;u=c,c=a,a=l,l=s+g|0,s=i,i=o,o=n,n=g+h|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,l=l+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,o,i,s,l,a,c,u)}roundClean(){kt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class Qa extends Wo{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const ae=qo(()=>new Wo);qo(()=>new Qa);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function le(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function yt(...e){const t=(o,i)=>s=>o(i(s)),r=Array.from(e).reverse().reduce((o,i)=>o?t(o,i.encode):i.encode,void 0),n=e.reduce((o,i)=>o?t(o,i.decode):i.decode,void 0);return{encode:r,decode:n}}function wt(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return t.map(r=>{if(le(r),r<0||r>=e.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${e.length})`);return e[r]})},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("alphabet.decode input should be array of strings");return t.map(r=>{if(typeof r!="string")throw new Error(`alphabet.decode: not string element=${r}`);const n=e.indexOf(r);if(n===-1)throw new Error(`Unknown letter: "${r}". Allowed: ${e}`);return n})}}}function vt(e=""){if(typeof e!="string")throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("join.encode input should be array of strings");for(let r of t)if(typeof r!="string")throw new Error(`join.encode: non-string input=${r}`);return t.join(e)},decode:t=>{if(typeof t!="string")throw new Error("join.decode input should be string");return t.split(e)}}}function Ge(e,t="="){if(le(e),typeof t!="string")throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let n of r)if(typeof n!="string")throw new Error(`padding.encode: non-string input=${n}`);for(;r.length*e%8;)r.push(t);return r},decode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let o of r)if(typeof o!="string")throw new Error(`padding.decode: non-string input=${o}`);let n=r.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===t;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function Ko(e){if(typeof e!="function")throw new Error("normalize fn should be function");return{encode:t=>t,decode:t=>e(t)}}function Xn(e,t,r){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: wrong to=${r}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let n=0;const o=[],i=Array.from(e);for(i.forEach(s=>{if(le(s),s<0||s>=t)throw new Error(`Wrong integer: ${s}`)});;){let s=0,l=!0;for(let a=n;at?Zo(t,e%t):e,ze=(e,t)=>e+(t-Zo(e,t));function Ir(e,t,r,n){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(ze(t,r)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${ze(t,r)}`);let o=0,i=0;const s=2**r-1,l=[];for(const a of e){if(le(a),a>=2**t)throw new Error(`convertRadix2: invalid data word=${a} from=${t}`);if(o=o<32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${t}`);for(i+=t;i>=r;i-=r)l.push((o>>i-r&s)>>>0);o&=2**i-1}if(o=o<=t)throw new Error("Excess padding");if(!n&&o)throw new Error(`Non-zero padding: ${o}`);return n&&i>0&&l.push(o>>>0),l}function tl(e){return le(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return Xn(Array.from(t),2**8,e)},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(Xn(t,e,2**8))}}}function It(e,t=!1){if(le(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(ze(8,e)>32||ze(e,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return Ir(Array.from(r),8,e,!t)},decode:r=>{if(!Array.isArray(r)||r.length&&typeof r[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(Ir(r,e,8,t))}}}function Qn(e){if(typeof e!="function")throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch{}}}const el=yt(It(4),wt("0123456789ABCDEF"),vt("")),rl=yt(It(5),wt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Ge(5),vt(""));yt(It(5),wt("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Ge(5),vt(""));yt(It(5),wt("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),vt(""),Ko(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const bt=yt(It(6),wt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Ge(6),vt("")),nl=yt(It(6),wt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Ge(6),vt("")),nn=e=>yt(tl(58),wt(e),vt("")),Mr=nn("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");nn("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");nn("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const to=[0,2,3,5,6,7,9,10,11],ol={encode(e){let t="";for(let r=0;r>25;let r=(e&33554431)<<5;for(let n=0;n>n&1)===1&&(r^=eo[n]);return r}function ro(e,t,r=1){const n=e.length;let o=1;for(let i=0;i126)throw new Error(`Invalid prefix (${e})`);o=he(o)^s>>5}o=he(o);for(let i=0;im)throw new TypeError(`Length ${g} exceeds limit ${m}`);return u=u.toLowerCase(),`${u}1${Rr.encode(d)}${ro(u,d,t)}`}function l(u,d=90){if(typeof u!="string")throw new Error(`bech32.decode input should be string, not ${typeof u}`);if(u.length<8||d!==!1&&u.length>d)throw new TypeError(`Wrong string length: ${u.length} (${u}). Expected (8..${d})`);const m=u.toLowerCase();if(u!==m&&u!==u.toUpperCase())throw new Error("String must be lowercase or uppercase");u=m;const g=u.lastIndexOf("1");if(g===0||g===-1)throw new Error('Letter "1" must be present between prefix and data only');const p=u.slice(0,g),h=u.slice(g+1);if(h.length<6)throw new Error("Data must be at least 6 characters long");const f=Rr.decode(h).slice(0,-6),b=ro(p,f,t);if(!h.endsWith(b))throw new Error(`Invalid checksum in ${u}: expected "${b}"`);return{prefix:p,words:f}}const a=Qn(l);function c(u){const{prefix:d,words:m}=l(u,!1);return{prefix:d,words:m,bytes:n(m)}}return{encode:s,decode:l,decodeToBytes:c,decodeUnsafe:a,fromWords:n,fromWordsUnsafe:i,toWords:o}}const oe=Go("bech32");Go("bech32m");const il={encode:e=>new TextDecoder().decode(e),decode:e=>new TextEncoder().encode(e)},sl=yt(It(4),wt("0123456789abcdef"),vt(""),Ko(e=>{if(typeof e!="string"||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})),al={utf8:il,hex:sl,base16:el,base32:rl,base64:bt,base64url:nl,base58:Mr,base58xmr:ol};`${Object.keys(al).join(", ")}`;function br(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function no(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function ll(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function ft(e,...t){if(!ll(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const J=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),cl=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!cl)throw new Error("Non little-endian hardware is not supported");function dl(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function ul(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n(Object.assign(t,e),t),Ut=16,fl=283;function on(e){return e<<1^fl&-(e>>7)}function Xt(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(t&1),e=on(e);return r}const Nr=(()=>{let e=new Uint8Array(256);for(let r=0,n=1;r<256;r++,n^=on(n))e[r]=n;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let n=e[255-r];n|=n<<8,t[e[r]]=(n^n>>4^n>>5^n>>6^n>>7^99)&255}return t})(),pl=Nr.map((e,t)=>Nr.indexOf(t)),gl=e=>e<<24|e>>>8,mr=e=>e<<8|e>>>24;function Jo(e,t){if(e.length!==256)throw new Error("Wrong sbox length");const r=new Uint32Array(256).map((c,u)=>t(e[u])),n=r.map(mr),o=n.map(mr),i=o.map(mr),s=new Uint32Array(256*256),l=new Uint32Array(256*256),a=new Uint16Array(256*256);for(let c=0;c<256;c++)for(let u=0;u<256;u++){const d=c*256+u;s[d]=r[c]^n[u],l[d]=o[c]^i[u],a[d]=e[c]<<8|e[u]}return{sbox:e,sbox2:a,T0:r,T1:n,T2:o,T3:i,T01:s,T23:l}}const sn=Jo(Nr,e=>Xt(e,3)<<24|e<<16|e<<8|Xt(e,2)),Yo=Jo(pl,e=>Xt(e,11)<<24|Xt(e,13)<<16|Xt(e,9)<<8|Xt(e,14)),bl=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=on(r))e[t]=r;return e})();function Xo(e){ft(e);const t=e.length;if(![16,24,32].includes(t))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${t}`);const{sbox2:r}=sn,n=J(e),o=n.length,i=l=>at(r,l,l,l,l),s=new Uint32Array(t+28);s.set(n);for(let l=o;l6&&l%o===4&&(a=i(a)),s[l]=s[l-o]^a}return s}function ml(e){const t=Xo(e),r=t.slice(),n=t.length,{sbox2:o}=sn,{T0:i,T1:s,T2:l,T3:a}=Yo;for(let c=0;c>>8&255]^l[d>>>16&255]^a[d>>>24]}return r}function Bt(e,t,r,n,o,i){return e[r<<8&65280|n>>>8&255]^t[o>>>8&65280|i>>>24&255]}function at(e,t,r,n,o){return e[t&255|r&65280]|e[n>>>16&255|o>>>16&65280]<<16}function oo(e,t,r,n,o){const{sbox2:i,T01:s,T23:l}=sn;let a=0;t^=e[a++],r^=e[a++],n^=e[a++],o^=e[a++];const c=e.length/4-2;for(let p=0;p16)throw new Error(`aes/pcks5: wrong padding byte: ${n}`);const o=e.subarray(0,-n);for(let i=0;i{const l=Xo(t),{b:a,o:c,out:u}=vl(i,o,s),d=J(r);let m=d[0],g=d[1],p=d[2],h=d[3],f=0;for(;f+4<=a.length;)m^=a[f+0],g^=a[f+1],p^=a[f+2],h^=a[f+3],{s0:m,s1:g,s2:p,s3:h}=oo(l,m,g,p,h),c[f++]=m,c[f++]=g,c[f++]=p,c[f++]=h;if(o){const b=El(i.subarray(f*4));m^=b[0],g^=b[1],p^=b[2],h^=b[3],{s0:m,s1:g,s2:p,s3:h}=oo(l,m,g,p,h),c[f++]=m,c[f++]=g,c[f++]=p,c[f++]=h}return l.fill(0),u},decrypt:(i,s)=>{wl(i);const l=ml(t),a=J(r),c=Qo(i.length,s),u=J(i),d=J(c);let m=a[0],g=a[1],p=a[2],h=a[3];for(let f=0;f+4<=u.length;){const b=m,x=g,A=p,U=h;m=u[f+0],g=u[f+1],p=u[f+2],h=u[f+3];const{s0:C,s1:v,s2:E,s3:_}=yl(l,m,g,p,h);d[f++]=C^b,d[f++]=v^x,d[f++]=E^A,d[f++]=_^U}return l.fill(0),xl(c,o)}}}),ei=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),_l=ei("expand 16-byte k"),$l=ei("expand 32-byte k"),Al=J(_l),ri=J($l);ri.slice();function M(e,t){return e<>>32-t}function Or(e){return e.byteOffset%4===0}const ke=64,Sl=16,ni=2**32-1,io=new Uint32Array;function kl(e,t,r,n,o,i,s,l){const a=o.length,c=new Uint8Array(ke),u=J(c),d=Or(o)&&Or(i),m=d?J(o):io,g=d?J(i):io;for(let p=0;p=ni)throw new Error("arx: counter overflow");const h=Math.min(ke,a-p);if(d&&h===ke){const f=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let b=0,x;b{ft(l),ft(a),ft(c);const m=c.length;if(u||(u=new Uint8Array(m)),ft(u),br(d),d<0||d>=ni)throw new Error("arx: counter overflow");if(u.length0;)g.pop().fill(0);return u}}function Cl(e,t,r,n,o,i=20){let s=e[0],l=e[1],a=e[2],c=e[3],u=t[0],d=t[1],m=t[2],g=t[3],p=t[4],h=t[5],f=t[6],b=t[7],x=o,A=r[0],U=r[1],C=r[2],v=s,E=l,_=a,V=c,L=u,k=d,O=m,H=g,D=p,y=h,w=f,$=b,B=x,P=A,I=U,z=C;for(let et=0;et