"use strict"; var __defProp = Object.defineProperty; var __exportAll = (all, no_symbols) => { let target = {}; for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); __defProp(target, Symbol.toStringTag, { value: "Module" }); return target; }; function OrderedMap(content) { this.content = content; } OrderedMap.prototype = { constructor: OrderedMap, find: function(key) { for (var i = 0; i < this.content.length; i += 2) if (this.content[i] === key) return i; return -1; }, // :: (string) → ?any // Retrieve the value stored under `key`, or return undefined when // no such key exists. get: function(key) { var found2 = this.find(key); return found2 == -1 ? void 0 : this.content[found2 + 1]; }, // :: (string, any, ?string) → OrderedMap // Create a new map by replacing the value of `key` with a new // value, or adding a binding to the end of the map. If `newKey` is // given, the key of the binding will be replaced with that key. update: function(key, value, newKey) { var self = newKey && newKey != key ? this.remove(newKey) : this; var found2 = self.find(key), content = self.content.slice(); if (found2 == -1) { content.push(newKey || key, value); } else { content[found2 + 1] = value; if (newKey) content[found2] = newKey; } return new OrderedMap(content); }, // :: (string) → OrderedMap // Return a map with the given key removed, if it existed. remove: function(key) { var found2 = this.find(key); if (found2 == -1) return this; var content = this.content.slice(); content.splice(found2, 2); return new OrderedMap(content); }, // :: (string, any) → OrderedMap // Add a new key to the start of the map. addToStart: function(key, value) { return new OrderedMap([key, value].concat(this.remove(key).content)); }, // :: (string, any) → OrderedMap // Add a new key to the end of the map. addToEnd: function(key, value) { var content = this.remove(key).content.slice(); content.push(key, value); return new OrderedMap(content); }, // :: (string, string, any) → OrderedMap // Add a key after the given key. If `place` is not found, the new // key is added to the end. addBefore: function(place, key, value) { var without = this.remove(key), content = without.content.slice(); var found2 = without.find(place); content.splice(found2 == -1 ? content.length : found2, 0, key, value); return new OrderedMap(content); }, // :: ((key: string, value: any)) // Call the given function for each key/value pair in the map, in // order. forEach: function(f) { for (var i = 0; i < this.content.length; i += 2) f(this.content[i], this.content[i + 1]); }, // :: (union) → OrderedMap // Create a new map by prepending the keys in this map that don't // appear in `map` before the keys in `map`. prepend: function(map2) { map2 = OrderedMap.from(map2); if (!map2.size) return this; return new OrderedMap(map2.content.concat(this.subtract(map2).content)); }, // :: (union) → OrderedMap // Create a new map by appending the keys in this map that don't // appear in `map` after the keys in `map`. append: function(map2) { map2 = OrderedMap.from(map2); if (!map2.size) return this; return new OrderedMap(this.subtract(map2).content.concat(map2.content)); }, // :: (union) → OrderedMap // Create a map containing all the keys in this map that don't // appear in `map`. subtract: function(map2) { var result = this; map2 = OrderedMap.from(map2); for (var i = 0; i < map2.content.length; i += 2) result = result.remove(map2.content[i]); return result; }, // :: () → Object // Turn ordered map into a plain object. toObject: function() { var result = {}; this.forEach(function(key, value) { result[key] = value; }); return result; }, // :: number // The amount of keys in this map. get size() { return this.content.length >> 1; } }; OrderedMap.from = function(value) { if (value instanceof OrderedMap) return value; var content = []; if (value) for (var prop in value) content.push(prop, value[prop]); return new OrderedMap(content); }; function findDiffStart(a, b, pos) { for (let i = 0; ; i++) { if (i == a.childCount || i == b.childCount) return a.childCount == b.childCount ? null : pos; let childA = a.child(i), childB = b.child(i); if (childA == childB) { pos += childA.nodeSize; continue; } if (!childA.sameMarkup(childB)) return pos; if (childA.isText && childA.text != childB.text) { let tA = childA.text, tB = childB.text, j = 0; for (; tA[j] == tB[j]; j++) pos++; if (j && j < tA.length && j < tB.length && surrogateHigh(tA.charCodeAt(j - 1)) && surrogateLow(tA.charCodeAt(j))) pos--; return pos; } if (childA.content.size || childB.content.size) { let inner = findDiffStart(childA.content, childB.content, pos + 1); if (inner != null) return inner; } pos += childA.nodeSize; } } function findDiffEnd(a, b, posA, posB) { for (let iA = a.childCount, iB = b.childCount; ; ) { if (iA == 0 || iB == 0) return iA == iB ? null : { a: posA, b: posB }; let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize; if (childA == childB) { posA -= size; posB -= size; continue; } if (!childA.sameMarkup(childB)) return { a: posA, b: posB }; if (childA.isText && childA.text != childB.text) { let tA = childA.text, tB = childB.text, iA2 = tA.length, iB2 = tB.length; while (iA2 > 0 && iB2 > 0 && tA[iA2 - 1] == tB[iB2 - 1]) { iA2--; iB2--; posA--; posB--; } if (iA2 && iB2 && iA2 < tA.length && surrogateHigh(tA.charCodeAt(iA2 - 1)) && surrogateLow(tA.charCodeAt(iA2))) { posA++; posB++; } return { a: posA, b: posB }; } if (childA.content.size || childB.content.size) { let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1); if (inner) return inner; } posA -= size; posB -= size; } } function surrogateLow(ch) { return ch >= 56320 && ch < 57344; } function surrogateHigh(ch) { return ch >= 55296 && ch < 56320; } class Fragment { /** @internal */ constructor(content, size) { this.content = content; this.size = size || 0; if (size == null) for (let i = 0; i < content.length; i++) this.size += content[i].nodeSize; } /** Invoke a callback for all descendant nodes between the given two positions (relative to start of this fragment). Doesn't descend into a node when the callback returns `false`. */ nodesBetween(from2, to, f, nodeStart = 0, parent) { for (let i = 0, pos = 0; pos < to; i++) { let child = this.content[i], end = pos + child.nodeSize; if (end > from2 && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) { let start = pos + 1; child.nodesBetween(Math.max(0, from2 - start), Math.min(child.content.size, to - start), f, nodeStart + start); } pos = end; } } /** Call the given callback for every descendant node. `pos` will be relative to the start of the fragment. The callback may return `false` to prevent traversal of a given node's children. */ descendants(f) { this.nodesBetween(0, this.size, f); } /** Extract the text between `from` and `to`. See the same method on [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween). */ textBetween(from2, to, blockSeparator, leafText) { let text = "", first2 = true; this.nodesBetween(from2, to, (node, pos) => { let nodeText = node.isText ? node.text.slice(Math.max(from2, pos) - pos, to - pos) : !node.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node) : leafText : node.type.spec.leafText ? node.type.spec.leafText(node) : ""; if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) { if (first2) first2 = false; else text += blockSeparator; } text += nodeText; }, 0); return text; } /** Create a new fragment containing the combined content of this fragment and the other. */ append(other) { if (!other.size) return this; if (!this.size) return other; let last = this.lastChild, first2 = other.firstChild, content = this.content.slice(), i = 0; if (last.isText && last.sameMarkup(first2)) { content[content.length - 1] = last.withText(last.text + first2.text); i = 1; } for (; i < other.content.length; i++) content.push(other.content[i]); return new Fragment(content, this.size + other.size); } /** Cut out the sub-fragment between the two given positions. */ cut(from2, to = this.size) { if (from2 == 0 && to == this.size) return this; let result = [], size = 0; if (to > from2) for (let i = 0, pos = 0; pos < to; i++) { let child = this.content[i], end = pos + child.nodeSize; if (end > from2) { if (pos < from2 || end > to) { if (child.isText) child = child.cut(Math.max(0, from2 - pos), Math.min(child.text.length, to - pos)); else child = child.cut(Math.max(0, from2 - pos - 1), Math.min(child.content.size, to - pos - 1)); } result.push(child); size += child.nodeSize; } pos = end; } return new Fragment(result, size); } /** @internal */ cutByIndex(from2, to) { if (from2 == to) return Fragment.empty; if (from2 == 0 && to == this.content.length) return this; return new Fragment(this.content.slice(from2, to)); } /** Create a new fragment in which the node at the given index is replaced by the given node. */ replaceChild(index, node) { let current = this.content[index]; if (current == node) return this; let copy2 = this.content.slice(); let size = this.size + node.nodeSize - current.nodeSize; copy2[index] = node; return new Fragment(copy2, size); } /** Create a new fragment by prepending the given node to this fragment. */ addToStart(node) { return new Fragment([node].concat(this.content), this.size + node.nodeSize); } /** Create a new fragment by appending the given node to this fragment. */ addToEnd(node) { return new Fragment(this.content.concat(node), this.size + node.nodeSize); } /** Compare this fragment to another one. */ eq(other) { if (this.content.length != other.content.length) return false; for (let i = 0; i < this.content.length; i++) if (!this.content[i].eq(other.content[i])) return false; return true; } /** The first child of the fragment, or `null` if it is empty. */ get firstChild() { return this.content.length ? this.content[0] : null; } /** The last child of the fragment, or `null` if it is empty. */ get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; } /** The number of child nodes in this fragment. */ get childCount() { return this.content.length; } /** Get the child node at the given index. Raise an error when the index is out of range. */ child(index) { let found2 = this.content[index]; if (!found2) throw new RangeError("Index " + index + " out of range for " + this); return found2; } /** Get the child node at the given index, if it exists. */ maybeChild(index) { return this.content[index] || null; } /** Call `f` for every child node, passing the node, its offset into this parent node, and its index. */ forEach(f) { for (let i = 0, p = 0; i < this.content.length; i++) { let child = this.content[i]; f(child, p, i); p += child.nodeSize; } } /** Find the first position at which this fragment and another fragment differ, or `null` if they are the same. */ findDiffStart(other, pos = 0) { return findDiffStart(this, other, pos); } /** Find the first position, searching from the end, at which this fragment and the given fragment differ, or `null` if they are the same. Since this position will not be the same in both nodes, an object with two separate positions is returned. */ findDiffEnd(other, pos = this.size, otherPos = other.size) { return findDiffEnd(this, other, pos, otherPos); } /** Find the index and inner offset corresponding to a given relative position in this fragment. The result object will be reused (overwritten) the next time the function is called. @internal */ findIndex(pos) { if (pos == 0) return retIndex(0, pos); if (pos == this.size) return retIndex(this.content.length, pos); if (pos > this.size || pos < 0) throw new RangeError(`Position ${pos} outside of fragment (${this})`); for (let i = 0, curPos = 0; ; i++) { let cur = this.child(i), end = curPos + cur.nodeSize; if (end >= pos) { if (end == pos) return retIndex(i + 1, end); return retIndex(i, curPos); } curPos = end; } } /** Return a debugging string that describes this fragment. */ toString() { return "<" + this.toStringInner() + ">"; } /** @internal */ toStringInner() { return this.content.join(", "); } /** Create a JSON-serializeable representation of this fragment. */ toJSON() { return this.content.length ? this.content.map((n) => n.toJSON()) : null; } /** Deserialize a fragment from its JSON representation. */ static fromJSON(schema, value) { if (!value) return Fragment.empty; if (!Array.isArray(value)) throw new RangeError("Invalid input for Fragment.fromJSON"); return Fragment.fromArray(value.map(schema.nodeFromJSON)); } /** Build a fragment from an array of nodes. Ensures that adjacent text nodes with the same marks are joined together. */ static fromArray(array) { if (!array.length) return Fragment.empty; let joined, size = 0; for (let i = 0; i < array.length; i++) { let node = array[i]; size += node.nodeSize; if (i && node.isText && array[i - 1].sameMarkup(node)) { if (!joined) joined = array.slice(0, i); joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text); } else if (joined) { joined.push(node); } } return new Fragment(joined || array, size); } /** Create a fragment from something that can be interpreted as a set of nodes. For `null`, it returns the empty fragment. For a fragment, the fragment itself. For a node or array of nodes, a fragment containing those nodes. */ static from(nodes) { if (!nodes) return Fragment.empty; if (nodes instanceof Fragment) return nodes; if (Array.isArray(nodes)) return this.fromArray(nodes); if (nodes.attrs) return new Fragment([nodes], nodes.nodeSize); throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : "")); } } Fragment.empty = new Fragment([], 0); const found = { index: 0, offset: 0 }; function retIndex(index, offset) { found.index = index; found.offset = offset; return found; } function compareDeep(a, b) { if (a === b) return true; if (!(a && typeof a == "object") || !(b && typeof b == "object")) return false; let array = Array.isArray(a); if (Array.isArray(b) != array) return false; if (array) { if (a.length != b.length) return false; for (let i = 0; i < a.length; i++) if (!compareDeep(a[i], b[i])) return false; } else { for (let p in a) if (!(p in b) || !compareDeep(a[p], b[p])) return false; for (let p in b) if (!(p in a)) return false; } return true; } let Mark$1 = class Mark { /** @internal */ constructor(type, attrs) { this.type = type; this.attrs = attrs; } /** Given a set of marks, create a new set which contains this one as well, in the right position. If this mark is already in the set, the set itself is returned. If any marks that are set to be [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present, those are replaced by this one. */ addToSet(set) { let copy2, placed = false; for (let i = 0; i < set.length; i++) { let other = set[i]; if (this.eq(other)) return set; if (this.type.excludes(other.type)) { if (!copy2) copy2 = set.slice(0, i); } else if (other.type.excludes(this.type)) { return set; } else { if (!placed && other.type.rank > this.type.rank) { if (!copy2) copy2 = set.slice(0, i); copy2.push(this); placed = true; } if (copy2) copy2.push(other); } } if (!copy2) copy2 = set.slice(); if (!placed) copy2.push(this); return copy2; } /** Remove this mark from the given set, returning a new set. If this mark is not in the set, the set itself is returned. */ removeFromSet(set) { for (let i = 0; i < set.length; i++) if (this.eq(set[i])) return set.slice(0, i).concat(set.slice(i + 1)); return set; } /** Test whether this mark is in the given set of marks. */ isInSet(set) { for (let i = 0; i < set.length; i++) if (this.eq(set[i])) return true; return false; } /** Test whether this mark has the same type and attributes as another mark. */ eq(other) { return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs); } /** Convert this mark to a JSON-serializeable representation. */ toJSON() { let obj = { type: this.type.name }; for (let _ in this.attrs) { obj.attrs = this.attrs; break; } return obj; } /** Deserialize a mark from JSON. */ static fromJSON(schema, json) { if (!json) throw new RangeError("Invalid input for Mark.fromJSON"); let type = schema.marks[json.type]; if (!type) throw new RangeError(`There is no mark type ${json.type} in this schema`); let mark = type.create(json.attrs); type.checkAttrs(mark.attrs); return mark; } /** Test whether two sets of marks are identical. */ static sameSet(a, b) { if (a == b) return true; if (a.length != b.length) return false; for (let i = 0; i < a.length; i++) if (!a[i].eq(b[i])) return false; return true; } /** Create a properly sorted mark set from null, a single mark, or an unsorted array of marks. */ static setFrom(marks) { if (!marks || Array.isArray(marks) && marks.length == 0) return Mark.none; if (marks instanceof Mark) return [marks]; let copy2 = marks.slice(); copy2.sort((a, b) => a.type.rank - b.type.rank); return copy2; } }; Mark$1.none = []; class ReplaceError extends Error { } class Slice { /** Create a slice. When specifying a non-zero open depth, you must make sure that there are nodes of at least that depth at the appropriate side of the fragment—i.e. if the fragment is an empty paragraph node, `openStart` and `openEnd` can't be greater than 1. It is not necessary for the content of open nodes to conform to the schema's content constraints, though it should be a valid start/end/middle for such a node, depending on which sides are open. */ constructor(content, openStart, openEnd) { this.content = content; this.openStart = openStart; this.openEnd = openEnd; } /** The size this slice would add when inserted into a document. */ get size() { return this.content.size - this.openStart - this.openEnd; } /** @internal */ insertAt(pos, fragment) { let content = insertInto(this.content, pos + this.openStart, fragment, this.openStart + 1, this.openEnd + 1); return content && new Slice(content, this.openStart, this.openEnd); } /** @internal */ removeBetween(from2, to) { return new Slice(removeRange(this.content, from2 + this.openStart, to + this.openStart), this.openStart, this.openEnd); } /** Tests whether this slice is equal to another slice. */ eq(other) { return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd; } /** @internal */ toString() { return this.content + "(" + this.openStart + "," + this.openEnd + ")"; } /** Convert a slice to a JSON-serializable representation. */ toJSON() { if (!this.content.size) return null; let json = { content: this.content.toJSON() }; if (this.openStart > 0) json.openStart = this.openStart; if (this.openEnd > 0) json.openEnd = this.openEnd; return json; } /** Deserialize a slice from its JSON representation. */ static fromJSON(schema, json) { if (!json) return Slice.empty; let openStart = json.openStart || 0, openEnd = json.openEnd || 0; if (typeof openStart != "number" || typeof openEnd != "number") throw new RangeError("Invalid input for Slice.fromJSON"); return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd); } /** Create a slice from a fragment by taking the maximum possible open value on both side of the fragment. */ static maxOpen(fragment, openIsolating = true) { let openStart = 0, openEnd = 0; for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) openStart++; for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild) openEnd++; return new Slice(fragment, openStart, openEnd); } } Slice.empty = new Slice(Fragment.empty, 0, 0); function removeRange(content, from2, to) { let { index, offset } = content.findIndex(from2), child = content.maybeChild(index); let { index: indexTo, offset: offsetTo } = content.findIndex(to); if (offset == from2 || child.isText) { if (offsetTo != to && !content.child(indexTo).isText) throw new RangeError("Removing non-flat range"); return content.cut(0, from2).append(content.cut(to)); } if (index != indexTo) throw new RangeError("Removing non-flat range"); return content.replaceChild(index, child.copy(removeRange(child.content, from2 - offset - 1, to - offset - 1))); } function insertInto(content, dist, insert, openStart, openEnd, parent) { let { index, offset } = content.findIndex(dist), child = content.maybeChild(index); if (offset == dist || child.isText) { if (parent && openStart <= 0 && openEnd <= 0 && !parent.canReplace(index, index, insert)) return null; return content.cut(0, dist).append(insert).append(content.cut(dist)); } let inner = insertInto(child.content, dist - offset - 1, insert, index == 0 ? openStart - 1 : 0, index == content.childCount - 1 ? openEnd - 1 : 0, child); return inner && content.replaceChild(index, child.copy(inner)); } function replace($from, $to, slice2) { if (slice2.openStart > $from.depth) throw new ReplaceError("Inserted content deeper than insertion position"); if ($from.depth - slice2.openStart != $to.depth - slice2.openEnd) throw new ReplaceError("Inconsistent open depths"); return replaceOuter($from, $to, slice2, 0); } function replaceOuter($from, $to, slice2, depth) { let index = $from.index(depth), node = $from.node(depth); if (index == $to.index(depth) && depth < $from.depth - slice2.openStart) { let inner = replaceOuter($from, $to, slice2, depth + 1); return node.copy(node.content.replaceChild(index, inner)); } else if (!slice2.content.size) { return close$1(node, replaceTwoWay($from, $to, depth)); } else if (!slice2.openStart && !slice2.openEnd && $from.depth == depth && $to.depth == depth) { let parent = $from.parent, content = parent.content; return close$1(parent, content.cut(0, $from.parentOffset).append(slice2.content).append(content.cut($to.parentOffset))); } else { let { start, end } = prepareSliceForReplace(slice2, $from); return close$1(node, replaceThreeWay($from, start, end, $to, depth)); } } function checkJoin(main, sub) { if (!sub.type.compatibleContent(main.type)) throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name); } function joinable$1($before, $after, depth) { let node = $before.node(depth); checkJoin(node, $after.node(depth)); return node; } function addNode(child, target) { let last = target.length - 1; if (last >= 0 && child.isText && child.sameMarkup(target[last])) target[last] = child.withText(target[last].text + child.text); else target.push(child); } function addRange($start, $end, depth, target) { let node = ($end || $start).node(depth); let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount; if ($start) { startIndex = $start.index(depth); if ($start.depth > depth) { startIndex++; } else if ($start.textOffset) { addNode($start.nodeAfter, target); startIndex++; } } for (let i = startIndex; i < endIndex; i++) addNode(node.child(i), target); if ($end && $end.depth == depth && $end.textOffset) addNode($end.nodeBefore, target); } function close$1(node, content) { if (!node.type.validContent(content)) throw new ReplaceError("Invalid content for node " + node.type.name); return node.copy(content); } function replaceThreeWay($from, $start, $end, $to, depth) { let openStart = $from.depth > depth && joinable$1($from, $start, depth + 1); let openEnd = $to.depth > depth && joinable$1($end, $to, depth + 1); let content = []; addRange(null, $from, depth, content); if (openStart && openEnd && $start.index(depth) == $end.index(depth)) { checkJoin(openStart, openEnd); addNode(close$1(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content); } else { if (openStart) addNode(close$1(openStart, replaceTwoWay($from, $start, depth + 1)), content); addRange($start, $end, depth, content); if (openEnd) addNode(close$1(openEnd, replaceTwoWay($end, $to, depth + 1)), content); } addRange($to, null, depth, content); return new Fragment(content); } function replaceTwoWay($from, $to, depth) { let content = []; addRange(null, $from, depth, content); if ($from.depth > depth) { let type = joinable$1($from, $to, depth + 1); addNode(close$1(type, replaceTwoWay($from, $to, depth + 1)), content); } addRange($to, null, depth, content); return new Fragment(content); } function prepareSliceForReplace(slice2, $along) { let extra = $along.depth - slice2.openStart, parent = $along.node(extra); let node = parent.copy(slice2.content); for (let i = extra - 1; i >= 0; i--) node = $along.node(i).copy(Fragment.from(node)); return { start: node.resolveNoCache(slice2.openStart + extra), end: node.resolveNoCache(node.content.size - slice2.openEnd - extra) }; } class ResolvedPos { /** @internal */ constructor(pos, path, parentOffset) { this.pos = pos; this.path = path; this.parentOffset = parentOffset; this.depth = path.length / 3 - 1; } /** @internal */ resolveDepth(val) { if (val == null) return this.depth; if (val < 0) return this.depth + val; return val; } /** The parent node that the position points into. Note that even if a position points into a text node, that node is not considered the parent—text nodes are ‘flat’ in this model, and have no content. */ get parent() { return this.node(this.depth); } /** The root node in which the position was resolved. */ get doc() { return this.node(0); } /** The ancestor node at the given level. `p.node(p.depth)` is the same as `p.parent`. */ node(depth) { return this.path[this.resolveDepth(depth) * 3]; } /** The index into the ancestor at the given level. If this points at the 3rd node in the 2nd paragraph on the top level, for example, `p.index(0)` is 1 and `p.index(1)` is 2. */ index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; } /** The index pointing after this position into the ancestor at the given level. */ indexAfter(depth) { depth = this.resolveDepth(depth); return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1); } /** The (absolute) position at the start of the node at the given level. */ start(depth) { depth = this.resolveDepth(depth); return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; } /** The (absolute) position at the end of the node at the given level. */ end(depth) { depth = this.resolveDepth(depth); return this.start(depth) + this.node(depth).content.size; } /** The (absolute) position directly before the wrapping node at the given level, or, when `depth` is `this.depth + 1`, the original position. */ before(depth) { depth = this.resolveDepth(depth); if (!depth) throw new RangeError("There is no position before the top-level node"); return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1]; } /** The (absolute) position directly after the wrapping node at the given level, or the original position when `depth` is `this.depth + 1`. */ after(depth) { depth = this.resolveDepth(depth); if (!depth) throw new RangeError("There is no position after the top-level node"); return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize; } /** When this position points into a text node, this returns the distance between the position and the start of the text node. Will be zero for positions that point between nodes. */ get textOffset() { return this.pos - this.path[this.path.length - 1]; } /** Get the node directly after the position, if any. If the position points into a text node, only the part of that node after the position is returned. */ get nodeAfter() { let parent = this.parent, index = this.index(this.depth); if (index == parent.childCount) return null; let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index); return dOff ? parent.child(index).cut(dOff) : child; } /** Get the node directly before the position, if any. If the position points into a text node, only the part of that node before the position is returned. */ get nodeBefore() { let index = this.index(this.depth); let dOff = this.pos - this.path[this.path.length - 1]; if (dOff) return this.parent.child(index).cut(0, dOff); return index == 0 ? null : this.parent.child(index - 1); } /** Get the position at the given index in the parent node at the given depth (which defaults to `this.depth`). */ posAtIndex(index, depth) { depth = this.resolveDepth(depth); let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; for (let i = 0; i < index; i++) pos += node.child(i).nodeSize; return pos; } /** Get the marks at this position, factoring in the surrounding marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the position is at the start of a non-empty node, the marks of the node after it (if any) are returned. */ marks() { let parent = this.parent, index = this.index(); if (parent.content.size == 0) return Mark$1.none; if (this.textOffset) return parent.child(index).marks; let main = parent.maybeChild(index - 1), other = parent.maybeChild(index); if (!main) { let tmp = main; main = other; other = tmp; } let marks = main.marks; for (var i = 0; i < marks.length; i++) if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks))) marks = marks[i--].removeFromSet(marks); return marks; } /** Get the marks after the current position, if any, except those that are non-inclusive and not present at position `$end`. This is mostly useful for getting the set of marks to preserve after a deletion. Will return `null` if this position is at the end of its parent node or its parent node isn't a textblock (in which case no marks should be preserved). */ marksAcross($end) { let after = this.parent.maybeChild(this.index()); if (!after || !after.isInline) return null; let marks = after.marks, next = $end.parent.maybeChild($end.index()); for (var i = 0; i < marks.length; i++) if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks))) marks = marks[i--].removeFromSet(marks); return marks; } /** The depth up to which this position and the given (non-resolved) position share the same parent nodes. */ sharedDepth(pos) { for (let depth = this.depth; depth > 0; depth--) if (this.start(depth) <= pos && this.end(depth) >= pos) return depth; return 0; } /** Returns a range based on the place where this position and the given position diverge around block content. If both point into the same textblock, for example, a range around that textblock will be returned. If they point into different blocks, the range around those blocks in their shared ancestor is returned. You can pass in an optional predicate that will be called with a parent node to see if a range into that parent is acceptable. */ blockRange(other = this, pred) { if (other.pos < this.pos) return other.blockRange(this); for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--) if (other.pos <= this.end(d) && (!pred || pred(this.node(d)))) return new NodeRange(this, other, d); return null; } /** Query whether the given position shares the same parent node. */ sameParent(other) { return this.pos - this.parentOffset == other.pos - other.parentOffset; } /** Return the greater of this and the given position. */ max(other) { return other.pos > this.pos ? other : this; } /** Return the smaller of this and the given position. */ min(other) { return other.pos < this.pos ? other : this; } /** @internal */ toString() { let str = ""; for (let i = 1; i <= this.depth; i++) str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1); return str + ":" + this.parentOffset; } /** @internal */ static resolve(doc2, pos) { if (!(pos >= 0 && pos <= doc2.content.size)) throw new RangeError("Position " + pos + " out of range"); let path = []; let start = 0, parentOffset = pos; for (let node = doc2; ; ) { let { index, offset } = node.content.findIndex(parentOffset); let rem = parentOffset - offset; path.push(node, index, start + offset); if (!rem) break; node = node.child(index); if (node.isText) break; parentOffset = rem - 1; start += offset + 1; } return new ResolvedPos(pos, path, parentOffset); } /** @internal */ static resolveCached(doc2, pos) { let cache = resolveCache.get(doc2); if (cache) { for (let i = 0; i < cache.elts.length; i++) { let elt = cache.elts[i]; if (elt.pos == pos) return elt; } } else { resolveCache.set(doc2, cache = new ResolveCache()); } let result = cache.elts[cache.i] = ResolvedPos.resolve(doc2, pos); cache.i = (cache.i + 1) % resolveCacheSize; return result; } } class ResolveCache { constructor() { this.elts = []; this.i = 0; } } const resolveCacheSize = 12, resolveCache = /* @__PURE__ */ new WeakMap(); class NodeRange { /** Construct a node range. `$from` and `$to` should point into the same node until at least the given `depth`, since a node range denotes an adjacent set of nodes in a single parent node. */ constructor($from, $to, depth) { this.$from = $from; this.$to = $to; this.depth = depth; } /** The position at the start of the range. */ get start() { return this.$from.before(this.depth + 1); } /** The position at the end of the range. */ get end() { return this.$to.after(this.depth + 1); } /** The parent node that the range points into. */ get parent() { return this.$from.node(this.depth); } /** The start index of the range in the parent node. */ get startIndex() { return this.$from.index(this.depth); } /** The end index of the range in the parent node. */ get endIndex() { return this.$to.indexAfter(this.depth); } } const emptyAttrs = /* @__PURE__ */ Object.create(null); let Node$1 = class Node { /** @internal */ constructor(type, attrs, content, marks = Mark$1.none) { this.type = type; this.attrs = attrs; this.marks = marks; this.content = content || Fragment.empty; } /** The array of this node's child nodes. */ get children() { return this.content.content; } /** The size of this node, as defined by the integer-based [indexing scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the amount of characters. For other leaf nodes, it is one. For non-leaf nodes, it is the size of the content plus two (the start and end token). */ get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; } /** The number of children that the node has. */ get childCount() { return this.content.childCount; } /** Get the child node at the given index. Raises an error when the index is out of range. */ child(index) { return this.content.child(index); } /** Get the child node at the given index, if it exists. */ maybeChild(index) { return this.content.maybeChild(index); } /** Call `f` for every child node, passing the node, its offset into this parent node, and its index. */ forEach(f) { this.content.forEach(f); } /** Invoke a callback for all descendant nodes recursively overlapping the given two positions that are relative to start of this node's content. This includes all ancestors of the nodes containing the two positions. The callback is invoked with the node, its position relative to the original node (method receiver), its parent node, and its child index. When the callback returns false for a given node, that node's children will not be recursed over. The last parameter can be used to specify a starting position to count from. */ nodesBetween(from2, to, f, startPos = 0) { this.content.nodesBetween(from2, to, f, startPos, this); } /** Call the given callback for every descendant node. Doesn't descend into a node when the callback returns `false`. */ descendants(f) { this.nodesBetween(0, this.content.size, f); } /** Concatenates all the text nodes found in this fragment and its children. */ get textContent() { return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, ""); } /** Get all text between positions `from` and `to`. When `blockSeparator` is given, it will be inserted to separate text from different block nodes. If `leafText` is given, it'll be inserted for every non-text leaf node encountered, otherwise [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used. */ textBetween(from2, to, blockSeparator, leafText) { return this.content.textBetween(from2, to, blockSeparator, leafText); } /** Returns this node's first child, or `null` if there are no children. */ get firstChild() { return this.content.firstChild; } /** Returns this node's last child, or `null` if there are no children. */ get lastChild() { return this.content.lastChild; } /** Test whether two nodes represent the same piece of document. */ eq(other) { return this == other || this.sameMarkup(other) && this.content.eq(other.content); } /** Compare the markup (type, attributes, and marks) of this node to those of another. Returns `true` if both have the same markup. */ sameMarkup(other) { return this.hasMarkup(other.type, other.attrs, other.marks); } /** Check whether this node's markup correspond to the given type, attributes, and marks. */ hasMarkup(type, attrs, marks) { return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark$1.sameSet(this.marks, marks || Mark$1.none); } /** Create a new node with the same markup as this node, containing the given content (or empty, if no content is given). */ copy(content = null) { if (content == this.content) return this; return new Node(this.type, this.attrs, content, this.marks); } /** Create a copy of this node, with the given set of marks instead of the node's own marks. */ mark(marks) { return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks); } /** Create a copy of this node with only the content between the given positions. If `to` is not given, it defaults to the end of the node. */ cut(from2, to = this.content.size) { if (from2 == 0 && to == this.content.size) return this; return this.copy(this.content.cut(from2, to)); } /** Cut out the part of the document between the given positions, and return it as a `Slice` object. */ slice(from2, to = this.content.size, includeParents = false) { if (from2 == to) return Slice.empty; let $from = this.resolve(from2), $to = this.resolve(to); let depth = includeParents ? 0 : $from.sharedDepth(to); let start = $from.start(depth), node = $from.node(depth); let content = node.content.cut($from.pos - start, $to.pos - start); return new Slice(content, $from.depth - depth, $to.depth - depth); } /** Replace the part of the document between the given positions with the given slice. The slice must 'fit', meaning its open sides must be able to connect to the surrounding content, and its content nodes must be valid children for the node they are placed into. If any of this is violated, an error of type [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown. */ replace(from2, to, slice2) { return replace(this.resolve(from2), this.resolve(to), slice2); } /** Find the node directly after the given position. */ nodeAt(pos) { for (let node = this; ; ) { let { index, offset } = node.content.findIndex(pos); node = node.maybeChild(index); if (!node) return null; if (offset == pos || node.isText) return node; pos -= offset + 1; } } /** Find the (direct) child node after the given offset, if any, and return it along with its index and offset relative to this node. */ childAfter(pos) { let { index, offset } = this.content.findIndex(pos); return { node: this.content.maybeChild(index), index, offset }; } /** Find the (direct) child node before the given offset, if any, and return it along with its index and offset relative to this node. */ childBefore(pos) { if (pos == 0) return { node: null, index: 0, offset: 0 }; let { index, offset } = this.content.findIndex(pos); if (offset < pos) return { node: this.content.child(index), index, offset }; let node = this.content.child(index - 1); return { node, index: index - 1, offset: offset - node.nodeSize }; } /** Resolve the given position in the document, returning an [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context. */ resolve(pos) { return ResolvedPos.resolveCached(this, pos); } /** @internal */ resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); } /** Test whether a given mark or mark type occurs in this document between the two given positions. */ rangeHasMark(from2, to, type) { let found2 = false; if (to > from2) this.nodesBetween(from2, to, (node) => { if (type.isInSet(node.marks)) found2 = true; return !found2; }); return found2; } /** True when this is a block (non-inline node) */ get isBlock() { return this.type.isBlock; } /** True when this is a textblock node, a block node with inline content. */ get isTextblock() { return this.type.isTextblock; } /** True when this node allows inline content. */ get inlineContent() { return this.type.inlineContent; } /** True when this is an inline node (a text node or a node that can appear among text). */ get isInline() { return this.type.isInline; } /** True when this is a text node. */ get isText() { return this.type.isText; } /** True when this is a leaf node. */ get isLeaf() { return this.type.isLeaf; } /** True when this is an atom, i.e. when it does not have directly editable content. This is usually the same as `isLeaf`, but can be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom) on a node's spec (typically used when the node is displayed as an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)). */ get isAtom() { return this.type.isAtom; } /** Return a string representation of this node for debugging purposes. */ toString() { if (this.type.spec.toDebugString) return this.type.spec.toDebugString(this); let name = this.type.name; if (this.content.size) name += "(" + this.content.toStringInner() + ")"; return wrapMarks(this.marks, name); } /** Get the content match in this node at the given index. */ contentMatchAt(index) { let match = this.type.contentMatch.matchFragment(this.content, 0, index); if (!match) throw new Error("Called contentMatchAt on a node with invalid content"); return match; } /** Test whether replacing the range between `from` and `to` (by child index) with the given replacement fragment (which defaults to the empty fragment) would leave the node's content valid. You can optionally pass `start` and `end` indices into the replacement fragment. */ canReplace(from2, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) { let one = this.contentMatchAt(from2).matchFragment(replacement, start, end); let two = one && one.matchFragment(this.content, to); if (!two || !two.validEnd) return false; for (let i = start; i < end; i++) if (!this.type.allowsMarks(replacement.child(i).marks)) return false; return true; } /** Test whether replacing the range `from` to `to` (by index) with a node of the given type would leave the node's content valid. */ canReplaceWith(from2, to, type, marks) { if (marks && !this.type.allowsMarks(marks)) return false; let start = this.contentMatchAt(from2).matchType(type); let end = start && start.matchFragment(this.content, to); return end ? end.validEnd : false; } /** Test whether the given node's content could be appended to this node. If that node is empty, this will only return true if there is at least one node type that can appear in both nodes (to avoid merging completely incompatible nodes). */ canAppend(other) { if (other.content.size) return this.canReplace(this.childCount, this.childCount, other.content); else return this.type.compatibleContent(other.type); } /** Check whether this node and its descendants conform to the schema, and raise an exception when they do not. */ check() { this.type.checkContent(this.content); this.type.checkAttrs(this.attrs); let copy2 = Mark$1.none; for (let i = 0; i < this.marks.length; i++) { let mark = this.marks[i]; mark.type.checkAttrs(mark.attrs); copy2 = mark.addToSet(copy2); } if (!Mark$1.sameSet(copy2, this.marks)) throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m) => m.type.name)}`); this.content.forEach((node) => node.check()); } /** Return a JSON-serializeable representation of this node. */ toJSON() { let obj = { type: this.type.name }; for (let _ in this.attrs) { obj.attrs = this.attrs; break; } if (this.content.size) obj.content = this.content.toJSON(); if (this.marks.length) obj.marks = this.marks.map((n) => n.toJSON()); return obj; } /** Deserialize a node from its JSON representation. */ static fromJSON(schema, json) { if (!json) throw new RangeError("Invalid input for Node.fromJSON"); let marks = void 0; if (json.marks) { if (!Array.isArray(json.marks)) throw new RangeError("Invalid mark data for Node.fromJSON"); marks = json.marks.map(schema.markFromJSON); } if (json.type == "text") { if (typeof json.text != "string") throw new RangeError("Invalid text node in JSON"); return schema.text(json.text, marks); } let content = Fragment.fromJSON(schema, json.content); let node = schema.nodeType(json.type).create(json.attrs, content, marks); node.type.checkAttrs(node.attrs); return node; } }; Node$1.prototype.text = void 0; class TextNode extends Node$1 { /** @internal */ constructor(type, attrs, content, marks) { super(type, attrs, null, marks); if (!content) throw new RangeError("Empty text nodes are not allowed"); this.text = content; } toString() { if (this.type.spec.toDebugString) return this.type.spec.toDebugString(this); return wrapMarks(this.marks, JSON.stringify(this.text)); } get textContent() { return this.text; } textBetween(from2, to) { return this.text.slice(from2, to); } get nodeSize() { return this.text.length; } mark(marks) { return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks); } withText(text) { if (text == this.text) return this; return new TextNode(this.type, this.attrs, text, this.marks); } cut(from2 = 0, to = this.text.length) { if (from2 == 0 && to == this.text.length) return this; return this.withText(this.text.slice(from2, to)); } eq(other) { return this.sameMarkup(other) && this.text == other.text; } toJSON() { let base2 = super.toJSON(); base2.text = this.text; return base2; } } function wrapMarks(marks, str) { for (let i = marks.length - 1; i >= 0; i--) str = marks[i].type.name + "(" + str + ")"; return str; } class ContentMatch { /** @internal */ constructor(validEnd) { this.validEnd = validEnd; this.next = []; this.wrapCache = []; } /** @internal */ static parse(string, nodeTypes) { let stream = new TokenStream(string, nodeTypes); if (stream.next == null) return ContentMatch.empty; let expr = parseExpr(stream); if (stream.next) stream.err("Unexpected trailing text"); let match = dfa(nfa(expr)); checkForDeadEnds(match, stream); return match; } /** Match a node type, returning a match after that node if successful. */ matchType(type) { for (let i = 0; i < this.next.length; i++) if (this.next[i].type == type) return this.next[i].next; return null; } /** Try to match a fragment. Returns the resulting match when successful. */ matchFragment(frag, start = 0, end = frag.childCount) { let cur = this; for (let i = start; cur && i < end; i++) cur = cur.matchType(frag.child(i).type); return cur; } /** @internal */ get inlineContent() { return this.next.length != 0 && this.next[0].type.isInline; } /** Get the first matching node type at this match position that can be generated. */ get defaultType() { for (let i = 0; i < this.next.length; i++) { let { type } = this.next[i]; if (!(type.isText || type.hasRequiredAttrs())) return type; } return null; } /** @internal */ compatible(other) { for (let i = 0; i < this.next.length; i++) for (let j = 0; j < other.next.length; j++) if (this.next[i].type == other.next[j].type) return true; return false; } /** Try to match the given fragment, and if that fails, see if it can be made to match by inserting nodes in front of it. When successful, return a fragment of inserted nodes (which may be empty if nothing had to be inserted). When `toEnd` is true, only return a fragment if the resulting match goes to the end of the content expression. */ fillBefore(after, toEnd = false, startIndex = 0) { let seen = [this]; function search(match, types) { let finished = match.matchFragment(after, startIndex); if (finished && (!toEnd || finished.validEnd)) return Fragment.from(types.map((tp) => tp.createAndFill())); for (let i = 0; i < match.next.length; i++) { let { type, next } = match.next[i]; if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) { seen.push(next); let found2 = search(next, types.concat(type)); if (found2) return found2; } } return null; } return search(this, []); } /** Find a set of wrapping node types that would allow a node of the given type to appear at this position. The result may be empty (when it fits directly) and will be null when no such wrapping exists. */ findWrapping(target) { for (let i = 0; i < this.wrapCache.length; i += 2) if (this.wrapCache[i] == target) return this.wrapCache[i + 1]; let computed = this.computeWrapping(target); this.wrapCache.push(target, computed); return computed; } /** @internal */ computeWrapping(target) { let seen = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }]; while (active.length) { let current = active.shift(), match = current.match; if (match.matchType(target)) { let result = []; for (let obj = current; obj.type; obj = obj.via) result.push(obj.type); return result.reverse(); } for (let i = 0; i < match.next.length; i++) { let { type, next } = match.next[i]; if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) { active.push({ match: type.contentMatch, type, via: current }); seen[type.name] = true; } } } return null; } /** The number of outgoing edges this node has in the finite automaton that describes the content expression. */ get edgeCount() { return this.next.length; } /** Get the _n_​th outgoing edge from this node in the finite automaton that describes the content expression. */ edge(n) { if (n >= this.next.length) throw new RangeError(`There's no ${n}th edge in this content match`); return this.next[n]; } /** @internal */ toString() { let seen = []; function scan(m) { seen.push(m); for (let i = 0; i < m.next.length; i++) if (seen.indexOf(m.next[i].next) == -1) scan(m.next[i].next); } scan(this); return seen.map((m, i) => { let out = i + (m.validEnd ? "*" : " ") + " "; for (let i2 = 0; i2 < m.next.length; i2++) out += (i2 ? ", " : "") + m.next[i2].type.name + "->" + seen.indexOf(m.next[i2].next); return out; }).join("\n"); } } ContentMatch.empty = new ContentMatch(true); class TokenStream { constructor(string, nodeTypes) { this.string = string; this.nodeTypes = nodeTypes; this.inline = null; this.pos = 0; this.tokens = string.split(/\s*(?=\b|\W|$)/); if (this.tokens[this.tokens.length - 1] == "") this.tokens.pop(); if (this.tokens[0] == "") this.tokens.shift(); } get next() { return this.tokens[this.pos]; } eat(tok) { return this.next == tok && (this.pos++ || true); } err(str) { throw new SyntaxError(str + " (in content expression '" + this.string + "')"); } } function parseExpr(stream) { let exprs = []; do { exprs.push(parseExprSeq(stream)); } while (stream.eat("|")); return exprs.length == 1 ? exprs[0] : { type: "choice", exprs }; } function parseExprSeq(stream) { let exprs = []; do { exprs.push(parseExprSubscript(stream)); } while (stream.next && stream.next != ")" && stream.next != "|"); return exprs.length == 1 ? exprs[0] : { type: "seq", exprs }; } function parseExprSubscript(stream) { let expr = parseExprAtom(stream); for (; ; ) { if (stream.eat("+")) expr = { type: "plus", expr }; else if (stream.eat("*")) expr = { type: "star", expr }; else if (stream.eat("?")) expr = { type: "opt", expr }; else if (stream.eat("{")) expr = parseExprRange(stream, expr); else break; } return expr; } function parseNum(stream) { if (/\D/.test(stream.next)) stream.err("Expected number, got '" + stream.next + "'"); let result = Number(stream.next); stream.pos++; return result; } function parseExprRange(stream, expr) { let min = parseNum(stream), max = min; if (stream.eat(",")) { if (stream.next != "}") max = parseNum(stream); else max = -1; } if (!stream.eat("}")) stream.err("Unclosed braced range"); return { type: "range", min, max, expr }; } function resolveName(stream, name) { let types = stream.nodeTypes, type = types[name]; if (type) return [type]; let result = []; for (let typeName in types) { let type2 = types[typeName]; if (type2.isInGroup(name)) result.push(type2); } if (result.length == 0) stream.err("No node type or group '" + name + "' found"); return result; } function parseExprAtom(stream) { if (stream.eat("(")) { let expr = parseExpr(stream); if (!stream.eat(")")) stream.err("Missing closing paren"); return expr; } else if (!/\W/.test(stream.next)) { let exprs = resolveName(stream, stream.next).map((type) => { if (stream.inline == null) stream.inline = type.isInline; else if (stream.inline != type.isInline) stream.err("Mixing inline and block content"); return { type: "name", value: type }; }); stream.pos++; return exprs.length == 1 ? exprs[0] : { type: "choice", exprs }; } else { stream.err("Unexpected token '" + stream.next + "'"); } } function nfa(expr) { let nfa2 = [[]]; connect(compile(expr, 0), node()); return nfa2; function node() { return nfa2.push([]) - 1; } function edge(from2, to, term) { let edge2 = { term, to }; nfa2[from2].push(edge2); return edge2; } function connect(edges, to) { edges.forEach((edge2) => edge2.to = to); } function compile(expr2, from2) { if (expr2.type == "choice") { return expr2.exprs.reduce((out, expr3) => out.concat(compile(expr3, from2)), []); } else if (expr2.type == "seq") { for (let i = 0; ; i++) { let next = compile(expr2.exprs[i], from2); if (i == expr2.exprs.length - 1) return next; connect(next, from2 = node()); } } else if (expr2.type == "star") { let loop = node(); edge(from2, loop); connect(compile(expr2.expr, loop), loop); return [edge(loop)]; } else if (expr2.type == "plus") { let loop = node(); connect(compile(expr2.expr, from2), loop); connect(compile(expr2.expr, loop), loop); return [edge(loop)]; } else if (expr2.type == "opt") { return [edge(from2)].concat(compile(expr2.expr, from2)); } else if (expr2.type == "range") { let cur = from2; for (let i = 0; i < expr2.min; i++) { let next = node(); connect(compile(expr2.expr, cur), next); cur = next; } if (expr2.max == -1) { connect(compile(expr2.expr, cur), cur); } else { for (let i = expr2.min; i < expr2.max; i++) { let next = node(); edge(cur, next); connect(compile(expr2.expr, cur), next); cur = next; } } return [edge(cur)]; } else if (expr2.type == "name") { return [edge(from2, void 0, expr2.value)]; } else { throw new Error("Unknown expr type"); } } } function cmp(a, b) { return b - a; } function nullFrom(nfa2, node) { let result = []; scan(node); return result.sort(cmp); function scan(node2) { let edges = nfa2[node2]; if (edges.length == 1 && !edges[0].term) return scan(edges[0].to); result.push(node2); for (let i = 0; i < edges.length; i++) { let { term, to } = edges[i]; if (!term && result.indexOf(to) == -1) scan(to); } } } function dfa(nfa2) { let labeled = /* @__PURE__ */ Object.create(null); return explore(nullFrom(nfa2, 0)); function explore(states) { let out = []; states.forEach((node) => { nfa2[node].forEach(({ term, to }) => { if (!term) return; let set; for (let i = 0; i < out.length; i++) if (out[i][0] == term) set = out[i][1]; nullFrom(nfa2, to).forEach((node2) => { if (!set) out.push([term, set = []]); if (set.indexOf(node2) == -1) set.push(node2); }); }); }); let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1); for (let i = 0; i < out.length; i++) { let states2 = out[i][1].sort(cmp); state.next.push({ type: out[i][0], next: labeled[states2.join(",")] || explore(states2) }); } return state; } } function checkForDeadEnds(match, stream) { for (let i = 0, work = [match]; i < work.length; i++) { let state = work[i], dead = !state.validEnd, nodes = []; for (let j = 0; j < state.next.length; j++) { let { type, next } = state.next[j]; nodes.push(type.name); if (dead && !(type.isText || type.hasRequiredAttrs())) dead = false; if (work.indexOf(next) == -1) work.push(next); } if (dead) stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)"); } } function defaultAttrs(attrs) { let defaults2 = /* @__PURE__ */ Object.create(null); for (let attrName in attrs) { let attr = attrs[attrName]; if (!attr.hasDefault) return null; defaults2[attrName] = attr.default; } return defaults2; } function computeAttrs(attrs, value) { let built = /* @__PURE__ */ Object.create(null); for (let name in attrs) { let given = value && value[name]; if (given === void 0) { let attr = attrs[name]; if (attr.hasDefault) given = attr.default; else throw new RangeError("No value supplied for attribute " + name); } built[name] = given; } return built; } function checkAttrs(attrs, values, type, name) { for (let attr in values) if (!(attr in attrs)) throw new RangeError(`Unsupported attribute ${attr} for ${type} of type ${name}`); for (let attr in attrs) { if (attrs[attr].validate) attrs[attr].validate(values[attr]); } } function initAttrs(typeName, attrs) { let result = /* @__PURE__ */ Object.create(null); if (attrs) for (let name in attrs) result[name] = new Attribute(typeName, name, attrs[name]); return result; } let NodeType$1 = class NodeType { /** @internal */ constructor(name, schema, spec) { this.name = name; this.schema = schema; this.spec = spec; this.markSet = null; this.groups = spec.group ? spec.group.split(" ") : []; this.attrs = initAttrs(name, spec.attrs); this.defaultAttrs = defaultAttrs(this.attrs); this.contentMatch = null; this.inlineContent = null; this.isBlock = !(spec.inline || name == "text"); this.isText = name == "text"; } /** True if this is an inline type. */ get isInline() { return !this.isBlock; } /** True if this is a textblock type, a block that contains inline content. */ get isTextblock() { return this.isBlock && this.inlineContent; } /** True for node types that allow no content. */ get isLeaf() { return this.contentMatch == ContentMatch.empty; } /** True when this node is an atom, i.e. when it does not have directly editable content. */ get isAtom() { return this.isLeaf || !!this.spec.atom; } /** Return true when this node type is part of the given [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group). */ isInGroup(group) { return this.groups.indexOf(group) > -1; } /** The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option. */ get whitespace() { return this.spec.whitespace || (this.spec.code ? "pre" : "normal"); } /** Tells you whether this node type has any required attributes. */ hasRequiredAttrs() { for (let n in this.attrs) if (this.attrs[n].isRequired) return true; return false; } /** Indicates whether this node allows some of the same content as the given node type. */ compatibleContent(other) { return this == other || this.contentMatch.compatible(other.contentMatch); } /** @internal */ computeAttrs(attrs) { if (!attrs && this.defaultAttrs) return this.defaultAttrs; else return computeAttrs(this.attrs, attrs); } /** Create a `Node` of this type. The given attributes are checked and defaulted (you can pass `null` to use the type's defaults entirely, if no required attributes exist). `content` may be a `Fragment`, a node, an array of nodes, or `null`. Similarly `marks` may be `null` to default to the empty set of marks. */ create(attrs = null, content, marks) { if (this.isText) throw new Error("NodeType.create can't construct text nodes"); return new Node$1(this, this.computeAttrs(attrs), Fragment.from(content), Mark$1.setFrom(marks)); } /** Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content against the node type's content restrictions, and throw an error if it doesn't match. */ createChecked(attrs = null, content, marks) { content = Fragment.from(content); this.checkContent(content); return new Node$1(this, this.computeAttrs(attrs), content, Mark$1.setFrom(marks)); } /** Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is necessary to add nodes to the start or end of the given fragment to make it fit the node. If no fitting wrapping can be found, return null. Note that, due to the fact that required nodes can always be created, this will always succeed if you pass null or `Fragment.empty` as content. */ createAndFill(attrs = null, content, marks) { attrs = this.computeAttrs(attrs); content = Fragment.from(content); if (content.size) { let before = this.contentMatch.fillBefore(content); if (!before) return null; content = before.append(content); } let matched = this.contentMatch.matchFragment(content); let after = matched && matched.fillBefore(Fragment.empty, true); if (!after) return null; return new Node$1(this, attrs, content.append(after), Mark$1.setFrom(marks)); } /** Returns true if the given fragment is valid content for this node type. */ validContent(content) { let result = this.contentMatch.matchFragment(content); if (!result || !result.validEnd) return false; for (let i = 0; i < content.childCount; i++) if (!this.allowsMarks(content.child(i).marks)) return false; return true; } /** Throws a RangeError if the given fragment is not valid content for this node type. @internal */ checkContent(content) { if (!this.validContent(content)) throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`); } /** @internal */ checkAttrs(attrs) { checkAttrs(this.attrs, attrs, "node", this.name); } /** Check whether the given mark type is allowed in this node. */ allowsMarkType(markType) { return this.markSet == null || this.markSet.indexOf(markType) > -1; } /** Test whether the given set of marks are allowed in this node. */ allowsMarks(marks) { if (this.markSet == null) return true; for (let i = 0; i < marks.length; i++) if (!this.allowsMarkType(marks[i].type)) return false; return true; } /** Removes the marks that are not allowed in this node from the given set. */ allowedMarks(marks) { if (this.markSet == null) return marks; let copy2; for (let i = 0; i < marks.length; i++) { if (!this.allowsMarkType(marks[i].type)) { if (!copy2) copy2 = marks.slice(0, i); } else if (copy2) { copy2.push(marks[i]); } } return !copy2 ? marks : copy2.length ? copy2 : Mark$1.none; } /** @internal */ static compile(nodes, schema) { let result = /* @__PURE__ */ Object.create(null); nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec)); let topType = schema.spec.topNode || "doc"; if (!result[topType]) throw new RangeError("Schema is missing its top node type ('" + topType + "')"); if (!result.text) throw new RangeError("Every schema needs a 'text' type"); for (let _ in result.text.attrs) throw new RangeError("The text node type should not have attributes"); return result; } }; function validateType(typeName, attrName, type) { let types = type.split("|"); return (value) => { let name = value === null ? "null" : typeof value; if (types.indexOf(name) < 0) throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`); }; } class Attribute { constructor(typeName, attrName, options) { this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default"); this.default = options.default; this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate; } get isRequired() { return !this.hasDefault; } } class MarkType { /** @internal */ constructor(name, rank, schema, spec) { this.name = name; this.rank = rank; this.schema = schema; this.spec = spec; this.attrs = initAttrs(name, spec.attrs); this.excluded = null; let defaults2 = defaultAttrs(this.attrs); this.instance = defaults2 ? new Mark$1(this, defaults2) : null; } /** Create a mark of this type. `attrs` may be `null` or an object containing only some of the mark's attributes. The others, if they have defaults, will be added. */ create(attrs = null) { if (!attrs && this.instance) return this.instance; return new Mark$1(this, computeAttrs(this.attrs, attrs)); } /** @internal */ static compile(marks, schema) { let result = /* @__PURE__ */ Object.create(null), rank = 0; marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec)); return result; } /** When there is a mark of this type in the given set, a new set without it is returned. Otherwise, the input set is returned. */ removeFromSet(set) { for (var i = 0; i < set.length; i++) if (set[i].type == this) { set = set.slice(0, i).concat(set.slice(i + 1)); i--; } return set; } /** Tests whether there is a mark of this type in the given set. */ isInSet(set) { for (let i = 0; i < set.length; i++) if (set[i].type == this) return set[i]; } /** @internal */ checkAttrs(attrs) { checkAttrs(this.attrs, attrs, "mark", this.name); } /** Queries whether a given mark type is [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one. */ excludes(other) { return this.excluded.indexOf(other) > -1; } } class Schema { /** Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec). */ constructor(spec) { this.linebreakReplacement = null; this.cached = /* @__PURE__ */ Object.create(null); let instanceSpec = this.spec = {}; for (let prop in spec) instanceSpec[prop] = spec[prop]; instanceSpec.nodes = OrderedMap.from(spec.nodes), instanceSpec.marks = OrderedMap.from(spec.marks || {}), this.nodes = NodeType$1.compile(this.spec.nodes, this); this.marks = MarkType.compile(this.spec.marks, this); let contentExprCache = /* @__PURE__ */ Object.create(null); for (let prop in this.nodes) { if (prop in this.marks) throw new RangeError(prop + " can not be both a node and a mark"); let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks; type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes)); type.inlineContent = type.contentMatch.inlineContent; if (type.spec.linebreakReplacement) { if (this.linebreakReplacement) throw new RangeError("Multiple linebreak nodes defined"); if (!type.isInline || !type.isLeaf) throw new RangeError("Linebreak replacement nodes must be inline leaf nodes"); this.linebreakReplacement = type; } type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null; } for (let prop in this.marks) { let type = this.marks[prop], excl = type.spec.excludes; type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" ")); } this.nodeFromJSON = (json) => Node$1.fromJSON(this, json); this.markFromJSON = (json) => Mark$1.fromJSON(this, json); this.topNodeType = this.nodes[this.spec.topNode || "doc"]; this.cached.wrappings = /* @__PURE__ */ Object.create(null); } /** Create a node in this schema. The `type` may be a string or a `NodeType` instance. Attributes will be extended with defaults, `content` may be a `Fragment`, `null`, a `Node`, or an array of nodes. */ node(type, attrs = null, content, marks) { if (typeof type == "string") type = this.nodeType(type); else if (!(type instanceof NodeType$1)) throw new RangeError("Invalid node type: " + type); else if (type.schema != this) throw new RangeError("Node type from different schema used (" + type.name + ")"); return type.createChecked(attrs, content, marks); } /** Create a text node in the schema. Empty text nodes are not allowed. */ text(text, marks) { let type = this.nodes.text; return new TextNode(type, type.defaultAttrs, text, Mark$1.setFrom(marks)); } /** Create a mark with the given type and attributes. */ mark(type, attrs) { if (typeof type == "string") type = this.marks[type]; return type.create(attrs); } /** @internal */ nodeType(name) { let found2 = this.nodes[name]; if (!found2) throw new RangeError("Unknown node type: " + name); return found2; } } function gatherMarks(schema, marks) { let found2 = []; for (let i = 0; i < marks.length; i++) { let name = marks[i], mark = schema.marks[name], ok = mark; if (mark) { found2.push(mark); } else { for (let prop in schema.marks) { let mark2 = schema.marks[prop]; if (name == "_" || mark2.spec.group && mark2.spec.group.split(" ").indexOf(name) > -1) found2.push(ok = mark2); } } if (!ok) throw new SyntaxError("Unknown mark type: '" + marks[i] + "'"); } return found2; } function isTagRule(rule) { return rule.tag != null; } function isStyleRule(rule) { return rule.style != null; } let DOMParser$1 = class DOMParser2 { /** Create a parser that targets the given schema, using the given parsing rules. */ constructor(schema, rules) { this.schema = schema; this.rules = rules; this.tags = []; this.styles = []; let matchedStyles = this.matchedStyles = []; rules.forEach((rule) => { if (isTagRule(rule)) { this.tags.push(rule); } else if (isStyleRule(rule)) { let prop = /[^=]*/.exec(rule.style)[0]; if (matchedStyles.indexOf(prop) < 0) matchedStyles.push(prop); this.styles.push(rule); } }); this.normalizeLists = !this.tags.some((r) => { if (!/^(ul|ol)\b/.test(r.tag) || !r.node) return false; let node = schema.nodes[r.node]; return node.contentMatch.matchType(node); }); } /** Parse a document from the content of a DOM node. */ parse(dom, options = {}) { let context = new ParseContext(this, options, false); context.addAll(dom, Mark$1.none, options.from, options.to); return context.finish(); } /** Parses the content of the given DOM node, like [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of options. But unlike that method, which produces a whole node, this one returns a slice that is open at the sides, meaning that the schema constraints aren't applied to the start of nodes to the left of the input and the end of nodes at the end. */ parseSlice(dom, options = {}) { let context = new ParseContext(this, options, true); context.addAll(dom, Mark$1.none, options.from, options.to); return Slice.maxOpen(context.finish()); } /** @internal */ matchTag(dom, context, after) { for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) { let rule = this.tags[i]; if (matches(dom, rule.tag) && (rule.namespace === void 0 || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) { if (rule.getAttrs) { let result = rule.getAttrs(dom); if (result === false) continue; rule.attrs = result || void 0; } return rule; } } } /** @internal */ matchStyle(prop, value, context, after) { for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) { let rule = this.styles[i], style = rule.style; if (style.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop, // or has an '=' sign after the prop, followed by the given // value. style.length > prop.length && (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value)) continue; if (rule.getAttrs) { let result = rule.getAttrs(value); if (result === false) continue; rule.attrs = result || void 0; } return rule; } } /** @internal */ static schemaRules(schema) { let result = []; function insert(rule) { let priority = rule.priority == null ? 50 : rule.priority, i = 0; for (; i < result.length; i++) { let next = result[i], nextPriority = next.priority == null ? 50 : next.priority; if (nextPriority < priority) break; } result.splice(i, 0, rule); } for (let name in schema.marks) { let rules = schema.marks[name].spec.parseDOM; if (rules) rules.forEach((rule) => { insert(rule = copy(rule)); if (!(rule.mark || rule.ignore || rule.clearMark)) rule.mark = name; }); } for (let name in schema.nodes) { let rules = schema.nodes[name].spec.parseDOM; if (rules) rules.forEach((rule) => { insert(rule = copy(rule)); if (!(rule.node || rule.ignore || rule.mark)) rule.node = name; }); } return result; } /** Construct a DOM parser using the parsing rules listed in a schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority). */ static fromSchema(schema) { return schema.cached.domParser || (schema.cached.domParser = new DOMParser2(schema, DOMParser2.schemaRules(schema))); } }; const blockTags = { address: true, article: true, aside: true, blockquote: true, body: true, canvas: true, dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true, footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true, h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true, output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true }; const ignoreTags = { head: true, noscript: true, object: true, script: true, style: true, title: true }; const listTags = { ol: true, ul: true }; const OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4; function wsOptionsFor(type, preserveWhitespace, base2) { if (preserveWhitespace != null) return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0); return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base2 & ~OPT_OPEN_LEFT; } class NodeContext { constructor(type, attrs, marks, solid, match, options) { this.type = type; this.attrs = attrs; this.marks = marks; this.solid = solid; this.options = options; this.content = []; this.activeMarks = Mark$1.none; this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch); } findWrapping(node) { if (!this.match) { if (!this.type) return []; let fill = this.type.contentMatch.fillBefore(Fragment.from(node)); if (fill) { this.match = this.type.contentMatch.matchFragment(fill); } else { let start = this.type.contentMatch, wrap2; if (wrap2 = start.findWrapping(node.type)) { this.match = start; return wrap2; } else { return null; } } } return this.match.findWrapping(node.type); } finish(openEnd) { if (!(this.options & OPT_PRESERVE_WS)) { let last = this.content[this.content.length - 1], m; if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) { let text = last; if (last.text.length == m[0].length) this.content.pop(); else this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length)); } } let content = Fragment.from(this.content); if (!openEnd && this.match) content = content.append(this.match.fillBefore(Fragment.empty, true)); return this.type ? this.type.create(this.attrs, content, this.marks) : content; } inlineContext(node) { if (this.type) return this.type.inlineContent; if (this.content.length) return this.content[0].isInline; return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase()); } } class ParseContext { constructor(parser, options, isOpen) { this.parser = parser; this.options = options; this.isOpen = isOpen; this.open = 0; this.localPreserveWS = false; let topNode = options.topNode, topContext; let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0); if (topNode) topContext = new NodeContext(topNode.type, topNode.attrs, Mark$1.none, true, options.topMatch || topNode.type.contentMatch, topOptions); else if (isOpen) topContext = new NodeContext(null, null, Mark$1.none, true, null, topOptions); else topContext = new NodeContext(parser.schema.topNodeType, null, Mark$1.none, true, null, topOptions); this.nodes = [topContext]; this.find = options.findPositions; this.needsBlock = false; } get top() { return this.nodes[this.open]; } // Add a DOM node to the content. Text is inserted as text node, // otherwise, the node is passed to `addElement` or, if it has a // `style` attribute, `addElementWithStyles`. addDOM(dom, marks) { if (dom.nodeType == 3) this.addTextNode(dom, marks); else if (dom.nodeType == 1) this.addElement(dom, marks); } addTextNode(dom, marks) { let value = dom.nodeValue; let top = this.top, preserveWS = top.options & OPT_PRESERVE_WS_FULL ? "full" : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0; let { schema } = this.parser; if (preserveWS === "full" || top.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) { if (!preserveWS) { value = value.replace(/[ \t\r\n\u000c]+/g, " "); if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) { let nodeBefore = top.content[top.content.length - 1]; let domNodeBefore = dom.previousSibling; if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == "BR" || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text)) value = value.slice(1); } } else if (preserveWS === "full") { value = value.replace(/\r\n?/g, "\n"); } else if (schema.linebreakReplacement && /[\r\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) { let lines = value.split(/\r?\n|\r/); for (let i = 0; i < lines.length; i++) { if (i) this.insertNode(schema.linebreakReplacement.create(), marks, true); if (lines[i]) this.insertNode(schema.text(lines[i]), marks, !/\S/.test(lines[i])); } value = ""; } else { value = value.replace(/\r?\n|\r/g, " "); } if (value) this.insertNode(schema.text(value), marks, !/\S/.test(value)); this.findInText(dom); } else { this.findInside(dom); } } // Try to find a handler for the given tag and use that to parse. If // none is found, the element's content nodes are added directly. addElement(dom, marks, matchAfter) { let outerWS = this.localPreserveWS, top = this.top; if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace)) this.localPreserveWS = true; let name = dom.nodeName.toLowerCase(), ruleID; if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) normalizeList(dom); let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter)); out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) { this.findInside(dom); this.ignoreFallback(dom, marks); } else if (!rule || rule.skip || rule.closeParent) { if (rule && rule.closeParent) this.open = Math.max(0, this.open - 1); else if (rule && rule.skip.nodeType) dom = rule.skip; let sync, oldNeedsBlock = this.needsBlock; if (blockTags.hasOwnProperty(name)) { if (top.content.length && top.content[0].isInline && this.open) { this.open--; top = this.top; } sync = true; if (!top.type) this.needsBlock = true; } else if (!dom.firstChild) { this.leafFallback(dom, marks); break out; } let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks); if (innerMarks) this.addAll(dom, innerMarks); if (sync) this.sync(top); this.needsBlock = oldNeedsBlock; } else { let innerMarks = this.readStyles(dom, marks); if (innerMarks) this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : void 0); } this.localPreserveWS = outerWS; } // Called for leaf DOM nodes that would otherwise be ignored leafFallback(dom, marks) { if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent) this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks); } // Called for ignored nodes ignoreFallback(dom, marks) { if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent)) this.findPlace(this.parser.schema.text("-"), marks, true); } // Run any style parser associated with the node's styles. Either // return an updated array of marks, or null to indicate some of the // styles had a rule with `ignore` set. readStyles(dom, marks) { let styles = dom.style; if (styles && styles.length) for (let i = 0; i < this.parser.matchedStyles.length; i++) { let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name); if (value) for (let after = void 0; ; ) { let rule = this.parser.matchStyle(name, value, this, after); if (!rule) break; if (rule.ignore) return null; if (rule.clearMark) marks = marks.filter((m) => !rule.clearMark(m)); else marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs)); if (rule.consuming === false) after = rule; else break; } } return marks; } // Look up a handler for the given node. If none are found, return // false. Otherwise, apply it, use its return value to drive the way // the node's content is wrapped, and return true. addElementByRule(dom, rule, marks, continueAfter) { let sync, nodeType; if (rule.node) { nodeType = this.parser.schema.nodes[rule.node]; if (!nodeType.isLeaf) { let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace); if (inner) { sync = true; marks = inner; } } else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == "BR")) { this.leafFallback(dom, marks); } } else { let markType = this.parser.schema.marks[rule.mark]; marks = marks.concat(markType.create(rule.attrs)); } let startIn = this.top; if (nodeType && nodeType.isLeaf) { this.findInside(dom); } else if (continueAfter) { this.addElement(dom, marks, continueAfter); } else if (rule.getContent) { this.findInside(dom); rule.getContent(dom, this.parser.schema).forEach((node) => this.insertNode(node, marks, false)); } else { let contentDOM = dom; if (typeof rule.contentElement == "string") contentDOM = dom.querySelector(rule.contentElement); else if (typeof rule.contentElement == "function") contentDOM = rule.contentElement(dom); else if (rule.contentElement) contentDOM = rule.contentElement; this.findAround(dom, contentDOM, true); this.addAll(contentDOM, marks); this.findAround(dom, contentDOM, false); } if (sync && this.sync(startIn)) this.open--; } // Add all child nodes between `startIndex` and `endIndex` (or the // whole node, if not given). If `sync` is passed, use it to // synchronize after every block element. addAll(parent, marks, startIndex, endIndex) { let index = startIndex || 0; for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) { this.findAtPoint(parent, index); this.addDOM(dom, marks); } this.findAtPoint(parent, index); } // Try to find a way to fit the given node type into the current // context. May add intermediate wrappers and/or leave non-solid // nodes that we're in. findPlace(node, marks, cautious) { let route, sync; for (let depth = this.open, penalty = 0; depth >= 0; depth--) { let cx = this.nodes[depth]; let found2 = cx.findWrapping(node); if (found2 && (!route || route.length > found2.length + penalty)) { route = found2; sync = cx; if (!found2.length) break; } if (cx.solid) { if (cautious) break; penalty += 2; } } if (!route) return null; this.sync(sync); for (let i = 0; i < route.length; i++) marks = this.enterInner(route[i], null, marks, false); return marks; } // Try to insert the given node, adjusting the context when needed. insertNode(node, marks, cautious) { if (node.isInline && this.needsBlock && !this.top.type) { let block = this.textblockFromContext(); if (block) marks = this.enterInner(block, null, marks); } let innerMarks = this.findPlace(node, marks, cautious); if (innerMarks) { this.closeExtra(); let top = this.top; if (top.match) top.match = top.match.matchType(node.type); let nodeMarks = Mark$1.none; for (let m of innerMarks.concat(node.marks)) if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type)) nodeMarks = m.addToSet(nodeMarks); top.content.push(node.mark(nodeMarks)); return true; } return false; } // Try to start a node of the given type, adjusting the context when // necessary. enter(type, attrs, marks, preserveWS) { let innerMarks = this.findPlace(type.create(attrs), marks, false); if (innerMarks) innerMarks = this.enterInner(type, attrs, marks, true, preserveWS); return innerMarks; } // Open a node of the given type enterInner(type, attrs, marks, solid = false, preserveWS) { this.closeExtra(); let top = this.top; top.match = top.match && top.match.matchType(type); let options = wsOptionsFor(type, preserveWS, top.options); if (top.options & OPT_OPEN_LEFT && top.content.length == 0) options |= OPT_OPEN_LEFT; let applyMarks = Mark$1.none; marks = marks.filter((m) => { if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) { applyMarks = m.addToSet(applyMarks); return false; } return true; }); this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options)); this.open++; return marks; } // Make sure all nodes above this.open are finished and added to // their parents closeExtra(openEnd = false) { let i = this.nodes.length - 1; if (i > this.open) { for (; i > this.open; i--) this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd)); this.nodes.length = this.open + 1; } } finish() { this.open = 0; this.closeExtra(this.isOpen); return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen)); } sync(to) { for (let i = this.open; i >= 0; i--) { if (this.nodes[i] == to) { this.open = i; return true; } else if (this.localPreserveWS) { this.nodes[i].options |= OPT_PRESERVE_WS; } } return false; } get currentPos() { this.closeExtra(); let pos = 0; for (let i = this.open; i >= 0; i--) { let content = this.nodes[i].content; for (let j = content.length - 1; j >= 0; j--) pos += content[j].nodeSize; if (i) pos++; } return pos; } findAtPoint(parent, offset) { if (this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].node == parent && this.find[i].offset == offset) this.find[i].pos = this.currentPos; } } findInside(parent) { if (this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) this.find[i].pos = this.currentPos; } } findAround(parent, content, before) { if (parent != content && this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) { let pos = content.compareDocumentPosition(this.find[i].node); if (pos & (before ? 2 : 4)) this.find[i].pos = this.currentPos; } } } findInText(textNode) { if (this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].node == textNode) this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset); } } // Determines whether the given context string matches this context. matchesContext(context) { if (context.indexOf("|") > -1) return context.split(/\s*\|\s*/).some(this.matchesContext, this); let parts = context.split("/"); let option = this.options.context; let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type); let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1); let match = (i, depth) => { for (; i >= 0; i--) { let part = parts[i]; if (part == "") { if (i == parts.length - 1 || i == 0) continue; for (; depth >= minDepth; depth--) if (match(i - 1, depth)) return true; return false; } else { let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null; if (!next || next.name != part && !next.isInGroup(part)) return false; depth--; } } return true; }; return match(parts.length - 1, this.open); } textblockFromContext() { let $context = this.options.context; if ($context) for (let d = $context.depth; d >= 0; d--) { let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType; if (deflt && deflt.isTextblock && deflt.defaultAttrs) return deflt; } for (let name in this.parser.schema.nodes) { let type = this.parser.schema.nodes[name]; if (type.isTextblock && type.defaultAttrs) return type; } } } function normalizeList(dom) { for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) { let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null; if (name && listTags.hasOwnProperty(name) && prevItem) { prevItem.appendChild(child); child = prevItem; } else if (name == "li") { prevItem = child; } else if (name) { prevItem = null; } } } function matches(dom, selector) { return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector); } function copy(obj) { let copy2 = {}; for (let prop in obj) copy2[prop] = obj[prop]; return copy2; } function markMayApply(markType, nodeType) { let nodes = nodeType.schema.nodes; for (let name in nodes) { let parent = nodes[name]; if (!parent.allowsMarkType(markType)) continue; let seen = [], scan = (match) => { seen.push(match); for (let i = 0; i < match.edgeCount; i++) { let { type, next } = match.edge(i); if (type == nodeType) return true; if (seen.indexOf(next) < 0 && scan(next)) return true; } }; if (scan(parent.contentMatch)) return true; } } class DOMSerializer { /** Create a serializer. `nodes` should map node names to functions that take a node and return a description of the corresponding DOM. `marks` does the same for mark names, but also gets an argument that tells it whether the mark's content is block or inline content (for typical use, it'll always be inline). A mark serializer may be `null` to indicate that marks of that type should not be serialized. */ constructor(nodes, marks) { this.nodes = nodes; this.marks = marks; } /** Serialize the content of this fragment to a DOM fragment. When not in the browser, the `document` option, containing a DOM document, should be passed so that the serializer can create nodes. */ serializeFragment(fragment, options = {}, target) { if (!target) target = doc$2(options).createDocumentFragment(); let top = target, active = []; fragment.forEach((node) => { if (active.length || node.marks.length) { let keep = 0, rendered = 0; while (keep < active.length && rendered < node.marks.length) { let next = node.marks[rendered]; if (!this.marks[next.type.name]) { rendered++; continue; } if (!next.eq(active[keep][0]) || next.type.spec.spanning === false) break; keep++; rendered++; } while (keep < active.length) top = active.pop()[1]; while (rendered < node.marks.length) { let add = node.marks[rendered++]; let markDOM = this.serializeMark(add, node.isInline, options); if (markDOM) { active.push([add, top]); top.appendChild(markDOM.dom); top = markDOM.contentDOM || markDOM.dom; } } } top.appendChild(this.serializeNodeInner(node, options)); }); return target; } /** @internal */ serializeNodeInner(node, options) { if (node.isText) return doc$2(options).createTextNode(node.text); let { dom, contentDOM } = renderSpec(doc$2(options), this.nodes[node.type.name](node), null, node.attrs); if (contentDOM) { if (node.isLeaf) throw new RangeError("Content hole not allowed in a leaf node spec"); this.serializeFragment(node.content, options, contentDOM); } return dom; } /** Serialize this node to a DOM node. This can be useful when you need to serialize a part of a document, as opposed to the whole document. To serialize a whole document, use [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on its [content](https://prosemirror.net/docs/ref/#model.Node.content). */ serializeNode(node, options = {}) { let dom = this.serializeNodeInner(node, options); for (let i = node.marks.length - 1; i >= 0; i--) { let wrap2 = this.serializeMark(node.marks[i], node.isInline, options); if (wrap2) { (wrap2.contentDOM || wrap2.dom).appendChild(dom); dom = wrap2.dom; } } return dom; } /** @internal */ serializeMark(mark, inline, options = {}) { let toDOM = this.marks[mark.type.name]; return toDOM && renderSpec(doc$2(options), toDOM(mark, inline), null, mark.attrs); } static renderSpec(doc2, structure, xmlNS = null, blockArraysIn) { if (typeof structure == "string") return { dom: doc2.createTextNode(structure) }; return renderSpec(doc2, structure, xmlNS, blockArraysIn); } /** Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM) properties in a schema's node and mark specs. */ static fromSchema(schema) { return schema.cached.domSerializer || (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema))); } /** Gather the serializers in a schema's node specs into an object. This can be useful as a base to build a custom serializer from. */ static nodesFromSchema(schema) { let result = gatherToDOM(schema.nodes); if (!result.text) result.text = (node) => node.text; return result; } /** Gather the serializers in a schema's mark specs into an object. */ static marksFromSchema(schema) { return gatherToDOM(schema.marks); } } function gatherToDOM(obj) { let result = {}; for (let name in obj) { let toDOM = obj[name].spec.toDOM; if (toDOM) result[name] = toDOM; } return result; } function doc$2(options) { return options.document || window.document; } const suspiciousAttributeCache = /* @__PURE__ */ new WeakMap(); function suspiciousAttributes(attrs) { let value = suspiciousAttributeCache.get(attrs); if (value === void 0) suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs)); return value; } function suspiciousAttributesInner(attrs) { let result = null; function scan(value) { if (value && typeof value == "object") { if (Array.isArray(value)) { if (typeof value[0] == "string") { if (!result) result = []; result.push(value); } else { for (let i = 0; i < value.length; i++) scan(value[i]); } } else { for (let prop in value) scan(value[prop]); } } } scan(attrs); return result; } function renderSpec(doc2, structure, xmlNS, blockArraysIn) { if (structure.nodeType == 1) return { dom: structure }; if (structure.dom && structure.dom.nodeType == 1) return structure; let tagName = structure[0], suspicious; if (typeof tagName != "string") throw new RangeError("Invalid array passed to renderSpec"); if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1) throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack."); let space = tagName.indexOf(" "); if (space > 0) { xmlNS = tagName.slice(0, space); tagName = tagName.slice(space + 1); } let contentDOM; let dom = xmlNS ? doc2.createElementNS(xmlNS, tagName) : doc2.createElement(tagName); let attrs = structure[1], start = 1; if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) { start = 2; for (let name in attrs) if (attrs[name] != null) { let space2 = name.indexOf(" "); if (space2 > 0) dom.setAttributeNS(name.slice(0, space2), name.slice(space2 + 1), attrs[name]); else if (name == "style" && dom.style) dom.style.cssText = attrs[name]; else dom.setAttribute(name, attrs[name]); } } for (let i = start; i < structure.length; i++) { let child = structure[i]; if (child === 0) { if (i < structure.length - 1 || i > start) throw new RangeError("Content hole must be the only child of its parent node"); return { dom, contentDOM: dom }; } else if (typeof child == "string") { dom.appendChild(doc2.createTextNode(child)); } else { let { dom: inner, contentDOM: innerContent } = renderSpec(doc2, child, xmlNS, blockArraysIn); dom.appendChild(inner); if (innerContent) { if (contentDOM) throw new RangeError("Multiple content holes"); contentDOM = innerContent; } } } return { dom, contentDOM }; } const lower16 = 65535; const factor16 = Math.pow(2, 16); function makeRecover(index, offset) { return index + offset * factor16; } function recoverIndex(value) { return value & lower16; } function recoverOffset(value) { return (value - (value & lower16)) / factor16; } const DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8; class MapResult { /** @internal */ constructor(pos, delInfo, recover) { this.pos = pos; this.delInfo = delInfo; this.recover = recover; } /** Tells you whether the position was deleted, that is, whether the step removed the token on the side queried (via the `assoc`) argument from the document. */ get deleted() { return (this.delInfo & DEL_SIDE) > 0; } /** Tells you whether the token before the mapped position was deleted. */ get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; } /** True when the token after the mapped position was deleted. */ get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; } /** Tells whether any of the steps mapped through deletes across the position (including both the token before and after the position). */ get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; } } class StepMap { /** Create a position map. The modifications to the document are represented as an array of numbers, in which each group of three represents a modified chunk as `[start, oldSize, newSize]`. */ constructor(ranges, inverted = false) { this.ranges = ranges; this.inverted = inverted; if (!ranges.length && StepMap.empty) return StepMap.empty; } /** @internal */ recover(value) { let diff = 0, index = recoverIndex(value); if (!this.inverted) for (let i = 0; i < index; i++) diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1]; return this.ranges[index * 3] + diff + recoverOffset(value); } mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); } map(pos, assoc = 1) { return this._map(pos, assoc, true); } /** @internal */ _map(pos, assoc, simple) { let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; for (let i = 0; i < this.ranges.length; i += 3) { let start = this.ranges[i] - (this.inverted ? diff : 0); if (start > pos) break; let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize; if (pos <= end) { let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc; let result = start + diff + (side < 0 ? 0 : newSize); if (simple) return result; let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start); let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS; if (assoc < 0 ? pos != start : pos != end) del |= DEL_SIDE; return new MapResult(result, del, recover); } diff += newSize - oldSize; } return simple ? pos + diff : new MapResult(pos + diff, 0, null); } /** @internal */ touches(pos, recover) { let diff = 0, index = recoverIndex(recover); let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; for (let i = 0; i < this.ranges.length; i += 3) { let start = this.ranges[i] - (this.inverted ? diff : 0); if (start > pos) break; let oldSize = this.ranges[i + oldIndex], end = start + oldSize; if (pos <= end && i == index * 3) return true; diff += this.ranges[i + newIndex] - oldSize; } return false; } /** Calls the given function on each of the changed ranges included in this map. */ forEach(f) { let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; for (let i = 0, diff = 0; i < this.ranges.length; i += 3) { let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff); let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex]; f(oldStart, oldStart + oldSize, newStart, newStart + newSize); diff += newSize - oldSize; } } /** Create an inverted version of this map. The result can be used to map positions in the post-step document to the pre-step document. */ invert() { return new StepMap(this.ranges, !this.inverted); } /** @internal */ toString() { return (this.inverted ? "-" : "") + JSON.stringify(this.ranges); } /** Create a map that moves all positions by offset `n` (which may be negative). This can be useful when applying steps meant for a sub-document to a larger document, or vice-versa. */ static offset(n) { return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]); } } StepMap.empty = new StepMap([]); class Mapping { /** Create a new mapping with the given position maps. */ constructor(maps, mirror, from2 = 0, to = maps ? maps.length : 0) { this.mirror = mirror; this.from = from2; this.to = to; this._maps = maps || []; this.ownData = !(maps || mirror); } /** The step maps in this mapping. */ get maps() { return this._maps; } /** Create a mapping that maps only through a part of this one. */ slice(from2 = 0, to = this.maps.length) { return new Mapping(this._maps, this.mirror, from2, to); } /** Add a step map to the end of this mapping. If `mirrors` is given, it should be the index of the step map that is the mirror image of this one. */ appendMap(map2, mirrors) { if (!this.ownData) { this._maps = this._maps.slice(); this.mirror = this.mirror && this.mirror.slice(); this.ownData = true; } this.to = this._maps.push(map2); if (mirrors != null) this.setMirror(this._maps.length - 1, mirrors); } /** Add all the step maps in a given mapping to this one (preserving mirroring information). */ appendMapping(mapping) { for (let i = 0, startSize = this._maps.length; i < mapping._maps.length; i++) { let mirr = mapping.getMirror(i); this.appendMap(mapping._maps[i], mirr != null && mirr < i ? startSize + mirr : void 0); } } /** Finds the offset of the step map that mirrors the map at the given offset, in this mapping (as per the second argument to `appendMap`). */ getMirror(n) { if (this.mirror) { for (let i = 0; i < this.mirror.length; i++) if (this.mirror[i] == n) return this.mirror[i + (i % 2 ? -1 : 1)]; } } /** @internal */ setMirror(n, m) { if (!this.mirror) this.mirror = []; this.mirror.push(n, m); } /** Append the inverse of the given mapping to this one. */ appendMappingInverted(mapping) { for (let i = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i >= 0; i--) { let mirr = mapping.getMirror(i); this.appendMap(mapping._maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : void 0); } } /** Create an inverted version of this mapping. */ invert() { let inverse = new Mapping(); inverse.appendMappingInverted(this); return inverse; } /** Map a position through this mapping. */ map(pos, assoc = 1) { if (this.mirror) return this._map(pos, assoc, true); for (let i = this.from; i < this.to; i++) pos = this._maps[i].map(pos, assoc); return pos; } /** Map a position through this mapping, returning a mapping result. */ mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); } /** @internal */ _map(pos, assoc, simple) { let delInfo = 0; for (let i = this.from; i < this.to; i++) { let map2 = this._maps[i], result = map2.mapResult(pos, assoc); if (result.recover != null) { let corr = this.getMirror(i); if (corr != null && corr > i && corr < this.to) { i = corr; pos = this._maps[corr].recover(result.recover); continue; } } delInfo |= result.delInfo; pos = result.pos; } return simple ? pos : new MapResult(pos, delInfo, null); } } const stepsByID = /* @__PURE__ */ Object.create(null); class Step { /** Get the step map that represents the changes made by this step, and which can be used to transform between positions in the old and the new document. */ getMap() { return StepMap.empty; } /** Try to merge this step with another one, to be applied directly after it. Returns the merged step when possible, null if the steps can't be merged. */ merge(other) { return null; } /** Deserialize a step from its JSON representation. Will call through to the step class' own implementation of this method. */ static fromJSON(schema, json) { if (!json || !json.stepType) throw new RangeError("Invalid input for Step.fromJSON"); let type = stepsByID[json.stepType]; if (!type) throw new RangeError(`No step type ${json.stepType} defined`); return type.fromJSON(schema, json); } /** To be able to serialize steps to JSON, each step needs a string ID to attach to its JSON representation. Use this method to register an ID for your step classes. Try to pick something that's unlikely to clash with steps from other modules. */ static jsonID(id, stepClass) { if (id in stepsByID) throw new RangeError("Duplicate use of step JSON ID " + id); stepsByID[id] = stepClass; stepClass.prototype.jsonID = id; return stepClass; } } class StepResult { /** @internal */ constructor(doc2, failed) { this.doc = doc2; this.failed = failed; } /** Create a successful step result. */ static ok(doc2) { return new StepResult(doc2, null); } /** Create a failed step result. */ static fail(message) { return new StepResult(null, message); } /** Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given arguments. Create a successful result if it succeeds, and a failed one if it throws a `ReplaceError`. */ static fromReplace(doc2, from2, to, slice2) { try { return StepResult.ok(doc2.replace(from2, to, slice2)); } catch (e) { if (e instanceof ReplaceError) return StepResult.fail(e.message); throw e; } } } function mapFragment(fragment, f, parent) { let mapped = []; for (let i = 0; i < fragment.childCount; i++) { let child = fragment.child(i); if (child.content.size) child = child.copy(mapFragment(child.content, f, child)); if (child.isInline) child = f(child, parent, i); mapped.push(child); } return Fragment.fromArray(mapped); } class AddMarkStep extends Step { /** Create a mark step. */ constructor(from2, to, mark) { super(); this.from = from2; this.to = to; this.mark = mark; } apply(doc2) { let oldSlice = doc2.slice(this.from, this.to), $from = doc2.resolve(this.from); let parent = $from.node($from.sharedDepth(this.to)); let slice2 = new Slice(mapFragment(oldSlice.content, (node, parent2) => { if (!node.isAtom || !parent2.type.allowsMarkType(this.mark.type)) return node; return node.mark(this.mark.addToSet(node.marks)); }, parent), oldSlice.openStart, oldSlice.openEnd); return StepResult.fromReplace(doc2, this.from, this.to, slice2); } invert() { return new RemoveMarkStep(this.from, this.to, this.mark); } map(mapping) { let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); if (from2.deleted && to.deleted || from2.pos >= to.pos) return null; return new AddMarkStep(from2.pos, to.pos, this.mark); } merge(other) { if (other instanceof AddMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark); return null; } toJSON() { return { stepType: "addMark", mark: this.mark.toJSON(), from: this.from, to: this.to }; } /** @internal */ static fromJSON(schema, json) { if (typeof json.from != "number" || typeof json.to != "number") throw new RangeError("Invalid input for AddMarkStep.fromJSON"); return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark)); } } Step.jsonID("addMark", AddMarkStep); class RemoveMarkStep extends Step { /** Create a mark-removing step. */ constructor(from2, to, mark) { super(); this.from = from2; this.to = to; this.mark = mark; } apply(doc2) { let oldSlice = doc2.slice(this.from, this.to); let slice2 = new Slice(mapFragment(oldSlice.content, (node) => { return node.mark(this.mark.removeFromSet(node.marks)); }, doc2), oldSlice.openStart, oldSlice.openEnd); return StepResult.fromReplace(doc2, this.from, this.to, slice2); } invert() { return new AddMarkStep(this.from, this.to, this.mark); } map(mapping) { let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); if (from2.deleted && to.deleted || from2.pos >= to.pos) return null; return new RemoveMarkStep(from2.pos, to.pos, this.mark); } merge(other) { if (other instanceof RemoveMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark); return null; } toJSON() { return { stepType: "removeMark", mark: this.mark.toJSON(), from: this.from, to: this.to }; } /** @internal */ static fromJSON(schema, json) { if (typeof json.from != "number" || typeof json.to != "number") throw new RangeError("Invalid input for RemoveMarkStep.fromJSON"); return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark)); } } Step.jsonID("removeMark", RemoveMarkStep); class AddNodeMarkStep extends Step { /** Create a node mark step. */ constructor(pos, mark) { super(); this.pos = pos; this.mark = mark; } apply(doc2) { let node = doc2.nodeAt(this.pos); if (!node) return StepResult.fail("No node at mark step's position"); let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks)); return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); } invert(doc2) { let node = doc2.nodeAt(this.pos); if (node) { let newSet = this.mark.addToSet(node.marks); if (newSet.length == node.marks.length) { for (let i = 0; i < node.marks.length; i++) if (!node.marks[i].isInSet(newSet)) return new AddNodeMarkStep(this.pos, node.marks[i]); return new AddNodeMarkStep(this.pos, this.mark); } } return new RemoveNodeMarkStep(this.pos, this.mark); } map(mapping) { let pos = mapping.mapResult(this.pos, 1); return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark); } toJSON() { return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() }; } /** @internal */ static fromJSON(schema, json) { if (typeof json.pos != "number") throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON"); return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark)); } } Step.jsonID("addNodeMark", AddNodeMarkStep); class RemoveNodeMarkStep extends Step { /** Create a mark-removing step. */ constructor(pos, mark) { super(); this.pos = pos; this.mark = mark; } apply(doc2) { let node = doc2.nodeAt(this.pos); if (!node) return StepResult.fail("No node at mark step's position"); let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks)); return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); } invert(doc2) { let node = doc2.nodeAt(this.pos); if (!node || !this.mark.isInSet(node.marks)) return this; return new AddNodeMarkStep(this.pos, this.mark); } map(mapping) { let pos = mapping.mapResult(this.pos, 1); return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark); } toJSON() { return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() }; } /** @internal */ static fromJSON(schema, json) { if (typeof json.pos != "number") throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON"); return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark)); } } Step.jsonID("removeNodeMark", RemoveNodeMarkStep); class ReplaceStep extends Step { /** The given `slice` should fit the 'gap' between `from` and `to`—the depths must line up, and the surrounding nodes must be able to be joined with the open sides of the slice. When `structure` is true, the step will fail if the content between from and to is not just a sequence of closing and then opening tokens (this is to guard against rebased replace steps overwriting something they weren't supposed to). */ constructor(from2, to, slice2, structure = false) { super(); this.from = from2; this.to = to; this.slice = slice2; this.structure = structure; } apply(doc2) { if (this.structure && contentBetween(doc2, this.from, this.to)) return StepResult.fail("Structure replace would overwrite content"); return StepResult.fromReplace(doc2, this.from, this.to, this.slice); } getMap() { return new StepMap([this.from, this.to - this.from, this.slice.size]); } invert(doc2) { return new ReplaceStep(this.from, this.from + this.slice.size, doc2.slice(this.from, this.to)); } map(mapping) { let to = mapping.mapResult(this.to, -1); let from2 = this.from == this.to && ReplaceStep.MAP_BIAS < 0 ? to : mapping.mapResult(this.from, 1); if (from2.deletedAcross && to.deletedAcross) return null; return new ReplaceStep(from2.pos, Math.max(from2.pos, to.pos), this.slice, this.structure); } merge(other) { if (!(other instanceof ReplaceStep) || other.structure || this.structure) return null; if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) { let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd); return new ReplaceStep(this.from, this.to + (other.to - other.from), slice2, this.structure); } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) { let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd); return new ReplaceStep(other.from, this.to, slice2, this.structure); } else { return null; } } toJSON() { let json = { stepType: "replace", from: this.from, to: this.to }; if (this.slice.size) json.slice = this.slice.toJSON(); if (this.structure) json.structure = true; return json; } /** @internal */ static fromJSON(schema, json) { if (typeof json.from != "number" || typeof json.to != "number") throw new RangeError("Invalid input for ReplaceStep.fromJSON"); return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure); } } ReplaceStep.MAP_BIAS = 1; Step.jsonID("replace", ReplaceStep); class ReplaceAroundStep extends Step { /** Create a replace-around step with the given range and gap. `insert` should be the point in the slice into which the content of the gap should be moved. `structure` has the same meaning as it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class. */ constructor(from2, to, gapFrom, gapTo, slice2, insert, structure = false) { super(); this.from = from2; this.to = to; this.gapFrom = gapFrom; this.gapTo = gapTo; this.slice = slice2; this.insert = insert; this.structure = structure; } apply(doc2) { if (this.structure && (contentBetween(doc2, this.from, this.gapFrom) || contentBetween(doc2, this.gapTo, this.to))) return StepResult.fail("Structure gap-replace would overwrite content"); let gap = doc2.slice(this.gapFrom, this.gapTo); if (gap.openStart || gap.openEnd) return StepResult.fail("Gap is not a flat range"); let inserted = this.slice.insertAt(this.insert, gap.content); if (!inserted) return StepResult.fail("Content does not fit in gap"); return StepResult.fromReplace(doc2, this.from, this.to, inserted); } getMap() { return new StepMap([ this.from, this.gapFrom - this.from, this.insert, this.gapTo, this.to - this.gapTo, this.slice.size - this.insert ]); } invert(doc2) { let gap = this.gapTo - this.gapFrom; return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc2.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure); } map(mapping) { let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); let gapFrom = this.from == this.gapFrom ? from2.pos : mapping.map(this.gapFrom, -1); let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1); if (from2.deletedAcross && to.deletedAcross || gapFrom < from2.pos || gapTo > to.pos) return null; return new ReplaceAroundStep(from2.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure); } toJSON() { let json = { stepType: "replaceAround", from: this.from, to: this.to, gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert }; if (this.slice.size) json.slice = this.slice.toJSON(); if (this.structure) json.structure = true; return json; } /** @internal */ static fromJSON(schema, json) { if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number") throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON"); return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure); } } Step.jsonID("replaceAround", ReplaceAroundStep); function contentBetween(doc2, from2, to) { let $from = doc2.resolve(from2), dist = to - from2, depth = $from.depth; while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) { depth--; dist--; } if (dist > 0) { let next = $from.node(depth).maybeChild($from.indexAfter(depth)); while (dist > 0) { if (!next || next.isLeaf) return true; next = next.firstChild; dist--; } } return false; } function addMark(tr2, from2, to, mark) { let removed = [], added = []; let removing, adding; tr2.doc.nodesBetween(from2, to, (node, pos, parent) => { if (!node.isInline) return; let marks = node.marks; if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) { let start = Math.max(pos, from2), end = Math.min(pos + node.nodeSize, to); let newSet = mark.addToSet(marks); for (let i = 0; i < marks.length; i++) { if (!marks[i].isInSet(newSet)) { if (removing && removing.to == start && removing.mark.eq(marks[i])) removing.to = end; else removed.push(removing = new RemoveMarkStep(start, end, marks[i])); } } if (adding && adding.to == start) adding.to = end; else added.push(adding = new AddMarkStep(start, end, mark)); } }); removed.forEach((s) => tr2.step(s)); added.forEach((s) => tr2.step(s)); } function removeMark(tr2, from2, to, mark) { let matched = [], step = 0; tr2.doc.nodesBetween(from2, to, (node, pos) => { if (!node.isInline) return; step++; let toRemove = null; if (mark instanceof MarkType) { let set = node.marks, found2; while (found2 = mark.isInSet(set)) { (toRemove || (toRemove = [])).push(found2); set = found2.removeFromSet(set); } } else if (mark) { if (mark.isInSet(node.marks)) toRemove = [mark]; } else { toRemove = node.marks; } if (toRemove && toRemove.length) { let end = Math.min(pos + node.nodeSize, to); for (let i = 0; i < toRemove.length; i++) { let style = toRemove[i], found2; for (let j = 0; j < matched.length; j++) { let m = matched[j]; if (m.step == step - 1 && style.eq(matched[j].style)) found2 = m; } if (found2) { found2.to = end; found2.step = step; } else { matched.push({ style, from: Math.max(pos, from2), to: end, step }); } } } }); matched.forEach((m) => tr2.step(new RemoveMarkStep(m.from, m.to, m.style))); } function clearIncompatible(tr2, pos, parentType, match = parentType.contentMatch, clearNewlines = true) { let node = tr2.doc.nodeAt(pos); let replSteps = [], cur = pos + 1; for (let i = 0; i < node.childCount; i++) { let child = node.child(i), end = cur + child.nodeSize; let allowed = match.matchType(child.type); if (!allowed) { replSteps.push(new ReplaceStep(cur, end, Slice.empty)); } else { match = allowed; for (let j = 0; j < child.marks.length; j++) if (!parentType.allowsMarkType(child.marks[j].type)) tr2.step(new RemoveMarkStep(cur, end, child.marks[j])); if (clearNewlines && child.isText && parentType.whitespace != "pre") { let m, newline = /\r?\n|\r/g, slice2; while (m = newline.exec(child.text)) { if (!slice2) slice2 = new Slice(Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child.marks))), 0, 0); replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice2)); } } } cur = end; } if (!match.validEnd) { let fill = match.fillBefore(Fragment.empty, true); tr2.replace(cur, cur, new Slice(fill, 0, 0)); } for (let i = replSteps.length - 1; i >= 0; i--) tr2.step(replSteps[i]); } function canCut(node, start, end) { return (start == 0 || node.canReplace(start, node.childCount)) && (end == node.childCount || node.canReplace(0, end)); } function liftTarget(range) { let parent = range.parent; let content = parent.content.cutByIndex(range.startIndex, range.endIndex); for (let depth = range.depth, contentBefore = 0, contentAfter = 0; ; --depth) { let node = range.$from.node(depth); let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter; if (depth < range.depth && node.canReplace(index, endIndex, content)) return depth; if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex)) break; if (index) contentBefore = 1; if (endIndex < node.childCount) contentAfter = 1; } return null; } function lift$2(tr2, range, target) { let { $from, $to, depth } = range; let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1); let start = gapStart, end = gapEnd; let before = Fragment.empty, openStart = 0; for (let d = depth, splitting = false; d > target; d--) if (splitting || $from.index(d) > 0) { splitting = true; before = Fragment.from($from.node(d).copy(before)); openStart++; } else { start--; } let after = Fragment.empty, openEnd = 0; for (let d = depth, splitting = false; d > target; d--) if (splitting || $to.after(d + 1) < $to.end(d)) { splitting = true; after = Fragment.from($to.node(d).copy(after)); openEnd++; } else { end++; } tr2.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true)); } function findWrapping(range, nodeType, attrs = null, innerRange = range) { let around = findWrappingOutside(range, nodeType); let inner = around && findWrappingInside(innerRange, nodeType); if (!inner) return null; return around.map(withAttrs).concat({ type: nodeType, attrs }).concat(inner.map(withAttrs)); } function withAttrs(type) { return { type, attrs: null }; } function findWrappingOutside(range, type) { let { parent, startIndex, endIndex } = range; let around = parent.contentMatchAt(startIndex).findWrapping(type); if (!around) return null; let outer = around.length ? around[0] : type; return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null; } function findWrappingInside(range, type) { let { parent, startIndex, endIndex } = range; let inner = parent.child(startIndex); let inside = type.contentMatch.findWrapping(inner.type); if (!inside) return null; let lastType = inside.length ? inside[inside.length - 1] : type; let innerMatch = lastType.contentMatch; for (let i = startIndex; innerMatch && i < endIndex; i++) innerMatch = innerMatch.matchType(parent.child(i).type); if (!innerMatch || !innerMatch.validEnd) return null; return inside; } function wrap(tr2, range, wrappers) { let content = Fragment.empty; for (let i = wrappers.length - 1; i >= 0; i--) { if (content.size) { let match = wrappers[i].type.contentMatch.matchFragment(content); if (!match || !match.validEnd) throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper"); } content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); } let start = range.start, end = range.end; tr2.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true)); } function setBlockType$1(tr2, from2, to, type, attrs) { if (!type.isTextblock) throw new RangeError("Type given to setBlockType should be a textblock"); let mapFrom = tr2.steps.length; tr2.doc.nodesBetween(from2, to, (node, pos) => { let attrsHere = typeof attrs == "function" ? attrs(node) : attrs; if (node.isTextblock && !node.hasMarkup(type, attrsHere) && canChangeType(tr2.doc, tr2.mapping.slice(mapFrom).map(pos), type)) { let convertNewlines = null; if (type.schema.linebreakReplacement) { let pre = type.whitespace == "pre", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement); if (pre && !supportLinebreak) convertNewlines = false; else if (!pre && supportLinebreak) convertNewlines = true; } if (convertNewlines === false) replaceLinebreaks(tr2, node, pos, mapFrom); clearIncompatible(tr2, tr2.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null); let mapping = tr2.mapping.slice(mapFrom); let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1); tr2.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true)); if (convertNewlines === true) replaceNewlines(tr2, node, pos, mapFrom); return false; } }); } function replaceNewlines(tr2, node, pos, mapFrom) { node.forEach((child, offset) => { if (child.isText) { let m, newline = /\r?\n|\r/g; while (m = newline.exec(child.text)) { let start = tr2.mapping.slice(mapFrom).map(pos + 1 + offset + m.index); tr2.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create()); } } }); } function replaceLinebreaks(tr2, node, pos, mapFrom) { node.forEach((child, offset) => { if (child.type == child.type.schema.linebreakReplacement) { let start = tr2.mapping.slice(mapFrom).map(pos + 1 + offset); tr2.replaceWith(start, start + 1, node.type.schema.text("\n")); } }); } function canChangeType(doc2, pos, type) { let $pos = doc2.resolve(pos), index = $pos.index(); return $pos.parent.canReplaceWith(index, index + 1, type); } function setNodeMarkup(tr2, pos, type, attrs, marks) { let node = tr2.doc.nodeAt(pos); if (!node) throw new RangeError("No node at given position"); if (!type) type = node.type; let newNode = type.create(attrs, null, marks || node.marks); if (node.isLeaf) return tr2.replaceWith(pos, pos + node.nodeSize, newNode); if (!type.validContent(node.content)) throw new RangeError("Invalid content for node type " + type.name); tr2.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true)); } function canSplit(doc2, pos, depth = 1, typesAfter) { let $pos = doc2.resolve(pos), base2 = $pos.depth - depth; let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent; if (base2 < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount))) return false; for (let d = $pos.depth - 1, i = depth - 2; d > base2; d--, i--) { let node = $pos.node(d), index2 = $pos.index(d); if (node.type.spec.isolating) return false; let rest = node.content.cutByIndex(index2, node.childCount); let overrideChild = typesAfter && typesAfter[i + 1]; if (overrideChild) rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs)); let after = typesAfter && typesAfter[i] || node; if (!node.canReplace(index2 + 1, node.childCount) || !after.type.validContent(rest)) return false; } let index = $pos.indexAfter(base2); let baseType = typesAfter && typesAfter[0]; return $pos.node(base2).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base2 + 1).type); } function split(tr2, pos, depth = 1, typesAfter) { let $pos = tr2.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty; for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) { before = Fragment.from($pos.node(d).copy(before)); let typeAfter = typesAfter && typesAfter[i]; after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after)); } tr2.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true)); } function canJoin(doc2, pos) { let $pos = doc2.resolve(pos), index = $pos.index(); return joinable($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index, index + 1); } function canAppendWithSubstitutedLinebreaks(a, b) { if (!b.content.size) a.type.compatibleContent(b.type); let match = a.contentMatchAt(a.childCount); let { linebreakReplacement } = a.type.schema; for (let i = 0; i < b.childCount; i++) { let child = b.child(i); let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type; match = match.matchType(type); if (!match) return false; if (!a.type.allowsMarks(child.marks)) return false; } return match.validEnd; } function joinable(a, b) { return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b)); } function joinPoint(doc2, pos, dir = -1) { let $pos = doc2.resolve(pos); for (let d = $pos.depth; ; d--) { let before, after, index = $pos.index(d); if (d == $pos.depth) { before = $pos.nodeBefore; after = $pos.nodeAfter; } else if (dir > 0) { before = $pos.node(d + 1); index++; after = $pos.node(d).maybeChild(index); } else { before = $pos.node(d).maybeChild(index - 1); after = $pos.node(d + 1); } if (before && !before.isTextblock && joinable(before, after) && $pos.node(d).canReplace(index, index + 1)) return pos; if (d == 0) break; pos = dir < 0 ? $pos.before(d) : $pos.after(d); } } function join(tr2, pos, depth) { let convertNewlines = null; let { linebreakReplacement } = tr2.doc.type.schema; let $before = tr2.doc.resolve(pos - depth), beforeType = $before.node().type; if (linebreakReplacement && beforeType.inlineContent) { let pre = beforeType.whitespace == "pre"; let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement); if (pre && !supportLinebreak) convertNewlines = false; else if (!pre && supportLinebreak) convertNewlines = true; } let mapFrom = tr2.steps.length; if (convertNewlines === false) { let $after = tr2.doc.resolve(pos + depth); replaceLinebreaks(tr2, $after.node(), $after.before(), mapFrom); } if (beforeType.inlineContent) clearIncompatible(tr2, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null); let mapping = tr2.mapping.slice(mapFrom), start = mapping.map(pos - depth); tr2.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true)); if (convertNewlines === true) { let $full = tr2.doc.resolve(start); replaceNewlines(tr2, $full.node(), $full.before(), tr2.steps.length); } return tr2; } function insertPoint(doc2, pos, nodeType) { let $pos = doc2.resolve(pos); if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) return pos; if ($pos.parentOffset == 0) for (let d = $pos.depth - 1; d >= 0; d--) { let index = $pos.index(d); if ($pos.node(d).canReplaceWith(index, index, nodeType)) return $pos.before(d + 1); if (index > 0) return null; } if ($pos.parentOffset == $pos.parent.content.size) for (let d = $pos.depth - 1; d >= 0; d--) { let index = $pos.indexAfter(d); if ($pos.node(d).canReplaceWith(index, index, nodeType)) return $pos.after(d + 1); if (index < $pos.node(d).childCount) return null; } return null; } function dropPoint(doc2, pos, slice2) { let $pos = doc2.resolve(pos); if (!slice2.content.size) return pos; let content = slice2.content; for (let i = 0; i < slice2.openStart; i++) content = content.firstChild.content; for (let pass = 1; pass <= (slice2.openStart == 0 && slice2.size ? 2 : 1); pass++) { for (let d = $pos.depth; d >= 0; d--) { let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1; let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0); let parent = $pos.node(d), fits = false; if (pass == 1) { fits = parent.canReplace(insertPos, insertPos, content); } else { let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type); fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]); } if (fits) return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1); } } return null; } function replaceStep(doc2, from2, to = from2, slice2 = Slice.empty) { if (from2 == to && !slice2.size) return null; let $from = doc2.resolve(from2), $to = doc2.resolve(to); if (fitsTrivially($from, $to, slice2)) return new ReplaceStep(from2, to, slice2); return new Fitter($from, $to, slice2).fit(); } function fitsTrivially($from, $to, slice2) { return !slice2.openStart && !slice2.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice2.content); } class Fitter { constructor($from, $to, unplaced) { this.$from = $from; this.$to = $to; this.unplaced = unplaced; this.frontier = []; this.placed = Fragment.empty; for (let i = 0; i <= $from.depth; i++) { let node = $from.node(i); this.frontier.push({ type: node.type, match: node.contentMatchAt($from.indexAfter(i)) }); } for (let i = $from.depth; i > 0; i--) this.placed = Fragment.from($from.node(i).copy(this.placed)); } get depth() { return this.frontier.length - 1; } fit() { while (this.unplaced.size) { let fit = this.findFittable(); if (fit) this.placeNodes(fit); else this.openMore() || this.dropNode(); } let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth; let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline)); if (!$to) return null; let content = this.placed, openStart = $from.depth, openEnd = $to.depth; while (openStart && openEnd && content.childCount == 1) { content = content.firstChild.content; openStart--; openEnd--; } let slice2 = new Slice(content, openStart, openEnd); if (moveInline > -1) return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice2, placedSize); if (slice2.size || $from.pos != this.$to.pos) return new ReplaceStep($from.pos, $to.pos, slice2); return null; } // Find a position on the start spine of `this.unplaced` that has // content that can be moved somewhere on the frontier. Returns two // depths, one for the slice and one for the frontier. findFittable() { let startDepth = this.unplaced.openStart; for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) { let node = cur.firstChild; if (cur.childCount > 1) openEnd = 0; if (node.type.spec.isolating && openEnd <= d) { startDepth = d; break; } cur = node.content; } for (let pass = 1; pass <= 2; pass++) { for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) { let fragment, parent = null; if (sliceDepth) { parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild; fragment = parent.content; } else { fragment = this.unplaced.content; } let first2 = fragment.firstChild; for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) { let { type, match } = this.frontier[frontierDepth], wrap2, inject = null; if (pass == 1 && (first2 ? match.matchType(first2.type) || (inject = match.fillBefore(Fragment.from(first2), false)) : parent && type.compatibleContent(parent.type))) return { sliceDepth, frontierDepth, parent, inject }; else if (pass == 2 && first2 && (wrap2 = match.findWrapping(first2.type))) return { sliceDepth, frontierDepth, parent, wrap: wrap2 }; if (parent && match.matchType(parent.type)) break; } } } } openMore() { let { content, openStart, openEnd } = this.unplaced; if (maxOpen(content, -1) <= openStart) return false; if (this.unplaced.size > 1 && maxOpen(content, 1) > openEnd) openEnd++; this.unplaced = new Slice(content, openStart + 1, openEnd); return true; } dropNode() { let { content, openStart, openEnd } = this.unplaced; let inner = contentAt(content, openStart); if (inner.childCount <= 1 && openStart > 0) { let openAtEnd = content.size - openStart <= openStart + inner.size; this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd); } else { this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd); } } // Move content from the unplaced slice at `sliceDepth` to the // frontier node at `frontierDepth`. Close that frontier node when // applicable. placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap: wrap2 }) { while (this.depth > frontierDepth) this.closeFrontierNode(); if (wrap2) for (let i = 0; i < wrap2.length; i++) this.openFrontierNode(wrap2[i]); let slice2 = this.unplaced, fragment = parent ? parent.content : slice2.content; let openStart = slice2.openStart - sliceDepth; let taken = 0, add = []; let { match, type } = this.frontier[frontierDepth]; if (inject) { for (let i = 0; i < inject.childCount; i++) add.push(inject.child(i)); match = match.matchFragment(inject); } let openEndCount = fragment.size + sliceDepth - (slice2.content.size - slice2.openEnd); while (taken < fragment.childCount) { let next = fragment.child(taken), matches2 = match.matchType(next.type); if (!matches2) break; taken++; if (taken > 1 || openStart == 0 || next.content.size) { match = matches2; add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1)); } } let toEnd = taken == fragment.childCount; if (!toEnd) openEndCount = -1; this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add)); this.frontier[frontierDepth].match = match; if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1) this.closeFrontierNode(); for (let i = 0, cur = fragment; i < openEndCount; i++) { let node = cur.lastChild; this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) }); cur = node.content; } this.unplaced = !toEnd ? new Slice(dropFromFragment(slice2.content, sliceDepth, taken), slice2.openStart, slice2.openEnd) : sliceDepth == 0 ? Slice.empty : new Slice(dropFromFragment(slice2.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice2.openEnd : sliceDepth - 1); } mustMoveInline() { if (!this.$to.parent.isTextblock) return -1; let top = this.frontier[this.depth], level; if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth) return -1; let { depth } = this.$to, after = this.$to.after(depth); while (depth > 1 && after == this.$to.end(--depth)) ++after; return after; } findCloseLevel($to) { scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) { let { match, type } = this.frontier[i]; let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1)); let fit = contentAfterFits($to, i, type, match, dropInner); if (!fit) continue; for (let d = i - 1; d >= 0; d--) { let { match: match2, type: type2 } = this.frontier[d]; let matches2 = contentAfterFits($to, d, type2, match2, true); if (!matches2 || matches2.childCount) continue scan; } return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to }; } } close($to) { let close2 = this.findCloseLevel($to); if (!close2) return null; while (this.depth > close2.depth) this.closeFrontierNode(); if (close2.fit.childCount) this.placed = addToFragment(this.placed, close2.depth, close2.fit); $to = close2.move; for (let d = close2.depth + 1; d <= $to.depth; d++) { let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d)); this.openFrontierNode(node.type, node.attrs, add); } return $to; } openFrontierNode(type, attrs = null, content) { let top = this.frontier[this.depth]; top.match = top.match.matchType(type); this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content))); this.frontier.push({ type, match: type.contentMatch }); } closeFrontierNode() { let open = this.frontier.pop(); let add = open.match.fillBefore(Fragment.empty, true); if (add.childCount) this.placed = addToFragment(this.placed, this.frontier.length, add); } } function dropFromFragment(fragment, depth, count) { if (depth == 0) return fragment.cutByIndex(count, fragment.childCount); return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count))); } function addToFragment(fragment, depth, content) { if (depth == 0) return fragment.append(content); return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content))); } function contentAt(fragment, depth) { for (let i = 0; i < depth; i++) fragment = fragment.firstChild.content; return fragment; } function closeNodeStart(node, openStart, openEnd) { if (openStart <= 0) return node; let frag = node.content; if (openStart > 1) frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0)); if (openStart > 0) { frag = node.type.contentMatch.fillBefore(frag).append(frag); if (openEnd <= 0) frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true)); } return node.copy(frag); } function contentAfterFits($to, depth, type, match, open) { let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth); if (index == node.childCount && !type.compatibleContent(node.type)) return null; let fit = match.fillBefore(node.content, true, index); return fit && !invalidMarks(type, node.content, index) ? fit : null; } function invalidMarks(type, fragment, start) { for (let i = start; i < fragment.childCount; i++) if (!type.allowsMarks(fragment.child(i).marks)) return true; return false; } function definesContent(type) { return type.spec.defining || type.spec.definingForContent; } function maxOpen(frag, side) { for (let count = 0; ; count++) { let ch = side < 0 ? frag.firstChild : frag.lastChild; if (!ch || ch.isAtom) return count; frag = ch.content; } } function replaceRange(tr2, from2, to, slice2) { if (!slice2.size) return tr2.deleteRange(from2, to); let $from = tr2.doc.resolve(from2), $to = tr2.doc.resolve(to); if (fitsTrivially($from, $to, slice2)) return tr2.step(new ReplaceStep(from2, to, slice2)); let targetDepths = coveredDepths($from, $to); if (targetDepths[targetDepths.length - 1] == 0) targetDepths.pop(); let preferredTarget = -($from.depth + 1); targetDepths.unshift(preferredTarget); for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) { let spec = $from.node(d).type.spec; if (spec.defining || spec.definingAsContext || spec.isolating) break; if (targetDepths.indexOf(d) > -1) preferredTarget = d; else if ($from.before(d) == pos) targetDepths.splice(1, 0, -d); } let preferredTargetIndex = targetDepths.indexOf(preferredTarget); let leftNodes = [], preferredDepth = slice2.openStart; for (let content = slice2.content, i = 0; ; i++) { let node = content.firstChild; leftNodes.push(node); if (i == slice2.openStart) break; content = node.content; } for (let d = preferredDepth - 1; d >= 0; d--) { let leftNode = leftNodes[d], def = definesContent(leftNode.type); if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1))) preferredDepth = d; else if (def || !leftNode.type.isTextblock) break; } for (let j = slice2.openStart; j >= 0; j--) { let openDepth = (j + preferredDepth + 1) % (slice2.openStart + 1); let insert = leftNodes[openDepth]; if (!insert) continue; for (let i = 0; i < targetDepths.length; i++) { let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true; if (targetDepth < 0) { expand = false; targetDepth = -targetDepth; } let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1); if (parent.canReplaceWith(index, index, insert.type, insert.marks)) return tr2.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice2.content, 0, slice2.openStart, openDepth), openDepth, slice2.openEnd)); } } let startSteps = tr2.steps.length; for (let i = targetDepths.length - 1; i >= 0; i--) { tr2.replace(from2, to, slice2); if (tr2.steps.length > startSteps) break; let depth = targetDepths[i]; if (depth < 0) continue; from2 = $from.before(depth); to = $to.after(depth); } } function closeFragment(fragment, depth, oldOpen, newOpen, parent) { if (depth < oldOpen) { let first2 = fragment.firstChild; fragment = fragment.replaceChild(0, first2.copy(closeFragment(first2.content, depth + 1, oldOpen, newOpen, first2))); } if (depth > newOpen) { let match = parent.contentMatchAt(0); let start = match.fillBefore(fragment).append(fragment); fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true)); } return fragment; } function replaceRangeWith(tr2, from2, to, node) { if (!node.isInline && from2 == to && tr2.doc.resolve(from2).parent.content.size) { let point = insertPoint(tr2.doc, from2, node.type); if (point != null) from2 = to = point; } tr2.replaceRange(from2, to, new Slice(Fragment.from(node), 0, 0)); } function deleteRange$1(tr2, from2, to) { let $from = tr2.doc.resolve(from2), $to = tr2.doc.resolve(to); if ($from.parent.isTextblock && $to.parent.isTextblock && $from.start() != $to.start() && $from.parentOffset == 0 && $to.parentOffset == 0) { let shared = $from.sharedDepth(to), isolated = false; for (let d = $from.depth; d > shared; d--) if ($from.node(d).type.spec.isolating) isolated = true; for (let d = $to.depth; d > shared; d--) if ($to.node(d).type.spec.isolating) isolated = true; if (!isolated) { for (let d = $from.depth; d > 0 && from2 == $from.start(d); d--) from2 = $from.before(d); for (let d = $to.depth; d > 0 && to == $to.start(d); d--) to = $to.before(d); $from = tr2.doc.resolve(from2); $to = tr2.doc.resolve(to); } } let covered = coveredDepths($from, $to); for (let i = 0; i < covered.length; i++) { let depth = covered[i], last = i == covered.length - 1; if (last && depth == 0 || $from.node(depth).type.contentMatch.validEnd) return tr2.delete($from.start(depth), $to.end(depth)); if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1)))) return tr2.delete($from.before(depth), $to.after(depth)); } for (let d = 1; d <= $from.depth && d <= $to.depth; d++) { if (from2 - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d && $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1))) return tr2.delete($from.before(d), to); } tr2.delete(from2, to); } function coveredDepths($from, $to) { let result = [], minDepth = Math.min($from.depth, $to.depth); for (let d = minDepth; d >= 0; d--) { let start = $from.start(d); if (start < $from.pos - ($from.depth - d) || $to.end(d) > $to.pos + ($to.depth - d) || $from.node(d).type.spec.isolating || $to.node(d).type.spec.isolating) break; if (start == $to.start(d) || d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent && d && $to.start(d - 1) == start - 1) result.push(d); } return result; } class AttrStep extends Step { /** Construct an attribute step. */ constructor(pos, attr, value) { super(); this.pos = pos; this.attr = attr; this.value = value; } apply(doc2) { let node = doc2.nodeAt(this.pos); if (!node) return StepResult.fail("No node at attribute step's position"); let attrs = /* @__PURE__ */ Object.create(null); for (let name in node.attrs) attrs[name] = node.attrs[name]; attrs[this.attr] = this.value; let updated = node.type.create(attrs, null, node.marks); return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); } getMap() { return StepMap.empty; } invert(doc2) { return new AttrStep(this.pos, this.attr, doc2.nodeAt(this.pos).attrs[this.attr]); } map(mapping) { let pos = mapping.mapResult(this.pos, 1); return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value); } toJSON() { return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value }; } static fromJSON(schema, json) { if (typeof json.pos != "number" || typeof json.attr != "string") throw new RangeError("Invalid input for AttrStep.fromJSON"); return new AttrStep(json.pos, json.attr, json.value); } } Step.jsonID("attr", AttrStep); class DocAttrStep extends Step { /** Construct an attribute step. */ constructor(attr, value) { super(); this.attr = attr; this.value = value; } apply(doc2) { let attrs = /* @__PURE__ */ Object.create(null); for (let name in doc2.attrs) attrs[name] = doc2.attrs[name]; attrs[this.attr] = this.value; let updated = doc2.type.create(attrs, doc2.content, doc2.marks); return StepResult.ok(updated); } getMap() { return StepMap.empty; } invert(doc2) { return new DocAttrStep(this.attr, doc2.attrs[this.attr]); } map(mapping) { return this; } toJSON() { return { stepType: "docAttr", attr: this.attr, value: this.value }; } static fromJSON(schema, json) { if (typeof json.attr != "string") throw new RangeError("Invalid input for DocAttrStep.fromJSON"); return new DocAttrStep(json.attr, json.value); } } Step.jsonID("docAttr", DocAttrStep); let TransformError = class extends Error { }; TransformError = function TransformError2(message) { let err = Error.call(this, message); err.__proto__ = TransformError2.prototype; return err; }; TransformError.prototype = Object.create(Error.prototype); TransformError.prototype.constructor = TransformError; TransformError.prototype.name = "TransformError"; class Transform { /** Create a transform that starts with the given document. */ constructor(doc2) { this.doc = doc2; this.steps = []; this.docs = []; this.mapping = new Mapping(); } /** The starting document. */ get before() { return this.docs.length ? this.docs[0] : this.doc; } /** Apply a new step in this transform, saving the result. Throws an error when the step fails. */ step(step) { let result = this.maybeStep(step); if (result.failed) throw new TransformError(result.failed); return this; } /** Try to apply a step in this transformation, ignoring it if it fails. Returns the step result. */ maybeStep(step) { let result = step.apply(this.doc); if (!result.failed) this.addStep(step, result.doc); return result; } /** True when the document has been changed (when there are any steps). */ get docChanged() { return this.steps.length > 0; } /** Return a single range, in post-transform document positions, that covers all content changed by this transform. Returns null if no replacements are made. Note that this will ignore changes that add/remove marks without replacing the underlying content. */ changedRange() { let from2 = 1e9, to = -1e9; for (let i = 0; i < this.mapping.maps.length; i++) { let map2 = this.mapping.maps[i]; if (i) { from2 = map2.map(from2, 1); to = map2.map(to, -1); } map2.forEach((_f, _t, fromB, toB) => { from2 = Math.min(from2, fromB); to = Math.max(to, toB); }); } return from2 == 1e9 ? null : { from: from2, to }; } /** @internal */ addStep(step, doc2) { this.docs.push(this.doc); this.steps.push(step); this.mapping.appendMap(step.getMap()); this.doc = doc2; } /** Replace the part of the document between `from` and `to` with the given `slice`. */ replace(from2, to = from2, slice2 = Slice.empty) { let step = replaceStep(this.doc, from2, to, slice2); if (step) this.step(step); return this; } /** Replace the given range with the given content, which may be a fragment, node, or array of nodes. */ replaceWith(from2, to, content) { return this.replace(from2, to, new Slice(Fragment.from(content), 0, 0)); } /** Delete the content between the given positions. */ delete(from2, to) { return this.replace(from2, to, Slice.empty); } /** Insert the given content at the given position. */ insert(pos, content) { return this.replaceWith(pos, pos, content); } /** Replace a range of the document with a given slice, using `from`, `to`, and the slice's [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather than fixed start and end points. This method may grow the replaced area or close open nodes in the slice in order to get a fit that is more in line with WYSIWYG expectations, by dropping fully covered parent nodes of the replaced region when they are marked [non-defining as context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an open parent node from the slice that _is_ marked as [defining its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent). This is the method, for example, to handle paste. The similar [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more primitive tool which will _not_ move the start and end of its given range, and is useful in situations where you need more precise control over what happens. */ replaceRange(from2, to, slice2) { replaceRange(this, from2, to, slice2); return this; } /** Replace the given range with a node, but use `from` and `to` as hints, rather than precise positions. When from and to are the same and are at the start or end of a parent node in which the given node doesn't fit, this method may _move_ them out towards a parent that does allow the given node to be placed. When the given range completely covers a parent node, this method may completely replace that parent node. */ replaceRangeWith(from2, to, node) { replaceRangeWith(this, from2, to, node); return this; } /** Delete the given range, expanding it to cover fully covered parent nodes until a valid replace is found. */ deleteRange(from2, to) { deleteRange$1(this, from2, to); return this; } /** Split the content in the given range off from its parent, if there is sibling content before or after it, and move it up the tree to the depth specified by `target`. You'll probably want to use [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make sure the lift is valid. */ lift(range, target) { lift$2(this, range, target); return this; } /** Join the blocks around the given position. If depth is 2, their last and first siblings are also joined, and so on. */ join(pos, depth = 1) { join(this, pos, depth); return this; } /** Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers. The wrappers are assumed to be valid in this position, and should probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping). */ wrap(range, wrappers) { wrap(this, range, wrappers); return this; } /** Set the type of all textblocks (partly) between `from` and `to` to the given node type with the given attributes. */ setBlockType(from2, to = from2, type, attrs = null) { setBlockType$1(this, from2, to, type, attrs); return this; } /** Change the type, attributes, and/or marks of the node at `pos`. When `type` isn't given, the existing node type is preserved, */ setNodeMarkup(pos, type, attrs = null, marks) { setNodeMarkup(this, pos, type, attrs, marks); return this; } /** Set a single attribute on a given node to a new value. The `pos` addresses the document content. Use `setDocAttribute` to set attributes on the document itself. */ setNodeAttribute(pos, attr, value) { this.step(new AttrStep(pos, attr, value)); return this; } /** Set a single attribute on the document to a new value. */ setDocAttribute(attr, value) { this.step(new DocAttrStep(attr, value)); return this; } /** Add a mark to the node at position `pos`. */ addNodeMark(pos, mark) { this.step(new AddNodeMarkStep(pos, mark)); return this; } /** Remove a mark (or all marks of the given type) from the node at position `pos`. */ removeNodeMark(pos, mark) { let node = this.doc.nodeAt(pos); if (!node) throw new RangeError("No node at position " + pos); if (mark instanceof Mark$1) { if (mark.isInSet(node.marks)) this.step(new RemoveNodeMarkStep(pos, mark)); } else { let set = node.marks, found2, steps = []; while (found2 = mark.isInSet(set)) { steps.push(new RemoveNodeMarkStep(pos, found2)); set = found2.removeFromSet(set); } for (let i = steps.length - 1; i >= 0; i--) this.step(steps[i]); } return this; } /** Split the node at the given position, and optionally, if `depth` is greater than one, any number of nodes above that. By default, the parts split off will inherit the node type of the original node. This can be changed by passing an array of types and attributes to use after the split (with the outermost nodes coming first). */ split(pos, depth = 1, typesAfter) { split(this, pos, depth, typesAfter); return this; } /** Add the given mark to the inline content between `from` and `to`. */ addMark(from2, to, mark) { addMark(this, from2, to, mark); return this; } /** Remove marks from inline nodes between `from` and `to`. When `mark` is a single mark, remove precisely that mark. When it is a mark type, remove all marks of that type. When it is null, remove all marks of any type. */ removeMark(from2, to, mark) { removeMark(this, from2, to, mark); return this; } /** Removes all marks and nodes from the content of the node at `pos` that don't match the given new parent node type. Accepts an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as third argument. */ clearIncompatible(pos, parentType, match) { clearIncompatible(this, pos, parentType, match); return this; } } const classesById = /* @__PURE__ */ Object.create(null); class Selection { /** Initialize a selection with the head and anchor and ranges. If no ranges are given, constructs a single range across `$anchor` and `$head`. */ constructor($anchor, $head, ranges) { this.$anchor = $anchor; this.$head = $head; this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))]; } /** The selection's anchor, as an unresolved position. */ get anchor() { return this.$anchor.pos; } /** The selection's head. */ get head() { return this.$head.pos; } /** The lower bound of the selection's main range. */ get from() { return this.$from.pos; } /** The upper bound of the selection's main range. */ get to() { return this.$to.pos; } /** The resolved lower bound of the selection's main range. */ get $from() { return this.ranges[0].$from; } /** The resolved upper bound of the selection's main range. */ get $to() { return this.ranges[0].$to; } /** Indicates whether the selection contains any content. */ get empty() { let ranges = this.ranges; for (let i = 0; i < ranges.length; i++) if (ranges[i].$from.pos != ranges[i].$to.pos) return false; return true; } /** Get the content of this selection as a slice. */ content() { return this.$from.doc.slice(this.from, this.to, true); } /** Replace the selection with a slice or, if no slice is given, delete the selection. Will append to the given transaction. */ replace(tr2, content = Slice.empty) { let lastNode = content.content.lastChild, lastParent = null; for (let i = 0; i < content.openEnd; i++) { lastParent = lastNode; lastNode = lastNode.lastChild; } let mapFrom = tr2.steps.length, ranges = this.ranges; for (let i = 0; i < ranges.length; i++) { let { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom); tr2.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content); if (i == 0) selectionToInsertionEnd$1(tr2, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1); } } /** Replace the selection with the given node, appending the changes to the given transaction. */ replaceWith(tr2, node) { let mapFrom = tr2.steps.length, ranges = this.ranges; for (let i = 0; i < ranges.length; i++) { let { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom); let from2 = mapping.map($from.pos), to = mapping.map($to.pos); if (i) { tr2.deleteRange(from2, to); } else { tr2.replaceRangeWith(from2, to, node); selectionToInsertionEnd$1(tr2, mapFrom, node.isInline ? -1 : 1); } } } /** Find a valid cursor or leaf node selection starting at the given position and searching back if `dir` is negative, and forward if positive. When `textOnly` is true, only consider cursor selections. Will return null when no valid selection position is found. */ static findFrom($pos, dir, textOnly = false) { let inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly); if (inner) return inner; for (let depth = $pos.depth - 1; depth >= 0; depth--) { let found2 = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly); if (found2) return found2; } return null; } /** Find a valid cursor or leaf node selection near the given position. Searches forward first by default, but if `bias` is negative, it will search backwards first. */ static near($pos, bias = 1) { return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0)); } /** Find the cursor or leaf node selection closest to the start of the given document. Will return an [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position exists. */ static atStart(doc2) { return findSelectionIn(doc2, doc2, 0, 0, 1) || new AllSelection(doc2); } /** Find the cursor or leaf node selection closest to the end of the given document. */ static atEnd(doc2) { return findSelectionIn(doc2, doc2, doc2.content.size, doc2.childCount, -1) || new AllSelection(doc2); } /** Deserialize the JSON representation of a selection. Must be implemented for custom classes (as a static class method). */ static fromJSON(doc2, json) { if (!json || !json.type) throw new RangeError("Invalid input for Selection.fromJSON"); let cls = classesById[json.type]; if (!cls) throw new RangeError(`No selection type ${json.type} defined`); return cls.fromJSON(doc2, json); } /** To be able to deserialize selections from JSON, custom selection classes must register themselves with an ID string, so that they can be disambiguated. Try to pick something that's unlikely to clash with classes from other modules. */ static jsonID(id, selectionClass) { if (id in classesById) throw new RangeError("Duplicate use of selection JSON ID " + id); classesById[id] = selectionClass; selectionClass.prototype.jsonID = id; return selectionClass; } /** Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection, which is a value that can be mapped without having access to a current document, and later resolved to a real selection for a given document again. (This is used mostly by the history to track and restore old selections.) The default implementation of this method just converts the selection to a text selection and returns the bookmark for that. */ getBookmark() { return TextSelection.between(this.$anchor, this.$head).getBookmark(); } } Selection.prototype.visible = true; class SelectionRange { /** Create a range. */ constructor($from, $to) { this.$from = $from; this.$to = $to; } } let warnedAboutTextSelection = false; function checkTextSelection($pos) { if (!warnedAboutTextSelection && !$pos.parent.inlineContent) { warnedAboutTextSelection = true; console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")"); } } class TextSelection extends Selection { /** Construct a text selection between the given points. */ constructor($anchor, $head = $anchor) { checkTextSelection($anchor); checkTextSelection($head); super($anchor, $head); } /** Returns a resolved position if this is a cursor selection (an empty text selection), and null otherwise. */ get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; } map(doc2, mapping) { let $head = doc2.resolve(mapping.map(this.head)); if (!$head.parent.inlineContent) return Selection.near($head); let $anchor = doc2.resolve(mapping.map(this.anchor)); return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head); } replace(tr2, content = Slice.empty) { super.replace(tr2, content); if (content == Slice.empty) { let marks = this.$from.marksAcross(this.$to); if (marks) tr2.ensureMarks(marks); } } eq(other) { return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head; } getBookmark() { return new TextBookmark(this.anchor, this.head); } toJSON() { return { type: "text", anchor: this.anchor, head: this.head }; } /** @internal */ static fromJSON(doc2, json) { if (typeof json.anchor != "number" || typeof json.head != "number") throw new RangeError("Invalid input for TextSelection.fromJSON"); return new TextSelection(doc2.resolve(json.anchor), doc2.resolve(json.head)); } /** Create a text selection from non-resolved positions. */ static create(doc2, anchor, head = anchor) { let $anchor = doc2.resolve(anchor); return new this($anchor, head == anchor ? $anchor : doc2.resolve(head)); } /** Return a text selection that spans the given positions or, if they aren't text positions, find a text selection near them. `bias` determines whether the method searches forward (default) or backwards (negative number) first. Will fall back to calling [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document doesn't contain a valid text position. */ static between($anchor, $head, bias) { let dPos = $anchor.pos - $head.pos; if (!bias || dPos) bias = dPos >= 0 ? 1 : -1; if (!$head.parent.inlineContent) { let found2 = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true); if (found2) $head = found2.$head; else return Selection.near($head, bias); } if (!$anchor.parent.inlineContent) { if (dPos == 0) { $anchor = $head; } else { $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor; if ($anchor.pos < $head.pos != dPos < 0) $anchor = $head; } } return new TextSelection($anchor, $head); } } Selection.jsonID("text", TextSelection); class TextBookmark { constructor(anchor, head) { this.anchor = anchor; this.head = head; } map(mapping) { return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head)); } resolve(doc2) { return TextSelection.between(doc2.resolve(this.anchor), doc2.resolve(this.head)); } } class NodeSelection extends Selection { /** Create a node selection. Does not verify the validity of its argument. */ constructor($pos) { let node = $pos.nodeAfter; let $end = $pos.node(0).resolve($pos.pos + node.nodeSize); super($pos, $end); this.node = node; } map(doc2, mapping) { let { deleted, pos } = mapping.mapResult(this.anchor); let $pos = doc2.resolve(pos); if (deleted) return Selection.near($pos); return new NodeSelection($pos); } content() { return new Slice(Fragment.from(this.node), 0, 0); } eq(other) { return other instanceof NodeSelection && other.anchor == this.anchor; } toJSON() { return { type: "node", anchor: this.anchor }; } getBookmark() { return new NodeBookmark(this.anchor); } /** @internal */ static fromJSON(doc2, json) { if (typeof json.anchor != "number") throw new RangeError("Invalid input for NodeSelection.fromJSON"); return new NodeSelection(doc2.resolve(json.anchor)); } /** Create a node selection from non-resolved positions. */ static create(doc2, from2) { return new NodeSelection(doc2.resolve(from2)); } /** Determines whether the given node may be selected as a node selection. */ static isSelectable(node) { return !node.isText && node.type.spec.selectable !== false; } } NodeSelection.prototype.visible = false; Selection.jsonID("node", NodeSelection); class NodeBookmark { constructor(anchor) { this.anchor = anchor; } map(mapping) { let { deleted, pos } = mapping.mapResult(this.anchor); return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos); } resolve(doc2) { let $pos = doc2.resolve(this.anchor), node = $pos.nodeAfter; if (node && NodeSelection.isSelectable(node)) return new NodeSelection($pos); return Selection.near($pos); } } class AllSelection extends Selection { /** Create an all-selection over the given document. */ constructor(doc2) { super(doc2.resolve(0), doc2.resolve(doc2.content.size)); } replace(tr2, content = Slice.empty) { if (content == Slice.empty) { tr2.delete(0, tr2.doc.content.size); let sel = Selection.atStart(tr2.doc); if (!sel.eq(tr2.selection)) tr2.setSelection(sel); } else { super.replace(tr2, content); } } toJSON() { return { type: "all" }; } /** @internal */ static fromJSON(doc2) { return new AllSelection(doc2); } map(doc2) { return new AllSelection(doc2); } eq(other) { return other instanceof AllSelection; } getBookmark() { return AllBookmark; } } Selection.jsonID("all", AllSelection); const AllBookmark = { map() { return this; }, resolve(doc2) { return new AllSelection(doc2); } }; function findSelectionIn(doc2, node, pos, index, dir, text = false) { if (node.inlineContent) return TextSelection.create(doc2, pos); for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) { let child = node.child(i); if (!child.isAtom) { let inner = findSelectionIn(doc2, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text); if (inner) return inner; } else if (!text && NodeSelection.isSelectable(child)) { return NodeSelection.create(doc2, pos - (dir < 0 ? child.nodeSize : 0)); } pos += child.nodeSize * dir; } return null; } function selectionToInsertionEnd$1(tr2, startLen, bias) { let last = tr2.steps.length - 1; if (last < startLen) return; let step = tr2.steps[last]; if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) return; let map2 = tr2.mapping.maps[last], end; map2.forEach((_from, _to, _newFrom, newTo) => { if (end == null) end = newTo; }); tr2.setSelection(Selection.near(tr2.doc.resolve(end), bias)); } function bind(f, self) { return !self || !f ? f : f.bind(self); } class FieldDesc { constructor(name, desc, self) { this.name = name; this.init = bind(desc.init, self); this.apply = bind(desc.apply, self); } } [ new FieldDesc("doc", { init(config) { return config.doc || config.schema.topNodeType.createAndFill(); }, apply(tr2) { return tr2.doc; } }), new FieldDesc("selection", { init(config, instance) { return config.selection || Selection.atStart(instance.doc); }, apply(tr2) { return tr2.selection; } }), new FieldDesc("storedMarks", { init(config) { return config.storedMarks || null; }, apply(tr2, _marks, _old, state) { return state.selection.$cursor ? tr2.storedMarks : null; } }), new FieldDesc("scrollToSelection", { init() { return 0; }, apply(tr2, prev) { return tr2.scrolledIntoView ? prev + 1 : prev; } }) ]; function bindProps(obj, self, target) { for (let prop in obj) { let val = obj[prop]; if (val instanceof Function) val = val.bind(self); else if (prop == "handleDOMEvents") val = bindProps(val, self, {}); target[prop] = val; } return target; } class Plugin { /** Create a plugin. */ constructor(spec) { this.spec = spec; this.props = {}; if (spec.props) bindProps(spec.props, this, this.props); this.key = spec.key ? spec.key.key : createKey("plugin"); } /** Extract the plugin's state field from an editor state. */ getState(state) { return state[this.key]; } } const keys = /* @__PURE__ */ Object.create(null); function createKey(name) { if (name in keys) return name + "$" + ++keys[name]; keys[name] = 0; return name + "$"; } class PluginKey { /** Create a plugin key. */ constructor(name = "key") { this.key = createKey(name); } /** Get the active plugin with this key, if any, from an editor state. */ get(state) { return state.config.pluginsByKey[this.key]; } /** Get the plugin's state from an editor state. */ getState(state) { return state[this.key]; } } const deleteSelection$1 = (state, dispatch) => { if (state.selection.empty) return false; if (dispatch) dispatch(state.tr.deleteSelection().scrollIntoView()); return true; }; function atBlockStart(state, view) { let { $cursor } = state.selection; if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0)) return null; return $cursor; } const joinBackward = (state, dispatch, view) => { let $cursor = atBlockStart(state, view); if (!$cursor) return false; let $cut = findCutBefore($cursor); if (!$cut) { let range = $cursor.blockRange(), target = range && liftTarget(range); if (target == null) return false; if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView()); return true; } let before = $cut.nodeBefore; if (deleteBarrier(state, $cut, dispatch, -1)) return true; if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || NodeSelection.isSelectable(before))) { for (let depth = $cursor.depth; ; depth--) { let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty); if (delStep && delStep.slice.size < delStep.to - delStep.from) { if (dispatch) { let tr2 = state.tr.step(delStep); tr2.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr2.doc, $cut.pos - before.nodeSize)); dispatch(tr2.scrollIntoView()); } return true; } if (depth == 1 || $cursor.node(depth - 1).childCount > 1) break; } } if (before.isAtom && $cut.depth == $cursor.depth - 1) { if (dispatch) dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView()); return true; } return false; }; const joinTextblockBackward = (state, dispatch, view) => { let $cursor = atBlockStart(state, view); if (!$cursor) return false; let $cut = findCutBefore($cursor); return $cut ? joinTextblocksAround(state, $cut, dispatch) : false; }; const joinTextblockForward = (state, dispatch, view) => { let $cursor = atBlockEnd(state, view); if (!$cursor) return false; let $cut = findCutAfter($cursor); return $cut ? joinTextblocksAround(state, $cut, dispatch) : false; }; function joinTextblocksAround(state, $cut, dispatch) { let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1; for (; !beforeText.isTextblock; beforePos--) { if (beforeText.type.spec.isolating) return false; let child = beforeText.lastChild; if (!child) return false; beforeText = child; } let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1; for (; !afterText.isTextblock; afterPos++) { if (afterText.type.spec.isolating) return false; let child = afterText.firstChild; if (!child) return false; afterText = child; } let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty); if (!step || step.from != beforePos || step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos) return false; if (dispatch) { let tr2 = state.tr.step(step); tr2.setSelection(TextSelection.create(tr2.doc, beforePos)); dispatch(tr2.scrollIntoView()); } return true; } function textblockAt(node, side, only = false) { for (let scan = node; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) { if (scan.isTextblock) return true; if (only && scan.childCount != 1) return false; } return false; } const selectNodeBackward = (state, dispatch, view) => { let { $head, empty: empty2 } = state.selection, $cut = $head; if (!empty2) return false; if ($head.parent.isTextblock) { if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0) return false; $cut = findCutBefore($head); } let node = $cut && $cut.nodeBefore; if (!node || !NodeSelection.isSelectable(node)) return false; if (dispatch) dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView()); return true; }; function findCutBefore($pos) { if (!$pos.parent.type.spec.isolating) for (let i = $pos.depth - 1; i >= 0; i--) { if ($pos.index(i) > 0) return $pos.doc.resolve($pos.before(i + 1)); if ($pos.node(i).type.spec.isolating) break; } return null; } function atBlockEnd(state, view) { let { $cursor } = state.selection; if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size)) return null; return $cursor; } const joinForward = (state, dispatch, view) => { let $cursor = atBlockEnd(state, view); if (!$cursor) return false; let $cut = findCutAfter($cursor); if (!$cut) return false; let after = $cut.nodeAfter; if (deleteBarrier(state, $cut, dispatch, 1)) return true; if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || NodeSelection.isSelectable(after))) { let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty); if (delStep && delStep.slice.size < delStep.to - delStep.from) { if (dispatch) { let tr2 = state.tr.step(delStep); tr2.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos)), 1) : NodeSelection.create(tr2.doc, tr2.mapping.map($cut.pos))); dispatch(tr2.scrollIntoView()); } return true; } } if (after.isAtom && $cut.depth == $cursor.depth - 1) { if (dispatch) dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView()); return true; } return false; }; const selectNodeForward = (state, dispatch, view) => { let { $head, empty: empty2 } = state.selection, $cut = $head; if (!empty2) return false; if ($head.parent.isTextblock) { if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size) return false; $cut = findCutAfter($head); } let node = $cut && $cut.nodeAfter; if (!node || !NodeSelection.isSelectable(node)) return false; if (dispatch) dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView()); return true; }; function findCutAfter($pos) { if (!$pos.parent.type.spec.isolating) for (let i = $pos.depth - 1; i >= 0; i--) { let parent = $pos.node(i); if ($pos.index(i) + 1 < parent.childCount) return $pos.doc.resolve($pos.after(i + 1)); if (parent.type.spec.isolating) break; } return null; } const joinUp = (state, dispatch) => { let sel = state.selection, nodeSel = sel instanceof NodeSelection, point; if (nodeSel) { if (sel.node.isTextblock || !canJoin(state.doc, sel.from)) return false; point = sel.from; } else { point = joinPoint(state.doc, sel.from, -1); if (point == null) return false; } if (dispatch) { let tr2 = state.tr.join(point); if (nodeSel) tr2.setSelection(NodeSelection.create(tr2.doc, point - state.doc.resolve(point).nodeBefore.nodeSize)); dispatch(tr2.scrollIntoView()); } return true; }; const joinDown = (state, dispatch) => { let sel = state.selection, point; if (sel instanceof NodeSelection) { if (sel.node.isTextblock || !canJoin(state.doc, sel.to)) return false; point = sel.to; } else { point = joinPoint(state.doc, sel.to, 1); if (point == null) return false; } if (dispatch) dispatch(state.tr.join(point).scrollIntoView()); return true; }; const lift = (state, dispatch) => { let { $from, $to } = state.selection; let range = $from.blockRange($to), target = range && liftTarget(range); if (target == null) return false; if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView()); return true; }; const newlineInCode = (state, dispatch) => { let { $head, $anchor } = state.selection; if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) return false; if (dispatch) dispatch(state.tr.insertText("\n").scrollIntoView()); return true; }; function defaultBlockAt$1(match) { for (let i = 0; i < match.edgeCount; i++) { let { type } = match.edge(i); if (type.isTextblock && !type.hasRequiredAttrs()) return type; } return null; } const exitCode = (state, dispatch) => { let { $head, $anchor } = state.selection; if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) return false; let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt$1(above.contentMatchAt(after)); if (!type || !above.canReplaceWith(after, after, type)) return false; if (dispatch) { let pos = $head.after(), tr2 = state.tr.replaceWith(pos, pos, type.createAndFill()); tr2.setSelection(Selection.near(tr2.doc.resolve(pos), 1)); dispatch(tr2.scrollIntoView()); } return true; }; const createParagraphNear = (state, dispatch) => { let sel = state.selection, { $from, $to } = sel; if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent) return false; let type = defaultBlockAt$1($to.parent.contentMatchAt($to.indexAfter())); if (!type || !type.isTextblock) return false; if (dispatch) { let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos; let tr2 = state.tr.insert(side, type.createAndFill()); tr2.setSelection(TextSelection.create(tr2.doc, side + 1)); dispatch(tr2.scrollIntoView()); } return true; }; const liftEmptyBlock = (state, dispatch) => { let { $cursor } = state.selection; if (!$cursor || $cursor.parent.content.size) return false; if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) { let before = $cursor.before(); if (canSplit(state.doc, before)) { if (dispatch) dispatch(state.tr.split(before).scrollIntoView()); return true; } } let range = $cursor.blockRange(), target = range && liftTarget(range); if (target == null) return false; if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView()); return true; }; function splitBlockAs(splitNode) { return (state, dispatch) => { if (state.selection instanceof NodeSelection && state.selection.node.isBlock) { let { $from: $from2 } = state.selection; if (!$from2.parentOffset || !canSplit(state.doc, $from2.pos)) return false; if (dispatch) dispatch(state.tr.split($from2.pos).scrollIntoView()); return true; } if (!state.selection.$from.depth) return false; let tr2 = state.tr; if (!state.selection.empty && (state.selection instanceof TextSelection || state.selection instanceof AllSelection)) tr2.deleteSelection(); let { $from } = tr2.selection, mapFrom = tr2.steps.length; let types = []; let splitDepth, deflt, atEnd = false, atStart = false; for (let d = $from.depth; ; d--) { let node = $from.node(d); if (node.isBlock) { atEnd = $from.end(d) == $from.pos + ($from.depth - d); atStart = $from.start(d) == $from.pos - ($from.depth - d); deflt = defaultBlockAt$1($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1))); types.unshift(atEnd && deflt ? { type: deflt } : null); splitDepth = d; break; } else { if (d == 1) return false; types.unshift(null); } } let splitPos = $from.pos; let can = canSplit(tr2.doc, splitPos, types.length, types); if (!can) { types[0] = deflt ? { type: deflt } : null; can = canSplit(tr2.doc, splitPos, types.length, types); } if (!can) return false; tr2.split(splitPos, types.length, types); if (!atEnd && atStart && $from.node(splitDepth).type != deflt) { let mapping = tr2.mapping.slice(mapFrom); let first2 = mapping.map($from.before(splitDepth)), $first = tr2.doc.resolve(first2); if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt)) tr2.setNodeMarkup(mapping.map($from.before(splitDepth)), deflt); } if (dispatch) dispatch(tr2.scrollIntoView()); return true; }; } const splitBlock$1 = splitBlockAs(); const selectParentNode = (state, dispatch) => { let { $from, to } = state.selection, pos; let same = $from.sharedDepth(to); if (same == 0) return false; pos = $from.before(same); if (dispatch) dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos))); return true; }; function joinMaybeClear(state, $pos, dispatch) { let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index(); if (!before || !after || !before.type.compatibleContent(after.type)) return false; if (!before.content.size && $pos.parent.canReplace(index - 1, index)) { if (dispatch) dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView()); return true; } if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos))) return false; if (dispatch) dispatch(state.tr.join($pos.pos).scrollIntoView()); return true; } function deleteBarrier(state, $cut, dispatch, dir) { let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match; let isolated = before.type.spec.isolating || after.type.spec.isolating; if (!isolated && joinMaybeClear(state, $cut, dispatch)) return true; let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1); if (canDelAfter && (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match.matchType(conn[0] || after.type).validEnd) { if (dispatch) { let end = $cut.pos + after.nodeSize, wrap2 = Fragment.empty; for (let i = conn.length - 1; i >= 0; i--) wrap2 = Fragment.from(conn[i].create(null, wrap2)); wrap2 = Fragment.from(before.copy(wrap2)); let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap2, 1, 0), conn.length, true)); let $joinAt = tr2.doc.resolve(end + 2 * conn.length); if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr2.doc, $joinAt.pos)) tr2.join($joinAt.pos); dispatch(tr2.scrollIntoView()); } return true; } let selAfter = after.type.spec.isolating || dir > 0 && isolated ? null : Selection.findFrom($cut, 1); let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range); if (target != null && target >= $cut.depth) { if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView()); return true; } if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) { let at = before, wrap2 = []; for (; ; ) { wrap2.push(at); if (at.isTextblock) break; at = at.lastChild; } let afterText = after, afterDepth = 1; for (; !afterText.isTextblock; afterText = afterText.firstChild) afterDepth++; if (at.canReplace(at.childCount, at.childCount, afterText.content)) { if (dispatch) { let end = Fragment.empty; for (let i = wrap2.length - 1; i >= 0; i--) end = Fragment.from(wrap2[i].copy(end)); let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - wrap2.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap2.length, 0), 0, true)); dispatch(tr2.scrollIntoView()); } return true; } } return false; } function selectTextblockSide(side) { return function(state, dispatch) { let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to; let depth = $pos.depth; while ($pos.node(depth).isInline) { if (!depth) return false; depth--; } if (!$pos.node(depth).isTextblock) return false; if (dispatch) dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth)))); return true; }; } const selectTextblockStart = selectTextblockSide(-1); const selectTextblockEnd = selectTextblockSide(1); function wrapIn(nodeType, attrs = null) { return function(state, dispatch) { let { $from, $to } = state.selection; let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs); if (!wrapping) return false; if (dispatch) dispatch(state.tr.wrap(range, wrapping).scrollIntoView()); return true; }; } function setBlockType(nodeType, attrs = null) { return function(state, dispatch) { let applicable = false; for (let i = 0; i < state.selection.ranges.length && !applicable; i++) { let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i]; state.doc.nodesBetween(from2, to, (node, pos) => { if (applicable) return false; if (!node.isTextblock || node.hasMarkup(nodeType, attrs)) return; if (node.type == nodeType) { applicable = true; } else { let $pos = state.doc.resolve(pos), index = $pos.index(); applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType); } }); } if (!applicable) return false; if (dispatch) { let tr2 = state.tr; for (let i = 0; i < state.selection.ranges.length; i++) { let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i]; tr2.setBlockType(from2, to, nodeType, attrs); } dispatch(tr2.scrollIntoView()); } return true; }; } function chainCommands(...commands) { return function(state, dispatch, view) { for (let i = 0; i < commands.length; i++) if (commands[i](state, dispatch, view)) return true; return false; }; } chainCommands(deleteSelection$1, joinBackward, selectNodeBackward); chainCommands(deleteSelection$1, joinForward, selectNodeForward); ({ "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock$1) }); typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false; function wrapInList(listType, attrs = null) { return function(state, dispatch) { let { $from, $to } = state.selection; let range = $from.blockRange($to); if (!range) return false; let tr2 = dispatch ? state.tr : null; if (!wrapRangeInList(tr2, range, listType, attrs)) return false; if (dispatch) dispatch(tr2.scrollIntoView()); return true; }; } function wrapRangeInList(tr2, range, listType, attrs = null) { let doJoin = false, outerRange = range, doc2 = range.$from.doc; if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) { if (range.$from.index(range.depth - 1) == 0) return false; let $insert = doc2.resolve(range.start - 2); outerRange = new NodeRange($insert, $insert, range.depth); if (range.endIndex < range.parent.childCount) range = new NodeRange(range.$from, doc2.resolve(range.$to.end(range.depth)), range.depth); doJoin = true; } let wrap2 = findWrapping(outerRange, listType, attrs, range); if (!wrap2) return false; if (tr2) doWrapInList(tr2, range, wrap2, doJoin, listType); return true; } function doWrapInList(tr2, range, wrappers, joinBefore, listType) { let content = Fragment.empty; for (let i = wrappers.length - 1; i >= 0; i--) content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); tr2.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true)); let found2 = 0; for (let i = 0; i < wrappers.length; i++) if (wrappers[i].type == listType) found2 = i + 1; let splitDepth = wrappers.length - found2; let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent; for (let i = range.startIndex, e = range.endIndex, first2 = true; i < e; i++, first2 = false) { if (!first2 && canSplit(tr2.doc, splitPos, splitDepth)) { tr2.split(splitPos, splitDepth); splitPos += 2 * splitDepth; } splitPos += parent.child(i).nodeSize; } return tr2; } function liftListItem(itemType) { return function(state, dispatch) { let { $from, $to } = state.selection; let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType); if (!range) return false; if (!dispatch) return true; if ($from.node(range.depth - 1).type == itemType) return liftToOuterList(state, dispatch, itemType, range); else return liftOutOfList(state, dispatch, range); }; } function liftToOuterList(state, dispatch, itemType, range) { let tr2 = state.tr, end = range.end, endOfList = range.$to.end(range.depth); if (end < endOfList) { tr2.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true)); range = new NodeRange(tr2.doc.resolve(range.$from.pos), tr2.doc.resolve(endOfList), range.depth); } const target = liftTarget(range); if (target == null) return false; tr2.lift(range, target); let $after = tr2.doc.resolve(tr2.mapping.map(end, -1) - 1); if (canJoin(tr2.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type) tr2.join($after.pos); dispatch(tr2.scrollIntoView()); return true; } function liftOutOfList(state, dispatch, range) { let tr2 = state.tr, list = range.parent; for (let pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) { pos -= list.child(i).nodeSize; tr2.delete(pos - 1, pos + 1); } let $start = tr2.doc.resolve(range.start), item = $start.nodeAfter; if (tr2.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize) return false; let atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount; let parent = $start.node(-1), indexBefore = $start.index(-1); if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list)))) return false; let start = $start.pos, end = start + item.nodeSize; tr2.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1)); dispatch(tr2.scrollIntoView()); return true; } function sinkListItem(itemType) { return function(state, dispatch) { let { $from, $to } = state.selection; let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType); if (!range) return false; let startIndex = range.startIndex; if (startIndex == 0) return false; let parent = range.parent, nodeBefore = parent.child(startIndex - 1); if (nodeBefore.type != itemType) return false; if (dispatch) { let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type; let inner = Fragment.from(nestedBefore ? itemType.create() : null); let slice2 = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0); let before = range.start, after = range.end; dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice2, 1, true)).scrollIntoView()); } return true; }; } const domIndex = function(node) { for (var index = 0; ; index++) { node = node.previousSibling; if (!node) return index; } }; const isEquivalentPosition = function(node, off2, targetNode, targetOff) { return targetNode && (scanFor(node, off2, targetNode, targetOff, -1) || scanFor(node, off2, targetNode, targetOff, 1)); }; const atomElements = /^(img|br|input|textarea|hr)$/i; function scanFor(node, off2, targetNode, targetOff, dir) { var _a; for (; ; ) { if (node == targetNode && off2 == targetOff) return true; if (off2 == (dir < 0 ? 0 : nodeSize(node))) { let parent = node.parentNode; if (!parent || parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false") return false; off2 = domIndex(node) + (dir < 0 ? 0 : 1); node = parent; } else if (node.nodeType == 1) { let child = node.childNodes[off2 + (dir < 0 ? -1 : 0)]; if (child.nodeType == 1 && child.contentEditable == "false") { if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection) off2 += dir; else return false; } else { node = child; off2 = dir < 0 ? nodeSize(node) : 0; } } else { return false; } } } function nodeSize(node) { return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; } function isOnEdge(node, offset, parent) { for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd; ) { if (node == parent) return true; let index = domIndex(node); node = node.parentNode; if (!node) return false; atStart = atStart && index == 0; atEnd = atEnd && index == nodeSize(node); } } function hasBlockDesc(dom) { let desc; for (let cur = dom; cur; cur = cur.parentNode) if (desc = cur.pmViewDesc) break; return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom); } const selectionCollapsed = function(domSel) { return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset); }; function keyEvent(keyCode, key) { let event = document.createEvent("Event"); event.initEvent("keydown", true, true); event.keyCode = keyCode; event.key = event.code = key; return event; } const nav = typeof navigator != "undefined" ? navigator : null; const doc$1 = typeof document != "undefined" ? document : null; const agent = nav && nav.userAgent || ""; const ie_edge = /Edge\/(\d+)/.exec(agent); const ie_upto10 = /MSIE \d/.exec(agent); const ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent); const ie$1 = !!(ie_upto10 || ie_11up || ie_edge); const ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0; const gecko = !ie$1 && /gecko\/(\d+)/i.test(agent); gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1]; const _chrome = !ie$1 && /Chrome\/(\d+)/.exec(agent); const chrome = !!_chrome; const chrome_version = _chrome ? +_chrome[1] : 0; const safari = !ie$1 && !!nav && /Apple Computer/.test(nav.vendor); const ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2); const mac$2 = ios || (nav ? /Mac/.test(nav.platform) : false); const windows$1 = nav ? /Win/.test(nav.platform) : false; const android = /Android \d/.test(agent); const webkit = !!doc$1 && "webkitFontSmoothing" in doc$1.documentElement.style; const webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0; function selectionFromDOM(view, origin = null) { let domSel = view.domSelectionRange(), doc2 = view.state.doc; if (!domSel.focusNode) return null; let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0; let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1); if (head < 0) return null; let $head = doc2.resolve(head), anchor, selection; if (selectionCollapsed(domSel)) { anchor = head; while (nearestDesc && !nearestDesc.node) nearestDesc = nearestDesc.parent; let nearestDescNode = nearestDesc.node; if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) { let pos = nearestDesc.posBefore; selection = new NodeSelection(head == pos ? $head : doc2.resolve(pos)); } } else { if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) { let min = head, max = head; for (let i = 0; i < domSel.rangeCount; i++) { let range = domSel.getRangeAt(i); min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1)); max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1)); } if (min < 0) return null; [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max]; $head = doc2.resolve(head); } else { anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1); } if (anchor < 0) return null; } let $anchor = doc2.resolve(anchor); if (!selection) { let bias = origin == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1; selection = selectionBetween(view, $anchor, $head, bias); } return selection; } function editorOwnsSelection(view) { return view.editable ? view.hasFocus() : hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom); } function selectionToDOM(view, force = false) { let sel = view.state.selection; syncNodeSelection(view, sel); if (!editorOwnsSelection(view)) return; let mouseDown = view.input.mouseDown; if (!force && chrome && mouseDown) { let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection; if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset) && mouseDown.delaySelUpdate()) { view.domObserver.setCurSelection(); return; } } view.domObserver.disconnectSelection(); if (view.cursorWrapper) { selectCursorWrapper(view); } else { let { anchor, head } = sel, resetEditableFrom, resetEditableTo; if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) { if (!sel.$from.parent.inlineContent) resetEditableFrom = temporarilyEditableNear(view, sel.from); if (!sel.empty && !sel.$from.parent.inlineContent) resetEditableTo = temporarilyEditableNear(view, sel.to); } view.docView.setSelection(anchor, head, view, force); if (brokenSelectBetweenUneditable) { if (resetEditableFrom) resetEditable(resetEditableFrom); if (resetEditableTo) resetEditable(resetEditableTo); } if (sel.visible) { view.dom.classList.remove("ProseMirror-hideselection"); } else { view.dom.classList.add("ProseMirror-hideselection"); if ("onselectionchange" in document) removeClassOnSelectionChange(view); } } view.domObserver.setCurSelection(); view.domObserver.connectSelection(); } const brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63; function temporarilyEditableNear(view, pos) { let { node, offset } = view.docView.domFromPos(pos, 0); let after = offset < node.childNodes.length ? node.childNodes[offset] : null; let before = offset ? node.childNodes[offset - 1] : null; if (safari && after && after.contentEditable == "false") return setEditable(after); if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) { if (after) return setEditable(after); else if (before) return setEditable(before); } } function setEditable(element) { element.contentEditable = "true"; if (safari && element.draggable) { element.draggable = false; element.wasDraggable = true; } return element; } function resetEditable(element) { element.contentEditable = "false"; if (element.wasDraggable) { element.draggable = true; element.wasDraggable = null; } } function removeClassOnSelectionChange(view) { let doc2 = view.dom.ownerDocument; doc2.removeEventListener("selectionchange", view.input.hideSelectionGuard); let domSel = view.domSelectionRange(); let node = domSel.anchorNode, offset = domSel.anchorOffset; doc2.addEventListener("selectionchange", view.input.hideSelectionGuard = () => { if (domSel.anchorNode != node || domSel.anchorOffset != offset) { doc2.removeEventListener("selectionchange", view.input.hideSelectionGuard); setTimeout(() => { if (!editorOwnsSelection(view) || view.state.selection.visible) view.dom.classList.remove("ProseMirror-hideselection"); }, 20); } }); } function selectCursorWrapper(view) { let domSel = view.domSelection(); if (!domSel) return; let node = view.cursorWrapper.dom, img = node.nodeName == "IMG"; if (img) domSel.collapse(node.parentNode, domIndex(node) + 1); else domSel.collapse(node, 0); if (!img && !view.state.selection.visible && ie$1 && ie_version <= 11) { node.disabled = true; node.disabled = false; } } function syncNodeSelection(view, sel) { if (sel instanceof NodeSelection) { let desc = view.docView.descAt(sel.from); if (desc != view.lastSelectedViewDesc) { clearNodeSelection(view); if (desc) desc.selectNode(); view.lastSelectedViewDesc = desc; } } else { clearNodeSelection(view); } } function clearNodeSelection(view) { if (view.lastSelectedViewDesc) { if (view.lastSelectedViewDesc.parent) view.lastSelectedViewDesc.deselectNode(); view.lastSelectedViewDesc = void 0; } } function selectionBetween(view, $anchor, $head, bias) { return view.someProp("createSelectionBetween", (f) => f(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias); } function hasSelection(view) { let sel = view.domSelectionRange(); if (!sel.anchorNode) return false; try { return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode)); } catch (_) { return false; } } function moveSelectionBlock(state, dir) { let { $anchor, $head } = state.selection; let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head); let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null; return $start && Selection.findFrom($start, dir); } function apply(view, sel) { view.dispatch(view.state.tr.setSelection(sel).scrollIntoView()); return true; } function selectHorizontally(view, dir, mods) { let sel = view.state.selection; if (sel instanceof TextSelection) { if (mods.indexOf("s") > -1) { let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter; if (!node || node.isText || !node.isLeaf) return false; let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1)); return apply(view, new TextSelection(sel.$anchor, $newHead)); } else if (!sel.empty) { return false; } else if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) { let next = moveSelectionBlock(view.state, dir); if (next && next instanceof NodeSelection) return apply(view, next); return false; } else if (!(mac$2 && mods.indexOf("m") > -1)) { let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc; if (!node || node.isText) return false; let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos; if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) return false; if (NodeSelection.isSelectable(node)) { return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head)); } else if (webkit) { return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize))); } else { return false; } } } else if (sel instanceof NodeSelection && sel.node.isInline) { return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from)); } else { let next = moveSelectionBlock(view.state, dir); if (next) return apply(view, next); return false; } } function nodeLen(node) { return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; } function isIgnorable(dom, dir) { let desc = dom.pmViewDesc; return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != "BR"); } function skipIgnoredNodes(view, dir) { return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view); } function skipIgnoredNodesBefore(view) { let sel = view.domSelectionRange(); let node = sel.focusNode, offset = sel.focusOffset; if (!node) return; let moveNode, moveOffset, force = false; if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1)) force = true; for (; ; ) { if (offset > 0) { if (node.nodeType != 1) { break; } else { let before = node.childNodes[offset - 1]; if (isIgnorable(before, -1)) { moveNode = node; moveOffset = --offset; } else if (before.nodeType == 3) { node = before; offset = node.nodeValue.length; } else break; } } else if (isBlockNode(node)) { break; } else { let prev = node.previousSibling; while (prev && isIgnorable(prev, -1)) { moveNode = node.parentNode; moveOffset = domIndex(prev); prev = prev.previousSibling; } if (!prev) { node = node.parentNode; if (node == view.dom) break; offset = 0; } else { node = prev; offset = nodeLen(node); } } } if (force) setSelFocus(view, node, offset); else if (moveNode) setSelFocus(view, moveNode, moveOffset); } function skipIgnoredNodesAfter(view) { let sel = view.domSelectionRange(); let node = sel.focusNode, offset = sel.focusOffset; if (!node) return; let len = nodeLen(node); let moveNode, moveOffset; for (; ; ) { if (offset < len) { if (node.nodeType != 1) break; let after = node.childNodes[offset]; if (isIgnorable(after, 1)) { moveNode = node; moveOffset = ++offset; } else break; } else if (isBlockNode(node)) { break; } else { let next = node.nextSibling; while (next && isIgnorable(next, 1)) { moveNode = next.parentNode; moveOffset = domIndex(next) + 1; next = next.nextSibling; } if (!next) { node = node.parentNode; if (node == view.dom) break; offset = len = 0; } else { node = next; offset = 0; len = nodeLen(node); } } } if (moveNode) setSelFocus(view, moveNode, moveOffset); } function isBlockNode(dom) { let desc = dom.pmViewDesc; return desc && desc.node && desc.node.isBlock; } function textNodeAfter(node, offset) { while (node && offset == node.childNodes.length && !hasBlockDesc(node)) { offset = domIndex(node) + 1; node = node.parentNode; } while (node && offset < node.childNodes.length) { let next = node.childNodes[offset]; if (next.nodeType == 3) return next; if (next.nodeType == 1 && next.contentEditable == "false") break; node = next; offset = 0; } } function textNodeBefore(node, offset) { while (node && !offset && !hasBlockDesc(node)) { offset = domIndex(node); node = node.parentNode; } while (node && offset) { let next = node.childNodes[offset - 1]; if (next.nodeType == 3) return next; if (next.nodeType == 1 && next.contentEditable == "false") break; node = next; offset = node.childNodes.length; } } function setSelFocus(view, node, offset) { if (node.nodeType != 3) { let before, after; if (after = textNodeAfter(node, offset)) { node = after; offset = 0; } else if (before = textNodeBefore(node, offset)) { node = before; offset = before.nodeValue.length; } } let sel = view.domSelection(); if (!sel) return; if (selectionCollapsed(sel)) { let range = document.createRange(); range.setEnd(node, offset); range.setStart(node, offset); sel.removeAllRanges(); sel.addRange(range); } else if (sel.extend) { sel.extend(node, offset); } view.domObserver.setCurSelection(); let { state } = view; setTimeout(() => { if (view.state == state) selectionToDOM(view); }, 50); } function findDirection(view, pos) { let $pos = view.state.doc.resolve(pos); if (!(chrome || windows$1) && $pos.parent.inlineContent) { let coords = view.coordsAtPos(pos); if (pos > $pos.start()) { let before = view.coordsAtPos(pos - 1); let mid = (before.top + before.bottom) / 2; if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1) return before.left < coords.left ? "ltr" : "rtl"; } if (pos < $pos.end()) { let after = view.coordsAtPos(pos + 1); let mid = (after.top + after.bottom) / 2; if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1) return after.left > coords.left ? "ltr" : "rtl"; } } let computed = getComputedStyle(view.dom).direction; return computed == "rtl" ? "rtl" : "ltr"; } function selectVertically(view, dir, mods) { let sel = view.state.selection; if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1) return false; if (mac$2 && mods.indexOf("m") > -1) return false; let { $from, $to } = sel; if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) { let next = moveSelectionBlock(view.state, dir); if (next && next instanceof NodeSelection) return apply(view, next); } if (!$from.parent.inlineContent) { let side = dir < 0 ? $from : $to; let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir); return beyond ? apply(view, beyond) : false; } return false; } function stopNativeHorizontalDelete(view, dir) { if (!(view.state.selection instanceof TextSelection)) return true; let { $head, $anchor, empty: empty2 } = view.state.selection; if (!$head.sameParent($anchor)) return true; if (!empty2) return false; if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) return true; let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter); if (nextNode && !nextNode.isText) { let tr2 = view.state.tr; if (dir < 0) tr2.delete($head.pos - nextNode.nodeSize, $head.pos); else tr2.delete($head.pos, $head.pos + nextNode.nodeSize); view.dispatch(tr2); return true; } return false; } function switchEditable(view, node, state) { view.domObserver.stop(); node.contentEditable = state; view.domObserver.start(); } function safariDownArrowBug(view) { if (!safari || view.state.selection.$head.parentOffset > 0) return false; let { focusNode, focusOffset } = view.domSelectionRange(); if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && focusNode.firstChild && focusNode.firstChild.contentEditable == "false") { let child = focusNode.firstChild; switchEditable(view, child, "true"); setTimeout(() => switchEditable(view, child, "false"), 20); } return false; } function getMods(event) { let result = ""; if (event.ctrlKey) result += "c"; if (event.metaKey) result += "m"; if (event.altKey) result += "a"; if (event.shiftKey) result += "s"; return result; } function captureKeyDown(view, event) { let code = event.keyCode, mods = getMods(event); if (code == 8 || mac$2 && code == 72 && mods == "c") { return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1); } else if (code == 46 && !event.shiftKey || mac$2 && code == 68 && mods == "c") { return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1); } else if (code == 13 || code == 27) { return true; } else if (code == 37 || mac$2 && code == 66 && mods == "c") { let dir = code == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1; return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); } else if (code == 39 || mac$2 && code == 70 && mods == "c") { let dir = code == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1; return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); } else if (code == 38 || mac$2 && code == 80 && mods == "c") { return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1); } else if (code == 40 || mac$2 && code == 78 && mods == "c") { return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1); } else if (mods == (mac$2 ? "m" : "c") && (code == 66 || code == 73 || code == 89 || code == 90)) { return true; } return false; } function serializeForClipboard(view, slice2) { view.someProp("transformCopied", (f) => { slice2 = f(slice2, view); }); let context = [], { content, openStart, openEnd } = slice2; while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) { openStart--; openEnd--; let node = content.firstChild; context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null); content = node.content; } let serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema); let doc2 = detachedDoc(), wrap2 = doc2.createElement("div"); wrap2.appendChild(serializer.serializeFragment(content, { document: doc2 })); let firstChild = wrap2.firstChild, needsWrap, wrappers = 0; while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) { for (let i = needsWrap.length - 1; i >= 0; i--) { let wrapper = doc2.createElement(needsWrap[i]); while (wrap2.firstChild) wrapper.appendChild(wrap2.firstChild); wrap2.appendChild(wrapper); wrappers++; } firstChild = wrap2.firstChild; } if (firstChild && firstChild.nodeType == 1) firstChild.setAttribute("data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`); let text = view.someProp("clipboardTextSerializer", (f) => f(slice2, view)) || slice2.content.textBetween(0, slice2.content.size, "\n\n"); return { dom: wrap2, text, slice: slice2 }; } function parseFromClipboard(view, text, html2, plainText, $context) { let inCode = $context.parent.type.spec.code; let dom, slice2; if (!html2 && !text) return null; let asText = !!text && (plainText || inCode || !html2); if (asText) { view.someProp("transformPastedText", (f) => { text = f(text, inCode || plainText, view); }); if (inCode) { slice2 = new Slice(Fragment.from(view.state.schema.text(text.replace(/\r\n?/g, "\n"))), 0, 0); view.someProp("transformPasted", (f) => { slice2 = f(slice2, view, true); }); return slice2; } let parsed = view.someProp("clipboardTextParser", (f) => f(text, $context, plainText, view)); if (parsed) { slice2 = parsed; } else { let marks = $context.marks(); let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema); dom = document.createElement("div"); text.split(/(?:\r\n?|\n)+/).forEach((block) => { let p = dom.appendChild(document.createElement("p")); if (block) p.appendChild(serializer.serializeNode(schema.text(block, marks))); }); } } else { view.someProp("transformPastedHTML", (f) => { html2 = f(html2, view); }); dom = readHTML(html2); if (webkit) restoreReplacedSpaces(dom); } let contextNode = dom && dom.querySelector("[data-pm-slice]"); let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || ""); if (sliceData && sliceData[3]) for (let i = +sliceData[3]; i > 0; i--) { let child = dom.firstChild; while (child && child.nodeType != 1) child = child.nextSibling; if (!child) break; dom = child; } if (!slice2) { let parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser$1.fromSchema(view.state.schema); slice2 = parser.parseSlice(dom, { preserveWhitespace: !!(asText || sliceData), context: $context, ruleFromNode(dom2) { if (dom2.nodeName == "BR" && !dom2.nextSibling && dom2.parentNode && !inlineParents.test(dom2.parentNode.nodeName)) return { ignore: true }; return null; } }); } if (sliceData) { slice2 = addContext(closeSlice(slice2, +sliceData[1], +sliceData[2]), sliceData[4]); } else { slice2 = Slice.maxOpen(normalizeSiblings(slice2.content, $context), true); if (slice2.openStart || slice2.openEnd) { let openStart = 0, openEnd = 0; for (let node = slice2.content.firstChild; openStart < slice2.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { } for (let node = slice2.content.lastChild; openEnd < slice2.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { } slice2 = closeSlice(slice2, openStart, openEnd); } } view.someProp("transformPasted", (f) => { slice2 = f(slice2, view, asText); }); return slice2; } const 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; function normalizeSiblings(fragment, $context) { if (fragment.childCount < 2) return fragment; for (let d = $context.depth; d >= 0; d--) { let parent = $context.node(d); let match = parent.contentMatchAt($context.index(d)); let lastWrap, result = []; fragment.forEach((node) => { if (!result) return; let wrap2 = match.findWrapping(node.type), inLast; if (!wrap2) return result = null; if (inLast = result.length && lastWrap.length && addToSibling(wrap2, lastWrap, node, result[result.length - 1], 0)) { result[result.length - 1] = inLast; } else { if (result.length) result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length); let wrapped = withWrappers(node, wrap2); result.push(wrapped); match = match.matchType(wrapped.type); lastWrap = wrap2; } }); if (result) return Fragment.from(result); } return fragment; } function withWrappers(node, wrap2, from2 = 0) { for (let i = wrap2.length - 1; i >= from2; i--) node = wrap2[i].create(null, Fragment.from(node)); return node; } function addToSibling(wrap2, lastWrap, node, sibling, depth) { if (depth < wrap2.length && depth < lastWrap.length && wrap2[depth] == lastWrap[depth]) { let inner = addToSibling(wrap2, lastWrap, node, sibling.lastChild, depth + 1); if (inner) return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner)); let match = sibling.contentMatchAt(sibling.childCount); if (match.matchType(depth == wrap2.length - 1 ? node.type : wrap2[depth + 1])) return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap2, depth + 1)))); } } function closeRight(node, depth) { if (depth == 0) return node; let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1)); let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true); return node.copy(fragment.append(fill)); } function closeRange(fragment, side, from2, to, depth, openEnd) { let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content; if (fragment.childCount > 1) openEnd = 0; if (depth < to - 1) inner = closeRange(inner, side, from2, to, depth + 1, openEnd); if (depth >= from2) inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner) : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true)); return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner)); } function closeSlice(slice2, openStart, openEnd) { if (openStart < slice2.openStart) slice2 = new Slice(closeRange(slice2.content, -1, openStart, slice2.openStart, 0, slice2.openEnd), openStart, slice2.openEnd); if (openEnd < slice2.openEnd) slice2 = new Slice(closeRange(slice2.content, 1, openEnd, slice2.openEnd, 0, 0), slice2.openStart, openEnd); return slice2; } const wrapMap = { thead: ["table"], tbody: ["table"], tfoot: ["table"], caption: ["table"], colgroup: ["table"], col: ["table", "colgroup"], tr: ["table", "tbody"], td: ["table", "tbody", "tr"], th: ["table", "tbody", "tr"] }; function detachedDoc() { return document.implementation.createHTMLDocument("title"); } let _policy = null; function maybeWrapTrusted(html2) { let trustedTypes = window.trustedTypes; if (!trustedTypes) return html2; if (!_policy) { if (_policy = trustedTypes.defaultPolicy) try { return _policy.createHTML(html2); } catch (_a) { } _policy = trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: (s) => s }); } return _policy.createHTML(html2); } function readHTML(html2) { let metas = /^(\s*]*>)*/.exec(html2); if (metas) html2 = html2.slice(metas[0].length); let doc2 = detachedDoc(), elt = doc2.body; let firstTag = /<([a-z][^>\s]+)/i.exec(html2), wrap2; if (wrap2 = firstTag && wrapMap[firstTag[1].toLowerCase()]) html2 = wrap2.map((n) => "<" + n + ">").join("") + html2 + wrap2.map((n) => "").reverse().join(""); elt.innerHTML = maybeWrapTrusted(html2); if (wrap2) for (let i = 0; i < wrap2.length; i++) elt = elt.querySelector(wrap2[i]) || elt; for (let i = 0; i < doc2.styleSheets.length; i++) { let style = doc2.styleSheets[i]; for (let j = 0; j < style.rules.length; j++) { let rule = style.rules[j]; if (rule instanceof CSSStyleRule) { let matches2 = elt.querySelectorAll(rule.selectorText); for (let k = 0; k < matches2.length; k++) matches2[k].style.cssText += rule.style.cssText; } } } return elt; } function restoreReplacedSpaces(dom) { let nodes = dom.querySelectorAll(chrome ? "span:not([class]):not([style])" : "span.Apple-converted-space"); for (let i = 0; i < nodes.length; i++) { let node = nodes[i]; if (node.childNodes.length == 1 && node.textContent == " " && node.parentNode) node.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node); } } function addContext(slice2, context) { if (!slice2.size) return slice2; let schema = slice2.content.firstChild.type.schema, array; try { array = JSON.parse(context); } catch (e) { return slice2; } let { content, openStart, openEnd } = slice2; for (let i = array.length - 2; i >= 0; i -= 2) { let type = schema.nodes[array[i]]; if (!type || type.hasRequiredAttrs()) break; try { type.checkAttrs(array[i + 1]); } catch (e) { break; } content = Fragment.from(type.create(array[i + 1], content)); openStart++; openEnd++; } return new Slice(content, openStart, openEnd); } const handlers = {}; const editHandlers = {}; function setSelectionOrigin(view, origin) { view.input.lastSelectionOrigin = origin; view.input.lastSelectionTime = Date.now(); } editHandlers.keydown = (view, _event) => { let event = _event; view.input.shiftKey = event.keyCode == 16 || event.shiftKey; if (inOrNearComposition(view)) return; view.input.lastKeyCode = event.keyCode; view.input.lastKeyCodeTime = Date.now(); if (android && chrome && event.keyCode == 13) return; if (event.keyCode != 229) view.domObserver.forceFlush(); if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) { let now = Date.now(); view.input.lastIOSEnter = now; view.input.lastIOSEnterFallbackTimeout = setTimeout(() => { if (view.input.lastIOSEnter == now) { view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter"))); view.input.lastIOSEnter = 0; } }, 200); } else if (view.someProp("handleKeyDown", (f) => f(view, event)) || captureKeyDown(view, event)) { event.preventDefault(); } else { setSelectionOrigin(view, "key"); } }; editHandlers.keyup = (view, event) => { if (event.keyCode == 16) view.input.shiftKey = false; }; editHandlers.keypress = (view, _event) => { let event = _event; if (inOrNearComposition(view) || !event.charCode || event.ctrlKey && !event.altKey || mac$2 && event.metaKey) return; if (view.someProp("handleKeyPress", (f) => f(view, event))) { event.preventDefault(); return; } let sel = view.state.selection; if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) { let text = String.fromCharCode(event.charCode); let deflt = () => view.state.tr.insertText(text).scrollIntoView(); if (!/[\r\n]/.test(text) && !view.someProp("handleTextInput", (f) => f(view, sel.$from.pos, sel.$to.pos, text, deflt))) view.dispatch(deflt()); event.preventDefault(); } }; function eventCoords(event) { return { left: event.clientX, top: event.clientY }; } function isNear(event, click) { let dx = click.x - event.clientX, dy = click.y - event.clientY; return dx * dx + dy * dy < 100; } function runHandlerOnContext(view, propName, pos, inside, event) { if (inside == -1) return false; let $pos = view.state.doc.resolve(inside); for (let i = $pos.depth + 1; i > 0; i--) { if (view.someProp(propName, (f) => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true) : f(view, pos, $pos.node(i), $pos.before(i), event, false))) return true; } return false; } function updateSelection(view, selection, origin) { if (!view.focused) view.focus(); if (view.state.selection.eq(selection)) return; let tr2 = view.state.tr.setSelection(selection); tr2.setMeta("pointer", true); view.dispatch(tr2); } function selectClickedLeaf(view, inside) { if (inside == -1) return false; let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter; if (node && node.isAtom && NodeSelection.isSelectable(node)) { updateSelection(view, new NodeSelection($pos)); return true; } return false; } function selectClickedNode(view, inside) { if (inside == -1) return false; let sel = view.state.selection, selectedNode, selectAt; if (sel instanceof NodeSelection) selectedNode = sel.node; let $pos = view.state.doc.resolve(inside); for (let i = $pos.depth + 1; i > 0; i--) { let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); if (NodeSelection.isSelectable(node)) { if (selectedNode && sel.$from.depth > 0 && i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos) selectAt = $pos.before(sel.$from.depth); else selectAt = $pos.before(i); break; } } if (selectAt != null) { updateSelection(view, NodeSelection.create(view.state.doc, selectAt)); return true; } else { return false; } } function handleSingleClick(view, pos, inside, event, selectNode) { return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f) => f(view, pos, event)) || (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside)); } function handleDoubleClick(view, pos, inside, event) { return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", (f) => f(view, pos, event)); } function handleTripleClick(view, pos, inside, event) { return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f) => f(view, pos, event)) || defaultTripleClick(view, inside, event); } function defaultTripleClick(view, inside, event) { if (event.button != 0) return false; let selection = selectionForTripleClick(view, inside, true), doc2 = view.state.doc; if (!selection) return false; updateSelection(view, selection); if (selection instanceof TextSelection && doc2.eq(view.state.doc)) view.input.mouseDown = new TripleClickDrag(view, selection); return true; } function selectionForTripleClick(view, inside, selectNodes) { let doc2 = view.state.doc; if (inside == -1) return doc2.inlineContent ? TextSelection.create(doc2, 0, doc2.content.size) : null; let $pos = doc2.resolve(inside); for (let i = $pos.depth + 1; i > 0; i--) { let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); let nodePos = $pos.before(i); if (node.inlineContent) return TextSelection.create(doc2, nodePos + 1, nodePos + 1 + node.content.size); else if (selectNodes && NodeSelection.isSelectable(node)) return NodeSelection.create(doc2, nodePos); } return null; } function forceDOMFlush(view) { return endComposition(view); } const selectNodeModifier = mac$2 ? "metaKey" : "ctrlKey"; handlers.mousedown = (view, _event) => { let event = _event; view.input.shiftKey = event.shiftKey; let flushed = forceDOMFlush(view); let now = Date.now(), type = "singleClick"; if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] && view.input.lastClick.button == event.button) { if (view.input.lastClick.type == "singleClick") type = "doubleClick"; else if (view.input.lastClick.type == "doubleClick") type = "tripleClick"; } view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button }; if (view.input.mouseDown) view.input.mouseDown.done(); let pos = view.posAtCoords(eventCoords(event)); if (!pos) return; if (type == "singleClick") { view.input.mouseDown = new LeftMouseDown(view, pos, event, !!flushed); } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) { event.preventDefault(); } else { setSelectionOrigin(view, "pointer"); } }; class MouseDown { constructor(view) { this.view = view; this.mightDrag = null; view.root.addEventListener("mouseup", this.up = this.up.bind(this)); view.root.addEventListener("mousemove", this.move = this.move.bind(this)); } up(event) { this.done(); } move(event) { if (event.buttons == 0) this.done(); } done() { this.view.root.removeEventListener("mouseup", this.up); this.view.root.removeEventListener("mousemove", this.move); if (this.view.input.mouseDown == this) this.view.input.mouseDown = null; } delaySelUpdate() { return false; } } class LeftMouseDown extends MouseDown { constructor(view, pos, event, flushed) { super(view); this.pos = pos; this.event = event; this.flushed = flushed; this.delayedSelectionSync = false; this.startDoc = view.state.doc; this.selectNode = !!event[selectNodeModifier]; this.allowDefault = event.shiftKey; let targetNode, targetPos; if (pos.inside > -1) { targetNode = view.state.doc.nodeAt(pos.inside); targetPos = pos.inside; } else { let $pos = view.state.doc.resolve(pos.pos); targetNode = $pos.parent; targetPos = $pos.depth ? $pos.before() : 0; } const target = flushed ? null : event.target; const targetDesc = target ? view.docView.nearestDesc(target, true) : null; this.target = targetDesc && targetDesc.nodeDOM.nodeType == 1 ? targetDesc.nodeDOM : null; let { selection } = view.state; if (event.button == 0 && (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)) this.mightDrag = { node: targetNode, pos: targetPos, addAttr: !!(this.target && !this.target.draggable), setUneditable: !!(this.target && gecko && !this.target.hasAttribute("contentEditable")) }; if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) { this.view.domObserver.stop(); if (this.mightDrag.addAttr) this.target.draggable = true; if (this.mightDrag.setUneditable) setTimeout(() => { if (this.view.input.mouseDown == this) this.target.setAttribute("contentEditable", "false"); }, 20); this.view.domObserver.start(); } setSelectionOrigin(view, "pointer"); } done() { super.done(); if (this.mightDrag && this.target) { this.view.domObserver.stop(); if (this.mightDrag.addAttr) this.target.removeAttribute("draggable"); if (this.mightDrag.setUneditable) this.target.removeAttribute("contentEditable"); this.view.domObserver.start(); } if (this.delayedSelectionSync) setTimeout(() => { if (!this.view.isDestroyed) selectionToDOM(this.view); }); } up(event) { this.done(); if (!this.view.dom.contains(event.target)) return; let pos = this.pos; if (this.view.state.doc != this.startDoc) pos = this.view.posAtCoords(eventCoords(event)); this.updateAllowDefault(event); if (this.allowDefault || !pos) { setSelectionOrigin(this.view, "pointer"); } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) { event.preventDefault(); } else if (event.button == 0 && (this.flushed || // Safari ignores clicks on draggable elements safari && this.mightDrag && !this.mightDrag.node.isAtom || // Chrome will sometimes treat a node selection as a // cursor, but still report that the node is selected // when asked through getSelection. You'll then get a // situation where clicking at the point where that // (hidden) cursor is doesn't change the selection, and // thus doesn't get a reaction from ProseMirror. This // works around that. chrome && !this.view.state.selection.visible && Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2)) { updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos))); event.preventDefault(); } else { setSelectionOrigin(this.view, "pointer"); } } move(event) { this.updateAllowDefault(event); setSelectionOrigin(this.view, "pointer"); super.move(event); } updateAllowDefault(event) { if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4)) this.allowDefault = true; } delaySelUpdate() { if (!this.allowDefault) return false; this.delayedSelectionSync = true; return true; } } class TripleClickDrag extends MouseDown { constructor(view, startSelection) { super(view); this.startSelection = startSelection; this.startDoc = view.state.doc; } move(event) { if (event.buttons == 0 || this.view.isDestroyed || !this.view.state.doc.eq(this.startDoc)) { this.done(); return; } event.preventDefault(); setSelectionOrigin(this.view, "pointer"); let pos = this.view.posAtCoords(eventCoords(event)); let target = pos && selectionForTripleClick(this.view, pos.inside, false); if (!target) return; let { doc: doc2 } = this.view.state, start = this.startSelection; let [anchor, head] = target.from < start.from ? [start.to, target.from] : [start.from, target.to]; updateSelection(this.view, TextSelection.create(doc2, anchor, head)); } } handlers.touchstart = (view) => { view.input.lastTouch = Date.now(); forceDOMFlush(view); setSelectionOrigin(view, "pointer"); }; handlers.touchmove = (view) => { view.input.lastTouch = Date.now(); setSelectionOrigin(view, "pointer"); }; handlers.contextmenu = (view) => forceDOMFlush(view); function inOrNearComposition(view, event) { if (view.composing) return true; if (safari && Math.abs(Date.now() - view.input.compositionEndedAt) < 500) { view.input.compositionEndedAt = -2e8; return true; } return false; } const timeoutComposition = android ? 5e3 : -1; editHandlers.compositionstart = editHandlers.compositionupdate = (view) => { if (!view.composing) { view.domObserver.flush(); let { state } = view, $pos = state.selection.$to; if (state.selection instanceof TextSelection && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some((m) => m.type.spec.inclusive === false) || chrome && windows$1 && selectionBeforeUneditable(view))) { view.markCursor = view.state.storedMarks || $pos.marks(); endComposition(view, true); view.markCursor = null; } else { endComposition(view, !state.selection.empty); if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) { let sel = view.domSelectionRange(); for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0; ) { let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1]; if (!before) break; if (before.nodeType == 3) { let sel2 = view.domSelection(); if (sel2) sel2.collapse(before, before.nodeValue.length); break; } else { node = before; offset = -1; } } } } view.input.composing = true; } scheduleComposeEnd(view, timeoutComposition); }; function selectionBeforeUneditable(view) { let { focusNode, focusOffset } = view.domSelectionRange(); if (!focusNode || focusNode.nodeType != 1 || focusOffset >= focusNode.childNodes.length) return false; let next = focusNode.childNodes[focusOffset]; return next.nodeType == 1 && next.contentEditable == "false"; } editHandlers.compositionend = (view, event) => { if (view.composing) { view.input.composing = false; view.input.compositionEndedAt = Date.now(); view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0; view.input.compositionNode = null; if (view.input.badSafariComposition) view.domObserver.forceFlush(); else if (view.input.compositionPendingChanges) Promise.resolve().then(() => view.domObserver.flush()); view.input.compositionID++; scheduleComposeEnd(view, 20); } }; function scheduleComposeEnd(view, delay) { clearTimeout(view.input.composingTimeout); if (delay > -1) view.input.composingTimeout = setTimeout(() => endComposition(view), delay); } function clearComposition(view) { if (view.composing) { view.input.composing = false; view.input.compositionEndedAt = Date.now(); } while (view.input.compositionNodes.length > 0) view.input.compositionNodes.pop().markParentsDirty(); } function endComposition(view, restarting = false) { if (android && view.domObserver.flushingSoon >= 0) return; view.domObserver.forceFlush(); clearComposition(view); if (restarting || view.docView && view.docView.dirty) { let sel = selectionFromDOM(view), cur = view.state.selection; if (sel && !sel.eq(cur)) view.dispatch(view.state.tr.setSelection(sel)); else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent) view.dispatch(view.state.tr.deleteSelection()); else view.updateState(view.state); return true; } return false; } function captureCopy(view, dom) { if (!view.dom.parentNode) return; let wrap2 = view.dom.parentNode.appendChild(document.createElement("div")); wrap2.appendChild(dom); wrap2.style.cssText = "position: fixed; left: -10000px; top: 10px"; let sel = getSelection(), range = document.createRange(); range.selectNodeContents(dom); view.dom.blur(); sel.removeAllRanges(); sel.addRange(range); setTimeout(() => { if (wrap2.parentNode) wrap2.parentNode.removeChild(wrap2); view.focus(); }, 50); } const brokenClipboardAPI = ie$1 && ie_version < 15 || ios && webkit_version < 604; handlers.copy = editHandlers.cut = (view, _event) => { let event = _event; let sel = view.state.selection, cut2 = event.type == "cut"; if (sel.empty) return; let data = brokenClipboardAPI ? null : event.clipboardData; let slice2 = sel.content(), { dom, text } = serializeForClipboard(view, slice2); if (data) { event.preventDefault(); data.clearData(); data.setData("text/html", dom.innerHTML); data.setData("text/plain", text); } else { captureCopy(view, dom); } if (cut2) view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut")); }; function sliceSingleNode(slice2) { return slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1 ? slice2.content.firstChild : null; } function capturePaste(view, event) { if (!view.dom.parentNode) return; let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code; let target = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div")); if (!plainText) target.contentEditable = "true"; target.style.cssText = "position: fixed; left: -10000px; top: 10px"; target.focus(); let plain = view.input.shiftKey && view.input.lastKeyCode != 45; setTimeout(() => { view.focus(); if (target.parentNode) target.parentNode.removeChild(target); if (plainText) doPaste(view, target.value, null, plain, event); else doPaste(view, target.textContent, target.innerHTML, plain, event); }, 50); } function doPaste(view, text, html2, preferPlain, event) { let slice2 = parseFromClipboard(view, text, html2, preferPlain, view.state.selection.$from); if (view.someProp("handlePaste", (f) => f(view, event, slice2 || Slice.empty))) return true; if (!slice2) return false; let singleNode = sliceSingleNode(slice2); let tr2 = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice2); view.dispatch(tr2.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste")); return true; } function getText(clipboardData) { let text = clipboardData.getData("text/plain") || clipboardData.getData("Text"); if (text) return text; let uris = clipboardData.getData("text/uri-list"); return uris ? uris.replace(/\r?\n/g, " ") : ""; } editHandlers.paste = (view, _event) => { let event = _event; if (view.composing && !android) return; let data = brokenClipboardAPI ? null : event.clipboardData; let plain = view.input.shiftKey && view.input.lastKeyCode != 45; if (data && doPaste(view, getText(data), data.getData("text/html"), plain, event)) event.preventDefault(); else capturePaste(view, event); }; class Dragging { constructor(slice2, move2, node) { this.slice = slice2; this.move = move2; this.node = node; } } const dragCopyModifier = mac$2 ? "altKey" : "ctrlKey"; function dragMoves(view, event) { let copy2; view.someProp("dragCopies", (test) => { copy2 = copy2 || test(event); }); return copy2 != null ? !copy2 : !event[dragCopyModifier]; } handlers.dragstart = (view, _event) => { let event = _event; let mouseDown = view.input.mouseDown; if (mouseDown) mouseDown.done(); if (!event.dataTransfer) return; let sel = view.state.selection; let pos = sel.empty ? null : view.posAtCoords(eventCoords(event)); let node; if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ; else if (mouseDown && mouseDown.mightDrag) { node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos); } else if (event.target && event.target.nodeType == 1) { let desc = view.docView.nearestDesc(event.target, true); if (desc && desc.node.type.spec.draggable && desc != view.docView) node = NodeSelection.create(view.state.doc, desc.posBefore); } let draggedSlice = (node || view.state.selection).content(); let { dom, text, slice: slice2 } = serializeForClipboard(view, draggedSlice); if (!event.dataTransfer.files.length || !chrome || chrome_version > 120) event.dataTransfer.clearData(); event.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML); event.dataTransfer.effectAllowed = "copyMove"; if (!brokenClipboardAPI) event.dataTransfer.setData("text/plain", text); view.dragging = new Dragging(slice2, dragMoves(view, event), node); }; handlers.dragend = (view) => { let dragging2 = view.dragging; window.setTimeout(() => { if (view.dragging == dragging2) view.dragging = null; }, 50); }; editHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault(); editHandlers.drop = (view, event) => { try { handleDrop(view, event, view.dragging); } finally { view.dragging = null; } }; function handleDrop(view, event, dragging2) { if (!event.dataTransfer) return; let eventPos = view.posAtCoords(eventCoords(event)); if (!eventPos) return; let $mouse = view.state.doc.resolve(eventPos.pos); let slice2 = dragging2 && dragging2.slice; if (slice2) { view.someProp("transformPasted", (f) => { slice2 = f(slice2, view, false); }); } else { slice2 = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"), false, $mouse); } let move2 = !!(dragging2 && dragMoves(view, event)); if (view.someProp("handleDrop", (f) => f(view, event, slice2 || Slice.empty, move2))) { event.preventDefault(); return; } if (!slice2) return; event.preventDefault(); let insertPos = slice2 ? dropPoint(view.state.doc, $mouse.pos, slice2) : $mouse.pos; if (insertPos == null) insertPos = $mouse.pos; let tr2 = view.state.tr; if (move2) { let { node } = dragging2; if (node) node.replace(tr2); else tr2.deleteSelection(); } let pos = tr2.mapping.map(insertPos); let isNode = slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1; let beforeInsert = tr2.doc; if (isNode) tr2.replaceRangeWith(pos, pos, slice2.content.firstChild); else tr2.replaceRange(pos, pos, slice2); if (tr2.doc.eq(beforeInsert)) return; let $pos = tr2.doc.resolve(pos); if (isNode && NodeSelection.isSelectable(slice2.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice2.content.firstChild)) { tr2.setSelection(new NodeSelection($pos)); } else { let end = tr2.mapping.map(insertPos); tr2.mapping.maps[tr2.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo); tr2.setSelection(selectionBetween(view, $pos, tr2.doc.resolve(end))); } view.focus(); view.dispatch(tr2.setMeta("uiEvent", "drop")); } handlers.focus = (view) => { view.input.lastFocus = Date.now(); if (!view.focused) { view.domObserver.stop(); view.dom.classList.add("ProseMirror-focused"); view.domObserver.start(); view.focused = true; setTimeout(() => { if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange())) selectionToDOM(view); }, 20); } }; handlers.blur = (view, _event) => { let event = _event; if (view.focused) { view.domObserver.stop(); view.dom.classList.remove("ProseMirror-focused"); view.domObserver.start(); if (event.relatedTarget && view.dom.contains(event.relatedTarget)) view.domObserver.currentSelection.clear(); view.focused = false; } }; handlers.beforeinput = (view, _event) => { let event = _event; if (android && event.inputType == "deleteContentBackward") { view.domObserver.flushSoon(); let { domChangeCount } = view.input; setTimeout(() => { if (view.input.domChangeCount != domChangeCount) return; view.dom.blur(); view.focus(); if (view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) return; let { $cursor } = view.state.selection; if ($cursor && $cursor.pos > 0) view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView()); }, 50); } }; for (let prop in editHandlers) handlers[prop] = editHandlers[prop]; function compareObjs(a, b) { if (a == b) return true; for (let p in a) if (a[p] !== b[p]) return false; for (let p in b) if (!(p in a)) return false; return true; } class WidgetType { constructor(toDOM, spec) { this.toDOM = toDOM; this.spec = spec || noSpec; this.side = this.spec.side || 0; } map(mapping, span, offset, oldOffset) { let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1); return deleted ? null : new Decoration(pos - offset, pos - offset, this); } valid() { return true; } eq(other) { return this == other || other instanceof WidgetType && (this.spec.key && this.spec.key == other.spec.key || this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)); } destroy(node) { if (this.spec.destroy) this.spec.destroy(node); } } class InlineType { constructor(attrs, spec) { this.attrs = attrs; this.spec = spec || noSpec; } map(mapping, span, offset, oldOffset) { let from2 = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset; let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset; return from2 >= to ? null : new Decoration(from2, to, this); } valid(_, span) { return span.from < span.to; } eq(other) { return this == other || other instanceof InlineType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec); } static is(span) { return span.type instanceof InlineType; } destroy() { } } class NodeType2 { constructor(attrs, spec) { this.attrs = attrs; this.spec = spec || noSpec; } map(mapping, span, offset, oldOffset) { let from2 = mapping.mapResult(span.from + oldOffset, 1); if (from2.deleted) return null; let to = mapping.mapResult(span.to + oldOffset, -1); if (to.deleted || to.pos <= from2.pos) return null; return new Decoration(from2.pos - offset, to.pos - offset, this); } valid(node, span) { let { index, offset } = node.content.findIndex(span.from), child; return offset == span.from && !(child = node.child(index)).isText && offset + child.nodeSize == span.to; } eq(other) { return this == other || other instanceof NodeType2 && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec); } destroy() { } } class Decoration { /** @internal */ constructor(from2, to, type) { this.from = from2; this.to = to; this.type = type; } /** @internal */ copy(from2, to) { return new Decoration(from2, to, this.type); } /** @internal */ eq(other, offset = 0) { return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to; } /** @internal */ map(mapping, offset, oldOffset) { return this.type.map(mapping, this, offset, oldOffset); } /** Creates a widget decoration, which is a DOM node that's shown in the document at the given position. It is recommended that you delay rendering the widget by passing a function that will be called when the widget is actually drawn in a view, but you can also directly pass a DOM node. `getPos` can be used to find the widget's current document position. */ static widget(pos, toDOM, spec) { return new Decoration(pos, pos, new WidgetType(toDOM, spec)); } /** Creates an inline decoration, which adds the given attributes to each inline node between `from` and `to`. */ static inline(from2, to, attrs, spec) { return new Decoration(from2, to, new InlineType(attrs, spec)); } /** Creates a node decoration. `from` and `to` should point precisely before and after a node in the document. That node, and only that node, will receive the given attributes. */ static node(from2, to, attrs, spec) { return new Decoration(from2, to, new NodeType2(attrs, spec)); } /** The spec provided when creating this decoration. Can be useful if you've stored extra information in that object. */ get spec() { return this.type.spec; } /** @internal */ get inline() { return this.type instanceof InlineType; } /** @internal */ get widget() { return this.type instanceof WidgetType; } } const none = [], noSpec = {}; class DecorationSet { /** @internal */ constructor(local, children) { this.local = local.length ? local : none; this.children = children.length ? children : none; } /** Create a set of decorations, using the structure of the given document. This will consume (modify) the `decorations` array, so you must make a copy if you want need to preserve that. */ static create(doc2, decorations) { return decorations.length ? buildTree(decorations, doc2, 0, noSpec) : empty; } /** Find all decorations in this set which touch the given range (including decorations that start or end directly at the boundaries) and match the given predicate on their spec. When `start` and `end` are omitted, all decorations in the set are considered. When `predicate` isn't given, all decorations are assumed to match. */ find(start, end, predicate) { let result = []; this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate); return result; } findInner(start, end, result, offset, predicate) { for (let i = 0; i < this.local.length; i++) { let span = this.local[i]; if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec))) result.push(span.copy(span.from + offset, span.to + offset)); } for (let i = 0; i < this.children.length; i += 3) { if (this.children[i] < end && this.children[i + 1] > start) { let childOff = this.children[i] + 1; this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate); } } } /** Map the set of decorations in response to a change in the document. */ map(mapping, doc2, options) { if (this == empty || mapping.maps.length == 0) return this; return this.mapInner(mapping, doc2, 0, 0, options || noSpec); } /** @internal */ mapInner(mapping, node, offset, oldOffset, options) { let newLocal; for (let i = 0; i < this.local.length; i++) { let mapped = this.local[i].map(mapping, offset, oldOffset); if (mapped && mapped.type.valid(node, mapped)) (newLocal || (newLocal = [])).push(mapped); else if (options.onRemove) options.onRemove(this.local[i].spec); } if (this.children.length) return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options); else return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty; } /** Add the given array of decorations to the ones in the set, producing a new set. Consumes the `decorations` array. Needs access to the current document to create the appropriate tree structure. */ add(doc2, decorations) { if (!decorations.length) return this; if (this == empty) return DecorationSet.create(doc2, decorations); return this.addInner(doc2, decorations, 0); } addInner(doc2, decorations, offset) { let children, childIndex = 0; doc2.forEach((childNode, childOffset) => { let baseOffset = childOffset + offset, found2; if (!(found2 = takeSpansForNode(decorations, childNode, baseOffset))) return; if (!children) children = this.children.slice(); while (childIndex < children.length && children[childIndex] < childOffset) childIndex += 3; if (children[childIndex] == childOffset) children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found2, baseOffset + 1); else children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found2, childNode, baseOffset + 1, noSpec)); childIndex += 3; }); let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset); for (let i = 0; i < local.length; i++) if (!local[i].type.valid(doc2, local[i])) local.splice(i--, 1); return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children); } /** Create a new set that contains the decorations in this set, minus the ones in the given array. */ remove(decorations) { if (decorations.length == 0 || this == empty) return this; return this.removeInner(decorations, 0); } removeInner(decorations, offset) { let children = this.children, local = this.local; for (let i = 0; i < children.length; i += 3) { let found2; let from2 = children[i] + offset, to = children[i + 1] + offset; for (let j = 0, span; j < decorations.length; j++) if (span = decorations[j]) { if (span.from > from2 && span.to < to) { decorations[j] = null; (found2 || (found2 = [])).push(span); } } if (!found2) continue; if (children == this.children) children = this.children.slice(); let removed = children[i + 2].removeInner(found2, from2 + 1); if (removed != empty) { children[i + 2] = removed; } else { children.splice(i, 3); i -= 3; } } if (local.length) { for (let i = 0, span; i < decorations.length; i++) if (span = decorations[i]) { for (let j = 0; j < local.length; j++) if (local[j].eq(span, offset)) { if (local == this.local) local = this.local.slice(); local.splice(j--, 1); } } } if (children == this.children && local == this.local) return this; return local.length || children.length ? new DecorationSet(local, children) : empty; } forChild(offset, node) { if (this == empty) return this; if (node.isLeaf) return DecorationSet.empty; let child, local; for (let i = 0; i < this.children.length; i += 3) if (this.children[i] >= offset) { if (this.children[i] == offset) child = this.children[i + 2]; break; } let start = offset + 1, end = start + node.content.size; for (let i = 0; i < this.local.length; i++) { let dec = this.local[i]; if (dec.from < end && dec.to > start && dec.type instanceof InlineType) { let from2 = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start; if (from2 < to) (local || (local = [])).push(dec.copy(from2, to)); } } if (local) { let localSet = new DecorationSet(local.sort(byPos), none); return child ? new DecorationGroup([localSet, child]) : localSet; } return child || empty; } /** @internal */ eq(other) { if (this == other) return true; if (!(other instanceof DecorationSet) || this.local.length != other.local.length || this.children.length != other.children.length) return false; for (let i = 0; i < this.local.length; i++) if (!this.local[i].eq(other.local[i])) return false; for (let i = 0; i < this.children.length; i += 3) if (this.children[i] != other.children[i] || this.children[i + 1] != other.children[i + 1] || !this.children[i + 2].eq(other.children[i + 2])) return false; return true; } /** @internal */ locals(node) { return removeOverlap(this.localsInner(node)); } /** @internal */ localsInner(node) { if (this == empty) return none; if (node.inlineContent || !this.local.some(InlineType.is)) return this.local; let result = []; for (let i = 0; i < this.local.length; i++) { if (!(this.local[i].type instanceof InlineType)) result.push(this.local[i]); } return result; } forEachSet(f) { f(this); } } DecorationSet.empty = new DecorationSet([], []); DecorationSet.removeOverlap = removeOverlap; const empty = DecorationSet.empty; class DecorationGroup { constructor(members) { this.members = members; } map(mapping, doc2) { const mappedDecos = this.members.map((member) => member.map(mapping, doc2, noSpec)); return DecorationGroup.from(mappedDecos); } forChild(offset, child) { if (child.isLeaf) return DecorationSet.empty; let found2 = []; for (let i = 0; i < this.members.length; i++) { let result = this.members[i].forChild(offset, child); if (result == empty) continue; if (result instanceof DecorationGroup) found2 = found2.concat(result.members); else found2.push(result); } return DecorationGroup.from(found2); } eq(other) { if (!(other instanceof DecorationGroup) || other.members.length != this.members.length) return false; for (let i = 0; i < this.members.length; i++) if (!this.members[i].eq(other.members[i])) return false; return true; } locals(node) { let result, sorted = true; for (let i = 0; i < this.members.length; i++) { let locals = this.members[i].localsInner(node); if (!locals.length) continue; if (!result) { result = locals; } else { if (sorted) { result = result.slice(); sorted = false; } for (let j = 0; j < locals.length; j++) result.push(locals[j]); } } return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none; } // Create a group for the given array of decoration sets, or return // a single set when possible. static from(members) { switch (members.length) { case 0: return empty; case 1: return members[0]; default: return new DecorationGroup(members.every((m) => m instanceof DecorationSet) ? members : members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), [])); } } forEachSet(f) { for (let i = 0; i < this.members.length; i++) this.members[i].forEachSet(f); } } function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) { let children = oldChildren.slice(); for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) { let moved = 0; mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => { let dSize = newEnd - newStart - (oldEnd - oldStart); for (let i2 = 0; i2 < children.length; i2 += 3) { let end = children[i2 + 1]; if (end < 0 || oldStart > end + baseOffset - moved) continue; let start = children[i2] + baseOffset - moved; if (oldEnd >= start) { children[i2 + 1] = oldStart <= start ? -2 : -1; } else if (oldStart >= baseOffset && dSize) { children[i2] += dSize; children[i2 + 1] += dSize; } } moved += dSize; }); baseOffset = mapping.maps[i].map(baseOffset, -1); } let mustRebuild = false; for (let i = 0; i < children.length; i += 3) if (children[i + 1] < 0) { if (children[i + 1] == -2) { mustRebuild = true; children[i + 1] = -1; continue; } let from2 = mapping.map(oldChildren[i] + oldOffset), fromLocal = from2 - offset; if (fromLocal < 0 || fromLocal >= node.content.size) { mustRebuild = true; continue; } let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset; let { index, offset: childOffset } = node.content.findIndex(fromLocal); let childNode = node.maybeChild(index); if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) { let mapped = children[i + 2].mapInner(mapping, childNode, from2 + 1, oldChildren[i] + oldOffset + 1, options); if (mapped != empty) { children[i] = fromLocal; children[i + 1] = toLocal; children[i + 2] = mapped; } else { children[i + 1] = -2; mustRebuild = true; } } else { mustRebuild = true; } } if (mustRebuild) { let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options); let built = buildTree(decorations, node, 0, options); newLocal = built.local; for (let i = 0; i < children.length; i += 3) if (children[i + 1] < 0) { children.splice(i, 3); i -= 3; } for (let i = 0, j = 0; i < built.children.length; i += 3) { let from2 = built.children[i]; while (j < children.length && children[j] < from2) j += 3; children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]); } } return new DecorationSet(newLocal.sort(byPos), children); } function moveSpans(spans, offset) { if (!offset || !spans.length) return spans; let result = []; for (let i = 0; i < spans.length; i++) { let span = spans[i]; result.push(new Decoration(span.from + offset, span.to + offset, span.type)); } return result; } function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) { function gather(set, oldOffset2) { for (let i = 0; i < set.local.length; i++) { let mapped = set.local[i].map(mapping, offset, oldOffset2); if (mapped) decorations.push(mapped); else if (options.onRemove) options.onRemove(set.local[i].spec); } for (let i = 0; i < set.children.length; i += 3) gather(set.children[i + 2], set.children[i] + oldOffset2 + 1); } for (let i = 0; i < children.length; i += 3) if (children[i + 1] == -1) gather(children[i + 2], oldChildren[i] + oldOffset + 1); return decorations; } function takeSpansForNode(spans, node, offset) { if (node.isLeaf) return null; let end = offset + node.nodeSize, found2 = null; for (let i = 0, span; i < spans.length; i++) { if ((span = spans[i]) && span.from > offset && span.to < end) { (found2 || (found2 = [])).push(span); spans[i] = null; } } return found2; } function withoutNulls(array) { let result = []; for (let i = 0; i < array.length; i++) if (array[i] != null) result.push(array[i]); return result; } function buildTree(spans, node, offset, options) { let children = [], hasNulls = false; node.forEach((childNode, localStart) => { let found2 = takeSpansForNode(spans, childNode, localStart + offset); if (found2) { hasNulls = true; let subtree = buildTree(found2, childNode, offset + localStart + 1, options); if (subtree != empty) children.push(localStart, localStart + childNode.nodeSize, subtree); } }); let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos); for (let i = 0; i < locals.length; i++) if (!locals[i].type.valid(node, locals[i])) { if (options.onRemove) options.onRemove(locals[i].spec); locals.splice(i--, 1); } return locals.length || children.length ? new DecorationSet(locals, children) : empty; } function byPos(a, b) { return a.from - b.from || a.to - b.to; } function removeOverlap(spans) { let working = spans; for (let i = 0; i < working.length - 1; i++) { let span = working[i]; if (span.from != span.to) for (let j = i + 1; j < working.length; j++) { let next = working[j]; if (next.from == span.from) { if (next.to != span.to) { if (working == spans) working = spans.slice(); working[j] = next.copy(next.from, span.to); insertAhead(working, j + 1, next.copy(span.to, next.to)); } continue; } else { if (next.from < span.to) { if (working == spans) working = spans.slice(); working[i] = span.copy(span.from, next.from); insertAhead(working, j, span.copy(next.from, span.to)); } break; } } } return working; } function insertAhead(array, i, deco) { while (i < array.length && byPos(deco, array[i]) > 0) i++; array.splice(i, 0, deco); } var base = { 8: "Backspace", 9: "Tab", 10: "Enter", 12: "NumLock", 13: "Enter", 16: "Shift", 17: "Control", 18: "Alt", 20: "CapsLock", 27: "Escape", 32: " ", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "ArrowLeft", 38: "ArrowUp", 39: "ArrowRight", 40: "ArrowDown", 44: "PrintScreen", 45: "Insert", 46: "Delete", 59: ";", 61: "=", 91: "Meta", 92: "Meta", 106: "*", 107: "+", 108: ",", 109: "-", 110: ".", 111: "/", 144: "NumLock", 145: "ScrollLock", 160: "Shift", 161: "Shift", 162: "Control", 163: "Control", 164: "Alt", 165: "Alt", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'" }; var shift = { 48: ")", 49: "!", 50: "@", 51: "#", 52: "$", 53: "%", 54: "^", 55: "&", 56: "*", 57: "(", 59: ":", 61: "+", 173: "_", 186: ":", 187: "+", 188: "<", 189: "_", 190: ">", 191: "?", 192: "~", 219: "{", 220: "|", 221: "}", 222: '"' }; var mac$1 = typeof navigator != "undefined" && /Mac/.test(navigator.platform); var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; for (var i = 65; i <= 90; i++) { base[i] = String.fromCharCode(i + 32); shift[i] = String.fromCharCode(i); } for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; function keyName(event) { var ignoreKey = mac$1 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified"; var name = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified"; if (name == "Esc") name = "Escape"; if (name == "Del") name = "Delete"; if (name == "Left") name = "ArrowLeft"; if (name == "Up") name = "ArrowUp"; if (name == "Right") name = "ArrowRight"; if (name == "Down") name = "ArrowDown"; return name; } const mac = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform); const windows = typeof navigator != "undefined" && /Win/.test(navigator.platform); function normalizeKeyName$1(name) { let parts = name.split(/-(?!$)/), result = parts[parts.length - 1]; if (result == "Space") result = " "; let alt, ctrl, shift2, meta; for (let i = 0; i < parts.length - 1; i++) { let mod = parts[i]; if (/^(cmd|meta|m)$/i.test(mod)) meta = true; else if (/^a(lt)?$/i.test(mod)) alt = true; else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; else if (/^s(hift)?$/i.test(mod)) shift2 = true; else if (/^mod$/i.test(mod)) { if (mac) meta = true; else ctrl = true; } else throw new Error("Unrecognized modifier name: " + mod); } if (alt) result = "Alt-" + result; if (ctrl) result = "Ctrl-" + result; if (meta) result = "Meta-" + result; if (shift2) result = "Shift-" + result; return result; } function normalize(map2) { let copy2 = /* @__PURE__ */ Object.create(null); for (let prop in map2) copy2[normalizeKeyName$1(prop)] = map2[prop]; return copy2; } function modifiers(name, event, shift2 = true) { if (event.altKey) name = "Alt-" + name; if (event.ctrlKey) name = "Ctrl-" + name; if (event.metaKey) name = "Meta-" + name; if (shift2 && event.shiftKey) name = "Shift-" + name; return name; } function keydownHandler$1(bindings) { let map2 = normalize(bindings); return function(view, event) { let name = keyName(event), baseName, direct = map2[modifiers(name, event)]; if (direct && direct(view.state, view.dispatch, view)) return true; if (name.length == 1 && name != " ") { if (event.shiftKey) { let noShift = map2[modifiers(name, event, false)]; if (noShift && noShift(view.state, view.dispatch, view)) return true; } if ((event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows !(windows && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name) { let fromCode = map2[modifiers(baseName, event)]; if (fromCode && fromCode(view.state, view.dispatch, view)) return true; } } return false; }; } function createChainableState(config) { const { state, transaction } = config; let { selection } = transaction; let { doc: doc2 } = transaction; let { storedMarks } = transaction; return { ...state, apply: state.apply.bind(state), applyTransaction: state.applyTransaction.bind(state), plugins: state.plugins, schema: state.schema, reconfigure: state.reconfigure.bind(state), toJSON: state.toJSON.bind(state), get storedMarks() { return storedMarks; }, get selection() { return selection; }, get doc() { return doc2; }, get tr() { selection = transaction.selection; doc2 = transaction.doc; storedMarks = transaction.storedMarks; return transaction; } }; } var CommandManager = class CommandManager2 { constructor(props) { this.editor = props.editor; this.rawCommands = this.editor.extensionManager.commands; this.customState = props.state; } get hasCustomState() { return !!this.customState; } get state() { return this.customState || this.editor.state; } get commands() { const { rawCommands, editor, state } = this; const { view } = editor; const { tr: tr2 } = state; const props = this.buildProps(tr2); return Object.fromEntries(Object.entries(rawCommands).map(([name, command2]) => { const method = (...args) => { const callback = command2(...args)(props); if (!tr2.getMeta("preventDispatch") && !this.hasCustomState) view.dispatch(tr2); return callback; }; return [name, method]; })); } get chain() { return () => this.createChain(); } get can() { return () => this.createCan(); } createChain(startTr, shouldDispatch = true) { const { rawCommands, editor, state } = this; const { view } = editor; const callbacks = []; const hasStartTransaction = !!startTr; const tr2 = startTr || state.tr; const run2 = () => { if (!hasStartTransaction && shouldDispatch && !tr2.getMeta("preventDispatch") && !this.hasCustomState) view.dispatch(tr2); return callbacks.every((callback) => callback === true); }; const chain = { ...Object.fromEntries(Object.entries(rawCommands).map(([name, command2]) => { const chainedCommand = (...args) => { const props = this.buildProps(tr2, shouldDispatch); const callback = command2(...args)(props); callbacks.push(callback); return chain; }; return [name, chainedCommand]; })), run: run2 }; return chain; } /** * Creates a chain that safely returns `false` when run. * @returns A non-dispatching command chain. * @example * const chain = CommandManager.createFakeChain() * chain.focus().run() // false */ static createFakeChain() { const chain = new Proxy({}, { get: (_target, property) => { if (property === "then") return; if (property === "run") return () => false; return () => chain; } }); return chain; } createCan(startTr) { const { rawCommands, state } = this; const dispatch = false; const tr2 = startTr || state.tr; const props = this.buildProps(tr2, dispatch); return { ...Object.fromEntries(Object.entries(rawCommands).map(([name, command2]) => { return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })]; })), chain: () => this.createChain(tr2, dispatch) }; } /** * Creates capability checks that safely return `false`. * @returns A non-dispatching capability checker. * @example * const can = CommandManager.createFallbackCan() * can.focus() // false */ static createFallbackCan() { const chain = CommandManager2.createFakeChain(); return new Proxy({ chain: () => chain }, { get: (target, property) => { if (property === "then") return; if (property === "chain") return target.chain; return () => false; } }); } buildProps(tr2, shouldDispatch = true) { const { rawCommands, editor, state } = this; const { view } = editor; const props = { tr: tr2, editor, view, state: createChainableState({ state, transaction: tr2 }), dispatch: shouldDispatch ? () => void 0 : void 0, chain: () => this.createChain(tr2, shouldDispatch), can: () => this.createCan(tr2), get commands() { return Object.fromEntries(Object.entries(rawCommands).map(([name, command2]) => { return [name, (...args) => command2(...args)(props)]; })); } }; return props; } }; const blur = () => ({ editor, view }) => { requestAnimationFrame(() => { if (!editor.isDestroyed) { var _window; view.dom.blur(); (_window = window) === null || _window === void 0 || (_window = _window.getSelection()) === null || _window === void 0 || _window.removeAllRanges(); } }); return true; }; const clearContent = (emitUpdate = true) => ({ commands }) => { return commands.setContent("", { emitUpdate }); }; const clearNodes = () => ({ state, tr: tr2, dispatch }) => { const { selection } = tr2; const { ranges } = selection; if (!dispatch) return true; ranges.forEach(({ $from, $to }) => { state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => { if (node.type.isText) return; const { doc: doc2, mapping } = tr2; const $mappedFrom = doc2.resolve(mapping.map(pos)); const $mappedTo = doc2.resolve(mapping.map(pos + node.nodeSize)); const nodeRange = $mappedFrom.blockRange($mappedTo); if (!nodeRange) return; const targetLiftDepth = liftTarget(nodeRange); if (node.type.isTextblock) { const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index()); tr2.setNodeMarkup(nodeRange.start, defaultType); } if (targetLiftDepth || targetLiftDepth === 0) tr2.lift(nodeRange, targetLiftDepth); }); }); return true; }; const command = (fn) => (props) => { return fn(props); }; const createParagraphNear$1 = () => ({ state, dispatch }) => { return createParagraphNear(state, dispatch); }; const cut = (originRange, targetPos) => ({ editor, tr: tr2 }) => { const { state } = editor; const contentSlice = state.doc.slice(originRange.from, originRange.to); tr2.deleteRange(originRange.from, originRange.to); const newPos = tr2.mapping.map(targetPos); tr2.insert(newPos, contentSlice.content); tr2.setSelection(new TextSelection(tr2.doc.resolve(Math.max(newPos - 1, 0)))); return true; }; const deleteCurrentNode = () => ({ tr: tr2, dispatch }) => { const { selection } = tr2; const currentNode = selection.$anchor.node(); if (currentNode.content.size > 0) return false; const $pos = tr2.selection.$anchor; for (let depth = $pos.depth; depth > 0; depth -= 1) if ($pos.node(depth).type === currentNode.type) { if (dispatch) { const from2 = $pos.before(depth); const to = $pos.after(depth); tr2.delete(from2, to).scrollIntoView(); } return true; } return false; }; function getNodeType(nameOrType, schema) { if (typeof nameOrType === "string") { if (!schema.nodes[nameOrType]) throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`); return schema.nodes[nameOrType]; } return nameOrType; } const deleteNode = (typeOrName) => ({ tr: tr2, state, dispatch }) => { const type = getNodeType(typeOrName, state.schema); const $pos = tr2.selection.$anchor; for (let depth = $pos.depth; depth > 0; depth -= 1) if ($pos.node(depth).type === type) { if (dispatch) { const from2 = $pos.before(depth); const to = $pos.after(depth); tr2.delete(from2, to).scrollIntoView(); } return true; } return false; }; const deleteRange = (range) => ({ tr: tr2, dispatch }) => { const { from: from2, to } = range; if (dispatch) tr2.delete(from2, to); return true; }; const hasTextContent = (nodeSpec) => { if (!nodeSpec.content) return false; return /^text(\*|\+)/.test(nodeSpec.content); }; const expandSelectionForSide = ($pos, schema, side) => { if (!$pos.parent.isInline) return $pos.pos; if (side === "left" && $pos.pos > $pos.start() || side === "right" && $pos.pos < $pos.end()) return $pos.pos; const parentContent = schema.nodes[$pos.parent.type.name].spec; if (!hasTextContent(parentContent)) return $pos.pos; return side === "left" ? $pos.start() - 1 : $pos.end() + 1; }; const expandSelectionForInlineText = ($from, $to, schema) => { return { from: expandSelectionForSide($from, schema, "left"), to: expandSelectionForSide($to, schema, "right") }; }; const deleteSelection = () => ({ state, dispatch }) => { if (state.selection.empty) return false; if (dispatch) { const tr2 = state.tr; const { ranges } = state.selection; const mapFrom = tr2.steps.length; ranges.forEach((range) => { const mapping = tr2.mapping.slice(mapFrom); const $from = tr2.doc.resolve(mapping.map(range.$from.pos)); const $to = tr2.doc.resolve(mapping.map(range.$to.pos)); const { from: from2, to } = expandSelectionForInlineText($from, $to, state.schema); tr2.deleteRange(from2, to); }); if (!tr2.selection.empty) tr2.setSelection(TextSelection.near(tr2.doc.resolve(tr2.selection.from))); tr2.scrollIntoView(); dispatch(tr2); } return true; }; const enter = () => ({ commands }) => { return commands.keyboardShortcut("Enter"); }; const exitCode$1 = () => ({ state, dispatch }) => { return exitCode(state, dispatch); }; function isRegExp(value) { return Object.prototype.toString.call(value) === "[object RegExp]"; } function objectIncludes(object1, object2, options = { strict: true }) { const keys2 = Object.keys(object2); if (!keys2.length) return true; return keys2.every((key) => { if (options.strict) return object2[key] === object1[key]; if (isRegExp(object2[key])) return object2[key].test(object1[key]); return object2[key] === object1[key]; }); } function findMarkInSet(marks, type, attributes = {}) { return marks.find((item) => { return item.type === type && objectIncludes(Object.fromEntries(Object.keys(attributes).map((k) => [k, item.attrs[k]])), attributes); }); } function isMarkInSet(marks, type, attributes = {}) { return !!findMarkInSet(marks, type, attributes); } function getMarkRange($pos, type, attributes) { if (!$pos || !type) return; let start = $pos.parent.childAfter($pos.parentOffset); if (!start.node || !start.node.marks.some((mark) => mark.type === type)) start = $pos.parent.childBefore($pos.parentOffset); if (!start.node || !start.node.marks.some((mark) => mark.type === type)) return; if (!attributes) { const firstMark = start.node.marks.find((mark) => mark.type === type); if (firstMark) attributes = firstMark.attrs; } if (!findMarkInSet([...start.node.marks], type, attributes)) return; let startIndex = start.index; let startPos = $pos.start() + start.offset; let endIndex = startIndex + 1; let endPos = startPos + start.node.nodeSize; while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) { startIndex -= 1; startPos -= $pos.parent.child(startIndex).nodeSize; } while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) { endPos += $pos.parent.child(endIndex).nodeSize; endIndex += 1; } return { from: startPos, to: endPos }; } function getMarkType(nameOrType, schema) { if (typeof nameOrType === "string") { if (!schema.marks[nameOrType]) throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`); return schema.marks[nameOrType]; } return nameOrType; } const extendMarkRange = (typeOrName, attributes) => ({ tr: tr2, state, dispatch }) => { const type = getMarkType(typeOrName, state.schema); const { doc: doc2, selection } = tr2; const { $from, from: from2, to } = selection; if (dispatch) { const range = getMarkRange($from, type, attributes); if (range && range.from <= from2 && range.to >= to) { const newSelection = TextSelection.create(doc2, range.from, range.to); tr2.setSelection(newSelection); } } return true; }; const first = (commands) => (props) => { const items = typeof commands === "function" ? commands(props) : commands; for (let i = 0; i < items.length; i += 1) if (items[i](props)) return true; return false; }; function isTextSelection(value) { return value instanceof TextSelection; } function minMax(value = 0, min = 0, max = 0) { return Math.min(Math.max(value, min), max); } function resolveFocusPosition(doc2, position = null) { if (!position) return null; const selectionAtStart = Selection.atStart(doc2); const selectionAtEnd = Selection.atEnd(doc2); if (position === "start" || position === true) return selectionAtStart; if (position === "end") return selectionAtEnd; const minPos = selectionAtStart.from; const maxPos = selectionAtEnd.to; if (position === "all") return TextSelection.create(doc2, minMax(0, minPos, maxPos), minMax(doc2.content.size, minPos, maxPos)); return TextSelection.create(doc2, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos)); } function isAndroid() { return ["Android"].includes(navigator.platform) || /android/i.test(navigator.userAgent); } function isiOS() { return [ "iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod" ].includes(navigator.platform) || navigator.userAgent.includes("Mac") && "ontouchend" in document; } function isSafari() { return typeof navigator !== "undefined" ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false; } const focus = (position = null, options = {}) => ({ editor, view, tr: tr2, dispatch }) => { options = { scrollIntoView: true, ...options }; const delayedFocus = () => { if (isiOS() || isAndroid()) view.dom.focus(); if (isSafari() && !isiOS() && !isAndroid()) view.dom.focus({ preventScroll: true }); requestAnimationFrame(() => { if (!editor.isDestroyed) { view.focus(); if (options === null || options === void 0 ? void 0 : options.scrollIntoView) editor.commands.scrollIntoView(); } }); }; try { if (view.hasFocus() && position === null || position === false) return true; } catch { return false; } if (dispatch && position === null && !isTextSelection(editor.state.selection)) { delayedFocus(); return true; } const selection = resolveFocusPosition(tr2.doc, position) || editor.state.selection; const isSameSelection = editor.state.selection.eq(selection); if (dispatch) { if (!isSameSelection) tr2.setSelection(selection); if (isSameSelection && tr2.storedMarks) tr2.setStoredMarks(tr2.storedMarks); delayedFocus(); } return true; }; const forEach = (items, fn) => (props) => { return items.every((item, index) => fn(item, { ...props, index })); }; const insertContent = (value, options) => ({ tr: tr2, commands }) => { return commands.insertContentAt({ from: tr2.selection.from, to: tr2.selection.to }, value, options); }; const removeWhitespaces = (node) => { const children = node.childNodes; for (let i = children.length - 1; i >= 0; i -= 1) { const child = children[i]; if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) node.removeChild(child); else if (child.nodeType === 1) removeWhitespaces(child); } return node; }; function elementFromString(value) { if (typeof window === "undefined") throw new Error("[tiptap error]: there is no window object available, so this function cannot be used"); const wrappedValue = `${value}`; const html2 = new window.DOMParser().parseFromString(wrappedValue, "text/html").body; return removeWhitespaces(html2); } function isProseMirrorContent(value) { return typeof (value === null || value === void 0 ? void 0 : value.nodesBetween) === "function"; } function createNodeFromContent(content, schema, options) { if (isProseMirrorContent(content)) return content; const isJSONContent = typeof content === "object" && content !== null; options = { slice: true, parseOptions: {}, ...options }; const isTextContent = typeof content === "string"; if (isJSONContent) try { if (Array.isArray(content) && content.length > 0) return Fragment.fromArray(content.map((item) => schema.nodeFromJSON(item))); const node = schema.nodeFromJSON(content); if (options.errorOnInvalidContent) node.check(); return node; } catch (error2) { if (options.errorOnInvalidContent) throw new Error("[tiptap error]: Invalid JSON content", { cause: error2 }); console.warn("[tiptap warn]: Invalid content.", "Passed value:", content, "Error:", error2); return createNodeFromContent("", schema, options); } if (isTextContent) { if (options.errorOnInvalidContent) { let hasInvalidContent = false; let invalidContent = ""; const contentCheckSchema = new Schema({ topNode: schema.spec.topNode, marks: schema.spec.marks, nodes: schema.spec.nodes.append({ __tiptap__private__unknown__catch__all__node: { content: "inline*", group: "block", parseDOM: [{ tag: "*", getAttrs: (e) => { hasInvalidContent = true; invalidContent = typeof e === "string" ? e : e.outerHTML; return null; } }] } }) }); if (options.slice) DOMParser$1.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions); else DOMParser$1.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions); if (options.errorOnInvalidContent && hasInvalidContent) throw new Error("[tiptap error]: Invalid HTML content", { cause: /* @__PURE__ */ new Error(`Invalid element found: ${invalidContent}`) }); } const parser = DOMParser$1.fromSchema(schema); if (options.slice) return parser.parseSlice(elementFromString(content), options.parseOptions).content; return parser.parse(elementFromString(content), options.parseOptions); } return createNodeFromContent("", schema, options); } function isFragment(nodeOrFragment) { return !("type" in nodeOrFragment); } function selectionToInsertionEnd(tr2, startLen, bias) { const last = tr2.steps.length - 1; if (last < startLen) return; const step = tr2.steps[last]; if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) return; const map2 = tr2.mapping.maps[last]; let end = 0; map2.forEach((_from, _to, _newFrom, newTo) => { if (end === 0) end = newTo; }); tr2.setSelection(Selection.near(tr2.doc.resolve(end), bias)); } const insertContentAt = (position, value, options) => ({ tr: tr2, dispatch, editor }) => { if (dispatch) { options = { parseOptions: editor.options.parseOptions, updateSelection: true, applyInputRules: false, applyPasteRules: false, ...options }; let content; const emitContentError = (error2) => { editor.emit("contentError", { editor, error: error2, disableCollaboration: () => { if ("collaboration" in editor.storage && typeof editor.storage.collaboration === "object" && editor.storage.collaboration) editor.storage.collaboration.isDisabled = true; } }); }; const parseOptions = { preserveWhitespace: "full", ...options.parseOptions }; if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) try { createNodeFromContent(value, editor.schema, { parseOptions, errorOnInvalidContent: true }); } catch (e) { emitContentError(e); } try { var _options$errorOnInval; content = createNodeFromContent(value, editor.schema, { parseOptions, errorOnInvalidContent: (_options$errorOnInval = options.errorOnInvalidContent) !== null && _options$errorOnInval !== void 0 ? _options$errorOnInval : editor.options.enableContentCheck }); } catch (e) { emitContentError(e); return false; } let { from: from2, to } = typeof position === "number" ? { from: position, to: position } : { from: position.from, to: position.to }; let isOnlyTextContent = true; let isOnlyBlockContent = true; const nodes = isFragment(content) ? content.content : [content]; nodes.forEach((node) => { node.check(); isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false; isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false; }); if (from2 === to && isOnlyBlockContent) { const { parent } = tr2.doc.resolve(from2); if (parent.isTextblock && !parent.type.spec.code && !parent.childCount) { from2 -= 1; to += 1; } } let newContent; if (isOnlyTextContent) { if (Array.isArray(value)) newContent = value.map((item) => item.text || "").join(""); else if (isProseMirrorContent(value)) newContent = nodes.map((node) => { var _node$text; return (_node$text = node.text) !== null && _node$text !== void 0 ? _node$text : ""; }).join(""); else if (typeof value === "object" && !!value && !!value.text) newContent = value.text; else newContent = value; tr2.insertText(newContent, from2, to); } else { newContent = Fragment.from(nodes); const $from = tr2.doc.resolve(from2); const $fromNode = $from.node(); const fromSelectionAtStart = $from.parentOffset === 0; const isTextSelection2 = $fromNode.isText || $fromNode.isTextblock; const hasContent = $fromNode.content.size > 0; if (fromSelectionAtStart && isTextSelection2 && hasContent && isOnlyBlockContent) from2 = Math.max(0, from2 - 1); tr2.replaceWith(from2, to, nodes); } if (options.updateSelection) selectionToInsertionEnd(tr2, tr2.steps.length - 1, -1); if (options.applyInputRules) tr2.setMeta("applyInputRules", { from: from2, text: newContent }); if (options.applyPasteRules) tr2.setMeta("applyPasteRules", { from: from2, text: newContent }); } return true; }; function defaultBlockAt(match) { for (let i = 0; i < match.edgeCount; i += 1) { const { type } = match.edge(i); if (type.isTextblock && !type.hasRequiredAttrs()) return type; } return null; } const insertDefaultBlock = (options = {}) => ({ tr: tr2, dispatch, editor }) => { const { pos, attrs, content, updateSelection: updateSelection2 = true } = options; let $pos; if (typeof pos === "number") $pos = tr2.doc.resolve(pos); else if (pos) $pos = pos; else $pos = tr2.selection.$from; const defaultType = defaultBlockAt($pos.parent.contentMatchAt($pos.index())); if (!defaultType) return false; const validAttrKeys = Object.keys(defaultType.spec.attrs || {}); const filteredAttrs = attrs ? Object.fromEntries(Object.entries(attrs).filter(([key]) => validAttrKeys.includes(key))) : {}; let node; if (content) { const parsed = createNodeFromContent(content, editor.schema); node = defaultType.createAndFill(filteredAttrs, parsed); } else node = defaultType.createAndFill(filteredAttrs); if (!node) return false; if (dispatch) { tr2.insert($pos.pos, node); if (updateSelection2) selectionToInsertionEnd(tr2, tr2.steps.length - 1, -1); } return true; }; const joinUp$1 = () => ({ state, dispatch }) => { return joinUp(state, dispatch); }; const joinDown$1 = () => ({ state, dispatch }) => { return joinDown(state, dispatch); }; const joinBackward$1 = () => ({ state, dispatch }) => { return joinBackward(state, dispatch); }; const joinForward$1 = () => ({ state, dispatch }) => { return joinForward(state, dispatch); }; const joinItemBackward = () => ({ state, dispatch, tr: tr2 }) => { try { const point = joinPoint(state.doc, state.selection.$from.pos, -1); if (point === null || point === void 0) return false; tr2.join(point, 2); if (dispatch) dispatch(tr2); return true; } catch { return false; } }; const joinItemForward = () => ({ state, dispatch, tr: tr2 }) => { try { const point = joinPoint(state.doc, state.selection.$from.pos, 1); if (point === null || point === void 0) return false; tr2.join(point, 2); if (dispatch) dispatch(tr2); return true; } catch { return false; } }; const joinTextblockBackward$1 = () => ({ state, dispatch }) => { return joinTextblockBackward(state, dispatch); }; const joinTextblockForward$1 = () => ({ state, dispatch }) => { return joinTextblockForward(state, dispatch); }; function isMacOS() { return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false; } function normalizeKeyName(name) { const parts = name.split(/-(?!$)/); let result = parts[parts.length - 1]; if (result === "Space") result = " "; let alt; let ctrl; let shift2; let meta; for (let i = 0; i < parts.length - 1; i += 1) { const mod = parts[i]; if (/^(cmd|meta|m)$/i.test(mod)) meta = true; else if (/^a(lt)?$/i.test(mod)) alt = true; else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; else if (/^s(hift)?$/i.test(mod)) shift2 = true; else if (/^mod$/i.test(mod)) { if (isiOS() || isMacOS()) meta = true; else ctrl = true; } else throw new Error(`Unrecognized modifier name: ${mod}`); } if (alt) result = `Alt-${result}`; if (ctrl) result = `Ctrl-${result}`; if (meta) result = `Meta-${result}`; if (shift2) result = `Shift-${result}`; return result; } const keyboardShortcut = (name) => ({ editor, view, tr: tr2, dispatch }) => { const keys2 = normalizeKeyName(name).split(/-(?!$)/); const key = keys2.find((item) => ![ "Alt", "Ctrl", "Meta", "Shift" ].includes(item)); const event = new KeyboardEvent("keydown", { key: key === "Space" ? " " : key, altKey: keys2.includes("Alt"), ctrlKey: keys2.includes("Ctrl"), metaKey: keys2.includes("Meta"), shiftKey: keys2.includes("Shift"), bubbles: true, cancelable: true }); const capturedTransaction = editor.captureTransaction(() => { view.someProp("handleKeyDown", (f) => f(view, event)); }); capturedTransaction === null || capturedTransaction === void 0 || capturedTransaction.steps.forEach((step) => { const newStep = step.map(tr2.mapping); if (newStep && dispatch) tr2.maybeStep(newStep); }); return true; }; function isNodeActive(state, typeOrName, attributes = {}) { const { from: from2, to, empty: empty2 } = state.selection; const type = typeOrName ? getNodeType(typeOrName, state.schema) : null; const nodeRanges = []; state.doc.nodesBetween(from2, to, (node, pos) => { if (node.isText) return; const relativeFrom = Math.max(from2, pos); const relativeTo = Math.min(to, pos + node.nodeSize); nodeRanges.push({ node, from: relativeFrom, to: relativeTo }); }); const selectionRange = to - from2; const matchedNodeRanges = nodeRanges.filter((nodeRange) => { if (!type) return true; return type.name === nodeRange.node.type.name; }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false })); if (empty2) return !!matchedNodeRanges.length; return matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0) >= selectionRange; } const lift$1 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { if (!isNodeActive(state, getNodeType(typeOrName, state.schema), attributes)) return false; return lift(state, dispatch); }; const liftEmptyBlock$1 = () => ({ state, dispatch }) => { return liftEmptyBlock(state, dispatch); }; const liftListItem$1 = (typeOrName) => ({ state, dispatch }) => { const type = getNodeType(typeOrName, state.schema); return liftListItem(type)(state, dispatch); }; const newlineInCode$1 = () => ({ state, dispatch }) => { return newlineInCode(state, dispatch); }; function getSchemaTypeNameByName(name, schema) { if (schema.nodes[name]) return "node"; if (schema.marks[name]) return "mark"; return null; } function deleteProps(obj, propOrProps) { const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps; return Object.keys(obj).reduce((newObj, prop) => { if (!props.includes(prop)) newObj[prop] = obj[prop]; return newObj; }, {}); } const resetAttributes = (typeOrName, attributes) => ({ tr: tr2, state, dispatch }) => { let nodeType = null; let markType = null; const schemaType = getSchemaTypeNameByName(typeof typeOrName === "string" ? typeOrName : typeOrName.name, state.schema); if (!schemaType) return false; if (schemaType === "node") nodeType = getNodeType(typeOrName, state.schema); if (schemaType === "mark") markType = getMarkType(typeOrName, state.schema); let canReset = false; tr2.selection.ranges.forEach((range) => { state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => { if (nodeType && nodeType === node.type) { canReset = true; if (dispatch) tr2.setNodeMarkup(pos, void 0, deleteProps(node.attrs, attributes)); } if (markType && node.marks.length) node.marks.forEach((mark) => { if (markType === mark.type) { canReset = true; if (dispatch) tr2.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes))); } }); }); }); return canReset; }; const scrollIntoView = () => ({ tr: tr2, dispatch }) => { if (dispatch) tr2.scrollIntoView(); return true; }; const selectAll = () => ({ tr: tr2, dispatch }) => { if (dispatch) { const selection = new AllSelection(tr2.doc); tr2.setSelection(selection); } return true; }; const selectNodeBackward$1 = () => ({ state, dispatch }) => { return selectNodeBackward(state, dispatch); }; const selectNodeForward$1 = () => ({ state, dispatch }) => { return selectNodeForward(state, dispatch); }; const selectParentNode$1 = () => ({ state, dispatch }) => { return selectParentNode(state, dispatch); }; const selectTextblockEnd$1 = () => ({ state, dispatch }) => { return selectTextblockEnd(state, dispatch); }; const selectTextblockStart$1 = () => ({ state, dispatch }) => { return selectTextblockStart(state, dispatch); }; function createDocument(content, schema, parseOptions = {}, options = {}) { return createNodeFromContent(content, schema, { slice: false, parseOptions, errorOnInvalidContent: options.errorOnInvalidContent }); } const setContent$1 = (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) => ({ editor, tr: tr2, dispatch, commands }) => { const { doc: doc2 } = tr2; if (parseOptions.preserveWhitespace !== "full") { const document2 = createDocument(content, editor.schema, parseOptions, { errorOnInvalidContent: errorOnInvalidContent !== null && errorOnInvalidContent !== void 0 ? errorOnInvalidContent : editor.options.enableContentCheck }); if (dispatch) { const nodes = isFragment(document2) ? document2.content : [document2]; tr2.replaceWith(0, doc2.content.size, nodes).setMeta("preventUpdate", !emitUpdate); } return true; } if (dispatch) tr2.setMeta("preventUpdate", !emitUpdate); return commands.insertContentAt({ from: 0, to: doc2.content.size }, content, { parseOptions, errorOnInvalidContent: errorOnInvalidContent !== null && errorOnInvalidContent !== void 0 ? errorOnInvalidContent : editor.options.enableContentCheck }); }; function getMarkAttributes(state, typeOrName) { const type = getMarkType(typeOrName, state.schema); const { from: from2, to, empty: empty2 } = state.selection; const marks = []; if (empty2) { if (state.storedMarks) marks.push(...state.storedMarks); marks.push(...state.selection.$head.marks()); } else state.doc.nodesBetween(from2, to, (node) => { marks.push(...node.marks); }); const mark = marks.find((markItem) => markItem.type.name === type.name); if (!mark) return {}; return { ...mark.attrs }; } function combineTransactionSteps(oldDoc, transactions) { const transform = new Transform(oldDoc); transactions.forEach((transaction) => { transaction.steps.forEach((step) => { transform.step(step); }); }); return transform; } function findChildrenInRange(node, range, predicate) { const nodesWithPos = []; node.nodesBetween(range.from, range.to, (child, pos) => { if (predicate(child)) nodesWithPos.push({ node: child, pos }); }); return nodesWithPos; } function findParentNodeClosestToPos($pos, predicate) { for (let i = $pos.depth; i > 0; i -= 1) { const node = $pos.node(i); if (predicate(node)) return { pos: i > 0 ? $pos.before(i) : 0, start: $pos.start(i), depth: i, node }; } } function findParentNode(predicate) { return (selection) => findParentNodeClosestToPos(selection.$from, predicate); } function getExtensionField(extension, field, context) { if (extension.config[field] === void 0 && extension.parent) return getExtensionField(extension.parent, field, context); if (typeof extension.config[field] === "function") return extension.config[field].bind({ ...context, parent: extension.parent ? getExtensionField(extension.parent, field, context) : null }); return extension.config[field]; } function flattenExtensions(extensions) { return extensions.map((extension) => { const addExtensions = getExtensionField(extension, "addExtensions", { name: extension.name, options: extension.options, storage: extension.storage }); if (addExtensions) return [extension, ...flattenExtensions(addExtensions())]; return extension; }).flat(10); } function isFunction(value) { return typeof value === "function"; } function callOrReturn(value, context = void 0, ...props) { if (isFunction(value)) { if (context) return value.bind(context)(...props); return value(...props); } return value; } function isEmptyObject(value = {}) { return Object.keys(value).length === 0 && value.constructor === Object; } function splitExtensions(extensions) { return { baseExtensions: extensions.filter((extension) => extension.type === "extension"), nodeExtensions: extensions.filter((extension) => extension.type === "node"), markExtensions: extensions.filter((extension) => extension.type === "mark") }; } function getAttributesFromExtensions(extensions) { const extensionAttributes = []; const { nodeExtensions, markExtensions } = splitExtensions(extensions); const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions]; const defaultAttribute = { default: null, validate: void 0, rendered: true, renderHTML: null, parseHTML: null, keepOnSplit: true, isRequired: false }; const nodeExtensionTypes = nodeExtensions.filter((ext) => ext.name !== "text").map((ext) => ext.name); const markExtensionTypes = markExtensions.map((ext) => ext.name); const allExtensionTypes = [...nodeExtensionTypes, ...markExtensionTypes]; extensions.forEach((extension) => { const addGlobalAttributes = getExtensionField(extension, "addGlobalAttributes", { name: extension.name, options: extension.options, storage: extension.storage, extensions: nodeAndMarkExtensions }); if (!addGlobalAttributes) return; addGlobalAttributes().forEach((globalAttribute) => { let resolvedTypes; if (Array.isArray(globalAttribute.types)) resolvedTypes = globalAttribute.types; else if (globalAttribute.types === "*") resolvedTypes = allExtensionTypes; else if (globalAttribute.types === "nodes") resolvedTypes = nodeExtensionTypes; else if (globalAttribute.types === "marks") resolvedTypes = markExtensionTypes; else resolvedTypes = []; resolvedTypes.forEach((type) => { Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => { extensionAttributes.push({ type, name, attribute: { ...defaultAttribute, ...attribute } }); }); }); }); }); nodeAndMarkExtensions.forEach((extension) => { const addAttributes = getExtensionField(extension, "addAttributes", { name: extension.name, options: extension.options, storage: extension.storage }); if (!addAttributes) return; const attributes = addAttributes(); Object.entries(attributes).forEach(([name, attribute]) => { const mergedAttr = { ...defaultAttribute, ...attribute }; if (typeof (mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.default) === "function") mergedAttr.default = mergedAttr.default(); if ((mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.isRequired) && (mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.default) === void 0) delete mergedAttr.default; extensionAttributes.push({ type: extension.name, name, attribute: mergedAttr }); }); }); return extensionAttributes; } function splitStyleDeclarations(styles) { const result = []; let current = ""; let inSingleQuote = false; let inDoubleQuote = false; let parenDepth = 0; const length = styles.length; for (let i = 0; i < length; i += 1) { const char = styles[i]; if (char === "'" && !inDoubleQuote) { inSingleQuote = !inSingleQuote; current += char; continue; } if (char === '"' && !inSingleQuote) { inDoubleQuote = !inDoubleQuote; current += char; continue; } if (!inSingleQuote && !inDoubleQuote) { if (char === "(") { parenDepth += 1; current += char; continue; } if (char === ")" && parenDepth > 0) { parenDepth -= 1; current += char; continue; } if (char === ";" && parenDepth === 0) { result.push(current); current = ""; continue; } } current += char; } if (current) result.push(current); return result; } function parseStyleEntries(styles) { const pairs = []; const declarations = splitStyleDeclarations(styles || ""); const numDeclarations = declarations.length; for (let i = 0; i < numDeclarations; i += 1) { const declaration = declarations[i]; const firstColonIndex = declaration.indexOf(":"); if (firstColonIndex === -1) continue; const property = declaration.slice(0, firstColonIndex).trim(); const value = declaration.slice(firstColonIndex + 1).trim(); if (property && value) pairs.push([property, value]); } return pairs; } function mergeAttributes(...objects) { return objects.filter((item) => !!item).reduce((items, item) => { const mergedAttributes = { ...items }; Object.entries(item).forEach(([key, value]) => { if (key === "__proto__") { Object.defineProperty(mergedAttributes, key, { configurable: true, enumerable: true, value, writable: true }); return; } if (!mergedAttributes[key]) { mergedAttributes[key] = value; return; } if (key === "class") { const valueClasses = value ? String(value).split(" ") : []; const existingClasses = mergedAttributes[key] ? mergedAttributes[key].split(" ") : []; const insertClasses = valueClasses.filter((valueClass) => !existingClasses.includes(valueClass)); mergedAttributes[key] = [...existingClasses, ...insertClasses].join(" "); } else if (key === "style") { const styleMap = new Map([...parseStyleEntries(mergedAttributes[key]), ...parseStyleEntries(value)]); mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join("; "); } else mergedAttributes[key] = value; }); return mergedAttributes; }, {}); } function getRenderedAttributes(nodeOrMark, extensionAttributes) { return extensionAttributes.filter((attribute) => attribute.type === nodeOrMark.type.name).filter((item) => item.attribute.rendered).map((item) => { if (!item.attribute.renderHTML) return { [item.name]: nodeOrMark.attrs[item.name] }; return item.attribute.renderHTML(nodeOrMark.attrs) || {}; }).reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {}); } function fromString(value) { if (typeof value !== "string") return value; if (value.match(/^[+-]?(?:\d*\.)?\d+$/)) return Number(value); if (value === "true") return true; if (value === "false") return false; return value; } function injectExtensionAttributesToParseRule(parseRule, extensionAttributes) { if ("style" in parseRule) return parseRule; return { ...parseRule, getAttrs: (node) => { const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs; if (oldAttributes === false) return false; const newAttributes = extensionAttributes.reduce((items, item) => { const value = item.attribute.parseHTML ? item.attribute.parseHTML(node) : fromString(node.getAttribute(item.name)); if (value === null || value === void 0) return items; return { ...items, [item.name]: value }; }, {}); return { ...oldAttributes, ...newAttributes }; } }; } function cleanUpSchemaItem(data) { return Object.fromEntries(Object.entries(data).filter(([key, value]) => { if (key === "attrs" && isEmptyObject(value)) return false; return value !== null && value !== void 0; })); } function buildAttributeSpec(extensionAttribute) { var _extensionAttribute$a, _extensionAttribute$a2; const spec = {}; if (!(extensionAttribute === null || extensionAttribute === void 0 || (_extensionAttribute$a = extensionAttribute.attribute) === null || _extensionAttribute$a === void 0 ? void 0 : _extensionAttribute$a.isRequired) && "default" in ((extensionAttribute === null || extensionAttribute === void 0 ? void 0 : extensionAttribute.attribute) || {})) spec.default = extensionAttribute.attribute.default; if ((extensionAttribute === null || extensionAttribute === void 0 || (_extensionAttribute$a2 = extensionAttribute.attribute) === null || _extensionAttribute$a2 === void 0 ? void 0 : _extensionAttribute$a2.validate) !== void 0) spec.validate = extensionAttribute.attribute.validate; return [extensionAttribute.name, spec]; } function getSchemaByResolvedExtensions(extensions, editor) { var _nodeExtensions$find; const allAttributes = getAttributesFromExtensions(extensions); const { nodeExtensions, markExtensions } = splitExtensions(extensions); const topNode = (_nodeExtensions$find = nodeExtensions.find((extension) => getExtensionField(extension, "topNode"))) === null || _nodeExtensions$find === void 0 ? void 0 : _nodeExtensions$find.name; const nodes = Object.fromEntries(nodeExtensions.map((extension) => { const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name); const context = { name: extension.name, options: extension.options, storage: extension.storage, editor }; const schema = cleanUpSchemaItem({ ...extensions.reduce((fields, e) => { const extendNodeSchema = getExtensionField(e, "extendNodeSchema", context); return { ...fields, ...extendNodeSchema ? extendNodeSchema(extension) : {} }; }, {}), content: callOrReturn(getExtensionField(extension, "content", context)), marks: callOrReturn(getExtensionField(extension, "marks", context)), group: callOrReturn(getExtensionField(extension, "group", context)), inline: callOrReturn(getExtensionField(extension, "inline", context)), atom: callOrReturn(getExtensionField(extension, "atom", context)), selectable: callOrReturn(getExtensionField(extension, "selectable", context)), draggable: callOrReturn(getExtensionField(extension, "draggable", context)), code: callOrReturn(getExtensionField(extension, "code", context)), whitespace: callOrReturn(getExtensionField(extension, "whitespace", context)), linebreakReplacement: callOrReturn(getExtensionField(extension, "linebreakReplacement", context)), defining: callOrReturn(getExtensionField(extension, "defining", context)), isolating: callOrReturn(getExtensionField(extension, "isolating", context)), attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) }); const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context)); if (parseHTML) schema.parseDOM = parseHTML.map((parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes)); const renderHTML = getExtensionField(extension, "renderHTML", context); if (renderHTML) schema.toDOM = (node) => renderHTML({ node, HTMLAttributes: getRenderedAttributes(node, extensionAttributes) }); const renderText = getExtensionField(extension, "renderText", context); if (renderText) schema.toText = renderText; return [extension.name, schema]; })); const marks = Object.fromEntries(markExtensions.map((extension) => { const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name); const context = { name: extension.name, options: extension.options, storage: extension.storage, editor }; const schema = cleanUpSchemaItem({ ...extensions.reduce((fields, e) => { const extendMarkSchema = getExtensionField(e, "extendMarkSchema", context); return { ...fields, ...extendMarkSchema ? extendMarkSchema(extension) : {} }; }, {}), inclusive: callOrReturn(getExtensionField(extension, "inclusive", context)), excludes: callOrReturn(getExtensionField(extension, "excludes", context)), group: callOrReturn(getExtensionField(extension, "group", context)), spanning: callOrReturn(getExtensionField(extension, "spanning", context)), code: callOrReturn(getExtensionField(extension, "code", context)), attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) }); const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context)); if (parseHTML) schema.parseDOM = parseHTML.map((parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes)); const renderHTML = getExtensionField(extension, "renderHTML", context); if (renderHTML) schema.toDOM = (mark) => renderHTML({ mark, HTMLAttributes: getRenderedAttributes(mark, extensionAttributes) }); return [extension.name, schema]; })); return new Schema({ topNode, nodes, marks }); } function findDuplicates(items) { const filtered = items.filter((el, index) => items.indexOf(el) !== index); return Array.from(new Set(filtered)); } function sortExtensions(extensions) { const defaultPriority = 100; return extensions.sort((a, b) => { const priorityA = getExtensionField(a, "priority") || defaultPriority; const priorityB = getExtensionField(b, "priority") || defaultPriority; if (priorityA > priorityB) return -1; if (priorityA < priorityB) return 1; return 0; }); } function resolveExtensions(extensions) { const resolvedExtensions = sortExtensions(flattenExtensions(extensions)); const duplicatedNames = findDuplicates(resolvedExtensions.map((extension) => extension.name)); if (duplicatedNames.length) console.warn(`[tiptap warn]: Duplicate extension names found: [${duplicatedNames.map((item) => `'${item}'`).join(", ")}]. This can lead to issues.`); return resolvedExtensions; } function getTextBetween(startNode, range, options) { const { from: from2, to } = range; const { blockSeparator = "\n\n", textSerializers = {} } = options || {}; let text = ""; startNode.nodesBetween(from2, to, (node, pos, parent, index) => { if (node.isBlock && pos > from2) text += blockSeparator; const textSerializer = textSerializers === null || textSerializers === void 0 ? void 0 : textSerializers[node.type.name]; if (textSerializer) { if (parent) text += textSerializer({ node, pos, parent, index, range }); return false; } if (node.isText) { var _node$text; text += node === null || node === void 0 || (_node$text = node.text) === null || _node$text === void 0 ? void 0 : _node$text.slice(Math.max(from2, pos) - pos, to - pos); } }); return text; } function getTextSerializersFromSchema(schema) { return Object.fromEntries(Object.entries(schema.nodes).filter(([, node]) => node.spec.toText).map(([name, node]) => [name, node.spec.toText])); } function getNodeAttributes(state, typeOrName) { const type = getNodeType(typeOrName, state.schema); const { from: from2, to } = state.selection; const nodes = []; state.doc.nodesBetween(from2, to, (node2) => { nodes.push(node2); }); const node = nodes.reverse().find((nodeItem) => nodeItem.type.name === type.name); if (!node) return {}; return { ...node.attrs }; } function getAttributes$1(state, typeOrName) { const schemaType = getSchemaTypeNameByName(typeof typeOrName === "string" ? typeOrName : typeOrName.name, state.schema); if (schemaType === "node") return getNodeAttributes(state, typeOrName); if (schemaType === "mark") return getMarkAttributes(state, typeOrName); return {}; } function removeDuplicates(array, by = JSON.stringify) { const seen = {}; return array.filter((item) => { const key = by(item); return Object.prototype.hasOwnProperty.call(seen, key) ? false : seen[key] = true; }); } function simplifyChangedRanges(changes) { const uniqueChanges = removeDuplicates(changes); return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index) => { return !uniqueChanges.filter((_, i) => i !== index).some((otherChange) => { return change.oldRange.from >= otherChange.oldRange.from && change.oldRange.to <= otherChange.oldRange.to && change.newRange.from >= otherChange.newRange.from && change.newRange.to <= otherChange.newRange.to; }); }); } function getChangedRanges(transform) { const { mapping, steps } = transform; const changes = []; mapping.maps.forEach((stepMap, index) => { const ranges = []; if (!stepMap.ranges.length) { const { from: from2, to } = steps[index]; if (from2 === void 0 || to === void 0) return; ranges.push({ from: from2, to }); } else stepMap.forEach((from2, to) => { ranges.push({ from: from2, to }); }); ranges.forEach(({ from: from2, to }) => { const newStart = mapping.slice(index).map(from2, -1); const newEnd = mapping.slice(index).map(to); const oldStart = mapping.invert().map(newStart, -1); const oldEnd = mapping.invert().map(newEnd); changes.push({ oldRange: { from: oldStart, to: oldEnd }, newRange: { from: newStart, to: newEnd } }); }); }); return simplifyChangedRanges(changes); } function getMarksBetween(from2, to, doc2) { const marks = []; if (from2 === to) doc2.resolve(from2).marks().forEach((mark) => { const range = getMarkRange(doc2.resolve(from2), mark.type); if (!range) return; marks.push({ mark, ...range }); }); else doc2.nodesBetween(from2, to, (node, pos) => { if (!node || (node === null || node === void 0 ? void 0 : node.nodeSize) === void 0) return; marks.push(...node.marks.map((mark) => ({ from: pos, to: pos + node.nodeSize, mark }))); }); return marks; } const getNodeAtPosition = (state, typeOrName, pos, maxDepth = 20) => { const $pos = state.doc.resolve(pos); let currentDepth = maxDepth; let node = null; while (currentDepth > 0 && node === null) { const currentNode = $pos.node(currentDepth); if ((currentNode === null || currentNode === void 0 ? void 0 : currentNode.type.name) === typeOrName) node = currentNode; else currentDepth -= 1; } return [node, currentDepth]; }; const getPreviousBlockSibling = ($pos) => { const parentDepth = $pos.depth - 1; if (parentDepth < 0) return null; const index = $pos.index(parentDepth); if (index === 0) return null; return $pos.node(parentDepth).child(index - 1); }; function getSplittedAttributes(extensionAttributes, typeName, attributes) { return Object.fromEntries(Object.entries(attributes).filter(([name]) => { const extensionAttribute = extensionAttributes.find((item) => { return item.type === typeName && item.name === name; }); if (!extensionAttribute) return false; return extensionAttribute.attribute.keepOnSplit; })); } function isMarkActive(state, typeOrName, attributes = {}) { const { empty: empty2, ranges } = state.selection; const type = typeOrName ? getMarkType(typeOrName, state.schema) : null; if (empty2) return !!(state.storedMarks || state.selection.$from.marks()).filter((mark) => { if (!type) return true; return type.name === mark.type.name; }).find((mark) => objectIncludes(mark.attrs, attributes, { strict: false })); let selectionRange = 0; const markRanges = []; ranges.forEach(({ $from, $to }) => { const from2 = $from.pos; const to = $to.pos; state.doc.nodesBetween(from2, to, (node, pos) => { if (type && node.inlineContent && !node.type.allowsMarkType(type)) return false; if (!node.isText && !node.marks.length) return; const relativeFrom = Math.max(from2, pos); const relativeTo = Math.min(to, pos + node.nodeSize); const range = relativeTo - relativeFrom; selectionRange += range; markRanges.push(...node.marks.map((mark) => ({ mark, from: relativeFrom, to: relativeTo }))); }); }); if (selectionRange === 0) return false; const matchedRange = markRanges.filter((markRange) => { if (!type) return true; return type.name === markRange.mark.type.name; }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0); const excludedRange = markRanges.filter((markRange) => { if (!type) return true; return markRange.mark.type !== type && markRange.mark.type.excludes(type); }).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0); return (matchedRange > 0 ? matchedRange + excludedRange : matchedRange) >= selectionRange; } const isAtEndOfNode = (state, nodeType) => { const { $from, $to, $anchor } = state.selection; if (nodeType) { const parentNode = findParentNode((node) => node.type.name === nodeType)(state.selection); if (!parentNode) return false; const $parentPos = state.doc.resolve(parentNode.pos + 1); if ($anchor.pos + 1 === $parentPos.end()) return true; return false; } if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) return false; return true; }; const isAtStartOfNode = (state) => { const { $from, $to } = state.selection; if ($from.parentOffset > 0 || $from.pos !== $to.pos) return false; return true; }; function isList(name, extensions) { const { nodeExtensions } = splitExtensions(extensions); const extension = nodeExtensions.find((item) => item.name === name); if (!extension) return false; const group = callOrReturn(getExtensionField(extension, "group", { name: extension.name, options: extension.options, storage: extension.storage })); if (typeof group !== "string") return false; return group.split(" ").includes("list"); } function isNodeEmpty(node, { checkChildren = true, ignoreWhitespace = false } = {}) { if (ignoreWhitespace) { if (node.type.name === "hardBreak") return true; if (node.isText) { var _node$text; return !/\S/.test((_node$text = node.text) !== null && _node$text !== void 0 ? _node$text : ""); } } if (node.isText) return !node.text; if (node.isAtom || node.isLeaf) return false; if (node.content.childCount === 0) return true; if (checkChildren) { let isContentEmpty = true; node.content.forEach((childNode) => { if (isContentEmpty === false) return; if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) isContentEmpty = false; }); return isContentEmpty; } return false; } function isNodeSelection(value) { return value instanceof NodeSelection; } function canSetMark(state, tr2, newMarkType) { const { selection } = tr2; let cursor = null; if (isTextSelection(selection)) cursor = selection.$cursor; if (cursor) { var _state$storedMarks; const currentMarks = (_state$storedMarks = state.storedMarks) !== null && _state$storedMarks !== void 0 ? _state$storedMarks : cursor.marks(); return cursor.parent.type.allowsMarkType(newMarkType) && (!!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark) => mark.type.excludes(newMarkType))); } const { ranges } = selection; return ranges.some(({ $from, $to }) => { let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false; state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => { if (someNodeSupportsMark) return false; if (node.isInline) { const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType); const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks) || !node.marks.some((otherMark) => otherMark.type.excludes(newMarkType)); someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType; } return !someNodeSupportsMark; }); return someNodeSupportsMark; }); } const setMark = (typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => { const { selection } = tr2; const { empty: empty2, ranges } = selection; const type = getMarkType(typeOrName, state.schema); if (dispatch) { if (empty2) { const oldAttributes = getMarkAttributes(state, type); tr2.addStoredMark(type.create({ ...oldAttributes, ...attributes })); } else ranges.forEach((range) => { const from2 = range.$from.pos; const to = range.$to.pos; state.doc.nodesBetween(from2, to, (node, pos) => { const trimmedFrom = Math.max(pos, from2); const trimmedTo = Math.min(pos + node.nodeSize, to); if (node.marks.find((mark) => mark.type === type)) node.marks.forEach((mark) => { if (type === mark.type) tr2.addMark(trimmedFrom, trimmedTo, type.create({ ...mark.attrs, ...attributes })); }); else tr2.addMark(trimmedFrom, trimmedTo, type.create(attributes)); }); }); } return canSetMark(state, tr2, type); }; const setMeta = (key, value) => ({ tr: tr2 }) => { tr2.setMeta(key, value); return true; }; const setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => { const type = getNodeType(typeOrName, state.schema); let attributesToCopy; if (state.selection.$anchor.sameParent(state.selection.$head)) attributesToCopy = state.selection.$anchor.parent.attrs; if (!type.isTextblock) { console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'); return false; } return chain().command(({ commands }) => { if (setBlockType(type, { ...attributesToCopy, ...attributes })(state)) return true; return commands.clearNodes(); }).command(({ state: updatedState }) => { return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch); }).run(); }; const setNodeSelection = (position) => ({ tr: tr2, dispatch }) => { if (dispatch) { const { doc: doc2 } = tr2; const from2 = minMax(position, 0, doc2.content.size); const selection = NodeSelection.create(doc2, from2); tr2.setSelection(selection); } return true; }; const setTextDirection = (direction, position) => ({ tr: tr2, state, dispatch }) => { const { selection } = state; let from2; let to; if (typeof position === "number") { from2 = position; to = position; } else if (position && "from" in position && "to" in position) { from2 = position.from; to = position.to; } else { from2 = selection.from; to = selection.to; } if (dispatch) tr2.doc.nodesBetween(from2, to, (node, pos) => { if (node.isText) return; tr2.setNodeMarkup(pos, void 0, { ...node.attrs, dir: direction }); }); return true; }; const setTextSelection = (position) => ({ tr: tr2, dispatch }) => { if (dispatch) { const { doc: doc2 } = tr2; const { from: from2, to } = typeof position === "number" ? { from: position, to: position } : position; const minPos = TextSelection.atStart(doc2).from; const maxPos = TextSelection.atEnd(doc2).to; const resolvedFrom = minMax(from2, minPos, maxPos); const resolvedEnd = minMax(to, minPos, maxPos); const selection = TextSelection.create(doc2, resolvedFrom, resolvedEnd); tr2.setSelection(selection); } return true; }; const sinkListItem$1 = (typeOrName) => ({ state, dispatch }) => { const type = getNodeType(typeOrName, state.schema); return sinkListItem(type)(state, dispatch); }; function ensureMarks(state, splittableMarks) { const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks(); if (marks) { const filteredMarks = marks.filter((mark) => splittableMarks === null || splittableMarks === void 0 ? void 0 : splittableMarks.includes(mark.type.name)); state.tr.ensureMarks(filteredMarks); } } const splitBlock = ({ keepMarks = true } = {}) => ({ tr: tr2, state, dispatch, editor }) => { const { selection, doc: doc2 } = tr2; const { $from, $to } = selection; const extensionAttributes = editor.extensionManager.attributes; const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs); if (selection instanceof NodeSelection && selection.node.isBlock) { if (!$from.parentOffset || !canSplit(doc2, $from.pos)) return false; if (dispatch) { if (keepMarks) ensureMarks(state, editor.extensionManager.splittableMarks); tr2.split($from.pos).scrollIntoView(); } return true; } if (!$from.parent.isBlock) return false; const atEnd = $to.parentOffset === $to.parent.content.size; const deflt = $from.depth === 0 ? void 0 : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1))); let types = atEnd && deflt ? [{ type: deflt, attrs: newAttributes }] : void 0; let can = canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, types); if (!types && !can && canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) { can = true; types = deflt ? [{ type: deflt, attrs: newAttributes }] : void 0; } if (dispatch) { if (can) { if (selection instanceof TextSelection) tr2.deleteSelection(); tr2.split(tr2.mapping.map($from.pos), 1, types); if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) { const first2 = tr2.mapping.map($from.before()); const $first = tr2.doc.resolve(first2); if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) tr2.setNodeMarkup(tr2.mapping.map($from.before()), deflt); } } if (keepMarks) ensureMarks(state, editor.extensionManager.splittableMarks); tr2.scrollIntoView(); } return can; }; const splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr: tr2, state, dispatch, editor }) => { const type = getNodeType(typeOrName, state.schema); const { $from, $to } = state.selection; const node = state.selection.node; if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) return false; const grandParent = $from.node(-1); if (grandParent.type !== type) return false; const extensionAttributes = editor.extensionManager.attributes; if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) { if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) return false; if (dispatch) { var _type$contentMatch$de; let wrap2 = Fragment.empty; const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3; for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) wrap2 = Fragment.from($from.node(d).copy(wrap2)); const depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3; const newNextTypeAttributes2 = { ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs), ...overrideAttrs }; const nextType2 = ((_type$contentMatch$de = type.contentMatch.defaultType) === null || _type$contentMatch$de === void 0 ? void 0 : _type$contentMatch$de.createAndFill(newNextTypeAttributes2)) || void 0; wrap2 = wrap2.append(Fragment.from(type.createAndFill(null, nextType2) || void 0)); const start = $from.before($from.depth - (depthBefore - 1)); tr2.replace(start, $from.after(-depthAfter), new Slice(wrap2, 4 - depthBefore, 0)); let sel = -1; tr2.doc.nodesBetween(start, tr2.doc.content.size, (n, pos) => { if (sel > -1) return false; if (n.isTextblock && n.content.size === 0) sel = pos + 1; }); if (sel > -1) tr2.setSelection(TextSelection.near(tr2.doc.resolve(sel))); tr2.scrollIntoView(); } return true; } const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null; const newTypeAttributes = { ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs), ...overrideAttrs }; const newNextTypeAttributes = { ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs), ...overrideAttrs }; tr2.delete($from.pos, $to.pos); const types = nextType ? [{ type, attrs: newTypeAttributes }, { type: nextType, attrs: newNextTypeAttributes }] : [{ type, attrs: newTypeAttributes }]; if (!canSplit(tr2.doc, $from.pos, 2)) return false; if (dispatch) { const { selection, storedMarks } = state; const { splittableMarks } = editor.extensionManager; const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); tr2.split($from.pos, 2, types).scrollIntoView(); if (!marks || !dispatch) return true; const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); tr2.ensureMarks(filteredMarks); } return true; }; function normalizeListType(type) { return !type || type === "1" ? null : type; } function areListTypesCompatible(typeA, typeB) { return normalizeListType(typeA) === normalizeListType(typeB); } const joinListBackwards = (tr2, listType) => { const list = findParentNode((node) => node.type === listType)(tr2.selection); if (!list) return true; const before = tr2.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth); if (before === void 0) return true; const nodeBefore = tr2.doc.nodeAt(before); if (!(list.node.type === (nodeBefore === null || nodeBefore === void 0 ? void 0 : nodeBefore.type) && canJoin(tr2.doc, list.pos))) return true; if (!areListTypesCompatible(list.node.attrs.type, nodeBefore === null || nodeBefore === void 0 ? void 0 : nodeBefore.attrs.type)) return true; tr2.join(list.pos); return true; }; const joinListForwards = (tr2, listType) => { const list = findParentNode((node) => node.type === listType)(tr2.selection); if (!list) return true; const after = tr2.doc.resolve(list.start).after(list.depth); if (after === void 0) return true; const nodeAfter = tr2.doc.nodeAt(after); if (!(list.node.type === (nodeAfter === null || nodeAfter === void 0 ? void 0 : nodeAfter.type) && canJoin(tr2.doc, after))) return true; if (!areListTypesCompatible(list.node.attrs.type, nodeAfter === null || nodeAfter === void 0 ? void 0 : nodeAfter.attrs.type)) return true; tr2.join(after); return true; }; function createInnerSelectionForWholeDocList(tr2) { const doc2 = tr2.doc; const list = doc2.firstChild; if (!list) return null; const $start = doc2.resolve(1); const $end = doc2.resolve(list.nodeSize - 1); return TextSelection.between($start, $end); } const toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr: tr2, state, dispatch, chain, commands, can }) => { const { extensions, splittableMarks } = editor.extensionManager; const listType = getNodeType(listTypeOrName, state.schema); const itemType = getNodeType(itemTypeOrName, state.schema); const { selection, storedMarks } = state; const { $from, $to } = selection; const range = $from.blockRange($to); const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); if (!range) return false; const parentList = findParentNode((node) => isList(node.type.name, extensions))(selection); const isAllSelection = selection.from === 0 && selection.to === state.doc.content.size; const topLevelNodes = state.doc.content.content; const soleTopLevelNode = topLevelNodes.length === 1 ? topLevelNodes[0] : null; const allSelectionList = isAllSelection && soleTopLevelNode && isList(soleTopLevelNode.type.name, extensions) ? { node: soleTopLevelNode, pos: 0 } : null; const currentList = parentList !== null && parentList !== void 0 ? parentList : allSelectionList; const isInsideExistingList = !!parentList && range.depth >= 1 && range.depth - parentList.depth <= 1; const hasWholeDocSelectedList = !!allSelectionList; if ((isInsideExistingList || hasWholeDocSelectedList) && currentList) { if (currentList.node.type === listType) { if (isAllSelection && hasWholeDocSelectedList) return chain().command(({ tr: trx, dispatch: disp }) => { const nextSelection = createInnerSelectionForWholeDocList(trx); if (!nextSelection) return false; trx.setSelection(nextSelection); if (disp) disp(trx); return true; }).liftListItem(itemType).run(); return commands.liftListItem(itemType); } if (isList(currentList.node.type.name, extensions) && listType.validContent(currentList.node.content)) return chain().command(() => { tr2.setNodeMarkup(currentList.pos, listType); return true; }).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run(); } if (!keepMarks || !marks || !dispatch) return chain().command(() => { if (can().wrapInList(listType, attributes)) return true; return commands.clearNodes(); }).wrapInList(listType, attributes).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run(); return chain().command(() => { const canWrapInList = can().wrapInList(listType, attributes); const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); tr2.ensureMarks(filteredMarks); if (canWrapInList) return true; return commands.clearNodes(); }).wrapInList(listType, attributes).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run(); }; const toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => { const { extendEmptyMarkRange = false } = options; const type = getMarkType(typeOrName, state.schema); if (isMarkActive(state, type, attributes)) return commands.unsetMark(type, { extendEmptyMarkRange }); return commands.setMark(type, attributes); }; const toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => { const type = getNodeType(typeOrName, state.schema); const toggleType = getNodeType(toggleTypeOrName, state.schema); const isActive = isNodeActive(state, type, attributes); let attributesToCopy; if (state.selection.$anchor.sameParent(state.selection.$head)) attributesToCopy = state.selection.$anchor.parent.attrs; if (isActive) return commands.setNode(toggleType, attributesToCopy); return commands.setNode(type, { ...attributesToCopy, ...attributes }); }; const toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => { const type = getNodeType(typeOrName, state.schema); if (isNodeActive(state, type, attributes)) return commands.lift(type); return commands.wrapIn(type, attributes); }; const undoInputRule = () => ({ state, dispatch }) => { const plugins = state.plugins; for (let i = 0; i < plugins.length; i += 1) { const plugin = plugins[i]; let undoable; if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) { if (dispatch) { const tr2 = state.tr; const toUndo = undoable.transform; for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) tr2.step(toUndo.steps[j].invert(toUndo.docs[j])); if (undoable.text) { const marks = tr2.doc.resolve(undoable.from).marks(); tr2.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks)); } else tr2.delete(undoable.from, undoable.to); } return true; } } return false; }; const unsetAllMarks = (options = {}) => ({ tr: tr2, dispatch, editor }) => { const { ignoreClearable = false } = options; const { selection } = tr2; const { empty: empty2, ranges } = selection; if (empty2) return true; const { nonClearableMarks } = editor.extensionManager; if (dispatch) { const clearableMarkTypes = Object.values(editor.schema.marks).filter((markType) => ignoreClearable || !nonClearableMarks.includes(markType.name)); ranges.forEach((range) => { for (const markType of clearableMarkTypes) tr2.removeMark(range.$from.pos, range.$to.pos, markType); }); } return true; }; const unsetMark = (typeOrName, options = {}) => ({ tr: tr2, state, dispatch }) => { const { extendEmptyMarkRange = false } = options; const { selection } = tr2; const type = getMarkType(typeOrName, state.schema); const { $from, empty: empty2, ranges } = selection; if (!dispatch) return true; if (empty2 && extendEmptyMarkRange) { var _$from$marks$find; let { from: from2, to } = selection; const range = getMarkRange($from, type, (_$from$marks$find = $from.marks().find((mark) => mark.type === type)) === null || _$from$marks$find === void 0 ? void 0 : _$from$marks$find.attrs); if (range) { from2 = range.from; to = range.to; } tr2.removeMark(from2, to, type); } else ranges.forEach((range) => { tr2.removeMark(range.$from.pos, range.$to.pos, type); }); tr2.removeStoredMark(type); return true; }; const unsetTextDirection = (position) => ({ tr: tr2, state, dispatch }) => { const { selection } = state; let from2; let to; if (typeof position === "number") { from2 = position; to = position; } else if (position && "from" in position && "to" in position) { from2 = position.from; to = position.to; } else { from2 = selection.from; to = selection.to; } if (dispatch) tr2.doc.nodesBetween(from2, to, (node, pos) => { if (node.isText) return; const newAttrs = { ...node.attrs }; delete newAttrs.dir; tr2.setNodeMarkup(pos, void 0, newAttrs); }); return true; }; const updateAttributes = (typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => { let nodeType = null; let markType = null; const schemaType = getSchemaTypeNameByName(typeof typeOrName === "string" ? typeOrName : typeOrName.name, state.schema); if (!schemaType) return false; if (schemaType === "node") nodeType = getNodeType(typeOrName, state.schema); if (schemaType === "mark") markType = getMarkType(typeOrName, state.schema); let canUpdate = false; tr2.selection.ranges.forEach((range) => { const from2 = range.$from.pos; const to = range.$to.pos; let lastPos; let lastNode; let trimmedFrom; let trimmedTo; if (tr2.selection.empty) state.doc.nodesBetween(from2, to, (node, pos) => { if (nodeType && nodeType === node.type) { canUpdate = true; trimmedFrom = Math.max(pos, from2); trimmedTo = Math.min(pos + node.nodeSize, to); lastPos = pos; lastNode = node; } }); else state.doc.nodesBetween(from2, to, (node, pos) => { if (pos < from2 && nodeType && nodeType === node.type) { canUpdate = true; trimmedFrom = Math.max(pos, from2); trimmedTo = Math.min(pos + node.nodeSize, to); lastPos = pos; lastNode = node; } if (pos >= from2 && pos <= to) { if (nodeType && nodeType === node.type) { canUpdate = true; if (dispatch) tr2.setNodeMarkup(pos, void 0, { ...node.attrs, ...attributes }); } if (markType && node.marks.length) node.marks.forEach((mark) => { if (markType === mark.type) { canUpdate = true; if (dispatch) { const trimmedFrom2 = Math.max(pos, from2); const trimmedTo2 = Math.min(pos + node.nodeSize, to); tr2.addMark(trimmedFrom2, trimmedTo2, markType.create({ ...mark.attrs, ...attributes })); } } }); } }); if (lastNode) { if (lastPos !== void 0 && dispatch) tr2.setNodeMarkup(lastPos, void 0, { ...lastNode.attrs, ...attributes }); if (markType && lastNode.marks.length) lastNode.marks.forEach((mark) => { if (markType === mark.type && dispatch) tr2.addMark(trimmedFrom, trimmedTo, markType.create({ ...mark.attrs, ...attributes })); }); } }); return canUpdate; }; const DECORATION_MANAGER_PLUGIN_KEY = new PluginKey("__tiptap_decorations__"); const updateDecorations = (extensionName) => ({ tr: tr2, dispatch }) => { if (dispatch) tr2.setMeta(DECORATION_MANAGER_PLUGIN_KEY, { type: "force", name: extensionName }); return true; }; const wrapIn$1 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { const type = getNodeType(typeOrName, state.schema); return wrapIn(type, attributes)(state, dispatch); }; const wrapInList$1 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { const type = getNodeType(typeOrName, state.schema); return wrapInList(type, attributes)(state, dispatch); }; var commands_exports = /* @__PURE__ */ __exportAll({ blur: () => blur, clearContent: () => clearContent, clearNodes: () => clearNodes, command: () => command, createParagraphNear: () => createParagraphNear$1, cut: () => cut, deleteCurrentNode: () => deleteCurrentNode, deleteNode: () => deleteNode, deleteRange: () => deleteRange, deleteSelection: () => deleteSelection, enter: () => enter, exitCode: () => exitCode$1, extendMarkRange: () => extendMarkRange, first: () => first, focus: () => focus, forEach: () => forEach, insertContent: () => insertContent, insertContentAt: () => insertContentAt, insertDefaultBlock: () => insertDefaultBlock, joinBackward: () => joinBackward$1, joinDown: () => joinDown$1, joinForward: () => joinForward$1, joinItemBackward: () => joinItemBackward, joinItemForward: () => joinItemForward, joinTextblockBackward: () => joinTextblockBackward$1, joinTextblockForward: () => joinTextblockForward$1, joinUp: () => joinUp$1, keyboardShortcut: () => keyboardShortcut, lift: () => lift$1, liftEmptyBlock: () => liftEmptyBlock$1, liftListItem: () => liftListItem$1, newlineInCode: () => newlineInCode$1, resetAttributes: () => resetAttributes, scrollIntoView: () => scrollIntoView, selectAll: () => selectAll, selectNodeBackward: () => selectNodeBackward$1, selectNodeForward: () => selectNodeForward$1, selectParentNode: () => selectParentNode$1, selectTextblockEnd: () => selectTextblockEnd$1, selectTextblockStart: () => selectTextblockStart$1, setContent: () => setContent$1, setMark: () => setMark, setMeta: () => setMeta, setNode: () => setNode, setNodeSelection: () => setNodeSelection, setTextDirection: () => setTextDirection, setTextSelection: () => setTextSelection, sinkListItem: () => sinkListItem$1, splitBlock: () => splitBlock, splitListItem: () => splitListItem, toggleList: () => toggleList, toggleMark: () => toggleMark, toggleNode: () => toggleNode, toggleWrap: () => toggleWrap, undoInputRule: () => undoInputRule, unsetAllMarks: () => unsetAllMarks, unsetMark: () => unsetMark, unsetTextDirection: () => unsetTextDirection, updateAttributes: () => updateAttributes, updateDecorations: () => updateDecorations, wrapIn: () => wrapIn$1, wrapInList: () => wrapInList$1 }); typeof process !== "undefined" && process.env.NODE_ENV !== "production"; function canInsertNode(state, nodeType) { const { selection } = state; const { $from } = selection; if (selection instanceof NodeSelection) { const index = $from.index(); return $from.parent.canReplaceWith(index, index + 1, nodeType); } let depth = $from.depth; while (depth >= 0) { const index = $from.index(depth); if ($from.node(depth).contentMatchAt(index).matchType(nodeType)) return true; depth -= 1; } return false; } function getType(value) { return Object.prototype.toString.call(value).slice(8, -1); } function isPlainObject(value) { if (getType(value) !== "Object") return false; return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype; } function parseIndentedBlocks(src, config, lexer) { const lines = src.split("\n"); const items = []; let totalRaw = ""; let i = 0; const baseIndentSize = config.baseIndentSize || 2; while (i < lines.length) { const currentLine = lines[i]; const itemMatch = currentLine.match(config.itemPattern); if (!itemMatch) { if (items.length > 0) break; else if (currentLine.trim() === "") { i += 1; totalRaw = `${totalRaw}${currentLine} `; continue; } else return; } const itemData = config.extractItemData(itemMatch); const { indentLevel, mainContent } = itemData; totalRaw = `${totalRaw}${currentLine} `; const itemContent = [mainContent]; i += 1; while (i < lines.length) { var _nextLine$match; const nextLine = lines[i]; if (nextLine.trim() === "") { var _nextNonEmpty$match; const nextNonEmptyIndex = lines.slice(i + 1).findIndex((l) => l.trim() !== ""); if (nextNonEmptyIndex === -1) break; if ((((_nextNonEmpty$match = lines[i + 1 + nextNonEmptyIndex].match(/^(\s*)/)) === null || _nextNonEmpty$match === void 0 || (_nextNonEmpty$match = _nextNonEmpty$match[1]) === null || _nextNonEmpty$match === void 0 ? void 0 : _nextNonEmpty$match.length) || 0) > indentLevel) { itemContent.push(nextLine); totalRaw = `${totalRaw}${nextLine} `; i += 1; continue; } else break; } if ((((_nextLine$match = nextLine.match(/^(\s*)/)) === null || _nextLine$match === void 0 || (_nextLine$match = _nextLine$match[1]) === null || _nextLine$match === void 0 ? void 0 : _nextLine$match.length) || 0) > indentLevel) { itemContent.push(nextLine); totalRaw = `${totalRaw}${nextLine} `; i += 1; } else break; } let nestedTokens; const nestedContent = itemContent.slice(1); if (nestedContent.length > 0) { const dedentedNested = nestedContent.map((nestedLine) => nestedLine.slice(indentLevel + baseIndentSize)).join("\n"); if (dedentedNested.trim()) { if (config.customNestedParser) nestedTokens = config.customNestedParser(dedentedNested); else nestedTokens = lexer.blockTokens(dedentedNested); } } const token = config.createToken(itemData, nestedTokens); items.push(token); } if (items.length === 0) return; return { items, raw: totalRaw }; } const TAB_STOP = 4; function columnWidth(text) { let width = 0; for (const character of text) width = character === " " ? width + TAB_STOP - width % TAB_STOP : width + 1; return width; } function renderNestedMarkdownContent(node, h2, prefixOrGenerator, ctx, options) { if (!node || !Array.isArray(node.content)) return ""; const prefix = typeof prefixOrGenerator === "function" ? prefixOrGenerator(ctx) : prefixOrGenerator; const [content, ...children] = node.content; let output = `${prefix}${h2.renderChildren([content])}`; if (children && children.length > 0) children.forEach((child, index) => { var _h$renderChild, _h$renderChild2; const childContent = (_h$renderChild = (_h$renderChild2 = h2.renderChild) === null || _h$renderChild2 === void 0 ? void 0 : _h$renderChild2.call(h2, child, index + 1)) !== null && _h$renderChild !== void 0 ? _h$renderChild : h2.renderChildren([child]); if (childContent !== void 0 && childContent !== null) { const indentLine = (line) => { if (!(options === null || options === void 0 ? void 0 : options.alignNestedToPrefix)) return h2.indent(line); const configured = h2.indent(""); const prefixWidth = columnWidth(prefix); return (columnWidth(configured) >= prefixWidth ? configured : " ".repeat(prefixWidth)) + line; }; const indentedChild = childContent.split("\n").map((line) => line ? indentLine(line) : indentLine("")).join("\n"); output += child.type === "paragraph" ? ` ${indentedChild}` : ` ${indentedChild}`; } }); return output; } function mergeDeep(target, source) { const output = { ...target }; if (isPlainObject(target) && isPlainObject(source)) Object.keys(source).forEach((key) => { if (isPlainObject(source[key]) && isPlainObject(target[key])) output[key] = mergeDeep(target[key], source[key]); else output[key] = source[key]; }); return output; } var InputRule = class { constructor(config) { var _config$undoable; this.find = config.find; this.handler = config.handler; this.undoable = (_config$undoable = config.undoable) !== null && _config$undoable !== void 0 ? _config$undoable : true; } }; var Extendable = class { constructor(config = {}) { this.type = "extendable"; this.parent = null; this.child = null; this.name = ""; this.config = { name: this.name }; this.config = { ...this.config, ...config }; this.name = this.config.name; } get options() { return { ...callOrReturn(getExtensionField(this, "addOptions", { name: this.name })) }; } get storage() { return { ...callOrReturn(getExtensionField(this, "addStorage", { name: this.name, options: this.options })) }; } configure(options = {}) { const extension = this.extend({ ...this.config, addOptions: () => { return mergeDeep(this.options, options); } }); extension.name = this.name; extension.parent = this.parent; this.child = null; return extension; } extend(extendedConfig = {}) { const extension = new this.constructor({ ...this.config, ...extendedConfig }); extension.parent = this; this.child = extension; extension.name = "name" in extendedConfig ? extendedConfig.name : extension.parent.name; return extension; } }; var Mark2 = class Mark3 extends Extendable { constructor(..._args) { super(..._args); this.type = "mark"; } /** * Create a new Mark instance * @param config - Mark configuration object or a function that returns a configuration object */ static create(config = {}) { const resolvedConfig = typeof config === "function" ? config() : config; return new Mark3(resolvedConfig); } static handleExit({ editor, mark }) { const { tr: tr2 } = editor.state; const currentPos = editor.state.selection.$from; if (currentPos.pos === currentPos.end()) { const currentMarks = currentPos.marks(); if (!!!currentMarks.find((m) => (m === null || m === void 0 ? void 0 : m.type.name) === mark.name)) return false; const removeMark2 = currentMarks.find((m) => (m === null || m === void 0 ? void 0 : m.type.name) === mark.name); if (removeMark2) tr2.removeStoredMark(removeMark2); tr2.insertText(" ", currentPos.pos); editor.view.dispatch(tr2); return true; } return false; } configure(options) { return super.configure(options); } extend(extendedConfig) { const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; return super.extend(resolvedConfig); } }; var PasteRule = class { constructor(config) { this.find = config.find; this.handler = config.handler; } }; var Extension = class Extension2 extends Extendable { constructor(..._args) { super(..._args); this.type = "extension"; } /** * Create a new Extension instance * @param config - Extension configuration object or a function that returns a configuration object */ static create(config = {}) { const resolvedConfig = typeof config === "function" ? config() : config; return new Extension2(resolvedConfig); } configure(options) { return super.configure(options); } extend(extendedConfig) { const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; return super.extend(resolvedConfig); } }; const ClipboardTextSerializer = Extension.create({ name: "clipboardTextSerializer", addOptions() { return { blockSeparator: void 0 }; }, addProseMirrorPlugins() { return [new Plugin({ key: new PluginKey("clipboardTextSerializer"), props: { clipboardTextSerializer: () => { const { editor } = this; const { state, schema } = editor; const { doc: doc2, selection } = state; const textSerializers = getTextSerializersFromSchema(schema); const { blockSeparator } = this.options; const options = { ...blockSeparator !== void 0 ? { blockSeparator } : {}, textSerializers }; return [...selection.ranges].sort((a, b) => a.$from.pos - b.$from.pos).map(({ $from, $to }) => getTextBetween(doc2, { from: $from.pos, to: $to.pos }, options)).join(blockSeparator !== null && blockSeparator !== void 0 ? blockSeparator : "\n\n"); } } })]; } }); const Commands = Extension.create({ name: "commands", addCommands() { return { ...commands_exports }; } }); const Delete = Extension.create({ name: "delete", onUpdate({ transaction, appendedTransactions }) { var _this$editor$options$4, _this$editor$options$5; const callback = () => { var _this$editor$options$, _this$editor$options$2, _this$editor$options$3; if ((_this$editor$options$ = (_this$editor$options$2 = this.editor.options.coreExtensionOptions) === null || _this$editor$options$2 === void 0 || (_this$editor$options$2 = _this$editor$options$2.delete) === null || _this$editor$options$2 === void 0 || (_this$editor$options$3 = _this$editor$options$2.filterTransaction) === null || _this$editor$options$3 === void 0 ? void 0 : _this$editor$options$3.call(_this$editor$options$2, transaction)) !== null && _this$editor$options$ !== void 0 ? _this$editor$options$ : transaction.getMeta("y-sync$")) return; const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions]); getChangedRanges(nextTransaction).forEach((change) => { if (nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter && nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore) nextTransaction.before.nodesBetween(change.oldRange.from, change.oldRange.to, (node, from2) => { const to = from2 + node.nodeSize - 2; const isFullyWithinRange = change.oldRange.from <= from2 && to <= change.oldRange.to; this.editor.emit("delete", { type: "node", node, from: from2, to, newFrom: nextTransaction.mapping.map(from2), newTo: nextTransaction.mapping.map(to), deletedRange: change.oldRange, newRange: change.newRange, partial: !isFullyWithinRange, editor: this.editor, transaction, combinedTransform: nextTransaction }); }); }); const mapping = nextTransaction.mapping; nextTransaction.steps.forEach((step, index) => { if (step instanceof RemoveMarkStep) { var _nextTransaction$doc$, _nextTransaction$doc$2; const newStart = mapping.slice(index).map(step.from, -1); const newEnd = mapping.slice(index).map(step.to); const oldStart = mapping.invert().map(newStart, -1); const oldEnd = mapping.invert().map(newEnd); const foundBeforeMark = newStart > 0 ? (_nextTransaction$doc$ = nextTransaction.doc.nodeAt(newStart - 1)) === null || _nextTransaction$doc$ === void 0 ? void 0 : _nextTransaction$doc$.marks.some((mark) => mark.eq(step.mark)) : false; const foundAfterMark = (_nextTransaction$doc$2 = nextTransaction.doc.nodeAt(newEnd)) === null || _nextTransaction$doc$2 === void 0 ? void 0 : _nextTransaction$doc$2.marks.some((mark) => mark.eq(step.mark)); this.editor.emit("delete", { type: "mark", mark: step.mark, from: step.from, to: step.to, deletedRange: { from: oldStart, to: oldEnd }, newRange: { from: newStart, to: newEnd }, partial: Boolean(foundAfterMark || foundBeforeMark), editor: this.editor, transaction, combinedTransform: nextTransaction }); } }); }; if ((_this$editor$options$4 = (_this$editor$options$5 = this.editor.options.coreExtensionOptions) === null || _this$editor$options$5 === void 0 || (_this$editor$options$5 = _this$editor$options$5.delete) === null || _this$editor$options$5 === void 0 ? void 0 : _this$editor$options$5.async) !== null && _this$editor$options$4 !== void 0 ? _this$editor$options$4 : true) setTimeout(callback, 0); else callback(); } }); const Drop = Extension.create({ name: "drop", addProseMirrorPlugins() { return [new Plugin({ key: new PluginKey("tiptapDrop"), props: { handleDrop: (_, e, slice2, moved) => { this.editor.emit("drop", { editor: this.editor, event: e, slice: slice2, moved }); } } })]; } }); const Editable = Extension.create({ name: "editable", addProseMirrorPlugins() { return [new Plugin({ key: new PluginKey("editable"), props: { editable: () => this.editor.options.editable } })]; } }); const focusEventsPluginKey = new PluginKey("focusEvents"); const FocusEvents = Extension.create({ name: "focusEvents", addProseMirrorPlugins() { const { editor } = this; return [new Plugin({ key: focusEventsPluginKey, props: { handleDOMEvents: { focus: (view, event) => { editor.isFocused = true; const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false); view.dispatch(transaction); return false; }, blur: (view, event) => { editor.isFocused = false; const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false); view.dispatch(transaction); return false; } } } })]; } }); const Keymap = Extension.create({ name: "keymap", addKeyboardShortcuts() { const handleBackspace2 = () => this.editor.commands.first(({ commands }) => [ () => commands.undoInputRule(), () => commands.command(({ tr: tr2 }) => { const { selection, doc: doc2 } = tr2; const { empty: empty2, $anchor } = selection; const { pos, parent } = $anchor; const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr2.doc.resolve(pos - 1) : $anchor; const parentIsIsolating = $parentPos.parent.type.spec.isolating; const parentPos = $anchor.pos - $anchor.parentOffset; const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : Selection.atStart(doc2).from === pos; if (!empty2 || !parent.type.isTextblock || parent.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") return false; return commands.clearNodes(); }), () => commands.deleteSelection(), () => commands.joinBackward(), () => commands.selectNodeBackward() ]); const handleDelete2 = () => this.editor.commands.first(({ commands }) => [ () => commands.deleteSelection(), () => commands.deleteCurrentNode(), () => commands.joinForward(), () => commands.selectNodeForward() ]); const handleEnter2 = () => this.editor.commands.first(({ commands }) => [ () => commands.newlineInCode(), () => commands.createParagraphNear(), () => commands.liftEmptyBlock(), () => commands.splitBlock() ]); const baseKeymap = { Enter: handleEnter2, "Mod-Enter": () => this.editor.commands.exitCode(), Backspace: handleBackspace2, "Mod-Backspace": handleBackspace2, "Shift-Backspace": handleBackspace2, Delete: handleDelete2, "Mod-Delete": handleDelete2, "Mod-a": () => this.editor.commands.selectAll() }; const pcKeymap = { ...baseKeymap }; const macKeymap = { ...baseKeymap, "Ctrl-h": handleBackspace2, "Alt-Backspace": handleBackspace2, "Ctrl-d": handleDelete2, "Ctrl-Alt-Backspace": handleDelete2, "Alt-Delete": handleDelete2, "Alt-d": handleDelete2, "Ctrl-a": () => this.editor.commands.selectTextblockStart(), "Ctrl-e": () => this.editor.commands.selectTextblockEnd() }; if (isiOS() || isMacOS()) return macKeymap; return pcKeymap; }, addProseMirrorPlugins() { return [new Plugin({ key: new PluginKey("clearDocument"), appendTransaction: (transactions, oldState, newState) => { if (transactions.some((tr3) => tr3.getMeta("composition"))) return; const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc); const ignoreTr = transactions.some((transaction) => transaction.getMeta("preventClearDocument")); if (!docChanges || ignoreTr) return; const { empty: empty2, from: from2, to } = oldState.selection; const allFrom = Selection.atStart(oldState.doc).from; const allEnd = Selection.atEnd(oldState.doc).to; if (empty2 || !(from2 === allFrom && to === allEnd)) return; if (!isNodeEmpty(newState.doc)) return; const tr2 = newState.tr; const state = createChainableState({ state: newState, transaction: tr2 }); const { commands } = new CommandManager({ editor: this.editor, state }); commands.clearNodes(); if (!tr2.steps.length) return; return tr2; } })]; } }); const Paste = Extension.create({ name: "paste", addProseMirrorPlugins() { return [new Plugin({ key: new PluginKey("tiptapPaste"), props: { handlePaste: (_view, e, slice2) => { this.editor.emit("paste", { editor: this.editor, event: e, slice: slice2 }); } } })]; } }); const Tabindex = Extension.create({ name: "tabindex", addOptions() { return { value: void 0 }; }, addProseMirrorPlugins() { return [new Plugin({ key: new PluginKey("tabindex"), props: { attributes: () => { var _this$options$value; if (!this.editor.isEditable && this.options.value === void 0) return {}; return { tabindex: (_this$options$value = this.options.value) !== null && _this$options$value !== void 0 ? _this$options$value : "0" }; } } })]; } }); const TextDirection = Extension.create({ name: "textDirection", addOptions() { return { direction: void 0 }; }, addGlobalAttributes() { if (!this.options.direction) return []; const { nodeExtensions } = splitExtensions(this.extensions); return [{ types: nodeExtensions.filter((extension) => extension.name !== "text").map((extension) => extension.name), attributes: { dir: { default: this.options.direction, parseHTML: (element) => { const dir = element.getAttribute("dir"); if (dir && (dir === "ltr" || dir === "rtl" || dir === "auto")) return dir; return this.options.direction; }, renderHTML: (attributes) => { if (!attributes.dir) return {}; return { dir: attributes.dir }; } } } }]; }, addProseMirrorPlugins() { return [new Plugin({ key: new PluginKey("textDirection"), props: { attributes: () => { const direction = this.options.direction; if (!direction) return {}; return { dir: direction }; } } })]; } }); var extensions_exports = /* @__PURE__ */ __exportAll({ ClipboardTextSerializer: () => ClipboardTextSerializer, Commands: () => Commands, Delete: () => Delete, Drop: () => Drop, Editable: () => Editable, FocusEvents: () => FocusEvents, Keymap: () => Keymap, Paste: () => Paste, Tabindex: () => Tabindex, TextDirection: () => TextDirection, focusEventsPluginKey: () => focusEventsPluginKey }); function markInputRule(config) { return new InputRule({ find: config.find, handler: ({ state, range, match }) => { const attributes = callOrReturn(config.getAttributes, void 0, match); if (attributes === false || attributes === null) return null; const { tr: tr2 } = state; const captureGroup = match[match.length - 1]; const fullMatch = match[0]; if (captureGroup) { const startSpaces = fullMatch.search(/\S/); const textStart = range.from + fullMatch.indexOf(captureGroup); const textEnd = textStart + captureGroup.length; if (getMarksBetween(range.from, range.to, state.doc).filter((item) => { return item.mark.type.excluded.find((type) => type === config.type && type !== item.mark.type); }).filter((item) => item.to > textStart).length) return null; if (textEnd < range.to) tr2.delete(textEnd, range.to); if (textStart > range.from) tr2.delete(range.from + startSpaces, textStart); const markEnd = range.from + startSpaces + captureGroup.length; tr2.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); tr2.removeStoredMark(config.type); } }, undoable: config.undoable }); } function nodeInputRule(config) { return new InputRule({ find: config.find, handler: ({ state, range, match }) => { const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; const { tr: tr2 } = state; const start = range.from; let end = range.to; const newNode = config.type.create(attributes); if (match[1]) { let matchStart = start + match[0].lastIndexOf(match[1]); if (matchStart > end) matchStart = end; else end = matchStart + match[1].length; const lastChar = match[0][match[0].length - 1]; tr2.insertText(lastChar, start + match[0].length - 1); tr2.replaceWith(matchStart, end, newNode); } else if (match[0]) { const insertionStart = config.type.isInline ? start : start - 1; tr2.insert(insertionStart, config.type.create(attributes)).delete(tr2.mapping.map(start), tr2.mapping.map(end)); } tr2.scrollIntoView(); }, undoable: config.undoable }); } function textblockTypeInputRule(config) { return new InputRule({ find: config.find, handler: ({ state, range, match }) => { const $start = state.doc.resolve(range.from); const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) return null; state.tr.delete(range.from, range.to).setBlockType(range.from, range.from, config.type, attributes); }, undoable: config.undoable }); } function wrappingInputRule(config) { return new InputRule({ find: config.find, handler: ({ state, range, match, chain }) => { const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; const tr2 = state.tr.delete(range.from, range.to); const blockRange = tr2.doc.resolve(range.from).blockRange(); const wrapping = blockRange && findWrapping(blockRange, config.type, attributes); if (!wrapping) return null; tr2.wrap(blockRange, wrapping); if (config.keepMarks && config.editor) { const { selection, storedMarks } = state; const { splittableMarks } = config.editor.extensionManager; const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); if (marks) { const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); tr2.ensureMarks(filteredMarks); } } if (config.keepAttributes) { const nodeType = config.type.name === "bulletList" || config.type.name === "orderedList" ? "listItem" : "taskList"; chain().updateAttributes(nodeType, attributes).run(); } const before = tr2.doc.resolve(range.from - 1).nodeBefore; if (before && before.type === config.type && canJoin(tr2.doc, range.from - 1) && (!config.joinPredicate || config.joinPredicate(match, before))) tr2.join(range.from - 1); }, undoable: config.undoable }); } const isTouchEvent = (e) => { return "touches" in e; }; var ResizableNodeView = class { /** * Creates a new ResizableNodeView instance. * * The constructor sets up the resize handles, applies initial sizing from * node attributes, and configures all resize behavior options. * * @param options - Configuration options for the resizable node view */ constructor(options) { var _options$options, _options$options2, _options$options3, _options$options4, _options$options5, _options$options6; this.directions = [ "bottom-left", "bottom-right", "top-left", "top-right" ]; this.minSize = { height: 8, width: 8 }; this.preserveAspectRatio = false; this.classNames = { container: "", wrapper: "", handle: "", resizing: "" }; this.initialWidth = 0; this.initialHeight = 0; this.aspectRatio = 1; this.isResizing = false; this.activeHandle = null; this.startX = 0; this.startY = 0; this.startWidth = 0; this.startHeight = 0; this.isShiftKeyPressed = false; this.lastEditableState = void 0; this.handleMap = /* @__PURE__ */ new Map(); this.handleMouseMove = (event) => { if (!this.isResizing || !this.activeHandle) return; const deltaX = event.clientX - this.startX; const deltaY = event.clientY - this.startY; this.handleResize(deltaX, deltaY); }; this.handleTouchMove = (event) => { if (!this.isResizing || !this.activeHandle) return; const touch = event.touches[0]; if (!touch) return; const deltaX = touch.clientX - this.startX; const deltaY = touch.clientY - this.startY; this.handleResize(deltaX, deltaY); }; this.handleMouseUp = () => { if (!this.isResizing) return; const finalWidth = this.element.offsetWidth; const finalHeight = this.element.offsetHeight; this.onCommit(finalWidth, finalHeight); this.isResizing = false; this.activeHandle = null; this.container.dataset.resizeState = "false"; if (this.classNames.resizing) this.container.classList.remove(this.classNames.resizing); document.removeEventListener("mousemove", this.handleMouseMove); document.removeEventListener("mouseup", this.handleMouseUp); document.removeEventListener("keydown", this.handleKeyDown); document.removeEventListener("keyup", this.handleKeyUp); }; this.handleKeyDown = (event) => { if (event.key === "Shift") this.isShiftKeyPressed = true; }; this.handleKeyUp = (event) => { if (event.key === "Shift") this.isShiftKeyPressed = false; }; this.node = options.node; this.editor = options.editor; this.element = options.element; this.element.draggable = false; this.contentElement = options.contentElement; this.getPos = options.getPos; this.onResize = options.onResize; this.onCommit = options.onCommit; this.onUpdate = options.onUpdate; if ((_options$options = options.options) === null || _options$options === void 0 ? void 0 : _options$options.min) this.minSize = { ...this.minSize, ...options.options.min }; if ((_options$options2 = options.options) === null || _options$options2 === void 0 ? void 0 : _options$options2.max) this.maxSize = options.options.max; if (options === null || options === void 0 || (_options$options3 = options.options) === null || _options$options3 === void 0 ? void 0 : _options$options3.directions) this.directions = options.options.directions; if ((_options$options4 = options.options) === null || _options$options4 === void 0 ? void 0 : _options$options4.preserveAspectRatio) this.preserveAspectRatio = options.options.preserveAspectRatio; if ((_options$options5 = options.options) === null || _options$options5 === void 0 ? void 0 : _options$options5.className) this.classNames = { container: options.options.className.container || "", wrapper: options.options.className.wrapper || "", handle: options.options.className.handle || "", resizing: options.options.className.resizing || "" }; if ((_options$options6 = options.options) === null || _options$options6 === void 0 ? void 0 : _options$options6.createCustomHandle) this.createCustomHandle = options.options.createCustomHandle; this.wrapper = this.createWrapper(); this.container = this.createContainer(); this.applyInitialSize(); this.attachHandles(); this.editor.on("update", this.handleEditorUpdate.bind(this)); } /** * Returns the top-level DOM node that should be placed in the editor. * * This is required by the ProseMirror NodeView interface. The container * includes the wrapper, handles, and the actual content element. * * @returns The container element to be inserted into the editor */ get dom() { return this.container; } get contentDOM() { var _this$contentElement; return (_this$contentElement = this.contentElement) !== null && _this$contentElement !== void 0 ? _this$contentElement : null; } handleEditorUpdate() { const isEditable = this.editor.isEditable; if (isEditable === this.lastEditableState) return; this.lastEditableState = isEditable; if (!isEditable) this.removeHandles(); else if (isEditable && this.handleMap.size === 0) this.attachHandles(); } /** * Called when the node's content or attributes change. * * Updates the internal node reference. If a custom `onUpdate` callback * was provided, it will be called to handle additional update logic. * * @param node - The new/updated node * @param decorations - Node decorations * @param innerDecorations - Inner decorations * @returns `false` if the node type has changed (requires full rebuild), otherwise the result of `onUpdate` or `true` */ update(node, decorations, innerDecorations) { if (node.type !== this.node.type) return false; this.node = node; if (this.onUpdate) return this.onUpdate(node, decorations, innerDecorations); return true; } /** * Cleanup method called when the node view is being removed. * * Removes all event listeners to prevent memory leaks. This is required * by the ProseMirror NodeView interface. If a resize is active when * destroy is called, it will be properly cancelled. */ destroy() { if (this.isResizing) { this.container.dataset.resizeState = "false"; if (this.classNames.resizing) this.container.classList.remove(this.classNames.resizing); document.removeEventListener("mousemove", this.handleMouseMove); document.removeEventListener("mouseup", this.handleMouseUp); document.removeEventListener("keydown", this.handleKeyDown); document.removeEventListener("keyup", this.handleKeyUp); this.isResizing = false; this.activeHandle = null; } this.editor.off("update", this.handleEditorUpdate.bind(this)); this.container.remove(); } /** * Creates the outer container element. * * The container is the top-level element returned by the NodeView and * wraps the entire resizable node. It's set up with flexbox to handle * alignment and includes data attributes for styling and identification. * * @returns The container element */ createContainer() { const element = document.createElement("div"); element.dataset.resizeContainer = ""; element.dataset.node = this.node.type.name; element.style.display = this.node.type.isInline ? "inline-flex" : "flex"; if (this.classNames.container) element.className = this.classNames.container; element.appendChild(this.wrapper); return element; } /** * Creates the wrapper element that contains the content and handles. * * The wrapper uses relative positioning so that resize handles can be * positioned absolutely within it. This is the direct parent of the * content element being made resizable. * * @returns The wrapper element */ createWrapper() { const element = document.createElement("div"); element.style.position = "relative"; element.style.display = "block"; element.dataset.resizeWrapper = ""; if (this.classNames.wrapper) element.className = this.classNames.wrapper; element.appendChild(this.element); return element; } /** * Creates a resize handle element for a specific direction. * * Each handle is absolutely positioned and includes a data attribute * identifying its direction for styling purposes. * * @param direction - The resize direction for this handle * @returns The handle element */ createHandle(direction) { const handle = document.createElement("div"); handle.dataset.resizeHandle = direction; handle.style.position = "absolute"; if (this.classNames.handle) handle.className = this.classNames.handle; return handle; } /** * Positions a handle element according to its direction. * * Corner handles (e.g., 'top-left') are positioned at the intersection * of two edges. Edge handles (e.g., 'top') span the full width or height. * * @param handle - The handle element to position * @param direction - The direction determining the position */ positionHandle(handle, direction) { const isTop = direction.includes("top"); const isBottom = direction.includes("bottom"); const isLeft = direction.includes("left"); const isRight = direction.includes("right"); if (isTop) handle.style.top = "0"; if (isBottom) handle.style.bottom = "0"; if (isLeft) handle.style.left = "0"; if (isRight) handle.style.right = "0"; if (direction === "top" || direction === "bottom") { handle.style.left = "0"; handle.style.right = "0"; } if (direction === "left" || direction === "right") { handle.style.top = "0"; handle.style.bottom = "0"; } } /** * Creates and attaches all resize handles to the wrapper. * * Iterates through the configured directions, creates a handle for each, * positions it, attaches the mousedown listener, and appends it to the DOM. */ attachHandles() { this.directions.forEach((direction) => { let handle; if (this.createCustomHandle) handle = this.createCustomHandle(direction); else handle = this.createHandle(direction); if (!(handle instanceof HTMLElement)) { console.warn(`[ResizableNodeView] createCustomHandle("${direction}") did not return an HTMLElement. Falling back to default handle.`); handle = this.createHandle(direction); } if (!this.createCustomHandle) this.positionHandle(handle, direction); handle.addEventListener("mousedown", (event) => this.handleResizeStart(event, direction)); handle.addEventListener("touchstart", (event) => this.handleResizeStart(event, direction)); this.handleMap.set(direction, handle); this.wrapper.appendChild(handle); }); } /** * Removes all resize handles from the wrapper. * * Cleans up the handle map and removes each handle element from the DOM. */ removeHandles() { this.handleMap.forEach((el) => el.remove()); this.handleMap.clear(); } /** * Applies initial sizing from node attributes to the element. * * If width/height attributes exist on the node, they're applied to the element. * Otherwise, the element's natural/current dimensions are measured. The aspect * ratio is calculated for later use in aspect-ratio-preserving resizes. */ applyInitialSize() { const width = this.node.attrs.width; const height = this.node.attrs.height; if (width) { this.element.style.width = `${width}px`; this.initialWidth = width; } else this.initialWidth = this.element.offsetWidth; if (height) { this.element.style.height = `${height}px`; this.initialHeight = height; } else this.initialHeight = this.element.offsetHeight; if (this.initialWidth > 0 && this.initialHeight > 0) this.aspectRatio = this.initialWidth / this.initialHeight; } /** * Initiates a resize operation when a handle is clicked. * * Captures the starting mouse position and element dimensions, sets up * the resize state, adds the resizing class and state attribute, and * attaches document-level listeners for mouse movement and keyboard input. * * @param event - The mouse down event * @param direction - The direction of the handle being dragged */ handleResizeStart(event, direction) { event.preventDefault(); event.stopPropagation(); this.isResizing = true; this.activeHandle = direction; if (isTouchEvent(event)) { this.startX = event.touches[0].clientX; this.startY = event.touches[0].clientY; } else { this.startX = event.clientX; this.startY = event.clientY; } this.startWidth = this.element.offsetWidth; this.startHeight = this.element.offsetHeight; if (this.startWidth > 0 && this.startHeight > 0) this.aspectRatio = this.startWidth / this.startHeight; if (this.getPos() !== void 0) ; this.container.dataset.resizeState = "true"; if (this.classNames.resizing) this.container.classList.add(this.classNames.resizing); document.addEventListener("mousemove", this.handleMouseMove); document.addEventListener("touchmove", this.handleTouchMove); document.addEventListener("mouseup", this.handleMouseUp); document.addEventListener("keydown", this.handleKeyDown); document.addEventListener("keyup", this.handleKeyUp); } handleResize(deltaX, deltaY) { if (!this.activeHandle) return; const shouldPreserveAspectRatio = this.preserveAspectRatio || this.isShiftKeyPressed; const { width, height } = this.calculateNewDimensions(this.activeHandle, deltaX, deltaY); const constrained = this.applyConstraints(width, height, shouldPreserveAspectRatio); this.element.style.width = `${constrained.width}px`; this.element.style.height = `${constrained.height}px`; if (this.onResize) this.onResize(constrained.width, constrained.height); } /** * Calculates new dimensions based on mouse delta and resize direction. * * Takes the starting dimensions and applies the mouse movement delta * according to the handle direction. For corner handles, both dimensions * are affected. For edge handles, only one dimension changes. If aspect * ratio should be preserved, delegates to applyAspectRatio. * * @param direction - The active resize handle direction * @param deltaX - Horizontal mouse movement since resize start * @param deltaY - Vertical mouse movement since resize start * @returns The calculated width and height */ calculateNewDimensions(direction, deltaX, deltaY) { let newWidth = this.startWidth; let newHeight = this.startHeight; const isRight = direction.includes("right"); const isLeft = direction.includes("left"); const isBottom = direction.includes("bottom"); const isTop = direction.includes("top"); if (isRight) newWidth = this.startWidth + deltaX; else if (isLeft) newWidth = this.startWidth - deltaX; if (isBottom) newHeight = this.startHeight + deltaY; else if (isTop) newHeight = this.startHeight - deltaY; if (direction === "right" || direction === "left") newWidth = this.startWidth + (isRight ? deltaX : -deltaX); if (direction === "top" || direction === "bottom") newHeight = this.startHeight + (isBottom ? deltaY : -deltaY); if (this.preserveAspectRatio || this.isShiftKeyPressed) return this.applyAspectRatio(newWidth, newHeight, direction); return { width: newWidth, height: newHeight }; } /** * Applies min/max constraints to dimensions. * * When aspect ratio is NOT preserved, constraints are applied independently * to width and height. When aspect ratio IS preserved, constraints are * applied while maintaining the aspect ratio—if one dimension hits a limit, * the other is recalculated proportionally. * * This ensures that aspect ratio is never broken when constrained. * * @param width - The unconstrained width * @param height - The unconstrained height * @param preserveAspectRatio - Whether to maintain aspect ratio while constraining * @returns The constrained dimensions */ applyConstraints(width, height, preserveAspectRatio) { var _this$maxSize3, _this$maxSize4; if (!preserveAspectRatio) { var _this$maxSize, _this$maxSize2; let constrainedWidth2 = Math.max(this.minSize.width, width); let constrainedHeight2 = Math.max(this.minSize.height, height); if ((_this$maxSize = this.maxSize) === null || _this$maxSize === void 0 ? void 0 : _this$maxSize.width) constrainedWidth2 = Math.min(this.maxSize.width, constrainedWidth2); if ((_this$maxSize2 = this.maxSize) === null || _this$maxSize2 === void 0 ? void 0 : _this$maxSize2.height) constrainedHeight2 = Math.min(this.maxSize.height, constrainedHeight2); return { width: constrainedWidth2, height: constrainedHeight2 }; } let constrainedWidth = width; let constrainedHeight = height; if (constrainedWidth < this.minSize.width) { constrainedWidth = this.minSize.width; constrainedHeight = constrainedWidth / this.aspectRatio; } if (constrainedHeight < this.minSize.height) { constrainedHeight = this.minSize.height; constrainedWidth = constrainedHeight * this.aspectRatio; } if (((_this$maxSize3 = this.maxSize) === null || _this$maxSize3 === void 0 ? void 0 : _this$maxSize3.width) && constrainedWidth > this.maxSize.width) { constrainedWidth = this.maxSize.width; constrainedHeight = constrainedWidth / this.aspectRatio; } if (((_this$maxSize4 = this.maxSize) === null || _this$maxSize4 === void 0 ? void 0 : _this$maxSize4.height) && constrainedHeight > this.maxSize.height) { constrainedHeight = this.maxSize.height; constrainedWidth = constrainedHeight * this.aspectRatio; } return { width: constrainedWidth, height: constrainedHeight }; } /** * Adjusts dimensions to maintain the original aspect ratio. * * For horizontal handles (left/right), uses width as the primary dimension * and calculates height from it. For vertical handles (top/bottom), uses * height as primary and calculates width. For corner handles, uses width * as the primary dimension. * * @param width - The new width * @param height - The new height * @param direction - The active resize direction * @returns Dimensions adjusted to preserve aspect ratio */ applyAspectRatio(width, height, direction) { const isHorizontal = direction === "left" || direction === "right"; const isVertical = direction === "top" || direction === "bottom"; if (isHorizontal) return { width, height: width / this.aspectRatio }; if (isVertical) return { width: height * this.aspectRatio, height }; return { width, height: width / this.aspectRatio }; } }; var Node2 = class Node3 extends Extendable { constructor(..._args) { super(..._args); this.type = "node"; } /** * Create a new Node instance * @param config - Node configuration object or a function that returns a configuration object */ static create(config = {}) { const resolvedConfig = typeof config === "function" ? config() : config; return new Node3(resolvedConfig); } configure(options) { return super.configure(options); } extend(extendedConfig) { const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; return super.extend(resolvedConfig); } }; var NodeView = class { constructor(component, props, options) { this.isDragging = false; this.component = component; this.editor = props.editor; this.options = { stopEvent: null, ignoreMutation: null, ...options }; this.extension = props.extension; this.node = props.node; this.decorations = props.decorations; this.innerDecorations = props.innerDecorations; this.view = props.view; this.HTMLAttributes = props.HTMLAttributes; this.getPos = () => { try { return props.getPos(); } catch { return; } }; this.mount(); } mount() { } get dom() { return this.editor.view.dom; } get contentDOM() { return null; } onDragStart(event) { var _target$parentElement, _this$contentDOM; const { view } = this.editor; const target = event.target; const dragHandle = target.nodeType === 3 ? (_target$parentElement = target.parentElement) === null || _target$parentElement === void 0 ? void 0 : _target$parentElement.closest("[data-drag-handle]") : target.closest("[data-drag-handle]"); if (!this.dom || ((_this$contentDOM = this.contentDOM) === null || _this$contentDOM === void 0 ? void 0 : _this$contentDOM.contains(target)) || !dragHandle) return; let x = 0; let y = 0; if (this.dom !== dragHandle) { var _event$offsetX, _nativeEvent, _event$offsetY, _nativeEvent2; const domBox = this.dom.getBoundingClientRect(); const handleBox = dragHandle.getBoundingClientRect(); const offsetX = (_event$offsetX = event.offsetX) !== null && _event$offsetX !== void 0 ? _event$offsetX : (_nativeEvent = event.nativeEvent) === null || _nativeEvent === void 0 ? void 0 : _nativeEvent.offsetX; const offsetY = (_event$offsetY = event.offsetY) !== null && _event$offsetY !== void 0 ? _event$offsetY : (_nativeEvent2 = event.nativeEvent) === null || _nativeEvent2 === void 0 ? void 0 : _nativeEvent2.offsetY; x = handleBox.x - domBox.x + offsetX; y = handleBox.y - domBox.y + offsetY; } const clonedNode = this.dom.cloneNode(true); try { const domBox = this.dom.getBoundingClientRect(); clonedNode.style.width = `${Math.round(domBox.width)}px`; clonedNode.style.height = `${Math.round(domBox.height)}px`; clonedNode.style.boxSizing = "border-box"; clonedNode.style.pointerEvents = "none"; } catch { } let dragImageWrapper = null; try { var _event$dataTransfer; dragImageWrapper = document.createElement("div"); dragImageWrapper.style.position = "absolute"; dragImageWrapper.style.top = "-9999px"; dragImageWrapper.style.left = "-9999px"; dragImageWrapper.style.pointerEvents = "none"; dragImageWrapper.appendChild(clonedNode); document.body.appendChild(dragImageWrapper); (_event$dataTransfer = event.dataTransfer) === null || _event$dataTransfer === void 0 || _event$dataTransfer.setDragImage(clonedNode, x, y); } finally { if (dragImageWrapper) setTimeout(() => { try { dragImageWrapper === null || dragImageWrapper === void 0 || dragImageWrapper.remove(); } catch { } }, 0); } const pos = this.getPos(); if (typeof pos !== "number") return; const selection = NodeSelection.create(view.state.doc, pos); const transaction = view.state.tr.setSelection(selection); view.dispatch(transaction); } stopEvent(event) { var _this$contentDOM2; if (!this.dom) return false; if (typeof this.options.stopEvent === "function") return this.options.stopEvent({ event }); const target = event.target; if (!(this.dom.contains(target) && !((_this$contentDOM2 = this.contentDOM) === null || _this$contentDOM2 === void 0 ? void 0 : _this$contentDOM2.contains(target)))) return false; const isDragEvent = event.type.startsWith("drag"); const isDragOverEnterEvent = event.type === "dragover" || event.type === "dragenter"; const isDropEvent = event.type === "drop"; if (([ "INPUT", "BUTTON", "SELECT", "TEXTAREA" ].includes(target.tagName) || target.isContentEditable) && !isDropEvent && !isDragEvent) return true; const { isEditable } = this.editor; const { isDragging } = this; const isDraggable = !!this.node.type.spec.draggable; const isSelectable = NodeSelection.isSelectable(this.node); const isCopyEvent = event.type === "copy"; const isPasteEvent = event.type === "paste"; const isCutEvent = event.type === "cut"; const isClickEvent = event.type === "mousedown"; if (!isDraggable && isSelectable && isDragEvent && event.target === this.dom) event.preventDefault(); if (isDraggable && isDragEvent && !isDragging && event.target === this.dom) { event.preventDefault(); return false; } if (isDraggable && isEditable && !isDragging && isClickEvent) { const dragHandle = target.closest("[data-drag-handle]"); if (dragHandle && (this.dom === dragHandle || this.dom.contains(dragHandle))) { this.isDragging = true; document.addEventListener("dragend", () => { this.isDragging = false; }, { once: true }); document.addEventListener("drop", () => { this.isDragging = false; }, { once: true }); document.addEventListener("mouseup", () => { this.isDragging = false; }, { once: true }); } } if (isDragging || isDragOverEnterEvent || isDropEvent || isCopyEvent || isPasteEvent || isCutEvent || isClickEvent && isSelectable) return false; return true; } /** * Called when a DOM [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) or a selection change happens within the view. * @return `false` if the editor should re-read the selection or re-parse the range around the mutation * @return `true` if it can safely be ignored. */ ignoreMutation(mutation) { if (!this.dom || !this.contentDOM) return true; if (typeof this.options.ignoreMutation === "function") return this.options.ignoreMutation({ mutation }); if (this.node.isLeaf || this.node.isAtom) return true; if (mutation.type === "selection") return false; if (this.contentDOM.contains(mutation.target) && mutation.type === "childList" && (isiOS() || isAndroid()) && this.editor.isFocused) { if ([...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)].every((node) => node.isContentEditable)) return false; } if (this.contentDOM === mutation.target && mutation.type === "attributes") return true; if (this.contentDOM.contains(mutation.target)) return false; return true; } /** * Update the attributes of the prosemirror node. */ updateAttributes(attributes) { this.editor.commands.command(({ tr: tr2 }) => { const pos = this.getPos(); if (typeof pos !== "number") return false; tr2.setNodeMarkup(pos, void 0, { ...this.node.attrs, ...attributes }); return true; }); } /** * Delete the node. */ deleteNode() { const from2 = this.getPos(); if (typeof from2 !== "number") return; const to = from2 + this.node.nodeSize; this.editor.commands.deleteRange({ from: from2, to }); } }; function markPasteRule(config) { return new PasteRule({ find: config.find, handler: ({ state, range, match, pasteEvent }) => { const attributes = callOrReturn(config.getAttributes, void 0, match, pasteEvent); if (attributes === false || attributes === null) return null; const { tr: tr2 } = state; const captureGroup = match[match.length - 1]; const fullMatch = match[0]; let markEnd = range.to; if (captureGroup) { const startSpaces = fullMatch.search(/\S/); const textStart = range.from + fullMatch.indexOf(captureGroup); const textEnd = textStart + captureGroup.length; if (getMarksBetween(range.from, range.to, state.doc).filter((item) => { return item.mark.type.excluded.find((type) => type === config.type && type !== item.mark.type); }).filter((item) => item.to > textStart).length) return null; if (textEnd < range.to) tr2.delete(textEnd, range.to); if (textStart > range.from) tr2.delete(range.from + startSpaces, textStart); markEnd = range.from + startSpaces + captureGroup.length; tr2.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); if (!(match.index !== void 0 && match.input !== void 0 && match.index + match[0].length >= match.input.length)) tr2.removeStoredMark(config.type); } } }); } function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; } var react = { exports: {} }; var react_production_min = {}; /** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredReact_production_min; function requireReact_production_min() { if (hasRequiredReact_production_min) return react_production_min; hasRequiredReact_production_min = 1; var l = Symbol.for("react.element"), n = Symbol.for("react.portal"), p = Symbol.for("react.fragment"), q = Symbol.for("react.strict_mode"), r = Symbol.for("react.profiler"), t = Symbol.for("react.provider"), u = Symbol.for("react.context"), v = Symbol.for("react.forward_ref"), w = Symbol.for("react.suspense"), x = Symbol.for("react.memo"), y = Symbol.for("react.lazy"), z = Symbol.iterator; function A(a) { if (null === a || "object" !== typeof a) return null; a = z && a[z] || a["@@iterator"]; return "function" === typeof a ? a : null; } var B = { isMounted: function() { return false; }, enqueueForceUpdate: function() { }, enqueueReplaceState: function() { }, enqueueSetState: function() { } }, C = Object.assign, D = {}; function E(a, b, e) { this.props = a; this.context = b; this.refs = D; this.updater = e || B; } E.prototype.isReactComponent = {}; E.prototype.setState = function(a, b) { if ("object" !== typeof a && "function" !== typeof a && null != a) throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); this.updater.enqueueSetState(this, a, b, "setState"); }; E.prototype.forceUpdate = function(a) { this.updater.enqueueForceUpdate(this, a, "forceUpdate"); }; function F() { } F.prototype = E.prototype; function G(a, b, e) { this.props = a; this.context = b; this.refs = D; this.updater = e || B; } var H = G.prototype = new F(); H.constructor = G; C(H, E.prototype); H.isPureReactComponent = true; var I = Array.isArray, J = Object.prototype.hasOwnProperty, K = { current: null }, L = { key: true, ref: true, __self: true, __source: true }; function M(a, b, e) { var d, c = {}, k = null, h2 = null; if (null != b) for (d in void 0 !== b.ref && (h2 = b.ref), void 0 !== b.key && (k = "" + b.key), b) J.call(b, d) && !L.hasOwnProperty(d) && (c[d] = b[d]); var g = arguments.length - 2; if (1 === g) c.children = e; else if (1 < g) { for (var f = Array(g), m = 0; m < g; m++) f[m] = arguments[m + 2]; c.children = f; } if (a && a.defaultProps) for (d in g = a.defaultProps, g) void 0 === c[d] && (c[d] = g[d]); return { $$typeof: l, type: a, key: k, ref: h2, props: c, _owner: K.current }; } function N(a, b) { return { $$typeof: l, type: a.type, key: b, ref: a.ref, props: a.props, _owner: a._owner }; } function O(a) { return "object" === typeof a && null !== a && a.$$typeof === l; } function escape(a) { var b = { "=": "=0", ":": "=2" }; return "$" + a.replace(/[=:]/g, function(a2) { return b[a2]; }); } var P = /\/+/g; function Q(a, b) { return "object" === typeof a && null !== a && null != a.key ? escape("" + a.key) : b.toString(36); } function R(a, b, e, d, c) { var k = typeof a; if ("undefined" === k || "boolean" === k) a = null; var h2 = false; if (null === a) h2 = true; else switch (k) { case "string": case "number": h2 = true; break; case "object": switch (a.$$typeof) { case l: case n: h2 = true; } } if (h2) return h2 = a, c = c(h2), a = "" === d ? "." + Q(h2, 0) : d, I(c) ? (e = "", null != a && (e = a.replace(P, "$&/") + "/"), R(c, b, e, "", function(a2) { return a2; })) : null != c && (O(c) && (c = N(c, e + (!c.key || h2 && h2.key === c.key ? "" : ("" + c.key).replace(P, "$&/") + "/") + a)), b.push(c)), 1; h2 = 0; d = "" === d ? "." : d + ":"; if (I(a)) for (var g = 0; g < a.length; g++) { k = a[g]; var f = d + Q(k, g); h2 += R(k, b, e, f, c); } else if (f = A(a), "function" === typeof f) for (a = f.call(a), g = 0; !(k = a.next()).done; ) k = k.value, f = d + Q(k, g++), h2 += R(k, b, e, f, c); else if ("object" === k) throw b = String(a), Error("Objects are not valid as a React child (found: " + ("[object Object]" === b ? "object with keys {" + Object.keys(a).join(", ") + "}" : b) + "). If you meant to render a collection of children, use an array instead."); return h2; } function S(a, b, e) { if (null == a) return a; var d = [], c = 0; R(a, d, "", "", function(a2) { return b.call(e, a2, c++); }); return d; } function T(a) { if (-1 === a._status) { var b = a._result; b = b(); b.then(function(b2) { if (0 === a._status || -1 === a._status) a._status = 1, a._result = b2; }, function(b2) { if (0 === a._status || -1 === a._status) a._status = 2, a._result = b2; }); -1 === a._status && (a._status = 0, a._result = b); } if (1 === a._status) return a._result.default; throw a._result; } var U = { current: null }, V = { transition: null }, W = { ReactCurrentDispatcher: U, ReactCurrentBatchConfig: V, ReactCurrentOwner: K }; function X() { throw Error("act(...) is not supported in production builds of React."); } react_production_min.Children = { map: S, forEach: function(a, b, e) { S(a, function() { b.apply(this, arguments); }, e); }, count: function(a) { var b = 0; S(a, function() { b++; }); return b; }, toArray: function(a) { return S(a, function(a2) { return a2; }) || []; }, only: function(a) { if (!O(a)) throw Error("React.Children.only expected to receive a single React element child."); return a; } }; react_production_min.Component = E; react_production_min.Fragment = p; react_production_min.Profiler = r; react_production_min.PureComponent = G; react_production_min.StrictMode = q; react_production_min.Suspense = w; react_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = W; react_production_min.act = X; react_production_min.cloneElement = function(a, b, e) { if (null === a || void 0 === a) throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + a + "."); var d = C({}, a.props), c = a.key, k = a.ref, h2 = a._owner; if (null != b) { void 0 !== b.ref && (k = b.ref, h2 = K.current); void 0 !== b.key && (c = "" + b.key); if (a.type && a.type.defaultProps) var g = a.type.defaultProps; for (f in b) J.call(b, f) && !L.hasOwnProperty(f) && (d[f] = void 0 === b[f] && void 0 !== g ? g[f] : b[f]); } var f = arguments.length - 2; if (1 === f) d.children = e; else if (1 < f) { g = Array(f); for (var m = 0; m < f; m++) g[m] = arguments[m + 2]; d.children = g; } return { $$typeof: l, type: a.type, key: c, ref: k, props: d, _owner: h2 }; }; react_production_min.createContext = function(a) { a = { $$typeof: u, _currentValue: a, _currentValue2: a, _threadCount: 0, Provider: null, Consumer: null, _defaultValue: null, _globalName: null }; a.Provider = { $$typeof: t, _context: a }; return a.Consumer = a; }; react_production_min.createElement = M; react_production_min.createFactory = function(a) { var b = M.bind(null, a); b.type = a; return b; }; react_production_min.createRef = function() { return { current: null }; }; react_production_min.forwardRef = function(a) { return { $$typeof: v, render: a }; }; react_production_min.isValidElement = O; react_production_min.lazy = function(a) { return { $$typeof: y, _payload: { _status: -1, _result: a }, _init: T }; }; react_production_min.memo = function(a, b) { return { $$typeof: x, type: a, compare: void 0 === b ? null : b }; }; react_production_min.startTransition = function(a) { var b = V.transition; V.transition = {}; try { a(); } finally { V.transition = b; } }; react_production_min.unstable_act = X; react_production_min.useCallback = function(a, b) { return U.current.useCallback(a, b); }; react_production_min.useContext = function(a) { return U.current.useContext(a); }; react_production_min.useDebugValue = function() { }; react_production_min.useDeferredValue = function(a) { return U.current.useDeferredValue(a); }; react_production_min.useEffect = function(a, b) { return U.current.useEffect(a, b); }; react_production_min.useId = function() { return U.current.useId(); }; react_production_min.useImperativeHandle = function(a, b, e) { return U.current.useImperativeHandle(a, b, e); }; react_production_min.useInsertionEffect = function(a, b) { return U.current.useInsertionEffect(a, b); }; react_production_min.useLayoutEffect = function(a, b) { return U.current.useLayoutEffect(a, b); }; react_production_min.useMemo = function(a, b) { return U.current.useMemo(a, b); }; react_production_min.useReducer = function(a, b, e) { return U.current.useReducer(a, b, e); }; react_production_min.useRef = function(a) { return U.current.useRef(a); }; react_production_min.useState = function(a) { return U.current.useState(a); }; react_production_min.useSyncExternalStore = function(a, b, e) { return U.current.useSyncExternalStore(a, b, e); }; react_production_min.useTransition = function() { return U.current.useTransition(); }; react_production_min.version = "18.3.1"; return react_production_min; } var react_development = { exports: {} }; /** * @license React * react.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ react_development.exports; var hasRequiredReact_development; function requireReact_development() { if (hasRequiredReact_development) return react_development.exports; hasRequiredReact_development = 1; (function(module2, exports2) { if (process.env.NODE_ENV !== "production") { (function() { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var ReactVersion = "18.3.1"; var REACT_ELEMENT_TYPE = Symbol.for("react.element"); var REACT_PORTAL_TYPE = Symbol.for("react.portal"); var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); var REACT_CONTEXT_TYPE = Symbol.for("react.context"); var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); var REACT_MEMO_TYPE = Symbol.for("react.memo"); var REACT_LAZY_TYPE = Symbol.for("react.lazy"); var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== "object") { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === "function") { return maybeIterator; } return null; } var ReactCurrentDispatcher = { /** * @internal * @type {ReactComponent} */ current: null }; var ReactCurrentBatchConfig = { transition: null }; var ReactCurrentActQueue = { current: null, // Used to reproduce behavior of `batchedUpdates` in legacy mode. isBatchingLegacy: false, didScheduleLegacyUpdate: false }; var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; var ReactDebugCurrentFrame = {}; var currentExtraStackFrame = null; function setExtraStackFrame(stack) { { currentExtraStackFrame = stack; } } { ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { { currentExtraStackFrame = stack; } }; ReactDebugCurrentFrame.getCurrentStack = null; ReactDebugCurrentFrame.getStackAddendum = function() { var stack = ""; if (currentExtraStackFrame) { stack += currentExtraStackFrame; } var impl = ReactDebugCurrentFrame.getCurrentStack; if (impl) { stack += impl() || ""; } return stack; }; } var enableScopeAPI = false; var enableCacheElement = false; var enableTransitionTracing = false; var enableLegacyHidden = false; var enableDebugTracing = false; var ReactSharedInternals = { ReactCurrentDispatcher, ReactCurrentBatchConfig, ReactCurrentOwner }; { ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; } function warn2(format) { { { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning("warn", format, args); } } } function error2(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning("error", format, args); } } } function printWarning(level, format, args) { { var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame2.getStackAddendum(); if (stack !== "") { format += "%s"; args = args.concat([stack]); } var argsWithFormat = args.map(function(item) { return String(item); }); argsWithFormat.unshift("Warning: " + format); Function.prototype.apply.call(console[level], console, argsWithFormat); } } var didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; var warningKey = componentName + "." + callerName; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } error2("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function(publicInstance) { return false; }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueForceUpdate: function(publicInstance, callback, callerName) { warnNoop(publicInstance, "forceUpdate"); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { warnNoop(publicInstance, "replaceState"); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function(publicInstance, partialState, callback, callerName) { warnNoop(publicInstance, "setState"); } }; var assign = Object.assign; var emptyObject = {}; { Object.freeze(emptyObject); } function Component(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } Component.prototype.isReactComponent = {}; Component.prototype.setState = function(partialState, callback) { if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) { throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); } this.updater.enqueueSetState(this, partialState, callback, "setState"); }; Component.prototype.forceUpdate = function(callback) { this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); }; { var deprecatedAPIs = { isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."], replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."] }; var defineDeprecationWarning = function(methodName, info) { Object.defineProperty(Component.prototype, methodName, { get: function() { warn2("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); return void 0; } }); }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() { } ComponentDummy.prototype = Component.prototype; function PureComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); pureComponentPrototype.constructor = PureComponent; assign(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; function createRef() { var refObject = { current: null }; { Object.seal(refObject); } return refObject; } var isArrayImpl = Array.isArray; function isArray(a) { return isArrayImpl(a); } function typeName(value) { { var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; return type; } } function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value) { return "" + value; } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error2("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); return testStringCoercion(value); } } } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ""; return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; } function getContextName(type) { return type.displayName || "Context"; } function getComponentNameFromType(type) { if (type == null) { return null; } { if (typeof type.tag === "number") { error2("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); } } if (typeof type === "function") { return type.displayName || type.name || null; } if (typeof type === "string") { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return "Fragment"; case REACT_PORTAL_TYPE: return "Portal"; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return "StrictMode"; case REACT_SUSPENSE_TYPE: return "Suspense"; case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } if (typeof type === "object") { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: var context = type; return getContextName(context) + ".Consumer"; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._context) + ".Provider"; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, "ForwardRef"); case REACT_MEMO_TYPE: var outerName = type.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || "Memo"; case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return getComponentNameFromType(init2(payload)); } catch (x) { return null; } } } } return null; } var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, "ref")) { var getter = Object.getOwnPropertyDescriptor(config, "ref").get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== void 0; } function hasValidKey(config) { { if (hasOwnProperty.call(config, "key")) { var getter = Object.getOwnPropertyDescriptor(config, "key").get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== void 0; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function() { { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error2("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); } } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, "key", { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function() { { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error2("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); } } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, "ref", { get: warnAboutAccessingRef, configurable: true }); } function warnIfStringRefCannotBeAutoConverted(config) { { if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error2('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); didWarnAboutStringRefs[componentName] = true; } } } } var ReactElement = function(type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type, key, ref, props, // Record the component responsible for creating this element. _owner: owner }; { element._store = {}; Object.defineProperty(element._store, "validated", { configurable: false, enumerable: false, writable: true, value: false }); Object.defineProperty(element, "_self", { configurable: false, enumerable: false, writable: false, value: self }); Object.defineProperty(element, "_source", { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; function createElement(type, config, children) { var propName; var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; { warnIfStringRefCannotBeAutoConverted(config); } } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = "" + config.key; } self = config.__self === void 0 ? null : config.__self; source = config.__source === void 0 ? null : config.__source; for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } { if (key || ref) { var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } function cloneAndReplaceKey(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; } function cloneElement(element, config, children) { if (element === null || element === void 0) { throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); } var propName; var props = assign({}, element.props); var key = element.key; var ref = element.ref; var self = element._self; var source = element._source; var owner = element._owner; if (config != null) { if (hasValidRef(config)) { ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = "" + config.key; } var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === void 0 && defaultProps !== void 0) { props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); } function isValidElement(object) { return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } var SEPARATOR = "."; var SUBSEPARATOR = ":"; function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { "=": "=0", ":": "=2" }; var escapedString = key.replace(escapeRegex, function(match) { return escaperLookup[match]; }); return "$" + escapedString; } var didWarnAboutMaps = false; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return text.replace(userProvidedKeyEscapeRegex, "$&/"); } function getElementKey(element, index) { if (typeof element === "object" && element !== null && element.key != null) { { checkKeyStringCoercion(element.key); } return escape("" + element.key); } return index.toString(36); } function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { var type = typeof children; if (type === "undefined" || type === "boolean") { children = null; } var invokeCallback = false; if (children === null) { invokeCallback = true; } else { switch (type) { case "string": case "number": invokeCallback = true; break; case "object": switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { var _child = children; var mappedChild = callback(_child); var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; if (isArray(mappedChild)) { var escapedChildKey = ""; if (childKey != null) { escapedChildKey = escapeUserProvidedKey(childKey) + "/"; } mapIntoArray(mappedChild, array, escapedChildKey, "", function(c) { return c; }); } else if (mappedChild != null) { if (isValidElement(mappedChild)) { { if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { checkKeyStringCoercion(mappedChild.key); } } mappedChild = cloneAndReplaceKey( mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children escapedPrefix + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? ( // $FlowFixMe Flow incorrectly thinks existing element's key can be a number // eslint-disable-next-line react-internal/safe-string-coercion escapeUserProvidedKey("" + mappedChild.key) + "/" ) : "") + childKey ); } array.push(mappedChild); } return 1; } var child; var nextName; var subtreeCount = 0; var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getElementKey(child, i); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === "function") { var iterableChildren = children; { if (iteratorFn === iterableChildren.entries) { if (!didWarnAboutMaps) { warn2("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); } didWarnAboutMaps = true; } } var iterator = iteratorFn.call(iterableChildren); var step; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getElementKey(child, ii++); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else if (type === "object") { var childrenString = String(children); throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); } } return subtreeCount; } function mapChildren2(children, func, context) { if (children == null) { return children; } var result = []; var count = 0; mapIntoArray(children, result, "", "", function(child) { return func.call(context, child, count++); }); return result; } function countChildren(children) { var n = 0; mapChildren2(children, function() { n++; }); return n; } function forEachChildren(children, forEachFunc, forEachContext) { mapChildren2(children, function() { forEachFunc.apply(this, arguments); }, forEachContext); } function toArray(children) { return mapChildren2(children, function(child) { return child; }) || []; } function onlyChild(children) { if (!isValidElement(children)) { throw new Error("React.Children.only expected to receive a single React element child."); } return children; } function createContext(defaultValue) { var context = { $$typeof: REACT_CONTEXT_TYPE, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: null, Consumer: null, // Add these to use same hidden class in VM as ServerContext _defaultValue: null, _globalName: null }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }; var hasWarnedAboutUsingNestedContextConsumers = false; var hasWarnedAboutUsingConsumerProvider = false; var hasWarnedAboutDisplayNameOnConsumer = false; { var Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context }; Object.defineProperties(Consumer, { Provider: { get: function() { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; error2("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); } return context.Provider; }, set: function(_Provider) { context.Provider = _Provider; } }, _currentValue: { get: function() { return context._currentValue; }, set: function(_currentValue) { context._currentValue = _currentValue; } }, _currentValue2: { get: function() { return context._currentValue2; }, set: function(_currentValue2) { context._currentValue2 = _currentValue2; } }, _threadCount: { get: function() { return context._threadCount; }, set: function(_threadCount) { context._threadCount = _threadCount; } }, Consumer: { get: function() { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; error2("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); } return context.Consumer; } }, displayName: { get: function() { return context.displayName; }, set: function(displayName) { if (!hasWarnedAboutDisplayNameOnConsumer) { warn2("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); hasWarnedAboutDisplayNameOnConsumer = true; } } } }); context.Consumer = Consumer; } { context._currentRenderer = null; context._currentRenderer2 = null; } return context; } var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; function lazyInitializer(payload) { if (payload._status === Uninitialized) { var ctor = payload._result; var thenable = ctor(); thenable.then(function(moduleObject2) { if (payload._status === Pending || payload._status === Uninitialized) { var resolved = payload; resolved._status = Resolved; resolved._result = moduleObject2; } }, function(error3) { if (payload._status === Pending || payload._status === Uninitialized) { var rejected = payload; rejected._status = Rejected; rejected._result = error3; } }); if (payload._status === Uninitialized) { var pending = payload; pending._status = Pending; pending._result = thenable; } } if (payload._status === Resolved) { var moduleObject = payload._result; { if (moduleObject === void 0) { error2("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject); } } { if (!("default" in moduleObject)) { error2("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); } } return moduleObject.default; } else { throw payload._result; } } function lazy(ctor) { var payload = { // We use these fields to store the result. _status: Uninitialized, _result: ctor }; var lazyType = { $$typeof: REACT_LAZY_TYPE, _payload: payload, _init: lazyInitializer }; { var defaultProps; var propTypes; Object.defineProperties(lazyType, { defaultProps: { configurable: true, get: function() { return defaultProps; }, set: function(newDefaultProps) { error2("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); defaultProps = newDefaultProps; Object.defineProperty(lazyType, "defaultProps", { enumerable: true }); } }, propTypes: { configurable: true, get: function() { return propTypes; }, set: function(newPropTypes) { error2("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); propTypes = newPropTypes; Object.defineProperty(lazyType, "propTypes", { enumerable: true }); } } }); } return lazyType; } function forwardRef(render2) { { if (render2 != null && render2.$$typeof === REACT_MEMO_TYPE) { error2("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); } else if (typeof render2 !== "function") { error2("forwardRef requires a render function but was given %s.", render2 === null ? "null" : typeof render2); } else { if (render2.length !== 0 && render2.length !== 2) { error2("forwardRef render functions accept exactly two parameters: props and ref. %s", render2.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); } } if (render2 != null) { if (render2.defaultProps != null || render2.propTypes != null) { error2("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); } } } var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render: render2 }; { var ownName; Object.defineProperty(elementType, "displayName", { enumerable: false, configurable: true, get: function() { return ownName; }, set: function(name) { ownName = name; if (!render2.name && !render2.displayName) { render2.displayName = name; } } }); } return elementType; } var REACT_MODULE_REFERENCE; { REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); } function isValidElementType(type) { if (typeof type === "string" || typeof type === "function") { return true; } if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { return true; } if (typeof type === "object" && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) { return true; } } return false; } function memo(type, compare) { { if (!isValidElementType(type)) { error2("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type); } } var elementType = { $$typeof: REACT_MEMO_TYPE, type, compare: compare === void 0 ? null : compare }; { var ownName; Object.defineProperty(elementType, "displayName", { enumerable: false, configurable: true, get: function() { return ownName; }, set: function(name) { ownName = name; if (!type.name && !type.displayName) { type.displayName = name; } } }); } return elementType; } function resolveDispatcher() { var dispatcher = ReactCurrentDispatcher.current; { if (dispatcher === null) { error2("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); } } return dispatcher; } function useContext(Context) { var dispatcher = resolveDispatcher(); { if (Context._context !== void 0) { var realContext = Context._context; if (realContext.Consumer === Context) { error2("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); } else if (realContext.Provider === Context) { error2("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); } } } return dispatcher.useContext(Context); } function useState(initialState) { var dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); } function useReducer(reducer, initialArg, init2) { var dispatcher = resolveDispatcher(); return dispatcher.useReducer(reducer, initialArg, init2); } function useRef(initialValue) { var dispatcher = resolveDispatcher(); return dispatcher.useRef(initialValue); } function useEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useEffect(create, deps); } function useInsertionEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useInsertionEffect(create, deps); } function useLayoutEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useLayoutEffect(create, deps); } function useCallback(callback, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useCallback(callback, deps); } function useMemo(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useMemo(create, deps); } function useImperativeHandle(ref, create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useImperativeHandle(ref, create, deps); } function useDebugValue(value, formatterFn) { { var dispatcher = resolveDispatcher(); return dispatcher.useDebugValue(value, formatterFn); } } function useTransition() { var dispatcher = resolveDispatcher(); return dispatcher.useTransition(); } function useDeferredValue(value) { var dispatcher = resolveDispatcher(); return dispatcher.useDeferredValue(value); } function useId() { var dispatcher = resolveDispatcher(); return dispatcher.useId(); } function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { var dispatcher = resolveDispatcher(); return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); } var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() { } disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { var props = { configurable: true, enumerable: true, writable: true }; Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); } if (disabledDepth < 0) { error2("disabledDepth fell below zero. This is a bug in React. Please file an issue."); } } } var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === void 0) { try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ""; } } return "\n" + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { if (!fn || reentry) { return ""; } { var frame = componentFrameCache.get(fn); if (frame !== void 0) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = void 0; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = null; disableLogs(); } try { if (construct) { var Fake = function() { throw Error(); }; Object.defineProperty(Fake.prototype, "props", { set: function() { throw Error(); } }); if (typeof Reflect === "object" && Reflect.construct) { try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { if (sample && control && typeof sample.stack === "string") { var sampleLines = sample.stack.split("\n"); var controlLines = control.stack.split("\n"); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { c--; } for (; s >= 1 && c >= 0; s--, c--) { if (sampleLines[s] !== controlLines[c]) { if (s !== 1 || c !== 1) { do { s--; c--; if (c < 0 || sampleLines[s] !== controlLines[c]) { var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); if (fn.displayName && _frame.includes("")) { _frame = _frame.replace("", fn.displayName); } { if (typeof fn === "function") { componentFrameCache.set(fn, _frame); } } return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher$1.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } var name = fn ? fn.displayName || fn.name : ""; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; { if (typeof fn === "function") { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component2) { var prototype = Component2.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ""; } if (typeof type === "function") { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === "string") { return describeBuiltInComponentFrame(type); } switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame("Suspense"); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame("SuspenseList"); } if (typeof type === "object") { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return describeUnknownElementTypeFrameInDEV(init2(payload), source, ownerFn); } catch (x) { } } } } return ""; } var loggedTypeFailures = {}; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { var has = Function.call.bind(hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; try { if (typeof typeSpecs[typeSpecName] !== "function") { var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); err.name = "Invariant Violation"; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error2("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error2("Failed %s type: %s", location, error$1.message); setCurrentlyValidatingElement(null); } } } } } function setCurrentlyValidatingElement$1(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); setExtraStackFrame(stack); } else { setExtraStackFrame(null); } } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = getComponentNameFromType(ReactCurrentOwner.current.type); if (name) { return "\n\nCheck the render method of `" + name + "`."; } } return ""; } function getSourceInfoErrorAddendum(source) { if (source !== void 0) { var fileName = source.fileName.replace(/^.*[\\\/]/, ""); var lineNumber = source.lineNumber; return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; } return ""; } function getSourceInfoErrorAddendumForProps(elementProps) { if (elementProps !== null && elementProps !== void 0) { return getSourceInfoErrorAddendum(elementProps.__source); } return ""; } var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; var childOwner = ""; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; } { setCurrentlyValidatingElement$1(element); error2('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } function validateChildKeys(node, parentType) { if (typeof node !== "object") { return; } if (isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === "function") { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } function validatePropTypes(element) { { var type = element.type; if (type === null || type === void 0 || typeof type === "string") { return; } var propTypes; if (typeof type === "function") { propTypes = type.propTypes; } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { var name = getComponentNameFromType(type); checkPropTypes(propTypes, element.props, "prop", name, element); } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; var _name = getComponentNameFromType(type); error2("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); } if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { error2("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); } } } function validateFragmentProps(fragment) { { var keys2 = Object.keys(fragment.props); for (var i = 0; i < keys2.length; i++) { var key = keys2[i]; if (key !== "children" && key !== "key") { setCurrentlyValidatingElement$1(fragment); error2("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error2("Invalid attribute `ref` supplied to `React.Fragment`."); setCurrentlyValidatingElement$1(null); } } } function createElementWithValidation(type, props, children) { var validType = isValidElementType(type); if (!validType) { var info = ""; if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendumForProps(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = "null"; } else if (isArray(type)) { typeString = "array"; } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; info = " Did you accidentally export a JSX literal instead of a component?"; } else { typeString = typeof type; } { error2("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); } } var element = createElement.apply(this, arguments); if (element == null) { return element; } if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } if (type === REACT_FRAGMENT_TYPE) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } var didWarnAboutDeprecatedCreateFactory = false; function createFactoryWithValidation(type) { var validatedFactory = createElementWithValidation.bind(null, type); validatedFactory.type = type; { if (!didWarnAboutDeprecatedCreateFactory) { didWarnAboutDeprecatedCreateFactory = true; warn2("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); } Object.defineProperty(validatedFactory, "type", { enumerable: false, get: function() { warn2("Factory.type is deprecated. Access the class directly before passing it to createFactory."); Object.defineProperty(this, "type", { value: type }); return type; } }); } return validatedFactory; } function cloneElementWithValidation(element, props, children) { var newElement = cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } function startTransition(scope, options) { var prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = {}; var currentTransition = ReactCurrentBatchConfig.transition; { ReactCurrentBatchConfig.transition._updatedFibers = /* @__PURE__ */ new Set(); } try { scope(); } finally { ReactCurrentBatchConfig.transition = prevTransition; { if (prevTransition === null && currentTransition._updatedFibers) { var updatedFibersCount = currentTransition._updatedFibers.size; if (updatedFibersCount > 10) { warn2("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."); } currentTransition._updatedFibers.clear(); } } } } var didWarnAboutMessageChannel = false; var enqueueTaskImpl = null; function enqueueTask(task) { if (enqueueTaskImpl === null) { try { var requireString = ("require" + Math.random()).slice(0, 7); var nodeRequire = module2 && module2[requireString]; enqueueTaskImpl = nodeRequire.call(module2, "timers").setImmediate; } catch (_err) { enqueueTaskImpl = function(callback) { { if (didWarnAboutMessageChannel === false) { didWarnAboutMessageChannel = true; if (typeof MessageChannel === "undefined") { error2("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."); } } } var channel = new MessageChannel(); channel.port1.onmessage = callback; channel.port2.postMessage(void 0); }; } } return enqueueTaskImpl(task); } var actScopeDepth = 0; var didWarnNoAwaitAct = false; function act(callback) { { var prevActScopeDepth = actScopeDepth; actScopeDepth++; if (ReactCurrentActQueue.current === null) { ReactCurrentActQueue.current = []; } var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; var result; try { ReactCurrentActQueue.isBatchingLegacy = true; result = callback(); if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { var queue = ReactCurrentActQueue.current; if (queue !== null) { ReactCurrentActQueue.didScheduleLegacyUpdate = false; flushActQueue(queue); } } } catch (error3) { popActScope(prevActScopeDepth); throw error3; } finally { ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; } if (result !== null && typeof result === "object" && typeof result.then === "function") { var thenableResult = result; var wasAwaited = false; var thenable = { then: function(resolve, reject) { wasAwaited = true; thenableResult.then(function(returnValue2) { popActScope(prevActScopeDepth); if (actScopeDepth === 0) { recursivelyFlushAsyncActWork(returnValue2, resolve, reject); } else { resolve(returnValue2); } }, function(error3) { popActScope(prevActScopeDepth); reject(error3); }); } }; { if (!didWarnNoAwaitAct && typeof Promise !== "undefined") { Promise.resolve().then(function() { }).then(function() { if (!wasAwaited) { didWarnNoAwaitAct = true; error2("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"); } }); } } return thenable; } else { var returnValue = result; popActScope(prevActScopeDepth); if (actScopeDepth === 0) { var _queue = ReactCurrentActQueue.current; if (_queue !== null) { flushActQueue(_queue); ReactCurrentActQueue.current = null; } var _thenable = { then: function(resolve, reject) { if (ReactCurrentActQueue.current === null) { ReactCurrentActQueue.current = []; recursivelyFlushAsyncActWork(returnValue, resolve, reject); } else { resolve(returnValue); } } }; return _thenable; } else { var _thenable2 = { then: function(resolve, reject) { resolve(returnValue); } }; return _thenable2; } } } } function popActScope(prevActScopeDepth) { { if (prevActScopeDepth !== actScopeDepth - 1) { error2("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "); } actScopeDepth = prevActScopeDepth; } } function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { { var queue = ReactCurrentActQueue.current; if (queue !== null) { try { flushActQueue(queue); enqueueTask(function() { if (queue.length === 0) { ReactCurrentActQueue.current = null; resolve(returnValue); } else { recursivelyFlushAsyncActWork(returnValue, resolve, reject); } }); } catch (error3) { reject(error3); } } else { resolve(returnValue); } } } var isFlushing = false; function flushActQueue(queue) { { if (!isFlushing) { isFlushing = true; var i = 0; try { for (; i < queue.length; i++) { var callback = queue[i]; do { callback = callback(true); } while (callback !== null); } queue.length = 0; } catch (error3) { queue = queue.slice(i + 1); throw error3; } finally { isFlushing = false; } } } } var createElement$1 = createElementWithValidation; var cloneElement$1 = cloneElementWithValidation; var createFactory = createFactoryWithValidation; var Children = { map: mapChildren2, forEach: forEachChildren, count: countChildren, toArray, only: onlyChild }; exports2.Children = Children; exports2.Component = Component; exports2.Fragment = REACT_FRAGMENT_TYPE; exports2.Profiler = REACT_PROFILER_TYPE; exports2.PureComponent = PureComponent; exports2.StrictMode = REACT_STRICT_MODE_TYPE; exports2.Suspense = REACT_SUSPENSE_TYPE; exports2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; exports2.act = act; exports2.cloneElement = cloneElement$1; exports2.createContext = createContext; exports2.createElement = createElement$1; exports2.createFactory = createFactory; exports2.createRef = createRef; exports2.forwardRef = forwardRef; exports2.isValidElement = isValidElement; exports2.lazy = lazy; exports2.memo = memo; exports2.startTransition = startTransition; exports2.unstable_act = act; exports2.useCallback = useCallback; exports2.useContext = useContext; exports2.useDebugValue = useDebugValue; exports2.useDeferredValue = useDeferredValue; exports2.useEffect = useEffect; exports2.useId = useId; exports2.useImperativeHandle = useImperativeHandle; exports2.useInsertionEffect = useInsertionEffect; exports2.useLayoutEffect = useLayoutEffect; exports2.useMemo = useMemo; exports2.useReducer = useReducer; exports2.useRef = useRef; exports2.useState = useState; exports2.useSyncExternalStore = useSyncExternalStore; exports2.useTransition = useTransition; exports2.version = ReactVersion; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } })(react_development, react_development.exports); return react_development.exports; } if (process.env.NODE_ENV === "production") { react.exports = requireReact_production_min(); } else { react.exports = requireReact_development(); } var reactExports = react.exports; const React = /* @__PURE__ */ getDefaultExportFromCjs(reactExports); let readFromCache; let addToCache; if (typeof WeakMap != "undefined") { let cache = /* @__PURE__ */ new WeakMap(); readFromCache = (key) => cache.get(key); addToCache = (key, value) => { cache.set(key, value); return value; }; } else { const cache = []; const cacheSize = 10; let cachePos = 0; readFromCache = (key) => { for (let i = 0; i < cache.length; i += 2) if (cache[i] == key) return cache[i + 1]; }; addToCache = (key, value) => { if (cachePos == cacheSize) cachePos = 0; cache[cachePos++] = key; return cache[cachePos++] = value; }; } var TableMap = class { constructor(width, height, map2, problems) { this.width = width; this.height = height; this.map = map2; this.problems = problems; } findCell(pos) { for (let i = 0; i < this.map.length; i++) { const curPos = this.map[i]; if (curPos != pos) continue; const left = i % this.width; const top = i / this.width | 0; let right = left + 1; let bottom = top + 1; for (let j = 1; right < this.width && this.map[i + j] == curPos; j++) right++; for (let j = 1; bottom < this.height && this.map[i + this.width * j] == curPos; j++) bottom++; return { left, top, right, bottom }; } throw new RangeError(`No cell with offset ${pos} found`); } colCount(pos) { for (let i = 0; i < this.map.length; i++) if (this.map[i] == pos) return i % this.width; throw new RangeError(`No cell with offset ${pos} found`); } nextCell(pos, axis, dir) { const { left, right, top, bottom } = this.findCell(pos); if (axis == "horiz") { if (dir < 0 ? left == 0 : right == this.width) return null; return this.map[top * this.width + (dir < 0 ? left - 1 : right)]; } else { if (dir < 0 ? top == 0 : bottom == this.height) return null; return this.map[left + this.width * (dir < 0 ? top - 1 : bottom)]; } } rectBetween(a, b) { const { left: leftA, right: rightA, top: topA, bottom: bottomA } = this.findCell(a); const { left: leftB, right: rightB, top: topB, bottom: bottomB } = this.findCell(b); return { left: Math.min(leftA, leftB), top: Math.min(topA, topB), right: Math.max(rightA, rightB), bottom: Math.max(bottomA, bottomB) }; } cellsInRect(rect) { const result = []; const seen = {}; for (let row = rect.top; row < rect.bottom; row++) for (let col = rect.left; col < rect.right; col++) { const index = row * this.width + col; const pos = this.map[index]; if (seen[pos]) continue; seen[pos] = true; if (col == rect.left && col && this.map[index - 1] == pos || row == rect.top && row && this.map[index - this.width] == pos) continue; result.push(pos); } return result; } positionAt(row, col, table) { for (let i = 0, rowStart = 0; ; i++) { const rowEnd = rowStart + table.child(i).nodeSize; if (i == row) { let index = col + row * this.width; const rowEndIndex = (row + 1) * this.width; while (index < rowEndIndex && this.map[index] < rowStart) index++; return index == rowEndIndex ? rowEnd - 1 : this.map[index]; } rowStart = rowEnd; } } static get(table) { return readFromCache(table) || addToCache(table, computeMap(table)); } }; function computeMap(table) { if (table.type.spec.tableRole != "table") throw new RangeError("Not a table node: " + table.type.name); const width = findWidth(table), height = table.childCount; const map2 = []; let mapPos = 0; let problems = null; const colWidths = []; for (let i = 0, e = width * height; i < e; i++) map2[i] = 0; for (let row = 0, pos = 0; row < height; row++) { const rowNode = table.child(row); pos++; for (let i = 0; ; i++) { while (mapPos < map2.length && map2[mapPos] != 0) mapPos++; if (i == rowNode.childCount) break; const cellNode = rowNode.child(i); const { colspan, rowspan, colwidth } = cellNode.attrs; for (let h2 = 0; h2 < rowspan; h2++) { if (h2 + row >= height) { (problems || (problems = [])).push({ type: "overlong_rowspan", pos, n: rowspan - h2 }); break; } const start = mapPos + h2 * width; for (let w = 0; w < colspan; w++) { if (map2[start + w] == 0) map2[start + w] = pos; else (problems || (problems = [])).push({ type: "collision", row, pos, n: colspan - w }); const colW = colwidth && colwidth[w]; if (colW) { const widthIndex = (start + w) % width * 2, prev = colWidths[widthIndex]; if (prev == null || prev != colW && colWidths[widthIndex + 1] == 1) { colWidths[widthIndex] = colW; colWidths[widthIndex + 1] = 1; } else if (prev == colW) colWidths[widthIndex + 1]++; } } } mapPos += colspan; pos += cellNode.nodeSize; } const expectedPos = (row + 1) * width; let missing = 0; while (mapPos < expectedPos) if (map2[mapPos++] == 0) missing++; if (missing) (problems || (problems = [])).push({ type: "missing", row, n: missing }); pos++; } if (width === 0 || height === 0) (problems || (problems = [])).push({ type: "zero_sized" }); const tableMap = new TableMap(width, height, map2, problems); let badWidths = false; for (let i = 0; !badWidths && i < colWidths.length; i += 2) if (colWidths[i] != null && colWidths[i + 1] < height) badWidths = true; if (badWidths) findBadColWidths(tableMap, colWidths, table); return tableMap; } function findWidth(table) { let width = -1; let hasRowSpan = false; for (let row = 0; row < table.childCount; row++) { const rowNode = table.child(row); let rowWidth = 0; if (hasRowSpan) for (let j = 0; j < row; j++) { const prevRow = table.child(j); for (let i = 0; i < prevRow.childCount; i++) { const cell = prevRow.child(i); if (j + cell.attrs.rowspan > row) rowWidth += cell.attrs.colspan; } } for (let i = 0; i < rowNode.childCount; i++) { const cell = rowNode.child(i); rowWidth += cell.attrs.colspan; if (cell.attrs.rowspan > 1) hasRowSpan = true; } if (width == -1) width = rowWidth; else if (width != rowWidth) width = Math.max(width, rowWidth); } return width; } function findBadColWidths(map2, colWidths, table) { if (!map2.problems) map2.problems = []; const seen = {}; for (let i = 0; i < map2.map.length; i++) { const pos = map2.map[i]; if (seen[pos]) continue; seen[pos] = true; const node = table.nodeAt(pos); if (!node) throw new RangeError(`No cell with offset ${pos} found`); let updated = null; const attrs = node.attrs; for (let j = 0; j < attrs.colspan; j++) { const colWidth = colWidths[(i + j) % map2.width * 2]; if (colWidth != null && (!attrs.colwidth || attrs.colwidth[j] != colWidth)) (updated || (updated = freshColWidth(attrs)))[j] = colWidth; } if (updated) map2.problems.unshift({ type: "colwidth mismatch", pos, colwidth: updated }); } } function freshColWidth(attrs) { if (attrs.colwidth) return attrs.colwidth.slice(); const result = []; for (let i = 0; i < attrs.colspan; i++) result.push(0); return result; } function tableNodeTypes(schema) { let result = schema.cached.tableNodeTypes; if (!result) { result = schema.cached.tableNodeTypes = {}; for (const name in schema.nodes) { const type = schema.nodes[name], role = type.spec.tableRole; if (role) result[role] = type; } } return result; } new PluginKey("selectingCells"); function cellAround($pos) { for (let d = $pos.depth - 1; d > 0; d--) if ($pos.node(d).type.spec.tableRole == "row") return $pos.node(0).resolve($pos.before(d + 1)); return null; } function isInTable(state) { const $head = state.selection.$head; for (let d = $head.depth; d > 0; d--) if ($head.node(d).type.spec.tableRole == "row") return true; return false; } function selectionCell(state) { const sel = state.selection; if ("$anchorCell" in sel && sel.$anchorCell) return sel.$anchorCell.pos > sel.$headCell.pos ? sel.$anchorCell : sel.$headCell; else if ("node" in sel && sel.node && sel.node.type.spec.tableRole == "cell") return sel.$anchor; const $cell = cellAround(sel.$head) || cellNear(sel.$head); if ($cell) return $cell; throw new RangeError(`No cell found around position ${sel.head}`); } function cellNear($pos) { for (let after = $pos.nodeAfter, pos = $pos.pos; after; after = after.firstChild, pos++) { const role = after.type.spec.tableRole; if (role == "cell" || role == "header_cell") return $pos.doc.resolve(pos); } for (let before = $pos.nodeBefore, pos = $pos.pos; before; before = before.lastChild, pos--) { const role = before.type.spec.tableRole; if (role == "cell" || role == "header_cell") return $pos.doc.resolve(pos - before.nodeSize); } } function pointsAtCell($pos) { return $pos.parent.type.spec.tableRole == "row" && !!$pos.nodeAfter; } function inSameTable($cellA, $cellB) { return $cellA.depth == $cellB.depth && $cellA.pos >= $cellB.start(-1) && $cellA.pos <= $cellB.end(-1); } function nextCell($pos, axis, dir) { const table = $pos.node(-1); const map2 = TableMap.get(table); const tableStart = $pos.start(-1); const moved = map2.nextCell($pos.pos - tableStart, axis, dir); return moved == null ? null : $pos.node(0).resolve(tableStart + moved); } function removeColSpan(attrs, pos, n = 1) { const result = { ...attrs, colspan: attrs.colspan - n }; if (result.colwidth) { result.colwidth = result.colwidth.slice(); result.colwidth.splice(pos, n); if (!result.colwidth.some((w) => w > 0)) result.colwidth = null; } return result; } var CellSelection = class CellSelection2 extends Selection { constructor($anchorCell, $headCell = $anchorCell) { const table = $anchorCell.node(-1); const map2 = TableMap.get(table); const tableStart = $anchorCell.start(-1); const rect = map2.rectBetween($anchorCell.pos - tableStart, $headCell.pos - tableStart); const doc2 = $anchorCell.node(0); const cells = map2.cellsInRect(rect).filter((p) => p != $headCell.pos - tableStart); cells.unshift($headCell.pos - tableStart); const ranges = cells.map((pos) => { const cell = table.nodeAt(pos); if (!cell) throw new RangeError(`No cell with offset ${pos} found`); const from2 = tableStart + pos + 1; return new SelectionRange(doc2.resolve(from2), doc2.resolve(from2 + cell.content.size)); }); super(ranges[0].$from, ranges[0].$to, ranges); this.$anchorCell = $anchorCell; this.$headCell = $headCell; } map(doc2, mapping) { const $anchorCell = doc2.resolve(mapping.map(this.$anchorCell.pos)); const $headCell = doc2.resolve(mapping.map(this.$headCell.pos)); if (pointsAtCell($anchorCell) && pointsAtCell($headCell) && inSameTable($anchorCell, $headCell)) { const tableChanged = this.$anchorCell.node(-1) != $anchorCell.node(-1); if (tableChanged && this.isRowSelection()) return CellSelection2.rowSelection($anchorCell, $headCell); else if (tableChanged && this.isColSelection()) return CellSelection2.colSelection($anchorCell, $headCell); else return new CellSelection2($anchorCell, $headCell); } return TextSelection.between($anchorCell, $headCell); } content() { const table = this.$anchorCell.node(-1); const map2 = TableMap.get(table); const tableStart = this.$anchorCell.start(-1); const rect = map2.rectBetween(this.$anchorCell.pos - tableStart, this.$headCell.pos - tableStart); const seen = {}; const rows = []; for (let row = rect.top; row < rect.bottom; row++) { const rowContent = []; for (let index = row * map2.width + rect.left, col = rect.left; col < rect.right; col++, index++) { const pos = map2.map[index]; if (seen[pos]) continue; seen[pos] = true; const cellRect = map2.findCell(pos); let cell = table.nodeAt(pos); if (!cell) throw new RangeError(`No cell with offset ${pos} found`); const extraLeft = rect.left - cellRect.left; const extraRight = cellRect.right - rect.right; if (extraLeft > 0 || extraRight > 0) { let attrs = cell.attrs; if (extraLeft > 0) attrs = removeColSpan(attrs, 0, extraLeft); if (extraRight > 0) attrs = removeColSpan(attrs, attrs.colspan - extraRight, extraRight); if (cellRect.left < rect.left) { cell = cell.type.createAndFill(attrs); if (!cell) throw new RangeError(`Could not create cell with attrs ${JSON.stringify(attrs)}`); } else cell = cell.type.create(attrs, cell.content); } if (cellRect.top < rect.top || cellRect.bottom > rect.bottom) { const attrs = { ...cell.attrs, rowspan: Math.min(cellRect.bottom, rect.bottom) - Math.max(cellRect.top, rect.top) }; if (cellRect.top < rect.top) cell = cell.type.createAndFill(attrs); else cell = cell.type.create(attrs, cell.content); } rowContent.push(cell); } rows.push(table.child(row).copy(Fragment.from(rowContent))); } const fragment = this.isColSelection() && this.isRowSelection() ? table : rows; return new Slice(Fragment.from(fragment), 1, 1); } replace(tr2, content = Slice.empty) { const mapFrom = tr2.steps.length, ranges = this.ranges; for (let i = 0; i < ranges.length; i++) { const { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom); tr2.replace(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content); } const sel = Selection.findFrom(tr2.doc.resolve(tr2.mapping.slice(mapFrom).map(this.to)), -1); if (sel) tr2.setSelection(sel); } replaceWith(tr2, node) { this.replace(tr2, new Slice(Fragment.from(node), 0, 0)); } forEachCell(f) { const table = this.$anchorCell.node(-1); const map2 = TableMap.get(table); const tableStart = this.$anchorCell.start(-1); const cells = map2.cellsInRect(map2.rectBetween(this.$anchorCell.pos - tableStart, this.$headCell.pos - tableStart)); for (let i = 0; i < cells.length; i++) f(table.nodeAt(cells[i]), tableStart + cells[i]); } isColSelection() { const anchorTop = this.$anchorCell.index(-1); const headTop = this.$headCell.index(-1); if (Math.min(anchorTop, headTop) > 0) return false; const anchorBottom = anchorTop + this.$anchorCell.nodeAfter.attrs.rowspan; const headBottom = headTop + this.$headCell.nodeAfter.attrs.rowspan; return Math.max(anchorBottom, headBottom) == this.$headCell.node(-1).childCount; } static colSelection($anchorCell, $headCell = $anchorCell) { const table = $anchorCell.node(-1); const map2 = TableMap.get(table); const tableStart = $anchorCell.start(-1); const anchorRect = map2.findCell($anchorCell.pos - tableStart); const headRect = map2.findCell($headCell.pos - tableStart); const doc2 = $anchorCell.node(0); if (anchorRect.top <= headRect.top) { if (anchorRect.top > 0) $anchorCell = doc2.resolve(tableStart + map2.map[anchorRect.left]); if (headRect.bottom < map2.height) $headCell = doc2.resolve(tableStart + map2.map[map2.width * (map2.height - 1) + headRect.right - 1]); } else { if (headRect.top > 0) $headCell = doc2.resolve(tableStart + map2.map[headRect.left]); if (anchorRect.bottom < map2.height) $anchorCell = doc2.resolve(tableStart + map2.map[map2.width * (map2.height - 1) + anchorRect.right - 1]); } return new CellSelection2($anchorCell, $headCell); } isRowSelection() { const table = this.$anchorCell.node(-1); const map2 = TableMap.get(table); const tableStart = this.$anchorCell.start(-1); const anchorLeft = map2.colCount(this.$anchorCell.pos - tableStart); const headLeft = map2.colCount(this.$headCell.pos - tableStart); if (Math.min(anchorLeft, headLeft) > 0) return false; const anchorRight = anchorLeft + this.$anchorCell.nodeAfter.attrs.colspan; const headRight = headLeft + this.$headCell.nodeAfter.attrs.colspan; return Math.max(anchorRight, headRight) == map2.width; } eq(other) { return other instanceof CellSelection2 && other.$anchorCell.pos == this.$anchorCell.pos && other.$headCell.pos == this.$headCell.pos; } static rowSelection($anchorCell, $headCell = $anchorCell) { const table = $anchorCell.node(-1); const map2 = TableMap.get(table); const tableStart = $anchorCell.start(-1); const anchorRect = map2.findCell($anchorCell.pos - tableStart); const headRect = map2.findCell($headCell.pos - tableStart); const doc2 = $anchorCell.node(0); if (anchorRect.left <= headRect.left) { if (anchorRect.left > 0) $anchorCell = doc2.resolve(tableStart + map2.map[anchorRect.top * map2.width]); if (headRect.right < map2.width) $headCell = doc2.resolve(tableStart + map2.map[map2.width * (headRect.top + 1) - 1]); } else { if (headRect.left > 0) $headCell = doc2.resolve(tableStart + map2.map[headRect.top * map2.width]); if (anchorRect.right < map2.width) $anchorCell = doc2.resolve(tableStart + map2.map[map2.width * (anchorRect.top + 1) - 1]); } return new CellSelection2($anchorCell, $headCell); } toJSON() { return { type: "cell", anchor: this.$anchorCell.pos, head: this.$headCell.pos }; } static fromJSON(doc2, json) { return new CellSelection2(doc2.resolve(json.anchor), doc2.resolve(json.head)); } static create(doc2, anchorCell, headCell = anchorCell) { return new CellSelection2(doc2.resolve(anchorCell), doc2.resolve(headCell)); } getBookmark() { return new CellBookmark(this.$anchorCell.pos, this.$headCell.pos); } }; CellSelection.prototype.visible = false; Selection.jsonID("cell", CellSelection); var CellBookmark = class CellBookmark2 { constructor(anchor, head) { this.anchor = anchor; this.head = head; } map(mapping) { return new CellBookmark2(mapping.map(this.anchor), mapping.map(this.head)); } resolve(doc2) { const $anchorCell = doc2.resolve(this.anchor), $headCell = doc2.resolve(this.head); if ($anchorCell.parent.type.spec.tableRole == "row" && $headCell.parent.type.spec.tableRole == "row" && $anchorCell.index() < $anchorCell.parent.childCount && $headCell.index() < $headCell.parent.childCount && inSameTable($anchorCell, $headCell)) return new CellSelection($anchorCell, $headCell); else return Selection.near($headCell, 1); } }; new PluginKey("fix-tables"); function selectedRect(state) { const sel = state.selection; const $pos = selectionCell(state); const table = $pos.node(-1); const tableStart = $pos.start(-1); const map2 = TableMap.get(table); return { ...sel instanceof CellSelection ? map2.rectBetween(sel.$anchorCell.pos - tableStart, sel.$headCell.pos - tableStart) : map2.findCell($pos.pos - tableStart), tableStart, map: map2, table }; } function deprecated_toggleHeader(type) { return function(state, dispatch) { if (!isInTable(state)) return false; if (dispatch) { const types = tableNodeTypes(state.schema); const rect = selectedRect(state), tr2 = state.tr; const cells = rect.map.cellsInRect(type == "column" ? { left: rect.left, top: 0, right: rect.right, bottom: rect.map.height } : type == "row" ? { left: 0, top: rect.top, right: rect.map.width, bottom: rect.bottom } : rect); const nodes = cells.map((pos) => rect.table.nodeAt(pos)); for (let i = 0; i < cells.length; i++) if (nodes[i].type == types.header_cell) tr2.setNodeMarkup(rect.tableStart + cells[i], types.cell, nodes[i].attrs); if (tr2.steps.length === 0) for (let i = 0; i < cells.length; i++) tr2.setNodeMarkup(rect.tableStart + cells[i], types.header_cell, nodes[i].attrs); dispatch(tr2); } return true; }; } function isHeaderEnabledByType(type, rect, types) { const cellPositions = rect.map.cellsInRect({ left: 0, top: 0, right: type == "row" ? rect.map.width : 1, bottom: type == "column" ? rect.map.height : 1 }); for (let i = 0; i < cellPositions.length; i++) { const cell = rect.table.nodeAt(cellPositions[i]); if (cell && cell.type !== types.header_cell) return false; } return true; } function toggleHeader(type, options) { options = options || { useDeprecatedLogic: false }; if (options.useDeprecatedLogic) return deprecated_toggleHeader(type); return function(state, dispatch) { if (!isInTable(state)) return false; if (dispatch) { const types = tableNodeTypes(state.schema); const rect = selectedRect(state), tr2 = state.tr; const isHeaderRowEnabled = isHeaderEnabledByType("row", rect, types); const isHeaderColumnEnabled = isHeaderEnabledByType("column", rect, types); const selectionStartsAt = (type === "column" ? isHeaderRowEnabled : type === "row" ? isHeaderColumnEnabled : false) ? 1 : 0; const cellsRect = type == "column" ? { left: 0, top: selectionStartsAt, right: 1, bottom: rect.map.height } : type == "row" ? { left: selectionStartsAt, top: 0, right: rect.map.width, bottom: 1 } : rect; const newType = type == "column" ? isHeaderColumnEnabled ? types.cell : types.header_cell : type == "row" ? isHeaderRowEnabled ? types.cell : types.header_cell : types.cell; rect.map.cellsInRect(cellsRect).forEach((relativeCellPos) => { const cellPos = relativeCellPos + rect.tableStart; const cell = tr2.doc.nodeAt(cellPos); if (cell) tr2.setNodeMarkup(cellPos, newType, cell.attrs); }); dispatch(tr2); } return true; }; } toggleHeader("row", { useDeprecatedLogic: true }); toggleHeader("column", { useDeprecatedLogic: true }); toggleHeader("cell", { useDeprecatedLogic: true }); function deleteCellSelection(state, dispatch) { const sel = state.selection; if (!(sel instanceof CellSelection)) return false; if (dispatch) { const tr2 = state.tr; const baseContent = tableNodeTypes(state.schema).cell.createAndFill().content; sel.forEachCell((cell, pos) => { if (!cell.content.eq(baseContent)) tr2.replace(tr2.mapping.map(pos + 1), tr2.mapping.map(pos + cell.nodeSize - 1), new Slice(baseContent, 0, 0)); }); if (tr2.docChanged) dispatch(tr2); } return true; } keydownHandler$1({ ArrowLeft: arrow$1("horiz", -1), ArrowRight: arrow$1("horiz", 1), ArrowUp: arrow$1("vert", -1), ArrowDown: arrow$1("vert", 1), "Shift-ArrowLeft": shiftArrow("horiz", -1), "Shift-ArrowRight": shiftArrow("horiz", 1), "Shift-ArrowUp": shiftArrow("vert", -1), "Shift-ArrowDown": shiftArrow("vert", 1), Backspace: deleteCellSelection, "Mod-Backspace": deleteCellSelection, Delete: deleteCellSelection, "Mod-Delete": deleteCellSelection }); function maybeSetSelection(state, dispatch, selection) { if (selection.eq(state.selection)) return false; if (dispatch) dispatch(state.tr.setSelection(selection).scrollIntoView()); return true; } function arrow$1(axis, dir) { return (state, dispatch, view) => { if (!view) return false; const sel = state.selection; if (sel instanceof CellSelection) return maybeSetSelection(state, dispatch, Selection.near(sel.$headCell, dir)); if (axis != "horiz" && !sel.empty) return false; const end = atEndOfCell(view, axis, dir); if (end == null) return false; if (axis == "horiz") return maybeSetSelection(state, dispatch, Selection.near(state.doc.resolve(sel.head + dir), dir)); else { const $cell = state.doc.resolve(end); const $next = nextCell($cell, axis, dir); let newSel; if ($next) newSel = Selection.near($next, 1); else if (dir < 0) newSel = Selection.near(state.doc.resolve($cell.before(-1)), -1); else newSel = Selection.near(state.doc.resolve($cell.after(-1)), 1); return maybeSetSelection(state, dispatch, newSel); } }; } function shiftArrow(axis, dir) { return (state, dispatch, view) => { if (!view) return false; const sel = state.selection; let cellSel; if (sel instanceof CellSelection) cellSel = sel; else { const end = atEndOfCell(view, axis, dir); if (end == null) return false; cellSel = new CellSelection(state.doc.resolve(end)); } const $head = nextCell(cellSel.$headCell, axis, dir); if (!$head) return false; return maybeSetSelection(state, dispatch, new CellSelection(cellSel.$anchorCell, $head)); }; } function atEndOfCell(view, axis, dir) { if (!(view.state.selection instanceof TextSelection)) return null; const { $head } = view.state.selection; for (let d = $head.depth - 1; d >= 0; d--) { const parent = $head.node(d); if ((dir < 0 ? $head.index(d) : $head.indexAfter(d)) != (dir < 0 ? 0 : parent.childCount)) return null; if (parent.type.spec.tableRole == "cell" || parent.type.spec.tableRole == "header_cell") { const cellPos = $head.before(d); const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left"; return view.endOfTextblock(dirStr) ? cellPos : null; } } return null; } new PluginKey("tableColumnResizing"); function getAttributes(nodeOrMark, extensionAttributes, onlyRenderedAttributes) { const nodeOrMarkAttributes = nodeOrMark.attrs; if (!nodeOrMarkAttributes) return {}; return extensionAttributes.filter((item) => { if (item.type !== (typeof nodeOrMark.type === "string" ? nodeOrMark.type : nodeOrMark.type.name)) return false; return item.attribute.rendered; }).map((item) => { if (!item.attribute.renderHTML) return { [item.name]: item.name in nodeOrMarkAttributes ? nodeOrMarkAttributes[item.name] : item.attribute.default }; return item.attribute.renderHTML(nodeOrMarkAttributes) || { [item.name]: item.name in nodeOrMarkAttributes ? nodeOrMarkAttributes[item.name] : item.attribute.default }; }).reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {}); } function getHTMLAttributes(nodeOrMark, extensionAttributes) { return getAttributes(nodeOrMark, extensionAttributes); } function TiptapStaticRenderer(renderComponent, { nodeMapping, markMapping, unhandledNode, unhandledMark }) { return function renderContent2({ content, parent }) { var _content$type$name, _content$type, _nodeMapping$nodeType; const nodeType = typeof content.type === "string" ? content.type : (_content$type$name = (_content$type = content.type) === null || _content$type === void 0 ? void 0 : _content$type.name) !== null && _content$type$name !== void 0 ? _content$type$name : ""; const NodeHandler = (_nodeMapping$nodeType = nodeMapping[nodeType]) !== null && _nodeMapping$nodeType !== void 0 ? _nodeMapping$nodeType : unhandledNode; if (!NodeHandler) throw new Error(`missing handler for node type ${nodeType}`); const nodeContent = renderComponent({ component: NodeHandler, props: { node: content, parent, renderElement: renderContent2, get children() { const children = []; if (content.content) content.content.forEach((child) => { children.push(renderContent2({ content: child, parent: content })); }); return children; } } }); return content.marks ? content.marks.reduce((acc, mark) => { var _markMapping$markType; const markType = typeof mark.type === "string" ? mark.type : mark.type.name; const MarkHandler = (_markMapping$markType = markMapping[markType]) !== null && _markMapping$markType !== void 0 ? _markMapping$markType : unhandledMark; if (!MarkHandler) throw new Error(`missing handler for mark type ${markType}`); return renderComponent({ component: MarkHandler, props: { mark, parent, node: content, children: acc } }); }, nodeContent) : nodeContent; }; } function renderJSONContentToString(options) { return TiptapStaticRenderer((ctx) => { return ctx.component(ctx.props); }, options); } function escapeHTML(value) { return value.replace(/&/g, "&").replace(//g, ">"); } function escapeHTMLAttribute(value) { return escapeHTML(value).replace(/"/g, """); } function serializeAttrsToHTMLString(attrs) { const output = Object.entries(attrs || {}).filter(([, value]) => value != null).map(([key, value]) => `${key.split(" ").at(-1)}="${escapeHTMLAttribute(String(value))}"`).join(" "); return output ? ` ${output}` : ""; } function serializeChildrenToHTMLString(children) { return [].concat(children || "").filter(Boolean).join(""); } function applyStaticEditorOptionsToExtensions(extensions$1, options) { if (!(options === null || options === void 0 ? void 0 : options.textDirection)) return extensions$1; return [extensions_exports.TextDirection.configure({ direction: options.textDirection }), ...extensions$1]; } function mapNodeExtensionToReactNode(domOutputSpecToElement, extension, extensionAttributes, options) { const context = { name: extension.name, options: extension.options, storage: extension.storage, parent: extension.parent }; const renderToHTML = getExtensionField(extension, "renderHTML", context); if (!renderToHTML) { if (options === null || options === void 0 ? void 0 : options.unhandledNode) return [extension.name, options.unhandledNode]; return [extension.name, () => { throw new Error(`[tiptap error]: Node ${extension.name} cannot be rendered, it is missing a "renderToHTML" method, please implement it or override the corresponding "nodeMapping" method to have a custom rendering`); }]; } return [extension.name, ({ node, children }) => { try { return domOutputSpecToElement(renderToHTML({ node, HTMLAttributes: getHTMLAttributes(node, extensionAttributes) }))(children); } catch (e) { throw new Error(`[tiptap error]: Node ${extension.name} cannot be rendered, it's "renderToHTML" method threw an error: ${e.message}`, { cause: e }); } }]; } function mapMarkExtensionToReactNode(domOutputSpecToElement, extension, extensionAttributes, options) { const context = { name: extension.name, options: extension.options, storage: extension.storage, parent: extension.parent }; const renderToHTML = getExtensionField(extension, "renderHTML", context); if (!renderToHTML) { if (options === null || options === void 0 ? void 0 : options.unhandledMark) return [extension.name, options.unhandledMark]; return [extension.name, () => { throw new Error(`Node ${extension.name} cannot be rendered, it is missing a "renderToHTML" method`); }]; } return [extension.name, ({ mark, children }) => { try { return domOutputSpecToElement(renderToHTML({ mark, HTMLAttributes: getHTMLAttributes(mark, extensionAttributes) }))(children); } catch (e) { throw new Error(`[tiptap error]: Mark ${extension.name} cannot be rendered, it's "renderToHTML" method threw an error: ${e.message}`, { cause: e }); } }]; } const UNHANDLED_NODE_TYPE = "__tiptapUnhandledNode__"; const UNHANDLED_MARK_TYPE = "__tiptapUnhandledMark__"; const ORIGINAL_TYPE_ATTR = "__originalType"; const ORIGINAL_ATTRS_ATTR = "__originalAttrs"; const placeholderAttrs = { [ORIGINAL_TYPE_ATTR]: { default: "" }, [ORIGINAL_ATTRS_ATTR]: { default: {} } }; function hasUnknownType(content, schema) { let found2 = false; const visit = (node) => { var _node$marks, _node$content; if (found2) return; if (node.type && !(node.type in schema.nodes)) found2 = true; (_node$marks = node.marks) === null || _node$marks === void 0 || _node$marks.forEach((mark) => { if (mark.type && !(mark.type in schema.marks)) found2 = true; }); (_node$content = node.content) === null || _node$content === void 0 || _node$content.forEach(visit); }; visit(content); return found2; } function substituteUnknownTypes(content, schema, options) { const canSubstituteNode = Boolean(options === null || options === void 0 ? void 0 : options.unhandledNode); const canSubstituteMark = Boolean(options === null || options === void 0 ? void 0 : options.unhandledMark); const substituteMark = (mark) => { var _mark$attrs; return canSubstituteMark && !(mark.type in schema.marks) ? { type: UNHANDLED_MARK_TYPE, attrs: { [ORIGINAL_TYPE_ATTR]: mark.type, [ORIGINAL_ATTRS_ATTR]: (_mark$attrs = mark.attrs) !== null && _mark$attrs !== void 0 ? _mark$attrs : {} } } : mark; }; const isUnknownNode = (node) => canSubstituteNode && node.type != null && !(node.type in schema.nodes); const toPlaceholder = (node, rewritten) => { var _node$attrs; return { ...rewritten, type: UNHANDLED_NODE_TYPE, attrs: { [ORIGINAL_TYPE_ATTR]: node.type, [ORIGINAL_ATTRS_ATTR]: (_node$attrs = node.attrs) !== null && _node$attrs !== void 0 ? _node$attrs : {} } }; }; const substituteNode = (node) => { var _node$marks2, _node$content2; const rewritten = { ...node, marks: (_node$marks2 = node.marks) === null || _node$marks2 === void 0 ? void 0 : _node$marks2.map(substituteMark), content: (_node$content2 = node.content) === null || _node$content2 === void 0 ? void 0 : _node$content2.map(substituteNode) }; return isUnknownNode(node) ? toPlaceholder(node, rewritten) : rewritten; }; return substituteNode(content); } function withPlaceholderTypes(schema) { return new Schema({ topNode: schema.spec.topNode, nodes: schema.spec.nodes.addToEnd(UNHANDLED_NODE_TYPE, { attrs: placeholderAttrs }), marks: schema.spec.marks.addToEnd(UNHANDLED_MARK_TYPE, { attrs: placeholderAttrs }) }); } function resolveRenderContent(content, extensions, options) { if (content instanceof Node$1) return content; const schema = getSchemaByResolvedExtensions(extensions); if (!hasUnknownType(content, schema)) return Node$1.fromJSON(schema, content); return Node$1.fromJSON(withPlaceholderTypes(schema), substituteUnknownTypes(content, schema, options)); } function unwrapPlaceholderJSON(json) { return json.type === UNHANDLED_NODE_TYPE || json.type === UNHANDLED_MARK_TYPE ? { ...json, type: json.attrs[ORIGINAL_TYPE_ATTR], attrs: json.attrs[ORIGINAL_ATTRS_ATTR] } : json; } function restoreOriginalJSON(json) { var _node$marks3, _node$content3; const node = unwrapPlaceholderJSON(json); return { ...node, marks: (_node$marks3 = node.marks) === null || _node$marks3 === void 0 ? void 0 : _node$marks3.map((mark) => unwrapPlaceholderJSON(mark)), content: (_node$content3 = node.content) === null || _node$content3 === void 0 ? void 0 : _node$content3.map(restoreOriginalJSON) }; } function withOriginalIdentity(target) { const overrides = Object.assign(/* @__PURE__ */ Object.create(null), { type: { name: target.attrs[ORIGINAL_TYPE_ATTR] }, attrs: target.attrs[ORIGINAL_ATTRS_ATTR], toJSON: () => restoreOriginalJSON(target.toJSON()) }); return new Proxy(target, { get(node, prop) { const override = overrides[prop]; if (override !== void 0) return override; const value = node[prop]; return typeof value === "function" ? value.bind(node) : value; } }); } function placeholderNodeRenderer(unhandledNode) { return (props) => unhandledNode({ ...props, node: withOriginalIdentity(props.node) }); } function placeholderMarkRenderer(unhandledMark) { return (props) => unhandledMark({ ...props, mark: withOriginalIdentity(props.mark) }); } function renderToElement({ renderer, domOutputSpecToElement, mapDefinedTypes, content, extensions, options }) { extensions = resolveExtensions(extensions); const extensionAttributes = getAttributesFromExtensions(extensions); const { nodeExtensions, markExtensions } = splitExtensions(extensions); const { unhandledNode, unhandledMark, nodeMapping: userNodeMapping, markMapping: userMarkMapping } = options !== null && options !== void 0 ? options : {}; content = resolveRenderContent(content, extensions, options); return renderer({ ...options, nodeMapping: { ...Object.fromEntries(nodeExtensions.filter((e) => { if (e.name in mapDefinedTypes) return false; if (userNodeMapping) return !(e.name in userNodeMapping); return true; }).map((nodeExtension) => mapNodeExtensionToReactNode(domOutputSpecToElement, nodeExtension, extensionAttributes, options))), ...mapDefinedTypes, ...userNodeMapping, ...unhandledNode ? { [UNHANDLED_NODE_TYPE]: placeholderNodeRenderer(unhandledNode) } : {} }, markMapping: { ...Object.fromEntries(markExtensions.filter((e) => { if (userMarkMapping) return !(e.name in userMarkMapping); return true; }).map((mark) => mapMarkExtensionToReactNode(domOutputSpecToElement, mark, extensionAttributes, options))), ...userMarkMapping, ...unhandledMark ? { [UNHANDLED_MARK_TYPE]: placeholderMarkRenderer(unhandledMark) } : {} } })({ content }); } const NON_SELF_CLOSING_TAGS = /* @__PURE__ */ new Set([ "iframe", "script", "style", "title", "textarea", "div", "span", "a", "button" ]); function domOutputSpecToHTMLString(content) { if (typeof content === "string") return () => escapeHTML(content); if (typeof content === "object" && "length" in content) { const [_tag, attrs, children, ...rest] = content; let tag = _tag; const parts = tag.split(" "); if (parts.length > 1) tag = `${parts[1]} xmlns="${parts[0]}"`; if (attrs === void 0) return () => `<${tag}/>`; if (attrs === 0) return (child) => `<${tag}>${serializeChildrenToHTMLString(child)}`; if (typeof attrs === "object") { if (Array.isArray(attrs)) { if (children === void 0) return (child) => `<${tag}>${domOutputSpecToHTMLString(attrs)(child)}`; if (children === 0) return (child) => `<${tag}>${domOutputSpecToHTMLString(attrs)(child)}`; return (child) => `<${tag}>${domOutputSpecToHTMLString(attrs)(child)}${[children].concat(rest).map((a) => domOutputSpecToHTMLString(a)(child))}`; } if (children === void 0) { if (NON_SELF_CLOSING_TAGS.has(tag)) return () => `<${tag}${serializeAttrsToHTMLString(attrs)}>`; return () => `<${tag}${serializeAttrsToHTMLString(attrs)}/>`; } if (children === 0) return (child) => `<${tag}${serializeAttrsToHTMLString(attrs)}>${serializeChildrenToHTMLString(child)}`; return (child) => `<${tag}${serializeAttrsToHTMLString(attrs)}>${[children].concat(rest).map((a) => domOutputSpecToHTMLString(a)(child)).join("")}`; } } throw new Error("[tiptap error]: Unsupported DomOutputSpec type, check the `renderHTML` method output or implement a node mapping", { cause: content }); } function renderToHTMLString({ content, extensions, staticEditorOptions, options }) { return renderToElement({ renderer: renderJSONContentToString, domOutputSpecToElement: domOutputSpecToHTMLString, mapDefinedTypes: { doc: ({ children }) => serializeChildrenToHTMLString(children), text: ({ node }) => { var _node$text; return escapeHTML((_node$text = node.text) !== null && _node$text !== void 0 ? _node$text : ""); } }, content, extensions: applyStaticEditorOptionsToExtensions(extensions, staticEditorOptions), options }); } var jsxRuntime = { exports: {} }; var reactJsxRuntime_production_min = {}; /** * @license React * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredReactJsxRuntime_production_min; function requireReactJsxRuntime_production_min() { if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min; hasRequiredReactJsxRuntime_production_min = 1; var f = reactExports, k = Symbol.for("react.element"), l = Symbol.for("react.fragment"), m = Object.prototype.hasOwnProperty, n = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p = { key: true, ref: true, __self: true, __source: true }; function q(c, a, g) { var b, d = {}, e = null, h2 = null; void 0 !== g && (e = "" + g); void 0 !== a.key && (e = "" + a.key); void 0 !== a.ref && (h2 = a.ref); for (b in a) m.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d[b] && (d[b] = a[b]); return { $$typeof: k, type: c, key: e, ref: h2, props: d, _owner: n.current }; } reactJsxRuntime_production_min.Fragment = l; reactJsxRuntime_production_min.jsx = q; reactJsxRuntime_production_min.jsxs = q; return reactJsxRuntime_production_min; } var reactJsxRuntime_development = {}; /** * @license React * react-jsx-runtime.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredReactJsxRuntime_development; function requireReactJsxRuntime_development() { if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development; hasRequiredReactJsxRuntime_development = 1; if (process.env.NODE_ENV !== "production") { (function() { var React2 = reactExports; var REACT_ELEMENT_TYPE = Symbol.for("react.element"); var REACT_PORTAL_TYPE = Symbol.for("react.portal"); var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); var REACT_CONTEXT_TYPE = Symbol.for("react.context"); var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); var REACT_MEMO_TYPE = Symbol.for("react.memo"); var REACT_LAZY_TYPE = Symbol.for("react.lazy"); var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== "object") { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === "function") { return maybeIterator; } return null; } var ReactSharedInternals = React2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; function error2(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning("error", format, args); } } } function printWarning(level, format, args) { { var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame2.getStackAddendum(); if (stack !== "") { format += "%s"; args = args.concat([stack]); } var argsWithFormat = args.map(function(item) { return String(item); }); argsWithFormat.unshift("Warning: " + format); Function.prototype.apply.call(console[level], console, argsWithFormat); } } var enableScopeAPI = false; var enableCacheElement = false; var enableTransitionTracing = false; var enableLegacyHidden = false; var enableDebugTracing = false; var REACT_MODULE_REFERENCE; { REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); } function isValidElementType(type) { if (typeof type === "string" || typeof type === "function") { return true; } if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { return true; } if (typeof type === "object" && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) { return true; } } return false; } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ""; return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; } function getContextName(type) { return type.displayName || "Context"; } function getComponentNameFromType(type) { if (type == null) { return null; } { if (typeof type.tag === "number") { error2("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); } } if (typeof type === "function") { return type.displayName || type.name || null; } if (typeof type === "string") { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return "Fragment"; case REACT_PORTAL_TYPE: return "Portal"; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return "StrictMode"; case REACT_SUSPENSE_TYPE: return "Suspense"; case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } if (typeof type === "object") { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: var context = type; return getContextName(context) + ".Consumer"; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._context) + ".Provider"; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, "ForwardRef"); case REACT_MEMO_TYPE: var outerName = type.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || "Memo"; case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return getComponentNameFromType(init2(payload)); } catch (x) { return null; } } } } return null; } var assign = Object.assign; var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() { } disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { var props = { configurable: true, enumerable: true, writable: true }; Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); } if (disabledDepth < 0) { error2("disabledDepth fell below zero. This is a bug in React. Please file an issue."); } } } var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === void 0) { try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ""; } } return "\n" + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { if (!fn || reentry) { return ""; } { var frame = componentFrameCache.get(fn); if (frame !== void 0) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = void 0; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = null; disableLogs(); } try { if (construct) { var Fake = function() { throw Error(); }; Object.defineProperty(Fake.prototype, "props", { set: function() { throw Error(); } }); if (typeof Reflect === "object" && Reflect.construct) { try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { if (sample && control && typeof sample.stack === "string") { var sampleLines = sample.stack.split("\n"); var controlLines = control.stack.split("\n"); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { c--; } for (; s >= 1 && c >= 0; s--, c--) { if (sampleLines[s] !== controlLines[c]) { if (s !== 1 || c !== 1) { do { s--; c--; if (c < 0 || sampleLines[s] !== controlLines[c]) { var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); if (fn.displayName && _frame.includes("")) { _frame = _frame.replace("", fn.displayName); } { if (typeof fn === "function") { componentFrameCache.set(fn, _frame); } } return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } var name = fn ? fn.displayName || fn.name : ""; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; { if (typeof fn === "function") { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ""; } if (typeof type === "function") { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === "string") { return describeBuiltInComponentFrame(type); } switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame("Suspense"); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame("SuspenseList"); } if (typeof type === "object") { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return describeUnknownElementTypeFrameInDEV(init2(payload), source, ownerFn); } catch (x) { } } } } return ""; } var hasOwnProperty = Object.prototype.hasOwnProperty; var loggedTypeFailures = {}; var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { var has = Function.call.bind(hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; try { if (typeof typeSpecs[typeSpecName] !== "function") { var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); err.name = "Invariant Violation"; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error2("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error2("Failed %s type: %s", location, error$1.message); setCurrentlyValidatingElement(null); } } } } } var isArrayImpl = Array.isArray; function isArray(a) { return isArrayImpl(a); } function typeName(value) { { var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; return type; } } function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value) { return "" + value; } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error2("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); return testStringCoercion(value); } } } var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown; var specialPropRefWarningShown; function hasValidRef(config) { { if (hasOwnProperty.call(config, "ref")) { var getter = Object.getOwnPropertyDescriptor(config, "ref").get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== void 0; } function hasValidKey(config) { { if (hasOwnProperty.call(config, "key")) { var getter = Object.getOwnPropertyDescriptor(config, "key").get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== void 0; } function warnIfStringRefCannotBeAutoConverted(config, self) { { if (typeof config.ref === "string" && ReactCurrentOwner.current && self) ; } } function defineKeyPropWarningGetter(props, displayName) { { var warnAboutAccessingKey = function() { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error2("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, "key", { get: warnAboutAccessingKey, configurable: true }); } } function defineRefPropWarningGetter(props, displayName) { { var warnAboutAccessingRef = function() { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error2("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, "ref", { get: warnAboutAccessingRef, configurable: true }); } } var ReactElement = function(type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type, key, ref, props, // Record the component responsible for creating this element. _owner: owner }; { element._store = {}; Object.defineProperty(element._store, "validated", { configurable: false, enumerable: false, writable: true, value: false }); Object.defineProperty(element, "_self", { configurable: false, enumerable: false, writable: false, value: self }); Object.defineProperty(element, "_source", { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; function jsxDEV(type, config, maybeKey, source, self) { { var propName; var props = {}; var key = null; var ref = null; if (maybeKey !== void 0) { { checkKeyStringCoercion(maybeKey); } key = "" + maybeKey; } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = "" + config.key; } if (hasValidRef(config)) { ref = config.ref; warnIfStringRefCannotBeAutoConverted(config, self); } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } if (key || ref) { var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } } var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement$1(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } function isValidElement(object) { { return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } } function getDeclarationErrorAddendum() { { if (ReactCurrentOwner$1.current) { var name = getComponentNameFromType(ReactCurrentOwner$1.current.type); if (name) { return "\n\nCheck the render method of `" + name + "`."; } } return ""; } } function getSourceInfoErrorAddendum(source) { { return ""; } } var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } } function validateExplicitKey(element, parentType) { { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; var childOwner = ""; if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; } setCurrentlyValidatingElement$1(element); error2('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } function validateChildKeys(node, parentType) { { if (typeof node !== "object") { return; } if (isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === "function") { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } } function validatePropTypes(element) { { var type = element.type; if (type === null || type === void 0 || typeof type === "string") { return; } var propTypes; if (typeof type === "function") { propTypes = type.propTypes; } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { var name = getComponentNameFromType(type); checkPropTypes(propTypes, element.props, "prop", name, element); } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; var _name = getComponentNameFromType(type); error2("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); } if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { error2("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); } } } function validateFragmentProps(fragment) { { var keys2 = Object.keys(fragment.props); for (var i = 0; i < keys2.length; i++) { var key = keys2[i]; if (key !== "children" && key !== "key") { setCurrentlyValidatingElement$1(fragment); error2("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error2("Invalid attribute `ref` supplied to `React.Fragment`."); setCurrentlyValidatingElement$1(null); } } } var didWarnAboutKeySpread = {}; function jsxWithValidation(type, props, key, isStaticChildren, source, self) { { var validType = isValidElementType(type); if (!validType) { var info = ""; if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendum(); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = "null"; } else if (isArray(type)) { typeString = "array"; } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; info = " Did you accidentally export a JSX literal instead of a component?"; } else { typeString = typeof type; } error2("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); } var element = jsxDEV(type, props, key, source, self); if (element == null) { return element; } if (validType) { var children = props.children; if (children !== void 0) { if (isStaticChildren) { if (isArray(children)) { for (var i = 0; i < children.length; i++) { validateChildKeys(children[i], type); } if (Object.freeze) { Object.freeze(children); } } else { error2("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."); } } else { validateChildKeys(children, type); } } } { if (hasOwnProperty.call(props, "key")) { var componentName = getComponentNameFromType(type); var keys2 = Object.keys(props).filter(function(k) { return k !== "key"; }); var beforeExample = keys2.length > 0 ? "{key: someKey, " + keys2.join(": ..., ") + ": ...}" : "{key: someKey}"; if (!didWarnAboutKeySpread[componentName + beforeExample]) { var afterExample = keys2.length > 0 ? "{" + keys2.join(": ..., ") + ": ...}" : "{}"; error2('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName); didWarnAboutKeySpread[componentName + beforeExample] = true; } } } if (type === REACT_FRAGMENT_TYPE) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } } function jsxWithValidationStatic(type, props, key) { { return jsxWithValidation(type, props, key, true); } } function jsxWithValidationDynamic(type, props, key) { { return jsxWithValidation(type, props, key, false); } } var jsx = jsxWithValidationDynamic; var jsxs = jsxWithValidationStatic; reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE; reactJsxRuntime_development.jsx = jsx; reactJsxRuntime_development.jsxs = jsxs; })(); } return reactJsxRuntime_development; } if (process.env.NODE_ENV === "production") { jsxRuntime.exports = requireReactJsxRuntime_production_min(); } else { jsxRuntime.exports = requireReactJsxRuntime_development(); } var jsxRuntimeExports = jsxRuntime.exports; var reactDom = { exports: {} }; var reactDom_production_min = {}; var scheduler = { exports: {} }; var scheduler_production_min = {}; /** * @license React * scheduler.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredScheduler_production_min; function requireScheduler_production_min() { if (hasRequiredScheduler_production_min) return scheduler_production_min; hasRequiredScheduler_production_min = 1; (function(exports2) { function f(a, b) { var c = a.length; a.push(b); a: for (; 0 < c; ) { var d = c - 1 >>> 1, e = a[d]; if (0 < g(e, b)) a[d] = b, a[c] = e, c = d; else break a; } } function h2(a) { return 0 === a.length ? null : a[0]; } function k(a) { if (0 === a.length) return null; var b = a[0], c = a.pop(); if (c !== b) { a[0] = c; a: for (var d = 0, e = a.length, w = e >>> 1; d < w; ) { var m = 2 * (d + 1) - 1, C = a[m], n = m + 1, x = a[n]; if (0 > g(C, c)) n < e && 0 > g(x, C) ? (a[d] = x, a[n] = c, d = n) : (a[d] = C, a[m] = c, d = m); else if (n < e && 0 > g(x, c)) a[d] = x, a[n] = c, d = n; else break a; } } return b; } function g(a, b) { var c = a.sortIndex - b.sortIndex; return 0 !== c ? c : a.id - b.id; } if ("object" === typeof performance && "function" === typeof performance.now) { var l = performance; exports2.unstable_now = function() { return l.now(); }; } else { var p = Date, q = p.now(); exports2.unstable_now = function() { return p.now() - q; }; } var r = [], t = [], u = 1, v = null, y = 3, z = false, A = false, B = false, D = "function" === typeof setTimeout ? setTimeout : null, E = "function" === typeof clearTimeout ? clearTimeout : null, F = "undefined" !== typeof setImmediate ? setImmediate : null; "undefined" !== typeof navigator && void 0 !== navigator.scheduling && void 0 !== navigator.scheduling.isInputPending && navigator.scheduling.isInputPending.bind(navigator.scheduling); function G(a) { for (var b = h2(t); null !== b; ) { if (null === b.callback) k(t); else if (b.startTime <= a) k(t), b.sortIndex = b.expirationTime, f(r, b); else break; b = h2(t); } } function H(a) { B = false; G(a); if (!A) if (null !== h2(r)) A = true, I(J); else { var b = h2(t); null !== b && K(H, b.startTime - a); } } function J(a, b) { A = false; B && (B = false, E(L), L = -1); z = true; var c = y; try { G(b); for (v = h2(r); null !== v && (!(v.expirationTime > b) || a && !M()); ) { var d = v.callback; if ("function" === typeof d) { v.callback = null; y = v.priorityLevel; var e = d(v.expirationTime <= b); b = exports2.unstable_now(); "function" === typeof e ? v.callback = e : v === h2(r) && k(r); G(b); } else k(r); v = h2(r); } if (null !== v) var w = true; else { var m = h2(t); null !== m && K(H, m.startTime - b); w = false; } return w; } finally { v = null, y = c, z = false; } } var N = false, O = null, L = -1, P = 5, Q = -1; function M() { return exports2.unstable_now() - Q < P ? false : true; } function R() { if (null !== O) { var a = exports2.unstable_now(); Q = a; var b = true; try { b = O(true, a); } finally { b ? S() : (N = false, O = null); } } else N = false; } var S; if ("function" === typeof F) S = function() { F(R); }; else if ("undefined" !== typeof MessageChannel) { var T = new MessageChannel(), U = T.port2; T.port1.onmessage = R; S = function() { U.postMessage(null); }; } else S = function() { D(R, 0); }; function I(a) { O = a; N || (N = true, S()); } function K(a, b) { L = D(function() { a(exports2.unstable_now()); }, b); } exports2.unstable_IdlePriority = 5; exports2.unstable_ImmediatePriority = 1; exports2.unstable_LowPriority = 4; exports2.unstable_NormalPriority = 3; exports2.unstable_Profiling = null; exports2.unstable_UserBlockingPriority = 2; exports2.unstable_cancelCallback = function(a) { a.callback = null; }; exports2.unstable_continueExecution = function() { A || z || (A = true, I(J)); }; exports2.unstable_forceFrameRate = function(a) { 0 > a || 125 < a ? console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported") : P = 0 < a ? Math.floor(1e3 / a) : 5; }; exports2.unstable_getCurrentPriorityLevel = function() { return y; }; exports2.unstable_getFirstCallbackNode = function() { return h2(r); }; exports2.unstable_next = function(a) { switch (y) { case 1: case 2: case 3: var b = 3; break; default: b = y; } var c = y; y = b; try { return a(); } finally { y = c; } }; exports2.unstable_pauseExecution = function() { }; exports2.unstable_requestPaint = function() { }; exports2.unstable_runWithPriority = function(a, b) { switch (a) { case 1: case 2: case 3: case 4: case 5: break; default: a = 3; } var c = y; y = a; try { return b(); } finally { y = c; } }; exports2.unstable_scheduleCallback = function(a, b, c) { var d = exports2.unstable_now(); "object" === typeof c && null !== c ? (c = c.delay, c = "number" === typeof c && 0 < c ? d + c : d) : c = d; switch (a) { case 1: var e = -1; break; case 2: e = 250; break; case 5: e = 1073741823; break; case 4: e = 1e4; break; default: e = 5e3; } e = c + e; a = { id: u++, callback: b, priorityLevel: a, startTime: c, expirationTime: e, sortIndex: -1 }; c > d ? (a.sortIndex = c, f(t, a), null === h2(r) && a === h2(t) && (B ? (E(L), L = -1) : B = true, K(H, c - d))) : (a.sortIndex = e, f(r, a), A || z || (A = true, I(J))); return a; }; exports2.unstable_shouldYield = M; exports2.unstable_wrapCallback = function(a) { var b = y; return function() { var c = y; y = b; try { return a.apply(this, arguments); } finally { y = c; } }; }; })(scheduler_production_min); return scheduler_production_min; } var scheduler_development = {}; /** * @license React * scheduler.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredScheduler_development; function requireScheduler_development() { if (hasRequiredScheduler_development) return scheduler_development; hasRequiredScheduler_development = 1; (function(exports2) { if (process.env.NODE_ENV !== "production") { (function() { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var enableProfiling = false; var frameYieldMs = 5; function push(heap, node) { var index = heap.length; heap.push(node); siftUp(heap, node, index); } function peek(heap) { return heap.length === 0 ? null : heap[0]; } function pop(heap) { if (heap.length === 0) { return null; } var first2 = heap[0]; var last = heap.pop(); if (last !== first2) { heap[0] = last; siftDown(heap, last, 0); } return first2; } function siftUp(heap, node, i) { var index = i; while (index > 0) { var parentIndex = index - 1 >>> 1; var parent = heap[parentIndex]; if (compare(parent, node) > 0) { heap[parentIndex] = node; heap[index] = parent; index = parentIndex; } else { return; } } } function siftDown(heap, node, i) { var index = i; var length = heap.length; var halfLength = length >>> 1; while (index < halfLength) { var leftIndex = (index + 1) * 2 - 1; var left = heap[leftIndex]; var rightIndex = leftIndex + 1; var right = heap[rightIndex]; if (compare(left, node) < 0) { if (rightIndex < length && compare(right, left) < 0) { heap[index] = right; heap[rightIndex] = node; index = rightIndex; } else { heap[index] = left; heap[leftIndex] = node; index = leftIndex; } } else if (rightIndex < length && compare(right, node) < 0) { heap[index] = right; heap[rightIndex] = node; index = rightIndex; } else { return; } } } function compare(a, b) { var diff = a.sortIndex - b.sortIndex; return diff !== 0 ? diff : a.id - b.id; } var ImmediatePriority = 1; var UserBlockingPriority = 2; var NormalPriority = 3; var LowPriority = 4; var IdlePriority = 5; function markTaskErrored(task, ms) { } var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function"; if (hasPerformanceNow) { var localPerformance = performance; exports2.unstable_now = function() { return localPerformance.now(); }; } else { var localDate = Date; var initialTime = localDate.now(); exports2.unstable_now = function() { return localDate.now() - initialTime; }; } var maxSigned31BitInt = 1073741823; var IMMEDIATE_PRIORITY_TIMEOUT = -1; var USER_BLOCKING_PRIORITY_TIMEOUT = 250; var NORMAL_PRIORITY_TIMEOUT = 5e3; var LOW_PRIORITY_TIMEOUT = 1e4; var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; var taskQueue = []; var timerQueue = []; var taskIdCounter = 1; var currentTask = null; var currentPriorityLevel = NormalPriority; var isPerformingWork = false; var isHostCallbackScheduled = false; var isHostTimeoutScheduled = false; var localSetTimeout = typeof setTimeout === "function" ? setTimeout : null; var localClearTimeout = typeof clearTimeout === "function" ? clearTimeout : null; var localSetImmediate = typeof setImmediate !== "undefined" ? setImmediate : null; typeof navigator !== "undefined" && navigator.scheduling !== void 0 && navigator.scheduling.isInputPending !== void 0 ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; function advanceTimers(currentTime) { var timer = peek(timerQueue); while (timer !== null) { if (timer.callback === null) { pop(timerQueue); } else if (timer.startTime <= currentTime) { pop(timerQueue); timer.sortIndex = timer.expirationTime; push(taskQueue, timer); } else { return; } timer = peek(timerQueue); } } function handleTimeout(currentTime) { isHostTimeoutScheduled = false; advanceTimers(currentTime); if (!isHostCallbackScheduled) { if (peek(taskQueue) !== null) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } } } } function flushWork(hasTimeRemaining, initialTime2) { isHostCallbackScheduled = false; if (isHostTimeoutScheduled) { isHostTimeoutScheduled = false; cancelHostTimeout(); } isPerformingWork = true; var previousPriorityLevel = currentPriorityLevel; try { var currentTime; if (enableProfiling) ; else { return workLoop(hasTimeRemaining, initialTime2); } } finally { currentTask = null; currentPriorityLevel = previousPriorityLevel; isPerformingWork = false; } } function workLoop(hasTimeRemaining, initialTime2) { var currentTime = initialTime2; advanceTimers(currentTime); currentTask = peek(taskQueue); while (currentTask !== null && true) { if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { break; } var callback = currentTask.callback; if (typeof callback === "function") { currentTask.callback = null; currentPriorityLevel = currentTask.priorityLevel; var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; var continuationCallback = callback(didUserCallbackTimeout); currentTime = exports2.unstable_now(); if (typeof continuationCallback === "function") { currentTask.callback = continuationCallback; } else { if (currentTask === peek(taskQueue)) { pop(taskQueue); } } advanceTimers(currentTime); } else { pop(taskQueue); } currentTask = peek(taskQueue); } if (currentTask !== null) { return true; } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } return false; } } function unstable_runWithPriority(priorityLevel, eventHandler) { switch (priorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: case LowPriority: case IdlePriority: break; default: priorityLevel = NormalPriority; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_next(eventHandler) { var priorityLevel; switch (currentPriorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: priorityLevel = NormalPriority; break; default: priorityLevel = currentPriorityLevel; break; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_wrapCallback(callback) { var parentPriorityLevel = currentPriorityLevel; return function() { var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = parentPriorityLevel; try { return callback.apply(this, arguments); } finally { currentPriorityLevel = previousPriorityLevel; } }; } function unstable_scheduleCallback(priorityLevel, callback, options) { var currentTime = exports2.unstable_now(); var startTime2; if (typeof options === "object" && options !== null) { var delay = options.delay; if (typeof delay === "number" && delay > 0) { startTime2 = currentTime + delay; } else { startTime2 = currentTime; } } else { startTime2 = currentTime; } var timeout; switch (priorityLevel) { case ImmediatePriority: timeout = IMMEDIATE_PRIORITY_TIMEOUT; break; case UserBlockingPriority: timeout = USER_BLOCKING_PRIORITY_TIMEOUT; break; case IdlePriority: timeout = IDLE_PRIORITY_TIMEOUT; break; case LowPriority: timeout = LOW_PRIORITY_TIMEOUT; break; case NormalPriority: default: timeout = NORMAL_PRIORITY_TIMEOUT; break; } var expirationTime = startTime2 + timeout; var newTask = { id: taskIdCounter++, callback, priorityLevel, startTime: startTime2, expirationTime, sortIndex: -1 }; if (startTime2 > currentTime) { newTask.sortIndex = startTime2; push(timerQueue, newTask); if (peek(taskQueue) === null && newTask === peek(timerQueue)) { if (isHostTimeoutScheduled) { cancelHostTimeout(); } else { isHostTimeoutScheduled = true; } requestHostTimeout(handleTimeout, startTime2 - currentTime); } } else { newTask.sortIndex = expirationTime; push(taskQueue, newTask); if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } return newTask; } function unstable_pauseExecution() { } function unstable_continueExecution() { if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } function unstable_getFirstCallbackNode() { return peek(taskQueue); } function unstable_cancelCallback(task) { task.callback = null; } function unstable_getCurrentPriorityLevel() { return currentPriorityLevel; } var isMessageLoopRunning = false; var scheduledHostCallback = null; var taskTimeoutID = -1; var frameInterval = frameYieldMs; var startTime = -1; function shouldYieldToHost() { var timeElapsed = exports2.unstable_now() - startTime; if (timeElapsed < frameInterval) { return false; } return true; } function requestPaint() { } function forceFrameRate(fps) { if (fps < 0 || fps > 125) { console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"); return; } if (fps > 0) { frameInterval = Math.floor(1e3 / fps); } else { frameInterval = frameYieldMs; } } var performWorkUntilDeadline = function() { if (scheduledHostCallback !== null) { var currentTime = exports2.unstable_now(); startTime = currentTime; var hasTimeRemaining = true; var hasMoreWork = true; try { hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); } finally { if (hasMoreWork) { schedulePerformWorkUntilDeadline(); } else { isMessageLoopRunning = false; scheduledHostCallback = null; } } } else { isMessageLoopRunning = false; } }; var schedulePerformWorkUntilDeadline; if (typeof localSetImmediate === "function") { schedulePerformWorkUntilDeadline = function() { localSetImmediate(performWorkUntilDeadline); }; } else if (typeof MessageChannel !== "undefined") { var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = performWorkUntilDeadline; schedulePerformWorkUntilDeadline = function() { port.postMessage(null); }; } else { schedulePerformWorkUntilDeadline = function() { localSetTimeout(performWorkUntilDeadline, 0); }; } function requestHostCallback(callback) { scheduledHostCallback = callback; if (!isMessageLoopRunning) { isMessageLoopRunning = true; schedulePerformWorkUntilDeadline(); } } function requestHostTimeout(callback, ms) { taskTimeoutID = localSetTimeout(function() { callback(exports2.unstable_now()); }, ms); } function cancelHostTimeout() { localClearTimeout(taskTimeoutID); taskTimeoutID = -1; } var unstable_requestPaint = requestPaint; var unstable_Profiling = null; exports2.unstable_IdlePriority = IdlePriority; exports2.unstable_ImmediatePriority = ImmediatePriority; exports2.unstable_LowPriority = LowPriority; exports2.unstable_NormalPriority = NormalPriority; exports2.unstable_Profiling = unstable_Profiling; exports2.unstable_UserBlockingPriority = UserBlockingPriority; exports2.unstable_cancelCallback = unstable_cancelCallback; exports2.unstable_continueExecution = unstable_continueExecution; exports2.unstable_forceFrameRate = forceFrameRate; exports2.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; exports2.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; exports2.unstable_next = unstable_next; exports2.unstable_pauseExecution = unstable_pauseExecution; exports2.unstable_requestPaint = unstable_requestPaint; exports2.unstable_runWithPriority = unstable_runWithPriority; exports2.unstable_scheduleCallback = unstable_scheduleCallback; exports2.unstable_shouldYield = shouldYieldToHost; exports2.unstable_wrapCallback = unstable_wrapCallback; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } })(scheduler_development); return scheduler_development; } var hasRequiredScheduler; function requireScheduler() { if (hasRequiredScheduler) return scheduler.exports; hasRequiredScheduler = 1; if (process.env.NODE_ENV === "production") { scheduler.exports = requireScheduler_production_min(); } else { scheduler.exports = requireScheduler_development(); } return scheduler.exports; } /** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredReactDom_production_min; function requireReactDom_production_min() { if (hasRequiredReactDom_production_min) return reactDom_production_min; hasRequiredReactDom_production_min = 1; var aa = reactExports, ca = requireScheduler(); function p(a) { for (var b = "https://reactjs.org/docs/error-decoder.html?invariant=" + a, c = 1; c < arguments.length; c++) b += "&args[]=" + encodeURIComponent(arguments[c]); return "Minified React error #" + a + "; visit " + b + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings."; } var da = /* @__PURE__ */ new Set(), ea = {}; function fa(a, b) { ha(a, b); ha(a + "Capture", b); } function ha(a, b) { ea[a] = b; for (a = 0; a < b.length; a++) da.add(b[a]); } var ia = !("undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement), ja = Object.prototype.hasOwnProperty, ka = /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, la = {}, ma = {}; function oa(a) { if (ja.call(ma, a)) return true; if (ja.call(la, a)) return false; if (ka.test(a)) return ma[a] = true; la[a] = true; return false; } function pa(a, b, c, d) { if (null !== c && 0 === c.type) return false; switch (typeof b) { case "function": case "symbol": return true; case "boolean": if (d) return false; if (null !== c) return !c.acceptsBooleans; a = a.toLowerCase().slice(0, 5); return "data-" !== a && "aria-" !== a; default: return false; } } function qa(a, b, c, d) { if (null === b || "undefined" === typeof b || pa(a, b, c, d)) return true; if (d) return false; if (null !== c) switch (c.type) { case 3: return !b; case 4: return false === b; case 5: return isNaN(b); case 6: return isNaN(b) || 1 > b; } return false; } function v(a, b, c, d, e, f, g) { this.acceptsBooleans = 2 === b || 3 === b || 4 === b; this.attributeName = d; this.attributeNamespace = e; this.mustUseProperty = c; this.propertyName = a; this.type = b; this.sanitizeURL = f; this.removeEmptyString = g; } var z = {}; "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a) { z[a] = new v(a, 0, false, a, null, false, false); }); [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(a) { var b = a[0]; z[b] = new v(b, 1, false, a[1], null, false, false); }); ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(a) { z[a] = new v(a, 2, false, a.toLowerCase(), null, false, false); }); ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(a) { z[a] = new v(a, 2, false, a, null, false, false); }); "allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a) { z[a] = new v(a, 3, false, a.toLowerCase(), null, false, false); }); ["checked", "multiple", "muted", "selected"].forEach(function(a) { z[a] = new v(a, 3, true, a, null, false, false); }); ["capture", "download"].forEach(function(a) { z[a] = new v(a, 4, false, a, null, false, false); }); ["cols", "rows", "size", "span"].forEach(function(a) { z[a] = new v(a, 6, false, a, null, false, false); }); ["rowSpan", "start"].forEach(function(a) { z[a] = new v(a, 5, false, a.toLowerCase(), null, false, false); }); var ra = /[\-:]([a-z])/g; function sa(a) { return a[1].toUpperCase(); } "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a) { var b = a.replace( ra, sa ); z[b] = new v(b, 1, false, a, null, false, false); }); "xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a) { var b = a.replace(ra, sa); z[b] = new v(b, 1, false, a, "http://www.w3.org/1999/xlink", false, false); }); ["xml:base", "xml:lang", "xml:space"].forEach(function(a) { var b = a.replace(ra, sa); z[b] = new v(b, 1, false, a, "http://www.w3.org/XML/1998/namespace", false, false); }); ["tabIndex", "crossOrigin"].forEach(function(a) { z[a] = new v(a, 1, false, a.toLowerCase(), null, false, false); }); z.xlinkHref = new v("xlinkHref", 1, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false); ["src", "href", "action", "formAction"].forEach(function(a) { z[a] = new v(a, 1, false, a.toLowerCase(), null, true, true); }); function ta2(a, b, c, d) { var e = z.hasOwnProperty(b) ? z[b] : null; if (null !== e ? 0 !== e.type : d || !(2 < b.length) || "o" !== b[0] && "O" !== b[0] || "n" !== b[1] && "N" !== b[1]) qa(b, c, e, d) && (c = null), d || null === e ? oa(b) && (null === c ? a.removeAttribute(b) : a.setAttribute(b, "" + c)) : e.mustUseProperty ? a[e.propertyName] = null === c ? 3 === e.type ? false : "" : c : (b = e.attributeName, d = e.attributeNamespace, null === c ? a.removeAttribute(b) : (e = e.type, c = 3 === e || 4 === e && true === c ? "" : "" + c, d ? a.setAttributeNS(d, b, c) : a.setAttribute(b, c))); } var ua = aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, va = Symbol.for("react.element"), wa = Symbol.for("react.portal"), ya = Symbol.for("react.fragment"), za = Symbol.for("react.strict_mode"), Aa = Symbol.for("react.profiler"), Ba = Symbol.for("react.provider"), Ca = Symbol.for("react.context"), Da = Symbol.for("react.forward_ref"), Ea = Symbol.for("react.suspense"), Fa = Symbol.for("react.suspense_list"), Ga = Symbol.for("react.memo"), Ha = Symbol.for("react.lazy"); var Ia = Symbol.for("react.offscreen"); var Ja = Symbol.iterator; function Ka(a) { if (null === a || "object" !== typeof a) return null; a = Ja && a[Ja] || a["@@iterator"]; return "function" === typeof a ? a : null; } var A = Object.assign, La; function Ma(a) { if (void 0 === La) try { throw Error(); } catch (c) { var b = c.stack.trim().match(/\n( *(at )?)/); La = b && b[1] || ""; } return "\n" + La + a; } var Na = false; function Oa(a, b) { if (!a || Na) return ""; Na = true; var c = Error.prepareStackTrace; Error.prepareStackTrace = void 0; try { if (b) if (b = function() { throw Error(); }, Object.defineProperty(b.prototype, "props", { set: function() { throw Error(); } }), "object" === typeof Reflect && Reflect.construct) { try { Reflect.construct(b, []); } catch (l) { var d = l; } Reflect.construct(a, [], b); } else { try { b.call(); } catch (l) { d = l; } a.call(b.prototype); } else { try { throw Error(); } catch (l) { d = l; } a(); } } catch (l) { if (l && d && "string" === typeof l.stack) { for (var e = l.stack.split("\n"), f = d.stack.split("\n"), g = e.length - 1, h2 = f.length - 1; 1 <= g && 0 <= h2 && e[g] !== f[h2]; ) h2--; for (; 1 <= g && 0 <= h2; g--, h2--) if (e[g] !== f[h2]) { if (1 !== g || 1 !== h2) { do if (g--, h2--, 0 > h2 || e[g] !== f[h2]) { var k = "\n" + e[g].replace(" at new ", " at "); a.displayName && k.includes("") && (k = k.replace("", a.displayName)); return k; } while (1 <= g && 0 <= h2); } break; } } } finally { Na = false, Error.prepareStackTrace = c; } return (a = a ? a.displayName || a.name : "") ? Ma(a) : ""; } function Pa(a) { switch (a.tag) { case 5: return Ma(a.type); case 16: return Ma("Lazy"); case 13: return Ma("Suspense"); case 19: return Ma("SuspenseList"); case 0: case 2: case 15: return a = Oa(a.type, false), a; case 11: return a = Oa(a.type.render, false), a; case 1: return a = Oa(a.type, true), a; default: return ""; } } function Qa(a) { if (null == a) return null; if ("function" === typeof a) return a.displayName || a.name || null; if ("string" === typeof a) return a; switch (a) { case ya: return "Fragment"; case wa: return "Portal"; case Aa: return "Profiler"; case za: return "StrictMode"; case Ea: return "Suspense"; case Fa: return "SuspenseList"; } if ("object" === typeof a) switch (a.$$typeof) { case Ca: return (a.displayName || "Context") + ".Consumer"; case Ba: return (a._context.displayName || "Context") + ".Provider"; case Da: var b = a.render; a = a.displayName; a || (a = b.displayName || b.name || "", a = "" !== a ? "ForwardRef(" + a + ")" : "ForwardRef"); return a; case Ga: return b = a.displayName || null, null !== b ? b : Qa(a.type) || "Memo"; case Ha: b = a._payload; a = a._init; try { return Qa(a(b)); } catch (c) { } } return null; } function Ra(a) { var b = a.type; switch (a.tag) { case 24: return "Cache"; case 9: return (b.displayName || "Context") + ".Consumer"; case 10: return (b._context.displayName || "Context") + ".Provider"; case 18: return "DehydratedFragment"; case 11: return a = b.render, a = a.displayName || a.name || "", b.displayName || ("" !== a ? "ForwardRef(" + a + ")" : "ForwardRef"); case 7: return "Fragment"; case 5: return b; case 4: return "Portal"; case 3: return "Root"; case 6: return "Text"; case 16: return Qa(b); case 8: return b === za ? "StrictMode" : "Mode"; case 22: return "Offscreen"; case 12: return "Profiler"; case 21: return "Scope"; case 13: return "Suspense"; case 19: return "SuspenseList"; case 25: return "TracingMarker"; case 1: case 0: case 17: case 2: case 14: case 15: if ("function" === typeof b) return b.displayName || b.name || null; if ("string" === typeof b) return b; } return null; } function Sa(a) { switch (typeof a) { case "boolean": case "number": case "string": case "undefined": return a; case "object": return a; default: return ""; } } function Ta(a) { var b = a.type; return (a = a.nodeName) && "input" === a.toLowerCase() && ("checkbox" === b || "radio" === b); } function Ua(a) { var b = Ta(a) ? "checked" : "value", c = Object.getOwnPropertyDescriptor(a.constructor.prototype, b), d = "" + a[b]; if (!a.hasOwnProperty(b) && "undefined" !== typeof c && "function" === typeof c.get && "function" === typeof c.set) { var e = c.get, f = c.set; Object.defineProperty(a, b, { configurable: true, get: function() { return e.call(this); }, set: function(a2) { d = "" + a2; f.call(this, a2); } }); Object.defineProperty(a, b, { enumerable: c.enumerable }); return { getValue: function() { return d; }, setValue: function(a2) { d = "" + a2; }, stopTracking: function() { a._valueTracker = null; delete a[b]; } }; } } function Va(a) { a._valueTracker || (a._valueTracker = Ua(a)); } function Wa(a) { if (!a) return false; var b = a._valueTracker; if (!b) return true; var c = b.getValue(); var d = ""; a && (d = Ta(a) ? a.checked ? "true" : "false" : a.value); a = d; return a !== c ? (b.setValue(a), true) : false; } function Xa(a) { a = a || ("undefined" !== typeof document ? document : void 0); if ("undefined" === typeof a) return null; try { return a.activeElement || a.body; } catch (b) { return a.body; } } function Ya(a, b) { var c = b.checked; return A({}, b, { defaultChecked: void 0, defaultValue: void 0, value: void 0, checked: null != c ? c : a._wrapperState.initialChecked }); } function Za(a, b) { var c = null == b.defaultValue ? "" : b.defaultValue, d = null != b.checked ? b.checked : b.defaultChecked; c = Sa(null != b.value ? b.value : c); a._wrapperState = { initialChecked: d, initialValue: c, controlled: "checkbox" === b.type || "radio" === b.type ? null != b.checked : null != b.value }; } function ab(a, b) { b = b.checked; null != b && ta2(a, "checked", b, false); } function bb(a, b) { ab(a, b); var c = Sa(b.value), d = b.type; if (null != c) if ("number" === d) { if (0 === c && "" === a.value || a.value != c) a.value = "" + c; } else a.value !== "" + c && (a.value = "" + c); else if ("submit" === d || "reset" === d) { a.removeAttribute("value"); return; } b.hasOwnProperty("value") ? cb(a, b.type, c) : b.hasOwnProperty("defaultValue") && cb(a, b.type, Sa(b.defaultValue)); null == b.checked && null != b.defaultChecked && (a.defaultChecked = !!b.defaultChecked); } function db(a, b, c) { if (b.hasOwnProperty("value") || b.hasOwnProperty("defaultValue")) { var d = b.type; if (!("submit" !== d && "reset" !== d || void 0 !== b.value && null !== b.value)) return; b = "" + a._wrapperState.initialValue; c || b === a.value || (a.value = b); a.defaultValue = b; } c = a.name; "" !== c && (a.name = ""); a.defaultChecked = !!a._wrapperState.initialChecked; "" !== c && (a.name = c); } function cb(a, b, c) { if ("number" !== b || Xa(a.ownerDocument) !== a) null == c ? a.defaultValue = "" + a._wrapperState.initialValue : a.defaultValue !== "" + c && (a.defaultValue = "" + c); } var eb = Array.isArray; function fb(a, b, c, d) { a = a.options; if (b) { b = {}; for (var e = 0; e < c.length; e++) b["$" + c[e]] = true; for (c = 0; c < a.length; c++) e = b.hasOwnProperty("$" + a[c].value), a[c].selected !== e && (a[c].selected = e), e && d && (a[c].defaultSelected = true); } else { c = "" + Sa(c); b = null; for (e = 0; e < a.length; e++) { if (a[e].value === c) { a[e].selected = true; d && (a[e].defaultSelected = true); return; } null !== b || a[e].disabled || (b = a[e]); } null !== b && (b.selected = true); } } function gb(a, b) { if (null != b.dangerouslySetInnerHTML) throw Error(p(91)); return A({}, b, { value: void 0, defaultValue: void 0, children: "" + a._wrapperState.initialValue }); } function hb(a, b) { var c = b.value; if (null == c) { c = b.children; b = b.defaultValue; if (null != c) { if (null != b) throw Error(p(92)); if (eb(c)) { if (1 < c.length) throw Error(p(93)); c = c[0]; } b = c; } null == b && (b = ""); c = b; } a._wrapperState = { initialValue: Sa(c) }; } function ib(a, b) { var c = Sa(b.value), d = Sa(b.defaultValue); null != c && (c = "" + c, c !== a.value && (a.value = c), null == b.defaultValue && a.defaultValue !== c && (a.defaultValue = c)); null != d && (a.defaultValue = "" + d); } function jb(a) { var b = a.textContent; b === a._wrapperState.initialValue && "" !== b && null !== b && (a.value = b); } function kb(a) { switch (a) { case "svg": return "http://www.w3.org/2000/svg"; case "math": return "http://www.w3.org/1998/Math/MathML"; default: return "http://www.w3.org/1999/xhtml"; } } function lb(a, b) { return null == a || "http://www.w3.org/1999/xhtml" === a ? kb(b) : "http://www.w3.org/2000/svg" === a && "foreignObject" === b ? "http://www.w3.org/1999/xhtml" : a; } var mb, nb = function(a) { return "undefined" !== typeof MSApp && MSApp.execUnsafeLocalFunction ? function(b, c, d, e) { MSApp.execUnsafeLocalFunction(function() { return a(b, c, d, e); }); } : a; }(function(a, b) { if ("http://www.w3.org/2000/svg" !== a.namespaceURI || "innerHTML" in a) a.innerHTML = b; else { mb = mb || document.createElement("div"); mb.innerHTML = "" + b.valueOf().toString() + ""; for (b = mb.firstChild; a.firstChild; ) a.removeChild(a.firstChild); for (; b.firstChild; ) a.appendChild(b.firstChild); } }); function ob(a, b) { if (b) { var c = a.firstChild; if (c && c === a.lastChild && 3 === c.nodeType) { c.nodeValue = b; return; } } a.textContent = b; } var pb = { animationIterationCount: true, aspectRatio: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, columns: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridArea: true, gridRow: true, gridRowEnd: true, gridRowSpan: true, gridRowStart: true, gridColumn: true, gridColumnEnd: true, gridColumnSpan: true, gridColumnStart: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }, qb = ["Webkit", "ms", "Moz", "O"]; Object.keys(pb).forEach(function(a) { qb.forEach(function(b) { b = b + a.charAt(0).toUpperCase() + a.substring(1); pb[b] = pb[a]; }); }); function rb(a, b, c) { return null == b || "boolean" === typeof b || "" === b ? "" : c || "number" !== typeof b || 0 === b || pb.hasOwnProperty(a) && pb[a] ? ("" + b).trim() : b + "px"; } function sb(a, b) { a = a.style; for (var c in b) if (b.hasOwnProperty(c)) { var d = 0 === c.indexOf("--"), e = rb(c, b[c], d); "float" === c && (c = "cssFloat"); d ? a.setProperty(c, e) : a[c] = e; } } var tb = A({ menuitem: true }, { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true }); function ub(a, b) { if (b) { if (tb[a] && (null != b.children || null != b.dangerouslySetInnerHTML)) throw Error(p(137, a)); if (null != b.dangerouslySetInnerHTML) { if (null != b.children) throw Error(p(60)); if ("object" !== typeof b.dangerouslySetInnerHTML || !("__html" in b.dangerouslySetInnerHTML)) throw Error(p(61)); } if (null != b.style && "object" !== typeof b.style) throw Error(p(62)); } } function vb(a, b) { if (-1 === a.indexOf("-")) return "string" === typeof b.is; switch (a) { case "annotation-xml": case "color-profile": case "font-face": case "font-face-src": case "font-face-uri": case "font-face-format": case "font-face-name": case "missing-glyph": return false; default: return true; } } var wb = null; function xb(a) { a = a.target || a.srcElement || window; a.correspondingUseElement && (a = a.correspondingUseElement); return 3 === a.nodeType ? a.parentNode : a; } var yb = null, zb = null, Ab = null; function Bb(a) { if (a = Cb(a)) { if ("function" !== typeof yb) throw Error(p(280)); var b = a.stateNode; b && (b = Db(b), yb(a.stateNode, a.type, b)); } } function Eb(a) { zb ? Ab ? Ab.push(a) : Ab = [a] : zb = a; } function Fb() { if (zb) { var a = zb, b = Ab; Ab = zb = null; Bb(a); if (b) for (a = 0; a < b.length; a++) Bb(b[a]); } } function Gb(a, b) { return a(b); } function Hb() { } var Ib = false; function Jb(a, b, c) { if (Ib) return a(b, c); Ib = true; try { return Gb(a, b, c); } finally { if (Ib = false, null !== zb || null !== Ab) Hb(), Fb(); } } function Kb(a, b) { var c = a.stateNode; if (null === c) return null; var d = Db(c); if (null === d) return null; c = d[b]; a: switch (b) { case "onClick": case "onClickCapture": case "onDoubleClick": case "onDoubleClickCapture": case "onMouseDown": case "onMouseDownCapture": case "onMouseMove": case "onMouseMoveCapture": case "onMouseUp": case "onMouseUpCapture": case "onMouseEnter": (d = !d.disabled) || (a = a.type, d = !("button" === a || "input" === a || "select" === a || "textarea" === a)); a = !d; break a; default: a = false; } if (a) return null; if (c && "function" !== typeof c) throw Error(p(231, b, typeof c)); return c; } var Lb = false; if (ia) try { var Mb = {}; Object.defineProperty(Mb, "passive", { get: function() { Lb = true; } }); window.addEventListener("test", Mb, Mb); window.removeEventListener("test", Mb, Mb); } catch (a) { Lb = false; } function Nb(a, b, c, d, e, f, g, h2, k) { var l = Array.prototype.slice.call(arguments, 3); try { b.apply(c, l); } catch (m) { this.onError(m); } } var Ob = false, Pb = null, Qb = false, Rb = null, Sb = { onError: function(a) { Ob = true; Pb = a; } }; function Tb(a, b, c, d, e, f, g, h2, k) { Ob = false; Pb = null; Nb.apply(Sb, arguments); } function Ub(a, b, c, d, e, f, g, h2, k) { Tb.apply(this, arguments); if (Ob) { if (Ob) { var l = Pb; Ob = false; Pb = null; } else throw Error(p(198)); Qb || (Qb = true, Rb = l); } } function Vb(a) { var b = a, c = a; if (a.alternate) for (; b.return; ) b = b.return; else { a = b; do b = a, 0 !== (b.flags & 4098) && (c = b.return), a = b.return; while (a); } return 3 === b.tag ? c : null; } function Wb(a) { if (13 === a.tag) { var b = a.memoizedState; null === b && (a = a.alternate, null !== a && (b = a.memoizedState)); if (null !== b) return b.dehydrated; } return null; } function Xb(a) { if (Vb(a) !== a) throw Error(p(188)); } function Yb(a) { var b = a.alternate; if (!b) { b = Vb(a); if (null === b) throw Error(p(188)); return b !== a ? null : a; } for (var c = a, d = b; ; ) { var e = c.return; if (null === e) break; var f = e.alternate; if (null === f) { d = e.return; if (null !== d) { c = d; continue; } break; } if (e.child === f.child) { for (f = e.child; f; ) { if (f === c) return Xb(e), a; if (f === d) return Xb(e), b; f = f.sibling; } throw Error(p(188)); } if (c.return !== d.return) c = e, d = f; else { for (var g = false, h2 = e.child; h2; ) { if (h2 === c) { g = true; c = e; d = f; break; } if (h2 === d) { g = true; d = e; c = f; break; } h2 = h2.sibling; } if (!g) { for (h2 = f.child; h2; ) { if (h2 === c) { g = true; c = f; d = e; break; } if (h2 === d) { g = true; d = f; c = e; break; } h2 = h2.sibling; } if (!g) throw Error(p(189)); } } if (c.alternate !== d) throw Error(p(190)); } if (3 !== c.tag) throw Error(p(188)); return c.stateNode.current === c ? a : b; } function Zb(a) { a = Yb(a); return null !== a ? $b(a) : null; } function $b(a) { if (5 === a.tag || 6 === a.tag) return a; for (a = a.child; null !== a; ) { var b = $b(a); if (null !== b) return b; a = a.sibling; } return null; } var ac = ca.unstable_scheduleCallback, bc = ca.unstable_cancelCallback, cc = ca.unstable_shouldYield, dc = ca.unstable_requestPaint, B = ca.unstable_now, ec = ca.unstable_getCurrentPriorityLevel, fc = ca.unstable_ImmediatePriority, gc = ca.unstable_UserBlockingPriority, hc = ca.unstable_NormalPriority, ic = ca.unstable_LowPriority, jc = ca.unstable_IdlePriority, kc = null, lc = null; function mc(a) { if (lc && "function" === typeof lc.onCommitFiberRoot) try { lc.onCommitFiberRoot(kc, a, void 0, 128 === (a.current.flags & 128)); } catch (b) { } } var oc = Math.clz32 ? Math.clz32 : nc, pc = Math.log, qc = Math.LN2; function nc(a) { a >>>= 0; return 0 === a ? 32 : 31 - (pc(a) / qc | 0) | 0; } var rc = 64, sc = 4194304; function tc(a) { switch (a & -a) { case 1: return 1; case 2: return 2; case 4: return 4; case 8: return 8; case 16: return 16; case 32: return 32; case 64: case 128: case 256: case 512: case 1024: case 2048: case 4096: case 8192: case 16384: case 32768: case 65536: case 131072: case 262144: case 524288: case 1048576: case 2097152: return a & 4194240; case 4194304: case 8388608: case 16777216: case 33554432: case 67108864: return a & 130023424; case 134217728: return 134217728; case 268435456: return 268435456; case 536870912: return 536870912; case 1073741824: return 1073741824; default: return a; } } function uc(a, b) { var c = a.pendingLanes; if (0 === c) return 0; var d = 0, e = a.suspendedLanes, f = a.pingedLanes, g = c & 268435455; if (0 !== g) { var h2 = g & ~e; 0 !== h2 ? d = tc(h2) : (f &= g, 0 !== f && (d = tc(f))); } else g = c & ~e, 0 !== g ? d = tc(g) : 0 !== f && (d = tc(f)); if (0 === d) return 0; if (0 !== b && b !== d && 0 === (b & e) && (e = d & -d, f = b & -b, e >= f || 16 === e && 0 !== (f & 4194240))) return b; 0 !== (d & 4) && (d |= c & 16); b = a.entangledLanes; if (0 !== b) for (a = a.entanglements, b &= d; 0 < b; ) c = 31 - oc(b), e = 1 << c, d |= a[c], b &= ~e; return d; } function vc(a, b) { switch (a) { case 1: case 2: case 4: return b + 250; case 8: case 16: case 32: case 64: case 128: case 256: case 512: case 1024: case 2048: case 4096: case 8192: case 16384: case 32768: case 65536: case 131072: case 262144: case 524288: case 1048576: case 2097152: return b + 5e3; case 4194304: case 8388608: case 16777216: case 33554432: case 67108864: return -1; case 134217728: case 268435456: case 536870912: case 1073741824: return -1; default: return -1; } } function wc(a, b) { for (var c = a.suspendedLanes, d = a.pingedLanes, e = a.expirationTimes, f = a.pendingLanes; 0 < f; ) { var g = 31 - oc(f), h2 = 1 << g, k = e[g]; if (-1 === k) { if (0 === (h2 & c) || 0 !== (h2 & d)) e[g] = vc(h2, b); } else k <= b && (a.expiredLanes |= h2); f &= ~h2; } } function xc(a) { a = a.pendingLanes & -1073741825; return 0 !== a ? a : a & 1073741824 ? 1073741824 : 0; } function yc() { var a = rc; rc <<= 1; 0 === (rc & 4194240) && (rc = 64); return a; } function zc(a) { for (var b = [], c = 0; 31 > c; c++) b.push(a); return b; } function Ac(a, b, c) { a.pendingLanes |= b; 536870912 !== b && (a.suspendedLanes = 0, a.pingedLanes = 0); a = a.eventTimes; b = 31 - oc(b); a[b] = c; } function Bc(a, b) { var c = a.pendingLanes & ~b; a.pendingLanes = b; a.suspendedLanes = 0; a.pingedLanes = 0; a.expiredLanes &= b; a.mutableReadLanes &= b; a.entangledLanes &= b; b = a.entanglements; var d = a.eventTimes; for (a = a.expirationTimes; 0 < c; ) { var e = 31 - oc(c), f = 1 << e; b[e] = 0; d[e] = -1; a[e] = -1; c &= ~f; } } function Cc(a, b) { var c = a.entangledLanes |= b; for (a = a.entanglements; c; ) { var d = 31 - oc(c), e = 1 << d; e & b | a[d] & b && (a[d] |= b); c &= ~e; } } var C = 0; function Dc(a) { a &= -a; return 1 < a ? 4 < a ? 0 !== (a & 268435455) ? 16 : 536870912 : 4 : 1; } var Ec, Fc, Gc, Hc, Ic, Jc = false, Kc = [], Lc = null, Mc = null, Nc = null, Oc = /* @__PURE__ */ new Map(), Pc = /* @__PURE__ */ new Map(), Qc = [], Rc = "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" "); function Sc(a, b) { switch (a) { case "focusin": case "focusout": Lc = null; break; case "dragenter": case "dragleave": Mc = null; break; case "mouseover": case "mouseout": Nc = null; break; case "pointerover": case "pointerout": Oc.delete(b.pointerId); break; case "gotpointercapture": case "lostpointercapture": Pc.delete(b.pointerId); } } function Tc(a, b, c, d, e, f) { if (null === a || a.nativeEvent !== f) return a = { blockedOn: b, domEventName: c, eventSystemFlags: d, nativeEvent: f, targetContainers: [e] }, null !== b && (b = Cb(b), null !== b && Fc(b)), a; a.eventSystemFlags |= d; b = a.targetContainers; null !== e && -1 === b.indexOf(e) && b.push(e); return a; } function Uc(a, b, c, d, e) { switch (b) { case "focusin": return Lc = Tc(Lc, a, b, c, d, e), true; case "dragenter": return Mc = Tc(Mc, a, b, c, d, e), true; case "mouseover": return Nc = Tc(Nc, a, b, c, d, e), true; case "pointerover": var f = e.pointerId; Oc.set(f, Tc(Oc.get(f) || null, a, b, c, d, e)); return true; case "gotpointercapture": return f = e.pointerId, Pc.set(f, Tc(Pc.get(f) || null, a, b, c, d, e)), true; } return false; } function Vc(a) { var b = Wc(a.target); if (null !== b) { var c = Vb(b); if (null !== c) { if (b = c.tag, 13 === b) { if (b = Wb(c), null !== b) { a.blockedOn = b; Ic(a.priority, function() { Gc(c); }); return; } } else if (3 === b && c.stateNode.current.memoizedState.isDehydrated) { a.blockedOn = 3 === c.tag ? c.stateNode.containerInfo : null; return; } } } a.blockedOn = null; } function Xc(a) { if (null !== a.blockedOn) return false; for (var b = a.targetContainers; 0 < b.length; ) { var c = Yc(a.domEventName, a.eventSystemFlags, b[0], a.nativeEvent); if (null === c) { c = a.nativeEvent; var d = new c.constructor(c.type, c); wb = d; c.target.dispatchEvent(d); wb = null; } else return b = Cb(c), null !== b && Fc(b), a.blockedOn = c, false; b.shift(); } return true; } function Zc(a, b, c) { Xc(a) && c.delete(b); } function $c() { Jc = false; null !== Lc && Xc(Lc) && (Lc = null); null !== Mc && Xc(Mc) && (Mc = null); null !== Nc && Xc(Nc) && (Nc = null); Oc.forEach(Zc); Pc.forEach(Zc); } function ad(a, b) { a.blockedOn === b && (a.blockedOn = null, Jc || (Jc = true, ca.unstable_scheduleCallback(ca.unstable_NormalPriority, $c))); } function bd(a) { function b(b2) { return ad(b2, a); } if (0 < Kc.length) { ad(Kc[0], a); for (var c = 1; c < Kc.length; c++) { var d = Kc[c]; d.blockedOn === a && (d.blockedOn = null); } } null !== Lc && ad(Lc, a); null !== Mc && ad(Mc, a); null !== Nc && ad(Nc, a); Oc.forEach(b); Pc.forEach(b); for (c = 0; c < Qc.length; c++) d = Qc[c], d.blockedOn === a && (d.blockedOn = null); for (; 0 < Qc.length && (c = Qc[0], null === c.blockedOn); ) Vc(c), null === c.blockedOn && Qc.shift(); } var cd = ua.ReactCurrentBatchConfig, dd = true; function ed(a, b, c, d) { var e = C, f = cd.transition; cd.transition = null; try { C = 1, fd(a, b, c, d); } finally { C = e, cd.transition = f; } } function gd(a, b, c, d) { var e = C, f = cd.transition; cd.transition = null; try { C = 4, fd(a, b, c, d); } finally { C = e, cd.transition = f; } } function fd(a, b, c, d) { if (dd) { var e = Yc(a, b, c, d); if (null === e) hd(a, b, d, id, c), Sc(a, d); else if (Uc(e, a, b, c, d)) d.stopPropagation(); else if (Sc(a, d), b & 4 && -1 < Rc.indexOf(a)) { for (; null !== e; ) { var f = Cb(e); null !== f && Ec(f); f = Yc(a, b, c, d); null === f && hd(a, b, d, id, c); if (f === e) break; e = f; } null !== e && d.stopPropagation(); } else hd(a, b, d, null, c); } } var id = null; function Yc(a, b, c, d) { id = null; a = xb(d); a = Wc(a); if (null !== a) if (b = Vb(a), null === b) a = null; else if (c = b.tag, 13 === c) { a = Wb(b); if (null !== a) return a; a = null; } else if (3 === c) { if (b.stateNode.current.memoizedState.isDehydrated) return 3 === b.tag ? b.stateNode.containerInfo : null; a = null; } else b !== a && (a = null); id = a; return null; } function jd(a) { switch (a) { case "cancel": case "click": case "close": case "contextmenu": case "copy": case "cut": case "auxclick": case "dblclick": case "dragend": case "dragstart": case "drop": case "focusin": case "focusout": case "input": case "invalid": case "keydown": case "keypress": case "keyup": case "mousedown": case "mouseup": case "paste": case "pause": case "play": case "pointercancel": case "pointerdown": case "pointerup": case "ratechange": case "reset": case "resize": case "seeked": case "submit": case "touchcancel": case "touchend": case "touchstart": case "volumechange": case "change": case "selectionchange": case "textInput": case "compositionstart": case "compositionend": case "compositionupdate": case "beforeblur": case "afterblur": case "beforeinput": case "blur": case "fullscreenchange": case "focus": case "hashchange": case "popstate": case "select": case "selectstart": return 1; case "drag": case "dragenter": case "dragexit": case "dragleave": case "dragover": case "mousemove": case "mouseout": case "mouseover": case "pointermove": case "pointerout": case "pointerover": case "scroll": case "toggle": case "touchmove": case "wheel": case "mouseenter": case "mouseleave": case "pointerenter": case "pointerleave": return 4; case "message": switch (ec()) { case fc: return 1; case gc: return 4; case hc: case ic: return 16; case jc: return 536870912; default: return 16; } default: return 16; } } var kd = null, ld = null, md = null; function nd() { if (md) return md; var a, b = ld, c = b.length, d, e = "value" in kd ? kd.value : kd.textContent, f = e.length; for (a = 0; a < c && b[a] === e[a]; a++) ; var g = c - a; for (d = 1; d <= g && b[c - d] === e[f - d]; d++) ; return md = e.slice(a, 1 < d ? 1 - d : void 0); } function od(a) { var b = a.keyCode; "charCode" in a ? (a = a.charCode, 0 === a && 13 === b && (a = 13)) : a = b; 10 === a && (a = 13); return 32 <= a || 13 === a ? a : 0; } function pd() { return true; } function qd() { return false; } function rd(a) { function b(b2, d, e, f, g) { this._reactName = b2; this._targetInst = e; this.type = d; this.nativeEvent = f; this.target = g; this.currentTarget = null; for (var c in a) a.hasOwnProperty(c) && (b2 = a[c], this[c] = b2 ? b2(f) : f[c]); this.isDefaultPrevented = (null != f.defaultPrevented ? f.defaultPrevented : false === f.returnValue) ? pd : qd; this.isPropagationStopped = qd; return this; } A(b.prototype, { preventDefault: function() { this.defaultPrevented = true; var a2 = this.nativeEvent; a2 && (a2.preventDefault ? a2.preventDefault() : "unknown" !== typeof a2.returnValue && (a2.returnValue = false), this.isDefaultPrevented = pd); }, stopPropagation: function() { var a2 = this.nativeEvent; a2 && (a2.stopPropagation ? a2.stopPropagation() : "unknown" !== typeof a2.cancelBubble && (a2.cancelBubble = true), this.isPropagationStopped = pd); }, persist: function() { }, isPersistent: pd }); return b; } var sd = { eventPhase: 0, bubbles: 0, cancelable: 0, timeStamp: function(a) { return a.timeStamp || Date.now(); }, defaultPrevented: 0, isTrusted: 0 }, td = rd(sd), ud = A({}, sd, { view: 0, detail: 0 }), vd = rd(ud), wd, xd, yd, Ad = A({}, ud, { screenX: 0, screenY: 0, clientX: 0, clientY: 0, pageX: 0, pageY: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, getModifierState: zd, button: 0, buttons: 0, relatedTarget: function(a) { return void 0 === a.relatedTarget ? a.fromElement === a.srcElement ? a.toElement : a.fromElement : a.relatedTarget; }, movementX: function(a) { if ("movementX" in a) return a.movementX; a !== yd && (yd && "mousemove" === a.type ? (wd = a.screenX - yd.screenX, xd = a.screenY - yd.screenY) : xd = wd = 0, yd = a); return wd; }, movementY: function(a) { return "movementY" in a ? a.movementY : xd; } }), Bd = rd(Ad), Cd = A({}, Ad, { dataTransfer: 0 }), Dd = rd(Cd), Ed = A({}, ud, { relatedTarget: 0 }), Fd = rd(Ed), Gd = A({}, sd, { animationName: 0, elapsedTime: 0, pseudoElement: 0 }), Hd = rd(Gd), Id = A({}, sd, { clipboardData: function(a) { return "clipboardData" in a ? a.clipboardData : window.clipboardData; } }), Jd = rd(Id), Kd = A({}, sd, { data: 0 }), Ld = rd(Kd), Md = { Esc: "Escape", Spacebar: " ", Left: "ArrowLeft", Up: "ArrowUp", Right: "ArrowRight", Down: "ArrowDown", Del: "Delete", Win: "OS", Menu: "ContextMenu", Apps: "ContextMenu", Scroll: "ScrollLock", MozPrintableKey: "Unidentified" }, Nd = { 8: "Backspace", 9: "Tab", 12: "Clear", 13: "Enter", 16: "Shift", 17: "Control", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Escape", 32: " ", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "ArrowLeft", 38: "ArrowUp", 39: "ArrowRight", 40: "ArrowDown", 45: "Insert", 46: "Delete", 112: "F1", 113: "F2", 114: "F3", 115: "F4", 116: "F5", 117: "F6", 118: "F7", 119: "F8", 120: "F9", 121: "F10", 122: "F11", 123: "F12", 144: "NumLock", 145: "ScrollLock", 224: "Meta" }, Od = { Alt: "altKey", Control: "ctrlKey", Meta: "metaKey", Shift: "shiftKey" }; function Pd(a) { var b = this.nativeEvent; return b.getModifierState ? b.getModifierState(a) : (a = Od[a]) ? !!b[a] : false; } function zd() { return Pd; } var Qd = A({}, ud, { key: function(a) { if (a.key) { var b = Md[a.key] || a.key; if ("Unidentified" !== b) return b; } return "keypress" === a.type ? (a = od(a), 13 === a ? "Enter" : String.fromCharCode(a)) : "keydown" === a.type || "keyup" === a.type ? Nd[a.keyCode] || "Unidentified" : ""; }, code: 0, location: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, repeat: 0, locale: 0, getModifierState: zd, charCode: function(a) { return "keypress" === a.type ? od(a) : 0; }, keyCode: function(a) { return "keydown" === a.type || "keyup" === a.type ? a.keyCode : 0; }, which: function(a) { return "keypress" === a.type ? od(a) : "keydown" === a.type || "keyup" === a.type ? a.keyCode : 0; } }), Rd = rd(Qd), Sd = A({}, Ad, { pointerId: 0, width: 0, height: 0, pressure: 0, tangentialPressure: 0, tiltX: 0, tiltY: 0, twist: 0, pointerType: 0, isPrimary: 0 }), Td = rd(Sd), Ud = A({}, ud, { touches: 0, targetTouches: 0, changedTouches: 0, altKey: 0, metaKey: 0, ctrlKey: 0, shiftKey: 0, getModifierState: zd }), Vd = rd(Ud), Wd = A({}, sd, { propertyName: 0, elapsedTime: 0, pseudoElement: 0 }), Xd = rd(Wd), Yd = A({}, Ad, { deltaX: function(a) { return "deltaX" in a ? a.deltaX : "wheelDeltaX" in a ? -a.wheelDeltaX : 0; }, deltaY: function(a) { return "deltaY" in a ? a.deltaY : "wheelDeltaY" in a ? -a.wheelDeltaY : "wheelDelta" in a ? -a.wheelDelta : 0; }, deltaZ: 0, deltaMode: 0 }), Zd = rd(Yd), $d = [9, 13, 27, 32], ae = ia && "CompositionEvent" in window, be = null; ia && "documentMode" in document && (be = document.documentMode); var ce = ia && "TextEvent" in window && !be, de = ia && (!ae || be && 8 < be && 11 >= be), ee = String.fromCharCode(32), fe = false; function ge(a, b) { switch (a) { case "keyup": return -1 !== $d.indexOf(b.keyCode); case "keydown": return 229 !== b.keyCode; case "keypress": case "mousedown": case "focusout": return true; default: return false; } } function he(a) { a = a.detail; return "object" === typeof a && "data" in a ? a.data : null; } var ie2 = false; function je(a, b) { switch (a) { case "compositionend": return he(b); case "keypress": if (32 !== b.which) return null; fe = true; return ee; case "textInput": return a = b.data, a === ee && fe ? null : a; default: return null; } } function ke(a, b) { if (ie2) return "compositionend" === a || !ae && ge(a, b) ? (a = nd(), md = ld = kd = null, ie2 = false, a) : null; switch (a) { case "paste": return null; case "keypress": if (!(b.ctrlKey || b.altKey || b.metaKey) || b.ctrlKey && b.altKey) { if (b.char && 1 < b.char.length) return b.char; if (b.which) return String.fromCharCode(b.which); } return null; case "compositionend": return de && "ko" !== b.locale ? null : b.data; default: return null; } } var le = { color: true, date: true, datetime: true, "datetime-local": true, email: true, month: true, number: true, password: true, range: true, search: true, tel: true, text: true, time: true, url: true, week: true }; function me(a) { var b = a && a.nodeName && a.nodeName.toLowerCase(); return "input" === b ? !!le[a.type] : "textarea" === b ? true : false; } function ne(a, b, c, d) { Eb(d); b = oe(b, "onChange"); 0 < b.length && (c = new td("onChange", "change", null, c, d), a.push({ event: c, listeners: b })); } var pe = null, qe = null; function re(a) { se(a, 0); } function te(a) { var b = ue(a); if (Wa(b)) return a; } function ve(a, b) { if ("change" === a) return b; } var we = false; if (ia) { var xe; if (ia) { var ye = "oninput" in document; if (!ye) { var ze = document.createElement("div"); ze.setAttribute("oninput", "return;"); ye = "function" === typeof ze.oninput; } xe = ye; } else xe = false; we = xe && (!document.documentMode || 9 < document.documentMode); } function Ae() { pe && (pe.detachEvent("onpropertychange", Be), qe = pe = null); } function Be(a) { if ("value" === a.propertyName && te(qe)) { var b = []; ne(b, qe, a, xb(a)); Jb(re, b); } } function Ce(a, b, c) { "focusin" === a ? (Ae(), pe = b, qe = c, pe.attachEvent("onpropertychange", Be)) : "focusout" === a && Ae(); } function De(a) { if ("selectionchange" === a || "keyup" === a || "keydown" === a) return te(qe); } function Ee(a, b) { if ("click" === a) return te(b); } function Fe(a, b) { if ("input" === a || "change" === a) return te(b); } function Ge(a, b) { return a === b && (0 !== a || 1 / a === 1 / b) || a !== a && b !== b; } var He = "function" === typeof Object.is ? Object.is : Ge; function Ie(a, b) { if (He(a, b)) return true; if ("object" !== typeof a || null === a || "object" !== typeof b || null === b) return false; var c = Object.keys(a), d = Object.keys(b); if (c.length !== d.length) return false; for (d = 0; d < c.length; d++) { var e = c[d]; if (!ja.call(b, e) || !He(a[e], b[e])) return false; } return true; } function Je(a) { for (; a && a.firstChild; ) a = a.firstChild; return a; } function Ke(a, b) { var c = Je(a); a = 0; for (var d; c; ) { if (3 === c.nodeType) { d = a + c.textContent.length; if (a <= b && d >= b) return { node: c, offset: b - a }; a = d; } a: { for (; c; ) { if (c.nextSibling) { c = c.nextSibling; break a; } c = c.parentNode; } c = void 0; } c = Je(c); } } function Le(a, b) { return a && b ? a === b ? true : a && 3 === a.nodeType ? false : b && 3 === b.nodeType ? Le(a, b.parentNode) : "contains" in a ? a.contains(b) : a.compareDocumentPosition ? !!(a.compareDocumentPosition(b) & 16) : false : false; } function Me() { for (var a = window, b = Xa(); b instanceof a.HTMLIFrameElement; ) { try { var c = "string" === typeof b.contentWindow.location.href; } catch (d) { c = false; } if (c) a = b.contentWindow; else break; b = Xa(a.document); } return b; } function Ne(a) { var b = a && a.nodeName && a.nodeName.toLowerCase(); return b && ("input" === b && ("text" === a.type || "search" === a.type || "tel" === a.type || "url" === a.type || "password" === a.type) || "textarea" === b || "true" === a.contentEditable); } function Oe(a) { var b = Me(), c = a.focusedElem, d = a.selectionRange; if (b !== c && c && c.ownerDocument && Le(c.ownerDocument.documentElement, c)) { if (null !== d && Ne(c)) { if (b = d.start, a = d.end, void 0 === a && (a = b), "selectionStart" in c) c.selectionStart = b, c.selectionEnd = Math.min(a, c.value.length); else if (a = (b = c.ownerDocument || document) && b.defaultView || window, a.getSelection) { a = a.getSelection(); var e = c.textContent.length, f = Math.min(d.start, e); d = void 0 === d.end ? f : Math.min(d.end, e); !a.extend && f > d && (e = d, d = f, f = e); e = Ke(c, f); var g = Ke( c, d ); e && g && (1 !== a.rangeCount || a.anchorNode !== e.node || a.anchorOffset !== e.offset || a.focusNode !== g.node || a.focusOffset !== g.offset) && (b = b.createRange(), b.setStart(e.node, e.offset), a.removeAllRanges(), f > d ? (a.addRange(b), a.extend(g.node, g.offset)) : (b.setEnd(g.node, g.offset), a.addRange(b))); } } b = []; for (a = c; a = a.parentNode; ) 1 === a.nodeType && b.push({ element: a, left: a.scrollLeft, top: a.scrollTop }); "function" === typeof c.focus && c.focus(); for (c = 0; c < b.length; c++) a = b[c], a.element.scrollLeft = a.left, a.element.scrollTop = a.top; } } var Pe = ia && "documentMode" in document && 11 >= document.documentMode, Qe = null, Re = null, Se = null, Te = false; function Ue(a, b, c) { var d = c.window === c ? c.document : 9 === c.nodeType ? c : c.ownerDocument; Te || null == Qe || Qe !== Xa(d) || (d = Qe, "selectionStart" in d && Ne(d) ? d = { start: d.selectionStart, end: d.selectionEnd } : (d = (d.ownerDocument && d.ownerDocument.defaultView || window).getSelection(), d = { anchorNode: d.anchorNode, anchorOffset: d.anchorOffset, focusNode: d.focusNode, focusOffset: d.focusOffset }), Se && Ie(Se, d) || (Se = d, d = oe(Re, "onSelect"), 0 < d.length && (b = new td("onSelect", "select", null, b, c), a.push({ event: b, listeners: d }), b.target = Qe))); } function Ve(a, b) { var c = {}; c[a.toLowerCase()] = b.toLowerCase(); c["Webkit" + a] = "webkit" + b; c["Moz" + a] = "moz" + b; return c; } var We = { animationend: Ve("Animation", "AnimationEnd"), animationiteration: Ve("Animation", "AnimationIteration"), animationstart: Ve("Animation", "AnimationStart"), transitionend: Ve("Transition", "TransitionEnd") }, Xe = {}, Ye = {}; ia && (Ye = document.createElement("div").style, "AnimationEvent" in window || (delete We.animationend.animation, delete We.animationiteration.animation, delete We.animationstart.animation), "TransitionEvent" in window || delete We.transitionend.transition); function Ze(a) { if (Xe[a]) return Xe[a]; if (!We[a]) return a; var b = We[a], c; for (c in b) if (b.hasOwnProperty(c) && c in Ye) return Xe[a] = b[c]; return a; } var $e = Ze("animationend"), af = Ze("animationiteration"), bf = Ze("animationstart"), cf = Ze("transitionend"), df = /* @__PURE__ */ new Map(), ef = "abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" "); function ff(a, b) { df.set(a, b); fa(b, [a]); } for (var gf = 0; gf < ef.length; gf++) { var hf = ef[gf], jf = hf.toLowerCase(), kf = hf[0].toUpperCase() + hf.slice(1); ff(jf, "on" + kf); } ff($e, "onAnimationEnd"); ff(af, "onAnimationIteration"); ff(bf, "onAnimationStart"); ff("dblclick", "onDoubleClick"); ff("focusin", "onFocus"); ff("focusout", "onBlur"); ff(cf, "onTransitionEnd"); ha("onMouseEnter", ["mouseout", "mouseover"]); ha("onMouseLeave", ["mouseout", "mouseover"]); ha("onPointerEnter", ["pointerout", "pointerover"]); ha("onPointerLeave", ["pointerout", "pointerover"]); fa("onChange", "change click focusin focusout input keydown keyup selectionchange".split(" ")); fa("onSelect", "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")); fa("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]); fa("onCompositionEnd", "compositionend focusout keydown keypress keyup mousedown".split(" ")); fa("onCompositionStart", "compositionstart focusout keydown keypress keyup mousedown".split(" ")); fa("onCompositionUpdate", "compositionupdate focusout keydown keypress keyup mousedown".split(" ")); var lf = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "), mf = new Set("cancel close invalid load scroll toggle".split(" ").concat(lf)); function nf(a, b, c) { var d = a.type || "unknown-event"; a.currentTarget = c; Ub(d, b, void 0, a); a.currentTarget = null; } function se(a, b) { b = 0 !== (b & 4); for (var c = 0; c < a.length; c++) { var d = a[c], e = d.event; d = d.listeners; a: { var f = void 0; if (b) for (var g = d.length - 1; 0 <= g; g--) { var h2 = d[g], k = h2.instance, l = h2.currentTarget; h2 = h2.listener; if (k !== f && e.isPropagationStopped()) break a; nf(e, h2, l); f = k; } else for (g = 0; g < d.length; g++) { h2 = d[g]; k = h2.instance; l = h2.currentTarget; h2 = h2.listener; if (k !== f && e.isPropagationStopped()) break a; nf(e, h2, l); f = k; } } } if (Qb) throw a = Rb, Qb = false, Rb = null, a; } function D(a, b) { var c = b[of]; void 0 === c && (c = b[of] = /* @__PURE__ */ new Set()); var d = a + "__bubble"; c.has(d) || (pf(b, a, 2, false), c.add(d)); } function qf(a, b, c) { var d = 0; b && (d |= 4); pf(c, a, d, b); } var rf = "_reactListening" + Math.random().toString(36).slice(2); function sf(a) { if (!a[rf]) { a[rf] = true; da.forEach(function(b2) { "selectionchange" !== b2 && (mf.has(b2) || qf(b2, false, a), qf(b2, true, a)); }); var b = 9 === a.nodeType ? a : a.ownerDocument; null === b || b[rf] || (b[rf] = true, qf("selectionchange", false, b)); } } function pf(a, b, c, d) { switch (jd(b)) { case 1: var e = ed; break; case 4: e = gd; break; default: e = fd; } c = e.bind(null, b, c, a); e = void 0; !Lb || "touchstart" !== b && "touchmove" !== b && "wheel" !== b || (e = true); d ? void 0 !== e ? a.addEventListener(b, c, { capture: true, passive: e }) : a.addEventListener(b, c, true) : void 0 !== e ? a.addEventListener(b, c, { passive: e }) : a.addEventListener(b, c, false); } function hd(a, b, c, d, e) { var f = d; if (0 === (b & 1) && 0 === (b & 2) && null !== d) a: for (; ; ) { if (null === d) return; var g = d.tag; if (3 === g || 4 === g) { var h2 = d.stateNode.containerInfo; if (h2 === e || 8 === h2.nodeType && h2.parentNode === e) break; if (4 === g) for (g = d.return; null !== g; ) { var k = g.tag; if (3 === k || 4 === k) { if (k = g.stateNode.containerInfo, k === e || 8 === k.nodeType && k.parentNode === e) return; } g = g.return; } for (; null !== h2; ) { g = Wc(h2); if (null === g) return; k = g.tag; if (5 === k || 6 === k) { d = f = g; continue a; } h2 = h2.parentNode; } } d = d.return; } Jb(function() { var d2 = f, e2 = xb(c), g2 = []; a: { var h3 = df.get(a); if (void 0 !== h3) { var k2 = td, n = a; switch (a) { case "keypress": if (0 === od(c)) break a; case "keydown": case "keyup": k2 = Rd; break; case "focusin": n = "focus"; k2 = Fd; break; case "focusout": n = "blur"; k2 = Fd; break; case "beforeblur": case "afterblur": k2 = Fd; break; case "click": if (2 === c.button) break a; case "auxclick": case "dblclick": case "mousedown": case "mousemove": case "mouseup": case "mouseout": case "mouseover": case "contextmenu": k2 = Bd; break; case "drag": case "dragend": case "dragenter": case "dragexit": case "dragleave": case "dragover": case "dragstart": case "drop": k2 = Dd; break; case "touchcancel": case "touchend": case "touchmove": case "touchstart": k2 = Vd; break; case $e: case af: case bf: k2 = Hd; break; case cf: k2 = Xd; break; case "scroll": k2 = vd; break; case "wheel": k2 = Zd; break; case "copy": case "cut": case "paste": k2 = Jd; break; case "gotpointercapture": case "lostpointercapture": case "pointercancel": case "pointerdown": case "pointermove": case "pointerout": case "pointerover": case "pointerup": k2 = Td; } var t = 0 !== (b & 4), J = !t && "scroll" === a, x = t ? null !== h3 ? h3 + "Capture" : null : h3; t = []; for (var w = d2, u; null !== w; ) { u = w; var F = u.stateNode; 5 === u.tag && null !== F && (u = F, null !== x && (F = Kb(w, x), null != F && t.push(tf(w, F, u)))); if (J) break; w = w.return; } 0 < t.length && (h3 = new k2(h3, n, null, c, e2), g2.push({ event: h3, listeners: t })); } } if (0 === (b & 7)) { a: { h3 = "mouseover" === a || "pointerover" === a; k2 = "mouseout" === a || "pointerout" === a; if (h3 && c !== wb && (n = c.relatedTarget || c.fromElement) && (Wc(n) || n[uf])) break a; if (k2 || h3) { h3 = e2.window === e2 ? e2 : (h3 = e2.ownerDocument) ? h3.defaultView || h3.parentWindow : window; if (k2) { if (n = c.relatedTarget || c.toElement, k2 = d2, n = n ? Wc(n) : null, null !== n && (J = Vb(n), n !== J || 5 !== n.tag && 6 !== n.tag)) n = null; } else k2 = null, n = d2; if (k2 !== n) { t = Bd; F = "onMouseLeave"; x = "onMouseEnter"; w = "mouse"; if ("pointerout" === a || "pointerover" === a) t = Td, F = "onPointerLeave", x = "onPointerEnter", w = "pointer"; J = null == k2 ? h3 : ue(k2); u = null == n ? h3 : ue(n); h3 = new t(F, w + "leave", k2, c, e2); h3.target = J; h3.relatedTarget = u; F = null; Wc(e2) === d2 && (t = new t(x, w + "enter", n, c, e2), t.target = u, t.relatedTarget = J, F = t); J = F; if (k2 && n) b: { t = k2; x = n; w = 0; for (u = t; u; u = vf(u)) w++; u = 0; for (F = x; F; F = vf(F)) u++; for (; 0 < w - u; ) t = vf(t), w--; for (; 0 < u - w; ) x = vf(x), u--; for (; w--; ) { if (t === x || null !== x && t === x.alternate) break b; t = vf(t); x = vf(x); } t = null; } else t = null; null !== k2 && wf(g2, h3, k2, t, false); null !== n && null !== J && wf(g2, J, n, t, true); } } } a: { h3 = d2 ? ue(d2) : window; k2 = h3.nodeName && h3.nodeName.toLowerCase(); if ("select" === k2 || "input" === k2 && "file" === h3.type) var na = ve; else if (me(h3)) if (we) na = Fe; else { na = De; var xa = Ce; } else (k2 = h3.nodeName) && "input" === k2.toLowerCase() && ("checkbox" === h3.type || "radio" === h3.type) && (na = Ee); if (na && (na = na(a, d2))) { ne(g2, na, c, e2); break a; } xa && xa(a, h3, d2); "focusout" === a && (xa = h3._wrapperState) && xa.controlled && "number" === h3.type && cb(h3, "number", h3.value); } xa = d2 ? ue(d2) : window; switch (a) { case "focusin": if (me(xa) || "true" === xa.contentEditable) Qe = xa, Re = d2, Se = null; break; case "focusout": Se = Re = Qe = null; break; case "mousedown": Te = true; break; case "contextmenu": case "mouseup": case "dragend": Te = false; Ue(g2, c, e2); break; case "selectionchange": if (Pe) break; case "keydown": case "keyup": Ue(g2, c, e2); } var $a; if (ae) b: { switch (a) { case "compositionstart": var ba = "onCompositionStart"; break b; case "compositionend": ba = "onCompositionEnd"; break b; case "compositionupdate": ba = "onCompositionUpdate"; break b; } ba = void 0; } else ie2 ? ge(a, c) && (ba = "onCompositionEnd") : "keydown" === a && 229 === c.keyCode && (ba = "onCompositionStart"); ba && (de && "ko" !== c.locale && (ie2 || "onCompositionStart" !== ba ? "onCompositionEnd" === ba && ie2 && ($a = nd()) : (kd = e2, ld = "value" in kd ? kd.value : kd.textContent, ie2 = true)), xa = oe(d2, ba), 0 < xa.length && (ba = new Ld(ba, a, null, c, e2), g2.push({ event: ba, listeners: xa }), $a ? ba.data = $a : ($a = he(c), null !== $a && (ba.data = $a)))); if ($a = ce ? je(a, c) : ke(a, c)) d2 = oe(d2, "onBeforeInput"), 0 < d2.length && (e2 = new Ld("onBeforeInput", "beforeinput", null, c, e2), g2.push({ event: e2, listeners: d2 }), e2.data = $a); } se(g2, b); }); } function tf(a, b, c) { return { instance: a, listener: b, currentTarget: c }; } function oe(a, b) { for (var c = b + "Capture", d = []; null !== a; ) { var e = a, f = e.stateNode; 5 === e.tag && null !== f && (e = f, f = Kb(a, c), null != f && d.unshift(tf(a, f, e)), f = Kb(a, b), null != f && d.push(tf(a, f, e))); a = a.return; } return d; } function vf(a) { if (null === a) return null; do a = a.return; while (a && 5 !== a.tag); return a ? a : null; } function wf(a, b, c, d, e) { for (var f = b._reactName, g = []; null !== c && c !== d; ) { var h2 = c, k = h2.alternate, l = h2.stateNode; if (null !== k && k === d) break; 5 === h2.tag && null !== l && (h2 = l, e ? (k = Kb(c, f), null != k && g.unshift(tf(c, k, h2))) : e || (k = Kb(c, f), null != k && g.push(tf(c, k, h2)))); c = c.return; } 0 !== g.length && a.push({ event: b, listeners: g }); } var xf = /\r\n?/g, yf = /\u0000|\uFFFD/g; function zf(a) { return ("string" === typeof a ? a : "" + a).replace(xf, "\n").replace(yf, ""); } function Af(a, b, c) { b = zf(b); if (zf(a) !== b && c) throw Error(p(425)); } function Bf() { } var Cf = null, Df = null; function Ef(a, b) { return "textarea" === a || "noscript" === a || "string" === typeof b.children || "number" === typeof b.children || "object" === typeof b.dangerouslySetInnerHTML && null !== b.dangerouslySetInnerHTML && null != b.dangerouslySetInnerHTML.__html; } var Ff = "function" === typeof setTimeout ? setTimeout : void 0, Gf = "function" === typeof clearTimeout ? clearTimeout : void 0, Hf = "function" === typeof Promise ? Promise : void 0, Jf = "function" === typeof queueMicrotask ? queueMicrotask : "undefined" !== typeof Hf ? function(a) { return Hf.resolve(null).then(a).catch(If); } : Ff; function If(a) { setTimeout(function() { throw a; }); } function Kf(a, b) { var c = b, d = 0; do { var e = c.nextSibling; a.removeChild(c); if (e && 8 === e.nodeType) if (c = e.data, "/$" === c) { if (0 === d) { a.removeChild(e); bd(b); return; } d--; } else "$" !== c && "$?" !== c && "$!" !== c || d++; c = e; } while (c); bd(b); } function Lf(a) { for (; null != a; a = a.nextSibling) { var b = a.nodeType; if (1 === b || 3 === b) break; if (8 === b) { b = a.data; if ("$" === b || "$!" === b || "$?" === b) break; if ("/$" === b) return null; } } return a; } function Mf(a) { a = a.previousSibling; for (var b = 0; a; ) { if (8 === a.nodeType) { var c = a.data; if ("$" === c || "$!" === c || "$?" === c) { if (0 === b) return a; b--; } else "/$" === c && b++; } a = a.previousSibling; } return null; } var Nf = Math.random().toString(36).slice(2), Of = "__reactFiber$" + Nf, Pf = "__reactProps$" + Nf, uf = "__reactContainer$" + Nf, of = "__reactEvents$" + Nf, Qf = "__reactListeners$" + Nf, Rf = "__reactHandles$" + Nf; function Wc(a) { var b = a[Of]; if (b) return b; for (var c = a.parentNode; c; ) { if (b = c[uf] || c[Of]) { c = b.alternate; if (null !== b.child || null !== c && null !== c.child) for (a = Mf(a); null !== a; ) { if (c = a[Of]) return c; a = Mf(a); } return b; } a = c; c = a.parentNode; } return null; } function Cb(a) { a = a[Of] || a[uf]; return !a || 5 !== a.tag && 6 !== a.tag && 13 !== a.tag && 3 !== a.tag ? null : a; } function ue(a) { if (5 === a.tag || 6 === a.tag) return a.stateNode; throw Error(p(33)); } function Db(a) { return a[Pf] || null; } var Sf = [], Tf = -1; function Uf(a) { return { current: a }; } function E(a) { 0 > Tf || (a.current = Sf[Tf], Sf[Tf] = null, Tf--); } function G(a, b) { Tf++; Sf[Tf] = a.current; a.current = b; } var Vf = {}, H = Uf(Vf), Wf = Uf(false), Xf = Vf; function Yf(a, b) { var c = a.type.contextTypes; if (!c) return Vf; var d = a.stateNode; if (d && d.__reactInternalMemoizedUnmaskedChildContext === b) return d.__reactInternalMemoizedMaskedChildContext; var e = {}, f; for (f in c) e[f] = b[f]; d && (a = a.stateNode, a.__reactInternalMemoizedUnmaskedChildContext = b, a.__reactInternalMemoizedMaskedChildContext = e); return e; } function Zf(a) { a = a.childContextTypes; return null !== a && void 0 !== a; } function $f() { E(Wf); E(H); } function ag(a, b, c) { if (H.current !== Vf) throw Error(p(168)); G(H, b); G(Wf, c); } function bg(a, b, c) { var d = a.stateNode; b = b.childContextTypes; if ("function" !== typeof d.getChildContext) return c; d = d.getChildContext(); for (var e in d) if (!(e in b)) throw Error(p(108, Ra(a) || "Unknown", e)); return A({}, c, d); } function cg(a) { a = (a = a.stateNode) && a.__reactInternalMemoizedMergedChildContext || Vf; Xf = H.current; G(H, a); G(Wf, Wf.current); return true; } function dg(a, b, c) { var d = a.stateNode; if (!d) throw Error(p(169)); c ? (a = bg(a, b, Xf), d.__reactInternalMemoizedMergedChildContext = a, E(Wf), E(H), G(H, a)) : E(Wf); G(Wf, c); } var eg = null, fg = false, gg = false; function hg(a) { null === eg ? eg = [a] : eg.push(a); } function ig(a) { fg = true; hg(a); } function jg() { if (!gg && null !== eg) { gg = true; var a = 0, b = C; try { var c = eg; for (C = 1; a < c.length; a++) { var d = c[a]; do d = d(true); while (null !== d); } eg = null; fg = false; } catch (e) { throw null !== eg && (eg = eg.slice(a + 1)), ac(fc, jg), e; } finally { C = b, gg = false; } } return null; } var kg = [], lg = 0, mg = null, ng = 0, og = [], pg = 0, qg = null, rg = 1, sg = ""; function tg(a, b) { kg[lg++] = ng; kg[lg++] = mg; mg = a; ng = b; } function ug(a, b, c) { og[pg++] = rg; og[pg++] = sg; og[pg++] = qg; qg = a; var d = rg; a = sg; var e = 32 - oc(d) - 1; d &= ~(1 << e); c += 1; var f = 32 - oc(b) + e; if (30 < f) { var g = e - e % 5; f = (d & (1 << g) - 1).toString(32); d >>= g; e -= g; rg = 1 << 32 - oc(b) + e | c << e | d; sg = f + a; } else rg = 1 << f | c << e | d, sg = a; } function vg(a) { null !== a.return && (tg(a, 1), ug(a, 1, 0)); } function wg(a) { for (; a === mg; ) mg = kg[--lg], kg[lg] = null, ng = kg[--lg], kg[lg] = null; for (; a === qg; ) qg = og[--pg], og[pg] = null, sg = og[--pg], og[pg] = null, rg = og[--pg], og[pg] = null; } var xg = null, yg = null, I = false, zg = null; function Ag(a, b) { var c = Bg(5, null, null, 0); c.elementType = "DELETED"; c.stateNode = b; c.return = a; b = a.deletions; null === b ? (a.deletions = [c], a.flags |= 16) : b.push(c); } function Cg(a, b) { switch (a.tag) { case 5: var c = a.type; b = 1 !== b.nodeType || c.toLowerCase() !== b.nodeName.toLowerCase() ? null : b; return null !== b ? (a.stateNode = b, xg = a, yg = Lf(b.firstChild), true) : false; case 6: return b = "" === a.pendingProps || 3 !== b.nodeType ? null : b, null !== b ? (a.stateNode = b, xg = a, yg = null, true) : false; case 13: return b = 8 !== b.nodeType ? null : b, null !== b ? (c = null !== qg ? { id: rg, overflow: sg } : null, a.memoizedState = { dehydrated: b, treeContext: c, retryLane: 1073741824 }, c = Bg(18, null, null, 0), c.stateNode = b, c.return = a, a.child = c, xg = a, yg = null, true) : false; default: return false; } } function Dg(a) { return 0 !== (a.mode & 1) && 0 === (a.flags & 128); } function Eg(a) { if (I) { var b = yg; if (b) { var c = b; if (!Cg(a, b)) { if (Dg(a)) throw Error(p(418)); b = Lf(c.nextSibling); var d = xg; b && Cg(a, b) ? Ag(d, c) : (a.flags = a.flags & -4097 | 2, I = false, xg = a); } } else { if (Dg(a)) throw Error(p(418)); a.flags = a.flags & -4097 | 2; I = false; xg = a; } } } function Fg(a) { for (a = a.return; null !== a && 5 !== a.tag && 3 !== a.tag && 13 !== a.tag; ) a = a.return; xg = a; } function Gg(a) { if (a !== xg) return false; if (!I) return Fg(a), I = true, false; var b; (b = 3 !== a.tag) && !(b = 5 !== a.tag) && (b = a.type, b = "head" !== b && "body" !== b && !Ef(a.type, a.memoizedProps)); if (b && (b = yg)) { if (Dg(a)) throw Hg(), Error(p(418)); for (; b; ) Ag(a, b), b = Lf(b.nextSibling); } Fg(a); if (13 === a.tag) { a = a.memoizedState; a = null !== a ? a.dehydrated : null; if (!a) throw Error(p(317)); a: { a = a.nextSibling; for (b = 0; a; ) { if (8 === a.nodeType) { var c = a.data; if ("/$" === c) { if (0 === b) { yg = Lf(a.nextSibling); break a; } b--; } else "$" !== c && "$!" !== c && "$?" !== c || b++; } a = a.nextSibling; } yg = null; } } else yg = xg ? Lf(a.stateNode.nextSibling) : null; return true; } function Hg() { for (var a = yg; a; ) a = Lf(a.nextSibling); } function Ig() { yg = xg = null; I = false; } function Jg(a) { null === zg ? zg = [a] : zg.push(a); } var Kg = ua.ReactCurrentBatchConfig; function Lg(a, b, c) { a = c.ref; if (null !== a && "function" !== typeof a && "object" !== typeof a) { if (c._owner) { c = c._owner; if (c) { if (1 !== c.tag) throw Error(p(309)); var d = c.stateNode; } if (!d) throw Error(p(147, a)); var e = d, f = "" + a; if (null !== b && null !== b.ref && "function" === typeof b.ref && b.ref._stringRef === f) return b.ref; b = function(a2) { var b2 = e.refs; null === a2 ? delete b2[f] : b2[f] = a2; }; b._stringRef = f; return b; } if ("string" !== typeof a) throw Error(p(284)); if (!c._owner) throw Error(p(290, a)); } return a; } function Mg(a, b) { a = Object.prototype.toString.call(b); throw Error(p(31, "[object Object]" === a ? "object with keys {" + Object.keys(b).join(", ") + "}" : a)); } function Ng(a) { var b = a._init; return b(a._payload); } function Og(a) { function b(b2, c2) { if (a) { var d2 = b2.deletions; null === d2 ? (b2.deletions = [c2], b2.flags |= 16) : d2.push(c2); } } function c(c2, d2) { if (!a) return null; for (; null !== d2; ) b(c2, d2), d2 = d2.sibling; return null; } function d(a2, b2) { for (a2 = /* @__PURE__ */ new Map(); null !== b2; ) null !== b2.key ? a2.set(b2.key, b2) : a2.set(b2.index, b2), b2 = b2.sibling; return a2; } function e(a2, b2) { a2 = Pg(a2, b2); a2.index = 0; a2.sibling = null; return a2; } function f(b2, c2, d2) { b2.index = d2; if (!a) return b2.flags |= 1048576, c2; d2 = b2.alternate; if (null !== d2) return d2 = d2.index, d2 < c2 ? (b2.flags |= 2, c2) : d2; b2.flags |= 2; return c2; } function g(b2) { a && null === b2.alternate && (b2.flags |= 2); return b2; } function h2(a2, b2, c2, d2) { if (null === b2 || 6 !== b2.tag) return b2 = Qg(c2, a2.mode, d2), b2.return = a2, b2; b2 = e(b2, c2); b2.return = a2; return b2; } function k(a2, b2, c2, d2) { var f2 = c2.type; if (f2 === ya) return m(a2, b2, c2.props.children, d2, c2.key); if (null !== b2 && (b2.elementType === f2 || "object" === typeof f2 && null !== f2 && f2.$$typeof === Ha && Ng(f2) === b2.type)) return d2 = e(b2, c2.props), d2.ref = Lg(a2, b2, c2), d2.return = a2, d2; d2 = Rg(c2.type, c2.key, c2.props, null, a2.mode, d2); d2.ref = Lg(a2, b2, c2); d2.return = a2; return d2; } function l(a2, b2, c2, d2) { if (null === b2 || 4 !== b2.tag || b2.stateNode.containerInfo !== c2.containerInfo || b2.stateNode.implementation !== c2.implementation) return b2 = Sg(c2, a2.mode, d2), b2.return = a2, b2; b2 = e(b2, c2.children || []); b2.return = a2; return b2; } function m(a2, b2, c2, d2, f2) { if (null === b2 || 7 !== b2.tag) return b2 = Tg(c2, a2.mode, d2, f2), b2.return = a2, b2; b2 = e(b2, c2); b2.return = a2; return b2; } function q(a2, b2, c2) { if ("string" === typeof b2 && "" !== b2 || "number" === typeof b2) return b2 = Qg("" + b2, a2.mode, c2), b2.return = a2, b2; if ("object" === typeof b2 && null !== b2) { switch (b2.$$typeof) { case va: return c2 = Rg(b2.type, b2.key, b2.props, null, a2.mode, c2), c2.ref = Lg(a2, null, b2), c2.return = a2, c2; case wa: return b2 = Sg(b2, a2.mode, c2), b2.return = a2, b2; case Ha: var d2 = b2._init; return q(a2, d2(b2._payload), c2); } if (eb(b2) || Ka(b2)) return b2 = Tg(b2, a2.mode, c2, null), b2.return = a2, b2; Mg(a2, b2); } return null; } function r(a2, b2, c2, d2) { var e2 = null !== b2 ? b2.key : null; if ("string" === typeof c2 && "" !== c2 || "number" === typeof c2) return null !== e2 ? null : h2(a2, b2, "" + c2, d2); if ("object" === typeof c2 && null !== c2) { switch (c2.$$typeof) { case va: return c2.key === e2 ? k(a2, b2, c2, d2) : null; case wa: return c2.key === e2 ? l(a2, b2, c2, d2) : null; case Ha: return e2 = c2._init, r( a2, b2, e2(c2._payload), d2 ); } if (eb(c2) || Ka(c2)) return null !== e2 ? null : m(a2, b2, c2, d2, null); Mg(a2, c2); } return null; } function y(a2, b2, c2, d2, e2) { if ("string" === typeof d2 && "" !== d2 || "number" === typeof d2) return a2 = a2.get(c2) || null, h2(b2, a2, "" + d2, e2); if ("object" === typeof d2 && null !== d2) { switch (d2.$$typeof) { case va: return a2 = a2.get(null === d2.key ? c2 : d2.key) || null, k(b2, a2, d2, e2); case wa: return a2 = a2.get(null === d2.key ? c2 : d2.key) || null, l(b2, a2, d2, e2); case Ha: var f2 = d2._init; return y(a2, b2, c2, f2(d2._payload), e2); } if (eb(d2) || Ka(d2)) return a2 = a2.get(c2) || null, m(b2, a2, d2, e2, null); Mg(b2, d2); } return null; } function n(e2, g2, h3, k2) { for (var l2 = null, m2 = null, u = g2, w = g2 = 0, x = null; null !== u && w < h3.length; w++) { u.index > w ? (x = u, u = null) : x = u.sibling; var n2 = r(e2, u, h3[w], k2); if (null === n2) { null === u && (u = x); break; } a && u && null === n2.alternate && b(e2, u); g2 = f(n2, g2, w); null === m2 ? l2 = n2 : m2.sibling = n2; m2 = n2; u = x; } if (w === h3.length) return c(e2, u), I && tg(e2, w), l2; if (null === u) { for (; w < h3.length; w++) u = q(e2, h3[w], k2), null !== u && (g2 = f(u, g2, w), null === m2 ? l2 = u : m2.sibling = u, m2 = u); I && tg(e2, w); return l2; } for (u = d(e2, u); w < h3.length; w++) x = y(u, e2, w, h3[w], k2), null !== x && (a && null !== x.alternate && u.delete(null === x.key ? w : x.key), g2 = f(x, g2, w), null === m2 ? l2 = x : m2.sibling = x, m2 = x); a && u.forEach(function(a2) { return b(e2, a2); }); I && tg(e2, w); return l2; } function t(e2, g2, h3, k2) { var l2 = Ka(h3); if ("function" !== typeof l2) throw Error(p(150)); h3 = l2.call(h3); if (null == h3) throw Error(p(151)); for (var u = l2 = null, m2 = g2, w = g2 = 0, x = null, n2 = h3.next(); null !== m2 && !n2.done; w++, n2 = h3.next()) { m2.index > w ? (x = m2, m2 = null) : x = m2.sibling; var t2 = r(e2, m2, n2.value, k2); if (null === t2) { null === m2 && (m2 = x); break; } a && m2 && null === t2.alternate && b(e2, m2); g2 = f(t2, g2, w); null === u ? l2 = t2 : u.sibling = t2; u = t2; m2 = x; } if (n2.done) return c( e2, m2 ), I && tg(e2, w), l2; if (null === m2) { for (; !n2.done; w++, n2 = h3.next()) n2 = q(e2, n2.value, k2), null !== n2 && (g2 = f(n2, g2, w), null === u ? l2 = n2 : u.sibling = n2, u = n2); I && tg(e2, w); return l2; } for (m2 = d(e2, m2); !n2.done; w++, n2 = h3.next()) n2 = y(m2, e2, w, n2.value, k2), null !== n2 && (a && null !== n2.alternate && m2.delete(null === n2.key ? w : n2.key), g2 = f(n2, g2, w), null === u ? l2 = n2 : u.sibling = n2, u = n2); a && m2.forEach(function(a2) { return b(e2, a2); }); I && tg(e2, w); return l2; } function J(a2, d2, f2, h3) { "object" === typeof f2 && null !== f2 && f2.type === ya && null === f2.key && (f2 = f2.props.children); if ("object" === typeof f2 && null !== f2) { switch (f2.$$typeof) { case va: a: { for (var k2 = f2.key, l2 = d2; null !== l2; ) { if (l2.key === k2) { k2 = f2.type; if (k2 === ya) { if (7 === l2.tag) { c(a2, l2.sibling); d2 = e(l2, f2.props.children); d2.return = a2; a2 = d2; break a; } } else if (l2.elementType === k2 || "object" === typeof k2 && null !== k2 && k2.$$typeof === Ha && Ng(k2) === l2.type) { c(a2, l2.sibling); d2 = e(l2, f2.props); d2.ref = Lg(a2, l2, f2); d2.return = a2; a2 = d2; break a; } c(a2, l2); break; } else b(a2, l2); l2 = l2.sibling; } f2.type === ya ? (d2 = Tg(f2.props.children, a2.mode, h3, f2.key), d2.return = a2, a2 = d2) : (h3 = Rg(f2.type, f2.key, f2.props, null, a2.mode, h3), h3.ref = Lg(a2, d2, f2), h3.return = a2, a2 = h3); } return g(a2); case wa: a: { for (l2 = f2.key; null !== d2; ) { if (d2.key === l2) if (4 === d2.tag && d2.stateNode.containerInfo === f2.containerInfo && d2.stateNode.implementation === f2.implementation) { c(a2, d2.sibling); d2 = e(d2, f2.children || []); d2.return = a2; a2 = d2; break a; } else { c(a2, d2); break; } else b(a2, d2); d2 = d2.sibling; } d2 = Sg(f2, a2.mode, h3); d2.return = a2; a2 = d2; } return g(a2); case Ha: return l2 = f2._init, J(a2, d2, l2(f2._payload), h3); } if (eb(f2)) return n(a2, d2, f2, h3); if (Ka(f2)) return t(a2, d2, f2, h3); Mg(a2, f2); } return "string" === typeof f2 && "" !== f2 || "number" === typeof f2 ? (f2 = "" + f2, null !== d2 && 6 === d2.tag ? (c(a2, d2.sibling), d2 = e(d2, f2), d2.return = a2, a2 = d2) : (c(a2, d2), d2 = Qg(f2, a2.mode, h3), d2.return = a2, a2 = d2), g(a2)) : c(a2, d2); } return J; } var Ug = Og(true), Vg = Og(false), Wg = Uf(null), Xg = null, Yg = null, Zg = null; function $g() { Zg = Yg = Xg = null; } function ah(a) { var b = Wg.current; E(Wg); a._currentValue = b; } function bh(a, b, c) { for (; null !== a; ) { var d = a.alternate; (a.childLanes & b) !== b ? (a.childLanes |= b, null !== d && (d.childLanes |= b)) : null !== d && (d.childLanes & b) !== b && (d.childLanes |= b); if (a === c) break; a = a.return; } } function ch(a, b) { Xg = a; Zg = Yg = null; a = a.dependencies; null !== a && null !== a.firstContext && (0 !== (a.lanes & b) && (dh = true), a.firstContext = null); } function eh(a) { var b = a._currentValue; if (Zg !== a) if (a = { context: a, memoizedValue: b, next: null }, null === Yg) { if (null === Xg) throw Error(p(308)); Yg = a; Xg.dependencies = { lanes: 0, firstContext: a }; } else Yg = Yg.next = a; return b; } var fh = null; function gh(a) { null === fh ? fh = [a] : fh.push(a); } function hh(a, b, c, d) { var e = b.interleaved; null === e ? (c.next = c, gh(b)) : (c.next = e.next, e.next = c); b.interleaved = c; return ih(a, d); } function ih(a, b) { a.lanes |= b; var c = a.alternate; null !== c && (c.lanes |= b); c = a; for (a = a.return; null !== a; ) a.childLanes |= b, c = a.alternate, null !== c && (c.childLanes |= b), c = a, a = a.return; return 3 === c.tag ? c.stateNode : null; } var jh = false; function kh(a) { a.updateQueue = { baseState: a.memoizedState, firstBaseUpdate: null, lastBaseUpdate: null, shared: { pending: null, interleaved: null, lanes: 0 }, effects: null }; } function lh(a, b) { a = a.updateQueue; b.updateQueue === a && (b.updateQueue = { baseState: a.baseState, firstBaseUpdate: a.firstBaseUpdate, lastBaseUpdate: a.lastBaseUpdate, shared: a.shared, effects: a.effects }); } function mh(a, b) { return { eventTime: a, lane: b, tag: 0, payload: null, callback: null, next: null }; } function nh(a, b, c) { var d = a.updateQueue; if (null === d) return null; d = d.shared; if (0 !== (K & 2)) { var e = d.pending; null === e ? b.next = b : (b.next = e.next, e.next = b); d.pending = b; return ih(a, c); } e = d.interleaved; null === e ? (b.next = b, gh(d)) : (b.next = e.next, e.next = b); d.interleaved = b; return ih(a, c); } function oh(a, b, c) { b = b.updateQueue; if (null !== b && (b = b.shared, 0 !== (c & 4194240))) { var d = b.lanes; d &= a.pendingLanes; c |= d; b.lanes = c; Cc(a, c); } } function ph(a, b) { var c = a.updateQueue, d = a.alternate; if (null !== d && (d = d.updateQueue, c === d)) { var e = null, f = null; c = c.firstBaseUpdate; if (null !== c) { do { var g = { eventTime: c.eventTime, lane: c.lane, tag: c.tag, payload: c.payload, callback: c.callback, next: null }; null === f ? e = f = g : f = f.next = g; c = c.next; } while (null !== c); null === f ? e = f = b : f = f.next = b; } else e = f = b; c = { baseState: d.baseState, firstBaseUpdate: e, lastBaseUpdate: f, shared: d.shared, effects: d.effects }; a.updateQueue = c; return; } a = c.lastBaseUpdate; null === a ? c.firstBaseUpdate = b : a.next = b; c.lastBaseUpdate = b; } function qh(a, b, c, d) { var e = a.updateQueue; jh = false; var f = e.firstBaseUpdate, g = e.lastBaseUpdate, h2 = e.shared.pending; if (null !== h2) { e.shared.pending = null; var k = h2, l = k.next; k.next = null; null === g ? f = l : g.next = l; g = k; var m = a.alternate; null !== m && (m = m.updateQueue, h2 = m.lastBaseUpdate, h2 !== g && (null === h2 ? m.firstBaseUpdate = l : h2.next = l, m.lastBaseUpdate = k)); } if (null !== f) { var q = e.baseState; g = 0; m = l = k = null; h2 = f; do { var r = h2.lane, y = h2.eventTime; if ((d & r) === r) { null !== m && (m = m.next = { eventTime: y, lane: 0, tag: h2.tag, payload: h2.payload, callback: h2.callback, next: null }); a: { var n = a, t = h2; r = b; y = c; switch (t.tag) { case 1: n = t.payload; if ("function" === typeof n) { q = n.call(y, q, r); break a; } q = n; break a; case 3: n.flags = n.flags & -65537 | 128; case 0: n = t.payload; r = "function" === typeof n ? n.call(y, q, r) : n; if (null === r || void 0 === r) break a; q = A({}, q, r); break a; case 2: jh = true; } } null !== h2.callback && 0 !== h2.lane && (a.flags |= 64, r = e.effects, null === r ? e.effects = [h2] : r.push(h2)); } else y = { eventTime: y, lane: r, tag: h2.tag, payload: h2.payload, callback: h2.callback, next: null }, null === m ? (l = m = y, k = q) : m = m.next = y, g |= r; h2 = h2.next; if (null === h2) if (h2 = e.shared.pending, null === h2) break; else r = h2, h2 = r.next, r.next = null, e.lastBaseUpdate = r, e.shared.pending = null; } while (1); null === m && (k = q); e.baseState = k; e.firstBaseUpdate = l; e.lastBaseUpdate = m; b = e.shared.interleaved; if (null !== b) { e = b; do g |= e.lane, e = e.next; while (e !== b); } else null === f && (e.shared.lanes = 0); rh |= g; a.lanes = g; a.memoizedState = q; } } function sh(a, b, c) { a = b.effects; b.effects = null; if (null !== a) for (b = 0; b < a.length; b++) { var d = a[b], e = d.callback; if (null !== e) { d.callback = null; d = c; if ("function" !== typeof e) throw Error(p(191, e)); e.call(d); } } } var th = {}, uh = Uf(th), vh = Uf(th), wh = Uf(th); function xh(a) { if (a === th) throw Error(p(174)); return a; } function yh(a, b) { G(wh, b); G(vh, a); G(uh, th); a = b.nodeType; switch (a) { case 9: case 11: b = (b = b.documentElement) ? b.namespaceURI : lb(null, ""); break; default: a = 8 === a ? b.parentNode : b, b = a.namespaceURI || null, a = a.tagName, b = lb(b, a); } E(uh); G(uh, b); } function zh() { E(uh); E(vh); E(wh); } function Ah(a) { xh(wh.current); var b = xh(uh.current); var c = lb(b, a.type); b !== c && (G(vh, a), G(uh, c)); } function Bh(a) { vh.current === a && (E(uh), E(vh)); } var L = Uf(0); function Ch(a) { for (var b = a; null !== b; ) { if (13 === b.tag) { var c = b.memoizedState; if (null !== c && (c = c.dehydrated, null === c || "$?" === c.data || "$!" === c.data)) return b; } else if (19 === b.tag && void 0 !== b.memoizedProps.revealOrder) { if (0 !== (b.flags & 128)) return b; } else if (null !== b.child) { b.child.return = b; b = b.child; continue; } if (b === a) break; for (; null === b.sibling; ) { if (null === b.return || b.return === a) return null; b = b.return; } b.sibling.return = b.return; b = b.sibling; } return null; } var Dh = []; function Eh() { for (var a = 0; a < Dh.length; a++) Dh[a]._workInProgressVersionPrimary = null; Dh.length = 0; } var Fh = ua.ReactCurrentDispatcher, Gh = ua.ReactCurrentBatchConfig, Hh = 0, M = null, N = null, O = null, Ih = false, Jh = false, Kh = 0, Lh = 0; function P() { throw Error(p(321)); } function Mh(a, b) { if (null === b) return false; for (var c = 0; c < b.length && c < a.length; c++) if (!He(a[c], b[c])) return false; return true; } function Nh(a, b, c, d, e, f) { Hh = f; M = b; b.memoizedState = null; b.updateQueue = null; b.lanes = 0; Fh.current = null === a || null === a.memoizedState ? Oh : Ph; a = c(d, e); if (Jh) { f = 0; do { Jh = false; Kh = 0; if (25 <= f) throw Error(p(301)); f += 1; O = N = null; b.updateQueue = null; Fh.current = Qh; a = c(d, e); } while (Jh); } Fh.current = Rh; b = null !== N && null !== N.next; Hh = 0; O = N = M = null; Ih = false; if (b) throw Error(p(300)); return a; } function Sh() { var a = 0 !== Kh; Kh = 0; return a; } function Th() { var a = { memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null }; null === O ? M.memoizedState = O = a : O = O.next = a; return O; } function Uh() { if (null === N) { var a = M.alternate; a = null !== a ? a.memoizedState : null; } else a = N.next; var b = null === O ? M.memoizedState : O.next; if (null !== b) O = b, N = a; else { if (null === a) throw Error(p(310)); N = a; a = { memoizedState: N.memoizedState, baseState: N.baseState, baseQueue: N.baseQueue, queue: N.queue, next: null }; null === O ? M.memoizedState = O = a : O = O.next = a; } return O; } function Vh(a, b) { return "function" === typeof b ? b(a) : b; } function Wh(a) { var b = Uh(), c = b.queue; if (null === c) throw Error(p(311)); c.lastRenderedReducer = a; var d = N, e = d.baseQueue, f = c.pending; if (null !== f) { if (null !== e) { var g = e.next; e.next = f.next; f.next = g; } d.baseQueue = e = f; c.pending = null; } if (null !== e) { f = e.next; d = d.baseState; var h2 = g = null, k = null, l = f; do { var m = l.lane; if ((Hh & m) === m) null !== k && (k = k.next = { lane: 0, action: l.action, hasEagerState: l.hasEagerState, eagerState: l.eagerState, next: null }), d = l.hasEagerState ? l.eagerState : a(d, l.action); else { var q = { lane: m, action: l.action, hasEagerState: l.hasEagerState, eagerState: l.eagerState, next: null }; null === k ? (h2 = k = q, g = d) : k = k.next = q; M.lanes |= m; rh |= m; } l = l.next; } while (null !== l && l !== f); null === k ? g = d : k.next = h2; He(d, b.memoizedState) || (dh = true); b.memoizedState = d; b.baseState = g; b.baseQueue = k; c.lastRenderedState = d; } a = c.interleaved; if (null !== a) { e = a; do f = e.lane, M.lanes |= f, rh |= f, e = e.next; while (e !== a); } else null === e && (c.lanes = 0); return [b.memoizedState, c.dispatch]; } function Xh(a) { var b = Uh(), c = b.queue; if (null === c) throw Error(p(311)); c.lastRenderedReducer = a; var d = c.dispatch, e = c.pending, f = b.memoizedState; if (null !== e) { c.pending = null; var g = e = e.next; do f = a(f, g.action), g = g.next; while (g !== e); He(f, b.memoizedState) || (dh = true); b.memoizedState = f; null === b.baseQueue && (b.baseState = f); c.lastRenderedState = f; } return [f, d]; } function Yh() { } function Zh(a, b) { var c = M, d = Uh(), e = b(), f = !He(d.memoizedState, e); f && (d.memoizedState = e, dh = true); d = d.queue; $h(ai.bind(null, c, d, a), [a]); if (d.getSnapshot !== b || f || null !== O && O.memoizedState.tag & 1) { c.flags |= 2048; bi(9, ci.bind(null, c, d, e, b), void 0, null); if (null === Q) throw Error(p(349)); 0 !== (Hh & 30) || di(c, b, e); } return e; } function di(a, b, c) { a.flags |= 16384; a = { getSnapshot: b, value: c }; b = M.updateQueue; null === b ? (b = { lastEffect: null, stores: null }, M.updateQueue = b, b.stores = [a]) : (c = b.stores, null === c ? b.stores = [a] : c.push(a)); } function ci(a, b, c, d) { b.value = c; b.getSnapshot = d; ei(b) && fi(a); } function ai(a, b, c) { return c(function() { ei(b) && fi(a); }); } function ei(a) { var b = a.getSnapshot; a = a.value; try { var c = b(); return !He(a, c); } catch (d) { return true; } } function fi(a) { var b = ih(a, 1); null !== b && gi(b, a, 1, -1); } function hi(a) { var b = Th(); "function" === typeof a && (a = a()); b.memoizedState = b.baseState = a; a = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: Vh, lastRenderedState: a }; b.queue = a; a = a.dispatch = ii.bind(null, M, a); return [b.memoizedState, a]; } function bi(a, b, c, d) { a = { tag: a, create: b, destroy: c, deps: d, next: null }; b = M.updateQueue; null === b ? (b = { lastEffect: null, stores: null }, M.updateQueue = b, b.lastEffect = a.next = a) : (c = b.lastEffect, null === c ? b.lastEffect = a.next = a : (d = c.next, c.next = a, a.next = d, b.lastEffect = a)); return a; } function ji() { return Uh().memoizedState; } function ki(a, b, c, d) { var e = Th(); M.flags |= a; e.memoizedState = bi(1 | b, c, void 0, void 0 === d ? null : d); } function li(a, b, c, d) { var e = Uh(); d = void 0 === d ? null : d; var f = void 0; if (null !== N) { var g = N.memoizedState; f = g.destroy; if (null !== d && Mh(d, g.deps)) { e.memoizedState = bi(b, c, f, d); return; } } M.flags |= a; e.memoizedState = bi(1 | b, c, f, d); } function mi(a, b) { return ki(8390656, 8, a, b); } function $h(a, b) { return li(2048, 8, a, b); } function ni(a, b) { return li(4, 2, a, b); } function oi(a, b) { return li(4, 4, a, b); } function pi(a, b) { if ("function" === typeof b) return a = a(), b(a), function() { b(null); }; if (null !== b && void 0 !== b) return a = a(), b.current = a, function() { b.current = null; }; } function qi(a, b, c) { c = null !== c && void 0 !== c ? c.concat([a]) : null; return li(4, 4, pi.bind(null, b, a), c); } function ri() { } function si(a, b) { var c = Uh(); b = void 0 === b ? null : b; var d = c.memoizedState; if (null !== d && null !== b && Mh(b, d[1])) return d[0]; c.memoizedState = [a, b]; return a; } function ti(a, b) { var c = Uh(); b = void 0 === b ? null : b; var d = c.memoizedState; if (null !== d && null !== b && Mh(b, d[1])) return d[0]; a = a(); c.memoizedState = [a, b]; return a; } function ui(a, b, c) { if (0 === (Hh & 21)) return a.baseState && (a.baseState = false, dh = true), a.memoizedState = c; He(c, b) || (c = yc(), M.lanes |= c, rh |= c, a.baseState = true); return b; } function vi(a, b) { var c = C; C = 0 !== c && 4 > c ? c : 4; a(true); var d = Gh.transition; Gh.transition = {}; try { a(false), b(); } finally { C = c, Gh.transition = d; } } function wi() { return Uh().memoizedState; } function xi(a, b, c) { var d = yi(a); c = { lane: d, action: c, hasEagerState: false, eagerState: null, next: null }; if (zi(a)) Ai(b, c); else if (c = hh(a, b, c, d), null !== c) { var e = R(); gi(c, a, d, e); Bi(c, b, d); } } function ii(a, b, c) { var d = yi(a), e = { lane: d, action: c, hasEagerState: false, eagerState: null, next: null }; if (zi(a)) Ai(b, e); else { var f = a.alternate; if (0 === a.lanes && (null === f || 0 === f.lanes) && (f = b.lastRenderedReducer, null !== f)) try { var g = b.lastRenderedState, h2 = f(g, c); e.hasEagerState = true; e.eagerState = h2; if (He(h2, g)) { var k = b.interleaved; null === k ? (e.next = e, gh(b)) : (e.next = k.next, k.next = e); b.interleaved = e; return; } } catch (l) { } finally { } c = hh(a, b, e, d); null !== c && (e = R(), gi(c, a, d, e), Bi(c, b, d)); } } function zi(a) { var b = a.alternate; return a === M || null !== b && b === M; } function Ai(a, b) { Jh = Ih = true; var c = a.pending; null === c ? b.next = b : (b.next = c.next, c.next = b); a.pending = b; } function Bi(a, b, c) { if (0 !== (c & 4194240)) { var d = b.lanes; d &= a.pendingLanes; c |= d; b.lanes = c; Cc(a, c); } } var Rh = { readContext: eh, useCallback: P, useContext: P, useEffect: P, useImperativeHandle: P, useInsertionEffect: P, useLayoutEffect: P, useMemo: P, useReducer: P, useRef: P, useState: P, useDebugValue: P, useDeferredValue: P, useTransition: P, useMutableSource: P, useSyncExternalStore: P, useId: P, unstable_isNewReconciler: false }, Oh = { readContext: eh, useCallback: function(a, b) { Th().memoizedState = [a, void 0 === b ? null : b]; return a; }, useContext: eh, useEffect: mi, useImperativeHandle: function(a, b, c) { c = null !== c && void 0 !== c ? c.concat([a]) : null; return ki( 4194308, 4, pi.bind(null, b, a), c ); }, useLayoutEffect: function(a, b) { return ki(4194308, 4, a, b); }, useInsertionEffect: function(a, b) { return ki(4, 2, a, b); }, useMemo: function(a, b) { var c = Th(); b = void 0 === b ? null : b; a = a(); c.memoizedState = [a, b]; return a; }, useReducer: function(a, b, c) { var d = Th(); b = void 0 !== c ? c(b) : b; d.memoizedState = d.baseState = b; a = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: a, lastRenderedState: b }; d.queue = a; a = a.dispatch = xi.bind(null, M, a); return [d.memoizedState, a]; }, useRef: function(a) { var b = Th(); a = { current: a }; return b.memoizedState = a; }, useState: hi, useDebugValue: ri, useDeferredValue: function(a) { return Th().memoizedState = a; }, useTransition: function() { var a = hi(false), b = a[0]; a = vi.bind(null, a[1]); Th().memoizedState = a; return [b, a]; }, useMutableSource: function() { }, useSyncExternalStore: function(a, b, c) { var d = M, e = Th(); if (I) { if (void 0 === c) throw Error(p(407)); c = c(); } else { c = b(); if (null === Q) throw Error(p(349)); 0 !== (Hh & 30) || di(d, b, c); } e.memoizedState = c; var f = { value: c, getSnapshot: b }; e.queue = f; mi(ai.bind( null, d, f, a ), [a]); d.flags |= 2048; bi(9, ci.bind(null, d, f, c, b), void 0, null); return c; }, useId: function() { var a = Th(), b = Q.identifierPrefix; if (I) { var c = sg; var d = rg; c = (d & ~(1 << 32 - oc(d) - 1)).toString(32) + c; b = ":" + b + "R" + c; c = Kh++; 0 < c && (b += "H" + c.toString(32)); b += ":"; } else c = Lh++, b = ":" + b + "r" + c.toString(32) + ":"; return a.memoizedState = b; }, unstable_isNewReconciler: false }, Ph = { readContext: eh, useCallback: si, useContext: eh, useEffect: $h, useImperativeHandle: qi, useInsertionEffect: ni, useLayoutEffect: oi, useMemo: ti, useReducer: Wh, useRef: ji, useState: function() { return Wh(Vh); }, useDebugValue: ri, useDeferredValue: function(a) { var b = Uh(); return ui(b, N.memoizedState, a); }, useTransition: function() { var a = Wh(Vh)[0], b = Uh().memoizedState; return [a, b]; }, useMutableSource: Yh, useSyncExternalStore: Zh, useId: wi, unstable_isNewReconciler: false }, Qh = { readContext: eh, useCallback: si, useContext: eh, useEffect: $h, useImperativeHandle: qi, useInsertionEffect: ni, useLayoutEffect: oi, useMemo: ti, useReducer: Xh, useRef: ji, useState: function() { return Xh(Vh); }, useDebugValue: ri, useDeferredValue: function(a) { var b = Uh(); return null === N ? b.memoizedState = a : ui(b, N.memoizedState, a); }, useTransition: function() { var a = Xh(Vh)[0], b = Uh().memoizedState; return [a, b]; }, useMutableSource: Yh, useSyncExternalStore: Zh, useId: wi, unstable_isNewReconciler: false }; function Ci(a, b) { if (a && a.defaultProps) { b = A({}, b); a = a.defaultProps; for (var c in a) void 0 === b[c] && (b[c] = a[c]); return b; } return b; } function Di(a, b, c, d) { b = a.memoizedState; c = c(d, b); c = null === c || void 0 === c ? b : A({}, b, c); a.memoizedState = c; 0 === a.lanes && (a.updateQueue.baseState = c); } var Ei = { isMounted: function(a) { return (a = a._reactInternals) ? Vb(a) === a : false; }, enqueueSetState: function(a, b, c) { a = a._reactInternals; var d = R(), e = yi(a), f = mh(d, e); f.payload = b; void 0 !== c && null !== c && (f.callback = c); b = nh(a, f, e); null !== b && (gi(b, a, e, d), oh(b, a, e)); }, enqueueReplaceState: function(a, b, c) { a = a._reactInternals; var d = R(), e = yi(a), f = mh(d, e); f.tag = 1; f.payload = b; void 0 !== c && null !== c && (f.callback = c); b = nh(a, f, e); null !== b && (gi(b, a, e, d), oh(b, a, e)); }, enqueueForceUpdate: function(a, b) { a = a._reactInternals; var c = R(), d = yi(a), e = mh(c, d); e.tag = 2; void 0 !== b && null !== b && (e.callback = b); b = nh(a, e, d); null !== b && (gi(b, a, d, c), oh(b, a, d)); } }; function Fi(a, b, c, d, e, f, g) { a = a.stateNode; return "function" === typeof a.shouldComponentUpdate ? a.shouldComponentUpdate(d, f, g) : b.prototype && b.prototype.isPureReactComponent ? !Ie(c, d) || !Ie(e, f) : true; } function Gi(a, b, c) { var d = false, e = Vf; var f = b.contextType; "object" === typeof f && null !== f ? f = eh(f) : (e = Zf(b) ? Xf : H.current, d = b.contextTypes, f = (d = null !== d && void 0 !== d) ? Yf(a, e) : Vf); b = new b(c, f); a.memoizedState = null !== b.state && void 0 !== b.state ? b.state : null; b.updater = Ei; a.stateNode = b; b._reactInternals = a; d && (a = a.stateNode, a.__reactInternalMemoizedUnmaskedChildContext = e, a.__reactInternalMemoizedMaskedChildContext = f); return b; } function Hi(a, b, c, d) { a = b.state; "function" === typeof b.componentWillReceiveProps && b.componentWillReceiveProps(c, d); "function" === typeof b.UNSAFE_componentWillReceiveProps && b.UNSAFE_componentWillReceiveProps(c, d); b.state !== a && Ei.enqueueReplaceState(b, b.state, null); } function Ii(a, b, c, d) { var e = a.stateNode; e.props = c; e.state = a.memoizedState; e.refs = {}; kh(a); var f = b.contextType; "object" === typeof f && null !== f ? e.context = eh(f) : (f = Zf(b) ? Xf : H.current, e.context = Yf(a, f)); e.state = a.memoizedState; f = b.getDerivedStateFromProps; "function" === typeof f && (Di(a, b, f, c), e.state = a.memoizedState); "function" === typeof b.getDerivedStateFromProps || "function" === typeof e.getSnapshotBeforeUpdate || "function" !== typeof e.UNSAFE_componentWillMount && "function" !== typeof e.componentWillMount || (b = e.state, "function" === typeof e.componentWillMount && e.componentWillMount(), "function" === typeof e.UNSAFE_componentWillMount && e.UNSAFE_componentWillMount(), b !== e.state && Ei.enqueueReplaceState(e, e.state, null), qh(a, c, e, d), e.state = a.memoizedState); "function" === typeof e.componentDidMount && (a.flags |= 4194308); } function Ji(a, b) { try { var c = "", d = b; do c += Pa(d), d = d.return; while (d); var e = c; } catch (f) { e = "\nError generating stack: " + f.message + "\n" + f.stack; } return { value: a, source: b, stack: e, digest: null }; } function Ki(a, b, c) { return { value: a, source: null, stack: null != c ? c : null, digest: null != b ? b : null }; } function Li(a, b) { try { console.error(b.value); } catch (c) { setTimeout(function() { throw c; }); } } var Mi = "function" === typeof WeakMap ? WeakMap : Map; function Ni(a, b, c) { c = mh(-1, c); c.tag = 3; c.payload = { element: null }; var d = b.value; c.callback = function() { Oi || (Oi = true, Pi = d); Li(a, b); }; return c; } function Qi(a, b, c) { c = mh(-1, c); c.tag = 3; var d = a.type.getDerivedStateFromError; if ("function" === typeof d) { var e = b.value; c.payload = function() { return d(e); }; c.callback = function() { Li(a, b); }; } var f = a.stateNode; null !== f && "function" === typeof f.componentDidCatch && (c.callback = function() { Li(a, b); "function" !== typeof d && (null === Ri ? Ri = /* @__PURE__ */ new Set([this]) : Ri.add(this)); var c2 = b.stack; this.componentDidCatch(b.value, { componentStack: null !== c2 ? c2 : "" }); }); return c; } function Si(a, b, c) { var d = a.pingCache; if (null === d) { d = a.pingCache = new Mi(); var e = /* @__PURE__ */ new Set(); d.set(b, e); } else e = d.get(b), void 0 === e && (e = /* @__PURE__ */ new Set(), d.set(b, e)); e.has(c) || (e.add(c), a = Ti.bind(null, a, b, c), b.then(a, a)); } function Ui(a) { do { var b; if (b = 13 === a.tag) b = a.memoizedState, b = null !== b ? null !== b.dehydrated ? true : false : true; if (b) return a; a = a.return; } while (null !== a); return null; } function Vi(a, b, c, d, e) { if (0 === (a.mode & 1)) return a === b ? a.flags |= 65536 : (a.flags |= 128, c.flags |= 131072, c.flags &= -52805, 1 === c.tag && (null === c.alternate ? c.tag = 17 : (b = mh(-1, 1), b.tag = 2, nh(c, b, 1))), c.lanes |= 1), a; a.flags |= 65536; a.lanes = e; return a; } var Wi = ua.ReactCurrentOwner, dh = false; function Xi(a, b, c, d) { b.child = null === a ? Vg(b, null, c, d) : Ug(b, a.child, c, d); } function Yi(a, b, c, d, e) { c = c.render; var f = b.ref; ch(b, e); d = Nh(a, b, c, d, f, e); c = Sh(); if (null !== a && !dh) return b.updateQueue = a.updateQueue, b.flags &= -2053, a.lanes &= ~e, Zi(a, b, e); I && c && vg(b); b.flags |= 1; Xi(a, b, d, e); return b.child; } function $i(a, b, c, d, e) { if (null === a) { var f = c.type; if ("function" === typeof f && !aj(f) && void 0 === f.defaultProps && null === c.compare && void 0 === c.defaultProps) return b.tag = 15, b.type = f, bj(a, b, f, d, e); a = Rg(c.type, null, d, b, b.mode, e); a.ref = b.ref; a.return = b; return b.child = a; } f = a.child; if (0 === (a.lanes & e)) { var g = f.memoizedProps; c = c.compare; c = null !== c ? c : Ie; if (c(g, d) && a.ref === b.ref) return Zi(a, b, e); } b.flags |= 1; a = Pg(f, d); a.ref = b.ref; a.return = b; return b.child = a; } function bj(a, b, c, d, e) { if (null !== a) { var f = a.memoizedProps; if (Ie(f, d) && a.ref === b.ref) if (dh = false, b.pendingProps = d = f, 0 !== (a.lanes & e)) 0 !== (a.flags & 131072) && (dh = true); else return b.lanes = a.lanes, Zi(a, b, e); } return cj(a, b, c, d, e); } function dj(a, b, c) { var d = b.pendingProps, e = d.children, f = null !== a ? a.memoizedState : null; if ("hidden" === d.mode) if (0 === (b.mode & 1)) b.memoizedState = { baseLanes: 0, cachePool: null, transitions: null }, G(ej, fj), fj |= c; else { if (0 === (c & 1073741824)) return a = null !== f ? f.baseLanes | c : c, b.lanes = b.childLanes = 1073741824, b.memoizedState = { baseLanes: a, cachePool: null, transitions: null }, b.updateQueue = null, G(ej, fj), fj |= a, null; b.memoizedState = { baseLanes: 0, cachePool: null, transitions: null }; d = null !== f ? f.baseLanes : c; G(ej, fj); fj |= d; } else null !== f ? (d = f.baseLanes | c, b.memoizedState = null) : d = c, G(ej, fj), fj |= d; Xi(a, b, e, c); return b.child; } function gj(a, b) { var c = b.ref; if (null === a && null !== c || null !== a && a.ref !== c) b.flags |= 512, b.flags |= 2097152; } function cj(a, b, c, d, e) { var f = Zf(c) ? Xf : H.current; f = Yf(b, f); ch(b, e); c = Nh(a, b, c, d, f, e); d = Sh(); if (null !== a && !dh) return b.updateQueue = a.updateQueue, b.flags &= -2053, a.lanes &= ~e, Zi(a, b, e); I && d && vg(b); b.flags |= 1; Xi(a, b, c, e); return b.child; } function hj(a, b, c, d, e) { if (Zf(c)) { var f = true; cg(b); } else f = false; ch(b, e); if (null === b.stateNode) ij(a, b), Gi(b, c, d), Ii(b, c, d, e), d = true; else if (null === a) { var g = b.stateNode, h2 = b.memoizedProps; g.props = h2; var k = g.context, l = c.contextType; "object" === typeof l && null !== l ? l = eh(l) : (l = Zf(c) ? Xf : H.current, l = Yf(b, l)); var m = c.getDerivedStateFromProps, q = "function" === typeof m || "function" === typeof g.getSnapshotBeforeUpdate; q || "function" !== typeof g.UNSAFE_componentWillReceiveProps && "function" !== typeof g.componentWillReceiveProps || (h2 !== d || k !== l) && Hi(b, g, d, l); jh = false; var r = b.memoizedState; g.state = r; qh(b, d, g, e); k = b.memoizedState; h2 !== d || r !== k || Wf.current || jh ? ("function" === typeof m && (Di(b, c, m, d), k = b.memoizedState), (h2 = jh || Fi(b, c, h2, d, r, k, l)) ? (q || "function" !== typeof g.UNSAFE_componentWillMount && "function" !== typeof g.componentWillMount || ("function" === typeof g.componentWillMount && g.componentWillMount(), "function" === typeof g.UNSAFE_componentWillMount && g.UNSAFE_componentWillMount()), "function" === typeof g.componentDidMount && (b.flags |= 4194308)) : ("function" === typeof g.componentDidMount && (b.flags |= 4194308), b.memoizedProps = d, b.memoizedState = k), g.props = d, g.state = k, g.context = l, d = h2) : ("function" === typeof g.componentDidMount && (b.flags |= 4194308), d = false); } else { g = b.stateNode; lh(a, b); h2 = b.memoizedProps; l = b.type === b.elementType ? h2 : Ci(b.type, h2); g.props = l; q = b.pendingProps; r = g.context; k = c.contextType; "object" === typeof k && null !== k ? k = eh(k) : (k = Zf(c) ? Xf : H.current, k = Yf(b, k)); var y = c.getDerivedStateFromProps; (m = "function" === typeof y || "function" === typeof g.getSnapshotBeforeUpdate) || "function" !== typeof g.UNSAFE_componentWillReceiveProps && "function" !== typeof g.componentWillReceiveProps || (h2 !== q || r !== k) && Hi(b, g, d, k); jh = false; r = b.memoizedState; g.state = r; qh(b, d, g, e); var n = b.memoizedState; h2 !== q || r !== n || Wf.current || jh ? ("function" === typeof y && (Di(b, c, y, d), n = b.memoizedState), (l = jh || Fi(b, c, l, d, r, n, k) || false) ? (m || "function" !== typeof g.UNSAFE_componentWillUpdate && "function" !== typeof g.componentWillUpdate || ("function" === typeof g.componentWillUpdate && g.componentWillUpdate(d, n, k), "function" === typeof g.UNSAFE_componentWillUpdate && g.UNSAFE_componentWillUpdate(d, n, k)), "function" === typeof g.componentDidUpdate && (b.flags |= 4), "function" === typeof g.getSnapshotBeforeUpdate && (b.flags |= 1024)) : ("function" !== typeof g.componentDidUpdate || h2 === a.memoizedProps && r === a.memoizedState || (b.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h2 === a.memoizedProps && r === a.memoizedState || (b.flags |= 1024), b.memoizedProps = d, b.memoizedState = n), g.props = d, g.state = n, g.context = k, d = l) : ("function" !== typeof g.componentDidUpdate || h2 === a.memoizedProps && r === a.memoizedState || (b.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h2 === a.memoizedProps && r === a.memoizedState || (b.flags |= 1024), d = false); } return jj(a, b, c, d, f, e); } function jj(a, b, c, d, e, f) { gj(a, b); var g = 0 !== (b.flags & 128); if (!d && !g) return e && dg(b, c, false), Zi(a, b, f); d = b.stateNode; Wi.current = b; var h2 = g && "function" !== typeof c.getDerivedStateFromError ? null : d.render(); b.flags |= 1; null !== a && g ? (b.child = Ug(b, a.child, null, f), b.child = Ug(b, null, h2, f)) : Xi(a, b, h2, f); b.memoizedState = d.state; e && dg(b, c, true); return b.child; } function kj(a) { var b = a.stateNode; b.pendingContext ? ag(a, b.pendingContext, b.pendingContext !== b.context) : b.context && ag(a, b.context, false); yh(a, b.containerInfo); } function lj(a, b, c, d, e) { Ig(); Jg(e); b.flags |= 256; Xi(a, b, c, d); return b.child; } var mj = { dehydrated: null, treeContext: null, retryLane: 0 }; function nj(a) { return { baseLanes: a, cachePool: null, transitions: null }; } function oj(a, b, c) { var d = b.pendingProps, e = L.current, f = false, g = 0 !== (b.flags & 128), h2; (h2 = g) || (h2 = null !== a && null === a.memoizedState ? false : 0 !== (e & 2)); if (h2) f = true, b.flags &= -129; else if (null === a || null !== a.memoizedState) e |= 1; G(L, e & 1); if (null === a) { Eg(b); a = b.memoizedState; if (null !== a && (a = a.dehydrated, null !== a)) return 0 === (b.mode & 1) ? b.lanes = 1 : "$!" === a.data ? b.lanes = 8 : b.lanes = 1073741824, null; g = d.children; a = d.fallback; return f ? (d = b.mode, f = b.child, g = { mode: "hidden", children: g }, 0 === (d & 1) && null !== f ? (f.childLanes = 0, f.pendingProps = g) : f = pj(g, d, 0, null), a = Tg(a, d, c, null), f.return = b, a.return = b, f.sibling = a, b.child = f, b.child.memoizedState = nj(c), b.memoizedState = mj, a) : qj(b, g); } e = a.memoizedState; if (null !== e && (h2 = e.dehydrated, null !== h2)) return rj(a, b, g, d, h2, e, c); if (f) { f = d.fallback; g = b.mode; e = a.child; h2 = e.sibling; var k = { mode: "hidden", children: d.children }; 0 === (g & 1) && b.child !== e ? (d = b.child, d.childLanes = 0, d.pendingProps = k, b.deletions = null) : (d = Pg(e, k), d.subtreeFlags = e.subtreeFlags & 14680064); null !== h2 ? f = Pg(h2, f) : (f = Tg(f, g, c, null), f.flags |= 2); f.return = b; d.return = b; d.sibling = f; b.child = d; d = f; f = b.child; g = a.child.memoizedState; g = null === g ? nj(c) : { baseLanes: g.baseLanes | c, cachePool: null, transitions: g.transitions }; f.memoizedState = g; f.childLanes = a.childLanes & ~c; b.memoizedState = mj; return d; } f = a.child; a = f.sibling; d = Pg(f, { mode: "visible", children: d.children }); 0 === (b.mode & 1) && (d.lanes = c); d.return = b; d.sibling = null; null !== a && (c = b.deletions, null === c ? (b.deletions = [a], b.flags |= 16) : c.push(a)); b.child = d; b.memoizedState = null; return d; } function qj(a, b) { b = pj({ mode: "visible", children: b }, a.mode, 0, null); b.return = a; return a.child = b; } function sj(a, b, c, d) { null !== d && Jg(d); Ug(b, a.child, null, c); a = qj(b, b.pendingProps.children); a.flags |= 2; b.memoizedState = null; return a; } function rj(a, b, c, d, e, f, g) { if (c) { if (b.flags & 256) return b.flags &= -257, d = Ki(Error(p(422))), sj(a, b, g, d); if (null !== b.memoizedState) return b.child = a.child, b.flags |= 128, null; f = d.fallback; e = b.mode; d = pj({ mode: "visible", children: d.children }, e, 0, null); f = Tg(f, e, g, null); f.flags |= 2; d.return = b; f.return = b; d.sibling = f; b.child = d; 0 !== (b.mode & 1) && Ug(b, a.child, null, g); b.child.memoizedState = nj(g); b.memoizedState = mj; return f; } if (0 === (b.mode & 1)) return sj(a, b, g, null); if ("$!" === e.data) { d = e.nextSibling && e.nextSibling.dataset; if (d) var h2 = d.dgst; d = h2; f = Error(p(419)); d = Ki(f, d, void 0); return sj(a, b, g, d); } h2 = 0 !== (g & a.childLanes); if (dh || h2) { d = Q; if (null !== d) { switch (g & -g) { case 4: e = 2; break; case 16: e = 8; break; case 64: case 128: case 256: case 512: case 1024: case 2048: case 4096: case 8192: case 16384: case 32768: case 65536: case 131072: case 262144: case 524288: case 1048576: case 2097152: case 4194304: case 8388608: case 16777216: case 33554432: case 67108864: e = 32; break; case 536870912: e = 268435456; break; default: e = 0; } e = 0 !== (e & (d.suspendedLanes | g)) ? 0 : e; 0 !== e && e !== f.retryLane && (f.retryLane = e, ih(a, e), gi(d, a, e, -1)); } tj(); d = Ki(Error(p(421))); return sj(a, b, g, d); } if ("$?" === e.data) return b.flags |= 128, b.child = a.child, b = uj.bind(null, a), e._reactRetry = b, null; a = f.treeContext; yg = Lf(e.nextSibling); xg = b; I = true; zg = null; null !== a && (og[pg++] = rg, og[pg++] = sg, og[pg++] = qg, rg = a.id, sg = a.overflow, qg = b); b = qj(b, d.children); b.flags |= 4096; return b; } function vj(a, b, c) { a.lanes |= b; var d = a.alternate; null !== d && (d.lanes |= b); bh(a.return, b, c); } function wj(a, b, c, d, e) { var f = a.memoizedState; null === f ? a.memoizedState = { isBackwards: b, rendering: null, renderingStartTime: 0, last: d, tail: c, tailMode: e } : (f.isBackwards = b, f.rendering = null, f.renderingStartTime = 0, f.last = d, f.tail = c, f.tailMode = e); } function xj(a, b, c) { var d = b.pendingProps, e = d.revealOrder, f = d.tail; Xi(a, b, d.children, c); d = L.current; if (0 !== (d & 2)) d = d & 1 | 2, b.flags |= 128; else { if (null !== a && 0 !== (a.flags & 128)) a: for (a = b.child; null !== a; ) { if (13 === a.tag) null !== a.memoizedState && vj(a, c, b); else if (19 === a.tag) vj(a, c, b); else if (null !== a.child) { a.child.return = a; a = a.child; continue; } if (a === b) break a; for (; null === a.sibling; ) { if (null === a.return || a.return === b) break a; a = a.return; } a.sibling.return = a.return; a = a.sibling; } d &= 1; } G(L, d); if (0 === (b.mode & 1)) b.memoizedState = null; else switch (e) { case "forwards": c = b.child; for (e = null; null !== c; ) a = c.alternate, null !== a && null === Ch(a) && (e = c), c = c.sibling; c = e; null === c ? (e = b.child, b.child = null) : (e = c.sibling, c.sibling = null); wj(b, false, e, c, f); break; case "backwards": c = null; e = b.child; for (b.child = null; null !== e; ) { a = e.alternate; if (null !== a && null === Ch(a)) { b.child = e; break; } a = e.sibling; e.sibling = c; c = e; e = a; } wj(b, true, c, null, f); break; case "together": wj(b, false, null, null, void 0); break; default: b.memoizedState = null; } return b.child; } function ij(a, b) { 0 === (b.mode & 1) && null !== a && (a.alternate = null, b.alternate = null, b.flags |= 2); } function Zi(a, b, c) { null !== a && (b.dependencies = a.dependencies); rh |= b.lanes; if (0 === (c & b.childLanes)) return null; if (null !== a && b.child !== a.child) throw Error(p(153)); if (null !== b.child) { a = b.child; c = Pg(a, a.pendingProps); b.child = c; for (c.return = b; null !== a.sibling; ) a = a.sibling, c = c.sibling = Pg(a, a.pendingProps), c.return = b; c.sibling = null; } return b.child; } function yj(a, b, c) { switch (b.tag) { case 3: kj(b); Ig(); break; case 5: Ah(b); break; case 1: Zf(b.type) && cg(b); break; case 4: yh(b, b.stateNode.containerInfo); break; case 10: var d = b.type._context, e = b.memoizedProps.value; G(Wg, d._currentValue); d._currentValue = e; break; case 13: d = b.memoizedState; if (null !== d) { if (null !== d.dehydrated) return G(L, L.current & 1), b.flags |= 128, null; if (0 !== (c & b.child.childLanes)) return oj(a, b, c); G(L, L.current & 1); a = Zi(a, b, c); return null !== a ? a.sibling : null; } G(L, L.current & 1); break; case 19: d = 0 !== (c & b.childLanes); if (0 !== (a.flags & 128)) { if (d) return xj(a, b, c); b.flags |= 128; } e = b.memoizedState; null !== e && (e.rendering = null, e.tail = null, e.lastEffect = null); G(L, L.current); if (d) break; else return null; case 22: case 23: return b.lanes = 0, dj(a, b, c); } return Zi(a, b, c); } var zj, Aj, Bj, Cj; zj = function(a, b) { for (var c = b.child; null !== c; ) { if (5 === c.tag || 6 === c.tag) a.appendChild(c.stateNode); else if (4 !== c.tag && null !== c.child) { c.child.return = c; c = c.child; continue; } if (c === b) break; for (; null === c.sibling; ) { if (null === c.return || c.return === b) return; c = c.return; } c.sibling.return = c.return; c = c.sibling; } }; Aj = function() { }; Bj = function(a, b, c, d) { var e = a.memoizedProps; if (e !== d) { a = b.stateNode; xh(uh.current); var f = null; switch (c) { case "input": e = Ya(a, e); d = Ya(a, d); f = []; break; case "select": e = A({}, e, { value: void 0 }); d = A({}, d, { value: void 0 }); f = []; break; case "textarea": e = gb(a, e); d = gb(a, d); f = []; break; default: "function" !== typeof e.onClick && "function" === typeof d.onClick && (a.onclick = Bf); } ub(c, d); var g; c = null; for (l in e) if (!d.hasOwnProperty(l) && e.hasOwnProperty(l) && null != e[l]) if ("style" === l) { var h2 = e[l]; for (g in h2) h2.hasOwnProperty(g) && (c || (c = {}), c[g] = ""); } else "dangerouslySetInnerHTML" !== l && "children" !== l && "suppressContentEditableWarning" !== l && "suppressHydrationWarning" !== l && "autoFocus" !== l && (ea.hasOwnProperty(l) ? f || (f = []) : (f = f || []).push(l, null)); for (l in d) { var k = d[l]; h2 = null != e ? e[l] : void 0; if (d.hasOwnProperty(l) && k !== h2 && (null != k || null != h2)) if ("style" === l) if (h2) { for (g in h2) !h2.hasOwnProperty(g) || k && k.hasOwnProperty(g) || (c || (c = {}), c[g] = ""); for (g in k) k.hasOwnProperty(g) && h2[g] !== k[g] && (c || (c = {}), c[g] = k[g]); } else c || (f || (f = []), f.push( l, c )), c = k; else "dangerouslySetInnerHTML" === l ? (k = k ? k.__html : void 0, h2 = h2 ? h2.__html : void 0, null != k && h2 !== k && (f = f || []).push(l, k)) : "children" === l ? "string" !== typeof k && "number" !== typeof k || (f = f || []).push(l, "" + k) : "suppressContentEditableWarning" !== l && "suppressHydrationWarning" !== l && (ea.hasOwnProperty(l) ? (null != k && "onScroll" === l && D("scroll", a), f || h2 === k || (f = [])) : (f = f || []).push(l, k)); } c && (f = f || []).push("style", c); var l = f; if (b.updateQueue = l) b.flags |= 4; } }; Cj = function(a, b, c, d) { c !== d && (b.flags |= 4); }; function Dj(a, b) { if (!I) switch (a.tailMode) { case "hidden": b = a.tail; for (var c = null; null !== b; ) null !== b.alternate && (c = b), b = b.sibling; null === c ? a.tail = null : c.sibling = null; break; case "collapsed": c = a.tail; for (var d = null; null !== c; ) null !== c.alternate && (d = c), c = c.sibling; null === d ? b || null === a.tail ? a.tail = null : a.tail.sibling = null : d.sibling = null; } } function S(a) { var b = null !== a.alternate && a.alternate.child === a.child, c = 0, d = 0; if (b) for (var e = a.child; null !== e; ) c |= e.lanes | e.childLanes, d |= e.subtreeFlags & 14680064, d |= e.flags & 14680064, e.return = a, e = e.sibling; else for (e = a.child; null !== e; ) c |= e.lanes | e.childLanes, d |= e.subtreeFlags, d |= e.flags, e.return = a, e = e.sibling; a.subtreeFlags |= d; a.childLanes = c; return b; } function Ej(a, b, c) { var d = b.pendingProps; wg(b); switch (b.tag) { case 2: case 16: case 15: case 0: case 11: case 7: case 8: case 12: case 9: case 14: return S(b), null; case 1: return Zf(b.type) && $f(), S(b), null; case 3: d = b.stateNode; zh(); E(Wf); E(H); Eh(); d.pendingContext && (d.context = d.pendingContext, d.pendingContext = null); if (null === a || null === a.child) Gg(b) ? b.flags |= 4 : null === a || a.memoizedState.isDehydrated && 0 === (b.flags & 256) || (b.flags |= 1024, null !== zg && (Fj(zg), zg = null)); Aj(a, b); S(b); return null; case 5: Bh(b); var e = xh(wh.current); c = b.type; if (null !== a && null != b.stateNode) Bj(a, b, c, d, e), a.ref !== b.ref && (b.flags |= 512, b.flags |= 2097152); else { if (!d) { if (null === b.stateNode) throw Error(p(166)); S(b); return null; } a = xh(uh.current); if (Gg(b)) { d = b.stateNode; c = b.type; var f = b.memoizedProps; d[Of] = b; d[Pf] = f; a = 0 !== (b.mode & 1); switch (c) { case "dialog": D("cancel", d); D("close", d); break; case "iframe": case "object": case "embed": D("load", d); break; case "video": case "audio": for (e = 0; e < lf.length; e++) D(lf[e], d); break; case "source": D("error", d); break; case "img": case "image": case "link": D( "error", d ); D("load", d); break; case "details": D("toggle", d); break; case "input": Za(d, f); D("invalid", d); break; case "select": d._wrapperState = { wasMultiple: !!f.multiple }; D("invalid", d); break; case "textarea": hb(d, f), D("invalid", d); } ub(c, f); e = null; for (var g in f) if (f.hasOwnProperty(g)) { var h2 = f[g]; "children" === g ? "string" === typeof h2 ? d.textContent !== h2 && (true !== f.suppressHydrationWarning && Af(d.textContent, h2, a), e = ["children", h2]) : "number" === typeof h2 && d.textContent !== "" + h2 && (true !== f.suppressHydrationWarning && Af( d.textContent, h2, a ), e = ["children", "" + h2]) : ea.hasOwnProperty(g) && null != h2 && "onScroll" === g && D("scroll", d); } switch (c) { case "input": Va(d); db(d, f, true); break; case "textarea": Va(d); jb(d); break; case "select": case "option": break; default: "function" === typeof f.onClick && (d.onclick = Bf); } d = e; b.updateQueue = d; null !== d && (b.flags |= 4); } else { g = 9 === e.nodeType ? e : e.ownerDocument; "http://www.w3.org/1999/xhtml" === a && (a = kb(c)); "http://www.w3.org/1999/xhtml" === a ? "script" === c ? (a = g.createElement("div"), a.innerHTML = "