import { require_client } from "./chunk-DZXNXIW7.js"; import { i } from "./chunk-RU4TY2CQ.js"; import { require_browser } from "./chunk-5QTNICOS.js"; import { require_react_dom } from "./chunk-LRUX6XQC.js"; import { require_jsx_runtime } from "./chunk-YAGB2RBV.js"; import { require_react } from "./chunk-T3SJLYUH.js"; import { __commonJS, __export, __publicField, __toESM } from "./chunk-4B2QHNJT.js"; // ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js var require_fast_deep_equal = __commonJS({ "../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) { "use strict"; module.exports = function equal(a3, b4) { if (a3 === b4) return true; if (a3 && b4 && typeof a3 == "object" && typeof b4 == "object") { if (a3.constructor !== b4.constructor) return false; var length2, i3, keys5; if (Array.isArray(a3)) { length2 = a3.length; if (length2 != b4.length) return false; for (i3 = length2; i3-- !== 0; ) if (!equal(a3[i3], b4[i3])) return false; return true; } if (a3.constructor === RegExp) return a3.source === b4.source && a3.flags === b4.flags; if (a3.valueOf !== Object.prototype.valueOf) return a3.valueOf() === b4.valueOf(); if (a3.toString !== Object.prototype.toString) return a3.toString() === b4.toString(); keys5 = Object.keys(a3); length2 = keys5.length; if (length2 !== Object.keys(b4).length) return false; for (i3 = length2; i3-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(b4, keys5[i3])) return false; for (i3 = length2; i3-- !== 0; ) { var key2 = keys5[i3]; if (!equal(a3[key2], b4[key2])) return false; } return true; } return a3 !== a3 && b4 !== b4; }; } }); // ../../node_modules/.pnpm/extend@3.0.2/node_modules/extend/index.js var require_extend = __commonJS({ "../../node_modules/.pnpm/extend@3.0.2/node_modules/extend/index.js"(exports, module) { "use strict"; var hasOwn2 = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var defineProperty = Object.defineProperty; var gOPD = Object.getOwnPropertyDescriptor; var isArray2 = function isArray3(arr) { if (typeof Array.isArray === "function") { return Array.isArray(arr); } return toStr.call(arr) === "[object Array]"; }; var isPlainObject3 = function isPlainObject4(obj) { if (!obj || toStr.call(obj) !== "[object Object]") { return false; } var hasOwnConstructor = hasOwn2.call(obj, "constructor"); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn2.call(obj.constructor.prototype, "isPrototypeOf"); if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } var key2; for (key2 in obj) { } return typeof key2 === "undefined" || hasOwn2.call(obj, key2); }; var setProperty = function setProperty2(target, options2) { if (defineProperty && options2.name === "__proto__") { defineProperty(target, options2.name, { enumerable: true, configurable: true, value: options2.newValue, writable: true }); } else { target[options2.name] = options2.newValue; } }; var getProperty = function getProperty2(obj, name) { if (name === "__proto__") { if (!hasOwn2.call(obj, name)) { return void 0; } else if (gOPD) { return gOPD(obj, name).value; } } return obj[name]; }; module.exports = function extend2() { var options2, name, src, copy3, copyIsArray, clone; var target = arguments[0]; var i3 = 1; var length2 = arguments.length; var deep = false; if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; i3 = 2; } if (target == null || typeof target !== "object" && typeof target !== "function") { target = {}; } for (; i3 < length2; ++i3) { options2 = arguments[i3]; if (options2 != null) { for (name in options2) { src = getProperty(target, name); copy3 = getProperty(options2, name); if (target !== copy3) { if (deep && copy3 && (isPlainObject3(copy3) || (copyIsArray = isArray2(copy3)))) { if (copyIsArray) { copyIsArray = false; clone = src && isArray2(src) ? src : []; } else { clone = src && isPlainObject3(src) ? src : {}; } setProperty(target, { name, newValue: extend2(deep, clone, copy3) }); } else if (typeof copy3 !== "undefined") { setProperty(target, { name, newValue: copy3 }); } } } } } return target; }; } }); // ../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js var require_use_sync_external_store_shim_development = __commonJS({ "../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js"(exports) { "use strict"; (function() { function is2(x5, y3) { return x5 === y3 && (0 !== x5 || 1 / x5 === 1 / y3) || x5 !== x5 && y3 !== y3; } function useSyncExternalStore$2(subscribe, getSnapshot) { didWarnOld18Alpha || void 0 === React5.startTransition || (didWarnOld18Alpha = true, console.error( "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release." )); var value = getSnapshot(); if (!didWarnUncachedGetSnapshot) { var cachedValue = getSnapshot(); objectIs(value, cachedValue) || (console.error( "The result of getSnapshot should be cached to avoid an infinite loop" ), didWarnUncachedGetSnapshot = true); } cachedValue = useState4({ inst: { value, getSnapshot } }); var inst = cachedValue[0].inst, forceUpdate = cachedValue[1]; useLayoutEffect4( function() { inst.value = value; inst.getSnapshot = getSnapshot; checkIfSnapshotChanged(inst) && forceUpdate({ inst }); }, [subscribe, value, getSnapshot] ); useEffect4( function() { checkIfSnapshotChanged(inst) && forceUpdate({ inst }); return subscribe(function() { checkIfSnapshotChanged(inst) && forceUpdate({ inst }); }); }, [subscribe] ); useDebugValue3(value); return value; } function checkIfSnapshotChanged(inst) { var latestGetSnapshot = inst.getSnapshot; inst = inst.value; try { var nextValue = latestGetSnapshot(); return !objectIs(inst, nextValue); } catch (error2) { return true; } } function useSyncExternalStore$1(subscribe, getSnapshot) { return getSnapshot(); } "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); var React5 = require_react(), objectIs = "function" === typeof Object.is ? Object.is : is2, useState4 = React5.useState, useEffect4 = React5.useEffect, useLayoutEffect4 = React5.useLayoutEffect, useDebugValue3 = React5.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2; exports.useSyncExternalStore = void 0 !== React5.useSyncExternalStore ? React5.useSyncExternalStore : shim; "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); })(); } }); // ../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/shim/index.js var require_shim = __commonJS({ "../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/shim/index.js"(exports, module) { "use strict"; if (false) { module.exports = null; } else { module.exports = require_use_sync_external_store_shim_development(); } } }); // ../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js var require_with_selector_development = __commonJS({ "../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js"(exports) { "use strict"; (function() { function is2(x5, y3) { return x5 === y3 && (0 !== x5 || 1 / x5 === 1 / y3) || x5 !== x5 && y3 !== y3; } "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); var React5 = require_react(), shim = require_shim(), objectIs = "function" === typeof Object.is ? Object.is : is2, useSyncExternalStore3 = shim.useSyncExternalStore, useRef5 = React5.useRef, useEffect4 = React5.useEffect, useMemo4 = React5.useMemo, useDebugValue3 = React5.useDebugValue; exports.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) { var instRef = useRef5(null); if (null === instRef.current) { var inst = { hasValue: false, value: null }; instRef.current = inst; } else inst = instRef.current; instRef = useMemo4( function() { function memoizedSelector(nextSnapshot) { if (!hasMemo) { hasMemo = true; memoizedSnapshot = nextSnapshot; nextSnapshot = selector(nextSnapshot); if (void 0 !== isEqual && inst.hasValue) { var currentSelection = inst.value; if (isEqual(currentSelection, nextSnapshot)) return memoizedSelection = currentSelection; } return memoizedSelection = nextSnapshot; } currentSelection = memoizedSelection; if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection; var nextSelection = selector(nextSnapshot); if (void 0 !== isEqual && isEqual(currentSelection, nextSelection)) return memoizedSnapshot = nextSnapshot, currentSelection; memoizedSnapshot = nextSnapshot; return memoizedSelection = nextSelection; } var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot; return [ function() { return memoizedSelector(getSnapshot()); }, null === maybeGetServerSnapshot ? void 0 : function() { return memoizedSelector(maybeGetServerSnapshot()); } ]; }, [getSnapshot, getServerSnapshot, selector, isEqual] ); var value = useSyncExternalStore3(subscribe, instRef[0], instRef[1]); useEffect4( function() { inst.hasValue = true; inst.value = value; }, [value] ); useDebugValue3(value); return value; }; "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); })(); } }); // ../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/shim/with-selector.js var require_with_selector = __commonJS({ "../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/shim/with-selector.js"(exports, module) { "use strict"; if (false) { module.exports = null; } else { module.exports = require_with_selector_development(); } } }); // ../../node_modules/.pnpm/@blocknote+react@0.45.0_@floating-ui+dom@1.7.4_@tiptap+extensions@3.14.0_@tiptap+core@3_4c2381f288dfb667bae932edc4edea17/node_modules/@blocknote/react/dist/blocknote-react.js var import_react12 = __toESM(require_react()); var import_jsx_runtime10 = __toESM(require_jsx_runtime()); // ../../node_modules/.pnpm/orderedmap@2.1.1/node_modules/orderedmap/dist/index.js function OrderedMap(content5) { this.content = content5; } OrderedMap.prototype = { constructor: OrderedMap, find: function(key2) { for (var i3 = 0; i3 < this.content.length; i3 += 2) if (this.content[i3] === key2) return i3; return -1; }, // :: (string) → ?any // Retrieve the value stored under `key`, or return undefined when // no such key exists. get: function(key2) { var found2 = this.find(key2); 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(key2, value, newKey) { var self2 = newKey && newKey != key2 ? this.remove(newKey) : this; var found2 = self2.find(key2), content5 = self2.content.slice(); if (found2 == -1) { content5.push(newKey || key2, value); } else { content5[found2 + 1] = value; if (newKey) content5[found2] = newKey; } return new OrderedMap(content5); }, // :: (string) → OrderedMap // Return a map with the given key removed, if it existed. remove: function(key2) { var found2 = this.find(key2); if (found2 == -1) return this; var content5 = this.content.slice(); content5.splice(found2, 2); return new OrderedMap(content5); }, // :: (string, any) → OrderedMap // Add a new key to the start of the map. addToStart: function(key2, value) { return new OrderedMap([key2, value].concat(this.remove(key2).content)); }, // :: (string, any) → OrderedMap // Add a new key to the end of the map. addToEnd: function(key2, value) { var content5 = this.remove(key2).content.slice(); content5.push(key2, value); return new OrderedMap(content5); }, // :: (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, key2, value) { var without = this.remove(key2), content5 = without.content.slice(); var found2 = without.find(place); content5.splice(found2 == -1 ? content5.length : found2, 0, key2, value); return new OrderedMap(content5); }, // :: ((key: string, value: any)) // Call the given function for each key/value pair in the map, in // order. forEach: function(f6) { for (var i3 = 0; i3 < this.content.length; i3 += 2) f6(this.content[i3], this.content[i3 + 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(map7) { map7 = OrderedMap.from(map7); if (!map7.size) return this; return new OrderedMap(map7.content.concat(this.subtract(map7).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(map7) { map7 = OrderedMap.from(map7); if (!map7.size) return this; return new OrderedMap(this.subtract(map7).content.concat(map7.content)); }, // :: (union) → OrderedMap // Create a map containing all the keys in this map that don't // appear in `map`. subtract: function(map7) { var result = this; map7 = OrderedMap.from(map7); for (var i3 = 0; i3 < map7.content.length; i3 += 2) result = result.remove(map7.content[i3]); return result; }, // :: () → Object // Turn ordered map into a plain object. toObject: function() { var result = {}; this.forEach(function(key2, value) { result[key2] = 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 content5 = []; if (value) for (var prop in value) content5.push(prop, value[prop]); return new OrderedMap(content5); }; var dist_default = OrderedMap; // ../../node_modules/.pnpm/prosemirror-model@1.25.4/node_modules/prosemirror-model/dist/index.js function findDiffStart(a3, b4, pos) { for (let i3 = 0; ; i3++) { if (i3 == a3.childCount || i3 == b4.childCount) return a3.childCount == b4.childCount ? null : pos; let childA = a3.child(i3), childB = b4.child(i3); if (childA == childB) { pos += childA.nodeSize; continue; } if (!childA.sameMarkup(childB)) return pos; if (childA.isText && childA.text != childB.text) { for (let j4 = 0; childA.text[j4] == childB.text[j4]; j4++) 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(a3, b4, posA, posB) { for (let iA = a3.childCount, iB = b4.childCount; ; ) { if (iA == 0 || iB == 0) return iA == iB ? null : { a: posA, b: posB }; let childA = a3.child(--iA), childB = b4.child(--iB), size5 = childA.nodeSize; if (childA == childB) { posA -= size5; posB -= size5; continue; } if (!childA.sameMarkup(childB)) return { a: posA, b: posB }; if (childA.isText && childA.text != childB.text) { let same = 0, minSize = Math.min(childA.text.length, childB.text.length); while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) { same++; 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 -= size5; posB -= size5; } } var Fragment = class _Fragment { /** @internal */ constructor(content5, size5) { this.content = content5; this.size = size5 || 0; if (size5 == null) for (let i3 = 0; i3 < content5.length; i3++) this.size += content5[i3].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(from4, to2, f6, nodeStart = 0, parent) { for (let i3 = 0, pos = 0; pos < to2; i3++) { let child = this.content[i3], end = pos + child.nodeSize; if (end > from4 && f6(child, nodeStart + pos, parent || null, i3) !== false && child.content.size) { let start = pos + 1; child.nodesBetween(Math.max(0, from4 - start), Math.min(child.content.size, to2 - start), f6, 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(f6) { this.nodesBetween(0, this.size, f6); } /** Extract the text between `from` and `to`. See the same method on [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween). */ textBetween(from4, to2, blockSeparator, leafText) { let text10 = "", first2 = true; this.nodesBetween(from4, to2, (node2, pos) => { let nodeText = node2.isText ? node2.text.slice(Math.max(from4, pos) - pos, to2 - pos) : !node2.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node2) : leafText : node2.type.spec.leafText ? node2.type.spec.leafText(node2) : ""; if (node2.isBlock && (node2.isLeaf && nodeText || node2.isTextblock) && blockSeparator) { if (first2) first2 = false; else text10 += blockSeparator; } text10 += nodeText; }, 0); return text10; } /** 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 last2 = this.lastChild, first2 = other.firstChild, content5 = this.content.slice(), i3 = 0; if (last2.isText && last2.sameMarkup(first2)) { content5[content5.length - 1] = last2.withText(last2.text + first2.text); i3 = 1; } for (; i3 < other.content.length; i3++) content5.push(other.content[i3]); return new _Fragment(content5, this.size + other.size); } /** Cut out the sub-fragment between the two given positions. */ cut(from4, to2 = this.size) { if (from4 == 0 && to2 == this.size) return this; let result = [], size5 = 0; if (to2 > from4) for (let i3 = 0, pos = 0; pos < to2; i3++) { let child = this.content[i3], end = pos + child.nodeSize; if (end > from4) { if (pos < from4 || end > to2) { if (child.isText) child = child.cut(Math.max(0, from4 - pos), Math.min(child.text.length, to2 - pos)); else child = child.cut(Math.max(0, from4 - pos - 1), Math.min(child.content.size, to2 - pos - 1)); } result.push(child); size5 += child.nodeSize; } pos = end; } return new _Fragment(result, size5); } /** @internal */ cutByIndex(from4, to2) { if (from4 == to2) return _Fragment.empty; if (from4 == 0 && to2 == this.content.length) return this; return new _Fragment(this.content.slice(from4, to2)); } /** Create a new fragment in which the node at the given index is replaced by the given node. */ replaceChild(index4, node2) { let current = this.content[index4]; if (current == node2) return this; let copy3 = this.content.slice(); let size5 = this.size + node2.nodeSize - current.nodeSize; copy3[index4] = node2; return new _Fragment(copy3, size5); } /** Create a new fragment by prepending the given node to this fragment. */ addToStart(node2) { return new _Fragment([node2].concat(this.content), this.size + node2.nodeSize); } /** Create a new fragment by appending the given node to this fragment. */ addToEnd(node2) { return new _Fragment(this.content.concat(node2), this.size + node2.nodeSize); } /** Compare this fragment to another one. */ eq(other) { if (this.content.length != other.content.length) return false; for (let i3 = 0; i3 < this.content.length; i3++) if (!this.content[i3].eq(other.content[i3])) 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(index4) { let found2 = this.content[index4]; if (!found2) throw new RangeError("Index " + index4 + " out of range for " + this); return found2; } /** Get the child node at the given index, if it exists. */ maybeChild(index4) { return this.content[index4] || null; } /** Call `f` for every child node, passing the node, its offset into this parent node, and its index. */ forEach(f6) { for (let i3 = 0, p4 = 0; i3 < this.content.length; i3++) { let child = this.content[i3]; f6(child, p4, i3); p4 += 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 i3 = 0, curPos = 0; ; i3++) { let cur = this.child(i3), end = curPos + cur.nodeSize; if (end >= pos) { if (end == pos) return retIndex(i3 + 1, end); return retIndex(i3, 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 new _Fragment(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, size5 = 0; for (let i3 = 0; i3 < array.length; i3++) { let node2 = array[i3]; size5 += node2.nodeSize; if (i3 && node2.isText && array[i3 - 1].sameMarkup(node2)) { if (!joined) joined = array.slice(0, i3); joined[joined.length - 1] = node2.withText(joined[joined.length - 1].text + node2.text); } else if (joined) { joined.push(node2); } } return new _Fragment(joined || array, size5); } /** 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); var found = { index: 0, offset: 0 }; function retIndex(index4, offset4) { found.index = index4; found.offset = offset4; return found; } function compareDeep(a3, b4) { if (a3 === b4) return true; if (!(a3 && typeof a3 == "object") || !(b4 && typeof b4 == "object")) return false; let array = Array.isArray(a3); if (Array.isArray(b4) != array) return false; if (array) { if (a3.length != b4.length) return false; for (let i3 = 0; i3 < a3.length; i3++) if (!compareDeep(a3[i3], b4[i3])) return false; } else { for (let p4 in a3) if (!(p4 in b4) || !compareDeep(a3[p4], b4[p4])) return false; for (let p4 in b4) if (!(p4 in a3)) return false; } return true; } var Mark = class _Mark2 { /** @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 copy3, placed = false; for (let i3 = 0; i3 < set.length; i3++) { let other = set[i3]; if (this.eq(other)) return set; if (this.type.excludes(other.type)) { if (!copy3) copy3 = set.slice(0, i3); } else if (other.type.excludes(this.type)) { return set; } else { if (!placed && other.type.rank > this.type.rank) { if (!copy3) copy3 = set.slice(0, i3); copy3.push(this); placed = true; } if (copy3) copy3.push(other); } } if (!copy3) copy3 = set.slice(); if (!placed) copy3.push(this); return copy3; } /** 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 i3 = 0; i3 < set.length; i3++) if (this.eq(set[i3])) return set.slice(0, i3).concat(set.slice(i3 + 1)); return set; } /** Test whether this mark is in the given set of marks. */ isInSet(set) { for (let i3 = 0; i3 < set.length; i3++) if (this.eq(set[i3])) 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 _2 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 mark2 = type.create(json.attrs); type.checkAttrs(mark2.attrs); return mark2; } /** Test whether two sets of marks are identical. */ static sameSet(a3, b4) { if (a3 == b4) return true; if (a3.length != b4.length) return false; for (let i3 = 0; i3 < a3.length; i3++) if (!a3[i3].eq(b4[i3])) 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 _Mark2.none; if (marks instanceof _Mark2) return [marks]; let copy3 = marks.slice(); copy3.sort((a3, b4) => a3.type.rank - b4.type.rank); return copy3; } }; Mark.none = []; var ReplaceError = class extends Error { }; var Slice = 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(content5, openStart, openEnd) { this.content = content5; 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 content5 = insertInto(this.content, pos + this.openStart, fragment); return content5 && new _Slice(content5, this.openStart, this.openEnd); } /** @internal */ removeBetween(from4, to2) { return new _Slice(removeRange(this.content, from4 + this.openStart, to2 + 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(content5, from4, to2) { let { index: index4, offset: offset4 } = content5.findIndex(from4), child = content5.maybeChild(index4); let { index: indexTo, offset: offsetTo } = content5.findIndex(to2); if (offset4 == from4 || child.isText) { if (offsetTo != to2 && !content5.child(indexTo).isText) throw new RangeError("Removing non-flat range"); return content5.cut(0, from4).append(content5.cut(to2)); } if (index4 != indexTo) throw new RangeError("Removing non-flat range"); return content5.replaceChild(index4, child.copy(removeRange(child.content, from4 - offset4 - 1, to2 - offset4 - 1))); } function insertInto(content5, dist, insert, parent) { let { index: index4, offset: offset4 } = content5.findIndex(dist), child = content5.maybeChild(index4); if (offset4 == dist || child.isText) { if (parent && !parent.canReplace(index4, index4, insert)) return null; return content5.cut(0, dist).append(insert).append(content5.cut(dist)); } let inner = insertInto(child.content, dist - offset4 - 1, insert, child); return inner && content5.replaceChild(index4, 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 index4 = $from.index(depth), node2 = $from.node(depth); if (index4 == $to.index(depth) && depth < $from.depth - slice2.openStart) { let inner = replaceOuter($from, $to, slice2, depth + 1); return node2.copy(node2.content.replaceChild(index4, inner)); } else if (!slice2.content.size) { return close(node2, replaceTwoWay($from, $to, depth)); } else if (!slice2.openStart && !slice2.openEnd && $from.depth == depth && $to.depth == depth) { let parent = $from.parent, content5 = parent.content; return close(parent, content5.cut(0, $from.parentOffset).append(slice2.content).append(content5.cut($to.parentOffset))); } else { let { start, end } = prepareSliceForReplace(slice2, $from); return close(node2, 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($before, $after, depth) { let node2 = $before.node(depth); checkJoin(node2, $after.node(depth)); return node2; } function addNode(child, target) { let last2 = target.length - 1; if (last2 >= 0 && child.isText && child.sameMarkup(target[last2])) target[last2] = child.withText(target[last2].text + child.text); else target.push(child); } function addRange($start, $end, depth, target) { let node2 = ($end || $start).node(depth); let startIndex = 0, endIndex = $end ? $end.index(depth) : node2.childCount; if ($start) { startIndex = $start.index(depth); if ($start.depth > depth) { startIndex++; } else if ($start.textOffset) { addNode($start.nodeAfter, target); startIndex++; } } for (let i3 = startIndex; i3 < endIndex; i3++) addNode(node2.child(i3), target); if ($end && $end.depth == depth && $end.textOffset) addNode($end.nodeBefore, target); } function close(node2, content5) { node2.type.checkContent(content5); return node2.copy(content5); } function replaceThreeWay($from, $start, $end, $to, depth) { let openStart = $from.depth > depth && joinable($from, $start, depth + 1); let openEnd = $to.depth > depth && joinable($end, $to, depth + 1); let content5 = []; addRange(null, $from, depth, content5); if (openStart && openEnd && $start.index(depth) == $end.index(depth)) { checkJoin(openStart, openEnd); addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content5); } else { if (openStart) addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content5); addRange($start, $end, depth, content5); if (openEnd) addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content5); } addRange($to, null, depth, content5); return new Fragment(content5); } function replaceTwoWay($from, $to, depth) { let content5 = []; addRange(null, $from, depth, content5); if ($from.depth > depth) { let type = joinable($from, $to, depth + 1); addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content5); } addRange($to, null, depth, content5); return new Fragment(content5); } function prepareSliceForReplace(slice2, $along) { let extra = $along.depth - slice2.openStart, parent = $along.node(extra); let node2 = parent.copy(slice2.content); for (let i3 = extra - 1; i3 >= 0; i3--) node2 = $along.node(i3).copy(Fragment.from(node2)); return { start: node2.resolveNoCache(slice2.openStart + extra), end: node2.resolveNoCache(node2.content.size - slice2.openEnd - extra) }; } var ResolvedPos = class _ResolvedPos { /** @internal */ constructor(pos, path2, parentOffset) { this.pos = pos; this.path = path2; this.parentOffset = parentOffset; this.depth = path2.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, index4 = this.index(this.depth); if (index4 == parent.childCount) return null; let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index4); return dOff ? parent.child(index4).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 index4 = this.index(this.depth); let dOff = this.pos - this.path[this.path.length - 1]; if (dOff) return this.parent.child(index4).cut(0, dOff); return index4 == 0 ? null : this.parent.child(index4 - 1); } /** Get the position at the given index in the parent node at the given depth (which defaults to `this.depth`). */ posAtIndex(index4, depth) { depth = this.resolveDepth(depth); let node2 = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; for (let i3 = 0; i3 < index4; i3++) pos += node2.child(i3).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, index4 = this.index(); if (parent.content.size == 0) return Mark.none; if (this.textOffset) return parent.child(index4).marks; let main = parent.maybeChild(index4 - 1), other = parent.maybeChild(index4); if (!main) { let tmp = main; main = other; other = tmp; } let marks = main.marks; for (var i3 = 0; i3 < marks.length; i3++) if (marks[i3].type.spec.inclusive === false && (!other || !marks[i3].isInSet(other.marks))) marks = marks[i3--].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, next2 = $end.parent.maybeChild($end.index()); for (var i3 = 0; i3 < marks.length; i3++) if (marks[i3].type.spec.inclusive === false && (!next2 || !marks[i3].isInSet(next2.marks))) marks = marks[i3--].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 i3 = 1; i3 <= this.depth; i3++) str += (str ? "/" : "") + this.node(i3).type.name + "_" + this.index(i3 - 1); return str + ":" + this.parentOffset; } /** @internal */ static resolve(doc4, pos) { if (!(pos >= 0 && pos <= doc4.content.size)) throw new RangeError("Position " + pos + " out of range"); let path2 = []; let start = 0, parentOffset = pos; for (let node2 = doc4; ; ) { let { index: index4, offset: offset4 } = node2.content.findIndex(parentOffset); let rem = parentOffset - offset4; path2.push(node2, index4, start + offset4); if (!rem) break; node2 = node2.child(index4); if (node2.isText) break; parentOffset = rem - 1; start += offset4 + 1; } return new _ResolvedPos(pos, path2, parentOffset); } /** @internal */ static resolveCached(doc4, pos) { let cache = resolveCache.get(doc4); if (cache) { for (let i3 = 0; i3 < cache.elts.length; i3++) { let elt = cache.elts[i3]; if (elt.pos == pos) return elt; } } else { resolveCache.set(doc4, cache = new ResolveCache()); } let result = cache.elts[cache.i] = _ResolvedPos.resolve(doc4, pos); cache.i = (cache.i + 1) % resolveCacheSize; return result; } }; var ResolveCache = class { constructor() { this.elts = []; this.i = 0; } }; var resolveCacheSize = 12; var resolveCache = /* @__PURE__ */ new WeakMap(); var NodeRange = class { /** 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); } }; var emptyAttrs = /* @__PURE__ */ Object.create(null); var Node2 = class _Node2 { /** @internal */ constructor(type, attrs, content5, marks = Mark.none) { this.type = type; this.attrs = attrs; this.marks = marks; this.content = content5 || 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(index4) { return this.content.child(index4); } /** Get the child node at the given index, if it exists. */ maybeChild(index4) { return this.content.maybeChild(index4); } /** Call `f` for every child node, passing the node, its offset into this parent node, and its index. */ forEach(f6) { this.content.forEach(f6); } /** Invoke a callback for all descendant nodes recursively between the given two positions that are relative to start of this node's content. 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(from4, to2, f6, startPos = 0) { this.content.nodesBetween(from4, to2, f6, startPos, this); } /** Call the given callback for every descendant node. Doesn't descend into a node when the callback returns `false`. */ descendants(f6) { this.nodesBetween(0, this.content.size, f6); } /** 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(from4, to2, blockSeparator, leafText) { return this.content.textBetween(from4, to2, 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.sameSet(this.marks, marks || Mark.none); } /** Create a new node with the same markup as this node, containing the given content (or empty, if no content is given). */ copy(content5 = null) { if (content5 == this.content) return this; return new _Node2(this.type, this.attrs, content5, 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 _Node2(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(from4, to2 = this.content.size) { if (from4 == 0 && to2 == this.content.size) return this; return this.copy(this.content.cut(from4, to2)); } /** Cut out the part of the document between the given positions, and return it as a `Slice` object. */ slice(from4, to2 = this.content.size, includeParents = false) { if (from4 == to2) return Slice.empty; let $from = this.resolve(from4), $to = this.resolve(to2); let depth = includeParents ? 0 : $from.sharedDepth(to2); let start = $from.start(depth), node2 = $from.node(depth); let content5 = node2.content.cut($from.pos - start, $to.pos - start); return new Slice(content5, $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(from4, to2, slice2) { return replace(this.resolve(from4), this.resolve(to2), slice2); } /** Find the node directly after the given position. */ nodeAt(pos) { for (let node2 = this; ; ) { let { index: index4, offset: offset4 } = node2.content.findIndex(pos); node2 = node2.maybeChild(index4); if (!node2) return null; if (offset4 == pos || node2.isText) return node2; pos -= offset4 + 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: index4, offset: offset4 } = this.content.findIndex(pos); return { node: this.content.maybeChild(index4), index: index4, offset: offset4 }; } /** 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: index4, offset: offset4 } = this.content.findIndex(pos); if (offset4 < pos) return { node: this.content.child(index4), index: index4, offset: offset4 }; let node2 = this.content.child(index4 - 1); return { node: node2, index: index4 - 1, offset: offset4 - node2.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(from4, to2, type) { let found2 = false; if (to2 > from4) this.nodesBetween(from4, to2, (node2) => { if (type.isInSet(node2.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(index4) { let match2 = this.type.contentMatch.matchFragment(this.content, 0, index4); if (!match2) throw new Error("Called contentMatchAt on a node with invalid content"); return match2; } /** 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(from4, to2, replacement = Fragment.empty, start = 0, end = replacement.childCount) { let one6 = this.contentMatchAt(from4).matchFragment(replacement, start, end); let two = one6 && one6.matchFragment(this.content, to2); if (!two || !two.validEnd) return false; for (let i3 = start; i3 < end; i3++) if (!this.type.allowsMarks(replacement.child(i3).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(from4, to2, type, marks) { if (marks && !this.type.allowsMarks(marks)) return false; let start = this.contentMatchAt(from4).matchType(type); let end = start && start.matchFragment(this.content, to2); 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 copy3 = Mark.none; for (let i3 = 0; i3 < this.marks.length; i3++) { let mark2 = this.marks[i3]; mark2.type.checkAttrs(mark2.attrs); copy3 = mark2.addToSet(copy3); } if (!Mark.sameSet(copy3, this.marks)) throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m2) => m2.type.name)}`); this.content.forEach((node2) => node2.check()); } /** Return a JSON-serializeable representation of this node. */ toJSON() { let obj = { type: this.type.name }; for (let _2 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 content5 = Fragment.fromJSON(schema, json.content); let node2 = schema.nodeType(json.type).create(json.attrs, content5, marks); node2.type.checkAttrs(node2.attrs); return node2; } }; Node2.prototype.text = void 0; var TextNode = class _TextNode extends Node2 { /** @internal */ constructor(type, attrs, content5, marks) { super(type, attrs, null, marks); if (!content5) throw new RangeError("Empty text nodes are not allowed"); this.text = content5; } 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(from4, to2) { return this.text.slice(from4, to2); } get nodeSize() { return this.text.length; } mark(marks) { return marks == this.marks ? this : new _TextNode(this.type, this.attrs, this.text, marks); } withText(text10) { if (text10 == this.text) return this; return new _TextNode(this.type, this.attrs, text10, this.marks); } cut(from4 = 0, to2 = this.text.length) { if (from4 == 0 && to2 == this.text.length) return this; return this.withText(this.text.slice(from4, to2)); } eq(other) { return this.sameMarkup(other) && this.text == other.text; } toJSON() { let base4 = super.toJSON(); base4.text = this.text; return base4; } }; function wrapMarks(marks, str) { for (let i3 = marks.length - 1; i3 >= 0; i3--) str = marks[i3].type.name + "(" + str + ")"; return str; } var ContentMatch = class _ContentMatch { /** @internal */ constructor(validEnd) { this.validEnd = validEnd; this.next = []; this.wrapCache = []; } /** @internal */ static parse(string3, nodeTypes) { let stream = new TokenStream(string3, nodeTypes); if (stream.next == null) return _ContentMatch.empty; let expr = parseExpr(stream); if (stream.next) stream.err("Unexpected trailing text"); let match2 = dfa(nfa(expr)); checkForDeadEnds(match2, stream); return match2; } /** Match a node type, returning a match after that node if successful. */ matchType(type) { for (let i3 = 0; i3 < this.next.length; i3++) if (this.next[i3].type == type) return this.next[i3].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 i3 = start; cur && i3 < end; i3++) cur = cur.matchType(frag.child(i3).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 i3 = 0; i3 < this.next.length; i3++) { let { type } = this.next[i3]; if (!(type.isText || type.hasRequiredAttrs())) return type; } return null; } /** @internal */ compatible(other) { for (let i3 = 0; i3 < this.next.length; i3++) for (let j4 = 0; j4 < other.next.length; j4++) if (this.next[i3].type == other.next[j4].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 search3(match2, types2) { let finished = match2.matchFragment(after, startIndex); if (finished && (!toEnd || finished.validEnd)) return Fragment.from(types2.map((tp) => tp.createAndFill())); for (let i3 = 0; i3 < match2.next.length; i3++) { let { type, next: next2 } = match2.next[i3]; if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next2) == -1) { seen.push(next2); let found2 = search3(next2, types2.concat(type)); if (found2) return found2; } } return null; } return search3(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 i3 = 0; i3 < this.wrapCache.length; i3 += 2) if (this.wrapCache[i3] == target) return this.wrapCache[i3 + 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(), match2 = current.match; if (match2.matchType(target)) { let result = []; for (let obj = current; obj.type; obj = obj.via) result.push(obj.type); return result.reverse(); } for (let i3 = 0; i3 < match2.next.length; i3++) { let { type, next: next2 } = match2.next[i3]; if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next2.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(m2) { seen.push(m2); for (let i3 = 0; i3 < m2.next.length; i3++) if (seen.indexOf(m2.next[i3].next) == -1) scan(m2.next[i3].next); } scan(this); return seen.map((m2, i3) => { let out = i3 + (m2.validEnd ? "*" : " ") + " "; for (let i4 = 0; i4 < m2.next.length; i4++) out += (i4 ? ", " : "") + m2.next[i4].type.name + "->" + seen.indexOf(m2.next[i4].next); return out; }).join("\n"); } }; ContentMatch.empty = new ContentMatch(true); var TokenStream = class { constructor(string3, nodeTypes) { this.string = string3; this.nodeTypes = nodeTypes; this.inline = null; this.pos = 0; this.tokens = string3.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 min3 = parseNum(stream), max3 = min3; if (stream.eat(",")) { if (stream.next != "}") max3 = parseNum(stream); else max3 = -1; } if (!stream.eat("}")) stream.err("Unclosed braced range"); return { type: "range", min: min3, max: max3, expr }; } function resolveName(stream, name) { let types2 = stream.nodeTypes, type = types2[name]; if (type) return [type]; let result = []; for (let typeName in types2) { let type2 = types2[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(compile2(expr, 0), node2()); return nfa2; function node2() { return nfa2.push([]) - 1; } function edge(from4, to2, term) { let edge2 = { term, to: to2 }; nfa2[from4].push(edge2); return edge2; } function connect(edges, to2) { edges.forEach((edge2) => edge2.to = to2); } function compile2(expr2, from4) { if (expr2.type == "choice") { return expr2.exprs.reduce((out, expr3) => out.concat(compile2(expr3, from4)), []); } else if (expr2.type == "seq") { for (let i3 = 0; ; i3++) { let next2 = compile2(expr2.exprs[i3], from4); if (i3 == expr2.exprs.length - 1) return next2; connect(next2, from4 = node2()); } } else if (expr2.type == "star") { let loop = node2(); edge(from4, loop); connect(compile2(expr2.expr, loop), loop); return [edge(loop)]; } else if (expr2.type == "plus") { let loop = node2(); connect(compile2(expr2.expr, from4), loop); connect(compile2(expr2.expr, loop), loop); return [edge(loop)]; } else if (expr2.type == "opt") { return [edge(from4)].concat(compile2(expr2.expr, from4)); } else if (expr2.type == "range") { let cur = from4; for (let i3 = 0; i3 < expr2.min; i3++) { let next2 = node2(); connect(compile2(expr2.expr, cur), next2); cur = next2; } if (expr2.max == -1) { connect(compile2(expr2.expr, cur), cur); } else { for (let i3 = expr2.min; i3 < expr2.max; i3++) { let next2 = node2(); edge(cur, next2); connect(compile2(expr2.expr, cur), next2); cur = next2; } } return [edge(cur)]; } else if (expr2.type == "name") { return [edge(from4, void 0, expr2.value)]; } else { throw new Error("Unknown expr type"); } } } function cmp(a3, b4) { return b4 - a3; } function nullFrom(nfa2, node2) { let result = []; scan(node2); return result.sort(cmp); function scan(node3) { let edges = nfa2[node3]; if (edges.length == 1 && !edges[0].term) return scan(edges[0].to); result.push(node3); for (let i3 = 0; i3 < edges.length; i3++) { let { term, to: to2 } = edges[i3]; if (!term && result.indexOf(to2) == -1) scan(to2); } } } function dfa(nfa2) { let labeled = /* @__PURE__ */ Object.create(null); return explore(nullFrom(nfa2, 0)); function explore(states) { let out = []; states.forEach((node2) => { nfa2[node2].forEach(({ term, to: to2 }) => { if (!term) return; let set; for (let i3 = 0; i3 < out.length; i3++) if (out[i3][0] == term) set = out[i3][1]; nullFrom(nfa2, to2).forEach((node3) => { if (!set) out.push([term, set = []]); if (set.indexOf(node3) == -1) set.push(node3); }); }); }); let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1); for (let i3 = 0; i3 < out.length; i3++) { let states2 = out[i3][1].sort(cmp); state.next.push({ type: out[i3][0], next: labeled[states2.join(",")] || explore(states2) }); } return state; } } function checkForDeadEnds(match2, stream) { for (let i3 = 0, work = [match2]; i3 < work.length; i3++) { let state = work[i3], dead = !state.validEnd, nodes = []; for (let j4 = 0; j4 < state.next.length; j4++) { let { type, next: next2 } = state.next[j4]; nodes.push(type.name); if (dead && !(type.isText || type.hasRequiredAttrs())) dead = false; if (work.indexOf(next2) == -1) work.push(next2); } 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 defaults3 = /* @__PURE__ */ Object.create(null); for (let attrName in attrs) { let attr2 = attrs[attrName]; if (!attr2.hasDefault) return null; defaults3[attrName] = attr2.default; } return defaults3; } 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 attr2 = attrs[name]; if (attr2.hasDefault) given = attr2.default; else throw new RangeError("No value supplied for attribute " + name); } built[name] = given; } return built; } function checkAttrs(attrs, values2, type, name) { for (let name2 in values2) if (!(name2 in attrs)) throw new RangeError(`Unsupported attribute ${name2} for ${type} of type ${name2}`); for (let name2 in attrs) { let attr2 = attrs[name2]; if (attr2.validate) attr2.validate(values2[name2]); } } 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; } var NodeType = 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, content5, marks) { if (this.isText) throw new Error("NodeType.create can't construct text nodes"); return new Node2(this, this.computeAttrs(attrs), Fragment.from(content5), Mark.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, content5, marks) { content5 = Fragment.from(content5); this.checkContent(content5); return new Node2(this, this.computeAttrs(attrs), content5, Mark.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, content5, marks) { attrs = this.computeAttrs(attrs); content5 = Fragment.from(content5); if (content5.size) { let before = this.contentMatch.fillBefore(content5); if (!before) return null; content5 = before.append(content5); } let matched = this.contentMatch.matchFragment(content5); let after = matched && matched.fillBefore(Fragment.empty, true); if (!after) return null; return new Node2(this, attrs, content5.append(after), Mark.setFrom(marks)); } /** Returns true if the given fragment is valid content for this node type. */ validContent(content5) { let result = this.contentMatch.matchFragment(content5); if (!result || !result.validEnd) return false; for (let i3 = 0; i3 < content5.childCount; i3++) if (!this.allowsMarks(content5.child(i3).marks)) return false; return true; } /** Throws a RangeError if the given fragment is not valid content for this node type. @internal */ checkContent(content5) { if (!this.validContent(content5)) throw new RangeError(`Invalid content for node ${this.name}: ${content5.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 i3 = 0; i3 < marks.length; i3++) if (!this.allowsMarkType(marks[i3].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 copy3; for (let i3 = 0; i3 < marks.length; i3++) { if (!this.allowsMarkType(marks[i3].type)) { if (!copy3) copy3 = marks.slice(0, i3); } else if (copy3) { copy3.push(marks[i3]); } } return !copy3 ? marks : copy3.length ? copy3 : Mark.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 _2 in result.text.attrs) throw new RangeError("The text node type should not have attributes"); return result; } }; function validateType(typeName, attrName, type) { let types2 = type.split("|"); return (value) => { let name = value === null ? "null" : typeof value; if (types2.indexOf(name) < 0) throw new RangeError(`Expected value of type ${types2} for attribute ${attrName} on type ${typeName}, got ${name}`); }; } var Attribute = class { constructor(typeName, attrName, options2) { this.hasDefault = Object.prototype.hasOwnProperty.call(options2, "default"); this.default = options2.default; this.validate = typeof options2.validate == "string" ? validateType(typeName, attrName, options2.validate) : options2.validate; } get isRequired() { return !this.hasDefault; } }; var MarkType = 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 defaults3 = defaultAttrs(this.attrs); this.instance = defaults3 ? new Mark(this, defaults3) : 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(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 i3 = 0; i3 < set.length; i3++) if (set[i3].type == this) { set = set.slice(0, i3).concat(set.slice(i3 + 1)); i3--; } return set; } /** Tests whether there is a mark of this type in the given set. */ isInSet(set) { for (let i3 = 0; i3 < set.length; i3++) if (set[i3].type == this) return set[i3]; } /** @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; } }; var Schema = class { /** 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 = dist_default.from(spec.nodes), instanceSpec.marks = dist_default.from(spec.marks || {}), this.nodes = NodeType.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) => Node2.fromJSON(this, json); this.markFromJSON = (json) => Mark.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, content5, marks) { if (typeof type == "string") type = this.nodeType(type); else if (!(type instanceof NodeType)) 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, content5, marks); } /** Create a text node in the schema. Empty text nodes are not allowed. */ text(text10, marks) { let type = this.nodes.text; return new TextNode(type, type.defaultAttrs, text10, Mark.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 i3 = 0; i3 < marks.length; i3++) { let name = marks[i3], mark2 = schema.marks[name], ok3 = mark2; if (mark2) { found2.push(mark2); } else { for (let prop in schema.marks) { let mark3 = schema.marks[prop]; if (name == "_" || mark3.spec.group && mark3.spec.group.split(" ").indexOf(name) > -1) found2.push(ok3 = mark3); } } if (!ok3) throw new SyntaxError("Unknown mark type: '" + marks[i3] + "'"); } return found2; } function isTagRule(rule) { return rule.tag != null; } function isStyleRule(rule) { return rule.style != null; } var DOMParser2 = class _DOMParser { /** 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((r4) => { if (!/^(ul|ol)\b/.test(r4.tag) || !r4.node) return false; let node2 = schema.nodes[r4.node]; return node2.contentMatch.matchType(node2); }); } /** Parse a document from the content of a DOM node. */ parse(dom, options2 = {}) { let context = new ParseContext(this, options2, false); context.addAll(dom, Mark.none, options2.from, options2.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, options2 = {}) { let context = new ParseContext(this, options2, true); context.addAll(dom, Mark.none, options2.from, options2.to); return Slice.maxOpen(context.finish()); } /** @internal */ matchTag(dom, context, after) { for (let i3 = after ? this.tags.indexOf(after) + 1 : 0; i3 < this.tags.length; i3++) { let rule = this.tags[i3]; 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 i3 = after ? this.styles.indexOf(after) + 1 : 0; i3 < this.styles.length; i3++) { let rule = this.styles[i3], style3 = rule.style; if (style3.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. style3.length > prop.length && (style3.charCodeAt(prop.length) != 61 || style3.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, i3 = 0; for (; i3 < result.length; i3++) { let next2 = result[i3], nextPriority = next2.priority == null ? 50 : next2.priority; if (nextPriority < priority) break; } result.splice(i3, 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 _DOMParser(schema, _DOMParser.schemaRules(schema))); } }; var blockTags = { address: true, article: true, aside: true, blockquote: 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 }; var ignoreTags = { head: true, noscript: true, object: true, script: true, style: true, title: true }; var listTags = { ol: true, ul: true }; var OPT_PRESERVE_WS = 1; var OPT_PRESERVE_WS_FULL = 2; var OPT_OPEN_LEFT = 4; function wsOptionsFor(type, preserveWhitespace, base4) { 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 : base4 & ~OPT_OPEN_LEFT; } var NodeContext = class { constructor(type, attrs, marks, solid, match2, options2) { this.type = type; this.attrs = attrs; this.marks = marks; this.solid = solid; this.options = options2; this.content = []; this.activeMarks = Mark.none; this.match = match2 || (options2 & OPT_OPEN_LEFT ? null : type.contentMatch); } findWrapping(node2) { if (!this.match) { if (!this.type) return []; let fill = this.type.contentMatch.fillBefore(Fragment.from(node2)); if (fill) { this.match = this.type.contentMatch.matchFragment(fill); } else { let start = this.type.contentMatch, wrap5; if (wrap5 = start.findWrapping(node2.type)) { this.match = start; return wrap5; } else { return null; } } } return this.match.findWrapping(node2.type); } finish(openEnd) { if (!(this.options & OPT_PRESERVE_WS)) { let last2 = this.content[this.content.length - 1], m2; if (last2 && last2.isText && (m2 = /[ \t\r\n\u000c]+$/.exec(last2.text))) { let text10 = last2; if (last2.text.length == m2[0].length) this.content.pop(); else this.content[this.content.length - 1] = text10.withText(text10.text.slice(0, text10.text.length - m2[0].length)); } } let content5 = Fragment.from(this.content); if (!openEnd && this.match) content5 = content5.append(this.match.fillBefore(Fragment.empty, true)); return this.type ? this.type.create(this.attrs, content5, this.marks) : content5; } inlineContext(node2) { if (this.type) return this.type.inlineContent; if (this.content.length) return this.content[0].isInline; return node2.parentNode && !blockTags.hasOwnProperty(node2.parentNode.nodeName.toLowerCase()); } }; var ParseContext = class { constructor(parser, options2, isOpen) { this.parser = parser; this.options = options2; this.isOpen = isOpen; this.open = 0; this.localPreserveWS = false; let topNode = options2.topNode, topContext; let topOptions = wsOptionsFor(null, options2.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0); if (topNode) topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options2.topMatch || topNode.type.contentMatch, topOptions); else if (isOpen) topContext = new NodeContext(null, null, Mark.none, true, null, topOptions); else topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions); this.nodes = [topContext]; this.find = options2.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 i3 = 0; i3 < lines.length; i3++) { if (i3) this.insertNode(schema.linebreakReplacement.create(), marks, true); if (lines[i3]) this.insertNode(schema.text(lines[i3]), marks, !/\S/.test(lines[i3])); } 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 i3 = 0; i3 < this.parser.matchedStyles.length; i3++) { let name = this.parser.matchedStyles[i3], 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((m2) => !rule.clearMark(m2)); 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((node2) => this.insertNode(node2, 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 index4 = startIndex || 0; for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index4) { this.findAtPoint(parent, index4); this.addDOM(dom, marks); } this.findAtPoint(parent, index4); } // 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(node2, marks, cautious) { let route, sync; for (let depth = this.open, penalty = 0; depth >= 0; depth--) { let cx = this.nodes[depth]; let found2 = cx.findWrapping(node2); 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 i3 = 0; i3 < route.length; i3++) marks = this.enterInner(route[i3], null, marks, false); return marks; } // Try to insert the given node, adjusting the context when needed. insertNode(node2, marks, cautious) { if (node2.isInline && this.needsBlock && !this.top.type) { let block = this.textblockFromContext(); if (block) marks = this.enterInner(block, null, marks); } let innerMarks = this.findPlace(node2, marks, cautious); if (innerMarks) { this.closeExtra(); let top = this.top; if (top.match) top.match = top.match.matchType(node2.type); let nodeMarks = Mark.none; for (let m2 of innerMarks.concat(node2.marks)) if (top.type ? top.type.allowsMarkType(m2.type) : markMayApply(m2.type, node2.type)) nodeMarks = m2.addToSet(nodeMarks); top.content.push(node2.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 options2 = wsOptionsFor(type, preserveWS, top.options); if (top.options & OPT_OPEN_LEFT && top.content.length == 0) options2 |= OPT_OPEN_LEFT; let applyMarks = Mark.none; marks = marks.filter((m2) => { if (top.type ? top.type.allowsMarkType(m2.type) : markMayApply(m2.type, type)) { applyMarks = m2.addToSet(applyMarks); return false; } return true; }); this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options2)); this.open++; return marks; } // Make sure all nodes above this.open are finished and added to // their parents closeExtra(openEnd = false) { let i3 = this.nodes.length - 1; if (i3 > this.open) { for (; i3 > this.open; i3--) this.nodes[i3 - 1].content.push(this.nodes[i3].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(to2) { for (let i3 = this.open; i3 >= 0; i3--) { if (this.nodes[i3] == to2) { this.open = i3; return true; } else if (this.localPreserveWS) { this.nodes[i3].options |= OPT_PRESERVE_WS; } } return false; } get currentPos() { this.closeExtra(); let pos = 0; for (let i3 = this.open; i3 >= 0; i3--) { let content5 = this.nodes[i3].content; for (let j4 = content5.length - 1; j4 >= 0; j4--) pos += content5[j4].nodeSize; if (i3) pos++; } return pos; } findAtPoint(parent, offset4) { if (this.find) for (let i3 = 0; i3 < this.find.length; i3++) { if (this.find[i3].node == parent && this.find[i3].offset == offset4) this.find[i3].pos = this.currentPos; } } findInside(parent) { if (this.find) for (let i3 = 0; i3 < this.find.length; i3++) { if (this.find[i3].pos == null && parent.nodeType == 1 && parent.contains(this.find[i3].node)) this.find[i3].pos = this.currentPos; } } findAround(parent, content5, before) { if (parent != content5 && this.find) for (let i3 = 0; i3 < this.find.length; i3++) { if (this.find[i3].pos == null && parent.nodeType == 1 && parent.contains(this.find[i3].node)) { let pos = content5.compareDocumentPosition(this.find[i3].node); if (pos & (before ? 2 : 4)) this.find[i3].pos = this.currentPos; } } } findInText(textNode) { if (this.find) for (let i3 = 0; i3 < this.find.length; i3++) { if (this.find[i3].node == textNode) this.find[i3].pos = this.currentPos - (textNode.nodeValue.length - this.find[i3].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 option2 = this.options.context; let useRoot = !this.isOpen && (!option2 || option2.parent.type == this.nodes[0].type); let minDepth = -(option2 ? option2.depth + 1 : 0) + (useRoot ? 0 : 1); let match2 = (i3, depth) => { for (; i3 >= 0; i3--) { let part = parts[i3]; if (part == "") { if (i3 == parts.length - 1 || i3 == 0) continue; for (; depth >= minDepth; depth--) if (match2(i3 - 1, depth)) return true; return false; } else { let next2 = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option2 && depth >= minDepth ? option2.node(depth - minDepth).type : null; if (!next2 || next2.name != part && !next2.isInGroup(part)) return false; depth--; } } return true; }; return match2(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 copy3 = {}; for (let prop in obj) copy3[prop] = obj[prop]; return copy3; } 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 = (match2) => { seen.push(match2); for (let i3 = 0; i3 < match2.edgeCount; i3++) { let { type, next: next2 } = match2.edge(i3); if (type == nodeType) return true; if (seen.indexOf(next2) < 0 && scan(next2)) return true; } }; if (scan(parent.contentMatch)) return true; } } var DOMSerializer = 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, options2 = {}, target) { if (!target) target = doc(options2).createDocumentFragment(); let top = target, active = []; fragment.forEach((node2) => { if (active.length || node2.marks.length) { let keep = 0, rendered = 0; while (keep < active.length && rendered < node2.marks.length) { let next2 = node2.marks[rendered]; if (!this.marks[next2.type.name]) { rendered++; continue; } if (!next2.eq(active[keep][0]) || next2.type.spec.spanning === false) break; keep++; rendered++; } while (keep < active.length) top = active.pop()[1]; while (rendered < node2.marks.length) { let add = node2.marks[rendered++]; let markDOM = this.serializeMark(add, node2.isInline, options2); if (markDOM) { active.push([add, top]); top.appendChild(markDOM.dom); top = markDOM.contentDOM || markDOM.dom; } } } top.appendChild(this.serializeNodeInner(node2, options2)); }); return target; } /** @internal */ serializeNodeInner(node2, options2) { let { dom, contentDOM } = renderSpec(doc(options2), this.nodes[node2.type.name](node2), null, node2.attrs); if (contentDOM) { if (node2.isLeaf) throw new RangeError("Content hole not allowed in a leaf node spec"); this.serializeFragment(node2.content, options2, 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(node2, options2 = {}) { let dom = this.serializeNodeInner(node2, options2); for (let i3 = node2.marks.length - 1; i3 >= 0; i3--) { let wrap5 = this.serializeMark(node2.marks[i3], node2.isInline, options2); if (wrap5) { (wrap5.contentDOM || wrap5.dom).appendChild(dom); dom = wrap5.dom; } } return dom; } /** @internal */ serializeMark(mark2, inline4, options2 = {}) { let toDOM = this.marks[mark2.type.name]; return toDOM && renderSpec(doc(options2), toDOM(mark2, inline4), null, mark2.attrs); } static renderSpec(doc4, structure, xmlNS = null, blockArraysIn) { return renderSpec(doc4, 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 = (node2) => node2.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(options2) { return options2.document || window.document; } var 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 i3 = 0; i3 < value.length; i3++) scan(value[i3]); } } else { for (let prop in value) scan(value[prop]); } } } scan(attrs); return result; } function renderSpec(doc4, structure, xmlNS, blockArraysIn) { if (typeof structure == "string") return { dom: doc4.createTextNode(structure) }; if (structure.nodeType != null) return { dom: structure }; if (structure.dom && structure.dom.nodeType != null) 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 space2 = tagName.indexOf(" "); if (space2 > 0) { xmlNS = tagName.slice(0, space2); tagName = tagName.slice(space2 + 1); } let contentDOM; let dom = xmlNS ? doc4.createElementNS(xmlNS, tagName) : doc4.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 space3 = name.indexOf(" "); if (space3 > 0) dom.setAttributeNS(name.slice(0, space3), name.slice(space3 + 1), attrs[name]); else if (name == "style" && dom.style) dom.style.cssText = attrs[name]; else dom.setAttribute(name, attrs[name]); } } for (let i3 = start; i3 < structure.length; i3++) { let child = structure[i3]; if (child === 0) { if (i3 < structure.length - 1 || i3 > start) throw new RangeError("Content hole must be the only child of its parent node"); return { dom, contentDOM: dom }; } else { let { dom: inner, contentDOM: innerContent } = renderSpec(doc4, child, xmlNS, blockArraysIn); dom.appendChild(inner); if (innerContent) { if (contentDOM) throw new RangeError("Multiple content holes"); contentDOM = innerContent; } } } return { dom, contentDOM }; } // ../../node_modules/.pnpm/prosemirror-transform@1.10.5/node_modules/prosemirror-transform/dist/index.js var lower16 = 65535; var factor16 = Math.pow(2, 16); function makeRecover(index4, offset4) { return index4 + offset4 * factor16; } function recoverIndex(value) { return value & lower16; } function recoverOffset(value) { return (value - (value & lower16)) / factor16; } var DEL_BEFORE = 1; var DEL_AFTER = 2; var DEL_ACROSS = 4; var DEL_SIDE = 8; var MapResult = class { /** @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; } }; var StepMap = 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, index4 = recoverIndex(value); if (!this.inverted) for (let i3 = 0; i3 < index4; i3++) diff += this.ranges[i3 * 3 + 2] - this.ranges[i3 * 3 + 1]; return this.ranges[index4 * 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 i3 = 0; i3 < this.ranges.length; i3 += 3) { let start = this.ranges[i3] - (this.inverted ? diff : 0); if (start > pos) break; let oldSize = this.ranges[i3 + oldIndex], newSize = this.ranges[i3 + 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(i3 / 3, pos - start); let del3 = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS; if (assoc < 0 ? pos != start : pos != end) del3 |= DEL_SIDE; return new MapResult(result, del3, recover); } diff += newSize - oldSize; } return simple ? pos + diff : new MapResult(pos + diff, 0, null); } /** @internal */ touches(pos, recover) { let diff = 0, index4 = recoverIndex(recover); let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; for (let i3 = 0; i3 < this.ranges.length; i3 += 3) { let start = this.ranges[i3] - (this.inverted ? diff : 0); if (start > pos) break; let oldSize = this.ranges[i3 + oldIndex], end = start + oldSize; if (pos <= end && i3 == index4 * 3) return true; diff += this.ranges[i3 + newIndex] - oldSize; } return false; } /** Calls the given function on each of the changed ranges included in this map. */ forEach(f6) { let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; for (let i3 = 0, diff = 0; i3 < this.ranges.length; i3 += 3) { let start = this.ranges[i3], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff); let oldSize = this.ranges[i3 + oldIndex], newSize = this.ranges[i3 + newIndex]; f6(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([]); var Mapping = class _Mapping { /** Create a new mapping with the given position maps. */ constructor(maps, mirror, from4 = 0, to2 = maps ? maps.length : 0) { this.mirror = mirror; this.from = from4; this.to = to2; 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(from4 = 0, to2 = this.maps.length) { return new _Mapping(this._maps, this.mirror, from4, to2); } /** 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(map7, mirrors) { if (!this.ownData) { this._maps = this._maps.slice(); this.mirror = this.mirror && this.mirror.slice(); this.ownData = true; } this.to = this._maps.push(map7); 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 i3 = 0, startSize = this._maps.length; i3 < mapping._maps.length; i3++) { let mirr = mapping.getMirror(i3); this.appendMap(mapping._maps[i3], mirr != null && mirr < i3 ? 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 i3 = 0; i3 < this.mirror.length; i3++) if (this.mirror[i3] == n) return this.mirror[i3 + (i3 % 2 ? -1 : 1)]; } } /** @internal */ setMirror(n, m2) { if (!this.mirror) this.mirror = []; this.mirror.push(n, m2); } /** Append the inverse of the given mapping to this one. */ appendMappingInverted(mapping) { for (let i3 = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i3 >= 0; i3--) { let mirr = mapping.getMirror(i3); this.appendMap(mapping._maps[i3].invert(), mirr != null && mirr > i3 ? 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 i3 = this.from; i3 < this.to; i3++) pos = this._maps[i3].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 i3 = this.from; i3 < this.to; i3++) { let map7 = this._maps[i3], result = map7.mapResult(pos, assoc); if (result.recover != null) { let corr = this.getMirror(i3); if (corr != null && corr > i3 && corr < this.to) { i3 = corr; pos = this._maps[corr].recover(result.recover); continue; } } delInfo |= result.delInfo; pos = result.pos; } return simple ? pos : new MapResult(pos, delInfo, null); } }; var stepsByID = /* @__PURE__ */ Object.create(null); var Step = class { /** 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(id2, stepClass) { if (id2 in stepsByID) throw new RangeError("Duplicate use of step JSON ID " + id2); stepsByID[id2] = stepClass; stepClass.prototype.jsonID = id2; return stepClass; } }; var StepResult = class _StepResult { /** @internal */ constructor(doc4, failed) { this.doc = doc4; this.failed = failed; } /** Create a successful step result. */ static ok(doc4) { return new _StepResult(doc4, 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(doc4, from4, to2, slice2) { try { return _StepResult.ok(doc4.replace(from4, to2, slice2)); } catch (e2) { if (e2 instanceof ReplaceError) return _StepResult.fail(e2.message); throw e2; } } }; function mapFragment(fragment, f6, parent) { let mapped = []; for (let i3 = 0; i3 < fragment.childCount; i3++) { let child = fragment.child(i3); if (child.content.size) child = child.copy(mapFragment(child.content, f6, child)); if (child.isInline) child = f6(child, parent, i3); mapped.push(child); } return Fragment.fromArray(mapped); } var AddMarkStep = class _AddMarkStep extends Step { /** Create a mark step. */ constructor(from4, to2, mark2) { super(); this.from = from4; this.to = to2; this.mark = mark2; } apply(doc4) { let oldSlice = doc4.slice(this.from, this.to), $from = doc4.resolve(this.from); let parent = $from.node($from.sharedDepth(this.to)); let slice2 = new Slice(mapFragment(oldSlice.content, (node2, parent2) => { if (!node2.isAtom || !parent2.type.allowsMarkType(this.mark.type)) return node2; return node2.mark(this.mark.addToSet(node2.marks)); }, parent), oldSlice.openStart, oldSlice.openEnd); return StepResult.fromReplace(doc4, this.from, this.to, slice2); } invert() { return new RemoveMarkStep(this.from, this.to, this.mark); } map(mapping) { let from4 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1); if (from4.deleted && to2.deleted || from4.pos >= to2.pos) return null; return new _AddMarkStep(from4.pos, to2.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); var RemoveMarkStep = class _RemoveMarkStep extends Step { /** Create a mark-removing step. */ constructor(from4, to2, mark2) { super(); this.from = from4; this.to = to2; this.mark = mark2; } apply(doc4) { let oldSlice = doc4.slice(this.from, this.to); let slice2 = new Slice(mapFragment(oldSlice.content, (node2) => { return node2.mark(this.mark.removeFromSet(node2.marks)); }, doc4), oldSlice.openStart, oldSlice.openEnd); return StepResult.fromReplace(doc4, this.from, this.to, slice2); } invert() { return new AddMarkStep(this.from, this.to, this.mark); } map(mapping) { let from4 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1); if (from4.deleted && to2.deleted || from4.pos >= to2.pos) return null; return new _RemoveMarkStep(from4.pos, to2.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); var AddNodeMarkStep = class _AddNodeMarkStep extends Step { /** Create a node mark step. */ constructor(pos, mark2) { super(); this.pos = pos; this.mark = mark2; } apply(doc4) { let node2 = doc4.nodeAt(this.pos); if (!node2) return StepResult.fail("No node at mark step's position"); let updated = node2.type.create(node2.attrs, null, this.mark.addToSet(node2.marks)); return StepResult.fromReplace(doc4, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node2.isLeaf ? 0 : 1)); } invert(doc4) { let node2 = doc4.nodeAt(this.pos); if (node2) { let newSet = this.mark.addToSet(node2.marks); if (newSet.length == node2.marks.length) { for (let i3 = 0; i3 < node2.marks.length; i3++) if (!node2.marks[i3].isInSet(newSet)) return new _AddNodeMarkStep(this.pos, node2.marks[i3]); 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); var RemoveNodeMarkStep = class _RemoveNodeMarkStep extends Step { /** Create a mark-removing step. */ constructor(pos, mark2) { super(); this.pos = pos; this.mark = mark2; } apply(doc4) { let node2 = doc4.nodeAt(this.pos); if (!node2) return StepResult.fail("No node at mark step's position"); let updated = node2.type.create(node2.attrs, null, this.mark.removeFromSet(node2.marks)); return StepResult.fromReplace(doc4, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node2.isLeaf ? 0 : 1)); } invert(doc4) { let node2 = doc4.nodeAt(this.pos); if (!node2 || !this.mark.isInSet(node2.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); var ReplaceStep = 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(from4, to2, slice2, structure = false) { super(); this.from = from4; this.to = to2; this.slice = slice2; this.structure = structure; } apply(doc4) { if (this.structure && contentBetween(doc4, this.from, this.to)) return StepResult.fail("Structure replace would overwrite content"); return StepResult.fromReplace(doc4, this.from, this.to, this.slice); } getMap() { return new StepMap([this.from, this.to - this.from, this.slice.size]); } invert(doc4) { return new _ReplaceStep(this.from, this.from + this.slice.size, doc4.slice(this.from, this.to)); } map(mapping) { let from4 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1); if (from4.deletedAcross && to2.deletedAcross) return null; return new _ReplaceStep(from4.pos, Math.max(from4.pos, to2.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); } }; Step.jsonID("replace", ReplaceStep); var ReplaceAroundStep = 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(from4, to2, gapFrom, gapTo, slice2, insert, structure = false) { super(); this.from = from4; this.to = to2; this.gapFrom = gapFrom; this.gapTo = gapTo; this.slice = slice2; this.insert = insert; this.structure = structure; } apply(doc4) { if (this.structure && (contentBetween(doc4, this.from, this.gapFrom) || contentBetween(doc4, this.gapTo, this.to))) return StepResult.fail("Structure gap-replace would overwrite content"); let gap = doc4.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(doc4, 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(doc4) { 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, doc4.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure); } map(mapping) { let from4 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1); let gapFrom = this.from == this.gapFrom ? from4.pos : mapping.map(this.gapFrom, -1); let gapTo = this.to == this.gapTo ? to2.pos : mapping.map(this.gapTo, 1); if (from4.deletedAcross && to2.deletedAcross || gapFrom < from4.pos || gapTo > to2.pos) return null; return new _ReplaceAroundStep(from4.pos, to2.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(doc4, from4, to2) { let $from = doc4.resolve(from4), dist = to2 - from4, depth = $from.depth; while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) { depth--; dist--; } if (dist > 0) { let next2 = $from.node(depth).maybeChild($from.indexAfter(depth)); while (dist > 0) { if (!next2 || next2.isLeaf) return true; next2 = next2.firstChild; dist--; } } return false; } function addMark(tr4, from4, to2, mark2) { let removed = [], added = []; let removing, adding; tr4.doc.nodesBetween(from4, to2, (node2, pos, parent) => { if (!node2.isInline) return; let marks = node2.marks; if (!mark2.isInSet(marks) && parent.type.allowsMarkType(mark2.type)) { let start = Math.max(pos, from4), end = Math.min(pos + node2.nodeSize, to2); let newSet = mark2.addToSet(marks); for (let i3 = 0; i3 < marks.length; i3++) { if (!marks[i3].isInSet(newSet)) { if (removing && removing.to == start && removing.mark.eq(marks[i3])) removing.to = end; else removed.push(removing = new RemoveMarkStep(start, end, marks[i3])); } } if (adding && adding.to == start) adding.to = end; else added.push(adding = new AddMarkStep(start, end, mark2)); } }); removed.forEach((s2) => tr4.step(s2)); added.forEach((s2) => tr4.step(s2)); } function removeMark(tr4, from4, to2, mark2) { let matched = [], step = 0; tr4.doc.nodesBetween(from4, to2, (node2, pos) => { if (!node2.isInline) return; step++; let toRemove = null; if (mark2 instanceof MarkType) { let set = node2.marks, found2; while (found2 = mark2.isInSet(set)) { (toRemove || (toRemove = [])).push(found2); set = found2.removeFromSet(set); } } else if (mark2) { if (mark2.isInSet(node2.marks)) toRemove = [mark2]; } else { toRemove = node2.marks; } if (toRemove && toRemove.length) { let end = Math.min(pos + node2.nodeSize, to2); for (let i3 = 0; i3 < toRemove.length; i3++) { let style3 = toRemove[i3], found2; for (let j4 = 0; j4 < matched.length; j4++) { let m2 = matched[j4]; if (m2.step == step - 1 && style3.eq(matched[j4].style)) found2 = m2; } if (found2) { found2.to = end; found2.step = step; } else { matched.push({ style: style3, from: Math.max(pos, from4), to: end, step }); } } } }); matched.forEach((m2) => tr4.step(new RemoveMarkStep(m2.from, m2.to, m2.style))); } function clearIncompatible(tr4, pos, parentType, match2 = parentType.contentMatch, clearNewlines = true) { let node2 = tr4.doc.nodeAt(pos); let replSteps = [], cur = pos + 1; for (let i3 = 0; i3 < node2.childCount; i3++) { let child = node2.child(i3), end = cur + child.nodeSize; let allowed = match2.matchType(child.type); if (!allowed) { replSteps.push(new ReplaceStep(cur, end, Slice.empty)); } else { match2 = allowed; for (let j4 = 0; j4 < child.marks.length; j4++) if (!parentType.allowsMarkType(child.marks[j4].type)) tr4.step(new RemoveMarkStep(cur, end, child.marks[j4])); if (clearNewlines && child.isText && parentType.whitespace != "pre") { let m2, newline = /\r?\n|\r/g, slice2; while (m2 = 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 + m2.index, cur + m2.index + m2[0].length, slice2)); } } } cur = end; } if (!match2.validEnd) { let fill = match2.fillBefore(Fragment.empty, true); tr4.replace(cur, cur, new Slice(fill, 0, 0)); } for (let i3 = replSteps.length - 1; i3 >= 0; i3--) tr4.step(replSteps[i3]); } function canCut(node2, start, end) { return (start == 0 || node2.canReplace(start, node2.childCount)) && (end == node2.childCount || node2.canReplace(0, end)); } function liftTarget(range) { let parent = range.parent; let content5 = parent.content.cutByIndex(range.startIndex, range.endIndex); for (let depth = range.depth, contentBefore = 0, contentAfter = 0; ; --depth) { let node2 = range.$from.node(depth); let index4 = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter; if (depth < range.depth && node2.canReplace(index4, endIndex, content5)) return depth; if (depth == 0 || node2.type.spec.isolating || !canCut(node2, index4, endIndex)) break; if (index4) contentBefore = 1; if (endIndex < node2.childCount) contentAfter = 1; } return null; } function lift(tr4, 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++; } tr4.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 i3 = startIndex; innerMatch && i3 < endIndex; i3++) innerMatch = innerMatch.matchType(parent.child(i3).type); if (!innerMatch || !innerMatch.validEnd) return null; return inside; } function wrap(tr4, range, wrappers) { let content5 = Fragment.empty; for (let i3 = wrappers.length - 1; i3 >= 0; i3--) { if (content5.size) { let match2 = wrappers[i3].type.contentMatch.matchFragment(content5); if (!match2 || !match2.validEnd) throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper"); } content5 = Fragment.from(wrappers[i3].type.create(wrappers[i3].attrs, content5)); } let start = range.start, end = range.end; tr4.step(new ReplaceAroundStep(start, end, start, end, new Slice(content5, 0, 0), wrappers.length, true)); } function setBlockType(tr4, from4, to2, type, attrs) { if (!type.isTextblock) throw new RangeError("Type given to setBlockType should be a textblock"); let mapFrom = tr4.steps.length; tr4.doc.nodesBetween(from4, to2, (node2, pos) => { let attrsHere = typeof attrs == "function" ? attrs(node2) : attrs; if (node2.isTextblock && !node2.hasMarkup(type, attrsHere) && canChangeType(tr4.doc, tr4.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(tr4, node2, pos, mapFrom); clearIncompatible(tr4, tr4.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null); let mapping = tr4.mapping.slice(mapFrom); let startM = mapping.map(pos, 1), endM = mapping.map(pos + node2.nodeSize, 1); tr4.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node2.marks)), 0, 0), 1, true)); if (convertNewlines === true) replaceNewlines(tr4, node2, pos, mapFrom); return false; } }); } function replaceNewlines(tr4, node2, pos, mapFrom) { node2.forEach((child, offset4) => { if (child.isText) { let m2, newline = /\r?\n|\r/g; while (m2 = newline.exec(child.text)) { let start = tr4.mapping.slice(mapFrom).map(pos + 1 + offset4 + m2.index); tr4.replaceWith(start, start + 1, node2.type.schema.linebreakReplacement.create()); } } }); } function replaceLinebreaks(tr4, node2, pos, mapFrom) { node2.forEach((child, offset4) => { if (child.type == child.type.schema.linebreakReplacement) { let start = tr4.mapping.slice(mapFrom).map(pos + 1 + offset4); tr4.replaceWith(start, start + 1, node2.type.schema.text("\n")); } }); } function canChangeType(doc4, pos, type) { let $pos = doc4.resolve(pos), index4 = $pos.index(); return $pos.parent.canReplaceWith(index4, index4 + 1, type); } function setNodeMarkup(tr4, pos, type, attrs, marks) { let node2 = tr4.doc.nodeAt(pos); if (!node2) throw new RangeError("No node at given position"); if (!type) type = node2.type; let newNode = type.create(attrs, null, marks || node2.marks); if (node2.isLeaf) return tr4.replaceWith(pos, pos + node2.nodeSize, newNode); if (!type.validContent(node2.content)) throw new RangeError("Invalid content for node type " + type.name); tr4.step(new ReplaceAroundStep(pos, pos + node2.nodeSize, pos + 1, pos + node2.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true)); } function canSplit(doc4, pos, depth = 1, typesAfter) { let $pos = doc4.resolve(pos), base4 = $pos.depth - depth; let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent; if (base4 < 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, i3 = depth - 2; d > base4; d--, i3--) { let node2 = $pos.node(d), index5 = $pos.index(d); if (node2.type.spec.isolating) return false; let rest = node2.content.cutByIndex(index5, node2.childCount); let overrideChild = typesAfter && typesAfter[i3 + 1]; if (overrideChild) rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs)); let after = typesAfter && typesAfter[i3] || node2; if (!node2.canReplace(index5 + 1, node2.childCount) || !after.type.validContent(rest)) return false; } let index4 = $pos.indexAfter(base4); let baseType = typesAfter && typesAfter[0]; return $pos.node(base4).canReplaceWith(index4, index4, baseType ? baseType.type : $pos.node(base4 + 1).type); } function split(tr4, pos, depth = 1, typesAfter) { let $pos = tr4.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty; for (let d = $pos.depth, e2 = $pos.depth - depth, i3 = depth - 1; d > e2; d--, i3--) { before = Fragment.from($pos.node(d).copy(before)); let typeAfter = typesAfter && typesAfter[i3]; after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after)); } tr4.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true)); } function canJoin(doc4, pos) { let $pos = doc4.resolve(pos), index4 = $pos.index(); return joinable2($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index4, index4 + 1); } function canAppendWithSubstitutedLinebreaks(a3, b4) { if (!b4.content.size) a3.type.compatibleContent(b4.type); let match2 = a3.contentMatchAt(a3.childCount); let { linebreakReplacement } = a3.type.schema; for (let i3 = 0; i3 < b4.childCount; i3++) { let child = b4.child(i3); let type = child.type == linebreakReplacement ? a3.type.schema.nodes.text : child.type; match2 = match2.matchType(type); if (!match2) return false; if (!a3.type.allowsMarks(child.marks)) return false; } return match2.validEnd; } function joinable2(a3, b4) { return !!(a3 && b4 && !a3.isLeaf && canAppendWithSubstitutedLinebreaks(a3, b4)); } function joinPoint(doc4, pos, dir = -1) { let $pos = doc4.resolve(pos); for (let d = $pos.depth; ; d--) { let before, after, index4 = $pos.index(d); if (d == $pos.depth) { before = $pos.nodeBefore; after = $pos.nodeAfter; } else if (dir > 0) { before = $pos.node(d + 1); index4++; after = $pos.node(d).maybeChild(index4); } else { before = $pos.node(d).maybeChild(index4 - 1); after = $pos.node(d + 1); } if (before && !before.isTextblock && joinable2(before, after) && $pos.node(d).canReplace(index4, index4 + 1)) return pos; if (d == 0) break; pos = dir < 0 ? $pos.before(d) : $pos.after(d); } } function join(tr4, pos, depth) { let convertNewlines = null; let { linebreakReplacement } = tr4.doc.type.schema; let $before = tr4.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 = tr4.steps.length; if (convertNewlines === false) { let $after = tr4.doc.resolve(pos + depth); replaceLinebreaks(tr4, $after.node(), $after.before(), mapFrom); } if (beforeType.inlineContent) clearIncompatible(tr4, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null); let mapping = tr4.mapping.slice(mapFrom), start = mapping.map(pos - depth); tr4.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true)); if (convertNewlines === true) { let $full = tr4.doc.resolve(start); replaceNewlines(tr4, $full.node(), $full.before(), tr4.steps.length); } return tr4; } function insertPoint(doc4, pos, nodeType) { let $pos = doc4.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 index4 = $pos.index(d); if ($pos.node(d).canReplaceWith(index4, index4, nodeType)) return $pos.before(d + 1); if (index4 > 0) return null; } if ($pos.parentOffset == $pos.parent.content.size) for (let d = $pos.depth - 1; d >= 0; d--) { let index4 = $pos.indexAfter(d); if ($pos.node(d).canReplaceWith(index4, index4, nodeType)) return $pos.after(d + 1); if (index4 < $pos.node(d).childCount) return null; } return null; } function dropPoint(doc4, pos, slice2) { let $pos = doc4.resolve(pos); if (!slice2.content.size) return pos; let content5 = slice2.content; for (let i3 = 0; i3 < slice2.openStart; i3++) content5 = content5.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, content5); } else { let wrapping = parent.contentMatchAt(insertPos).findWrapping(content5.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(doc4, from4, to2 = from4, slice2 = Slice.empty) { if (from4 == to2 && !slice2.size) return null; let $from = doc4.resolve(from4), $to = doc4.resolve(to2); if (fitsTrivially($from, $to, slice2)) return new ReplaceStep(from4, to2, 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); } var Fitter = class { constructor($from, $to, unplaced) { this.$from = $from; this.$to = $to; this.unplaced = unplaced; this.frontier = []; this.placed = Fragment.empty; for (let i3 = 0; i3 <= $from.depth; i3++) { let node2 = $from.node(i3); this.frontier.push({ type: node2.type, match: node2.contentMatchAt($from.indexAfter(i3)) }); } for (let i3 = $from.depth; i3 > 0; i3--) this.placed = Fragment.from($from.node(i3).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 content5 = this.placed, openStart = $from.depth, openEnd = $to.depth; while (openStart && openEnd && content5.childCount == 1) { content5 = content5.firstChild.content; openStart--; openEnd--; } let slice2 = new Slice(content5, 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 node2 = cur.firstChild; if (cur.childCount > 1) openEnd = 0; if (node2.type.spec.isolating && openEnd <= d) { startDepth = d; break; } cur = node2.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: match2 } = this.frontier[frontierDepth], wrap5, inject = null; if (pass == 1 && (first2 ? match2.matchType(first2.type) || (inject = match2.fillBefore(Fragment.from(first2), false)) : parent && type.compatibleContent(parent.type))) return { sliceDepth, frontierDepth, parent, inject }; else if (pass == 2 && first2 && (wrap5 = match2.findWrapping(first2.type))) return { sliceDepth, frontierDepth, parent, wrap: wrap5 }; if (parent && match2.matchType(parent.type)) break; } } } } openMore() { let { content: content5, openStart, openEnd } = this.unplaced; let inner = contentAt(content5, openStart); if (!inner.childCount || inner.firstChild.isLeaf) return false; this.unplaced = new Slice(content5, openStart + 1, Math.max(openEnd, inner.size + openStart >= content5.size - openEnd ? openStart + 1 : 0)); return true; } dropNode() { let { content: content5, openStart, openEnd } = this.unplaced; let inner = contentAt(content5, openStart); if (inner.childCount <= 1 && openStart > 0) { let openAtEnd = content5.size - openStart <= openStart + inner.size; this.unplaced = new Slice(dropFromFragment(content5, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd); } else { this.unplaced = new Slice(dropFromFragment(content5, 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: wrap5 }) { while (this.depth > frontierDepth) this.closeFrontierNode(); if (wrap5) for (let i3 = 0; i3 < wrap5.length; i3++) this.openFrontierNode(wrap5[i3]); let slice2 = this.unplaced, fragment = parent ? parent.content : slice2.content; let openStart = slice2.openStart - sliceDepth; let taken = 0, add = []; let { match: match2, type } = this.frontier[frontierDepth]; if (inject) { for (let i3 = 0; i3 < inject.childCount; i3++) add.push(inject.child(i3)); match2 = match2.matchFragment(inject); } let openEndCount = fragment.size + sliceDepth - (slice2.content.size - slice2.openEnd); while (taken < fragment.childCount) { let next2 = fragment.child(taken), matches3 = match2.matchType(next2.type); if (!matches3) break; taken++; if (taken > 1 || openStart == 0 || next2.content.size) { match2 = matches3; add.push(closeNodeStart(next2.mark(type.allowedMarks(next2.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 = match2; if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1) this.closeFrontierNode(); for (let i3 = 0, cur = fragment; i3 < openEndCount; i3++) { let node2 = cur.lastChild; this.frontier.push({ type: node2.type, match: node2.contentMatchAt(node2.childCount) }); cur = node2.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 i3 = Math.min(this.depth, $to.depth); i3 >= 0; i3--) { let { match: match2, type } = this.frontier[i3]; let dropInner = i3 < $to.depth && $to.end(i3 + 1) == $to.pos + ($to.depth - (i3 + 1)); let fit = contentAfterFits($to, i3, type, match2, dropInner); if (!fit) continue; for (let d = i3 - 1; d >= 0; d--) { let { match: match3, type: type2 } = this.frontier[d]; let matches3 = contentAfterFits($to, d, type2, match3, true); if (!matches3 || matches3.childCount) continue scan; } return { depth: i3, fit, move: dropInner ? $to.doc.resolve($to.after(i3 + 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 node2 = $to.node(d), add = node2.type.contentMatch.fillBefore(node2.content, true, $to.index(d)); this.openFrontierNode(node2.type, node2.attrs, add); } return $to; } openFrontierNode(type, attrs = null, content5) { let top = this.frontier[this.depth]; top.match = top.match.matchType(type); this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content5))); 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, count2) { if (depth == 0) return fragment.cutByIndex(count2, fragment.childCount); return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count2))); } function addToFragment(fragment, depth, content5) { if (depth == 0) return fragment.append(content5); return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content5))); } function contentAt(fragment, depth) { for (let i3 = 0; i3 < depth; i3++) fragment = fragment.firstChild.content; return fragment; } function closeNodeStart(node2, openStart, openEnd) { if (openStart <= 0) return node2; let frag = node2.content; if (openStart > 1) frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0)); if (openStart > 0) { frag = node2.type.contentMatch.fillBefore(frag).append(frag); if (openEnd <= 0) frag = frag.append(node2.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true)); } return node2.copy(frag); } function contentAfterFits($to, depth, type, match2, open) { let node2 = $to.node(depth), index4 = open ? $to.indexAfter(depth) : $to.index(depth); if (index4 == node2.childCount && !type.compatibleContent(node2.type)) return null; let fit = match2.fillBefore(node2.content, true, index4); return fit && !invalidMarks(type, node2.content, index4) ? fit : null; } function invalidMarks(type, fragment, start) { for (let i3 = start; i3 < fragment.childCount; i3++) if (!type.allowsMarks(fragment.child(i3).marks)) return true; return false; } function definesContent(type) { return type.spec.defining || type.spec.definingForContent; } function replaceRange(tr4, from4, to2, slice2) { if (!slice2.size) return tr4.deleteRange(from4, to2); let $from = tr4.doc.resolve(from4), $to = tr4.doc.resolve(to2); if (fitsTrivially($from, $to, slice2)) return tr4.step(new ReplaceStep(from4, to2, 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 content5 = slice2.content, i3 = 0; ; i3++) { let node2 = content5.firstChild; leftNodes.push(node2); if (i3 == slice2.openStart) break; content5 = node2.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 j4 = slice2.openStart; j4 >= 0; j4--) { let openDepth = (j4 + preferredDepth + 1) % (slice2.openStart + 1); let insert = leftNodes[openDepth]; if (!insert) continue; for (let i3 = 0; i3 < targetDepths.length; i3++) { let targetDepth = targetDepths[(i3 + preferredTargetIndex) % targetDepths.length], expand = true; if (targetDepth < 0) { expand = false; targetDepth = -targetDepth; } let parent = $from.node(targetDepth - 1), index4 = $from.index(targetDepth - 1); if (parent.canReplaceWith(index4, index4, insert.type, insert.marks)) return tr4.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to2, new Slice(closeFragment(slice2.content, 0, slice2.openStart, openDepth), openDepth, slice2.openEnd)); } } let startSteps = tr4.steps.length; for (let i3 = targetDepths.length - 1; i3 >= 0; i3--) { tr4.replace(from4, to2, slice2); if (tr4.steps.length > startSteps) break; let depth = targetDepths[i3]; if (depth < 0) continue; from4 = $from.before(depth); to2 = $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 match2 = parent.contentMatchAt(0); let start = match2.fillBefore(fragment).append(fragment); fragment = start.append(match2.matchFragment(start).fillBefore(Fragment.empty, true)); } return fragment; } function replaceRangeWith(tr4, from4, to2, node2) { if (!node2.isInline && from4 == to2 && tr4.doc.resolve(from4).parent.content.size) { let point5 = insertPoint(tr4.doc, from4, node2.type); if (point5 != null) from4 = to2 = point5; } tr4.replaceRange(from4, to2, new Slice(Fragment.from(node2), 0, 0)); } function deleteRange(tr4, from4, to2) { let $from = tr4.doc.resolve(from4), $to = tr4.doc.resolve(to2); let covered = coveredDepths($from, $to); for (let i3 = 0; i3 < covered.length; i3++) { let depth = covered[i3], last2 = i3 == covered.length - 1; if (last2 && depth == 0 || $from.node(depth).type.contentMatch.validEnd) return tr4.delete($from.start(depth), $to.end(depth)); if (depth > 0 && (last2 || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1)))) return tr4.delete($from.before(depth), $to.after(depth)); } for (let d = 1; d <= $from.depth && d <= $to.depth; d++) { if (from4 - $from.start(d) == $from.depth - d && to2 > $from.end(d) && $to.end(d) - to2 != $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 tr4.delete($from.before(d), to2); } tr4.delete(from4, to2); } 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; } var AttrStep = class _AttrStep extends Step { /** Construct an attribute step. */ constructor(pos, attr2, value) { super(); this.pos = pos; this.attr = attr2; this.value = value; } apply(doc4) { let node2 = doc4.nodeAt(this.pos); if (!node2) return StepResult.fail("No node at attribute step's position"); let attrs = /* @__PURE__ */ Object.create(null); for (let name in node2.attrs) attrs[name] = node2.attrs[name]; attrs[this.attr] = this.value; let updated = node2.type.create(attrs, null, node2.marks); return StepResult.fromReplace(doc4, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node2.isLeaf ? 0 : 1)); } getMap() { return StepMap.empty; } invert(doc4) { return new _AttrStep(this.pos, this.attr, doc4.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); var DocAttrStep = class _DocAttrStep extends Step { /** Construct an attribute step. */ constructor(attr2, value) { super(); this.attr = attr2; this.value = value; } apply(doc4) { let attrs = /* @__PURE__ */ Object.create(null); for (let name in doc4.attrs) attrs[name] = doc4.attrs[name]; attrs[this.attr] = this.value; let updated = doc4.type.create(attrs, doc4.content, doc4.marks); return StepResult.ok(updated); } getMap() { return StepMap.empty; } invert(doc4) { return new _DocAttrStep(this.attr, doc4.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); var 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"; var Transform = class { /** Create a transform that starts with the given document. */ constructor(doc4) { this.doc = doc4; 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; } /** @internal */ addStep(step, doc4) { this.docs.push(this.doc); this.steps.push(step); this.mapping.appendMap(step.getMap()); this.doc = doc4; } /** Replace the part of the document between `from` and `to` with the given `slice`. */ replace(from4, to2 = from4, slice2 = Slice.empty) { let step = replaceStep(this.doc, from4, to2, 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(from4, to2, content5) { return this.replace(from4, to2, new Slice(Fragment.from(content5), 0, 0)); } /** Delete the content between the given positions. */ delete(from4, to2) { return this.replace(from4, to2, Slice.empty); } /** Insert the given content at the given position. */ insert(pos, content5) { return this.replaceWith(pos, pos, content5); } /** 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(from4, to2, slice2) { replaceRange(this, from4, to2, 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(from4, to2, node2) { replaceRangeWith(this, from4, to2, node2); return this; } /** Delete the given range, expanding it to cover fully covered parent nodes until a valid replace is found. */ deleteRange(from4, to2) { deleteRange(this, from4, to2); 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(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(from4, to2 = from4, type, attrs = null) { setBlockType(this, from4, to2, 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, attr2, value) { this.step(new AttrStep(pos, attr2, value)); return this; } /** Set a single attribute on the document to a new value. */ setDocAttribute(attr2, value) { this.step(new DocAttrStep(attr2, value)); return this; } /** Add a mark to the node at position `pos`. */ addNodeMark(pos, mark2) { this.step(new AddNodeMarkStep(pos, mark2)); return this; } /** Remove a mark (or all marks of the given type) from the node at position `pos`. */ removeNodeMark(pos, mark2) { let node2 = this.doc.nodeAt(pos); if (!node2) throw new RangeError("No node at position " + pos); if (mark2 instanceof Mark) { if (mark2.isInSet(node2.marks)) this.step(new RemoveNodeMarkStep(pos, mark2)); } else { let set = node2.marks, found2, steps = []; while (found2 = mark2.isInSet(set)) { steps.push(new RemoveNodeMarkStep(pos, found2)); set = found2.removeFromSet(set); } for (let i3 = steps.length - 1; i3 >= 0; i3--) this.step(steps[i3]); } 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(from4, to2, mark2) { addMark(this, from4, to2, mark2); 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(from4, to2, mark2) { removeMark(this, from4, to2, mark2); 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, match2) { clearIncompatible(this, pos, parentType, match2); return this; } }; // ../../node_modules/.pnpm/prosemirror-state@1.4.4/node_modules/prosemirror-state/dist/index.js var classesById = /* @__PURE__ */ Object.create(null); var Selection = class { /** 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 i3 = 0; i3 < ranges.length; i3++) if (ranges[i3].$from.pos != ranges[i3].$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(tr4, content5 = Slice.empty) { let lastNode = content5.content.lastChild, lastParent = null; for (let i3 = 0; i3 < content5.openEnd; i3++) { lastParent = lastNode; lastNode = lastNode.lastChild; } let mapFrom = tr4.steps.length, ranges = this.ranges; for (let i3 = 0; i3 < ranges.length; i3++) { let { $from, $to } = ranges[i3], mapping = tr4.mapping.slice(mapFrom); tr4.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i3 ? Slice.empty : content5); if (i3 == 0) selectionToInsertionEnd(tr4, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1); } } /** Replace the selection with the given node, appending the changes to the given transaction. */ replaceWith(tr4, node2) { let mapFrom = tr4.steps.length, ranges = this.ranges; for (let i3 = 0; i3 < ranges.length; i3++) { let { $from, $to } = ranges[i3], mapping = tr4.mapping.slice(mapFrom); let from4 = mapping.map($from.pos), to2 = mapping.map($to.pos); if (i3) { tr4.deleteRange(from4, to2); } else { tr4.replaceRangeWith(from4, to2, node2); selectionToInsertionEnd(tr4, mapFrom, node2.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(doc4) { return findSelectionIn(doc4, doc4, 0, 0, 1) || new AllSelection(doc4); } /** Find the cursor or leaf node selection closest to the end of the given document. */ static atEnd(doc4) { return findSelectionIn(doc4, doc4, doc4.content.size, doc4.childCount, -1) || new AllSelection(doc4); } /** Deserialize the JSON representation of a selection. Must be implemented for custom classes (as a static class method). */ static fromJSON(doc4, 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(doc4, 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(id2, selectionClass) { if (id2 in classesById) throw new RangeError("Duplicate use of selection JSON ID " + id2); classesById[id2] = selectionClass; selectionClass.prototype.jsonID = id2; 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; var SelectionRange = class { /** Create a range. */ constructor($from, $to) { this.$from = $from; this.$to = $to; } }; var 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 + ")"); } } var TextSelection = 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(doc4, mapping) { let $head = doc4.resolve(mapping.map(this.head)); if (!$head.parent.inlineContent) return Selection.near($head); let $anchor = doc4.resolve(mapping.map(this.anchor)); return new _TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head); } replace(tr4, content5 = Slice.empty) { super.replace(tr4, content5); if (content5 == Slice.empty) { let marks = this.$from.marksAcross(this.$to); if (marks) tr4.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(doc4, json) { if (typeof json.anchor != "number" || typeof json.head != "number") throw new RangeError("Invalid input for TextSelection.fromJSON"); return new _TextSelection(doc4.resolve(json.anchor), doc4.resolve(json.head)); } /** Create a text selection from non-resolved positions. */ static create(doc4, anchor, head2 = anchor) { let $anchor = doc4.resolve(anchor); return new this($anchor, head2 == anchor ? $anchor : doc4.resolve(head2)); } /** 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); var TextBookmark = class _TextBookmark { constructor(anchor, head2) { this.anchor = anchor; this.head = head2; } map(mapping) { return new _TextBookmark(mapping.map(this.anchor), mapping.map(this.head)); } resolve(doc4) { return TextSelection.between(doc4.resolve(this.anchor), doc4.resolve(this.head)); } }; var NodeSelection = class _NodeSelection extends Selection { /** Create a node selection. Does not verify the validity of its argument. */ constructor($pos) { let node2 = $pos.nodeAfter; let $end = $pos.node(0).resolve($pos.pos + node2.nodeSize); super($pos, $end); this.node = node2; } map(doc4, mapping) { let { deleted, pos } = mapping.mapResult(this.anchor); let $pos = doc4.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(doc4, json) { if (typeof json.anchor != "number") throw new RangeError("Invalid input for NodeSelection.fromJSON"); return new _NodeSelection(doc4.resolve(json.anchor)); } /** Create a node selection from non-resolved positions. */ static create(doc4, from4) { return new _NodeSelection(doc4.resolve(from4)); } /** Determines whether the given node may be selected as a node selection. */ static isSelectable(node2) { return !node2.isText && node2.type.spec.selectable !== false; } }; NodeSelection.prototype.visible = false; Selection.jsonID("node", NodeSelection); var NodeBookmark = 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(doc4) { let $pos = doc4.resolve(this.anchor), node2 = $pos.nodeAfter; if (node2 && NodeSelection.isSelectable(node2)) return new NodeSelection($pos); return Selection.near($pos); } }; var AllSelection = class _AllSelection extends Selection { /** Create an all-selection over the given document. */ constructor(doc4) { super(doc4.resolve(0), doc4.resolve(doc4.content.size)); } replace(tr4, content5 = Slice.empty) { if (content5 == Slice.empty) { tr4.delete(0, tr4.doc.content.size); let sel = Selection.atStart(tr4.doc); if (!sel.eq(tr4.selection)) tr4.setSelection(sel); } else { super.replace(tr4, content5); } } toJSON() { return { type: "all" }; } /** @internal */ static fromJSON(doc4) { return new _AllSelection(doc4); } map(doc4) { return new _AllSelection(doc4); } eq(other) { return other instanceof _AllSelection; } getBookmark() { return AllBookmark; } }; Selection.jsonID("all", AllSelection); var AllBookmark = { map() { return this; }, resolve(doc4) { return new AllSelection(doc4); } }; function findSelectionIn(doc4, node2, pos, index4, dir, text10 = false) { if (node2.inlineContent) return TextSelection.create(doc4, pos); for (let i3 = index4 - (dir > 0 ? 0 : 1); dir > 0 ? i3 < node2.childCount : i3 >= 0; i3 += dir) { let child = node2.child(i3); if (!child.isAtom) { let inner = findSelectionIn(doc4, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text10); if (inner) return inner; } else if (!text10 && NodeSelection.isSelectable(child)) { return NodeSelection.create(doc4, pos - (dir < 0 ? child.nodeSize : 0)); } pos += child.nodeSize * dir; } return null; } function selectionToInsertionEnd(tr4, startLen, bias) { let last2 = tr4.steps.length - 1; if (last2 < startLen) return; let step = tr4.steps[last2]; if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) return; let map7 = tr4.mapping.maps[last2], end; map7.forEach((_from, _to, _newFrom, newTo) => { if (end == null) end = newTo; }); tr4.setSelection(Selection.near(tr4.doc.resolve(end), bias)); } var UPDATED_SEL = 1; var UPDATED_MARKS = 2; var UPDATED_SCROLL = 4; var Transaction = class extends Transform { /** @internal */ constructor(state) { super(state.doc); this.curSelectionFor = 0; this.updated = 0; this.meta = /* @__PURE__ */ Object.create(null); this.time = Date.now(); this.curSelection = state.selection; this.storedMarks = state.storedMarks; } /** The transaction's current selection. This defaults to the editor selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the transaction, but can be overwritten with [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection). */ get selection() { if (this.curSelectionFor < this.steps.length) { this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor)); this.curSelectionFor = this.steps.length; } return this.curSelection; } /** Update the transaction's current selection. Will determine the selection that the editor gets when the transaction is applied. */ setSelection(selection) { if (selection.$from.doc != this.doc) throw new RangeError("Selection passed to setSelection must point at the current document"); this.curSelection = selection; this.curSelectionFor = this.steps.length; this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS; this.storedMarks = null; return this; } /** Whether the selection was explicitly updated by this transaction. */ get selectionSet() { return (this.updated & UPDATED_SEL) > 0; } /** Set the current stored marks. */ setStoredMarks(marks) { this.storedMarks = marks; this.updated |= UPDATED_MARKS; return this; } /** Make sure the current stored marks or, if that is null, the marks at the selection, match the given set of marks. Does nothing if this is already the case. */ ensureMarks(marks) { if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks)) this.setStoredMarks(marks); return this; } /** Add a mark to the set of stored marks. */ addStoredMark(mark2) { return this.ensureMarks(mark2.addToSet(this.storedMarks || this.selection.$head.marks())); } /** Remove a mark or mark type from the set of stored marks. */ removeStoredMark(mark2) { return this.ensureMarks(mark2.removeFromSet(this.storedMarks || this.selection.$head.marks())); } /** Whether the stored marks were explicitly set for this transaction. */ get storedMarksSet() { return (this.updated & UPDATED_MARKS) > 0; } /** @internal */ addStep(step, doc4) { super.addStep(step, doc4); this.updated = this.updated & ~UPDATED_MARKS; this.storedMarks = null; } /** Update the timestamp for the transaction. */ setTime(time) { this.time = time; return this; } /** Replace the current selection with the given slice. */ replaceSelection(slice2) { this.selection.replace(this, slice2); return this; } /** Replace the selection with the given node. When `inheritMarks` is true and the content is inline, it inherits the marks from the place where it is inserted. */ replaceSelectionWith(node2, inheritMarks = true) { let selection = this.selection; if (inheritMarks) node2 = node2.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark.none)); selection.replaceWith(this, node2); return this; } /** Delete the selection. */ deleteSelection() { this.selection.replace(this); return this; } /** Replace the given range, or the selection if no range is given, with a text node containing the given string. */ insertText(text10, from4, to2) { let schema = this.doc.type.schema; if (from4 == null) { if (!text10) return this.deleteSelection(); return this.replaceSelectionWith(schema.text(text10), true); } else { if (to2 == null) to2 = from4; if (!text10) return this.deleteRange(from4, to2); let marks = this.storedMarks; if (!marks) { let $from = this.doc.resolve(from4); marks = to2 == from4 ? $from.marks() : $from.marksAcross(this.doc.resolve(to2)); } this.replaceRangeWith(from4, to2, schema.text(text10, marks)); if (!this.selection.empty && this.selection.to == from4 + text10.length) this.setSelection(Selection.near(this.selection.$to)); return this; } } /** Store a metadata property in this transaction, keyed either by name or by plugin. */ setMeta(key2, value) { this.meta[typeof key2 == "string" ? key2 : key2.key] = value; return this; } /** Retrieve a metadata property for a given name or plugin. */ getMeta(key2) { return this.meta[typeof key2 == "string" ? key2 : key2.key]; } /** Returns true if this transaction doesn't contain any metadata, and can thus safely be extended. */ get isGeneric() { for (let _2 in this.meta) return false; return true; } /** Indicate that the editor should scroll the selection into view when updated to the state produced by this transaction. */ scrollIntoView() { this.updated |= UPDATED_SCROLL; return this; } /** True when this transaction has had `scrollIntoView` called on it. */ get scrolledIntoView() { return (this.updated & UPDATED_SCROLL) > 0; } }; function bind(f6, self2) { return !self2 || !f6 ? f6 : f6.bind(self2); } var FieldDesc = class { constructor(name, desc, self2) { this.name = name; this.init = bind(desc.init, self2); this.apply = bind(desc.apply, self2); } }; var baseFields = [ new FieldDesc("doc", { init(config) { return config.doc || config.schema.topNodeType.createAndFill(); }, apply(tr4) { return tr4.doc; } }), new FieldDesc("selection", { init(config, instance) { return config.selection || Selection.atStart(instance.doc); }, apply(tr4) { return tr4.selection; } }), new FieldDesc("storedMarks", { init(config) { return config.storedMarks || null; }, apply(tr4, _marks, _old, state) { return state.selection.$cursor ? tr4.storedMarks : null; } }), new FieldDesc("scrollToSelection", { init() { return 0; }, apply(tr4, prev) { return tr4.scrolledIntoView ? prev + 1 : prev; } }) ]; var Configuration = class { constructor(schema, plugins) { this.schema = schema; this.plugins = []; this.pluginsByKey = /* @__PURE__ */ Object.create(null); this.fields = baseFields.slice(); if (plugins) plugins.forEach((plugin) => { if (this.pluginsByKey[plugin.key]) throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")"); this.plugins.push(plugin); this.pluginsByKey[plugin.key] = plugin; if (plugin.spec.state) this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin)); }); } }; var EditorState = class _EditorState { /** @internal */ constructor(config) { this.config = config; } /** The schema of the state's document. */ get schema() { return this.config.schema; } /** The plugins that are active in this state. */ get plugins() { return this.config.plugins; } /** Apply the given transaction to produce a new state. */ apply(tr4) { return this.applyTransaction(tr4).state; } /** @internal */ filterTransaction(tr4, ignore3 = -1) { for (let i3 = 0; i3 < this.config.plugins.length; i3++) if (i3 != ignore3) { let plugin = this.config.plugins[i3]; if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr4, this)) return false; } return true; } /** Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that returns the precise transactions that were applied (which might be influenced by the [transaction hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of plugins) along with the new state. */ applyTransaction(rootTr) { if (!this.filterTransaction(rootTr)) return { state: this, transactions: [] }; let trs = [rootTr], newState = this.applyInner(rootTr), seen = null; for (; ; ) { let haveNew = false; for (let i3 = 0; i3 < this.config.plugins.length; i3++) { let plugin = this.config.plugins[i3]; if (plugin.spec.appendTransaction) { let n = seen ? seen[i3].n : 0, oldState = seen ? seen[i3].state : this; let tr4 = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState); if (tr4 && newState.filterTransaction(tr4, i3)) { tr4.setMeta("appendedTransaction", rootTr); if (!seen) { seen = []; for (let j4 = 0; j4 < this.config.plugins.length; j4++) seen.push(j4 < i3 ? { state: newState, n: trs.length } : { state: this, n: 0 }); } trs.push(tr4); newState = newState.applyInner(tr4); haveNew = true; } if (seen) seen[i3] = { state: newState, n: trs.length }; } } if (!haveNew) return { state: newState, transactions: trs }; } } /** @internal */ applyInner(tr4) { if (!tr4.before.eq(this.doc)) throw new RangeError("Applying a mismatched transaction"); let newInstance = new _EditorState(this.config), fields = this.config.fields; for (let i3 = 0; i3 < fields.length; i3++) { let field = fields[i3]; newInstance[field.name] = field.apply(tr4, this[field.name], this, newInstance); } return newInstance; } /** Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state. */ get tr() { return new Transaction(this); } /** Create a new state. */ static create(config) { let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins); let instance = new _EditorState($config); for (let i3 = 0; i3 < $config.fields.length; i3++) instance[$config.fields[i3].name] = $config.fields[i3].init(config, instance); return instance; } /** Create a new state based on this one, but with an adjusted set of active plugins. State fields that exist in both sets of plugins are kept unchanged. Those that no longer exist are dropped, and those that are new are initialized using their [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new configuration object.. */ reconfigure(config) { let $config = new Configuration(this.schema, config.plugins); let fields = $config.fields, instance = new _EditorState($config); for (let i3 = 0; i3 < fields.length; i3++) { let name = fields[i3].name; instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i3].init(config, instance); } return instance; } /** Serialize this state to JSON. If you want to serialize the state of plugins, pass an object mapping property names to use in the resulting JSON object to plugin objects. The argument may also be a string or number, in which case it is ignored, to support the way `JSON.stringify` calls `toString` methods. */ toJSON(pluginFields) { let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() }; if (this.storedMarks) result.storedMarks = this.storedMarks.map((m2) => m2.toJSON()); if (pluginFields && typeof pluginFields == "object") for (let prop in pluginFields) { if (prop == "doc" || prop == "selection") throw new RangeError("The JSON fields `doc` and `selection` are reserved"); let plugin = pluginFields[prop], state = plugin.spec.state; if (state && state.toJSON) result[prop] = state.toJSON.call(plugin, this[plugin.key]); } return result; } /** Deserialize a JSON representation of a state. `config` should have at least a `schema` field, and should contain array of plugins to initialize the state with. `pluginFields` can be used to deserialize the state of plugins, by associating plugin instances with the property names they use in the JSON object. */ static fromJSON(config, json, pluginFields) { if (!json) throw new RangeError("Invalid input for EditorState.fromJSON"); if (!config.schema) throw new RangeError("Required config field 'schema' missing"); let $config = new Configuration(config.schema, config.plugins); let instance = new _EditorState($config); $config.fields.forEach((field) => { if (field.name == "doc") { instance.doc = Node2.fromJSON(config.schema, json.doc); } else if (field.name == "selection") { instance.selection = Selection.fromJSON(instance.doc, json.selection); } else if (field.name == "storedMarks") { if (json.storedMarks) instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON); } else { if (pluginFields) for (let prop in pluginFields) { let plugin = pluginFields[prop], state = plugin.spec.state; if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop)) { instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance); return; } } instance[field.name] = field.init(config, instance); } }); return instance; } }; function bindProps(obj, self2, target) { for (let prop in obj) { let val = obj[prop]; if (val instanceof Function) val = val.bind(self2); else if (prop == "handleDOMEvents") val = bindProps(val, self2, {}); target[prop] = val; } return target; } var Plugin = class { /** 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]; } }; var keys = /* @__PURE__ */ Object.create(null); function createKey(name) { if (name in keys) return name + "$" + ++keys[name]; keys[name] = 0; return name + "$"; } var PluginKey = class { /** 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]; } }; // ../../node_modules/.pnpm/prosemirror-view@1.41.4/node_modules/prosemirror-view/dist/index.js var domIndex = function(node2) { for (var index4 = 0; ; index4++) { node2 = node2.previousSibling; if (!node2) return index4; } }; var parentNode = function(node2) { let parent = node2.assignedSlot || node2.parentNode; return parent && parent.nodeType == 11 ? parent.host : parent; }; var reusedRange = null; var textRange = function(node2, from4, to2) { let range = reusedRange || (reusedRange = document.createRange()); range.setEnd(node2, to2 == null ? node2.nodeValue.length : to2); range.setStart(node2, from4 || 0); return range; }; var clearReusedRange = function() { reusedRange = null; }; var isEquivalentPosition = function(node2, off, targetNode, targetOff) { return targetNode && (scanFor(node2, off, targetNode, targetOff, -1) || scanFor(node2, off, targetNode, targetOff, 1)); }; var atomElements = /^(img|br|input|textarea|hr)$/i; function scanFor(node2, off, targetNode, targetOff, dir) { var _a2; for (; ; ) { if (node2 == targetNode && off == targetOff) return true; if (off == (dir < 0 ? 0 : nodeSize(node2))) { let parent = node2.parentNode; if (!parent || parent.nodeType != 1 || hasBlockDesc(node2) || atomElements.test(node2.nodeName) || node2.contentEditable == "false") return false; off = domIndex(node2) + (dir < 0 ? 0 : 1); node2 = parent; } else if (node2.nodeType == 1) { let child = node2.childNodes[off + (dir < 0 ? -1 : 0)]; if (child.nodeType == 1 && child.contentEditable == "false") { if ((_a2 = child.pmViewDesc) === null || _a2 === void 0 ? void 0 : _a2.ignoreForSelection) off += dir; else return false; } else { node2 = child; off = dir < 0 ? nodeSize(node2) : 0; } } else { return false; } } } function nodeSize(node2) { return node2.nodeType == 3 ? node2.nodeValue.length : node2.childNodes.length; } function textNodeBefore$1(node2, offset4) { for (; ; ) { if (node2.nodeType == 3 && offset4) return node2; if (node2.nodeType == 1 && offset4 > 0) { if (node2.contentEditable == "false") return null; node2 = node2.childNodes[offset4 - 1]; offset4 = nodeSize(node2); } else if (node2.parentNode && !hasBlockDesc(node2)) { offset4 = domIndex(node2); node2 = node2.parentNode; } else { return null; } } } function textNodeAfter$1(node2, offset4) { for (; ; ) { if (node2.nodeType == 3 && offset4 < node2.nodeValue.length) return node2; if (node2.nodeType == 1 && offset4 < node2.childNodes.length) { if (node2.contentEditable == "false") return null; node2 = node2.childNodes[offset4]; offset4 = 0; } else if (node2.parentNode && !hasBlockDesc(node2)) { offset4 = domIndex(node2) + 1; node2 = node2.parentNode; } else { return null; } } } function isOnEdge(node2, offset4, parent) { for (let atStart = offset4 == 0, atEnd = offset4 == nodeSize(node2); atStart || atEnd; ) { if (node2 == parent) return true; let index4 = domIndex(node2); node2 = node2.parentNode; if (!node2) return false; atStart = atStart && index4 == 0; atEnd = atEnd && index4 == nodeSize(node2); } } 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); } var selectionCollapsed = function(domSel) { return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset); }; function keyEvent(keyCode, key2) { let event = document.createEvent("Event"); event.initEvent("keydown", true, true); event.keyCode = keyCode; event.key = event.code = key2; return event; } function deepActiveElement(doc4) { let elt = doc4.activeElement; while (elt && elt.shadowRoot) elt = elt.shadowRoot.activeElement; return elt; } function caretFromPoint(doc4, x5, y3) { if (doc4.caretPositionFromPoint) { try { let pos = doc4.caretPositionFromPoint(x5, y3); if (pos) return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) }; } catch (_2) { } } if (doc4.caretRangeFromPoint) { let range = doc4.caretRangeFromPoint(x5, y3); if (range) return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) }; } } var nav = typeof navigator != "undefined" ? navigator : null; var doc2 = typeof document != "undefined" ? document : null; var agent = nav && nav.userAgent || ""; var ie_edge = /Edge\/(\d+)/.exec(agent); var ie_upto10 = /MSIE \d/.exec(agent); var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent); var ie = !!(ie_upto10 || ie_11up || ie_edge); var ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0; var gecko = !ie && /gecko\/(\d+)/i.test(agent); gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1]; var _chrome = !ie && /Chrome\/(\d+)/.exec(agent); var chrome = !!_chrome; var chrome_version = _chrome ? +_chrome[1] : 0; var safari = !ie && !!nav && /Apple Computer/.test(nav.vendor); var ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2); var mac = ios || (nav ? /Mac/.test(nav.platform) : false); var windows = nav ? /Win/.test(nav.platform) : false; var android = /Android \d/.test(agent); var webkit = !!doc2 && "webkitFontSmoothing" in doc2.documentElement.style; var webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0; function windowRect(doc4) { let vp = doc4.defaultView && doc4.defaultView.visualViewport; if (vp) return { left: 0, right: vp.width, top: 0, bottom: vp.height }; return { left: 0, right: doc4.documentElement.clientWidth, top: 0, bottom: doc4.documentElement.clientHeight }; } function getSide(value, side) { return typeof value == "number" ? value : value[side]; } function clientRect(node2) { let rect = node2.getBoundingClientRect(); let scaleX = rect.width / node2.offsetWidth || 1; let scaleY = rect.height / node2.offsetHeight || 1; return { left: rect.left, right: rect.left + node2.clientWidth * scaleX, top: rect.top, bottom: rect.top + node2.clientHeight * scaleY }; } function scrollRectIntoView(view, rect, startDOM) { let scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5; let doc4 = view.dom.ownerDocument; for (let parent = startDOM || view.dom; ; ) { if (!parent) break; if (parent.nodeType != 1) { parent = parentNode(parent); continue; } let elt = parent; let atTop = elt == doc4.body; let bounding = atTop ? windowRect(doc4) : clientRect(elt); let moveX = 0, moveY = 0; if (rect.top < bounding.top + getSide(scrollThreshold, "top")) moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top")); else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom")) moveY = rect.bottom - rect.top > bounding.bottom - bounding.top ? rect.top + getSide(scrollMargin, "top") - bounding.top : rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom"); if (rect.left < bounding.left + getSide(scrollThreshold, "left")) moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left")); else if (rect.right > bounding.right - getSide(scrollThreshold, "right")) moveX = rect.right - bounding.right + getSide(scrollMargin, "right"); if (moveX || moveY) { if (atTop) { doc4.defaultView.scrollBy(moveX, moveY); } else { let startX = elt.scrollLeft, startY = elt.scrollTop; if (moveY) elt.scrollTop += moveY; if (moveX) elt.scrollLeft += moveX; let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY; rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY }; } } let pos = atTop ? "fixed" : getComputedStyle(parent).position; if (/^(fixed|sticky)$/.test(pos)) break; parent = pos == "absolute" ? parent.offsetParent : parentNode(parent); } } function storeScrollPos(view) { let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top); let refDOM, refTop; for (let x5 = (rect.left + rect.right) / 2, y3 = startY + 1; y3 < Math.min(innerHeight, rect.bottom); y3 += 5) { let dom = view.root.elementFromPoint(x5, y3); if (!dom || dom == view.dom || !view.dom.contains(dom)) continue; let localRect = dom.getBoundingClientRect(); if (localRect.top >= startY - 20) { refDOM = dom; refTop = localRect.top; break; } } return { refDOM, refTop, stack: scrollStack(view.dom) }; } function scrollStack(dom) { let stack = [], doc4 = dom.ownerDocument; for (let cur = dom; cur; cur = parentNode(cur)) { stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft }); if (dom == doc4) break; } return stack; } function resetScrollPos({ refDOM, refTop, stack }) { let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0; restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop); } function restoreScrollStack(stack, dTop) { for (let i3 = 0; i3 < stack.length; i3++) { let { dom, top, left } = stack[i3]; if (dom.scrollTop != top + dTop) dom.scrollTop = top + dTop; if (dom.scrollLeft != left) dom.scrollLeft = left; } } var preventScrollSupported = null; function focusPreventScroll(dom) { if (dom.setActive) return dom.setActive(); if (preventScrollSupported) return dom.focus(preventScrollSupported); let stored = scrollStack(dom); dom.focus(preventScrollSupported == null ? { get preventScroll() { preventScrollSupported = { preventScroll: true }; return true; } } : void 0); if (!preventScrollSupported) { preventScrollSupported = false; restoreScrollStack(stored, 0); } } function findOffsetInNode(node2, coords) { let closest, dxClosest = 2e8, coordsClosest, offset4 = 0; let rowBot = coords.top, rowTop = coords.top; let firstBelow, coordsBelow; for (let child = node2.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) { let rects; if (child.nodeType == 1) rects = child.getClientRects(); else if (child.nodeType == 3) rects = textRange(child).getClientRects(); else continue; for (let i3 = 0; i3 < rects.length; i3++) { let rect = rects[i3]; if (rect.top <= rowBot && rect.bottom >= rowTop) { rowBot = Math.max(rect.bottom, rowBot); rowTop = Math.min(rect.top, rowTop); let dx = rect.left > coords.left ? rect.left - coords.left : rect.right < coords.left ? coords.left - rect.right : 0; if (dx < dxClosest) { closest = child; dxClosest = dx; coordsClosest = dx && closest.nodeType == 3 ? { left: rect.right < coords.left ? rect.right : rect.left, top: coords.top } : coords; if (child.nodeType == 1 && dx) offset4 = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0); continue; } } else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) { firstBelow = child; coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top }; } if (!closest && (coords.left >= rect.right && coords.top >= rect.top || coords.left >= rect.left && coords.top >= rect.bottom)) offset4 = childIndex + 1; } } if (!closest && firstBelow) { closest = firstBelow; coordsClosest = coordsBelow; dxClosest = 0; } if (closest && closest.nodeType == 3) return findOffsetInText(closest, coordsClosest); if (!closest || dxClosest && closest.nodeType == 1) return { node: node2, offset: offset4 }; return findOffsetInNode(closest, coordsClosest); } function findOffsetInText(node2, coords) { let len = node2.nodeValue.length; let range = document.createRange(), result; for (let i3 = 0; i3 < len; i3++) { range.setEnd(node2, i3 + 1); range.setStart(node2, i3); let rect = singleRect(range, 1); if (rect.top == rect.bottom) continue; if (inRect(coords, rect)) { result = { node: node2, offset: i3 + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) }; break; } } range.detach(); return result || { node: node2, offset: 0 }; } function inRect(coords, rect) { return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 && coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1; } function targetKludge(dom, coords) { let parent = dom.parentNode; if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left) return parent; return dom; } function posFromElement(view, elt, coords) { let { node: node2, offset: offset4 } = findOffsetInNode(elt, coords), bias = -1; if (node2.nodeType == 1 && !node2.firstChild) { let rect = node2.getBoundingClientRect(); bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1; } return view.docView.posFromDOM(node2, offset4, bias); } function posFromCaret(view, node2, offset4, coords) { let outsideBlock = -1; for (let cur = node2, sawBlock = false; ; ) { if (cur == view.dom) break; let desc = view.docView.nearestDesc(cur, true), rect; if (!desc) return null; if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) && // Ignore elements with zero-size bounding rectangles ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) { if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) { if (!sawBlock && rect.left > coords.left || rect.top > coords.top) outsideBlock = desc.posBefore; else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top) outsideBlock = desc.posAfter; sawBlock = true; } if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) { let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2 : coords.left < (rect.left + rect.right) / 2; return before ? desc.posBefore : desc.posAfter; } } cur = desc.dom.parentNode; } return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node2, offset4, -1); } function elementFromPoint(element7, coords, box) { let len = element7.childNodes.length; if (len && box.top < box.bottom) { for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i3 = startI; ; ) { let child = element7.childNodes[i3]; if (child.nodeType == 1) { let rects = child.getClientRects(); for (let j4 = 0; j4 < rects.length; j4++) { let rect = rects[j4]; if (inRect(coords, rect)) return elementFromPoint(child, coords, rect); } } if ((i3 = (i3 + 1) % len) == startI) break; } } return element7; } function posAtCoords(view, coords) { let doc4 = view.dom.ownerDocument, node2, offset4 = 0; let caret = caretFromPoint(doc4, coords.left, coords.top); if (caret) ({ node: node2, offset: offset4 } = caret); let elt = (view.root.elementFromPoint ? view.root : doc4).elementFromPoint(coords.left, coords.top); let pos; if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) { let box = view.dom.getBoundingClientRect(); if (!inRect(coords, box)) return null; elt = elementFromPoint(view.dom, coords, box); if (!elt) return null; } if (safari) { for (let p4 = elt; node2 && p4; p4 = parentNode(p4)) if (p4.draggable) node2 = void 0; } elt = targetKludge(elt, coords); if (node2) { if (gecko && node2.nodeType == 1) { offset4 = Math.min(offset4, node2.childNodes.length); if (offset4 < node2.childNodes.length) { let next2 = node2.childNodes[offset4], box; if (next2.nodeName == "IMG" && (box = next2.getBoundingClientRect()).right <= coords.left && box.bottom > coords.top) offset4++; } } let prev; if (webkit && offset4 && node2.nodeType == 1 && (prev = node2.childNodes[offset4 - 1]).nodeType == 1 && prev.contentEditable == "false" && prev.getBoundingClientRect().top >= coords.top) offset4--; if (node2 == view.dom && offset4 == node2.childNodes.length - 1 && node2.lastChild.nodeType == 1 && coords.top > node2.lastChild.getBoundingClientRect().bottom) pos = view.state.doc.content.size; else if (offset4 == 0 || node2.nodeType != 1 || node2.childNodes[offset4 - 1].nodeName != "BR") pos = posFromCaret(view, node2, offset4, coords); } if (pos == null) pos = posFromElement(view, elt, coords); let desc = view.docView.nearestDesc(elt, true); return { pos, inside: desc ? desc.posAtStart - desc.border : -1 }; } function nonZero(rect) { return rect.top < rect.bottom || rect.left < rect.right; } function singleRect(target, bias) { let rects = target.getClientRects(); if (rects.length) { let first2 = rects[bias < 0 ? 0 : rects.length - 1]; if (nonZero(first2)) return first2; } return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect(); } var BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; function coordsAtPos(view, pos, side) { let { node: node2, offset: offset4, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1); let supportEmptyRange = webkit || gecko; if (node2.nodeType == 3) { if (supportEmptyRange && (BIDI.test(node2.nodeValue) || (side < 0 ? !offset4 : offset4 == node2.nodeValue.length))) { let rect = singleRect(textRange(node2, offset4, offset4), side); if (gecko && offset4 && /\s/.test(node2.nodeValue[offset4 - 1]) && offset4 < node2.nodeValue.length) { let rectBefore = singleRect(textRange(node2, offset4 - 1, offset4 - 1), -1); if (rectBefore.top == rect.top) { let rectAfter = singleRect(textRange(node2, offset4, offset4 + 1), -1); if (rectAfter.top != rect.top) return flattenV(rectAfter, rectAfter.left < rectBefore.left); } } return rect; } else { let from4 = offset4, to2 = offset4, takeSide = side < 0 ? 1 : -1; if (side < 0 && !offset4) { to2++; takeSide = -1; } else if (side >= 0 && offset4 == node2.nodeValue.length) { from4--; takeSide = 1; } else if (side < 0) { from4--; } else { to2++; } return flattenV(singleRect(textRange(node2, from4, to2), takeSide), takeSide < 0); } } let $dom = view.state.doc.resolve(pos - (atom || 0)); if (!$dom.parent.inlineContent) { if (atom == null && offset4 && (side < 0 || offset4 == nodeSize(node2))) { let before = node2.childNodes[offset4 - 1]; if (before.nodeType == 1) return flattenH(before.getBoundingClientRect(), false); } if (atom == null && offset4 < nodeSize(node2)) { let after = node2.childNodes[offset4]; if (after.nodeType == 1) return flattenH(after.getBoundingClientRect(), true); } return flattenH(node2.getBoundingClientRect(), side >= 0); } if (atom == null && offset4 && (side < 0 || offset4 == nodeSize(node2))) { let before = node2.childNodes[offset4 - 1]; let target = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1)) : before.nodeType == 1 && (before.nodeName != "BR" || !before.nextSibling) ? before : null; if (target) return flattenV(singleRect(target, 1), false); } if (atom == null && offset4 < nodeSize(node2)) { let after = node2.childNodes[offset4]; while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords) after = after.nextSibling; let target = !after ? null : after.nodeType == 3 ? textRange(after, 0, supportEmptyRange ? 0 : 1) : after.nodeType == 1 ? after : null; if (target) return flattenV(singleRect(target, -1), true); } return flattenV(singleRect(node2.nodeType == 3 ? textRange(node2) : node2, -side), side >= 0); } function flattenV(rect, left) { if (rect.width == 0) return rect; let x5 = left ? rect.left : rect.right; return { top: rect.top, bottom: rect.bottom, left: x5, right: x5 }; } function flattenH(rect, top) { if (rect.height == 0) return rect; let y3 = top ? rect.top : rect.bottom; return { top: y3, bottom: y3, left: rect.left, right: rect.right }; } function withFlushedState(view, state, f6) { let viewState = view.state, active = view.root.activeElement; if (viewState != state) view.updateState(state); if (active != view.dom) view.focus(); try { return f6(); } finally { if (viewState != state) view.updateState(viewState); if (active != view.dom && active) active.focus(); } } function endOfTextblockVertical(view, state, dir) { let sel = state.selection; let $pos = dir == "up" ? sel.$from : sel.$to; return withFlushedState(view, state, () => { let { node: dom } = view.docView.domFromPos($pos.pos, dir == "up" ? -1 : 1); for (; ; ) { let nearest = view.docView.nearestDesc(dom, true); if (!nearest) break; if (nearest.node.isBlock) { dom = nearest.contentDOM || nearest.dom; break; } dom = nearest.dom.parentNode; } let coords = coordsAtPos(view, $pos.pos, 1); for (let child = dom.firstChild; child; child = child.nextSibling) { let boxes; if (child.nodeType == 1) boxes = child.getClientRects(); else if (child.nodeType == 3) boxes = textRange(child, 0, child.nodeValue.length).getClientRects(); else continue; for (let i3 = 0; i3 < boxes.length; i3++) { let box = boxes[i3]; if (box.bottom > box.top + 1 && (dir == "up" ? coords.top - box.top > (box.bottom - coords.top) * 2 : box.bottom - coords.bottom > (coords.bottom - box.top) * 2)) return false; } } return true; }); } var maybeRTL = /[\u0590-\u08ac]/; function endOfTextblockHorizontal(view, state, dir) { let { $head } = state.selection; if (!$head.parent.isTextblock) return false; let offset4 = $head.parentOffset, atStart = !offset4, atEnd = offset4 == $head.parent.content.size; let sel = view.domSelection(); if (!sel) return $head.pos == $head.start() || $head.pos == $head.end(); if (!maybeRTL.test($head.parent.textContent) || !sel.modify) return dir == "left" || dir == "backward" ? atStart : atEnd; return withFlushedState(view, state, () => { let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange(); let oldBidiLevel = sel.caretBidiLevel; sel.modify("move", dir, "character"); let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom; let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange(); let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) || oldNode == newNode && oldOff == newOff; try { sel.collapse(anchorNode, anchorOffset); if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend) sel.extend(oldNode, oldOff); } catch (_2) { } if (oldBidiLevel != null) sel.caretBidiLevel = oldBidiLevel; return result; }); } var cachedState = null; var cachedDir = null; var cachedResult = false; function endOfTextblock(view, state, dir) { if (cachedState == state && cachedDir == dir) return cachedResult; cachedState = state; cachedDir = dir; return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir); } var NOT_DIRTY = 0; var CHILD_DIRTY = 1; var CONTENT_DIRTY = 2; var NODE_DIRTY = 3; var ViewDesc = class { constructor(parent, children, dom, contentDOM) { this.parent = parent; this.children = children; this.dom = dom; this.contentDOM = contentDOM; this.dirty = NOT_DIRTY; dom.pmViewDesc = this; } // Used to check whether a given description corresponds to a // widget/mark/node. matchesWidget(widget) { return false; } matchesMark(mark2) { return false; } matchesNode(node2, outerDeco, innerDeco) { return false; } matchesHack(nodeName) { return false; } // When parsing in-editor content (in domchange.js), we allow // descriptions to determine the parse rules that should be used to // parse them. parseRule() { return null; } // Used by the editor's event handler to ignore events that come // from certain descs. stopEvent(event) { return false; } // The size of the content represented by this desc. get size() { let size5 = 0; for (let i3 = 0; i3 < this.children.length; i3++) size5 += this.children[i3].size; return size5; } // For block nodes, this represents the space taken up by their // start/end tokens. get border() { return 0; } destroy() { this.parent = void 0; if (this.dom.pmViewDesc == this) this.dom.pmViewDesc = void 0; for (let i3 = 0; i3 < this.children.length; i3++) this.children[i3].destroy(); } posBeforeChild(child) { for (let i3 = 0, pos = this.posAtStart; ; i3++) { let cur = this.children[i3]; if (cur == child) return pos; pos += cur.size; } } get posBefore() { return this.parent.posBeforeChild(this); } get posAtStart() { return this.parent ? this.parent.posBeforeChild(this) + this.border : 0; } get posAfter() { return this.posBefore + this.size; } get posAtEnd() { return this.posAtStart + this.size - 2 * this.border; } localPosFromDOM(dom, offset4, bias) { if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) { if (bias < 0) { let domBefore, desc; if (dom == this.contentDOM) { domBefore = dom.childNodes[offset4 - 1]; } else { while (dom.parentNode != this.contentDOM) dom = dom.parentNode; domBefore = dom.previousSibling; } while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) domBefore = domBefore.previousSibling; return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart; } else { let domAfter, desc; if (dom == this.contentDOM) { domAfter = dom.childNodes[offset4]; } else { while (dom.parentNode != this.contentDOM) dom = dom.parentNode; domAfter = dom.nextSibling; } while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this)) domAfter = domAfter.nextSibling; return domAfter ? this.posBeforeChild(desc) : this.posAtEnd; } } let atEnd; if (dom == this.dom && this.contentDOM) { atEnd = offset4 > domIndex(this.contentDOM); } else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) { atEnd = dom.compareDocumentPosition(this.contentDOM) & 2; } else if (this.dom.firstChild) { if (offset4 == 0) for (let search3 = dom; ; search3 = search3.parentNode) { if (search3 == this.dom) { atEnd = false; break; } if (search3.previousSibling) break; } if (atEnd == null && offset4 == dom.childNodes.length) for (let search3 = dom; ; search3 = search3.parentNode) { if (search3 == this.dom) { atEnd = true; break; } if (search3.nextSibling) break; } } return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart; } nearestDesc(dom, onlyNodes = false) { for (let first2 = true, cur = dom; cur; cur = cur.parentNode) { let desc = this.getDesc(cur), nodeDOM; if (desc && (!onlyNodes || desc.node)) { if (first2 && (nodeDOM = desc.nodeDOM) && !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom)) first2 = false; else return desc; } } } getDesc(dom) { let desc = dom.pmViewDesc; for (let cur = desc; cur; cur = cur.parent) if (cur == this) return desc; } posFromDOM(dom, offset4, bias) { for (let scan = dom; scan; scan = scan.parentNode) { let desc = this.getDesc(scan); if (desc) return desc.localPosFromDOM(dom, offset4, bias); } return -1; } // Find the desc for the node after the given pos, if any. (When a // parent node overrode rendering, there might not be one.) descAt(pos) { for (let i3 = 0, offset4 = 0; i3 < this.children.length; i3++) { let child = this.children[i3], end = offset4 + child.size; if (offset4 == pos && end != offset4) { while (!child.border && child.children.length) { for (let i4 = 0; i4 < child.children.length; i4++) { let inner = child.children[i4]; if (inner.size) { child = inner; break; } } } return child; } if (pos < end) return child.descAt(pos - offset4 - child.border); offset4 = end; } } domFromPos(pos, side) { if (!this.contentDOM) return { node: this.dom, offset: 0, atom: pos + 1 }; let i3 = 0, offset4 = 0; for (let curPos = 0; i3 < this.children.length; i3++) { let child = this.children[i3], end = curPos + child.size; if (end > pos || child instanceof TrailingHackViewDesc) { offset4 = pos - curPos; break; } curPos = end; } if (offset4) return this.children[i3].domFromPos(offset4 - this.children[i3].border, side); for (let prev; i3 && !(prev = this.children[i3 - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i3--) { } if (side <= 0) { let prev, enter2 = true; for (; ; i3--, enter2 = false) { prev = i3 ? this.children[i3 - 1] : null; if (!prev || prev.dom.parentNode == this.contentDOM) break; } if (prev && side && enter2 && !prev.border && !prev.domAtom) return prev.domFromPos(prev.size, side); return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 }; } else { let next2, enter2 = true; for (; ; i3++, enter2 = false) { next2 = i3 < this.children.length ? this.children[i3] : null; if (!next2 || next2.dom.parentNode == this.contentDOM) break; } if (next2 && enter2 && !next2.border && !next2.domAtom) return next2.domFromPos(0, side); return { node: this.contentDOM, offset: next2 ? domIndex(next2.dom) : this.contentDOM.childNodes.length }; } } // Used to find a DOM range in a single parent for a given changed // range. parseRange(from4, to2, base4 = 0) { if (this.children.length == 0) return { node: this.contentDOM, from: from4, to: to2, fromOffset: 0, toOffset: this.contentDOM.childNodes.length }; let fromOffset = -1, toOffset = -1; for (let offset4 = base4, i3 = 0; ; i3++) { let child = this.children[i3], end = offset4 + child.size; if (fromOffset == -1 && from4 <= end) { let childBase = offset4 + child.border; if (from4 >= childBase && to2 <= end - child.border && child.node && child.contentDOM && this.contentDOM.contains(child.contentDOM)) return child.parseRange(from4, to2, childBase); from4 = offset4; for (let j4 = i3; j4 > 0; j4--) { let prev = this.children[j4 - 1]; if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) { fromOffset = domIndex(prev.dom) + 1; break; } from4 -= prev.size; } if (fromOffset == -1) fromOffset = 0; } if (fromOffset > -1 && (end > to2 || i3 == this.children.length - 1)) { to2 = end; for (let j4 = i3 + 1; j4 < this.children.length; j4++) { let next2 = this.children[j4]; if (next2.size && next2.dom.parentNode == this.contentDOM && !next2.emptyChildAt(-1)) { toOffset = domIndex(next2.dom); break; } to2 += next2.size; } if (toOffset == -1) toOffset = this.contentDOM.childNodes.length; break; } offset4 = end; } return { node: this.contentDOM, from: from4, to: to2, fromOffset, toOffset }; } emptyChildAt(side) { if (this.border || !this.contentDOM || !this.children.length) return false; let child = this.children[side < 0 ? 0 : this.children.length - 1]; return child.size == 0 || child.emptyChildAt(side); } domAfterPos(pos) { let { node: node2, offset: offset4 } = this.domFromPos(pos, 0); if (node2.nodeType != 1 || offset4 == node2.childNodes.length) throw new RangeError("No node after pos " + pos); return node2.childNodes[offset4]; } // View descs are responsible for setting any selection that falls // entirely inside of them, so that custom implementations can do // custom things with the selection. Note that this falls apart when // a selection starts in such a node and ends in another, in which // case we just use whatever domFromPos produces as a best effort. setSelection(anchor, head2, view, force = false) { let from4 = Math.min(anchor, head2), to2 = Math.max(anchor, head2); for (let i3 = 0, offset4 = 0; i3 < this.children.length; i3++) { let child = this.children[i3], end = offset4 + child.size; if (from4 > offset4 && to2 < end) return child.setSelection(anchor - offset4 - child.border, head2 - offset4 - child.border, view, force); offset4 = end; } let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1); let headDOM = head2 == anchor ? anchorDOM : this.domFromPos(head2, head2 ? -1 : 1); let domSel = view.root.getSelection(); let selRange = view.domSelectionRange(); let brKludge = false; if ((gecko || safari) && anchor == head2) { let { node: node2, offset: offset4 } = anchorDOM; if (node2.nodeType == 3) { brKludge = !!(offset4 && node2.nodeValue[offset4 - 1] == "\n"); if (brKludge && offset4 == node2.nodeValue.length) { for (let scan = node2, after; scan; scan = scan.parentNode) { if (after = scan.nextSibling) { if (after.nodeName == "BR") anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 }; break; } let desc = scan.pmViewDesc; if (desc && desc.node && desc.node.isBlock) break; } } } else { let prev = node2.childNodes[offset4 - 1]; brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false"); } } if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) { let after = selRange.focusNode.childNodes[selRange.focusOffset]; if (after && after.contentEditable == "false") force = true; } if (!(force || brKludge && safari) && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset)) return; let domSelExtended = false; if ((domSel.extend || anchor == head2) && !(brKludge && gecko)) { domSel.collapse(anchorDOM.node, anchorDOM.offset); try { if (anchor != head2) domSel.extend(headDOM.node, headDOM.offset); domSelExtended = true; } catch (_2) { } } if (!domSelExtended) { if (anchor > head2) { let tmp = anchorDOM; anchorDOM = headDOM; headDOM = tmp; } let range = document.createRange(); range.setEnd(headDOM.node, headDOM.offset); range.setStart(anchorDOM.node, anchorDOM.offset); domSel.removeAllRanges(); domSel.addRange(range); } } ignoreMutation(mutation) { return !this.contentDOM && mutation.type != "selection"; } get contentLost() { return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM); } // Remove a subtree of the element tree that has been touched // by a DOM change, so that the next update will redraw it. markDirty(from4, to2) { for (let offset4 = 0, i3 = 0; i3 < this.children.length; i3++) { let child = this.children[i3], end = offset4 + child.size; if (offset4 == end ? from4 <= end && to2 >= offset4 : from4 < end && to2 > offset4) { let startInside = offset4 + child.border, endInside = end - child.border; if (from4 >= startInside && to2 <= endInside) { this.dirty = from4 == offset4 || to2 == end ? CONTENT_DIRTY : CHILD_DIRTY; if (from4 == startInside && to2 == endInside && (child.contentLost || child.dom.parentNode != this.contentDOM)) child.dirty = NODE_DIRTY; else child.markDirty(from4 - startInside, to2 - startInside); return; } else { child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length ? CONTENT_DIRTY : NODE_DIRTY; } } offset4 = end; } this.dirty = CONTENT_DIRTY; } markParentsDirty() { let level = 1; for (let node2 = this.parent; node2; node2 = node2.parent, level++) { let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY; if (node2.dirty < dirty) node2.dirty = dirty; } } get domAtom() { return false; } get ignoreForCoords() { return false; } get ignoreForSelection() { return false; } isText(text10) { return false; } }; var WidgetViewDesc = class extends ViewDesc { constructor(parent, widget, view, pos) { let self2, dom = widget.type.toDOM; if (typeof dom == "function") dom = dom(view, () => { if (!self2) return pos; if (self2.parent) return self2.parent.posBeforeChild(self2); }); if (!widget.type.spec.raw) { if (dom.nodeType != 1) { let wrap5 = document.createElement("span"); wrap5.appendChild(dom); dom = wrap5; } dom.contentEditable = "false"; dom.classList.add("ProseMirror-widget"); } super(parent, [], dom, null); this.widget = widget; this.widget = widget; self2 = this; } matchesWidget(widget) { return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type); } parseRule() { return { ignore: true }; } stopEvent(event) { let stop = this.widget.spec.stopEvent; return stop ? stop(event) : false; } ignoreMutation(mutation) { return mutation.type != "selection" || this.widget.spec.ignoreSelection; } destroy() { this.widget.type.destroy(this.dom); super.destroy(); } get domAtom() { return true; } get ignoreForSelection() { return !!this.widget.type.spec.relaxedSide; } get side() { return this.widget.type.side; } }; var CompositionViewDesc = class extends ViewDesc { constructor(parent, dom, textDOM, text10) { super(parent, [], dom, null); this.textDOM = textDOM; this.text = text10; } get size() { return this.text.length; } localPosFromDOM(dom, offset4) { if (dom != this.textDOM) return this.posAtStart + (offset4 ? this.size : 0); return this.posAtStart + offset4; } domFromPos(pos) { return { node: this.textDOM, offset: pos }; } ignoreMutation(mut) { return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue; } }; var MarkViewDesc = class _MarkViewDesc extends ViewDesc { constructor(parent, mark2, dom, contentDOM, spec) { super(parent, [], dom, contentDOM); this.mark = mark2; this.spec = spec; } static create(parent, mark2, inline4, view) { let custom = view.nodeViews[mark2.type.name]; let spec = custom && custom(mark2, view, inline4); if (!spec || !spec.dom) spec = DOMSerializer.renderSpec(document, mark2.type.spec.toDOM(mark2, inline4), null, mark2.attrs); return new _MarkViewDesc(parent, mark2, spec.dom, spec.contentDOM || spec.dom, spec); } parseRule() { if (this.dirty & NODE_DIRTY || this.mark.type.spec.reparseInView) return null; return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM }; } matchesMark(mark2) { return this.dirty != NODE_DIRTY && this.mark.eq(mark2); } markDirty(from4, to2) { super.markDirty(from4, to2); if (this.dirty != NOT_DIRTY) { let parent = this.parent; while (!parent.node) parent = parent.parent; if (parent.dirty < this.dirty) parent.dirty = this.dirty; this.dirty = NOT_DIRTY; } } slice(from4, to2, view) { let copy3 = _MarkViewDesc.create(this.parent, this.mark, true, view); let nodes = this.children, size5 = this.size; if (to2 < size5) nodes = replaceNodes(nodes, to2, size5, view); if (from4 > 0) nodes = replaceNodes(nodes, 0, from4, view); for (let i3 = 0; i3 < nodes.length; i3++) nodes[i3].parent = copy3; copy3.children = nodes; return copy3; } ignoreMutation(mutation) { return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation); } destroy() { if (this.spec.destroy) this.spec.destroy(); super.destroy(); } }; var NodeViewDesc = class _NodeViewDesc extends ViewDesc { constructor(parent, node2, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) { super(parent, [], dom, contentDOM); this.node = node2; this.outerDeco = outerDeco; this.innerDeco = innerDeco; this.nodeDOM = nodeDOM; } // By default, a node is rendered using the `toDOM` method from the // node type spec. But client code can use the `nodeViews` spec to // supply a custom node view, which can influence various aspects of // the way the node works. // // (Using subclassing for this was intentionally decided against, // since it'd require exposing a whole slew of finicky // implementation details to the user code that they probably will // never need.) static create(parent, node2, outerDeco, innerDeco, view, pos) { let custom = view.nodeViews[node2.type.name], descObj; let spec = custom && custom(node2, view, () => { if (!descObj) return pos; if (descObj.parent) return descObj.parent.posBeforeChild(descObj); }, outerDeco, innerDeco); let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM; if (node2.isText) { if (!dom) dom = document.createTextNode(node2.text); else if (dom.nodeType != 3) throw new RangeError("Text must be rendered as a DOM text node"); } else if (!dom) { let spec2 = DOMSerializer.renderSpec(document, node2.type.spec.toDOM(node2), null, node2.attrs); ({ dom, contentDOM } = spec2); } if (!contentDOM && !node2.isText && dom.nodeName != "BR") { if (!dom.hasAttribute("contenteditable")) dom.contentEditable = "false"; if (node2.type.spec.draggable) dom.draggable = true; } let nodeDOM = dom; dom = applyOuterDeco(dom, outerDeco, node2); if (spec) return descObj = new CustomNodeViewDesc(parent, node2, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1); else if (node2.isText) return new TextViewDesc(parent, node2, outerDeco, innerDeco, dom, nodeDOM, view); else return new _NodeViewDesc(parent, node2, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1); } parseRule() { if (this.node.type.spec.reparseInView) return null; let rule = { node: this.node.type.name, attrs: this.node.attrs }; if (this.node.type.whitespace == "pre") rule.preserveWhitespace = "full"; if (!this.contentDOM) { rule.getContent = () => this.node.content; } else if (!this.contentLost) { rule.contentElement = this.contentDOM; } else { for (let i3 = this.children.length - 1; i3 >= 0; i3--) { let child = this.children[i3]; if (this.dom.contains(child.dom.parentNode)) { rule.contentElement = child.dom.parentNode; break; } } if (!rule.contentElement) rule.getContent = () => Fragment.empty; } return rule; } matchesNode(node2, outerDeco, innerDeco) { return this.dirty == NOT_DIRTY && node2.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco); } get size() { return this.node.nodeSize; } get border() { return this.node.isLeaf ? 0 : 1; } // Syncs `this.children` to match `this.node.content` and the local // decorations, possibly introducing nesting for marks. Then, in a // separate step, syncs the DOM inside `this.contentDOM` to // `this.children`. updateChildren(view, pos) { let inline4 = this.node.inlineContent, off = pos; let composition = view.composing ? this.localCompositionInfo(view, pos) : null; let localComposition = composition && composition.pos > -1 ? composition : null; let compositionInChild = composition && composition.pos < 0; let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view); iterDeco(this.node, this.innerDeco, (widget, i3, insideNode) => { if (widget.spec.marks) updater.syncToMarks(widget.spec.marks, inline4, view); else if (widget.type.side >= 0 && !insideNode) updater.syncToMarks(i3 == this.node.childCount ? Mark.none : this.node.child(i3).marks, inline4, view); updater.placeWidget(widget, view, off); }, (child, outerDeco, innerDeco, i3) => { updater.syncToMarks(child.marks, inline4, view); let compIndex; if (updater.findNodeMatch(child, outerDeco, innerDeco, i3)) ; else if (compositionInChild && view.state.selection.from > off && view.state.selection.to < off + child.nodeSize && (compIndex = updater.findIndexWithChild(composition.node)) > -1 && updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ; else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i3, off)) ; else { updater.addNode(child, outerDeco, innerDeco, view, off); } off += child.nodeSize; }); updater.syncToMarks([], inline4, view); if (this.node.isTextblock) updater.addTextblockHacks(); updater.destroyRest(); if (updater.changed || this.dirty == CONTENT_DIRTY) { if (localComposition) this.protectLocalComposition(view, localComposition); renderDescs(this.contentDOM, this.children, view); if (ios) iosHacks(this.dom); } } localCompositionInfo(view, pos) { let { from: from4, to: to2 } = view.state.selection; if (!(view.state.selection instanceof TextSelection) || from4 < pos || to2 > pos + this.node.content.size) return null; let textNode = view.input.compositionNode; if (!textNode || !this.dom.contains(textNode.parentNode)) return null; if (this.node.inlineContent) { let text10 = textNode.nodeValue; let textPos = findTextInFragment(this.node.content, text10, from4 - pos, to2 - pos); return textPos < 0 ? null : { node: textNode, pos: textPos, text: text10 }; } else { return { node: textNode, pos: -1, text: "" }; } } protectLocalComposition(view, { node: node2, pos, text: text10 }) { if (this.getDesc(node2)) return; let topNode = node2; for (; ; topNode = topNode.parentNode) { if (topNode.parentNode == this.contentDOM) break; while (topNode.previousSibling) topNode.parentNode.removeChild(topNode.previousSibling); while (topNode.nextSibling) topNode.parentNode.removeChild(topNode.nextSibling); if (topNode.pmViewDesc) topNode.pmViewDesc = void 0; } let desc = new CompositionViewDesc(this, topNode, node2, text10); view.input.compositionNodes.push(desc); this.children = replaceNodes(this.children, pos, pos + text10.length, view, desc); } // If this desc must be updated to match the given node decoration, // do so and return true. update(node2, outerDeco, innerDeco, view) { if (this.dirty == NODE_DIRTY || !node2.sameMarkup(this.node)) return false; this.updateInner(node2, outerDeco, innerDeco, view); return true; } updateInner(node2, outerDeco, innerDeco, view) { this.updateOuterDeco(outerDeco); this.node = node2; this.innerDeco = innerDeco; if (this.contentDOM) this.updateChildren(view, this.posAtStart); this.dirty = NOT_DIRTY; } updateOuterDeco(outerDeco) { if (sameOuterDeco(outerDeco, this.outerDeco)) return; let needsWrap = this.nodeDOM.nodeType != 1; let oldDOM = this.dom; this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap)); if (this.dom != oldDOM) { oldDOM.pmViewDesc = void 0; this.dom.pmViewDesc = this; } this.outerDeco = outerDeco; } // Mark this node as being the selected node. selectNode() { if (this.nodeDOM.nodeType == 1) { this.nodeDOM.classList.add("ProseMirror-selectednode"); if (this.contentDOM || !this.node.type.spec.draggable) this.nodeDOM.draggable = true; } } // Remove selected node marking from this node. deselectNode() { if (this.nodeDOM.nodeType == 1) { this.nodeDOM.classList.remove("ProseMirror-selectednode"); if (this.contentDOM || !this.node.type.spec.draggable) this.nodeDOM.removeAttribute("draggable"); } } get domAtom() { return this.node.isAtom; } }; function docViewDesc(doc4, outerDeco, innerDeco, dom, view) { applyOuterDeco(dom, outerDeco, doc4); let docView = new NodeViewDesc(void 0, doc4, outerDeco, innerDeco, dom, dom, dom, view, 0); if (docView.contentDOM) docView.updateChildren(view, 0); return docView; } var TextViewDesc = class _TextViewDesc extends NodeViewDesc { constructor(parent, node2, outerDeco, innerDeco, dom, nodeDOM, view) { super(parent, node2, outerDeco, innerDeco, dom, null, nodeDOM, view, 0); } parseRule() { let skip = this.nodeDOM.parentNode; while (skip && skip != this.dom && !skip.pmIsDeco) skip = skip.parentNode; return { skip: skip || true }; } update(node2, outerDeco, innerDeco, view) { if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node2.sameMarkup(this.node)) return false; this.updateOuterDeco(outerDeco); if ((this.dirty != NOT_DIRTY || node2.text != this.node.text) && node2.text != this.nodeDOM.nodeValue) { this.nodeDOM.nodeValue = node2.text; if (view.trackWrites == this.nodeDOM) view.trackWrites = null; } this.node = node2; this.dirty = NOT_DIRTY; return true; } inParent() { let parentDOM = this.parent.contentDOM; for (let n = this.nodeDOM; n; n = n.parentNode) if (n == parentDOM) return true; return false; } domFromPos(pos) { return { node: this.nodeDOM, offset: pos }; } localPosFromDOM(dom, offset4, bias) { if (dom == this.nodeDOM) return this.posAtStart + Math.min(offset4, this.node.text.length); return super.localPosFromDOM(dom, offset4, bias); } ignoreMutation(mutation) { return mutation.type != "characterData" && mutation.type != "selection"; } slice(from4, to2, view) { let node2 = this.node.cut(from4, to2), dom = document.createTextNode(node2.text); return new _TextViewDesc(this.parent, node2, this.outerDeco, this.innerDeco, dom, dom, view); } markDirty(from4, to2) { super.markDirty(from4, to2); if (this.dom != this.nodeDOM && (from4 == 0 || to2 == this.nodeDOM.nodeValue.length)) this.dirty = NODE_DIRTY; } get domAtom() { return false; } isText(text10) { return this.node.text == text10; } }; var TrailingHackViewDesc = class extends ViewDesc { parseRule() { return { ignore: true }; } matchesHack(nodeName) { return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; } get domAtom() { return true; } get ignoreForCoords() { return this.dom.nodeName == "IMG"; } }; var CustomNodeViewDesc = class extends NodeViewDesc { constructor(parent, node2, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) { super(parent, node2, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos); this.spec = spec; } // A custom `update` method gets to decide whether the update goes // through. If it does, and there's a `contentDOM` node, our logic // updates the children. update(node2, outerDeco, innerDeco, view) { if (this.dirty == NODE_DIRTY) return false; if (this.spec.update && (this.node.type == node2.type || this.spec.multiType)) { let result = this.spec.update(node2, outerDeco, innerDeco); if (result) this.updateInner(node2, outerDeco, innerDeco, view); return result; } else if (!this.contentDOM && !node2.isLeaf) { return false; } else { return super.update(node2, outerDeco, innerDeco, view); } } selectNode() { this.spec.selectNode ? this.spec.selectNode() : super.selectNode(); } deselectNode() { this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode(); } setSelection(anchor, head2, view, force) { this.spec.setSelection ? this.spec.setSelection(anchor, head2, view.root) : super.setSelection(anchor, head2, view, force); } destroy() { if (this.spec.destroy) this.spec.destroy(); super.destroy(); } stopEvent(event) { return this.spec.stopEvent ? this.spec.stopEvent(event) : false; } ignoreMutation(mutation) { return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation); } }; function renderDescs(parentDOM, descs, view) { let dom = parentDOM.firstChild, written = false; for (let i3 = 0; i3 < descs.length; i3++) { let desc = descs[i3], childDOM = desc.dom; if (childDOM.parentNode == parentDOM) { while (childDOM != dom) { dom = rm(dom); written = true; } dom = dom.nextSibling; } else { written = true; parentDOM.insertBefore(childDOM, dom); } if (desc instanceof MarkViewDesc) { let pos = dom ? dom.previousSibling : parentDOM.lastChild; renderDescs(desc.contentDOM, desc.children, view); dom = pos ? pos.nextSibling : parentDOM.firstChild; } } while (dom) { dom = rm(dom); written = true; } if (written && view.trackWrites == parentDOM) view.trackWrites = null; } var OuterDecoLevel = function(nodeName) { if (nodeName) this.nodeName = nodeName; }; OuterDecoLevel.prototype = /* @__PURE__ */ Object.create(null); var noDeco = [new OuterDecoLevel()]; function computeOuterDeco(outerDeco, node2, needsWrap) { if (outerDeco.length == 0) return noDeco; let top = needsWrap ? noDeco[0] : new OuterDecoLevel(), result = [top]; for (let i3 = 0; i3 < outerDeco.length; i3++) { let attrs = outerDeco[i3].type.attrs; if (!attrs) continue; if (attrs.nodeName) result.push(top = new OuterDecoLevel(attrs.nodeName)); for (let name in attrs) { let val = attrs[name]; if (val == null) continue; if (needsWrap && result.length == 1) result.push(top = new OuterDecoLevel(node2.isInline ? "span" : "div")); if (name == "class") top.class = (top.class ? top.class + " " : "") + val; else if (name == "style") top.style = (top.style ? top.style + ";" : "") + val; else if (name != "nodeName") top[name] = val; } } return result; } function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) { if (prevComputed == noDeco && curComputed == noDeco) return nodeDOM; let curDOM = nodeDOM; for (let i3 = 0; i3 < curComputed.length; i3++) { let deco = curComputed[i3], prev = prevComputed[i3]; if (i3) { let parent; if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) { curDOM = parent; } else { parent = document.createElement(deco.nodeName); parent.pmIsDeco = true; parent.appendChild(curDOM); prev = noDeco[0]; curDOM = parent; } } patchAttributes(curDOM, prev || noDeco[0], deco); } return curDOM; } function patchAttributes(dom, prev, cur) { for (let name in prev) if (name != "class" && name != "style" && name != "nodeName" && !(name in cur)) dom.removeAttribute(name); for (let name in cur) if (name != "class" && name != "style" && name != "nodeName" && cur[name] != prev[name]) dom.setAttribute(name, cur[name]); if (prev.class != cur.class) { let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : []; let curList = cur.class ? cur.class.split(" ").filter(Boolean) : []; for (let i3 = 0; i3 < prevList.length; i3++) if (curList.indexOf(prevList[i3]) == -1) dom.classList.remove(prevList[i3]); for (let i3 = 0; i3 < curList.length; i3++) if (prevList.indexOf(curList[i3]) == -1) dom.classList.add(curList[i3]); if (dom.classList.length == 0) dom.removeAttribute("class"); } if (prev.style != cur.style) { if (prev.style) { let prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m2; while (m2 = prop.exec(prev.style)) dom.style.removeProperty(m2[1]); } if (cur.style) dom.style.cssText += cur.style; } } function applyOuterDeco(dom, deco, node2) { return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node2, dom.nodeType != 1)); } function sameOuterDeco(a3, b4) { if (a3.length != b4.length) return false; for (let i3 = 0; i3 < a3.length; i3++) if (!a3[i3].type.eq(b4[i3].type)) return false; return true; } function rm(dom) { let next2 = dom.nextSibling; dom.parentNode.removeChild(dom); return next2; } var ViewTreeUpdater = class { constructor(top, lock, view) { this.lock = lock; this.view = view; this.index = 0; this.stack = []; this.changed = false; this.top = top; this.preMatch = preMatch(top.node.content, top); } // Destroy and remove the children between the given indices in // `this.top`. destroyBetween(start, end) { if (start == end) return; for (let i3 = start; i3 < end; i3++) this.top.children[i3].destroy(); this.top.children.splice(start, end - start); this.changed = true; } // Destroy all remaining children in `this.top`. destroyRest() { this.destroyBetween(this.index, this.top.children.length); } // Sync the current stack of mark descs with the given array of // marks, reusing existing mark descs when possible. syncToMarks(marks, inline4, view) { let keep = 0, depth = this.stack.length >> 1; let maxKeep = Math.min(depth, marks.length); while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false) keep++; while (keep < depth) { this.destroyRest(); this.top.dirty = NOT_DIRTY; this.index = this.stack.pop(); this.top = this.stack.pop(); depth--; } while (depth < marks.length) { this.stack.push(this.top, this.index + 1); let found2 = -1; for (let i3 = this.index; i3 < Math.min(this.index + 3, this.top.children.length); i3++) { let next2 = this.top.children[i3]; if (next2.matchesMark(marks[depth]) && !this.isLocked(next2.dom)) { found2 = i3; break; } } if (found2 > -1) { if (found2 > this.index) { this.changed = true; this.destroyBetween(this.index, found2); } this.top = this.top.children[this.index]; } else { let markDesc = MarkViewDesc.create(this.top, marks[depth], inline4, view); this.top.children.splice(this.index, 0, markDesc); this.top = markDesc; this.changed = true; } this.index = 0; depth++; } } // Try to find a node desc matching the given data. Skip over it and // return true when successful. findNodeMatch(node2, outerDeco, innerDeco, index4) { let found2 = -1, targetDesc; if (index4 >= this.preMatch.index && (targetDesc = this.preMatch.matches[index4 - this.preMatch.index]).parent == this.top && targetDesc.matchesNode(node2, outerDeco, innerDeco)) { found2 = this.top.children.indexOf(targetDesc, this.index); } else { for (let i3 = this.index, e2 = Math.min(this.top.children.length, i3 + 5); i3 < e2; i3++) { let child = this.top.children[i3]; if (child.matchesNode(node2, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) { found2 = i3; break; } } } if (found2 < 0) return false; this.destroyBetween(this.index, found2); this.index++; return true; } updateNodeAt(node2, outerDeco, innerDeco, index4, view) { let child = this.top.children[index4]; if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM) child.dirty = CONTENT_DIRTY; if (!child.update(node2, outerDeco, innerDeco, view)) return false; this.destroyBetween(this.index, index4); this.index++; return true; } findIndexWithChild(domNode) { for (; ; ) { let parent = domNode.parentNode; if (!parent) return -1; if (parent == this.top.contentDOM) { let desc = domNode.pmViewDesc; if (desc) for (let i3 = this.index; i3 < this.top.children.length; i3++) { if (this.top.children[i3] == desc) return i3; } return -1; } domNode = parent; } } // Try to update the next node, if any, to the given data. Checks // pre-matches to avoid overwriting nodes that could still be used. updateNextNode(node2, outerDeco, innerDeco, view, index4, pos) { for (let i3 = this.index; i3 < this.top.children.length; i3++) { let next2 = this.top.children[i3]; if (next2 instanceof NodeViewDesc) { let preMatch2 = this.preMatch.matched.get(next2); if (preMatch2 != null && preMatch2 != index4) return false; let nextDOM = next2.dom, updated; let locked = this.isLocked(nextDOM) && !(node2.isText && next2.node && next2.node.isText && next2.nodeDOM.nodeValue == node2.text && next2.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next2.outerDeco)); if (!locked && next2.update(node2, outerDeco, innerDeco, view)) { this.destroyBetween(this.index, i3); if (next2.dom != nextDOM) this.changed = true; this.index++; return true; } else if (!locked && (updated = this.recreateWrapper(next2, node2, outerDeco, innerDeco, view, pos))) { this.destroyBetween(this.index, i3); this.top.children[this.index] = updated; if (updated.contentDOM) { updated.dirty = CONTENT_DIRTY; updated.updateChildren(view, pos + 1); updated.dirty = NOT_DIRTY; } this.changed = true; this.index++; return true; } break; } } return false; } // When a node with content is replaced by a different node with // identical content, move over its children. recreateWrapper(next2, node2, outerDeco, innerDeco, view, pos) { if (next2.dirty || node2.isAtom || !next2.children.length || !next2.node.content.eq(node2.content) || !sameOuterDeco(outerDeco, next2.outerDeco) || !innerDeco.eq(next2.innerDeco)) return null; let wrapper = NodeViewDesc.create(this.top, node2, outerDeco, innerDeco, view, pos); if (wrapper.contentDOM) { wrapper.children = next2.children; next2.children = []; for (let ch of wrapper.children) ch.parent = wrapper; } next2.destroy(); return wrapper; } // Insert the node as a newly created node desc. addNode(node2, outerDeco, innerDeco, view, pos) { let desc = NodeViewDesc.create(this.top, node2, outerDeco, innerDeco, view, pos); if (desc.contentDOM) desc.updateChildren(view, pos + 1); this.top.children.splice(this.index++, 0, desc); this.changed = true; } placeWidget(widget, view, pos) { let next2 = this.index < this.top.children.length ? this.top.children[this.index] : null; if (next2 && next2.matchesWidget(widget) && (widget == next2.widget || !next2.widget.type.toDOM.parentNode)) { this.index++; } else { let desc = new WidgetViewDesc(this.top, widget, view, pos); this.top.children.splice(this.index++, 0, desc); this.changed = true; } } // Make sure a textblock looks and behaves correctly in // contentEditable. addTextblockHacks() { let lastChild = this.top.children[this.index - 1], parent = this.top; while (lastChild instanceof MarkViewDesc) { parent = lastChild; lastChild = parent.children[parent.children.length - 1]; } if (!lastChild || // Empty textblock !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text)) { if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == "false") this.addHackNode("IMG", parent); this.addHackNode("BR", this.top); } } addHackNode(nodeName, parent) { if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) { this.index++; } else { let dom = document.createElement(nodeName); if (nodeName == "IMG") { dom.className = "ProseMirror-separator"; dom.alt = ""; } if (nodeName == "BR") dom.className = "ProseMirror-trailingBreak"; let hack = new TrailingHackViewDesc(this.top, [], dom, null); if (parent != this.top) parent.children.push(hack); else parent.children.splice(this.index++, 0, hack); this.changed = true; } } isLocked(node2) { return this.lock && (node2 == this.lock || node2.nodeType == 1 && node2.contains(this.lock.parentNode)); } }; function preMatch(frag, parentDesc) { let curDesc = parentDesc, descI = curDesc.children.length; let fI = frag.childCount, matched = /* @__PURE__ */ new Map(), matches3 = []; outer: while (fI > 0) { let desc; for (; ; ) { if (descI) { let next2 = curDesc.children[descI - 1]; if (next2 instanceof MarkViewDesc) { curDesc = next2; descI = next2.children.length; } else { desc = next2; descI--; break; } } else if (curDesc == parentDesc) { break outer; } else { descI = curDesc.parent.children.indexOf(curDesc); curDesc = curDesc.parent; } } let node2 = desc.node; if (!node2) continue; if (node2 != frag.child(fI - 1)) break; --fI; matched.set(desc, fI); matches3.push(desc); } return { index: fI, matched, matches: matches3.reverse() }; } function compareSide(a3, b4) { return a3.type.side - b4.type.side; } function iterDeco(parent, deco, onWidget, onNode) { let locals = deco.locals(parent), offset4 = 0; if (locals.length == 0) { for (let i3 = 0; i3 < parent.childCount; i3++) { let child = parent.child(i3); onNode(child, locals, deco.forChild(offset4, child), i3); offset4 += child.nodeSize; } return; } let decoIndex = 0, active = [], restNode = null; for (let parentIndex = 0; ; ) { let widget, widgets; while (decoIndex < locals.length && locals[decoIndex].to == offset4) { let next2 = locals[decoIndex++]; if (next2.widget) { if (!widget) widget = next2; else (widgets || (widgets = [widget])).push(next2); } } if (widget) { if (widgets) { widgets.sort(compareSide); for (let i3 = 0; i3 < widgets.length; i3++) onWidget(widgets[i3], parentIndex, !!restNode); } else { onWidget(widget, parentIndex, !!restNode); } } let child, index4; if (restNode) { index4 = -1; child = restNode; restNode = null; } else if (parentIndex < parent.childCount) { index4 = parentIndex; child = parent.child(parentIndex++); } else { break; } for (let i3 = 0; i3 < active.length; i3++) if (active[i3].to <= offset4) active.splice(i3--, 1); while (decoIndex < locals.length && locals[decoIndex].from <= offset4 && locals[decoIndex].to > offset4) active.push(locals[decoIndex++]); let end = offset4 + child.nodeSize; if (child.isText) { let cutAt = end; if (decoIndex < locals.length && locals[decoIndex].from < cutAt) cutAt = locals[decoIndex].from; for (let i3 = 0; i3 < active.length; i3++) if (active[i3].to < cutAt) cutAt = active[i3].to; if (cutAt < end) { restNode = child.cut(cutAt - offset4); child = child.cut(0, cutAt - offset4); end = cutAt; index4 = -1; } } else { while (decoIndex < locals.length && locals[decoIndex].to < end) decoIndex++; } let outerDeco = child.isInline && !child.isLeaf ? active.filter((d) => !d.inline) : active.slice(); onNode(child, outerDeco, deco.forChild(offset4, child), index4); offset4 = end; } } function iosHacks(dom) { if (dom.nodeName == "UL" || dom.nodeName == "OL") { let oldCSS = dom.style.cssText; dom.style.cssText = oldCSS + "; list-style: square !important"; window.getComputedStyle(dom).listStyle; dom.style.cssText = oldCSS; } } function findTextInFragment(frag, text10, from4, to2) { for (let i3 = 0, pos = 0; i3 < frag.childCount && pos <= to2; ) { let child = frag.child(i3++), childStart = pos; pos += child.nodeSize; if (!child.isText) continue; let str = child.text; while (i3 < frag.childCount) { let next2 = frag.child(i3++); pos += next2.nodeSize; if (!next2.isText) break; str += next2.text; } if (pos >= from4) { if (pos >= to2 && str.slice(to2 - text10.length - childStart, to2 - childStart) == text10) return to2 - text10.length; let found2 = childStart < to2 ? str.lastIndexOf(text10, to2 - childStart - 1) : -1; if (found2 >= 0 && found2 + text10.length + childStart >= from4) return childStart + found2; if (from4 == to2 && str.length >= to2 + text10.length - childStart && str.slice(to2 - childStart, to2 - childStart + text10.length) == text10) return to2; } } return -1; } function replaceNodes(nodes, from4, to2, view, replacement) { let result = []; for (let i3 = 0, off = 0; i3 < nodes.length; i3++) { let child = nodes[i3], start = off, end = off += child.size; if (start >= to2 || end <= from4) { result.push(child); } else { if (start < from4) result.push(child.slice(0, from4 - start, view)); if (replacement) { result.push(replacement); replacement = void 0; } if (end > to2) result.push(child.slice(to2 - start, child.size, view)); } } return result; } function selectionFromDOM(view, origin = null) { let domSel = view.domSelectionRange(), doc4 = view.state.doc; if (!domSel.focusNode) return null; let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0; let head2 = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1); if (head2 < 0) return null; let $head = doc4.resolve(head2), anchor, selection; if (selectionCollapsed(domSel)) { anchor = head2; 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(head2 == pos ? $head : doc4.resolve(pos)); } } else { if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) { let min3 = head2, max3 = head2; for (let i3 = 0; i3 < domSel.rangeCount; i3++) { let range = domSel.getRangeAt(i3); min3 = Math.min(min3, view.docView.posFromDOM(range.startContainer, range.startOffset, 1)); max3 = Math.max(max3, view.docView.posFromDOM(range.endContainer, range.endOffset, -1)); } if (min3 < 0) return null; [anchor, head2] = max3 == view.state.selection.anchor ? [max3, min3] : [min3, max3]; $head = doc4.resolve(head2); } else { anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1); } if (anchor < 0) return null; } let $anchor = doc4.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; if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome) { let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection; if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) { view.input.mouseDown.delayedSelectionSync = true; view.domObserver.setCurSelection(); return; } } view.domObserver.disconnectSelection(); if (view.cursorWrapper) { selectCursorWrapper(view); } else { let { anchor, head: head2 } = 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, head2, 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(); } var brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63; function temporarilyEditableNear(view, pos) { let { node: node2, offset: offset4 } = view.docView.domFromPos(pos, 0); let after = offset4 < node2.childNodes.length ? node2.childNodes[offset4] : null; let before = offset4 ? node2.childNodes[offset4 - 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(element7) { element7.contentEditable = "true"; if (safari && element7.draggable) { element7.draggable = false; element7.wasDraggable = true; } return element7; } function resetEditable(element7) { element7.contentEditable = "false"; if (element7.wasDraggable) { element7.draggable = true; element7.wasDraggable = null; } } function removeClassOnSelectionChange(view) { let doc4 = view.dom.ownerDocument; doc4.removeEventListener("selectionchange", view.input.hideSelectionGuard); let domSel = view.domSelectionRange(); let node2 = domSel.anchorNode, offset4 = domSel.anchorOffset; doc4.addEventListener("selectionchange", view.input.hideSelectionGuard = () => { if (domSel.anchorNode != node2 || domSel.anchorOffset != offset4) { doc4.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 node2 = view.cursorWrapper.dom, img2 = node2.nodeName == "IMG"; if (img2) domSel.collapse(node2.parentNode, domIndex(node2) + 1); else domSel.collapse(node2, 0); if (!img2 && !view.state.selection.visible && ie && ie_version <= 11) { node2.disabled = true; node2.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", (f6) => f6(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias); } function hasFocusAndSelection(view) { if (view.editable && !view.hasFocus()) return false; return hasSelection(view); } 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 (_2) { return false; } } function anchorInRightPlace(view) { let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0); let domSel = view.domSelectionRange(); return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset); } 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, node2 = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter; if (!node2 || node2.isText || !node2.isLeaf) return false; let $newHead = view.state.doc.resolve($head.pos + node2.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 next2 = moveSelectionBlock(view.state, dir); if (next2 && next2 instanceof NodeSelection) return apply(view, next2); return false; } else if (!(mac && mods.indexOf("m") > -1)) { let $head = sel.$head, node2 = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc; if (!node2 || node2.isText) return false; let nodePos = dir < 0 ? $head.pos - node2.nodeSize : $head.pos; if (!(node2.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) return false; if (NodeSelection.isSelectable(node2)) { return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node2.nodeSize) : $head)); } else if (webkit) { return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node2.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 next2 = moveSelectionBlock(view.state, dir); if (next2) return apply(view, next2); return false; } } function nodeLen(node2) { return node2.nodeType == 3 ? node2.nodeValue.length : node2.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 node2 = sel.focusNode, offset4 = sel.focusOffset; if (!node2) return; let moveNode, moveOffset, force = false; if (gecko && node2.nodeType == 1 && offset4 < nodeLen(node2) && isIgnorable(node2.childNodes[offset4], -1)) force = true; for (; ; ) { if (offset4 > 0) { if (node2.nodeType != 1) { break; } else { let before = node2.childNodes[offset4 - 1]; if (isIgnorable(before, -1)) { moveNode = node2; moveOffset = --offset4; } else if (before.nodeType == 3) { node2 = before; offset4 = node2.nodeValue.length; } else break; } } else if (isBlockNode(node2)) { break; } else { let prev = node2.previousSibling; while (prev && isIgnorable(prev, -1)) { moveNode = node2.parentNode; moveOffset = domIndex(prev); prev = prev.previousSibling; } if (!prev) { node2 = node2.parentNode; if (node2 == view.dom) break; offset4 = 0; } else { node2 = prev; offset4 = nodeLen(node2); } } } if (force) setSelFocus(view, node2, offset4); else if (moveNode) setSelFocus(view, moveNode, moveOffset); } function skipIgnoredNodesAfter(view) { let sel = view.domSelectionRange(); let node2 = sel.focusNode, offset4 = sel.focusOffset; if (!node2) return; let len = nodeLen(node2); let moveNode, moveOffset; for (; ; ) { if (offset4 < len) { if (node2.nodeType != 1) break; let after = node2.childNodes[offset4]; if (isIgnorable(after, 1)) { moveNode = node2; moveOffset = ++offset4; } else break; } else if (isBlockNode(node2)) { break; } else { let next2 = node2.nextSibling; while (next2 && isIgnorable(next2, 1)) { moveNode = next2.parentNode; moveOffset = domIndex(next2) + 1; next2 = next2.nextSibling; } if (!next2) { node2 = node2.parentNode; if (node2 == view.dom) break; offset4 = len = 0; } else { node2 = next2; offset4 = 0; len = nodeLen(node2); } } } if (moveNode) setSelFocus(view, moveNode, moveOffset); } function isBlockNode(dom) { let desc = dom.pmViewDesc; return desc && desc.node && desc.node.isBlock; } function textNodeAfter(node2, offset4) { while (node2 && offset4 == node2.childNodes.length && !hasBlockDesc(node2)) { offset4 = domIndex(node2) + 1; node2 = node2.parentNode; } while (node2 && offset4 < node2.childNodes.length) { let next2 = node2.childNodes[offset4]; if (next2.nodeType == 3) return next2; if (next2.nodeType == 1 && next2.contentEditable == "false") break; node2 = next2; offset4 = 0; } } function textNodeBefore(node2, offset4) { while (node2 && !offset4 && !hasBlockDesc(node2)) { offset4 = domIndex(node2); node2 = node2.parentNode; } while (node2 && offset4) { let next2 = node2.childNodes[offset4 - 1]; if (next2.nodeType == 3) return next2; if (next2.nodeType == 1 && next2.contentEditable == "false") break; node2 = next2; offset4 = node2.childNodes.length; } } function setSelFocus(view, node2, offset4) { if (node2.nodeType != 3) { let before, after; if (after = textNodeAfter(node2, offset4)) { node2 = after; offset4 = 0; } else if (before = textNodeBefore(node2, offset4)) { node2 = before; offset4 = before.nodeValue.length; } } let sel = view.domSelection(); if (!sel) return; if (selectionCollapsed(sel)) { let range = document.createRange(); range.setEnd(node2, offset4); range.setStart(node2, offset4); sel.removeAllRanges(); sel.addRange(range); } else if (sel.extend) { sel.extend(node2, offset4); } 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) && $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 && mods.indexOf("m") > -1) return false; let { $from, $to } = sel; if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) { let next2 = moveSelectionBlock(view.state, dir); if (next2 && next2 instanceof NodeSelection) return apply(view, next2); } 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: empty4 } = view.state.selection; if (!$head.sameParent($anchor)) return true; if (!empty4) 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 tr4 = view.state.tr; if (dir < 0) tr4.delete($head.pos - nextNode.nodeSize, $head.pos); else tr4.delete($head.pos, $head.pos + nextNode.nodeSize); view.dispatch(tr4); return true; } return false; } function switchEditable(view, node2, state) { view.domObserver.stop(); node2.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 code5 = event.keyCode, mods = getMods(event); if (code5 == 8 || mac && code5 == 72 && mods == "c") { return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1); } else if (code5 == 46 && !event.shiftKey || mac && code5 == 68 && mods == "c") { return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1); } else if (code5 == 13 || code5 == 27) { return true; } else if (code5 == 37 || mac && code5 == 66 && mods == "c") { let dir = code5 == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1; return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); } else if (code5 == 39 || mac && code5 == 70 && mods == "c") { let dir = code5 == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1; return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); } else if (code5 == 38 || mac && code5 == 80 && mods == "c") { return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1); } else if (code5 == 40 || mac && code5 == 78 && mods == "c") { return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1); } else if (mods == (mac ? "m" : "c") && (code5 == 66 || code5 == 73 || code5 == 89 || code5 == 90)) { return true; } return false; } function serializeForClipboard(view, slice2) { view.someProp("transformCopied", (f6) => { slice2 = f6(slice2, view); }); let context = [], { content: content5, openStart, openEnd } = slice2; while (openStart > 1 && openEnd > 1 && content5.childCount == 1 && content5.firstChild.childCount == 1) { openStart--; openEnd--; let node2 = content5.firstChild; context.push(node2.type.name, node2.attrs != node2.type.defaultAttrs ? node2.attrs : null); content5 = node2.content; } let serializer2 = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema); let doc4 = detachedDoc(), wrap5 = doc4.createElement("div"); wrap5.appendChild(serializer2.serializeFragment(content5, { document: doc4 })); let firstChild = wrap5.firstChild, needsWrap, wrappers = 0; while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) { for (let i3 = needsWrap.length - 1; i3 >= 0; i3--) { let wrapper = doc4.createElement(needsWrap[i3]); while (wrap5.firstChild) wrapper.appendChild(wrap5.firstChild); wrap5.appendChild(wrapper); wrappers++; } firstChild = wrap5.firstChild; } if (firstChild && firstChild.nodeType == 1) firstChild.setAttribute("data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`); let text10 = view.someProp("clipboardTextSerializer", (f6) => f6(slice2, view)) || slice2.content.textBetween(0, slice2.content.size, "\n\n"); return { dom: wrap5, text: text10, slice: slice2 }; } function parseFromClipboard(view, text10, html7, plainText, $context) { let inCode = $context.parent.type.spec.code; let dom, slice2; if (!html7 && !text10) return null; let asText = !!text10 && (plainText || inCode || !html7); if (asText) { view.someProp("transformPastedText", (f6) => { text10 = f6(text10, inCode || plainText, view); }); if (inCode) { slice2 = new Slice(Fragment.from(view.state.schema.text(text10.replace(/\r\n?/g, "\n"))), 0, 0); view.someProp("transformPasted", (f6) => { slice2 = f6(slice2, view, true); }); return slice2; } let parsed = view.someProp("clipboardTextParser", (f6) => f6(text10, $context, plainText, view)); if (parsed) { slice2 = parsed; } else { let marks = $context.marks(); let { schema } = view.state, serializer2 = DOMSerializer.fromSchema(schema); dom = document.createElement("div"); text10.split(/(?:\r\n?|\n)+/).forEach((block) => { let p4 = dom.appendChild(document.createElement("p")); if (block) p4.appendChild(serializer2.serializeNode(schema.text(block, marks))); }); } } else { view.someProp("transformPastedHTML", (f6) => { html7 = f6(html7, view); }); dom = readHTML(html7); 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 i3 = +sliceData[3]; i3 > 0; i3--) { 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") || DOMParser2.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 node2 = slice2.content.firstChild; openStart < slice2.openStart && !node2.type.spec.isolating; openStart++, node2 = node2.firstChild) { } for (let node2 = slice2.content.lastChild; openEnd < slice2.openEnd && !node2.type.spec.isolating; openEnd++, node2 = node2.lastChild) { } slice2 = closeSlice(slice2, openStart, openEnd); } } view.someProp("transformPasted", (f6) => { slice2 = f6(slice2, view, asText); }); return slice2; } var 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 match2 = parent.contentMatchAt($context.index(d)); let lastWrap, result = []; fragment.forEach((node2) => { if (!result) return; let wrap5 = match2.findWrapping(node2.type), inLast; if (!wrap5) return result = null; if (inLast = result.length && lastWrap.length && addToSibling(wrap5, lastWrap, node2, 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(node2, wrap5); result.push(wrapped); match2 = match2.matchType(wrapped.type); lastWrap = wrap5; } }); if (result) return Fragment.from(result); } return fragment; } function withWrappers(node2, wrap5, from4 = 0) { for (let i3 = wrap5.length - 1; i3 >= from4; i3--) node2 = wrap5[i3].create(null, Fragment.from(node2)); return node2; } function addToSibling(wrap5, lastWrap, node2, sibling, depth) { if (depth < wrap5.length && depth < lastWrap.length && wrap5[depth] == lastWrap[depth]) { let inner = addToSibling(wrap5, lastWrap, node2, sibling.lastChild, depth + 1); if (inner) return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner)); let match2 = sibling.contentMatchAt(sibling.childCount); if (match2.matchType(depth == wrap5.length - 1 ? node2.type : wrap5[depth + 1])) return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node2, wrap5, depth + 1)))); } } function closeRight(node2, depth) { if (depth == 0) return node2; let fragment = node2.content.replaceChild(node2.childCount - 1, closeRight(node2.lastChild, depth - 1)); let fill = node2.contentMatchAt(node2.childCount).fillBefore(Fragment.empty, true); return node2.copy(fragment.append(fill)); } function closeRange(fragment, side, from4, to2, depth, openEnd) { let node2 = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node2.content; if (fragment.childCount > 1) openEnd = 0; if (depth < to2 - 1) inner = closeRange(inner, side, from4, to2, depth + 1, openEnd); if (depth >= from4) inner = side < 0 ? node2.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner) : inner.append(node2.contentMatchAt(node2.childCount).fillBefore(Fragment.empty, true)); return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node2.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; } var 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"] }; var _detachedDoc = null; function detachedDoc() { return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title")); } var _policy = null; function maybeWrapTrusted(html7) { let trustedTypes = window.trustedTypes; if (!trustedTypes) return html7; if (!_policy) _policy = trustedTypes.defaultPolicy || trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: (s2) => s2 }); return _policy.createHTML(html7); } function readHTML(html7) { let metas = /^(\s*]*>)*/.exec(html7); if (metas) html7 = html7.slice(metas[0].length); let elt = detachedDoc().createElement("div"); let firstTag = /<([a-z][^>\s]+)/i.exec(html7), wrap5; if (wrap5 = firstTag && wrapMap[firstTag[1].toLowerCase()]) html7 = wrap5.map((n) => "<" + n + ">").join("") + html7 + wrap5.map((n) => "").reverse().join(""); elt.innerHTML = maybeWrapTrusted(html7); if (wrap5) for (let i3 = 0; i3 < wrap5.length; i3++) elt = elt.querySelector(wrap5[i3]) || elt; return elt; } function restoreReplacedSpaces(dom) { let nodes = dom.querySelectorAll(chrome ? "span:not([class]):not([style])" : "span.Apple-converted-space"); for (let i3 = 0; i3 < nodes.length; i3++) { let node2 = nodes[i3]; if (node2.childNodes.length == 1 && node2.textContent == " " && node2.parentNode) node2.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node2); } } function addContext(slice2, context) { if (!slice2.size) return slice2; let schema = slice2.content.firstChild.type.schema, array; try { array = JSON.parse(context); } catch (e2) { return slice2; } let { content: content5, openStart, openEnd } = slice2; for (let i3 = array.length - 2; i3 >= 0; i3 -= 2) { let type = schema.nodes[array[i3]]; if (!type || type.hasRequiredAttrs()) break; content5 = Fragment.from(type.create(array[i3 + 1], content5)); openStart++; openEnd++; } return new Slice(content5, openStart, openEnd); } var handlers = {}; var editHandlers = {}; var passiveHandlers = { touchstart: true, touchmove: true }; var InputState = class { constructor() { this.shiftKey = false; this.mouseDown = null; this.lastKeyCode = null; this.lastKeyCodeTime = 0; this.lastClick = { time: 0, x: 0, y: 0, type: "", button: 0 }; this.lastSelectionOrigin = null; this.lastSelectionTime = 0; this.lastIOSEnter = 0; this.lastIOSEnterFallbackTimeout = -1; this.lastFocus = 0; this.lastTouch = 0; this.lastChromeDelete = 0; this.composing = false; this.compositionNode = null; this.composingTimeout = -1; this.compositionNodes = []; this.compositionEndedAt = -2e8; this.compositionID = 1; this.compositionPendingChanges = 0; this.domChangeCount = 0; this.eventHandlers = /* @__PURE__ */ Object.create(null); this.hideSelectionGuard = null; } }; function initInput(view) { for (let event in handlers) { let handler = handlers[event]; view.dom.addEventListener(event, view.input.eventHandlers[event] = (event2) => { if (eventBelongsToView(view, event2) && !runCustomHandler(view, event2) && (view.editable || !(event2.type in editHandlers))) handler(view, event2); }, passiveHandlers[event] ? { passive: true } : void 0); } if (safari) view.dom.addEventListener("input", () => null); ensureListeners(view); } function setSelectionOrigin(view, origin) { view.input.lastSelectionOrigin = origin; view.input.lastSelectionTime = Date.now(); } function destroyInput(view) { view.domObserver.stop(); for (let type in view.input.eventHandlers) view.dom.removeEventListener(type, view.input.eventHandlers[type]); clearTimeout(view.input.composingTimeout); clearTimeout(view.input.lastIOSEnterFallbackTimeout); } function ensureListeners(view) { view.someProp("handleDOMEvents", (currentHandlers) => { for (let type in currentHandlers) if (!view.input.eventHandlers[type]) view.dom.addEventListener(type, view.input.eventHandlers[type] = (event) => runCustomHandler(view, event)); }); } function runCustomHandler(view, event) { return view.someProp("handleDOMEvents", (handlers4) => { let handler = handlers4[event.type]; return handler ? handler(view, event) || event.defaultPrevented : false; }); } function eventBelongsToView(view, event) { if (!event.bubbles) return true; if (event.defaultPrevented) return false; for (let node2 = event.target; node2 != view.dom; node2 = node2.parentNode) if (!node2 || node2.nodeType == 11 || node2.pmViewDesc && node2.pmViewDesc.stopEvent(event)) return false; return true; } function dispatchEvent(view, event) { if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers))) handlers[event.type](view, event); } editHandlers.keydown = (view, _event) => { let event = _event; view.input.shiftKey = event.keyCode == 16 || event.shiftKey; if (inOrNearComposition(view, event)) 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", (f6) => f6(view, keyEvent(13, "Enter"))); view.input.lastIOSEnter = 0; } }, 200); } else if (view.someProp("handleKeyDown", (f6) => f6(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) || !event.charCode || event.ctrlKey && !event.altKey || mac && event.metaKey) return; if (view.someProp("handleKeyPress", (f6) => f6(view, event))) { event.preventDefault(); return; } let sel = view.state.selection; if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) { let text10 = String.fromCharCode(event.charCode); let deflt = () => view.state.tr.insertText(text10).scrollIntoView(); if (!/[\r\n]/.test(text10) && !view.someProp("handleTextInput", (f6) => f6(view, sel.$from.pos, sel.$to.pos, text10, 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 i3 = $pos.depth + 1; i3 > 0; i3--) { if (view.someProp(propName, (f6) => i3 > $pos.depth ? f6(view, pos, $pos.nodeAfter, $pos.before(i3), event, true) : f6(view, pos, $pos.node(i3), $pos.before(i3), event, false))) return true; } return false; } function updateSelection(view, selection, origin) { if (!view.focused) view.focus(); if (view.state.selection.eq(selection)) return; let tr4 = view.state.tr.setSelection(selection); if (origin == "pointer") tr4.setMeta("pointer", true); view.dispatch(tr4); } function selectClickedLeaf(view, inside) { if (inside == -1) return false; let $pos = view.state.doc.resolve(inside), node2 = $pos.nodeAfter; if (node2 && node2.isAtom && NodeSelection.isSelectable(node2)) { updateSelection(view, new NodeSelection($pos), "pointer"); 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 i3 = $pos.depth + 1; i3 > 0; i3--) { let node2 = i3 > $pos.depth ? $pos.nodeAfter : $pos.node(i3); if (NodeSelection.isSelectable(node2)) { if (selectedNode && sel.$from.depth > 0 && i3 >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos) selectAt = $pos.before(sel.$from.depth); else selectAt = $pos.before(i3); break; } } if (selectAt != null) { updateSelection(view, NodeSelection.create(view.state.doc, selectAt), "pointer"); return true; } else { return false; } } function handleSingleClick(view, pos, inside, event, selectNode) { return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f6) => f6(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", (f6) => f6(view, pos, event)); } function handleTripleClick(view, pos, inside, event) { return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f6) => f6(view, pos, event)) || defaultTripleClick(view, inside, event); } function defaultTripleClick(view, inside, event) { if (event.button != 0) return false; let doc4 = view.state.doc; if (inside == -1) { if (doc4.inlineContent) { updateSelection(view, TextSelection.create(doc4, 0, doc4.content.size), "pointer"); return true; } return false; } let $pos = doc4.resolve(inside); for (let i3 = $pos.depth + 1; i3 > 0; i3--) { let node2 = i3 > $pos.depth ? $pos.nodeAfter : $pos.node(i3); let nodePos = $pos.before(i3); if (node2.inlineContent) updateSelection(view, TextSelection.create(doc4, nodePos + 1, nodePos + 1 + node2.content.size), "pointer"); else if (NodeSelection.isSelectable(node2)) updateSelection(view, NodeSelection.create(doc4, nodePos), "pointer"); else continue; return true; } } function forceDOMFlush(view) { return endComposition(view); } var selectNodeModifier = mac ? "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 }; let pos = view.posAtCoords(eventCoords(event)); if (!pos) return; if (type == "singleClick") { if (view.input.mouseDown) view.input.mouseDown.done(); view.input.mouseDown = new MouseDown(view, pos, event, !!flushed); } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) { event.preventDefault(); } else { setSelectionOrigin(view, "pointer"); } }; var MouseDown = class { constructor(view, pos, event, flushed) { this.view = view; this.pos = pos; this.event = event; this.flushed = flushed; this.delayedSelectionSync = false; this.mightDrag = null; 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(); } view.root.addEventListener("mouseup", this.up = this.up.bind(this)); view.root.addEventListener("mousemove", this.move = this.move.bind(this)); setSelectionOrigin(view, "pointer"); } done() { this.view.root.removeEventListener("mouseup", this.up); this.view.root.removeEventListener("mousemove", this.move); 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(() => selectionToDOM(this.view)); this.view.input.mouseDown = null; } 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)), "pointer"); event.preventDefault(); } else { setSelectionOrigin(this.view, "pointer"); } } move(event) { this.updateAllowDefault(event); setSelectionOrigin(this.view, "pointer"); if (event.buttons == 0) this.done(); } updateAllowDefault(event) { if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4)) this.allowDefault = true; } }; 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(event.timeStamp - view.input.compositionEndedAt) < 500) { view.input.compositionEndedAt = -2e8; return true; } return false; } var 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((m2) => m2.type.spec.inclusive === false) || chrome && windows && 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 node2 = sel.focusNode, offset4 = sel.focusOffset; node2 && node2.nodeType == 1 && offset4 != 0; ) { let before = offset4 < 0 ? node2.lastChild : node2.childNodes[offset4 - 1]; if (!before) break; if (before.nodeType == 3) { let sel2 = view.domSelection(); if (sel2) sel2.collapse(before, before.nodeValue.length); break; } else { node2 = before; offset4 = -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 next2 = focusNode.childNodes[focusOffset]; return next2.nodeType == 1 && next2.contentEditable == "false"; } editHandlers.compositionend = (view, event) => { if (view.composing) { view.input.composing = false; view.input.compositionEndedAt = event.timeStamp; view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0; view.input.compositionNode = null; 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 = timestampFromCustomEvent(); } while (view.input.compositionNodes.length > 0) view.input.compositionNodes.pop().markParentsDirty(); } function findCompositionNode(view) { let sel = view.domSelectionRange(); if (!sel.focusNode) return null; let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset); let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset); if (textBefore && textAfter && textBefore != textAfter) { let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode; if (textBefore == lastChanged || textAfter == lastChanged) return lastChanged; if (!descAfter || !descAfter.isText(textAfter.nodeValue)) { return textAfter; } else if (view.input.compositionNode == textAfter) { let descBefore = textBefore.pmViewDesc; if (!(!descBefore || !descBefore.isText(textBefore.nodeValue))) return textAfter; } } return textBefore || textAfter; } function timestampFromCustomEvent() { let event = document.createEvent("Event"); event.initEvent("event", true, true); return event.timeStamp; } 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 wrap5 = view.dom.parentNode.appendChild(document.createElement("div")); wrap5.appendChild(dom); wrap5.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 (wrap5.parentNode) wrap5.parentNode.removeChild(wrap5); view.focus(); }, 50); } var brokenClipboardAPI = ie && 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: text10 } = serializeForClipboard(view, slice2); if (data) { event.preventDefault(); data.clearData(); data.setData("text/html", dom.innerHTML); data.setData("text/plain", text10); } 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, text10, html7, preferPlain, event) { let slice2 = parseFromClipboard(view, text10, html7, preferPlain, view.state.selection.$from); if (view.someProp("handlePaste", (f6) => f6(view, event, slice2 || Slice.empty))) return true; if (!slice2) return false; let singleNode = sliceSingleNode(slice2); let tr4 = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice2); view.dispatch(tr4.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste")); return true; } function getText(clipboardData) { let text10 = clipboardData.getData("text/plain") || clipboardData.getData("Text"); if (text10) return text10; 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); }; var Dragging = class { constructor(slice2, move, node2) { this.slice = slice2; this.move = move; this.node = node2; } }; var dragCopyModifier = mac ? "altKey" : "ctrlKey"; function dragMoves(view, event) { let moves = view.someProp("dragCopies", (test) => !test(event)); return moves != null ? moves : !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 node2; if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ; else if (mouseDown && mouseDown.mightDrag) { node2 = 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) node2 = NodeSelection.create(view.state.doc, desc.posBefore); } let draggedSlice = (node2 || view.state.selection).content(); let { dom, text: text10, 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", text10); view.dragging = new Dragging(slice2, dragMoves(view, event), node2); }; handlers.dragend = (view) => { let dragging = view.dragging; window.setTimeout(() => { if (view.dragging == dragging) view.dragging = null; }, 50); }; editHandlers.dragover = editHandlers.dragenter = (_2, e2) => e2.preventDefault(); editHandlers.drop = (view, event) => { try { handleDrop(view, event, view.dragging); } finally { view.dragging = null; } }; function handleDrop(view, event, dragging) { if (!event.dataTransfer) return; let eventPos = view.posAtCoords(eventCoords(event)); if (!eventPos) return; let $mouse = view.state.doc.resolve(eventPos.pos); let slice2 = dragging && dragging.slice; if (slice2) { view.someProp("transformPasted", (f6) => { slice2 = f6(slice2, view, false); }); } else { slice2 = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"), false, $mouse); } let move = !!(dragging && dragMoves(view, event)); if (view.someProp("handleDrop", (f6) => f6(view, event, slice2 || Slice.empty, move))) { 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 tr4 = view.state.tr; if (move) { let { node: node2 } = dragging; if (node2) node2.replace(tr4); else tr4.deleteSelection(); } let pos = tr4.mapping.map(insertPos); let isNode3 = slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1; let beforeInsert = tr4.doc; if (isNode3) tr4.replaceRangeWith(pos, pos, slice2.content.firstChild); else tr4.replaceRange(pos, pos, slice2); if (tr4.doc.eq(beforeInsert)) return; let $pos = tr4.doc.resolve(pos); if (isNode3 && NodeSelection.isSelectable(slice2.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice2.content.firstChild)) { tr4.setSelection(new NodeSelection($pos)); } else { let end = tr4.mapping.map(insertPos); tr4.mapping.maps[tr4.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo); tr4.setSelection(selectionBetween(view, $pos, tr4.doc.resolve(end))); } view.focus(); view.dispatch(tr4.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 (chrome && 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", (f6) => f6(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(a3, b4) { if (a3 == b4) return true; for (let p4 in a3) if (a3[p4] !== b4[p4]) return false; for (let p4 in b4) if (!(p4 in a3)) return false; return true; } var WidgetType = class _WidgetType { constructor(toDOM, spec) { this.toDOM = toDOM; this.spec = spec || noSpec; this.side = this.spec.side || 0; } map(mapping, span, offset4, oldOffset) { let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1); return deleted ? null : new Decoration(pos - offset4, pos - offset4, 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(node2) { if (this.spec.destroy) this.spec.destroy(node2); } }; var InlineType = class _InlineType { constructor(attrs, spec) { this.attrs = attrs; this.spec = spec || noSpec; } map(mapping, span, offset4, oldOffset) { let from4 = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset4; let to2 = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset4; return from4 >= to2 ? null : new Decoration(from4, to2, this); } valid(_2, 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() { } }; var NodeType2 = class _NodeType { constructor(attrs, spec) { this.attrs = attrs; this.spec = spec || noSpec; } map(mapping, span, offset4, oldOffset) { let from4 = mapping.mapResult(span.from + oldOffset, 1); if (from4.deleted) return null; let to2 = mapping.mapResult(span.to + oldOffset, -1); if (to2.deleted || to2.pos <= from4.pos) return null; return new Decoration(from4.pos - offset4, to2.pos - offset4, this); } valid(node2, span) { let { index: index4, offset: offset4 } = node2.content.findIndex(span.from), child; return offset4 == span.from && !(child = node2.child(index4)).isText && offset4 + child.nodeSize == span.to; } eq(other) { return this == other || other instanceof _NodeType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec); } destroy() { } }; var Decoration = class _Decoration { /** @internal */ constructor(from4, to2, type) { this.from = from4; this.to = to2; this.type = type; } /** @internal */ copy(from4, to2) { return new _Decoration(from4, to2, this.type); } /** @internal */ eq(other, offset4 = 0) { return this.type.eq(other.type) && this.from + offset4 == other.from && this.to + offset4 == other.to; } /** @internal */ map(mapping, offset4, oldOffset) { return this.type.map(mapping, this, offset4, 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(from4, to2, attrs, spec) { return new _Decoration(from4, to2, 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(from4, to2, attrs, spec) { return new _Decoration(from4, to2, 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; } }; var none = []; var noSpec = {}; var DecorationSet = 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(doc4, decorations) { return decorations.length ? buildTree(decorations, doc4, 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, offset4, predicate) { for (let i3 = 0; i3 < this.local.length; i3++) { let span = this.local[i3]; if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec))) result.push(span.copy(span.from + offset4, span.to + offset4)); } for (let i3 = 0; i3 < this.children.length; i3 += 3) { if (this.children[i3] < end && this.children[i3 + 1] > start) { let childOff = this.children[i3] + 1; this.children[i3 + 2].findInner(start - childOff, end - childOff, result, offset4 + childOff, predicate); } } } /** Map the set of decorations in response to a change in the document. */ map(mapping, doc4, options2) { if (this == empty || mapping.maps.length == 0) return this; return this.mapInner(mapping, doc4, 0, 0, options2 || noSpec); } /** @internal */ mapInner(mapping, node2, offset4, oldOffset, options2) { let newLocal; for (let i3 = 0; i3 < this.local.length; i3++) { let mapped = this.local[i3].map(mapping, offset4, oldOffset); if (mapped && mapped.type.valid(node2, mapped)) (newLocal || (newLocal = [])).push(mapped); else if (options2.onRemove) options2.onRemove(this.local[i3].spec); } if (this.children.length) return mapChildren(this.children, newLocal || [], mapping, node2, offset4, oldOffset, options2); 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(doc4, decorations) { if (!decorations.length) return this; if (this == empty) return _DecorationSet.create(doc4, decorations); return this.addInner(doc4, decorations, 0); } addInner(doc4, decorations, offset4) { let children, childIndex = 0; doc4.forEach((childNode, childOffset) => { let baseOffset = childOffset + offset4, 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, -offset4); for (let i3 = 0; i3 < local.length; i3++) if (!local[i3].type.valid(doc4, local[i3])) local.splice(i3--, 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, offset4) { let children = this.children, local = this.local; for (let i3 = 0; i3 < children.length; i3 += 3) { let found2; let from4 = children[i3] + offset4, to2 = children[i3 + 1] + offset4; for (let j4 = 0, span; j4 < decorations.length; j4++) if (span = decorations[j4]) { if (span.from > from4 && span.to < to2) { decorations[j4] = null; (found2 || (found2 = [])).push(span); } } if (!found2) continue; if (children == this.children) children = this.children.slice(); let removed = children[i3 + 2].removeInner(found2, from4 + 1); if (removed != empty) { children[i3 + 2] = removed; } else { children.splice(i3, 3); i3 -= 3; } } if (local.length) { for (let i3 = 0, span; i3 < decorations.length; i3++) if (span = decorations[i3]) { for (let j4 = 0; j4 < local.length; j4++) if (local[j4].eq(span, offset4)) { if (local == this.local) local = this.local.slice(); local.splice(j4--, 1); } } } if (children == this.children && local == this.local) return this; return local.length || children.length ? new _DecorationSet(local, children) : empty; } forChild(offset4, node2) { if (this == empty) return this; if (node2.isLeaf) return _DecorationSet.empty; let child, local; for (let i3 = 0; i3 < this.children.length; i3 += 3) if (this.children[i3] >= offset4) { if (this.children[i3] == offset4) child = this.children[i3 + 2]; break; } let start = offset4 + 1, end = start + node2.content.size; for (let i3 = 0; i3 < this.local.length; i3++) { let dec = this.local[i3]; if (dec.from < end && dec.to > start && dec.type instanceof InlineType) { let from4 = Math.max(start, dec.from) - start, to2 = Math.min(end, dec.to) - start; if (from4 < to2) (local || (local = [])).push(dec.copy(from4, to2)); } } 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 i3 = 0; i3 < this.local.length; i3++) if (!this.local[i3].eq(other.local[i3])) return false; for (let i3 = 0; i3 < this.children.length; i3 += 3) if (this.children[i3] != other.children[i3] || this.children[i3 + 1] != other.children[i3 + 1] || !this.children[i3 + 2].eq(other.children[i3 + 2])) return false; return true; } /** @internal */ locals(node2) { return removeOverlap(this.localsInner(node2)); } /** @internal */ localsInner(node2) { if (this == empty) return none; if (node2.inlineContent || !this.local.some(InlineType.is)) return this.local; let result = []; for (let i3 = 0; i3 < this.local.length; i3++) { if (!(this.local[i3].type instanceof InlineType)) result.push(this.local[i3]); } return result; } forEachSet(f6) { f6(this); } }; DecorationSet.empty = new DecorationSet([], []); DecorationSet.removeOverlap = removeOverlap; var empty = DecorationSet.empty; var DecorationGroup = class _DecorationGroup { constructor(members) { this.members = members; } map(mapping, doc4) { const mappedDecos = this.members.map((member) => member.map(mapping, doc4, noSpec)); return _DecorationGroup.from(mappedDecos); } forChild(offset4, child) { if (child.isLeaf) return DecorationSet.empty; let found2 = []; for (let i3 = 0; i3 < this.members.length; i3++) { let result = this.members[i3].forChild(offset4, 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 i3 = 0; i3 < this.members.length; i3++) if (!this.members[i3].eq(other.members[i3])) return false; return true; } locals(node2) { let result, sorted = true; for (let i3 = 0; i3 < this.members.length; i3++) { let locals = this.members[i3].localsInner(node2); if (!locals.length) continue; if (!result) { result = locals; } else { if (sorted) { result = result.slice(); sorted = false; } for (let j4 = 0; j4 < locals.length; j4++) result.push(locals[j4]); } } 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((m2) => m2 instanceof DecorationSet) ? members : members.reduce((r4, m2) => r4.concat(m2 instanceof DecorationSet ? m2 : m2.members), [])); } } forEachSet(f6) { for (let i3 = 0; i3 < this.members.length; i3++) this.members[i3].forEachSet(f6); } }; function mapChildren(oldChildren, newLocal, mapping, node2, offset4, oldOffset, options2) { let children = oldChildren.slice(); for (let i3 = 0, baseOffset = oldOffset; i3 < mapping.maps.length; i3++) { let moved = 0; mapping.maps[i3].forEach((oldStart, oldEnd, newStart, newEnd) => { let dSize = newEnd - newStart - (oldEnd - oldStart); for (let i4 = 0; i4 < children.length; i4 += 3) { let end = children[i4 + 1]; if (end < 0 || oldStart > end + baseOffset - moved) continue; let start = children[i4] + baseOffset - moved; if (oldEnd >= start) { children[i4 + 1] = oldStart <= start ? -2 : -1; } else if (oldStart >= baseOffset && dSize) { children[i4] += dSize; children[i4 + 1] += dSize; } } moved += dSize; }); baseOffset = mapping.maps[i3].map(baseOffset, -1); } let mustRebuild = false; for (let i3 = 0; i3 < children.length; i3 += 3) if (children[i3 + 1] < 0) { if (children[i3 + 1] == -2) { mustRebuild = true; children[i3 + 1] = -1; continue; } let from4 = mapping.map(oldChildren[i3] + oldOffset), fromLocal = from4 - offset4; if (fromLocal < 0 || fromLocal >= node2.content.size) { mustRebuild = true; continue; } let to2 = mapping.map(oldChildren[i3 + 1] + oldOffset, -1), toLocal = to2 - offset4; let { index: index4, offset: childOffset } = node2.content.findIndex(fromLocal); let childNode = node2.maybeChild(index4); if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) { let mapped = children[i3 + 2].mapInner(mapping, childNode, from4 + 1, oldChildren[i3] + oldOffset + 1, options2); if (mapped != empty) { children[i3] = fromLocal; children[i3 + 1] = toLocal; children[i3 + 2] = mapped; } else { children[i3 + 1] = -2; mustRebuild = true; } } else { mustRebuild = true; } } if (mustRebuild) { let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset4, oldOffset, options2); let built = buildTree(decorations, node2, 0, options2); newLocal = built.local; for (let i3 = 0; i3 < children.length; i3 += 3) if (children[i3 + 1] < 0) { children.splice(i3, 3); i3 -= 3; } for (let i3 = 0, j4 = 0; i3 < built.children.length; i3 += 3) { let from4 = built.children[i3]; while (j4 < children.length && children[j4] < from4) j4 += 3; children.splice(j4, 0, built.children[i3], built.children[i3 + 1], built.children[i3 + 2]); } } return new DecorationSet(newLocal.sort(byPos), children); } function moveSpans(spans, offset4) { if (!offset4 || !spans.length) return spans; let result = []; for (let i3 = 0; i3 < spans.length; i3++) { let span = spans[i3]; result.push(new Decoration(span.from + offset4, span.to + offset4, span.type)); } return result; } function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset4, oldOffset, options2) { function gather(set, oldOffset2) { for (let i3 = 0; i3 < set.local.length; i3++) { let mapped = set.local[i3].map(mapping, offset4, oldOffset2); if (mapped) decorations.push(mapped); else if (options2.onRemove) options2.onRemove(set.local[i3].spec); } for (let i3 = 0; i3 < set.children.length; i3 += 3) gather(set.children[i3 + 2], set.children[i3] + oldOffset2 + 1); } for (let i3 = 0; i3 < children.length; i3 += 3) if (children[i3 + 1] == -1) gather(children[i3 + 2], oldChildren[i3] + oldOffset + 1); return decorations; } function takeSpansForNode(spans, node2, offset4) { if (node2.isLeaf) return null; let end = offset4 + node2.nodeSize, found2 = null; for (let i3 = 0, span; i3 < spans.length; i3++) { if ((span = spans[i3]) && span.from > offset4 && span.to < end) { (found2 || (found2 = [])).push(span); spans[i3] = null; } } return found2; } function withoutNulls(array) { let result = []; for (let i3 = 0; i3 < array.length; i3++) if (array[i3] != null) result.push(array[i3]); return result; } function buildTree(spans, node2, offset4, options2) { let children = [], hasNulls = false; node2.forEach((childNode, localStart) => { let found2 = takeSpansForNode(spans, childNode, localStart + offset4); if (found2) { hasNulls = true; let subtree = buildTree(found2, childNode, offset4 + localStart + 1, options2); if (subtree != empty) children.push(localStart, localStart + childNode.nodeSize, subtree); } }); let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset4).sort(byPos); for (let i3 = 0; i3 < locals.length; i3++) if (!locals[i3].type.valid(node2, locals[i3])) { if (options2.onRemove) options2.onRemove(locals[i3].spec); locals.splice(i3--, 1); } return locals.length || children.length ? new DecorationSet(locals, children) : empty; } function byPos(a3, b4) { return a3.from - b4.from || a3.to - b4.to; } function removeOverlap(spans) { let working = spans; for (let i3 = 0; i3 < working.length - 1; i3++) { let span = working[i3]; if (span.from != span.to) for (let j4 = i3 + 1; j4 < working.length; j4++) { let next2 = working[j4]; if (next2.from == span.from) { if (next2.to != span.to) { if (working == spans) working = spans.slice(); working[j4] = next2.copy(next2.from, span.to); insertAhead(working, j4 + 1, next2.copy(span.to, next2.to)); } continue; } else { if (next2.from < span.to) { if (working == spans) working = spans.slice(); working[i3] = span.copy(span.from, next2.from); insertAhead(working, j4, span.copy(next2.from, span.to)); } break; } } } return working; } function insertAhead(array, i3, deco) { while (i3 < array.length && byPos(deco, array[i3]) > 0) i3++; array.splice(i3, 0, deco); } function viewDecorations(view) { let found2 = []; view.someProp("decorations", (f6) => { let result = f6(view.state); if (result && result != empty) found2.push(result); }); if (view.cursorWrapper) found2.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco])); return DecorationGroup.from(found2); } var observeOptions = { childList: true, characterData: true, characterDataOldValue: true, attributes: true, attributeOldValue: true, subtree: true }; var useCharData = ie && ie_version <= 11; var SelectionState = class { constructor() { this.anchorNode = null; this.anchorOffset = 0; this.focusNode = null; this.focusOffset = 0; } set(sel) { this.anchorNode = sel.anchorNode; this.anchorOffset = sel.anchorOffset; this.focusNode = sel.focusNode; this.focusOffset = sel.focusOffset; } clear() { this.anchorNode = this.focusNode = null; } eq(sel) { return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset; } }; var DOMObserver = class { constructor(view, handleDOMChange) { this.view = view; this.handleDOMChange = handleDOMChange; this.queue = []; this.flushingSoon = -1; this.observer = null; this.currentSelection = new SelectionState(); this.onCharData = null; this.suppressingSelectionUpdates = false; this.lastChangedTextNode = null; this.observer = window.MutationObserver && new window.MutationObserver((mutations) => { for (let i3 = 0; i3 < mutations.length; i3++) this.queue.push(mutations[i3]); if (ie && ie_version <= 11 && mutations.some((m2) => m2.type == "childList" && m2.removedNodes.length || m2.type == "characterData" && m2.oldValue.length > m2.target.nodeValue.length)) this.flushSoon(); else this.flush(); }); if (useCharData) { this.onCharData = (e2) => { this.queue.push({ target: e2.target, type: "characterData", oldValue: e2.prevValue }); this.flushSoon(); }; } this.onSelectionChange = this.onSelectionChange.bind(this); } flushSoon() { if (this.flushingSoon < 0) this.flushingSoon = window.setTimeout(() => { this.flushingSoon = -1; this.flush(); }, 20); } forceFlush() { if (this.flushingSoon > -1) { window.clearTimeout(this.flushingSoon); this.flushingSoon = -1; this.flush(); } } start() { if (this.observer) { this.observer.takeRecords(); this.observer.observe(this.view.dom, observeOptions); } if (this.onCharData) this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData); this.connectSelection(); } stop() { if (this.observer) { let take = this.observer.takeRecords(); if (take.length) { for (let i3 = 0; i3 < take.length; i3++) this.queue.push(take[i3]); window.setTimeout(() => this.flush(), 20); } this.observer.disconnect(); } if (this.onCharData) this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); this.disconnectSelection(); } connectSelection() { this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange); } disconnectSelection() { this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange); } suppressSelectionUpdates() { this.suppressingSelectionUpdates = true; setTimeout(() => this.suppressingSelectionUpdates = false, 50); } onSelectionChange() { if (!hasFocusAndSelection(this.view)) return; if (this.suppressingSelectionUpdates) return selectionToDOM(this.view); if (ie && ie_version <= 11 && !this.view.state.selection.empty) { let sel = this.view.domSelectionRange(); if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) return this.flushSoon(); } this.flush(); } setCurSelection() { this.currentSelection.set(this.view.domSelectionRange()); } ignoreSelectionChange(sel) { if (!sel.focusNode) return true; let ancestors = /* @__PURE__ */ new Set(), container; for (let scan = sel.focusNode; scan; scan = parentNode(scan)) ancestors.add(scan); for (let scan = sel.anchorNode; scan; scan = parentNode(scan)) if (ancestors.has(scan)) { container = scan; break; } let desc = container && this.view.docView.nearestDesc(container); if (desc && desc.ignoreMutation({ type: "selection", target: container.nodeType == 3 ? container.parentNode : container })) { this.setCurSelection(); return true; } } pendingRecords() { if (this.observer) for (let mut of this.observer.takeRecords()) this.queue.push(mut); return this.queue; } flush() { let { view } = this; if (!view.docView || this.flushingSoon > -1) return; let mutations = this.pendingRecords(); if (mutations.length) this.queue = []; let sel = view.domSelectionRange(); let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel); let from4 = -1, to2 = -1, typeOver = false, added = []; if (view.editable) { for (let i3 = 0; i3 < mutations.length; i3++) { let result = this.registerMutation(mutations[i3], added); if (result) { from4 = from4 < 0 ? result.from : Math.min(result.from, from4); to2 = to2 < 0 ? result.to : Math.max(result.to, to2); if (result.typeOver) typeOver = true; } } } if (gecko && added.length) { let brs = added.filter((n) => n.nodeName == "BR"); if (brs.length == 2) { let [a3, b4] = brs; if (a3.parentNode && a3.parentNode.parentNode == b4.parentNode) b4.remove(); else a3.remove(); } else { let { focusNode } = this.currentSelection; for (let br4 of brs) { let parent = br4.parentNode; if (parent && parent.nodeName == "LI" && (!focusNode || blockParent(view, focusNode) != parent)) br4.remove(); } } } else if ((chrome || safari) && added.some((n) => n.nodeName == "BR") && (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46)) { for (let node2 of added) if (node2.nodeName == "BR" && node2.parentNode) { let after = node2.nextSibling; if (after && after.nodeType == 1 && after.contentEditable == "false") node2.parentNode.removeChild(node2); } } let readSel = null; if (from4 < 0 && newSel && view.input.lastFocus > Date.now() - 200 && Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 && selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) && readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) { view.input.lastFocus = 0; selectionToDOM(view); this.currentSelection.set(sel); view.scrollToSelection(); } else if (from4 > -1 || newSel) { if (from4 > -1) { view.docView.markDirty(from4, to2); checkCSS(view); } this.handleDOMChange(from4, to2, typeOver, added); if (view.docView && view.docView.dirty) view.updateState(view.state); else if (!this.currentSelection.eq(sel)) selectionToDOM(view); this.currentSelection.set(sel); } } registerMutation(mut, added) { if (added.indexOf(mut.target) > -1) return null; let desc = this.view.docView.nearestDesc(mut.target); if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style"))) return null; if (!desc || desc.ignoreMutation(mut)) return null; if (mut.type == "childList") { for (let i3 = 0; i3 < mut.addedNodes.length; i3++) { let node2 = mut.addedNodes[i3]; added.push(node2); if (node2.nodeType == 3) this.lastChangedTextNode = node2; } if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target)) return { from: desc.posBefore, to: desc.posAfter }; let prev = mut.previousSibling, next2 = mut.nextSibling; if (ie && ie_version <= 11 && mut.addedNodes.length) { for (let i3 = 0; i3 < mut.addedNodes.length; i3++) { let { previousSibling, nextSibling } = mut.addedNodes[i3]; if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0) prev = previousSibling; if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0) next2 = nextSibling; } } let fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0; let from4 = desc.localPosFromDOM(mut.target, fromOffset, -1); let toOffset = next2 && next2.parentNode == mut.target ? domIndex(next2) : mut.target.childNodes.length; let to2 = desc.localPosFromDOM(mut.target, toOffset, 1); return { from: from4, to: to2 }; } else if (mut.type == "attributes") { return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border }; } else { this.lastChangedTextNode = mut.target; return { from: desc.posAtStart, to: desc.posAtEnd, // An event was generated for a text change that didn't change // any text. Mark the dom change to fall back to assuming the // selection was typed over with an identical value if it can't // find another change. typeOver: mut.target.nodeValue == mut.oldValue }; } } }; var cssChecked = /* @__PURE__ */ new WeakMap(); var cssCheckWarned = false; function checkCSS(view) { if (cssChecked.has(view)) return; cssChecked.set(view, null); if (["normal", "nowrap", "pre-line"].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) { view.requiresGeckoHackNode = gecko; if (cssCheckWarned) return; console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."); cssCheckWarned = true; } } function rangeToSelectionRange(view, range) { let anchorNode = range.startContainer, anchorOffset = range.startOffset; let focusNode = range.endContainer, focusOffset = range.endOffset; let currentAnchor = view.domAtPos(view.state.selection.anchor); if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset)) [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]; return { anchorNode, anchorOffset, focusNode, focusOffset }; } function safariShadowSelectionRange(view, selection) { if (selection.getComposedRanges) { let range = selection.getComposedRanges(view.root)[0]; if (range) return rangeToSelectionRange(view, range); } let found2; function read(event) { event.preventDefault(); event.stopImmediatePropagation(); found2 = event.getTargetRanges()[0]; } view.dom.addEventListener("beforeinput", read, true); document.execCommand("indent"); view.dom.removeEventListener("beforeinput", read, true); return found2 ? rangeToSelectionRange(view, found2) : null; } function blockParent(view, node2) { for (let p4 = node2.parentNode; p4 && p4 != view.dom; p4 = p4.parentNode) { let desc = view.docView.nearestDesc(p4, true); if (desc && desc.node.isBlock) return p4; } return null; } function parseBetween(view, from_, to_) { let { node: parent, fromOffset, toOffset, from: from4, to: to2 } = view.docView.parseRange(from_, to_); let domSel = view.domSelectionRange(); let find4; let anchor = domSel.anchorNode; if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) { find4 = [{ node: anchor, offset: domSel.anchorOffset }]; if (!selectionCollapsed(domSel)) find4.push({ node: domSel.focusNode, offset: domSel.focusOffset }); } if (chrome && view.input.lastKeyCode === 8) { for (let off = toOffset; off > fromOffset; off--) { let node2 = parent.childNodes[off - 1], desc = node2.pmViewDesc; if (node2.nodeName == "BR" && !desc) { toOffset = off; break; } if (!desc || desc.size) break; } } let startDoc = view.state.doc; let parser = view.someProp("domParser") || DOMParser2.fromSchema(view.state.schema); let $from = startDoc.resolve(from4); let sel = null, doc4 = parser.parse(parent, { topNode: $from.parent, topMatch: $from.parent.contentMatchAt($from.index()), topOpen: true, from: fromOffset, to: toOffset, preserveWhitespace: $from.parent.type.whitespace == "pre" ? "full" : true, findPositions: find4, ruleFromNode, context: $from }); if (find4 && find4[0].pos != null) { let anchor2 = find4[0].pos, head2 = find4[1] && find4[1].pos; if (head2 == null) head2 = anchor2; sel = { anchor: anchor2 + from4, head: head2 + from4 }; } return { doc: doc4, sel, from: from4, to: to2 }; } function ruleFromNode(dom) { let desc = dom.pmViewDesc; if (desc) { return desc.parseRule(); } else if (dom.nodeName == "BR" && dom.parentNode) { if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) { let skip = document.createElement("div"); skip.appendChild(document.createElement("li")); return { skip }; } else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) { return { ignore: true }; } } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) { return { ignore: true }; } return null; } var isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i; function readDOMChange(view, from4, to2, typeOver, addedNodes) { let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0); view.input.compositionPendingChanges = 0; if (from4 < 0) { let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null; let newSel = selectionFromDOM(view, origin); if (newSel && !view.state.selection.eq(newSel)) { if (chrome && android && view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime && view.someProp("handleKeyDown", (f6) => f6(view, keyEvent(13, "Enter")))) return; let tr4 = view.state.tr.setSelection(newSel); if (origin == "pointer") tr4.setMeta("pointer", true); else if (origin == "key") tr4.scrollIntoView(); if (compositionID) tr4.setMeta("composition", compositionID); view.dispatch(tr4); } return; } let $before = view.state.doc.resolve(from4); let shared = $before.sharedDepth(to2); from4 = $before.before(shared + 1); to2 = view.state.doc.resolve(to2).after(shared + 1); let sel = view.state.selection; let parse6 = parseBetween(view, from4, to2); let doc4 = view.state.doc, compare = doc4.slice(parse6.from, parse6.to); let preferredPos, preferredSide; if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) { preferredPos = view.state.selection.to; preferredSide = "end"; } else { preferredPos = view.state.selection.from; preferredSide = "start"; } view.input.lastKeyCode = null; let change = findDiff(compare.content, parse6.doc.content, parse6.from, preferredPos, preferredSide); if (change) view.input.domChangeCount++; if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) && addedNodes.some((n) => n.nodeType == 1 && !isInline.test(n.nodeName)) && (!change || change.endA >= change.endB) && view.someProp("handleKeyDown", (f6) => f6(view, keyEvent(13, "Enter")))) { view.input.lastIOSEnter = 0; return; } if (!change) { if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse6.sel && parse6.sel.anchor != parse6.sel.head)) { change = { start: sel.from, endA: sel.to, endB: sel.to }; } else { if (parse6.sel) { let sel2 = resolveSelection(view, view.state.doc, parse6.sel); if (sel2 && !sel2.eq(view.state.selection)) { let tr4 = view.state.tr.setSelection(sel2); if (compositionID) tr4.setMeta("composition", compositionID); view.dispatch(tr4); } } return; } } if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof TextSelection) { if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 && view.state.selection.from >= parse6.from) { change.start = view.state.selection.from; } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 && view.state.selection.to <= parse6.to) { change.endB += view.state.selection.to - change.endA; change.endA = view.state.selection.to; } } if (ie && ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse6.from && parse6.doc.textBetween(change.start - parse6.from - 1, change.start - parse6.from + 1) == "  ") { change.start--; change.endA--; change.endB--; } let $from = parse6.doc.resolveNoCache(change.start - parse6.from); let $to = parse6.doc.resolveNoCache(change.endB - parse6.from); let $fromA = doc4.resolve(change.start); let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA; if ((ios && view.input.lastIOSEnter > Date.now() - 225 && (!inlineChange || addedNodes.some((n) => n.nodeName == "DIV" || n.nodeName == "P")) || !inlineChange && $from.pos < parse6.doc.content.size && (!$from.sameParent($to) || !$from.parent.inlineContent) && $from.pos < $to.pos && !/\S/.test(parse6.doc.textBetween($from.pos, $to.pos, "", ""))) && view.someProp("handleKeyDown", (f6) => f6(view, keyEvent(13, "Enter")))) { view.input.lastIOSEnter = 0; return; } if (view.state.selection.anchor > change.start && looksLikeBackspace(doc4, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", (f6) => f6(view, keyEvent(8, "Backspace")))) { if (android && chrome) view.domObserver.suppressSelectionUpdates(); return; } if (chrome && change.endB == change.start) view.input.lastChromeDelete = Date.now(); if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && parse6.sel && parse6.sel.anchor == parse6.sel.head && parse6.sel.head == change.endA) { change.endB -= 2; $to = parse6.doc.resolveNoCache(change.endB - parse6.from); setTimeout(() => { view.someProp("handleKeyDown", function(f6) { return f6(view, keyEvent(13, "Enter")); }); }, 20); } let chFrom = change.start, chTo = change.endA; let mkTr = (base4) => { let tr4 = base4 || view.state.tr.replace(chFrom, chTo, parse6.doc.slice(change.start - parse6.from, change.endB - parse6.from)); if (parse6.sel) { let sel2 = resolveSelection(view, tr4.doc, parse6.sel); if (sel2 && !(chrome && view.composing && sel2.empty && (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) && (sel2.head == chFrom || sel2.head == tr4.mapping.map(chTo) - 1) || ie && sel2.empty && sel2.head == chFrom)) tr4.setSelection(sel2); } if (compositionID) tr4.setMeta("composition", compositionID); return tr4.scrollIntoView(); }; let markChange; if (inlineChange) { if ($from.pos == $to.pos) { if (ie && ie_version <= 11 && $from.parentOffset == 0) { view.domObserver.suppressSelectionUpdates(); setTimeout(() => selectionToDOM(view), 20); } let tr4 = mkTr(view.state.tr.delete(chFrom, chTo)); let marks = doc4.resolve(change.start).marksAcross(doc4.resolve(change.endA)); if (marks) tr4.ensureMarks(marks); view.dispatch(tr4); } else if ( // Adding or removing a mark change.endA == change.endB && (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start()))) ) { let tr4 = mkTr(view.state.tr); if (markChange.type == "add") tr4.addMark(chFrom, chTo, markChange.mark); else tr4.removeMark(chFrom, chTo, markChange.mark); view.dispatch(tr4); } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) { let text10 = $from.parent.textBetween($from.parentOffset, $to.parentOffset); let deflt = () => mkTr(view.state.tr.insertText(text10, chFrom, chTo)); if (!view.someProp("handleTextInput", (f6) => f6(view, chFrom, chTo, text10, deflt))) view.dispatch(deflt()); } else { view.dispatch(mkTr()); } } else { view.dispatch(mkTr()); } } function resolveSelection(view, doc4, parsedSel) { if (Math.max(parsedSel.anchor, parsedSel.head) > doc4.content.size) return null; return selectionBetween(view, doc4.resolve(parsedSel.anchor), doc4.resolve(parsedSel.head)); } function isMarkChange(cur, prev) { let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks; let added = curMarks, removed = prevMarks, type, mark2, update; for (let i3 = 0; i3 < prevMarks.length; i3++) added = prevMarks[i3].removeFromSet(added); for (let i3 = 0; i3 < curMarks.length; i3++) removed = curMarks[i3].removeFromSet(removed); if (added.length == 1 && removed.length == 0) { mark2 = added[0]; type = "add"; update = (node2) => node2.mark(mark2.addToSet(node2.marks)); } else if (added.length == 0 && removed.length == 1) { mark2 = removed[0]; type = "remove"; update = (node2) => node2.mark(mark2.removeFromSet(node2.marks)); } else { return null; } let updated = []; for (let i3 = 0; i3 < prev.childCount; i3++) updated.push(update(prev.child(i3))); if (Fragment.from(updated).eq(cur)) return { mark: mark2, type }; } function looksLikeBackspace(old, start, end, $newStart, $newEnd) { if ( // The content must have shrunk end - start <= $newEnd.pos - $newStart.pos || // newEnd must point directly at or after the end of the block that newStart points into skipClosingAndOpening($newStart, true, false) < $newEnd.pos ) return false; let $start = old.resolve(start); if (!$newStart.parent.isTextblock) { let after = $start.nodeAfter; return after != null && end == start + after.nodeSize; } if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock) return false; let $next = old.resolve(skipClosingAndOpening($start, true, true)); if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end) return false; return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content); } function skipClosingAndOpening($pos, fromEnd, mayOpen) { let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos; while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) { depth--; end++; fromEnd = false; } if (mayOpen) { let next2 = $pos.node(depth).maybeChild($pos.indexAfter(depth)); while (next2 && !next2.isLeaf) { next2 = next2.firstChild; end++; } } return end; } function findDiff(a3, b4, pos, preferredPos, preferredSide) { let start = a3.findDiffStart(b4, pos); if (start == null) return null; let { a: endA, b: endB } = a3.findDiffEnd(b4, pos + a3.size, pos + b4.size); if (preferredSide == "end") { let adjust = Math.max(0, start - Math.min(endA, endB)); preferredPos -= endA + adjust - start; } if (endA < start && a3.size < b4.size) { let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0; start -= move; if (start && start < b4.size && isSurrogatePair(b4.textBetween(start - 1, start + 1))) start += move ? 1 : -1; endB = start + (endB - endA); endA = start; } else if (endB < start) { let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0; start -= move; if (start && start < a3.size && isSurrogatePair(a3.textBetween(start - 1, start + 1))) start += move ? 1 : -1; endA = start + (endA - endB); endB = start; } return { start, endA, endB }; } function isSurrogatePair(str) { if (str.length != 2) return false; let a3 = str.charCodeAt(0), b4 = str.charCodeAt(1); return a3 >= 56320 && a3 <= 57343 && b4 >= 55296 && b4 <= 56319; } var EditorView = class { /** Create a view. `place` may be a DOM node that the editor should be appended to, a function that will place it into the document, or an object whose `mount` property holds the node to use as the document container. If it is `null`, the editor will not be added to the document. */ constructor(place, props) { this._root = null; this.focused = false; this.trackWrites = null; this.mounted = false; this.markCursor = null; this.cursorWrapper = null; this.lastSelectedViewDesc = void 0; this.input = new InputState(); this.prevDirectPlugins = []; this.pluginViews = []; this.requiresGeckoHackNode = false; this.dragging = null; this._props = props; this.state = props.state; this.directPlugins = props.plugins || []; this.directPlugins.forEach(checkStateComponent); this.dispatch = this.dispatch.bind(this); this.dom = place && place.mount || document.createElement("div"); if (place) { if (place.appendChild) place.appendChild(this.dom); else if (typeof place == "function") place(this.dom); else if (place.mount) this.mounted = true; } this.editable = getEditable(this); updateCursorWrapper(this); this.nodeViews = buildNodeViews(this); this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this); this.domObserver = new DOMObserver(this, (from4, to2, typeOver, added) => readDOMChange(this, from4, to2, typeOver, added)); this.domObserver.start(); initInput(this); this.updatePluginViews(); } /** Holds `true` when a [composition](https://w3c.github.io/uievents/#events-compositionevents) is active. */ get composing() { return this.input.composing; } /** The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps). */ get props() { if (this._props.state != this.state) { let prev = this._props; this._props = {}; for (let name in prev) this._props[name] = prev[name]; this._props.state = this.state; } return this._props; } /** Update the view's props. Will immediately cause an update to the DOM. */ update(props) { if (props.handleDOMEvents != this._props.handleDOMEvents) ensureListeners(this); let prevProps = this._props; this._props = props; if (props.plugins) { props.plugins.forEach(checkStateComponent); this.directPlugins = props.plugins; } this.updateStateInner(props.state, prevProps); } /** Update the view by updating existing props object with the object given as argument. Equivalent to `view.update(Object.assign({}, view.props, props))`. */ setProps(props) { let updated = {}; for (let name in this._props) updated[name] = this._props[name]; updated.state = this.state; for (let name in props) updated[name] = props[name]; this.update(updated); } /** Update the editor's `state` prop, without touching any of the other props. */ updateState(state) { this.updateStateInner(state, this._props); } updateStateInner(state, prevProps) { var _a2; let prev = this.state, redraw = false, updateSel = false; if (state.storedMarks && this.composing) { clearComposition(this); updateSel = true; } this.state = state; let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins; if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) { let nodeViews = buildNodeViews(this); if (changedNodeViews(nodeViews, this.nodeViews)) { this.nodeViews = nodeViews; redraw = true; } } if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) { ensureListeners(this); } this.editable = getEditable(this); updateCursorWrapper(this); let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this); let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve"; let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco); if (updateDoc || !state.selection.eq(prev.selection)) updateSel = true; let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this); if (updateSel) { this.domObserver.stop(); let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection); if (updateDoc) { let chromeKludge = chrome ? this.trackWrites = this.domSelectionRange().focusNode : null; if (this.composing) this.input.compositionNode = findCompositionNode(this); if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) { this.docView.updateOuterDeco(outerDeco); this.docView.destroy(); this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this); } if (chromeKludge && !this.trackWrites) forceSelUpdate = true; } if (forceSelUpdate || !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && anchorInRightPlace(this))) { selectionToDOM(this, forceSelUpdate); } else { syncNodeSelection(this, state.selection); this.domObserver.setCurSelection(); } this.domObserver.start(); } this.updatePluginViews(prev); if (((_a2 = this.dragging) === null || _a2 === void 0 ? void 0 : _a2.node) && !prev.doc.eq(state.doc)) this.updateDraggedNode(this.dragging, prev); if (scroll == "reset") { this.dom.scrollTop = 0; } else if (scroll == "to selection") { this.scrollToSelection(); } else if (oldScrollPos) { resetScrollPos(oldScrollPos); } } /** @internal */ scrollToSelection() { let startDOM = this.domSelectionRange().focusNode; if (!startDOM || !this.dom.contains(startDOM.nodeType == 1 ? startDOM : startDOM.parentNode)) ; else if (this.someProp("handleScrollToSelection", (f6) => f6(this))) ; else if (this.state.selection instanceof NodeSelection) { let target = this.docView.domAfterPos(this.state.selection.from); if (target.nodeType == 1) scrollRectIntoView(this, target.getBoundingClientRect(), startDOM); } else { scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM); } } destroyPluginViews() { let view; while (view = this.pluginViews.pop()) if (view.destroy) view.destroy(); } updatePluginViews(prevState) { if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) { this.prevDirectPlugins = this.directPlugins; this.destroyPluginViews(); for (let i3 = 0; i3 < this.directPlugins.length; i3++) { let plugin = this.directPlugins[i3]; if (plugin.spec.view) this.pluginViews.push(plugin.spec.view(this)); } for (let i3 = 0; i3 < this.state.plugins.length; i3++) { let plugin = this.state.plugins[i3]; if (plugin.spec.view) this.pluginViews.push(plugin.spec.view(this)); } } else { for (let i3 = 0; i3 < this.pluginViews.length; i3++) { let pluginView = this.pluginViews[i3]; if (pluginView.update) pluginView.update(this, prevState); } } } updateDraggedNode(dragging, prev) { let sel = dragging.node, found2 = -1; if (this.state.doc.nodeAt(sel.from) == sel.node) { found2 = sel.from; } else { let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size); let moved = movedPos > 0 && this.state.doc.nodeAt(movedPos); if (moved == sel.node) found2 = movedPos; } this.dragging = new Dragging(dragging.slice, dragging.move, found2 < 0 ? void 0 : NodeSelection.create(this.state.doc, found2)); } someProp(propName, f6) { let prop = this._props && this._props[propName], value; if (prop != null && (value = f6 ? f6(prop) : prop)) return value; for (let i3 = 0; i3 < this.directPlugins.length; i3++) { let prop2 = this.directPlugins[i3].props[propName]; if (prop2 != null && (value = f6 ? f6(prop2) : prop2)) return value; } let plugins = this.state.plugins; if (plugins) for (let i3 = 0; i3 < plugins.length; i3++) { let prop2 = plugins[i3].props[propName]; if (prop2 != null && (value = f6 ? f6(prop2) : prop2)) return value; } } /** Query whether the view has focus. */ hasFocus() { if (ie) { let node2 = this.root.activeElement; if (node2 == this.dom) return true; if (!node2 || !this.dom.contains(node2)) return false; while (node2 && this.dom != node2 && this.dom.contains(node2)) { if (node2.contentEditable == "false") return false; node2 = node2.parentElement; } return true; } return this.root.activeElement == this.dom; } /** Focus the editor. */ focus() { this.domObserver.stop(); if (this.editable) focusPreventScroll(this.dom); selectionToDOM(this); this.domObserver.start(); } /** Get the document root in which the editor exists. This will usually be the top-level `document`, but might be a [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM) root if the editor is inside one. */ get root() { let cached = this._root; if (cached == null) for (let search3 = this.dom.parentNode; search3; search3 = search3.parentNode) { if (search3.nodeType == 9 || search3.nodeType == 11 && search3.host) { if (!search3.getSelection) Object.getPrototypeOf(search3).getSelection = () => search3.ownerDocument.getSelection(); return this._root = search3; } } return cached || document; } /** When an existing editor view is moved to a new document or shadow tree, call this to make it recompute its root. */ updateRoot() { this._root = null; } /** Given a pair of viewport coordinates, return the document position that corresponds to them. May return null if the given coordinates aren't inside of the editor. When an object is returned, its `pos` property is the position nearest to the coordinates, and its `inside` property holds the position of the inner node that the position falls inside of, or -1 if it is at the top level, not in any node. */ posAtCoords(coords) { return posAtCoords(this, coords); } /** Returns the viewport rectangle at a given document position. `left` and `right` will be the same number, as this returns a flat cursor-ish rectangle. If the position is between two things that aren't directly adjacent, `side` determines which element is used. When < 0, the element before the position is used, otherwise the element after. */ coordsAtPos(pos, side = 1) { return coordsAtPos(this, pos, side); } /** Find the DOM position that corresponds to the given document position. When `side` is negative, find the position as close as possible to the content before the position. When positive, prefer positions close to the content after the position. When zero, prefer as shallow a position as possible. Note that you should **not** mutate the editor's internal DOM, only inspect it (and even that is usually not necessary). */ domAtPos(pos, side = 0) { return this.docView.domFromPos(pos, side); } /** Find the DOM node that represents the document node after the given position. May return `null` when the position doesn't point in front of a node or if the node is inside an opaque node view. This is intended to be able to call things like `getBoundingClientRect` on that DOM node. Do **not** mutate the editor DOM directly, or add styling this way, since that will be immediately overriden by the editor as it redraws the node. */ nodeDOM(pos) { let desc = this.docView.descAt(pos); return desc ? desc.nodeDOM : null; } /** Find the document position that corresponds to a given DOM position. (Whenever possible, it is preferable to inspect the document structure directly, rather than poking around in the DOM, but sometimes—for example when interpreting an event target—you don't have a choice.) The `bias` parameter can be used to influence which side of a DOM node to use when the position is inside a leaf node. */ posAtDOM(node2, offset4, bias = -1) { let pos = this.docView.posFromDOM(node2, offset4, bias); if (pos == null) throw new RangeError("DOM position not inside the editor"); return pos; } /** Find out whether the selection is at the end of a textblock when moving in a given direction. When, for example, given `"left"`, it will return true if moving left from the current cursor position would leave that position's parent textblock. Will apply to the view's current state by default, but it is possible to pass a different state. */ endOfTextblock(dir, state) { return endOfTextblock(this, state || this.state, dir); } /** Run the editor's paste logic with the given HTML string. The `event`, if given, will be passed to the [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook. */ pasteHTML(html7, event) { return doPaste(this, "", html7, false, event || new ClipboardEvent("paste")); } /** Run the editor's paste logic with the given plain-text input. */ pasteText(text10, event) { return doPaste(this, text10, null, true, event || new ClipboardEvent("paste")); } /** Serialize the given slice as it would be if it was copied from this editor. Returns a DOM element that contains a representation of the slice as its children, a textual representation, and the transformed slice (which can be different from the given input due to hooks like [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)). */ serializeForClipboard(slice2) { return serializeForClipboard(this, slice2); } /** Removes the editor from the DOM and destroys all [node views](https://prosemirror.net/docs/ref/#view.NodeView). */ destroy() { if (!this.docView) return; destroyInput(this); this.destroyPluginViews(); if (this.mounted) { this.docView.update(this.state.doc, [], viewDecorations(this), this); this.dom.textContent = ""; } else if (this.dom.parentNode) { this.dom.parentNode.removeChild(this.dom); } this.docView.destroy(); this.docView = null; clearReusedRange(); } /** This is true when the view has been [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be used anymore). */ get isDestroyed() { return this.docView == null; } /** Used for testing. */ dispatchEvent(event) { return dispatchEvent(this, event); } /** @internal */ domSelectionRange() { let sel = this.domSelection(); if (!sel) return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 }; return safari && this.root.nodeType === 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel; } /** @internal */ domSelection() { return this.root.getSelection(); } }; EditorView.prototype.dispatch = function(tr4) { let dispatchTransaction = this._props.dispatchTransaction; if (dispatchTransaction) dispatchTransaction.call(this, tr4); else this.updateState(this.state.apply(tr4)); }; function computeDocDeco(view) { let attrs = /* @__PURE__ */ Object.create(null); attrs.class = "ProseMirror"; attrs.contenteditable = String(view.editable); view.someProp("attributes", (value) => { if (typeof value == "function") value = value(view.state); if (value) for (let attr2 in value) { if (attr2 == "class") attrs.class += " " + value[attr2]; else if (attr2 == "style") attrs.style = (attrs.style ? attrs.style + ";" : "") + value[attr2]; else if (!attrs[attr2] && attr2 != "contenteditable" && attr2 != "nodeName") attrs[attr2] = String(value[attr2]); } }); if (!attrs.translate) attrs.translate = "no"; return [Decoration.node(0, view.state.doc.content.size, attrs)]; } function updateCursorWrapper(view) { if (view.markCursor) { let dom = document.createElement("img"); dom.className = "ProseMirror-separator"; dom.setAttribute("mark-placeholder", "true"); dom.setAttribute("alt", ""); view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) }; } else { view.cursorWrapper = null; } } function getEditable(view) { return !view.someProp("editable", (value) => value(view.state) === false); } function selectionContextChanged(sel1, sel2) { let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head)); return sel1.$anchor.start(depth) != sel2.$anchor.start(depth); } function buildNodeViews(view) { let result = /* @__PURE__ */ Object.create(null); function add(obj) { for (let prop in obj) if (!Object.prototype.hasOwnProperty.call(result, prop)) result[prop] = obj[prop]; } view.someProp("nodeViews", add); view.someProp("markViews", add); return result; } function changedNodeViews(a3, b4) { let nA = 0, nB = 0; for (let prop in a3) { if (a3[prop] != b4[prop]) return true; nA++; } for (let _2 in b4) nB++; return nA != nB; } function checkStateComponent(plugin) { if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction) throw new RangeError("Plugins passed directly to the view must not have a state component"); } // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/map.js var create = () => /* @__PURE__ */ new Map(); var copy2 = (m2) => { const r4 = create(); m2.forEach((v8, k3) => { r4.set(k3, v8); }); return r4; }; var setIfUndefined = (map7, key2, createT) => { let set = map7.get(key2); if (set === void 0) { map7.set(key2, set = createT()); } return set; }; var map = (m2, f6) => { const res = []; for (const [key2, value] of m2) { res.push(f6(value, key2)); } return res; }; var any = (m2, f6) => { for (const [key2, value] of m2) { if (f6(value, key2)) { return true; } } return false; }; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/set.js var create2 = () => /* @__PURE__ */ new Set(); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/array.js var last = (arr) => arr[arr.length - 1]; var appendTo = (dest, src) => { for (let i3 = 0; i3 < src.length; i3++) { dest.push(src[i3]); } }; var from2 = Array.from; var every = (arr, f6) => { for (let i3 = 0; i3 < arr.length; i3++) { if (!f6(arr[i3], i3, arr)) { return false; } } return true; }; var some = (arr, f6) => { for (let i3 = 0; i3 < arr.length; i3++) { if (f6(arr[i3], i3, arr)) { return true; } } return false; }; var unfold = (len, f6) => { const array = new Array(len); for (let i3 = 0; i3 < len; i3++) { array[i3] = f6(i3, array); } return array; }; var isArray = Array.isArray; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/observable.js var ObservableV2 = class { constructor() { this._observers = create(); } /** * @template {keyof EVENTS & string} NAME * @param {NAME} name * @param {EVENTS[NAME]} f */ on(name, f6) { setIfUndefined( this._observers, /** @type {string} */ name, create2 ).add(f6); return f6; } /** * @template {keyof EVENTS & string} NAME * @param {NAME} name * @param {EVENTS[NAME]} f */ once(name, f6) { const _f = (...args2) => { this.off( name, /** @type {any} */ _f ); f6(...args2); }; this.on( name, /** @type {any} */ _f ); } /** * @template {keyof EVENTS & string} NAME * @param {NAME} name * @param {EVENTS[NAME]} f */ off(name, f6) { const observers = this._observers.get(name); if (observers !== void 0) { observers.delete(f6); if (observers.size === 0) { this._observers.delete(name); } } } /** * Emit a named event. All registered event listeners that listen to the * specified name will receive the event. * * @todo This should catch exceptions * * @template {keyof EVENTS & string} NAME * @param {NAME} name The event name. * @param {Parameters} args The arguments that are applied to the event listener. */ emit(name, args2) { return from2((this._observers.get(name) || create()).values()).forEach((f6) => f6(...args2)); } destroy() { this._observers = create(); } }; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/math.js var floor = Math.floor; var abs = Math.abs; var min = (a3, b4) => a3 < b4 ? a3 : b4; var max = (a3, b4) => a3 > b4 ? a3 : b4; var isNaN2 = Number.isNaN; var isNegativeZero = (n) => n !== 0 ? n < 0 : 1 / n < 0; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/binary.js var BIT1 = 1; var BIT2 = 2; var BIT3 = 4; var BIT4 = 8; var BIT6 = 32; var BIT7 = 64; var BIT8 = 128; var BIT18 = 1 << 17; var BIT19 = 1 << 18; var BIT20 = 1 << 19; var BIT21 = 1 << 20; var BIT22 = 1 << 21; var BIT23 = 1 << 22; var BIT24 = 1 << 23; var BIT25 = 1 << 24; var BIT26 = 1 << 25; var BIT27 = 1 << 26; var BIT28 = 1 << 27; var BIT29 = 1 << 28; var BIT30 = 1 << 29; var BIT31 = 1 << 30; var BIT32 = 1 << 31; var BITS5 = 31; var BITS6 = 63; var BITS7 = 127; var BITS17 = BIT18 - 1; var BITS18 = BIT19 - 1; var BITS19 = BIT20 - 1; var BITS20 = BIT21 - 1; var BITS21 = BIT22 - 1; var BITS22 = BIT23 - 1; var BITS23 = BIT24 - 1; var BITS24 = BIT25 - 1; var BITS25 = BIT26 - 1; var BITS26 = BIT27 - 1; var BITS27 = BIT28 - 1; var BITS28 = BIT29 - 1; var BITS29 = BIT30 - 1; var BITS30 = BIT31 - 1; var BITS31 = 2147483647; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/number.js var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER; var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER; var LOWEST_INT32 = 1 << 31; var isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num); var isNaN3 = Number.isNaN; var parseInt2 = Number.parseInt; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/string.js var fromCharCode = String.fromCharCode; var fromCodePoint = String.fromCodePoint; var MAX_UTF16_CHARACTER = fromCharCode(65535); var toLowerCase = (s2) => s2.toLowerCase(); var trimLeftRegex = /^\s*/g; var trimLeft = (s2) => s2.replace(trimLeftRegex, ""); var fromCamelCaseRegex = /([A-Z])/g; var fromCamelCase = (s2, separator) => trimLeft(s2.replace(fromCamelCaseRegex, (match2) => `${separator}${toLowerCase(match2)}`)); var _encodeUtf8Polyfill = (str) => { const encodedString = unescape(encodeURIComponent(str)); const len = encodedString.length; const buf = new Uint8Array(len); for (let i3 = 0; i3 < len; i3++) { buf[i3] = /** @type {number} */ encodedString.codePointAt(i3); } return buf; }; var utf8TextEncoder = ( /** @type {TextEncoder} */ typeof TextEncoder !== "undefined" ? new TextEncoder() : null ); var _encodeUtf8Native = (str) => utf8TextEncoder.encode(str); var encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill; var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) { utf8TextDecoder = null; } var repeat = (source, n) => unfold(n, () => source).join(""); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/encoding.js var Encoder = class { constructor() { this.cpos = 0; this.cbuf = new Uint8Array(100); this.bufs = []; } }; var createEncoder = () => new Encoder(); var encode = (f6) => { const encoder = createEncoder(); f6(encoder); return toUint8Array(encoder); }; var length = (encoder) => { let len = encoder.cpos; for (let i3 = 0; i3 < encoder.bufs.length; i3++) { len += encoder.bufs[i3].length; } return len; }; var toUint8Array = (encoder) => { const uint8arr = new Uint8Array(length(encoder)); let curPos = 0; for (let i3 = 0; i3 < encoder.bufs.length; i3++) { const d = encoder.bufs[i3]; uint8arr.set(d, curPos); curPos += d.length; } uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos); return uint8arr; }; var verifyLen = (encoder, len) => { const bufferLen = encoder.cbuf.length; if (bufferLen - encoder.cpos < len) { encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos)); encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2); encoder.cpos = 0; } }; var write = (encoder, num) => { const bufferLen = encoder.cbuf.length; if (encoder.cpos === bufferLen) { encoder.bufs.push(encoder.cbuf); encoder.cbuf = new Uint8Array(bufferLen * 2); encoder.cpos = 0; } encoder.cbuf[encoder.cpos++] = num; }; var writeUint8 = write; var writeVarUint = (encoder, num) => { while (num > BITS7) { write(encoder, BIT8 | BITS7 & num); num = floor(num / 128); } write(encoder, BITS7 & num); }; var writeVarInt = (encoder, num) => { const isNegative = isNegativeZero(num); if (isNegative) { num = -num; } write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num); num = floor(num / 64); while (num > 0) { write(encoder, (num > BITS7 ? BIT8 : 0) | BITS7 & num); num = floor(num / 128); } }; var _strBuffer = new Uint8Array(3e4); var _maxStrBSize = _strBuffer.length / 3; var _writeVarStringNative = (encoder, str) => { if (str.length < _maxStrBSize) { const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0; writeVarUint(encoder, written); for (let i3 = 0; i3 < written; i3++) { write(encoder, _strBuffer[i3]); } } else { writeVarUint8Array(encoder, encodeUtf8(str)); } }; var _writeVarStringPolyfill = (encoder, str) => { const encodedString = unescape(encodeURIComponent(str)); const len = encodedString.length; writeVarUint(encoder, len); for (let i3 = 0; i3 < len; i3++) { write( encoder, /** @type {number} */ encodedString.codePointAt(i3) ); } }; var writeVarString = utf8TextEncoder && /** @type {any} */ utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill; var writeUint8Array = (encoder, uint8Array) => { const bufferLen = encoder.cbuf.length; const cpos = encoder.cpos; const leftCopyLen = min(bufferLen - cpos, uint8Array.length); const rightCopyLen = uint8Array.length - leftCopyLen; encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos); encoder.cpos += leftCopyLen; if (rightCopyLen > 0) { encoder.bufs.push(encoder.cbuf); encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen)); encoder.cbuf.set(uint8Array.subarray(leftCopyLen)); encoder.cpos = rightCopyLen; } }; var writeVarUint8Array = (encoder, uint8Array) => { writeVarUint(encoder, uint8Array.byteLength); writeUint8Array(encoder, uint8Array); }; var writeOnDataView = (encoder, len) => { verifyLen(encoder, len); const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len); encoder.cpos += len; return dview; }; var writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false); var writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false); var writeBigInt64 = (encoder, num) => ( /** @type {any} */ writeOnDataView(encoder, 8).setBigInt64(0, num, false) ); var floatTestBed = new DataView(new ArrayBuffer(4)); var isFloat32 = (num) => { floatTestBed.setFloat32(0, num); return floatTestBed.getFloat32(0) === num; }; var writeAny = (encoder, data) => { switch (typeof data) { case "string": write(encoder, 119); writeVarString(encoder, data); break; case "number": if (isInteger(data) && abs(data) <= BITS31) { write(encoder, 125); writeVarInt(encoder, data); } else if (isFloat32(data)) { write(encoder, 124); writeFloat32(encoder, data); } else { write(encoder, 123); writeFloat64(encoder, data); } break; case "bigint": write(encoder, 122); writeBigInt64(encoder, data); break; case "object": if (data === null) { write(encoder, 126); } else if (isArray(data)) { write(encoder, 117); writeVarUint(encoder, data.length); for (let i3 = 0; i3 < data.length; i3++) { writeAny(encoder, data[i3]); } } else if (data instanceof Uint8Array) { write(encoder, 116); writeVarUint8Array(encoder, data); } else { write(encoder, 118); const keys5 = Object.keys(data); writeVarUint(encoder, keys5.length); for (let i3 = 0; i3 < keys5.length; i3++) { const key2 = keys5[i3]; writeVarString(encoder, key2); writeAny(encoder, data[key2]); } } break; case "boolean": write(encoder, data ? 120 : 121); break; default: write(encoder, 127); } }; var RleEncoder = class extends Encoder { /** * @param {function(Encoder, T):void} writer */ constructor(writer) { super(); this.w = writer; this.s = null; this.count = 0; } /** * @param {T} v */ write(v8) { if (this.s === v8) { this.count++; } else { if (this.count > 0) { writeVarUint(this, this.count - 1); } this.count = 1; this.w(this, v8); this.s = v8; } } }; var flushUintOptRleEncoder = (encoder) => { if (encoder.count > 0) { writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s); if (encoder.count > 1) { writeVarUint(encoder.encoder, encoder.count - 2); } } }; var UintOptRleEncoder = class { constructor() { this.encoder = new Encoder(); this.s = 0; this.count = 0; } /** * @param {number} v */ write(v8) { if (this.s === v8) { this.count++; } else { flushUintOptRleEncoder(this); this.count = 1; this.s = v8; } } /** * Flush the encoded state and transform this to a Uint8Array. * * Note that this should only be called once. */ toUint8Array() { flushUintOptRleEncoder(this); return toUint8Array(this.encoder); } }; var flushIntDiffOptRleEncoder = (encoder) => { if (encoder.count > 0) { const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1); writeVarInt(encoder.encoder, encodedDiff); if (encoder.count > 1) { writeVarUint(encoder.encoder, encoder.count - 2); } } }; var IntDiffOptRleEncoder = class { constructor() { this.encoder = new Encoder(); this.s = 0; this.count = 0; this.diff = 0; } /** * @param {number} v */ write(v8) { if (this.diff === v8 - this.s) { this.s = v8; this.count++; } else { flushIntDiffOptRleEncoder(this); this.count = 1; this.diff = v8 - this.s; this.s = v8; } } /** * Flush the encoded state and transform this to a Uint8Array. * * Note that this should only be called once. */ toUint8Array() { flushIntDiffOptRleEncoder(this); return toUint8Array(this.encoder); } }; var StringEncoder = class { constructor() { this.sarr = []; this.s = ""; this.lensE = new UintOptRleEncoder(); } /** * @param {string} string */ write(string3) { this.s += string3; if (this.s.length > 19) { this.sarr.push(this.s); this.s = ""; } this.lensE.write(string3.length); } toUint8Array() { const encoder = new Encoder(); this.sarr.push(this.s); this.s = ""; writeVarString(encoder, this.sarr.join("")); writeUint8Array(encoder, this.lensE.toUint8Array()); return toUint8Array(encoder); } }; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/error.js var create3 = (s2) => new Error(s2); var methodUnimplemented = () => { throw create3("Method unimplemented"); }; var unexpectedCase = () => { throw create3("Unexpected case"); }; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/decoding.js var errorUnexpectedEndOfArray = create3("Unexpected end of array"); var errorIntegerOutOfRange = create3("Integer out of Range"); var Decoder = class { /** * @param {Uint8Array} uint8Array Binary data to decode */ constructor(uint8Array) { this.arr = uint8Array; this.pos = 0; } }; var createDecoder = (uint8Array) => new Decoder(uint8Array); var hasContent = (decoder) => decoder.pos !== decoder.arr.length; var readUint8Array = (decoder, len) => { const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len); decoder.pos += len; return view; }; var readVarUint8Array = (decoder) => readUint8Array(decoder, readVarUint(decoder)); var readUint8 = (decoder) => decoder.arr[decoder.pos++]; var readVarUint = (decoder) => { let num = 0; let mult = 1; const len = decoder.arr.length; while (decoder.pos < len) { const r4 = decoder.arr[decoder.pos++]; num = num + (r4 & BITS7) * mult; mult *= 128; if (r4 < BIT8) { return num; } if (num > MAX_SAFE_INTEGER) { throw errorIntegerOutOfRange; } } throw errorUnexpectedEndOfArray; }; var readVarInt = (decoder) => { let r4 = decoder.arr[decoder.pos++]; let num = r4 & BITS6; let mult = 64; const sign = (r4 & BIT7) > 0 ? -1 : 1; if ((r4 & BIT8) === 0) { return sign * num; } const len = decoder.arr.length; while (decoder.pos < len) { r4 = decoder.arr[decoder.pos++]; num = num + (r4 & BITS7) * mult; mult *= 128; if (r4 < BIT8) { return sign * num; } if (num > MAX_SAFE_INTEGER) { throw errorIntegerOutOfRange; } } throw errorUnexpectedEndOfArray; }; var _readVarStringPolyfill = (decoder) => { let remainingLen = readVarUint(decoder); if (remainingLen === 0) { return ""; } else { let encodedString = String.fromCodePoint(readUint8(decoder)); if (--remainingLen < 100) { while (remainingLen--) { encodedString += String.fromCodePoint(readUint8(decoder)); } } else { while (remainingLen > 0) { const nextLen = remainingLen < 1e4 ? remainingLen : 1e4; const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen); decoder.pos += nextLen; encodedString += String.fromCodePoint.apply( null, /** @type {any} */ bytes ); remainingLen -= nextLen; } } return decodeURIComponent(escape(encodedString)); } }; var _readVarStringNative = (decoder) => ( /** @type any */ utf8TextDecoder.decode(readVarUint8Array(decoder)) ); var readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill; var readFromDataView = (decoder, len) => { const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len); decoder.pos += len; return dv; }; var readFloat32 = (decoder) => readFromDataView(decoder, 4).getFloat32(0, false); var readFloat64 = (decoder) => readFromDataView(decoder, 8).getFloat64(0, false); var readBigInt64 = (decoder) => ( /** @type {any} */ readFromDataView(decoder, 8).getBigInt64(0, false) ); var readAnyLookupTable = [ (decoder) => void 0, // CASE 127: undefined (decoder) => null, // CASE 126: null readVarInt, // CASE 125: integer readFloat32, // CASE 124: float32 readFloat64, // CASE 123: float64 readBigInt64, // CASE 122: bigint (decoder) => false, // CASE 121: boolean (false) (decoder) => true, // CASE 120: boolean (true) readVarString, // CASE 119: string (decoder) => { const len = readVarUint(decoder); const obj = {}; for (let i3 = 0; i3 < len; i3++) { const key2 = readVarString(decoder); obj[key2] = readAny(decoder); } return obj; }, (decoder) => { const len = readVarUint(decoder); const arr = []; for (let i3 = 0; i3 < len; i3++) { arr.push(readAny(decoder)); } return arr; }, readVarUint8Array // CASE 116: Uint8Array ]; var readAny = (decoder) => readAnyLookupTable[127 - readUint8(decoder)](decoder); var RleDecoder = class extends Decoder { /** * @param {Uint8Array} uint8Array * @param {function(Decoder):T} reader */ constructor(uint8Array, reader) { super(uint8Array); this.reader = reader; this.s = null; this.count = 0; } read() { if (this.count === 0) { this.s = this.reader(this); if (hasContent(this)) { this.count = readVarUint(this) + 1; } else { this.count = -1; } } this.count--; return ( /** @type {T} */ this.s ); } }; var UintOptRleDecoder = class extends Decoder { /** * @param {Uint8Array} uint8Array */ constructor(uint8Array) { super(uint8Array); this.s = 0; this.count = 0; } read() { if (this.count === 0) { this.s = readVarInt(this); const isNegative = isNegativeZero(this.s); this.count = 1; if (isNegative) { this.s = -this.s; this.count = readVarUint(this) + 2; } } this.count--; return ( /** @type {number} */ this.s ); } }; var IntDiffOptRleDecoder = class extends Decoder { /** * @param {Uint8Array} uint8Array */ constructor(uint8Array) { super(uint8Array); this.s = 0; this.count = 0; this.diff = 0; } /** * @return {number} */ read() { if (this.count === 0) { const diff = readVarInt(this); const hasCount = diff & 1; this.diff = floor(diff / 2); this.count = 1; if (hasCount) { this.count = readVarUint(this) + 2; } } this.s += this.diff; this.count--; return this.s; } }; var StringDecoder = class { /** * @param {Uint8Array} uint8Array */ constructor(uint8Array) { this.decoder = new UintOptRleDecoder(uint8Array); this.str = readVarString(this.decoder); this.spos = 0; } /** * @return {string} */ read() { const end = this.spos + this.decoder.read(); const res = this.str.slice(this.spos, end); this.spos = end; return res; } }; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/webcrypto.js var subtle = crypto.subtle; var getRandomValues = crypto.getRandomValues.bind(crypto); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/random.js var rand = Math.random; var uint32 = () => getRandomValues(new Uint32Array(1))[0]; var oneOf = (arr) => arr[floor(rand() * arr.length)]; var uuidv4Template = "10000000-1000-4000-8000" + -1e11; var uuidv4 = () => uuidv4Template.replace( /[018]/g, /** @param {number} c */ (c3) => (c3 ^ uint32() & 15 >> c3 / 4).toString(16) ); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/time.js var getUnixTime = Date.now; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/promise.js var create4 = (f6) => ( /** @type {Promise} */ new Promise(f6) ); var all = Promise.all.bind(Promise); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/conditions.js var undefinedToNull = (v8) => v8 === void 0 ? null : v8; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/storage.js var VarStoragePolyfill = class { constructor() { this.map = /* @__PURE__ */ new Map(); } /** * @param {string} key * @param {any} newValue */ setItem(key2, newValue) { this.map.set(key2, newValue); } /** * @param {string} key */ getItem(key2) { return this.map.get(key2); } }; var _localStorage = new VarStoragePolyfill(); var usePolyfill = true; try { if (typeof localStorage !== "undefined" && localStorage) { _localStorage = localStorage; usePolyfill = false; } } catch (e2) { } var varStorage = _localStorage; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/trait/equality.js var EqualityTraitSymbol = Symbol("Equality"); var equals = (a3, b4) => { var _a2; return a3 === b4 || !!((_a2 = a3 == null ? void 0 : a3[EqualityTraitSymbol]) == null ? void 0 : _a2.call(a3, b4)) || false; }; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/object.js var isObject = (o2) => typeof o2 === "object"; var assign = Object.assign; var keys2 = Object.keys; var forEach = (obj, f6) => { for (const key2 in obj) { f6(obj[key2], key2); } }; var size = (obj) => keys2(obj).length; var isEmpty = (obj) => { for (const _k in obj) { return false; } return true; }; var every2 = (obj, f6) => { for (const key2 in obj) { if (!f6(obj[key2], key2)) { return false; } } return true; }; var hasProperty = (obj, key2) => Object.prototype.hasOwnProperty.call(obj, key2); var equalFlat = (a3, b4) => a3 === b4 || size(a3) === size(b4) && every2(a3, (val, key2) => (val !== void 0 || hasProperty(b4, key2)) && equals(b4[key2], val)); var freeze = Object.freeze; var deepFreeze = (o2) => { for (const key2 in o2) { const c3 = o2[key2]; if (typeof c3 === "object" || typeof c3 === "function") { deepFreeze(o2[key2]); } } return freeze(o2); }; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/function.js var callAll = (fs, args2, i3 = 0) => { try { for (; i3 < fs.length; i3++) { fs[i3](...args2); } } finally { if (i3 < fs.length) { callAll(fs, args2, i3 + 1); } } }; var id = (a3) => a3; var equalityDeep = (a3, b4) => { if (a3 === b4) { return true; } if (a3 == null || b4 == null || a3.constructor !== b4.constructor && (a3.constructor || Object) !== (b4.constructor || Object)) { return false; } if (a3[EqualityTraitSymbol] != null) { return a3[EqualityTraitSymbol](b4); } switch (a3.constructor) { case ArrayBuffer: a3 = new Uint8Array(a3); b4 = new Uint8Array(b4); // eslint-disable-next-line no-fallthrough case Uint8Array: { if (a3.byteLength !== b4.byteLength) { return false; } for (let i3 = 0; i3 < a3.length; i3++) { if (a3[i3] !== b4[i3]) { return false; } } break; } case Set: { if (a3.size !== b4.size) { return false; } for (const value of a3) { if (!b4.has(value)) { return false; } } break; } case Map: { if (a3.size !== b4.size) { return false; } for (const key2 of a3.keys()) { if (!b4.has(key2) || !equalityDeep(a3.get(key2), b4.get(key2))) { return false; } } break; } case void 0: case Object: if (size(a3) !== size(b4)) { return false; } for (const key2 in a3) { if (!hasProperty(a3, key2) || !equalityDeep(a3[key2], b4[key2])) { return false; } } break; case Array: if (a3.length !== b4.length) { return false; } for (let i3 = 0; i3 < a3.length; i3++) { if (!equalityDeep(a3[i3], b4[i3])) { return false; } } break; default: return false; } return true; }; var isOneOf = (value, options2) => options2.includes(value); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/environment.js var isNode = typeof process !== "undefined" && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]"; var isBrowser = typeof window !== "undefined" && typeof document !== "undefined" && !isNode; var isMac = typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false; var params; var args = []; var computeParams = () => { if (params === void 0) { if (isNode) { params = create(); const pargs = process.argv; let currParamName = null; for (let i3 = 0; i3 < pargs.length; i3++) { const parg = pargs[i3]; if (parg[0] === "-") { if (currParamName !== null) { params.set(currParamName, ""); } currParamName = parg; } else { if (currParamName !== null) { params.set(currParamName, parg); currParamName = null; } else { args.push(parg); } } } if (currParamName !== null) { params.set(currParamName, ""); } } else if (typeof location === "object") { params = create(); (location.search || "?").slice(1).split("&").forEach((kv) => { if (kv.length !== 0) { const [key2, value] = kv.split("="); params.set(`--${fromCamelCase(key2, "-")}`, value); params.set(`-${fromCamelCase(key2, "-")}`, value); } }); } else { params = create(); } } return params; }; var hasParam = (name) => computeParams().has(name); var getVariable = (name) => isNode ? undefinedToNull(process.env[name.toUpperCase().replaceAll("-", "_")]) : undefinedToNull(varStorage.getItem(name)); var hasConf = (name) => hasParam("--" + name) || getVariable(name) !== null; var production = hasConf("production"); var forceColor = isNode && isOneOf(process.env.FORCE_COLOR, ["true", "1", "2"]); var supportsColor = forceColor || !hasParam("--no-colors") && // @todo deprecate --no-colors !hasConf("no-color") && (!isNode || process.stdout.isTTY) && (!isNode || hasParam("--color") || getVariable("COLORTERM") !== null || (getVariable("TERM") || "").includes("color")); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/buffer.js var createUint8ArrayFromLen = (len) => new Uint8Array(len); var toBase64Browser = (bytes) => { let s2 = ""; for (let i3 = 0; i3 < bytes.byteLength; i3++) { s2 += fromCharCode(bytes[i3]); } return btoa(s2); }; var toBase64Node = (bytes) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64"); var toBase64 = isBrowser ? toBase64Browser : toBase64Node; var copyUint8Array = (uint8Array) => { const newBuf = createUint8ArrayFromLen(uint8Array.byteLength); newBuf.set(uint8Array); return newBuf; }; var encodeAny = (data) => encode((encoder) => writeAny(encoder, data)); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/pair.js var Pair = class { /** * @param {L} left * @param {R} right */ constructor(left, right) { this.left = left; this.right = right; } }; var create5 = (left, right) => new Pair(left, right); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/prng.js var bool = (gen) => gen.next() >= 0.5; var int53 = (gen, min3, max3) => floor(gen.next() * (max3 + 1 - min3) + min3); var int32 = (gen, min3, max3) => floor(gen.next() * (max3 + 1 - min3) + min3); var int31 = (gen, min3, max3) => int32(gen, min3, max3); var letter = (gen) => fromCharCode(int31(gen, 97, 122)); var word = (gen, minLen = 0, maxLen = 20) => { const len = int31(gen, minLen, maxLen); let str = ""; for (let i3 = 0; i3 < len; i3++) { str += letter(gen); } return str; }; var oneOf2 = (gen, array) => array[int31(gen, 0, array.length - 1)]; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/schema.js var schemaSymbol = Symbol("0schema"); var ValidationError = class { constructor() { this._rerrs = []; } /** * @param {string?} path * @param {string} expected * @param {string} has * @param {string?} message */ extend(path2, expected, has, message = null) { this._rerrs.push({ path: path2, expected, has, message }); } toString() { const s2 = []; for (let i3 = this._rerrs.length - 1; i3 > 0; i3--) { const r4 = this._rerrs[i3]; s2.push(repeat(" ", (this._rerrs.length - i3) * 2) + `${r4.path != null ? `[${r4.path}] ` : ""}${r4.has} doesn't match ${r4.expected}. ${r4.message}`); } return s2.join("\n"); } }; var shapeExtends = (a3, b4) => { if (a3 === b4) return true; if (a3 == null || b4 == null || a3.constructor !== b4.constructor) return false; if (a3[EqualityTraitSymbol]) return equals(a3, b4); if (isArray(a3)) { return every( a3, (aitem) => some(b4, (bitem) => shapeExtends(aitem, bitem)) ); } else if (isObject(a3)) { return every2( a3, (aitem, akey) => shapeExtends(aitem, b4[akey]) ); } return false; }; var Schema2 = class { /** * @param {Schema} other */ extends(other) { let [a3, b4] = [ /** @type {any} */ this.shape, /** @type {any} */ other.shape ]; if ( /** @type {typeof Schema} */ this.constructor._dilutes ) [b4, a3] = [a3, b4]; return shapeExtends(a3, b4); } /** * Overwrite this when necessary. By default, we only check the `shape` property which every shape * should have. * @param {Schema} other */ equals(other) { return this.constructor === other.constructor && equalityDeep(this.shape, other.shape); } [schemaSymbol]() { return true; } /** * @param {object} other */ [EqualityTraitSymbol](other) { return this.equals( /** @type {any} */ other ); } /** * Use `schema.validate(obj)` with a typed parameter that is already of typed to be an instance of * Schema. Validate will check the structure of the parameter and return true iff the instance * really is an instance of Schema. * * @param {T} o * @return {boolean} */ validate(o2) { return this.check(o2); } /* c8 ignore start */ /** * Similar to validate, but this method accepts untyped parameters. * * @param {any} _o * @param {ValidationError} [_err] * @return {_o is T} */ check(_o3, _err) { methodUnimplemented(); } /* c8 ignore stop */ /** * @type {Schema} */ get nullable() { return $union(this, $null); } /** * @type {$Optional>} */ get optional() { return new $Optional( /** @type {Schema} */ this ); } /** * Cast a variable to a specific type. Returns the casted value, or throws an exception otherwise. * Use this if you know that the type is of a specific type and you just want to convince the type * system. * * **Do not rely on these error messages!** * Performs an assertion check only if not in a production environment. * * @template OO * @param {OO} o * @return {Extract extends never ? T : (OO extends Array ? T : Extract)} */ cast(o2) { assert(o2, this); return ( /** @type {any} */ o2 ); } /** * EXPECTO PATRONUM!! 🪄 * This function protects against type errors. Though it may not work in the real world. * * "After all this time?" * "Always." - Snape, talking about type safety * * Ensures that a variable is a a specific type. Returns the value, or throws an exception if the assertion check failed. * Use this if you know that the type is of a specific type and you just want to convince the type * system. * * Can be useful when defining lambdas: `s.lambda(s.$number, s.$void).expect((n) => n + 1)` * * **Do not rely on these error messages!** * Performs an assertion check if not in a production environment. * * @param {T} o * @return {o extends T ? T : never} */ expect(o2) { assert(o2, this); return o2; } }; // this.shape must not be defined on Schema. Otherwise typecheck on metatypes (e.g. $$object) won't work as expected anymore /** * If true, the more things are added to the shape the more objects this schema will accept (e.g. * union). By default, the more objects are added, the the fewer objects this schema will accept. * @protected */ __publicField(Schema2, "_dilutes", false); var $ConstructedBy = class extends Schema2 { /** * @param {C} c * @param {((o:Instance)=>boolean)|null} check */ constructor(c3, check) { super(); this.shape = c3; this._c = check; } /** * @param {any} o * @param {ValidationError} [err] * @return {o is C extends ((...args:any[]) => infer T) ? T : (C extends (new (...args:any[]) => any) ? InstanceType : never)} o */ check(o2, err = void 0) { const c3 = (o2 == null ? void 0 : o2.constructor) === this.shape && (this._c == null || this._c(o2)); !c3 && (err == null ? void 0 : err.extend(null, this.shape.name, o2 == null ? void 0 : o2.constructor.name, (o2 == null ? void 0 : o2.constructor) !== this.shape ? "Constructor match failed" : "Check failed")); return c3; } }; var $constructedBy = (c3, check = null) => new $ConstructedBy(c3, check); var $$constructedBy = $constructedBy($ConstructedBy); var $Custom = class extends Schema2 { /** * @param {(o:any) => boolean} check */ constructor(check) { super(); this.shape = check; } /** * @param {any} o * @param {ValidationError} err * @return {o is any} */ check(o2, err) { const c3 = this.shape(o2); !c3 && (err == null ? void 0 : err.extend(null, "custom prop", o2 == null ? void 0 : o2.constructor.name, "failed to check custom prop")); return c3; } }; var $custom = (check) => new $Custom(check); var $$custom = $constructedBy($Custom); var $Literal = class extends Schema2 { /** * @param {Array} literals */ constructor(literals) { super(); this.shape = literals; } /** * * @param {any} o * @param {ValidationError} [err] * @return {o is T} */ check(o2, err) { const c3 = this.shape.some((a3) => a3 === o2); !c3 && (err == null ? void 0 : err.extend(null, this.shape.join(" | "), o2.toString())); return c3; } }; var $literal = (...literals) => new $Literal(literals); var $$literal = $constructedBy($Literal); var _regexEscape = ( /** @type {any} */ RegExp.escape || /** @type {(str:string) => string} */ ((str) => str.replace(/[().|&,$^[\]]/g, (s2) => "\\" + s2)) ); var _schemaStringTemplateToRegex = (s2) => { if ($string.check(s2)) { return [_regexEscape(s2)]; } if ($$literal.check(s2)) { return ( /** @type {Array} */ s2.shape.map((v8) => v8 + "") ); } if ($$number.check(s2)) { return ["[+-]?\\d+.?\\d*"]; } if ($$string.check(s2)) { return [".*"]; } if ($$union.check(s2)) { return s2.shape.map(_schemaStringTemplateToRegex).flat(1); } unexpectedCase(); }; var $StringTemplate = class extends Schema2 { /** * @param {T} shape */ constructor(shape) { super(); this.shape = shape; this._r = new RegExp("^" + shape.map(_schemaStringTemplateToRegex).map((opts) => `(${opts.join("|")})`).join("") + "$"); } /** * @param {any} o * @param {ValidationError} [err] * @return {o is CastStringTemplateArgsToTemplate} */ check(o2, err) { const c3 = this._r.exec(o2) != null; !c3 && (err == null ? void 0 : err.extend(null, this._r.toString(), o2.toString(), "String doesn't match string template.")); return c3; } }; var $$stringTemplate = $constructedBy($StringTemplate); var isOptionalSymbol = Symbol("optional"); var $Optional = class extends Schema2 { /** * @param {S} shape */ constructor(shape) { super(); this.shape = shape; } /** * @param {any} o * @param {ValidationError} [err] * @return {o is (Unwrap|undefined)} */ check(o2, err) { const c3 = o2 === void 0 || this.shape.check(o2); !c3 && (err == null ? void 0 : err.extend(null, "undefined (optional)", "()")); return c3; } get [isOptionalSymbol]() { return true; } }; var $$optional = $constructedBy($Optional); var $Never = class extends Schema2 { /** * @param {any} _o * @param {ValidationError} [err] * @return {_o is never} */ check(_o3, err) { err == null ? void 0 : err.extend(null, "never", typeof _o3); return false; } }; var $never = new $Never(); var $$never = $constructedBy($Never); var _$Object = class _$Object extends Schema2 { /** * @param {S} shape * @param {boolean} partial */ constructor(shape, partial = false) { super(); this.shape = shape; this._isPartial = partial; } /** * @type {Schema>>} */ get partial() { return new _$Object(this.shape, true); } /** * @param {any} o * @param {ValidationError} err * @return {o is $ObjectToType} */ check(o2, err) { if (o2 == null) { err == null ? void 0 : err.extend(null, "object", "null"); return false; } return every2(this.shape, (vv, vk) => { const c3 = this._isPartial && !hasProperty(o2, vk) || vv.check(o2[vk], err); !c3 && (err == null ? void 0 : err.extend(vk.toString(), vv.toString(), typeof o2[vk], "Object property does not match")); return c3; }); } }; __publicField(_$Object, "_dilutes", true); var $Object = _$Object; var $object = (def) => ( /** @type {any} */ new $Object(def) ); var $$object = $constructedBy($Object); var $objectAny = $custom((o2) => o2 != null && (o2.constructor === Object || o2.constructor == null)); var $Record = class extends Schema2 { /** * @param {Keys} keys * @param {Values} values */ constructor(keys5, values2) { super(); this.shape = { keys: keys5, values: values2 }; } /** * @param {any} o * @param {ValidationError} err * @return {o is { [key in Unwrap]: Unwrap }} */ check(o2, err) { return o2 != null && every2(o2, (vv, vk) => { const ck = this.shape.keys.check(vk, err); !ck && (err == null ? void 0 : err.extend(vk + "", "Record", typeof o2, ck ? "Key doesn't match schema" : "Value doesn't match value")); return ck && this.shape.values.check(vv, err); }); } }; var $record = (keys5, values2) => new $Record(keys5, values2); var $$record = $constructedBy($Record); var $Tuple = class extends Schema2 { /** * @param {S} shape */ constructor(shape) { super(); this.shape = shape; } /** * @param {any} o * @param {ValidationError} err * @return {o is { [K in keyof S]: S[K] extends Schema ? Type : never }} */ check(o2, err) { return o2 != null && every2(this.shape, (vv, vk) => { const c3 = ( /** @type {Schema} */ vv.check(o2[vk], err) ); !c3 && (err == null ? void 0 : err.extend(vk.toString(), "Tuple", typeof vv)); return c3; }); } }; var $tuple = (...def) => new $Tuple(def); var $$tuple = $constructedBy($Tuple); var $Array = class extends Schema2 { /** * @param {Array} v */ constructor(v8) { super(); this.shape = v8.length === 1 ? v8[0] : new $Union(v8); } /** * @param {any} o * @param {ValidationError} [err] * @return {o is Array ? T : never>} o */ check(o2, err) { const c3 = isArray(o2) && every(o2, (oi2) => this.shape.check(oi2)); !c3 && (err == null ? void 0 : err.extend(null, "Array", "")); return c3; } }; var $array = (...def) => new $Array(def); var $$array = $constructedBy($Array); var $arrayAny = $custom((o2) => isArray(o2)); var $InstanceOf = class extends Schema2 { /** * @param {new (...args:any) => T} constructor * @param {((o:T) => boolean)|null} check */ constructor(constructor, check) { super(); this.shape = constructor; this._c = check; } /** * @param {any} o * @param {ValidationError} err * @return {o is T} */ check(o2, err) { const c3 = o2 instanceof this.shape && (this._c == null || this._c(o2)); !c3 && (err == null ? void 0 : err.extend(null, this.shape.name, o2 == null ? void 0 : o2.constructor.name)); return c3; } }; var $instanceOf = (c3, check = null) => new $InstanceOf(c3, check); var $$instanceOf = $constructedBy($InstanceOf); var $$schema = $instanceOf(Schema2); var $Lambda = class extends Schema2 { /** * @param {Args} args */ constructor(args2) { super(); this.len = args2.length - 1; this.args = $tuple(...args2.slice(-1)); this.res = args2[this.len]; } /** * @param {any} f * @param {ValidationError} err * @return {f is _LArgsToLambdaDef} */ check(f6, err) { const c3 = f6.constructor === Function && f6.length <= this.len; !c3 && (err == null ? void 0 : err.extend(null, "function", typeof f6)); return c3; } }; var $$lambda = $constructedBy($Lambda); var $function = $custom((o2) => typeof o2 === "function"); var $Intersection = class extends Schema2 { /** * @param {T} v */ constructor(v8) { super(); this.shape = v8; } /** * @param {any} o * @param {ValidationError} [err] * @return {o is Intersect>} */ check(o2, err) { const c3 = every(this.shape, (check) => check.check(o2, err)); !c3 && (err == null ? void 0 : err.extend(null, "Intersectinon", typeof o2)); return c3; } }; var $$intersect = $constructedBy($Intersection, (o2) => o2.shape.length > 0); var $Union = class extends Schema2 { /** * @param {Array>} v */ constructor(v8) { super(); this.shape = v8; } /** * @param {any} o * @param {ValidationError} [err] * @return {o is S} */ check(o2, err) { const c3 = some(this.shape, (vv) => vv.check(o2, err)); err == null ? void 0 : err.extend(null, "Union", typeof o2); return c3; } }; __publicField($Union, "_dilutes", true); var $union = (...schemas) => schemas.findIndex(($s) => $$union.check($s)) >= 0 ? $union(...schemas.map(($s) => $($s)).map(($s) => $$union.check($s) ? $s.shape : [$s]).flat(1)) : schemas.length === 1 ? schemas[0] : new $Union(schemas); var $$union = ( /** @type {Schema<$Union>} */ $constructedBy($Union) ); var _t = () => true; var $any = $custom(_t); var $$any = ( /** @type {Schema>} */ $constructedBy($Custom, (o2) => o2.shape === _t) ); var $bigint = $custom((o2) => typeof o2 === "bigint"); var $$bigint = ( /** @type {Schema>} */ $custom((o2) => o2 === $bigint) ); var $symbol = $custom((o2) => typeof o2 === "symbol"); var $$symbol = ( /** @type {Schema>} */ $custom((o2) => o2 === $symbol) ); var $number = $custom((o2) => typeof o2 === "number"); var $$number = ( /** @type {Schema>} */ $custom((o2) => o2 === $number) ); var $string = $custom((o2) => typeof o2 === "string"); var $$string = ( /** @type {Schema>} */ $custom((o2) => o2 === $string) ); var $boolean = $custom((o2) => typeof o2 === "boolean"); var $$boolean = ( /** @type {Schema>} */ $custom((o2) => o2 === $boolean) ); var $undefined = $literal(void 0); var $$undefined = ( /** @type {Schema>} */ $constructedBy($Literal, (o2) => o2.shape.length === 1 && o2.shape[0] === void 0) ); var $void = $literal(void 0); var $null = $literal(null); var $$null = ( /** @type {Schema>} */ $constructedBy($Literal, (o2) => o2.shape.length === 1 && o2.shape[0] === null) ); var $uint8Array = $constructedBy(Uint8Array); var $$uint8Array = ( /** @type {Schema>} */ $constructedBy($ConstructedBy, (o2) => o2.shape === Uint8Array) ); var $primitive = $union($number, $string, $null, $undefined, $bigint, $boolean, $symbol); var $json = (() => { const $jsonArr = ( /** @type {$Array<$any>} */ $array($any) ); const $jsonRecord = ( /** @type {$Record<$string,$any>} */ $record($string, $any) ); const $json2 = $union($number, $string, $null, $boolean, $jsonArr, $jsonRecord); $jsonArr.shape = $json2; $jsonRecord.shape.values = $json2; return $json2; })(); var $ = (o2) => { if ($$schema.check(o2)) { return ( /** @type {any} */ o2 ); } else if ($objectAny.check(o2)) { const o22 = {}; for (const k3 in o2) { o22[k3] = $(o2[k3]); } return ( /** @type {any} */ $object(o22) ); } else if ($arrayAny.check(o2)) { return ( /** @type {any} */ $union(...o2.map($)) ); } else if ($primitive.check(o2)) { return ( /** @type {any} */ $literal(o2) ); } else if ($function.check(o2)) { return ( /** @type {any} */ $constructedBy( /** @type {any} */ o2 ) ); } unexpectedCase(); }; var assert = production ? () => { } : (o2, schema) => { const err = new ValidationError(); if (!schema.check(o2, err)) { throw create3(`Expected value to be of type ${schema.constructor.name}. ${err.toString()}`); } }; var PatternMatcher = class { /** * @param {Schema} [$state] */ constructor($state) { this.patterns = []; this.$state = $state; } /** * @template P * @template R * @param {P} pattern * @param {(o:NoInfer>>,s:State)=>R} handler * @return {PatternMatcher>,R>>} */ if(pattern, handler) { this.patterns.push({ if: $(pattern), h: handler }); return this; } /** * @template R * @param {(o:any,s:State)=>R} h */ else(h7) { return this.if($any, h7); } /** * @return {State extends undefined * ? >(o:In,state?:undefined)=>PatternMatchResult * : >(o:In,state:State)=>PatternMatchResult} */ done() { return ( /** @type {any} */ (o2, s2) => { for (let i3 = 0; i3 < this.patterns.length; i3++) { const p4 = this.patterns[i3]; if (p4.if.check(o2)) { return p4.h(o2, s2); } } throw create3("Unhandled pattern"); } ); } }; var match = (state) => new PatternMatcher( /** @type {any} */ state ); var _random = ( /** @type {any} */ match( /** @type {Schema} */ $any ).if($$number, (_o3, gen) => int53(gen, MIN_SAFE_INTEGER, MAX_SAFE_INTEGER)).if($$string, (_o3, gen) => word(gen)).if($$boolean, (_o3, gen) => bool(gen)).if($$bigint, (_o3, gen) => BigInt(int53(gen, MIN_SAFE_INTEGER, MAX_SAFE_INTEGER))).if($$union, (o2, gen) => random(gen, oneOf2(gen, o2.shape))).if($$object, (o2, gen) => { const res = {}; for (const k3 in o2.shape) { let prop = o2.shape[k3]; if ($$optional.check(prop)) { if (bool(gen)) { continue; } prop = prop.shape; } res[k3] = _random(prop, gen); } return res; }).if($$array, (o2, gen) => { const arr = []; const n = int32(gen, 0, 42); for (let i3 = 0; i3 < n; i3++) { arr.push(random(gen, o2.shape)); } return arr; }).if($$literal, (o2, gen) => { return oneOf2(gen, o2.shape); }).if($$null, (o2, gen) => { return null; }).if($$lambda, (o2, gen) => { const res = random(gen, o2.res); return () => res; }).if($$any, (o2, gen) => random(gen, oneOf2(gen, [ $number, $string, $null, $undefined, $bigint, $boolean, $array($number), $record($union("a", "b", "c"), $number) ]))).if($$record, (o2, gen) => { const res = {}; const keysN = int53(gen, 0, 3); for (let i3 = 0; i3 < keysN; i3++) { const key2 = random(gen, o2.shape.keys); const val = random(gen, o2.shape.values); res[key2] = val; } return res; }).done() ); var random = (gen, schema) => ( /** @type {any} */ _random($(schema), gen) ); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/dom.js var doc3 = ( /** @type {Document} */ typeof document !== "undefined" ? document : {} ); var $fragment = $custom((el2) => el2.nodeType === DOCUMENT_FRAGMENT_NODE); var domParser = ( /** @type {DOMParser} */ typeof DOMParser !== "undefined" ? new DOMParser() : null ); var $element = $custom((el2) => el2.nodeType === ELEMENT_NODE); var $text = $custom((el2) => el2.nodeType === TEXT_NODE); var mapToStyleString = (m2) => map(m2, (value, key2) => `${key2}:${value};`).join(""); var ELEMENT_NODE = doc3.ELEMENT_NODE; var TEXT_NODE = doc3.TEXT_NODE; var CDATA_SECTION_NODE = doc3.CDATA_SECTION_NODE; var COMMENT_NODE = doc3.COMMENT_NODE; var DOCUMENT_NODE = doc3.DOCUMENT_NODE; var DOCUMENT_TYPE_NODE = doc3.DOCUMENT_TYPE_NODE; var DOCUMENT_FRAGMENT_NODE = doc3.DOCUMENT_FRAGMENT_NODE; var $node = $custom((el2) => el2.nodeType === DOCUMENT_NODE); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/eventloop.js var createTimeoutClass = (clearFunction) => class TT { /** * @param {number} timeoutId */ constructor(timeoutId) { this._ = timeoutId; } destroy() { clearFunction(this._); } }; var Timeout = createTimeoutClass(clearTimeout); var timeout = (timeout2, callback) => new Timeout(setTimeout(callback, timeout2)); var Interval = createTimeoutClass(clearInterval); var Animation = createTimeoutClass((arg) => typeof requestAnimationFrame !== "undefined" && cancelAnimationFrame(arg)); var Idle = createTimeoutClass((arg) => typeof cancelIdleCallback !== "undefined" && cancelIdleCallback(arg)); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/symbol.js var create6 = Symbol; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/logging.common.js var BOLD = create6(); var UNBOLD = create6(); var BLUE = create6(); var GREY = create6(); var GREEN = create6(); var RED = create6(); var PURPLE = create6(); var ORANGE = create6(); var UNCOLOR = create6(); var computeNoColorLoggingArgs = (args2) => { var _a2; if (args2.length === 1 && ((_a2 = args2[0]) == null ? void 0 : _a2.constructor) === Function) { args2 = /** @type {Array} */ /** @type {[function]} */ args2[0](); } const strBuilder = []; const logArgs = []; let i3 = 0; for (; i3 < args2.length; i3++) { const arg = args2[i3]; if (arg === void 0) { break; } else if (arg.constructor === String || arg.constructor === Number) { strBuilder.push(arg); } else if (arg.constructor === Object) { break; } } if (i3 > 0) { logArgs.push(strBuilder.join("")); } for (; i3 < args2.length; i3++) { const arg = args2[i3]; if (!(arg instanceof Symbol)) { logArgs.push(arg); } } return logArgs; }; var lastLoggingTime = getUnixTime(); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/logging.js var _browserStyleMap = { [BOLD]: create5("font-weight", "bold"), [UNBOLD]: create5("font-weight", "normal"), [BLUE]: create5("color", "blue"), [GREEN]: create5("color", "green"), [GREY]: create5("color", "grey"), [RED]: create5("color", "red"), [PURPLE]: create5("color", "purple"), [ORANGE]: create5("color", "orange"), // not well supported in chrome when debugging node with inspector - TODO: deprecate [UNCOLOR]: create5("color", "black") }; var computeBrowserLoggingArgs = (args2) => { var _a2; if (args2.length === 1 && ((_a2 = args2[0]) == null ? void 0 : _a2.constructor) === Function) { args2 = /** @type {Array} */ /** @type {[function]} */ args2[0](); } const strBuilder = []; const styles = []; const currentStyle = create(); let logArgs = []; let i3 = 0; for (; i3 < args2.length; i3++) { const arg = args2[i3]; const style3 = _browserStyleMap[arg]; if (style3 !== void 0) { currentStyle.set(style3.left, style3.right); } else { if (arg === void 0) { break; } if (arg.constructor === String || arg.constructor === Number) { const style4 = mapToStyleString(currentStyle); if (i3 > 0 || style4.length > 0) { strBuilder.push("%c" + arg); styles.push(style4); } else { strBuilder.push(arg); } } else { break; } } } if (i3 > 0) { logArgs = styles; logArgs.unshift(strBuilder.join("")); } for (; i3 < args2.length; i3++) { const arg = args2[i3]; if (!(arg instanceof Symbol)) { logArgs.push(arg); } } return logArgs; }; var computeLoggingArgs = supportsColor ? computeBrowserLoggingArgs : computeNoColorLoggingArgs; var print = (...args2) => { console.log(...computeLoggingArgs(args2)); vconsoles.forEach((vc) => vc.print(args2)); }; var warn = (...args2) => { console.warn(...computeLoggingArgs(args2)); args2.unshift(ORANGE); vconsoles.forEach((vc) => vc.print(args2)); }; var vconsoles = create2(); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/iterator.js var createIterator = (next2) => ({ /** * @return {IterableIterator} */ [Symbol.iterator]() { return this; }, // @ts-ignore next: next2 }); var iteratorFilter = (iterator, filter) => createIterator(() => { let res; do { res = iterator.next(); } while (!res.done && !filter(res.value)); return res; }); var iteratorMap = (iterator, fmap) => createIterator(() => { const { done, value } = iterator.next(); return { done, value: done ? void 0 : fmap(value) }; }); // ../../node_modules/.pnpm/yjs@13.6.28/node_modules/yjs/dist/yjs.mjs var DeleteItem = class { /** * @param {number} clock * @param {number} len */ constructor(clock, len) { this.clock = clock; this.len = len; } }; var DeleteSet = class { constructor() { this.clients = /* @__PURE__ */ new Map(); } }; var iterateDeletedStructs = (transaction, ds, f6) => ds.clients.forEach((deletes, clientid) => { const structs = ( /** @type {Array} */ transaction.doc.store.clients.get(clientid) ); if (structs != null) { const lastStruct = structs[structs.length - 1]; const clockState = lastStruct.id.clock + lastStruct.length; for (let i3 = 0, del3 = deletes[i3]; i3 < deletes.length && del3.clock < clockState; del3 = deletes[++i3]) { iterateStructs(transaction, structs, del3.clock, del3.len, f6); } } }); var findIndexDS = (dis, clock) => { let left = 0; let right = dis.length - 1; while (left <= right) { const midindex = floor((left + right) / 2); const mid = dis[midindex]; const midclock = mid.clock; if (midclock <= clock) { if (clock < midclock + mid.len) { return midindex; } left = midindex + 1; } else { right = midindex - 1; } } return null; }; var isDeleted = (ds, id2) => { const dis = ds.clients.get(id2.client); return dis !== void 0 && findIndexDS(dis, id2.clock) !== null; }; var sortAndMergeDeleteSet = (ds) => { ds.clients.forEach((dels) => { dels.sort((a3, b4) => a3.clock - b4.clock); let i3, j4; for (i3 = 1, j4 = 1; i3 < dels.length; i3++) { const left = dels[j4 - 1]; const right = dels[i3]; if (left.clock + left.len >= right.clock) { left.len = max(left.len, right.clock + right.len - left.clock); } else { if (j4 < i3) { dels[j4] = right; } j4++; } } dels.length = j4; }); }; var mergeDeleteSets = (dss) => { const merged = new DeleteSet(); for (let dssI = 0; dssI < dss.length; dssI++) { dss[dssI].clients.forEach((delsLeft, client) => { if (!merged.clients.has(client)) { const dels = delsLeft.slice(); for (let i3 = dssI + 1; i3 < dss.length; i3++) { appendTo(dels, dss[i3].clients.get(client) || []); } merged.clients.set(client, dels); } }); } sortAndMergeDeleteSet(merged); return merged; }; var addToDeleteSet = (ds, client, clock, length2) => { setIfUndefined(ds.clients, client, () => ( /** @type {Array} */ [] )).push(new DeleteItem(clock, length2)); }; var createDeleteSet = () => new DeleteSet(); var createDeleteSetFromStructStore = (ss) => { const ds = createDeleteSet(); ss.clients.forEach((structs, client) => { const dsitems = []; for (let i3 = 0; i3 < structs.length; i3++) { const struct = structs[i3]; if (struct.deleted) { const clock = struct.id.clock; let len = struct.length; if (i3 + 1 < structs.length) { for (let next2 = structs[i3 + 1]; i3 + 1 < structs.length && next2.deleted; next2 = structs[++i3 + 1]) { len += next2.length; } } dsitems.push(new DeleteItem(clock, len)); } } if (dsitems.length > 0) { ds.clients.set(client, dsitems); } }); return ds; }; var writeDeleteSet = (encoder, ds) => { writeVarUint(encoder.restEncoder, ds.clients.size); from2(ds.clients.entries()).sort((a3, b4) => b4[0] - a3[0]).forEach(([client, dsitems]) => { encoder.resetDsCurVal(); writeVarUint(encoder.restEncoder, client); const len = dsitems.length; writeVarUint(encoder.restEncoder, len); for (let i3 = 0; i3 < len; i3++) { const item = dsitems[i3]; encoder.writeDsClock(item.clock); encoder.writeDsLen(item.len); } }); }; var readDeleteSet = (decoder) => { const ds = new DeleteSet(); const numClients = readVarUint(decoder.restDecoder); for (let i3 = 0; i3 < numClients; i3++) { decoder.resetDsCurVal(); const client = readVarUint(decoder.restDecoder); const numberOfDeletes = readVarUint(decoder.restDecoder); if (numberOfDeletes > 0) { const dsField = setIfUndefined(ds.clients, client, () => ( /** @type {Array} */ [] )); for (let i4 = 0; i4 < numberOfDeletes; i4++) { dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen())); } } } return ds; }; var readAndApplyDeleteSet = (decoder, transaction, store) => { const unappliedDS = new DeleteSet(); const numClients = readVarUint(decoder.restDecoder); for (let i3 = 0; i3 < numClients; i3++) { decoder.resetDsCurVal(); const client = readVarUint(decoder.restDecoder); const numberOfDeletes = readVarUint(decoder.restDecoder); const structs = store.clients.get(client) || []; const state = getState(store, client); for (let i4 = 0; i4 < numberOfDeletes; i4++) { const clock = decoder.readDsClock(); const clockEnd = clock + decoder.readDsLen(); if (clock < state) { if (state < clockEnd) { addToDeleteSet(unappliedDS, client, state, clockEnd - state); } let index4 = findIndexSS(structs, clock); let struct = structs[index4]; if (!struct.deleted && struct.id.clock < clock) { structs.splice(index4 + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); index4++; } while (index4 < structs.length) { struct = structs[index4++]; if (struct.id.clock < clockEnd) { if (!struct.deleted) { if (clockEnd < struct.id.clock + struct.length) { structs.splice(index4, 0, splitItem(transaction, struct, clockEnd - struct.id.clock)); } struct.delete(transaction); } } else { break; } } } else { addToDeleteSet(unappliedDS, client, clock, clockEnd - clock); } } } if (unappliedDS.clients.size > 0) { const ds = new UpdateEncoderV2(); writeVarUint(ds.restEncoder, 0); writeDeleteSet(ds, unappliedDS); return ds.toUint8Array(); } return null; }; var generateNewClientId = uint32; var Doc = class _Doc extends ObservableV2 { /** * @param {DocOpts} opts configuration */ constructor({ guid = uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta: meta2 = null, autoLoad = false, shouldLoad = true } = {}) { super(); this.gc = gc; this.gcFilter = gcFilter; this.clientID = generateNewClientId(); this.guid = guid; this.collectionid = collectionid; this.share = /* @__PURE__ */ new Map(); this.store = new StructStore(); this._transaction = null; this._transactionCleanups = []; this.subdocs = /* @__PURE__ */ new Set(); this._item = null; this.shouldLoad = shouldLoad; this.autoLoad = autoLoad; this.meta = meta2; this.isLoaded = false; this.isSynced = false; this.isDestroyed = false; this.whenLoaded = create4((resolve2) => { this.on("load", () => { this.isLoaded = true; resolve2(this); }); }); const provideSyncedPromise = () => create4((resolve2) => { const eventHandler = (isSynced) => { if (isSynced === void 0 || isSynced === true) { this.off("sync", eventHandler); resolve2(); } }; this.on("sync", eventHandler); }); this.on("sync", (isSynced) => { if (isSynced === false && this.isSynced) { this.whenSynced = provideSyncedPromise(); } this.isSynced = isSynced === void 0 || isSynced === true; if (this.isSynced && !this.isLoaded) { this.emit("load", [this]); } }); this.whenSynced = provideSyncedPromise(); } /** * Notify the parent document that you request to load data into this subdocument (if it is a subdocument). * * `load()` might be used in the future to request any provider to load the most current data. * * It is safe to call `load()` multiple times. */ load() { const item = this._item; if (item !== null && !this.shouldLoad) { transact( /** @type {any} */ item.parent.doc, (transaction) => { transaction.subdocsLoaded.add(this); }, null, true ); } this.shouldLoad = true; } getSubdocs() { return this.subdocs; } getSubdocGuids() { return new Set(from2(this.subdocs).map((doc4) => doc4.guid)); } /** * Changes that happen inside of a transaction are bundled. This means that * the observer fires _after_ the transaction is finished and that all changes * that happened inside of the transaction are sent as one message to the * other peers. * * @template T * @param {function(Transaction):T} f The function that should be executed as a transaction * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin * @return T * * @public */ transact(f6, origin = null) { return transact(this, f6, origin); } /** * Define a shared data type. * * Multiple calls of `ydoc.get(name, TypeConstructor)` yield the same result * and do not overwrite each other. I.e. * `ydoc.get(name, Y.Array) === ydoc.get(name, Y.Array)` * * After this method is called, the type is also available on `ydoc.share.get(name)`. * * *Best Practices:* * Define all types right after the Y.Doc instance is created and store them in a separate object. * Also use the typed methods `getText(name)`, `getArray(name)`, .. * * @template {typeof AbstractType} Type * @example * const ydoc = new Y.Doc(..) * const appState = { * document: ydoc.getText('document') * comments: ydoc.getArray('comments') * } * * @param {string} name * @param {Type} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ... * @return {InstanceType} The created type. Constructed with TypeConstructor * * @public */ get(name, TypeConstructor = ( /** @type {any} */ AbstractType )) { const type = setIfUndefined(this.share, name, () => { const t2 = new TypeConstructor(); t2._integrate(this, null); return t2; }); const Constr = type.constructor; if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) { if (Constr === AbstractType) { const t2 = new TypeConstructor(); t2._map = type._map; type._map.forEach( /** @param {Item?} n */ (n) => { for (; n !== null; n = n.left) { n.parent = t2; } } ); t2._start = type._start; for (let n = t2._start; n !== null; n = n.right) { n.parent = t2; } t2._length = type._length; this.share.set(name, t2); t2._integrate(this, null); return ( /** @type {InstanceType} */ t2 ); } else { throw new Error(`Type with the name ${name} has already been defined with a different constructor`); } } return ( /** @type {InstanceType} */ type ); } /** * @template T * @param {string} [name] * @return {YArray} * * @public */ getArray(name = "") { return ( /** @type {YArray} */ this.get(name, YArray) ); } /** * @param {string} [name] * @return {YText} * * @public */ getText(name = "") { return this.get(name, YText); } /** * @template T * @param {string} [name] * @return {YMap} * * @public */ getMap(name = "") { return ( /** @type {YMap} */ this.get(name, YMap) ); } /** * @param {string} [name] * @return {YXmlElement} * * @public */ getXmlElement(name = "") { return ( /** @type {YXmlElement<{[key:string]:string}>} */ this.get(name, YXmlElement) ); } /** * @param {string} [name] * @return {YXmlFragment} * * @public */ getXmlFragment(name = "") { return this.get(name, YXmlFragment); } /** * Converts the entire document into a js object, recursively traversing each yjs type * Doesn't log types that have not been defined (using ydoc.getType(..)). * * @deprecated Do not use this method and rather call toJSON directly on the shared types. * * @return {Object} */ toJSON() { const doc4 = {}; this.share.forEach((value, key2) => { doc4[key2] = value.toJSON(); }); return doc4; } /** * Emit `destroy` event and unregister all event handlers. */ destroy() { this.isDestroyed = true; from2(this.subdocs).forEach((subdoc) => subdoc.destroy()); const item = this._item; if (item !== null) { this._item = null; const content5 = ( /** @type {ContentDoc} */ item.content ); content5.doc = new _Doc({ guid: this.guid, ...content5.opts, shouldLoad: false }); content5.doc._item = item; transact( /** @type {any} */ item.parent.doc, (transaction) => { const doc4 = content5.doc; if (!item.deleted) { transaction.subdocsAdded.add(doc4); } transaction.subdocsRemoved.add(this); }, null, true ); } this.emit("destroyed", [true]); this.emit("destroy", [this]); super.destroy(); } }; var DSDecoderV1 = class { /** * @param {decoding.Decoder} decoder */ constructor(decoder) { this.restDecoder = decoder; } resetDsCurVal() { } /** * @return {number} */ readDsClock() { return readVarUint(this.restDecoder); } /** * @return {number} */ readDsLen() { return readVarUint(this.restDecoder); } }; var UpdateDecoderV1 = class extends DSDecoderV1 { /** * @return {ID} */ readLeftID() { return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)); } /** * @return {ID} */ readRightID() { return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)); } /** * Read the next client id. * Use this in favor of readID whenever possible to reduce the number of objects created. */ readClient() { return readVarUint(this.restDecoder); } /** * @return {number} info An unsigned 8-bit integer */ readInfo() { return readUint8(this.restDecoder); } /** * @return {string} */ readString() { return readVarString(this.restDecoder); } /** * @return {boolean} isKey */ readParentInfo() { return readVarUint(this.restDecoder) === 1; } /** * @return {number} info An unsigned 8-bit integer */ readTypeRef() { return readVarUint(this.restDecoder); } /** * Write len of a struct - well suited for Opt RLE encoder. * * @return {number} len */ readLen() { return readVarUint(this.restDecoder); } /** * @return {any} */ readAny() { return readAny(this.restDecoder); } /** * @return {Uint8Array} */ readBuf() { return copyUint8Array(readVarUint8Array(this.restDecoder)); } /** * Legacy implementation uses JSON parse. We use any-decoding in v2. * * @return {any} */ readJSON() { return JSON.parse(readVarString(this.restDecoder)); } /** * @return {string} */ readKey() { return readVarString(this.restDecoder); } }; var DSDecoderV2 = class { /** * @param {decoding.Decoder} decoder */ constructor(decoder) { this.dsCurrVal = 0; this.restDecoder = decoder; } resetDsCurVal() { this.dsCurrVal = 0; } /** * @return {number} */ readDsClock() { this.dsCurrVal += readVarUint(this.restDecoder); return this.dsCurrVal; } /** * @return {number} */ readDsLen() { const diff = readVarUint(this.restDecoder) + 1; this.dsCurrVal += diff; return diff; } }; var UpdateDecoderV2 = class extends DSDecoderV2 { /** * @param {decoding.Decoder} decoder */ constructor(decoder) { super(decoder); this.keys = []; readVarUint(decoder); this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); this.stringDecoder = new StringDecoder(readVarUint8Array(decoder)); this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); } /** * @return {ID} */ readLeftID() { return new ID(this.clientDecoder.read(), this.leftClockDecoder.read()); } /** * @return {ID} */ readRightID() { return new ID(this.clientDecoder.read(), this.rightClockDecoder.read()); } /** * Read the next client id. * Use this in favor of readID whenever possible to reduce the number of objects created. */ readClient() { return this.clientDecoder.read(); } /** * @return {number} info An unsigned 8-bit integer */ readInfo() { return ( /** @type {number} */ this.infoDecoder.read() ); } /** * @return {string} */ readString() { return this.stringDecoder.read(); } /** * @return {boolean} */ readParentInfo() { return this.parentInfoDecoder.read() === 1; } /** * @return {number} An unsigned 8-bit integer */ readTypeRef() { return this.typeRefDecoder.read(); } /** * Write len of a struct - well suited for Opt RLE encoder. * * @return {number} */ readLen() { return this.lenDecoder.read(); } /** * @return {any} */ readAny() { return readAny(this.restDecoder); } /** * @return {Uint8Array} */ readBuf() { return readVarUint8Array(this.restDecoder); } /** * This is mainly here for legacy purposes. * * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. * * @return {any} */ readJSON() { return readAny(this.restDecoder); } /** * @return {string} */ readKey() { const keyClock = this.keyClockDecoder.read(); if (keyClock < this.keys.length) { return this.keys[keyClock]; } else { const key2 = this.stringDecoder.read(); this.keys.push(key2); return key2; } } }; var DSEncoderV1 = class { constructor() { this.restEncoder = createEncoder(); } toUint8Array() { return toUint8Array(this.restEncoder); } resetDsCurVal() { } /** * @param {number} clock */ writeDsClock(clock) { writeVarUint(this.restEncoder, clock); } /** * @param {number} len */ writeDsLen(len) { writeVarUint(this.restEncoder, len); } }; var UpdateEncoderV1 = class extends DSEncoderV1 { /** * @param {ID} id */ writeLeftID(id2) { writeVarUint(this.restEncoder, id2.client); writeVarUint(this.restEncoder, id2.clock); } /** * @param {ID} id */ writeRightID(id2) { writeVarUint(this.restEncoder, id2.client); writeVarUint(this.restEncoder, id2.clock); } /** * Use writeClient and writeClock instead of writeID if possible. * @param {number} client */ writeClient(client) { writeVarUint(this.restEncoder, client); } /** * @param {number} info An unsigned 8-bit integer */ writeInfo(info) { writeUint8(this.restEncoder, info); } /** * @param {string} s */ writeString(s2) { writeVarString(this.restEncoder, s2); } /** * @param {boolean} isYKey */ writeParentInfo(isYKey) { writeVarUint(this.restEncoder, isYKey ? 1 : 0); } /** * @param {number} info An unsigned 8-bit integer */ writeTypeRef(info) { writeVarUint(this.restEncoder, info); } /** * Write len of a struct - well suited for Opt RLE encoder. * * @param {number} len */ writeLen(len) { writeVarUint(this.restEncoder, len); } /** * @param {any} any */ writeAny(any2) { writeAny(this.restEncoder, any2); } /** * @param {Uint8Array} buf */ writeBuf(buf) { writeVarUint8Array(this.restEncoder, buf); } /** * @param {any} embed */ writeJSON(embed) { writeVarString(this.restEncoder, JSON.stringify(embed)); } /** * @param {string} key */ writeKey(key2) { writeVarString(this.restEncoder, key2); } }; var DSEncoderV2 = class { constructor() { this.restEncoder = createEncoder(); this.dsCurrVal = 0; } toUint8Array() { return toUint8Array(this.restEncoder); } resetDsCurVal() { this.dsCurrVal = 0; } /** * @param {number} clock */ writeDsClock(clock) { const diff = clock - this.dsCurrVal; this.dsCurrVal = clock; writeVarUint(this.restEncoder, diff); } /** * @param {number} len */ writeDsLen(len) { if (len === 0) { unexpectedCase(); } writeVarUint(this.restEncoder, len - 1); this.dsCurrVal += len; } }; var UpdateEncoderV2 = class extends DSEncoderV2 { constructor() { super(); this.keyMap = /* @__PURE__ */ new Map(); this.keyClock = 0; this.keyClockEncoder = new IntDiffOptRleEncoder(); this.clientEncoder = new UintOptRleEncoder(); this.leftClockEncoder = new IntDiffOptRleEncoder(); this.rightClockEncoder = new IntDiffOptRleEncoder(); this.infoEncoder = new RleEncoder(writeUint8); this.stringEncoder = new StringEncoder(); this.parentInfoEncoder = new RleEncoder(writeUint8); this.typeRefEncoder = new UintOptRleEncoder(); this.lenEncoder = new UintOptRleEncoder(); } toUint8Array() { const encoder = createEncoder(); writeVarUint(encoder, 0); writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array()); writeVarUint8Array(encoder, this.clientEncoder.toUint8Array()); writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array()); writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array()); writeVarUint8Array(encoder, toUint8Array(this.infoEncoder)); writeVarUint8Array(encoder, this.stringEncoder.toUint8Array()); writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder)); writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array()); writeVarUint8Array(encoder, this.lenEncoder.toUint8Array()); writeUint8Array(encoder, toUint8Array(this.restEncoder)); return toUint8Array(encoder); } /** * @param {ID} id */ writeLeftID(id2) { this.clientEncoder.write(id2.client); this.leftClockEncoder.write(id2.clock); } /** * @param {ID} id */ writeRightID(id2) { this.clientEncoder.write(id2.client); this.rightClockEncoder.write(id2.clock); } /** * @param {number} client */ writeClient(client) { this.clientEncoder.write(client); } /** * @param {number} info An unsigned 8-bit integer */ writeInfo(info) { this.infoEncoder.write(info); } /** * @param {string} s */ writeString(s2) { this.stringEncoder.write(s2); } /** * @param {boolean} isYKey */ writeParentInfo(isYKey) { this.parentInfoEncoder.write(isYKey ? 1 : 0); } /** * @param {number} info An unsigned 8-bit integer */ writeTypeRef(info) { this.typeRefEncoder.write(info); } /** * Write len of a struct - well suited for Opt RLE encoder. * * @param {number} len */ writeLen(len) { this.lenEncoder.write(len); } /** * @param {any} any */ writeAny(any2) { writeAny(this.restEncoder, any2); } /** * @param {Uint8Array} buf */ writeBuf(buf) { writeVarUint8Array(this.restEncoder, buf); } /** * This is mainly here for legacy purposes. * * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. * * @param {any} embed */ writeJSON(embed) { writeAny(this.restEncoder, embed); } /** * Property keys are often reused. For example, in y-prosemirror the key `bold` might * occur very often. For a 3d application, the key `position` might occur very often. * * We cache these keys in a Map and refer to them via a unique number. * * @param {string} key */ writeKey(key2) { const clock = this.keyMap.get(key2); if (clock === void 0) { this.keyClockEncoder.write(this.keyClock++); this.stringEncoder.write(key2); } else { this.keyClockEncoder.write(clock); } } }; var writeStructs = (encoder, structs, client, clock) => { clock = max(clock, structs[0].id.clock); const startNewStructs = findIndexSS(structs, clock); writeVarUint(encoder.restEncoder, structs.length - startNewStructs); encoder.writeClient(client); writeVarUint(encoder.restEncoder, clock); const firstStruct = structs[startNewStructs]; firstStruct.write(encoder, clock - firstStruct.id.clock); for (let i3 = startNewStructs + 1; i3 < structs.length; i3++) { structs[i3].write(encoder, 0); } }; var writeClientsStructs = (encoder, store, _sm) => { const sm = /* @__PURE__ */ new Map(); _sm.forEach((clock, client) => { if (getState(store, client) > clock) { sm.set(client, clock); } }); getStateVector(store).forEach((_clock, client) => { if (!_sm.has(client)) { sm.set(client, 0); } }); writeVarUint(encoder.restEncoder, sm.size); from2(sm.entries()).sort((a3, b4) => b4[0] - a3[0]).forEach(([client, clock]) => { writeStructs( encoder, /** @type {Array} */ store.clients.get(client), client, clock ); }); }; var readClientsStructRefs = (decoder, doc4) => { const clientRefs = create(); const numOfStateUpdates = readVarUint(decoder.restDecoder); for (let i3 = 0; i3 < numOfStateUpdates; i3++) { const numberOfStructs = readVarUint(decoder.restDecoder); const refs = new Array(numberOfStructs); const client = decoder.readClient(); let clock = readVarUint(decoder.restDecoder); clientRefs.set(client, { i: 0, refs }); for (let i4 = 0; i4 < numberOfStructs; i4++) { const info = decoder.readInfo(); switch (BITS5 & info) { case 0: { const len = decoder.readLen(); refs[i4] = new GC(createID(client, clock), len); clock += len; break; } case 10: { const len = readVarUint(decoder.restDecoder); refs[i4] = new Skip(createID(client, clock), len); clock += len; break; } default: { const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0; const struct = new Item( createID(client, clock), null, // left (info & BIT8) === BIT8 ? decoder.readLeftID() : null, // origin null, // right (info & BIT7) === BIT7 ? decoder.readRightID() : null, // right origin cantCopyParentInfo ? decoder.readParentInfo() ? doc4.get(decoder.readString()) : decoder.readLeftID() : null, // parent cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, // parentSub readItemContent(decoder, info) // item content ); refs[i4] = struct; clock += struct.length; } } } } return clientRefs; }; var integrateStructs = (transaction, store, clientsStructRefs) => { const stack = []; let clientsStructRefsIds = from2(clientsStructRefs.keys()).sort((a3, b4) => a3 - b4); if (clientsStructRefsIds.length === 0) { return null; } const getNextStructTarget = () => { if (clientsStructRefsIds.length === 0) { return null; } let nextStructsTarget = ( /** @type {{i:number,refs:Array}} */ clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]) ); while (nextStructsTarget.refs.length === nextStructsTarget.i) { clientsStructRefsIds.pop(); if (clientsStructRefsIds.length > 0) { nextStructsTarget = /** @type {{i:number,refs:Array}} */ clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]); } else { return null; } } return nextStructsTarget; }; let curStructsTarget = getNextStructTarget(); if (curStructsTarget === null) { return null; } const restStructs = new StructStore(); const missingSV = /* @__PURE__ */ new Map(); const updateMissingSv = (client, clock) => { const mclock = missingSV.get(client); if (mclock == null || mclock > clock) { missingSV.set(client, clock); } }; let stackHead = ( /** @type {any} */ curStructsTarget.refs[ /** @type {any} */ curStructsTarget.i++ ] ); const state = /* @__PURE__ */ new Map(); const addStackToRestSS = () => { for (const item of stack) { const client = item.id.client; const inapplicableItems = clientsStructRefs.get(client); if (inapplicableItems) { inapplicableItems.i--; restStructs.clients.set(client, inapplicableItems.refs.slice(inapplicableItems.i)); clientsStructRefs.delete(client); inapplicableItems.i = 0; inapplicableItems.refs = []; } else { restStructs.clients.set(client, [item]); } clientsStructRefsIds = clientsStructRefsIds.filter((c3) => c3 !== client); } stack.length = 0; }; while (true) { if (stackHead.constructor !== Skip) { const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client)); const offset4 = localClock - stackHead.id.clock; if (offset4 < 0) { stack.push(stackHead); updateMissingSv(stackHead.id.client, stackHead.id.clock - 1); addStackToRestSS(); } else { const missing = stackHead.getMissing(transaction, store); if (missing !== null) { stack.push(stackHead); const structRefs = clientsStructRefs.get( /** @type {number} */ missing ) || { refs: [], i: 0 }; if (structRefs.refs.length === structRefs.i) { updateMissingSv( /** @type {number} */ missing, getState(store, missing) ); addStackToRestSS(); } else { stackHead = structRefs.refs[structRefs.i++]; continue; } } else if (offset4 === 0 || offset4 < stackHead.length) { stackHead.integrate(transaction, offset4); state.set(stackHead.id.client, stackHead.id.clock + stackHead.length); } } } if (stack.length > 0) { stackHead = /** @type {GC|Item} */ stack.pop(); } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) { stackHead = /** @type {GC|Item} */ curStructsTarget.refs[curStructsTarget.i++]; } else { curStructsTarget = getNextStructTarget(); if (curStructsTarget === null) { break; } else { stackHead = /** @type {GC|Item} */ curStructsTarget.refs[curStructsTarget.i++]; } } } if (restStructs.clients.size > 0) { const encoder = new UpdateEncoderV2(); writeClientsStructs(encoder, restStructs, /* @__PURE__ */ new Map()); writeVarUint(encoder.restEncoder, 0); return { missing: missingSV, update: encoder.toUint8Array() }; } return null; }; var writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState); var readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => transact(ydoc, (transaction) => { transaction.local = false; let retry = false; const doc4 = transaction.doc; const store = doc4.store; const ss = readClientsStructRefs(structDecoder, doc4); const restStructs = integrateStructs(transaction, store, ss); const pending = store.pendingStructs; if (pending) { for (const [client, clock] of pending.missing) { if (clock < getState(store, client)) { retry = true; break; } } if (restStructs) { for (const [client, clock] of restStructs.missing) { const mclock = pending.missing.get(client); if (mclock == null || mclock > clock) { pending.missing.set(client, clock); } } pending.update = mergeUpdatesV2([pending.update, restStructs.update]); } } else { store.pendingStructs = restStructs; } const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store); if (store.pendingDs) { const pendingDSUpdate = new UpdateDecoderV2(createDecoder(store.pendingDs)); readVarUint(pendingDSUpdate.restDecoder); const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store); if (dsRest && dsRest2) { store.pendingDs = mergeUpdatesV2([dsRest, dsRest2]); } else { store.pendingDs = dsRest || dsRest2; } } else { store.pendingDs = dsRest; } if (retry) { const update = ( /** @type {{update: Uint8Array}} */ store.pendingStructs.update ); store.pendingStructs = null; applyUpdateV2(transaction.doc, update); } }, transactionOrigin, false); var applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => { const decoder = createDecoder(update); readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder)); }; var applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1); var writeStateAsUpdate = (encoder, doc4, targetStateVector = /* @__PURE__ */ new Map()) => { writeClientsStructs(encoder, doc4.store, targetStateVector); writeDeleteSet(encoder, createDeleteSetFromStructStore(doc4.store)); }; var encodeStateAsUpdateV2 = (doc4, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => { const targetStateVector = decodeStateVector(encodedTargetStateVector); writeStateAsUpdate(encoder, doc4, targetStateVector); const updates = [encoder.toUint8Array()]; if (doc4.store.pendingDs) { updates.push(doc4.store.pendingDs); } if (doc4.store.pendingStructs) { updates.push(diffUpdateV2(doc4.store.pendingStructs.update, encodedTargetStateVector)); } if (updates.length > 1) { if (encoder.constructor === UpdateEncoderV1) { return mergeUpdates(updates.map((update, i3) => i3 === 0 ? update : convertUpdateFormatV2ToV1(update))); } else if (encoder.constructor === UpdateEncoderV2) { return mergeUpdatesV2(updates); } } return updates[0]; }; var encodeStateAsUpdate = (doc4, encodedTargetStateVector) => encodeStateAsUpdateV2(doc4, encodedTargetStateVector, new UpdateEncoderV1()); var readStateVector = (decoder) => { const ss = /* @__PURE__ */ new Map(); const ssLength = readVarUint(decoder.restDecoder); for (let i3 = 0; i3 < ssLength; i3++) { const client = readVarUint(decoder.restDecoder); const clock = readVarUint(decoder.restDecoder); ss.set(client, clock); } return ss; }; var decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState))); var writeStateVector = (encoder, sv) => { writeVarUint(encoder.restEncoder, sv.size); from2(sv.entries()).sort((a3, b4) => b4[0] - a3[0]).forEach(([client, clock]) => { writeVarUint(encoder.restEncoder, client); writeVarUint(encoder.restEncoder, clock); }); return encoder; }; var writeDocumentStateVector = (encoder, doc4) => writeStateVector(encoder, getStateVector(doc4.store)); var encodeStateVectorV2 = (doc4, encoder = new DSEncoderV2()) => { if (doc4 instanceof Map) { writeStateVector(encoder, doc4); } else { writeDocumentStateVector(encoder, doc4); } return encoder.toUint8Array(); }; var encodeStateVector = (doc4) => encodeStateVectorV2(doc4, new DSEncoderV1()); var EventHandler = class { constructor() { this.l = []; } }; var createEventHandler = () => new EventHandler(); var addEventHandlerListener = (eventHandler, f6) => eventHandler.l.push(f6); var removeEventHandlerListener = (eventHandler, f6) => { const l2 = eventHandler.l; const len = l2.length; eventHandler.l = l2.filter((g) => f6 !== g); if (len === eventHandler.l.length) { console.error("[yjs] Tried to remove event handler that doesn't exist."); } }; var callEventHandlerListeners = (eventHandler, arg0, arg1) => callAll(eventHandler.l, [arg0, arg1]); var ID = class { /** * @param {number} client client id * @param {number} clock unique per client id, continuous number */ constructor(client, clock) { this.client = client; this.clock = clock; } }; var compareIDs = (a3, b4) => a3 === b4 || a3 !== null && b4 !== null && a3.client === b4.client && a3.clock === b4.clock; var createID = (client, clock) => new ID(client, clock); var findRootTypeKey = (type) => { for (const [key2, value] of type.doc.share.entries()) { if (value === type) { return key2; } } throw unexpectedCase(); }; var isParentOf = (parent, child) => { while (child !== null) { if (child.parent === parent) { return true; } child = /** @type {AbstractType} */ child.parent._item; } return false; }; var RelativePosition = class { /** * @param {ID|null} type * @param {string|null} tname * @param {ID|null} item * @param {number} assoc */ constructor(type, tname, item, assoc = 0) { this.type = type; this.tname = tname; this.item = item; this.assoc = assoc; } }; var createRelativePositionFromJSON = (json) => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname ?? null, json.item == null ? null : createID(json.item.client, json.item.clock), json.assoc == null ? 0 : json.assoc); var AbsolutePosition = class { /** * @param {AbstractType} type * @param {number} index * @param {number} [assoc] */ constructor(type, index4, assoc = 0) { this.type = type; this.index = index4; this.assoc = assoc; } }; var createAbsolutePosition = (type, index4, assoc = 0) => new AbsolutePosition(type, index4, assoc); var createRelativePosition = (type, item, assoc) => { let typeid = null; let tname = null; if (type._item === null) { tname = findRootTypeKey(type); } else { typeid = createID(type._item.id.client, type._item.id.clock); } return new RelativePosition(typeid, tname, item, assoc); }; var createRelativePositionFromTypeIndex = (type, index4, assoc = 0) => { let t2 = type._start; if (assoc < 0) { if (index4 === 0) { return createRelativePosition(type, null, assoc); } index4--; } while (t2 !== null) { if (!t2.deleted && t2.countable) { if (t2.length > index4) { return createRelativePosition(type, createID(t2.id.client, t2.id.clock + index4), assoc); } index4 -= t2.length; } if (t2.right === null && assoc < 0) { return createRelativePosition(type, t2.lastId, assoc); } t2 = t2.right; } return createRelativePosition(type, null, assoc); }; var getItemWithOffset = (store, id2) => { const item = getItem(store, id2); const diff = id2.clock - item.id.clock; return { item, diff }; }; var createAbsolutePositionFromRelativePosition = (rpos, doc4, followUndoneDeletions = true) => { const store = doc4.store; const rightID = rpos.item; const typeID = rpos.type; const tname = rpos.tname; const assoc = rpos.assoc; let type = null; let index4 = 0; if (rightID !== null) { if (getState(store, rightID.client) <= rightID.clock) { return null; } const res = followUndoneDeletions ? followRedone(store, rightID) : getItemWithOffset(store, rightID); const right = res.item; if (!(right instanceof Item)) { return null; } type = /** @type {AbstractType} */ right.parent; if (type._item === null || !type._item.deleted) { index4 = right.deleted || !right.countable ? 0 : res.diff + (assoc >= 0 ? 0 : 1); let n = right.left; while (n !== null) { if (!n.deleted && n.countable) { index4 += n.length; } n = n.left; } } } else { if (tname !== null) { type = doc4.get(tname); } else if (typeID !== null) { if (getState(store, typeID.client) <= typeID.clock) { return null; } const { item } = followUndoneDeletions ? followRedone(store, typeID) : { item: getItem(store, typeID) }; if (item instanceof Item && item.content instanceof ContentType) { type = item.content.type; } else { return null; } } else { throw unexpectedCase(); } if (assoc >= 0) { index4 = type._length; } else { index4 = 0; } } return createAbsolutePosition(type, index4, rpos.assoc); }; var compareRelativePositions = (a3, b4) => a3 === b4 || a3 !== null && b4 !== null && a3.tname === b4.tname && compareIDs(a3.item, b4.item) && compareIDs(a3.type, b4.type) && a3.assoc === b4.assoc; var Snapshot = class { /** * @param {DeleteSet} ds * @param {Map} sv state map */ constructor(ds, sv) { this.ds = ds; this.sv = sv; } }; var createSnapshot = (ds, sm) => new Snapshot(ds, sm); var emptySnapshot = createSnapshot(createDeleteSet(), /* @__PURE__ */ new Map()); var snapshot = (doc4) => createSnapshot(createDeleteSetFromStructStore(doc4.store), getStateVector(doc4.store)); var isVisible = (item, snapshot2) => snapshot2 === void 0 ? !item.deleted : snapshot2.sv.has(item.id.client) && (snapshot2.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot2.ds, item.id); var splitSnapshotAffectedStructs = (transaction, snapshot2) => { const meta2 = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create2); const store = transaction.doc.store; if (!meta2.has(snapshot2)) { snapshot2.sv.forEach((clock, client) => { if (clock < getState(store, client)) { getItemCleanStart(transaction, createID(client, clock)); } }); iterateDeletedStructs(transaction, snapshot2.ds, (_item) => { }); meta2.add(snapshot2); } }; var StructStore = class { constructor() { this.clients = /* @__PURE__ */ new Map(); this.pendingStructs = null; this.pendingDs = null; } }; var getStateVector = (store) => { const sm = /* @__PURE__ */ new Map(); store.clients.forEach((structs, client) => { const struct = structs[structs.length - 1]; sm.set(client, struct.id.clock + struct.length); }); return sm; }; var getState = (store, client) => { const structs = store.clients.get(client); if (structs === void 0) { return 0; } const lastStruct = structs[structs.length - 1]; return lastStruct.id.clock + lastStruct.length; }; var addStruct = (store, struct) => { let structs = store.clients.get(struct.id.client); if (structs === void 0) { structs = []; store.clients.set(struct.id.client, structs); } else { const lastStruct = structs[structs.length - 1]; if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) { throw unexpectedCase(); } } structs.push(struct); }; var findIndexSS = (structs, clock) => { let left = 0; let right = structs.length - 1; let mid = structs[right]; let midclock = mid.id.clock; if (midclock === clock) { return right; } let midindex = floor(clock / (midclock + mid.length - 1) * right); while (left <= right) { mid = structs[midindex]; midclock = mid.id.clock; if (midclock <= clock) { if (clock < midclock + mid.length) { return midindex; } left = midindex + 1; } else { right = midindex - 1; } midindex = floor((left + right) / 2); } throw unexpectedCase(); }; var find = (store, id2) => { const structs = store.clients.get(id2.client); return structs[findIndexSS(structs, id2.clock)]; }; var getItem = ( /** @type {function(StructStore,ID):Item} */ find ); var findIndexCleanStart = (transaction, structs, clock) => { const index4 = findIndexSS(structs, clock); const struct = structs[index4]; if (struct.id.clock < clock && struct instanceof Item) { structs.splice(index4 + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); return index4 + 1; } return index4; }; var getItemCleanStart = (transaction, id2) => { const structs = ( /** @type {Array} */ transaction.doc.store.clients.get(id2.client) ); return structs[findIndexCleanStart(transaction, structs, id2.clock)]; }; var getItemCleanEnd = (transaction, store, id2) => { const structs = store.clients.get(id2.client); const index4 = findIndexSS(structs, id2.clock); const struct = structs[index4]; if (id2.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) { structs.splice(index4 + 1, 0, splitItem(transaction, struct, id2.clock - struct.id.clock + 1)); } return struct; }; var replaceStruct = (store, struct, newStruct) => { const structs = ( /** @type {Array} */ store.clients.get(struct.id.client) ); structs[findIndexSS(structs, struct.id.clock)] = newStruct; }; var iterateStructs = (transaction, structs, clockStart, len, f6) => { if (len === 0) { return; } const clockEnd = clockStart + len; let index4 = findIndexCleanStart(transaction, structs, clockStart); let struct; do { struct = structs[index4++]; if (clockEnd < struct.id.clock + struct.length) { findIndexCleanStart(transaction, structs, clockEnd); } f6(struct); } while (index4 < structs.length && structs[index4].id.clock < clockEnd); }; var Transaction2 = class { /** * @param {Doc} doc * @param {any} origin * @param {boolean} local */ constructor(doc4, origin, local) { this.doc = doc4; this.deleteSet = new DeleteSet(); this.beforeState = getStateVector(doc4.store); this.afterState = /* @__PURE__ */ new Map(); this.changed = /* @__PURE__ */ new Map(); this.changedParentTypes = /* @__PURE__ */ new Map(); this._mergeStructs = []; this.origin = origin; this.meta = /* @__PURE__ */ new Map(); this.local = local; this.subdocsAdded = /* @__PURE__ */ new Set(); this.subdocsRemoved = /* @__PURE__ */ new Set(); this.subdocsLoaded = /* @__PURE__ */ new Set(); this._needFormattingCleanup = false; } }; var writeUpdateMessageFromTransaction = (encoder, transaction) => { if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) { return false; } sortAndMergeDeleteSet(transaction.deleteSet); writeStructsFromTransaction(encoder, transaction); writeDeleteSet(encoder, transaction.deleteSet); return true; }; var addChangedTypeToTransaction = (transaction, type, parentSub) => { const item = type._item; if (item === null || item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted) { setIfUndefined(transaction.changed, type, create2).add(parentSub); } }; var tryToMergeWithLefts = (structs, pos) => { let right = structs[pos]; let left = structs[pos - 1]; let i3 = pos; for (; i3 > 0; right = left, left = structs[--i3 - 1]) { if (left.deleted === right.deleted && left.constructor === right.constructor) { if (left.mergeWith(right)) { if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType} */ right.parent._map.get(right.parentSub) === right) { right.parent._map.set( right.parentSub, /** @type {Item} */ left ); } continue; } } break; } const merged = pos - i3; if (merged) { structs.splice(pos + 1 - merged, merged); } return merged; }; var tryGcDeleteSet = (ds, store, gcFilter) => { for (const [client, deleteItems] of ds.clients.entries()) { const structs = ( /** @type {Array} */ store.clients.get(client) ); for (let di2 = deleteItems.length - 1; di2 >= 0; di2--) { const deleteItem = deleteItems[di2]; const endDeleteItemClock = deleteItem.clock + deleteItem.len; for (let si2 = findIndexSS(structs, deleteItem.clock), struct = structs[si2]; si2 < structs.length && struct.id.clock < endDeleteItemClock; struct = structs[++si2]) { const struct2 = structs[si2]; if (deleteItem.clock + deleteItem.len <= struct2.id.clock) { break; } if (struct2 instanceof Item && struct2.deleted && !struct2.keep && gcFilter(struct2)) { struct2.gc(store, false); } } } } }; var tryMergeDeleteSet = (ds, store) => { ds.clients.forEach((deleteItems, client) => { const structs = ( /** @type {Array} */ store.clients.get(client) ); for (let di2 = deleteItems.length - 1; di2 >= 0; di2--) { const deleteItem = deleteItems[di2]; const mostRightIndexToCheck = min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1)); for (let si2 = mostRightIndexToCheck, struct = structs[si2]; si2 > 0 && struct.id.clock >= deleteItem.clock; struct = structs[si2]) { si2 -= 1 + tryToMergeWithLefts(structs, si2); } } }); }; var cleanupTransactions = (transactionCleanups, i3) => { if (i3 < transactionCleanups.length) { const transaction = transactionCleanups[i3]; const doc4 = transaction.doc; const store = doc4.store; const ds = transaction.deleteSet; const mergeStructs = transaction._mergeStructs; try { sortAndMergeDeleteSet(ds); transaction.afterState = getStateVector(transaction.doc.store); doc4.emit("beforeObserverCalls", [transaction, doc4]); const fs = []; transaction.changed.forEach( (subs, itemtype) => fs.push(() => { if (itemtype._item === null || !itemtype._item.deleted) { itemtype._callObserver(transaction, subs); } }) ); fs.push(() => { transaction.changedParentTypes.forEach((events, type) => { if (type._dEH.l.length > 0 && (type._item === null || !type._item.deleted)) { events = events.filter( (event) => event.target._item === null || !event.target._item.deleted ); events.forEach((event) => { event.currentTarget = type; event._path = null; }); events.sort((event1, event2) => event1.path.length - event2.path.length); callEventHandlerListeners(type._dEH, events, transaction); } }); }); fs.push(() => doc4.emit("afterTransaction", [transaction, doc4])); callAll(fs, []); if (transaction._needFormattingCleanup) { cleanupYTextAfterTransaction(transaction); } } finally { if (doc4.gc) { tryGcDeleteSet(ds, store, doc4.gcFilter); } tryMergeDeleteSet(ds, store); transaction.afterState.forEach((clock, client) => { const beforeClock = transaction.beforeState.get(client) || 0; if (beforeClock !== clock) { const structs = ( /** @type {Array} */ store.clients.get(client) ); const firstChangePos = max(findIndexSS(structs, beforeClock), 1); for (let i4 = structs.length - 1; i4 >= firstChangePos; ) { i4 -= 1 + tryToMergeWithLefts(structs, i4); } } }); for (let i4 = mergeStructs.length - 1; i4 >= 0; i4--) { const { client, clock } = mergeStructs[i4].id; const structs = ( /** @type {Array} */ store.clients.get(client) ); const replacedStructPos = findIndexSS(structs, clock); if (replacedStructPos + 1 < structs.length) { if (tryToMergeWithLefts(structs, replacedStructPos + 1) > 1) { continue; } } if (replacedStructPos > 0) { tryToMergeWithLefts(structs, replacedStructPos); } } if (!transaction.local && transaction.afterState.get(doc4.clientID) !== transaction.beforeState.get(doc4.clientID)) { print(ORANGE, BOLD, "[yjs] ", UNBOLD, RED, "Changed the client-id because another client seems to be using it."); doc4.clientID = generateNewClientId(); } doc4.emit("afterTransactionCleanup", [transaction, doc4]); if (doc4._observers.has("update")) { const encoder = new UpdateEncoderV1(); const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction); if (hasContent2) { doc4.emit("update", [encoder.toUint8Array(), transaction.origin, doc4, transaction]); } } if (doc4._observers.has("updateV2")) { const encoder = new UpdateEncoderV2(); const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction); if (hasContent2) { doc4.emit("updateV2", [encoder.toUint8Array(), transaction.origin, doc4, transaction]); } } const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction; if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) { subdocsAdded.forEach((subdoc) => { subdoc.clientID = doc4.clientID; if (subdoc.collectionid == null) { subdoc.collectionid = doc4.collectionid; } doc4.subdocs.add(subdoc); }); subdocsRemoved.forEach((subdoc) => doc4.subdocs.delete(subdoc)); doc4.emit("subdocs", [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc4, transaction]); subdocsRemoved.forEach((subdoc) => subdoc.destroy()); } if (transactionCleanups.length <= i3 + 1) { doc4._transactionCleanups = []; doc4.emit("afterAllTransactions", [doc4, transactionCleanups]); } else { cleanupTransactions(transactionCleanups, i3 + 1); } } } }; var transact = (doc4, f6, origin = null, local = true) => { const transactionCleanups = doc4._transactionCleanups; let initialCall = false; let result = null; if (doc4._transaction === null) { initialCall = true; doc4._transaction = new Transaction2(doc4, origin, local); transactionCleanups.push(doc4._transaction); if (transactionCleanups.length === 1) { doc4.emit("beforeAllTransactions", [doc4]); } doc4.emit("beforeTransaction", [doc4._transaction, doc4]); } try { result = f6(doc4._transaction); } finally { if (initialCall) { const finishCleanup = doc4._transaction === transactionCleanups[0]; doc4._transaction = null; if (finishCleanup) { cleanupTransactions(transactionCleanups, 0); } } } return result; }; var StackItem = class { /** * @param {DeleteSet} deletions * @param {DeleteSet} insertions */ constructor(deletions, insertions) { this.insertions = insertions; this.deletions = deletions; this.meta = /* @__PURE__ */ new Map(); } }; var clearUndoManagerStackItem = (tr4, um, stackItem) => { iterateDeletedStructs(tr4, stackItem.deletions, (item) => { if (item instanceof Item && um.scope.some((type) => type === tr4.doc || isParentOf( /** @type {AbstractType} */ type, item ))) { keepItem(item, false); } }); }; var popStackItem = (undoManager, stack, eventType) => { let _tr = null; const doc4 = undoManager.doc; const scope = undoManager.scope; transact(doc4, (transaction) => { while (stack.length > 0 && undoManager.currStackItem === null) { const store = doc4.store; const stackItem = ( /** @type {StackItem} */ stack.pop() ); const itemsToRedo = /* @__PURE__ */ new Set(); const itemsToDelete = []; let performedChange = false; iterateDeletedStructs(transaction, stackItem.insertions, (struct) => { if (struct instanceof Item) { if (struct.redone !== null) { let { item, diff } = followRedone(store, struct.id); if (diff > 0) { item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff)); } struct = item; } if (!struct.deleted && scope.some((type) => type === transaction.doc || isParentOf( /** @type {AbstractType} */ type, /** @type {Item} */ struct ))) { itemsToDelete.push(struct); } } }); iterateDeletedStructs(transaction, stackItem.deletions, (struct) => { if (struct instanceof Item && scope.some((type) => type === transaction.doc || isParentOf( /** @type {AbstractType} */ type, struct )) && // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval. !isDeleted(stackItem.insertions, struct.id)) { itemsToRedo.add(struct); } }); itemsToRedo.forEach((struct) => { performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions, undoManager.ignoreRemoteMapChanges, undoManager) !== null || performedChange; }); for (let i3 = itemsToDelete.length - 1; i3 >= 0; i3--) { const item = itemsToDelete[i3]; if (undoManager.deleteFilter(item)) { item.delete(transaction); performedChange = true; } } undoManager.currStackItem = performedChange ? stackItem : null; } transaction.changed.forEach((subProps, type) => { if (subProps.has(null) && type._searchMarker) { type._searchMarker.length = 0; } }); _tr = transaction; }, undoManager); const res = undoManager.currStackItem; if (res != null) { const changedParentTypes = _tr.changedParentTypes; undoManager.emit("stack-item-popped", [{ stackItem: res, type: eventType, changedParentTypes, origin: undoManager }, undoManager]); undoManager.currStackItem = null; } return res; }; var UndoManager = class extends ObservableV2 { /** * @param {Doc|AbstractType|Array>} typeScope Limits the scope of the UndoManager. If this is set to a ydoc instance, all changes on that ydoc will be undone. If set to a specific type, only changes on that type or its children will be undone. Also accepts an array of types. * @param {UndoManagerOptions} options */ constructor(typeScope, { captureTimeout = 500, captureTransaction = (_tr) => true, deleteFilter = () => true, trackedOrigins = /* @__PURE__ */ new Set([null]), ignoreRemoteMapChanges = false, doc: doc4 = ( /** @type {Doc} */ isArray(typeScope) ? typeScope[0].doc : typeScope instanceof Doc ? typeScope : typeScope.doc ) } = {}) { super(); this.scope = []; this.doc = doc4; this.addToScope(typeScope); this.deleteFilter = deleteFilter; trackedOrigins.add(this); this.trackedOrigins = trackedOrigins; this.captureTransaction = captureTransaction; this.undoStack = []; this.redoStack = []; this.undoing = false; this.redoing = false; this.currStackItem = null; this.lastChange = 0; this.ignoreRemoteMapChanges = ignoreRemoteMapChanges; this.captureTimeout = captureTimeout; this.afterTransactionHandler = (transaction) => { if (!this.captureTransaction(transaction) || !this.scope.some((type) => transaction.changedParentTypes.has( /** @type {AbstractType} */ type ) || type === this.doc) || !this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor))) { return; } const undoing = this.undoing; const redoing = this.redoing; const stack = undoing ? this.redoStack : this.undoStack; if (undoing) { this.stopCapturing(); } else if (!redoing) { this.clear(false, true); } const insertions = new DeleteSet(); transaction.afterState.forEach((endClock, client) => { const startClock = transaction.beforeState.get(client) || 0; const len = endClock - startClock; if (len > 0) { addToDeleteSet(insertions, client, startClock, len); } }); const now = getUnixTime(); let didAdd = false; if (this.lastChange > 0 && now - this.lastChange < this.captureTimeout && stack.length > 0 && !undoing && !redoing) { const lastOp = stack[stack.length - 1]; lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet]); lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions]); } else { stack.push(new StackItem(transaction.deleteSet, insertions)); didAdd = true; } if (!undoing && !redoing) { this.lastChange = now; } iterateDeletedStructs( transaction, transaction.deleteSet, /** @param {Item|GC} item */ (item) => { if (item instanceof Item && this.scope.some((type) => type === transaction.doc || isParentOf( /** @type {AbstractType} */ type, item ))) { keepItem(item, true); } } ); const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? "redo" : "undo", changedParentTypes: transaction.changedParentTypes }, this]; if (didAdd) { this.emit("stack-item-added", changeEvent); } else { this.emit("stack-item-updated", changeEvent); } }; this.doc.on("afterTransaction", this.afterTransactionHandler); this.doc.on("destroy", () => { this.destroy(); }); } /** * Extend the scope. * * @param {Array | Doc> | AbstractType | Doc} ytypes */ addToScope(ytypes) { const tmpSet = new Set(this.scope); ytypes = isArray(ytypes) ? ytypes : [ytypes]; ytypes.forEach((ytype) => { if (!tmpSet.has(ytype)) { tmpSet.add(ytype); if (ytype instanceof AbstractType ? ytype.doc !== this.doc : ytype !== this.doc) warn("[yjs#509] Not same Y.Doc"); this.scope.push(ytype); } }); } /** * @param {any} origin */ addTrackedOrigin(origin) { this.trackedOrigins.add(origin); } /** * @param {any} origin */ removeTrackedOrigin(origin) { this.trackedOrigins.delete(origin); } clear(clearUndoStack = true, clearRedoStack = true) { if (clearUndoStack && this.canUndo() || clearRedoStack && this.canRedo()) { this.doc.transact((tr4) => { if (clearUndoStack) { this.undoStack.forEach((item) => clearUndoManagerStackItem(tr4, this, item)); this.undoStack = []; } if (clearRedoStack) { this.redoStack.forEach((item) => clearUndoManagerStackItem(tr4, this, item)); this.redoStack = []; } this.emit("stack-cleared", [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }]); }); } } /** * UndoManager merges Undo-StackItem if they are created within time-gap * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next * StackItem won't be merged. * * * @example * // without stopCapturing * ytext.insert(0, 'a') * ytext.insert(1, 'b') * um.undo() * ytext.toString() // => '' (note that 'ab' was removed) * // with stopCapturing * ytext.insert(0, 'a') * um.stopCapturing() * ytext.insert(0, 'b') * um.undo() * ytext.toString() // => 'a' (note that only 'b' was removed) * */ stopCapturing() { this.lastChange = 0; } /** * Undo last changes on type. * * @return {StackItem?} Returns StackItem if a change was applied */ undo() { this.undoing = true; let res; try { res = popStackItem(this, this.undoStack, "undo"); } finally { this.undoing = false; } return res; } /** * Redo last undo operation. * * @return {StackItem?} Returns StackItem if a change was applied */ redo() { this.redoing = true; let res; try { res = popStackItem(this, this.redoStack, "redo"); } finally { this.redoing = false; } return res; } /** * Are undo steps available? * * @return {boolean} `true` if undo is possible */ canUndo() { return this.undoStack.length > 0; } /** * Are redo steps available? * * @return {boolean} `true` if redo is possible */ canRedo() { return this.redoStack.length > 0; } destroy() { this.trackedOrigins.delete(this); this.doc.off("afterTransaction", this.afterTransactionHandler); super.destroy(); } }; function* lazyStructReaderGenerator(decoder) { const numOfStateUpdates = readVarUint(decoder.restDecoder); for (let i3 = 0; i3 < numOfStateUpdates; i3++) { const numberOfStructs = readVarUint(decoder.restDecoder); const client = decoder.readClient(); let clock = readVarUint(decoder.restDecoder); for (let i4 = 0; i4 < numberOfStructs; i4++) { const info = decoder.readInfo(); if (info === 10) { const len = readVarUint(decoder.restDecoder); yield new Skip(createID(client, clock), len); clock += len; } else if ((BITS5 & info) !== 0) { const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0; const struct = new Item( createID(client, clock), null, // left (info & BIT8) === BIT8 ? decoder.readLeftID() : null, // origin null, // right (info & BIT7) === BIT7 ? decoder.readRightID() : null, // right origin // @ts-ignore Force writing a string here. cantCopyParentInfo ? decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID() : null, // parent cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, // parentSub readItemContent(decoder, info) // item content ); yield struct; clock += struct.length; } else { const len = decoder.readLen(); yield new GC(createID(client, clock), len); clock += len; } } } } var LazyStructReader = class { /** * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder * @param {boolean} filterSkips */ constructor(decoder, filterSkips) { this.gen = lazyStructReaderGenerator(decoder); this.curr = null; this.done = false; this.filterSkips = filterSkips; this.next(); } /** * @return {Item | GC | Skip |null} */ next() { do { this.curr = this.gen.next().value || null; } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip); return this.curr; } }; var LazyStructWriter = class { /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder */ constructor(encoder) { this.currClient = 0; this.startClock = 0; this.written = 0; this.encoder = encoder; this.clientStructs = []; } }; var mergeUpdates = (updates) => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1); var sliceStruct = (left, diff) => { if (left.constructor === GC) { const { client, clock } = left.id; return new GC(createID(client, clock + diff), left.length - diff); } else if (left.constructor === Skip) { const { client, clock } = left.id; return new Skip(createID(client, clock + diff), left.length - diff); } else { const leftItem = ( /** @type {Item} */ left ); const { client, clock } = leftItem.id; return new Item( createID(client, clock + diff), null, createID(client, clock + diff - 1), null, leftItem.rightOrigin, leftItem.parent, leftItem.parentSub, leftItem.content.splice(diff) ); } }; var mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => { if (updates.length === 1) { return updates[0]; } const updateDecoders = updates.map((update) => new YDecoder(createDecoder(update))); let lazyStructDecoders = updateDecoders.map((decoder) => new LazyStructReader(decoder, true)); let currWrite = null; const updateEncoder = new YEncoder(); const lazyStructEncoder = new LazyStructWriter(updateEncoder); while (true) { lazyStructDecoders = lazyStructDecoders.filter((dec) => dec.curr !== null); lazyStructDecoders.sort( /** @type {function(any,any):number} */ (dec1, dec2) => { if (dec1.curr.id.client === dec2.curr.id.client) { const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock; if (clockDiff === 0) { return dec1.curr.constructor === dec2.curr.constructor ? 0 : dec1.curr.constructor === Skip ? 1 : -1; } else { return clockDiff; } } else { return dec2.curr.id.client - dec1.curr.id.client; } } ); if (lazyStructDecoders.length === 0) { break; } const currDecoder = lazyStructDecoders[0]; const firstClient = ( /** @type {Item | GC} */ currDecoder.curr.id.client ); if (currWrite !== null) { let curr = ( /** @type {Item | GC | null} */ currDecoder.curr ); let iterated = false; while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) { curr = currDecoder.next(); iterated = true; } if (curr === null || // current decoder is empty curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient` iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) { continue; } if (firstClient !== currWrite.struct.id.client) { writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); currWrite = { struct: curr, offset: 0 }; currDecoder.next(); } else { if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) { if (currWrite.struct.constructor === Skip) { currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock; } else { writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length; const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff); currWrite = { struct, offset: 0 }; } } else { const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock; if (diff > 0) { if (currWrite.struct.constructor === Skip) { currWrite.struct.length -= diff; } else { curr = sliceStruct(curr, diff); } } if (!currWrite.struct.mergeWith( /** @type {any} */ curr )) { writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); currWrite = { struct: curr, offset: 0 }; currDecoder.next(); } } } } else { currWrite = { struct: ( /** @type {Item | GC} */ currDecoder.curr ), offset: 0 }; currDecoder.next(); } for (let next2 = currDecoder.curr; next2 !== null && next2.id.client === firstClient && next2.id.clock === currWrite.struct.id.clock + currWrite.struct.length && next2.constructor !== Skip; next2 = currDecoder.next()) { writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); currWrite = { struct: next2, offset: 0 }; } } if (currWrite !== null) { writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); currWrite = null; } finishLazyStructWriting(lazyStructEncoder); const dss = updateDecoders.map((decoder) => readDeleteSet(decoder)); const ds = mergeDeleteSets(dss); writeDeleteSet(updateEncoder, ds); return updateEncoder.toUint8Array(); }; var diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => { const state = decodeStateVector(sv); const encoder = new YEncoder(); const lazyStructWriter = new LazyStructWriter(encoder); const decoder = new YDecoder(createDecoder(update)); const reader = new LazyStructReader(decoder, false); while (reader.curr) { const curr = reader.curr; const currClient = curr.id.client; const svClock = state.get(currClient) || 0; if (reader.curr.constructor === Skip) { reader.next(); continue; } if (curr.id.clock + curr.length > svClock) { writeStructToLazyStructWriter(lazyStructWriter, curr, max(svClock - curr.id.clock, 0)); reader.next(); while (reader.curr && reader.curr.id.client === currClient) { writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0); reader.next(); } } else { while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) { reader.next(); } } } finishLazyStructWriting(lazyStructWriter); const ds = readDeleteSet(decoder); writeDeleteSet(encoder, ds); return encoder.toUint8Array(); }; var flushLazyStructWriter = (lazyWriter) => { if (lazyWriter.written > 0) { lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: toUint8Array(lazyWriter.encoder.restEncoder) }); lazyWriter.encoder.restEncoder = createEncoder(); lazyWriter.written = 0; } }; var writeStructToLazyStructWriter = (lazyWriter, struct, offset4) => { if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) { flushLazyStructWriter(lazyWriter); } if (lazyWriter.written === 0) { lazyWriter.currClient = struct.id.client; lazyWriter.encoder.writeClient(struct.id.client); writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset4); } struct.write(lazyWriter.encoder, offset4); lazyWriter.written++; }; var finishLazyStructWriting = (lazyWriter) => { flushLazyStructWriter(lazyWriter); const restEncoder = lazyWriter.encoder.restEncoder; writeVarUint(restEncoder, lazyWriter.clientStructs.length); for (let i3 = 0; i3 < lazyWriter.clientStructs.length; i3++) { const partStructs = lazyWriter.clientStructs[i3]; writeVarUint(restEncoder, partStructs.written); writeUint8Array(restEncoder, partStructs.restEncoder); } }; var convertUpdateFormat = (update, blockTransformer, YDecoder, YEncoder) => { const updateDecoder = new YDecoder(createDecoder(update)); const lazyDecoder = new LazyStructReader(updateDecoder, false); const updateEncoder = new YEncoder(); const lazyWriter = new LazyStructWriter(updateEncoder); for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) { writeStructToLazyStructWriter(lazyWriter, blockTransformer(curr), 0); } finishLazyStructWriting(lazyWriter); const ds = readDeleteSet(updateDecoder); writeDeleteSet(updateEncoder, ds); return updateEncoder.toUint8Array(); }; var convertUpdateFormatV2ToV1 = (update) => convertUpdateFormat(update, id, UpdateDecoderV2, UpdateEncoderV1); var errorComputeChanges = "You must not compute changes after the event-handler fired."; var YEvent = class { /** * @param {T} target The changed type. * @param {Transaction} transaction */ constructor(target, transaction) { this.target = target; this.currentTarget = target; this.transaction = transaction; this._changes = null; this._keys = null; this._delta = null; this._path = null; } /** * Computes the path from `y` to the changed type. * * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with. * * The following property holds: * @example * let type = y * event.path.forEach(dir => { * type = type.get(dir) * }) * type === event.target // => true */ get path() { return this._path || (this._path = getPathTo(this.currentTarget, this.target)); } /** * Check if a struct is deleted by this event. * * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. * * @param {AbstractStruct} struct * @return {boolean} */ deletes(struct) { return isDeleted(this.transaction.deleteSet, struct.id); } /** * @type {Map} */ get keys() { if (this._keys === null) { if (this.transaction.doc._transactionCleanups.length === 0) { throw create3(errorComputeChanges); } const keys5 = /* @__PURE__ */ new Map(); const target = this.target; const changed = ( /** @type Set */ this.transaction.changed.get(target) ); changed.forEach((key2) => { if (key2 !== null) { const item = ( /** @type {Item} */ target._map.get(key2) ); let action; let oldValue; if (this.adds(item)) { let prev = item.left; while (prev !== null && this.adds(prev)) { prev = prev.left; } if (this.deletes(item)) { if (prev !== null && this.deletes(prev)) { action = "delete"; oldValue = last(prev.content.getContent()); } else { return; } } else { if (prev !== null && this.deletes(prev)) { action = "update"; oldValue = last(prev.content.getContent()); } else { action = "add"; oldValue = void 0; } } } else { if (this.deletes(item)) { action = "delete"; oldValue = last( /** @type {Item} */ item.content.getContent() ); } else { return; } } keys5.set(key2, { action, oldValue }); } }); this._keys = keys5; } return this._keys; } /** * This is a computed property. Note that this can only be safely computed during the * event call. Computing this property after other changes happened might result in * unexpected behavior (incorrect computation of deltas). A safe way to collect changes * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object. * * @type {Array<{insert?: string | Array | object | AbstractType, retain?: number, delete?: number, attributes?: Object}>} */ get delta() { return this.changes.delta; } /** * Check if a struct is added by this event. * * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. * * @param {AbstractStruct} struct * @return {boolean} */ adds(struct) { return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0); } /** * This is a computed property. Note that this can only be safely computed during the * event call. Computing this property after other changes happened might result in * unexpected behavior (incorrect computation of deltas). A safe way to collect changes * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object. * * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string, delete?:number, retain?:number}>}} */ get changes() { let changes = this._changes; if (changes === null) { if (this.transaction.doc._transactionCleanups.length === 0) { throw create3(errorComputeChanges); } const target = this.target; const added = create2(); const deleted = create2(); const delta = []; changes = { added, deleted, delta, keys: this.keys }; const changed = ( /** @type Set */ this.transaction.changed.get(target) ); if (changed.has(null)) { let lastOp = null; const packOp = () => { if (lastOp) { delta.push(lastOp); } }; for (let item = target._start; item !== null; item = item.right) { if (item.deleted) { if (this.deletes(item) && !this.adds(item)) { if (lastOp === null || lastOp.delete === void 0) { packOp(); lastOp = { delete: 0 }; } lastOp.delete += item.length; deleted.add(item); } } else { if (this.adds(item)) { if (lastOp === null || lastOp.insert === void 0) { packOp(); lastOp = { insert: [] }; } lastOp.insert = lastOp.insert.concat(item.content.getContent()); added.add(item); } else { if (lastOp === null || lastOp.retain === void 0) { packOp(); lastOp = { retain: 0 }; } lastOp.retain += item.length; } } } if (lastOp !== null && lastOp.retain === void 0) { packOp(); } } this._changes = changes; } return ( /** @type {any} */ changes ); } }; var getPathTo = (parent, child) => { const path2 = []; while (child._item !== null && child !== parent) { if (child._item.parentSub !== null) { path2.unshift(child._item.parentSub); } else { let i3 = 0; let c3 = ( /** @type {AbstractType} */ child._item.parent._start ); while (c3 !== child._item && c3 !== null) { if (!c3.deleted && c3.countable) { i3 += c3.length; } c3 = c3.right; } path2.unshift(i3); } child = /** @type {AbstractType} */ child._item.parent; } return path2; }; var warnPrematureAccess = () => { warn("Invalid access: Add Yjs type to a document before reading data."); }; var maxSearchMarker = 80; var globalSearchMarkerTimestamp = 0; var ArraySearchMarker = class { /** * @param {Item} p * @param {number} index */ constructor(p4, index4) { p4.marker = true; this.p = p4; this.index = index4; this.timestamp = globalSearchMarkerTimestamp++; } }; var refreshMarkerTimestamp = (marker) => { marker.timestamp = globalSearchMarkerTimestamp++; }; var overwriteMarker = (marker, p4, index4) => { marker.p.marker = false; marker.p = p4; p4.marker = true; marker.index = index4; marker.timestamp = globalSearchMarkerTimestamp++; }; var markPosition = (searchMarker, p4, index4) => { if (searchMarker.length >= maxSearchMarker) { const marker = searchMarker.reduce((a3, b4) => a3.timestamp < b4.timestamp ? a3 : b4); overwriteMarker(marker, p4, index4); return marker; } else { const pm = new ArraySearchMarker(p4, index4); searchMarker.push(pm); return pm; } }; var findMarker = (yarray, index4) => { if (yarray._start === null || index4 === 0 || yarray._searchMarker === null) { return null; } const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a3, b4) => abs(index4 - a3.index) < abs(index4 - b4.index) ? a3 : b4); let p4 = yarray._start; let pindex = 0; if (marker !== null) { p4 = marker.p; pindex = marker.index; refreshMarkerTimestamp(marker); } while (p4.right !== null && pindex < index4) { if (!p4.deleted && p4.countable) { if (index4 < pindex + p4.length) { break; } pindex += p4.length; } p4 = p4.right; } while (p4.left !== null && pindex > index4) { p4 = p4.left; if (!p4.deleted && p4.countable) { pindex -= p4.length; } } while (p4.left !== null && p4.left.id.client === p4.id.client && p4.left.id.clock + p4.left.length === p4.id.clock) { p4 = p4.left; if (!p4.deleted && p4.countable) { pindex -= p4.length; } } if (marker !== null && abs(marker.index - pindex) < /** @type {YText|YArray} */ p4.parent.length / maxSearchMarker) { overwriteMarker(marker, p4, pindex); return marker; } else { return markPosition(yarray._searchMarker, p4, pindex); } }; var updateMarkerChanges = (searchMarker, index4, len) => { for (let i3 = searchMarker.length - 1; i3 >= 0; i3--) { const m2 = searchMarker[i3]; if (len > 0) { let p4 = m2.p; p4.marker = false; while (p4 && (p4.deleted || !p4.countable)) { p4 = p4.left; if (p4 && !p4.deleted && p4.countable) { m2.index -= p4.length; } } if (p4 === null || p4.marker === true) { searchMarker.splice(i3, 1); continue; } m2.p = p4; p4.marker = true; } if (index4 < m2.index || len > 0 && index4 === m2.index) { m2.index = max(index4, m2.index + len); } } }; var callTypeObservers = (type, transaction, event) => { const changedType = type; const changedParentTypes = transaction.changedParentTypes; while (true) { setIfUndefined(changedParentTypes, type, () => []).push(event); if (type._item === null) { break; } type = /** @type {AbstractType} */ type._item.parent; } callEventHandlerListeners(changedType._eH, event, transaction); }; var AbstractType = class { constructor() { this._item = null; this._map = /* @__PURE__ */ new Map(); this._start = null; this.doc = null; this._length = 0; this._eH = createEventHandler(); this._dEH = createEventHandler(); this._searchMarker = null; } /** * @return {AbstractType|null} */ get parent() { return this._item ? ( /** @type {AbstractType} */ this._item.parent ) : null; } /** * Integrate this type into the Yjs instance. * * * Save this struct in the os * * This type is sent to other client * * Observer functions are fired * * @param {Doc} y The Yjs instance * @param {Item|null} item */ _integrate(y3, item) { this.doc = y3; this._item = item; } /** * @return {AbstractType} */ _copy() { throw methodUnimplemented(); } /** * Makes a copy of this data type that can be included somewhere else. * * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. * * @return {AbstractType} */ clone() { throw methodUnimplemented(); } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder */ _write(_encoder) { } /** * The first non-deleted item */ get _first() { let n = this._start; while (n !== null && n.deleted) { n = n.right; } return n; } /** * Creates YEvent and calls all type observers. * Must be implemented by each type. * * @param {Transaction} transaction * @param {Set} _parentSubs Keys changed on this type. `null` if list was modified. */ _callObserver(transaction, _parentSubs) { if (!transaction.local && this._searchMarker) { this._searchMarker.length = 0; } } /** * Observe all events that are created on this type. * * @param {function(EventType, Transaction):void} f Observer function */ observe(f6) { addEventHandlerListener(this._eH, f6); } /** * Observe all events that are created by this type and its children. * * @param {function(Array>,Transaction):void} f Observer function */ observeDeep(f6) { addEventHandlerListener(this._dEH, f6); } /** * Unregister an observer function. * * @param {function(EventType,Transaction):void} f Observer function */ unobserve(f6) { removeEventHandlerListener(this._eH, f6); } /** * Unregister an observer function. * * @param {function(Array>,Transaction):void} f Observer function */ unobserveDeep(f6) { removeEventHandlerListener(this._dEH, f6); } /** * @abstract * @return {any} */ toJSON() { } }; var typeListSlice = (type, start, end) => { type.doc ?? warnPrematureAccess(); if (start < 0) { start = type._length + start; } if (end < 0) { end = type._length + end; } let len = end - start; const cs = []; let n = type._start; while (n !== null && len > 0) { if (n.countable && !n.deleted) { const c3 = n.content.getContent(); if (c3.length <= start) { start -= c3.length; } else { for (let i3 = start; i3 < c3.length && len > 0; i3++) { cs.push(c3[i3]); len--; } start = 0; } } n = n.right; } return cs; }; var typeListToArray = (type) => { type.doc ?? warnPrematureAccess(); const cs = []; let n = type._start; while (n !== null) { if (n.countable && !n.deleted) { const c3 = n.content.getContent(); for (let i3 = 0; i3 < c3.length; i3++) { cs.push(c3[i3]); } } n = n.right; } return cs; }; var typeListToArraySnapshot = (type, snapshot2) => { const cs = []; let n = type._start; while (n !== null) { if (n.countable && isVisible(n, snapshot2)) { const c3 = n.content.getContent(); for (let i3 = 0; i3 < c3.length; i3++) { cs.push(c3[i3]); } } n = n.right; } return cs; }; var typeListForEach = (type, f6) => { let index4 = 0; let n = type._start; type.doc ?? warnPrematureAccess(); while (n !== null) { if (n.countable && !n.deleted) { const c3 = n.content.getContent(); for (let i3 = 0; i3 < c3.length; i3++) { f6(c3[i3], index4++, type); } } n = n.right; } }; var typeListMap = (type, f6) => { const result = []; typeListForEach(type, (c3, i3) => { result.push(f6(c3, i3, type)); }); return result; }; var typeListCreateIterator = (type) => { let n = type._start; let currentContent = null; let currentContentIndex = 0; return { [Symbol.iterator]() { return this; }, next: () => { if (currentContent === null) { while (n !== null && n.deleted) { n = n.right; } if (n === null) { return { done: true, value: void 0 }; } currentContent = n.content.getContent(); currentContentIndex = 0; n = n.right; } const value = currentContent[currentContentIndex++]; if (currentContent.length <= currentContentIndex) { currentContent = null; } return { done: false, value }; } }; }; var typeListGet = (type, index4) => { type.doc ?? warnPrematureAccess(); const marker = findMarker(type, index4); let n = type._start; if (marker !== null) { n = marker.p; index4 -= marker.index; } for (; n !== null; n = n.right) { if (!n.deleted && n.countable) { if (index4 < n.length) { return n.content.getContent()[index4]; } index4 -= n.length; } } }; var typeListInsertGenericsAfter = (transaction, parent, referenceItem, content5) => { let left = referenceItem; const doc4 = transaction.doc; const ownClientId = doc4.clientID; const store = doc4.store; const right = referenceItem === null ? parent._start : referenceItem.right; let jsonContent = []; const packJsonContent = () => { if (jsonContent.length > 0) { left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent)); left.integrate(transaction, 0); jsonContent = []; } }; content5.forEach((c3) => { if (c3 === null) { jsonContent.push(c3); } else { switch (c3.constructor) { case Number: case Object: case Boolean: case Array: case String: jsonContent.push(c3); break; default: packJsonContent(); switch (c3.constructor) { case Uint8Array: case ArrayBuffer: left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array( /** @type {Uint8Array} */ c3 ))); left.integrate(transaction, 0); break; case Doc: left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc( /** @type {Doc} */ c3 )); left.integrate(transaction, 0); break; default: if (c3 instanceof AbstractType) { left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c3)); left.integrate(transaction, 0); } else { throw new Error("Unexpected content type in insert operation"); } } } } }); packJsonContent(); }; var lengthExceeded = () => create3("Length exceeded!"); var typeListInsertGenerics = (transaction, parent, index4, content5) => { if (index4 > parent._length) { throw lengthExceeded(); } if (index4 === 0) { if (parent._searchMarker) { updateMarkerChanges(parent._searchMarker, index4, content5.length); } return typeListInsertGenericsAfter(transaction, parent, null, content5); } const startIndex = index4; const marker = findMarker(parent, index4); let n = parent._start; if (marker !== null) { n = marker.p; index4 -= marker.index; if (index4 === 0) { n = n.prev; index4 += n && n.countable && !n.deleted ? n.length : 0; } } for (; n !== null; n = n.right) { if (!n.deleted && n.countable) { if (index4 <= n.length) { if (index4 < n.length) { getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index4)); } break; } index4 -= n.length; } } if (parent._searchMarker) { updateMarkerChanges(parent._searchMarker, startIndex, content5.length); } return typeListInsertGenericsAfter(transaction, parent, n, content5); }; var typeListPushGenerics = (transaction, parent, content5) => { const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start }); let n = marker.p; if (n) { while (n.right) { n = n.right; } } return typeListInsertGenericsAfter(transaction, parent, n, content5); }; var typeListDelete = (transaction, parent, index4, length2) => { if (length2 === 0) { return; } const startIndex = index4; const startLength = length2; const marker = findMarker(parent, index4); let n = parent._start; if (marker !== null) { n = marker.p; index4 -= marker.index; } for (; n !== null && index4 > 0; n = n.right) { if (!n.deleted && n.countable) { if (index4 < n.length) { getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index4)); } index4 -= n.length; } } while (length2 > 0 && n !== null) { if (!n.deleted) { if (length2 < n.length) { getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length2)); } n.delete(transaction); length2 -= n.length; } n = n.right; } if (length2 > 0) { throw lengthExceeded(); } if (parent._searchMarker) { updateMarkerChanges( parent._searchMarker, startIndex, -startLength + length2 /* in case we remove the above exception */ ); } }; var typeMapDelete = (transaction, parent, key2) => { const c3 = parent._map.get(key2); if (c3 !== void 0) { c3.delete(transaction); } }; var typeMapSet = (transaction, parent, key2, value) => { const left = parent._map.get(key2) || null; const doc4 = transaction.doc; const ownClientId = doc4.clientID; let content5; if (value == null) { content5 = new ContentAny([value]); } else { switch (value.constructor) { case Number: case Object: case Boolean: case Array: case String: case Date: case BigInt: content5 = new ContentAny([value]); break; case Uint8Array: content5 = new ContentBinary( /** @type {Uint8Array} */ value ); break; case Doc: content5 = new ContentDoc( /** @type {Doc} */ value ); break; default: if (value instanceof AbstractType) { content5 = new ContentType(value); } else { throw new Error("Unexpected content type"); } } } new Item(createID(ownClientId, getState(doc4.store, ownClientId)), left, left && left.lastId, null, null, parent, key2, content5).integrate(transaction, 0); }; var typeMapGet = (parent, key2) => { parent.doc ?? warnPrematureAccess(); const val = parent._map.get(key2); return val !== void 0 && !val.deleted ? val.content.getContent()[val.length - 1] : void 0; }; var typeMapGetAll = (parent) => { const res = {}; parent.doc ?? warnPrematureAccess(); parent._map.forEach((value, key2) => { if (!value.deleted) { res[key2] = value.content.getContent()[value.length - 1]; } }); return res; }; var typeMapHas = (parent, key2) => { parent.doc ?? warnPrematureAccess(); const val = parent._map.get(key2); return val !== void 0 && !val.deleted; }; var typeMapGetAllSnapshot = (parent, snapshot2) => { const res = {}; parent._map.forEach((value, key2) => { let v8 = value; while (v8 !== null && (!snapshot2.sv.has(v8.id.client) || v8.id.clock >= (snapshot2.sv.get(v8.id.client) || 0))) { v8 = v8.left; } if (v8 !== null && isVisible(v8, snapshot2)) { res[key2] = v8.content.getContent()[v8.length - 1]; } }); return res; }; var createMapIterator = (type) => { type.doc ?? warnPrematureAccess(); return iteratorFilter( type._map.entries(), /** @param {any} entry */ (entry) => !entry[1].deleted ); }; var YArrayEvent = class extends YEvent { }; var YArray = class _YArray extends AbstractType { constructor() { super(); this._prelimContent = []; this._searchMarker = []; } /** * Construct a new YArray containing the specified items. * @template {Object|Array|number|null|string|Uint8Array} T * @param {Array} items * @return {YArray} */ static from(items) { const a3 = new _YArray(); a3.push(items); return a3; } /** * Integrate this type into the Yjs instance. * * * Save this struct in the os * * This type is sent to other client * * Observer functions are fired * * @param {Doc} y The Yjs instance * @param {Item} item */ _integrate(y3, item) { super._integrate(y3, item); this.insert( 0, /** @type {Array} */ this._prelimContent ); this._prelimContent = null; } /** * @return {YArray} */ _copy() { return new _YArray(); } /** * Makes a copy of this data type that can be included somewhere else. * * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. * * @return {YArray} */ clone() { const arr = new _YArray(); arr.insert(0, this.toArray().map( (el2) => el2 instanceof AbstractType ? ( /** @type {typeof el} */ el2.clone() ) : el2 )); return arr; } get length() { this.doc ?? warnPrematureAccess(); return this._length; } /** * Creates YArrayEvent and calls observers. * * @param {Transaction} transaction * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. */ _callObserver(transaction, parentSubs) { super._callObserver(transaction, parentSubs); callTypeObservers(this, transaction, new YArrayEvent(this, transaction)); } /** * Inserts new content at an index. * * Important: This function expects an array of content. Not just a content * object. The reason for this "weirdness" is that inserting several elements * is very efficient when it is done as a single operation. * * @example * // Insert character 'a' at position 0 * yarray.insert(0, ['a']) * // Insert numbers 1, 2 at position 1 * yarray.insert(1, [1, 2]) * * @param {number} index The index to insert content at. * @param {Array} content The array of content */ insert(index4, content5) { if (this.doc !== null) { transact(this.doc, (transaction) => { typeListInsertGenerics( transaction, this, index4, /** @type {any} */ content5 ); }); } else { this._prelimContent.splice(index4, 0, ...content5); } } /** * Appends content to this YArray. * * @param {Array} content Array of content to append. * * @todo Use the following implementation in all types. */ push(content5) { if (this.doc !== null) { transact(this.doc, (transaction) => { typeListPushGenerics( transaction, this, /** @type {any} */ content5 ); }); } else { this._prelimContent.push(...content5); } } /** * Prepends content to this YArray. * * @param {Array} content Array of content to prepend. */ unshift(content5) { this.insert(0, content5); } /** * Deletes elements starting from an index. * * @param {number} index Index at which to start deleting elements * @param {number} length The number of elements to remove. Defaults to 1. */ delete(index4, length2 = 1) { if (this.doc !== null) { transact(this.doc, (transaction) => { typeListDelete(transaction, this, index4, length2); }); } else { this._prelimContent.splice(index4, length2); } } /** * Returns the i-th element from a YArray. * * @param {number} index The index of the element to return from the YArray * @return {T} */ get(index4) { return typeListGet(this, index4); } /** * Transforms this YArray to a JavaScript Array. * * @return {Array} */ toArray() { return typeListToArray(this); } /** * Returns a portion of this YArray into a JavaScript Array selected * from start to end (end not included). * * @param {number} [start] * @param {number} [end] * @return {Array} */ slice(start = 0, end = this.length) { return typeListSlice(this, start, end); } /** * Transforms this Shared Type to a JSON object. * * @return {Array} */ toJSON() { return this.map((c3) => c3 instanceof AbstractType ? c3.toJSON() : c3); } /** * Returns an Array with the result of calling a provided function on every * element of this YArray. * * @template M * @param {function(T,number,YArray):M} f Function that produces an element of the new Array * @return {Array} A new array with each element being the result of the * callback function */ map(f6) { return typeListMap( this, /** @type {any} */ f6 ); } /** * Executes a provided function once on every element of this YArray. * * @param {function(T,number,YArray):void} f A function to execute on every element of this YArray. */ forEach(f6) { typeListForEach(this, f6); } /** * @return {IterableIterator} */ [Symbol.iterator]() { return typeListCreateIterator(this); } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder */ _write(encoder) { encoder.writeTypeRef(YArrayRefID); } }; var readYArray = (_decoder) => new YArray(); var YMapEvent = class extends YEvent { /** * @param {YMap} ymap The YArray that changed. * @param {Transaction} transaction * @param {Set} subs The keys that changed. */ constructor(ymap, transaction, subs) { super(ymap, transaction); this.keysChanged = subs; } }; var YMap = class _YMap extends AbstractType { /** * * @param {Iterable=} entries - an optional iterable to initialize the YMap */ constructor(entries) { super(); this._prelimContent = null; if (entries === void 0) { this._prelimContent = /* @__PURE__ */ new Map(); } else { this._prelimContent = new Map(entries); } } /** * Integrate this type into the Yjs instance. * * * Save this struct in the os * * This type is sent to other client * * Observer functions are fired * * @param {Doc} y The Yjs instance * @param {Item} item */ _integrate(y3, item) { super._integrate(y3, item); this._prelimContent.forEach((value, key2) => { this.set(key2, value); }); this._prelimContent = null; } /** * @return {YMap} */ _copy() { return new _YMap(); } /** * Makes a copy of this data type that can be included somewhere else. * * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. * * @return {YMap} */ clone() { const map7 = new _YMap(); this.forEach((value, key2) => { map7.set(key2, value instanceof AbstractType ? ( /** @type {typeof value} */ value.clone() ) : value); }); return map7; } /** * Creates YMapEvent and calls observers. * * @param {Transaction} transaction * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. */ _callObserver(transaction, parentSubs) { callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs)); } /** * Transforms this Shared Type to a JSON object. * * @return {Object} */ toJSON() { this.doc ?? warnPrematureAccess(); const map7 = {}; this._map.forEach((item, key2) => { if (!item.deleted) { const v8 = item.content.getContent()[item.length - 1]; map7[key2] = v8 instanceof AbstractType ? v8.toJSON() : v8; } }); return map7; } /** * Returns the size of the YMap (count of key/value pairs) * * @return {number} */ get size() { return [...createMapIterator(this)].length; } /** * Returns the keys for each element in the YMap Type. * * @return {IterableIterator} */ keys() { return iteratorMap( createMapIterator(this), /** @param {any} v */ (v8) => v8[0] ); } /** * Returns the values for each element in the YMap Type. * * @return {IterableIterator} */ values() { return iteratorMap( createMapIterator(this), /** @param {any} v */ (v8) => v8[1].content.getContent()[v8[1].length - 1] ); } /** * Returns an Iterator of [key, value] pairs * * @return {IterableIterator<[string, MapType]>} */ entries() { return iteratorMap( createMapIterator(this), /** @param {any} v */ (v8) => ( /** @type {any} */ [v8[0], v8[1].content.getContent()[v8[1].length - 1]] ) ); } /** * Executes a provided function on once on every key-value pair. * * @param {function(MapType,string,YMap):void} f A function to execute on every element of this YArray. */ forEach(f6) { this.doc ?? warnPrematureAccess(); this._map.forEach((item, key2) => { if (!item.deleted) { f6(item.content.getContent()[item.length - 1], key2, this); } }); } /** * Returns an Iterator of [key, value] pairs * * @return {IterableIterator<[string, MapType]>} */ [Symbol.iterator]() { return this.entries(); } /** * Remove a specified element from this YMap. * * @param {string} key The key of the element to remove. */ delete(key2) { if (this.doc !== null) { transact(this.doc, (transaction) => { typeMapDelete(transaction, this, key2); }); } else { this._prelimContent.delete(key2); } } /** * Adds or updates an element with a specified key and value. * @template {MapType} VAL * * @param {string} key The key of the element to add to this YMap * @param {VAL} value The value of the element to add * @return {VAL} */ set(key2, value) { if (this.doc !== null) { transact(this.doc, (transaction) => { typeMapSet( transaction, this, key2, /** @type {any} */ value ); }); } else { this._prelimContent.set(key2, value); } return value; } /** * Returns a specified element from this YMap. * * @param {string} key * @return {MapType|undefined} */ get(key2) { return ( /** @type {any} */ typeMapGet(this, key2) ); } /** * Returns a boolean indicating whether the specified key exists or not. * * @param {string} key The key to test. * @return {boolean} */ has(key2) { return typeMapHas(this, key2); } /** * Removes all elements from this YMap. */ clear() { if (this.doc !== null) { transact(this.doc, (transaction) => { this.forEach(function(_value, key2, map7) { typeMapDelete(transaction, map7, key2); }); }); } else { this._prelimContent.clear(); } } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder */ _write(encoder) { encoder.writeTypeRef(YMapRefID); } }; var readYMap = (_decoder) => new YMap(); var equalAttrs = (a3, b4) => a3 === b4 || typeof a3 === "object" && typeof b4 === "object" && a3 && b4 && equalFlat(a3, b4); var ItemTextListPosition = class { /** * @param {Item|null} left * @param {Item|null} right * @param {number} index * @param {Map} currentAttributes */ constructor(left, right, index4, currentAttributes) { this.left = left; this.right = right; this.index = index4; this.currentAttributes = currentAttributes; } /** * Only call this if you know that this.right is defined */ forward() { if (this.right === null) { unexpectedCase(); } switch (this.right.content.constructor) { case ContentFormat: if (!this.right.deleted) { updateCurrentAttributes( this.currentAttributes, /** @type {ContentFormat} */ this.right.content ); } break; default: if (!this.right.deleted) { this.index += this.right.length; } break; } this.left = this.right; this.right = this.right.right; } }; var findNextPosition = (transaction, pos, count2) => { while (pos.right !== null && count2 > 0) { switch (pos.right.content.constructor) { case ContentFormat: if (!pos.right.deleted) { updateCurrentAttributes( pos.currentAttributes, /** @type {ContentFormat} */ pos.right.content ); } break; default: if (!pos.right.deleted) { if (count2 < pos.right.length) { getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count2)); } pos.index += pos.right.length; count2 -= pos.right.length; } break; } pos.left = pos.right; pos.right = pos.right.right; } return pos; }; var findPosition = (transaction, parent, index4, useSearchMarker) => { const currentAttributes = /* @__PURE__ */ new Map(); const marker = useSearchMarker ? findMarker(parent, index4) : null; if (marker) { const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes); return findNextPosition(transaction, pos, index4 - marker.index); } else { const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes); return findNextPosition(transaction, pos, index4); } }; var insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => { while (currPos.right !== null && (currPos.right.deleted === true || currPos.right.content.constructor === ContentFormat && equalAttrs( negatedAttributes.get( /** @type {ContentFormat} */ currPos.right.content.key ), /** @type {ContentFormat} */ currPos.right.content.value ))) { if (!currPos.right.deleted) { negatedAttributes.delete( /** @type {ContentFormat} */ currPos.right.content.key ); } currPos.forward(); } const doc4 = transaction.doc; const ownClientId = doc4.clientID; negatedAttributes.forEach((val, key2) => { const left = currPos.left; const right = currPos.right; const nextFormat = new Item(createID(ownClientId, getState(doc4.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key2, val)); nextFormat.integrate(transaction, 0); currPos.right = nextFormat; currPos.forward(); }); }; var updateCurrentAttributes = (currentAttributes, format) => { const { key: key2, value } = format; if (value === null) { currentAttributes.delete(key2); } else { currentAttributes.set(key2, value); } }; var minimizeAttributeChanges = (currPos, attributes) => { while (true) { if (currPos.right === null) { break; } else if (currPos.right.deleted || currPos.right.content.constructor === ContentFormat && equalAttrs( attributes[ /** @type {ContentFormat} */ currPos.right.content.key ] ?? null, /** @type {ContentFormat} */ currPos.right.content.value )) ; else { break; } currPos.forward(); } }; var insertAttributes = (transaction, parent, currPos, attributes) => { const doc4 = transaction.doc; const ownClientId = doc4.clientID; const negatedAttributes = /* @__PURE__ */ new Map(); for (const key2 in attributes) { const val = attributes[key2]; const currentVal = currPos.currentAttributes.get(key2) ?? null; if (!equalAttrs(currentVal, val)) { negatedAttributes.set(key2, currentVal); const { left, right } = currPos; currPos.right = new Item(createID(ownClientId, getState(doc4.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key2, val)); currPos.right.integrate(transaction, 0); currPos.forward(); } } return negatedAttributes; }; var insertText = (transaction, parent, currPos, text10, attributes) => { currPos.currentAttributes.forEach((_val, key2) => { if (attributes[key2] === void 0) { attributes[key2] = null; } }); const doc4 = transaction.doc; const ownClientId = doc4.clientID; minimizeAttributeChanges(currPos, attributes); const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); const content5 = text10.constructor === String ? new ContentString( /** @type {string} */ text10 ) : text10 instanceof AbstractType ? new ContentType(text10) : new ContentEmbed(text10); let { left, right, index: index4 } = currPos; if (parent._searchMarker) { updateMarkerChanges(parent._searchMarker, currPos.index, content5.getLength()); } right = new Item(createID(ownClientId, getState(doc4.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content5); right.integrate(transaction, 0); currPos.right = right; currPos.index = index4; currPos.forward(); insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); }; var formatText = (transaction, parent, currPos, length2, attributes) => { const doc4 = transaction.doc; const ownClientId = doc4.clientID; minimizeAttributeChanges(currPos, attributes); const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); iterationLoop: while (currPos.right !== null && (length2 > 0 || negatedAttributes.size > 0 && (currPos.right.deleted || currPos.right.content.constructor === ContentFormat))) { if (!currPos.right.deleted) { switch (currPos.right.content.constructor) { case ContentFormat: { const { key: key2, value } = ( /** @type {ContentFormat} */ currPos.right.content ); const attr2 = attributes[key2]; if (attr2 !== void 0) { if (equalAttrs(attr2, value)) { negatedAttributes.delete(key2); } else { if (length2 === 0) { break iterationLoop; } negatedAttributes.set(key2, value); } currPos.right.delete(transaction); } else { currPos.currentAttributes.set(key2, value); } break; } default: if (length2 < currPos.right.length) { getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2)); } length2 -= currPos.right.length; break; } } currPos.forward(); } if (length2 > 0) { let newlines = ""; for (; length2 > 0; length2--) { newlines += "\n"; } currPos.right = new Item(createID(ownClientId, getState(doc4.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines)); currPos.right.integrate(transaction, 0); currPos.forward(); } insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); }; var cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => { let end = start; const endFormats = create(); while (end && (!end.countable || end.deleted)) { if (!end.deleted && end.content.constructor === ContentFormat) { const cf = ( /** @type {ContentFormat} */ end.content ); endFormats.set(cf.key, cf); } end = end.right; } let cleanups = 0; let reachedCurr = false; while (start !== end) { if (curr === start) { reachedCurr = true; } if (!start.deleted) { const content5 = start.content; switch (content5.constructor) { case ContentFormat: { const { key: key2, value } = ( /** @type {ContentFormat} */ content5 ); const startAttrValue = startAttributes.get(key2) ?? null; if (endFormats.get(key2) !== content5 || startAttrValue === value) { start.delete(transaction); cleanups++; if (!reachedCurr && (currAttributes.get(key2) ?? null) === value && startAttrValue !== value) { if (startAttrValue === null) { currAttributes.delete(key2); } else { currAttributes.set(key2, startAttrValue); } } } if (!reachedCurr && !start.deleted) { updateCurrentAttributes( currAttributes, /** @type {ContentFormat} */ content5 ); } break; } } } start = /** @type {Item} */ start.right; } return cleanups; }; var cleanupContextlessFormattingGap = (transaction, item) => { while (item && item.right && (item.right.deleted || !item.right.countable)) { item = item.right; } const attrs = /* @__PURE__ */ new Set(); while (item && (item.deleted || !item.countable)) { if (!item.deleted && item.content.constructor === ContentFormat) { const key2 = ( /** @type {ContentFormat} */ item.content.key ); if (attrs.has(key2)) { item.delete(transaction); } else { attrs.add(key2); } } item = item.left; } }; var cleanupYTextFormatting = (type) => { let res = 0; transact( /** @type {Doc} */ type.doc, (transaction) => { let start = ( /** @type {Item} */ type._start ); let end = type._start; let startAttributes = create(); const currentAttributes = copy2(startAttributes); while (end) { if (end.deleted === false) { switch (end.content.constructor) { case ContentFormat: updateCurrentAttributes( currentAttributes, /** @type {ContentFormat} */ end.content ); break; default: res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes); startAttributes = copy2(currentAttributes); start = end; break; } } end = end.right; } } ); return res; }; var cleanupYTextAfterTransaction = (transaction) => { const needFullCleanup = /* @__PURE__ */ new Set(); const doc4 = transaction.doc; for (const [client, afterClock] of transaction.afterState.entries()) { const clock = transaction.beforeState.get(client) || 0; if (afterClock === clock) { continue; } iterateStructs( transaction, /** @type {Array} */ doc4.store.clients.get(client), clock, afterClock, (item) => { if (!item.deleted && /** @type {Item} */ item.content.constructor === ContentFormat && item.constructor !== GC) { needFullCleanup.add( /** @type {any} */ item.parent ); } } ); } transact(doc4, (t2) => { iterateDeletedStructs(transaction, transaction.deleteSet, (item) => { if (item instanceof GC || !/** @type {YText} */ item.parent._hasFormatting || needFullCleanup.has( /** @type {YText} */ item.parent )) { return; } const parent = ( /** @type {YText} */ item.parent ); if (item.content.constructor === ContentFormat) { needFullCleanup.add(parent); } else { cleanupContextlessFormattingGap(t2, item); } }); for (const yText of needFullCleanup) { cleanupYTextFormatting(yText); } }); }; var deleteText = (transaction, currPos, length2) => { const startLength = length2; const startAttrs = copy2(currPos.currentAttributes); const start = currPos.right; while (length2 > 0 && currPos.right !== null) { if (currPos.right.deleted === false) { switch (currPos.right.content.constructor) { case ContentType: case ContentEmbed: case ContentString: if (length2 < currPos.right.length) { getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2)); } length2 -= currPos.right.length; currPos.right.delete(transaction); break; } } currPos.forward(); } if (start) { cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes); } const parent = ( /** @type {AbstractType} */ /** @type {Item} */ (currPos.left || currPos.right).parent ); if (parent._searchMarker) { updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length2); } return currPos; }; var YTextEvent = class extends YEvent { /** * @param {YText} ytext * @param {Transaction} transaction * @param {Set} subs The keys that changed */ constructor(ytext, transaction, subs) { super(ytext, transaction); this.childListChanged = false; this.keysChanged = /* @__PURE__ */ new Set(); subs.forEach((sub) => { if (sub === null) { this.childListChanged = true; } else { this.keysChanged.add(sub); } }); } /** * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string, delete?:number, retain?:number}>}} */ get changes() { if (this._changes === null) { const changes = { keys: this.keys, delta: this.delta, added: /* @__PURE__ */ new Set(), deleted: /* @__PURE__ */ new Set() }; this._changes = changes; } return ( /** @type {any} */ this._changes ); } /** * Compute the changes in the delta format. * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document. * * @type {Array<{insert?:string|object|AbstractType, delete?:number, retain?:number, attributes?: Object}>} * * @public */ get delta() { if (this._delta === null) { const y3 = ( /** @type {Doc} */ this.target.doc ); const delta = []; transact(y3, (transaction) => { const currentAttributes = /* @__PURE__ */ new Map(); const oldAttributes = /* @__PURE__ */ new Map(); let item = this.target._start; let action = null; const attributes = {}; let insert = ""; let retain = 0; let deleteLen = 0; const addOp = () => { if (action !== null) { let op = null; switch (action) { case "delete": if (deleteLen > 0) { op = { delete: deleteLen }; } deleteLen = 0; break; case "insert": if (typeof insert === "object" || insert.length > 0) { op = { insert }; if (currentAttributes.size > 0) { op.attributes = {}; currentAttributes.forEach((value, key2) => { if (value !== null) { op.attributes[key2] = value; } }); } } insert = ""; break; case "retain": if (retain > 0) { op = { retain }; if (!isEmpty(attributes)) { op.attributes = assign({}, attributes); } } retain = 0; break; } if (op) delta.push(op); action = null; } }; while (item !== null) { switch (item.content.constructor) { case ContentType: case ContentEmbed: if (this.adds(item)) { if (!this.deletes(item)) { addOp(); action = "insert"; insert = item.content.getContent()[0]; addOp(); } } else if (this.deletes(item)) { if (action !== "delete") { addOp(); action = "delete"; } deleteLen += 1; } else if (!item.deleted) { if (action !== "retain") { addOp(); action = "retain"; } retain += 1; } break; case ContentString: if (this.adds(item)) { if (!this.deletes(item)) { if (action !== "insert") { addOp(); action = "insert"; } insert += /** @type {ContentString} */ item.content.str; } } else if (this.deletes(item)) { if (action !== "delete") { addOp(); action = "delete"; } deleteLen += item.length; } else if (!item.deleted) { if (action !== "retain") { addOp(); action = "retain"; } retain += item.length; } break; case ContentFormat: { const { key: key2, value } = ( /** @type {ContentFormat} */ item.content ); if (this.adds(item)) { if (!this.deletes(item)) { const curVal = currentAttributes.get(key2) ?? null; if (!equalAttrs(curVal, value)) { if (action === "retain") { addOp(); } if (equalAttrs(value, oldAttributes.get(key2) ?? null)) { delete attributes[key2]; } else { attributes[key2] = value; } } else if (value !== null) { item.delete(transaction); } } } else if (this.deletes(item)) { oldAttributes.set(key2, value); const curVal = currentAttributes.get(key2) ?? null; if (!equalAttrs(curVal, value)) { if (action === "retain") { addOp(); } attributes[key2] = curVal; } } else if (!item.deleted) { oldAttributes.set(key2, value); const attr2 = attributes[key2]; if (attr2 !== void 0) { if (!equalAttrs(attr2, value)) { if (action === "retain") { addOp(); } if (value === null) { delete attributes[key2]; } else { attributes[key2] = value; } } else if (attr2 !== null) { item.delete(transaction); } } } if (!item.deleted) { if (action === "insert") { addOp(); } updateCurrentAttributes( currentAttributes, /** @type {ContentFormat} */ item.content ); } break; } } item = item.right; } addOp(); while (delta.length > 0) { const lastOp = delta[delta.length - 1]; if (lastOp.retain !== void 0 && lastOp.attributes === void 0) { delta.pop(); } else { break; } } }); this._delta = delta; } return ( /** @type {any} */ this._delta ); } }; var YText = class _YText extends AbstractType { /** * @param {String} [string] The initial value of the YText. */ constructor(string3) { super(); this._pending = string3 !== void 0 ? [() => this.insert(0, string3)] : []; this._searchMarker = []; this._hasFormatting = false; } /** * Number of characters of this text type. * * @type {number} */ get length() { this.doc ?? warnPrematureAccess(); return this._length; } /** * @param {Doc} y * @param {Item} item */ _integrate(y3, item) { super._integrate(y3, item); try { this._pending.forEach((f6) => f6()); } catch (e2) { console.error(e2); } this._pending = null; } _copy() { return new _YText(); } /** * Makes a copy of this data type that can be included somewhere else. * * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. * * @return {YText} */ clone() { const text10 = new _YText(); text10.applyDelta(this.toDelta()); return text10; } /** * Creates YTextEvent and calls observers. * * @param {Transaction} transaction * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. */ _callObserver(transaction, parentSubs) { super._callObserver(transaction, parentSubs); const event = new YTextEvent(this, transaction, parentSubs); callTypeObservers(this, transaction, event); if (!transaction.local && this._hasFormatting) { transaction._needFormattingCleanup = true; } } /** * Returns the unformatted string representation of this YText type. * * @public */ toString() { this.doc ?? warnPrematureAccess(); let str = ""; let n = this._start; while (n !== null) { if (!n.deleted && n.countable && n.content.constructor === ContentString) { str += /** @type {ContentString} */ n.content.str; } n = n.right; } return str; } /** * Returns the unformatted string representation of this YText type. * * @return {string} * @public */ toJSON() { return this.toString(); } /** * Apply a {@link Delta} on this shared YText type. * * @param {Array} delta The changes to apply on this element. * @param {object} opts * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true. * * * @public */ applyDelta(delta, { sanitize = true } = {}) { if (this.doc !== null) { transact(this.doc, (transaction) => { const currPos = new ItemTextListPosition(null, this._start, 0, /* @__PURE__ */ new Map()); for (let i3 = 0; i3 < delta.length; i3++) { const op = delta[i3]; if (op.insert !== void 0) { const ins = !sanitize && typeof op.insert === "string" && i3 === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === "\n" ? op.insert.slice(0, -1) : op.insert; if (typeof ins !== "string" || ins.length > 0) { insertText(transaction, this, currPos, ins, op.attributes || {}); } } else if (op.retain !== void 0) { formatText(transaction, this, currPos, op.retain, op.attributes || {}); } else if (op.delete !== void 0) { deleteText(transaction, currPos, op.delete); } } }); } else { this._pending.push(() => this.applyDelta(delta)); } } /** * Returns the Delta representation of this YText type. * * @param {Snapshot} [snapshot] * @param {Snapshot} [prevSnapshot] * @param {function('removed' | 'added', ID):any} [computeYChange] * @return {any} The Delta representation of this type. * * @public */ toDelta(snapshot2, prevSnapshot, computeYChange) { this.doc ?? warnPrematureAccess(); const ops = []; const currentAttributes = /* @__PURE__ */ new Map(); const doc4 = ( /** @type {Doc} */ this.doc ); let str = ""; let n = this._start; function packStr() { if (str.length > 0) { const attributes = {}; let addAttributes = false; currentAttributes.forEach((value, key2) => { addAttributes = true; attributes[key2] = value; }); const op = { insert: str }; if (addAttributes) { op.attributes = attributes; } ops.push(op); str = ""; } } const computeDelta = () => { while (n !== null) { if (isVisible(n, snapshot2) || prevSnapshot !== void 0 && isVisible(n, prevSnapshot)) { switch (n.content.constructor) { case ContentString: { const cur = currentAttributes.get("ychange"); if (snapshot2 !== void 0 && !isVisible(n, snapshot2)) { if (cur === void 0 || cur.user !== n.id.client || cur.type !== "removed") { packStr(); currentAttributes.set("ychange", computeYChange ? computeYChange("removed", n.id) : { type: "removed" }); } } else if (prevSnapshot !== void 0 && !isVisible(n, prevSnapshot)) { if (cur === void 0 || cur.user !== n.id.client || cur.type !== "added") { packStr(); currentAttributes.set("ychange", computeYChange ? computeYChange("added", n.id) : { type: "added" }); } } else if (cur !== void 0) { packStr(); currentAttributes.delete("ychange"); } str += /** @type {ContentString} */ n.content.str; break; } case ContentType: case ContentEmbed: { packStr(); const op = { insert: n.content.getContent()[0] }; if (currentAttributes.size > 0) { const attrs = ( /** @type {Object} */ {} ); op.attributes = attrs; currentAttributes.forEach((value, key2) => { attrs[key2] = value; }); } ops.push(op); break; } case ContentFormat: if (isVisible(n, snapshot2)) { packStr(); updateCurrentAttributes( currentAttributes, /** @type {ContentFormat} */ n.content ); } break; } } n = n.right; } packStr(); }; if (snapshot2 || prevSnapshot) { transact(doc4, (transaction) => { if (snapshot2) { splitSnapshotAffectedStructs(transaction, snapshot2); } if (prevSnapshot) { splitSnapshotAffectedStructs(transaction, prevSnapshot); } computeDelta(); }, "cleanup"); } else { computeDelta(); } return ops; } /** * Insert text at a given index. * * @param {number} index The index at which to start inserting. * @param {String} text The text to insert at the specified position. * @param {TextAttributes} [attributes] Optionally define some formatting * information to apply on the inserted * Text. * @public */ insert(index4, text10, attributes) { if (text10.length <= 0) { return; } const y3 = this.doc; if (y3 !== null) { transact(y3, (transaction) => { const pos = findPosition(transaction, this, index4, !attributes); if (!attributes) { attributes = {}; pos.currentAttributes.forEach((v8, k3) => { attributes[k3] = v8; }); } insertText(transaction, this, pos, text10, attributes); }); } else { this._pending.push(() => this.insert(index4, text10, attributes)); } } /** * Inserts an embed at a index. * * @param {number} index The index to insert the embed at. * @param {Object | AbstractType} embed The Object that represents the embed. * @param {TextAttributes} [attributes] Attribute information to apply on the * embed * * @public */ insertEmbed(index4, embed, attributes) { const y3 = this.doc; if (y3 !== null) { transact(y3, (transaction) => { const pos = findPosition(transaction, this, index4, !attributes); insertText(transaction, this, pos, embed, attributes || {}); }); } else { this._pending.push(() => this.insertEmbed(index4, embed, attributes || {})); } } /** * Deletes text starting from an index. * * @param {number} index Index at which to start deleting. * @param {number} length The number of characters to remove. Defaults to 1. * * @public */ delete(index4, length2) { if (length2 === 0) { return; } const y3 = this.doc; if (y3 !== null) { transact(y3, (transaction) => { deleteText(transaction, findPosition(transaction, this, index4, true), length2); }); } else { this._pending.push(() => this.delete(index4, length2)); } } /** * Assigns properties to a range of text. * * @param {number} index The position where to start formatting. * @param {number} length The amount of characters to assign properties to. * @param {TextAttributes} attributes Attribute information to apply on the * text. * * @public */ format(index4, length2, attributes) { if (length2 === 0) { return; } const y3 = this.doc; if (y3 !== null) { transact(y3, (transaction) => { const pos = findPosition(transaction, this, index4, false); if (pos.right === null) { return; } formatText(transaction, this, pos, length2, attributes); }); } else { this._pending.push(() => this.format(index4, length2, attributes)); } } /** * Removes an attribute. * * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. * * @param {String} attributeName The attribute name that is to be removed. * * @public */ removeAttribute(attributeName) { if (this.doc !== null) { transact(this.doc, (transaction) => { typeMapDelete(transaction, this, attributeName); }); } else { this._pending.push(() => this.removeAttribute(attributeName)); } } /** * Sets or updates an attribute. * * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. * * @param {String} attributeName The attribute name that is to be set. * @param {any} attributeValue The attribute value that is to be set. * * @public */ setAttribute(attributeName, attributeValue) { if (this.doc !== null) { transact(this.doc, (transaction) => { typeMapSet(transaction, this, attributeName, attributeValue); }); } else { this._pending.push(() => this.setAttribute(attributeName, attributeValue)); } } /** * Returns an attribute value that belongs to the attribute name. * * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. * * @param {String} attributeName The attribute name that identifies the * queried value. * @return {any} The queried attribute value. * * @public */ getAttribute(attributeName) { return ( /** @type {any} */ typeMapGet(this, attributeName) ); } /** * Returns all attribute name/value pairs in a JSON Object. * * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. * * @return {Object} A JSON Object that describes the attributes. * * @public */ getAttributes() { return typeMapGetAll(this); } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder */ _write(encoder) { encoder.writeTypeRef(YTextRefID); } }; var readYText = (_decoder) => new YText(); var YXmlTreeWalker = class { /** * @param {YXmlFragment | YXmlElement} root * @param {function(AbstractType):boolean} [f] */ constructor(root6, f6 = () => true) { this._filter = f6; this._root = root6; this._currentNode = /** @type {Item} */ root6._start; this._firstCall = true; root6.doc ?? warnPrematureAccess(); } [Symbol.iterator]() { return this; } /** * Get the next node. * * @return {IteratorResult} The next node. * * @public */ next() { let n = this._currentNode; let type = n && n.content && /** @type {any} */ n.content.type; if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { do { type = /** @type {any} */ n.content.type; if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) { n = type._start; } else { while (n !== null) { const nxt = n.next; if (nxt !== null) { n = nxt; break; } else if (n.parent === this._root) { n = null; } else { n = /** @type {AbstractType} */ n.parent._item; } } } } while (n !== null && (n.deleted || !this._filter( /** @type {ContentType} */ n.content.type ))); } this._firstCall = false; if (n === null) { return { value: void 0, done: true }; } this._currentNode = n; return { value: ( /** @type {any} */ n.content.type ), done: false }; } }; var YXmlFragment = class _YXmlFragment extends AbstractType { constructor() { super(); this._prelimContent = []; } /** * @type {YXmlElement|YXmlText|null} */ get firstChild() { const first2 = this._first; return first2 ? first2.content.getContent()[0] : null; } /** * Integrate this type into the Yjs instance. * * * Save this struct in the os * * This type is sent to other client * * Observer functions are fired * * @param {Doc} y The Yjs instance * @param {Item} item */ _integrate(y3, item) { super._integrate(y3, item); this.insert( 0, /** @type {Array} */ this._prelimContent ); this._prelimContent = null; } _copy() { return new _YXmlFragment(); } /** * Makes a copy of this data type that can be included somewhere else. * * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. * * @return {YXmlFragment} */ clone() { const el2 = new _YXmlFragment(); el2.insert(0, this.toArray().map((item) => item instanceof AbstractType ? item.clone() : item)); return el2; } get length() { this.doc ?? warnPrematureAccess(); return this._prelimContent === null ? this._length : this._prelimContent.length; } /** * Create a subtree of childNodes. * * @example * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div') * for (let node in walker) { * // `node` is a div node * nop(node) * } * * @param {function(AbstractType):boolean} filter Function that is called on each child element and * returns a Boolean indicating whether the child * is to be included in the subtree. * @return {YXmlTreeWalker} A subtree and a position within it. * * @public */ createTreeWalker(filter) { return new YXmlTreeWalker(this, filter); } /** * Returns the first YXmlElement that matches the query. * Similar to DOM's {@link querySelector}. * * Query support: * - tagname * TODO: * - id * - attribute * * @param {CSS_Selector} query The query on the children. * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null. * * @public */ querySelector(query) { query = query.toUpperCase(); const iterator = new YXmlTreeWalker(this, (element7) => element7.nodeName && element7.nodeName.toUpperCase() === query); const next2 = iterator.next(); if (next2.done) { return null; } else { return next2.value; } } /** * Returns all YXmlElements that match the query. * Similar to Dom's {@link querySelectorAll}. * * @todo Does not yet support all queries. Currently only query by tagName. * * @param {CSS_Selector} query The query on the children * @return {Array} The elements that match this query. * * @public */ querySelectorAll(query) { query = query.toUpperCase(); return from2(new YXmlTreeWalker(this, (element7) => element7.nodeName && element7.nodeName.toUpperCase() === query)); } /** * Creates YXmlEvent and calls observers. * * @param {Transaction} transaction * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. */ _callObserver(transaction, parentSubs) { callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction)); } /** * Get the string representation of all the children of this YXmlFragment. * * @return {string} The string representation of all children. */ toString() { return typeListMap(this, (xml2) => xml2.toString()).join(""); } /** * @return {string} */ toJSON() { return this.toString(); } /** * Creates a Dom Element that mirrors this YXmlElement. * * @param {Document} [_document=document] The document object (you must define * this when calling this method in * nodejs) * @param {Object} [hooks={}] Optional property to customize how hooks * are presented in the DOM * @param {any} [binding] You should not set this property. This is * used if DomBinding wants to create a * association to the created DOM type. * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} * * @public */ toDOM(_document = document, hooks = {}, binding) { const fragment = _document.createDocumentFragment(); if (binding !== void 0) { binding._createAssociation(fragment, this); } typeListForEach(this, (xmlType) => { fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null); }); return fragment; } /** * Inserts new content at an index. * * @example * // Insert character 'a' at position 0 * xml.insert(0, [new Y.XmlText('text')]) * * @param {number} index The index to insert content at * @param {Array} content The array of content */ insert(index4, content5) { if (this.doc !== null) { transact(this.doc, (transaction) => { typeListInsertGenerics(transaction, this, index4, content5); }); } else { this._prelimContent.splice(index4, 0, ...content5); } } /** * Inserts new content at an index. * * @example * // Insert character 'a' at position 0 * xml.insert(0, [new Y.XmlText('text')]) * * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at * @param {Array} content The array of content */ insertAfter(ref, content5) { if (this.doc !== null) { transact(this.doc, (transaction) => { const refItem = ref && ref instanceof AbstractType ? ref._item : ref; typeListInsertGenericsAfter(transaction, this, refItem, content5); }); } else { const pc = ( /** @type {Array} */ this._prelimContent ); const index4 = ref === null ? 0 : pc.findIndex((el2) => el2 === ref) + 1; if (index4 === 0 && ref !== null) { throw create3("Reference item not found"); } pc.splice(index4, 0, ...content5); } } /** * Deletes elements starting from an index. * * @param {number} index Index at which to start deleting elements * @param {number} [length=1] The number of elements to remove. Defaults to 1. */ delete(index4, length2 = 1) { if (this.doc !== null) { transact(this.doc, (transaction) => { typeListDelete(transaction, this, index4, length2); }); } else { this._prelimContent.splice(index4, length2); } } /** * Transforms this YArray to a JavaScript Array. * * @return {Array} */ toArray() { return typeListToArray(this); } /** * Appends content to this YArray. * * @param {Array} content Array of content to append. */ push(content5) { this.insert(this.length, content5); } /** * Prepends content to this YArray. * * @param {Array} content Array of content to prepend. */ unshift(content5) { this.insert(0, content5); } /** * Returns the i-th element from a YArray. * * @param {number} index The index of the element to return from the YArray * @return {YXmlElement|YXmlText} */ get(index4) { return typeListGet(this, index4); } /** * Returns a portion of this YXmlFragment into a JavaScript Array selected * from start to end (end not included). * * @param {number} [start] * @param {number} [end] * @return {Array} */ slice(start = 0, end = this.length) { return typeListSlice(this, start, end); } /** * Executes a provided function on once on every child element. * * @param {function(YXmlElement|YXmlText,number, typeof self):void} f A function to execute on every element of this YArray. */ forEach(f6) { typeListForEach(this, f6); } /** * Transform the properties of this type to binary and write it to an * BinaryEncoder. * * This is called when this Item is sent to a remote peer. * * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. */ _write(encoder) { encoder.writeTypeRef(YXmlFragmentRefID); } }; var readYXmlFragment = (_decoder) => new YXmlFragment(); var YXmlElement = class _YXmlElement extends YXmlFragment { constructor(nodeName = "UNDEFINED") { super(); this.nodeName = nodeName; this._prelimAttrs = /* @__PURE__ */ new Map(); } /** * @type {YXmlElement|YXmlText|null} */ get nextSibling() { const n = this._item ? this._item.next : null; return n ? ( /** @type {YXmlElement|YXmlText} */ /** @type {ContentType} */ n.content.type ) : null; } /** * @type {YXmlElement|YXmlText|null} */ get prevSibling() { const n = this._item ? this._item.prev : null; return n ? ( /** @type {YXmlElement|YXmlText} */ /** @type {ContentType} */ n.content.type ) : null; } /** * Integrate this type into the Yjs instance. * * * Save this struct in the os * * This type is sent to other client * * Observer functions are fired * * @param {Doc} y The Yjs instance * @param {Item} item */ _integrate(y3, item) { super._integrate(y3, item); /** @type {Map} */ this._prelimAttrs.forEach((value, key2) => { this.setAttribute(key2, value); }); this._prelimAttrs = null; } /** * Creates an Item with the same effect as this Item (without position effect) * * @return {YXmlElement} */ _copy() { return new _YXmlElement(this.nodeName); } /** * Makes a copy of this data type that can be included somewhere else. * * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. * * @return {YXmlElement} */ clone() { const el2 = new _YXmlElement(this.nodeName); const attrs = this.getAttributes(); forEach(attrs, (value, key2) => { el2.setAttribute( key2, /** @type {any} */ value ); }); el2.insert(0, this.toArray().map((v8) => v8 instanceof AbstractType ? v8.clone() : v8)); return el2; } /** * Returns the XML serialization of this YXmlElement. * The attributes are ordered by attribute-name, so you can easily use this * method to compare YXmlElements * * @return {string} The string representation of this type. * * @public */ toString() { const attrs = this.getAttributes(); const stringBuilder = []; const keys5 = []; for (const key2 in attrs) { keys5.push(key2); } keys5.sort(); const keysLen = keys5.length; for (let i3 = 0; i3 < keysLen; i3++) { const key2 = keys5[i3]; stringBuilder.push(key2 + '="' + attrs[key2] + '"'); } const nodeName = this.nodeName.toLocaleLowerCase(); const attrsString = stringBuilder.length > 0 ? " " + stringBuilder.join(" ") : ""; return `<${nodeName}${attrsString}>${super.toString()}`; } /** * Removes an attribute from this YXmlElement. * * @param {string} attributeName The attribute name that is to be removed. * * @public */ removeAttribute(attributeName) { if (this.doc !== null) { transact(this.doc, (transaction) => { typeMapDelete(transaction, this, attributeName); }); } else { this._prelimAttrs.delete(attributeName); } } /** * Sets or updates an attribute. * * @template {keyof KV & string} KEY * * @param {KEY} attributeName The attribute name that is to be set. * @param {KV[KEY]} attributeValue The attribute value that is to be set. * * @public */ setAttribute(attributeName, attributeValue) { if (this.doc !== null) { transact(this.doc, (transaction) => { typeMapSet(transaction, this, attributeName, attributeValue); }); } else { this._prelimAttrs.set(attributeName, attributeValue); } } /** * Returns an attribute value that belongs to the attribute name. * * @template {keyof KV & string} KEY * * @param {KEY} attributeName The attribute name that identifies the * queried value. * @return {KV[KEY]|undefined} The queried attribute value. * * @public */ getAttribute(attributeName) { return ( /** @type {any} */ typeMapGet(this, attributeName) ); } /** * Returns whether an attribute exists * * @param {string} attributeName The attribute name to check for existence. * @return {boolean} whether the attribute exists. * * @public */ hasAttribute(attributeName) { return ( /** @type {any} */ typeMapHas(this, attributeName) ); } /** * Returns all attribute name/value pairs in a JSON Object. * * @param {Snapshot} [snapshot] * @return {{ [Key in Extract]?: KV[Key]}} A JSON Object that describes the attributes. * * @public */ getAttributes(snapshot2) { return ( /** @type {any} */ snapshot2 ? typeMapGetAllSnapshot(this, snapshot2) : typeMapGetAll(this) ); } /** * Creates a Dom Element that mirrors this YXmlElement. * * @param {Document} [_document=document] The document object (you must define * this when calling this method in * nodejs) * @param {Object} [hooks={}] Optional property to customize how hooks * are presented in the DOM * @param {any} [binding] You should not set this property. This is * used if DomBinding wants to create a * association to the created DOM type. * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} * * @public */ toDOM(_document = document, hooks = {}, binding) { const dom = _document.createElement(this.nodeName); const attrs = this.getAttributes(); for (const key2 in attrs) { const value = attrs[key2]; if (typeof value === "string") { dom.setAttribute(key2, value); } } typeListForEach(this, (yxml) => { dom.appendChild(yxml.toDOM(_document, hooks, binding)); }); if (binding !== void 0) { binding._createAssociation(dom, this); } return dom; } /** * Transform the properties of this type to binary and write it to an * BinaryEncoder. * * This is called when this Item is sent to a remote peer. * * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. */ _write(encoder) { encoder.writeTypeRef(YXmlElementRefID); encoder.writeKey(this.nodeName); } }; var readYXmlElement = (decoder) => new YXmlElement(decoder.readKey()); var YXmlEvent = class extends YEvent { /** * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created. * @param {Set} subs The set of changed attributes. `null` is included if the * child list changed. * @param {Transaction} transaction The transaction instance with which the * change was created. */ constructor(target, subs, transaction) { super(target, transaction); this.childListChanged = false; this.attributesChanged = /* @__PURE__ */ new Set(); subs.forEach((sub) => { if (sub === null) { this.childListChanged = true; } else { this.attributesChanged.add(sub); } }); } }; var YXmlHook = class _YXmlHook extends YMap { /** * @param {string} hookName nodeName of the Dom Node. */ constructor(hookName) { super(); this.hookName = hookName; } /** * Creates an Item with the same effect as this Item (without position effect) */ _copy() { return new _YXmlHook(this.hookName); } /** * Makes a copy of this data type that can be included somewhere else. * * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. * * @return {YXmlHook} */ clone() { const el2 = new _YXmlHook(this.hookName); this.forEach((value, key2) => { el2.set(key2, value); }); return el2; } /** * Creates a Dom Element that mirrors this YXmlElement. * * @param {Document} [_document=document] The document object (you must define * this when calling this method in * nodejs) * @param {Object.} [hooks] Optional property to customize how hooks * are presented in the DOM * @param {any} [binding] You should not set this property. This is * used if DomBinding wants to create a * association to the created DOM type * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} * * @public */ toDOM(_document = document, hooks = {}, binding) { const hook = hooks[this.hookName]; let dom; if (hook !== void 0) { dom = hook.createDom(this); } else { dom = document.createElement(this.hookName); } dom.setAttribute("data-yjs-hook", this.hookName); if (binding !== void 0) { binding._createAssociation(dom, this); } return dom; } /** * Transform the properties of this type to binary and write it to an * BinaryEncoder. * * This is called when this Item is sent to a remote peer. * * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. */ _write(encoder) { encoder.writeTypeRef(YXmlHookRefID); encoder.writeKey(this.hookName); } }; var readYXmlHook = (decoder) => new YXmlHook(decoder.readKey()); var YXmlText = class _YXmlText extends YText { /** * @type {YXmlElement|YXmlText|null} */ get nextSibling() { const n = this._item ? this._item.next : null; return n ? ( /** @type {YXmlElement|YXmlText} */ /** @type {ContentType} */ n.content.type ) : null; } /** * @type {YXmlElement|YXmlText|null} */ get prevSibling() { const n = this._item ? this._item.prev : null; return n ? ( /** @type {YXmlElement|YXmlText} */ /** @type {ContentType} */ n.content.type ) : null; } _copy() { return new _YXmlText(); } /** * Makes a copy of this data type that can be included somewhere else. * * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. * * @return {YXmlText} */ clone() { const text10 = new _YXmlText(); text10.applyDelta(this.toDelta()); return text10; } /** * Creates a Dom Element that mirrors this YXmlText. * * @param {Document} [_document=document] The document object (you must define * this when calling this method in * nodejs) * @param {Object} [hooks] Optional property to customize how hooks * are presented in the DOM * @param {any} [binding] You should not set this property. This is * used if DomBinding wants to create a * association to the created DOM type. * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} * * @public */ toDOM(_document = document, hooks, binding) { const dom = _document.createTextNode(this.toString()); if (binding !== void 0) { binding._createAssociation(dom, this); } return dom; } toString() { return this.toDelta().map((delta) => { const nestedNodes = []; for (const nodeName in delta.attributes) { const attrs = []; for (const key2 in delta.attributes[nodeName]) { attrs.push({ key: key2, value: delta.attributes[nodeName][key2] }); } attrs.sort((a3, b4) => a3.key < b4.key ? -1 : 1); nestedNodes.push({ nodeName, attrs }); } nestedNodes.sort((a3, b4) => a3.nodeName < b4.nodeName ? -1 : 1); let str = ""; for (let i3 = 0; i3 < nestedNodes.length; i3++) { const node2 = nestedNodes[i3]; str += `<${node2.nodeName}`; for (let j4 = 0; j4 < node2.attrs.length; j4++) { const attr2 = node2.attrs[j4]; str += ` ${attr2.key}="${attr2.value}"`; } str += ">"; } str += delta.insert; for (let i3 = nestedNodes.length - 1; i3 >= 0; i3--) { str += ``; } return str; }).join(""); } /** * @return {string} */ toJSON() { return this.toString(); } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder */ _write(encoder) { encoder.writeTypeRef(YXmlTextRefID); } }; var readYXmlText = (decoder) => new YXmlText(); var AbstractStruct = class { /** * @param {ID} id * @param {number} length */ constructor(id2, length2) { this.id = id2; this.length = length2; } /** * @type {boolean} */ get deleted() { throw methodUnimplemented(); } /** * Merge this struct with the item to the right. * This method is already assuming that `this.id.clock + this.length === this.id.clock`. * Also this method does *not* remove right from StructStore! * @param {AbstractStruct} right * @return {boolean} whether this merged with right */ mergeWith(right) { return false; } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. * @param {number} offset * @param {number} encodingRef */ write(encoder, offset4, encodingRef) { throw methodUnimplemented(); } /** * @param {Transaction} transaction * @param {number} offset */ integrate(transaction, offset4) { throw methodUnimplemented(); } }; var structGCRefNumber = 0; var GC = class extends AbstractStruct { get deleted() { return true; } delete() { } /** * @param {GC} right * @return {boolean} */ mergeWith(right) { if (this.constructor !== right.constructor) { return false; } this.length += right.length; return true; } /** * @param {Transaction} transaction * @param {number} offset */ integrate(transaction, offset4) { if (offset4 > 0) { this.id.clock += offset4; this.length -= offset4; } addStruct(transaction.doc.store, this); } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder * @param {number} offset */ write(encoder, offset4) { encoder.writeInfo(structGCRefNumber); encoder.writeLen(this.length - offset4); } /** * @param {Transaction} transaction * @param {StructStore} store * @return {null | number} */ getMissing(transaction, store) { return null; } }; var ContentBinary = class _ContentBinary { /** * @param {Uint8Array} content */ constructor(content5) { this.content = content5; } /** * @return {number} */ getLength() { return 1; } /** * @return {Array} */ getContent() { return [this.content]; } /** * @return {boolean} */ isCountable() { return true; } /** * @return {ContentBinary} */ copy() { return new _ContentBinary(this.content); } /** * @param {number} offset * @return {ContentBinary} */ splice(offset4) { throw methodUnimplemented(); } /** * @param {ContentBinary} right * @return {boolean} */ mergeWith(right) { return false; } /** * @param {Transaction} transaction * @param {Item} item */ integrate(transaction, item) { } /** * @param {Transaction} transaction */ delete(transaction) { } /** * @param {StructStore} store */ gc(store) { } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder * @param {number} offset */ write(encoder, offset4) { encoder.writeBuf(this.content); } /** * @return {number} */ getRef() { return 3; } }; var readContentBinary = (decoder) => new ContentBinary(decoder.readBuf()); var ContentDeleted = class _ContentDeleted { /** * @param {number} len */ constructor(len) { this.len = len; } /** * @return {number} */ getLength() { return this.len; } /** * @return {Array} */ getContent() { return []; } /** * @return {boolean} */ isCountable() { return false; } /** * @return {ContentDeleted} */ copy() { return new _ContentDeleted(this.len); } /** * @param {number} offset * @return {ContentDeleted} */ splice(offset4) { const right = new _ContentDeleted(this.len - offset4); this.len = offset4; return right; } /** * @param {ContentDeleted} right * @return {boolean} */ mergeWith(right) { this.len += right.len; return true; } /** * @param {Transaction} transaction * @param {Item} item */ integrate(transaction, item) { addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len); item.markDeleted(); } /** * @param {Transaction} transaction */ delete(transaction) { } /** * @param {StructStore} store */ gc(store) { } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder * @param {number} offset */ write(encoder, offset4) { encoder.writeLen(this.len - offset4); } /** * @return {number} */ getRef() { return 1; } }; var readContentDeleted = (decoder) => new ContentDeleted(decoder.readLen()); var createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false }); var ContentDoc = class _ContentDoc { /** * @param {Doc} doc */ constructor(doc4) { if (doc4._item) { console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."); } this.doc = doc4; const opts = {}; this.opts = opts; if (!doc4.gc) { opts.gc = false; } if (doc4.autoLoad) { opts.autoLoad = true; } if (doc4.meta !== null) { opts.meta = doc4.meta; } } /** * @return {number} */ getLength() { return 1; } /** * @return {Array} */ getContent() { return [this.doc]; } /** * @return {boolean} */ isCountable() { return true; } /** * @return {ContentDoc} */ copy() { return new _ContentDoc(createDocFromOpts(this.doc.guid, this.opts)); } /** * @param {number} offset * @return {ContentDoc} */ splice(offset4) { throw methodUnimplemented(); } /** * @param {ContentDoc} right * @return {boolean} */ mergeWith(right) { return false; } /** * @param {Transaction} transaction * @param {Item} item */ integrate(transaction, item) { this.doc._item = item; transaction.subdocsAdded.add(this.doc); if (this.doc.shouldLoad) { transaction.subdocsLoaded.add(this.doc); } } /** * @param {Transaction} transaction */ delete(transaction) { if (transaction.subdocsAdded.has(this.doc)) { transaction.subdocsAdded.delete(this.doc); } else { transaction.subdocsRemoved.add(this.doc); } } /** * @param {StructStore} store */ gc(store) { } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder * @param {number} offset */ write(encoder, offset4) { encoder.writeString(this.doc.guid); encoder.writeAny(this.opts); } /** * @return {number} */ getRef() { return 9; } }; var readContentDoc = (decoder) => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny())); var ContentEmbed = class _ContentEmbed { /** * @param {Object} embed */ constructor(embed) { this.embed = embed; } /** * @return {number} */ getLength() { return 1; } /** * @return {Array} */ getContent() { return [this.embed]; } /** * @return {boolean} */ isCountable() { return true; } /** * @return {ContentEmbed} */ copy() { return new _ContentEmbed(this.embed); } /** * @param {number} offset * @return {ContentEmbed} */ splice(offset4) { throw methodUnimplemented(); } /** * @param {ContentEmbed} right * @return {boolean} */ mergeWith(right) { return false; } /** * @param {Transaction} transaction * @param {Item} item */ integrate(transaction, item) { } /** * @param {Transaction} transaction */ delete(transaction) { } /** * @param {StructStore} store */ gc(store) { } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder * @param {number} offset */ write(encoder, offset4) { encoder.writeJSON(this.embed); } /** * @return {number} */ getRef() { return 5; } }; var readContentEmbed = (decoder) => new ContentEmbed(decoder.readJSON()); var ContentFormat = class _ContentFormat { /** * @param {string} key * @param {Object} value */ constructor(key2, value) { this.key = key2; this.value = value; } /** * @return {number} */ getLength() { return 1; } /** * @return {Array} */ getContent() { return []; } /** * @return {boolean} */ isCountable() { return false; } /** * @return {ContentFormat} */ copy() { return new _ContentFormat(this.key, this.value); } /** * @param {number} _offset * @return {ContentFormat} */ splice(_offset) { throw methodUnimplemented(); } /** * @param {ContentFormat} _right * @return {boolean} */ mergeWith(_right) { return false; } /** * @param {Transaction} _transaction * @param {Item} item */ integrate(_transaction, item) { const p4 = ( /** @type {YText} */ item.parent ); p4._searchMarker = null; p4._hasFormatting = true; } /** * @param {Transaction} transaction */ delete(transaction) { } /** * @param {StructStore} store */ gc(store) { } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder * @param {number} offset */ write(encoder, offset4) { encoder.writeKey(this.key); encoder.writeJSON(this.value); } /** * @return {number} */ getRef() { return 6; } }; var readContentFormat = (decoder) => new ContentFormat(decoder.readKey(), decoder.readJSON()); var ContentJSON = class _ContentJSON { /** * @param {Array} arr */ constructor(arr) { this.arr = arr; } /** * @return {number} */ getLength() { return this.arr.length; } /** * @return {Array} */ getContent() { return this.arr; } /** * @return {boolean} */ isCountable() { return true; } /** * @return {ContentJSON} */ copy() { return new _ContentJSON(this.arr); } /** * @param {number} offset * @return {ContentJSON} */ splice(offset4) { const right = new _ContentJSON(this.arr.slice(offset4)); this.arr = this.arr.slice(0, offset4); return right; } /** * @param {ContentJSON} right * @return {boolean} */ mergeWith(right) { this.arr = this.arr.concat(right.arr); return true; } /** * @param {Transaction} transaction * @param {Item} item */ integrate(transaction, item) { } /** * @param {Transaction} transaction */ delete(transaction) { } /** * @param {StructStore} store */ gc(store) { } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder * @param {number} offset */ write(encoder, offset4) { const len = this.arr.length; encoder.writeLen(len - offset4); for (let i3 = offset4; i3 < len; i3++) { const c3 = this.arr[i3]; encoder.writeString(c3 === void 0 ? "undefined" : JSON.stringify(c3)); } } /** * @return {number} */ getRef() { return 2; } }; var readContentJSON = (decoder) => { const len = decoder.readLen(); const cs = []; for (let i3 = 0; i3 < len; i3++) { const c3 = decoder.readString(); if (c3 === "undefined") { cs.push(void 0); } else { cs.push(JSON.parse(c3)); } } return new ContentJSON(cs); }; var isDevMode = getVariable("node_env") === "development"; var ContentAny = class _ContentAny { /** * @param {Array} arr */ constructor(arr) { this.arr = arr; isDevMode && deepFreeze(arr); } /** * @return {number} */ getLength() { return this.arr.length; } /** * @return {Array} */ getContent() { return this.arr; } /** * @return {boolean} */ isCountable() { return true; } /** * @return {ContentAny} */ copy() { return new _ContentAny(this.arr); } /** * @param {number} offset * @return {ContentAny} */ splice(offset4) { const right = new _ContentAny(this.arr.slice(offset4)); this.arr = this.arr.slice(0, offset4); return right; } /** * @param {ContentAny} right * @return {boolean} */ mergeWith(right) { this.arr = this.arr.concat(right.arr); return true; } /** * @param {Transaction} transaction * @param {Item} item */ integrate(transaction, item) { } /** * @param {Transaction} transaction */ delete(transaction) { } /** * @param {StructStore} store */ gc(store) { } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder * @param {number} offset */ write(encoder, offset4) { const len = this.arr.length; encoder.writeLen(len - offset4); for (let i3 = offset4; i3 < len; i3++) { const c3 = this.arr[i3]; encoder.writeAny(c3); } } /** * @return {number} */ getRef() { return 8; } }; var readContentAny = (decoder) => { const len = decoder.readLen(); const cs = []; for (let i3 = 0; i3 < len; i3++) { cs.push(decoder.readAny()); } return new ContentAny(cs); }; var ContentString = class _ContentString { /** * @param {string} str */ constructor(str) { this.str = str; } /** * @return {number} */ getLength() { return this.str.length; } /** * @return {Array} */ getContent() { return this.str.split(""); } /** * @return {boolean} */ isCountable() { return true; } /** * @return {ContentString} */ copy() { return new _ContentString(this.str); } /** * @param {number} offset * @return {ContentString} */ splice(offset4) { const right = new _ContentString(this.str.slice(offset4)); this.str = this.str.slice(0, offset4); const firstCharCode = this.str.charCodeAt(offset4 - 1); if (firstCharCode >= 55296 && firstCharCode <= 56319) { this.str = this.str.slice(0, offset4 - 1) + "�"; right.str = "�" + right.str.slice(1); } return right; } /** * @param {ContentString} right * @return {boolean} */ mergeWith(right) { this.str += right.str; return true; } /** * @param {Transaction} transaction * @param {Item} item */ integrate(transaction, item) { } /** * @param {Transaction} transaction */ delete(transaction) { } /** * @param {StructStore} store */ gc(store) { } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder * @param {number} offset */ write(encoder, offset4) { encoder.writeString(offset4 === 0 ? this.str : this.str.slice(offset4)); } /** * @return {number} */ getRef() { return 4; } }; var readContentString = (decoder) => new ContentString(decoder.readString()); var typeRefs = [ readYArray, readYMap, readYText, readYXmlElement, readYXmlFragment, readYXmlHook, readYXmlText ]; var YArrayRefID = 0; var YMapRefID = 1; var YTextRefID = 2; var YXmlElementRefID = 3; var YXmlFragmentRefID = 4; var YXmlHookRefID = 5; var YXmlTextRefID = 6; var ContentType = class _ContentType { /** * @param {AbstractType} type */ constructor(type) { this.type = type; } /** * @return {number} */ getLength() { return 1; } /** * @return {Array} */ getContent() { return [this.type]; } /** * @return {boolean} */ isCountable() { return true; } /** * @return {ContentType} */ copy() { return new _ContentType(this.type._copy()); } /** * @param {number} offset * @return {ContentType} */ splice(offset4) { throw methodUnimplemented(); } /** * @param {ContentType} right * @return {boolean} */ mergeWith(right) { return false; } /** * @param {Transaction} transaction * @param {Item} item */ integrate(transaction, item) { this.type._integrate(transaction.doc, item); } /** * @param {Transaction} transaction */ delete(transaction) { let item = this.type._start; while (item !== null) { if (!item.deleted) { item.delete(transaction); } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) { transaction._mergeStructs.push(item); } item = item.right; } this.type._map.forEach((item2) => { if (!item2.deleted) { item2.delete(transaction); } else if (item2.id.clock < (transaction.beforeState.get(item2.id.client) || 0)) { transaction._mergeStructs.push(item2); } }); transaction.changed.delete(this.type); } /** * @param {StructStore} store */ gc(store) { let item = this.type._start; while (item !== null) { item.gc(store, true); item = item.right; } this.type._start = null; this.type._map.forEach( /** @param {Item | null} item */ (item2) => { while (item2 !== null) { item2.gc(store, true); item2 = item2.left; } } ); this.type._map = /* @__PURE__ */ new Map(); } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder * @param {number} offset */ write(encoder, offset4) { this.type._write(encoder); } /** * @return {number} */ getRef() { return 7; } }; var readContentType = (decoder) => new ContentType(typeRefs[decoder.readTypeRef()](decoder)); var followRedone = (store, id2) => { let nextID = id2; let diff = 0; let item; do { if (diff > 0) { nextID = createID(nextID.client, nextID.clock + diff); } item = getItem(store, nextID); diff = nextID.clock - item.id.clock; nextID = item.redone; } while (nextID !== null && item instanceof Item); return { item, diff }; }; var keepItem = (item, keep) => { while (item !== null && item.keep !== keep) { item.keep = keep; item = /** @type {AbstractType} */ item.parent._item; } }; var splitItem = (transaction, leftItem, diff) => { const { client, clock } = leftItem.id; const rightItem = new Item( createID(client, clock + diff), leftItem, createID(client, clock + diff - 1), leftItem.right, leftItem.rightOrigin, leftItem.parent, leftItem.parentSub, leftItem.content.splice(diff) ); if (leftItem.deleted) { rightItem.markDeleted(); } if (leftItem.keep) { rightItem.keep = true; } if (leftItem.redone !== null) { rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff); } leftItem.right = rightItem; if (rightItem.right !== null) { rightItem.right.left = rightItem; } transaction._mergeStructs.push(rightItem); if (rightItem.parentSub !== null && rightItem.right === null) { rightItem.parent._map.set(rightItem.parentSub, rightItem); } leftItem.length = diff; return rightItem; }; var isDeletedByUndoStack = (stack, id2) => some( stack, /** @param {StackItem} s */ (s2) => isDeleted(s2.deletions, id2) ); var redoItem = (transaction, item, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) => { const doc4 = transaction.doc; const store = doc4.store; const ownClientID = doc4.clientID; const redone = item.redone; if (redone !== null) { return getItemCleanStart(transaction, redone); } let parentItem = ( /** @type {AbstractType} */ item.parent._item ); let left = null; let right; if (parentItem !== null && parentItem.deleted === true) { if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) === null)) { return null; } while (parentItem.redone !== null) { parentItem = getItemCleanStart(transaction, parentItem.redone); } } const parentType = parentItem === null ? ( /** @type {AbstractType} */ item.parent ) : ( /** @type {ContentType} */ parentItem.content.type ); if (item.parentSub === null) { left = item.left; right = item; while (left !== null) { let leftTrace = left; while (leftTrace !== null && /** @type {AbstractType} */ leftTrace.parent._item !== parentItem) { leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone); } if (leftTrace !== null && /** @type {AbstractType} */ leftTrace.parent._item === parentItem) { left = leftTrace; break; } left = left.left; } while (right !== null) { let rightTrace = right; while (rightTrace !== null && /** @type {AbstractType} */ rightTrace.parent._item !== parentItem) { rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone); } if (rightTrace !== null && /** @type {AbstractType} */ rightTrace.parent._item === parentItem) { right = rightTrace; break; } right = right.right; } } else { right = null; if (item.right && !ignoreRemoteMapChanges) { left = item; while (left !== null && left.right !== null && (left.right.redone || isDeleted(itemsToDelete, left.right.id) || isDeletedByUndoStack(um.undoStack, left.right.id) || isDeletedByUndoStack(um.redoStack, left.right.id))) { left = left.right; while (left.redone) left = getItemCleanStart(transaction, left.redone); } if (left && left.right !== null) { return null; } } else { left = parentType._map.get(item.parentSub) || null; } } const nextClock = getState(store, ownClientID); const nextId = createID(ownClientID, nextClock); const redoneItem = new Item( nextId, left, left && left.lastId, right, right && right.id, parentType, item.parentSub, item.content.copy() ); item.redone = nextId; keepItem(redoneItem, true); redoneItem.integrate(transaction, 0); return redoneItem; }; var Item = class _Item extends AbstractStruct { /** * @param {ID} id * @param {Item | null} left * @param {ID | null} origin * @param {Item | null} right * @param {ID | null} rightOrigin * @param {AbstractType|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it. * @param {string | null} parentSub * @param {AbstractContent} content */ constructor(id2, left, origin, right, rightOrigin, parent, parentSub, content5) { super(id2, content5.getLength()); this.origin = origin; this.left = left; this.right = right; this.rightOrigin = rightOrigin; this.parent = parent; this.parentSub = parentSub; this.redone = null; this.content = content5; this.info = this.content.isCountable() ? BIT2 : 0; } /** * This is used to mark the item as an indexed fast-search marker * * @type {boolean} */ set marker(isMarked) { if ((this.info & BIT4) > 0 !== isMarked) { this.info ^= BIT4; } } get marker() { return (this.info & BIT4) > 0; } /** * If true, do not garbage collect this Item. */ get keep() { return (this.info & BIT1) > 0; } set keep(doKeep) { if (this.keep !== doKeep) { this.info ^= BIT1; } } get countable() { return (this.info & BIT2) > 0; } /** * Whether this item was deleted or not. * @type {Boolean} */ get deleted() { return (this.info & BIT3) > 0; } set deleted(doDelete) { if (this.deleted !== doDelete) { this.info ^= BIT3; } } markDeleted() { this.info |= BIT3; } /** * Return the creator clientID of the missing op or define missing items and return null. * * @param {Transaction} transaction * @param {StructStore} store * @return {null | number} */ getMissing(transaction, store) { if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) { return this.origin.client; } if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) { return this.rightOrigin.client; } if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) { return this.parent.client; } if (this.origin) { this.left = getItemCleanEnd(transaction, store, this.origin); this.origin = this.left.lastId; } if (this.rightOrigin) { this.right = getItemCleanStart(transaction, this.rightOrigin); this.rightOrigin = this.right.id; } if (this.left && this.left.constructor === GC || this.right && this.right.constructor === GC) { this.parent = null; } else if (!this.parent) { if (this.left && this.left.constructor === _Item) { this.parent = this.left.parent; this.parentSub = this.left.parentSub; } else if (this.right && this.right.constructor === _Item) { this.parent = this.right.parent; this.parentSub = this.right.parentSub; } } else if (this.parent.constructor === ID) { const parentItem = getItem(store, this.parent); if (parentItem.constructor === GC) { this.parent = null; } else { this.parent = /** @type {ContentType} */ parentItem.content.type; } } return null; } /** * @param {Transaction} transaction * @param {number} offset */ integrate(transaction, offset4) { if (offset4 > 0) { this.id.clock += offset4; this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1)); this.origin = this.left.lastId; this.content = this.content.splice(offset4); this.length -= offset4; } if (this.parent) { if (!this.left && (!this.right || this.right.left !== null) || this.left && this.left.right !== this.right) { let left = this.left; let o2; if (left !== null) { o2 = left.right; } else if (this.parentSub !== null) { o2 = /** @type {AbstractType} */ this.parent._map.get(this.parentSub) || null; while (o2 !== null && o2.left !== null) { o2 = o2.left; } } else { o2 = /** @type {AbstractType} */ this.parent._start; } const conflictingItems = /* @__PURE__ */ new Set(); const itemsBeforeOrigin = /* @__PURE__ */ new Set(); while (o2 !== null && o2 !== this.right) { itemsBeforeOrigin.add(o2); conflictingItems.add(o2); if (compareIDs(this.origin, o2.origin)) { if (o2.id.client < this.id.client) { left = o2; conflictingItems.clear(); } else if (compareIDs(this.rightOrigin, o2.rightOrigin)) { break; } } else if (o2.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o2.origin))) { if (!conflictingItems.has(getItem(transaction.doc.store, o2.origin))) { left = o2; conflictingItems.clear(); } } else { break; } o2 = o2.right; } this.left = left; } if (this.left !== null) { const right = this.left.right; this.right = right; this.left.right = this; } else { let r4; if (this.parentSub !== null) { r4 = /** @type {AbstractType} */ this.parent._map.get(this.parentSub) || null; while (r4 !== null && r4.left !== null) { r4 = r4.left; } } else { r4 = /** @type {AbstractType} */ this.parent._start; this.parent._start = this; } this.right = r4; } if (this.right !== null) { this.right.left = this; } else if (this.parentSub !== null) { this.parent._map.set(this.parentSub, this); if (this.left !== null) { this.left.delete(transaction); } } if (this.parentSub === null && this.countable && !this.deleted) { this.parent._length += this.length; } addStruct(transaction.doc.store, this); this.content.integrate(transaction, this); addChangedTypeToTransaction( transaction, /** @type {AbstractType} */ this.parent, this.parentSub ); if ( /** @type {AbstractType} */ this.parent._item !== null && /** @type {AbstractType} */ this.parent._item.deleted || this.parentSub !== null && this.right !== null ) { this.delete(transaction); } } else { new GC(this.id, this.length).integrate(transaction, 0); } } /** * Returns the next non-deleted item */ get next() { let n = this.right; while (n !== null && n.deleted) { n = n.right; } return n; } /** * Returns the previous non-deleted item */ get prev() { let n = this.left; while (n !== null && n.deleted) { n = n.left; } return n; } /** * Computes the last content address of this Item. */ get lastId() { return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1); } /** * Try to merge two items * * @param {Item} right * @return {boolean} */ mergeWith(right) { if (this.constructor === right.constructor && compareIDs(right.origin, this.lastId) && this.right === right && compareIDs(this.rightOrigin, right.rightOrigin) && this.id.client === right.id.client && this.id.clock + this.length === right.id.clock && this.deleted === right.deleted && this.redone === null && right.redone === null && this.content.constructor === right.content.constructor && this.content.mergeWith(right.content)) { const searchMarker = ( /** @type {AbstractType} */ this.parent._searchMarker ); if (searchMarker) { searchMarker.forEach((marker) => { if (marker.p === right) { marker.p = this; if (!this.deleted && this.countable) { marker.index -= this.length; } } }); } if (right.keep) { this.keep = true; } this.right = right.right; if (this.right !== null) { this.right.left = this; } this.length += right.length; return true; } return false; } /** * Mark this Item as deleted. * * @param {Transaction} transaction */ delete(transaction) { if (!this.deleted) { const parent = ( /** @type {AbstractType} */ this.parent ); if (this.countable && this.parentSub === null) { parent._length -= this.length; } this.markDeleted(); addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length); addChangedTypeToTransaction(transaction, parent, this.parentSub); this.content.delete(transaction); } } /** * @param {StructStore} store * @param {boolean} parentGCd */ gc(store, parentGCd) { if (!this.deleted) { throw unexpectedCase(); } this.content.gc(store); if (parentGCd) { replaceStruct(store, this, new GC(this.id, this.length)); } else { this.content = new ContentDeleted(this.length); } } /** * Transform the properties of this type to binary and write it to an * BinaryEncoder. * * This is called when this Item is sent to a remote peer. * * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. * @param {number} offset */ write(encoder, offset4) { const origin = offset4 > 0 ? createID(this.id.client, this.id.clock + offset4 - 1) : this.origin; const rightOrigin = this.rightOrigin; const parentSub = this.parentSub; const info = this.content.getRef() & BITS5 | (origin === null ? 0 : BIT8) | // origin is defined (rightOrigin === null ? 0 : BIT7) | // right origin is defined (parentSub === null ? 0 : BIT6); encoder.writeInfo(info); if (origin !== null) { encoder.writeLeftID(origin); } if (rightOrigin !== null) { encoder.writeRightID(rightOrigin); } if (origin === null && rightOrigin === null) { const parent = ( /** @type {AbstractType} */ this.parent ); if (parent._item !== void 0) { const parentItem = parent._item; if (parentItem === null) { const ykey = findRootTypeKey(parent); encoder.writeParentInfo(true); encoder.writeString(ykey); } else { encoder.writeParentInfo(false); encoder.writeLeftID(parentItem.id); } } else if (parent.constructor === String) { encoder.writeParentInfo(true); encoder.writeString(parent); } else if (parent.constructor === ID) { encoder.writeParentInfo(false); encoder.writeLeftID(parent); } else { unexpectedCase(); } if (parentSub !== null) { encoder.writeString(parentSub); } } this.content.write(encoder, offset4); } }; var readItemContent = (decoder, info) => contentRefs[info & BITS5](decoder); var contentRefs = [ () => { unexpectedCase(); }, // GC is not ItemContent readContentDeleted, // 1 readContentJSON, // 2 readContentBinary, // 3 readContentString, // 4 readContentEmbed, // 5 readContentFormat, // 6 readContentType, // 7 readContentAny, // 8 readContentDoc, // 9 () => { unexpectedCase(); } // 10 - Skip is not ItemContent ]; var structSkipRefNumber = 10; var Skip = class extends AbstractStruct { get deleted() { return true; } delete() { } /** * @param {Skip} right * @return {boolean} */ mergeWith(right) { if (this.constructor !== right.constructor) { return false; } this.length += right.length; return true; } /** * @param {Transaction} transaction * @param {number} offset */ integrate(transaction, offset4) { unexpectedCase(); } /** * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder * @param {number} offset */ write(encoder, offset4) { encoder.writeInfo(structSkipRefNumber); writeVarUint(encoder.restEncoder, this.length - offset4); } /** * @param {Transaction} transaction * @param {StructStore} store * @return {null | number} */ getMissing(transaction, store) { return null; } }; var glo = ( /** @type {any} */ typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {} ); var importIdentifier = "__ $YJS$ __"; if (glo[importIdentifier] === true) { console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438"); } glo[importIdentifier] = true; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/mutex.js var createMutex = () => { let token = true; return (f6, g) => { if (token) { token = false; try { f6(); } finally { token = true; } } else if (g !== void 0) { g(); } }; }; // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/diff.js var highSurrogateRegex = /[\uD800-\uDBFF]/; var lowSurrogateRegex = /[\uDC00-\uDFFF]/; var simpleDiffString = (a3, b4) => { let left = 0; let right = 0; while (left < a3.length && left < b4.length && a3[left] === b4[left]) { left++; } if (left > 0 && highSurrogateRegex.test(a3[left - 1])) left--; while (right + left < a3.length && right + left < b4.length && a3[a3.length - right - 1] === b4[b4.length - right - 1]) { right++; } if (right > 0 && lowSurrogateRegex.test(a3[a3.length - right])) right--; return { index: left, remove: a3.length - left - right, insert: b4.slice(left, b4.length - right) }; }; var simpleDiff = simpleDiffString; // ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/plugins/keys.js var ySyncPluginKey = new PluginKey("y-sync"); var yUndoPluginKey = new PluginKey("y-undo"); var yCursorPluginKey = new PluginKey("yjs-cursor"); // ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/hash/sha256.js var rotr = (w3, shift5) => w3 >>> shift5 | w3 << 32 - shift5; var sum0to256 = (x5) => rotr(x5, 2) ^ rotr(x5, 13) ^ rotr(x5, 22); var sum1to256 = (x5) => rotr(x5, 6) ^ rotr(x5, 11) ^ rotr(x5, 25); var sigma0to256 = (x5) => rotr(x5, 7) ^ rotr(x5, 18) ^ x5 >>> 3; var sigma1to256 = (x5) => rotr(x5, 17) ^ rotr(x5, 19) ^ x5 >>> 10; var K = new Uint32Array([ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]); var HINIT = new Uint32Array([ 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 ]); var Hasher = class { constructor() { const buf = new ArrayBuffer(64 + 64 * 4); this._H = new Uint32Array(buf, 0, 8); this._H.set(HINIT); this._W = new Uint32Array(buf, 64, 64); } _updateHash() { const H4 = this._H; const W3 = this._W; for (let t2 = 16; t2 < 64; t2++) { W3[t2] = sigma1to256(W3[t2 - 2]) + W3[t2 - 7] + sigma0to256(W3[t2 - 15]) + W3[t2 - 16]; } let a3 = H4[0]; let b4 = H4[1]; let c3 = H4[2]; let d = H4[3]; let e2 = H4[4]; let f6 = H4[5]; let g = H4[6]; let h7 = H4[7]; for (let tt3 = 0, T1, T22; tt3 < 64; tt3++) { T1 = h7 + sum1to256(e2) + (e2 & f6 ^ ~e2 & g) + K[tt3] + W3[tt3] >>> 0; T22 = sum0to256(a3) + (a3 & b4 ^ a3 & c3 ^ b4 & c3) >>> 0; h7 = g; g = f6; f6 = e2; e2 = d + T1 >>> 0; d = c3; c3 = b4; b4 = a3; a3 = T1 + T22 >>> 0; } H4[0] += a3; H4[1] += b4; H4[2] += c3; H4[3] += d; H4[4] += e2; H4[5] += f6; H4[6] += g; H4[7] += h7; } /** * Returns a 32-byte hash. * * @param {Uint8Array} data */ digest(data) { let i3 = 0; for (; i3 + 56 <= data.length; ) { let j5 = 0; for (; j5 < 16 && i3 + 3 < data.length; j5++) { this._W[j5] = data[i3++] << 24 | data[i3++] << 16 | data[i3++] << 8 | data[i3++]; } if (i3 % 64 !== 0) { this._W.fill(0, j5, 16); while (i3 < data.length) { this._W[j5] |= data[i3] << (3 - i3 % 4) * 8; i3++; } this._W[j5] |= BIT8 << (3 - i3 % 4) * 8; } this._updateHash(); } const isPaddedWith1 = i3 % 64 !== 0; this._W.fill(0, 0, 16); let j4 = 0; for (; i3 < data.length; j4++) { for (let ci2 = 3; ci2 >= 0 && i3 < data.length; ci2--) { this._W[j4] |= data[i3++] << ci2 * 8; } } if (!isPaddedWith1) { this._W[j4 - (i3 % 4 === 0 ? 0 : 1)] |= BIT8 << (3 - i3 % 4) * 8; } this._W[14] = data.byteLength / BIT30; this._W[15] = data.byteLength * 8; this._updateHash(); const dv = new Uint8Array(32); for (let i4 = 0; i4 < this._H.length; i4++) { for (let ci2 = 0; ci2 < 4; ci2++) { dv[i4 * 4 + ci2] = this._H[i4] >>> (3 - ci2) * 8; } } return dv; } }; var digest = (data) => new Hasher().digest(data); // ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/utils.js var _convolute = (digest2) => { const N3 = 6; for (let i3 = N3; i3 < digest2.length; i3++) { digest2[i3 % N3] = digest2[i3 % N3] ^ digest2[i3]; } return digest2.slice(0, N3); }; var hashOfJSON = (json) => toBase64(_convolute(digest(encodeAny(json)))); // ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/plugins/sync-plugin.js var isVisible2 = (item, snapshot2) => snapshot2 === void 0 ? !item.deleted : snapshot2.sv.has(item.id.client) && /** @type {number} */ snapshot2.sv.get(item.id.client) > item.id.clock && !isDeleted(snapshot2.ds, item.id); var defaultColors = [{ light: "#ecd44433", dark: "#ecd444" }]; var getUserColor = (colorMapping, colors, user) => { if (!colorMapping.has(user)) { if (colorMapping.size < colors.length) { const usedColors = create2(); colorMapping.forEach((color2) => usedColors.add(color2)); colors = colors.filter((color2) => !usedColors.has(color2)); } colorMapping.set(user, oneOf(colors)); } return ( /** @type {ColorDef} */ colorMapping.get(user) ); }; var ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = /* @__PURE__ */ new Map(), permanentUserData = null, onFirstRender = () => { }, mapping } = {}) => { let initialContentChanged = false; const binding = new ProsemirrorBinding(yXmlFragment, mapping); const plugin = new Plugin({ props: { editable: (state) => { const syncState = ySyncPluginKey.getState(state); return syncState.snapshot == null && syncState.prevSnapshot == null; } }, key: ySyncPluginKey, state: { /** * @returns {any} */ init: (_initargs, _state) => { return { type: yXmlFragment, doc: yXmlFragment.doc, binding, snapshot: null, prevSnapshot: null, isChangeOrigin: false, isUndoRedoOperation: false, addToHistory: true, colors, colorMapping, permanentUserData }; }, apply: (tr4, pluginState) => { const change = tr4.getMeta(ySyncPluginKey); if (change !== void 0) { pluginState = Object.assign({}, pluginState); for (const key2 in change) { pluginState[key2] = change[key2]; } } pluginState.addToHistory = tr4.getMeta("addToHistory") !== false; pluginState.isChangeOrigin = change !== void 0 && !!change.isChangeOrigin; pluginState.isUndoRedoOperation = change !== void 0 && !!change.isChangeOrigin && !!change.isUndoRedoOperation; if (binding.prosemirrorView !== null) { if (change !== void 0 && (change.snapshot != null || change.prevSnapshot != null)) { timeout(0, () => { if (binding.prosemirrorView == null) { return; } if (change.restore == null) { binding._renderSnapshot( change.snapshot, change.prevSnapshot, pluginState ); } else { binding._renderSnapshot( change.snapshot, change.snapshot, pluginState ); delete pluginState.restore; delete pluginState.snapshot; delete pluginState.prevSnapshot; binding.mux(() => { binding._prosemirrorChanged( binding.prosemirrorView.state.doc ); }); } }); } } return pluginState; } }, view: (view) => { binding.initView(view); if (mapping == null) { binding._forceRerender(); } onFirstRender(); return { update: () => { const pluginState = plugin.getState(view.state); if (pluginState.snapshot == null && pluginState.prevSnapshot == null) { if ( // If the content doesn't change initially, we don't render anything to Yjs // If the content was cleared by a user action, we want to catch the change and // represent it in Yjs initialContentChanged || view.state.doc.content.findDiffStart( view.state.doc.type.createAndFill().content ) !== null ) { initialContentChanged = true; if (pluginState.addToHistory === false && !pluginState.isChangeOrigin) { const yUndoPluginState = yUndoPluginKey.getState(view.state); const um = yUndoPluginState && yUndoPluginState.undoManager; if (um) { um.stopCapturing(); } } binding.mux(() => { pluginState.doc.transact((tr4) => { tr4.meta.set("addToHistory", pluginState.addToHistory); binding._prosemirrorChanged(view.state.doc); }, ySyncPluginKey); }); } } }, destroy: () => { binding.destroy(); } }; } }); return plugin; }; var restoreRelativeSelection = (tr4, relSel, binding) => { if (relSel !== null && relSel.anchor !== null && relSel.head !== null) { if (relSel.type === "all") { tr4.setSelection(new AllSelection(tr4.doc)); } else if (relSel.type === "node") { const anchor = relativePositionToAbsolutePosition( binding.doc, binding.type, relSel.anchor, binding.mapping ); tr4.setSelection(NodeSelection.create(tr4.doc, anchor)); } else { const anchor = relativePositionToAbsolutePosition( binding.doc, binding.type, relSel.anchor, binding.mapping ); const head2 = relativePositionToAbsolutePosition( binding.doc, binding.type, relSel.head, binding.mapping ); if (anchor !== null && head2 !== null) { const sel = TextSelection.between(tr4.doc.resolve(anchor), tr4.doc.resolve(head2)); tr4.setSelection(sel); } } } }; var getRelativeSelection = (pmbinding, state) => ({ type: ( /** @type {any} */ state.selection.jsonID ), anchor: absolutePositionToRelativePosition( state.selection.anchor, pmbinding.type, pmbinding.mapping ), head: absolutePositionToRelativePosition( state.selection.head, pmbinding.type, pmbinding.mapping ) }); var ProsemirrorBinding = class { /** * @param {Y.XmlFragment} yXmlFragment The bind source * @param {ProsemirrorMapping} mapping */ constructor(yXmlFragment, mapping = /* @__PURE__ */ new Map()) { this.type = yXmlFragment; this.prosemirrorView = null; this.mux = createMutex(); this.mapping = mapping; this.isOMark = /* @__PURE__ */ new Map(); this._observeFunction = this._typeChanged.bind(this); this.doc = yXmlFragment.doc; this.beforeTransactionSelection = null; this.beforeAllTransactions = () => { if (this.beforeTransactionSelection === null && this.prosemirrorView != null) { this.beforeTransactionSelection = getRelativeSelection( this, this.prosemirrorView.state ); } }; this.afterAllTransactions = () => { this.beforeTransactionSelection = null; }; this._domSelectionInView = null; } /** * Create a transaction for changing the prosemirror state. * * @returns */ get _tr() { return this.prosemirrorView.state.tr.setMeta("addToHistory", false); } _isLocalCursorInView() { if (!this.prosemirrorView.hasFocus()) return false; if (isBrowser && this._domSelectionInView === null) { timeout(0, () => { this._domSelectionInView = null; }); this._domSelectionInView = this._isDomSelectionInView(); } return this._domSelectionInView; } _isDomSelectionInView() { const selection = this.prosemirrorView._root.getSelection(); if (selection == null || selection.anchorNode == null) return false; const range = this.prosemirrorView._root.createRange(); range.setStart(selection.anchorNode, selection.anchorOffset); range.setEnd(selection.focusNode, selection.focusOffset); const rects = range.getClientRects(); if (rects.length === 0) { if (range.startContainer && range.collapsed) { range.selectNodeContents(range.startContainer); } } const bounding = range.getBoundingClientRect(); const documentElement = doc3.documentElement; return bounding.bottom >= 0 && bounding.right >= 0 && bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) && bounding.top <= (window.innerHeight || documentElement.clientHeight || 0); } /** * @param {Y.Snapshot} snapshot * @param {Y.Snapshot} prevSnapshot */ renderSnapshot(snapshot2, prevSnapshot) { if (!prevSnapshot) { prevSnapshot = createSnapshot(createDeleteSet(), /* @__PURE__ */ new Map()); } this.prosemirrorView.dispatch( this._tr.setMeta(ySyncPluginKey, { snapshot: snapshot2, prevSnapshot }) ); } unrenderSnapshot() { this.mapping.clear(); this.mux(() => { const fragmentContent = this.type.toArray().map( (t2) => createNodeFromYElement( /** @type {Y.XmlElement} */ t2, this.prosemirrorView.state.schema, this ) ).filter((n) => n !== null); const tr4 = this._tr.replace( 0, this.prosemirrorView.state.doc.content.size, new Slice(Fragment.from(fragmentContent), 0, 0) ); tr4.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null }); this.prosemirrorView.dispatch(tr4); }); } _forceRerender() { this.mapping.clear(); this.mux(() => { const sel = this.beforeTransactionSelection !== null ? null : this.prosemirrorView.state.selection; const fragmentContent = this.type.toArray().map( (t2) => createNodeFromYElement( /** @type {Y.XmlElement} */ t2, this.prosemirrorView.state.schema, this ) ).filter((n) => n !== null); const tr4 = this._tr.replace( 0, this.prosemirrorView.state.doc.content.size, new Slice(Fragment.from(fragmentContent), 0, 0) ); if (sel) { const clampedAnchor = min(max(sel.anchor, 0), tr4.doc.content.size); const clampedHead = min(max(sel.head, 0), tr4.doc.content.size); tr4.setSelection(TextSelection.create(tr4.doc, clampedAnchor, clampedHead)); } this.prosemirrorView.dispatch( tr4.setMeta(ySyncPluginKey, { isChangeOrigin: true, binding: this }) ); }); } /** * @param {Y.Snapshot|Uint8Array} snapshot * @param {Y.Snapshot|Uint8Array} prevSnapshot * @param {Object} pluginState */ _renderSnapshot(snapshot2, prevSnapshot, pluginState) { let historyDoc = this.doc; let historyType = this.type; if (!snapshot2) { snapshot2 = snapshot(this.doc); } if (snapshot2 instanceof Uint8Array || prevSnapshot instanceof Uint8Array) { if (!(snapshot2 instanceof Uint8Array) || !(prevSnapshot instanceof Uint8Array)) { unexpectedCase(); } historyDoc = new Doc({ gc: false }); applyUpdateV2(historyDoc, prevSnapshot); prevSnapshot = snapshot(historyDoc); applyUpdateV2(historyDoc, snapshot2); snapshot2 = snapshot(historyDoc); if (historyType._item === null) { const rootKey = Array.from(this.doc.share.keys()).find( (key2) => this.doc.share.get(key2) === this.type ); historyType = historyDoc.getXmlFragment(rootKey); } else { const historyStructs = historyDoc.store.clients.get(historyType._item.id.client) ?? []; const itemIndex = findIndexSS( historyStructs, historyType._item.id.clock ); const item = ( /** @type {Y.Item} */ historyStructs[itemIndex] ); const content5 = ( /** @type {Y.ContentType} */ item.content ); historyType = /** @type {Y.XmlFragment} */ content5.type; } } this.mapping.clear(); this.mux(() => { historyDoc.transact((transaction) => { const pud = pluginState.permanentUserData; if (pud) { pud.dss.forEach((ds) => { iterateDeletedStructs(transaction, ds, (_item) => { }); }); } const computeYChange = (type, id2) => { const user = type === "added" ? pud.getUserByClientId(id2.client) : pud.getUserByDeletedId(id2); return { user, type, color: getUserColor( pluginState.colorMapping, pluginState.colors, user ) }; }; const fragmentContent = typeListToArraySnapshot( historyType, new Snapshot(prevSnapshot.ds, snapshot2.sv) ).map((t2) => { if (!t2._item.deleted || isVisible2(t2._item, snapshot2) || isVisible2(t2._item, prevSnapshot)) { return createNodeFromYElement( t2, this.prosemirrorView.state.schema, { mapping: /* @__PURE__ */ new Map(), isOMark: /* @__PURE__ */ new Map() }, snapshot2, prevSnapshot, computeYChange ); } else { return null; } }).filter((n) => n !== null); const tr4 = this._tr.replace( 0, this.prosemirrorView.state.doc.content.size, new Slice(Fragment.from(fragmentContent), 0, 0) ); this.prosemirrorView.dispatch( tr4.setMeta(ySyncPluginKey, { isChangeOrigin: true }) ); }, ySyncPluginKey); }); } /** * @param {Array>} events * @param {Y.Transaction} transaction */ _typeChanged(events, transaction) { if (this.prosemirrorView == null) return; const syncState = ySyncPluginKey.getState(this.prosemirrorView.state); if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) { this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot); return; } this.mux(() => { const delType = (_2, type) => this.mapping.delete(type); iterateDeletedStructs( transaction, transaction.deleteSet, (struct) => { if (struct.constructor === Item) { const type = ( /** @type {Y.ContentType} */ /** @type {Y.Item} */ struct.content.type ); type && this.mapping.delete(type); } } ); transaction.changed.forEach(delType); transaction.changedParentTypes.forEach(delType); const fragmentContent = this.type.toArray().map( (t2) => createNodeIfNotExists( /** @type {Y.XmlElement | Y.XmlHook} */ t2, this.prosemirrorView.state.schema, this ) ).filter((n) => n !== null); let tr4 = this._tr.replace( 0, this.prosemirrorView.state.doc.content.size, new Slice(Fragment.from(fragmentContent), 0, 0) ); restoreRelativeSelection(tr4, this.beforeTransactionSelection, this); tr4 = tr4.setMeta(ySyncPluginKey, { isChangeOrigin: true, isUndoRedoOperation: transaction.origin instanceof UndoManager }); if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) { tr4.scrollIntoView(); } this.prosemirrorView.dispatch(tr4); }); } /** * @param {import('prosemirror-model').Node} doc */ _prosemirrorChanged(doc4) { this.doc.transact(() => { updateYFragment(this.doc, this.type, doc4, this); this.beforeTransactionSelection = getRelativeSelection( this, this.prosemirrorView.state ); }, ySyncPluginKey); } /** * View is ready to listen to changes. Register observers. * @param {any} prosemirrorView */ initView(prosemirrorView) { if (this.prosemirrorView != null) this.destroy(); this.prosemirrorView = prosemirrorView; this.doc.on("beforeAllTransactions", this.beforeAllTransactions); this.doc.on("afterAllTransactions", this.afterAllTransactions); this.type.observeDeep(this._observeFunction); } destroy() { if (this.prosemirrorView == null) return; this.prosemirrorView = null; this.type.unobserveDeep(this._observeFunction); this.doc.off("beforeAllTransactions", this.beforeAllTransactions); this.doc.off("afterAllTransactions", this.afterAllTransactions); } }; var createNodeIfNotExists = (el2, schema, meta2, snapshot2, prevSnapshot, computeYChange) => { const node2 = ( /** @type {PModel.Node} */ meta2.mapping.get(el2) ); if (node2 === void 0) { if (el2 instanceof YXmlElement) { return createNodeFromYElement( el2, schema, meta2, snapshot2, prevSnapshot, computeYChange ); } else { throw methodUnimplemented(); } } return node2; }; var createNodeFromYElement = (el2, schema, meta2, snapshot2, prevSnapshot, computeYChange) => { const children = []; const createChildren = (type) => { var _a2, _b; if (type instanceof YXmlElement) { const n = createNodeIfNotExists( type, schema, meta2, snapshot2, prevSnapshot, computeYChange ); if (n !== null) { children.push(n); } } else { const nextytext = ( /** @type {Y.ContentType} */ (_b = (_a2 = type._item.right) == null ? void 0 : _a2.content) == null ? void 0 : _b.type ); if (nextytext instanceof YText && !nextytext._item.deleted && nextytext._item.id.client === nextytext.doc.clientID) { type.applyDelta([ { retain: type.length }, ...nextytext.toDelta() ]); nextytext.doc.transact((tr4) => { nextytext._item.delete(tr4); }); } const ns = createTextNodesFromYText( type, schema, meta2, snapshot2, prevSnapshot, computeYChange ); if (ns !== null) { ns.forEach((textchild) => { if (textchild !== null) { children.push(textchild); } }); } } }; if (snapshot2 === void 0 || prevSnapshot === void 0) { el2.toArray().forEach(createChildren); } else { typeListToArraySnapshot(el2, new Snapshot(prevSnapshot.ds, snapshot2.sv)).forEach(createChildren); } try { const attrs = el2.getAttributes(snapshot2); if (snapshot2 !== void 0) { if (!isVisible2( /** @type {Y.Item} */ el2._item, snapshot2 )) { attrs.ychange = computeYChange ? computeYChange( "removed", /** @type {Y.Item} */ el2._item.id ) : { type: "removed" }; } else if (!isVisible2( /** @type {Y.Item} */ el2._item, prevSnapshot )) { attrs.ychange = computeYChange ? computeYChange( "added", /** @type {Y.Item} */ el2._item.id ) : { type: "added" }; } } const node2 = schema.node(el2.nodeName, attrs, children); meta2.mapping.set(el2, node2); return node2; } catch (e2) { el2.doc.transact((transaction) => { el2._item.delete(transaction); }, ySyncPluginKey); meta2.mapping.delete(el2); return null; } }; var createTextNodesFromYText = (text10, schema, _meta, snapshot2, prevSnapshot, computeYChange) => { const nodes = []; const deltas = text10.toDelta(snapshot2, prevSnapshot, computeYChange); try { for (let i3 = 0; i3 < deltas.length; i3++) { const delta = deltas[i3]; nodes.push(schema.text(delta.insert, attributesToMarks(delta.attributes, schema))); } } catch (e2) { text10.doc.transact((transaction) => { text10._item.delete(transaction); }, ySyncPluginKey); return null; } return nodes; }; var createTypeFromTextNodes = (nodes, meta2) => { const type = new YXmlText(); const delta = nodes.map((node2) => ({ // @ts-ignore insert: node2.text, attributes: marksToAttributes(node2.marks, meta2) })); type.applyDelta(delta); meta2.mapping.set(type, nodes); return type; }; var createTypeFromElementNode = (node2, meta2) => { const type = new YXmlElement(node2.type.name); for (const key2 in node2.attrs) { const val = node2.attrs[key2]; if (val !== null && key2 !== "ychange") { type.setAttribute(key2, val); } } type.insert( 0, normalizePNodeContent(node2).map( (n) => createTypeFromTextOrElementNode(n, meta2) ) ); meta2.mapping.set(type, node2); return type; }; var createTypeFromTextOrElementNode = (node2, meta2) => node2 instanceof Array ? createTypeFromTextNodes(node2, meta2) : createTypeFromElementNode(node2, meta2); var isObject2 = (val) => typeof val === "object" && val !== null; var equalAttrs2 = (pattrs, yattrs) => { const keys5 = Object.keys(pattrs).filter((key2) => pattrs[key2] !== null); let eq = keys5.length === (yattrs == null ? 0 : Object.keys(yattrs).filter((key2) => yattrs[key2] !== null).length); for (let i3 = 0; i3 < keys5.length && eq; i3++) { const key2 = keys5[i3]; const l2 = pattrs[key2]; const r4 = yattrs[key2]; eq = key2 === "ychange" || l2 === r4 || isObject2(l2) && isObject2(r4) && equalAttrs2(l2, r4); } return eq; }; var normalizePNodeContent = (pnode) => { const c3 = pnode.content.content; const res = []; for (let i3 = 0; i3 < c3.length; i3++) { const n = c3[i3]; if (n.isText) { const textNodes = []; for (let tnode = c3[i3]; i3 < c3.length && tnode.isText; tnode = c3[++i3]) { textNodes.push(tnode); } i3--; res.push(textNodes); } else { res.push(n); } } return res; }; var equalYTextPText = (ytext, ptexts) => { const delta = ytext.toDelta(); return delta.length === ptexts.length && delta.every( /** @type {(d:any,i:number) => boolean} */ (d, i3) => d.insert === /** @type {any} */ ptexts[i3].text && keys2(d.attributes || {}).length === ptexts[i3].marks.length && every2(d.attributes, (attr2, yattrname) => { var _a2; const markname = yattr2markname(yattrname); const pmarks = ptexts[i3].marks; return equalAttrs2(attr2, (_a2 = pmarks.find( /** @param {any} mark */ (mark2) => mark2.type.name === markname )) == null ? void 0 : _a2.attrs); }) ); }; var equalYTypePNode = (ytype, pnode) => { if (ytype instanceof YXmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) { const normalizedContent = normalizePNodeContent(pnode); return ytype._length === normalizedContent.length && equalAttrs2(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every( (ychild, i3) => equalYTypePNode(ychild, normalizedContent[i3]) ); } return ytype instanceof YXmlText && pnode instanceof Array && equalYTextPText(ytype, pnode); }; var mappedIdentity = (mapped, pcontent) => mapped === pcontent || mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every( (a3, i3) => pcontent[i3] === a3 ); var computeChildEqualityFactor = (ytype, pnode, meta2) => { const yChildren = ytype.toArray(); const pChildren = normalizePNodeContent(pnode); const pChildCnt = pChildren.length; const yChildCnt = yChildren.length; const minCnt = min(yChildCnt, pChildCnt); let left = 0; let right = 0; let foundMappedChild = false; for (; left < minCnt; left++) { const leftY = yChildren[left]; const leftP = pChildren[left]; if (mappedIdentity(meta2.mapping.get(leftY), leftP)) { foundMappedChild = true; } else if (!equalYTypePNode(leftY, leftP)) { break; } } for (; left + right < minCnt; right++) { const rightY = yChildren[yChildCnt - right - 1]; const rightP = pChildren[pChildCnt - right - 1]; if (mappedIdentity(meta2.mapping.get(rightY), rightP)) { foundMappedChild = true; } else if (!equalYTypePNode(rightY, rightP)) { break; } } return { equalityFactor: left + right, foundMappedChild }; }; var ytextTrans = (ytext) => { let str = ""; let n = ytext._start; const nAttrs = {}; while (n !== null) { if (!n.deleted) { if (n.countable && n.content instanceof ContentString) { str += n.content.str; } else if (n.content instanceof ContentFormat) { nAttrs[n.content.key] = null; } } n = n.right; } return { str, nAttrs }; }; var updateYText = (ytext, ptexts, meta2) => { meta2.mapping.set(ytext, ptexts); const { nAttrs, str } = ytextTrans(ytext); const content5 = ptexts.map((p4) => ({ insert: ( /** @type {any} */ p4.text ), attributes: Object.assign({}, nAttrs, marksToAttributes(p4.marks, meta2)) })); const { insert, remove, index: index4 } = simpleDiff( str, content5.map((c3) => c3.insert).join("") ); ytext.delete(index4, remove); ytext.insert(index4, insert); ytext.applyDelta( content5.map((c3) => ({ retain: c3.insert.length, attributes: c3.attributes })) ); }; var hashedMarkNameRegex = /(.*)(--[a-zA-Z0-9+/=]{8})$/; var yattr2markname = (attrName) => { var _a2; return ((_a2 = hashedMarkNameRegex.exec(attrName)) == null ? void 0 : _a2[1]) ?? attrName; }; var attributesToMarks = (attrs, schema) => { const marks = []; for (const markName in attrs) { marks.push(schema.mark(yattr2markname(markName), attrs[markName])); } return marks; }; var marksToAttributes = (marks, meta2) => { const pattrs = {}; marks.forEach((mark2) => { if (mark2.type.name !== "ychange") { const isOverlapping = setIfUndefined(meta2.isOMark, mark2.type, () => !mark2.type.excludes(mark2.type)); pattrs[isOverlapping ? `${mark2.type.name}--${hashOfJSON(mark2.toJSON())}` : mark2.type.name] = mark2.attrs; } }); return pattrs; }; var updateYFragment = (y3, yDomFragment, pNode, meta2) => { if (yDomFragment instanceof YXmlElement && yDomFragment.nodeName !== pNode.type.name) { throw new Error("node name mismatch!"); } meta2.mapping.set(yDomFragment, pNode); if (yDomFragment instanceof YXmlElement) { const yDomAttrs = yDomFragment.getAttributes(); const pAttrs = pNode.attrs; for (const key2 in pAttrs) { if (pAttrs[key2] !== null) { if (yDomAttrs[key2] !== pAttrs[key2] && key2 !== "ychange") { yDomFragment.setAttribute(key2, pAttrs[key2]); } } else { yDomFragment.removeAttribute(key2); } } for (const key2 in yDomAttrs) { if (pAttrs[key2] === void 0) { yDomFragment.removeAttribute(key2); } } } const pChildren = normalizePNodeContent(pNode); const pChildCnt = pChildren.length; const yChildren = yDomFragment.toArray(); const yChildCnt = yChildren.length; const minCnt = min(pChildCnt, yChildCnt); let left = 0; let right = 0; for (; left < minCnt; left++) { const leftY = yChildren[left]; const leftP = pChildren[left]; if (!mappedIdentity(meta2.mapping.get(leftY), leftP)) { if (equalYTypePNode(leftY, leftP)) { meta2.mapping.set(leftY, leftP); } else { break; } } } for (; right + left < minCnt; right++) { const rightY = yChildren[yChildCnt - right - 1]; const rightP = pChildren[pChildCnt - right - 1]; if (!mappedIdentity(meta2.mapping.get(rightY), rightP)) { if (equalYTypePNode(rightY, rightP)) { meta2.mapping.set(rightY, rightP); } else { break; } } } y3.transact(() => { while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) { const leftY = yChildren[left]; const leftP = pChildren[left]; const rightY = yChildren[yChildCnt - right - 1]; const rightP = pChildren[pChildCnt - right - 1]; if (leftY instanceof YXmlText && leftP instanceof Array) { if (!equalYTextPText(leftY, leftP)) { updateYText(leftY, leftP, meta2); } left += 1; } else { let updateLeft = leftY instanceof YXmlElement && matchNodeName(leftY, leftP); let updateRight = rightY instanceof YXmlElement && matchNodeName(rightY, rightP); if (updateLeft && updateRight) { const equalityLeft = computeChildEqualityFactor( /** @type {Y.XmlElement} */ leftY, /** @type {PModel.Node} */ leftP, meta2 ); const equalityRight = computeChildEqualityFactor( /** @type {Y.XmlElement} */ rightY, /** @type {PModel.Node} */ rightP, meta2 ); if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) { updateRight = false; } else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) { updateLeft = false; } else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) { updateLeft = false; } else { updateRight = false; } } if (updateLeft) { updateYFragment( y3, /** @type {Y.XmlFragment} */ leftY, /** @type {PModel.Node} */ leftP, meta2 ); left += 1; } else if (updateRight) { updateYFragment( y3, /** @type {Y.XmlFragment} */ rightY, /** @type {PModel.Node} */ rightP, meta2 ); right += 1; } else { meta2.mapping.delete(yDomFragment.get(left)); yDomFragment.delete(left, 1); yDomFragment.insert(left, [ createTypeFromTextOrElementNode(leftP, meta2) ]); left += 1; } } } const yDelLen = yChildCnt - left - right; if (yChildCnt === 1 && pChildCnt === 0 && yChildren[0] instanceof YXmlText) { meta2.mapping.delete(yChildren[0]); yChildren[0].delete(0, yChildren[0].length); } else if (yDelLen > 0) { yDomFragment.slice(left, left + yDelLen).forEach((type) => meta2.mapping.delete(type)); yDomFragment.delete(left, yDelLen); } if (left + right < pChildCnt) { const ins = []; for (let i3 = left; i3 < pChildCnt - right; i3++) { ins.push(createTypeFromTextOrElementNode(pChildren[i3], meta2)); } yDomFragment.insert(left, ins); } }, ySyncPluginKey); }; var matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name; // ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/lib.js var viewsToUpdate = null; var updateMetas = () => { const ups = ( /** @type {Map>} */ viewsToUpdate ); viewsToUpdate = null; ups.forEach((metas, view) => { const tr4 = view.state.tr; const syncState = ySyncPluginKey.getState(view.state); if (syncState && syncState.binding && !syncState.binding.isDestroyed) { metas.forEach((val, key2) => { tr4.setMeta(key2, val); }); view.dispatch(tr4); } }); }; var setMeta = (view, key2, value) => { if (!viewsToUpdate) { viewsToUpdate = /* @__PURE__ */ new Map(); timeout(0, updateMetas); } setIfUndefined(viewsToUpdate, view, create).set(key2, value); }; var absolutePositionToRelativePosition = (pos, type, mapping) => { if (pos === 0) { return createRelativePositionFromTypeIndex(type, 0, type.length === 0 ? -1 : 0); } let n = type._first === null ? null : ( /** @type {Y.ContentType} */ type._first.content.type ); while (n !== null && type !== n) { if (n instanceof YXmlText) { if (n._length >= pos) { return createRelativePositionFromTypeIndex(n, pos, type.length === 0 ? -1 : 0); } else { pos -= n._length; } if (n._item !== null && n._item.next !== null) { n = /** @type {Y.ContentType} */ n._item.next.content.type; } else { do { n = n._item === null ? null : n._item.parent; pos--; } while (n !== type && n !== null && n._item !== null && n._item.next === null); if (n !== null && n !== type) { n = n._item === null ? null : ( /** @type {Y.ContentType} */ /** @type Y.Item */ n._item.next.content.type ); } } } else { const pNodeSize = ( /** @type {any} */ (mapping.get(n) || { nodeSize: 0 }).nodeSize ); if (n._first !== null && pos < pNodeSize) { n = /** @type {Y.ContentType} */ n._first.content.type; pos--; } else { if (pos === 1 && n._length === 0 && pNodeSize > 1) { return new RelativePosition(n._item === null ? null : n._item.id, n._item === null ? findRootTypeKey(n) : null, null); } pos -= pNodeSize; if (n._item !== null && n._item.next !== null) { n = /** @type {Y.ContentType} */ n._item.next.content.type; } else { if (pos === 0) { n = n._item === null ? n : n._item.parent; return new RelativePosition(n._item === null ? null : n._item.id, n._item === null ? findRootTypeKey(n) : null, null); } do { n = /** @type {Y.Item} */ n._item.parent; pos--; } while (n !== type && /** @type {Y.Item} */ n._item.next === null); if (n !== type) { n = /** @type {Y.ContentType} */ /** @type {Y.Item} */ /** @type {Y.Item} */ n._item.next.content.type; } } } } if (n === null) { throw unexpectedCase(); } if (pos === 0 && n.constructor !== YXmlText && n !== type) { return createRelativePosition2(n._item.parent, n._item); } } return createRelativePositionFromTypeIndex(type, type._length, type.length === 0 ? -1 : 0); }; var createRelativePosition2 = (type, item) => { let typeid = null; let tname = null; if (type._item === null) { tname = findRootTypeKey(type); } else { typeid = createID(type._item.id.client, type._item.id.clock); } return new RelativePosition(typeid, tname, item.id); }; var relativePositionToAbsolutePosition = (y3, documentType, relPos, mapping) => { const decodedPos = createAbsolutePositionFromRelativePosition(relPos, y3); if (decodedPos === null || decodedPos.type !== documentType && !isParentOf(documentType, decodedPos.type._item)) { return null; } let type = decodedPos.type; let pos = 0; if (type.constructor === YXmlText) { pos = decodedPos.index; } else if (type._item === null || !type._item.deleted) { let n = type._first; let i3 = 0; while (i3 < type._length && i3 < decodedPos.index && n !== null) { if (!n.deleted) { const t2 = ( /** @type {Y.ContentType} */ n.content.type ); i3++; if (t2 instanceof YXmlText) { pos += t2._length; } else { pos += /** @type {any} */ mapping.get(t2).nodeSize; } } n = /** @type {Y.Item} */ n.right; } pos += 1; } while (type !== documentType && type._item !== null) { const parent = type._item.parent; if (parent._item === null || !parent._item.deleted) { pos += 1; let n = ( /** @type {Y.AbstractType} */ parent._first ); while (n !== null) { const contentType = ( /** @type {Y.ContentType} */ n.content.type ); if (contentType === type) { break; } if (!n.deleted) { if (contentType instanceof YXmlText) { pos += contentType._length; } else { pos += /** @type {any} */ mapping.get(contentType).nodeSize; } } n = n.right; } } type = /** @type {Y.AbstractType} */ parent; } return pos - 1; }; // ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/plugins/cursor-plugin.js var defaultAwarenessStateFilter = (currentClientId, userClientId, _user) => currentClientId !== userClientId; var defaultCursorBuilder = (user) => { const cursor = document.createElement("span"); cursor.classList.add("ProseMirror-yjs-cursor"); cursor.setAttribute("style", `border-color: ${user.color}`); const userDiv = document.createElement("div"); userDiv.setAttribute("style", `background-color: ${user.color}`); userDiv.insertBefore(document.createTextNode(user.name), null); const nonbreakingSpace1 = document.createTextNode("⁠"); const nonbreakingSpace2 = document.createTextNode("⁠"); cursor.insertBefore(nonbreakingSpace1, null); cursor.insertBefore(userDiv, null); cursor.insertBefore(nonbreakingSpace2, null); return cursor; }; var defaultSelectionBuilder = (user) => { return { style: `background-color: ${user.color}70`, class: "ProseMirror-yjs-selection" }; }; var rxValidColor = /^#[0-9a-fA-F]{6}$/; var createDecorations = (state, awareness, awarenessFilter, createCursor, createSelection) => { const ystate = ySyncPluginKey.getState(state); const y3 = ystate.doc; const decorations = []; if (ystate.snapshot != null || ystate.prevSnapshot != null || ystate.binding.mapping.size === 0) { return DecorationSet.create(state.doc, []); } awareness.getStates().forEach((aw, clientId) => { if (!awarenessFilter(y3.clientID, clientId, aw)) { return; } if (aw.cursor != null) { const user = aw.user || {}; if (user.color == null) { user.color = "#ffa500"; } else if (!rxValidColor.test(user.color)) { console.warn("A user uses an unsupported color format", user); } if (user.name == null) { user.name = `User: ${clientId}`; } let anchor = relativePositionToAbsolutePosition( y3, ystate.type, createRelativePositionFromJSON(aw.cursor.anchor), ystate.binding.mapping ); let head2 = relativePositionToAbsolutePosition( y3, ystate.type, createRelativePositionFromJSON(aw.cursor.head), ystate.binding.mapping ); if (anchor !== null && head2 !== null) { const maxsize = max(state.doc.content.size - 1, 0); anchor = min(anchor, maxsize); head2 = min(head2, maxsize); decorations.push( Decoration.widget(head2, () => createCursor(user, clientId), { key: clientId + "", side: 10 }) ); const from4 = min(anchor, head2); const to2 = max(anchor, head2); decorations.push( Decoration.inline(from4, to2, createSelection(user, clientId), { inclusiveEnd: true, inclusiveStart: false }) ); } } }); return DecorationSet.create(state.doc, decorations); }; var yCursorPlugin = (awareness, { awarenessStateFilter = defaultAwarenessStateFilter, cursorBuilder = defaultCursorBuilder, selectionBuilder = defaultSelectionBuilder, getSelection: getSelection2 = (state) => state.selection } = {}, cursorStateField = "cursor") => new Plugin({ key: yCursorPluginKey, state: { init(_2, state) { return createDecorations( state, awareness, awarenessStateFilter, cursorBuilder, selectionBuilder ); }, apply(tr4, prevState, _oldState, newState) { const ystate = ySyncPluginKey.getState(newState); const yCursorState = tr4.getMeta(yCursorPluginKey); if (ystate && ystate.isChangeOrigin || yCursorState && yCursorState.awarenessUpdated) { return createDecorations( newState, awareness, awarenessStateFilter, cursorBuilder, selectionBuilder ); } return prevState.map(tr4.mapping, tr4.doc); } }, props: { decorations: (state) => { return yCursorPluginKey.getState(state); } }, view: (view) => { const awarenessListener = () => { if (view.docView) { setMeta(view, yCursorPluginKey, { awarenessUpdated: true }); } }; const updateCursorInfo = () => { const ystate = ySyncPluginKey.getState(view.state); const current = awareness.getLocalState() || {}; if (view.hasFocus()) { const selection = getSelection2(view.state); const anchor = absolutePositionToRelativePosition( selection.anchor, ystate.type, ystate.binding.mapping ); const head2 = absolutePositionToRelativePosition( selection.head, ystate.type, ystate.binding.mapping ); if (current.cursor == null || !compareRelativePositions( createRelativePositionFromJSON(current.cursor.anchor), anchor ) || !compareRelativePositions( createRelativePositionFromJSON(current.cursor.head), head2 )) { awareness.setLocalStateField(cursorStateField, { anchor, head: head2 }); } } else if (current.cursor != null && relativePositionToAbsolutePosition( ystate.doc, ystate.type, createRelativePositionFromJSON(current.cursor.anchor), ystate.binding.mapping ) !== null) { awareness.setLocalStateField(cursorStateField, null); } }; awareness.on("change", awarenessListener); view.dom.addEventListener("focusin", updateCursorInfo); view.dom.addEventListener("focusout", updateCursorInfo); return { update: updateCursorInfo, destroy: () => { view.dom.removeEventListener("focusin", updateCursorInfo); view.dom.removeEventListener("focusout", updateCursorInfo); awareness.off("change", awarenessListener); awareness.setLocalStateField(cursorStateField, null); } }; } }); // ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/plugins/undo-plugin.js var undo = (state) => { var _a2, _b; return ((_b = (_a2 = yUndoPluginKey.getState(state)) == null ? void 0 : _a2.undoManager) == null ? void 0 : _b.undo()) != null; }; var redo = (state) => { var _a2, _b; return ((_b = (_a2 = yUndoPluginKey.getState(state)) == null ? void 0 : _a2.undoManager) == null ? void 0 : _b.redo()) != null; }; var undoCommand = (state, dispatch) => { var _a2, _b; return dispatch == null ? (_b = (_a2 = yUndoPluginKey.getState(state)) == null ? void 0 : _a2.undoManager) == null ? void 0 : _b.canUndo() : undo(state); }; var redoCommand = (state, dispatch) => { var _a2, _b; return dispatch == null ? (_b = (_a2 = yUndoPluginKey.getState(state)) == null ? void 0 : _a2.undoManager) == null ? void 0 : _b.canRedo() : redo(state); }; var defaultProtectedNodes = /* @__PURE__ */ new Set(["paragraph"]); var defaultDeleteFilter = (item, protectedNodes) => !(item instanceof Item) || !(item.content instanceof ContentType) || !(item.content.type instanceof YText || item.content.type instanceof YXmlElement && protectedNodes.has(item.content.type.nodeName)) || item.content.type._length === 0; var yUndoPlugin = ({ protectedNodes = defaultProtectedNodes, trackedOrigins = [], undoManager = null } = {}) => new Plugin({ key: yUndoPluginKey, state: { init: (initargs, state) => { const ystate = ySyncPluginKey.getState(state); const _undoManager = undoManager || new UndoManager(ystate.type, { trackedOrigins: new Set([ySyncPluginKey].concat(trackedOrigins)), deleteFilter: (item) => defaultDeleteFilter(item, protectedNodes), captureTransaction: (tr4) => tr4.meta.get("addToHistory") !== false }); return { undoManager: _undoManager, prevSel: null, hasUndoOps: _undoManager.undoStack.length > 0, hasRedoOps: _undoManager.redoStack.length > 0 }; }, apply: (tr4, val, oldState, state) => { const binding = ySyncPluginKey.getState(state).binding; const undoManager2 = val.undoManager; const hasUndoOps = undoManager2.undoStack.length > 0; const hasRedoOps = undoManager2.redoStack.length > 0; if (binding) { return { undoManager: undoManager2, prevSel: getRelativeSelection(binding, oldState), hasUndoOps, hasRedoOps }; } else { if (hasUndoOps !== val.hasUndoOps || hasRedoOps !== val.hasRedoOps) { return Object.assign({}, val, { hasUndoOps: undoManager2.undoStack.length > 0, hasRedoOps: undoManager2.redoStack.length > 0 }); } else { return val; } } } }, view: (view) => { const ystate = ySyncPluginKey.getState(view.state); const undoManager2 = yUndoPluginKey.getState(view.state).undoManager; undoManager2.on("stack-item-added", ({ stackItem }) => { const binding = ystate.binding; if (binding) { stackItem.meta.set(binding, yUndoPluginKey.getState(view.state).prevSel); } }); undoManager2.on("stack-item-popped", ({ stackItem }) => { const binding = ystate.binding; if (binding) { binding.beforeTransactionSelection = stackItem.meta.get(binding) || binding.beforeTransactionSelection; } }); return { destroy: () => { undoManager2.destroy(); } }; } }); // ../../node_modules/.pnpm/@tanstack+store@0.7.7/node_modules/@tanstack/store/dist/esm/scheduler.js var __storeToDerived = /* @__PURE__ */ new WeakMap(); var __derivedToStore = /* @__PURE__ */ new WeakMap(); var __depsThatHaveWrittenThisTick = { current: [] }; var __isFlushing = false; var __batchDepth = 0; var __pendingUpdates = /* @__PURE__ */ new Set(); var __initialBatchValues = /* @__PURE__ */ new Map(); function __flush_internals(relatedVals) { const sorted = Array.from(relatedVals).sort((a3, b4) => { if (a3 instanceof Derived && a3.options.deps.includes(b4)) return 1; if (b4 instanceof Derived && b4.options.deps.includes(a3)) return -1; return 0; }); for (const derived of sorted) { if (__depsThatHaveWrittenThisTick.current.includes(derived)) { continue; } __depsThatHaveWrittenThisTick.current.push(derived); derived.recompute(); const stores = __derivedToStore.get(derived); if (stores) { for (const store of stores) { const relatedLinkedDerivedVals = __storeToDerived.get(store); if (!relatedLinkedDerivedVals) continue; __flush_internals(relatedLinkedDerivedVals); } } } } function __notifyListeners(store) { const value = { prevVal: store.prevState, currentVal: store.state }; for (const listener of store.listeners) { listener(value); } } function __notifyDerivedListeners(derived) { const value = { prevVal: derived.prevState, currentVal: derived.state }; for (const listener of derived.listeners) { listener(value); } } function __flush(store) { if (__batchDepth > 0 && !__initialBatchValues.has(store)) { __initialBatchValues.set(store, store.prevState); } __pendingUpdates.add(store); if (__batchDepth > 0) return; if (__isFlushing) return; try { __isFlushing = true; while (__pendingUpdates.size > 0) { const stores = Array.from(__pendingUpdates); __pendingUpdates.clear(); for (const store2 of stores) { const prevState = __initialBatchValues.get(store2) ?? store2.prevState; store2.prevState = prevState; __notifyListeners(store2); } for (const store2 of stores) { const derivedVals = __storeToDerived.get(store2); if (!derivedVals) continue; __depsThatHaveWrittenThisTick.current.push(store2); __flush_internals(derivedVals); } for (const store2 of stores) { const derivedVals = __storeToDerived.get(store2); if (!derivedVals) continue; for (const derived of derivedVals) { __notifyDerivedListeners(derived); } } } } finally { __isFlushing = false; __depsThatHaveWrittenThisTick.current = []; __initialBatchValues.clear(); } } // ../../node_modules/.pnpm/@tanstack+store@0.7.7/node_modules/@tanstack/store/dist/esm/types.js function isUpdaterFunction(updater) { return typeof updater === "function"; } // ../../node_modules/.pnpm/@tanstack+store@0.7.7/node_modules/@tanstack/store/dist/esm/store.js var Store = class { constructor(initialState, options2) { this.listeners = /* @__PURE__ */ new Set(); this.subscribe = (listener) => { var _a2, _b; this.listeners.add(listener); const unsub = (_b = (_a2 = this.options) == null ? void 0 : _a2.onSubscribe) == null ? void 0 : _b.call(_a2, listener, this); return () => { this.listeners.delete(listener); unsub == null ? void 0 : unsub(); }; }; this.prevState = initialState; this.state = initialState; this.options = options2; } setState(updater) { var _a2, _b, _c; this.prevState = this.state; if ((_a2 = this.options) == null ? void 0 : _a2.updateFn) { this.state = this.options.updateFn(this.prevState)(updater); } else { if (isUpdaterFunction(updater)) { this.state = updater(this.prevState); } else { this.state = updater; } } (_c = (_b = this.options) == null ? void 0 : _b.onUpdate) == null ? void 0 : _c.call(_b); __flush(this); } }; // ../../node_modules/.pnpm/@tanstack+store@0.7.7/node_modules/@tanstack/store/dist/esm/derived.js var Derived = class _Derived { constructor(options2) { this.listeners = /* @__PURE__ */ new Set(); this._subscriptions = []; this.lastSeenDepValues = []; this.getDepVals = () => { const l2 = this.options.deps.length; const prevDepVals = new Array(l2); const currDepVals = new Array(l2); for (let i3 = 0; i3 < l2; i3++) { const dep = this.options.deps[i3]; prevDepVals[i3] = dep.prevState; currDepVals[i3] = dep.state; } this.lastSeenDepValues = currDepVals; return { prevDepVals, currDepVals, prevVal: this.prevState ?? void 0 }; }; this.recompute = () => { var _a2, _b; this.prevState = this.state; const depVals = this.getDepVals(); this.state = this.options.fn(depVals); (_b = (_a2 = this.options).onUpdate) == null ? void 0 : _b.call(_a2); }; this.checkIfRecalculationNeededDeeply = () => { for (const dep of this.options.deps) { if (dep instanceof _Derived) { dep.checkIfRecalculationNeededDeeply(); } } let shouldRecompute = false; const lastSeenDepValues = this.lastSeenDepValues; const { currDepVals } = this.getDepVals(); for (let i3 = 0; i3 < currDepVals.length; i3++) { if (currDepVals[i3] !== lastSeenDepValues[i3]) { shouldRecompute = true; break; } } if (shouldRecompute) { this.recompute(); } }; this.mount = () => { this.registerOnGraph(); this.checkIfRecalculationNeededDeeply(); return () => { this.unregisterFromGraph(); for (const cleanup2 of this._subscriptions) { cleanup2(); } }; }; this.subscribe = (listener) => { var _a2, _b; this.listeners.add(listener); const unsub = (_b = (_a2 = this.options).onSubscribe) == null ? void 0 : _b.call(_a2, listener, this); return () => { this.listeners.delete(listener); unsub == null ? void 0 : unsub(); }; }; this.options = options2; this.state = options2.fn({ prevDepVals: void 0, prevVal: void 0, currDepVals: this.getDepVals().currDepVals }); } registerOnGraph(deps = this.options.deps) { for (const dep of deps) { if (dep instanceof _Derived) { dep.registerOnGraph(); this.registerOnGraph(dep.options.deps); } else if (dep instanceof Store) { let relatedLinkedDerivedVals = __storeToDerived.get(dep); if (!relatedLinkedDerivedVals) { relatedLinkedDerivedVals = /* @__PURE__ */ new Set(); __storeToDerived.set(dep, relatedLinkedDerivedVals); } relatedLinkedDerivedVals.add(this); let relatedStores = __derivedToStore.get(this); if (!relatedStores) { relatedStores = /* @__PURE__ */ new Set(); __derivedToStore.set(this, relatedStores); } relatedStores.add(dep); } } } unregisterFromGraph(deps = this.options.deps) { for (const dep of deps) { if (dep instanceof _Derived) { this.unregisterFromGraph(dep.options.deps); } else if (dep instanceof Store) { const relatedLinkedDerivedVals = __storeToDerived.get(dep); if (relatedLinkedDerivedVals) { relatedLinkedDerivedVals.delete(this); } const relatedStores = __derivedToStore.get(this); if (relatedStores) { relatedStores.delete(dep); } } } } }; // ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/BlockNoteExtension-C2X7LW-V.js var r = Symbol("originalFactory"); function a(n) { if (typeof n == "object" && "key" in n) return function t2() { return n[r] = t2, n; }; if (typeof n != "function") throw new Error("factory must be a function"); return function t2(e2) { return (i3) => { const o2 = n({ editor: i3.editor, options: e2 }); return o2[r] = t2, o2; }; }; } function f(n, t2) { return new Store(n, t2); } // ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/ShowSelection-Dz-NEase.js var r2 = new PluginKey("blocknote-show-selection"); var f2 = a(({ editor: s2 }) => { const t2 = f( { enabled: false }, { onUpdate() { s2.transact((e2) => e2.setMeta(r2, {})); } } ); return { key: "showSelection", store: t2, prosemirrorPlugins: [ new Plugin({ key: r2, props: { decorations: (e2) => { const { doc: a3, selection: o2 } = e2; if (!t2.state.enabled) return DecorationSet.empty; const c3 = Decoration.inline(o2.from, o2.to, { "data-show-selection": "true" }); return DecorationSet.create(a3, [c3]); } } }) ], /** * Show or hide the selection decoration */ showSelection(e2) { t2.setState({ enabled: e2 }); } }; }); // ../../node_modules/.pnpm/prosemirror-commands@1.7.1/node_modules/prosemirror-commands/dist/index.js var deleteSelection = (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; } var 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 tr4 = state.tr.step(delStep); tr4.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr4.doc.resolve(tr4.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr4.doc, $cut.pos - before.nodeSize)); dispatch(tr4.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; }; var joinTextblockBackward = (state, dispatch, view) => { let $cursor = atBlockStart(state, view); if (!$cursor) return false; let $cut = findCutBefore($cursor); return $cut ? joinTextblocksAround(state, $cut, dispatch) : false; }; var 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 tr4 = state.tr.step(step); tr4.setSelection(TextSelection.create(tr4.doc, beforePos)); dispatch(tr4.scrollIntoView()); } return true; } function textblockAt(node2, side, only = false) { for (let scan = node2; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) { if (scan.isTextblock) return true; if (only && scan.childCount != 1) return false; } return false; } var selectNodeBackward = (state, dispatch, view) => { let { $head, empty: empty4 } = state.selection, $cut = $head; if (!empty4) return false; if ($head.parent.isTextblock) { if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0) return false; $cut = findCutBefore($head); } let node2 = $cut && $cut.nodeBefore; if (!node2 || !NodeSelection.isSelectable(node2)) return false; if (dispatch) dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node2.nodeSize)).scrollIntoView()); return true; }; function findCutBefore($pos) { if (!$pos.parent.type.spec.isolating) for (let i3 = $pos.depth - 1; i3 >= 0; i3--) { if ($pos.index(i3) > 0) return $pos.doc.resolve($pos.before(i3 + 1)); if ($pos.node(i3).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; } var 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 tr4 = state.tr.step(delStep); tr4.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr4.doc.resolve(tr4.mapping.map($cut.pos)), 1) : NodeSelection.create(tr4.doc, tr4.mapping.map($cut.pos))); dispatch(tr4.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; }; var selectNodeForward = (state, dispatch, view) => { let { $head, empty: empty4 } = state.selection, $cut = $head; if (!empty4) return false; if ($head.parent.isTextblock) { if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size) return false; $cut = findCutAfter($head); } let node2 = $cut && $cut.nodeAfter; if (!node2 || !NodeSelection.isSelectable(node2)) 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 i3 = $pos.depth - 1; i3 >= 0; i3--) { let parent = $pos.node(i3); if ($pos.index(i3) + 1 < parent.childCount) return $pos.doc.resolve($pos.after(i3 + 1)); if (parent.type.spec.isolating) break; } return null; } var joinUp = (state, dispatch) => { let sel = state.selection, nodeSel = sel instanceof NodeSelection, point5; if (nodeSel) { if (sel.node.isTextblock || !canJoin(state.doc, sel.from)) return false; point5 = sel.from; } else { point5 = joinPoint(state.doc, sel.from, -1); if (point5 == null) return false; } if (dispatch) { let tr4 = state.tr.join(point5); if (nodeSel) tr4.setSelection(NodeSelection.create(tr4.doc, point5 - state.doc.resolve(point5).nodeBefore.nodeSize)); dispatch(tr4.scrollIntoView()); } return true; }; var joinDown = (state, dispatch) => { let sel = state.selection, point5; if (sel instanceof NodeSelection) { if (sel.node.isTextblock || !canJoin(state.doc, sel.to)) return false; point5 = sel.to; } else { point5 = joinPoint(state.doc, sel.to, 1); if (point5 == null) return false; } if (dispatch) dispatch(state.tr.join(point5).scrollIntoView()); return true; }; var lift2 = (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; }; var 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(match2) { for (let i3 = 0; i3 < match2.edgeCount; i3++) { let { type } = match2.edge(i3); if (type.isTextblock && !type.hasRequiredAttrs()) return type; } return null; } var 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(above.contentMatchAt(after)); if (!type || !above.canReplaceWith(after, after, type)) return false; if (dispatch) { let pos = $head.after(), tr4 = state.tr.replaceWith(pos, pos, type.createAndFill()); tr4.setSelection(Selection.near(tr4.doc.resolve(pos), 1)); dispatch(tr4.scrollIntoView()); } return true; }; var 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($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 tr4 = state.tr.insert(side, type.createAndFill()); tr4.setSelection(TextSelection.create(tr4.doc, side + 1)); dispatch(tr4.scrollIntoView()); } return true; }; var 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) => { let { $from, $to } = state.selection; if (state.selection instanceof NodeSelection && state.selection.node.isBlock) { if (!$from.parentOffset || !canSplit(state.doc, $from.pos)) return false; if (dispatch) dispatch(state.tr.split($from.pos).scrollIntoView()); return true; } if (!$from.depth) return false; let types2 = []; let splitDepth, deflt, atEnd = false, atStart = false; for (let d = $from.depth; ; d--) { let node2 = $from.node(d); if (node2.isBlock) { atEnd = $from.end(d) == $from.pos + ($from.depth - d); atStart = $from.start(d) == $from.pos - ($from.depth - d); deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1))); let splitType = splitNode && splitNode($to.parent, atEnd, $from); types2.unshift(splitType || (atEnd && deflt ? { type: deflt } : null)); splitDepth = d; break; } else { if (d == 1) return false; types2.unshift(null); } } let tr4 = state.tr; if (state.selection instanceof TextSelection || state.selection instanceof AllSelection) tr4.deleteSelection(); let splitPos = tr4.mapping.map($from.pos); let can = canSplit(tr4.doc, splitPos, types2.length, types2); if (!can) { types2[0] = deflt ? { type: deflt } : null; can = canSplit(tr4.doc, splitPos, types2.length, types2); } if (!can) return false; tr4.split(splitPos, types2.length, types2); if (!atEnd && atStart && $from.node(splitDepth).type != deflt) { let first2 = tr4.mapping.map($from.before(splitDepth)), $first = tr4.doc.resolve(first2); if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt)) tr4.setNodeMarkup(tr4.mapping.map($from.before(splitDepth)), deflt); } if (dispatch) dispatch(tr4.scrollIntoView()); return true; }; } var splitBlock = splitBlockAs(); var selectParentNode = (state, dispatch) => { let { $from, to: to2 } = state.selection, pos; let same = $from.sharedDepth(to2); if (same == 0) return false; pos = $from.before(same); if (dispatch) dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos))); return true; }; var selectAll = (state, dispatch) => { if (dispatch) dispatch(state.tr.setSelection(new AllSelection(state.doc))); return true; }; function joinMaybeClear(state, $pos, dispatch) { let before = $pos.nodeBefore, after = $pos.nodeAfter, index4 = $pos.index(); if (!before || !after || !before.type.compatibleContent(after.type)) return false; if (!before.content.size && $pos.parent.canReplace(index4 - 1, index4)) { if (dispatch) dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView()); return true; } if (!$pos.parent.canReplace(index4, index4 + 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, match2; 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 = (match2 = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match2.matchType(conn[0] || after.type).validEnd) { if (dispatch) { let end = $cut.pos + after.nodeSize, wrap5 = Fragment.empty; for (let i3 = conn.length - 1; i3 >= 0; i3--) wrap5 = Fragment.from(conn[i3].create(null, wrap5)); wrap5 = Fragment.from(before.copy(wrap5)); let tr4 = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap5, 1, 0), conn.length, true)); let $joinAt = tr4.doc.resolve(end + 2 * conn.length); if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr4.doc, $joinAt.pos)) tr4.join($joinAt.pos); dispatch(tr4.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 at2 = before, wrap5 = []; for (; ; ) { wrap5.push(at2); if (at2.isTextblock) break; at2 = at2.lastChild; } let afterText = after, afterDepth = 1; for (; !afterText.isTextblock; afterText = afterText.firstChild) afterDepth++; if (at2.canReplace(at2.childCount, at2.childCount, afterText.content)) { if (dispatch) { let end = Fragment.empty; for (let i3 = wrap5.length - 1; i3 >= 0; i3--) end = Fragment.from(wrap5[i3].copy(end)); let tr4 = state.tr.step(new ReplaceAroundStep($cut.pos - wrap5.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap5.length, 0), 0, true)); dispatch(tr4.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; }; } var selectTextblockStart = selectTextblockSide(-1); var 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 setBlockType2(nodeType, attrs = null) { return function(state, dispatch) { let applicable = false; for (let i3 = 0; i3 < state.selection.ranges.length && !applicable; i3++) { let { $from: { pos: from4 }, $to: { pos: to2 } } = state.selection.ranges[i3]; state.doc.nodesBetween(from4, to2, (node2, pos) => { if (applicable) return false; if (!node2.isTextblock || node2.hasMarkup(nodeType, attrs)) return; if (node2.type == nodeType) { applicable = true; } else { let $pos = state.doc.resolve(pos), index4 = $pos.index(); applicable = $pos.parent.canReplaceWith(index4, index4 + 1, nodeType); } }); } if (!applicable) return false; if (dispatch) { let tr4 = state.tr; for (let i3 = 0; i3 < state.selection.ranges.length; i3++) { let { $from: { pos: from4 }, $to: { pos: to2 } } = state.selection.ranges[i3]; tr4.setBlockType(from4, to2, nodeType, attrs); } dispatch(tr4.scrollIntoView()); } return true; }; } function chainCommands(...commands) { return function(state, dispatch, view) { for (let i3 = 0; i3 < commands.length; i3++) if (commands[i3](state, dispatch, view)) return true; return false; }; } var backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward); var del = chainCommands(deleteSelection, joinForward, selectNodeForward); var pcBaseKeymap = { "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock), "Mod-Enter": exitCode, "Backspace": backspace, "Mod-Backspace": backspace, "Shift-Backspace": backspace, "Delete": del, "Mod-Delete": del, "Mod-a": selectAll }; var macBaseKeymap = { "Ctrl-h": pcBaseKeymap["Backspace"], "Alt-Backspace": pcBaseKeymap["Mod-Backspace"], "Ctrl-d": pcBaseKeymap["Delete"], "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"], "Alt-Delete": pcBaseKeymap["Mod-Delete"], "Alt-d": pcBaseKeymap["Mod-Delete"], "Ctrl-a": selectTextblockStart, "Ctrl-e": selectTextblockEnd }; for (let key2 in pcBaseKeymap) macBaseKeymap[key2] = pcBaseKeymap[key2]; var mac2 = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false; // ../../node_modules/.pnpm/prosemirror-schema-list@1.5.1/node_modules/prosemirror-schema-list/dist/index.js function wrapInList(listType, attrs = null) { return function(state, dispatch) { let { $from, $to } = state.selection; let range = $from.blockRange($to); if (!range) return false; let tr4 = dispatch ? state.tr : null; if (!wrapRangeInList(tr4, range, listType, attrs)) return false; if (dispatch) dispatch(tr4.scrollIntoView()); return true; }; } function wrapRangeInList(tr4, range, listType, attrs = null) { let doJoin = false, outerRange = range, doc4 = 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 = doc4.resolve(range.start - 2); outerRange = new NodeRange($insert, $insert, range.depth); if (range.endIndex < range.parent.childCount) range = new NodeRange(range.$from, doc4.resolve(range.$to.end(range.depth)), range.depth); doJoin = true; } let wrap5 = findWrapping(outerRange, listType, attrs, range); if (!wrap5) return false; if (tr4) doWrapInList(tr4, range, wrap5, doJoin, listType); return true; } function doWrapInList(tr4, range, wrappers, joinBefore, listType) { let content5 = Fragment.empty; for (let i3 = wrappers.length - 1; i3 >= 0; i3--) content5 = Fragment.from(wrappers[i3].type.create(wrappers[i3].attrs, content5)); tr4.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content5, 0, 0), wrappers.length, true)); let found2 = 0; for (let i3 = 0; i3 < wrappers.length; i3++) if (wrappers[i3].type == listType) found2 = i3 + 1; let splitDepth = wrappers.length - found2; let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent; for (let i3 = range.startIndex, e2 = range.endIndex, first2 = true; i3 < e2; i3++, first2 = false) { if (!first2 && canSplit(tr4.doc, splitPos, splitDepth)) { tr4.split(splitPos, splitDepth); splitPos += 2 * splitDepth; } splitPos += parent.child(i3).nodeSize; } return tr4; } function liftListItem(itemType) { return function(state, dispatch) { let { $from, $to } = state.selection; let range = $from.blockRange($to, (node2) => node2.childCount > 0 && node2.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 tr4 = state.tr, end = range.end, endOfList = range.$to.end(range.depth); if (end < endOfList) { tr4.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(tr4.doc.resolve(range.$from.pos), tr4.doc.resolve(endOfList), range.depth); } const target = liftTarget(range); if (target == null) return false; tr4.lift(range, target); let $after = tr4.doc.resolve(tr4.mapping.map(end, -1) - 1); if (canJoin(tr4.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type) tr4.join($after.pos); dispatch(tr4.scrollIntoView()); return true; } function liftOutOfList(state, dispatch, range) { let tr4 = state.tr, list7 = range.parent; for (let pos = range.end, i3 = range.endIndex - 1, e2 = range.startIndex; i3 > e2; i3--) { pos -= list7.child(i3).nodeSize; tr4.delete(pos - 1, pos + 1); } let $start = tr4.doc.resolve(range.start), item = $start.nodeAfter; if (tr4.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize) return false; let atStart = range.startIndex == 0, atEnd = range.endIndex == list7.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(list7)))) return false; let start = $start.pos, end = start + item.nodeSize; tr4.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list7.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list7.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1)); dispatch(tr4.scrollIntoView()); return true; } function sinkListItem(itemType) { return function(state, dispatch) { let { $from, $to } = state.selection; let range = $from.blockRange($to, (node2) => node2.childCount > 0 && node2.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; }; } // ../../node_modules/.pnpm/w3c-keyname@2.2.8/node_modules/w3c-keyname/index.js 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 mac3 = typeof navigator != "undefined" && /Mac/.test(navigator.platform); var ie2 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); for (i3 = 0; i3 < 10; i3++) base[48 + i3] = base[96 + i3] = String(i3); var i3; for (i3 = 1; i3 <= 24; i3++) base[i3 + 111] = "F" + i3; var i3; for (i3 = 65; i3 <= 90; i3++) { base[i3] = String.fromCharCode(i3 + 32); shift[i3] = String.fromCharCode(i3); } var i3; for (code5 in base) if (!shift.hasOwnProperty(code5)) shift[code5] = base[code5]; var code5; function keyName(event) { var ignoreKey = mac3 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie2 && 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; } // ../../node_modules/.pnpm/prosemirror-keymap@1.2.3/node_modules/prosemirror-keymap/dist/index.js var mac4 = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform); var windows2 = typeof navigator != "undefined" && /Win/.test(navigator.platform); function normalizeKeyName(name) { let parts = name.split(/-(?!$)/), result = parts[parts.length - 1]; if (result == "Space") result = " "; let alt, ctrl, shift5, meta2; for (let i3 = 0; i3 < parts.length - 1; i3++) { let mod = parts[i3]; if (/^(cmd|meta|m)$/i.test(mod)) meta2 = 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)) shift5 = true; else if (/^mod$/i.test(mod)) { if (mac4) meta2 = true; else ctrl = true; } else throw new Error("Unrecognized modifier name: " + mod); } if (alt) result = "Alt-" + result; if (ctrl) result = "Ctrl-" + result; if (meta2) result = "Meta-" + result; if (shift5) result = "Shift-" + result; return result; } function normalize(map7) { let copy3 = /* @__PURE__ */ Object.create(null); for (let prop in map7) copy3[normalizeKeyName(prop)] = map7[prop]; return copy3; } function modifiers(name, event, shift5 = true) { if (event.altKey) name = "Alt-" + name; if (event.ctrlKey) name = "Ctrl-" + name; if (event.metaKey) name = "Meta-" + name; if (shift5 && event.shiftKey) name = "Shift-" + name; return name; } function keymap(bindings) { return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } }); } function keydownHandler(bindings) { let map7 = normalize(bindings); return function(view, event) { let name = keyName(event), baseName, direct = map7[modifiers(name, event)]; if (direct && direct(view.state, view.dispatch, view)) return true; if (name.length == 1 && name != " ") { if (event.shiftKey) { let noShift = map7[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 !(windows2 && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name) { let fromCode = map7[modifiers(baseName, event)]; if (fromCode && fromCode(view.state, view.dispatch, view)) return true; } } return false; }; } // ../../node_modules/.pnpm/@tiptap+core@3.14.0_@tiptap+pm@3.14.0/node_modules/@tiptap/core/dist/index.js var __defProp = Object.defineProperty; var __export2 = (target, all9) => { for (var name in all9) __defProp(target, name, { get: all9[name], enumerable: true }); }; function createChainableState(config) { const { state, transaction } = config; let { selection } = transaction; let { doc: doc4 } = 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 doc4; }, get tr() { selection = transaction.selection; doc4 = transaction.doc; storedMarks = transaction.storedMarks; return transaction; } }; } var CommandManager = class { 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: tr4 } = state; const props = this.buildProps(tr4); return Object.fromEntries( Object.entries(rawCommands).map(([name, command2]) => { const method = (...args2) => { const callback = command2(...args2)(props); if (!tr4.getMeta("preventDispatch") && !this.hasCustomState) { view.dispatch(tr4); } 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 tr4 = startTr || state.tr; const run32 = () => { if (!hasStartTransaction && shouldDispatch && !tr4.getMeta("preventDispatch") && !this.hasCustomState) { view.dispatch(tr4); } return callbacks.every((callback) => callback === true); }; const chain = { ...Object.fromEntries( Object.entries(rawCommands).map(([name, command2]) => { const chainedCommand = (...args2) => { const props = this.buildProps(tr4, shouldDispatch); const callback = command2(...args2)(props); callbacks.push(callback); return chain; }; return [name, chainedCommand]; }) ), run: run32 }; return chain; } createCan(startTr) { const { rawCommands, state } = this; const dispatch = false; const tr4 = startTr || state.tr; const props = this.buildProps(tr4, dispatch); const formattedCommands = Object.fromEntries( Object.entries(rawCommands).map(([name, command2]) => { return [name, (...args2) => command2(...args2)({ ...props, dispatch: void 0 })]; }) ); return { ...formattedCommands, chain: () => this.createChain(tr4, dispatch) }; } buildProps(tr4, shouldDispatch = true) { const { rawCommands, editor, state } = this; const { view } = editor; const props = { tr: tr4, editor, view, state: createChainableState({ state, transaction: tr4 }), dispatch: shouldDispatch ? () => void 0 : void 0, chain: () => this.createChain(tr4, shouldDispatch), can: () => this.createCan(tr4), get commands() { return Object.fromEntries( Object.entries(rawCommands).map(([name, command2]) => { return [name, (...args2) => command2(...args2)(props)]; }) ); } }; return props; } }; var commands_exports = {}; __export2(commands_exports, { blur: () => blur, clearContent: () => clearContent, clearNodes: () => clearNodes, command: () => command, createParagraphNear: () => createParagraphNear2, cut: () => cut, deleteCurrentNode: () => deleteCurrentNode, deleteNode: () => deleteNode, deleteRange: () => deleteRange2, deleteSelection: () => deleteSelection2, enter: () => enter, exitCode: () => exitCode2, extendMarkRange: () => extendMarkRange, first: () => first, focus: () => focus, forEach: () => forEach3, insertContent: () => insertContent, insertContentAt: () => insertContentAt, joinBackward: () => joinBackward2, joinDown: () => joinDown2, joinForward: () => joinForward2, joinItemBackward: () => joinItemBackward, joinItemForward: () => joinItemForward, joinTextblockBackward: () => joinTextblockBackward2, joinTextblockForward: () => joinTextblockForward2, joinUp: () => joinUp2, keyboardShortcut: () => keyboardShortcut, lift: () => lift3, liftEmptyBlock: () => liftEmptyBlock2, liftListItem: () => liftListItem2, newlineInCode: () => newlineInCode2, resetAttributes: () => resetAttributes, scrollIntoView: () => scrollIntoView, selectAll: () => selectAll2, selectNodeBackward: () => selectNodeBackward2, selectNodeForward: () => selectNodeForward2, selectParentNode: () => selectParentNode2, selectTextblockEnd: () => selectTextblockEnd2, selectTextblockStart: () => selectTextblockStart2, setContent: () => setContent, setMark: () => setMark, setMeta: () => setMeta2, setNode: () => setNode, setNodeSelection: () => setNodeSelection, setTextDirection: () => setTextDirection, setTextSelection: () => setTextSelection, sinkListItem: () => sinkListItem2, splitBlock: () => splitBlock2, splitListItem: () => splitListItem, toggleList: () => toggleList, toggleMark: () => toggleMark, toggleNode: () => toggleNode, toggleWrap: () => toggleWrap, undoInputRule: () => undoInputRule, unsetAllMarks: () => unsetAllMarks, unsetMark: () => unsetMark, unsetTextDirection: () => unsetTextDirection, updateAttributes: () => updateAttributes, wrapIn: () => wrapIn2, wrapInList: () => wrapInList2 }); var blur = () => ({ editor, view }) => { requestAnimationFrame(() => { var _a2; if (!editor.isDestroyed) { ; view.dom.blur(); (_a2 = window == null ? void 0 : window.getSelection()) == null ? void 0 : _a2.removeAllRanges(); } }); return true; }; var clearContent = (emitUpdate = true) => ({ commands }) => { return commands.setContent("", { emitUpdate }); }; var clearNodes = () => ({ state, tr: tr4, dispatch }) => { const { selection } = tr4; const { ranges } = selection; if (!dispatch) { return true; } ranges.forEach(({ $from, $to }) => { state.doc.nodesBetween($from.pos, $to.pos, (node2, pos) => { if (node2.type.isText) { return; } const { doc: doc4, mapping } = tr4; const $mappedFrom = doc4.resolve(mapping.map(pos)); const $mappedTo = doc4.resolve(mapping.map(pos + node2.nodeSize)); const nodeRange = $mappedFrom.blockRange($mappedTo); if (!nodeRange) { return; } const targetLiftDepth = liftTarget(nodeRange); if (node2.type.isTextblock) { const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index()); tr4.setNodeMarkup(nodeRange.start, defaultType); } if (targetLiftDepth || targetLiftDepth === 0) { tr4.lift(nodeRange, targetLiftDepth); } }); }); return true; }; var command = (fn4) => (props) => { return fn4(props); }; var createParagraphNear2 = () => ({ state, dispatch }) => { return createParagraphNear(state, dispatch); }; var cut = (originRange, targetPos) => ({ editor, tr: tr4 }) => { const { state } = editor; const contentSlice = state.doc.slice(originRange.from, originRange.to); tr4.deleteRange(originRange.from, originRange.to); const newPos = tr4.mapping.map(targetPos); tr4.insert(newPos, contentSlice.content); tr4.setSelection(new TextSelection(tr4.doc.resolve(Math.max(newPos - 1, 0)))); return true; }; var deleteCurrentNode = () => ({ tr: tr4, dispatch }) => { const { selection } = tr4; const currentNode = selection.$anchor.node(); if (currentNode.content.size > 0) { return false; } const $pos = tr4.selection.$anchor; for (let depth = $pos.depth; depth > 0; depth -= 1) { const node2 = $pos.node(depth); if (node2.type === currentNode.type) { if (dispatch) { const from4 = $pos.before(depth); const to2 = $pos.after(depth); tr4.delete(from4, to2).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; } var deleteNode = (typeOrName) => ({ tr: tr4, state, dispatch }) => { const type = getNodeType(typeOrName, state.schema); const $pos = tr4.selection.$anchor; for (let depth = $pos.depth; depth > 0; depth -= 1) { const node2 = $pos.node(depth); if (node2.type === type) { if (dispatch) { const from4 = $pos.before(depth); const to2 = $pos.after(depth); tr4.delete(from4, to2).scrollIntoView(); } return true; } } return false; }; var deleteRange2 = (range) => ({ tr: tr4, dispatch }) => { const { from: from4, to: to2 } = range; if (dispatch) { tr4.delete(from4, to2); } return true; }; var deleteSelection2 = () => ({ state, dispatch }) => { return deleteSelection(state, dispatch); }; var enter = () => ({ commands }) => { return commands.keyboardShortcut("Enter"); }; var exitCode2 = () => ({ state, dispatch }) => { return exitCode(state, dispatch); }; function isRegExp(value) { return Object.prototype.toString.call(value) === "[object RegExp]"; } function objectIncludes(object1, object2, options2 = { strict: true }) { const keys5 = Object.keys(object2); if (!keys5.length) { return true; } return keys5.every((key2) => { if (options2.strict) { return object2[key2] === object1[key2]; } if (isRegExp(object2[key2])) { return object2[key2].test(object1[key2]); } return object2[key2] === object1[key2]; }); } function findMarkInSet(marks, type, attributes = {}) { return marks.find((item) => { return item.type === type && objectIncludes( // Only check equality for the attributes that are provided Object.fromEntries(Object.keys(attributes).map((k3) => [k3, item.attrs[k3]])), attributes ); }); } function isMarkInSet(marks, type, attributes = {}) { return !!findMarkInSet(marks, type, attributes); } function getMarkRange($pos, type, attributes) { var _a2; if (!$pos || !type) { return; } let start = $pos.parent.childAfter($pos.parentOffset); if (!start.node || !start.node.marks.some((mark22) => mark22.type === type)) { start = $pos.parent.childBefore($pos.parentOffset); } if (!start.node || !start.node.marks.some((mark22) => mark22.type === type)) { return; } attributes = attributes || ((_a2 = start.node.marks[0]) == null ? void 0 : _a2.attrs); const mark2 = findMarkInSet([...start.node.marks], type, attributes); if (!mark2) { 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; } var extendMarkRange = (typeOrName, attributes = {}) => ({ tr: tr4, state, dispatch }) => { const type = getMarkType(typeOrName, state.schema); const { doc: doc4, selection } = tr4; const { $from, from: from4, to: to2 } = selection; if (dispatch) { const range = getMarkRange($from, type, attributes); if (range && range.from <= from4 && range.to >= to2) { const newSelection = TextSelection.create(doc4, range.from, range.to); tr4.setSelection(newSelection); } } return true; }; var first = (commands) => (props) => { const items = typeof commands === "function" ? commands(props) : commands; for (let i3 = 0; i3 < items.length; i3 += 1) { if (items[i3](props)) { return true; } } return false; }; function isTextSelection(value) { return value instanceof TextSelection; } function minMax(value = 0, min3 = 0, max3 = 0) { return Math.min(Math.max(value, min3), max3); } function resolveFocusPosition(doc4, position4 = null) { if (!position4) { return null; } const selectionAtStart = Selection.atStart(doc4); const selectionAtEnd = Selection.atEnd(doc4); if (position4 === "start" || position4 === true) { return selectionAtStart; } if (position4 === "end") { return selectionAtEnd; } const minPos = selectionAtStart.from; const maxPos = selectionAtEnd.to; if (position4 === "all") { return TextSelection.create(doc4, minMax(0, minPos, maxPos), minMax(doc4.content.size, minPos, maxPos)); } return TextSelection.create(doc4, minMax(position4, minPos, maxPos), minMax(position4, minPos, maxPos)); } function isAndroid() { return navigator.platform === "Android" || /android/i.test(navigator.userAgent); } function isiOS() { return ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"].includes(navigator.platform) || // iPad on iOS 13 detection navigator.userAgent.includes("Mac") && "ontouchend" in document; } var focus = (position4 = null, options2 = {}) => ({ editor, view, tr: tr4, dispatch }) => { options2 = { scrollIntoView: true, ...options2 }; const delayedFocus = () => { if (isiOS() || isAndroid()) { ; view.dom.focus(); } requestAnimationFrame(() => { if (!editor.isDestroyed) { view.focus(); if (options2 == null ? void 0 : options2.scrollIntoView) { editor.commands.scrollIntoView(); } } }); }; if (view.hasFocus() && position4 === null || position4 === false) { return true; } if (dispatch && position4 === null && !isTextSelection(editor.state.selection)) { delayedFocus(); return true; } const selection = resolveFocusPosition(tr4.doc, position4) || editor.state.selection; const isSameSelection = editor.state.selection.eq(selection); if (dispatch) { if (!isSameSelection) { tr4.setSelection(selection); } if (isSameSelection && tr4.storedMarks) { tr4.setStoredMarks(tr4.storedMarks); } delayedFocus(); } return true; }; var forEach3 = (items, fn4) => (props) => { return items.every((item, index4) => fn4(item, { ...props, index: index4 })); }; var insertContent = (value, options2) => ({ tr: tr4, commands }) => { return commands.insertContentAt({ from: tr4.selection.from, to: tr4.selection.to }, value, options2); }; var removeWhitespaces = (node2) => { const children = node2.childNodes; for (let i3 = children.length - 1; i3 >= 0; i3 -= 1) { const child = children[i3]; if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) { node2.removeChild(child); } else if (child.nodeType === 1) { removeWhitespaces(child); } } return node2; }; 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 html7 = new window.DOMParser().parseFromString(wrappedValue, "text/html").body; return removeWhitespaces(html7); } function createNodeFromContent(content5, schema, options2) { if (content5 instanceof Node2 || content5 instanceof Fragment) { return content5; } options2 = { slice: true, parseOptions: {}, ...options2 }; const isJSONContent = typeof content5 === "object" && content5 !== null; const isTextContent = typeof content5 === "string"; if (isJSONContent) { try { const isArrayContent = Array.isArray(content5) && content5.length > 0; if (isArrayContent) { return Fragment.fromArray(content5.map((item) => schema.nodeFromJSON(item))); } const node2 = schema.nodeFromJSON(content5); if (options2.errorOnInvalidContent) { node2.check(); } return node2; } catch (error2) { if (options2.errorOnInvalidContent) { throw new Error("[tiptap error]: Invalid JSON content", { cause: error2 }); } console.warn("[tiptap warn]: Invalid content.", "Passed value:", content5, "Error:", error2); return createNodeFromContent("", schema, options2); } } if (isTextContent) { if (options2.errorOnInvalidContent) { let hasInvalidContent = false; let invalidContent = ""; const contentCheckSchema = new Schema({ topNode: schema.spec.topNode, marks: schema.spec.marks, // Prosemirror's schemas are executed such that: the last to execute, matches last // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle nodes: schema.spec.nodes.append({ __tiptap__private__unknown__catch__all__node: { content: "inline*", group: "block", parseDOM: [ { tag: "*", getAttrs: (e2) => { hasInvalidContent = true; invalidContent = typeof e2 === "string" ? e2 : e2.outerHTML; return null; } } ] } }) }); if (options2.slice) { DOMParser2.fromSchema(contentCheckSchema).parseSlice(elementFromString(content5), options2.parseOptions); } else { DOMParser2.fromSchema(contentCheckSchema).parse(elementFromString(content5), options2.parseOptions); } if (options2.errorOnInvalidContent && hasInvalidContent) { throw new Error("[tiptap error]: Invalid HTML content", { cause: new Error(`Invalid element found: ${invalidContent}`) }); } } const parser = DOMParser2.fromSchema(schema); if (options2.slice) { return parser.parseSlice(elementFromString(content5), options2.parseOptions).content; } return parser.parse(elementFromString(content5), options2.parseOptions); } return createNodeFromContent("", schema, options2); } function selectionToInsertionEnd2(tr4, startLen, bias) { const last2 = tr4.steps.length - 1; if (last2 < startLen) { return; } const step = tr4.steps[last2]; if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) { return; } const map7 = tr4.mapping.maps[last2]; let end = 0; map7.forEach((_from, _to, _newFrom, newTo) => { if (end === 0) { end = newTo; } }); tr4.setSelection(Selection.near(tr4.doc.resolve(end), bias)); } var isFragment = (nodeOrFragment) => { return !("type" in nodeOrFragment); }; var insertContentAt = (position4, value, options2) => ({ tr: tr4, dispatch, editor }) => { var _a2; if (dispatch) { options2 = { parseOptions: editor.options.parseOptions, updateSelection: true, applyInputRules: false, applyPasteRules: false, ...options2 }; let content5; 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", ...options2.parseOptions }; if (!options2.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) { try { createNodeFromContent(value, editor.schema, { parseOptions, errorOnInvalidContent: true }); } catch (e2) { emitContentError(e2); } } try { content5 = createNodeFromContent(value, editor.schema, { parseOptions, errorOnInvalidContent: (_a2 = options2.errorOnInvalidContent) != null ? _a2 : editor.options.enableContentCheck }); } catch (e2) { emitContentError(e2); return false; } let { from: from4, to: to2 } = typeof position4 === "number" ? { from: position4, to: position4 } : { from: position4.from, to: position4.to }; let isOnlyTextContent = true; let isOnlyBlockContent = true; const nodes = isFragment(content5) ? content5 : [content5]; nodes.forEach((node2) => { node2.check(); isOnlyTextContent = isOnlyTextContent ? node2.isText && node2.marks.length === 0 : false; isOnlyBlockContent = isOnlyBlockContent ? node2.isBlock : false; }); if (from4 === to2 && isOnlyBlockContent) { const { parent } = tr4.doc.resolve(from4); const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount; if (isEmptyTextBlock) { from4 -= 1; to2 += 1; } } let newContent; if (isOnlyTextContent) { if (Array.isArray(value)) { newContent = value.map((v8) => v8.text || "").join(""); } else if (value instanceof Fragment) { let text10 = ""; value.forEach((node2) => { if (node2.text) { text10 += node2.text; } }); newContent = text10; } else if (typeof value === "object" && !!value && !!value.text) { newContent = value.text; } else { newContent = value; } tr4.insertText(newContent, from4, to2); } else { newContent = content5; const $from = tr4.doc.resolve(from4); const $fromNode = $from.node(); const fromSelectionAtStart = $from.parentOffset === 0; const isTextSelection2 = $fromNode.isText || $fromNode.isTextblock; const hasContent2 = $fromNode.content.size > 0; if (fromSelectionAtStart && isTextSelection2 && hasContent2) { from4 = Math.max(0, from4 - 1); } tr4.replaceWith(from4, to2, newContent); } if (options2.updateSelection) { selectionToInsertionEnd2(tr4, tr4.steps.length - 1, -1); } if (options2.applyInputRules) { tr4.setMeta("applyInputRules", { from: from4, text: newContent }); } if (options2.applyPasteRules) { tr4.setMeta("applyPasteRules", { from: from4, text: newContent }); } } return true; }; var joinUp2 = () => ({ state, dispatch }) => { return joinUp(state, dispatch); }; var joinDown2 = () => ({ state, dispatch }) => { return joinDown(state, dispatch); }; var joinBackward2 = () => ({ state, dispatch }) => { return joinBackward(state, dispatch); }; var joinForward2 = () => ({ state, dispatch }) => { return joinForward(state, dispatch); }; var joinItemBackward = () => ({ state, dispatch, tr: tr4 }) => { try { const point5 = joinPoint(state.doc, state.selection.$from.pos, -1); if (point5 === null || point5 === void 0) { return false; } tr4.join(point5, 2); if (dispatch) { dispatch(tr4); } return true; } catch { return false; } }; var joinItemForward = () => ({ state, dispatch, tr: tr4 }) => { try { const point5 = joinPoint(state.doc, state.selection.$from.pos, 1); if (point5 === null || point5 === void 0) { return false; } tr4.join(point5, 2); if (dispatch) { dispatch(tr4); } return true; } catch { return false; } }; var joinTextblockBackward2 = () => ({ state, dispatch }) => { return joinTextblockBackward(state, dispatch); }; var joinTextblockForward2 = () => ({ state, dispatch }) => { return joinTextblockForward(state, dispatch); }; function isMacOS() { return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false; } function normalizeKeyName2(name) { const parts = name.split(/-(?!$)/); let result = parts[parts.length - 1]; if (result === "Space") { result = " "; } let alt; let ctrl; let shift5; let meta2; for (let i3 = 0; i3 < parts.length - 1; i3 += 1) { const mod = parts[i3]; if (/^(cmd|meta|m)$/i.test(mod)) { meta2 = 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)) { shift5 = true; } else if (/^mod$/i.test(mod)) { if (isiOS() || isMacOS()) { meta2 = true; } else { ctrl = true; } } else { throw new Error(`Unrecognized modifier name: ${mod}`); } } if (alt) { result = `Alt-${result}`; } if (ctrl) { result = `Ctrl-${result}`; } if (meta2) { result = `Meta-${result}`; } if (shift5) { result = `Shift-${result}`; } return result; } var keyboardShortcut = (name) => ({ editor, view, tr: tr4, dispatch }) => { const keys5 = normalizeKeyName2(name).split(/-(?!$)/); const key2 = keys5.find((item) => !["Alt", "Ctrl", "Meta", "Shift"].includes(item)); const event = new KeyboardEvent("keydown", { key: key2 === "Space" ? " " : key2, altKey: keys5.includes("Alt"), ctrlKey: keys5.includes("Ctrl"), metaKey: keys5.includes("Meta"), shiftKey: keys5.includes("Shift"), bubbles: true, cancelable: true }); const capturedTransaction = editor.captureTransaction(() => { view.someProp("handleKeyDown", (f6) => f6(view, event)); }); capturedTransaction == null ? void 0 : capturedTransaction.steps.forEach((step) => { const newStep = step.map(tr4.mapping); if (newStep && dispatch) { tr4.maybeStep(newStep); } }); return true; }; function isNodeActive(state, typeOrName, attributes = {}) { const { from: from4, to: to2, empty: empty4 } = state.selection; const type = typeOrName ? getNodeType(typeOrName, state.schema) : null; const nodeRanges = []; state.doc.nodesBetween(from4, to2, (node2, pos) => { if (node2.isText) { return; } const relativeFrom = Math.max(from4, pos); const relativeTo = Math.min(to2, pos + node2.nodeSize); nodeRanges.push({ node: node2, from: relativeFrom, to: relativeTo }); }); const selectionRange = to2 - from4; 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 (empty4) { return !!matchedNodeRanges.length; } const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0); return range >= selectionRange; } var lift3 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { const type = getNodeType(typeOrName, state.schema); const isActive2 = isNodeActive(state, type, attributes); if (!isActive2) { return false; } return lift2(state, dispatch); }; var liftEmptyBlock2 = () => ({ state, dispatch }) => { return liftEmptyBlock(state, dispatch); }; var liftListItem2 = (typeOrName) => ({ state, dispatch }) => { const type = getNodeType(typeOrName, state.schema); return liftListItem(type)(state, dispatch); }; var newlineInCode2 = () => ({ 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; }, {}); } var resetAttributes = (typeOrName, attributes) => ({ tr: tr4, 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; tr4.selection.ranges.forEach((range) => { state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node2, pos) => { if (nodeType && nodeType === node2.type) { canReset = true; if (dispatch) { tr4.setNodeMarkup(pos, void 0, deleteProps(node2.attrs, attributes)); } } if (markType && node2.marks.length) { node2.marks.forEach((mark2) => { if (markType === mark2.type) { canReset = true; if (dispatch) { tr4.addMark(pos, pos + node2.nodeSize, markType.create(deleteProps(mark2.attrs, attributes))); } } }); } }); }); return canReset; }; var scrollIntoView = () => ({ tr: tr4, dispatch }) => { if (dispatch) { tr4.scrollIntoView(); } return true; }; var selectAll2 = () => ({ tr: tr4, dispatch }) => { if (dispatch) { const selection = new AllSelection(tr4.doc); tr4.setSelection(selection); } return true; }; var selectNodeBackward2 = () => ({ state, dispatch }) => { return selectNodeBackward(state, dispatch); }; var selectNodeForward2 = () => ({ state, dispatch }) => { return selectNodeForward(state, dispatch); }; var selectParentNode2 = () => ({ state, dispatch }) => { return selectParentNode(state, dispatch); }; var selectTextblockEnd2 = () => ({ state, dispatch }) => { return selectTextblockEnd(state, dispatch); }; var selectTextblockStart2 = () => ({ state, dispatch }) => { return selectTextblockStart(state, dispatch); }; function createDocument(content5, schema, parseOptions = {}, options2 = {}) { return createNodeFromContent(content5, schema, { slice: false, parseOptions, errorOnInvalidContent: options2.errorOnInvalidContent }); } var setContent = (content5, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) => ({ editor, tr: tr4, dispatch, commands }) => { const { doc: doc4 } = tr4; if (parseOptions.preserveWhitespace !== "full") { const document22 = createDocument(content5, editor.schema, parseOptions, { errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck }); if (dispatch) { tr4.replaceWith(0, doc4.content.size, document22).setMeta("preventUpdate", !emitUpdate); } return true; } if (dispatch) { tr4.setMeta("preventUpdate", !emitUpdate); } return commands.insertContentAt({ from: 0, to: doc4.content.size }, content5, { parseOptions, errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck }); }; function getMarkAttributes(state, typeOrName) { const type = getMarkType(typeOrName, state.schema); const { from: from4, to: to2, empty: empty4 } = state.selection; const marks = []; if (empty4) { if (state.storedMarks) { marks.push(...state.storedMarks); } marks.push(...state.selection.$head.marks()); } else { state.doc.nodesBetween(from4, to2, (node2) => { marks.push(...node2.marks); }); } const mark2 = marks.find((markItem) => markItem.type.name === type.name); if (!mark2) { return {}; } return { ...mark2.attrs }; } function combineTransactionSteps(oldDoc, transactions) { const transform2 = new Transform(oldDoc); transactions.forEach((transaction) => { transaction.steps.forEach((step) => { transform2.step(step); }); }); return transform2; } function defaultBlockAt2(match2) { for (let i3 = 0; i3 < match2.edgeCount; i3 += 1) { const { type } = match2.edge(i3); if (type.isTextblock && !type.hasRequiredAttrs()) { return type; } } return null; } function findChildren(node2, predicate) { const nodesWithPos = []; node2.descendants((child, pos) => { if (predicate(child)) { nodesWithPos.push({ node: child, pos }); } }); return nodesWithPos; } function findChildrenInRange(node2, range, predicate) { const nodesWithPos = []; node2.nodesBetween(range.from, range.to, (child, pos) => { if (predicate(child)) { nodesWithPos.push({ node: child, pos }); } }); return nodesWithPos; } function findParentNodeClosestToPos($pos, predicate) { for (let i3 = $pos.depth; i3 > 0; i3 -= 1) { const node2 = $pos.node(i3); if (predicate(node2)) { return { pos: i3 > 0 ? $pos.before(i3) : 0, start: $pos.start(i3), depth: i3, node: node2 }; } } } function findParentNode(predicate) { return (selection) => findParentNodeClosestToPos(selection.$from, predicate); } function getExtensionField(extension2, field, context) { if (extension2.config[field] === void 0 && extension2.parent) { return getExtensionField(extension2.parent, field, context); } if (typeof extension2.config[field] === "function") { const value = extension2.config[field].bind({ ...context, parent: extension2.parent ? getExtensionField(extension2.parent, field, context) : null }); return value; } return extension2.config[field]; } function flattenExtensions(extensions) { return extensions.map((extension2) => { const context = { name: extension2.name, options: extension2.options, storage: extension2.storage }; const addExtensions = getExtensionField(extension2, "addExtensions", context); if (addExtensions) { return [extension2, ...flattenExtensions(addExtensions())]; } return extension2; }).flat(10); } function getHTMLFromFragment(fragment, schema) { const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment); const temporaryDocument = document.implementation.createHTMLDocument(); const container = temporaryDocument.createElement("div"); container.appendChild(documentFragment); return container.innerHTML; } 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) { const baseExtensions = extensions.filter((extension2) => extension2.type === "extension"); const nodeExtensions = extensions.filter((extension2) => extension2.type === "node"); const markExtensions = extensions.filter((extension2) => extension2.type === "mark"); return { baseExtensions, nodeExtensions, markExtensions }; } 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 }; extensions.forEach((extension2) => { const context = { name: extension2.name, options: extension2.options, storage: extension2.storage, extensions: nodeAndMarkExtensions }; const addGlobalAttributes = getExtensionField( extension2, "addGlobalAttributes", context ); if (!addGlobalAttributes) { return; } const globalAttributes = addGlobalAttributes(); globalAttributes.forEach((globalAttribute) => { globalAttribute.types.forEach((type) => { Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => { extensionAttributes.push({ type, name, attribute: { ...defaultAttribute, ...attribute } }); }); }); }); }); nodeAndMarkExtensions.forEach((extension2) => { const context = { name: extension2.name, options: extension2.options, storage: extension2.storage }; const addAttributes = getExtensionField( extension2, "addAttributes", context ); if (!addAttributes) { return; } const attributes = addAttributes(); Object.entries(attributes).forEach(([name, attribute]) => { const mergedAttr = { ...defaultAttribute, ...attribute }; if (typeof (mergedAttr == null ? void 0 : mergedAttr.default) === "function") { mergedAttr.default = mergedAttr.default(); } if ((mergedAttr == null ? void 0 : mergedAttr.isRequired) && (mergedAttr == null ? void 0 : mergedAttr.default) === void 0) { delete mergedAttr.default; } extensionAttributes.push({ type: extension2.name, name, attribute: mergedAttr }); }); }); return extensionAttributes; } function mergeAttributes(...objects) { return objects.filter((item) => !!item).reduce((items, item) => { const mergedAttributes = { ...items }; Object.entries(item).forEach(([key2, value]) => { const exists = mergedAttributes[key2]; if (!exists) { mergedAttributes[key2] = value; return; } if (key2 === "class") { const valueClasses = value ? String(value).split(" ") : []; const existingClasses = mergedAttributes[key2] ? mergedAttributes[key2].split(" ") : []; const insertClasses = valueClasses.filter((valueClass) => !existingClasses.includes(valueClass)); mergedAttributes[key2] = [...existingClasses, ...insertClasses].join(" "); } else if (key2 === "style") { const newStyles = value ? value.split(";").map((style22) => style22.trim()).filter(Boolean) : []; const existingStyles = mergedAttributes[key2] ? mergedAttributes[key2].split(";").map((style22) => style22.trim()).filter(Boolean) : []; const styleMap = /* @__PURE__ */ new Map(); existingStyles.forEach((style22) => { const [property, val] = style22.split(":").map((part) => part.trim()); styleMap.set(property, val); }); newStyles.forEach((style22) => { const [property, val] = style22.split(":").map((part) => part.trim()); styleMap.set(property, val); }); mergedAttributes[key2] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join("; "); } else { mergedAttributes[key2] = 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: (node2) => { const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node2) : parseRule.attrs; if (oldAttributes === false) { return false; } const newAttributes = extensionAttributes.reduce((items, item) => { const value = item.attribute.parseHTML ? item.attribute.parseHTML(node2) : fromString(node2.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( // @ts-ignore Object.entries(data).filter(([key2, value]) => { if (key2 === "attrs" && isEmptyObject(value)) { return false; } return value !== null && value !== void 0; }) ); } function buildAttributeSpec(extensionAttribute) { var _a2, _b; const spec = {}; if (!((_a2 = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _a2.isRequired) && "default" in ((extensionAttribute == null ? void 0 : extensionAttribute.attribute) || {})) { spec.default = extensionAttribute.attribute.default; } if (((_b = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _b.validate) !== void 0) { spec.validate = extensionAttribute.attribute.validate; } return [extensionAttribute.name, spec]; } function getSchemaByResolvedExtensions(extensions, editor) { var _a2; const allAttributes = getAttributesFromExtensions(extensions); const { nodeExtensions, markExtensions } = splitExtensions(extensions); const topNode = (_a2 = nodeExtensions.find((extension2) => getExtensionField(extension2, "topNode"))) == null ? void 0 : _a2.name; const nodes = Object.fromEntries( nodeExtensions.map((extension2) => { const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension2.name); const context = { name: extension2.name, options: extension2.options, storage: extension2.storage, editor }; const extraNodeFields = extensions.reduce((fields, e2) => { const extendNodeSchema = getExtensionField(e2, "extendNodeSchema", context); return { ...fields, ...extendNodeSchema ? extendNodeSchema(extension2) : {} }; }, {}); const schema = cleanUpSchemaItem({ ...extraNodeFields, content: callOrReturn(getExtensionField(extension2, "content", context)), marks: callOrReturn(getExtensionField(extension2, "marks", context)), group: callOrReturn(getExtensionField(extension2, "group", context)), inline: callOrReturn(getExtensionField(extension2, "inline", context)), atom: callOrReturn(getExtensionField(extension2, "atom", context)), selectable: callOrReturn(getExtensionField(extension2, "selectable", context)), draggable: callOrReturn(getExtensionField(extension2, "draggable", context)), code: callOrReturn(getExtensionField(extension2, "code", context)), whitespace: callOrReturn(getExtensionField(extension2, "whitespace", context)), linebreakReplacement: callOrReturn( getExtensionField(extension2, "linebreakReplacement", context) ), defining: callOrReturn(getExtensionField(extension2, "defining", context)), isolating: callOrReturn(getExtensionField(extension2, "isolating", context)), attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) }); const parseHTML = callOrReturn(getExtensionField(extension2, "parseHTML", context)); if (parseHTML) { schema.parseDOM = parseHTML.map( (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes) ); } const renderHTML = getExtensionField(extension2, "renderHTML", context); if (renderHTML) { schema.toDOM = (node2) => renderHTML({ node: node2, HTMLAttributes: getRenderedAttributes(node2, extensionAttributes) }); } const renderText = getExtensionField(extension2, "renderText", context); if (renderText) { schema.toText = renderText; } return [extension2.name, schema]; }) ); const marks = Object.fromEntries( markExtensions.map((extension2) => { const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension2.name); const context = { name: extension2.name, options: extension2.options, storage: extension2.storage, editor }; const extraMarkFields = extensions.reduce((fields, e2) => { const extendMarkSchema = getExtensionField(e2, "extendMarkSchema", context); return { ...fields, ...extendMarkSchema ? extendMarkSchema(extension2) : {} }; }, {}); const schema = cleanUpSchemaItem({ ...extraMarkFields, inclusive: callOrReturn(getExtensionField(extension2, "inclusive", context)), excludes: callOrReturn(getExtensionField(extension2, "excludes", context)), group: callOrReturn(getExtensionField(extension2, "group", context)), spanning: callOrReturn(getExtensionField(extension2, "spanning", context)), code: callOrReturn(getExtensionField(extension2, "code", context)), attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) }); const parseHTML = callOrReturn(getExtensionField(extension2, "parseHTML", context)); if (parseHTML) { schema.parseDOM = parseHTML.map( (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes) ); } const renderHTML = getExtensionField(extension2, "renderHTML", context); if (renderHTML) { schema.toDOM = (mark2) => renderHTML({ mark: mark2, HTMLAttributes: getRenderedAttributes(mark2, extensionAttributes) }); } return [extension2.name, schema]; }) ); return new Schema({ topNode, nodes, marks }); } function findDuplicates(items) { const filtered = items.filter((el2, index4) => items.indexOf(el2) !== index4); return Array.from(new Set(filtered)); } function sortExtensions(extensions) { const defaultPriority = 100; return extensions.sort((a3, b4) => { const priorityA = getExtensionField(a3, "priority") || defaultPriority; const priorityB = getExtensionField(b4, "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((extension2) => extension2.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 getSchema(extensions, editor) { const resolvedExtensions = resolveExtensions(extensions); return getSchemaByResolvedExtensions(resolvedExtensions, editor); } function getTextBetween(startNode, range, options2) { const { from: from4, to: to2 } = range; const { blockSeparator = "\n\n", textSerializers = {} } = options2 || {}; let text10 = ""; startNode.nodesBetween(from4, to2, (node2, pos, parent, index4) => { var _a2; if (node2.isBlock && pos > from4) { text10 += blockSeparator; } const textSerializer = textSerializers == null ? void 0 : textSerializers[node2.type.name]; if (textSerializer) { if (parent) { text10 += textSerializer({ node: node2, pos, parent, index: index4, range }); } return false; } if (node2.isText) { text10 += (_a2 = node2 == null ? void 0 : node2.text) == null ? void 0 : _a2.slice(Math.max(from4, pos) - pos, to2 - pos); } }); return text10; } function getText2(node2, options2) { const range = { from: 0, to: node2.content.size }; return getTextBetween(node2, range, options2); } function getTextSerializersFromSchema(schema) { return Object.fromEntries( Object.entries(schema.nodes).filter(([, node2]) => node2.spec.toText).map(([name, node2]) => [name, node2.spec.toText]) ); } function getNodeAttributes(state, typeOrName) { const type = getNodeType(typeOrName, state.schema); const { from: from4, to: to2 } = state.selection; const nodes = []; state.doc.nodesBetween(from4, to2, (node22) => { nodes.push(node22); }); const node2 = nodes.reverse().find((nodeItem) => nodeItem.type.name === type.name); if (!node2) { return {}; } return { ...node2.attrs }; } function getAttributes(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 key2 = by(item); return Object.prototype.hasOwnProperty.call(seen, key2) ? false : seen[key2] = true; }); } function simplifyChangedRanges(changes) { const uniqueChanges = removeDuplicates(changes); return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index4) => { const rest = uniqueChanges.filter((_2, i3) => i3 !== index4); return !rest.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(transform2) { const { mapping, steps } = transform2; const changes = []; mapping.maps.forEach((stepMap, index4) => { const ranges = []; if (!stepMap.ranges.length) { const { from: from4, to: to2 } = steps[index4]; if (from4 === void 0 || to2 === void 0) { return; } ranges.push({ from: from4, to: to2 }); } else { stepMap.forEach((from4, to2) => { ranges.push({ from: from4, to: to2 }); }); } ranges.forEach(({ from: from4, to: to2 }) => { const newStart = mapping.slice(index4).map(from4, -1); const newEnd = mapping.slice(index4).map(to2); 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(from4, to2, doc4) { const marks = []; if (from4 === to2) { doc4.resolve(from4).marks().forEach((mark2) => { const $pos = doc4.resolve(from4); const range = getMarkRange($pos, mark2.type); if (!range) { return; } marks.push({ mark: mark2, ...range }); }); } else { doc4.nodesBetween(from4, to2, (node2, pos) => { if (!node2 || (node2 == null ? void 0 : node2.nodeSize) === void 0) { return; } marks.push( ...node2.marks.map((mark2) => ({ from: pos, to: pos + node2.nodeSize, mark: mark2 })) ); }); } return marks; } function getSchemaTypeByName(name, schema) { return schema.nodes[name] || schema.marks[name] || null; } 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; }) ); } var getTextContentFromNodes = ($from, maxMatch = 500) => { let textBefore = ""; const sliceEndPos = $from.parentOffset; $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node2, pos, parent, index4) => { var _a2, _b; const chunk = ((_b = (_a2 = node2.type.spec).toText) == null ? void 0 : _b.call(_a2, { node: node2, pos, parent, index: index4 })) || node2.textContent || "%leaf%"; textBefore += node2.isAtom && !node2.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos)); }); return textBefore; }; function isMarkActive(state, typeOrName, attributes = {}) { const { empty: empty4, ranges } = state.selection; const type = typeOrName ? getMarkType(typeOrName, state.schema) : null; if (empty4) { return !!(state.storedMarks || state.selection.$from.marks()).filter((mark2) => { if (!type) { return true; } return type.name === mark2.type.name; }).find((mark2) => objectIncludes(mark2.attrs, attributes, { strict: false })); } let selectionRange = 0; const markRanges = []; ranges.forEach(({ $from, $to }) => { const from4 = $from.pos; const to2 = $to.pos; state.doc.nodesBetween(from4, to2, (node2, pos) => { if (!node2.isText && !node2.marks.length) { return; } const relativeFrom = Math.max(from4, pos); const relativeTo = Math.min(to2, pos + node2.nodeSize); const range2 = relativeTo - relativeFrom; selectionRange += range2; markRanges.push( ...node2.marks.map((mark2) => ({ mark: mark2, 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); const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange; return range >= selectionRange; } function isActive(state, name, attributes = {}) { if (!name) { return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes); } const schemaType = getSchemaTypeNameByName(name, state.schema); if (schemaType === "node") { return isNodeActive(state, name, attributes); } if (schemaType === "mark") { return isMarkActive(state, name, attributes); } return false; } function isExtensionRulesEnabled(extension2, enabled) { if (Array.isArray(enabled)) { return enabled.some((enabledExtension) => { const name = typeof enabledExtension === "string" ? enabledExtension : enabledExtension.name; return name === extension2.name; }); } return enabled; } function isList(name, extensions) { const { nodeExtensions } = splitExtensions(extensions); const extension2 = nodeExtensions.find((item) => item.name === name); if (!extension2) { return false; } const context = { name: extension2.name, options: extension2.options, storage: extension2.storage }; const group = callOrReturn(getExtensionField(extension2, "group", context)); if (typeof group !== "string") { return false; } return group.split(" ").includes("list"); } function isNodeEmpty(node2, { checkChildren = true, ignoreWhitespace = false } = {}) { var _a2; if (ignoreWhitespace) { if (node2.type.name === "hardBreak") { return true; } if (node2.isText) { return /^\s*$/m.test((_a2 = node2.text) != null ? _a2 : ""); } } if (node2.isText) { return !node2.text; } if (node2.isAtom || node2.isLeaf) { return false; } if (node2.content.childCount === 0) { return true; } if (checkChildren) { let isContentEmpty = true; node2.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; } var MappablePosition = class _MappablePosition { constructor(position4) { this.position = position4; } /** * Creates a MappablePosition from a JSON object. */ static fromJSON(json) { return new _MappablePosition(json.position); } /** * Converts the MappablePosition to a JSON object. */ toJSON() { return { position: this.position }; } }; function getUpdatedPosition(position4, transaction) { const mapResult = transaction.mapping.mapResult(position4.position); return { position: new MappablePosition(mapResult.pos), mapResult }; } function createMappablePosition(position4) { return new MappablePosition(position4); } function posToDOMRect(view, from4, to2) { const minPos = 0; const maxPos = view.state.doc.content.size; const resolvedFrom = minMax(from4, minPos, maxPos); const resolvedEnd = minMax(to2, minPos, maxPos); const start = view.coordsAtPos(resolvedFrom); const end = view.coordsAtPos(resolvedEnd, -1); const top = Math.min(start.top, end.top); const bottom = Math.max(start.bottom, end.bottom); const left = Math.min(start.left, end.left); const right = Math.max(start.right, end.right); const width = right - left; const height = bottom - top; const x5 = left; const y3 = top; const data = { top, bottom, left, right, width, height, x: x5, y: y3 }; return { ...data, toJSON: () => data }; } function canSetMark(state, tr4, newMarkType) { var _a2; const { selection } = tr4; let cursor = null; if (isTextSelection(selection)) { cursor = selection.$cursor; } if (cursor) { const currentMarks = (_a2 = state.storedMarks) != null ? _a2 : cursor.marks(); const parentAllowsMarkType = cursor.parent.type.allowsMarkType(newMarkType); return parentAllowsMarkType && (!!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark2) => mark2.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, (node2, _pos, parent) => { if (someNodeSupportsMark) { return false; } if (node2.isInline) { const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType); const currentMarksAllowMarkType = !!newMarkType.isInSet(node2.marks) || !node2.marks.some((otherMark) => otherMark.type.excludes(newMarkType)); someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType; } return !someNodeSupportsMark; }); return someNodeSupportsMark; }); } var setMark = (typeOrName, attributes = {}) => ({ tr: tr4, state, dispatch }) => { const { selection } = tr4; const { empty: empty4, ranges } = selection; const type = getMarkType(typeOrName, state.schema); if (dispatch) { if (empty4) { const oldAttributes = getMarkAttributes(state, type); tr4.addStoredMark( type.create({ ...oldAttributes, ...attributes }) ); } else { ranges.forEach((range) => { const from4 = range.$from.pos; const to2 = range.$to.pos; state.doc.nodesBetween(from4, to2, (node2, pos) => { const trimmedFrom = Math.max(pos, from4); const trimmedTo = Math.min(pos + node2.nodeSize, to2); const someHasMark = node2.marks.find((mark2) => mark2.type === type); if (someHasMark) { node2.marks.forEach((mark2) => { if (type === mark2.type) { tr4.addMark( trimmedFrom, trimmedTo, type.create({ ...mark2.attrs, ...attributes }) ); } }); } else { tr4.addMark(trimmedFrom, trimmedTo, type.create(attributes)); } }); }); } } return canSetMark(state, tr4, type); }; var setMeta2 = (key2, value) => ({ tr: tr4 }) => { tr4.setMeta(key2, value); return true; }; var 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 }) => { const canSetBlock = setBlockType2(type, { ...attributesToCopy, ...attributes })(state); if (canSetBlock) { return true; } return commands.clearNodes(); }).command(({ state: updatedState }) => { return setBlockType2(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch); }).run(); }; var setNodeSelection = (position4) => ({ tr: tr4, dispatch }) => { if (dispatch) { const { doc: doc4 } = tr4; const from4 = minMax(position4, 0, doc4.content.size); const selection = NodeSelection.create(doc4, from4); tr4.setSelection(selection); } return true; }; var setTextDirection = (direction, position4) => ({ tr: tr4, state, dispatch }) => { const { selection } = state; let from4; let to2; if (typeof position4 === "number") { from4 = position4; to2 = position4; } else if (position4 && "from" in position4 && "to" in position4) { from4 = position4.from; to2 = position4.to; } else { from4 = selection.from; to2 = selection.to; } if (dispatch) { tr4.doc.nodesBetween(from4, to2, (node2, pos) => { if (node2.isText) { return; } tr4.setNodeMarkup(pos, void 0, { ...node2.attrs, dir: direction }); }); } return true; }; var setTextSelection = (position4) => ({ tr: tr4, dispatch }) => { if (dispatch) { const { doc: doc4 } = tr4; const { from: from4, to: to2 } = typeof position4 === "number" ? { from: position4, to: position4 } : position4; const minPos = TextSelection.atStart(doc4).from; const maxPos = TextSelection.atEnd(doc4).to; const resolvedFrom = minMax(from4, minPos, maxPos); const resolvedEnd = minMax(to2, minPos, maxPos); const selection = TextSelection.create(doc4, resolvedFrom, resolvedEnd); tr4.setSelection(selection); } return true; }; var sinkListItem2 = (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((mark2) => splittableMarks == null ? void 0 : splittableMarks.includes(mark2.type.name)); state.tr.ensureMarks(filteredMarks); } } var splitBlock2 = ({ keepMarks = true } = {}) => ({ tr: tr4, state, dispatch, editor }) => { const { selection, doc: doc4 } = tr4; 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(doc4, $from.pos)) { return false; } if (dispatch) { if (keepMarks) { ensureMarks(state, editor.extensionManager.splittableMarks); } tr4.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 : defaultBlockAt2($from.node(-1).contentMatchAt($from.indexAfter(-1))); let types2 = atEnd && deflt ? [ { type: deflt, attrs: newAttributes } ] : void 0; let can = canSplit(tr4.doc, tr4.mapping.map($from.pos), 1, types2); if (!types2 && !can && canSplit(tr4.doc, tr4.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) { can = true; types2 = deflt ? [ { type: deflt, attrs: newAttributes } ] : void 0; } if (dispatch) { if (can) { if (selection instanceof TextSelection) { tr4.deleteSelection(); } tr4.split(tr4.mapping.map($from.pos), 1, types2); if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) { const first2 = tr4.mapping.map($from.before()); const $first = tr4.doc.resolve(first2); if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) { tr4.setNodeMarkup(tr4.mapping.map($from.before()), deflt); } } } if (keepMarks) { ensureMarks(state, editor.extensionManager.splittableMarks); } tr4.scrollIntoView(); } return can; }; var splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr: tr4, state, dispatch, editor }) => { var _a2; const type = getNodeType(typeOrName, state.schema); const { $from, $to } = state.selection; const node2 = state.selection.node; if (node2 && node2.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) { let wrap5 = 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) { wrap5 = Fragment.from($from.node(d).copy(wrap5)); } const depthAfter = ( // eslint-disable-next-line no-nested-ternary $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 = ((_a2 = type.contentMatch.defaultType) == null ? void 0 : _a2.createAndFill(newNextTypeAttributes2)) || void 0; wrap5 = wrap5.append(Fragment.from(type.createAndFill(null, nextType2) || void 0)); const start = $from.before($from.depth - (depthBefore - 1)); tr4.replace(start, $from.after(-depthAfter), new Slice(wrap5, 4 - depthBefore, 0)); let sel = -1; tr4.doc.nodesBetween(start, tr4.doc.content.size, (n, pos) => { if (sel > -1) { return false; } if (n.isTextblock && n.content.size === 0) { sel = pos + 1; } }); if (sel > -1) { tr4.setSelection(TextSelection.near(tr4.doc.resolve(sel))); } tr4.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 }; tr4.delete($from.pos, $to.pos); const types2 = nextType ? [ { type, attrs: newTypeAttributes }, { type: nextType, attrs: newNextTypeAttributes } ] : [{ type, attrs: newTypeAttributes }]; if (!canSplit(tr4.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(); tr4.split($from.pos, 2, types2).scrollIntoView(); if (!marks || !dispatch) { return true; } const filteredMarks = marks.filter((mark2) => splittableMarks.includes(mark2.type.name)); tr4.ensureMarks(filteredMarks); } return true; }; var joinListBackwards = (tr4, listType) => { const list7 = findParentNode((node2) => node2.type === listType)(tr4.selection); if (!list7) { return true; } const before = tr4.doc.resolve(Math.max(0, list7.pos - 1)).before(list7.depth); if (before === void 0) { return true; } const nodeBefore = tr4.doc.nodeAt(before); const canJoinBackwards = list7.node.type === (nodeBefore == null ? void 0 : nodeBefore.type) && canJoin(tr4.doc, list7.pos); if (!canJoinBackwards) { return true; } tr4.join(list7.pos); return true; }; var joinListForwards = (tr4, listType) => { const list7 = findParentNode((node2) => node2.type === listType)(tr4.selection); if (!list7) { return true; } const after = tr4.doc.resolve(list7.start).after(list7.depth); if (after === void 0) { return true; } const nodeAfter = tr4.doc.nodeAt(after); const canJoinForwards = list7.node.type === (nodeAfter == null ? void 0 : nodeAfter.type) && canJoin(tr4.doc, after); if (!canJoinForwards) { return true; } tr4.join(after); return true; }; var toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr: tr4, 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((node2) => isList(node2.type.name, extensions))(selection); if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) { if (parentList.node.type === listType) { return commands.liftListItem(itemType); } if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content) && dispatch) { return chain().command(() => { tr4.setNodeMarkup(parentList.pos, listType); return true; }).command(() => joinListBackwards(tr4, listType)).command(() => joinListForwards(tr4, listType)).run(); } } if (!keepMarks || !marks || !dispatch) { return chain().command(() => { const canWrapInList = can().wrapInList(listType, attributes); if (canWrapInList) { return true; } return commands.clearNodes(); }).wrapInList(listType, attributes).command(() => joinListBackwards(tr4, listType)).command(() => joinListForwards(tr4, listType)).run(); } return chain().command(() => { const canWrapInList = can().wrapInList(listType, attributes); const filteredMarks = marks.filter((mark2) => splittableMarks.includes(mark2.type.name)); tr4.ensureMarks(filteredMarks); if (canWrapInList) { return true; } return commands.clearNodes(); }).wrapInList(listType, attributes).command(() => joinListBackwards(tr4, listType)).command(() => joinListForwards(tr4, listType)).run(); }; var toggleMark = (typeOrName, attributes = {}, options2 = {}) => ({ state, commands }) => { const { extendEmptyMarkRange = false } = options2; const type = getMarkType(typeOrName, state.schema); const isActive2 = isMarkActive(state, type, attributes); if (isActive2) { return commands.unsetMark(type, { extendEmptyMarkRange }); } return commands.setMark(type, attributes); }; var toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => { const type = getNodeType(typeOrName, state.schema); const toggleType = getNodeType(toggleTypeOrName, state.schema); const isActive2 = isNodeActive(state, type, attributes); let attributesToCopy; if (state.selection.$anchor.sameParent(state.selection.$head)) { attributesToCopy = state.selection.$anchor.parent.attrs; } if (isActive2) { return commands.setNode(toggleType, attributesToCopy); } return commands.setNode(type, { ...attributesToCopy, ...attributes }); }; var toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => { const type = getNodeType(typeOrName, state.schema); const isActive2 = isNodeActive(state, type, attributes); if (isActive2) { return commands.lift(type); } return commands.wrapIn(type, attributes); }; var undoInputRule = () => ({ state, dispatch }) => { const plugins = state.plugins; for (let i3 = 0; i3 < plugins.length; i3 += 1) { const plugin = plugins[i3]; let undoable; if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) { if (dispatch) { const tr4 = state.tr; const toUndo = undoable.transform; for (let j4 = toUndo.steps.length - 1; j4 >= 0; j4 -= 1) { tr4.step(toUndo.steps[j4].invert(toUndo.docs[j4])); } if (undoable.text) { const marks = tr4.doc.resolve(undoable.from).marks(); tr4.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks)); } else { tr4.delete(undoable.from, undoable.to); } } return true; } } return false; }; var unsetAllMarks = () => ({ tr: tr4, dispatch }) => { const { selection } = tr4; const { empty: empty4, ranges } = selection; if (empty4) { return true; } if (dispatch) { ranges.forEach((range) => { tr4.removeMark(range.$from.pos, range.$to.pos); }); } return true; }; var unsetMark = (typeOrName, options2 = {}) => ({ tr: tr4, state, dispatch }) => { var _a2; const { extendEmptyMarkRange = false } = options2; const { selection } = tr4; const type = getMarkType(typeOrName, state.schema); const { $from, empty: empty4, ranges } = selection; if (!dispatch) { return true; } if (empty4 && extendEmptyMarkRange) { let { from: from4, to: to2 } = selection; const attrs = (_a2 = $from.marks().find((mark2) => mark2.type === type)) == null ? void 0 : _a2.attrs; const range = getMarkRange($from, type, attrs); if (range) { from4 = range.from; to2 = range.to; } tr4.removeMark(from4, to2, type); } else { ranges.forEach((range) => { tr4.removeMark(range.$from.pos, range.$to.pos, type); }); } tr4.removeStoredMark(type); return true; }; var unsetTextDirection = (position4) => ({ tr: tr4, state, dispatch }) => { const { selection } = state; let from4; let to2; if (typeof position4 === "number") { from4 = position4; to2 = position4; } else if (position4 && "from" in position4 && "to" in position4) { from4 = position4.from; to2 = position4.to; } else { from4 = selection.from; to2 = selection.to; } if (dispatch) { tr4.doc.nodesBetween(from4, to2, (node2, pos) => { if (node2.isText) { return; } const newAttrs = { ...node2.attrs }; delete newAttrs.dir; tr4.setNodeMarkup(pos, void 0, newAttrs); }); } return true; }; var updateAttributes = (typeOrName, attributes = {}) => ({ tr: tr4, 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; tr4.selection.ranges.forEach((range) => { const from4 = range.$from.pos; const to2 = range.$to.pos; let lastPos; let lastNode; let trimmedFrom; let trimmedTo; if (tr4.selection.empty) { state.doc.nodesBetween(from4, to2, (node2, pos) => { if (nodeType && nodeType === node2.type) { canUpdate = true; trimmedFrom = Math.max(pos, from4); trimmedTo = Math.min(pos + node2.nodeSize, to2); lastPos = pos; lastNode = node2; } }); } else { state.doc.nodesBetween(from4, to2, (node2, pos) => { if (pos < from4 && nodeType && nodeType === node2.type) { canUpdate = true; trimmedFrom = Math.max(pos, from4); trimmedTo = Math.min(pos + node2.nodeSize, to2); lastPos = pos; lastNode = node2; } if (pos >= from4 && pos <= to2) { if (nodeType && nodeType === node2.type) { canUpdate = true; if (dispatch) { tr4.setNodeMarkup(pos, void 0, { ...node2.attrs, ...attributes }); } } if (markType && node2.marks.length) { node2.marks.forEach((mark2) => { if (markType === mark2.type) { canUpdate = true; if (dispatch) { const trimmedFrom2 = Math.max(pos, from4); const trimmedTo2 = Math.min(pos + node2.nodeSize, to2); tr4.addMark( trimmedFrom2, trimmedTo2, markType.create({ ...mark2.attrs, ...attributes }) ); } } }); } } }); } if (lastNode) { if (lastPos !== void 0 && dispatch) { tr4.setNodeMarkup(lastPos, void 0, { ...lastNode.attrs, ...attributes }); } if (markType && lastNode.marks.length) { lastNode.marks.forEach((mark2) => { if (markType === mark2.type && dispatch) { tr4.addMark( trimmedFrom, trimmedTo, markType.create({ ...mark2.attrs, ...attributes }) ); } }); } } }); return canUpdate; }; var wrapIn2 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { const type = getNodeType(typeOrName, state.schema); return wrapIn(type, attributes)(state, dispatch); }; var wrapInList2 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { const type = getNodeType(typeOrName, state.schema); return wrapInList(type, attributes)(state, dispatch); }; var EventEmitter = class { constructor() { this.callbacks = {}; } on(event, fn4) { if (!this.callbacks[event]) { this.callbacks[event] = []; } this.callbacks[event].push(fn4); return this; } emit(event, ...args2) { const callbacks = this.callbacks[event]; if (callbacks) { callbacks.forEach((callback) => callback.apply(this, args2)); } return this; } off(event, fn4) { const callbacks = this.callbacks[event]; if (callbacks) { if (fn4) { this.callbacks[event] = callbacks.filter((callback) => callback !== fn4); } else { delete this.callbacks[event]; } } return this; } once(event, fn4) { const onceFn = (...args2) => { this.off(event, onceFn); fn4.apply(this, args2); }; return this.on(event, onceFn); } removeAllListeners() { this.callbacks = {}; } }; var InputRule = class { constructor(config) { var _a2; this.find = config.find; this.handler = config.handler; this.undoable = (_a2 = config.undoable) != null ? _a2 : true; } }; var inputRuleMatcherHandler = (text10, find4) => { if (isRegExp(find4)) { return find4.exec(text10); } const inputRuleMatch = find4(text10); if (!inputRuleMatch) { return null; } const result = [inputRuleMatch.text]; result.index = inputRuleMatch.index; result.input = text10; result.data = inputRuleMatch.data; if (inputRuleMatch.replaceWith) { if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) { console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'); } result.push(inputRuleMatch.replaceWith); } return result; }; function run(config) { var _a2; const { editor, from: from4, to: to2, text: text10, rules, plugin } = config; const { view } = editor; if (view.composing) { return false; } const $from = view.state.doc.resolve(from4); if ( // check for code node $from.parent.type.spec.code || // check for code mark !!((_a2 = $from.nodeBefore || $from.nodeAfter) == null ? void 0 : _a2.marks.find((mark2) => mark2.type.spec.code)) ) { return false; } let matched = false; const textBefore = getTextContentFromNodes($from) + text10; rules.forEach((rule) => { if (matched) { return; } const match2 = inputRuleMatcherHandler(textBefore, rule.find); if (!match2) { return; } const tr4 = view.state.tr; const state = createChainableState({ state: view.state, transaction: tr4 }); const range = { from: from4 - (match2[0].length - text10.length), to: to2 }; const { commands, chain, can } = new CommandManager({ editor, state }); const handler = rule.handler({ state, range, match: match2, commands, chain, can }); if (handler === null || !tr4.steps.length) { return; } if (rule.undoable) { tr4.setMeta(plugin, { transform: tr4, from: from4, to: to2, text: text10 }); } view.dispatch(tr4); matched = true; }); return matched; } function inputRulesPlugin(props) { const { editor, rules } = props; const plugin = new Plugin({ state: { init() { return null; }, apply(tr4, prev, state) { const stored = tr4.getMeta(plugin); if (stored) { return stored; } const simulatedInputMeta = tr4.getMeta("applyInputRules"); const isSimulatedInput = !!simulatedInputMeta; if (isSimulatedInput) { setTimeout(() => { let { text: text10 } = simulatedInputMeta; if (typeof text10 === "string") { text10 = text10; } else { text10 = getHTMLFromFragment(Fragment.from(text10), state.schema); } const { from: from4 } = simulatedInputMeta; const to2 = from4 + text10.length; run({ editor, from: from4, to: to2, text: text10, rules, plugin }); }); } return tr4.selectionSet || tr4.docChanged ? null : prev; } }, props: { handleTextInput(view, from4, to2, text10) { return run({ editor, from: from4, to: to2, text: text10, rules, plugin }); }, handleDOMEvents: { compositionend: (view) => { setTimeout(() => { const { $cursor } = view.state.selection; if ($cursor) { run({ editor, from: $cursor.pos, to: $cursor.pos, text: "", rules, plugin }); } }); return false; } }, // add support for input rules to trigger on enter // this is useful for example for code blocks handleKeyDown(view, event) { if (event.key !== "Enter") { return false; } const { $cursor } = view.state.selection; if ($cursor) { return run({ editor, from: $cursor.pos, to: $cursor.pos, text: "\n", rules, plugin }); } return false; } }, // @ts-ignore isInputRules: true }); return plugin; } 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 mergeDeep(target, source) { const output = { ...target }; if (isPlainObject(target) && isPlainObject(source)) { Object.keys(source).forEach((key2) => { if (isPlainObject(source[key2]) && isPlainObject(target[key2])) { output[key2] = mergeDeep(target[key2], source[key2]); } else { output[key2] = source[key2]; } }); } return output; } 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(options2 = {}) { const extension2 = this.extend({ ...this.config, addOptions: () => { return mergeDeep(this.options, options2); } }); extension2.name = this.name; extension2.parent = this.parent; return extension2; } extend(extendedConfig = {}) { const extension2 = new this.constructor({ ...this.config, ...extendedConfig }); extension2.parent = this; this.child = extension2; extension2.name = "name" in extendedConfig ? extendedConfig.name : extension2.parent.name; return extension2; } }; var Mark2 = class _Mark extends Extendable { constructor() { super(...arguments); 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 _Mark(resolvedConfig); } static handleExit({ editor, mark: mark2 }) { const { tr: tr4 } = editor.state; const currentPos = editor.state.selection.$from; const isAtEnd = currentPos.pos === currentPos.end(); if (isAtEnd) { const currentMarks = currentPos.marks(); const isInMark = !!currentMarks.find((m2) => (m2 == null ? void 0 : m2.type.name) === mark2.name); if (!isInMark) { return false; } const removeMark2 = currentMarks.find((m2) => (m2 == null ? void 0 : m2.type.name) === mark2.name); if (removeMark2) { tr4.removeStoredMark(removeMark2); } tr4.insertText(" ", currentPos.pos); editor.view.dispatch(tr4); return true; } return false; } configure(options2) { return super.configure(options2); } extend(extendedConfig) { const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; return super.extend(resolvedConfig); } }; function isNumber(value) { return typeof value === "number"; } var PasteRule = class { constructor(config) { this.find = config.find; this.handler = config.handler; } }; var pasteRuleMatcherHandler = (text10, find4, event) => { if (isRegExp(find4)) { return [...text10.matchAll(find4)]; } const matches3 = find4(text10, event); if (!matches3) { return []; } return matches3.map((pasteRuleMatch) => { const result = [pasteRuleMatch.text]; result.index = pasteRuleMatch.index; result.input = text10; result.data = pasteRuleMatch.data; if (pasteRuleMatch.replaceWith) { if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) { console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'); } result.push(pasteRuleMatch.replaceWith); } return result; }); }; function run2(config) { const { editor, state, from: from4, to: to2, rule, pasteEvent, dropEvent } = config; const { commands, chain, can } = new CommandManager({ editor, state }); const handlers4 = []; state.doc.nodesBetween(from4, to2, (node2, pos) => { var _a2, _b, _c, _d, _e4; if (((_b = (_a2 = node2.type) == null ? void 0 : _a2.spec) == null ? void 0 : _b.code) || !(node2.isText || node2.isTextblock || node2.isInline)) { return; } const contentSize = (_e4 = (_d = (_c = node2.content) == null ? void 0 : _c.size) != null ? _d : node2.nodeSize) != null ? _e4 : 0; const resolvedFrom = Math.max(from4, pos); const resolvedTo = Math.min(to2, pos + contentSize); if (resolvedFrom >= resolvedTo) { return; } const textToMatch = node2.isText ? node2.text || "" : node2.textBetween(resolvedFrom - pos, resolvedTo - pos, void 0, ""); const matches3 = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent); matches3.forEach((match2) => { if (match2.index === void 0) { return; } const start = resolvedFrom + match2.index + 1; const end = start + match2[0].length; const range = { from: state.tr.mapping.map(start), to: state.tr.mapping.map(end) }; const handler = rule.handler({ state, range, match: match2, commands, chain, can, pasteEvent, dropEvent }); handlers4.push(handler); }); }); const success = handlers4.every((handler) => handler !== null); return success; } var tiptapDragFromOtherEditor = null; var createClipboardPasteEvent = (text10) => { var _a2; const event = new ClipboardEvent("paste", { clipboardData: new DataTransfer() }); (_a2 = event.clipboardData) == null ? void 0 : _a2.setData("text/html", text10); return event; }; function pasteRulesPlugin(props) { const { editor, rules } = props; let dragSourceElement = null; let isPastedFromProseMirror = false; let isDroppedFromProseMirror = false; let pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null; let dropEvent; try { dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null; } catch { dropEvent = null; } const processEvent = ({ state, from: from4, to: to2, rule, pasteEvt }) => { const tr4 = state.tr; const chainableState = createChainableState({ state, transaction: tr4 }); const handler = run2({ editor, state: chainableState, from: Math.max(from4 - 1, 0), to: to2.b - 1, rule, pasteEvent: pasteEvt, dropEvent }); if (!handler || !tr4.steps.length) { return; } try { dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null; } catch { dropEvent = null; } pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null; return tr4; }; const plugins = rules.map((rule) => { return new Plugin({ // we register a global drag handler to track the current drag source element view(view) { const handleDragstart = (event) => { var _a2; dragSourceElement = ((_a2 = view.dom.parentElement) == null ? void 0 : _a2.contains(event.target)) ? view.dom.parentElement : null; if (dragSourceElement) { tiptapDragFromOtherEditor = editor; } }; const handleDragend = () => { if (tiptapDragFromOtherEditor) { tiptapDragFromOtherEditor = null; } }; window.addEventListener("dragstart", handleDragstart); window.addEventListener("dragend", handleDragend); return { destroy() { window.removeEventListener("dragstart", handleDragstart); window.removeEventListener("dragend", handleDragend); } }; }, props: { handleDOMEvents: { drop: (view, event) => { isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement; dropEvent = event; if (!isDroppedFromProseMirror) { const dragFromOtherEditor = tiptapDragFromOtherEditor; if (dragFromOtherEditor == null ? void 0 : dragFromOtherEditor.isEditable) { setTimeout(() => { const selection = dragFromOtherEditor.state.selection; if (selection) { dragFromOtherEditor.commands.deleteRange({ from: selection.from, to: selection.to }); } }, 10); } } return false; }, paste: (_view, event) => { var _a2; const html7 = (_a2 = event.clipboardData) == null ? void 0 : _a2.getData("text/html"); pasteEvent = event; isPastedFromProseMirror = !!(html7 == null ? void 0 : html7.includes("data-pm-slice")); return false; } } }, appendTransaction: (transactions, oldState, state) => { const transaction = transactions[0]; const isPaste = transaction.getMeta("uiEvent") === "paste" && !isPastedFromProseMirror; const isDrop = transaction.getMeta("uiEvent") === "drop" && !isDroppedFromProseMirror; const simulatedPasteMeta = transaction.getMeta("applyPasteRules"); const isSimulatedPaste = !!simulatedPasteMeta; if (!isPaste && !isDrop && !isSimulatedPaste) { return; } if (isSimulatedPaste) { let { text: text10 } = simulatedPasteMeta; if (typeof text10 === "string") { text10 = text10; } else { text10 = getHTMLFromFragment(Fragment.from(text10), state.schema); } const { from: from22 } = simulatedPasteMeta; const to22 = from22 + text10.length; const pasteEvt = createClipboardPasteEvent(text10); return processEvent({ rule, state, from: from22, to: { b: to22 }, pasteEvt }); } const from4 = oldState.doc.content.findDiffStart(state.doc.content); const to2 = oldState.doc.content.findDiffEnd(state.doc.content); if (!isNumber(from4) || !to2 || from4 === to2.b) { return; } return processEvent({ rule, state, from: from4, to: to2, pasteEvt: pasteEvent }); } }); }); return plugins; } var ExtensionManager = class { constructor(extensions, editor) { this.splittableMarks = []; this.editor = editor; this.baseExtensions = extensions; this.extensions = resolveExtensions(extensions); this.schema = getSchemaByResolvedExtensions(this.extensions, editor); this.setupExtensions(); } /** * Get all commands from the extensions. * @returns An object with all commands where the key is the command name and the value is the command function */ get commands() { return this.extensions.reduce((commands, extension2) => { const context = { name: extension2.name, options: extension2.options, storage: this.editor.extensionStorage[extension2.name], editor: this.editor, type: getSchemaTypeByName(extension2.name, this.schema) }; const addCommands = getExtensionField(extension2, "addCommands", context); if (!addCommands) { return commands; } return { ...commands, ...addCommands() }; }, {}); } /** * Get all registered Prosemirror plugins from the extensions. * @returns An array of Prosemirror plugins */ get plugins() { const { editor } = this; const extensions = sortExtensions([...this.extensions].reverse()); const allPlugins = extensions.flatMap((extension2) => { const context = { name: extension2.name, options: extension2.options, storage: this.editor.extensionStorage[extension2.name], editor, type: getSchemaTypeByName(extension2.name, this.schema) }; const plugins = []; const addKeyboardShortcuts = getExtensionField( extension2, "addKeyboardShortcuts", context ); let defaultBindings = {}; if (extension2.type === "mark" && getExtensionField(extension2, "exitable", context)) { defaultBindings.ArrowRight = () => Mark2.handleExit({ editor, mark: extension2 }); } if (addKeyboardShortcuts) { const bindings = Object.fromEntries( Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => { return [shortcut, () => method({ editor })]; }) ); defaultBindings = { ...defaultBindings, ...bindings }; } const keyMapPlugin = keymap(defaultBindings); plugins.push(keyMapPlugin); const addInputRules = getExtensionField(extension2, "addInputRules", context); if (isExtensionRulesEnabled(extension2, editor.options.enableInputRules) && addInputRules) { const rules = addInputRules(); if (rules && rules.length) { const inputResult = inputRulesPlugin({ editor, rules }); const inputPlugins = Array.isArray(inputResult) ? inputResult : [inputResult]; plugins.push(...inputPlugins); } } const addPasteRules = getExtensionField(extension2, "addPasteRules", context); if (isExtensionRulesEnabled(extension2, editor.options.enablePasteRules) && addPasteRules) { const rules = addPasteRules(); if (rules && rules.length) { const pasteRules = pasteRulesPlugin({ editor, rules }); plugins.push(...pasteRules); } } const addProseMirrorPlugins = getExtensionField( extension2, "addProseMirrorPlugins", context ); if (addProseMirrorPlugins) { const proseMirrorPlugins = addProseMirrorPlugins(); plugins.push(...proseMirrorPlugins); } return plugins; }); return allPlugins; } /** * Get all attributes from the extensions. * @returns An array of attributes */ get attributes() { return getAttributesFromExtensions(this.extensions); } /** * Get all node views from the extensions. * @returns An object with all node views where the key is the node name and the value is the node view function */ get nodeViews() { const { editor } = this; const { nodeExtensions } = splitExtensions(this.extensions); return Object.fromEntries( nodeExtensions.filter((extension2) => !!getExtensionField(extension2, "addNodeView")).map((extension2) => { const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension2.name); const context = { name: extension2.name, options: extension2.options, storage: this.editor.extensionStorage[extension2.name], editor, type: getNodeType(extension2.name, this.schema) }; const addNodeView = getExtensionField(extension2, "addNodeView", context); if (!addNodeView) { return []; } const nodeViewResult = addNodeView(); if (!nodeViewResult) { return []; } const nodeview = (node2, view, getPos, decorations, innerDecorations) => { const HTMLAttributes = getRenderedAttributes(node2, extensionAttributes); return nodeViewResult({ // pass-through node: node2, view, getPos, decorations, innerDecorations, // tiptap-specific editor, extension: extension2, HTMLAttributes }); }; return [extension2.name, nodeview]; }) ); } get markViews() { const { editor } = this; const { markExtensions } = splitExtensions(this.extensions); return Object.fromEntries( markExtensions.filter((extension2) => !!getExtensionField(extension2, "addMarkView")).map((extension2) => { const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension2.name); const context = { name: extension2.name, options: extension2.options, storage: this.editor.extensionStorage[extension2.name], editor, type: getMarkType(extension2.name, this.schema) }; const addMarkView = getExtensionField(extension2, "addMarkView", context); if (!addMarkView) { return []; } const markView = (mark2, view, inline4) => { const HTMLAttributes = getRenderedAttributes(mark2, extensionAttributes); return addMarkView()({ // pass-through mark: mark2, view, inline: inline4, // tiptap-specific editor, extension: extension2, HTMLAttributes, updateAttributes: (attrs) => { updateMarkViewAttributes(mark2, editor, attrs); } }); }; return [extension2.name, markView]; }) ); } /** * Go through all extensions, create extension storages & setup marks * & bind editor event listener. */ setupExtensions() { const extensions = this.extensions; this.editor.extensionStorage = Object.fromEntries( extensions.map((extension2) => [extension2.name, extension2.storage]) ); extensions.forEach((extension2) => { var _a2; const context = { name: extension2.name, options: extension2.options, storage: this.editor.extensionStorage[extension2.name], editor: this.editor, type: getSchemaTypeByName(extension2.name, this.schema) }; if (extension2.type === "mark") { const keepOnSplit = (_a2 = callOrReturn(getExtensionField(extension2, "keepOnSplit", context))) != null ? _a2 : true; if (keepOnSplit) { this.splittableMarks.push(extension2.name); } } const onBeforeCreate = getExtensionField(extension2, "onBeforeCreate", context); const onCreate = getExtensionField(extension2, "onCreate", context); const onUpdate = getExtensionField(extension2, "onUpdate", context); const onSelectionUpdate = getExtensionField( extension2, "onSelectionUpdate", context ); const onTransaction = getExtensionField(extension2, "onTransaction", context); const onFocus = getExtensionField(extension2, "onFocus", context); const onBlur = getExtensionField(extension2, "onBlur", context); const onDestroy = getExtensionField(extension2, "onDestroy", context); if (onBeforeCreate) { this.editor.on("beforeCreate", onBeforeCreate); } if (onCreate) { this.editor.on("create", onCreate); } if (onUpdate) { this.editor.on("update", onUpdate); } if (onSelectionUpdate) { this.editor.on("selectionUpdate", onSelectionUpdate); } if (onTransaction) { this.editor.on("transaction", onTransaction); } if (onFocus) { this.editor.on("focus", onFocus); } if (onBlur) { this.editor.on("blur", onBlur); } if (onDestroy) { this.editor.on("destroy", onDestroy); } }); } }; ExtensionManager.resolve = resolveExtensions; ExtensionManager.sort = sortExtensions; ExtensionManager.flatten = flattenExtensions; var extensions_exports = {}; __export2(extensions_exports, { ClipboardTextSerializer: () => ClipboardTextSerializer, Commands: () => Commands, Delete: () => Delete, Drop: () => Drop, Editable: () => Editable, FocusEvents: () => FocusEvents, Keymap: () => Keymap, Paste: () => Paste, Tabindex: () => Tabindex, TextDirection: () => TextDirection, focusEventsPluginKey: () => focusEventsPluginKey }); var Extension = class _Extension extends Extendable { constructor() { super(...arguments); 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 _Extension(resolvedConfig); } configure(options2) { return super.configure(options2); } extend(extendedConfig) { const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; return super.extend(resolvedConfig); } }; var 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: doc4, selection } = state; const { ranges } = selection; const from4 = Math.min(...ranges.map((range2) => range2.$from.pos)); const to2 = Math.max(...ranges.map((range2) => range2.$to.pos)); const textSerializers = getTextSerializersFromSchema(schema); const range = { from: from4, to: to2 }; return getTextBetween(doc4, range, { ...this.options.blockSeparator !== void 0 ? { blockSeparator: this.options.blockSeparator } : {}, textSerializers }); } } }) ]; } }); var Commands = Extension.create({ name: "commands", addCommands() { return { ...commands_exports }; } }); var Delete = Extension.create({ name: "delete", onUpdate({ transaction, appendedTransactions }) { var _a2, _b, _c; const callback = () => { var _a22, _b2, _c2, _d; if ((_d = (_c2 = (_b2 = (_a22 = this.editor.options.coreExtensionOptions) == null ? void 0 : _a22.delete) == null ? void 0 : _b2.filterTransaction) == null ? void 0 : _c2.call(_b2, transaction)) != null ? _d : transaction.getMeta("y-sync$")) { return; } const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions]); const changes = getChangedRanges(nextTransaction); changes.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, (node2, from4) => { const to2 = from4 + node2.nodeSize - 2; const isFullyWithinRange = change.oldRange.from <= from4 && to2 <= change.oldRange.to; this.editor.emit("delete", { type: "node", node: node2, from: from4, to: to2, newFrom: nextTransaction.mapping.map(from4), newTo: nextTransaction.mapping.map(to2), deletedRange: change.oldRange, newRange: change.newRange, partial: !isFullyWithinRange, editor: this.editor, transaction, combinedTransform: nextTransaction }); }); } }); const mapping = nextTransaction.mapping; nextTransaction.steps.forEach((step, index4) => { var _a3, _b3; if (step instanceof RemoveMarkStep) { const newStart = mapping.slice(index4).map(step.from, -1); const newEnd = mapping.slice(index4).map(step.to); const oldStart = mapping.invert().map(newStart, -1); const oldEnd = mapping.invert().map(newEnd); const foundBeforeMark = (_a3 = nextTransaction.doc.nodeAt(newStart - 1)) == null ? void 0 : _a3.marks.some((mark2) => mark2.eq(step.mark)); const foundAfterMark = (_b3 = nextTransaction.doc.nodeAt(newEnd)) == null ? void 0 : _b3.marks.some((mark2) => mark2.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 ((_c = (_b = (_a2 = this.editor.options.coreExtensionOptions) == null ? void 0 : _a2.delete) == null ? void 0 : _b.async) != null ? _c : true) { setTimeout(callback, 0); } else { callback(); } } }); var Drop = Extension.create({ name: "drop", addProseMirrorPlugins() { return [ new Plugin({ key: new PluginKey("tiptapDrop"), props: { handleDrop: (_2, e2, slice2, moved) => { this.editor.emit("drop", { editor: this.editor, event: e2, slice: slice2, moved }); } } }) ]; } }); var Editable = Extension.create({ name: "editable", addProseMirrorPlugins() { return [ new Plugin({ key: new PluginKey("editable"), props: { editable: () => this.editor.options.editable } }) ]; } }); var focusEventsPluginKey = new PluginKey("focusEvents"); var 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; } } } }) ]; } }); var Keymap = Extension.create({ name: "keymap", addKeyboardShortcuts() { const handleBackspace = () => this.editor.commands.first(({ commands }) => [ () => commands.undoInputRule(), // maybe convert first text block node to default node () => commands.command(({ tr: tr4 }) => { const { selection, doc: doc4 } = tr4; const { empty: empty4, $anchor } = selection; const { pos, parent } = $anchor; const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr4.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(doc4).from === pos; if (!empty4 || !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 handleEnter = () => this.editor.commands.first(({ commands }) => [ () => commands.newlineInCode(), () => commands.createParagraphNear(), () => commands.liftEmptyBlock(), () => commands.splitBlock() ]); const baseKeymap = { Enter: handleEnter, "Mod-Enter": () => this.editor.commands.exitCode(), Backspace: handleBackspace, "Mod-Backspace": handleBackspace, "Shift-Backspace": handleBackspace, Delete: handleDelete2, "Mod-Delete": handleDelete2, "Mod-a": () => this.editor.commands.selectAll() }; const pcKeymap = { ...baseKeymap }; const macKeymap = { ...baseKeymap, "Ctrl-h": handleBackspace, "Alt-Backspace": handleBackspace, "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 [ // With this plugin we check if the whole document was selected and deleted. // In this case we will additionally call `clearNodes()` to convert e.g. a heading // to a paragraph if necessary. // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well // with many other commands. new Plugin({ key: new PluginKey("clearDocument"), appendTransaction: (transactions, oldState, newState) => { if (transactions.some((tr22) => tr22.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: empty4, from: from4, to: to2 } = oldState.selection; const allFrom = Selection.atStart(oldState.doc).from; const allEnd = Selection.atEnd(oldState.doc).to; const allWasSelected = from4 === allFrom && to2 === allEnd; if (empty4 || !allWasSelected) { return; } const isEmpty3 = isNodeEmpty(newState.doc); if (!isEmpty3) { return; } const tr4 = newState.tr; const state = createChainableState({ state: newState, transaction: tr4 }); const { commands } = new CommandManager({ editor: this.editor, state }); commands.clearNodes(); if (!tr4.steps.length) { return; } return tr4; } }) ]; } }); var Paste = Extension.create({ name: "paste", addProseMirrorPlugins() { return [ new Plugin({ key: new PluginKey("tiptapPaste"), props: { handlePaste: (_view, e2, slice2) => { this.editor.emit("paste", { editor: this.editor, event: e2, slice: slice2 }); } } }) ]; } }); var Tabindex = Extension.create({ name: "tabindex", addProseMirrorPlugins() { return [ new Plugin({ key: new PluginKey("tabindex"), props: { attributes: () => this.editor.isEditable ? { tabindex: "0" } : {} } }) ]; } }); var 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((extension2) => extension2.name !== "text").map((extension2) => extension2.name), attributes: { dir: { default: this.options.direction, parseHTML: (element7) => { const dir = element7.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 NodePos = class _NodePos { constructor(pos, editor, isBlock = false, node2 = null) { this.currentNode = null; this.actualDepth = null; this.isBlock = isBlock; this.resolvedPos = pos; this.editor = editor; this.currentNode = node2; } get name() { return this.node.type.name; } get node() { return this.currentNode || this.resolvedPos.node(); } get element() { return this.editor.view.domAtPos(this.pos).node; } get depth() { var _a2; return (_a2 = this.actualDepth) != null ? _a2 : this.resolvedPos.depth; } get pos() { return this.resolvedPos.pos; } get content() { return this.node.content; } set content(content5) { let from4 = this.from; let to2 = this.to; if (this.isBlock) { if (this.content.size === 0) { console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`); return; } from4 = this.from + 1; to2 = this.to - 1; } this.editor.commands.insertContentAt({ from: from4, to: to2 }, content5); } get attributes() { return this.node.attrs; } get textContent() { return this.node.textContent; } get size() { return this.node.nodeSize; } get from() { if (this.isBlock) { return this.pos; } return this.resolvedPos.start(this.resolvedPos.depth); } get range() { return { from: this.from, to: this.to }; } get to() { if (this.isBlock) { return this.pos + this.size; } return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1); } get parent() { if (this.depth === 0) { return null; } const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1); const $pos = this.resolvedPos.doc.resolve(parentPos); return new _NodePos($pos, this.editor); } get before() { let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2)); if ($pos.depth !== this.depth) { $pos = this.resolvedPos.doc.resolve(this.from - 3); } return new _NodePos($pos, this.editor); } get after() { let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1)); if ($pos.depth !== this.depth) { $pos = this.resolvedPos.doc.resolve(this.to + 3); } return new _NodePos($pos, this.editor); } get children() { const children = []; this.node.content.forEach((node2, offset4) => { const isBlock = node2.isBlock && !node2.isTextblock; const isNonTextAtom = node2.isAtom && !node2.isText; const targetPos = this.pos + offset4 + (isNonTextAtom ? 0 : 1); if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) { return; } const $pos = this.resolvedPos.doc.resolve(targetPos); if (!isBlock && $pos.depth <= this.depth) { return; } const childNodePos = new _NodePos($pos, this.editor, isBlock, isBlock ? node2 : null); if (isBlock) { childNodePos.actualDepth = this.depth + 1; } children.push(new _NodePos($pos, this.editor, isBlock, isBlock ? node2 : null)); }); return children; } get firstChild() { return this.children[0] || null; } get lastChild() { const children = this.children; return children[children.length - 1] || null; } closest(selector, attributes = {}) { let node2 = null; let currentNode = this.parent; while (currentNode && !node2) { if (currentNode.node.type.name === selector) { if (Object.keys(attributes).length > 0) { const nodeAttributes = currentNode.node.attrs; const attrKeys = Object.keys(attributes); for (let index4 = 0; index4 < attrKeys.length; index4 += 1) { const key2 = attrKeys[index4]; if (nodeAttributes[key2] !== attributes[key2]) { break; } } } else { node2 = currentNode; } } currentNode = currentNode.parent; } return node2; } querySelector(selector, attributes = {}) { return this.querySelectorAll(selector, attributes, true)[0] || null; } querySelectorAll(selector, attributes = {}, firstItemOnly = false) { let nodes = []; if (!this.children || this.children.length === 0) { return nodes; } const attrKeys = Object.keys(attributes); this.children.forEach((childPos) => { if (firstItemOnly && nodes.length > 0) { return; } if (childPos.node.type.name === selector) { const doesAllAttributesMatch = attrKeys.every((key2) => attributes[key2] === childPos.node.attrs[key2]); if (doesAllAttributesMatch) { nodes.push(childPos); } } if (firstItemOnly && nodes.length > 0) { return; } nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly)); }); return nodes; } setAttribute(attributes) { const { tr: tr4 } = this.editor.state; tr4.setNodeMarkup(this.from, void 0, { ...this.node.attrs, ...attributes }); this.editor.view.dispatch(tr4); } }; var style = `.ProseMirror { position: relative; } .ProseMirror { word-wrap: break-word; white-space: pre-wrap; white-space: break-spaces; -webkit-font-variant-ligatures: none; font-variant-ligatures: none; font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */ } .ProseMirror [contenteditable="false"] { white-space: normal; } .ProseMirror [contenteditable="false"] [contenteditable="true"] { white-space: pre-wrap; } .ProseMirror pre { white-space: pre-wrap; } img.ProseMirror-separator { display: inline !important; border: none !important; margin: 0 !important; width: 0 !important; height: 0 !important; } .ProseMirror-gapcursor { display: none; pointer-events: none; position: absolute; margin: 0; } .ProseMirror-gapcursor:after { content: ""; display: block; position: absolute; top: -2px; width: 20px; border-top: 1px solid black; animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite; } @keyframes ProseMirror-cursor-blink { to { visibility: hidden; } } .ProseMirror-hideselection *::selection { background: transparent; } .ProseMirror-hideselection *::-moz-selection { background: transparent; } .ProseMirror-hideselection * { caret-color: transparent; } .ProseMirror-focused .ProseMirror-gapcursor { display: block; }`; function createStyleTag(style22, nonce, suffix) { const tiptapStyleTag = document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ""}]`); if (tiptapStyleTag !== null) { return tiptapStyleTag; } const styleNode = document.createElement("style"); if (nonce) { styleNode.setAttribute("nonce", nonce); } styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ""}`, ""); styleNode.innerHTML = style22; document.getElementsByTagName("head")[0].appendChild(styleNode); return styleNode; } var Editor = class extends EventEmitter { constructor(options2 = {}) { super(); this.css = null; this.className = "tiptap"; this.editorView = null; this.isFocused = false; this.isInitialized = false; this.extensionStorage = {}; this.instanceId = Math.random().toString(36).slice(2, 9); this.options = { element: typeof document !== "undefined" ? document.createElement("div") : null, content: "", injectCSS: true, injectNonce: void 0, extensions: [], autofocus: false, editable: true, textDirection: void 0, editorProps: {}, parseOptions: {}, coreExtensionOptions: {}, enableInputRules: true, enablePasteRules: true, enableCoreExtensions: true, enableContentCheck: false, emitContentError: false, onBeforeCreate: () => null, onCreate: () => null, onMount: () => null, onUnmount: () => null, onUpdate: () => null, onSelectionUpdate: () => null, onTransaction: () => null, onFocus: () => null, onBlur: () => null, onDestroy: () => null, onContentError: ({ error: error2 }) => { throw error2; }, onPaste: () => null, onDrop: () => null, onDelete: () => null }; this.isCapturingTransaction = false; this.capturedTransaction = null; this.utils = { getUpdatedPosition, createMappablePosition }; this.setOptions(options2); this.createExtensionManager(); this.createCommandManager(); this.createSchema(); this.on("beforeCreate", this.options.onBeforeCreate); this.emit("beforeCreate", { editor: this }); this.on("mount", this.options.onMount); this.on("unmount", this.options.onUnmount); this.on("contentError", this.options.onContentError); this.on("create", this.options.onCreate); this.on("update", this.options.onUpdate); this.on("selectionUpdate", this.options.onSelectionUpdate); this.on("transaction", this.options.onTransaction); this.on("focus", this.options.onFocus); this.on("blur", this.options.onBlur); this.on("destroy", this.options.onDestroy); this.on("drop", ({ event, slice: slice2, moved }) => this.options.onDrop(event, slice2, moved)); this.on("paste", ({ event, slice: slice2 }) => this.options.onPaste(event, slice2)); this.on("delete", this.options.onDelete); const initialDoc = this.createDoc(); const selection = resolveFocusPosition(initialDoc, this.options.autofocus); this.editorState = EditorState.create({ doc: initialDoc, schema: this.schema, selection: selection || void 0 }); if (this.options.element) { this.mount(this.options.element); } } /** * Attach the editor to the DOM, creating a new editor view. */ mount(el2) { if (typeof document === "undefined") { throw new Error( `[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.` ); } this.createView(el2); this.emit("mount", { editor: this }); if (this.css && !document.head.contains(this.css)) { document.head.appendChild(this.css); } window.setTimeout(() => { if (this.isDestroyed) { return; } if (this.options.autofocus !== false && this.options.autofocus !== null) { this.commands.focus(this.options.autofocus); } this.emit("create", { editor: this }); this.isInitialized = true; }, 0); } /** * Remove the editor from the DOM, but still allow remounting at a different point in time */ unmount() { if (this.editorView) { const dom = this.editorView.dom; if (dom == null ? void 0 : dom.editor) { delete dom.editor; } this.editorView.destroy(); } this.editorView = null; this.isInitialized = false; if (this.css && !document.querySelectorAll(`.${this.className}`).length) { try { if (typeof this.css.remove === "function") { this.css.remove(); } else if (this.css.parentNode) { this.css.parentNode.removeChild(this.css); } } catch (error2) { console.warn("Failed to remove CSS element:", error2); } } this.css = null; this.emit("unmount", { editor: this }); } /** * Returns the editor storage. */ get storage() { return this.extensionStorage; } /** * An object of all registered commands. */ get commands() { return this.commandManager.commands; } /** * Create a command chain to call multiple commands at once. */ chain() { return this.commandManager.chain(); } /** * Check if a command or a command chain can be executed. Without executing it. */ can() { return this.commandManager.can(); } /** * Inject CSS styles. */ injectCSS() { if (this.options.injectCSS && typeof document !== "undefined") { this.css = createStyleTag(style, this.options.injectNonce); } } /** * Update editor options. * * @param options A list of options */ setOptions(options2 = {}) { this.options = { ...this.options, ...options2 }; if (!this.editorView || !this.state || this.isDestroyed) { return; } if (this.options.editorProps) { this.view.setProps(this.options.editorProps); } this.view.updateState(this.state); } /** * Update editable state of the editor. */ setEditable(editable, emitUpdate = true) { this.setOptions({ editable }); if (emitUpdate) { this.emit("update", { editor: this, transaction: this.state.tr, appendedTransactions: [] }); } } /** * Returns whether the editor is editable. */ get isEditable() { return this.options.editable && this.view && this.view.editable; } /** * Returns the editor state. */ get view() { if (this.editorView) { return this.editorView; } return new Proxy( { state: this.editorState, updateState: (state) => { this.editorState = state; }, dispatch: (tr4) => { this.dispatchTransaction(tr4); }, // Stub some commonly accessed properties to prevent errors composing: false, dragging: null, editable: true, isDestroyed: false }, { get: (obj, key2) => { if (this.editorView) { return this.editorView[key2]; } if (key2 === "state") { return this.editorState; } if (key2 in obj) { return Reflect.get(obj, key2); } throw new Error( `[tiptap error]: The editor view is not available. Cannot access view['${key2}']. The editor may not be mounted yet.` ); } } ); } /** * Returns the editor state. */ get state() { if (this.editorView) { this.editorState = this.view.state; } return this.editorState; } /** * Register a ProseMirror plugin. * * @param plugin A ProseMirror plugin * @param handlePlugins Control how to merge the plugin into the existing plugins. * @returns The new editor state */ registerPlugin(plugin, handlePlugins) { const plugins = isFunction(handlePlugins) ? handlePlugins(plugin, [...this.state.plugins]) : [...this.state.plugins, plugin]; const state = this.state.reconfigure({ plugins }); this.view.updateState(state); return state; } /** * Unregister a ProseMirror plugin. * * @param nameOrPluginKeyToRemove The plugins name * @returns The new editor state or undefined if the editor is destroyed */ unregisterPlugin(nameOrPluginKeyToRemove) { if (this.isDestroyed) { return void 0; } const prevPlugins = this.state.plugins; let plugins = prevPlugins; [].concat(nameOrPluginKeyToRemove).forEach((nameOrPluginKey) => { const name = typeof nameOrPluginKey === "string" ? `${nameOrPluginKey}$` : nameOrPluginKey.key; plugins = plugins.filter((plugin) => !plugin.key.startsWith(name)); }); if (prevPlugins.length === plugins.length) { return void 0; } const state = this.state.reconfigure({ plugins }); this.view.updateState(state); return state; } /** * Creates an extension manager. */ createExtensionManager() { var _a2, _b; const coreExtensions = this.options.enableCoreExtensions ? [ Editable, ClipboardTextSerializer.configure({ blockSeparator: (_b = (_a2 = this.options.coreExtensionOptions) == null ? void 0 : _a2.clipboardTextSerializer) == null ? void 0 : _b.blockSeparator }), Commands, FocusEvents, Keymap, Tabindex, Drop, Paste, Delete, TextDirection.configure({ direction: this.options.textDirection }) ].filter((ext) => { if (typeof this.options.enableCoreExtensions === "object") { return this.options.enableCoreExtensions[ext.name] !== false; } return true; }) : []; const allExtensions = [...coreExtensions, ...this.options.extensions].filter((extension2) => { return ["extension", "node", "mark"].includes(extension2 == null ? void 0 : extension2.type); }); this.extensionManager = new ExtensionManager(allExtensions, this); } /** * Creates an command manager. */ createCommandManager() { this.commandManager = new CommandManager({ editor: this }); } /** * Creates a ProseMirror schema. */ createSchema() { this.schema = this.extensionManager.schema; } /** * Creates the initial document. */ createDoc() { let doc4; try { doc4 = createDocument(this.options.content, this.schema, this.options.parseOptions, { errorOnInvalidContent: this.options.enableContentCheck }); } catch (e2) { if (!(e2 instanceof Error) || !["[tiptap error]: Invalid JSON content", "[tiptap error]: Invalid HTML content"].includes(e2.message)) { throw e2; } this.emit("contentError", { editor: this, error: e2, disableCollaboration: () => { if ("collaboration" in this.storage && typeof this.storage.collaboration === "object" && this.storage.collaboration) { ; this.storage.collaboration.isDisabled = true; } this.options.extensions = this.options.extensions.filter((extension2) => extension2.name !== "collaboration"); this.createExtensionManager(); } }); doc4 = createDocument(this.options.content, this.schema, this.options.parseOptions, { errorOnInvalidContent: false }); } return doc4; } /** * Creates a ProseMirror view. */ createView(element7) { var _a2; this.editorView = new EditorView(element7, { ...this.options.editorProps, attributes: { // add `role="textbox"` to the editor element role: "textbox", ...(_a2 = this.options.editorProps) == null ? void 0 : _a2.attributes }, dispatchTransaction: this.dispatchTransaction.bind(this), state: this.editorState, markViews: this.extensionManager.markViews, nodeViews: this.extensionManager.nodeViews }); const newState = this.state.reconfigure({ plugins: this.extensionManager.plugins }); this.view.updateState(newState); this.prependClass(); this.injectCSS(); const dom = this.view.dom; dom.editor = this; } /** * Creates all node and mark views. */ createNodeViews() { if (this.view.isDestroyed) { return; } this.view.setProps({ markViews: this.extensionManager.markViews, nodeViews: this.extensionManager.nodeViews }); } /** * Prepend class name to element. */ prependClass() { this.view.dom.className = `${this.className} ${this.view.dom.className}`; } captureTransaction(fn4) { this.isCapturingTransaction = true; fn4(); this.isCapturingTransaction = false; const tr4 = this.capturedTransaction; this.capturedTransaction = null; return tr4; } /** * The callback over which to send transactions (state updates) produced by the view. * * @param transaction An editor state transaction */ dispatchTransaction(transaction) { if (this.view.isDestroyed) { return; } if (this.isCapturingTransaction) { if (!this.capturedTransaction) { this.capturedTransaction = transaction; return; } transaction.steps.forEach((step) => { var _a2; return (_a2 = this.capturedTransaction) == null ? void 0 : _a2.step(step); }); return; } const { state, transactions } = this.state.applyTransaction(transaction); const selectionHasChanged = !this.state.selection.eq(state.selection); const rootTrWasApplied = transactions.includes(transaction); const prevState = this.state; this.emit("beforeTransaction", { editor: this, transaction, nextState: state }); if (!rootTrWasApplied) { return; } this.view.updateState(state); this.emit("transaction", { editor: this, transaction, appendedTransactions: transactions.slice(1) }); if (selectionHasChanged) { this.emit("selectionUpdate", { editor: this, transaction }); } const mostRecentFocusTr = transactions.findLast((tr4) => tr4.getMeta("focus") || tr4.getMeta("blur")); const focus2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("focus"); const blur2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("blur"); if (focus2) { this.emit("focus", { editor: this, event: focus2.event, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion transaction: mostRecentFocusTr }); } if (blur2) { this.emit("blur", { editor: this, event: blur2.event, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion transaction: mostRecentFocusTr }); } if (transaction.getMeta("preventUpdate") || !transactions.some((tr4) => tr4.docChanged) || prevState.doc.eq(state.doc)) { return; } this.emit("update", { editor: this, transaction, appendedTransactions: transactions.slice(1) }); } /** * Get attributes of the currently selected node or mark. */ getAttributes(nameOrType) { return getAttributes(this.state, nameOrType); } isActive(nameOrAttributes, attributesOrUndefined) { const name = typeof nameOrAttributes === "string" ? nameOrAttributes : null; const attributes = typeof nameOrAttributes === "string" ? attributesOrUndefined : nameOrAttributes; return isActive(this.state, name, attributes); } /** * Get the document as JSON. */ getJSON() { return this.state.doc.toJSON(); } /** * Get the document as HTML. */ getHTML() { return getHTMLFromFragment(this.state.doc.content, this.schema); } /** * Get the document as text. */ getText(options2) { const { blockSeparator = "\n\n", textSerializers = {} } = options2 || {}; return getText2(this.state.doc, { blockSeparator, textSerializers: { ...getTextSerializersFromSchema(this.schema), ...textSerializers } }); } /** * Check if there is no content. */ get isEmpty() { return isNodeEmpty(this.state.doc); } /** * Destroy the editor. */ destroy() { this.emit("destroy"); this.unmount(); this.removeAllListeners(); } /** * Check if the editor is already destroyed. */ get isDestroyed() { var _a2, _b; return (_b = (_a2 = this.editorView) == null ? void 0 : _a2.isDestroyed) != null ? _b : true; } $node(selector, attributes) { var _a2; return ((_a2 = this.$doc) == null ? void 0 : _a2.querySelector(selector, attributes)) || null; } $nodes(selector, attributes) { var _a2; return ((_a2 = this.$doc) == null ? void 0 : _a2.querySelectorAll(selector, attributes)) || null; } $pos(pos) { const $pos = this.state.doc.resolve(pos); return new NodePos($pos, this); } get $doc() { return this.$pos(0); } }; function markInputRule(config) { return new InputRule({ find: config.find, handler: ({ state, range, match: match2 }) => { const attributes = callOrReturn(config.getAttributes, void 0, match2); if (attributes === false || attributes === null) { return null; } const { tr: tr4 } = state; const captureGroup = match2[match2.length - 1]; const fullMatch = match2[0]; if (captureGroup) { const startSpaces = fullMatch.search(/\S/); const textStart = range.from + fullMatch.indexOf(captureGroup); const textEnd = textStart + captureGroup.length; const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => { const excluded = item.mark.type.excluded; return excluded.find((type) => type === config.type && type !== item.mark.type); }).filter((item) => item.to > textStart); if (excludedMarks.length) { return null; } if (textEnd < range.to) { tr4.delete(textEnd, range.to); } if (textStart > range.from) { tr4.delete(range.from + startSpaces, textStart); } const markEnd = range.from + startSpaces + captureGroup.length; tr4.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); tr4.removeStoredMark(config.type); } }, undoable: config.undoable }); } var markdown_exports = {}; __export2(markdown_exports, { createAtomBlockMarkdownSpec: () => createAtomBlockMarkdownSpec, createBlockMarkdownSpec: () => createBlockMarkdownSpec, createInlineMarkdownSpec: () => createInlineMarkdownSpec, parseAttributes: () => parseAttributes, parseIndentedBlocks: () => parseIndentedBlocks, renderNestedMarkdownContent: () => renderNestedMarkdownContent, serializeAttributes: () => serializeAttributes }); function parseAttributes(attrString) { if (!(attrString == null ? void 0 : attrString.trim())) { return {}; } const attributes = {}; const quotedStrings = []; const tempString = attrString.replace(/["']([^"']*)["']/g, (match2) => { quotedStrings.push(match2); return `__QUOTED_${quotedStrings.length - 1}__`; }); const classMatches = tempString.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g); if (classMatches) { const classes = classMatches.map((match2) => match2.trim().slice(1)); attributes.class = classes.join(" "); } const idMatch = tempString.match(/(?:^|\s)#([a-zA-Z][\w-]*)/); if (idMatch) { attributes.id = idMatch[1]; } const kvRegex = /([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g; const kvMatches = Array.from(tempString.matchAll(kvRegex)); kvMatches.forEach(([, key2, quotedRef]) => { var _a2; const quotedIndex = parseInt(((_a2 = quotedRef.match(/__QUOTED_(\d+)__/)) == null ? void 0 : _a2[1]) || "0", 10); const quotedValue = quotedStrings[quotedIndex]; if (quotedValue) { attributes[key2] = quotedValue.slice(1, -1); } }); const cleanString = tempString.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g, "").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g, "").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g, "").trim(); if (cleanString) { const booleanAttrs = cleanString.split(/\s+/).filter(Boolean); booleanAttrs.forEach((attr2) => { if (attr2.match(/^[a-zA-Z][\w-]*$/)) { attributes[attr2] = true; } }); } return attributes; } function serializeAttributes(attributes) { if (!attributes || Object.keys(attributes).length === 0) { return ""; } const parts = []; if (attributes.class) { const classes = String(attributes.class).split(/\s+/).filter(Boolean); classes.forEach((cls) => parts.push(`.${cls}`)); } if (attributes.id) { parts.push(`#${attributes.id}`); } Object.entries(attributes).forEach(([key2, value]) => { if (key2 === "class" || key2 === "id") { return; } if (value === true) { parts.push(key2); } else if (value !== false && value != null) { parts.push(`${key2}="${String(value)}"`); } }); return parts.join(" "); } function createAtomBlockMarkdownSpec(options2) { const { nodeName, name: markdownName, parseAttributes: parseAttributes2 = parseAttributes, serializeAttributes: serializeAttributes22 = serializeAttributes, defaultAttributes = {}, requiredAttributes = [], allowedAttributes } = options2; const blockName = markdownName || nodeName; const filterAttributes = (attrs) => { if (!allowedAttributes) { return attrs; } const filtered = {}; allowedAttributes.forEach((key2) => { if (key2 in attrs) { filtered[key2] = attrs[key2]; } }); return filtered; }; return { parseMarkdown: (token, h22) => { const attrs = { ...defaultAttributes, ...token.attributes }; return h22.createNode(nodeName, attrs, []); }, markdownTokenizer: { name: nodeName, level: "block", start(src) { var _a2; const regex = new RegExp(`^:::${blockName}(?:\\s|$)`, "m"); const index4 = (_a2 = src.match(regex)) == null ? void 0 : _a2.index; return index4 !== void 0 ? index4 : -1; }, tokenize(src, _tokens, _lexer) { const regex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`); const match2 = src.match(regex); if (!match2) { return void 0; } const attrString = match2[1] || ""; const attributes = parseAttributes2(attrString); const missingRequired = requiredAttributes.find((required) => !(required in attributes)); if (missingRequired) { return void 0; } return { type: nodeName, raw: match2[0], attributes }; } }, renderMarkdown: (node2) => { const filteredAttrs = filterAttributes(node2.attrs || {}); const attrs = serializeAttributes22(filteredAttrs); const attrString = attrs ? ` {${attrs}}` : ""; return `:::${blockName}${attrString} :::`; } }; } function createBlockMarkdownSpec(options2) { const { nodeName, name: markdownName, getContent, parseAttributes: parseAttributes2 = parseAttributes, serializeAttributes: serializeAttributes22 = serializeAttributes, defaultAttributes = {}, content: content5 = "block", allowedAttributes } = options2; const blockName = markdownName || nodeName; const filterAttributes = (attrs) => { if (!allowedAttributes) { return attrs; } const filtered = {}; allowedAttributes.forEach((key2) => { if (key2 in attrs) { filtered[key2] = attrs[key2]; } }); return filtered; }; return { parseMarkdown: (token, h22) => { let nodeContent; if (getContent) { const contentResult = getContent(token); nodeContent = typeof contentResult === "string" ? [{ type: "text", text: contentResult }] : contentResult; } else if (content5 === "block") { nodeContent = h22.parseChildren(token.tokens || []); } else { nodeContent = h22.parseInline(token.tokens || []); } const attrs = { ...defaultAttributes, ...token.attributes }; return h22.createNode(nodeName, attrs, nodeContent); }, markdownTokenizer: { name: nodeName, level: "block", start(src) { var _a2; const regex = new RegExp(`^:::${blockName}`, "m"); const index4 = (_a2 = src.match(regex)) == null ? void 0 : _a2.index; return index4 !== void 0 ? index4 : -1; }, tokenize(src, _tokens, lexer) { var _a2; const openingRegex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*\\n`); const openingMatch = src.match(openingRegex); if (!openingMatch) { return void 0; } const [openingTag, attrString = ""] = openingMatch; const attributes = parseAttributes2(attrString); let level = 1; const position4 = openingTag.length; let matchedContent = ""; const blockPattern = /^:::([\w-]*)(\s.*)?/gm; const remaining = src.slice(position4); blockPattern.lastIndex = 0; for (; ; ) { const match2 = blockPattern.exec(remaining); if (match2 === null) { break; } const matchPos = match2.index; const blockType = match2[1]; if ((_a2 = match2[2]) == null ? void 0 : _a2.endsWith(":::")) { continue; } if (blockType) { level += 1; } else { level -= 1; if (level === 0) { const rawContent = remaining.slice(0, matchPos); matchedContent = rawContent.trim(); const fullMatch = src.slice(0, position4 + matchPos + match2[0].length); let contentTokens = []; if (matchedContent) { if (content5 === "block") { contentTokens = lexer.blockTokens(rawContent); contentTokens.forEach((token) => { if (token.text && (!token.tokens || token.tokens.length === 0)) { token.tokens = lexer.inlineTokens(token.text); } }); while (contentTokens.length > 0) { const lastToken = contentTokens[contentTokens.length - 1]; if (lastToken.type === "paragraph" && (!lastToken.text || lastToken.text.trim() === "")) { contentTokens.pop(); } else { break; } } } else { contentTokens = lexer.inlineTokens(matchedContent); } } return { type: nodeName, raw: fullMatch, attributes, content: matchedContent, tokens: contentTokens }; } } } return void 0; } }, renderMarkdown: (node2, h22) => { const filteredAttrs = filterAttributes(node2.attrs || {}); const attrs = serializeAttributes22(filteredAttrs); const attrString = attrs ? ` {${attrs}}` : ""; const renderedContent = h22.renderChildren(node2.content || [], "\n\n"); return `:::${blockName}${attrString} ${renderedContent} :::`; } }; } function parseShortcodeAttributes(attrString) { if (!attrString.trim()) { return {}; } const attributes = {}; const regex = /(\w+)=(?:"([^"]*)"|'([^']*)')/g; let match2 = regex.exec(attrString); while (match2 !== null) { const [, key2, doubleQuoted, singleQuoted] = match2; attributes[key2] = doubleQuoted || singleQuoted; match2 = regex.exec(attrString); } return attributes; } function serializeShortcodeAttributes(attrs) { return Object.entries(attrs).filter(([, value]) => value !== void 0 && value !== null).map(([key2, value]) => `${key2}="${value}"`).join(" "); } function createInlineMarkdownSpec(options2) { const { nodeName, name: shortcodeName, getContent, parseAttributes: parseAttributes2 = parseShortcodeAttributes, serializeAttributes: serializeAttributes22 = serializeShortcodeAttributes, defaultAttributes = {}, selfClosing = false, allowedAttributes } = options2; const shortcode = shortcodeName || nodeName; const filterAttributes = (attrs) => { if (!allowedAttributes) { return attrs; } const filtered = {}; allowedAttributes.forEach((attr2) => { const attrName = typeof attr2 === "string" ? attr2 : attr2.name; const skipIfDefault = typeof attr2 === "string" ? void 0 : attr2.skipIfDefault; if (attrName in attrs) { const value = attrs[attrName]; if (skipIfDefault !== void 0 && value === skipIfDefault) { return; } filtered[attrName] = value; } }); return filtered; }; const escapedShortcode = shortcode.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); return { parseMarkdown: (token, h22) => { const attrs = { ...defaultAttributes, ...token.attributes }; if (selfClosing) { return h22.createNode(nodeName, attrs); } const content5 = getContent ? getContent(token) : token.content || ""; if (content5) { return h22.createNode(nodeName, attrs, [h22.createTextNode(content5)]); } return h22.createNode(nodeName, attrs, []); }, markdownTokenizer: { name: nodeName, level: "inline", start(src) { const startPattern = selfClosing ? new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\]`) : new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${escapedShortcode}\\]`); const match2 = src.match(startPattern); const index4 = match2 == null ? void 0 : match2.index; return index4 !== void 0 ? index4 : -1; }, tokenize(src, _tokens, _lexer) { const tokenPattern = selfClosing ? new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]`) : new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${escapedShortcode}\\]`); const match2 = src.match(tokenPattern); if (!match2) { return void 0; } let content5 = ""; let attrString = ""; if (selfClosing) { const [, attrs] = match2; attrString = attrs; } else { const [, attrs, contentMatch] = match2; attrString = attrs; content5 = contentMatch || ""; } const attributes = parseAttributes2(attrString.trim()); return { type: nodeName, raw: match2[0], content: content5.trim(), attributes }; } }, renderMarkdown: (node2) => { let content5 = ""; if (getContent) { content5 = getContent(node2); } else if (node2.content && node2.content.length > 0) { content5 = node2.content.filter((child) => child.type === "text").map((child) => child.text).join(""); } const filteredAttrs = filterAttributes(node2.attrs || {}); const attrs = serializeAttributes22(filteredAttrs); const attrString = attrs ? ` ${attrs}` : ""; if (selfClosing) { return `[${shortcode}${attrString}]`; } return `[${shortcode}${attrString}]${content5}[/${shortcode}]`; } }; } function parseIndentedBlocks(src, config, lexer) { var _a2, _b, _c, _d; const lines = src.split("\n"); const items = []; let totalRaw = ""; let i3 = 0; const baseIndentSize = config.baseIndentSize || 2; while (i3 < lines.length) { const currentLine = lines[i3]; const itemMatch = currentLine.match(config.itemPattern); if (!itemMatch) { if (items.length > 0) { break; } else if (currentLine.trim() === "") { i3 += 1; totalRaw = `${totalRaw}${currentLine} `; continue; } else { return void 0; } } const itemData = config.extractItemData(itemMatch); const { indentLevel, mainContent } = itemData; totalRaw = `${totalRaw}${currentLine} `; const itemContent = [mainContent]; i3 += 1; while (i3 < lines.length) { const nextLine = lines[i3]; if (nextLine.trim() === "") { const nextNonEmptyIndex = lines.slice(i3 + 1).findIndex((l2) => l2.trim() !== ""); if (nextNonEmptyIndex === -1) { break; } const nextNonEmpty = lines[i3 + 1 + nextNonEmptyIndex]; const nextIndent2 = ((_b = (_a2 = nextNonEmpty.match(/^(\s*)/)) == null ? void 0 : _a2[1]) == null ? void 0 : _b.length) || 0; if (nextIndent2 > indentLevel) { itemContent.push(nextLine); totalRaw = `${totalRaw}${nextLine} `; i3 += 1; continue; } else { break; } } const nextIndent = ((_d = (_c = nextLine.match(/^(\s*)/)) == null ? void 0 : _c[1]) == null ? void 0 : _d.length) || 0; if (nextIndent > indentLevel) { itemContent.push(nextLine); totalRaw = `${totalRaw}${nextLine} `; i3 += 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 void 0; } return { items, raw: totalRaw }; } function renderNestedMarkdownContent(node2, h22, prefixOrGenerator, ctx) { if (!node2 || !Array.isArray(node2.content)) { return ""; } const prefix3 = typeof prefixOrGenerator === "function" ? prefixOrGenerator(ctx) : prefixOrGenerator; const [content5, ...children] = node2.content; const mainContent = h22.renderChildren([content5]); const output = [`${prefix3}${mainContent}`]; if (children && children.length > 0) { children.forEach((child) => { const childContent = h22.renderChildren([child]); if (childContent) { const indentedChild = childContent.split("\n").map((line) => line ? h22.indent(line) : "").join("\n"); output.push(indentedChild); } }); } return output.join("\n"); } function updateMarkViewAttributes(checkMark, editor, attrs = {}) { const { state } = editor; const { doc: doc4, tr: tr4 } = state; const thisMark = checkMark; doc4.descendants((node2, pos) => { const from4 = tr4.mapping.map(pos); const to2 = tr4.mapping.map(pos) + node2.nodeSize; let foundMark = null; node2.marks.forEach((mark2) => { if (mark2 !== thisMark) { return false; } foundMark = mark2; }); if (!foundMark) { return; } let needsUpdate = false; Object.keys(attrs).forEach((k3) => { if (attrs[k3] !== foundMark.attrs[k3]) { needsUpdate = true; } }); if (needsUpdate) { const updatedMark = checkMark.type.create({ ...checkMark.attrs, ...attrs }); tr4.removeMark(from4, to2, checkMark.type); tr4.addMark(from4, to2, updatedMark); } }); if (tr4.docChanged) { editor.view.dispatch(tr4); } } var MarkView = class { constructor(component, props, options2) { this.component = component; this.editor = props.editor; this.options = { ...options2 }; this.mark = props.mark; this.HTMLAttributes = props.HTMLAttributes; } get dom() { return this.editor.view.dom; } get contentDOM() { return null; } /** * Update the attributes of the mark in the document. * @param attrs The attributes to update. */ updateAttributes(attrs, checkMark) { updateMarkViewAttributes(checkMark || this.mark, this.editor, attrs); } ignoreMutation(mutation) { if (!this.dom || !this.contentDOM) { return true; } if (typeof this.options.ignoreMutation === "function") { return this.options.ignoreMutation({ mutation }); } if (mutation.type === "selection") { return false; } if (this.dom.contains(mutation.target) && mutation.type === "childList" && (isiOS() || isAndroid()) && this.editor.isFocused) { const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)]; if (changedNodes.every((node2) => node2.isContentEditable)) { return false; } } if (this.contentDOM === mutation.target && mutation.type === "attributes") { return true; } if (this.contentDOM.contains(mutation.target)) { return false; } return true; } }; var Node3 = class _Node extends Extendable { constructor() { super(...arguments); 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 _Node(resolvedConfig); } configure(options2) { return super.configure(options2); } extend(extendedConfig) { const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; return super.extend(resolvedConfig); } }; var NodeView = class { constructor(component, props, options2) { this.isDragging = false; this.component = component; this.editor = props.editor; this.options = { stopEvent: null, ignoreMutation: null, ...options2 }; 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 = props.getPos; this.mount(); } mount() { return; } get dom() { return this.editor.view.dom; } get contentDOM() { return null; } onDragStart(event) { var _a2, _b, _c, _d, _e4, _f, _g; const { view } = this.editor; const target = event.target; const dragHandle = target.nodeType === 3 ? (_a2 = target.parentElement) == null ? void 0 : _a2.closest("[data-drag-handle]") : target.closest("[data-drag-handle]"); if (!this.dom || ((_b = this.contentDOM) == null ? void 0 : _b.contains(target)) || !dragHandle) { return; } let x5 = 0; let y3 = 0; if (this.dom !== dragHandle) { const domBox = this.dom.getBoundingClientRect(); const handleBox = dragHandle.getBoundingClientRect(); const offsetX = (_d = event.offsetX) != null ? _d : (_c = event.nativeEvent) == null ? void 0 : _c.offsetX; const offsetY = (_f = event.offsetY) != null ? _f : (_e4 = event.nativeEvent) == null ? void 0 : _e4.offsetY; x5 = handleBox.x - domBox.x + offsetX; y3 = 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 { 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); (_g = event.dataTransfer) == null ? void 0 : _g.setDragImage(clonedNode, x5, y3); } finally { if (dragImageWrapper) { setTimeout(() => { try { dragImageWrapper == null ? 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 _a2; if (!this.dom) { return false; } if (typeof this.options.stopEvent === "function") { return this.options.stopEvent({ event }); } const target = event.target; const isInElement = this.dom.contains(target) && !((_a2 = this.contentDOM) == null ? void 0 : _a2.contains(target)); if (!isInElement) { return false; } const isDragEvent = event.type.startsWith("drag"); const isDropEvent = event.type === "drop"; const isInput = ["INPUT", "BUTTON", "SELECT", "TEXTAREA"].includes(target.tagName) || target.isContentEditable; if (isInput && !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]"); const isValidDragHandle = dragHandle && (this.dom === dragHandle || this.dom.contains(dragHandle)); if (isValidDragHandle) { 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 || 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.dom.contains(mutation.target) && mutation.type === "childList" && (isiOS() || isAndroid()) && this.editor.isFocused) { const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)]; if (changedNodes.every((node2) => node2.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: tr4 }) => { const pos = this.getPos(); if (typeof pos !== "number") { return false; } tr4.setNodeMarkup(pos, void 0, { ...this.node.attrs, ...attributes }); return true; }); } /** * Delete the node. */ deleteNode() { const from4 = this.getPos(); if (typeof from4 !== "number") { return; } const to2 = from4 + this.node.nodeSize; this.editor.commands.deleteRange({ from: from4, to: to2 }); } }; function markPasteRule(config) { return new PasteRule({ find: config.find, handler: ({ state, range, match: match2, pasteEvent }) => { const attributes = callOrReturn(config.getAttributes, void 0, match2, pasteEvent); if (attributes === false || attributes === null) { return null; } const { tr: tr4 } = state; const captureGroup = match2[match2.length - 1]; const fullMatch = match2[0]; let markEnd = range.to; if (captureGroup) { const startSpaces = fullMatch.search(/\S/); const textStart = range.from + fullMatch.indexOf(captureGroup); const textEnd = textStart + captureGroup.length; const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => { const excluded = item.mark.type.excluded; return excluded.find((type) => type === config.type && type !== item.mark.type); }).filter((item) => item.to > textStart); if (excludedMarks.length) { return null; } if (textEnd < range.to) { tr4.delete(textEnd, range.to); } if (textStart > range.from) { tr4.delete(range.from + startSpaces, textStart); } markEnd = range.from + startSpaces + captureGroup.length; tr4.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); tr4.removeStoredMark(config.type); } } }); } // ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/EventEmitter-CjSwpTbz.js var h = Object.defineProperty; var b = (a3, s2, l2) => s2 in a3 ? h(a3, s2, { enumerable: true, configurable: true, writable: true, value: l2 }) : a3[s2] = l2; var t = (a3, s2, l2) => b(a3, typeof s2 != "symbol" ? s2 + "" : s2, l2); var f3 = class { constructor() { t(this, "callbacks", {}); } on(s2, l2) { return this.callbacks[s2] || (this.callbacks[s2] = []), this.callbacks[s2].push(l2), () => this.off(s2, l2); } emit(s2, ...l2) { const c3 = this.callbacks[s2]; c3 && c3.forEach((i3) => i3.apply(this, l2)); } off(s2, l2) { const c3 = this.callbacks[s2]; c3 && (l2 ? this.callbacks[s2] = c3.filter((i3) => i3 !== l2) : delete this.callbacks[s2]); } removeAllListeners() { this.callbacks = {}; } }; // ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/rng.js var getRandomValues2; var rnds8 = new Uint8Array(16); function rng() { if (!getRandomValues2) { getRandomValues2 = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== "undefined" && typeof msCrypto.getRandomValues === "function" && msCrypto.getRandomValues.bind(msCrypto); if (!getRandomValues2) { throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); } } return getRandomValues2(rnds8); } // ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/regex.js var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; // ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/validate.js function validate(uuid) { return typeof uuid === "string" && regex_default.test(uuid); } var validate_default = validate; // ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/stringify.js var byteToHex = []; for (i3 = 0; i3 < 256; ++i3) { byteToHex.push((i3 + 256).toString(16).substr(1)); } var i3; function stringify2(arr) { var offset4 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0; var uuid = (byteToHex[arr[offset4 + 0]] + byteToHex[arr[offset4 + 1]] + byteToHex[arr[offset4 + 2]] + byteToHex[arr[offset4 + 3]] + "-" + byteToHex[arr[offset4 + 4]] + byteToHex[arr[offset4 + 5]] + "-" + byteToHex[arr[offset4 + 6]] + byteToHex[arr[offset4 + 7]] + "-" + byteToHex[arr[offset4 + 8]] + byteToHex[arr[offset4 + 9]] + "-" + byteToHex[arr[offset4 + 10]] + byteToHex[arr[offset4 + 11]] + byteToHex[arr[offset4 + 12]] + byteToHex[arr[offset4 + 13]] + byteToHex[arr[offset4 + 14]] + byteToHex[arr[offset4 + 15]]).toLowerCase(); if (!validate_default(uuid)) { throw TypeError("Stringified UUID is invalid"); } return uuid; } var stringify_default = stringify2; // ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/parse.js function parse(uuid) { if (!validate_default(uuid)) { throw TypeError("Invalid UUID"); } var v8; var arr = new Uint8Array(16); arr[0] = (v8 = parseInt(uuid.slice(0, 8), 16)) >>> 24; arr[1] = v8 >>> 16 & 255; arr[2] = v8 >>> 8 & 255; arr[3] = v8 & 255; arr[4] = (v8 = parseInt(uuid.slice(9, 13), 16)) >>> 8; arr[5] = v8 & 255; arr[6] = (v8 = parseInt(uuid.slice(14, 18), 16)) >>> 8; arr[7] = v8 & 255; arr[8] = (v8 = parseInt(uuid.slice(19, 23), 16)) >>> 8; arr[9] = v8 & 255; arr[10] = (v8 = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255; arr[11] = v8 / 4294967296 & 255; arr[12] = v8 >>> 24 & 255; arr[13] = v8 >>> 16 & 255; arr[14] = v8 >>> 8 & 255; arr[15] = v8 & 255; return arr; } var parse_default = parse; // ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/v35.js function stringToBytes(str) { str = unescape(encodeURIComponent(str)); var bytes = []; for (var i3 = 0; i3 < str.length; ++i3) { bytes.push(str.charCodeAt(i3)); } return bytes; } var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; var URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; function v35_default(name, version, hashfunc) { function generateUUID(value, namespace, buf, offset4) { if (typeof value === "string") { value = stringToBytes(value); } if (typeof namespace === "string") { namespace = parse_default(namespace); } if (namespace.length !== 16) { throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)"); } var bytes = new Uint8Array(16 + value.length); bytes.set(namespace); bytes.set(value, namespace.length); bytes = hashfunc(bytes); bytes[6] = bytes[6] & 15 | version; bytes[8] = bytes[8] & 63 | 128; if (buf) { offset4 = offset4 || 0; for (var i3 = 0; i3 < 16; ++i3) { buf[offset4 + i3] = bytes[i3]; } return buf; } return stringify_default(bytes); } try { generateUUID.name = name; } catch (err) { } generateUUID.DNS = DNS; generateUUID.URL = URL2; return generateUUID; } // ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/md5.js function md5(bytes) { if (typeof bytes === "string") { var msg = unescape(encodeURIComponent(bytes)); bytes = new Uint8Array(msg.length); for (var i3 = 0; i3 < msg.length; ++i3) { bytes[i3] = msg.charCodeAt(i3); } } return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); } function md5ToHexEncodedArray(input2) { var output = []; var length32 = input2.length * 32; var hexTab = "0123456789abcdef"; for (var i3 = 0; i3 < length32; i3 += 8) { var x5 = input2[i3 >> 5] >>> i3 % 32 & 255; var hex = parseInt(hexTab.charAt(x5 >>> 4 & 15) + hexTab.charAt(x5 & 15), 16); output.push(hex); } return output; } function getOutputLength(inputLength8) { return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; } function wordsToMd5(x5, len) { x5[len >> 5] |= 128 << len % 32; x5[getOutputLength(len) - 1] = len; var a3 = 1732584193; var b4 = -271733879; var c3 = -1732584194; var d = 271733878; for (var i3 = 0; i3 < x5.length; i3 += 16) { var olda = a3; var oldb = b4; var oldc = c3; var oldd = d; a3 = md5ff(a3, b4, c3, d, x5[i3], 7, -680876936); d = md5ff(d, a3, b4, c3, x5[i3 + 1], 12, -389564586); c3 = md5ff(c3, d, a3, b4, x5[i3 + 2], 17, 606105819); b4 = md5ff(b4, c3, d, a3, x5[i3 + 3], 22, -1044525330); a3 = md5ff(a3, b4, c3, d, x5[i3 + 4], 7, -176418897); d = md5ff(d, a3, b4, c3, x5[i3 + 5], 12, 1200080426); c3 = md5ff(c3, d, a3, b4, x5[i3 + 6], 17, -1473231341); b4 = md5ff(b4, c3, d, a3, x5[i3 + 7], 22, -45705983); a3 = md5ff(a3, b4, c3, d, x5[i3 + 8], 7, 1770035416); d = md5ff(d, a3, b4, c3, x5[i3 + 9], 12, -1958414417); c3 = md5ff(c3, d, a3, b4, x5[i3 + 10], 17, -42063); b4 = md5ff(b4, c3, d, a3, x5[i3 + 11], 22, -1990404162); a3 = md5ff(a3, b4, c3, d, x5[i3 + 12], 7, 1804603682); d = md5ff(d, a3, b4, c3, x5[i3 + 13], 12, -40341101); c3 = md5ff(c3, d, a3, b4, x5[i3 + 14], 17, -1502002290); b4 = md5ff(b4, c3, d, a3, x5[i3 + 15], 22, 1236535329); a3 = md5gg(a3, b4, c3, d, x5[i3 + 1], 5, -165796510); d = md5gg(d, a3, b4, c3, x5[i3 + 6], 9, -1069501632); c3 = md5gg(c3, d, a3, b4, x5[i3 + 11], 14, 643717713); b4 = md5gg(b4, c3, d, a3, x5[i3], 20, -373897302); a3 = md5gg(a3, b4, c3, d, x5[i3 + 5], 5, -701558691); d = md5gg(d, a3, b4, c3, x5[i3 + 10], 9, 38016083); c3 = md5gg(c3, d, a3, b4, x5[i3 + 15], 14, -660478335); b4 = md5gg(b4, c3, d, a3, x5[i3 + 4], 20, -405537848); a3 = md5gg(a3, b4, c3, d, x5[i3 + 9], 5, 568446438); d = md5gg(d, a3, b4, c3, x5[i3 + 14], 9, -1019803690); c3 = md5gg(c3, d, a3, b4, x5[i3 + 3], 14, -187363961); b4 = md5gg(b4, c3, d, a3, x5[i3 + 8], 20, 1163531501); a3 = md5gg(a3, b4, c3, d, x5[i3 + 13], 5, -1444681467); d = md5gg(d, a3, b4, c3, x5[i3 + 2], 9, -51403784); c3 = md5gg(c3, d, a3, b4, x5[i3 + 7], 14, 1735328473); b4 = md5gg(b4, c3, d, a3, x5[i3 + 12], 20, -1926607734); a3 = md5hh(a3, b4, c3, d, x5[i3 + 5], 4, -378558); d = md5hh(d, a3, b4, c3, x5[i3 + 8], 11, -2022574463); c3 = md5hh(c3, d, a3, b4, x5[i3 + 11], 16, 1839030562); b4 = md5hh(b4, c3, d, a3, x5[i3 + 14], 23, -35309556); a3 = md5hh(a3, b4, c3, d, x5[i3 + 1], 4, -1530992060); d = md5hh(d, a3, b4, c3, x5[i3 + 4], 11, 1272893353); c3 = md5hh(c3, d, a3, b4, x5[i3 + 7], 16, -155497632); b4 = md5hh(b4, c3, d, a3, x5[i3 + 10], 23, -1094730640); a3 = md5hh(a3, b4, c3, d, x5[i3 + 13], 4, 681279174); d = md5hh(d, a3, b4, c3, x5[i3], 11, -358537222); c3 = md5hh(c3, d, a3, b4, x5[i3 + 3], 16, -722521979); b4 = md5hh(b4, c3, d, a3, x5[i3 + 6], 23, 76029189); a3 = md5hh(a3, b4, c3, d, x5[i3 + 9], 4, -640364487); d = md5hh(d, a3, b4, c3, x5[i3 + 12], 11, -421815835); c3 = md5hh(c3, d, a3, b4, x5[i3 + 15], 16, 530742520); b4 = md5hh(b4, c3, d, a3, x5[i3 + 2], 23, -995338651); a3 = md5ii(a3, b4, c3, d, x5[i3], 6, -198630844); d = md5ii(d, a3, b4, c3, x5[i3 + 7], 10, 1126891415); c3 = md5ii(c3, d, a3, b4, x5[i3 + 14], 15, -1416354905); b4 = md5ii(b4, c3, d, a3, x5[i3 + 5], 21, -57434055); a3 = md5ii(a3, b4, c3, d, x5[i3 + 12], 6, 1700485571); d = md5ii(d, a3, b4, c3, x5[i3 + 3], 10, -1894986606); c3 = md5ii(c3, d, a3, b4, x5[i3 + 10], 15, -1051523); b4 = md5ii(b4, c3, d, a3, x5[i3 + 1], 21, -2054922799); a3 = md5ii(a3, b4, c3, d, x5[i3 + 8], 6, 1873313359); d = md5ii(d, a3, b4, c3, x5[i3 + 15], 10, -30611744); c3 = md5ii(c3, d, a3, b4, x5[i3 + 6], 15, -1560198380); b4 = md5ii(b4, c3, d, a3, x5[i3 + 13], 21, 1309151649); a3 = md5ii(a3, b4, c3, d, x5[i3 + 4], 6, -145523070); d = md5ii(d, a3, b4, c3, x5[i3 + 11], 10, -1120210379); c3 = md5ii(c3, d, a3, b4, x5[i3 + 2], 15, 718787259); b4 = md5ii(b4, c3, d, a3, x5[i3 + 9], 21, -343485551); a3 = safeAdd(a3, olda); b4 = safeAdd(b4, oldb); c3 = safeAdd(c3, oldc); d = safeAdd(d, oldd); } return [a3, b4, c3, d]; } function bytesToWords(input2) { if (input2.length === 0) { return []; } var length8 = input2.length * 8; var output = new Uint32Array(getOutputLength(length8)); for (var i3 = 0; i3 < length8; i3 += 8) { output[i3 >> 5] |= (input2[i3 / 8] & 255) << i3 % 32; } return output; } function safeAdd(x5, y3) { var lsw = (x5 & 65535) + (y3 & 65535); var msw = (x5 >> 16) + (y3 >> 16) + (lsw >> 16); return msw << 16 | lsw & 65535; } function bitRotateLeft(num, cnt) { return num << cnt | num >>> 32 - cnt; } function md5cmn(q4, a3, b4, x5, s2, t2) { return safeAdd(bitRotateLeft(safeAdd(safeAdd(a3, q4), safeAdd(x5, t2)), s2), b4); } function md5ff(a3, b4, c3, d, x5, s2, t2) { return md5cmn(b4 & c3 | ~b4 & d, a3, b4, x5, s2, t2); } function md5gg(a3, b4, c3, d, x5, s2, t2) { return md5cmn(b4 & d | c3 & ~d, a3, b4, x5, s2, t2); } function md5hh(a3, b4, c3, d, x5, s2, t2) { return md5cmn(b4 ^ c3 ^ d, a3, b4, x5, s2, t2); } function md5ii(a3, b4, c3, d, x5, s2, t2) { return md5cmn(c3 ^ (b4 | ~d), a3, b4, x5, s2, t2); } var md5_default = md5; // ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/v3.js var v3 = v35_default("v3", 48, md5_default); // ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/v4.js function v4(options2, buf, offset4) { options2 = options2 || {}; var rnds = options2.random || (options2.rng || rng)(); rnds[6] = rnds[6] & 15 | 64; rnds[8] = rnds[8] & 63 | 128; if (buf) { offset4 = offset4 || 0; for (var i3 = 0; i3 < 16; ++i3) { buf[offset4 + i3] = rnds[i3]; } return buf; } return stringify_default(rnds); } var v4_default = v4; // ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/sha1.js function f4(s2, x5, y3, z2) { switch (s2) { case 0: return x5 & y3 ^ ~x5 & z2; case 1: return x5 ^ y3 ^ z2; case 2: return x5 & y3 ^ x5 & z2 ^ y3 & z2; case 3: return x5 ^ y3 ^ z2; } } function ROTL(x5, n) { return x5 << n | x5 >>> 32 - n; } function sha1(bytes) { var K6 = [1518500249, 1859775393, 2400959708, 3395469782]; var H4 = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]; if (typeof bytes === "string") { var msg = unescape(encodeURIComponent(bytes)); bytes = []; for (var i3 = 0; i3 < msg.length; ++i3) { bytes.push(msg.charCodeAt(i3)); } } else if (!Array.isArray(bytes)) { bytes = Array.prototype.slice.call(bytes); } bytes.push(128); var l2 = bytes.length / 4 + 2; var N3 = Math.ceil(l2 / 16); var M7 = new Array(N3); for (var _i2 = 0; _i2 < N3; ++_i2) { var arr = new Uint32Array(16); for (var j4 = 0; j4 < 16; ++j4) { arr[j4] = bytes[_i2 * 64 + j4 * 4] << 24 | bytes[_i2 * 64 + j4 * 4 + 1] << 16 | bytes[_i2 * 64 + j4 * 4 + 2] << 8 | bytes[_i2 * 64 + j4 * 4 + 3]; } M7[_i2] = arr; } M7[N3 - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); M7[N3 - 1][14] = Math.floor(M7[N3 - 1][14]); M7[N3 - 1][15] = (bytes.length - 1) * 8 & 4294967295; for (var _i22 = 0; _i22 < N3; ++_i22) { var W3 = new Uint32Array(80); for (var t2 = 0; t2 < 16; ++t2) { W3[t2] = M7[_i22][t2]; } for (var _t6 = 16; _t6 < 80; ++_t6) { W3[_t6] = ROTL(W3[_t6 - 3] ^ W3[_t6 - 8] ^ W3[_t6 - 14] ^ W3[_t6 - 16], 1); } var a3 = H4[0]; var b4 = H4[1]; var c3 = H4[2]; var d = H4[3]; var e2 = H4[4]; for (var _t22 = 0; _t22 < 80; ++_t22) { var s2 = Math.floor(_t22 / 20); var T4 = ROTL(a3, 5) + f4(s2, b4, c3, d) + e2 + K6[s2] + W3[_t22] >>> 0; e2 = d; d = c3; c3 = ROTL(b4, 30) >>> 0; b4 = a3; a3 = T4; } H4[0] = H4[0] + a3 >>> 0; H4[1] = H4[1] + b4 >>> 0; H4[2] = H4[2] + c3 >>> 0; H4[3] = H4[3] + d >>> 0; H4[4] = H4[4] + e2 >>> 0; } return [H4[0] >> 24 & 255, H4[0] >> 16 & 255, H4[0] >> 8 & 255, H4[0] & 255, H4[1] >> 24 & 255, H4[1] >> 16 & 255, H4[1] >> 8 & 255, H4[1] & 255, H4[2] >> 24 & 255, H4[2] >> 16 & 255, H4[2] >> 8 & 255, H4[2] & 255, H4[3] >> 24 & 255, H4[3] >> 16 & 255, H4[3] >> 8 & 255, H4[3] & 255, H4[4] >> 24 & 255, H4[4] >> 16 & 255, H4[4] >> 8 & 255, H4[4] & 255]; } var sha1_default = sha1; // ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/v5.js var v5 = v35_default("v5", 80, sha1_default); // ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/comments.js var x = Object.defineProperty; var Y = (r4, d, e2) => d in r4 ? x(r4, d, { enumerable: true, configurable: true, writable: true, value: e2 }) : r4[d] = e2; var c = (r4, d, e2) => Y(r4, typeof d != "symbol" ? d + "" : d, e2); var M = Mark2.create({ name: "comment", excludes: "", inclusive: false, keepOnSplit: true, addAttributes() { return { // orphans are marks that currently don't have an active thread. It could be // that users have resolved the thread. Resolved threads by default are not shown in the document, // but we need to keep the mark (positioning) data so we can still "revive" it when the thread is unresolved // or we enter a "comments" view that includes resolved threads. orphan: { parseHTML: (r4) => !!r4.getAttribute("data-orphan"), renderHTML: (r4) => r4.orphan ? { "data-orphan": "true" } : {}, default: false }, threadId: { parseHTML: (r4) => r4.getAttribute("data-bn-thread-id"), renderHTML: (r4) => ({ "data-bn-thread-id": r4.threadId }), default: "" } }; }, renderHTML({ HTMLAttributes: r4 }) { return [ "span", mergeAttributes(r4, { class: "bn-thread-mark" }) ]; }, parseHTML() { return [{ tag: "span.bn-thread-mark" }]; }, extendMarkSchema(r4) { return r4.name === "comment" ? { blocknoteIgnore: true } : {}; } }); var F = class extends f3 { constructor(e2) { super(); c(this, "userCache", /* @__PURE__ */ new Map()); c(this, "loadingUsers", /* @__PURE__ */ new Set()); this.resolveUsers = e2; } /** * Load information about users based on an array of user ids. */ async loadUsers(e2) { const t2 = e2.filter( (a3) => !this.userCache.has(a3) && !this.loadingUsers.has(a3) ); if (t2.length !== 0) { for (const a3 of t2) this.loadingUsers.add(a3); try { const a3 = await this.resolveUsers(t2); for (const s2 of a3) this.userCache.set(s2.id, s2); this.emit("update", this.userCache); } finally { for (const a3 of t2) this.loadingUsers.delete(a3); } } } /** * Retrieve information about a user based on their id, if cached. * * The user will have to be loaded via `loadUsers` first */ getUser(e2) { return this.userCache.get(e2); } /** * Subscribe to changes in the user store. * * @param cb - The callback to call when the user store changes. * @returns A function to unsubscribe from the user store. */ subscribe(e2) { return this.on("update", e2); } }; var w = new PluginKey("blocknote-comments"); function K2(r4, d) { const e2 = /* @__PURE__ */ new Map(); return r4.descendants((t2, a3) => { t2.marks.forEach((s2) => { if (s2.type.name === d) { const o2 = s2.attrs.threadId; if (!o2) return; const m2 = a3, n = m2 + t2.nodeSize, i3 = e2.get(o2) ?? { from: 1 / 0, to: 0 }; e2.set(o2, { from: Math.min(m2, i3.from), to: Math.max(n, i3.to) }); } }); }), e2; } var ne = a( ({ editor: r4, options: { schema: d, threadStore: e2, resolveUsers: t2 } }) => { if (!t2) throw new Error( "resolveUsers is required to be defined when using comments" ); if (!e2) throw new Error( "threadStore is required to be defined when using comments" ); const a3 = M.name, s2 = new F(t2), o2 = f( { pendingComment: false, selectedThreadId: void 0, threadPositions: /* @__PURE__ */ new Map() }, { onUpdate() { o2.state.selectedThreadId !== o2.prevState.selectedThreadId && r4.transact((n) => n.setMeta(w, true)); } } ), m2 = (n) => { r4.transact((i3) => { i3.doc.descendants((u2, l2) => { u2.marks.forEach((h7) => { if (h7.type.name === a3) { const T4 = h7.type, f6 = h7.attrs.threadId, A4 = n.get(f6), v8 = !!(!A4 || A4.resolved || A4.deletedAt); if (v8 !== h7.attrs.orphan) { const E4 = Math.max(l2, 0), b4 = Math.min( l2 + u2.nodeSize, i3.doc.content.size - 1, i3.doc.content.size - 1 ); i3.removeMark(E4, b4, h7), i3.addMark( E4, b4, T4.create({ ...h7.attrs, orphan: v8 }) ), v8 && o2.state.selectedThreadId === f6 && o2.setState((P4) => ({ ...P4, selectedThreadId: void 0 })); } } }); }); }); }; return { key: "comments", store: o2, prosemirrorPlugins: [ new Plugin({ key: w, state: { init() { return { decorations: DecorationSet.empty }; }, apply(n, i3) { const u2 = n.getMeta(w); if (!n.docChanged && !u2) return i3; const l2 = n.docChanged ? K2(n.doc, a3) : o2.state.threadPositions; (l2.size > 0 || o2.state.threadPositions.size > 0) && o2.setState((T4) => ({ ...T4, threadPositions: l2 })); const h7 = []; if (o2.state.selectedThreadId) { const T4 = l2.get( o2.state.selectedThreadId ); T4 && h7.push( Decoration.inline( T4.from, T4.to, { class: "bn-thread-mark-selected" } ) ); } return { decorations: DecorationSet.create(n.doc, h7) }; } }, props: { decorations(n) { var i3; return ((i3 = w.getState(n)) == null ? void 0 : i3.decorations) ?? DecorationSet.empty; }, handleClick: (n, i3, u2) => { if (u2.button !== 0) return; const l2 = n.state.doc.nodeAt(i3); if (!l2) { o2.setState((f6) => ({ ...f6, selectedThreadId: void 0 })); return; } const h7 = l2.marks.find( (f6) => f6.type.name === a3 && f6.attrs.orphan !== true ), T4 = h7 == null ? void 0 : h7.attrs.threadId; T4 !== o2.state.selectedThreadId && o2.setState((f6) => ({ ...f6, selectedThreadId: T4 })); } } }) ], threadStore: e2, mount() { const n = e2.subscribe(m2); m2(e2.getThreads()); const i3 = r4.onSelectionChange(() => { o2.state.pendingComment && o2.setState((u2) => ({ ...u2, pendingComment: false })); }); return () => { n(), i3(); }; }, selectThread(n, i3 = true) { var u2, l2; if (o2.state.selectedThreadId !== n && (o2.setState((h7) => ({ ...h7, pendingComment: false, selectedThreadId: n })), n && i3)) { const h7 = o2.state.threadPositions.get(n); if (!h7) return; (l2 = (u2 = r4.prosemirrorView) == null ? void 0 : u2.domAtPos(h7.from).node) == null || l2.scrollIntoView({ behavior: "smooth", block: "center" }); } }, startPendingComment() { var n; o2.setState((i3) => ({ ...i3, selectedThreadId: void 0, pendingComment: true })), (n = r4.getExtension(f2)) == null || n.showSelection(true); }, stopPendingComment() { var n; o2.setState((i3) => ({ ...i3, selectedThreadId: void 0, pendingComment: false })), (n = r4.getExtension(f2)) == null || n.showSelection(false); }, async createThread(n) { const i3 = await e2.createThread(n); if (e2.addThreadToDocument) { const u2 = r4.prosemirrorView, l2 = u2.state.selection, h7 = ySyncPluginKey.getState(u2.state), T4 = { prosemirror: { head: l2.head, anchor: l2.anchor }, yjs: h7 ? getRelativeSelection(h7.binding, u2.state) : void 0 }; await e2.addThreadToDocument({ threadId: i3.id, selection: T4 }); } else r4._tiptapEditor.commands.setMark(a3, { orphan: false, threadId: i3.id }); }, userStore: s2, commentEditorSchema: d, tiptapExtensions: [M] }; } ); // ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/TrailingNode-8cXFaQUm.js var import_fast_deep_equal = __toESM(require_fast_deep_equal(), 1); // ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/blockToNode-BNoNIXU7.js function pt(t2, o2 = JSON.stringify) { const r4 = {}; return t2.filter((n) => { const e2 = o2(n); return Object.prototype.hasOwnProperty.call(r4, e2) ? false : r4[e2] = true; }); } function dt(t2) { const o2 = t2.filter( (n, e2) => t2.indexOf(n) !== e2 ); return pt(o2); } var Q = Extension.create({ name: "uniqueID", // we’ll set a very high priority to make sure this runs first // and is compatible with `appendTransaction` hooks of other extensions priority: 1e4, addOptions() { return { attributeName: "id", types: [], setIdAttribute: false, generateID: () => { if (typeof window < "u" && window.__TEST_OPTIONS) { const t2 = window.__TEST_OPTIONS; return t2.mockID === void 0 ? t2.mockID = 0 : t2.mockID++, t2.mockID.toString(); } return v4_default(); }, filterTransaction: null }; }, addGlobalAttributes() { return [ { types: this.options.types, attributes: { [this.options.attributeName]: { default: null, parseHTML: (t2) => t2.getAttribute(`data-${this.options.attributeName}`), renderHTML: (t2) => { const o2 = { [`data-${this.options.attributeName}`]: t2[this.options.attributeName] }; return this.options.setIdAttribute ? { ...o2, id: t2[this.options.attributeName] } : o2; } } } } ]; }, // check initial content for missing ids // onCreate() { // // Don’t do this when the collaboration extension is active // // because this may update the content, so Y.js tries to merge these changes. // // This leads to empty block nodes. // // See: https://github.com/ueberdosis/tiptap/issues/2400 // if ( // this.editor.extensionManager.extensions.find( // (extension) => extension.name === "collaboration" // ) // ) { // return; // } // const { view, state } = this.editor; // const { tr, doc } = state; // const { types, attributeName, generateID } = this.options; // const nodesWithoutId = findChildren(doc, (node) => { // return ( // types.includes(node.type.name) && node.attrs[attributeName] === null // ); // }); // nodesWithoutId.forEach(({ node, pos }) => { // tr.setNodeMarkup(pos, undefined, { // ...node.attrs, // [attributeName]: generateID(), // }); // }); // tr.setMeta("addToHistory", false); // view.dispatch(tr); // }, addProseMirrorPlugins() { let t2 = null, o2 = false; return [ new Plugin({ key: new PluginKey("uniqueID"), appendTransaction: (r4, n, e2) => { const s2 = r4.some((g) => g.docChanged) && !n.doc.eq(e2.doc), i3 = this.options.filterTransaction && r4.some((g) => { var C3, d; return !((d = (C3 = this.options).filterTransaction) != null && d.call(C3, g)); }); if (!s2 || i3) return; const { tr: l2 } = e2, { types: a3, attributeName: c3, generateID: h7 } = this.options, f6 = combineTransactionSteps( n.doc, r4 ), { mapping: p4 } = f6; if (getChangedRanges(f6).forEach(({ newRange: g }) => { const C3 = findChildrenInRange( e2.doc, g, (y3) => a3.includes(y3.type.name) ), d = C3.map(({ node: y3 }) => y3.attrs[c3]).filter((y3) => y3 !== null), w3 = dt(d); C3.forEach(({ node: y3, pos: m2 }) => { var z2; const b4 = (z2 = l2.doc.nodeAt(m2)) == null ? void 0 : z2.attrs[c3]; if (b4 === null) { const U5 = n.doc.type.createAndFill().content; if (n.doc.content.findDiffStart(U5) === null) { const q4 = JSON.parse( JSON.stringify(e2.doc.toJSON()) ); if (q4.content[0].content[0].attrs.id = "initialBlockId", JSON.stringify(q4.content) === JSON.stringify(U5.toJSON())) { l2.setNodeMarkup(m2, void 0, { ...y3.attrs, [c3]: "initialBlockId" }); return; } } l2.setNodeMarkup(m2, void 0, { ...y3.attrs, [c3]: h7() }); return; } const { deleted: k3 } = p4.invert().mapResult(m2); k3 && w3.includes(b4) && l2.setNodeMarkup(m2, void 0, { ...y3.attrs, [c3]: h7() }); }); }), !!l2.steps.length) return l2.setMeta("uniqueID", true), l2; }, // we register a global drag handler to track the current drag source element view(r4) { const n = (e2) => { let s2; t2 = !((s2 = r4.dom.parentElement) === null || s2 === void 0) && s2.contains(e2.target) ? r4.dom.parentElement : null; }; return window.addEventListener("dragstart", n), { destroy() { window.removeEventListener("dragstart", n); } }; }, props: { // `handleDOMEvents` is called before `transformPasted` so we can do // some checks before. However, `transformPasted` only runs when // editor content is pasted - not external content. handleDOMEvents: { // only create new ids for dropped content while holding `alt` // or content is dragged from another editor drop: (r4, n) => { let e2; return t2 !== r4.dom.parentElement || ((e2 = n.dataTransfer) === null || e2 === void 0 ? void 0 : e2.effectAllowed) === "copy" ? o2 = true : o2 = false, t2 = null, false; }, // always create new ids on pasted content paste: () => (o2 = true, false) }, // we’ll remove ids for every pasted node // so we can create a new one within `appendTransaction` transformPasted: (r4) => { if (!o2) return r4; const { types: n, attributeName: e2 } = this.options, s2 = (i3) => { const l2 = []; return i3.forEach((a3) => { if (a3.isText) { l2.push(a3); return; } if (!n.includes(a3.type.name)) { l2.push(a3.copy(s2(a3.content))); return; } const c3 = a3.type.create( { ...a3.attrs, [e2]: null }, s2(a3.content), a3.marks ); l2.push(c3); }), Fragment.from(l2); }; return o2 = false, new Slice( s2(r4.content), r4.openStart, r4.openEnd ); } } }) ]; } }); function K3(t2) { return t2.type === "link"; } function X(t2) { return typeof t2 != "string" && t2.type === "link"; } function B(t2) { return typeof t2 != "string" && t2.type === "text"; } function S(t2) { var o2, r4, n, e2, s2; return R(t2) ? { ...t2 } : v(t2) ? { type: "tableCell", content: [].concat(t2.content), props: { backgroundColor: ((o2 = t2.props) == null ? void 0 : o2.backgroundColor) ?? "default", textColor: ((r4 = t2.props) == null ? void 0 : r4.textColor) ?? "default", textAlignment: ((n = t2.props) == null ? void 0 : n.textAlignment) ?? "left", colspan: ((e2 = t2.props) == null ? void 0 : e2.colspan) ?? 1, rowspan: ((s2 = t2.props) == null ? void 0 : s2.rowspan) ?? 1 } } : { type: "tableCell", content: [].concat(t2), props: { backgroundColor: "default", textColor: "default", textAlignment: "left", colspan: 1, rowspan: 1 } }; } function v(t2) { return t2 != null && typeof t2 != "string" && !Array.isArray(t2) && t2.type === "tableCell"; } function R(t2) { return v(t2) && t2.props !== void 0 && t2.content !== void 0; } function A(t2) { return R(t2) ? t2.props.colspan ?? 1 : 1; } function D(t2) { return R(t2) ? t2.props.rowspan ?? 1 : 1; } var O = class extends Error { constructor(o2) { super(`Unreachable case: ${o2}`); } }; function At(t2, o2 = true) { const { "data-test": r4, ...n } = t2; if (Object.keys(n).length > 0 && o2) throw new Error("Object must be empty " + JSON.stringify(t2)); } function Y2(t2, o2) { const r4 = t2.resolve(o2); if (r4.nodeAfter && r4.nodeAfter.type.isInGroup("bnBlock")) return { posBeforeNode: r4.pos, node: r4.nodeAfter }; let n = r4.depth, e2 = r4.node(n); for (; n > 0; ) { if (e2.type.isInGroup("bnBlock")) return { posBeforeNode: r4.before(n), node: e2 }; n--, e2 = r4.node(n); } const s2 = []; t2.descendants((l2, a3) => { l2.type.isInGroup("bnBlock") && s2.push(a3); }), console.warn(`Position ${o2} is not within a blockContainer node.`); const i3 = t2.resolve( s2.find((l2) => l2 >= o2) || s2[s2.length - 1] ); return { posBeforeNode: i3.pos, node: i3.nodeAfter }; } function $2(t2, o2) { if (!t2.type.isInGroup("bnBlock")) throw new Error( `Attempted to get bnBlock node at position but found node of different type ${t2.type.name}` ); const r4 = t2, n = o2, e2 = n + r4.nodeSize, s2 = { node: r4, beforePos: n, afterPos: e2 }; if (r4.type.name === "blockContainer") { let i3, l2; if (r4.forEach((a3, c3) => { if (a3.type.spec.group === "blockContent") { const h7 = a3, f6 = n + c3 + 1, p4 = f6 + a3.nodeSize; i3 = { node: h7, beforePos: f6, afterPos: p4 }; } else if (a3.type.name === "blockGroup") { const h7 = a3, f6 = n + c3 + 1, p4 = f6 + a3.nodeSize; l2 = { node: h7, beforePos: f6, afterPos: p4 }; } }), !i3) throw new Error( `blockContainer node does not contain a blockContent node in its children: ${r4}` ); return { isBlockContainer: true, bnBlock: s2, blockContent: i3, childContainer: l2, blockNoteType: i3.node.type.name }; } else { if (!s2.node.type.isInGroup("childContainer")) throw new Error( `bnBlock node is not in the childContainer group: ${s2.node}` ); return { isBlockContainer: false, bnBlock: s2, childContainer: s2, blockNoteType: s2.node.type.name }; } } function Z(t2) { return $2(t2.node, t2.posBeforeNode); } function It(t2) { if (!t2.nodeAfter) throw new Error( `Attempted to get blockContainer node at position ${t2.pos} but a node at this position does not exist` ); return $2(t2.nodeAfter, t2.pos); } function Tt(t2) { const o2 = Y2(t2.doc, t2.selection.anchor); return Z(o2); } function Ot(t2) { const o2 = Y2(t2.doc, t2.selection.anchor); return Z(o2); } function ht(t2) { return "doc" in t2 ? t2.doc.type.schema : t2.type.schema; } function G(t2) { return t2.cached.blockNoteEditor; } function J(t2) { return G(t2).schema; } function _(t2) { return J(t2).blockSchema; } function H(t2) { return J(t2).inlineContentSchema; } function N(t2) { return J(t2).styleSchema; } function j(t2) { return G(t2).blockCache; } function gt(t2, o2, r4) { var s2, i3; const n = { type: "tableContent", columnWidths: [], headerRows: void 0, headerCols: void 0, rows: [] }, e2 = []; t2.content.forEach((l2, a3, c3) => { const h7 = { cells: [] }; c3 === 0 && l2.content.forEach((f6) => { let p4 = f6.attrs.colwidth; p4 == null && (p4 = new Array(f6.attrs.colspan ?? 1).fill(void 0)), n.columnWidths.push(...p4); }), h7.cells = l2.content.content.map((f6, p4) => (e2[c3] || (e2[c3] = []), e2[c3][p4] = f6.type.name === "tableHeader", { type: "tableCell", content: f6.content.content.map( (g) => F2(g, o2, r4) ).reduce( (g, C3) => { if (!g.length) return C3; const d = g[g.length - 1], w3 = C3[0]; return w3 && B(d) && B(w3) && JSON.stringify(d.styles) === JSON.stringify(w3.styles) ? (d.text += ` ` + w3.text, g.push(...C3.slice(1)), g) : (g.push(...C3), g); }, [] ), props: { colspan: f6.attrs.colspan, rowspan: f6.attrs.rowspan, backgroundColor: f6.attrs.backgroundColor, textColor: f6.attrs.textColor, textAlignment: f6.attrs.textAlignment } })), n.rows.push(h7); }); for (let l2 = 0; l2 < e2.length; l2++) (s2 = e2[l2]) != null && s2.every((a3) => a3) && (n.headerRows = (n.headerRows ?? 0) + 1); for (let l2 = 0; l2 < ((i3 = e2[0]) == null ? void 0 : i3.length); l2++) e2 != null && e2.every((a3) => a3[l2]) && (n.headerCols = (n.headerCols ?? 0) + 1); return n; } function F2(t2, o2, r4) { const n = []; let e2; return t2.content.forEach((s2) => { if (s2.type.name === "hardBreak") { if (e2) if (B(e2)) e2.text += ` `; else if (K3(e2)) e2.content[e2.content.length - 1].text += ` `; else throw new Error("unexpected"); else e2 = { type: "text", text: ` `, styles: {} }; return; } if (s2.type.name !== "link" && s2.type.name !== "text") { if (!o2[s2.type.name]) { console.warn("unrecognized inline content type", s2.type.name); return; } e2 && (n.push(e2), e2 = void 0), n.push( wt(s2, o2, r4) ); return; } const i3 = {}; let l2; for (const a3 of s2.marks) if (a3.type.name === "link") l2 = a3; else { const c3 = r4[a3.type.name]; if (!c3) { if (a3.type.spec.blocknoteIgnore) continue; throw new Error(`style ${a3.type.name} not found in styleSchema`); } if (c3.propSchema === "boolean") i3[c3.type] = true; else if (c3.propSchema === "string") i3[c3.type] = a3.attrs.stringValue; else throw new O(c3.propSchema); } e2 ? B(e2) ? l2 ? (n.push(e2), e2 = { type: "link", href: l2.attrs.href, content: [ { type: "text", text: s2.textContent, styles: i3 } ] }) : JSON.stringify(e2.styles) === JSON.stringify(i3) ? e2.text += s2.textContent : (n.push(e2), e2 = { type: "text", text: s2.textContent, styles: i3 }) : K3(e2) && (l2 ? e2.href === l2.attrs.href ? JSON.stringify( e2.content[e2.content.length - 1].styles ) === JSON.stringify(i3) ? e2.content[e2.content.length - 1].text += s2.textContent : e2.content.push({ type: "text", text: s2.textContent, styles: i3 }) : (n.push(e2), e2 = { type: "link", href: l2.attrs.href, content: [ { type: "text", text: s2.textContent, styles: i3 } ] }) : (n.push(e2), e2 = { type: "text", text: s2.textContent, styles: i3 })) : l2 ? e2 = { type: "link", href: l2.attrs.href, content: [ { type: "text", text: s2.textContent, styles: i3 } ] } : e2 = { type: "text", text: s2.textContent, styles: i3 }; }), e2 && n.push(e2), n; } function wt(t2, o2, r4) { if (t2.type.name === "text" || t2.type.name === "link") throw new Error("unexpected"); const n = {}, e2 = o2[t2.type.name]; for (const [l2, a3] of Object.entries(t2.attrs)) { if (!e2) throw Error("ic node is of an unrecognized type: " + t2.type.name); const c3 = e2.propSchema; l2 in c3 && (n[l2] = a3); } let s2; return e2.content === "styled" ? s2 = F2( t2, o2, r4 ) : s2 = void 0, { type: t2.type.name, props: n, content: s2 }; } function L(t2, o2, r4 = _(o2), n = H(o2), e2 = N(o2), s2 = j(o2)) { var C3; if (!t2.type.isInGroup("bnBlock")) throw Error("Node should be a bnBlock, but is instead: " + t2.type.name); const i3 = s2 == null ? void 0 : s2.get(t2); if (i3) return i3; const l2 = $2(t2, 0); let a3 = l2.bnBlock.node.attrs.id; a3 === null && (a3 = Q.options.generateID()); const c3 = r4[l2.blockNoteType]; if (!c3) throw Error("Block is of an unrecognized type: " + l2.blockNoteType); const h7 = {}; for (const [d, w3] of Object.entries({ ...t2.attrs, ...l2.isBlockContainer ? l2.blockContent.node.attrs : {} })) { const y3 = c3.propSchema; d in y3 && !(y3[d].default === void 0 && w3 === void 0) && (h7[d] = w3); } const f6 = r4[l2.blockNoteType], p4 = []; (C3 = l2.childContainer) == null || C3.node.forEach((d) => { p4.push( L( d, o2, r4, n, e2, s2 ) ); }); let u2; if (f6.content === "inline") { if (!l2.isBlockContainer) throw new Error("impossible"); u2 = F2( l2.blockContent.node, n, e2 ); } else if (f6.content === "table") { if (!l2.isBlockContainer) throw new Error("impossible"); u2 = gt( l2.blockContent.node, n, e2 ); } else if (f6.content === "none") u2 = void 0; else throw new O(f6.content); const g = { id: a3, type: f6.type, props: h7, content: u2, children: p4 }; return s2 == null || s2.set(t2, g), g; } function St(t2, o2 = ht(t2), r4 = _(o2), n = H(o2), e2 = N(o2), s2 = j(o2)) { const i3 = []; return t2.firstChild && t2.firstChild.descendants((l2) => (i3.push( L( l2, o2, r4, n, e2, s2 ) ), false)), i3; } function Dt(t2, o2, r4 = _(o2), n = H(o2), e2 = N(o2), s2 = j(o2)) { function i3(l2, a3, c3) { if (l2.type.name !== "blockGroup") throw new Error("unexpected"); const h7 = []; let f6, p4; return l2.forEach((u2, g, C3) => { if (u2.type.name !== "blockContainer") throw new Error("unexpected"); if (u2.childCount === 0) return; if (u2.childCount === 0 || u2.childCount > 2) throw new Error( "unexpected, blockContainer.childCount: " + u2.childCount ); const d = C3 === 0, w3 = C3 === l2.childCount - 1; if (u2.firstChild.type.name === "blockGroup") { if (!d) throw new Error("unexpected"); const k3 = i3( u2.firstChild, Math.max(0, a3 - 1), w3 ? Math.max(0, c3 - 1) : 0 ); f6 = k3.blockCutAtStart, w3 && (p4 = k3.blockCutAtEnd), h7.push(...k3.blocks); return; } const y3 = L( u2, o2, r4, n, e2, s2 ), m2 = u2.childCount > 1 ? u2.child(1) : void 0; let b4 = []; if (m2) { const k3 = i3( m2, 0, // TODO: can this be anything other than 0? w3 ? Math.max(0, c3 - 1) : 0 ); b4 = k3.blocks, w3 && (p4 = k3.blockCutAtEnd); } w3 && !m2 && c3 > 1 && (p4 = y3.id), d && a3 > 1 && (f6 = y3.id), h7.push({ ...y3, children: b4 }); }), { blocks: h7, blockCutAtStart: f6, blockCutAtEnd: p4 }; } if (t2.content.childCount === 0) return { blocks: [], blockCutAtStart: void 0, blockCutAtEnd: void 0 }; if (t2.content.childCount !== 1) throw new Error( "slice must be a single block, did you forget includeParents=true?" ); return i3( t2.content.firstChild, Math.max(t2.openStart - 1, 0), Math.max(t2.openEnd - 1, 0) ); } function x2(t2) { const { height: o2, width: r4 } = tt(t2), n = new Array(o2).fill(false).map(() => new Array(r4).fill(null)), e2 = (s2, i3) => { for (let l2 = s2; l2 < o2; l2++) for (let a3 = i3; a3 < r4; a3++) if (!n[l2][a3]) return { row: l2, col: a3 }; throw new Error( "Unable to create occupancy grid for table, no more available cells" ); }; for (let s2 = 0; s2 < t2.content.rows.length; s2++) for (let i3 = 0; i3 < t2.content.rows[s2].cells.length; i3++) { const l2 = S(t2.content.rows[s2].cells[i3]), a3 = D(l2), c3 = A(l2), { row: h7, col: f6 } = e2(s2, i3); for (let p4 = h7; p4 < h7 + a3; p4++) for (let u2 = f6; u2 < f6 + c3; u2++) { if (n[p4][u2]) throw new Error( `Unable to create occupancy grid for table, cell at ${p4},${u2} is already occupied` ); n[p4][u2] = { row: s2, col: i3, rowspan: a3, colspan: c3, cell: l2 }; } } return n; } function I(t2) { const o2 = /* @__PURE__ */ new Set(); return t2.map((r4) => ({ cells: r4.map((n) => o2.has(n.row + ":" + n.col) ? false : (o2.add(n.row + ":" + n.col), n.cell)).filter((n) => n !== false) })); } function E(t2, o2, r4 = x2(o2)) { for (let n = 0; n < r4.length; n++) for (let e2 = 0; e2 < r4[n].length; e2++) { const s2 = r4[n][e2]; if (s2 && s2.row === t2.row && s2.col === t2.col) return { row: n, col: e2, cell: s2.cell }; } throw new Error( `Unable to resolve relative table cell indices for table, cell at ${t2.row},${t2.col} is not occupied` ); } function tt(t2) { const o2 = t2.content.rows.length; let r4 = 0; return t2.content.rows.forEach((n) => { let e2 = 0; n.cells.forEach((s2) => { e2 += A(s2); }), r4 = Math.max(r4, e2); }), { height: o2, width: r4 }; } function et(t2, o2, r4 = x2(o2)) { var e2; const n = (e2 = r4[t2.row]) == null ? void 0 : e2[t2.col]; if (n) return { row: n.row, col: n.col, cell: n.cell }; } function yt(t2, o2) { var s2; const r4 = x2(t2); if (o2 < 0 || o2 >= r4.length) return []; let n = 0; for (let i3 = 0; i3 < o2; i3++) { const l2 = (s2 = r4[n]) == null ? void 0 : s2[0]; if (!l2) return []; n += l2.rowspan; } const e2 = new Array(r4[0].length).fill(false).map((i3, l2) => et( { row: n, col: l2 }, t2, r4 )).filter( (i3) => i3 !== void 0 ); return e2.filter((i3, l2) => e2.findIndex((a3) => a3.row === i3.row && a3.col === i3.col) === l2); } function Ct(t2, o2) { var s2; const r4 = x2(t2); if (o2 < 0 || o2 >= r4[0].length) return []; let n = 0; for (let i3 = 0; i3 < o2; i3++) { const l2 = (s2 = r4[0]) == null ? void 0 : s2[n]; if (!l2) return []; n += l2.colspan; } const e2 = new Array(r4.length).fill(false).map((i3, l2) => et( { row: l2, col: n }, t2, r4 )).filter( (i3) => i3 !== void 0 ); return e2.filter((i3, l2) => e2.findIndex((a3) => a3.row === i3.row && a3.col === i3.col) === l2); } function Mt(t2, o2, r4, n = x2(t2)) { const { col: e2 } = E( { row: 0, col: o2 }, t2, n ), { col: s2 } = E( { row: 0, col: r4 }, t2, n ); return n.forEach((i3) => { const [l2] = i3.splice(e2, 1); i3.splice(s2, 0, l2); }), I(n); } function Pt(t2, o2, r4, n = x2(t2)) { const { row: e2 } = E( { row: o2, col: 0 }, t2, n ), { row: s2 } = E( { row: r4, col: 0 }, t2, n ), [i3] = n.splice(e2, 1); return n.splice(s2, 0, i3), I(n); } function M2(t2) { return t2 ? v(t2) ? M2(t2.content) : typeof t2 == "string" ? t2.length === 0 : Array.isArray(t2) ? t2.every( (o2) => typeof o2 == "string" ? o2.length === 0 : B(o2) ? o2.text.length === 0 : X(o2) ? typeof o2.content == "string" ? o2.content.length === 0 : o2.content.every((r4) => r4.text.length === 0) : false ) : false : true; } function Rt(t2, o2, r4 = x2(t2)) { if (o2 === "columns") { let s2 = 0; for (let i3 = r4[0].length - 1; i3 >= 0 && r4.every( (a3) => M2(a3[i3].cell) && a3[i3].colspan === 1 ); i3--) s2++; for (let i3 = r4.length - 1; i3 >= 0; i3--) { const l2 = Math.max( r4[i3].length - s2, 1 ); r4[i3] = r4[i3].slice(0, l2); } return I(r4); } let n = 0; for (let s2 = r4.length - 1; s2 >= 0 && r4[s2].every( (l2) => M2(l2.cell) && l2.rowspan === 1 ); s2--) n++; const e2 = Math.min(n, r4.length - 1); return r4.splice(r4.length - e2, e2), I(r4); } function $t(t2, o2, r4, n = x2(t2)) { const { width: e2, height: s2 } = tt(t2); if (o2 === "columns") n.forEach((i3, l2) => { if (r4 >= 0) for (let a3 = 0; a3 < r4; a3++) i3.push({ row: l2, col: Math.max(...i3.map((c3) => c3.col)) + 1, rowspan: 1, colspan: 1, cell: S("") }); else i3.splice(e2 + r4, -1 * r4); }); else if (r4 > 0) for (let i3 = 0; i3 < r4; i3++) { const l2 = new Array(e2).fill(null).map((a3, c3) => ({ row: s2 + i3, col: c3, rowspan: 1, colspan: 1, cell: S("") })); n.push(l2); } else r4 < 0 && n.splice(s2 + r4, -1 * r4); return I(n); } function Jt(t2, o2, r4) { const n = yt(t2, r4); if (!n.some((a3) => D(a3.cell) > 1)) return true; let s2 = r4, i3 = r4; return n.forEach((a3) => { const c3 = D(a3.cell); s2 = Math.max(s2, a3.row + c3 - 1), i3 = Math.min(i3, a3.row); }), o2 < r4 ? r4 === s2 : r4 === i3; } function _t2(t2, o2, r4) { const n = Ct(t2, r4); if (!n.some((a3) => A(a3.cell) > 1)) return true; let s2 = r4, i3 = r4; return n.forEach((a3) => { const c3 = A(a3.cell); s2 = Math.max(s2, a3.col + c3 - 1), i3 = Math.min(i3, a3.col); }), o2 < r4 ? r4 === s2 : r4 === i3; } function Ht(t2, o2, r4) { const n = E(t2, r4), e2 = E(o2, r4); return n.col === e2.col; } function V(t2, o2, r4, n) { const e2 = []; for (const [i3, l2] of Object.entries(t2.styles || {})) { const a3 = r4[i3]; if (!a3) throw new Error(`style ${i3} not found in styleSchema`); if (a3.propSchema === "boolean") l2 && e2.push(o2.mark(i3)); else if (a3.propSchema === "string") l2 && e2.push(o2.mark(i3, { stringValue: l2 })); else throw new O(a3.propSchema); } return !n || !o2.nodes[n].spec.code ? t2.text.split(/(\n)/g).filter((i3) => i3.length > 0).map((i3) => i3 === ` ` ? o2.nodes.hardBreak.createChecked() : o2.text(i3, e2)) : t2.text.length > 0 ? [o2.text(t2.text, e2)] : []; } function mt(t2, o2, r4) { const n = o2.marks.link.create({ href: t2.href }); return P(t2.content, o2, r4).map( (e2) => { if (e2.type.name === "text") return e2.mark([...e2.marks, n]); if (e2.type.name === "hardBreak") return e2; throw new Error("unexpected node type"); } ); } function P(t2, o2, r4, n) { const e2 = []; if (typeof t2 == "string") return e2.push( ...V( { text: t2, styles: {} }, o2, r4, n ) ), e2; for (const s2 of t2) e2.push( ...V(s2, o2, r4, n) ); return e2; } function T(t2, o2, r4, n = N(o2)) { const e2 = []; for (const s2 of t2) typeof s2 == "string" ? e2.push( ...P(s2, o2, n, r4) ) : X(s2) ? e2.push(...mt(s2, o2, n)) : B(s2) ? e2.push( ...P([s2], o2, n, r4) ) : e2.push( nt(s2, o2, n) ); return e2; } function kt(t2, o2, r4 = N(o2)) { const n = [], e2 = new Array(t2.headerRows ?? 0).fill(true), s2 = new Array(t2.headerCols ?? 0).fill(true), i3 = t2.columnWidths ?? []; for (let l2 = 0; l2 < t2.rows.length; l2++) { const a3 = t2.rows[l2], c3 = [], h7 = e2[l2]; for (let p4 = 0; p4 < a3.cells.length; p4++) { const u2 = a3.cells[p4], g = s2[p4], C3 = void 0; let d = null; const w3 = E( { row: l2, col: p4 }, { content: t2 } ); let y3 = i3[w3.col] ? [i3[w3.col]] : null; if (u2) if (typeof u2 == "string") d = o2.text(u2); else if (v(u2)) { u2.content && (d = T( u2.content, o2, "tableParagraph", r4 )); const b4 = A(u2); b4 > 1 && (y3 = new Array(b4).fill(false).map((k3, W3) => i3[w3.col + W3] ?? void 0)); } else d = T( u2, o2, "tableParagraph", r4 ); const m2 = o2.nodes[g || h7 ? "tableHeader" : "tableCell"].createChecked( { ...v(u2) ? u2.props : {}, colwidth: y3 }, o2.nodes.tableParagraph.createChecked(C3, d) ); c3.push(m2); } const f6 = o2.nodes.tableRow.createChecked({}, c3); n.push(f6); } return n; } function nt(t2, o2, r4) { let n, e2 = t2.type; if (e2 === void 0 && (e2 = "paragraph"), !o2.nodes[e2]) throw new Error(`node type ${e2} not found in schema`); if (!t2.content) n = o2.nodes[e2].createChecked(t2.props); else if (typeof t2.content == "string") { const s2 = T( [t2.content], o2, e2, r4 ); n = o2.nodes[e2].createChecked(t2.props, s2); } else if (Array.isArray(t2.content)) { const s2 = T( t2.content, o2, e2, r4 ); n = o2.nodes[e2].createChecked(t2.props, s2); } else if (t2.content.type === "tableContent") { const s2 = kt(t2.content, o2, r4); n = o2.nodes[e2].createChecked(t2.props, s2); } else throw new O(t2.content.type); return n; } function bt(t2, o2, r4 = N(o2)) { let n = t2.id; n === void 0 && (n = Q.options.generateID()); const e2 = []; if (t2.children) for (const i3 of t2.children) e2.push(bt(i3, o2, r4)); if (!t2.type || // can happen if block.type is not defined (this should create the default node) o2.nodes[t2.type].isInGroup("blockContent")) { const i3 = nt( t2, o2, r4 ), l2 = e2.length > 0 ? o2.nodes.blockGroup.createChecked({}, e2) : void 0; return o2.nodes.blockContainer.createChecked( { id: n, ...t2.props }, l2 ? [i3, l2] : i3 ); } else { if (o2.nodes[t2.type].isInGroup("bnBlock")) return o2.nodes[t2.type].createChecked( { id: n, ...t2.props }, e2 ); throw new Error( `block type ${t2.type} doesn't match blockContent or bnBlock group` ); } } // ../../node_modules/.pnpm/prosemirror-tables@1.8.5/node_modules/prosemirror-tables/dist/index.js var readFromCache; var addToCache; if (typeof WeakMap != "undefined") { let cache = /* @__PURE__ */ new WeakMap(); readFromCache = (key2) => cache.get(key2); addToCache = (key2, value) => { cache.set(key2, value); return value; }; } else { const cache = []; const cacheSize = 10; let cachePos = 0; readFromCache = (key2) => { for (let i3 = 0; i3 < cache.length; i3 += 2) if (cache[i3] == key2) return cache[i3 + 1]; }; addToCache = (key2, value) => { if (cachePos == cacheSize) cachePos = 0; cache[cachePos++] = key2; return cache[cachePos++] = value; }; } var TableMap = class { constructor(width, height, map7, problems) { this.width = width; this.height = height; this.map = map7; this.problems = problems; } findCell(pos) { for (let i3 = 0; i3 < this.map.length; i3++) { const curPos = this.map[i3]; if (curPos != pos) continue; const left = i3 % this.width; const top = i3 / this.width | 0; let right = left + 1; let bottom = top + 1; for (let j4 = 1; right < this.width && this.map[i3 + j4] == curPos; j4++) right++; for (let j4 = 1; bottom < this.height && this.map[i3 + this.width * j4] == curPos; j4++) bottom++; return { left, top, right, bottom }; } throw new RangeError(`No cell with offset ${pos} found`); } colCount(pos) { for (let i3 = 0; i3 < this.map.length; i3++) if (this.map[i3] == pos) return i3 % 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(a3, b4) { const { left: leftA, right: rightA, top: topA, bottom: bottomA } = this.findCell(a3); const { left: leftB, right: rightB, top: topB, bottom: bottomB } = this.findCell(b4); 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 row2 = rect.top; row2 < rect.bottom; row2++) for (let col = rect.left; col < rect.right; col++) { const index4 = row2 * this.width + col; const pos = this.map[index4]; if (seen[pos]) continue; seen[pos] = true; if (col == rect.left && col && this.map[index4 - 1] == pos || row2 == rect.top && row2 && this.map[index4 - this.width] == pos) continue; result.push(pos); } return result; } positionAt(row2, col, table3) { for (let i3 = 0, rowStart = 0; ; i3++) { const rowEnd = rowStart + table3.child(i3).nodeSize; if (i3 == row2) { let index4 = col + row2 * this.width; const rowEndIndex = (row2 + 1) * this.width; while (index4 < rowEndIndex && this.map[index4] < rowStart) index4++; return index4 == rowEndIndex ? rowEnd - 1 : this.map[index4]; } rowStart = rowEnd; } } static get(table3) { return readFromCache(table3) || addToCache(table3, computeMap(table3)); } }; function computeMap(table3) { if (table3.type.spec.tableRole != "table") throw new RangeError("Not a table node: " + table3.type.name); const width = findWidth(table3), height = table3.childCount; const map7 = []; let mapPos = 0; let problems = null; const colWidths = []; for (let i3 = 0, e2 = width * height; i3 < e2; i3++) map7[i3] = 0; for (let row2 = 0, pos = 0; row2 < height; row2++) { const rowNode = table3.child(row2); pos++; for (let i3 = 0; ; i3++) { while (mapPos < map7.length && map7[mapPos] != 0) mapPos++; if (i3 == rowNode.childCount) break; const cellNode = rowNode.child(i3); const { colspan, rowspan, colwidth } = cellNode.attrs; for (let h7 = 0; h7 < rowspan; h7++) { if (h7 + row2 >= height) { (problems || (problems = [])).push({ type: "overlong_rowspan", pos, n: rowspan - h7 }); break; } const start = mapPos + h7 * width; for (let w3 = 0; w3 < colspan; w3++) { if (map7[start + w3] == 0) map7[start + w3] = pos; else (problems || (problems = [])).push({ type: "collision", row: row2, pos, n: colspan - w3 }); const colW = colwidth && colwidth[w3]; if (colW) { const widthIndex = (start + w3) % 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 = (row2 + 1) * width; let missing = 0; while (mapPos < expectedPos) if (map7[mapPos++] == 0) missing++; if (missing) (problems || (problems = [])).push({ type: "missing", row: row2, n: missing }); pos++; } if (width === 0 || height === 0) (problems || (problems = [])).push({ type: "zero_sized" }); const tableMap = new TableMap(width, height, map7, problems); let badWidths = false; for (let i3 = 0; !badWidths && i3 < colWidths.length; i3 += 2) if (colWidths[i3] != null && colWidths[i3 + 1] < height) badWidths = true; if (badWidths) findBadColWidths(tableMap, colWidths, table3); return tableMap; } function findWidth(table3) { let width = -1; let hasRowSpan = false; for (let row2 = 0; row2 < table3.childCount; row2++) { const rowNode = table3.child(row2); let rowWidth = 0; if (hasRowSpan) for (let j4 = 0; j4 < row2; j4++) { const prevRow = table3.child(j4); for (let i3 = 0; i3 < prevRow.childCount; i3++) { const cell2 = prevRow.child(i3); if (j4 + cell2.attrs.rowspan > row2) rowWidth += cell2.attrs.colspan; } } for (let i3 = 0; i3 < rowNode.childCount; i3++) { const cell2 = rowNode.child(i3); rowWidth += cell2.attrs.colspan; if (cell2.attrs.rowspan > 1) hasRowSpan = true; } if (width == -1) width = rowWidth; else if (width != rowWidth) width = Math.max(width, rowWidth); } return width; } function findBadColWidths(map7, colWidths, table3) { if (!map7.problems) map7.problems = []; const seen = {}; for (let i3 = 0; i3 < map7.map.length; i3++) { const pos = map7.map[i3]; if (seen[pos]) continue; seen[pos] = true; const node2 = table3.nodeAt(pos); if (!node2) throw new RangeError(`No cell with offset ${pos} found`); let updated = null; const attrs = node2.attrs; for (let j4 = 0; j4 < attrs.colspan; j4++) { const colWidth = colWidths[(i3 + j4) % map7.width * 2]; if (colWidth != null && (!attrs.colwidth || attrs.colwidth[j4] != colWidth)) (updated || (updated = freshColWidth(attrs)))[j4] = colWidth; } if (updated) map7.problems.unshift({ type: "colwidth mismatch", pos, colwidth: updated }); } } function freshColWidth(attrs) { if (attrs.colwidth) return attrs.colwidth.slice(); const result = []; for (let i3 = 0; i3 < attrs.colspan; i3++) 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; } var tableEditingKey = 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 cellWrapping($pos) { for (let d = $pos.depth; d > 0; d--) { const role = $pos.node(d).type.spec.tableRole; if (role === "cell" || role === "header_cell") return $pos.node(d); } 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 moveCellForward($pos) { return $pos.node(0).resolve($pos.pos + $pos.nodeAfter.nodeSize); } 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 table3 = $pos.node(-1); const map7 = TableMap.get(table3); const tableStart = $pos.start(-1); const moved = map7.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((w3) => w3 > 0)) result.colwidth = null; } return result; } function addColSpan(attrs, pos, n = 1) { const result = { ...attrs, colspan: attrs.colspan + n }; if (result.colwidth) { result.colwidth = result.colwidth.slice(); for (let i3 = 0; i3 < n; i3++) result.colwidth.splice(pos, 0, 0); } return result; } function columnIsHeader(map7, table3, col) { const headerCell = tableNodeTypes(table3.type.schema).header_cell; for (let row2 = 0; row2 < map7.height; row2++) if (table3.nodeAt(map7.map[col + row2 * map7.width]).type != headerCell) return false; return true; } var CellSelection = class CellSelection2 extends Selection { constructor($anchorCell, $headCell = $anchorCell) { const table3 = $anchorCell.node(-1); const map7 = TableMap.get(table3); const tableStart = $anchorCell.start(-1); const rect = map7.rectBetween($anchorCell.pos - tableStart, $headCell.pos - tableStart); const doc4 = $anchorCell.node(0); const cells2 = map7.cellsInRect(rect).filter((p4) => p4 != $headCell.pos - tableStart); cells2.unshift($headCell.pos - tableStart); const ranges = cells2.map((pos) => { const cell2 = table3.nodeAt(pos); if (!cell2) throw new RangeError(`No cell with offset ${pos} found`); const from4 = tableStart + pos + 1; return new SelectionRange(doc4.resolve(from4), doc4.resolve(from4 + cell2.content.size)); }); super(ranges[0].$from, ranges[0].$to, ranges); this.$anchorCell = $anchorCell; this.$headCell = $headCell; } map(doc4, mapping) { const $anchorCell = doc4.resolve(mapping.map(this.$anchorCell.pos)); const $headCell = doc4.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 table3 = this.$anchorCell.node(-1); const map7 = TableMap.get(table3); const tableStart = this.$anchorCell.start(-1); const rect = map7.rectBetween(this.$anchorCell.pos - tableStart, this.$headCell.pos - tableStart); const seen = {}; const rows = []; for (let row2 = rect.top; row2 < rect.bottom; row2++) { const rowContent = []; for (let index4 = row2 * map7.width + rect.left, col = rect.left; col < rect.right; col++, index4++) { const pos = map7.map[index4]; if (seen[pos]) continue; seen[pos] = true; const cellRect = map7.findCell(pos); let cell2 = table3.nodeAt(pos); if (!cell2) 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 = cell2.attrs; if (extraLeft > 0) attrs = removeColSpan(attrs, 0, extraLeft); if (extraRight > 0) attrs = removeColSpan(attrs, attrs.colspan - extraRight, extraRight); if (cellRect.left < rect.left) { cell2 = cell2.type.createAndFill(attrs); if (!cell2) throw new RangeError(`Could not create cell with attrs ${JSON.stringify(attrs)}`); } else cell2 = cell2.type.create(attrs, cell2.content); } if (cellRect.top < rect.top || cellRect.bottom > rect.bottom) { const attrs = { ...cell2.attrs, rowspan: Math.min(cellRect.bottom, rect.bottom) - Math.max(cellRect.top, rect.top) }; if (cellRect.top < rect.top) cell2 = cell2.type.createAndFill(attrs); else cell2 = cell2.type.create(attrs, cell2.content); } rowContent.push(cell2); } rows.push(table3.child(row2).copy(Fragment.from(rowContent))); } const fragment = this.isColSelection() && this.isRowSelection() ? table3 : rows; return new Slice(Fragment.from(fragment), 1, 1); } replace(tr4, content5 = Slice.empty) { const mapFrom = tr4.steps.length, ranges = this.ranges; for (let i3 = 0; i3 < ranges.length; i3++) { const { $from, $to } = ranges[i3], mapping = tr4.mapping.slice(mapFrom); tr4.replace(mapping.map($from.pos), mapping.map($to.pos), i3 ? Slice.empty : content5); } const sel = Selection.findFrom(tr4.doc.resolve(tr4.mapping.slice(mapFrom).map(this.to)), -1); if (sel) tr4.setSelection(sel); } replaceWith(tr4, node2) { this.replace(tr4, new Slice(Fragment.from(node2), 0, 0)); } forEachCell(f6) { const table3 = this.$anchorCell.node(-1); const map7 = TableMap.get(table3); const tableStart = this.$anchorCell.start(-1); const cells2 = map7.cellsInRect(map7.rectBetween(this.$anchorCell.pos - tableStart, this.$headCell.pos - tableStart)); for (let i3 = 0; i3 < cells2.length; i3++) f6(table3.nodeAt(cells2[i3]), tableStart + cells2[i3]); } 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 table3 = $anchorCell.node(-1); const map7 = TableMap.get(table3); const tableStart = $anchorCell.start(-1); const anchorRect = map7.findCell($anchorCell.pos - tableStart); const headRect = map7.findCell($headCell.pos - tableStart); const doc4 = $anchorCell.node(0); if (anchorRect.top <= headRect.top) { if (anchorRect.top > 0) $anchorCell = doc4.resolve(tableStart + map7.map[anchorRect.left]); if (headRect.bottom < map7.height) $headCell = doc4.resolve(tableStart + map7.map[map7.width * (map7.height - 1) + headRect.right - 1]); } else { if (headRect.top > 0) $headCell = doc4.resolve(tableStart + map7.map[headRect.left]); if (anchorRect.bottom < map7.height) $anchorCell = doc4.resolve(tableStart + map7.map[map7.width * (map7.height - 1) + anchorRect.right - 1]); } return new CellSelection2($anchorCell, $headCell); } isRowSelection() { const table3 = this.$anchorCell.node(-1); const map7 = TableMap.get(table3); const tableStart = this.$anchorCell.start(-1); const anchorLeft = map7.colCount(this.$anchorCell.pos - tableStart); const headLeft = map7.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) == map7.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 table3 = $anchorCell.node(-1); const map7 = TableMap.get(table3); const tableStart = $anchorCell.start(-1); const anchorRect = map7.findCell($anchorCell.pos - tableStart); const headRect = map7.findCell($headCell.pos - tableStart); const doc4 = $anchorCell.node(0); if (anchorRect.left <= headRect.left) { if (anchorRect.left > 0) $anchorCell = doc4.resolve(tableStart + map7.map[anchorRect.top * map7.width]); if (headRect.right < map7.width) $headCell = doc4.resolve(tableStart + map7.map[map7.width * (headRect.top + 1) - 1]); } else { if (headRect.left > 0) $headCell = doc4.resolve(tableStart + map7.map[headRect.top * map7.width]); if (anchorRect.right < map7.width) $anchorCell = doc4.resolve(tableStart + map7.map[map7.width * (anchorRect.top + 1) - 1]); } return new CellSelection2($anchorCell, $headCell); } toJSON() { return { type: "cell", anchor: this.$anchorCell.pos, head: this.$headCell.pos }; } static fromJSON(doc4, json) { return new CellSelection2(doc4.resolve(json.anchor), doc4.resolve(json.head)); } static create(doc4, anchorCell, headCell = anchorCell) { return new CellSelection2(doc4.resolve(anchorCell), doc4.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, head2) { this.anchor = anchor; this.head = head2; } map(mapping) { return new CellBookmark2(mapping.map(this.anchor), mapping.map(this.head)); } resolve(doc4) { const $anchorCell = doc4.resolve(this.anchor), $headCell = doc4.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); } }; function drawCellSelection(state) { if (!(state.selection instanceof CellSelection)) return null; const cells2 = []; state.selection.forEachCell((node2, pos) => { cells2.push(Decoration.node(pos, pos + node2.nodeSize, { class: "selectedCell" })); }); return DecorationSet.create(state.doc, cells2); } function isCellBoundarySelection({ $from, $to }) { if ($from.pos == $to.pos || $from.pos < $to.pos - 6) return false; let afterFrom = $from.pos; let beforeTo = $to.pos; let depth = $from.depth; for (; depth >= 0; depth--, afterFrom++) if ($from.after(depth + 1) < $from.end(depth)) break; for (let d = $to.depth; d >= 0; d--, beforeTo--) if ($to.before(d + 1) > $to.start(d)) break; return afterFrom == beforeTo && /row|table/.test($from.node(depth).type.spec.tableRole); } function isTextSelectionAcrossCells({ $from, $to }) { let fromCellBoundaryNode; let toCellBoundaryNode; for (let i3 = $from.depth; i3 > 0; i3--) { const node2 = $from.node(i3); if (node2.type.spec.tableRole === "cell" || node2.type.spec.tableRole === "header_cell") { fromCellBoundaryNode = node2; break; } } for (let i3 = $to.depth; i3 > 0; i3--) { const node2 = $to.node(i3); if (node2.type.spec.tableRole === "cell" || node2.type.spec.tableRole === "header_cell") { toCellBoundaryNode = node2; break; } } return fromCellBoundaryNode !== toCellBoundaryNode && $to.parentOffset === 0; } function normalizeSelection(state, tr4, allowTableNodeSelection) { const sel = (tr4 || state).selection; const doc4 = (tr4 || state).doc; let normalize4; let role; if (sel instanceof NodeSelection && (role = sel.node.type.spec.tableRole)) { if (role == "cell" || role == "header_cell") normalize4 = CellSelection.create(doc4, sel.from); else if (role == "row") { const $cell = doc4.resolve(sel.from + 1); normalize4 = CellSelection.rowSelection($cell, $cell); } else if (!allowTableNodeSelection) { const map7 = TableMap.get(sel.node); const start = sel.from + 1; const lastCell = start + map7.map[map7.width * map7.height - 1]; normalize4 = CellSelection.create(doc4, start + 1, lastCell); } } else if (sel instanceof TextSelection && isCellBoundarySelection(sel)) normalize4 = TextSelection.create(doc4, sel.from); else if (sel instanceof TextSelection && isTextSelectionAcrossCells(sel)) normalize4 = TextSelection.create(doc4, sel.$from.start(), sel.$from.end()); if (normalize4) (tr4 || (tr4 = state.tr)).setSelection(normalize4); return tr4; } var fixTablesKey = new PluginKey("fix-tables"); function changedDescendants(old, cur, offset4, f6) { const oldSize = old.childCount, curSize = cur.childCount; outer: for (let i3 = 0, j4 = 0; i3 < curSize; i3++) { const child = cur.child(i3); for (let scan = j4, e2 = Math.min(oldSize, i3 + 3); scan < e2; scan++) if (old.child(scan) == child) { j4 = scan + 1; offset4 += child.nodeSize; continue outer; } f6(child, offset4); if (j4 < oldSize && old.child(j4).sameMarkup(child)) changedDescendants(old.child(j4), child, offset4 + 1, f6); else child.nodesBetween(0, child.content.size, f6, offset4 + 1); offset4 += child.nodeSize; } } function fixTables(state, oldState) { let tr4; const check = (node2, pos) => { if (node2.type.spec.tableRole == "table") tr4 = fixTable(state, node2, pos, tr4); }; if (!oldState) state.doc.descendants(check); else if (oldState.doc != state.doc) changedDescendants(oldState.doc, state.doc, 0, check); return tr4; } function fixTable(state, table3, tablePos, tr4) { const map7 = TableMap.get(table3); if (!map7.problems) return tr4; if (!tr4) tr4 = state.tr; const mustAdd = []; for (let i3 = 0; i3 < map7.height; i3++) mustAdd.push(0); for (let i3 = 0; i3 < map7.problems.length; i3++) { const prob = map7.problems[i3]; if (prob.type == "collision") { const cell2 = table3.nodeAt(prob.pos); if (!cell2) continue; const attrs = cell2.attrs; for (let j4 = 0; j4 < attrs.rowspan; j4++) mustAdd[prob.row + j4] += prob.n; tr4.setNodeMarkup(tr4.mapping.map(tablePos + 1 + prob.pos), null, removeColSpan(attrs, attrs.colspan - prob.n, prob.n)); } else if (prob.type == "missing") mustAdd[prob.row] += prob.n; else if (prob.type == "overlong_rowspan") { const cell2 = table3.nodeAt(prob.pos); if (!cell2) continue; tr4.setNodeMarkup(tr4.mapping.map(tablePos + 1 + prob.pos), null, { ...cell2.attrs, rowspan: cell2.attrs.rowspan - prob.n }); } else if (prob.type == "colwidth mismatch") { const cell2 = table3.nodeAt(prob.pos); if (!cell2) continue; tr4.setNodeMarkup(tr4.mapping.map(tablePos + 1 + prob.pos), null, { ...cell2.attrs, colwidth: prob.colwidth }); } else if (prob.type == "zero_sized") { const pos = tr4.mapping.map(tablePos); tr4.delete(pos, pos + table3.nodeSize); } } let first2, last2; for (let i3 = 0; i3 < mustAdd.length; i3++) if (mustAdd[i3]) { if (first2 == null) first2 = i3; last2 = i3; } for (let i3 = 0, pos = tablePos + 1; i3 < map7.height; i3++) { const row2 = table3.child(i3); const end = pos + row2.nodeSize; const add = mustAdd[i3]; if (add > 0) { let role = "cell"; if (row2.firstChild) role = row2.firstChild.type.spec.tableRole; const nodes = []; for (let j4 = 0; j4 < add; j4++) { const node2 = tableNodeTypes(state.schema)[role].createAndFill(); if (node2) nodes.push(node2); } const side = (i3 == 0 || first2 == i3 - 1) && last2 == i3 ? pos + 1 : end - 1; tr4.insert(tr4.mapping.map(side), nodes); } pos = end; } return tr4.setMeta(fixTablesKey, { fixTables: true }); } function selectedRect(state) { const sel = state.selection; const $pos = selectionCell(state); const table3 = $pos.node(-1); const tableStart = $pos.start(-1); const map7 = TableMap.get(table3); return { ...sel instanceof CellSelection ? map7.rectBetween(sel.$anchorCell.pos - tableStart, sel.$headCell.pos - tableStart) : map7.findCell($pos.pos - tableStart), tableStart, map: map7, table: table3 }; } function addColumn(tr4, { map: map7, tableStart, table: table3 }, col) { let refColumn = col > 0 ? -1 : 0; if (columnIsHeader(map7, table3, col + refColumn)) refColumn = col == 0 || col == map7.width ? null : 0; for (let row2 = 0; row2 < map7.height; row2++) { const index4 = row2 * map7.width + col; if (col > 0 && col < map7.width && map7.map[index4 - 1] == map7.map[index4]) { const pos = map7.map[index4]; const cell2 = table3.nodeAt(pos); tr4.setNodeMarkup(tr4.mapping.map(tableStart + pos), null, addColSpan(cell2.attrs, col - map7.colCount(pos))); row2 += cell2.attrs.rowspan - 1; } else { const type = refColumn == null ? tableNodeTypes(table3.type.schema).cell : table3.nodeAt(map7.map[index4 + refColumn]).type; const pos = map7.positionAt(row2, col, table3); tr4.insert(tr4.mapping.map(tableStart + pos), type.createAndFill()); } } return tr4; } function addColumnBefore(state, dispatch) { if (!isInTable(state)) return false; if (dispatch) { const rect = selectedRect(state); dispatch(addColumn(state.tr, rect, rect.left)); } return true; } function addColumnAfter(state, dispatch) { if (!isInTable(state)) return false; if (dispatch) { const rect = selectedRect(state); dispatch(addColumn(state.tr, rect, rect.right)); } return true; } function removeColumn(tr4, { map: map7, table: table3, tableStart }, col) { const mapStart = tr4.mapping.maps.length; for (let row2 = 0; row2 < map7.height; ) { const index4 = row2 * map7.width + col; const pos = map7.map[index4]; const cell2 = table3.nodeAt(pos); const attrs = cell2.attrs; if (col > 0 && map7.map[index4 - 1] == pos || col < map7.width - 1 && map7.map[index4 + 1] == pos) tr4.setNodeMarkup(tr4.mapping.slice(mapStart).map(tableStart + pos), null, removeColSpan(attrs, col - map7.colCount(pos))); else { const start = tr4.mapping.slice(mapStart).map(tableStart + pos); tr4.delete(start, start + cell2.nodeSize); } row2 += attrs.rowspan; } } function deleteColumn(state, dispatch) { if (!isInTable(state)) return false; if (dispatch) { const rect = selectedRect(state); const tr4 = state.tr; if (rect.left == 0 && rect.right == rect.map.width) return false; for (let i3 = rect.right - 1; ; i3--) { removeColumn(tr4, rect, i3); if (i3 == rect.left) break; const table3 = rect.tableStart ? tr4.doc.nodeAt(rect.tableStart - 1) : tr4.doc; if (!table3) throw new RangeError("No table found"); rect.table = table3; rect.map = TableMap.get(table3); } dispatch(tr4); } return true; } function rowIsHeader(map7, table3, row2) { var _table$nodeAt; const headerCell = tableNodeTypes(table3.type.schema).header_cell; for (let col = 0; col < map7.width; col++) if (((_table$nodeAt = table3.nodeAt(map7.map[col + row2 * map7.width])) === null || _table$nodeAt === void 0 ? void 0 : _table$nodeAt.type) != headerCell) return false; return true; } function addRow(tr4, { map: map7, tableStart, table: table3 }, row2) { let rowPos = tableStart; for (let i3 = 0; i3 < row2; i3++) rowPos += table3.child(i3).nodeSize; const cells2 = []; let refRow = row2 > 0 ? -1 : 0; if (rowIsHeader(map7, table3, row2 + refRow)) refRow = row2 == 0 || row2 == map7.height ? null : 0; for (let col = 0, index4 = map7.width * row2; col < map7.width; col++, index4++) if (row2 > 0 && row2 < map7.height && map7.map[index4] == map7.map[index4 - map7.width]) { const pos = map7.map[index4]; const attrs = table3.nodeAt(pos).attrs; tr4.setNodeMarkup(tableStart + pos, null, { ...attrs, rowspan: attrs.rowspan + 1 }); col += attrs.colspan - 1; } else { var _table$nodeAt2; const type = refRow == null ? tableNodeTypes(table3.type.schema).cell : (_table$nodeAt2 = table3.nodeAt(map7.map[index4 + refRow * map7.width])) === null || _table$nodeAt2 === void 0 ? void 0 : _table$nodeAt2.type; const node2 = type === null || type === void 0 ? void 0 : type.createAndFill(); if (node2) cells2.push(node2); } tr4.insert(rowPos, tableNodeTypes(table3.type.schema).row.create(null, cells2)); return tr4; } function addRowBefore(state, dispatch) { if (!isInTable(state)) return false; if (dispatch) { const rect = selectedRect(state); dispatch(addRow(state.tr, rect, rect.top)); } return true; } function addRowAfter(state, dispatch) { if (!isInTable(state)) return false; if (dispatch) { const rect = selectedRect(state); dispatch(addRow(state.tr, rect, rect.bottom)); } return true; } function removeRow(tr4, { map: map7, table: table3, tableStart }, row2) { let rowPos = 0; for (let i3 = 0; i3 < row2; i3++) rowPos += table3.child(i3).nodeSize; const nextRow = rowPos + table3.child(row2).nodeSize; const mapFrom = tr4.mapping.maps.length; tr4.delete(rowPos + tableStart, nextRow + tableStart); const seen = /* @__PURE__ */ new Set(); for (let col = 0, index4 = row2 * map7.width; col < map7.width; col++, index4++) { const pos = map7.map[index4]; if (seen.has(pos)) continue; seen.add(pos); if (row2 > 0 && pos == map7.map[index4 - map7.width]) { const attrs = table3.nodeAt(pos).attrs; tr4.setNodeMarkup(tr4.mapping.slice(mapFrom).map(pos + tableStart), null, { ...attrs, rowspan: attrs.rowspan - 1 }); col += attrs.colspan - 1; } else if (row2 < map7.height && pos == map7.map[index4 + map7.width]) { const cell2 = table3.nodeAt(pos); const attrs = cell2.attrs; const copy3 = cell2.type.create({ ...attrs, rowspan: cell2.attrs.rowspan - 1 }, cell2.content); const newPos = map7.positionAt(row2 + 1, col, table3); tr4.insert(tr4.mapping.slice(mapFrom).map(tableStart + newPos), copy3); col += attrs.colspan - 1; } } } function deleteRow(state, dispatch) { if (!isInTable(state)) return false; if (dispatch) { const rect = selectedRect(state), tr4 = state.tr; if (rect.top == 0 && rect.bottom == rect.map.height) return false; for (let i3 = rect.bottom - 1; ; i3--) { removeRow(tr4, rect, i3); if (i3 == rect.top) break; const table3 = rect.tableStart ? tr4.doc.nodeAt(rect.tableStart - 1) : tr4.doc; if (!table3) throw new RangeError("No table found"); rect.table = table3; rect.map = TableMap.get(rect.table); } dispatch(tr4); } return true; } function isEmpty2(cell2) { const c3 = cell2.content; return c3.childCount == 1 && c3.child(0).isTextblock && c3.child(0).childCount == 0; } function cellsOverlapRectangle({ width, height, map: map7 }, rect) { let indexTop = rect.top * width + rect.left, indexLeft = indexTop; let indexBottom = (rect.bottom - 1) * width + rect.left, indexRight = indexTop + (rect.right - rect.left - 1); for (let i3 = rect.top; i3 < rect.bottom; i3++) { if (rect.left > 0 && map7[indexLeft] == map7[indexLeft - 1] || rect.right < width && map7[indexRight] == map7[indexRight + 1]) return true; indexLeft += width; indexRight += width; } for (let i3 = rect.left; i3 < rect.right; i3++) { if (rect.top > 0 && map7[indexTop] == map7[indexTop - width] || rect.bottom < height && map7[indexBottom] == map7[indexBottom + width]) return true; indexTop++; indexBottom++; } return false; } function mergeCells(state, dispatch) { const sel = state.selection; if (!(sel instanceof CellSelection) || sel.$anchorCell.pos == sel.$headCell.pos) return false; const rect = selectedRect(state), { map: map7 } = rect; if (cellsOverlapRectangle(map7, rect)) return false; if (dispatch) { const tr4 = state.tr; const seen = {}; let content5 = Fragment.empty; let mergedPos; let mergedCell; for (let row2 = rect.top; row2 < rect.bottom; row2++) for (let col = rect.left; col < rect.right; col++) { const cellPos = map7.map[row2 * map7.width + col]; const cell2 = rect.table.nodeAt(cellPos); if (seen[cellPos] || !cell2) continue; seen[cellPos] = true; if (mergedPos == null) { mergedPos = cellPos; mergedCell = cell2; } else { if (!isEmpty2(cell2)) content5 = content5.append(cell2.content); const mapped = tr4.mapping.map(cellPos + rect.tableStart); tr4.delete(mapped, mapped + cell2.nodeSize); } } if (mergedPos == null || mergedCell == null) return true; tr4.setNodeMarkup(mergedPos + rect.tableStart, null, { ...addColSpan(mergedCell.attrs, mergedCell.attrs.colspan, rect.right - rect.left - mergedCell.attrs.colspan), rowspan: rect.bottom - rect.top }); if (content5.size > 0) { const end = mergedPos + 1 + mergedCell.content.size; const start = isEmpty2(mergedCell) ? mergedPos + 1 : end; tr4.replaceWith(start + rect.tableStart, end + rect.tableStart, content5); } tr4.setSelection(new CellSelection(tr4.doc.resolve(mergedPos + rect.tableStart))); dispatch(tr4); } return true; } function splitCell(state, dispatch) { const nodeTypes = tableNodeTypes(state.schema); return splitCellWithType(({ node: node2 }) => { return nodeTypes[node2.type.spec.tableRole]; })(state, dispatch); } function splitCellWithType(getCellType) { return (state, dispatch) => { const sel = state.selection; let cellNode; let cellPos; if (!(sel instanceof CellSelection)) { var _cellAround; cellNode = cellWrapping(sel.$from); if (!cellNode) return false; cellPos = (_cellAround = cellAround(sel.$from)) === null || _cellAround === void 0 ? void 0 : _cellAround.pos; } else { if (sel.$anchorCell.pos != sel.$headCell.pos) return false; cellNode = sel.$anchorCell.nodeAfter; cellPos = sel.$anchorCell.pos; } if (cellNode == null || cellPos == null) return false; if (cellNode.attrs.colspan == 1 && cellNode.attrs.rowspan == 1) return false; if (dispatch) { let baseAttrs = cellNode.attrs; const attrs = []; const colwidth = baseAttrs.colwidth; if (baseAttrs.rowspan > 1) baseAttrs = { ...baseAttrs, rowspan: 1 }; if (baseAttrs.colspan > 1) baseAttrs = { ...baseAttrs, colspan: 1 }; const rect = selectedRect(state), tr4 = state.tr; for (let i3 = 0; i3 < rect.right - rect.left; i3++) attrs.push(colwidth ? { ...baseAttrs, colwidth: colwidth && colwidth[i3] ? [colwidth[i3]] : null } : baseAttrs); let lastCell; for (let row2 = rect.top; row2 < rect.bottom; row2++) { let pos = rect.map.positionAt(row2, rect.left, rect.table); if (row2 == rect.top) pos += cellNode.nodeSize; for (let col = rect.left, i3 = 0; col < rect.right; col++, i3++) { if (col == rect.left && row2 == rect.top) continue; tr4.insert(lastCell = tr4.mapping.map(pos + rect.tableStart, 1), getCellType({ node: cellNode, row: row2, col }).createAndFill(attrs[i3])); } } tr4.setNodeMarkup(cellPos, getCellType({ node: cellNode, row: rect.top, col: rect.left }), attrs[0]); if (sel instanceof CellSelection) tr4.setSelection(new CellSelection(tr4.doc.resolve(sel.$anchorCell.pos), lastCell ? tr4.doc.resolve(lastCell) : void 0)); dispatch(tr4); } return true; }; } function deprecated_toggleHeader(type) { return function(state, dispatch) { if (!isInTable(state)) return false; if (dispatch) { const types2 = tableNodeTypes(state.schema); const rect = selectedRect(state), tr4 = state.tr; const cells2 = 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 = cells2.map((pos) => rect.table.nodeAt(pos)); for (let i3 = 0; i3 < cells2.length; i3++) if (nodes[i3].type == types2.header_cell) tr4.setNodeMarkup(rect.tableStart + cells2[i3], types2.cell, nodes[i3].attrs); if (tr4.steps.length === 0) for (let i3 = 0; i3 < cells2.length; i3++) tr4.setNodeMarkup(rect.tableStart + cells2[i3], types2.header_cell, nodes[i3].attrs); dispatch(tr4); } return true; }; } function isHeaderEnabledByType(type, rect, types2) { 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 i3 = 0; i3 < cellPositions.length; i3++) { const cell2 = rect.table.nodeAt(cellPositions[i3]); if (cell2 && cell2.type !== types2.header_cell) return false; } return true; } function toggleHeader(type, options2) { options2 = options2 || { useDeprecatedLogic: false }; if (options2.useDeprecatedLogic) return deprecated_toggleHeader(type); return function(state, dispatch) { if (!isInTable(state)) return false; if (dispatch) { const types2 = tableNodeTypes(state.schema); const rect = selectedRect(state), tr4 = state.tr; const isHeaderRowEnabled = isHeaderEnabledByType("row", rect, types2); const isHeaderColumnEnabled = isHeaderEnabledByType("column", rect, types2); 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 ? types2.cell : types2.header_cell : type == "row" ? isHeaderRowEnabled ? types2.cell : types2.header_cell : types2.cell; rect.map.cellsInRect(cellsRect).forEach((relativeCellPos) => { const cellPos = relativeCellPos + rect.tableStart; const cell2 = tr4.doc.nodeAt(cellPos); if (cell2) tr4.setNodeMarkup(cellPos, newType, cell2.attrs); }); dispatch(tr4); } return true; }; } var toggleHeaderRow = toggleHeader("row", { useDeprecatedLogic: true }); var toggleHeaderColumn = toggleHeader("column", { useDeprecatedLogic: true }); var toggleHeaderCell = toggleHeader("cell", { useDeprecatedLogic: true }); function findNextCell($cell, dir) { if (dir < 0) { const before = $cell.nodeBefore; if (before) return $cell.pos - before.nodeSize; for (let row2 = $cell.index(-1) - 1, rowEnd = $cell.before(); row2 >= 0; row2--) { const rowNode = $cell.node(-1).child(row2); const lastChild = rowNode.lastChild; if (lastChild) return rowEnd - 1 - lastChild.nodeSize; rowEnd -= rowNode.nodeSize; } } else { if ($cell.index() < $cell.parent.childCount - 1) return $cell.pos + $cell.nodeAfter.nodeSize; const table3 = $cell.node(-1); for (let row2 = $cell.indexAfter(-1), rowStart = $cell.after(); row2 < table3.childCount; row2++) { const rowNode = table3.child(row2); if (rowNode.childCount) return rowStart + 1; rowStart += rowNode.nodeSize; } } return null; } function goToNextCell(direction) { return function(state, dispatch) { if (!isInTable(state)) return false; const cell2 = findNextCell(selectionCell(state), direction); if (cell2 == null) return false; if (dispatch) { const $cell = state.doc.resolve(cell2); dispatch(state.tr.setSelection(TextSelection.between($cell, moveCellForward($cell))).scrollIntoView()); } return true; }; } function deleteCellSelection(state, dispatch) { const sel = state.selection; if (!(sel instanceof CellSelection)) return false; if (dispatch) { const tr4 = state.tr; const baseContent = tableNodeTypes(state.schema).cell.createAndFill().content; sel.forEachCell((cell2, pos) => { if (!cell2.content.eq(baseContent)) tr4.replace(tr4.mapping.map(pos + 1), tr4.mapping.map(pos + cell2.nodeSize - 1), new Slice(baseContent, 0, 0)); }); if (tr4.docChanged) dispatch(tr4); } return true; } function pastedCells(slice2) { if (slice2.size === 0) return null; let { content: content5, openStart, openEnd } = slice2; while (content5.childCount == 1 && (openStart > 0 && openEnd > 0 || content5.child(0).type.spec.tableRole == "table")) { openStart--; openEnd--; content5 = content5.child(0).content; } const first2 = content5.child(0); const role = first2.type.spec.tableRole; const schema = first2.type.schema, rows = []; if (role == "row") for (let i3 = 0; i3 < content5.childCount; i3++) { let cells2 = content5.child(i3).content; const left = i3 ? 0 : Math.max(0, openStart - 1); const right = i3 < content5.childCount - 1 ? 0 : Math.max(0, openEnd - 1); if (left || right) cells2 = fitSlice(tableNodeTypes(schema).row, new Slice(cells2, left, right)).content; rows.push(cells2); } else if (role == "cell" || role == "header_cell") rows.push(openStart || openEnd ? fitSlice(tableNodeTypes(schema).row, new Slice(content5, openStart, openEnd)).content : content5); else return null; return ensureRectangular(schema, rows); } function ensureRectangular(schema, rows) { const widths = []; for (let i3 = 0; i3 < rows.length; i3++) { const row2 = rows[i3]; for (let j4 = row2.childCount - 1; j4 >= 0; j4--) { const { rowspan, colspan } = row2.child(j4).attrs; for (let r4 = i3; r4 < i3 + rowspan; r4++) widths[r4] = (widths[r4] || 0) + colspan; } } let width = 0; for (let r4 = 0; r4 < widths.length; r4++) width = Math.max(width, widths[r4]); for (let r4 = 0; r4 < widths.length; r4++) { if (r4 >= rows.length) rows.push(Fragment.empty); if (widths[r4] < width) { const empty4 = tableNodeTypes(schema).cell.createAndFill(); const cells2 = []; for (let i3 = widths[r4]; i3 < width; i3++) cells2.push(empty4); rows[r4] = rows[r4].append(Fragment.from(cells2)); } } return { height: rows.length, width, rows }; } function fitSlice(nodeType, slice2) { const node2 = nodeType.createAndFill(); return new Transform(node2).replace(0, node2.content.size, slice2).doc; } function clipCells({ width, height, rows }, newWidth, newHeight) { if (width != newWidth) { const added = []; const newRows = []; for (let row2 = 0; row2 < rows.length; row2++) { const frag = rows[row2], cells2 = []; for (let col = added[row2] || 0, i3 = 0; col < newWidth; i3++) { let cell2 = frag.child(i3 % frag.childCount); if (col + cell2.attrs.colspan > newWidth) cell2 = cell2.type.createChecked(removeColSpan(cell2.attrs, cell2.attrs.colspan, col + cell2.attrs.colspan - newWidth), cell2.content); cells2.push(cell2); col += cell2.attrs.colspan; for (let j4 = 1; j4 < cell2.attrs.rowspan; j4++) added[row2 + j4] = (added[row2 + j4] || 0) + cell2.attrs.colspan; } newRows.push(Fragment.from(cells2)); } rows = newRows; width = newWidth; } if (height != newHeight) { const newRows = []; for (let row2 = 0, i3 = 0; row2 < newHeight; row2++, i3++) { const cells2 = [], source = rows[i3 % height]; for (let j4 = 0; j4 < source.childCount; j4++) { let cell2 = source.child(j4); if (row2 + cell2.attrs.rowspan > newHeight) cell2 = cell2.type.create({ ...cell2.attrs, rowspan: Math.max(1, newHeight - cell2.attrs.rowspan) }, cell2.content); cells2.push(cell2); } newRows.push(Fragment.from(cells2)); } rows = newRows; height = newHeight; } return { width, height, rows }; } function growTable(tr4, map7, table3, start, width, height, mapFrom) { const schema = tr4.doc.type.schema; const types2 = tableNodeTypes(schema); let empty4; let emptyHead; if (width > map7.width) for (let row2 = 0, rowEnd = 0; row2 < map7.height; row2++) { const rowNode = table3.child(row2); rowEnd += rowNode.nodeSize; const cells2 = []; let add; if (rowNode.lastChild == null || rowNode.lastChild.type == types2.cell) add = empty4 || (empty4 = types2.cell.createAndFill()); else add = emptyHead || (emptyHead = types2.header_cell.createAndFill()); for (let i3 = map7.width; i3 < width; i3++) cells2.push(add); tr4.insert(tr4.mapping.slice(mapFrom).map(rowEnd - 1 + start), cells2); } if (height > map7.height) { const cells2 = []; for (let i3 = 0, start$1 = (map7.height - 1) * map7.width; i3 < Math.max(map7.width, width); i3++) { const header = i3 >= map7.width ? false : table3.nodeAt(map7.map[start$1 + i3]).type == types2.header_cell; cells2.push(header ? emptyHead || (emptyHead = types2.header_cell.createAndFill()) : empty4 || (empty4 = types2.cell.createAndFill())); } const emptyRow = types2.row.create(null, Fragment.from(cells2)), rows = []; for (let i3 = map7.height; i3 < height; i3++) rows.push(emptyRow); tr4.insert(tr4.mapping.slice(mapFrom).map(start + table3.nodeSize - 2), rows); } return !!(empty4 || emptyHead); } function isolateHorizontal(tr4, map7, table3, start, left, right, top, mapFrom) { if (top == 0 || top == map7.height) return false; let found2 = false; for (let col = left; col < right; col++) { const index4 = top * map7.width + col, pos = map7.map[index4]; if (map7.map[index4 - map7.width] == pos) { found2 = true; const cell2 = table3.nodeAt(pos); const { top: cellTop, left: cellLeft } = map7.findCell(pos); tr4.setNodeMarkup(tr4.mapping.slice(mapFrom).map(pos + start), null, { ...cell2.attrs, rowspan: top - cellTop }); tr4.insert(tr4.mapping.slice(mapFrom).map(map7.positionAt(top, cellLeft, table3)), cell2.type.createAndFill({ ...cell2.attrs, rowspan: cellTop + cell2.attrs.rowspan - top })); col += cell2.attrs.colspan - 1; } } return found2; } function isolateVertical(tr4, map7, table3, start, top, bottom, left, mapFrom) { if (left == 0 || left == map7.width) return false; let found2 = false; for (let row2 = top; row2 < bottom; row2++) { const index4 = row2 * map7.width + left, pos = map7.map[index4]; if (map7.map[index4 - 1] == pos) { found2 = true; const cell2 = table3.nodeAt(pos); const cellLeft = map7.colCount(pos); const updatePos = tr4.mapping.slice(mapFrom).map(pos + start); tr4.setNodeMarkup(updatePos, null, removeColSpan(cell2.attrs, left - cellLeft, cell2.attrs.colspan - (left - cellLeft))); tr4.insert(updatePos + cell2.nodeSize, cell2.type.createAndFill(removeColSpan(cell2.attrs, 0, left - cellLeft))); row2 += cell2.attrs.rowspan - 1; } } return found2; } function insertCells(state, dispatch, tableStart, rect, cells2) { let table3 = tableStart ? state.doc.nodeAt(tableStart - 1) : state.doc; if (!table3) throw new Error("No table found"); let map7 = TableMap.get(table3); const { top, left } = rect; const right = left + cells2.width, bottom = top + cells2.height; const tr4 = state.tr; let mapFrom = 0; function recomp() { table3 = tableStart ? tr4.doc.nodeAt(tableStart - 1) : tr4.doc; if (!table3) throw new Error("No table found"); map7 = TableMap.get(table3); mapFrom = tr4.mapping.maps.length; } if (growTable(tr4, map7, table3, tableStart, right, bottom, mapFrom)) recomp(); if (isolateHorizontal(tr4, map7, table3, tableStart, left, right, top, mapFrom)) recomp(); if (isolateHorizontal(tr4, map7, table3, tableStart, left, right, bottom, mapFrom)) recomp(); if (isolateVertical(tr4, map7, table3, tableStart, top, bottom, left, mapFrom)) recomp(); if (isolateVertical(tr4, map7, table3, tableStart, top, bottom, right, mapFrom)) recomp(); for (let row2 = top; row2 < bottom; row2++) { const from4 = map7.positionAt(row2, left, table3), to2 = map7.positionAt(row2, right, table3); tr4.replace(tr4.mapping.slice(mapFrom).map(from4 + tableStart), tr4.mapping.slice(mapFrom).map(to2 + tableStart), new Slice(cells2.rows[row2 - top], 0, 0)); } recomp(); tr4.setSelection(new CellSelection(tr4.doc.resolve(tableStart + map7.positionAt(top, left, table3)), tr4.doc.resolve(tableStart + map7.positionAt(bottom - 1, right - 1, table3)))); dispatch(tr4); } var handleKeyDown = keydownHandler({ ArrowLeft: arrow("horiz", -1), ArrowRight: arrow("horiz", 1), ArrowUp: arrow("vert", -1), ArrowDown: arrow("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(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 handleTripleClick2(view, pos) { const doc4 = view.state.doc, $cell = cellAround(doc4.resolve(pos)); if (!$cell) return false; view.dispatch(view.state.tr.setSelection(new CellSelection($cell))); return true; } function handlePaste(view, _2, slice2) { if (!isInTable(view.state)) return false; let cells2 = pastedCells(slice2); const sel = view.state.selection; if (sel instanceof CellSelection) { if (!cells2) cells2 = { width: 1, height: 1, rows: [Fragment.from(fitSlice(tableNodeTypes(view.state.schema).cell, slice2))] }; const table3 = sel.$anchorCell.node(-1); const start = sel.$anchorCell.start(-1); const rect = TableMap.get(table3).rectBetween(sel.$anchorCell.pos - start, sel.$headCell.pos - start); cells2 = clipCells(cells2, rect.right - rect.left, rect.bottom - rect.top); insertCells(view.state, view.dispatch, start, rect, cells2); return true; } else if (cells2) { const $cell = selectionCell(view.state); const start = $cell.start(-1); insertCells(view.state, view.dispatch, start, TableMap.get($cell.node(-1)).findCell($cell.pos - start), cells2); return true; } else return false; } function handleMouseDown$1(view, startEvent) { var _cellUnderMouse; if (startEvent.button != 0) return; if (startEvent.ctrlKey || startEvent.metaKey) return; const startDOMCell = domInCell(view, startEvent.target); let $anchor; if (startEvent.shiftKey && view.state.selection instanceof CellSelection) { setCellSelection(view.state.selection.$anchorCell, startEvent); startEvent.preventDefault(); } else if (startEvent.shiftKey && startDOMCell && ($anchor = cellAround(view.state.selection.$anchor)) != null && ((_cellUnderMouse = cellUnderMouse(view, startEvent)) === null || _cellUnderMouse === void 0 ? void 0 : _cellUnderMouse.pos) != $anchor.pos) { setCellSelection($anchor, startEvent); startEvent.preventDefault(); } else if (!startDOMCell) return; function setCellSelection($anchor$1, event) { let $head = cellUnderMouse(view, event); const starting = tableEditingKey.getState(view.state) == null; if (!$head || !inSameTable($anchor$1, $head)) if (starting) $head = $anchor$1; else return; const selection = new CellSelection($anchor$1, $head); if (starting || !view.state.selection.eq(selection)) { const tr4 = view.state.tr.setSelection(selection); if (starting) tr4.setMeta(tableEditingKey, $anchor$1.pos); view.dispatch(tr4); } } function stop() { view.root.removeEventListener("mouseup", stop); view.root.removeEventListener("dragstart", stop); view.root.removeEventListener("mousemove", move); if (tableEditingKey.getState(view.state) != null) view.dispatch(view.state.tr.setMeta(tableEditingKey, -1)); } function move(_event) { const event = _event; const anchor = tableEditingKey.getState(view.state); let $anchor$1; if (anchor != null) $anchor$1 = view.state.doc.resolve(anchor); else if (domInCell(view, event.target) != startDOMCell) { $anchor$1 = cellUnderMouse(view, startEvent); if (!$anchor$1) return stop(); } if ($anchor$1) setCellSelection($anchor$1, event); } view.root.addEventListener("mouseup", stop); view.root.addEventListener("dragstart", stop); view.root.addEventListener("mousemove", move); } 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; } function domInCell(view, dom) { for (; dom && dom != view.dom; dom = dom.parentNode) if (dom.nodeName == "TD" || dom.nodeName == "TH") return dom; return null; } function cellUnderMouse(view, event) { const mousePos = view.posAtCoords({ left: event.clientX, top: event.clientY }); if (!mousePos) return null; let { inside, pos } = mousePos; return inside >= 0 && cellAround(view.state.doc.resolve(inside)) || cellAround(view.state.doc.resolve(pos)); } var TableView = class { constructor(node2, defaultCellMinWidth) { this.node = node2; this.defaultCellMinWidth = defaultCellMinWidth; this.dom = document.createElement("div"); this.dom.className = "tableWrapper"; this.table = this.dom.appendChild(document.createElement("table")); this.table.style.setProperty("--default-cell-min-width", `${defaultCellMinWidth}px`); this.colgroup = this.table.appendChild(document.createElement("colgroup")); updateColumnsOnResize(node2, this.colgroup, this.table, defaultCellMinWidth); this.contentDOM = this.table.appendChild(document.createElement("tbody")); } update(node2) { if (node2.type != this.node.type) return false; this.node = node2; updateColumnsOnResize(node2, this.colgroup, this.table, this.defaultCellMinWidth); return true; } ignoreMutation(record) { return record.type == "attributes" && (record.target == this.table || this.colgroup.contains(record.target)); } }; function updateColumnsOnResize(node2, colgroup2, table3, defaultCellMinWidth, overrideCol, overrideValue) { let totalWidth = 0; let fixedWidth = true; let nextDOM = colgroup2.firstChild; const row2 = node2.firstChild; if (!row2) return; for (let i3 = 0, col = 0; i3 < row2.childCount; i3++) { const { colspan, colwidth } = row2.child(i3).attrs; for (let j4 = 0; j4 < colspan; j4++, col++) { const hasWidth = overrideCol == col ? overrideValue : colwidth && colwidth[j4]; const cssWidth = hasWidth ? hasWidth + "px" : ""; totalWidth += hasWidth || defaultCellMinWidth; if (!hasWidth) fixedWidth = false; if (!nextDOM) { const col$1 = document.createElement("col"); col$1.style.width = cssWidth; colgroup2.appendChild(col$1); } else { if (nextDOM.style.width != cssWidth) nextDOM.style.width = cssWidth; nextDOM = nextDOM.nextSibling; } } } while (nextDOM) { var _nextDOM$parentNode; const after = nextDOM.nextSibling; (_nextDOM$parentNode = nextDOM.parentNode) === null || _nextDOM$parentNode === void 0 || _nextDOM$parentNode.removeChild(nextDOM); nextDOM = after; } if (fixedWidth) { table3.style.width = totalWidth + "px"; table3.style.minWidth = ""; } else { table3.style.width = ""; table3.style.minWidth = totalWidth + "px"; } } var columnResizingPluginKey = new PluginKey("tableColumnResizing"); function columnResizing({ handleWidth = 5, cellMinWidth = 25, defaultCellMinWidth = 100, View = TableView, lastColumnResizable = true } = {}) { const plugin = new Plugin({ key: columnResizingPluginKey, state: { init(_2, state) { var _plugin$spec; const nodeViews = (_plugin$spec = plugin.spec) === null || _plugin$spec === void 0 || (_plugin$spec = _plugin$spec.props) === null || _plugin$spec === void 0 ? void 0 : _plugin$spec.nodeViews; const tableName = tableNodeTypes(state.schema).table.name; if (View && nodeViews) nodeViews[tableName] = (node2, view) => { return new View(node2, defaultCellMinWidth, view); }; return new ResizeState(-1, false); }, apply(tr4, prev) { return prev.apply(tr4); } }, props: { attributes: (state) => { const pluginState = columnResizingPluginKey.getState(state); return pluginState && pluginState.activeHandle > -1 ? { class: "resize-cursor" } : {}; }, handleDOMEvents: { mousemove: (view, event) => { handleMouseMove(view, event, handleWidth, lastColumnResizable); }, mouseleave: (view) => { handleMouseLeave(view); }, mousedown: (view, event) => { handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth); } }, decorations: (state) => { const pluginState = columnResizingPluginKey.getState(state); if (pluginState && pluginState.activeHandle > -1) return handleDecorations(state, pluginState.activeHandle); }, nodeViews: {} } }); return plugin; } var ResizeState = class ResizeState2 { constructor(activeHandle, dragging) { this.activeHandle = activeHandle; this.dragging = dragging; } apply(tr4) { const state = this; const action = tr4.getMeta(columnResizingPluginKey); if (action && action.setHandle != null) return new ResizeState2(action.setHandle, false); if (action && action.setDragging !== void 0) return new ResizeState2(state.activeHandle, action.setDragging); if (state.activeHandle > -1 && tr4.docChanged) { let handle4 = tr4.mapping.map(state.activeHandle, -1); if (!pointsAtCell(tr4.doc.resolve(handle4))) handle4 = -1; return new ResizeState2(handle4, state.dragging); } return state; } }; function handleMouseMove(view, event, handleWidth, lastColumnResizable) { if (!view.editable) return; const pluginState = columnResizingPluginKey.getState(view.state); if (!pluginState) return; if (!pluginState.dragging) { const target = domCellAround(event.target); let cell2 = -1; if (target) { const { left, right } = target.getBoundingClientRect(); if (event.clientX - left <= handleWidth) cell2 = edgeCell(view, event, "left", handleWidth); else if (right - event.clientX <= handleWidth) cell2 = edgeCell(view, event, "right", handleWidth); } if (cell2 != pluginState.activeHandle) { if (!lastColumnResizable && cell2 !== -1) { const $cell = view.state.doc.resolve(cell2); const table3 = $cell.node(-1); const map7 = TableMap.get(table3); const tableStart = $cell.start(-1); if (map7.colCount($cell.pos - tableStart) + $cell.nodeAfter.attrs.colspan - 1 == map7.width - 1) return; } updateHandle(view, cell2); } } } function handleMouseLeave(view) { if (!view.editable) return; const pluginState = columnResizingPluginKey.getState(view.state); if (pluginState && pluginState.activeHandle > -1 && !pluginState.dragging) updateHandle(view, -1); } function handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth) { var _view$dom$ownerDocume; if (!view.editable) return false; const win = (_view$dom$ownerDocume = view.dom.ownerDocument.defaultView) !== null && _view$dom$ownerDocume !== void 0 ? _view$dom$ownerDocume : window; const pluginState = columnResizingPluginKey.getState(view.state); if (!pluginState || pluginState.activeHandle == -1 || pluginState.dragging) return false; const cell2 = view.state.doc.nodeAt(pluginState.activeHandle); const width = currentColWidth(view, pluginState.activeHandle, cell2.attrs); view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setDragging: { startX: event.clientX, startWidth: width } })); function finish(event$1) { win.removeEventListener("mouseup", finish); win.removeEventListener("mousemove", move); const pluginState$1 = columnResizingPluginKey.getState(view.state); if (pluginState$1 === null || pluginState$1 === void 0 ? void 0 : pluginState$1.dragging) { updateColumnWidth(view, pluginState$1.activeHandle, draggedWidth(pluginState$1.dragging, event$1, cellMinWidth)); view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null })); } } function move(event$1) { if (!event$1.which) return finish(event$1); const pluginState$1 = columnResizingPluginKey.getState(view.state); if (!pluginState$1) return; if (pluginState$1.dragging) { const dragged = draggedWidth(pluginState$1.dragging, event$1, cellMinWidth); displayColumnWidth(view, pluginState$1.activeHandle, dragged, defaultCellMinWidth); } } displayColumnWidth(view, pluginState.activeHandle, width, defaultCellMinWidth); win.addEventListener("mouseup", finish); win.addEventListener("mousemove", move); event.preventDefault(); return true; } function currentColWidth(view, cellPos, { colspan, colwidth }) { const width = colwidth && colwidth[colwidth.length - 1]; if (width) return width; const dom = view.domAtPos(cellPos); let domWidth = dom.node.childNodes[dom.offset].offsetWidth, parts = colspan; if (colwidth) { for (let i3 = 0; i3 < colspan; i3++) if (colwidth[i3]) { domWidth -= colwidth[i3]; parts--; } } return domWidth / parts; } function domCellAround(target) { while (target && target.nodeName != "TD" && target.nodeName != "TH") target = target.classList && target.classList.contains("ProseMirror") ? null : target.parentNode; return target; } function edgeCell(view, event, side, handleWidth) { const offset4 = side == "right" ? -handleWidth : handleWidth; const found2 = view.posAtCoords({ left: event.clientX + offset4, top: event.clientY }); if (!found2) return -1; const { pos } = found2; const $cell = cellAround(view.state.doc.resolve(pos)); if (!$cell) return -1; if (side == "right") return $cell.pos; const map7 = TableMap.get($cell.node(-1)), start = $cell.start(-1); const index4 = map7.map.indexOf($cell.pos - start); return index4 % map7.width == 0 ? -1 : start + map7.map[index4 - 1]; } function draggedWidth(dragging, event, resizeMinWidth) { const offset4 = event.clientX - dragging.startX; return Math.max(resizeMinWidth, dragging.startWidth + offset4); } function updateHandle(view, value) { view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value })); } function updateColumnWidth(view, cell2, width) { const $cell = view.state.doc.resolve(cell2); const table3 = $cell.node(-1), map7 = TableMap.get(table3), start = $cell.start(-1); const col = map7.colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1; const tr4 = view.state.tr; for (let row2 = 0; row2 < map7.height; row2++) { const mapIndex = row2 * map7.width + col; if (row2 && map7.map[mapIndex] == map7.map[mapIndex - map7.width]) continue; const pos = map7.map[mapIndex]; const attrs = table3.nodeAt(pos).attrs; const index4 = attrs.colspan == 1 ? 0 : col - map7.colCount(pos); if (attrs.colwidth && attrs.colwidth[index4] == width) continue; const colwidth = attrs.colwidth ? attrs.colwidth.slice() : zeroes(attrs.colspan); colwidth[index4] = width; tr4.setNodeMarkup(start + pos, null, { ...attrs, colwidth }); } if (tr4.docChanged) view.dispatch(tr4); } function displayColumnWidth(view, cell2, width, defaultCellMinWidth) { const $cell = view.state.doc.resolve(cell2); const table3 = $cell.node(-1), start = $cell.start(-1); const col = TableMap.get(table3).colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1; let dom = view.domAtPos($cell.start(-1)).node; while (dom && dom.nodeName != "TABLE") dom = dom.parentNode; if (!dom) return; updateColumnsOnResize(table3, dom.firstChild, dom, defaultCellMinWidth, col, width); } function zeroes(n) { return Array(n).fill(0); } function handleDecorations(state, cell2) { const decorations = []; const $cell = state.doc.resolve(cell2); const table3 = $cell.node(-1); if (!table3) return DecorationSet.empty; const map7 = TableMap.get(table3); const start = $cell.start(-1); const col = map7.colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1; for (let row2 = 0; row2 < map7.height; row2++) { const index4 = col + row2 * map7.width; if ((col == map7.width - 1 || map7.map[index4] != map7.map[index4 + 1]) && (row2 == 0 || map7.map[index4] != map7.map[index4 - map7.width])) { var _columnResizingPlugin; const cellPos = map7.map[index4]; const pos = start + cellPos + table3.nodeAt(cellPos).nodeSize - 1; const dom = document.createElement("div"); dom.className = "column-resize-handle"; if ((_columnResizingPlugin = columnResizingPluginKey.getState(state)) === null || _columnResizingPlugin === void 0 ? void 0 : _columnResizingPlugin.dragging) decorations.push(Decoration.node(start + cellPos, start + cellPos + table3.nodeAt(cellPos).nodeSize, { class: "column-resize-dragging" })); decorations.push(Decoration.widget(pos, dom)); } } return DecorationSet.create(state.doc, decorations); } function tableEditing({ allowTableNodeSelection = false } = {}) { return new Plugin({ key: tableEditingKey, state: { init() { return null; }, apply(tr4, cur) { const set = tr4.getMeta(tableEditingKey); if (set != null) return set == -1 ? null : set; if (cur == null || !tr4.docChanged) return cur; const { deleted, pos } = tr4.mapping.mapResult(cur); return deleted ? null : pos; } }, props: { decorations: drawCellSelection, handleDOMEvents: { mousedown: handleMouseDown$1 }, createSelectionBetween(view) { return tableEditingKey.getState(view.state) != null ? view.state.selection : null; }, handleTripleClick: handleTripleClick2, handleKeyDown, handlePaste }, appendTransaction(_2, oldState, state) { return normalizeSelection(state, fixTables(state, oldState), allowTableNodeSelection); } }); } // ../../node_modules/.pnpm/@tiptap+core@3.14.0_@tiptap+pm@3.14.0/node_modules/@tiptap/core/dist/jsx-runtime/jsx-runtime.js var h2 = (tag, attributes) => { if (tag === "slot") { return 0; } if (tag instanceof Function) { return tag(attributes); } const { children, ...rest } = attributes != null ? attributes : {}; if (tag === "svg") { throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead"); } return [tag, rest, children]; }; // ../../node_modules/.pnpm/@tiptap+extension-bold@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0_/node_modules/@tiptap/extension-bold/dist/index.js var starInputRegex = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/; var starPasteRegex = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g; var underscoreInputRegex = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/; var underscorePasteRegex = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g; var Bold = Mark2.create({ name: "bold", addOptions() { return { HTMLAttributes: {} }; }, parseHTML() { return [ { tag: "strong" }, { tag: "b", getAttrs: (node2) => node2.style.fontWeight !== "normal" && null }, { style: "font-weight=400", clearMark: (mark2) => mark2.type.name === this.name }, { style: "font-weight", getAttrs: (value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null } ]; }, renderHTML({ HTMLAttributes }) { return h2("strong", { ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), children: h2("slot", {}) }); }, markdownTokenName: "strong", parseMarkdown: (token, helpers) => { return helpers.applyMark("bold", helpers.parseInline(token.tokens || [])); }, renderMarkdown: (node2, h7) => { return `**${h7.renderChildren(node2)}**`; }, addCommands() { return { setBold: () => ({ commands }) => { return commands.setMark(this.name); }, toggleBold: () => ({ commands }) => { return commands.toggleMark(this.name); }, unsetBold: () => ({ commands }) => { return commands.unsetMark(this.name); } }; }, addKeyboardShortcuts() { return { "Mod-b": () => this.editor.commands.toggleBold(), "Mod-B": () => this.editor.commands.toggleBold() }; }, addInputRules() { return [ markInputRule({ find: starInputRegex, type: this.type }), markInputRule({ find: underscoreInputRegex, type: this.type }) ]; }, addPasteRules() { return [ markPasteRule({ find: starPasteRegex, type: this.type }), markPasteRule({ find: underscorePasteRegex, type: this.type }) ]; } }); var index_default = Bold; // ../../node_modules/.pnpm/@tiptap+extension-code@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0_/node_modules/@tiptap/extension-code/dist/index.js var inputRegex = /(^|[^`])`([^`]+)`(?!`)$/; var pasteRegex = /(^|[^`])`([^`]+)`(?!`)/g; var Code = Mark2.create({ name: "code", addOptions() { return { HTMLAttributes: {} }; }, excludes: "_", code: true, exitable: true, parseHTML() { return [{ tag: "code" }]; }, renderHTML({ HTMLAttributes }) { return ["code", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; }, markdownTokenName: "codespan", parseMarkdown: (token, helpers) => { return helpers.applyMark("code", [{ type: "text", text: token.text || "" }]); }, renderMarkdown: (node2, h7) => { if (!node2.content) { return ""; } return `\`${h7.renderChildren(node2.content)}\``; }, addCommands() { return { setCode: () => ({ commands }) => { return commands.setMark(this.name); }, toggleCode: () => ({ commands }) => { return commands.toggleMark(this.name); }, unsetCode: () => ({ commands }) => { return commands.unsetMark(this.name); } }; }, addKeyboardShortcuts() { return { "Mod-e": () => this.editor.commands.toggleCode() }; }, addInputRules() { return [ markInputRule({ find: inputRegex, type: this.type }) ]; }, addPasteRules() { return [ markPasteRule({ find: pasteRegex, type: this.type }) ]; } }); var index_default2 = Code; // ../../node_modules/.pnpm/@tiptap+extension-italic@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0_/node_modules/@tiptap/extension-italic/dist/index.js var starInputRegex2 = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/; var starPasteRegex2 = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g; var underscoreInputRegex2 = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/; var underscorePasteRegex2 = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g; var Italic = Mark2.create({ name: "italic", addOptions() { return { HTMLAttributes: {} }; }, parseHTML() { return [ { tag: "em" }, { tag: "i", getAttrs: (node2) => node2.style.fontStyle !== "normal" && null }, { style: "font-style=normal", clearMark: (mark2) => mark2.type.name === this.name }, { style: "font-style=italic" } ]; }, renderHTML({ HTMLAttributes }) { return ["em", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; }, addCommands() { return { setItalic: () => ({ commands }) => { return commands.setMark(this.name); }, toggleItalic: () => ({ commands }) => { return commands.toggleMark(this.name); }, unsetItalic: () => ({ commands }) => { return commands.unsetMark(this.name); } }; }, markdownTokenName: "em", parseMarkdown: (token, helpers) => { return helpers.applyMark("italic", helpers.parseInline(token.tokens || [])); }, renderMarkdown: (node2, h7) => { return `*${h7.renderChildren(node2)}*`; }, addKeyboardShortcuts() { return { "Mod-i": () => this.editor.commands.toggleItalic(), "Mod-I": () => this.editor.commands.toggleItalic() }; }, addInputRules() { return [ markInputRule({ find: starInputRegex2, type: this.type }), markInputRule({ find: underscoreInputRegex2, type: this.type }) ]; }, addPasteRules() { return [ markPasteRule({ find: starPasteRegex2, type: this.type }), markPasteRule({ find: underscorePasteRegex2, type: this.type }) ]; } }); var index_default3 = Italic; // ../../node_modules/.pnpm/@tiptap+extension-strike@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0_/node_modules/@tiptap/extension-strike/dist/index.js var inputRegex2 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/; var pasteRegex2 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g; var Strike = Mark2.create({ name: "strike", addOptions() { return { HTMLAttributes: {} }; }, parseHTML() { return [ { tag: "s" }, { tag: "del" }, { tag: "strike" }, { style: "text-decoration", consuming: false, getAttrs: (style3) => style3.includes("line-through") ? {} : false } ]; }, renderHTML({ HTMLAttributes }) { return ["s", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; }, markdownTokenName: "del", parseMarkdown: (token, helpers) => { return helpers.applyMark("strike", helpers.parseInline(token.tokens || [])); }, renderMarkdown: (node2, h7) => { return `~~${h7.renderChildren(node2)}~~`; }, addCommands() { return { setStrike: () => ({ commands }) => { return commands.setMark(this.name); }, toggleStrike: () => ({ commands }) => { return commands.toggleMark(this.name); }, unsetStrike: () => ({ commands }) => { return commands.unsetMark(this.name); } }; }, addKeyboardShortcuts() { return { "Mod-Shift-s": () => this.editor.commands.toggleStrike() }; }, addInputRules() { return [ markInputRule({ find: inputRegex2, type: this.type }) ]; }, addPasteRules() { return [ markPasteRule({ find: pasteRegex2, type: this.type }) ]; } }); var index_default4 = Strike; // ../../node_modules/.pnpm/@tiptap+extension-underline@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0_/node_modules/@tiptap/extension-underline/dist/index.js var Underline = Mark2.create({ name: "underline", addOptions() { return { HTMLAttributes: {} }; }, parseHTML() { return [ { tag: "u" }, { style: "text-decoration", consuming: false, getAttrs: (style3) => style3.includes("underline") ? {} : false } ]; }, renderHTML({ HTMLAttributes }) { return ["u", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; }, parseMarkdown(token, helpers) { return helpers.applyMark(this.name || "underline", helpers.parseInline(token.tokens || [])); }, renderMarkdown(node2, helpers) { return `++${helpers.renderChildren(node2)}++`; }, markdownTokenizer: { name: "underline", level: "inline", start(src) { return src.indexOf("++"); }, tokenize(src, _tokens, lexer) { const rule = /^(\+\+)([\s\S]+?)(\+\+)/; const match2 = rule.exec(src); if (!match2) { return void 0; } const innerContent = match2[2].trim(); return { type: "underline", raw: match2[0], text: innerContent, tokens: lexer.inlineTokens(innerContent) }; } }, addCommands() { return { setUnderline: () => ({ commands }) => { return commands.setMark(this.name); }, toggleUnderline: () => ({ commands }) => { return commands.toggleMark(this.name); }, unsetUnderline: () => ({ commands }) => { return commands.unsetMark(this.name); } }; }, addKeyboardShortcuts() { return { "Mod-u": () => this.editor.commands.toggleUnderline(), "Mod-U": () => this.editor.commands.toggleUnderline() }; } }); var index_default5 = Underline; // ../../node_modules/.pnpm/prosemirror-highlight@0.13.0_@shikijs+types@3.13.0_@types+hast@3.0.4_highlight.js@11.11_df16c183cc63c612ec9e976187502a02/node_modules/prosemirror-highlight/dist/index.js var DecorationCache = class _DecorationCache { constructor(cache) { this.cache = new Map(cache); } /** * Gets the cache entry at the given doc position, or null if it doesn't exist * @param pos The doc position of the node you want the cache for */ get(pos) { return this.cache.get(pos); } /** * Sets the cache entry at the given position with the give node/decoration * values * @param pos The doc position of the node to set the cache for * @param node The node to place in cache * @param decorations The decorations to place in cache */ set(pos, node2, decorations) { if (pos < 0) { return; } this.cache.set(pos, [node2, decorations]); } /** * Removes the value at the oldPos (if it exists) and sets the new position to * the given values * @param oldPos The old node position to overwrite * @param newPos The new node position to set the cache for * @param node The new node to place in cache * @param decorations The new decorations to place in cache */ replace(oldPos, newPos, node2, decorations) { this.remove(oldPos); this.set(newPos, node2, decorations); } /** * Removes the cache entry at the given position * @param pos The doc position to remove from cache */ remove(pos) { this.cache.delete(pos); } /** * Invalidates the cache by removing all decoration entries on nodes that have * changed, updating the positions of the nodes that haven't and removing all * the entries that have been deleted; NOTE: this does not affect the current * cache, but returns an entirely new one * @param tr A transaction to map the current cache to */ invalidate(tr4) { const returnCache = new _DecorationCache(this.cache); const mapping = tr4.mapping; this.cache.forEach(([node2, decorations], pos) => { if (pos < 0) { return; } const result = mapping.mapResult(pos); const mappedNode = tr4.doc.nodeAt(result.pos); if (result.deleted || !(mappedNode == null ? void 0 : mappedNode.eq(node2))) { returnCache.remove(pos); } else if (pos !== result.pos) { const updatedDecorations = decorations.map((d) => { return d.map(mapping, 0, 0); }).filter((d) => d != null); returnCache.replace(pos, result.pos, mappedNode, updatedDecorations); } }); return returnCache; } }; function createHighlightPlugin({ parser, nodeTypes = ["code_block", "codeBlock"], languageExtractor = (node2) => node2.attrs.language }) { const key2 = new PluginKey("prosemirror-highlight"); return new Plugin({ key: key2, state: { init(_2, instance) { const cache = new DecorationCache(); const [decorations, promises] = calculateDecoration( instance.doc, parser, nodeTypes, languageExtractor, cache ); return { cache, decorations, promises }; }, apply: (tr4, data) => { const cache = data.cache.invalidate(tr4); const refresh = !!tr4.getMeta("prosemirror-highlight-refresh"); if (!tr4.docChanged && !refresh) { const decorations2 = data.decorations.map(tr4.mapping, tr4.doc); const promises2 = data.promises; return { cache, decorations: decorations2, promises: promises2 }; } const [decorations, promises] = calculateDecoration( tr4.doc, parser, nodeTypes, languageExtractor, cache ); return { cache, decorations, promises }; } }, view: (view) => { const promises = /* @__PURE__ */ new Set(); const refresh = () => { if (promises.size > 0) { return; } const tr4 = view.state.tr.setMeta("prosemirror-highlight-refresh", true); view.dispatch(tr4); }; const check = () => { var _a2; const state = key2.getState(view.state); for (const promise of (_a2 = state == null ? void 0 : state.promises) != null ? _a2 : []) { promises.add(promise); promise.then(() => { promises.delete(promise); refresh(); }).catch(() => { promises.delete(promise); }); } }; check(); return { update: () => { check(); } }; }, props: { decorations(state) { var _a2; return (_a2 = this.getState(state)) == null ? void 0 : _a2.decorations; } } }); } function calculateDecoration(doc4, parser, nodeTypes, languageExtractor, cache) { const result = []; const promises = []; doc4.descendants((node2, pos) => { if (!node2.type.isTextblock) { return true; } if (nodeTypes.includes(node2.type.name)) { const language = languageExtractor(node2); const cached = cache.get(pos); if (cached) { const [_2, decorations] = cached; result.push(...decorations); } else { const decorations = parser({ content: node2.textContent, language: language || void 0, pos, size: node2.nodeSize }); if (decorations && Array.isArray(decorations)) { cache.set(pos, node2, decorations); result.push(...decorations); } else if (decorations instanceof Promise) { cache.remove(pos); promises.push(decorations); } } } return false; }); return [DecorationSet.create(doc4, result), promises]; } // ../../node_modules/.pnpm/prosemirror-highlight@0.13.0_@shikijs+types@3.13.0_@types+hast@3.0.4_highlight.js@11.11_df16c183cc63c612ec9e976187502a02/node_modules/prosemirror-highlight/dist/shiki.js function createParser(highlighter, options2) { return function parser({ content: content5, language, pos, size: size5 }) { var _a2; const decorations = []; const { tokens, fg, bg, rootStyle } = highlighter.codeToTokens(content5, { lang: language, // Use provided options for themes or just use first loaded theme ...options2 != null ? options2 : { theme: highlighter.getLoadedThemes()[0] } }); const style3 = rootStyle || (fg && bg ? `--prosemirror-highlight:${fg};--prosemirror-highlight-bg:${bg}` : ""); if (style3) { const decoration = Decoration.node(pos, pos + size5, { style: style3 }); decorations.push(decoration); } let from4 = pos + 1; for (const line of tokens) { for (const token of line) { const to2 = from4 + token.content.length; const decoration = Decoration.inline(from4, to2, { // When using `options.themes` the `htmlStyle` field will be set, otherwise `color` will be set style: stringifyTokenStyle( (_a2 = token.htmlStyle) != null ? _a2 : `color: ${token.color}` ), class: "shiki" }); decorations.push(decoration); from4 = to2; } from4 += 1; } return decorations; }; } function stringifyTokenStyle(token) { if (typeof token === "string") return token; return Object.entries(token).map(([key2, value]) => `${key2}:${value}`).join(";"); } // ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/defaultBlocks-DvCGYzqu.js var Oe = Object.defineProperty; var _e = (e2, t2, n) => t2 in e2 ? Oe(e2, t2, { enumerable: true, configurable: true, writable: true, value: n }) : e2[t2] = n; var M3 = (e2, t2, n) => _e(e2, typeof t2 != "symbol" ? t2 + "" : t2, n); var mt2 = () => typeof navigator < "u" && (/Mac/.test(navigator.platform) || /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent)); function L2(e2, t2 = "Ctrl") { return mt2() ? e2.replace("Mod", "⌘") : e2.replace("Mod", t2); } function D2(...e2) { return [ // Converts to & from set to remove duplicates. ...new Set( e2.filter((t2) => t2).join(" ").split(" ") ) ].join(" "); } function gt2(e2, t2, n, o2) { const r4 = document.createElement("div"); r4.className = D2( "bn-block-content", n.class ), r4.setAttribute("data-content-type", e2); for (const [s2, i3] of Object.entries(n)) s2 !== "class" && r4.setAttribute(s2, i3); const a3 = document.createElement(t2); a3.className = D2( "bn-inline-content", o2.class ); for (const [s2, i3] of Object.entries( o2 )) s2 !== "class" && a3.setAttribute(s2, i3); return r4.appendChild(a3), { dom: r4, contentDOM: a3 }; } var le = (e2, t2) => { let n = bt(e2, t2.pmSchema); n.type.name === "blockContainer" && (n = n.firstChild); const o2 = t2.pmSchema.nodes[n.type.name].spec.toDOM; if (o2 === void 0) throw new Error( "This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`." ); const r4 = o2(n); if (typeof r4 != "object" || !("dom" in r4)) throw new Error( "Cannot use this block's default HTML serialization as its corresponding TipTap node's `renderHTML` function does not return an object with the `dom` property." ); return r4; }; function bt2(e2, t2 = "
") { const n = e2.querySelectorAll("p"); if (n.length > 1) { const o2 = n[0]; for (let r4 = 1; r4 < n.length; r4++) { const a3 = n[r4]; o2.innerHTML += t2 + a3.innerHTML, a3.remove(); } } } function W(e2) { return "data-" + e2.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(); } function po(e2) { const t2 = e2.split("/"); return !t2.length || // invalid? t2[t2.length - 1] === "" ? e2 : t2[t2.length - 1]; } function fo(e2) { var n; const t2 = [ "mp4", "webm", "ogg", "mov", "mkv", "flv", "avi", "wmv", "m4v" ]; try { const r4 = ((n = new URL(e2).pathname.split(".").pop()) == null ? void 0 : n.toLowerCase()) || ""; return t2.includes(r4); } catch { return false; } } function Ct2(e2) { const t2 = {}; return Object.entries(e2).forEach(([n, o2]) => { t2[n] = { default: o2.default, keepOnSplit: true, // Props are displayed in kebab-case as HTML attributes. If a prop's // value is the same as its default, we don't display an HTML // attribute for it. parseHTML: (r4) => { const a3 = r4.getAttribute(W(n)); if (a3 === null) return null; if (o2.default === void 0 && o2.type === "boolean" || o2.default !== void 0 && typeof o2.default == "boolean") return a3 === "true" ? true : a3 === "false" ? false : null; if (o2.default === void 0 && o2.type === "number" || o2.default !== void 0 && typeof o2.default == "number") { const s2 = parseFloat(a3); return !Number.isNaN(s2) && Number.isFinite(s2) ? s2 : null; } return a3; }, renderHTML: (r4) => r4[n] !== o2.default ? { [W(n)]: r4[n] } : {} }; }), t2; } function kt2(e2, t2, n, o2) { const r4 = e2(); if (r4 === void 0) throw new Error("Cannot find node position"); const s2 = n.state.doc.resolve(r4).node().attrs.id; if (!s2) throw new Error("Block doesn't have id"); const i3 = t2.getBlock(s2); if (i3.type !== o2) throw new Error("Block type does not match"); return i3; } function Z2(e2, t2, n, o2, r4 = false, a3) { const s2 = document.createElement("div"); if (a3 !== void 0) for (const [i3, c3] of Object.entries(a3)) i3 !== "class" && s2.setAttribute(i3, c3); s2.className = D2( "bn-block-content", (a3 == null ? void 0 : a3.class) || "" ), s2.setAttribute("data-content-type", t2); for (const [i3, c3] of Object.entries(n)) { const u2 = o2[i3].default; c3 !== u2 && s2.setAttribute(W(i3), c3); } return r4 && s2.setAttribute("data-file-block", ""), s2.appendChild(e2.dom), e2.contentDOM && (e2.contentDOM.className = D2( "bn-inline-content", e2.contentDOM.className )), { ...e2, dom: s2 }; } function yt2(e2, t2, n) { return { config: { type: e2.type, content: e2.content, propSchema: t2 }, implementation: { node: e2.node, render: le, toExternalHTML: le }, extensions: n }; } function vt(e2, t2) { e2.stopEvent = (n) => (n.type === "mousedown" && setTimeout(() => { t2.view.dom.blur(); }, 10), true); } function Et(e2, t2) { const n = [ { tag: "[data-content-type=" + e2.type + "]", contentElement: ".bn-inline-content" } ]; return t2.parse && n.push({ tag: "*", getAttrs(o2) { var a3; if (typeof o2 == "string") return false; const r4 = (a3 = t2.parse) == null ? void 0 : a3.call(t2, o2); return r4 === void 0 ? false : r4; }, // Because we do the parsing ourselves, we want to preserve whitespace for content we've parsed preserveWhitespace: true, getContent: e2.content === "inline" || e2.content === "none" ? (o2, r4) => { var a3; if (t2.parseContent) return t2.parseContent({ el: o2, schema: r4 }); if (e2.content === "inline") { const i3 = o2.cloneNode(true); return bt2( i3, (a3 = t2.meta) != null && a3.code ? ` ` : "
" ), DOMParser2.fromSchema(r4).parse(i3, { topNode: r4.nodes.paragraph.create(), preserveWhitespace: true }).content; } return Fragment.empty; } : void 0 }), n; } function ho(e2, t2, n, o2) { var a3, s2, i3, c3; const r4 = t2.node || Node3.create({ name: e2.type, content: e2.content === "inline" ? "inline*" : e2.content === "none" ? "" : e2.content, group: "blockContent", selectable: ((a3 = t2.meta) == null ? void 0 : a3.selectable) ?? true, isolating: ((s2 = t2.meta) == null ? void 0 : s2.isolating) ?? true, code: ((i3 = t2.meta) == null ? void 0 : i3.code) ?? false, defining: ((c3 = t2.meta) == null ? void 0 : c3.defining) ?? true, priority: o2, addAttributes() { return Ct2(e2.propSchema); }, parseHTML() { return Et(e2, t2); }, renderHTML({ HTMLAttributes: l2 }) { var d; const u2 = document.createElement("div"); return Z2( { dom: u2, contentDOM: e2.content === "inline" ? u2 : void 0 }, e2.type, {}, e2.propSchema, ((d = t2.meta) == null ? void 0 : d.fileBlockAccept) !== void 0, l2 ); }, addNodeView() { return (l2) => { var f6, E4; const u2 = this.options.editor, d = kt2( l2.getPos, u2, this.editor, e2.type ), p4 = ((f6 = this.options.domAttributes) == null ? void 0 : f6.blockContent) || {}, m2 = t2.render.call( { blockContentDOMAttributes: p4, props: l2, renderType: "nodeView" }, d, u2 ); return ((E4 = t2.meta) == null ? void 0 : E4.selectable) === false && vt(m2, this.editor), m2; }; } }); if (r4.name !== e2.type) throw new Error( "Node name does not match block type. This is a bug in BlockNote." ); return { config: e2, implementation: { ...t2, node: r4, render(l2, u2) { var p4; const d = ((p4 = r4.options.domAttributes) == null ? void 0 : p4.blockContent) || {}; return t2.render.call( { blockContentDOMAttributes: d, props: void 0, renderType: "dom" }, l2, u2 ); }, // TODO: this should not have wrapInBlockStructure and generally be a lot simpler // post-processing in externalHTMLExporter should not be necessary toExternalHTML: (l2, u2) => { var p4, m2; const d = ((p4 = r4.options.domAttributes) == null ? void 0 : p4.blockContent) || {}; return ((m2 = t2.toExternalHTML) == null ? void 0 : m2.call( { blockContentDOMAttributes: d }, l2, u2 )) ?? t2.render.call( { blockContentDOMAttributes: d, renderType: "dom", props: void 0 }, l2, u2 ); } }, extensions: n }; } function mo(e2) { return e2; } function v2(e2, t2, n) { return (o2 = {}) => { const r4 = typeof e2 == "function" ? e2(o2) : e2, a3 = typeof t2 == "function" ? t2(o2) : t2, s2 = n ? typeof n == "function" ? n(o2) : n : void 0; return { config: r4, implementation: { ...a3, // TODO: this should not have wrapInBlockStructure and generally be a lot simpler // post-processing in externalHTMLExporter should not be necessary toExternalHTML(i3, c3) { var u2, d; const l2 = (u2 = a3.toExternalHTML) == null ? void 0 : u2.call( { blockContentDOMAttributes: this.blockContentDOMAttributes }, i3, c3 ); if (l2 !== void 0) return Z2( l2, i3.type, i3.props, r4.propSchema, ((d = a3.meta) == null ? void 0 : d.fileBlockAccept) !== void 0 ); }, render(i3, c3) { var d; const l2 = a3.render.call( { blockContentDOMAttributes: this.blockContentDOMAttributes, renderType: this.renderType, props: this.props }, i3, c3 ); return Z2( l2, i3.type, i3.props, r4.propSchema, ((d = a3.meta) == null ? void 0 : d.fileBlockAccept) !== void 0, this.blockContentDOMAttributes ); } }, extensions: s2 }; }; } function go(e2, t2, n, o2) { return e2.dom.setAttribute("data-inline-content-type", t2), Object.entries(n).filter(([r4, a3]) => { const s2 = o2[r4]; return a3 !== s2.default; }).map(([r4, a3]) => [W(r4), a3]).forEach(([r4, a3]) => e2.dom.setAttribute(r4, a3)), e2.contentDOM && e2.contentDOM.setAttribute("data-editable", ""), e2; } function bo(e2) { return { Backspace: ({ editor: t2 }) => { const n = t2.state.selection.$from; return t2.state.selection.empty && n.node().type.name === e2.type && n.parentOffset === 0; } }; } function xt(e2, t2) { return { config: e2, implementation: t2 }; } function wt2(e2) { return Object.fromEntries( Object.entries(e2).map(([t2, n]) => [t2, n.config]) ); } function St2(e2) { return e2 === "boolean" ? {} : { stringValue: { default: void 0, keepOnSplit: true, parseHTML: (t2) => t2.getAttribute("data-value"), renderHTML: (t2) => t2.stringValue !== void 0 ? { "data-value": t2.stringValue } : {} } }; } function V2(e2, t2, n, o2) { return e2.dom.setAttribute("data-style-type", t2), o2 === "string" && e2.dom.setAttribute("data-value", n), e2.contentDOM && e2.contentDOM.setAttribute("data-editable", ""), e2; } function Me(e2, t2) { return { config: e2, implementation: t2 }; } function H2(e2, t2) { return Me( { type: e2.name, propSchema: t2 }, { mark: e2, render(n, o2) { const r4 = o2.pmSchema.marks[e2.name].spec.toDOM; if (r4 === void 0) throw new Error( "This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`." ); const a3 = o2.pmSchema.mark(e2.name, { stringValue: n }), s2 = DOMSerializer.renderSpec( document, r4(a3, true) ); if (typeof s2 != "object" || !("dom" in s2)) throw new Error( "Cannot use this block's default HTML serialization as its corresponding TipTap mark's `renderHTML` function does not return an object with the `dom` property." ); return s2; }, toExternalHTML(n, o2) { const r4 = o2.pmSchema.marks[e2.name].spec.toDOM; if (r4 === void 0) throw new Error( "This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`." ); const a3 = o2.pmSchema.mark(e2.name, { stringValue: n }), s2 = DOMSerializer.renderSpec( document, r4(a3, true) ); if (typeof s2 != "object" || !("dom" in s2)) throw new Error( "Cannot use this block's default HTML serialization as its corresponding TipTap mark's `renderHTML` function does not return an object with the `dom` property." ); return s2; } } ); } function Mt2(e2) { return Object.fromEntries( Object.entries(e2).map(([t2, n]) => [t2, n.config]) ); } function Lt(e2, t2) { const n = [ { tag: `[data-style-type="${e2.type}"]`, contentElement: (o2) => { const r4 = o2; return r4.matches("[data-editable]") ? r4 : r4.querySelector("[data-editable]") || r4; } } ]; return t2 && n.push({ tag: "*", // By default, styles can overlap each other, so the rules should not // completely consume the element they parse (which can have multiple // styles). consuming: false, getAttrs(o2) { if (typeof o2 == "string") return false; const r4 = t2 == null ? void 0 : t2(o2); return r4 === void 0 ? false : { stringValue: r4 }; } }), n; } function Le(e2, t2) { const n = Mark2.create({ name: e2.type, addAttributes() { return St2(e2.propSchema); }, parseHTML() { return Lt(e2, t2.parse); }, renderHTML({ mark: o2 }) { const r4 = (t2.toExternalHTML || t2.render)(o2.attrs.stringValue); return V2( r4, e2.type, o2.attrs.stringValue, e2.propSchema ); }, addMarkView() { return ({ mark: o2 }) => { const r4 = t2.render(o2.attrs.stringValue); return V2( r4, e2.type, o2.attrs.stringValue, e2.propSchema ); }; } }); return Me(e2, { ...t2, mark: n, render: (o2) => { const r4 = t2.render(o2); return V2( r4, e2.type, o2, e2.propSchema ); }, toExternalHTML: (o2) => { const r4 = (t2.toExternalHTML || t2.render)(o2); return V2( r4, e2.type, o2, e2.propSchema ); } }); } function Tt2(e2, t2) { let n, o2; if (t2.firstChild.descendants((r4, a3) => n ? false : !Bt(r4) || r4.attrs.id !== e2 ? true : (n = r4, o2 = a3 + 1, false)), !(n === void 0 || o2 === void 0)) return { node: n, posBeforeNode: o2 }; } function Bt(e2) { return e2.type.isInGroup("bnBlock"); } var ko = (e2, t2) => ({ tr: n, dispatch: o2 }) => (o2 && K4(n, e2, t2), true); function K4(e2, t2, n, o2, r4) { const a3 = It(e2.doc.resolve(t2)); let s2 = null; a3.blockNoteType === "table" && (s2 = Pt2(e2)); const i3 = ht(e2); if (o2 !== void 0 && r4 !== void 0 && o2 > r4) throw new Error("Invalid replaceFromPos or replaceToPos"); const c3 = i3.nodes[a3.blockNoteType], l2 = i3.nodes[n.type || a3.blockNoteType], u2 = l2.isInGroup("bnBlock") ? l2 : i3.nodes.blockContainer; if (a3.isBlockContainer && l2.isInGroup("blockContent")) { const d = o2 !== void 0 && o2 > a3.blockContent.beforePos && o2 < a3.blockContent.afterPos ? o2 - a3.blockContent.beforePos - 1 : void 0, p4 = r4 !== void 0 && r4 > a3.blockContent.beforePos && r4 < a3.blockContent.afterPos ? r4 - a3.blockContent.beforePos - 1 : void 0; de(n, e2, a3), At2( n, e2, c3, l2, a3, d, p4 ); } else if (!a3.isBlockContainer && l2.isInGroup("bnBlock")) de(n, e2, a3); else { const d = L(a3.bnBlock.node, i3); e2.replaceWith( a3.bnBlock.beforePos, a3.bnBlock.afterPos, bt( { children: d.children, // if no children are passed in, use existing children ...n }, i3 ) ); return; } e2.setNodeMarkup(a3.bnBlock.beforePos, u2, { ...a3.bnBlock.node.attrs, ...n.props }), s2 && Nt(e2, a3, s2); } function At2(e2, t2, n, o2, r4, a3, s2) { const i3 = ht(t2); let c3 = "keep"; if (e2.content) if (typeof e2.content == "string") c3 = T( [e2.content], i3, o2.name ); else if (Array.isArray(e2.content)) c3 = T(e2.content, i3, o2.name); else if (e2.content.type === "tableContent") c3 = kt(e2.content, i3); else throw new O(e2.content.type); else n.spec.content === "" || o2.spec.content !== n.spec.content && (c3 = []); if (c3 === "keep") t2.setNodeMarkup(r4.blockContent.beforePos, o2, { ...r4.blockContent.node.attrs, ...e2.props }); else if (a3 !== void 0 || s2 !== void 0) { t2.setNodeMarkup(r4.blockContent.beforePos, o2, { ...r4.blockContent.node.attrs, ...e2.props }); const l2 = r4.blockContent.beforePos + 1 + (a3 ?? 0), u2 = r4.blockContent.beforePos + 1 + (s2 ?? r4.blockContent.node.content.size), d = t2.doc.resolve(r4.blockContent.beforePos).depth, p4 = t2.doc.resolve(l2).depth, m2 = t2.doc.resolve(u2).depth; t2.replace( l2, u2, new Slice( Fragment.from(c3), p4 - d - 1, m2 - d - 1 ) ); } else t2.replaceWith( r4.blockContent.beforePos, r4.blockContent.afterPos, o2.createChecked( { ...r4.blockContent.node.attrs, ...e2.props }, c3 ) ); } function de(e2, t2, n) { const o2 = ht(t2); if (e2.children !== void 0 && e2.children.length > 0) { const r4 = e2.children.map((a3) => bt(a3, o2)); if (n.childContainer) t2.step( new ReplaceStep( n.childContainer.beforePos + 1, n.childContainer.afterPos - 1, new Slice(Fragment.from(r4), 0, 0) ) ); else { if (!n.isBlockContainer) throw new Error("impossible"); t2.insert( n.blockContent.afterPos, o2.nodes.blockGroup.createChecked({}, r4) ); } } } function yo(e2, t2, n, o2, r4) { const a3 = typeof t2 == "string" ? t2 : t2.id, s2 = Tt2(a3, e2.doc); if (!s2) throw new Error(`Block with ID ${a3} not found`); K4( e2, s2.posBeforeNode, n, o2, r4 ); const i3 = e2.doc.resolve(s2.posBeforeNode + 1).node(), c3 = ht(e2); return L(i3, c3); } function Pt2(e2) { const t2 = "selection" in e2 ? e2.selection : null; if (!(t2 instanceof TextSelection)) return null; const n = e2.doc.resolve(t2.head); let o2 = -1, r4 = -1; for (let w3 = n.depth; w3 >= 0; w3--) { const x5 = n.node(w3).type.name; if (o2 < 0 && (x5 === "tableCell" || x5 === "tableHeader") && (o2 = w3), x5 === "table") { r4 = w3; break; } } if (o2 < 0 || r4 < 0) return null; const a3 = n.before(o2), s2 = n.before(r4), i3 = e2.doc.nodeAt(s2); if (!i3 || i3.type.name !== "table") return null; const c3 = TableMap.get(i3), l2 = a3 - (s2 + 1), u2 = c3.map.indexOf(l2); if (u2 < 0) return null; const d = Math.floor(u2 / c3.width), p4 = u2 % c3.width, f6 = a3 + 1 + 1, E4 = Math.max(0, t2.head - f6); return { row: d, col: p4, offset: E4 }; } function Nt(e2, t2, n) { var w3; if (t2.blockNoteType !== "table") return false; let o2 = -1; if (t2.isBlockContainer) o2 = e2.mapping.map(t2.blockContent.beforePos); else { const x5 = e2.mapping.map(t2.bnBlock.beforePos), P4 = x5 + (((w3 = e2.doc.nodeAt(x5)) == null ? void 0 : w3.nodeSize) || 0); e2.doc.nodesBetween(x5, P4, (g, S4) => g.type.name === "table" ? (o2 = S4, false) : true); } const r4 = o2 >= 0 ? e2.doc.nodeAt(o2) : null; if (!r4 || r4.type.name !== "table") return false; const a3 = TableMap.get(r4), s2 = Math.max(0, Math.min(n.row, a3.height - 1)), i3 = Math.max(0, Math.min(n.col, a3.width - 1)), c3 = s2 * a3.width + i3, l2 = a3.map[c3]; if (l2 == null) return false; const d = o2 + 1 + l2 + 1, p4 = e2.doc.nodeAt(d), m2 = d + 1, f6 = p4 ? p4.content.size : 0, E4 = m2 + Math.max(0, Math.min(n.offset, f6)); return "selection" in e2 && e2.setSelection(TextSelection.create(e2.doc, E4)), true; } var T2 = { gray: { text: "#9b9a97", background: "#ebeced" }, brown: { text: "#64473a", background: "#e9e5e3" }, red: { text: "#e03e3e", background: "#fbe4e4" }, orange: { text: "#d9730d", background: "#f6e9d9" }, yellow: { text: "#dfab01", background: "#fbf3db" }, green: { text: "#4d6461", background: "#ddedea" }, blue: { text: "#0b6e99", background: "#ddebf1" }, purple: { text: "#6940a5", background: "#eae4f2" }, pink: { text: "#ad1a72", background: "#f4dfeb" } }; var h3 = { backgroundColor: { default: "default" }, textColor: { default: "default" }, textAlignment: { default: "left", values: ["left", "center", "right", "justify"] } }; var y = (e2) => { const t2 = {}; return e2.hasAttribute("data-background-color") ? t2.backgroundColor = e2.getAttribute("data-background-color") : e2.style.backgroundColor && (t2.backgroundColor = e2.style.backgroundColor), e2.hasAttribute("data-text-color") ? t2.textColor = e2.getAttribute("data-text-color") : e2.style.color && (t2.textColor = e2.style.color), t2.textAlignment = h3.textAlignment.values.includes( e2.style.textAlign ) ? e2.style.textAlign : void 0, t2; }; var A2 = (e2, t2) => { e2.backgroundColor && e2.backgroundColor !== h3.backgroundColor.default && (t2.style.backgroundColor = e2.backgroundColor in T2 ? T2[e2.backgroundColor].background : e2.backgroundColor), e2.textColor && e2.textColor !== h3.textColor.default && (t2.style.color = e2.textColor in T2 ? T2[e2.textColor].text : e2.textColor), e2.textAlignment && e2.textAlignment !== h3.textAlignment.default && (t2.style.textAlign = e2.textAlignment); }; var Eo = (e2 = "backgroundColor") => ({ default: h3.backgroundColor.default, parseHTML: (t2) => t2.hasAttribute("data-background-color") ? t2.getAttribute("data-background-color") : t2.style.backgroundColor ? t2.style.backgroundColor : h3.backgroundColor.default, renderHTML: (t2) => t2[e2] === h3.backgroundColor.default ? {} : { "data-background-color": t2[e2] } }); var xo = (e2 = "textColor") => ({ default: h3.textColor.default, parseHTML: (t2) => t2.hasAttribute("data-text-color") ? t2.getAttribute("data-text-color") : t2.style.color ? t2.style.color : h3.textColor.default, renderHTML: (t2) => t2[e2] === h3.textColor.default ? {} : { "data-text-color": t2[e2] } }); var $3 = (e2, t2) => { const n = e2.querySelector( t2 ); if (!n) return; const o2 = e2.querySelector("figcaption"), r4 = (o2 == null ? void 0 : o2.textContent) ?? void 0; return { targetElement: n, caption: r4 }; }; var I2 = a(({ editor: e2 }) => { const t2 = f(void 0); function n() { t2.setState(void 0); } return { key: "filePanel", store: t2, mount({ signal: o2 }) { const r4 = e2.onChange( n, // Don't trigger if the changes are caused by a remote user. false ), a3 = e2.onSelectionChange( n, // Don't trigger if the changes are caused by a remote user. false ); o2.addEventListener("abort", () => { r4(), a3(); }); }, closeMenu: n, showMenu(o2) { t2.setState(o2); } }; }); var Ht2 = (e2, t2, n) => { const o2 = document.createElement("div"); o2.className = "bn-add-file-button"; const r4 = document.createElement("div"); r4.className = "bn-add-file-button-icon", n ? r4.appendChild(n) : r4.innerHTML = '', o2.appendChild(r4); const a3 = document.createElement("p"); a3.className = "bn-add-file-button-text", a3.innerHTML = e2.type in t2.dictionary.file_blocks.add_button_text ? t2.dictionary.file_blocks.add_button_text[e2.type] : t2.dictionary.file_blocks.add_button_text.file, o2.appendChild(a3); const s2 = (c3) => { c3.preventDefault(), c3.stopPropagation(); }, i3 = () => { var c3; t2.isEditable && ((c3 = t2.getExtension(I2)) == null || c3.showMenu(e2.id)); }; return o2.addEventListener( "mousedown", s2, true ), o2.addEventListener("click", i3, true), { dom: o2, destroy: () => { o2.removeEventListener( "mousedown", s2, true ), o2.removeEventListener( "click", i3, true ); } }; }; var It2 = ''; var Dt2 = (e2) => { const t2 = document.createElement("div"); t2.className = "bn-file-name-with-icon"; const n = document.createElement("div"); n.className = "bn-file-icon", n.innerHTML = It2, t2.appendChild(n); const o2 = document.createElement("p"); return o2.className = "bn-file-name", o2.textContent = e2.props.name, t2.appendChild(o2), { dom: t2 }; }; var Q2 = (e2, t2, n, o2) => { const r4 = document.createElement("div"); if (r4.className = "bn-file-block-content-wrapper", e2.props.url === "") { const s2 = Ht2(e2, t2, o2); r4.appendChild(s2.dom); const i3 = t2.onUploadStart((c3) => { if (c3 === e2.id) { r4.removeChild(s2.dom); const l2 = document.createElement("div"); l2.className = "bn-file-loading-preview", l2.textContent = "Loading...", r4.appendChild(l2); } }); return { dom: r4, destroy: () => { i3(), s2.destroy(); } }; } const a3 = { dom: r4 }; if (e2.props.showPreview === false || !n) { const s2 = Dt2(e2); r4.appendChild(s2.dom), a3.destroy = () => { var i3; (i3 = s2.destroy) == null || i3.call(s2); }; } else r4.appendChild(n.dom); if (e2.props.caption) { const s2 = document.createElement("p"); s2.className = "bn-file-caption", s2.textContent = e2.props.caption, r4.appendChild(s2); } return a3; }; var J2 = (e2, t2) => { const n = document.createElement("figure"), o2 = document.createElement("figcaption"); return o2.textContent = t2, n.appendChild(e2), n.appendChild(o2), { dom: n }; }; var U = (e2, t2) => { const n = document.createElement("div"), o2 = document.createElement("p"); return o2.textContent = t2, n.appendChild(e2), n.appendChild(o2), { dom: n }; }; var ue = (e2) => ({ url: e2.src || void 0 }); var Ot2 = ''; var _t3 = (e2) => ({ type: "audio", propSchema: { backgroundColor: h3.backgroundColor, // File name. name: { default: "" }, // File url. url: { default: "" }, // File caption. caption: { default: "" }, showPreview: { default: true } }, content: "none" }); var Vt = (e2 = {}) => (t2) => { if (t2.tagName === "AUDIO") { if (t2.closest("figure")) return; const { backgroundColor: n } = y(t2); return { ...ue(t2), backgroundColor: n }; } if (t2.tagName === "FIGURE") { const n = $3(t2, "audio"); if (!n) return; const { targetElement: o2, caption: r4 } = n, { backgroundColor: a3 } = y(t2); return { ...ue(o2), backgroundColor: a3, caption: r4 }; } }; var Rt2 = (e2 = {}) => (t2, n) => { const o2 = document.createElement("div"); o2.innerHTML = e2.icon ?? Ot2; const r4 = document.createElement("audio"); return r4.className = "bn-audio", n.resolveFileUrl ? n.resolveFileUrl(t2.props.url).then((a3) => { r4.src = a3; }) : r4.src = t2.props.url, r4.controls = true, r4.contentEditable = "false", r4.draggable = false, Q2( t2, n, { dom: r4 }, o2.firstElementChild ); }; var Wt = (e2 = {}) => (t2, n) => { if (!t2.props.url) { const r4 = document.createElement("p"); return r4.textContent = "Add audio", { dom: r4 }; } let o2; return t2.props.showPreview ? (o2 = document.createElement("audio"), o2.src = t2.props.url) : (o2 = document.createElement("a"), o2.href = t2.props.url, o2.textContent = t2.props.name || t2.props.url), t2.props.caption ? t2.props.showPreview ? J2(o2, t2.props.caption) : U(o2, t2.props.caption) : { dom: o2 }; }; var Ft = v2( _t3, (e2) => ({ meta: { fileBlockAccept: ["audio/*"] }, parse: Vt(e2), render: Rt2(e2), toExternalHTML: Wt(e2), runsBefore: ["file"] }) ); var pe = Symbol.for("blocknote.shikiParser"); var j2 = Symbol.for( "blocknote.shikiHighlighterPromise" ); function $t2(e2) { const t2 = globalThis; let n, o2, r4 = false; return createHighlightPlugin({ parser: (s2) => { if (!e2.createHighlighter) return !r4 && (console.log( "For syntax highlighting of code blocks, you must provide a `createCodeBlockSpec({ createHighlighter: () => ... })` function" ), r4 = true), []; if (!n) return t2[j2] = t2[j2] || e2.createHighlighter(), t2[j2].then( (c3) => { n = c3; } ); const i3 = Te(e2, s2.language); return !i3 || i3 === "text" || i3 === "none" || i3 === "plaintext" || i3 === "txt" ? [] : n.getLoadedLanguages().includes(i3) ? (o2 || (o2 = t2[pe] || createParser(n), t2[pe] = o2), o2(s2)) : n.loadLanguage(i3); }, languageExtractor: (s2) => s2.attrs.language, nodeTypes: ["codeBlock"] }); } var Ut = ({ defaultLanguage: e2 = "text" }) => ({ type: "codeBlock", propSchema: { language: { default: e2 } }, content: "inline" }); var qt = v2( Ut, (e2) => ({ meta: { code: true, defining: true, isolating: false }, parse: (t2) => { var r4, a3; if (t2.tagName !== "PRE" || t2.childElementCount !== 1 || ((r4 = t2.firstElementChild) == null ? void 0 : r4.tagName) !== "CODE") return; const n = t2.firstElementChild; return { language: n.getAttribute("data-language") || ((a3 = n.className.split(" ").find((s2) => s2.includes("language-"))) == null ? void 0 : a3.replace("language-", "")) }; }, parseContent: ({ el: t2, schema: n }) => { const o2 = DOMParser2.fromSchema(n), r4 = t2.firstElementChild; return o2.parse(r4, { preserveWhitespace: "full", topNode: n.nodes.codeBlock.create() }).content; }, render(t2, n) { const o2 = document.createDocumentFragment(), r4 = document.createElement("pre"), a3 = document.createElement("code"); r4.appendChild(a3); let s2; if (e2.supportedLanguages) { const i3 = document.createElement("select"); Object.entries(e2.supportedLanguages ?? {}).forEach( ([u2, { name: d }]) => { const p4 = document.createElement("option"); p4.value = u2, p4.text = d, i3.appendChild(p4); } ), i3.value = t2.props.language || e2.defaultLanguage || "text"; const c3 = (u2) => { const d = u2.target.value; n.updateBlock(t2.id, { props: { language: d } }); }; i3.addEventListener("change", c3), s2 = () => i3.removeEventListener("change", c3); const l2 = document.createElement("div"); l2.contentEditable = "false", l2.appendChild(i3), o2.appendChild(l2); } return o2.appendChild(r4), { dom: o2, contentDOM: a3, destroy: () => { s2 == null || s2(); } }; }, toExternalHTML(t2) { const n = document.createElement("pre"), o2 = document.createElement("code"); return o2.className = `language-${t2.props.language}`, o2.dataset.language = t2.props.language, n.appendChild(o2), { dom: n, contentDOM: o2 }; } }), (e2) => [ a({ key: "code-block-highlighter", prosemirrorPlugins: [$t2(e2)] }), a({ key: "code-block-keyboard-shortcuts", keyboardShortcuts: { Delete: ({ editor: t2 }) => t2.transact((n) => { const { block: o2 } = t2.getTextCursorPosition(); if (o2.type !== "codeBlock") return false; const { $from: r4 } = n.selection; return r4.parent.textContent ? false : (t2.removeBlocks([o2]), true); }), Tab: ({ editor: t2 }) => e2.indentLineWithTab === false ? false : t2.transact((n) => { const { block: o2 } = t2.getTextCursorPosition(); return o2.type === "codeBlock" ? (n.insertText(" "), true) : false; }), Enter: ({ editor: t2 }) => t2.transact((n) => { const { block: o2, nextBlock: r4 } = t2.getTextCursorPosition(); if (o2.type !== "codeBlock") return false; const { $from: a3 } = n.selection, s2 = a3.parentOffset === a3.parent.nodeSize - 2, i3 = a3.parent.textContent.endsWith(` `); if (s2 && i3) { if (n.delete(a3.pos - 2, a3.pos), r4) return t2.setTextCursorPosition(r4, "start"), true; const [c3] = t2.insertBlocks( [{ type: "paragraph" }], o2, "after" ); return t2.setTextCursorPosition(c3, "start"), true; } return n.insertText(` `), true; }), "Shift-Enter": ({ editor: t2 }) => t2.transact(() => { const { block: n } = t2.getTextCursorPosition(); if (n.type !== "codeBlock") return false; const [o2] = t2.insertBlocks( // insert a new paragraph [{ type: "paragraph" }], n, "after" ); return t2.setTextCursorPosition(o2, "start"), true; }) }, inputRules: [ { find: /^```(.*?)\s$/, replace: ({ match: t2 }) => { const n = t2[1].trim(); return { type: "codeBlock", props: { language: { language: Te(e2, n) ?? n }.language }, content: [] }; } } ] }) ] ); function Te(e2, t2) { var n; return (n = Object.entries(e2.supportedLanguages ?? {}).find( ([o2, { aliases: r4 }]) => (r4 == null ? void 0 : r4.includes(t2)) || o2 === t2 )) == null ? void 0 : n[0]; } var jt = () => ({ type: "divider", propSchema: {}, content: "none" }); var Gt = v2( jt, { meta: { isolating: false }, parse(e2) { if (e2.tagName === "HR") return {}; }, render() { return { dom: document.createElement("hr") }; } }, [ a({ key: "divider-block-shortcuts", inputRules: [ { find: new RegExp("^---$"), replace() { return { type: "divider", props: {}, content: [] }; } } ] }) ] ); var fe = (e2) => ({ url: e2.src || void 0 }); var Zt = () => ({ type: "file", propSchema: { backgroundColor: h3.backgroundColor, // File name. name: { default: "" }, // File url. url: { default: "" }, // File caption. caption: { default: "" } }, content: "none" }); var zt = () => (e2) => { if (e2.tagName === "EMBED") { if (e2.closest("figure")) return; const { backgroundColor: t2 } = y(e2); return { ...fe(e2), backgroundColor: t2 }; } if (e2.tagName === "FIGURE") { const t2 = $3(e2, "embed"); if (!t2) return; const { targetElement: n, caption: o2 } = t2, { backgroundColor: r4 } = y(e2); return { ...fe(n), backgroundColor: r4, caption: o2 }; } }; var Xt = v2(Zt, { meta: { fileBlockAccept: ["*/*"] }, parse: zt(), render(e2, t2) { return Q2(e2, t2); }, toExternalHTML(e2) { if (!e2.props.url) { const n = document.createElement("p"); return n.textContent = "Add file", { dom: n }; } const t2 = document.createElement("a"); return t2.href = e2.props.url, t2.textContent = e2.props.name || e2.props.url, e2.props.caption ? U(t2, e2.props.caption) : { dom: t2 }; } }); var Kt = { set: (e2, t2) => window.localStorage.setItem( `toggle-${e2.id}`, t2 ? "true" : "false" ), get: (e2) => window.localStorage.getItem(`toggle-${e2.id}`) === "true" }; var Be = (e2, t2, n, o2 = Kt) => { if ("isToggleable" in e2.props && !e2.props.isToggleable) return { dom: n }; const r4 = document.createElement("div"), a3 = document.createElement("div"); a3.className = "bn-toggle-wrapper"; const s2 = document.createElement("button"); s2.className = "bn-toggle-button", s2.type = "button", s2.innerHTML = // https://fonts.google.com/icons?selected=Material+Symbols+Rounded:chevron_right:FILL@0;wght@700;GRAD@0;opsz@24&icon.query=chevron&icon.style=Rounded&icon.size=24&icon.color=%23e8eaed ''; const i3 = (f6) => f6.preventDefault(); s2.addEventListener("mousedown", i3); const c3 = () => { var f6; a3.getAttribute("data-show-children") === "true" ? (a3.setAttribute("data-show-children", "false"), o2.set(t2.getBlock(e2), false), r4.contains(l2) && r4.removeChild(l2)) : (a3.setAttribute("data-show-children", "true"), o2.set(t2.getBlock(e2), true), t2.isEditable && ((f6 = t2.getBlock(e2)) == null ? void 0 : f6.children.length) === 0 && !r4.contains(l2) && r4.appendChild(l2)); }; s2.addEventListener("click", c3), a3.appendChild(s2), a3.appendChild(n); const l2 = document.createElement("button"); l2.className = "bn-toggle-add-block-button", l2.type = "button", l2.textContent = t2.dictionary.toggle_blocks.add_block_button; const u2 = (f6) => f6.preventDefault(); l2.addEventListener( "mousedown", u2 ); const d = () => { t2.transact(() => { const f6 = t2.updateBlock(e2, { // Single empty block with default type. children: [{}] }); t2.setTextCursorPosition(f6.children[0].id, "end"), t2.focus(); }); }; l2.addEventListener("click", d), r4.appendChild(a3); let p4 = e2.children.length; const m2 = t2.onChange(() => { var E4; const f6 = ((E4 = t2.getBlock(e2)) == null ? void 0 : E4.children.length) ?? 0; f6 > p4 ? (a3.getAttribute("data-show-children") === "false" && (a3.setAttribute("data-show-children", "true"), o2.set(t2.getBlock(e2), true)), r4.contains(l2) && r4.removeChild(l2)) : f6 === 0 && f6 < p4 && (a3.getAttribute("data-show-children") === "true" && (a3.setAttribute("data-show-children", "false"), o2.set(t2.getBlock(e2), false)), r4.contains(l2) && r4.removeChild(l2)), p4 = f6; }); return o2.get(e2) ? (a3.setAttribute("data-show-children", "true"), t2.isEditable && e2.children.length === 0 && r4.appendChild(l2)) : a3.setAttribute("data-show-children", "false"), { dom: r4, // Prevents re-renders when the toggle button is clicked. ignoreMutation: (f6) => f6 instanceof MutationRecord && // We want to prevent re-renders when the view changes, so we ignore // all mutations where the `data-show-children` attribute is changed // or the "add block" button is added/removed. (f6.type === "attributes" && f6.target === a3 && f6.attributeName === "data-show-children" || f6.type === "childList" && (f6.addedNodes[0] === l2 || f6.removedNodes[0] === l2)), destroy: () => { s2.removeEventListener("mousedown", i3), s2.removeEventListener("click", c3), l2.removeEventListener( "mousedown", u2 ), l2.removeEventListener( "click", d ), m2 == null || m2(); } }; }; var Ae = [1, 2, 3, 4, 5, 6]; var Qt = (e2) => ({ editor: t2 }) => { const n = t2.getTextCursorPosition(); return t2.schema.blockSchema[n.block.type].content !== "inline" ? false : (t2.updateBlock(n.block, { type: "heading", props: { level: e2 } }), true); }; var Jt2 = ({ defaultLevel: e2 = 1, levels: t2 = Ae, allowToggleHeadings: n = true } = {}) => ({ type: "heading", propSchema: { ...h3, level: { default: e2, values: t2 }, ...n ? { isToggleable: { default: false, optional: true } } : {} }, content: "inline" }); var Yt = v2( Jt2, ({ allowToggleHeadings: e2 = true } = {}) => ({ meta: { isolating: false }, parse(t2) { let n; switch (t2.tagName) { case "H1": n = 1; break; case "H2": n = 2; break; case "H3": n = 3; break; case "H4": n = 4; break; case "H5": n = 5; break; case "H6": n = 6; break; default: return; } return { ...y(t2), level: n }; }, render(t2, n) { const o2 = document.createElement(`h${t2.props.level}`); return e2 ? { ...Be(t2, n, o2), contentDOM: o2 } : { dom: o2, contentDOM: o2 }; }, toExternalHTML(t2) { const n = document.createElement(`h${t2.props.level}`); return A2(t2.props, n), { dom: n, contentDOM: n }; } }), ({ levels: e2 = Ae } = {}) => [ a({ key: "heading-shortcuts", keyboardShortcuts: Object.fromEntries( e2.map((t2) => [ `Mod-Alt-${t2}`, Qt(t2) ]) ?? [] ), inputRules: e2.map((t2) => ({ find: new RegExp(`^(#{${t2}})\\s$`), replace({ match: n }) { return { type: "heading", props: { level: n[1].length } }; } })) }) ] ); var Pe = (e2, t2, n, o2, r4) => { const { dom: a3, destroy: s2 } = Q2( e2, t2, n, r4 ), i3 = a3; i3.style.position = "relative", e2.props.url && e2.props.showPreview && (e2.props.previewWidth ? i3.style.width = `${e2.props.previewWidth}px` : i3.style.width = "fit-content"); const c3 = document.createElement("div"); c3.className = "bn-resize-handle", c3.style.left = "4px"; const l2 = document.createElement("div"); l2.className = "bn-resize-handle", l2.style.right = "4px"; const u2 = document.createElement("div"); u2.style.position = "absolute", u2.style.height = "100%", u2.style.width = "100%"; let d, p4 = e2.props.previewWidth; const m2 = (g) => { var ee3, te2; if (!d) { !t2.isEditable && o2.contains(c3) && o2.contains(l2) && (o2.removeChild(c3), o2.removeChild(l2)); return; } let S4; const _2 = "touches" in g ? g.touches[0].clientX : g.clientX; e2.props.textAlignment === "center" ? d.handleUsed === "left" ? S4 = d.initialWidth + (d.initialClientX - _2) * 2 : S4 = d.initialWidth + (_2 - d.initialClientX) * 2 : d.handleUsed === "left" ? S4 = d.initialWidth + d.initialClientX - _2 : S4 = d.initialWidth + _2 - d.initialClientX, p4 = Math.min( Math.max(S4, 64), ((te2 = (ee3 = t2.domElement) == null ? void 0 : ee3.firstElementChild) == null ? void 0 : te2.clientWidth) || Number.MAX_VALUE ), i3.style.width = `${p4}px`; }, f6 = (g) => { (!g.target || !i3.contains(g.target) || !t2.isEditable) && o2.contains(c3) && o2.contains(l2) && (o2.removeChild(c3), o2.removeChild(l2)), d && (d = void 0, i3.contains(u2) && i3.removeChild(u2), t2.updateBlock(e2, { props: { previewWidth: p4 } })); }, E4 = () => { t2.isEditable && (o2.appendChild(c3), o2.appendChild(l2)); }, w3 = (g) => { g.relatedTarget === c3 || g.relatedTarget === l2 || d || t2.isEditable && o2.contains(c3) && o2.contains(l2) && (o2.removeChild(c3), o2.removeChild(l2)); }, x5 = (g) => { g.preventDefault(), i3.contains(u2) || i3.appendChild(u2); const S4 = "touches" in g ? g.touches[0].clientX : g.clientX; d = { handleUsed: "left", initialWidth: i3.clientWidth, initialClientX: S4 }; }, P4 = (g) => { g.preventDefault(), i3.contains(u2) || i3.appendChild(u2); const S4 = "touches" in g ? g.touches[0].clientX : g.clientX; d = { handleUsed: "right", initialWidth: i3.clientWidth, initialClientX: S4 }; }; return window.addEventListener("mousemove", m2), window.addEventListener("touchmove", m2), window.addEventListener("mouseup", f6), window.addEventListener("touchend", f6), i3.addEventListener("mouseenter", E4), i3.addEventListener("mouseleave", w3), c3.addEventListener( "mousedown", x5 ), c3.addEventListener( "touchstart", x5 ), l2.addEventListener( "mousedown", P4 ), l2.addEventListener( "touchstart", P4 ), { dom: i3, destroy: () => { s2 == null || s2(), window.removeEventListener("mousemove", m2), window.removeEventListener("touchmove", m2), window.removeEventListener("mouseup", f6), window.removeEventListener("touchend", f6), i3.removeEventListener("mouseenter", E4), i3.removeEventListener("mouseleave", w3), c3.removeEventListener( "mousedown", x5 ), c3.removeEventListener( "touchstart", x5 ), l2.removeEventListener( "mousedown", P4 ), l2.removeEventListener( "touchstart", P4 ); } }; }; var he = (e2) => { const t2 = e2.src || void 0, n = e2.width || void 0, o2 = e2.alt || void 0; return { url: t2, previewWidth: n, name: o2 }; }; var en = ''; var tn = (e2 = {}) => ({ type: "image", propSchema: { textAlignment: h3.textAlignment, backgroundColor: h3.backgroundColor, // File name. name: { default: "" }, // File url. url: { default: "" }, // File caption. caption: { default: "" }, showPreview: { default: true }, // File preview width in px. previewWidth: { default: void 0, type: "number" } }, content: "none" }); var nn = (e2 = {}) => (t2) => { if (t2.tagName === "IMG") { if (t2.closest("figure")) return; const { backgroundColor: n } = y(t2); return { ...he(t2), backgroundColor: n }; } if (t2.tagName === "FIGURE") { const n = $3(t2, "img"); if (!n) return; const { targetElement: o2, caption: r4 } = n, { backgroundColor: a3 } = y(t2); return { ...he(o2), backgroundColor: a3, caption: r4 }; } }; var on = (e2 = {}) => (t2, n) => { const o2 = document.createElement("div"); o2.innerHTML = e2.icon ?? en; const r4 = document.createElement("div"); r4.className = "bn-visual-media-wrapper"; const a3 = document.createElement("img"); return a3.className = "bn-visual-media", n.resolveFileUrl ? n.resolveFileUrl(t2.props.url).then((s2) => { a3.src = s2; }) : a3.src = t2.props.url, a3.alt = t2.props.name || t2.props.caption || "BlockNote image", a3.contentEditable = "false", a3.draggable = false, r4.appendChild(a3), Pe( t2, n, { dom: r4 }, r4, o2.firstElementChild ); }; var rn = (e2 = {}) => (t2, n) => { if (!t2.props.url) { const r4 = document.createElement("p"); return r4.textContent = "Add image", { dom: r4 }; } let o2; return t2.props.showPreview ? (o2 = document.createElement("img"), o2.src = t2.props.url, o2.alt = t2.props.name || t2.props.caption || "BlockNote image", t2.props.previewWidth && (o2.width = t2.props.previewWidth)) : (o2 = document.createElement("a"), o2.href = t2.props.url, o2.textContent = t2.props.name || t2.props.url), t2.props.caption ? t2.props.showPreview ? J2(o2, t2.props.caption) : U(o2, t2.props.caption) : { dom: o2 }; }; var an = v2( tn, (e2) => ({ meta: { fileBlockAccept: ["image/*"] }, parse: nn(e2), render: on(e2), toExternalHTML: rn(e2), runsBefore: ["file"] }) ); var So = (e2, t2, n) => ({ state: o2, dispatch: r4 }) => r4 ? Ne(o2.tr, e2, t2, n) : true; var Ne = (e2, t2, n, o2) => { const r4 = Y2(e2.doc, t2), a3 = Z(r4); if (!a3.isBlockContainer) return false; const s2 = ht(e2), i3 = [ { type: a3.bnBlock.node.type, // always keep blockcontainer type attrs: o2 ? { ...a3.bnBlock.node.attrs, id: void 0 } : {} }, { type: n ? a3.blockContent.node.type : s2.nodes.paragraph, attrs: o2 ? { ...a3.blockContent.node.attrs } : {} } ]; return e2.split(t2, 2, i3), true; }; var q = (e2, t2) => { const { blockInfo: n, selectionEmpty: o2 } = e2.transact((s2) => ({ blockInfo: Ot(s2), selectionEmpty: s2.selection.anchor === s2.selection.head })); if (!n.isBlockContainer) return false; const { bnBlock: r4, blockContent: a3 } = n; return a3.node.type.name !== t2 || !o2 ? false : a3.node.childCount === 0 ? (e2.transact((s2) => { K4(s2, r4.beforePos, { type: "paragraph", props: {} }); }), true) : a3.node.childCount > 0 ? e2.transact((s2) => (s2.deleteSelection(), Ne(s2, s2.selection.from, true))) : false; }; function Y3(e2, t2, n) { var d, p4, m2; const o2 = DOMParser2.fromSchema(t2), r4 = e2, a3 = document.createElement("div"); a3.setAttribute("data-node-type", "blockGroup"); for (const f6 of Array.from(r4.childNodes)) a3.appendChild(f6.cloneNode(true)); let s2 = o2.parse(a3, { topNode: t2.nodes.blockGroup.create() }); ((p4 = (d = s2.firstChild) == null ? void 0 : d.firstChild) == null ? void 0 : p4.type.name) === "checkListItem" && (s2 = s2.copy( s2.content.cut( s2.firstChild.firstChild.nodeSize + 2 ) )); const i3 = (m2 = s2.firstChild) == null ? void 0 : m2.firstChild; if (!(i3 != null && i3.isTextblock)) return Fragment.from(s2); const c3 = t2.nodes[n].create( {}, i3.content ), l2 = s2.content.cut( // +2 for the `blockGroup` node's start and end markers i3.nodeSize + 2 ); if (l2.size > 0) { const f6 = s2.copy(l2); return c3.content.addToEnd(f6); } return c3.content; } var sn = () => ({ type: "bulletListItem", propSchema: { ...h3 }, content: "inline" }); var cn = v2( sn, { meta: { isolating: false }, parse(e2) { var n; if (e2.tagName !== "LI") return; const t2 = e2.parentElement; if (t2 !== null && (t2.tagName === "UL" || t2.tagName === "DIV" && ((n = t2.parentElement) == null ? void 0 : n.tagName) === "UL")) return y(e2); }, // As `li` elements can contain multiple paragraphs, we need to merge their contents // into a single one so that ProseMirror can parse everything correctly. parseContent: ({ el: e2, schema: t2 }) => Y3(e2, t2, "bulletListItem"), render() { const e2 = document.createElement("p"); return { dom: e2, contentDOM: e2 }; }, toExternalHTML(e2) { const t2 = document.createElement("li"), n = document.createElement("p"); return A2(e2.props, t2), t2.appendChild(n), { dom: t2, contentDOM: n }; } }, [ a({ key: "bullet-list-item-shortcuts", keyboardShortcuts: { Enter: ({ editor: e2 }) => q(e2, "bulletListItem"), "Mod-Shift-8": ({ editor: e2 }) => { const t2 = e2.getTextCursorPosition(); return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, { type: "bulletListItem", props: {} }), true); } }, inputRules: [ { find: new RegExp("^[-+*]\\s$"), replace({ editor: e2 }) { if (Tt( e2.prosemirrorState ).blockNoteType !== "heading") return { type: "bulletListItem", props: {} }; } } ] }) ] ); var ln = () => ({ type: "checkListItem", propSchema: { ...h3, checked: { default: false, type: "boolean" } }, content: "inline" }); var dn = v2( ln, { meta: { isolating: false }, parse(e2) { var n; if (e2.tagName === "input") return e2.closest("[data-content-type]") || e2.closest("li") ? void 0 : e2.type === "checkbox" ? { checked: e2.checked } : void 0; if (e2.tagName !== "LI") return; const t2 = e2.parentElement; if (t2 !== null && (t2.tagName === "UL" || t2.tagName === "DIV" && ((n = t2.parentElement) == null ? void 0 : n.tagName) === "UL")) { const o2 = e2.querySelector("input[type=checkbox]") || null; return o2 === null ? void 0 : { ...y(e2), checked: o2.checked }; } }, // As `li` elements can contain multiple paragraphs, we need to merge their contents // into a single one so that ProseMirror can parse everything correctly. parseContent: ({ el: e2, schema: t2 }) => Y3(e2, t2, "checkListItem"), render(e2, t2) { const n = document.createDocumentFragment(), o2 = document.createElement("input"); o2.type = "checkbox", o2.checked = e2.props.checked, e2.props.checked && o2.setAttribute("checked", ""), o2.addEventListener("change", () => { t2.updateBlock(e2, { props: { checked: !e2.props.checked } }); }); const r4 = document.createElement("p"); return n.appendChild(o2), n.appendChild(r4), { dom: n, contentDOM: r4 }; }, toExternalHTML(e2) { const t2 = document.createElement("li"), n = document.createElement("input"); n.type = "checkbox", n.checked = e2.props.checked, e2.props.checked && n.setAttribute("checked", ""); const o2 = document.createElement("p"); return A2(e2.props, t2), t2.appendChild(n), t2.appendChild(o2), { dom: t2, contentDOM: o2 }; }, runsBefore: ["bulletListItem"] }, [ a({ key: "check-list-item-shortcuts", keyboardShortcuts: { Enter: ({ editor: e2 }) => q(e2, "checkListItem"), "Mod-Shift-9": ({ editor: e2 }) => { const t2 = e2.getTextCursorPosition(); return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, { type: "checkListItem", props: {} }), true); } }, inputRules: [ { find: new RegExp("^\\[\\s*\\]\\s$"), replace() { return { type: "checkListItem", props: { checked: false }, content: [] }; } }, { find: new RegExp("^\\[[Xx]\\]\\s$"), replace() { return { type: "checkListItem", props: { checked: true } }; } } ] }) ] ); function He(e2, t2, n, o2) { let r4 = e2.firstChild.attrs.start || 1, a3 = true; const s2 = !!e2.firstChild.attrs.start, i3 = Z({ posBeforeNode: t2, node: e2 }); if (!i3.isBlockContainer) throw new Error("impossible"); const c3 = n.doc.resolve(i3.bnBlock.beforePos).nodeBefore, l2 = c3 ? o2.get(c3) : void 0; return l2 !== void 0 ? (r4 = l2 + 1, a3 = false) : c3 && Z({ posBeforeNode: i3.bnBlock.beforePos - c3.nodeSize, node: c3 }).blockNoteType === "numberedListItem" && (r4 = He( c3, i3.bnBlock.beforePos - c3.nodeSize, n, o2 ).index + 1, a3 = false), o2.set(e2, r4), { index: r4, isFirst: a3, hasStart: s2 }; } function me(e2, t2) { const n = /* @__PURE__ */ new Map(), o2 = t2.decorations.map( e2.mapping, e2.doc ), r4 = []; e2.doc.nodesBetween(0, e2.doc.nodeSize - 2, (s2, i3) => { if (s2.type.name === "blockContainer" && s2.firstChild.type.name === "numberedListItem") { const { index: c3, isFirst: l2, hasStart: u2 } = He( s2, i3, e2, n ); if (o2.find( i3, i3 + s2.nodeSize, (p4) => p4.index === c3 && p4.isFirst === l2 && p4.hasStart === u2 ).length === 0) { const p4 = e2.doc.nodeAt(i3 + 1); r4.push( // move in by 1 to account for the block container Decoration.node(i3 + 1, i3 + 1 + p4.nodeSize, { "data-index": c3.toString() }) ); } } }); const a3 = r4.flatMap( (s2) => o2.find(s2.from, s2.to) ); return { decorations: o2.remove(a3).add(e2.doc, r4) }; } var un = () => new Plugin({ key: new PluginKey("numbered-list-indexing-decorations"), state: { init(e2, t2) { return me(t2.tr, { decorations: DecorationSet.empty }); }, apply(e2, t2) { return !e2.docChanged && !e2.selectionSet && t2.decorations ? t2 : me(e2, t2); } }, props: { decorations(e2) { var t2; return ((t2 = this.getState(e2)) == null ? void 0 : t2.decorations) ?? DecorationSet.empty; } } }); var pn = () => ({ type: "numberedListItem", propSchema: { ...h3, start: { default: void 0, type: "number" } }, content: "inline" }); var fn = v2( pn, { meta: { isolating: false }, parse(e2) { var n; if (e2.tagName !== "LI") return; const t2 = e2.parentElement; if (t2 !== null && (t2.tagName === "OL" || t2.tagName === "DIV" && ((n = t2.parentElement) == null ? void 0 : n.tagName) === "OL")) { const o2 = parseInt(t2.getAttribute("start") || "1"), r4 = y(e2); return e2.previousElementSibling || o2 === 1 ? r4 : { ...r4, start: o2 }; } }, // As `li` elements can contain multiple paragraphs, we need to merge their contents // into a single one so that ProseMirror can parse everything correctly. parseContent: ({ el: e2, schema: t2 }) => Y3(e2, t2, "numberedListItem"), render() { const e2 = document.createElement("p"); return { dom: e2, contentDOM: e2 }; }, toExternalHTML(e2) { const t2 = document.createElement("li"), n = document.createElement("p"); return A2(e2.props, t2), t2.appendChild(n), { dom: t2, contentDOM: n }; } }, [ a({ key: "numbered-list-item-shortcuts", inputRules: [ { find: new RegExp("^(\\d+)\\.\\s$"), replace({ match: e2, editor: t2 }) { if (Tt( t2.prosemirrorState ).blockNoteType === "heading") return; const o2 = parseInt(e2[1]); return { type: "numberedListItem", props: { start: o2 !== 1 ? o2 : void 0 } }; } } ], keyboardShortcuts: { Enter: ({ editor: e2 }) => q(e2, "numberedListItem"), "Mod-Shift-7": ({ editor: e2 }) => { const t2 = e2.getTextCursorPosition(); return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, { type: "numberedListItem", props: {} }), true); } }, prosemirrorPlugins: [un()] }) ] ); var hn = () => ({ type: "toggleListItem", propSchema: { ...h3 }, content: "inline" }); var mn = v2( hn, { meta: { isolating: false }, render(e2, t2) { const n = document.createElement("p"); return { ...Be( e2, t2, n ), contentDOM: n }; }, toExternalHTML(e2) { const t2 = document.createElement("li"), n = document.createElement("p"); return A2(e2.props, t2), t2.appendChild(n), { dom: t2, contentDOM: n }; } }, [ a({ key: "toggle-list-item-shortcuts", keyboardShortcuts: { Enter: ({ editor: e2 }) => q(e2, "toggleListItem"), "Mod-Shift-6": ({ editor: e2 }) => { const t2 = e2.getTextCursorPosition(); return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, { type: "toggleListItem", props: {} }), true); } } }) ] ); var gn = () => ({ type: "paragraph", propSchema: h3, content: "inline" }); var bn = v2( gn, { meta: { isolating: false }, parse: (e2) => { var t2; if (e2.tagName === "P" && (t2 = e2.textContent) != null && t2.trim()) return y(e2); }, render: () => { const e2 = document.createElement("p"); return { dom: e2, contentDOM: e2 }; }, toExternalHTML: (e2) => { const t2 = document.createElement("p"); return A2(e2.props, t2), { dom: t2, contentDOM: t2 }; }, runsBefore: ["default"] }, [ a({ key: "paragraph-shortcuts", keyboardShortcuts: { "Mod-Alt-0": ({ editor: e2 }) => { const t2 = e2.getTextCursorPosition(); return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, { type: "paragraph", props: {} }), true); } } }) ] ); var Cn = () => ({ type: "quote", propSchema: { backgroundColor: h3.backgroundColor, textColor: h3.textColor }, content: "inline" }); var kn = v2( Cn, { meta: { isolating: false }, parse(e2) { if (e2.tagName === "BLOCKQUOTE") { const { backgroundColor: t2, textColor: n } = y(e2); return { backgroundColor: t2, textColor: n }; } }, render() { const e2 = document.createElement("blockquote"); return { dom: e2, contentDOM: e2 }; }, toExternalHTML(e2) { const t2 = document.createElement("blockquote"); return A2(e2.props, t2), { dom: t2, contentDOM: t2 }; } }, [ a({ key: "quote-block-shortcuts", keyboardShortcuts: { "Mod-Alt-q": ({ editor: e2 }) => { const t2 = e2.getTextCursorPosition(); return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, { type: "quote", props: {} }), true); } }, inputRules: [ { find: new RegExp("^>\\s$"), replace() { return { type: "quote", props: {} }; } } ] }) ] ); var yn = 35; var Ie = 120; var Mo = 31; var vn = Extension.create({ name: "BlockNoteTableExtension", addProseMirrorPlugins: () => [ columnResizing({ cellMinWidth: yn, defaultCellMinWidth: Ie, // We set this to null as we implement our own node view in the table // block content. This node view is the same as what's used by default, // but is wrapped in a `blockContent` HTML element. View: null }), tableEditing() ], addKeyboardShortcuts() { return { // Makes enter create a new line within the cell. Enter: () => this.editor.state.selection.empty && this.editor.state.selection.$head.parent.type.name === "tableParagraph" ? (this.editor.commands.insertContent({ type: "hardBreak" }), true) : false, // Ensures that backspace won't delete the table if the text cursor is at // the start of a cell and the selection is empty. Backspace: () => { const e2 = this.editor.state.selection, t2 = e2.empty, n = e2.$head.parentOffset === 0, o2 = e2.$head.node().type.name === "tableParagraph"; return t2 && n && o2; }, // Enables navigating cells using the tab key. Tab: () => this.editor.commands.command( ({ state: e2, dispatch: t2, view: n }) => goToNextCell(1)(e2, t2, n) ), "Shift-Tab": () => this.editor.commands.command( ({ state: e2, dispatch: t2, view: n }) => goToNextCell(-1)(e2, t2, n) ) }; }, extendNodeSchema(e2) { const t2 = { name: e2.name, options: e2.options, storage: e2.storage }; return { tableRole: callOrReturn( getExtensionField(e2, "tableRole", t2) ) }; } }); var En = { textColor: h3.textColor }; var xn = Node3.create({ name: "tableHeader", addOptions() { return { HTMLAttributes: {} }; }, /** * We allow table headers and cells to have multiple tableContent nodes because * when merging cells, prosemirror-tables will concat the contents of the cells naively. * This would cause that content to overflow into other cells when prosemirror tries to enforce the cell structure. * * So, we manually fix this up when reading back in the `nodeToBlock` and only ever place a single tableContent back into the cell. */ content: "tableContent+", addAttributes() { return { colspan: { default: 1 }, rowspan: { default: 1 }, colwidth: { default: null, parseHTML: (e2) => { const t2 = e2.getAttribute("colwidth"); return t2 ? t2.split(",").map((o2) => parseInt(o2, 10)) : null; } } }; }, tableRole: "header_cell", isolating: true, parseHTML() { return [ { tag: "th", // As `th` elements can contain multiple paragraphs, we need to merge their contents // into a single one so that ProseMirror can parse everything correctly. getContent: (e2, t2) => De(e2, t2) } ]; }, renderHTML({ HTMLAttributes: e2 }) { return [ "th", mergeAttributes(this.options.HTMLAttributes, e2), 0 ]; } }); var wn = Node3.create({ name: "tableCell", addOptions() { return { HTMLAttributes: {} }; }, content: "tableContent+", addAttributes() { return { colspan: { default: 1 }, rowspan: { default: 1 }, colwidth: { default: null, parseHTML: (e2) => { const t2 = e2.getAttribute("colwidth"); return t2 ? t2.split(",").map((o2) => parseInt(o2, 10)) : null; } } }; }, tableRole: "cell", isolating: true, parseHTML() { return [ { tag: "td", // As `td` elements can contain multiple paragraphs, we need to merge their contents // into a single one so that ProseMirror can parse everything correctly. getContent: (e2, t2) => De(e2, t2) } ]; }, renderHTML({ HTMLAttributes: e2 }) { return [ "td", mergeAttributes(this.options.HTMLAttributes, e2), 0 ]; } }); var Sn = Node3.create({ name: "table", content: "tableRow+", group: "blockContent", tableRole: "table", marks: "deletion insertion modification", isolating: true, parseHTML() { return [ { tag: "table" } ]; }, renderHTML({ node: e2, HTMLAttributes: t2 }) { var r4, a3, s2; const n = gt2( this.name, "table", { ...((r4 = this.options.domAttributes) == null ? void 0 : r4.blockContent) || {}, ...t2 }, ((a3 = this.options.domAttributes) == null ? void 0 : a3.inlineContent) || {} ), o2 = document.createElement("colgroup"); for (const i3 of e2.children[0].children) if (i3.attrs.colwidth) for (const l2 of i3.attrs.colwidth) { const u2 = document.createElement("col"); l2 && (u2.style = `width: ${l2}px`), o2.appendChild(u2); } else o2.appendChild(document.createElement("col")); return (s2 = n.dom.firstChild) == null || s2.appendChild(o2), n; }, // This node view is needed for the `columnResizing` plugin. By default, the // plugin adds its own node view, which overrides how the node is rendered vs // `renderHTML`. This means that the wrapping `blockContent` HTML element is // no longer rendered. The `columnResizing` plugin uses the `TableView` as its // default node view. `BlockNoteTableView` extends it by wrapping it in a // `blockContent` element, so the DOM structure is consistent with other block // types. addNodeView() { return ({ node: e2, HTMLAttributes: t2 }) => { var o2; class n extends TableView { constructor(a3, s2, i3) { super(a3, s2), this.node = a3, this.cellMinWidth = s2, this.blockContentHTMLAttributes = i3; const c3 = document.createElement("div"); c3.className = D2( "bn-block-content", i3.class ), c3.setAttribute("data-content-type", "table"); for (const [p4, m2] of Object.entries( i3 )) p4 !== "class" && c3.setAttribute(p4, m2); const l2 = this.dom, u2 = document.createElement("div"); u2.className = "tableWrapper-inner", u2.appendChild(l2.firstChild), l2.appendChild(u2), c3.appendChild(l2); const d = document.createElement("div"); d.className = "table-widgets-container", d.style.position = "relative", l2.appendChild(d), this.dom = c3; } ignoreMutation(a3) { return !a3.target.closest(".tableWrapper-inner") || super.ignoreMutation(a3); } } return new n(e2, Ie, { ...((o2 = this.options.domAttributes) == null ? void 0 : o2.blockContent) || {}, ...t2 }); }; } }); var Mn = Node3.create({ name: "tableParagraph", group: "tableContent", content: "inline*", parseHTML() { return [ { tag: "p", getAttrs: (e2) => { if (typeof e2 == "string" || !e2.textContent || !e2.closest("[data-content-type]")) return false; const t2 = e2.parentElement; return t2 === null ? false : t2.tagName === "TD" || t2.tagName === "TH" ? {} : false; }, node: "tableParagraph" } ]; }, renderHTML({ HTMLAttributes: e2 }) { return ["p", e2, 0]; } }); var Ln = Node3.create({ name: "tableRow", addOptions() { return { HTMLAttributes: {} }; }, content: "(tableCell | tableHeader)+", tableRole: "row", marks: "deletion insertion modification", parseHTML() { return [{ tag: "tr" }]; }, renderHTML({ HTMLAttributes: e2 }) { return [ "tr", mergeAttributes(this.options.HTMLAttributes, e2), 0 ]; } }); function De(e2, t2) { const o2 = DOMParser2.fromSchema(t2).parse(e2, { topNode: t2.nodes.blockGroup.create() }), r4 = []; return o2.content.descendants((a3) => { if (a3.isInline) return r4.push(a3), false; }), Fragment.fromArray(r4); } var Tn = () => yt2( { node: Sn, type: "table", content: "table" }, En, [ a({ key: "table-extensions", tiptapExtensions: [ vn, Mn, xn, wn, Ln ] }), // Extension for keyboard shortcut which deletes the table if it's empty // and all cells are selected. Uses a separate extension as it needs // priority over keyboard handlers in the `TableExtension`'s // `tableEditing` plugin. a({ key: "table-keyboard-delete", keyboardShortcuts: { Backspace: ({ editor: e2 }) => { if (!(e2.prosemirrorState.selection instanceof CellSelection)) return false; const t2 = e2.getTextCursorPosition().block, n = t2.content; let o2 = 0; for (const a3 of n.rows) for (const s2 of a3.cells) { if ("type" in s2 && s2.content.length > 0 || !("type" in s2) && s2.length > 0) return false; o2++; } let r4 = 0; return e2.prosemirrorState.selection.forEachCell(() => { r4++; }), r4 < o2 ? false : (e2.transact(() => { (e2.getPrevBlock(t2) || e2.getNextBlock(t2)) && e2.setTextCursorPosition(t2), e2.removeBlocks([t2]); }), true); } } }) ] ); var ge = (e2) => { const t2 = e2.src || void 0, n = e2.width || void 0; return { url: t2, previewWidth: n }; }; var Bn = ''; var An = (e2) => ({ type: "video", propSchema: { textAlignment: h3.textAlignment, backgroundColor: h3.backgroundColor, name: { default: "" }, url: { default: "" }, caption: { default: "" }, showPreview: { default: true }, previewWidth: { default: void 0, type: "number" } }, content: "none" }); var Pn = (e2) => (t2) => { if (t2.tagName === "VIDEO") { if (t2.closest("figure")) return; const { backgroundColor: n } = y(t2); return { ...ge(t2), backgroundColor: n }; } if (t2.tagName === "FIGURE") { const n = $3(t2, "video"); if (!n) return; const { targetElement: o2, caption: r4 } = n, { backgroundColor: a3 } = y(t2); return { ...ge(o2), backgroundColor: a3, caption: r4 }; } }; var Nn = v2( An, (e2) => ({ meta: { fileBlockAccept: ["video/*"] }, parse: Pn(), render(t2, n) { const o2 = document.createElement("div"); o2.innerHTML = e2.icon ?? Bn; const r4 = document.createElement("div"); r4.className = "bn-visual-media-wrapper"; const a3 = document.createElement("video"); return a3.className = "bn-visual-media", n.resolveFileUrl ? n.resolveFileUrl(t2.props.url).then((s2) => { a3.src = s2; }) : a3.src = t2.props.url, a3.controls = true, a3.contentEditable = "false", a3.draggable = false, a3.width = t2.props.previewWidth, r4.appendChild(a3), Pe( t2, n, { dom: r4 }, r4, o2.firstElementChild ); }, toExternalHTML(t2) { if (!t2.props.url) { const o2 = document.createElement("p"); return o2.textContent = "Add video", { dom: o2 }; } let n; return t2.props.showPreview ? (n = document.createElement("video"), n.src = t2.props.url, t2.props.previewWidth && (n.width = t2.props.previewWidth)) : (n = document.createElement("a"), n.href = t2.props.url, n.textContent = t2.props.name || t2.props.url), t2.props.caption ? t2.props.showPreview ? J2(n, t2.props.caption) : U(n, t2.props.caption) : { dom: n }; }, runsBefore: ["file"] }) ); function b2(e2, t2, n) { if (!(t2 in e2.schema.blockSpecs)) return false; if (!n) return true; for (const [o2, r4] of Object.entries(n)) { if (!(o2 in e2.schema.blockSpecs[t2].config.propSchema)) return false; if (typeof r4 == "string") { if (e2.schema.blockSpecs[t2].config.propSchema[o2].default !== void 0 && typeof e2.schema.blockSpecs[t2].config.propSchema[o2].default !== r4 || e2.schema.blockSpecs[t2].config.propSchema[o2].type !== void 0 && e2.schema.blockSpecs[t2].config.propSchema[o2].type !== r4) return false; } else { if (e2.schema.blockSpecs[t2].config.propSchema[o2].default !== r4.default || e2.schema.blockSpecs[t2].config.propSchema[o2].default === void 0 && r4.default === void 0 && e2.schema.blockSpecs[t2].config.propSchema[o2].type !== r4.type || typeof e2.schema.blockSpecs[t2].config.propSchema[o2].values != typeof r4.values) return false; if (typeof e2.schema.blockSpecs[t2].config.propSchema[o2].values == "object" && typeof r4.values == "object") { for (const a3 of r4.values) if (!e2.schema.blockSpecs[t2].config.propSchema[o2].values.includes(a3)) return false; } } } return true; } function Lo(e2, t2, n, o2) { return b2(t2, n, o2) && e2.type === n; } function To(e2) { return e2 instanceof CellSelection; } var R2 = /* @__PURE__ */ new Map(); function Hn(e2) { if (R2.has(e2)) return R2.get(e2); const t2 = new Mapping(); return e2._tiptapEditor.on("transaction", ({ transaction: n }) => { t2.appendMapping(n.mapping); }), e2._tiptapEditor.on("destroy", () => { R2.delete(e2); }), R2.set(e2, t2), t2; } function In(e2, t2, n = "left") { const o2 = ySyncPluginKey.getState(e2.prosemirrorState); if (!o2) { const a3 = Hn(e2), s2 = a3.maps.length; return () => a3.slice(s2).map(t2, n === "left" ? -1 : 1); } const r4 = absolutePositionToRelativePosition( // Track the position after the position if we are on the right side t2 + (n === "right" ? 1 : -1), o2.binding.type, o2.binding.mapping ); return () => { const a3 = ySyncPluginKey.getState( e2.prosemirrorState ), s2 = relativePositionToAbsolutePosition( a3.doc, a3.binding.type, r4, a3.binding.mapping ); if (s2 === null) throw new Error("Position not found, cannot track positions"); return s2 + (n === "right" ? -1 : 1); }; } var Dn = findParentNode((e2) => e2.type.name === "blockContainer"); var On = class { constructor(t2, n, o2) { M3(this, "state"); M3(this, "emitUpdate"); M3(this, "rootEl"); M3(this, "pluginState"); M3(this, "handleScroll", () => { var t3, n2; if ((t3 = this.state) != null && t3.show) { const o3 = (n2 = this.rootEl) == null ? void 0 : n2.querySelector( `[data-decoration-id="${this.pluginState.decorationId}"]` ); if (!o3) return; this.state.referencePos = o3.getBoundingClientRect().toJSON(), this.emitUpdate(this.pluginState.triggerCharacter); } }); M3(this, "closeMenu", () => { this.editor.transact((t3) => t3.setMeta(B2, null)); }); M3(this, "clearQuery", () => { this.pluginState !== void 0 && this.editor._tiptapEditor.chain().focus().deleteRange({ from: this.pluginState.queryStartPos() - (this.pluginState.deleteTriggerCharacter ? this.pluginState.triggerCharacter.length : 0), to: this.editor.transact((t3) => t3.selection.from) }).run(); }); var r4; this.editor = t2, this.pluginState = void 0, this.emitUpdate = (a3) => { var s2; if (!this.state) throw new Error("Attempting to update uninitialized suggestions menu"); n(a3, { ...this.state, ignoreQueryLength: (s2 = this.pluginState) == null ? void 0 : s2.ignoreQueryLength }); }, this.rootEl = o2.root, (r4 = this.rootEl) == null || r4.addEventListener("scroll", this.handleScroll, true); } update(t2, n) { var l2; const o2 = B2.getState(n), r4 = B2.getState( t2.state ), a3 = o2 === void 0 && r4 !== void 0, s2 = o2 !== void 0 && r4 === void 0; if (!a3 && !(o2 !== void 0 && r4 !== void 0) && !s2) return; if (this.pluginState = s2 ? o2 : r4, s2 || !this.editor.isEditable) { this.state && (this.state.show = false), this.emitUpdate(this.pluginState.triggerCharacter); return; } const c3 = (l2 = this.rootEl) == null ? void 0 : l2.querySelector( `[data-decoration-id="${this.pluginState.decorationId}"]` ); this.editor.isEditable && c3 && (this.state = { show: true, referencePos: c3.getBoundingClientRect().toJSON(), query: this.pluginState.query }, this.emitUpdate(this.pluginState.triggerCharacter)); } destroy() { var t2; (t2 = this.rootEl) == null || t2.removeEventListener("scroll", this.handleScroll, true); } }; var B2 = new PluginKey("SuggestionMenuPlugin"); var _n = a(({ editor: e2 }) => { const t2 = []; let n; const o2 = f(void 0); return { key: "suggestionMenu", store: o2, addTriggerCharacter: (r4) => { t2.push(r4); }, removeTriggerCharacter: (r4) => { t2.splice(t2.indexOf(r4), 1); }, closeMenu: () => { n == null || n.closeMenu(); }, clearQuery: () => { n == null || n.clearQuery(); }, shown: () => { var r4; return ((r4 = n == null ? void 0 : n.state) == null ? void 0 : r4.show) || false; }, openSuggestionMenu: (r4, a3) => { e2.headless || (e2.focus(), e2.transact((s2) => { a3 != null && a3.deleteTriggerCharacter && s2.insertText(r4), s2.scrollIntoView().setMeta(B2, { triggerCharacter: r4, deleteTriggerCharacter: (a3 == null ? void 0 : a3.deleteTriggerCharacter) || false, ignoreQueryLength: (a3 == null ? void 0 : a3.ignoreQueryLength) || false }); })); }, // TODO this whole plugin needs to be refactored (but I've done the minimal) prosemirrorPlugins: [ new Plugin({ key: B2, view: (r4) => (n = new On( e2, (a3, s2) => { o2.setState({ ...s2, triggerCharacter: a3 }); }, r4 ), n), state: { // Initialize the plugin's internal state. init() { }, // Apply changes to the plugin state from an editor transaction. apply: (r4, a3, s2, i3) => { if (r4.selection.$from.parent.type.spec.code) return a3; const c3 = r4.getMeta(B2); if (typeof c3 == "object" && c3 !== null) { a3 && (n == null || n.closeMenu()); const u2 = In( e2, i3.selection.from - // Need to account for the trigger char that was inserted, so we offset the position by the length of the trigger character. c3.triggerCharacter.length ); return { triggerCharacter: c3.triggerCharacter, deleteTriggerCharacter: c3.deleteTriggerCharacter !== false, // When reading the queryStartPos, we offset the result by the length of the trigger character, to make it easy on the caller queryStartPos: () => u2() + c3.triggerCharacter.length, query: "", decorationId: `id_${Math.floor(Math.random() * 4294967295)}`, ignoreQueryLength: c3 == null ? void 0 : c3.ignoreQueryLength }; } if (a3 === void 0) return a3; if ( // Highlighting text should hide the menu. i3.selection.from !== i3.selection.to || // Transactions with plugin metadata should hide the menu. c3 === null || // Certain mouse events should hide the menu. // TODO: Change to global mousedown listener. r4.getMeta("focus") || r4.getMeta("blur") || r4.getMeta("pointer") || // Moving the caret before the character which triggered the menu should hide it. a3.triggerCharacter !== void 0 && i3.selection.from < a3.queryStartPos() || // Moving the caret to a new block should hide the menu. !i3.selection.$from.sameParent( i3.doc.resolve(a3.queryStartPos()) ) ) return; const l2 = { ...a3 }; return l2.query = i3.doc.textBetween( a3.queryStartPos(), i3.selection.from ), l2; } }, props: { handleTextInput(r4, a3, s2, i3) { if (a3 === s2) { const c3 = r4.state.doc; for (const l2 of t2) { const u2 = l2.length > 1 ? c3.textBetween(a3 - l2.length, a3) + i3 : i3; if (l2 === u2) return r4.dispatch(r4.state.tr.insertText(i3)), r4.dispatch( r4.state.tr.setMeta(B2, { triggerCharacter: u2 }).scrollIntoView() ), true; } } return false; }, // Setup decorator on the currently active suggestion. decorations(r4) { const a3 = this.getState(r4); if (a3 === void 0) return null; if (!a3.deleteTriggerCharacter) { const s2 = Dn(r4.selection); if (s2) return DecorationSet.create(r4.doc, [ Decoration.node( s2.pos, s2.pos + s2.node.nodeSize, { nodeName: "span", class: "bn-suggestion-decorator", "data-decoration-id": a3.decorationId } ) ]); } return DecorationSet.create(r4.doc, [ Decoration.inline( a3.queryStartPos() - a3.triggerCharacter.length, a3.queryStartPos(), { nodeName: "span", class: "bn-suggestion-decorator", "data-decoration-id": a3.decorationId } ) ]); } } }) ] }; }); function Vn(e2) { let t2 = e2.getTextCursorPosition().block, n = e2.schema.blockSchema[t2.type].content; for (; n === "none"; ) { if (t2 = e2.getTextCursorPosition().nextBlock, t2 === void 0) return; n = e2.schema.blockSchema[t2.type].content, e2.setTextCursorPosition(t2, "end"); } } function C(e2, t2) { const n = e2.getTextCursorPosition().block; if (n.content === void 0) throw new Error("Slash Menu open in a block that doesn't contain content."); let o2; return Array.isArray(n.content) && (n.content.length === 1 && B(n.content[0]) && n.content[0].type === "text" && n.content[0].text === "/" || n.content.length === 0) ? (o2 = e2.updateBlock(n, t2), e2.setTextCursorPosition(o2)) : (o2 = e2.insertBlocks([t2], n, "after")[0], e2.setTextCursorPosition(e2.getTextCursorPosition().nextBlock)), Vn(e2), o2; } function Bo(e2) { const t2 = []; return b2(e2, "heading", { level: "number" }) && (e2.schema.blockSchema.heading.propSchema.level.values || []).filter((n) => n <= 3).forEach((n) => { t2.push({ onItemClick: () => { C(e2, { type: "heading", props: { level: n } }); }, badge: L2(`Mod-Alt-${n}`), key: n === 1 ? "heading" : `heading_${n}`, ...e2.dictionary.slash_menu[n === 1 ? "heading" : `heading_${n}`] }); }), b2(e2, "quote") && t2.push({ onItemClick: () => { C(e2, { type: "quote" }); }, key: "quote", ...e2.dictionary.slash_menu.quote }), b2(e2, "toggleListItem") && t2.push({ onItemClick: () => { C(e2, { type: "toggleListItem" }); }, badge: L2("Mod-Shift-6"), key: "toggle_list", ...e2.dictionary.slash_menu.toggle_list }), b2(e2, "numberedListItem") && t2.push({ onItemClick: () => { C(e2, { type: "numberedListItem" }); }, badge: L2("Mod-Shift-7"), key: "numbered_list", ...e2.dictionary.slash_menu.numbered_list }), b2(e2, "bulletListItem") && t2.push({ onItemClick: () => { C(e2, { type: "bulletListItem" }); }, badge: L2("Mod-Shift-8"), key: "bullet_list", ...e2.dictionary.slash_menu.bullet_list }), b2(e2, "checkListItem") && t2.push({ onItemClick: () => { C(e2, { type: "checkListItem" }); }, badge: L2("Mod-Shift-9"), key: "check_list", ...e2.dictionary.slash_menu.check_list }), b2(e2, "paragraph") && t2.push({ onItemClick: () => { C(e2, { type: "paragraph" }); }, badge: L2("Mod-Alt-0"), key: "paragraph", ...e2.dictionary.slash_menu.paragraph }), b2(e2, "codeBlock") && t2.push({ onItemClick: () => { C(e2, { type: "codeBlock" }); }, badge: L2("Mod-Alt-c"), key: "code_block", ...e2.dictionary.slash_menu.code_block }), b2(e2, "divider") && t2.push({ onItemClick: () => { C(e2, { type: "divider" }); }, key: "divider", ...e2.dictionary.slash_menu.divider }), b2(e2, "table") && t2.push({ onItemClick: () => { C(e2, { type: "table", content: { type: "tableContent", rows: [ { cells: ["", "", ""] }, { cells: ["", "", ""] } ] } }); }, badge: void 0, key: "table", ...e2.dictionary.slash_menu.table }), b2(e2, "image", { url: "string" }) && t2.push({ onItemClick: () => { var o2; const n = C(e2, { type: "image" }); (o2 = e2.getExtension(I2)) == null || o2.showMenu(n.id); }, key: "image", ...e2.dictionary.slash_menu.image }), b2(e2, "video", { url: "string" }) && t2.push({ onItemClick: () => { var o2; const n = C(e2, { type: "video" }); (o2 = e2.getExtension(I2)) == null || o2.showMenu(n.id); }, key: "video", ...e2.dictionary.slash_menu.video }), b2(e2, "audio", { url: "string" }) && t2.push({ onItemClick: () => { var o2; const n = C(e2, { type: "audio" }); (o2 = e2.getExtension(I2)) == null || o2.showMenu(n.id); }, key: "audio", ...e2.dictionary.slash_menu.audio }), b2(e2, "file", { url: "string" }) && t2.push({ onItemClick: () => { var o2; const n = C(e2, { type: "file" }); (o2 = e2.getExtension(I2)) == null || o2.showMenu(n.id); }, key: "file", ...e2.dictionary.slash_menu.file }), b2(e2, "heading", { level: "number", isToggleable: "boolean" }) && (e2.schema.blockSchema.heading.propSchema.level.values || []).filter((n) => n <= 3).forEach((n) => { t2.push({ onItemClick: () => { C(e2, { type: "heading", props: { level: n, isToggleable: true } }); }, key: n === 1 ? "toggle_heading" : `toggle_heading_${n}`, ...e2.dictionary.slash_menu[n === 1 ? "toggle_heading" : `toggle_heading_${n}`] }); }), b2(e2, "heading", { level: "number" }) && (e2.schema.blockSchema.heading.propSchema.level.values || []).filter((n) => n > 3).forEach((n) => { t2.push({ onItemClick: () => { C(e2, { type: "heading", props: { level: n } }); }, badge: L2(`Mod-Alt-${n}`), key: `heading_${n}`, ...e2.dictionary.slash_menu[`heading_${n}`] }); }), t2.push({ onItemClick: () => { var n; (n = e2.getExtension(_n)) == null || n.openSuggestionMenu(":", { deleteTriggerCharacter: true, ignoreQueryLength: true }); }, key: "emoji", ...e2.dictionary.slash_menu.emoji }), t2; } function Ao(e2, t2) { return e2.filter( ({ title: n, aliases: o2 }) => n.toLowerCase().includes(t2.toLowerCase()) || o2 && o2.filter( (r4) => r4.toLowerCase().includes(t2.toLowerCase()) ).length !== 0 ); } var Po = { audio: Ft(), bulletListItem: cn(), checkListItem: dn(), codeBlock: qt(), divider: Gt(), file: Xt(), heading: Yt(), image: an(), numberedListItem: fn(), paragraph: bn(), quote: kn(), table: Tn(), toggleListItem: mn(), video: Nn() }; var Rn = Le( { type: "textColor", propSchema: "string" }, { render: () => { const e2 = document.createElement("span"); return { dom: e2, contentDOM: e2 }; }, toExternalHTML: (e2) => { const t2 = document.createElement("span"); return e2 !== h3.textColor.default && (t2.style.color = e2 in T2 ? T2[e2].text : e2), { dom: t2, contentDOM: t2 }; }, parse: (e2) => { if (e2.tagName === "SPAN" && e2.style.color) return e2.style.color; } } ); var Wn = Le( { type: "backgroundColor", propSchema: "string" }, { render: () => { const e2 = document.createElement("span"); return { dom: e2, contentDOM: e2 }; }, toExternalHTML: (e2) => { const t2 = document.createElement("span"); return e2 !== h3.backgroundColor.default && (t2.style.backgroundColor = e2 in T2 ? T2[e2].background : e2), { dom: t2, contentDOM: t2 }; }, parse: (e2) => { if (e2.tagName === "SPAN" && e2.style.backgroundColor) return e2.style.backgroundColor; } } ); var Fn = { bold: H2(index_default, "boolean"), italic: H2(index_default3, "boolean"), underline: H2(index_default5, "boolean"), strike: H2(index_default4, "boolean"), code: H2(index_default2, "boolean"), textColor: Rn, backgroundColor: Wn }; var No = Mt2(Fn); var $n = { text: { config: "text", implementation: {} }, link: { config: "link", implementation: {} } }; var Ho = wt2( $n ); // ../../node_modules/.pnpm/prosemirror-dropcursor@1.8.2/node_modules/prosemirror-dropcursor/dist/index.js function dropCursor(options2 = {}) { return new Plugin({ view(editorView) { return new DropCursorView(editorView, options2); } }); } var DropCursorView = class { constructor(editorView, options2) { var _a2; this.editorView = editorView; this.cursorPos = null; this.element = null; this.timeout = -1; this.width = (_a2 = options2.width) !== null && _a2 !== void 0 ? _a2 : 1; this.color = options2.color === false ? void 0 : options2.color || "black"; this.class = options2.class; this.handlers = ["dragover", "dragend", "drop", "dragleave"].map((name) => { let handler = (e2) => { this[name](e2); }; editorView.dom.addEventListener(name, handler); return { name, handler }; }); } destroy() { this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler)); } update(editorView, prevState) { if (this.cursorPos != null && prevState.doc != editorView.state.doc) { if (this.cursorPos > editorView.state.doc.content.size) this.setCursor(null); else this.updateOverlay(); } } setCursor(pos) { if (pos == this.cursorPos) return; this.cursorPos = pos; if (pos == null) { this.element.parentNode.removeChild(this.element); this.element = null; } else { this.updateOverlay(); } } updateOverlay() { let $pos = this.editorView.state.doc.resolve(this.cursorPos); let isBlock = !$pos.parent.inlineContent, rect; let editorDOM = this.editorView.dom, editorRect = editorDOM.getBoundingClientRect(); let scaleX = editorRect.width / editorDOM.offsetWidth, scaleY = editorRect.height / editorDOM.offsetHeight; if (isBlock) { let before = $pos.nodeBefore, after = $pos.nodeAfter; if (before || after) { let node2 = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0)); if (node2) { let nodeRect = node2.getBoundingClientRect(); let top = before ? nodeRect.bottom : nodeRect.top; if (before && after) top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2; let halfWidth = this.width / 2 * scaleY; rect = { left: nodeRect.left, right: nodeRect.right, top: top - halfWidth, bottom: top + halfWidth }; } } } if (!rect) { let coords = this.editorView.coordsAtPos(this.cursorPos); let halfWidth = this.width / 2 * scaleX; rect = { left: coords.left - halfWidth, right: coords.left + halfWidth, top: coords.top, bottom: coords.bottom }; } let parent = this.editorView.dom.offsetParent; if (!this.element) { this.element = parent.appendChild(document.createElement("div")); if (this.class) this.element.className = this.class; this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none;"; if (this.color) { this.element.style.backgroundColor = this.color; } } this.element.classList.toggle("prosemirror-dropcursor-block", isBlock); this.element.classList.toggle("prosemirror-dropcursor-inline", !isBlock); let parentLeft, parentTop; if (!parent || parent == document.body && getComputedStyle(parent).position == "static") { parentLeft = -pageXOffset; parentTop = -pageYOffset; } else { let rect2 = parent.getBoundingClientRect(); let parentScaleX = rect2.width / parent.offsetWidth, parentScaleY = rect2.height / parent.offsetHeight; parentLeft = rect2.left - parent.scrollLeft * parentScaleX; parentTop = rect2.top - parent.scrollTop * parentScaleY; } this.element.style.left = (rect.left - parentLeft) / scaleX + "px"; this.element.style.top = (rect.top - parentTop) / scaleY + "px"; this.element.style.width = (rect.right - rect.left) / scaleX + "px"; this.element.style.height = (rect.bottom - rect.top) / scaleY + "px"; } scheduleRemoval(timeout2) { clearTimeout(this.timeout); this.timeout = setTimeout(() => this.setCursor(null), timeout2); } dragover(event) { if (!this.editorView.editable) return; let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY }); let node2 = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside); let disableDropCursor = node2 && node2.type.spec.disableDropCursor; let disabled = typeof disableDropCursor == "function" ? disableDropCursor(this.editorView, pos, event) : disableDropCursor; if (pos && !disabled) { let target = pos.pos; if (this.editorView.dragging && this.editorView.dragging.slice) { let point5 = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice); if (point5 != null) target = point5; } this.setCursor(target); this.scheduleRemoval(5e3); } } dragend() { this.scheduleRemoval(20); } drop() { this.scheduleRemoval(20); } dragleave(event) { if (!this.editorView.dom.contains(event.relatedTarget)) this.setCursor(null); } }; // ../../node_modules/.pnpm/rope-sequence@1.3.4/node_modules/rope-sequence/dist/index.js var GOOD_LEAF_SIZE = 200; var RopeSequence = function RopeSequence2() { }; RopeSequence.prototype.append = function append2(other) { if (!other.length) { return this; } other = RopeSequence.from(other); return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other); }; RopeSequence.prototype.prepend = function prepend(other) { if (!other.length) { return this; } return RopeSequence.from(other).append(this); }; RopeSequence.prototype.appendInner = function appendInner(other) { return new Append(this, other); }; RopeSequence.prototype.slice = function slice(from4, to2) { if (from4 === void 0) from4 = 0; if (to2 === void 0) to2 = this.length; if (from4 >= to2) { return RopeSequence.empty; } return this.sliceInner(Math.max(0, from4), Math.min(this.length, to2)); }; RopeSequence.prototype.get = function get(i3) { if (i3 < 0 || i3 >= this.length) { return void 0; } return this.getInner(i3); }; RopeSequence.prototype.forEach = function forEach4(f6, from4, to2) { if (from4 === void 0) from4 = 0; if (to2 === void 0) to2 = this.length; if (from4 <= to2) { this.forEachInner(f6, from4, to2, 0); } else { this.forEachInvertedInner(f6, from4, to2, 0); } }; RopeSequence.prototype.map = function map3(f6, from4, to2) { if (from4 === void 0) from4 = 0; if (to2 === void 0) to2 = this.length; var result = []; this.forEach(function(elt, i3) { return result.push(f6(elt, i3)); }, from4, to2); return result; }; RopeSequence.from = function from3(values2) { if (values2 instanceof RopeSequence) { return values2; } return values2 && values2.length ? new Leaf(values2) : RopeSequence.empty; }; var Leaf = (function(RopeSequence3) { function Leaf2(values2) { RopeSequence3.call(this); this.values = values2; } if (RopeSequence3) Leaf2.__proto__ = RopeSequence3; Leaf2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype); Leaf2.prototype.constructor = Leaf2; var prototypeAccessors = { length: { configurable: true }, depth: { configurable: true } }; Leaf2.prototype.flatten = function flatten2() { return this.values; }; Leaf2.prototype.sliceInner = function sliceInner(from4, to2) { if (from4 == 0 && to2 == this.length) { return this; } return new Leaf2(this.values.slice(from4, to2)); }; Leaf2.prototype.getInner = function getInner(i3) { return this.values[i3]; }; Leaf2.prototype.forEachInner = function forEachInner(f6, from4, to2, start) { for (var i3 = from4; i3 < to2; i3++) { if (f6(this.values[i3], start + i3) === false) { return false; } } }; Leaf2.prototype.forEachInvertedInner = function forEachInvertedInner(f6, from4, to2, start) { for (var i3 = from4 - 1; i3 >= to2; i3--) { if (f6(this.values[i3], start + i3) === false) { return false; } } }; Leaf2.prototype.leafAppend = function leafAppend(other) { if (this.length + other.length <= GOOD_LEAF_SIZE) { return new Leaf2(this.values.concat(other.flatten())); } }; Leaf2.prototype.leafPrepend = function leafPrepend(other) { if (this.length + other.length <= GOOD_LEAF_SIZE) { return new Leaf2(other.flatten().concat(this.values)); } }; prototypeAccessors.length.get = function() { return this.values.length; }; prototypeAccessors.depth.get = function() { return 0; }; Object.defineProperties(Leaf2.prototype, prototypeAccessors); return Leaf2; })(RopeSequence); RopeSequence.empty = new Leaf([]); var Append = (function(RopeSequence3) { function Append2(left, right) { RopeSequence3.call(this); this.left = left; this.right = right; this.length = left.length + right.length; this.depth = Math.max(left.depth, right.depth) + 1; } if (RopeSequence3) Append2.__proto__ = RopeSequence3; Append2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype); Append2.prototype.constructor = Append2; Append2.prototype.flatten = function flatten2() { return this.left.flatten().concat(this.right.flatten()); }; Append2.prototype.getInner = function getInner(i3) { return i3 < this.left.length ? this.left.get(i3) : this.right.get(i3 - this.left.length); }; Append2.prototype.forEachInner = function forEachInner(f6, from4, to2, start) { var leftLen = this.left.length; if (from4 < leftLen && this.left.forEachInner(f6, from4, Math.min(to2, leftLen), start) === false) { return false; } if (to2 > leftLen && this.right.forEachInner(f6, Math.max(from4 - leftLen, 0), Math.min(this.length, to2) - leftLen, start + leftLen) === false) { return false; } }; Append2.prototype.forEachInvertedInner = function forEachInvertedInner(f6, from4, to2, start) { var leftLen = this.left.length; if (from4 > leftLen && this.right.forEachInvertedInner(f6, from4 - leftLen, Math.max(to2, leftLen) - leftLen, start + leftLen) === false) { return false; } if (to2 < leftLen && this.left.forEachInvertedInner(f6, Math.min(from4, leftLen), to2, start) === false) { return false; } }; Append2.prototype.sliceInner = function sliceInner(from4, to2) { if (from4 == 0 && to2 == this.length) { return this; } var leftLen = this.left.length; if (to2 <= leftLen) { return this.left.slice(from4, to2); } if (from4 >= leftLen) { return this.right.slice(from4 - leftLen, to2 - leftLen); } return this.left.slice(from4, leftLen).append(this.right.slice(0, to2 - leftLen)); }; Append2.prototype.leafAppend = function leafAppend(other) { var inner = this.right.leafAppend(other); if (inner) { return new Append2(this.left, inner); } }; Append2.prototype.leafPrepend = function leafPrepend(other) { var inner = this.left.leafPrepend(other); if (inner) { return new Append2(inner, this.right); } }; Append2.prototype.appendInner = function appendInner2(other) { if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) { return new Append2(this.left, new Append2(this.right, other)); } return new Append2(this, other); }; return Append2; })(RopeSequence); var dist_default2 = RopeSequence; // ../../node_modules/.pnpm/prosemirror-history@1.5.0/node_modules/prosemirror-history/dist/index.js var max_empty_items = 500; var Branch = class _Branch { constructor(items, eventCount) { this.items = items; this.eventCount = eventCount; } // Pop the latest event off the branch's history and apply it // to a document transform. popEvent(state, preserveItems) { if (this.eventCount == 0) return null; let end = this.items.length; for (; ; end--) { let next2 = this.items.get(end - 1); if (next2.selection) { --end; break; } } let remap, mapFrom; if (preserveItems) { remap = this.remapping(end, this.items.length); mapFrom = remap.maps.length; } let transform2 = state.tr; let selection, remaining; let addAfter = [], addBefore = []; this.items.forEach((item, i3) => { if (!item.step) { if (!remap) { remap = this.remapping(end, i3 + 1); mapFrom = remap.maps.length; } mapFrom--; addBefore.push(item); return; } if (remap) { addBefore.push(new Item2(item.map)); let step = item.step.map(remap.slice(mapFrom)), map7; if (step && transform2.maybeStep(step).doc) { map7 = transform2.mapping.maps[transform2.mapping.maps.length - 1]; addAfter.push(new Item2(map7, void 0, void 0, addAfter.length + addBefore.length)); } mapFrom--; if (map7) remap.appendMap(map7, mapFrom); } else { transform2.maybeStep(item.step); } if (item.selection) { selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection; remaining = new _Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1); return false; } }, this.items.length, 0); return { remaining, transform: transform2, selection }; } // Create a new branch with the given transform added. addTransform(transform2, selection, histOptions, preserveItems) { let newItems = [], eventCount = this.eventCount; let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null; for (let i3 = 0; i3 < transform2.steps.length; i3++) { let step = transform2.steps[i3].invert(transform2.docs[i3]); let item = new Item2(transform2.mapping.maps[i3], step, selection), merged; if (merged = lastItem && lastItem.merge(item)) { item = merged; if (i3) newItems.pop(); else oldItems = oldItems.slice(0, oldItems.length - 1); } newItems.push(item); if (selection) { eventCount++; selection = void 0; } if (!preserveItems) lastItem = item; } let overflow = eventCount - histOptions.depth; if (overflow > DEPTH_OVERFLOW) { oldItems = cutOffEvents(oldItems, overflow); eventCount -= overflow; } return new _Branch(oldItems.append(newItems), eventCount); } remapping(from4, to2) { let maps = new Mapping(); this.items.forEach((item, i3) => { let mirrorPos = item.mirrorOffset != null && i3 - item.mirrorOffset >= from4 ? maps.maps.length - item.mirrorOffset : void 0; maps.appendMap(item.map, mirrorPos); }, from4, to2); return maps; } addMaps(array) { if (this.eventCount == 0) return this; return new _Branch(this.items.append(array.map((map7) => new Item2(map7))), this.eventCount); } // When the collab module receives remote changes, the history has // to know about those, so that it can adjust the steps that were // rebased on top of the remote changes, and include the position // maps for the remote changes in its array of items. rebased(rebasedTransform, rebasedCount) { if (!this.eventCount) return this; let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount); let mapping = rebasedTransform.mapping; let newUntil = rebasedTransform.steps.length; let eventCount = this.eventCount; this.items.forEach((item) => { if (item.selection) eventCount--; }, start); let iRebased = rebasedCount; this.items.forEach((item) => { let pos = mapping.getMirror(--iRebased); if (pos == null) return; newUntil = Math.min(newUntil, pos); let map7 = mapping.maps[pos]; if (item.step) { let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]); let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos)); if (selection) eventCount++; rebasedItems.push(new Item2(map7, step, selection)); } else { rebasedItems.push(new Item2(map7)); } }, start); let newMaps = []; for (let i3 = rebasedCount; i3 < newUntil; i3++) newMaps.push(new Item2(mapping.maps[i3])); let items = this.items.slice(0, start).append(newMaps).append(rebasedItems); let branch = new _Branch(items, eventCount); if (branch.emptyItemCount() > max_empty_items) branch = branch.compress(this.items.length - rebasedItems.length); return branch; } emptyItemCount() { let count2 = 0; this.items.forEach((item) => { if (!item.step) count2++; }); return count2; } // Compressing a branch means rewriting it to push the air (map-only // items) out. During collaboration, these naturally accumulate // because each remote change adds one. The `upto` argument is used // to ensure that only the items below a given level are compressed, // because `rebased` relies on a clean, untouched set of items in // order to associate old items with rebased steps. compress(upto = this.items.length) { let remap = this.remapping(0, upto), mapFrom = remap.maps.length; let items = [], events = 0; this.items.forEach((item, i3) => { if (i3 >= upto) { items.push(item); if (item.selection) events++; } else if (item.step) { let step = item.step.map(remap.slice(mapFrom)), map7 = step && step.getMap(); mapFrom--; if (map7) remap.appendMap(map7, mapFrom); if (step) { let selection = item.selection && item.selection.map(remap.slice(mapFrom)); if (selection) events++; let newItem = new Item2(map7.invert(), step, selection), merged, last2 = items.length - 1; if (merged = items.length && items[last2].merge(newItem)) items[last2] = merged; else items.push(newItem); } } else if (item.map) { mapFrom--; } }, this.items.length, 0); return new _Branch(dist_default2.from(items.reverse()), events); } }; Branch.empty = new Branch(dist_default2.empty, 0); function cutOffEvents(items, n) { let cutPoint; items.forEach((item, i3) => { if (item.selection && n-- == 0) { cutPoint = i3; return false; } }); return items.slice(cutPoint); } var Item2 = class _Item { constructor(map7, step, selection, mirrorOffset) { this.map = map7; this.step = step; this.selection = selection; this.mirrorOffset = mirrorOffset; } merge(other) { if (this.step && other.step && !other.selection) { let step = other.step.merge(this.step); if (step) return new _Item(step.getMap().invert(), step, this.selection); } } }; var HistoryState = class { constructor(done, undone, prevRanges, prevTime, prevComposition) { this.done = done; this.undone = undone; this.prevRanges = prevRanges; this.prevTime = prevTime; this.prevComposition = prevComposition; } }; var DEPTH_OVERFLOW = 20; function applyTransaction(history2, state, tr4, options2) { let historyTr = tr4.getMeta(historyKey), rebased; if (historyTr) return historyTr.historyState; if (tr4.getMeta(closeHistoryKey)) history2 = new HistoryState(history2.done, history2.undone, null, 0, -1); let appended = tr4.getMeta("appendedTransaction"); if (tr4.steps.length == 0) { return history2; } else if (appended && appended.getMeta(historyKey)) { if (appended.getMeta(historyKey).redo) return new HistoryState(history2.done.addTransform(tr4, void 0, options2, mustPreserveItems(state)), history2.undone, rangesFor(tr4.mapping.maps), history2.prevTime, history2.prevComposition); else return new HistoryState(history2.done, history2.undone.addTransform(tr4, void 0, options2, mustPreserveItems(state)), null, history2.prevTime, history2.prevComposition); } else if (tr4.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) { let composition = tr4.getMeta("composition"); let newGroup = history2.prevTime == 0 || !appended && history2.prevComposition != composition && (history2.prevTime < (tr4.time || 0) - options2.newGroupDelay || !isAdjacentTo(tr4, history2.prevRanges)); let prevRanges = appended ? mapRanges(history2.prevRanges, tr4.mapping) : rangesFor(tr4.mapping.maps); return new HistoryState(history2.done.addTransform(tr4, newGroup ? state.selection.getBookmark() : void 0, options2, mustPreserveItems(state)), Branch.empty, prevRanges, tr4.time, composition == null ? history2.prevComposition : composition); } else if (rebased = tr4.getMeta("rebased")) { return new HistoryState(history2.done.rebased(tr4, rebased), history2.undone.rebased(tr4, rebased), mapRanges(history2.prevRanges, tr4.mapping), history2.prevTime, history2.prevComposition); } else { return new HistoryState(history2.done.addMaps(tr4.mapping.maps), history2.undone.addMaps(tr4.mapping.maps), mapRanges(history2.prevRanges, tr4.mapping), history2.prevTime, history2.prevComposition); } } function isAdjacentTo(transform2, prevRanges) { if (!prevRanges) return false; if (!transform2.docChanged) return true; let adjacent = false; transform2.mapping.maps[0].forEach((start, end) => { for (let i3 = 0; i3 < prevRanges.length; i3 += 2) if (start <= prevRanges[i3 + 1] && end >= prevRanges[i3]) adjacent = true; }); return adjacent; } function rangesFor(maps) { let result = []; for (let i3 = maps.length - 1; i3 >= 0 && result.length == 0; i3--) maps[i3].forEach((_from, _to, from4, to2) => result.push(from4, to2)); return result; } function mapRanges(ranges, mapping) { if (!ranges) return null; let result = []; for (let i3 = 0; i3 < ranges.length; i3 += 2) { let from4 = mapping.map(ranges[i3], 1), to2 = mapping.map(ranges[i3 + 1], -1); if (from4 <= to2) result.push(from4, to2); } return result; } function histTransaction(history2, state, redo3) { let preserveItems = mustPreserveItems(state); let histOptions = historyKey.get(state).spec.config; let pop = (redo3 ? history2.undone : history2.done).popEvent(state, preserveItems); if (!pop) return null; let selection = pop.selection.resolve(pop.transform.doc); let added = (redo3 ? history2.done : history2.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems); let newHist = new HistoryState(redo3 ? added : pop.remaining, redo3 ? pop.remaining : added, null, 0, -1); return pop.transform.setSelection(selection).setMeta(historyKey, { redo: redo3, historyState: newHist }); } var cachedPreserveItems = false; var cachedPreserveItemsPlugins = null; function mustPreserveItems(state) { let plugins = state.plugins; if (cachedPreserveItemsPlugins != plugins) { cachedPreserveItems = false; cachedPreserveItemsPlugins = plugins; for (let i3 = 0; i3 < plugins.length; i3++) if (plugins[i3].spec.historyPreserveItems) { cachedPreserveItems = true; break; } } return cachedPreserveItems; } function closeHistory(tr4) { return tr4.setMeta(closeHistoryKey, true); } var historyKey = new PluginKey("history"); var closeHistoryKey = new PluginKey("closeHistory"); function history(config = {}) { config = { depth: config.depth || 100, newGroupDelay: config.newGroupDelay || 500 }; return new Plugin({ key: historyKey, state: { init() { return new HistoryState(Branch.empty, Branch.empty, null, 0, -1); }, apply(tr4, hist, state) { return applyTransaction(hist, state, tr4, config); } }, config, props: { handleDOMEvents: { beforeinput(view, e2) { let inputType = e2.inputType; let command2 = inputType == "historyUndo" ? undo2 : inputType == "historyRedo" ? redo2 : null; if (!command2 || !view.editable) return false; e2.preventDefault(); return command2(view.state, view.dispatch); } } } }); } function buildCommand(redo3, scroll) { return (state, dispatch) => { let hist = historyKey.getState(state); if (!hist || (redo3 ? hist.undone : hist.done).eventCount == 0) return false; if (dispatch) { let tr4 = histTransaction(hist, state, redo3); if (tr4) dispatch(scroll ? tr4.scrollIntoView() : tr4); } return true; }; } var undo2 = buildCommand(false, true); var redo2 = buildCommand(true, true); var undoNoScroll = buildCommand(false, false); var redoNoScroll = buildCommand(true, false); // ../../node_modules/.pnpm/devlop@1.1.0/node_modules/devlop/lib/development.js var AssertionError = class extends Error { /** * Create an assertion error. * * @param {string} message * Message explaining error. * @param {unknown} actual * Value. * @param {unknown} expected * Baseline. * @param {string} operator * Name of equality operation. * @param {boolean} generated * Whether `message` is a custom message or not * @returns * Instance. */ // eslint-disable-next-line max-params constructor(message, actual, expected, operator, generated) { super(message); __publicField( this, "name", /** @type {const} */ "Assertion" ); __publicField( this, "code", /** @type {const} */ "ERR_ASSERTION" ); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } this.actual = actual; this.expected = expected; this.generated = generated; this.operator = operator; } }; function ok(value, message) { assert2( Boolean(value), false, true, "ok", "Expected value to be truthy", message ); } function assert2(bool2, actual, expected, operator, defaultMessage, userMessage) { if (!bool2) { throw userMessage instanceof Error ? userMessage : new AssertionError( userMessage || defaultMessage, actual, expected, operator, !userMessage ); } } // ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/schema.js var Schema3 = class { /** * @param {SchemaType['property']} property * Property. * @param {SchemaType['normal']} normal * Normal. * @param {Space | undefined} [space] * Space. * @returns * Schema. */ constructor(property, normal, space2) { this.normal = normal; this.property = property; if (space2) { this.space = space2; } } }; Schema3.prototype.normal = {}; Schema3.prototype.property = {}; Schema3.prototype.space = void 0; // ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/merge.js function merge(definitions, space2) { const property = {}; const normal = {}; for (const definition3 of definitions) { Object.assign(property, definition3.property); Object.assign(normal, definition3.normal); } return new Schema3(property, normal, space2); } // ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/normalize.js function normalize2(value) { return value.toLowerCase(); } // ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/info.js var Info = class { /** * @param {string} property * Property. * @param {string} attribute * Attribute. * @returns * Info. */ constructor(property, attribute) { this.attribute = attribute; this.property = property; } }; Info.prototype.attribute = ""; Info.prototype.booleanish = false; Info.prototype.boolean = false; Info.prototype.commaOrSpaceSeparated = false; Info.prototype.commaSeparated = false; Info.prototype.defined = false; Info.prototype.mustUseProperty = false; Info.prototype.number = false; Info.prototype.overloadedBoolean = false; Info.prototype.property = ""; Info.prototype.spaceSeparated = false; Info.prototype.space = void 0; // ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/types.js var types_exports = {}; __export(types_exports, { boolean: () => boolean, booleanish: () => booleanish, commaOrSpaceSeparated: () => commaOrSpaceSeparated, commaSeparated: () => commaSeparated, number: () => number, overloadedBoolean: () => overloadedBoolean, spaceSeparated: () => spaceSeparated }); var powers = 0; var boolean = increment(); var booleanish = increment(); var overloadedBoolean = increment(); var number = increment(); var spaceSeparated = increment(); var commaSeparated = increment(); var commaOrSpaceSeparated = increment(); function increment() { return 2 ** ++powers; } // ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/defined-info.js var checks = ( /** @type {ReadonlyArray} */ Object.keys(types_exports) ); var DefinedInfo = class extends Info { /** * @constructor * @param {string} property * Property. * @param {string} attribute * Attribute. * @param {number | null | undefined} [mask] * Mask. * @param {Space | undefined} [space] * Space. * @returns * Info. */ constructor(property, attribute, mask, space2) { let index4 = -1; super(property, attribute); mark(this, "space", space2); if (typeof mask === "number") { while (++index4 < checks.length) { const check = checks[index4]; mark(this, checks[index4], (mask & types_exports[check]) === types_exports[check]); } } } }; DefinedInfo.prototype.defined = true; function mark(values2, key2, value) { if (value) { values2[key2] = value; } } // ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/create.js function create7(definition3) { const properties = {}; const normals = {}; for (const [property, value] of Object.entries(definition3.properties)) { const info = new DefinedInfo( property, definition3.transform(definition3.attributes || {}, property), value, definition3.space ); if (definition3.mustUseProperty && definition3.mustUseProperty.includes(property)) { info.mustUseProperty = true; } properties[property] = info; normals[normalize2(property)] = property; normals[normalize2(info.attribute)] = property; } return new Schema3(properties, normals, definition3.space); } // ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/aria.js var aria = create7({ properties: { ariaActiveDescendant: null, ariaAtomic: booleanish, ariaAutoComplete: null, ariaBusy: booleanish, ariaChecked: booleanish, ariaColCount: number, ariaColIndex: number, ariaColSpan: number, ariaControls: spaceSeparated, ariaCurrent: null, ariaDescribedBy: spaceSeparated, ariaDetails: null, ariaDisabled: booleanish, ariaDropEffect: spaceSeparated, ariaErrorMessage: null, ariaExpanded: booleanish, ariaFlowTo: spaceSeparated, ariaGrabbed: booleanish, ariaHasPopup: null, ariaHidden: booleanish, ariaInvalid: null, ariaKeyShortcuts: null, ariaLabel: null, ariaLabelledBy: spaceSeparated, ariaLevel: number, ariaLive: null, ariaModal: booleanish, ariaMultiLine: booleanish, ariaMultiSelectable: booleanish, ariaOrientation: null, ariaOwns: spaceSeparated, ariaPlaceholder: null, ariaPosInSet: number, ariaPressed: booleanish, ariaReadOnly: booleanish, ariaRelevant: null, ariaRequired: booleanish, ariaRoleDescription: spaceSeparated, ariaRowCount: number, ariaRowIndex: number, ariaRowSpan: number, ariaSelected: booleanish, ariaSetSize: number, ariaSort: null, ariaValueMax: number, ariaValueMin: number, ariaValueNow: number, ariaValueText: null, role: null }, transform(_2, property) { return property === "role" ? property : "aria-" + property.slice(4).toLowerCase(); } }); // ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/case-sensitive-transform.js function caseSensitiveTransform(attributes, attribute) { return attribute in attributes ? attributes[attribute] : attribute; } // ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/case-insensitive-transform.js function caseInsensitiveTransform(attributes, property) { return caseSensitiveTransform(attributes, property.toLowerCase()); } // ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/html.js var html = create7({ attributes: { acceptcharset: "accept-charset", classname: "class", htmlfor: "for", httpequiv: "http-equiv" }, mustUseProperty: ["checked", "multiple", "muted", "selected"], properties: { // Standard Properties. abbr: null, accept: commaSeparated, acceptCharset: spaceSeparated, accessKey: spaceSeparated, action: null, allow: null, allowFullScreen: boolean, allowPaymentRequest: boolean, allowUserMedia: boolean, alt: null, as: null, async: boolean, autoCapitalize: null, autoComplete: spaceSeparated, autoFocus: boolean, autoPlay: boolean, blocking: spaceSeparated, capture: null, charSet: null, checked: boolean, cite: null, className: spaceSeparated, cols: number, colSpan: null, content: null, contentEditable: booleanish, controls: boolean, controlsList: spaceSeparated, coords: number | commaSeparated, crossOrigin: null, data: null, dateTime: null, decoding: null, default: boolean, defer: boolean, dir: null, dirName: null, disabled: boolean, download: overloadedBoolean, draggable: booleanish, encType: null, enterKeyHint: null, fetchPriority: null, form: null, formAction: null, formEncType: null, formMethod: null, formNoValidate: boolean, formTarget: null, headers: spaceSeparated, height: number, hidden: overloadedBoolean, high: number, href: null, hrefLang: null, htmlFor: spaceSeparated, httpEquiv: spaceSeparated, id: null, imageSizes: null, imageSrcSet: null, inert: boolean, inputMode: null, integrity: null, is: null, isMap: boolean, itemId: null, itemProp: spaceSeparated, itemRef: spaceSeparated, itemScope: boolean, itemType: spaceSeparated, kind: null, label: null, lang: null, language: null, list: null, loading: null, loop: boolean, low: number, manifest: null, max: null, maxLength: number, media: null, method: null, min: null, minLength: number, multiple: boolean, muted: boolean, name: null, nonce: null, noModule: boolean, noValidate: boolean, onAbort: null, onAfterPrint: null, onAuxClick: null, onBeforeMatch: null, onBeforePrint: null, onBeforeToggle: null, onBeforeUnload: null, onBlur: null, onCancel: null, onCanPlay: null, onCanPlayThrough: null, onChange: null, onClick: null, onClose: null, onContextLost: null, onContextMenu: null, onContextRestored: null, onCopy: null, onCueChange: null, onCut: null, onDblClick: null, onDrag: null, onDragEnd: null, onDragEnter: null, onDragExit: null, onDragLeave: null, onDragOver: null, onDragStart: null, onDrop: null, onDurationChange: null, onEmptied: null, onEnded: null, onError: null, onFocus: null, onFormData: null, onHashChange: null, onInput: null, onInvalid: null, onKeyDown: null, onKeyPress: null, onKeyUp: null, onLanguageChange: null, onLoad: null, onLoadedData: null, onLoadedMetadata: null, onLoadEnd: null, onLoadStart: null, onMessage: null, onMessageError: null, onMouseDown: null, onMouseEnter: null, onMouseLeave: null, onMouseMove: null, onMouseOut: null, onMouseOver: null, onMouseUp: null, onOffline: null, onOnline: null, onPageHide: null, onPageShow: null, onPaste: null, onPause: null, onPlay: null, onPlaying: null, onPopState: null, onProgress: null, onRateChange: null, onRejectionHandled: null, onReset: null, onResize: null, onScroll: null, onScrollEnd: null, onSecurityPolicyViolation: null, onSeeked: null, onSeeking: null, onSelect: null, onSlotChange: null, onStalled: null, onStorage: null, onSubmit: null, onSuspend: null, onTimeUpdate: null, onToggle: null, onUnhandledRejection: null, onUnload: null, onVolumeChange: null, onWaiting: null, onWheel: null, open: boolean, optimum: number, pattern: null, ping: spaceSeparated, placeholder: null, playsInline: boolean, popover: null, popoverTarget: null, popoverTargetAction: null, poster: null, preload: null, readOnly: boolean, referrerPolicy: null, rel: spaceSeparated, required: boolean, reversed: boolean, rows: number, rowSpan: number, sandbox: spaceSeparated, scope: null, scoped: boolean, seamless: boolean, selected: boolean, shadowRootClonable: boolean, shadowRootDelegatesFocus: boolean, shadowRootMode: null, shape: null, size: number, sizes: null, slot: null, span: number, spellCheck: booleanish, src: null, srcDoc: null, srcLang: null, srcSet: null, start: number, step: null, style: null, tabIndex: number, target: null, title: null, translate: null, type: null, typeMustMatch: boolean, useMap: null, value: booleanish, width: number, wrap: null, writingSuggestions: null, // Legacy. // See: https://html.spec.whatwg.org/#other-elements,-attributes-and-apis align: null, // Several. Use CSS `text-align` instead, aLink: null, // ``. Use CSS `a:active {color}` instead archive: spaceSeparated, // ``. List of URIs to archives axis: null, // `` and ``. Use `scope` on `` background: null, // ``. Use CSS `background-image` instead bgColor: null, // `` and table elements. Use CSS `background-color` instead border: number, // ``. Use CSS `border-width` instead, borderColor: null, // `
`. Use CSS `border-color` instead, bottomMargin: number, // `` cellPadding: null, // `
` cellSpacing: null, // `
` char: null, // Several table elements. When `align=char`, sets the character to align on charOff: null, // Several table elements. When `char`, offsets the alignment classId: null, // `` clear: null, // `
`. Use CSS `clear` instead code: null, // `` codeBase: null, // `` codeType: null, // `` color: null, // `` and `
`. Use CSS instead compact: boolean, // Lists. Use CSS to reduce space between items instead declare: boolean, // `` event: null, // `