@rcarls/rc-textarea 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +204 -0
- package/README.md +67 -31
- package/dist/custom-elements.json +637 -41
- package/dist/folding-action-controller-sxM3IomW.js +91 -0
- package/dist/folding-action-controller-sxM3IomW.js.map +1 -0
- package/dist/{line-actions-controller-CB8U0WvH.js → line-actions-controller-DUdXQxMA.js} +912 -785
- package/dist/line-actions-controller-DUdXQxMA.js.map +1 -0
- package/dist/rc-textarea-define.js +2 -2
- package/dist/rc-textarea-folding.js +5 -0
- package/dist/rc-textarea-folding.js.map +1 -0
- package/dist/rc-textarea.js +1 -1
- package/dist/types/packages/rc-textarea/src/blots.d.ts +1 -1
- package/dist/types/packages/rc-textarea/src/decoration.d.ts +3 -2
- package/dist/types/packages/rc-textarea/src/document.d.ts +2 -1
- package/dist/types/packages/rc-textarea/src/folding-action-controller.d.ts +46 -0
- package/dist/types/packages/rc-textarea/src/folding.d.ts +2 -0
- package/dist/types/packages/rc-textarea/src/index.d.ts +7 -7
- package/dist/types/packages/rc-textarea/src/line-actions-controller.d.ts +5 -4
- package/dist/types/packages/rc-textarea/src/line-decorator.d.ts +1 -1
- package/dist/types/packages/rc-textarea/src/pattern-matcher.d.ts +1 -1
- package/dist/types/packages/rc-textarea/src/rc-textarea.d.ts +123 -20
- package/dist/types/packages/rc-textarea/src/selection.d.ts +2 -0
- package/dist/types/packages/rc-textarea/src/types.d.ts +52 -9
- package/package.json +9 -3
- package/dist/line-actions-controller-CB8U0WvH.js.map +0 -1
- package/dist/types/packages/rc-textarea/src/decoration.unit.test.d.ts +0 -1
- package/dist/types/packages/rc-textarea/src/line-decorator.test.d.ts +0 -1
- package/dist/types/packages/rc-textarea/src/pattern-matcher.unit.test.d.ts +0 -1
- package/dist/types/packages/rc-textarea/src/rc-textarea.test.d.ts +0 -0
- package/dist/types/packages/rc-textarea/src/test-helpers.d.ts +0 -20
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"line-actions-controller-DUdXQxMA.js","sources":["../../../node_modules/parchment/dist/parchment.js","../src/blots.ts","../src/document.ts","../src/selection.ts","../src/types.ts","../src/decoration.ts","../src/pattern-matcher.ts","../src/rc-textarea.styles.ts","../src/rc-textarea.ts","../src/line-decorator.ts","../src/line-actions-controller.ts"],"sourcesContent":["var Scope = /* @__PURE__ */ ((Scope2) => (Scope2[Scope2.TYPE = 3] = \"TYPE\", Scope2[Scope2.LEVEL = 12] = \"LEVEL\", Scope2[Scope2.ATTRIBUTE = 13] = \"ATTRIBUTE\", Scope2[Scope2.BLOT = 14] = \"BLOT\", Scope2[Scope2.INLINE = 7] = \"INLINE\", Scope2[Scope2.BLOCK = 11] = \"BLOCK\", Scope2[Scope2.BLOCK_BLOT = 10] = \"BLOCK_BLOT\", Scope2[Scope2.INLINE_BLOT = 6] = \"INLINE_BLOT\", Scope2[Scope2.BLOCK_ATTRIBUTE = 9] = \"BLOCK_ATTRIBUTE\", Scope2[Scope2.INLINE_ATTRIBUTE = 5] = \"INLINE_ATTRIBUTE\", Scope2[Scope2.ANY = 15] = \"ANY\", Scope2))(Scope || {});\nclass Attributor {\n constructor(attrName, keyName, options = {}) {\n this.attrName = attrName, this.keyName = keyName;\n const attributeBit = Scope.TYPE & Scope.ATTRIBUTE;\n this.scope = options.scope != null ? (\n // Ignore type bits, force attribute bit\n options.scope & Scope.LEVEL | attributeBit\n ) : Scope.ATTRIBUTE, options.whitelist != null && (this.whitelist = options.whitelist);\n }\n static keys(node) {\n return Array.from(node.attributes).map((item) => item.name);\n }\n add(node, value) {\n return this.canAdd(node, value) ? (node.setAttribute(this.keyName, value), !0) : !1;\n }\n canAdd(_node, value) {\n return this.whitelist == null ? !0 : typeof value == \"string\" ? this.whitelist.indexOf(value.replace(/[\"']/g, \"\")) > -1 : this.whitelist.indexOf(value) > -1;\n }\n remove(node) {\n node.removeAttribute(this.keyName);\n }\n value(node) {\n const value = node.getAttribute(this.keyName);\n return this.canAdd(node, value) && value ? value : \"\";\n }\n}\nclass ParchmentError extends Error {\n constructor(message) {\n message = \"[Parchment] \" + message, super(message), this.message = message, this.name = this.constructor.name;\n }\n}\nconst _Registry = class _Registry {\n constructor() {\n this.attributes = {}, this.classes = {}, this.tags = {}, this.types = {};\n }\n static find(node, bubble = !1) {\n if (node == null)\n return null;\n if (this.blots.has(node))\n return this.blots.get(node) || null;\n if (bubble) {\n let parentNode = null;\n try {\n parentNode = node.parentNode;\n } catch {\n return null;\n }\n return this.find(parentNode, bubble);\n }\n return null;\n }\n create(scroll, input, value) {\n const match2 = this.query(input);\n if (match2 == null)\n throw new ParchmentError(`Unable to create ${input} blot`);\n const blotClass = match2, node = (\n // @ts-expect-error Fix me later\n input instanceof Node || input.nodeType === Node.TEXT_NODE ? input : blotClass.create(value)\n ), blot = new blotClass(scroll, node, value);\n return _Registry.blots.set(blot.domNode, blot), blot;\n }\n find(node, bubble = !1) {\n return _Registry.find(node, bubble);\n }\n query(query, scope = Scope.ANY) {\n let match2;\n return typeof query == \"string\" ? match2 = this.types[query] || this.attributes[query] : query instanceof Text || query.nodeType === Node.TEXT_NODE ? match2 = this.types.text : typeof query == \"number\" ? query & Scope.LEVEL & Scope.BLOCK ? match2 = this.types.block : query & Scope.LEVEL & Scope.INLINE && (match2 = this.types.inline) : query instanceof Element && ((query.getAttribute(\"class\") || \"\").split(/\\s+/).some((name) => (match2 = this.classes[name], !!match2)), match2 = match2 || this.tags[query.tagName]), match2 == null ? null : \"scope\" in match2 && scope & Scope.LEVEL & match2.scope && scope & Scope.TYPE & match2.scope ? match2 : null;\n }\n register(...definitions) {\n return definitions.map((definition) => {\n const isBlot = \"blotName\" in definition, isAttr = \"attrName\" in definition;\n if (!isBlot && !isAttr)\n throw new ParchmentError(\"Invalid definition\");\n if (isBlot && definition.blotName === \"abstract\")\n throw new ParchmentError(\"Cannot register abstract class\");\n const key = isBlot ? definition.blotName : isAttr ? definition.attrName : void 0;\n return this.types[key] = definition, isAttr ? typeof definition.keyName == \"string\" && (this.attributes[definition.keyName] = definition) : isBlot && (definition.className && (this.classes[definition.className] = definition), definition.tagName && (Array.isArray(definition.tagName) ? definition.tagName = definition.tagName.map((tagName) => tagName.toUpperCase()) : definition.tagName = definition.tagName.toUpperCase(), (Array.isArray(definition.tagName) ? definition.tagName : [definition.tagName]).forEach((tag) => {\n (this.tags[tag] == null || definition.className == null) && (this.tags[tag] = definition);\n }))), definition;\n });\n }\n};\n_Registry.blots = /* @__PURE__ */ new WeakMap();\nlet Registry = _Registry;\nfunction match(node, prefix) {\n return (node.getAttribute(\"class\") || \"\").split(/\\s+/).filter((name) => name.indexOf(`${prefix}-`) === 0);\n}\nclass ClassAttributor extends Attributor {\n static keys(node) {\n return (node.getAttribute(\"class\") || \"\").split(/\\s+/).map((name) => name.split(\"-\").slice(0, -1).join(\"-\"));\n }\n add(node, value) {\n return this.canAdd(node, value) ? (this.remove(node), node.classList.add(`${this.keyName}-${value}`), !0) : !1;\n }\n remove(node) {\n match(node, this.keyName).forEach((name) => {\n node.classList.remove(name);\n }), node.classList.length === 0 && node.removeAttribute(\"class\");\n }\n value(node) {\n const value = (match(node, this.keyName)[0] || \"\").slice(this.keyName.length + 1);\n return this.canAdd(node, value) ? value : \"\";\n }\n}\nconst ClassAttributor$1 = ClassAttributor;\nfunction camelize(name) {\n const parts = name.split(\"-\"), rest = parts.slice(1).map((part) => part[0].toUpperCase() + part.slice(1)).join(\"\");\n return parts[0] + rest;\n}\nclass StyleAttributor extends Attributor {\n static keys(node) {\n return (node.getAttribute(\"style\") || \"\").split(\";\").map((value) => value.split(\":\")[0].trim());\n }\n add(node, value) {\n return this.canAdd(node, value) ? (node.style[camelize(this.keyName)] = value, !0) : !1;\n }\n remove(node) {\n node.style[camelize(this.keyName)] = \"\", node.getAttribute(\"style\") || node.removeAttribute(\"style\");\n }\n value(node) {\n const value = node.style[camelize(this.keyName)];\n return this.canAdd(node, value) ? value : \"\";\n }\n}\nconst StyleAttributor$1 = StyleAttributor;\nclass AttributorStore {\n constructor(domNode) {\n this.attributes = {}, this.domNode = domNode, this.build();\n }\n attribute(attribute, value) {\n value ? attribute.add(this.domNode, value) && (attribute.value(this.domNode) != null ? this.attributes[attribute.attrName] = attribute : delete this.attributes[attribute.attrName]) : (attribute.remove(this.domNode), delete this.attributes[attribute.attrName]);\n }\n build() {\n this.attributes = {};\n const blot = Registry.find(this.domNode);\n if (blot == null)\n return;\n const attributes = Attributor.keys(this.domNode), classes = ClassAttributor$1.keys(this.domNode), styles = StyleAttributor$1.keys(this.domNode);\n attributes.concat(classes).concat(styles).forEach((name) => {\n const attr = blot.scroll.query(name, Scope.ATTRIBUTE);\n attr instanceof Attributor && (this.attributes[attr.attrName] = attr);\n });\n }\n copy(target) {\n Object.keys(this.attributes).forEach((key) => {\n const value = this.attributes[key].value(this.domNode);\n target.format(key, value);\n });\n }\n move(target) {\n this.copy(target), Object.keys(this.attributes).forEach((key) => {\n this.attributes[key].remove(this.domNode);\n }), this.attributes = {};\n }\n values() {\n return Object.keys(this.attributes).reduce(\n (attributes, name) => (attributes[name] = this.attributes[name].value(this.domNode), attributes),\n {}\n );\n }\n}\nconst AttributorStore$1 = AttributorStore, _ShadowBlot = class _ShadowBlot {\n constructor(scroll, domNode) {\n this.scroll = scroll, this.domNode = domNode, Registry.blots.set(domNode, this), this.prev = null, this.next = null;\n }\n static create(rawValue) {\n if (this.tagName == null)\n throw new ParchmentError(\"Blot definition missing tagName\");\n let node, value;\n return Array.isArray(this.tagName) ? (typeof rawValue == \"string\" ? (value = rawValue.toUpperCase(), parseInt(value, 10).toString() === value && (value = parseInt(value, 10))) : typeof rawValue == \"number\" && (value = rawValue), typeof value == \"number\" ? node = document.createElement(this.tagName[value - 1]) : value && this.tagName.indexOf(value) > -1 ? node = document.createElement(value) : node = document.createElement(this.tagName[0])) : node = document.createElement(this.tagName), this.className && node.classList.add(this.className), node;\n }\n // Hack for accessing inherited static methods\n get statics() {\n return this.constructor;\n }\n attach() {\n }\n clone() {\n const domNode = this.domNode.cloneNode(!1);\n return this.scroll.create(domNode);\n }\n detach() {\n this.parent != null && this.parent.removeChild(this), Registry.blots.delete(this.domNode);\n }\n deleteAt(index, length) {\n this.isolate(index, length).remove();\n }\n formatAt(index, length, name, value) {\n const blot = this.isolate(index, length);\n if (this.scroll.query(name, Scope.BLOT) != null && value)\n blot.wrap(name, value);\n else if (this.scroll.query(name, Scope.ATTRIBUTE) != null) {\n const parent = this.scroll.create(this.statics.scope);\n blot.wrap(parent), parent.format(name, value);\n }\n }\n insertAt(index, value, def) {\n const blot = def == null ? this.scroll.create(\"text\", value) : this.scroll.create(value, def), ref = this.split(index);\n this.parent.insertBefore(blot, ref || void 0);\n }\n isolate(index, length) {\n const target = this.split(index);\n if (target == null)\n throw new Error(\"Attempt to isolate at end\");\n return target.split(length), target;\n }\n length() {\n return 1;\n }\n offset(root = this.parent) {\n return this.parent == null || this === root ? 0 : this.parent.children.offset(this) + this.parent.offset(root);\n }\n optimize(_context) {\n this.statics.requiredContainer && !(this.parent instanceof this.statics.requiredContainer) && this.wrap(this.statics.requiredContainer.blotName);\n }\n remove() {\n this.domNode.parentNode != null && this.domNode.parentNode.removeChild(this.domNode), this.detach();\n }\n replaceWith(name, value) {\n const replacement = typeof name == \"string\" ? this.scroll.create(name, value) : name;\n return this.parent != null && (this.parent.insertBefore(replacement, this.next || void 0), this.remove()), replacement;\n }\n split(index, _force) {\n return index === 0 ? this : this.next;\n }\n update(_mutations, _context) {\n }\n wrap(name, value) {\n const wrapper = typeof name == \"string\" ? this.scroll.create(name, value) : name;\n if (this.parent != null && this.parent.insertBefore(wrapper, this.next || void 0), typeof wrapper.appendChild != \"function\")\n throw new ParchmentError(`Cannot wrap ${name}`);\n return wrapper.appendChild(this), wrapper;\n }\n};\n_ShadowBlot.blotName = \"abstract\";\nlet ShadowBlot = _ShadowBlot;\nconst _LeafBlot = class _LeafBlot extends ShadowBlot {\n /**\n * Returns the value represented by domNode if it is this Blot's type\n * No checking that domNode can represent this Blot type is required so\n * applications needing it should check externally before calling.\n */\n static value(_domNode) {\n return !0;\n }\n /**\n * Given location represented by node and offset from DOM Selection Range,\n * return index to that location.\n */\n index(node, offset) {\n return this.domNode === node || this.domNode.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_CONTAINED_BY ? Math.min(offset, 1) : -1;\n }\n /**\n * Given index to location within blot, return node and offset representing\n * that location, consumable by DOM Selection Range\n */\n position(index, _inclusive) {\n let offset = Array.from(this.parent.domNode.childNodes).indexOf(this.domNode);\n return index > 0 && (offset += 1), [this.parent.domNode, offset];\n }\n /**\n * Return value represented by this blot\n * Should not change without interaction from API or\n * user change detectable by update()\n */\n value() {\n return {\n [this.statics.blotName]: this.statics.value(this.domNode) || !0\n };\n }\n};\n_LeafBlot.scope = Scope.INLINE_BLOT;\nlet LeafBlot = _LeafBlot;\nconst LeafBlot$1 = LeafBlot;\nclass LinkedList {\n constructor() {\n this.head = null, this.tail = null, this.length = 0;\n }\n append(...nodes) {\n if (this.insertBefore(nodes[0], null), nodes.length > 1) {\n const rest = nodes.slice(1);\n this.append(...rest);\n }\n }\n at(index) {\n const next = this.iterator();\n let cur = next();\n for (; cur && index > 0; )\n index -= 1, cur = next();\n return cur;\n }\n contains(node) {\n const next = this.iterator();\n let cur = next();\n for (; cur; ) {\n if (cur === node)\n return !0;\n cur = next();\n }\n return !1;\n }\n indexOf(node) {\n const next = this.iterator();\n let cur = next(), index = 0;\n for (; cur; ) {\n if (cur === node)\n return index;\n index += 1, cur = next();\n }\n return -1;\n }\n insertBefore(node, refNode) {\n node != null && (this.remove(node), node.next = refNode, refNode != null ? (node.prev = refNode.prev, refNode.prev != null && (refNode.prev.next = node), refNode.prev = node, refNode === this.head && (this.head = node)) : this.tail != null ? (this.tail.next = node, node.prev = this.tail, this.tail = node) : (node.prev = null, this.head = this.tail = node), this.length += 1);\n }\n offset(target) {\n let index = 0, cur = this.head;\n for (; cur != null; ) {\n if (cur === target)\n return index;\n index += cur.length(), cur = cur.next;\n }\n return -1;\n }\n remove(node) {\n this.contains(node) && (node.prev != null && (node.prev.next = node.next), node.next != null && (node.next.prev = node.prev), node === this.head && (this.head = node.next), node === this.tail && (this.tail = node.prev), this.length -= 1);\n }\n iterator(curNode = this.head) {\n return () => {\n const ret = curNode;\n return curNode != null && (curNode = curNode.next), ret;\n };\n }\n find(index, inclusive = !1) {\n const next = this.iterator();\n let cur = next();\n for (; cur; ) {\n const length = cur.length();\n if (index < length || inclusive && index === length && (cur.next == null || cur.next.length() !== 0))\n return [cur, index];\n index -= length, cur = next();\n }\n return [null, 0];\n }\n forEach(callback) {\n const next = this.iterator();\n let cur = next();\n for (; cur; )\n callback(cur), cur = next();\n }\n forEachAt(index, length, callback) {\n if (length <= 0)\n return;\n const [startNode, offset] = this.find(index);\n let curIndex = index - offset;\n const next = this.iterator(startNode);\n let cur = next();\n for (; cur && curIndex < index + length; ) {\n const curLength = cur.length();\n index > curIndex ? callback(\n cur,\n index - curIndex,\n Math.min(length, curIndex + curLength - index)\n ) : callback(cur, 0, Math.min(curLength, index + length - curIndex)), curIndex += curLength, cur = next();\n }\n }\n map(callback) {\n return this.reduce((memo, cur) => (memo.push(callback(cur)), memo), []);\n }\n reduce(callback, memo) {\n const next = this.iterator();\n let cur = next();\n for (; cur; )\n memo = callback(memo, cur), cur = next();\n return memo;\n }\n}\nfunction makeAttachedBlot(node, scroll) {\n const found = scroll.find(node);\n if (found)\n return found;\n try {\n return scroll.create(node);\n } catch {\n const blot = scroll.create(Scope.INLINE);\n return Array.from(node.childNodes).forEach((child) => {\n blot.domNode.appendChild(child);\n }), node.parentNode && node.parentNode.replaceChild(blot.domNode, node), blot.attach(), blot;\n }\n}\nconst _ParentBlot = class _ParentBlot extends ShadowBlot {\n constructor(scroll, domNode) {\n super(scroll, domNode), this.uiNode = null, this.build();\n }\n appendChild(other) {\n this.insertBefore(other);\n }\n attach() {\n super.attach(), this.children.forEach((child) => {\n child.attach();\n });\n }\n attachUI(node) {\n this.uiNode != null && this.uiNode.remove(), this.uiNode = node, _ParentBlot.uiClass && this.uiNode.classList.add(_ParentBlot.uiClass), this.uiNode.setAttribute(\"contenteditable\", \"false\"), this.domNode.insertBefore(this.uiNode, this.domNode.firstChild);\n }\n /**\n * Called during construction, should fill its own children LinkedList.\n */\n build() {\n this.children = new LinkedList(), Array.from(this.domNode.childNodes).filter((node) => node !== this.uiNode).reverse().forEach((node) => {\n try {\n const child = makeAttachedBlot(node, this.scroll);\n this.insertBefore(child, this.children.head || void 0);\n } catch (err) {\n if (err instanceof ParchmentError)\n return;\n throw err;\n }\n });\n }\n deleteAt(index, length) {\n if (index === 0 && length === this.length())\n return this.remove();\n this.children.forEachAt(index, length, (child, offset, childLength) => {\n child.deleteAt(offset, childLength);\n });\n }\n descendant(criteria, index = 0) {\n const [child, offset] = this.children.find(index);\n return criteria.blotName == null && criteria(child) || criteria.blotName != null && child instanceof criteria ? [child, offset] : child instanceof _ParentBlot ? child.descendant(criteria, offset) : [null, -1];\n }\n descendants(criteria, index = 0, length = Number.MAX_VALUE) {\n let descendants = [], lengthLeft = length;\n return this.children.forEachAt(\n index,\n length,\n (child, childIndex, childLength) => {\n (criteria.blotName == null && criteria(child) || criteria.blotName != null && child instanceof criteria) && descendants.push(child), child instanceof _ParentBlot && (descendants = descendants.concat(\n child.descendants(criteria, childIndex, lengthLeft)\n )), lengthLeft -= childLength;\n }\n ), descendants;\n }\n detach() {\n this.children.forEach((child) => {\n child.detach();\n }), super.detach();\n }\n enforceAllowedChildren() {\n let done = !1;\n this.children.forEach((child) => {\n done || this.statics.allowedChildren.some(\n (def) => child instanceof def\n ) || (child.statics.scope === Scope.BLOCK_BLOT ? (child.next != null && this.splitAfter(child), child.prev != null && this.splitAfter(child.prev), child.parent.unwrap(), done = !0) : child instanceof _ParentBlot ? child.unwrap() : child.remove());\n });\n }\n formatAt(index, length, name, value) {\n this.children.forEachAt(index, length, (child, offset, childLength) => {\n child.formatAt(offset, childLength, name, value);\n });\n }\n insertAt(index, value, def) {\n const [child, offset] = this.children.find(index);\n if (child)\n child.insertAt(offset, value, def);\n else {\n const blot = def == null ? this.scroll.create(\"text\", value) : this.scroll.create(value, def);\n this.appendChild(blot);\n }\n }\n insertBefore(childBlot, refBlot) {\n childBlot.parent != null && childBlot.parent.children.remove(childBlot);\n let refDomNode = null;\n this.children.insertBefore(childBlot, refBlot || null), childBlot.parent = this, refBlot != null && (refDomNode = refBlot.domNode), (this.domNode.parentNode !== childBlot.domNode || this.domNode.nextSibling !== refDomNode) && this.domNode.insertBefore(childBlot.domNode, refDomNode), childBlot.attach();\n }\n length() {\n return this.children.reduce((memo, child) => memo + child.length(), 0);\n }\n moveChildren(targetParent, refNode) {\n this.children.forEach((child) => {\n targetParent.insertBefore(child, refNode);\n });\n }\n optimize(context) {\n if (super.optimize(context), this.enforceAllowedChildren(), this.uiNode != null && this.uiNode !== this.domNode.firstChild && this.domNode.insertBefore(this.uiNode, this.domNode.firstChild), this.children.length === 0)\n if (this.statics.defaultChild != null) {\n const child = this.scroll.create(this.statics.defaultChild.blotName);\n this.appendChild(child);\n } else\n this.remove();\n }\n path(index, inclusive = !1) {\n const [child, offset] = this.children.find(index, inclusive), position = [[this, index]];\n return child instanceof _ParentBlot ? position.concat(child.path(offset, inclusive)) : (child != null && position.push([child, offset]), position);\n }\n removeChild(child) {\n this.children.remove(child);\n }\n replaceWith(name, value) {\n const replacement = typeof name == \"string\" ? this.scroll.create(name, value) : name;\n return replacement instanceof _ParentBlot && this.moveChildren(replacement), super.replaceWith(replacement);\n }\n split(index, force = !1) {\n if (!force) {\n if (index === 0)\n return this;\n if (index === this.length())\n return this.next;\n }\n const after = this.clone();\n return this.parent && this.parent.insertBefore(after, this.next || void 0), this.children.forEachAt(index, this.length(), (child, offset, _length) => {\n const split = child.split(offset, force);\n split != null && after.appendChild(split);\n }), after;\n }\n splitAfter(child) {\n const after = this.clone();\n for (; child.next != null; )\n after.appendChild(child.next);\n return this.parent && this.parent.insertBefore(after, this.next || void 0), after;\n }\n unwrap() {\n this.parent && this.moveChildren(this.parent, this.next || void 0), this.remove();\n }\n update(mutations, _context) {\n const addedNodes = [], removedNodes = [];\n mutations.forEach((mutation) => {\n mutation.target === this.domNode && mutation.type === \"childList\" && (addedNodes.push(...mutation.addedNodes), removedNodes.push(...mutation.removedNodes));\n }), removedNodes.forEach((node) => {\n if (node.parentNode != null && // @ts-expect-error Fix me later\n node.tagName !== \"IFRAME\" && document.body.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_CONTAINED_BY)\n return;\n const blot = this.scroll.find(node);\n blot != null && (blot.domNode.parentNode == null || blot.domNode.parentNode === this.domNode) && blot.detach();\n }), addedNodes.filter((node) => node.parentNode === this.domNode && node !== this.uiNode).sort((a, b) => a === b ? 0 : a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? 1 : -1).forEach((node) => {\n let refBlot = null;\n node.nextSibling != null && (refBlot = this.scroll.find(node.nextSibling));\n const blot = makeAttachedBlot(node, this.scroll);\n (blot.next !== refBlot || blot.next == null) && (blot.parent != null && blot.parent.removeChild(this), this.insertBefore(blot, refBlot || void 0));\n }), this.enforceAllowedChildren();\n }\n};\n_ParentBlot.uiClass = \"\";\nlet ParentBlot = _ParentBlot;\nconst ParentBlot$1 = ParentBlot;\nfunction isEqual(obj1, obj2) {\n if (Object.keys(obj1).length !== Object.keys(obj2).length)\n return !1;\n for (const prop in obj1)\n if (obj1[prop] !== obj2[prop])\n return !1;\n return !0;\n}\nconst _InlineBlot = class _InlineBlot extends ParentBlot$1 {\n static create(value) {\n return super.create(value);\n }\n static formats(domNode, scroll) {\n const match2 = scroll.query(_InlineBlot.blotName);\n if (!(match2 != null && domNode.tagName === match2.tagName)) {\n if (typeof this.tagName == \"string\")\n return !0;\n if (Array.isArray(this.tagName))\n return domNode.tagName.toLowerCase();\n }\n }\n constructor(scroll, domNode) {\n super(scroll, domNode), this.attributes = new AttributorStore$1(this.domNode);\n }\n format(name, value) {\n if (name === this.statics.blotName && !value)\n this.children.forEach((child) => {\n child instanceof _InlineBlot || (child = child.wrap(_InlineBlot.blotName, !0)), this.attributes.copy(child);\n }), this.unwrap();\n else {\n const format = this.scroll.query(name, Scope.INLINE);\n if (format == null)\n return;\n format instanceof Attributor ? this.attributes.attribute(format, value) : value && (name !== this.statics.blotName || this.formats()[name] !== value) && this.replaceWith(name, value);\n }\n }\n formats() {\n const formats = this.attributes.values(), format = this.statics.formats(this.domNode, this.scroll);\n return format != null && (formats[this.statics.blotName] = format), formats;\n }\n formatAt(index, length, name, value) {\n this.formats()[name] != null || this.scroll.query(name, Scope.ATTRIBUTE) ? this.isolate(index, length).format(name, value) : super.formatAt(index, length, name, value);\n }\n optimize(context) {\n super.optimize(context);\n const formats = this.formats();\n if (Object.keys(formats).length === 0)\n return this.unwrap();\n const next = this.next;\n next instanceof _InlineBlot && next.prev === this && isEqual(formats, next.formats()) && (next.moveChildren(this), next.remove());\n }\n replaceWith(name, value) {\n const replacement = super.replaceWith(name, value);\n return this.attributes.copy(replacement), replacement;\n }\n update(mutations, context) {\n super.update(mutations, context), mutations.some(\n (mutation) => mutation.target === this.domNode && mutation.type === \"attributes\"\n ) && this.attributes.build();\n }\n wrap(name, value) {\n const wrapper = super.wrap(name, value);\n return wrapper instanceof _InlineBlot && this.attributes.move(wrapper), wrapper;\n }\n};\n_InlineBlot.allowedChildren = [_InlineBlot, LeafBlot$1], _InlineBlot.blotName = \"inline\", _InlineBlot.scope = Scope.INLINE_BLOT, _InlineBlot.tagName = \"SPAN\";\nlet InlineBlot = _InlineBlot;\nconst InlineBlot$1 = InlineBlot, _BlockBlot = class _BlockBlot extends ParentBlot$1 {\n static create(value) {\n return super.create(value);\n }\n static formats(domNode, scroll) {\n const match2 = scroll.query(_BlockBlot.blotName);\n if (!(match2 != null && domNode.tagName === match2.tagName)) {\n if (typeof this.tagName == \"string\")\n return !0;\n if (Array.isArray(this.tagName))\n return domNode.tagName.toLowerCase();\n }\n }\n constructor(scroll, domNode) {\n super(scroll, domNode), this.attributes = new AttributorStore$1(this.domNode);\n }\n format(name, value) {\n const format = this.scroll.query(name, Scope.BLOCK);\n format != null && (format instanceof Attributor ? this.attributes.attribute(format, value) : name === this.statics.blotName && !value ? this.replaceWith(_BlockBlot.blotName) : value && (name !== this.statics.blotName || this.formats()[name] !== value) && this.replaceWith(name, value));\n }\n formats() {\n const formats = this.attributes.values(), format = this.statics.formats(this.domNode, this.scroll);\n return format != null && (formats[this.statics.blotName] = format), formats;\n }\n formatAt(index, length, name, value) {\n this.scroll.query(name, Scope.BLOCK) != null ? this.format(name, value) : super.formatAt(index, length, name, value);\n }\n insertAt(index, value, def) {\n if (def == null || this.scroll.query(value, Scope.INLINE) != null)\n super.insertAt(index, value, def);\n else {\n const after = this.split(index);\n if (after != null) {\n const blot = this.scroll.create(value, def);\n after.parent.insertBefore(blot, after);\n } else\n throw new Error(\"Attempt to insertAt after block boundaries\");\n }\n }\n replaceWith(name, value) {\n const replacement = super.replaceWith(name, value);\n return this.attributes.copy(replacement), replacement;\n }\n update(mutations, context) {\n super.update(mutations, context), mutations.some(\n (mutation) => mutation.target === this.domNode && mutation.type === \"attributes\"\n ) && this.attributes.build();\n }\n};\n_BlockBlot.blotName = \"block\", _BlockBlot.scope = Scope.BLOCK_BLOT, _BlockBlot.tagName = \"P\", _BlockBlot.allowedChildren = [\n InlineBlot$1,\n _BlockBlot,\n LeafBlot$1\n];\nlet BlockBlot = _BlockBlot;\nconst BlockBlot$1 = BlockBlot, _ContainerBlot = class _ContainerBlot extends ParentBlot$1 {\n checkMerge() {\n return this.next !== null && this.next.statics.blotName === this.statics.blotName;\n }\n deleteAt(index, length) {\n super.deleteAt(index, length), this.enforceAllowedChildren();\n }\n formatAt(index, length, name, value) {\n super.formatAt(index, length, name, value), this.enforceAllowedChildren();\n }\n insertAt(index, value, def) {\n super.insertAt(index, value, def), this.enforceAllowedChildren();\n }\n optimize(context) {\n super.optimize(context), this.children.length > 0 && this.next != null && this.checkMerge() && (this.next.moveChildren(this), this.next.remove());\n }\n};\n_ContainerBlot.blotName = \"container\", _ContainerBlot.scope = Scope.BLOCK_BLOT;\nlet ContainerBlot = _ContainerBlot;\nconst ContainerBlot$1 = ContainerBlot;\nclass EmbedBlot extends LeafBlot$1 {\n static formats(_domNode, _scroll) {\n }\n format(name, value) {\n super.formatAt(0, this.length(), name, value);\n }\n formatAt(index, length, name, value) {\n index === 0 && length === this.length() ? this.format(name, value) : super.formatAt(index, length, name, value);\n }\n formats() {\n return this.statics.formats(this.domNode, this.scroll);\n }\n}\nconst EmbedBlot$1 = EmbedBlot, OBSERVER_CONFIG = {\n attributes: !0,\n characterData: !0,\n characterDataOldValue: !0,\n childList: !0,\n subtree: !0\n}, MAX_OPTIMIZE_ITERATIONS = 100, _ScrollBlot = class _ScrollBlot extends ParentBlot$1 {\n constructor(registry, node) {\n super(null, node), this.registry = registry, this.scroll = this, this.build(), this.observer = new MutationObserver((mutations) => {\n this.update(mutations);\n }), this.observer.observe(this.domNode, OBSERVER_CONFIG), this.attach();\n }\n create(input, value) {\n return this.registry.create(this, input, value);\n }\n find(node, bubble = !1) {\n const blot = this.registry.find(node, bubble);\n return blot ? blot.scroll === this ? blot : bubble ? this.find(blot.scroll.domNode.parentNode, !0) : null : null;\n }\n query(query, scope = Scope.ANY) {\n return this.registry.query(query, scope);\n }\n register(...definitions) {\n return this.registry.register(...definitions);\n }\n build() {\n this.scroll != null && super.build();\n }\n detach() {\n super.detach(), this.observer.disconnect();\n }\n deleteAt(index, length) {\n this.update(), index === 0 && length === this.length() ? this.children.forEach((child) => {\n child.remove();\n }) : super.deleteAt(index, length);\n }\n formatAt(index, length, name, value) {\n this.update(), super.formatAt(index, length, name, value);\n }\n insertAt(index, value, def) {\n this.update(), super.insertAt(index, value, def);\n }\n optimize(mutations = [], context = {}) {\n super.optimize(context);\n const mutationsMap = context.mutationsMap || /* @__PURE__ */ new WeakMap();\n let records = Array.from(this.observer.takeRecords());\n for (; records.length > 0; )\n mutations.push(records.pop());\n const mark = (blot, markParent = !0) => {\n blot == null || blot === this || blot.domNode.parentNode != null && (mutationsMap.has(blot.domNode) || mutationsMap.set(blot.domNode, []), markParent && mark(blot.parent));\n }, optimize = (blot) => {\n mutationsMap.has(blot.domNode) && (blot instanceof ParentBlot$1 && blot.children.forEach(optimize), mutationsMap.delete(blot.domNode), blot.optimize(context));\n };\n let remaining = mutations;\n for (let i = 0; remaining.length > 0; i += 1) {\n if (i >= MAX_OPTIMIZE_ITERATIONS)\n throw new Error(\"[Parchment] Maximum optimize iterations reached\");\n for (remaining.forEach((mutation) => {\n const blot = this.find(mutation.target, !0);\n blot != null && (blot.domNode === mutation.target && (mutation.type === \"childList\" ? (mark(this.find(mutation.previousSibling, !1)), Array.from(mutation.addedNodes).forEach((node) => {\n const child = this.find(node, !1);\n mark(child, !1), child instanceof ParentBlot$1 && child.children.forEach((grandChild) => {\n mark(grandChild, !1);\n });\n })) : mutation.type === \"attributes\" && mark(blot.prev)), mark(blot));\n }), this.children.forEach(optimize), remaining = Array.from(this.observer.takeRecords()), records = remaining.slice(); records.length > 0; )\n mutations.push(records.pop());\n }\n }\n update(mutations, context = {}) {\n mutations = mutations || this.observer.takeRecords();\n const mutationsMap = /* @__PURE__ */ new WeakMap();\n mutations.map((mutation) => {\n const blot = this.find(mutation.target, !0);\n return blot == null ? null : mutationsMap.has(blot.domNode) ? (mutationsMap.get(blot.domNode).push(mutation), null) : (mutationsMap.set(blot.domNode, [mutation]), blot);\n }).forEach((blot) => {\n blot != null && blot !== this && mutationsMap.has(blot.domNode) && blot.update(mutationsMap.get(blot.domNode) || [], context);\n }), context.mutationsMap = mutationsMap, mutationsMap.has(this.domNode) && super.update(mutationsMap.get(this.domNode), context), this.optimize(mutations, context);\n }\n};\n_ScrollBlot.blotName = \"scroll\", _ScrollBlot.defaultChild = BlockBlot$1, _ScrollBlot.allowedChildren = [BlockBlot$1, ContainerBlot$1], _ScrollBlot.scope = Scope.BLOCK_BLOT, _ScrollBlot.tagName = \"DIV\";\nlet ScrollBlot = _ScrollBlot;\nconst ScrollBlot$1 = ScrollBlot, _TextBlot = class _TextBlot extends LeafBlot$1 {\n static create(value) {\n return document.createTextNode(value);\n }\n static value(domNode) {\n return domNode.data;\n }\n constructor(scroll, node) {\n super(scroll, node), this.text = this.statics.value(this.domNode);\n }\n deleteAt(index, length) {\n this.domNode.data = this.text = this.text.slice(0, index) + this.text.slice(index + length);\n }\n index(node, offset) {\n return this.domNode === node ? offset : -1;\n }\n insertAt(index, value, def) {\n def == null ? (this.text = this.text.slice(0, index) + value + this.text.slice(index), this.domNode.data = this.text) : super.insertAt(index, value, def);\n }\n length() {\n return this.text.length;\n }\n optimize(context) {\n super.optimize(context), this.text = this.statics.value(this.domNode), this.text.length === 0 ? this.remove() : this.next instanceof _TextBlot && this.next.prev === this && (this.insertAt(this.length(), this.next.value()), this.next.remove());\n }\n position(index, _inclusive = !1) {\n return [this.domNode, index];\n }\n split(index, force = !1) {\n if (!force) {\n if (index === 0)\n return this;\n if (index === this.length())\n return this.next;\n }\n const after = this.scroll.create(this.domNode.splitText(index));\n return this.parent.insertBefore(after, this.next || void 0), this.text = this.statics.value(this.domNode), after;\n }\n update(mutations, _context) {\n mutations.some((mutation) => mutation.type === \"characterData\" && mutation.target === this.domNode) && (this.text = this.statics.value(this.domNode));\n }\n value() {\n return this.text;\n }\n};\n_TextBlot.blotName = \"text\", _TextBlot.scope = Scope.INLINE_BLOT;\nlet TextBlot = _TextBlot;\nconst TextBlot$1 = TextBlot;\nexport {\n Attributor,\n AttributorStore$1 as AttributorStore,\n BlockBlot$1 as BlockBlot,\n ClassAttributor$1 as ClassAttributor,\n ContainerBlot$1 as ContainerBlot,\n EmbedBlot$1 as EmbedBlot,\n InlineBlot$1 as InlineBlot,\n LeafBlot$1 as LeafBlot,\n ParentBlot$1 as ParentBlot,\n Registry,\n Scope,\n ScrollBlot$1 as ScrollBlot,\n StyleAttributor$1 as StyleAttributor,\n TextBlot$1 as TextBlot\n};\n//# sourceMappingURL=parchment.js.map\n","/**\n * Parchment blot definitions for rc-textarea.\n *\n * Uses named imports from parchment (BlockBlot, InlineBlot, EmbedBlot, ScrollBlot).\n * Parchment's MutationObserver integration is suppressed — DOM updates are\n * managed entirely by RCDocument.build() on each render frame.\n *\n * @see https://github.com/quilljs/parchment\n */\nimport { Registry, ScrollBlot, BlockBlot, InlineBlot, EmbedBlot } from 'parchment';\n\nimport type { MarkDecoration } from './types.js';\n\nexport { Registry };\n\nexport class RCScrollBlot extends ScrollBlot {\n static override blotName = 'rc-scroll';\n\n constructor(registry: Registry, domNode: HTMLDivElement) {\n super(registry, domNode);\n\n // Disconnect MutationObserver immediately — we manage all DOM updates ourselves\n this.observer.disconnect();\n }\n\n // Suppress Parchment's automatic DOM reconciliation\n override update(_mutations: MutationRecord[], _context: Record<string, unknown>): void {}\n\n // Match ScrollBlot's two optimize overloads\n override optimize(context: { [key: string]: unknown }): void;\n override optimize(mutations: MutationRecord[], context: { [key: string]: unknown }): void;\n override optimize(\n _contextOrMutations?: MutationRecord[] | { [key: string]: unknown },\n _context?: { [key: string]: unknown },\n ): void {}\n}\n\nexport class RCBlockBlot extends BlockBlot {\n static override blotName = 'rc-block';\n static override tagName = 'DIV';\n static override className = 'line';\n}\n\ntype InlineFormats = Pick<\n MarkDecoration,\n 'className' | 'bold' | 'italic' | 'color' | 'background' | 'underline' | 'underlineColor'\n>;\n\nexport class RCInlineBlot extends InlineBlot {\n static override blotName = 'rc-inline';\n static override tagName = 'SPAN';\n static override className = 'mark';\n\n static override create(formats?: InlineFormats): HTMLElement {\n const $el = super.create() as HTMLSpanElement;\n\n if (formats) {\n applyInlineFormats($el, formats);\n }\n\n return $el;\n }\n}\n\n/**\n * Apply `MarkDecoration` style properties to a `.mark` span element as\n * inline styles and extra CSS classes. Called by `RCInlineBlot.create()` and\n * by external code that needs to style a span to match a decoration.\n */\nexport function applyInlineFormats($el: HTMLSpanElement, formats: InlineFormats): void {\n if (formats.className) {\n for (const cls of formats.className.split(/\\s+/).filter(Boolean)) {\n $el.classList.add(cls);\n }\n }\n\n if (formats.bold) {\n $el.style.fontWeight = 'bold';\n }\n\n if (formats.italic) {\n $el.style.fontStyle = 'italic';\n }\n\n if (formats.color) {\n $el.style.color = formats.color;\n }\n\n if (formats.background) {\n $el.style.backgroundColor = formats.background;\n }\n\n if (formats.underline) {\n $el.style.textDecoration = `${formats.underline} underline`;\n\n if (formats.underlineColor) {\n $el.style.textDecorationColor = formats.underlineColor;\n }\n }\n}\n\nexport class RCWidgetBlot extends EmbedBlot {\n static override blotName = 'rc-widget';\n static override tagName = 'SPAN';\n static override className = 'widget';\n\n static override create(): HTMLElement {\n const $el = super.create() as HTMLSpanElement;\n\n $el.contentEditable = 'false';\n $el.setAttribute('aria-hidden', 'true');\n\n return $el;\n }\n}\n\nexport function createRegistry(): Registry {\n const registry = new Registry();\n\n // Register content blots — ScrollBlot is the root, not registered like others\n registry.register(RCBlockBlot, RCInlineBlot, RCWidgetBlot);\n\n return registry;\n}\n","/**\n * RCDocument — manages the Parchment-backed contenteditable editor DOM.\n *\n * Maintains a RCScrollBlot as document root (wrapping the #editor div).\n * build() tears down the current tree and reconstructs it from plain text +\n * a flat array of decorations. DOM is built directly using the blots'\n * static create() methods for efficiency.\n *\n * @see {@link https://github.com/quilljs/parchment Parchment on GitHub}\n */\nimport { RCScrollBlot, RCBlockBlot, RCInlineBlot, RCWidgetBlot, createRegistry } from './blots.js';\nimport type { Decoration, MarkDecoration, LineDecoration, WidgetDecoration } from './types.js';\n\n/**\n * Builds the child DOM of a line element given the line text, absolute line\n * start offset, and all decorations that affect this line.\n */\nfunction buildLineContent(\n $line: HTMLElement,\n lineText: string,\n lineStart: number,\n markDecorations: MarkDecoration[],\n widgetDecorations: WidgetDecoration[],\n): void {\n if (lineText.length === 0) {\n // Empty line needs a <br> so contenteditable allows cursor placement\n $line.appendChild(document.createElement('br'));\n\n for (const widget of widgetDecorations) {\n $line.appendChild(createWidget(widget));\n }\n\n return;\n }\n\n // Collect segment boundary points from all mark decoration edges\n const boundarySet = new Set<number>([0, lineText.length]);\n\n for (const decoration of markDecorations) {\n boundarySet.add(Math.max(0, decoration.from - lineStart));\n boundarySet.add(Math.min(lineText.length, decoration.to - lineStart));\n }\n\n for (const decoration of widgetDecorations) {\n const localOffset = decoration.offset - lineStart;\n\n if (localOffset >= 0 && localOffset <= lineText.length) {\n boundarySet.add(localOffset);\n }\n }\n\n const boundaries = [...boundarySet].sort((a, b) => a - b);\n\n // A line start has no preceding segment to append 'after' widgets from.\n for (const widget of widgetDecorations) {\n if (widget.offset === lineStart && widget.side === 'after') {\n $line.appendChild(createWidget(widget));\n }\n }\n\n for (const [i, segmentStart] of boundaries.entries()) {\n const segmentEnd = boundaries[i + 1];\n\n if (segmentEnd === undefined) {\n break;\n }\n\n // Insert widgets whose position falls at segmentStart ('before' side)\n for (const widget of widgetDecorations) {\n const localOffset = widget.offset - lineStart;\n\n if (localOffset === segmentStart && (widget.side ?? 'before') === 'before') {\n $line.appendChild(createWidget(widget));\n }\n }\n\n const segment = lineText.slice(segmentStart, segmentEnd);\n\n if (!segment) {\n continue;\n }\n\n // Find the innermost (smallest) mark decoration fully covering [segmentStart, segmentEnd)\n let bestDecoration: MarkDecoration | undefined;\n let bestSize = Infinity;\n\n for (const decoration of markDecorations) {\n const localFrom = decoration.from - lineStart;\n const localTo = decoration.to - lineStart;\n\n if (localFrom <= segmentStart && localTo >= segmentEnd) {\n const size = localTo - localFrom;\n\n if (size < bestSize) {\n bestSize = size;\n bestDecoration = decoration;\n }\n }\n }\n\n if (bestDecoration) {\n const $span = RCInlineBlot.create(bestDecoration) as HTMLSpanElement;\n\n if (bestDecoration.attributes) {\n for (const [attrName, attrValue] of Object.entries(bestDecoration.attributes)) {\n $span.setAttribute(attrName, attrValue);\n }\n }\n\n $span.appendChild(document.createTextNode(segment));\n\n $line.appendChild($span);\n } else {\n $line.appendChild(document.createTextNode(segment));\n }\n\n // Insert 'after' widgets at segEnd\n for (const widget of widgetDecorations) {\n const localOffset = widget.offset - lineStart;\n\n if (localOffset === segmentEnd && widget.side === 'after') {\n $line.appendChild(createWidget(widget));\n }\n }\n }\n\n // Widgets at very end of line (default 'before' side)\n for (const widget of widgetDecorations) {\n const localOffset = widget.offset - lineStart;\n\n if (localOffset === lineText.length && (widget.side ?? 'before') === 'before') {\n $line.appendChild(createWidget(widget));\n }\n }\n}\n\n/** Create the `.widget` span wrapper for a `WidgetDecoration`. */\nfunction createWidget(decoration: WidgetDecoration): HTMLSpanElement {\n const $span = RCWidgetBlot.create() as HTMLSpanElement;\n\n if (decoration.accessible) {\n $span.removeAttribute('aria-hidden');\n }\n\n if (decoration.layout) {\n $span.classList.add(`widget--${decoration.layout}`);\n }\n\n $span.appendChild(decoration.create());\n\n return $span;\n}\n\nexport class RCDocument {\n private readonly scroll: RCScrollBlot;\n\n private readonly lineSignatures = new WeakMap<HTMLElement, string>();\n\n constructor($documentRoot: HTMLDivElement) {\n const registry = createRegistry();\n\n this.scroll = new RCScrollBlot(registry, $documentRoot);\n }\n\n /**\n * Rebuild the document tree.\n *\n * Reuses existing `.line` elements in place to preserve DOM identity\n * across renders (fixes DevTools node tracking and mouse gesture continuity).\n */\n build(value: string, decorations: Decoration[]): void {\n const $documentRoot = this.scroll.domNode as HTMLElement;\n const lines = value.split('\\n');\n\n // Snapshot existing line elements for reuse\n const $lines = Array.from($documentRoot.querySelectorAll<HTMLElement>('.line'));\n\n // Index decorations by type for fast per-line lookup\n const lineDecorationsMap = new Map<number, LineDecoration[]>();\n const markDecorations: MarkDecoration[] = [];\n const widgetDecorations: WidgetDecoration[] = [];\n const foldedLines = new Set<number>();\n\n for (const decoration of decorations) {\n if (decoration.type === 'line') {\n const lineDecorations = lineDecorationsMap.get(decoration.line) ?? [];\n\n lineDecorations.push(decoration);\n\n lineDecorationsMap.set(decoration.line, lineDecorations);\n } else if (decoration.type === 'mark') {\n markDecorations.push(decoration);\n } else if (decoration.type === 'widget') {\n widgetDecorations.push(decoration);\n } else {\n for (\n let line = Math.max(2, decoration.fromLine);\n line <= decoration.toLine && line <= lines.length;\n line++\n ) {\n foldedLines.add(line);\n }\n }\n }\n\n markDecorations.sort((a, b) => a.from - b.from || a.to - b.to);\n widgetDecorations.sort((a, b) => a.offset - b.offset);\n\n // Absolute character offset of the first character on the current line\n let lineStartOffset = 0;\n\n for (const [i, lineText] of lines.entries()) {\n const lineNum = i + 1;\n const lineStart = lineStartOffset;\n const lineEnd = lineStart + lineText.length;\n const lineDecorations = lineDecorationsMap.get(lineNum) ?? [];\n const marks = markDecorations.filter((d) => d.from < lineEnd && d.to > lineStart);\n const widgets = widgetDecorations.filter((d) => d.offset >= lineStart && d.offset <= lineEnd);\n const folded = foldedLines.has(lineNum);\n // Only opt-in keyed widgets promise stable content between plugin passes.\n const signature =\n widgets.length > 0 && widgets.every((widget) => widget.key)\n ? JSON.stringify([\n lineText,\n folded,\n [...lineDecorations, ...marks, ...widgets].map(({ id: _id, ...decoration }) =>\n decoration.type === 'line'\n ? { ...decoration, gutterContent: undefined }\n : decoration,\n ),\n ])\n : undefined;\n\n const $existing = $lines[i];\n\n if (\n $existing &&\n signature &&\n this.lineSignatures.get($existing) === signature &&\n getLineText($existing) === lineText\n ) {\n lineStartOffset += lineText.length + 1;\n\n continue;\n }\n\n // Reuse an existing line element when available, otherwise create a new one.\n let $block: HTMLElement;\n\n if ($existing) {\n $block = $existing;\n\n // Remove all attributes so stale class names, data-*, and title don't bleed through\n for (const name of $block.getAttributeNames()) {\n $block.removeAttribute(name);\n }\n\n $block.className = 'line';\n\n // Clear children\n while ($block.firstChild) {\n $block.removeChild($block.firstChild);\n }\n } else {\n $block = RCBlockBlot.create() as HTMLElement;\n\n $documentRoot.appendChild($block);\n }\n\n // Apply line decorations\n if (folded) {\n $block.hidden = true;\n }\n\n for (const decoration of lineDecorations) {\n if (decoration.className) {\n for (const cls of decoration.className.split(/\\s+/).filter(Boolean)) {\n $block.classList.add(cls);\n }\n }\n\n if (decoration.attributes) {\n for (const [attrName, attrValue] of Object.entries(decoration.attributes)) {\n $block.setAttribute(attrName, attrValue);\n }\n }\n }\n\n // Narrow decorations to those overlapping this line\n buildLineContent($block, lineText, lineStart, marks, widgets);\n\n if (widgets.some((widget) => widget.layout === 'trailing')) {\n $block.classList.add('line--trailing-widget');\n }\n\n if (signature) {\n this.lineSignatures.set($block, signature);\n } else {\n this.lineSignatures.delete($block);\n }\n\n // Set diagnostic message via data attribute — rendered by ::after pseudo-element\n // so it is completely outside the DOM selection and clipboard path.\n const diagnostics = lineDecorations.filter((decoration) => decoration.message);\n\n if (diagnostics.length > 0) {\n const text = diagnostics.map((decoration) => decoration.message).join(' · ');\n const classes = [\n ...new Set(\n diagnostics.flatMap((decoration) =>\n decoration.messageClassName\n ? decoration.messageClassName.split(/\\s+/).filter(Boolean)\n : [],\n ),\n ),\n ];\n\n $block.dataset.message = text;\n $block.title = text;\n\n if (classes.length > 0) {\n $block.dataset.messageClass = classes.join(' ');\n }\n }\n\n lineStartOffset += lineText.length + 1; // +1 for the '\\n' separator\n }\n\n // Remove trailing line elements left over from a shorter previous value\n while ($documentRoot.children.length > lines.length) {\n $documentRoot.lastChild?.remove();\n }\n }\n\n destroy(): void {\n const $documentRoot = this.scroll.domNode as HTMLElement;\n\n while ($documentRoot.firstChild) {\n $documentRoot.removeChild($documentRoot.firstChild);\n }\n }\n}\n\n/**\n * Extracts plain text directly from the contenteditable DOM.\n */\nexport function getText($editorEl: HTMLElement): string {\n const $lines = Array.from($editorEl.querySelectorAll<HTMLElement>('.line'));\n\n if ($lines.length > 0) {\n return $lines.map(($lineEl) => getLineText($lineEl)).join('\\n');\n }\n\n // Fallback: raw contenteditable DOM walk\n return extractRawText($editorEl);\n}\n\nfunction getLineText($lineEl: HTMLElement): string {\n let text = '';\n\n for (const node of $lineEl.childNodes) {\n text += getNodeText(node);\n }\n\n return text;\n}\n\nfunction getNodeText(node: Node): string {\n if (node.nodeType === Node.TEXT_NODE) {\n return (node as Text).data;\n }\n\n if (!(node instanceof Element)) {\n return '';\n }\n\n if (node.classList.contains('widget')) {\n return '';\n }\n\n if (node.classList.contains('line-message')) {\n return '';\n }\n\n if (node.tagName === 'BR') {\n return '';\n }\n\n let text = '';\n\n for (const child of node.childNodes) {\n text += getNodeText(child);\n }\n\n return text;\n}\n\nfunction extractRawText($el: HTMLElement): string {\n let result = '';\n let firstBlock = true;\n\n for (const node of $el.childNodes) {\n if (node.nodeType === Node.TEXT_NODE) {\n result += (node as Text).data;\n } else if (node instanceof HTMLElement) {\n if (node.tagName === 'BR') {\n result += '\\n';\n firstBlock = false;\n\n continue;\n }\n\n if (node.classList.contains('widget')) {\n continue;\n }\n\n const isBlock = node.tagName === 'DIV' || node.tagName === 'P';\n\n if (isBlock && !firstBlock) {\n result += '\\n';\n }\n\n firstBlock = false;\n result += extractRawText(node);\n }\n }\n\n return result;\n}\n","/**\n * Cursor save/restore for rc-textarea's contenteditable editor.\n *\n * The text model is a plain string with \\n line separators.\n *\n * WidgetDecoration spans (.widget) are zero-width in the text model (not part\n * of the value string). <br> elements (used to make empty lines editable) count\n * as 0 characters.\n */\n\nexport interface SavedSelection {\n /** Anchor position as a character offset into the plain text value. */\n anchorOffset: number;\n\n /** Focus position as a character offset into the plain text value. */\n focusOffset: number;\n}\n\ninterface SelectionEndpoints {\n $anchorNode: Node;\n anchorOffset: number;\n $focusNode: Node;\n focusOffset: number;\n}\n\ntype ShadowSelectionRoot = ShadowRoot & {\n getSelection?: () => Selection | null;\n};\n\ntype ComposedSelection = Selection & {\n getComposedRanges?: (options: { shadowRoots: ShadowRoot[] }) => StaticRange[];\n};\n\n/** Returns the text-model length of a DOM node and its descendants. */\nfunction textModelLength($node: Node): number {\n if ($node.nodeType === Node.TEXT_NODE) {\n return ($node as Text).length;\n }\n\n if (!($node instanceof Element)) {\n return 0;\n }\n\n if ($node.classList.contains('widget')) {\n return 0;\n }\n\n if ($node.tagName === 'BR') {\n return 0;\n }\n\n let len = 0;\n\n for (const $child of $node.childNodes) {\n len += textModelLength($child);\n }\n\n return len;\n}\n\n/**\n * Converts a DOM (node, nodeOffset) pair inside `$root` to a plain-text offset.\n * Returns the end-of-content offset if the target was not found inside `$root`.\n */\nexport function domToTextOffset(\n $root: Element,\n $targetNode: Node,\n targetNodeOffset: number,\n): number {\n const $lines = Array.from($root.querySelectorAll<HTMLElement>('.line'));\n\n let totalOffset = 0;\n\n for (const [lineIdx, $line] of $lines.entries()) {\n if (lineIdx > 0) {\n totalOffset++; // \\n between lines\n }\n\n // Firefox's Select All uses the editor itself as the range boundary.\n if ($targetNode === $root && $root.childNodes[targetNodeOffset] === $line) {\n return totalOffset;\n }\n\n const result = walkForOffset($line, $targetNode, targetNodeOffset, totalOffset);\n\n if (result.found) {\n return result.offset;\n }\n\n totalOffset += textModelLength($line);\n }\n\n // Target not found — fall back to end of content\n return totalOffset;\n}\n\ninterface WalkResult {\n found: boolean;\n offset: number;\n}\n\n/**\n * Recursively walk the subtree rooted at `$node`, accumulating character\n * offsets until `$targetNode` / `targetNodeOffset` is found.\n *\n * Returns `{ found: true, offset }` when the target is located, or\n * `{ found: false, offset }` where `offset` is the cumulative length of all\n * text visited so far (allowing the caller to continue from where we left off).\n */\nfunction walkForOffset(\n $node: Node,\n $targetNode: Node,\n targetNodeOffset: number,\n currentOffset: number,\n): WalkResult {\n if ($node === $targetNode) {\n if ($node.nodeType === Node.TEXT_NODE) {\n return { found: true, offset: currentOffset + targetNodeOffset };\n }\n\n const $children = Array.from($node.childNodes);\n\n // Element node - targetNodeOffset is a child index\n let offset = currentOffset;\n\n for (const $child of $children.slice(0, targetNodeOffset)) {\n offset += textModelLength($child);\n }\n\n return { found: true, offset: offset };\n }\n\n if ($node.nodeType === Node.TEXT_NODE) {\n return { found: false, offset: currentOffset + ($node as Text).length };\n }\n\n if ($node instanceof Element) {\n if ($node.classList.contains('widget')) {\n return { found: false, offset: currentOffset };\n }\n\n if ($node.tagName === 'BR') {\n return { found: false, offset: currentOffset };\n }\n\n let offset = currentOffset;\n\n for (const $child of $node.childNodes) {\n const result = walkForOffset($child, $targetNode, targetNodeOffset, offset);\n\n if (result.found) {\n return result;\n }\n\n offset = result.offset;\n }\n\n return { found: false, offset: offset };\n }\n\n return { found: false, offset: currentOffset };\n}\n\ninterface DomPosition {\n node: Node;\n offset: number;\n}\n\n/**\n * Converts a plain-text offset to a (node, nodeOffset) DOM position inside `$root`.\n *\n * Returns null if offset is out of range.\n */\nexport function textOffsetToDom($root: Element, targetOffset: number): DomPosition | null {\n const $lines = Array.from($root.querySelectorAll<HTMLElement>('.line'));\n\n let localOffset = targetOffset;\n\n for (const [i, $line] of $lines.entries()) {\n if (i > 0) {\n if (localOffset === 0) {\n // Position at boundary between lines — place at start of this line\n return { node: $line, offset: 0 };\n }\n\n localOffset--; // consume the \\n\n }\n\n const lineLen = textModelLength($line);\n\n if (localOffset <= lineLen) {\n const pos = walkToOffset($line, localOffset);\n\n if (pos) {\n return pos;\n }\n\n // Cursor at end of line element\n return { node: $line, offset: $line.childNodes.length };\n }\n\n localOffset -= lineLen;\n }\n\n // Beyond end of content — place at end of last line\n const $line = $lines[$lines.length - 1];\n\n if ($line) {\n return { node: $line, offset: $line.childNodes.length };\n }\n\n return { node: $root, offset: $root.childNodes.length };\n}\n\n/**\n * Walk `$node`'s subtree to find the DOM position corresponding to\n * `localOffset` text-model characters from the start of `$node`.\n *\n * Returns a `{ node, offset }` pair suitable for a `Range` endpoint, or\n * `null` if the target falls beyond this subtree (caller must keep going).\n */\nfunction walkToOffset($node: Node, localOffset: number): DomPosition | null {\n if ($node.nodeType === Node.TEXT_NODE) {\n const $textNode = $node as Text;\n\n if (localOffset <= $textNode.length) {\n return { node: $textNode, offset: localOffset };\n }\n\n return null;\n }\n\n if ($node instanceof Element) {\n if ($node.classList.contains('widget')) {\n return null;\n }\n\n if ($node.tagName === 'BR') {\n return null;\n }\n\n let offset = 0;\n\n for (const $child of $node.childNodes) {\n const length = textModelLength($child);\n\n if (localOffset <= length) {\n const result = walkToOffset($child, localOffset);\n\n if (result) {\n return result;\n }\n\n // Target is at boundary inside this child\n return { node: $node, offset: offset + 1 };\n }\n\n localOffset -= length;\n offset++;\n }\n }\n\n return null;\n}\n\nfunction readNativeSelectionEndpoints(\n $root: Element,\n selection: Selection | null,\n): SelectionEndpoints | null {\n if (!selection || selection.rangeCount === 0 || !selection.anchorNode || !selection.focusNode) {\n return null;\n }\n\n const $range = selection.getRangeAt(0);\n\n if (\n !$root.contains($range.commonAncestorContainer) ||\n !$root.contains(selection.anchorNode) ||\n !$root.contains(selection.focusNode)\n ) {\n return null;\n }\n\n return {\n $anchorNode: selection.anchorNode,\n anchorOffset: selection.anchorOffset,\n $focusNode: selection.focusNode,\n focusOffset: selection.focusOffset,\n };\n}\n\nfunction readSelectionEndpoints($root: Element): SelectionEndpoints | null {\n const $rootNode = $root.getRootNode();\n const getShadowSelection = ($rootNode as ShadowSelectionRoot).getSelection;\n const shadowEndpoints = readNativeSelectionEndpoints(\n $root,\n getShadowSelection?.call($rootNode) ?? null,\n );\n\n if (shadowEndpoints) {\n return shadowEndpoints;\n }\n\n const globalSelection = window.getSelection();\n const globalEndpoints = readNativeSelectionEndpoints($root, globalSelection);\n\n if (globalEndpoints) {\n return globalEndpoints;\n }\n\n if (!($rootNode instanceof ShadowRoot)) {\n return null;\n }\n\n const [$composedRange] =\n (globalSelection as ComposedSelection | null)?.getComposedRanges?.({\n shadowRoots: [$rootNode],\n }) ?? [];\n\n if (\n !$composedRange ||\n !$root.contains($composedRange.startContainer) ||\n !$root.contains($composedRange.endContainer)\n ) {\n return null;\n }\n\n return {\n $anchorNode: $composedRange.startContainer,\n anchorOffset: $composedRange.startOffset,\n $focusNode: $composedRange.endContainer,\n focusOffset: $composedRange.endOffset,\n };\n}\n\n/** Returns the current selection focus node when it belongs to `$root`. */\nexport function getSelectionFocusNode($root: Element): Node | null {\n return readSelectionEndpoints($root)?.$focusNode ?? null;\n}\n\n/**\n * Captures the current browser selection as plain-text offsets relative to `$root`.\n *\n * Returns null if there is no selection or the selection is outside `$root`.\n */\nexport function saveSelection($root: Element): SavedSelection | null {\n const endpoints = readSelectionEndpoints($root);\n\n if (!endpoints) {\n return null;\n }\n\n return {\n anchorOffset: domToTextOffset($root, endpoints.$anchorNode, endpoints.anchorOffset),\n focusOffset: domToTextOffset($root, endpoints.$focusNode, endpoints.focusOffset),\n };\n}\n\n/**\n * Restores a previously saved selection inside `$root`.\n *\n * Silently does nothing if the saved offsets are out of range.\n */\nexport function restoreSelection($root: Element, saved: SavedSelection): void {\n const anchor = textOffsetToDom($root, saved.anchorOffset);\n const focus = textOffsetToDom($root, saved.focusOffset);\n\n if (!anchor || !focus) {\n return;\n }\n\n try {\n const selection = window.getSelection();\n\n if (!selection) {\n return;\n }\n\n const range = document.createRange();\n\n range.setStart(anchor.node, anchor.offset);\n range.setEnd(focus.node, focus.offset);\n\n selection.removeAllRanges();\n selection.addRange(range);\n } catch {\n // setStart/setEnd can throw on invalid offsets — ignore gracefully\n }\n}\n","/**\n * A styled inline range over characters [from, to).\n *\n * Rich formatting properties (bold, italic, color, etc.) are rendered as\n * inline styles on the blot span; `className` adds an extra CSS class.\n */\nexport interface MarkDecoration {\n /** Unique identifier assigned at creation time. */\n id: string;\n\n /** Decoration type discriminant. */\n type: 'mark';\n\n /** Inclusive start offset (0-based character index into plain text). */\n from: number;\n\n /** Exclusive end offset. */\n to: number;\n\n /** Space-separated CSS class name(s) added to the blot span. */\n className?: string;\n\n /** Renders the range bold (`font-weight: bold`). */\n bold?: boolean;\n\n /** Renders the range italic (`font-style: italic`). */\n italic?: boolean;\n\n /** Text color (`color` CSS property). Accepts any CSS color value. */\n color?: string;\n\n /** Background color (`background` CSS property). Accepts any CSS color value. */\n background?: string;\n\n /** Underline style (`text-decoration-style`). */\n underline?: 'solid' | 'wavy' | 'dotted' | 'dashed';\n\n /** Underline color (`text-decoration-color`). Defaults to the text `color` when omitted. */\n underlineColor?: string;\n\n /** Additional HTML attributes set directly on the blot span element. */\n attributes?: Record<string, string>;\n}\n\n/**\n * A decoration applied to an entire logical line.\n *\n * Adds a CSS class and/or data attributes to the line div, and optionally\n * appends a diagnostic message at the end of the line.\n */\nexport interface LineDecoration {\n /** Unique identifier assigned at creation time. */\n id: string;\n\n /** Decoration type discriminant. */\n type: 'line';\n\n /** 1-based logical line number. */\n line: number;\n\n /** Space-separated CSS class name(s) added to the line div. */\n className?: string;\n\n /**\n * Error-lens style diagnostic text shown at the end of the line.\n */\n message?: string;\n\n /**\n * Space-separated CSS class name(s) applied to the `data-message-class` attribute\n * on the line div. Use attribute selectors in CSS to style the message:\n *\n * ```css\n * .line[data-message-class~=\"error\"][data-message]::after { color: red; }\n * ```\n */\n messageClassName?: string;\n\n /** Additional HTML attributes set directly on the line element. */\n attributes?: Record<string, string>;\n\n /**\n * Override the built-in gutter cell content for this line.\n *\n * - `string` — custom label (e.g. `\"!\"`, `\"▶\"`)\n * - `HTMLElement` — plugin-owned marker or control; reuse its node between updates.\n * Set `gutterAccessible` when it contains an interactive control.\n * - `null` — force empty cell (suppress built-in content)\n * - `undefined` — use the built-in mode default (`line-numbers`, `gutter`, etc.)\n */\n gutterContent?: string | HTMLElement | null;\n\n /** Keep the built-in line number before custom gutter content when `line-numbers` is enabled. */\n gutterLineNumber?: boolean;\n\n /** Expose this gutter cell to assistive technology when it contains a control. */\n gutterAccessible?: boolean;\n}\n\n/**\n * A non-editable DOM element inserted at a character offset.\n *\n * Widgets are purely visual and do not appear in the plain text value.\n */\nexport interface WidgetDecoration {\n /** Unique identifier assigned at creation time. */\n id: string;\n\n /** Decoration type discriminant. */\n type: 'widget';\n\n /** Character offset. Widget is placed before (or after) the character at this position. */\n offset: number;\n\n /** Create widget content when its line rebuilds. With a stable key, content may be reused. */\n create(): HTMLElement;\n\n /** Whether to place the widget before or after the character at `offset`. Default: 'before'. */\n side?: 'before' | 'after';\n\n /** Preserve this widget's line DOM while its key and decorations remain unchanged.\n * Change the key when its content changes. Scope keys to the owning plugin.\n */\n key?: string;\n\n /** Place the widget inline, below its logical line, or in a reserved trailing lane. */\n layout?: 'inline' | 'block' | 'trailing';\n\n /** Expose interactive or meaningful widget content to assistive technology. Default: false. */\n accessible?: boolean;\n}\n\n/** Hide complete source lines while retaining their text and model offsets. */\nexport interface FoldDecoration {\n id: string;\n type: 'fold';\n /** First hidden line, one-based and inclusive. */\n fromLine: number;\n /** Last hidden line, one-based and inclusive. */\n toLine: number;\n /** Reveal this range before a user edit or caret move enters its hidden lines. */\n reveal(): void;\n}\n\n/** Decorations are visual formatting applied to the field content without affecting\n * the underlying plain text value.\n */\nexport type Decoration = MarkDecoration | LineDecoration | WidgetDecoration | FoldDecoration;\n\n/** Input shape for creating a decoration — id-less variant of each decoration type. */\nexport type DecorationInput =\n | Omit<MarkDecoration, 'id'>\n | Omit<LineDecoration, 'id'>\n | Omit<WidgetDecoration, 'id'>\n | Omit<FoldDecoration, 'id'>;\n\n/**\n * A semantic token produced by an external tokenizer (lezer, tree-sitter, shiki, etc.).\n *\n * Offsets are absolute character indices into the plain-text value — the same coordinate\n * space as `MarkDecoration.from` / `MarkDecoration.to`.\n *\n * Use `RCTextareaPluginAPI.decorationsFromTokens()` to convert a token array into\n * `DecorationInput[]` using a theme map.\n */\nexport interface Token {\n /** Inclusive start offset (0-based character index into plain text). */\n from: number;\n\n /** Exclusive end offset. */\n to: number;\n\n /** Semantic token type. */\n type: string;\n\n /** Optional scope list. */\n scopes?: string[];\n}\n\n/**\n * Contextual API available inside plugin lifecycle callbacks.\n *\n * Plugins own the decoration state — keep a reference to `api` from `mount()`\n * to set decorations from outside the plugin lifecycle:\n *\n * ```ts\n * let api: RCTextareaPluginAPI;\n * editor.usePlugin({\n * mount(a) { api = a; },\n * update() {},\n * });\n *\n * // later:\n * api.setDecorations([...]);\n * api.scheduleUpdate();\n * ```\n */\nexport interface RCTextareaPluginAPI {\n /** The host `rc-textarea` element. */\n readonly host: HTMLElement;\n\n /** The current plain-text field value at the time of the callback. */\n readonly value: string;\n\n /** Normalized selection start offset (always ≤ `selectionEnd`). */\n readonly selectionStart: number;\n\n /** Normalized selection end offset (always ≥ `selectionStart`). Equals `selectionStart` when the cursor is collapsed. */\n readonly selectionEnd: number;\n\n /**\n * The editor's resolved base direction, from the textarea's `dir` or the\n * host's. Anchor caret-relative popups with this, not the host's flow.\n */\n readonly contentDirection: 'ltr' | 'rtl';\n\n /** The content language: the textarea's `lang`, or `''` when it sets none. */\n readonly contentLang: string;\n\n /**\n * The resolved direction of a 1-based line. Under `line-direction=\"auto\"`\n * that is the direction of the line's first strong character; otherwise,\n * and for lines without one, it is `contentDirection`.\n */\n lineDirection(line: number): 'ltr' | 'rtl';\n\n /**\n * Returns the bounding rect of the cursor (caret) in viewport coordinates.\n *\n * Useful for anchoring autocomplete popups or hover tooltips to the cursor.\n *\n * @returns the cursor bounding rect, or `null` if the editor is not focused\n * or the cursor is outside the editor\n */\n getCursorRect(): DOMRect | null;\n\n /**\n * Returns the word boundaries at the current cursor position.\n *\n * Words come from `Intl.Segmenter` for `contentLang` (UAX #29, with\n * dictionary segmentation for Japanese and Thai), so `crème`, `don't` and\n * `snake_case` are each one word. The word starting at the cursor wins over\n * the one ending there.\n *\n * @returns the word and its `[from, to)` offsets, or `null` if the cursor\n * touches no letter or digit\n */\n getWordAtCursor(): { word: string; from: number; to: number } | null;\n\n /**\n * Subscribe to cursor/selection changes. The callback fires on every cursor\n * move (arrow keys, mouse clicks, selection changes) while the editor is focused.\n *\n * @returns an unsubscribe function. Call this in `destroy()`\n *\n * @example\n * ```ts\n * let unsub: () => void;\n * editor.usePlugin({\n * mount(api) {\n * unsub = api.onCursorMove((start, end) => {\n * const word = api.getWordAtCursor();\n * if (word) showTooltip(word, api.getCursorRect());\n * });\n * },\n * destroy() { unsub?.(); },\n * });\n * ```\n */\n onCursorMove(callback: (selectionStart: number, selectionEnd: number) => void): () => void;\n\n /**\n * Add a single decoration to the plugin's decoration set.\n *\n * Use the returned id with `removeDecoration` to remove it individually.\n *\n * @returns the assigned `id`, used to remove or look up the decoration later\n */\n addDecoration(d: DecorationInput): string;\n\n /** Remove a previously added decoration by its id. */\n removeDecoration(id: string): void;\n\n /** Remove all decorations set by this plugin. */\n clearDecorations(): void;\n\n /**\n * Replace the full decoration set with `decorations`.\n */\n setDecorations(decorations: DecorationInput[]): void;\n\n /**\n * @returns the decorations this plugin has currently set, in insertion order\n */\n getDecorations(): readonly Decoration[];\n\n /** Trigger a render pass outside of normal text input events. */\n scheduleUpdate(): void;\n\n /**\n * Inject a stylesheet into the component's shadow root via `adoptedStyleSheets`.\n *\n * Adopted sheets are automatically removed when the plugin is unmounted.\n *\n * @returns the adopted `CSSStyleSheet`, which can be passed to `removeStyleSheet`\n * if explicit removal is needed before unmount\n *\n * @example CSS text string\n * ```ts\n * editor.usePlugin({\n * mount(api) {\n * api.adoptStyleSheet(`\n * .hljs-keyword { color: #cba6f7; }\n * .hljs-string { color: #a6e3a1; }\n * `);\n * },\n * });\n * ```\n *\n * @example Shared CSSStyleSheet (constructed once, adopted by many)\n * ```ts\n * const sharedSheet = new CSSStyleSheet();\n * sharedSheet.replaceSync('.hljs-keyword { color: #cba6f7; }');\n *\n * editor.usePlugin({\n * mount(api) { api.adoptStyleSheet(sharedSheet); },\n * });\n * ```\n */\n adoptStyleSheet(sheetOrCssText: CSSStyleSheet | string): CSSStyleSheet;\n\n /**\n * Remove a previously adopted stylesheet from the shadow root.\n */\n removeStyleSheet(sheet: CSSStyleSheet): void;\n\n /**\n * Compatibility bridge for highlight.js / prism.js.\n *\n * Parses an HTML string of `<span class=\"...\">text</span>` structures\n * (as returned by `hljs.highlight()` or `Prism.highlight()`) and converts\n * them into `MarkDecoration` objects covering the corresponding character\n * ranges of the plain text value.\n *\n * @example\n * ```ts\n * editor.usePlugin({\n * highlight(value, api) {\n * const html = hljs.highlight(value, { language: 'js' }).value;\n * api.setDecorations(api.parseDecorationsFromHtml(html));\n * },\n * });\n * ```\n */\n parseDecorationsFromHtml(html: string): Omit<MarkDecoration, 'id'>[];\n\n /**\n * Convert a flat token array from an external tokenizer (lezer, tree-sitter, shiki, moo, etc.)\n * into `DecorationInput` objects using a theme map keyed by `token.type`.\n *\n * Token offsets must be **absolute** character indices into the plain-text value\n * (same coordinate space as `MarkDecoration.from` / `MarkDecoration.to`).\n * Types not present in `themeMap` are silently ignored.\n *\n * @example\n * ```ts\n * editor.usePlugin({\n * update(value, api) {\n * const tokens = myTokenizer.tokenize(value);\n * api.setDecorations(api.decorationsFromTokens(tokens, {\n * keyword: { bold: true, color: 'var(--color-keyword)' },\n * string: { color: 'var(--color-string)' },\n * comment: { italic: true, color: 'var(--color-comment)' },\n * }));\n * },\n * });\n * ```\n */\n decorationsFromTokens(\n tokens: Token[],\n themeMap: Record<string, Omit<MarkDecoration, 'id' | 'type' | 'from' | 'to'>>,\n ): Omit<MarkDecoration, 'id'>[];\n\n /**\n * Insert `text` at the current cursor position, replacing any active selection.\n *\n * Equivalent to typing the text with the keyboard.\n */\n insertText(text: string): void;\n\n /**\n * Wrap the current selection with `prefix` and `suffix`.\n *\n * No-op when the selection is collapsed (no text selected).\n *\n * @example\n * ```ts\n * api.wrapSelection('**', '**'); // bold\n * api.wrapSelection('`', '`'); // inline code\n * ```\n */\n wrapSelection(prefix: string, suffix: string): void;\n\n /**\n * Replace the current selection with `text`.\n *\n * When the selection is collapsed this is equivalent to `insertText`.\n */\n replaceSelection(text: string): void;\n}\n\n/**\n * Plugin interface for rc-textarea.\n *\n * At least one of `update` or `highlight` must be provided.\n *\n * @example Syntax highlighting with highlight.js\n * ```ts\n * import hljs from 'highlight.js/lib/core';\n * import javascript from 'highlight.js/lib/languages/javascript';\n *\n * hljs.registerLanguage('javascript', javascript);\n *\n * editor.usePlugin({\n * highlight(value, api) {\n * const html = hljs.highlight(value, { language: 'javascript' }).value;\n *\n * api.setDecorations(api.parseDecorationsFromHtml(html));\n * },\n * });\n * ```\n *\n * @example Async highlighter (WASM / web worker)\n * ```ts\n * editor.usePlugin({\n * async update(value, api) {\n * const decs = await myParser.decorate(value);\n *\n * api.setDecorations(decs);\n * },\n * });\n * ```\n */\nexport interface RCTextareaPlugin {\n /** Called when the plugin is registered. Store `api` here for external use. */\n mount?(api: RCTextareaPluginAPI): void;\n\n /** Called when the plugin is replaced or the element disconnects. */\n destroy?(): void;\n\n /**\n * Display-layer value transform — called before `update`/`highlight`\n * while the slotted textarea is `readonly`.\n *\n * Return a non-null string to substitute it as the rendered\n * text passed to all subsequent hooks and to the document builder.\n * The underlying `element.value` is never modified; only the display\n * layer sees the transformed text.\n *\n * Return `null` or `void` to leave the value unchanged.\n */\n transform?(value: string, api: RCTextareaPluginAPI): string | null | void;\n\n /**\n * Imperative decoration API\n */\n update?(value: string, api: RCTextareaPluginAPI): void | Promise<void>;\n\n /**\n * HTML-based compat\n *\n * Return an HTML string (e.g. from hljs/prism); it will be parsed via\n * `api.parseDecorationsFromHtml()` and applied as mark decorations.\n *\n * Return `null` or `void` to skip.\n */\n highlight?(\n value: string,\n api: RCTextareaPluginAPI,\n ): string | null | void | Promise<string | null | void>;\n}\n\n/**\n * The subset of `MarkDecoration` properties used for styling.\n *\n * Used in `TextPattern.captureGroups` to assign a style to each named capture group.\n */\nexport type MarkDecorationStyle = Pick<\n MarkDecoration,\n | 'className'\n | 'bold'\n | 'italic'\n | 'color'\n | 'background'\n | 'underline'\n | 'underlineColor'\n | 'attributes'\n>;\n\nexport interface TextPattern {\n /** Unique identifier used to register and unregister the pattern. */\n id: string;\n\n /** Regular expression matched against the full editor value. Use the `g` flag for multiple matches. */\n pattern: RegExp;\n\n /** Space-separated CSS class name(s) applied to matched ranges. */\n className?: string;\n\n /** Renders matched ranges bold (`font-weight: bold`). */\n bold?: boolean;\n\n /** Renders matched ranges italic (`font-style: italic`). */\n italic?: boolean;\n\n /** Text color for matched ranges. Accepts any CSS color value. */\n color?: string;\n\n /** Background color for matched ranges. Accepts any CSS color value. */\n background?: string;\n\n /** Underline style for matched ranges (`text-decoration-style`). */\n underline?: 'solid' | 'wavy' | 'dotted' | 'dashed';\n\n /** Underline color for matched ranges (`text-decoration-color`). Defaults to the text `color` when omitted. */\n underlineColor?: string;\n\n /** Additional HTML attributes set directly on matched-range spans. */\n attributes?: Record<string, string>;\n\n /**\n * Factory called for each regex match.\n *\n * Return a partial LineDecoration\n * (message, messageClassName, className, attributes) to add a diagnostic\n * message on the matched line, or `null` to skip.\n */\n createLineDecoration?: (\n match: RegExpMatchArray,\n ) => Omit<LineDecoration, 'id' | 'type' | 'line'> | null;\n\n /**\n * Decoration styles for each named capture group in the pattern.\n *\n * When provided, one\n * `MarkDecoration` is emitted per captured group (unmatched optional groups\n * are skipped) instead of one decoration for the whole match.\n *\n * The `pattern` must use named capture groups (`(?<name>...)`). The `d`\n * flag (indices) is added automatically when `captureGroups` is set.\n *\n * @example\n * ```ts\n * {\n * id: 'kv',\n * pattern: /^(?<key>\\w+):\\s*(?<value>.+)$/gm,\n * captureGroups: {\n * key: { bold: true, color: '#c792ea' },\n * value: { color: '#c3e88d' },\n * },\n * }\n * ```\n */\n captureGroups?: Record<string, MarkDecorationStyle>;\n}\n\n/**\n * A simplified plugin variant for per-line decoration.\n *\n * Return mark/line decorations with offsets relative to the start of the\n * line.\n *\n * `createLineDecoratorPlugin()` converts them to absolute document\n * offsets automatically, so no `lineStart` bookkeeping is needed.\n *\n * @example\n * ```ts\n * const myDecorator: LineDecoratorPlugin = {\n * styles: '.kw { font-weight: bold; color: #cba6f7; }',\n * decorateLine(line) {\n * const results: Omit<MarkDecoration | LineDecoration, 'id'>[] = [];\n * const m = /\\bfunction\\b/.exec(line);\n *\n * if (m) {\n * results.push({ type: 'mark', from: m.index, to: m.index + m[0].length, className: 'kw' });\n * }\n *\n * return results;\n * },\n * };\n *\n * editor.usePlugin(createLineDecoratorPlugin(myDecorator));\n * ```\n */\nexport interface LineDecoratorPlugin {\n /**\n * Called for each line of text (including empty lines, which can be skipped\n * by returning `[]`). `lineIndex` is 0-based.\n *\n * Offsets in returned `MarkDecoration` objects must be **line-relative**\n * (0 = start of the line). `LineDecoration.line` should be 1-based as usual.\n */\n decorateLine(\n line: string,\n lineIndex: number,\n ): (Omit<MarkDecoration, 'id'> | Omit<LineDecoration, 'id'>)[];\n\n /** CSS text to inject into the component's shadow root once on mount. */\n styles?: string;\n}\n\n/** Generate a unique decoration ID (UUID v4). */\nexport function generateId(): string {\n return crypto.randomUUID();\n}\n","import type { Decoration, MarkDecoration, LineDecoration, DecorationInput } from './types.js';\n\nexport { generateId } from './types.js';\n\n/**\n * The minimal description of a single contiguous edit:\n * a deletion of `removed` characters at `start`, followed by an insertion of\n * `inserted` characters at that same position.\n */\ninterface Edit {\n /** Character offset where the edit begins (inclusive). */\n start: number;\n\n /** Number of characters removed. */\n removed: number;\n\n /** Number of characters inserted. */\n inserted: number;\n}\n\n/**\n * Find the single contiguous edit region that transforms `oldValue` into\n * `newValue` by trimming equal prefix and suffix.\n *\n * This is a heuristic (\"longest common prefix/suffix\"), not a full LCS diff.\n * It assumes the browser makes one contiguous edit per input event, which holds\n * true for normal typing, deletion, and paste.\n *\n * @see {@link http://www.xmailserver.org/diff2.pdf Myers 1986 — An O(ND) Difference Algorithm and Its Variations}\n */\nexport function findEdit(oldValue: string, newValue: string): Edit {\n let start = 0;\n\n while (\n start < oldValue.length &&\n start < newValue.length &&\n oldValue[start] === newValue[start]\n ) {\n start++;\n }\n\n let oldEnd = oldValue.length;\n let newEnd = newValue.length;\n\n while (oldEnd > start && newEnd > start && oldValue[oldEnd - 1] === newValue[newEnd - 1]) {\n oldEnd--;\n newEnd--;\n }\n\n return { start, removed: oldEnd - start, inserted: newEnd - start };\n}\n\n/**\n * Remap a `[from, to)` mark range through a single edit, returning the new\n * range or `null` if the decoration collapses to zero width and should be dropped.\n *\n * - Ranges entirely **before** the edit are unchanged.\n * - Ranges entirely **after** the edit are shifted by `edit.inserted − edit.removed`.\n * - Ranges that **overlap** the edit region are expanded/contracted to cover the\n * nearest edit boundary, then dropped if they collapse.\n *\n * Adapted from the position-mapping model described in ProseMirror's `StepMap`.\n *\n * @see {@link https://prosemirror.net/docs/ref/#transform.StepMap ProseMirror — StepMap}\n */\nfunction remapMarkRange(from: number, to: number, edit: Edit): { from: number; to: number } | null {\n const editEnd = edit.start + edit.removed;\n const delta = edit.inserted - edit.removed;\n\n // entirely before edit — unchanged\n if (to <= edit.start) {\n return { from, to };\n }\n\n // entirely after edit — shift by delta\n if (from >= editEnd) {\n return { from: from + delta, to: to + delta };\n }\n\n // overlaps the edit region — clamp to nearest edit boundary\n const newFrom = Math.min(from, edit.start);\n const newTo = Math.max(\n to > editEnd ? to + delta : edit.start + edit.inserted,\n edit.start + edit.inserted,\n );\n\n if (newFrom >= newTo) {\n return null;\n }\n\n return { from: newFrom, to: newTo };\n}\n\n/**\n * Count the number of `\\n` characters in `text` before `offset`.\n * The result is the zero-based line index at that position; add 1 for a 1-based line number.\n */\nfunction countNewlinesBefore(text: string, offset: number): number {\n let count = 0;\n\n for (let i = 0; i < offset && i < text.length; i++) {\n if (text[i] === '\\n') {\n count++;\n }\n }\n\n return count;\n}\n\n/**\n * Remap all decorations in `decorations` from positions in `oldValue` to\n * positions in `newValue`, assuming a single contiguous edit.\n *\n * - `MarkDecoration`: remapped via `remapMarkRange`; dropped if collapsed.\n * - `LineDecoration`: dropped if its line falls within the deleted region;\n * otherwise shifted by the line delta.\n * - `WidgetDecoration`: treated like a zero-width mark at its offset.\n * - `FoldDecoration`: dropped; the owning plugin recalculates source ranges.\n *\n * Returns a new array. The input array and its elements are not mutated.\n */\nexport function mapDecorationsThroughChange(\n decorations: Decoration[],\n oldValue: string,\n newValue: string,\n): Decoration[] {\n const edit = findEdit(oldValue, newValue);\n const editEnd = edit.start + edit.removed;\n\n const removedText = oldValue.slice(edit.start, editEnd);\n const insertedText = newValue.slice(edit.start, edit.start + edit.inserted);\n const linesRemoved = (removedText.match(/\\n/g) ?? []).length;\n const linesInserted = (insertedText.match(/\\n/g) ?? []).length;\n const lineDelta = linesInserted - linesRemoved;\n\n // 1-based line number of the first character that changed\n const editStartLine = countNewlinesBefore(oldValue, edit.start) + 1;\n const editEndLine = editStartLine + linesRemoved;\n\n const mapped: Decoration[] = [];\n\n for (const docoration of decorations) {\n if (docoration.type === 'mark') {\n const result = remapMarkRange(docoration.from, docoration.to, edit);\n\n if (result) {\n mapped.push({ ...docoration, from: result.from, to: result.to });\n }\n } else if (docoration.type === 'line') {\n if (docoration.line < editStartLine) {\n // before edit — unchanged\n mapped.push(docoration);\n } else if (docoration.line <= editEndLine) {\n // falls within deleted region — drop\n } else {\n // after edit — shift by line delta\n mapped.push({ ...docoration, line: docoration.line + lineDelta });\n }\n } else if (docoration.type === 'widget') {\n // WidgetDecoration: treat the offset like a mark's 'from'\n const result = remapMarkRange(docoration.offset, docoration.offset + 1, edit);\n\n if (result) {\n mapped.push({ ...docoration, offset: result.from });\n }\n } else {\n // Fold ranges are recalculated by their owning plugin after a text edit.\n }\n }\n\n return mapped;\n}\n\n/**\n * Heuristic: returns `true` when an edit is large enough that remapping\n * decorations would likely produce incorrect results and it's better to\n * clear them entirely.\n *\n * Threshold: the change affects > 50 characters **and** > 50% of the document.\n * This covers paste of large blocks, select-all + type, and programmatic value\n * sets with substantially different content. It deliberately ignores inserts\n * into an empty document (no existing decorations to preserve).\n */\nexport function isLargeChange(oldValue: string, edit: Edit): boolean {\n if (oldValue.length === 0) {\n return false;\n }\n\n const changeSize = Math.max(edit.removed, edit.inserted);\n\n return changeSize > 50 && changeSize > oldValue.length * 0.5;\n}\n\n/**\n * Map decorations through a text change, or clear them entirely if the change\n * is classified as \"large\" (see `isLargeChange`).\n *\n * This is the primary entry point used by the component on each input event.\n */\nexport function remapDecorations(\n decorations: Decoration[],\n oldValue: string,\n newValue: string,\n): Decoration[] {\n const edit = findEdit(oldValue, newValue);\n\n if (isLargeChange(oldValue, edit)) {\n return [];\n }\n\n return mapDecorationsThroughChange(decorations, oldValue, newValue);\n}\n\n/**\n * Add a single decoration to `map`, assigning it a fresh UUID as its `id`.\n *\n * @returns the assigned `id`, used to remove or look up the decoration later\n */\nexport function addDecoration(map: Map<string, Decoration>, input: DecorationInput): string {\n const id = crypto.randomUUID();\n\n map.set(id, { ...input, id } as Decoration);\n\n return id;\n}\n\n/**\n * Replace all decorations in `map` with a new set derived from `inputs`.\n * Each input is assigned a fresh UUID.\n */\nexport function setDecorations(map: Map<string, Decoration>, inputs: DecorationInput[]): void {\n map.clear();\n\n for (const input of inputs) {\n const id = crypto.randomUUID();\n\n map.set(id, { ...input, id } as Decoration);\n }\n}\n\nexport type { MarkDecoration, LineDecoration };\n","import type { TextPattern, MarkDecoration, LineDecoration } from './types.js';\n\nexport type { TextPattern };\n\n/**\n * Run all `patterns` against `value` and collect every match as decorations.\n *\n * For each pattern:\n *\n * - If `captureGroups` is set, one `MarkDecoration` is emitted per named\n * capture group instead of one for the whole match. Unmatched optional\n * groups are silently skipped. The `d` flag (match indices) is added to\n * the regex automatically.\n * - Otherwise, one `MarkDecoration` covering the entire match is emitted,\n * using the styling fields copied directly from the pattern.\n * - If `createLineDecoration` is provided, it is called for every match\n * (regardless of `captureGroups`) and may produce a paired `LineDecoration`.\n *\n * The global flag is added automatically if missing to ensure all occurrences\n * are found and to avoid stateful `lastIndex` bugs on the caller's regex.\n *\n * Zero-length matches are skipped to prevent infinite loops.\n */\nexport function matchPatternResults(\n value: string,\n patterns: TextPattern[],\n): {\n markDecorations: Omit<MarkDecoration, 'id'>[];\n lineDecorations: Omit<LineDecoration, 'id'>[];\n} {\n const markDecorations: Omit<MarkDecoration, 'id'>[] = [];\n const lineDecorations: Omit<LineDecoration, 'id'>[] = [];\n\n for (const pattern of patterns) {\n // Always clone the regex with the global flag so we can iterate all\n // occurrences without mutating the caller's RegExp.lastIndex.\n // Add the 'd' flag (indices) automatically when captureGroups is set.\n let flags = pattern.pattern.flags.includes('g')\n ? pattern.pattern.flags\n : pattern.pattern.flags + 'g';\n\n if (pattern.captureGroups && !flags.includes('d')) {\n flags += 'd';\n }\n\n const regex = new RegExp(pattern.pattern.source, flags);\n\n let match: RegExpExecArray | null;\n\n while ((match = regex.exec(value)) !== null) {\n // Skip zero-length matches to guard against infinite loops\n if (match[0].length === 0) {\n regex.lastIndex++;\n\n continue;\n }\n\n const from = match.index;\n\n if (pattern.captureGroups) {\n // Emit one MarkDecoration per named capture group\n // Unmatched optional groups are skipped\n const groupIndices = match.indices?.groups;\n\n if (groupIndices) {\n for (const [groupName, style] of Object.entries(pattern.captureGroups)) {\n const range = groupIndices[groupName];\n\n if (range === undefined) {\n continue;\n }\n\n const [groupStart, groupEnd] = range;\n\n markDecorations.push({ type: 'mark', from: groupStart, to: groupEnd, ...style });\n }\n }\n } else {\n // Whole-match mode: one decoration covering the entire match.\n const to = from + match[0].length;\n\n markDecorations.push({\n type: 'mark',\n from,\n to,\n className: pattern.className,\n bold: pattern.bold,\n italic: pattern.italic,\n color: pattern.color,\n background: pattern.background,\n underline: pattern.underline,\n underlineColor: pattern.underlineColor,\n attributes: pattern.attributes,\n });\n }\n\n if (pattern.createLineDecoration) {\n const lineInput = pattern.createLineDecoration(match);\n\n if (lineInput) {\n // 1-based line number\n const line = value.slice(0, from).split('\\n').length;\n\n lineDecorations.push({ type: 'line', line, ...lineInput });\n }\n }\n }\n }\n\n return { markDecorations, lineDecorations };\n}\n","import { css } from 'lit';\n\nexport const styles = css`\n .widget.widget--block {\n display: block;\n white-space: normal;\n }\n\n .line--trailing-widget {\n position: relative;\n padding-inline-end: var(--rc-textarea-trailing-size, 2.5em);\n min-block-size: var(--rc-textarea-trailing-size, 2.5em);\n }\n\n .widget--trailing {\n position: absolute;\n inset-inline-end: 0;\n inset-block-start: 0;\n inline-size: var(--rc-textarea-trailing-size, 2.5em);\n white-space: normal;\n }\n\n .fold-action-trigger {\n box-sizing: border-box;\n inline-size: 100%;\n block-size: 1lh;\n padding: 0;\n border: 0;\n background: transparent;\n cursor: pointer;\n color: inherit;\n font: inherit;\n }\n\n .gutter-cell {\n position: relative;\n }\n\n .gutter-cell > .fold-action-trigger::before,\n .gutter-cell > :not(.fold-action-group) .fold-action-trigger::before {\n content: '';\n position: absolute;\n inset: 0;\n }\n\n .fold-action-group,\n .fold-action-single {\n display: inline-flex;\n align-items: center;\n vertical-align: top;\n }\n\n .fold-action-group .fold-action-trigger {\n min-inline-size: 24px;\n }\n\n /* The trailing lane gives its trigger a target taller than one line; a gutter\n trigger sizes to its own row instead. */\n .widget--trailing .fold-action-trigger {\n min-block-size: var(--rc-textarea-trailing-size, 2.5em);\n }\n\n .widget--block [hidden] {\n display: none;\n }\n\n :host {\n display: block;\n box-sizing: border-box;\n min-inline-size: 0;\n color-scheme: inherit;\n }\n\n :host([hidden]) {\n display: none;\n }\n\n #root {\n display: flex;\n align-items: stretch;\n border: var(--rc-textarea-border, 1px solid ButtonBorder);\n border-radius: var(--rc-textarea-border-radius, 2px);\n background: var(--rc-textarea-background, Field);\n color: var(--rc-textarea-color, var(--rc-field-text, FieldText));\n overflow: hidden;\n min-height: var(--_rc-textarea-min-height, auto);\n }\n\n #gutter {\n display: none;\n flex-shrink: 0;\n background: var(--rc-textarea-gutter-bg, Canvas);\n color: var(--rc-textarea-gutter-color, GrayText);\n border-inline-end: var(--rc-textarea-gutter-border, 1px solid ButtonBorder);\n overflow: hidden;\n user-select: none;\n }\n\n :host([line-numbers]) #gutter,\n :host([gutter]) #gutter {\n display: block;\n }\n\n #gutter-cells {\n box-sizing: border-box;\n padding-block: var(--rc-textarea-padding-block, 0.5em);\n padding-inline: var(--rc-textarea-padding-inline, 0.5em)\n var(--rc-textarea-gutter-padding-inline-end, 0.75em);\n font-family: var(--rc-textarea-gutter-font-family, var(--rc-textarea-font-family, monospace));\n font-size: var(--rc-textarea-font-size, 1em);\n line-height: var(--rc-textarea-line-height, 1.5);\n text-align: end;\n min-inline-size: var(--rc-textarea-gutter-min-inline-size, 24px);\n }\n\n .gutter-cell {\n display: block;\n min-inline-size: var(--rc-textarea-gutter-min-inline-size, 24px);\n white-space: pre;\n }\n\n .gutter-cell[hidden],\n .line[hidden] {\n display: none;\n }\n\n .gutter-cell-composite {\n display: inline-flex;\n align-items: center;\n gap: var(--rc-textarea-gutter-content-gap, 0.25em);\n }\n\n .gutter-cell-number {\n font-variant-numeric: tabular-nums;\n }\n\n .gutter-cell-content {\n display: inline-flex;\n align-items: center;\n }\n\n .gutter-cell--active {\n position: relative;\n isolation: isolate;\n color: var(--rc-textarea-color, var(--rc-field-text, FieldText));\n }\n\n .gutter-cell--active::before {\n content: '';\n position: absolute;\n z-index: -1;\n inset-block: 0;\n inset-inline-start: calc(-1 * var(--rc-textarea-padding-inline, 0.5em));\n inset-inline-end: calc(-1 * var(--rc-textarea-gutter-padding-inline-end, 0.75em));\n background: var(--rc-textarea-active-line-bg, transparent);\n pointer-events: none;\n }\n\n #editor-area {\n position: relative;\n flex: 1;\n min-width: 0;\n overflow: hidden;\n }\n\n #editor {\n position: relative;\n z-index: 1;\n width: 100%;\n min-height: 100%;\n box-sizing: border-box;\n padding-block: var(--rc-textarea-padding-block, 0.5em);\n padding-inline: var(--rc-textarea-padding-inline, 0.5em);\n font-family: var(--rc-textarea-font-family, monospace);\n font-size: var(--rc-textarea-font-size, 1em);\n line-height: var(--rc-textarea-line-height, 1.5);\n color: var(--rc-textarea-color, var(--rc-field-text, FieldText));\n caret-color: var(--rc-textarea-caret-color, var(--rc-textarea-color, FieldText));\n background: transparent;\n outline: none;\n overflow: auto;\n resize: none;\n white-space: pre;\n word-break: normal;\n overflow-wrap: normal;\n tab-size: 4;\n word-break: normal;\n /* Prevent contenteditable from injecting <div> wrappers on Enter in some browsers */\n -webkit-user-modify: read-write-plaintext-only;\n }\n\n :host([word-wrap]) #editor {\n white-space: pre-wrap;\n overflow-wrap: break-word;\n word-break: normal;\n }\n\n :host([auto-grow]) #editor {\n overflow: visible;\n height: auto;\n }\n\n :host([auto-grow]) #root {\n height: auto;\n }\n\n /* A read-only field keeps its enabled appearance and focus ring; it only\n stops accepting edits. */\n :host([data-readonly]) #editor {\n -webkit-user-modify: read-only;\n }\n\n /* Focus ring on the root when editor is focused */\n #root:has(#editor:focus) {\n outline: var(--rc-textarea-focus-outline, 2px solid Highlight);\n outline-offset: -1px;\n }\n\n /* Slotted textarea is hidden on host upgrade */\n ::slotted(textarea) {\n position: absolute !important;\n width: 1px !important;\n height: 1px !important;\n padding: 0 !important;\n margin: -1px !important;\n overflow: hidden !important;\n clip: rect(0, 0, 0, 0) !important;\n border: 0 !important;\n opacity: 0 !important;\n pointer-events: none !important;\n }\n\n .line {\n position: relative;\n display: block;\n }\n\n :host(:not([word-wrap])) .line {\n inline-size: max-content;\n min-inline-size: 100%;\n }\n\n /* Paint the active row through the editor's inline padding without clipping\n its text or overflowing into adjacent rows. The padding is one length, so\n negating it stays valid, and logical insets follow RTL and vertical text.\n Only the pseudo-element paints, so a translucent color tints the row and\n its bleed evenly instead of doubling over the row itself. */\n .line--active {\n isolation: isolate;\n }\n\n .line--active::before {\n content: '';\n position: absolute;\n z-index: -1;\n inset-block: 0;\n inset-inline: calc(-1 * var(--rc-textarea-padding-inline, 0.5em));\n background: var(--rc-textarea-active-line-bg, transparent);\n pointer-events: none;\n }\n\n /* Error-lens -style end-of-line diagnostic message */\n .line[data-message]::after {\n content: attr(data-message);\n display: inline;\n margin-inline-start: 4ch;\n unicode-bidi: isolate;\n white-space: nowrap;\n pointer-events: none;\n font-size: 0.875em;\n opacity: 0.8;\n font-style: italic;\n }\n\n /* line-direction=\"auto\": a line orders and aligns by its own first strong\n character. Lines without one keep the base direction, which plaintext would\n turn LTR (UAX #9 rule P3). Only the embedding level changes, so padding,\n trailing widgets and the active-line bleed still follow the editor. */\n :host([line-direction='auto']) .line:not(.line--neutral) {\n unicode-bidi: plaintext;\n }\n\n .mark {\n border-radius: 2px;\n }\n\n /* Isolated, so a widget can neither reorder the text around it nor give a\n line its direction. */\n .widget {\n unicode-bidi: isolate;\n display: inline-block;\n user-select: none;\n cursor: default;\n vertical-align: middle;\n }\n`;\n","import { LitElement, html } from 'lit';\nimport type { CSSResultGroup } from 'lit';\nimport { property, query } from 'lit/decorators.js';\n\nimport {\n cssZoom,\n FlowController,\n LocaleController,\n logicalRect,\n NativeChildController,\n numberFormat,\n resolveFlow,\n warnMissingDirectChild,\n} from '@rcarls/rc-common';\nimport { RCDocument, getText } from './document.js';\nimport {\n getSelectionFocusNode,\n saveSelection,\n restoreSelection,\n type SavedSelection,\n} from './selection.js';\nimport { remapDecorations, addDecoration, setDecorations } from './decoration.js';\nimport { matchPatternResults } from './pattern-matcher.js';\nimport type {\n Decoration,\n DecorationInput,\n RCTextareaPlugin,\n RCTextareaPluginAPI,\n TextPattern,\n MarkDecoration,\n FoldDecoration,\n Token,\n} from './types.js';\nimport { generateId } from './types.js';\n\nimport { styles } from './rc-textarea.styles.js';\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'rc-textarea': RCTextarea;\n }\n}\n\ninterface UndoEntry {\n value: string;\n anchorOffset: number;\n focusOffset: number;\n}\n\ninterface FoldBounds {\n from: number;\n to: number;\n anchorEnd: number;\n reveal: () => void;\n}\n\nfunction getFoldBounds(value: string, folds: readonly FoldDecoration[]): FoldBounds[] {\n const lines = value.split('\\n');\n const starts: number[] = [];\n let offset = 0;\n\n for (const line of lines) {\n starts.push(offset);\n offset += line.length + 1;\n }\n\n return folds.flatMap((fold) => {\n if (fold.fromLine < 2 || fold.toLine < fold.fromLine || fold.toLine > lines.length) {\n return [];\n }\n\n /* eslint-disable @typescript-eslint/no-non-null-assertion -- the range check keeps every line index in bounds */\n return [\n {\n from: starts[fold.fromLine - 1]!,\n to: starts[fold.toLine - 1]! + lines[fold.toLine - 1]!.length,\n anchorEnd: starts[fold.fromLine - 2]! + lines[fold.fromLine - 2]!.length,\n reveal: fold.reveal,\n },\n ];\n /* eslint-enable @typescript-eslint/no-non-null-assertion */\n });\n}\n\nconst MAX_UNDO = 100;\n\n/** A letter or directional mark. Digits are weak. */\nconst STRONG_CHARACTER = /[\\p{L}\\u061C\\u200E\\u200F]/u;\n\n/** Strong characters of right-to-left scripts (Hebrew through Arabic Extended, presentation forms, RLM). */\nconst RTL_CHARACTER =\n /[\\u0590-\\u08FF\\uFB1D-\\uFDFF\\uFE70-\\uFEFF\\u061C\\u200F\\u{10800}-\\u{10FFF}\\u{1E800}-\\u{1EFFF}]/u;\n\n/** A letter or digit. A segment with one counts as a word, whatever `isWordLike` says. */\nconst WORD_CHARACTER = /[\\p{L}\\p{N}]/u;\n\n/** Per-character fallback where `Intl.Segmenter` is missing. `_` joins words, as in UAX #29. */\nconst WORD_CHARACTER_FALLBACK = /[\\p{L}\\p{M}\\p{N}_]/u;\n\n/** The direction of the first strong character in `text`, as UAX #9 rule P2 finds it. */\nfunction firstStrongDirection(text: string): 'ltr' | 'rtl' | null {\n let isolateDepth = 0;\n\n for (const character of text) {\n if ('\\u2066\\u2067\\u2068'.includes(character)) {\n isolateDepth += 1;\n\n continue;\n }\n\n if (character === '\\u2069') {\n isolateDepth = Math.max(0, isolateDepth - 1);\n\n continue;\n }\n\n if (isolateDepth === 0 && STRONG_CHARACTER.test(character)) {\n return RTL_CHARACTER.test(character) ? 'rtl' : 'ltr';\n }\n }\n\n return null;\n}\n\nconst wordSegmenters = new Map<string, Intl.Segmenter | null>();\n\n/** A shared word segmenter for `lang`, or `null` where `Intl.Segmenter` is missing. */\nfunction wordSegmenter(lang: string): Intl.Segmenter | null {\n let segmenter = wordSegmenters.get(lang);\n\n if (segmenter === undefined) {\n if (typeof Intl.Segmenter !== 'function') {\n segmenter = null;\n } else {\n try {\n segmenter = new Intl.Segmenter(lang || undefined, { granularity: 'word' });\n } catch {\n segmenter = new Intl.Segmenter(undefined, { granularity: 'word' });\n }\n }\n\n wordSegmenters.set(lang, segmenter);\n }\n\n return segmenter;\n}\n\n/**\n * The word in `line` touching `offset`, preferring the one that starts there.\n * Gecko reports some final Japanese words as not word-like, so any segment\n * with a letter or digit counts.\n */\nfunction wordAt(line: string, offset: number, lang: string): { from: number; to: number } | null {\n const segmenter = wordSegmenter(lang);\n\n if (!segmenter) {\n let from = offset;\n let to = offset;\n\n while (from > 0 && WORD_CHARACTER_FALLBACK.test(line.charAt(from - 1))) {\n from--;\n }\n\n while (to < line.length && WORD_CHARACTER_FALLBACK.test(line.charAt(to))) {\n to++;\n }\n\n return from === to ? null : { from, to };\n }\n\n const segments = segmenter.segment(line);\n\n for (const position of [offset, offset - 1]) {\n if (position < 0 || position >= line.length) {\n continue;\n }\n\n const segment = segments.containing(position);\n\n if (segment && WORD_CHARACTER.test(segment.segment)) {\n return { from: segment.index, to: segment.index + segment.segment.length };\n }\n }\n\n return null;\n}\n\n/**\n * Parse a highlight.js / prism.js -style HTML string (a flat tree of\n * `<span class=\"token ...\">text</span>` elements) into the supported\n * `MarkDecoration` objects.\n *\n * Only `<span>` elements with a non-empty `className` generate decorations;\n * all other nodes (text, non-span elements) are walked for offset accounting\n * only.\n */\nfunction parseDecorationsFromHtml(html: string): Omit<MarkDecoration, 'id'>[] {\n const $tmp = document.createElement('div');\n\n $tmp.innerHTML = html;\n\n const result: Omit<MarkDecoration, 'id'>[] = [];\n let charOffset = 0;\n\n function walk(node: Node): void {\n if (node.nodeType === Node.TEXT_NODE) {\n charOffset += (node as Text).length;\n\n return;\n }\n\n if (!(node instanceof HTMLElement)) {\n return;\n }\n\n const isSpan = node.tagName === 'SPAN' && node.className;\n const startOffset = charOffset;\n\n for (const child of node.childNodes) {\n walk(child);\n }\n\n if (isSpan && charOffset > startOffset) {\n result.push({\n type: 'mark',\n from: startOffset,\n to: charOffset,\n className: node.className,\n });\n }\n }\n\n for (const child of $tmp.childNodes) {\n walk(child);\n }\n\n return result;\n}\n\n/**\n * Textarea wrapper with line decorations, gutter rendering, folding actions, and plugin hooks.\n *\n * Provide a native `<textarea>` as the direct child when the component is\n * editable. Read-only displays may be driven from `value` or `defaultValue`.\n *\n * @see {@link https://richardcarls.github.io/rc-webcomponents/components/rc-textarea rc-textarea docs}\n *\n * @example Basic usage\n * ```html\n * <label for=\"editor\">Source</label>\n * <rc-textarea>\n * <textarea id=\"editor\" name=\"source\"></textarea>\n * </rc-textarea>\n * ```\n *\n * @example Controlled value (JavaScript)\n * ```js\n * const editor = document.querySelector('rc-textarea');\n * editor.value = 'hello world';\n * editor.addEventListener('rc-textarea-change', (e) => {\n * console.log(e.target.value);\n * });\n * ```\n *\n * The slotted `<textarea>` describes the content: its `lang` and `spellcheck` are\n * mirrored onto the editor, and its `dir` sets the editor's base direction (`auto`\n * resolves from the first strong character of the value, else the host's direction).\n * The host's own `lang` stays the interface language, which formats line numbers.\n *\n * @slot - Accepts a native `<textarea>` element for form wiring.\n *\n * @fires rc-textarea-change - Fired when the field value changes\n * @fires rc-textarea-focus - Fired when the field gains focus\n * @fires rc-textarea-blur - Fired when the field loses focus\n * @fires rc-textarea-select - Fired when the selection changes while the editor is focused\n *\n * @csspart root - The outer flex container wrapping the gutter and editor area.\n * @csspart gutter - The gutter column container.\n * @csspart gutter-cells - The gutter's line-label list.\n * @csspart fold-trigger - Native button created by a folding action; style its visual appearance without changing its target or keyboard behavior.\n * @csspart fold-icon - Consumer-supplied icon inside a folding action button, when provided.\n * @csspart editor-area - The container positioning the editor over the slotted textarea.\n * @csspart editor - The contenteditable field surface.\n *\n * @attr line-numbers - Show sequential line numbers in the gutter. Enables the gutter implicitly.\n * @attr gutter - Enable the gutter column without any built-in content.\n * @attr word-wrap - Wrap long lines within the field to prevent horizontal overflow.\n * @attr auto-grow - Allow the field to grow vertically with content to prevent vertical overflow.\n * @attr line-direction - `base` (default) gives every line the editor's base direction; `auto` gives\n * each line the direction of its first strong character, holding lines without one to the base.\n * @attr [data-readonly] - Reflected while the slotted `<textarea>` is `readonly`. The editor stays\n * focusable and selectable, announces `aria-readonly`, and blocks edits.\n * @attr value - Current field value.\n * @attr default-value - Initial uncontrolled value.\n *\n * @cssprop [--rc-textarea-border=1px solid ButtonBorder] - Border around the field\n * @cssprop [--rc-textarea-border-radius=2px] - Border radius of the field\n * @cssprop [--rc-textarea-background=Field] - Background color of the field\n * @cssprop [--rc-textarea-color=var(--rc-field-text, FieldText)] - Text color\n * @cssprop [--rc-textarea-font-family=monospace] - Font family\n * @cssprop [--rc-textarea-font-size=1em] - Font size\n * @cssprop [--rc-textarea-line-height=1.5] - Line height\n * @cssprop [--rc-textarea-padding-block=0.5em] - Block padding of the editor and gutter; any `padding-block` value\n * @cssprop [--rc-textarea-padding-inline=0.5em] - Inline padding on both sides of the editor and before the gutter; one length, which the active line highlight bleeds through\n * @cssprop [--rc-textarea-gutter-min-inline-size=24px] - Minimum width of the gutter, including its padding\n * @cssprop [--rc-textarea-trailing-size=2.5em] - Reserved inline space and minimum block size for trailing controls\n * @cssprop [--rc-textarea-focus-outline=2px solid Highlight] - Focus ring outline\n * @cssprop [--rc-textarea-caret-color=FieldText] - Caret color\n * @cssprop [--rc-textarea-active-line-bg=transparent] - Active line highlight color, including editor and gutter padding\n * @cssprop [--rc-textarea-gutter-bg=Canvas] - Gutter background color\n * @cssprop [--rc-textarea-gutter-color=GrayText] - Gutter text color\n * @cssprop [--rc-textarea-gutter-border=1px solid ButtonBorder] - Gutter right border\n * @cssprop [--rc-textarea-gutter-font-family=var(--rc-textarea-font-family, monospace)] - Gutter font family\n * @cssprop [--rc-textarea-gutter-content-gap=0.25em] - Gap between a retained line number and custom gutter content\n * @cssprop [--rc-textarea-gutter-padding-inline-end=0.75em] - Space between gutter labels and text\n * @cssprop [--rc-line-actions-gap=2px] - Gap between inline line actions; popover actions default to 4px\n * @cssprop [--rc-line-actions-margin-start=6px] - Inline-start margin before line actions\n * @cssprop [--rc-line-action-padding=1px] - Inline line-action padding; popover actions default to 4px 6px\n * @cssprop [--rc-line-action-border=none] - Line-action border; the popover surface defaults to 1px solid ButtonBorder\n * @cssprop [--rc-line-action-border-radius=3px] - Line-action border radius; the popover surface defaults to 4px\n * @cssprop [--rc-line-action-bg=transparent] - Line-action background; the popover surface defaults to Canvas\n * @cssprop [--rc-line-action-color=inherit] - Line-action color; popover actions default to ButtonText\n * @cssprop [--rc-line-action-font-size=1em] - Inline line-action font size; popover actions default to 0.85em\n * @cssprop [--rc-line-action-opacity=0.4] - Resting opacity of inline line actions\n * @cssprop [--rc-line-action-hover-opacity=1] - Hover and focus opacity of inline line actions\n * @cssprop [--rc-line-action-hover-bg=transparent] - Hover and focus background; popover actions default to ButtonFace\n * @cssprop [--rc-line-action-hover-color=inherit] - Hover and focus text color\n * @cssprop [--rc-line-action-shadow=0 2px 8px color-mix(in srgb, CanvasText 15%, transparent)] - Line-action popover shadow\n */\nexport class RCTextarea extends LitElement {\n static override styles: CSSResultGroup = styles;\n static override shadowRootOptions = {\n ...LitElement.shadowRootOptions,\n delegatesFocus: true,\n };\n\n /** Show sequential line numbers in the gutter. Enables the gutter implicitly. */\n @property({ type: Boolean, attribute: 'line-numbers', reflect: true })\n lineNumbers = false;\n\n /**\n * Enable the gutter column without any built-in content.\n *\n * Plugins can populate individual cells via `LineDecoration.gutterContent`.\n * For sequential line numbers use `lineNumbers` / `line-numbers` instead.\n */\n @property({ type: Boolean, attribute: 'gutter', reflect: true })\n gutter = false;\n\n /** Wrap long lines within the field to prevent horizontal overflow. */\n @property({ type: Boolean, attribute: 'word-wrap', reflect: true })\n wordWrap = false;\n\n /** Allow the field to grow vertically with content to prevent vertical overflow. */\n @property({ type: Boolean, attribute: 'auto-grow', reflect: true })\n autoGrow = false;\n\n /**\n * How each line's direction is chosen. `base` gives every line the editor's\n * base direction, which suits code. `auto` gives a line with a letter the\n * direction of its first strong character, for prose that mixes scripts, and\n * holds lines without one (empty, digits, punctuation) to the base direction.\n */\n @property({ attribute: 'line-direction', reflect: true })\n lineDirection: 'auto' | 'base' = 'base';\n\n /**\n * Whether the slotted `<textarea>` is `readonly`. The native control is the\n * source of truth; set `readonly` on it to change this state.\n */\n get readOnly(): boolean {\n return this._readOnly;\n }\n\n private _readOnly = false;\n private _textareaAttributeObserver: MutationObserver | null = null;\n\n /** Declarative plugin hook for framework integrations. */\n @property({ attribute: false })\n get plugin(): RCTextareaPlugin | null {\n return this._pluginProperty;\n }\n\n /** Declarative plugin hook for framework integrations. */\n set plugin(plugin: RCTextareaPlugin | null) {\n const oldPlugin = this._pluginProperty;\n\n if (plugin === oldPlugin) {\n return;\n }\n\n this._pluginProperty = plugin;\n\n // Framework property bindings can run before the element is connected.\n // Mounting at that point adopts plugin sheets before Lit installs its\n // static sheets, so the initial style adoption can be overwritten.\n if (plugin && this.isConnected) {\n this.usePlugin(plugin);\n } else if (!plugin) {\n this.removePlugin();\n }\n\n this.requestUpdate('plugin', oldPlugin);\n }\n\n /**\n * Imperatively set an external layer of decorations. Ideal for reactive frameworks.\n *\n * ```tsx\n * // Solid\n * <rc-textarea decorations={decorations()} />\n *\n * // React 19+\n * <rc-textarea decorations={decorations} />\n * ```\n *\n * Merges with plugin decorations and pattern decorations on every render.\n * Setting this property triggers a new render; setting it to `undefined` or `[]`\n * clears any previously set external decorations.\n */\n @property({ attribute: false })\n get decorations(): DecorationInput[] {\n return this._externalDecorations;\n }\n\n set decorations(value: DecorationInput[] | undefined) {\n this._externalDecorations = value ?? [];\n this.requestUpdate();\n }\n\n @query('#editor')\n protected _$editor!: HTMLElement;\n\n @query('#gutter-cells')\n protected _$gutterCells!: HTMLElement;\n\n @query('slot')\n protected _$slot!: HTMLSlotElement;\n\n private _value = '';\n private _defaultValue: string | undefined;\n private _initialValueResolved = false;\n private _valueSetByHost = false;\n protected _document: RCDocument | null = null;\n protected _$textareaRef: WeakRef<HTMLTextAreaElement> | null = null;\n\n protected readonly _textareaController = new NativeChildController<HTMLTextAreaElement>(this, {\n selector: ':scope > textarea',\n observe: true,\n onChange: ($textarea, $previousTextarea) => this._setupTextarea($textarea, $previousTextarea),\n onMissing: () => {\n if (import.meta.env.DEV) {\n warnMissingDirectChild(this, {\n selector: ':scope > textarea',\n message:\n '[rc-textarea] No direct child <textarea> found. Place a native <textarea> inside <rc-textarea>.',\n });\n }\n },\n });\n\n protected readonly _flowController = new FlowController(this);\n\n /** The interface locale, which formats line numbers. */\n protected readonly _localeController = new LocaleController(this, {\n onChange: () => this._scheduleRender(),\n });\n\n /** Plugin-owned decorations */\n protected _pluginDecorations = new Map<string, Decoration>();\n\n /** Pattern-generated decorations (rebuilt on each value change). */\n protected _patternDecorations: Decoration[] = [];\n\n /** Imperative decorations (set directly via the `decorations` property) */\n private _externalDecorations: DecorationInput[] = [];\n\n /** Registered patterns. */\n protected _patterns = new Map<string, TextPattern>();\n\n protected _plugin: RCTextareaPlugin | null = null;\n private _pluginProperty: RCTextareaPlugin | null = null;\n protected _pluginApi: RCTextareaPluginAPI | null = null;\n\n /** Sequence counter for async plugin safety (discard stale results). */\n protected _pluginSeq = 0;\n\n /** Stylesheets adopted into the shadow root by the active plugin. */\n protected _pluginSheets = new Set<CSSStyleSheet>();\n\n protected _savedSelection: SavedSelection | null = null;\n protected _rafHandle: number | null = null;\n protected _composing = false;\n private _contentAttributesPendingRender = false;\n /** Set by Escape: the next Tab moves focus instead of inserting `\\t`. */\n private _tabMovesFocus = false;\n protected _isRendering = false;\n\n /** The currently highlighted `.line` element (active line). */\n protected _$activeLine: HTMLElement | null = null;\n\n /** Callbacks registered via PluginAPI.onCursorMove(). */\n protected _cursorCallbacks = new Set<(start: number, end: number) => void>();\n\n protected _docSelectionChangeHandler = (): void => {\n if (document.activeElement !== this) {\n return;\n }\n\n this._onSelectionChange();\n };\n\n /** Synthetic undo/redo stack (DOM rebuilds invalidate native undo) */\n protected _undoStack: UndoEntry[] = [];\n protected _undoIndex = -1;\n\n protected _resizeObserver: ResizeObserver | null = null;\n\n protected _gutterBlockAxis: 'x' | 'y' | null = null;\n\n /** Cached per-line gutter labels from the last render — reused by ResizeObserver. */\n protected _gutterLabels: (\n | string\n | HTMLElement\n | null\n | { number: string; content: string | HTMLElement }\n )[] = [];\n\n /** Gutter cells with explicitly accessible plugin controls. */\n protected _accessibleGutterLines = new Set<number>();\n\n /** Collapsed source ranges from the most recent render. */\n protected _foldedRanges: FoldDecoration[] = [];\n\n protected _foldBounds: FoldBounds[] = [];\n\n protected _hiddenGutterLines = new Set<number>();\n\n /**\n * The current field value.\n *\n * Setting this property puts the component into\n * controlled mode (host owns the value, changes are reflected\n * immediately, no change events dispatched)\n */\n @property({ type: String })\n get value(): string {\n return this._value;\n }\n\n set value(val: string) {\n const oldValue = this._value;\n\n if (val === this._value) {\n return;\n }\n\n this._valueSetByHost = true;\n this._initialValueResolved = true;\n this._value = val;\n\n this._syncTextareaValue();\n this._scheduleRender();\n this.requestUpdate('value', oldValue);\n }\n\n /** Initial uncontrolled value. */\n @property({ type: String, attribute: 'default-value' })\n get defaultValue(): string | undefined {\n return this._defaultValue;\n }\n\n set defaultValue(val: string | undefined) {\n const oldValue = this._defaultValue;\n\n this._defaultValue = val;\n\n if (!this._valueSetByHost && !this._initialValueResolved && val !== undefined) {\n this._value = val;\n this._initialValueResolved = true;\n\n this._syncTextareaValue();\n this._scheduleRender();\n }\n\n this.requestUpdate('defaultValue', oldValue);\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n\n // Frameworks may temporarily move a custom element through a disconnected\n // tree while preserving its property values. disconnectedCallback tears\n // down plugin effects and styles; remount the still-assigned declarative\n // plugin when the same element reconnects.\n if (this._pluginProperty && !this._plugin) {\n this.usePlugin(this._pluginProperty);\n }\n\n document.addEventListener('selectionchange', this._docSelectionChangeHandler);\n\n const $textarea = this._$textareaRef?.deref();\n\n if ($textarea) {\n this._observeTextarea($textarea);\n this._syncReadOnly();\n this._syncContentAttributes();\n }\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n\n document.removeEventListener('selectionchange', this._docSelectionChangeHandler);\n\n this._plugin?.destroy?.();\n this._plugin = null;\n this._pluginApi = null;\n\n this._clearPluginSheets();\n\n this._cursorCallbacks.clear();\n this._resizeObserver?.disconnect();\n this._textareaAttributeObserver?.disconnect();\n this._$textareaRef?.deref()?.removeEventListener('invalid', this._onTextareaInvalid);\n\n if (this._rafHandle !== null) {\n cancelAnimationFrame(this._rafHandle);\n\n this._rafHandle = null;\n }\n }\n\n override firstUpdated(): void {\n if (this._$editor) {\n this._document = new RCDocument(this._$editor as HTMLDivElement);\n this._bindEditorEvents(this._$editor);\n this._syncLabel();\n }\n\n this._resizeObserver = new ResizeObserver(() => {\n this._syncGutter();\n this._syncGutterHeights();\n });\n\n this._resizeObserver.observe(this);\n\n // A slotted <textarea> fires slotchange, which calls _onSlotChange →\n // _scheduleRender, but slotchange may not fire when the textarea was\n // present before upgrade; seed the first render here when value or\n // defaultValue was set before upgrade or connection.\n this._syncReadOnly();\n this._syncContentAttributes();\n this._scheduleRender();\n }\n\n override updated(changed: Map<string, unknown>): void {\n if (changed.has('lineNumbers') || changed.has('gutter') || changed.has('lineDirection')) {\n this._scheduleRender();\n }\n\n // FlowController requests an update when the inherited direction changes.\n this._syncContentDirection();\n }\n\n private _observeTextarea($textarea: HTMLTextAreaElement): void {\n this._textareaAttributeObserver ??= new MutationObserver((records) => {\n this._syncReadOnly();\n this._syncContentAttributes();\n\n if (\n records.some((record) => record.attributeName === 'lang' || record.attributeName === 'dir')\n ) {\n if (this._composing) {\n this._contentAttributesPendingRender = true;\n } else {\n this._scheduleRender();\n }\n }\n });\n\n this._textareaAttributeObserver.disconnect();\n\n this._textareaAttributeObserver.observe($textarea, {\n attributes: true,\n attributeFilter: ['readonly', 'lang', 'dir', 'spellcheck'],\n });\n }\n\n /**\n * Mirror the native textarea's content attributes onto the editor. `lang`\n * picks glyphs, the spelling dictionary and word boundaries; `spellcheck`\n * stays off unless the textarea sets it. The host's own `lang` is the\n * interface language and is never copied.\n */\n protected _syncContentAttributes(): void {\n if (!this._$editor) {\n return;\n }\n\n const $textarea = this._$textareaRef?.deref();\n const lang = $textarea?.getAttribute('lang') ?? null;\n\n if (lang === null) {\n this._$editor.removeAttribute('lang');\n } else if (this._$editor.getAttribute('lang') !== lang) {\n this._$editor.setAttribute('lang', lang);\n }\n\n this._$editor.spellcheck = $textarea?.hasAttribute('spellcheck') ? $textarea.spellcheck : false;\n\n this._syncContentDirection();\n }\n\n /**\n * Set the editor's base direction from the textarea's `dir`. `auto` reads\n * the native control's directionality, including its LTR neutral fallback;\n * without `dir` the editor inherits. Composition keeps the current direction\n * so the IME session isn't disturbed.\n */\n protected _syncContentDirection(): void {\n if (!this._$editor || this._composing) {\n return;\n }\n\n const $textarea = this._$textareaRef?.deref();\n const dir = $textarea?.getAttribute('dir')?.toLowerCase();\n let resolved: 'ltr' | 'rtl' | null = null;\n\n if (dir === 'ltr' || dir === 'rtl') {\n resolved = dir;\n } else if (dir === 'auto' && $textarea) {\n resolved = $textarea.matches(':dir(rtl)') ? 'rtl' : 'ltr';\n }\n\n if (resolved === null) {\n this._$editor.removeAttribute('dir');\n } else if (this._$editor.getAttribute('dir') !== resolved) {\n this._$editor.setAttribute('dir', resolved);\n }\n }\n\n /** The textarea's `lang`, or `''` when it sets none. */\n protected _contentLang(): string {\n return this._$textareaRef?.deref()?.getAttribute('lang') ?? '';\n }\n\n /** The editor's resolved base direction. */\n protected _contentDirection(): 'ltr' | 'rtl' {\n return resolveFlow(this._$editor ?? this).rtl ? 'rtl' : 'ltr';\n }\n\n /**\n * Mark lines with no strong character so `line-direction=\"auto\"` holds them\n * to the base direction. Reads the model value, which composition text\n * doesn't reach until `compositionend`, so a composing line keeps its mark.\n */\n protected _syncLineDirections(value: string): void {\n if (!this._$editor) {\n return;\n }\n\n const auto = this.lineDirection === 'auto';\n const lines = value.split('\\n');\n const $lines = this._$editor.querySelectorAll<HTMLElement>(':scope > .line');\n\n for (const [i, $line] of $lines.entries()) {\n $line.classList.toggle(\n 'line--neutral',\n auto && firstStrongDirection(lines[i] ?? '') === null,\n );\n }\n }\n\n /**\n * Mirror the native textarea's `readonly` attribute: the editor stays a\n * focusable, selectable textbox that announces `aria-readonly`, and edits\n * are blocked by the existing input guards.\n */\n protected _syncReadOnly(): void {\n const readOnly = this._$textareaRef?.deref()?.readOnly ?? false;\n const changed = readOnly !== this._readOnly;\n\n this._readOnly = readOnly;\n this.toggleAttribute('data-readonly', readOnly);\n\n if (this._$editor) {\n this._$editor.contentEditable = readOnly ? 'false' : 'true';\n\n if (readOnly) {\n this._$editor.setAttribute('aria-readonly', 'true');\n this._$editor.tabIndex = 0;\n } else {\n this._$editor.removeAttribute('aria-readonly');\n this._$editor.removeAttribute('tabindex');\n }\n }\n\n if (changed) {\n // The plugin transform hook only applies while read-only.\n this._scheduleRender();\n }\n\n if (this._$editor && resolveFlow(this._$editor).block !== this._gutterBlockAxis) {\n this._syncGutterHeights();\n }\n }\n\n override render() {\n return html`\n <div id=\"root\" part=\"root\">\n <div id=\"gutter\" part=\"gutter\" aria-hidden=\"true\">\n <div id=\"gutter-cells\" part=\"gutter-cells\"></div>\n </div>\n\n <div id=\"editor-area\" part=\"editor-area\">\n <div\n id=\"editor\"\n part=\"editor\"\n contenteditable=${this._readOnly ? 'false' : 'true'}\n role=\"textbox\"\n aria-multiline=\"true\"\n spellcheck=\"false\"\n autocorrect=\"off\"\n autocapitalize=\"off\"\n ></div>\n\n <slot @slotchange=${this._onSlotChange}></slot>\n </div>\n </div>\n `;\n }\n\n protected _onSlotChange(): void {\n this._textareaController.sync();\n }\n\n protected _setupTextarea(\n $textarea: HTMLTextAreaElement | null,\n $previousTextarea?: HTMLTextAreaElement | null,\n ): void {\n if ($previousTextarea && $previousTextarea !== $textarea) {\n $previousTextarea.removeEventListener('invalid', this._onTextareaInvalid);\n }\n\n this._textareaAttributeObserver?.disconnect();\n\n if (!$textarea) {\n this._$textareaRef = null;\n this._syncReadOnly();\n this._syncContentAttributes();\n this._scheduleRender();\n\n return;\n }\n\n this._$textareaRef = new WeakRef($textarea);\n\n // Visually hide — keep in DOM for form submission\n Object.assign($textarea.style, {\n position: 'absolute',\n width: '1px',\n height: '1px',\n padding: '0',\n margin: '-1px',\n overflow: 'hidden',\n clip: 'rect(0,0,0,0)',\n border: '0',\n opacity: '0',\n pointerEvents: 'none',\n tabIndex: '-1',\n });\n\n $textarea.setAttribute('aria-hidden', 'true');\n $textarea.tabIndex = -1;\n\n // Sync attributes from textarea → editor ARIA / state\n if (this._$editor) {\n this._syncLabel();\n\n const placeholder = $textarea.getAttribute('placeholder');\n\n if (placeholder) {\n this._$editor.setAttribute('aria-placeholder', placeholder);\n }\n }\n\n // Adopt initial value from textarea after value/defaultValue precedence.\n if (!this._initialValueResolved) {\n this._value = $textarea.value;\n this._initialValueResolved = true;\n } else {\n $textarea.value = this._value;\n }\n\n // Wire up form validation feedback\n $textarea.addEventListener('invalid', this._onTextareaInvalid);\n\n this._observeTextarea($textarea);\n this._syncReadOnly();\n this._syncContentAttributes();\n\n // Sync typography from textarea's computed style to editor\n this._syncTypography($textarea);\n\n this._scheduleRender();\n }\n\n protected _onTextareaInvalid = (): void => {\n if (this._$editor) {\n this._$editor.setAttribute('aria-invalid', 'true');\n }\n };\n\n protected _bindEditorEvents($editor: HTMLElement): void {\n $editor.addEventListener('compositionstart', () => {\n this._composing = true;\n });\n\n $editor.addEventListener('compositionend', () => {\n this._composing = false;\n this._onInput();\n\n if (this._contentAttributesPendingRender) {\n this._contentAttributesPendingRender = false;\n this._syncContentDirection();\n this._scheduleRender();\n }\n });\n\n $editor.addEventListener('beforeinput', this._onBeforeInput);\n $editor.addEventListener('input', this._onInputEvent);\n $editor.addEventListener('keydown', this._onKeyDown);\n $editor.addEventListener('paste', this._onPaste);\n $editor.addEventListener('copy', this._onCopy);\n $editor.addEventListener('cut', this._onCopy);\n\n $editor.addEventListener('focus', () => {\n this.dispatchEvent(\n new CustomEvent('rc-textarea-focus', {\n bubbles: true,\n composed: true,\n }),\n );\n });\n\n $editor.addEventListener('blur', () => {\n this._tabMovesFocus = false;\n\n this.dispatchEvent(\n new CustomEvent('rc-textarea-blur', {\n bubbles: true,\n composed: true,\n }),\n );\n\n // Clear active line when editor loses focus\n this._$activeLine?.classList.remove('line--active');\n this._$activeLine = null;\n });\n\n // Note: Selection tracking is handled by the document-level selectionchange listener\n }\n\n protected _onInputEvent = (): void => {\n if (!this._composing) {\n this._onInput();\n }\n };\n\n protected _onBeforeInput = (event: InputEvent): void => {\n if (this.readOnly || this._isWidgetEvent(event)) {\n return;\n }\n\n if (this._revealFoldForEdit(event.inputType)) {\n event.preventDefault();\n\n return;\n }\n\n // Virtual keyboards may emit no keydown. Keep their browser-generated\n // blocks out of the component's model-owned `.line` document as well.\n if (\n !this._composing &&\n !event.isComposing &&\n (event.inputType === 'insertParagraph' || event.inputType === 'insertLineBreak')\n ) {\n event.preventDefault();\n this._insertText('\\n');\n }\n };\n\n protected _revealFoldAtOffset(offset: number): boolean {\n for (const fold of this._foldBounds) {\n if (offset >= fold.from && offset <= fold.to) {\n fold.reveal();\n\n return true;\n }\n }\n\n return false;\n }\n\n protected _revealFoldForEdit(inputType: string): boolean {\n if (!this._$editor) {\n return false;\n }\n\n const selection = saveSelection(this._$editor) ?? this._savedSelection;\n\n if (!selection) {\n return false;\n }\n\n const start = Math.min(selection.anchorOffset, selection.focusOffset);\n const end = Math.max(selection.anchorOffset, selection.focusOffset);\n\n for (const fold of this._foldBounds) {\n const intersects = start < fold.to && end > fold.from;\n const entersHiddenLine = start === end && start >= fold.from && start <= fold.to;\n const deletesIntoFold =\n start === end &&\n ((inputType.endsWith('Forward') && start === fold.anchorEnd) ||\n (inputType.endsWith('Backward') && start === fold.to + 1));\n const insertsLineIntoFold =\n start === end &&\n start === fold.anchorEnd &&\n (inputType === 'insertParagraph' ||\n inputType === 'insertLineBreak' ||\n inputType === 'insertFromPaste');\n\n if (intersects || entersHiddenLine || deletesIntoFold || insertsLineIntoFold) {\n fold.reveal();\n\n return true;\n }\n }\n\n return false;\n }\n\n protected _onInput(): void {\n if (!this._$editor) {\n return;\n }\n\n const newValue = getText(this._$editor);\n\n if (newValue === this._value) {\n return;\n }\n\n const oldValue = this._value;\n const preEditSelection = this._savedSelection;\n\n // Map existing plugin decorations through the text change\n const mappedDecorations = remapDecorations(\n [...this._pluginDecorations.values()],\n oldValue,\n newValue,\n );\n\n this._pluginDecorations.clear();\n\n for (const decoration of mappedDecorations) {\n this._pluginDecorations.set(decoration.id, decoration);\n }\n\n this._value = newValue;\n this._syncTextareaValue(true);\n\n // Save cursor position after input settles\n this._savedSelection = saveSelection(this._$editor);\n\n // On the very first edit, capture the pre-edit state as the undo baseline\n if (this._undoStack.length === 0) {\n // Note: selectionchange fires AFTER input, so _savedSelection still holds the\n // pre-edit cursor at this point (before saveSelection() overwrites it above).\n this._undoStack.push({\n value: oldValue,\n anchorOffset: preEditSelection?.anchorOffset ?? 0,\n focusOffset: preEditSelection?.focusOffset ?? 0,\n });\n\n this._undoIndex = 0;\n }\n\n // Push to undo stack\n this._pushUndo(this._savedSelection);\n this._dispatchChange(newValue);\n\n this._scheduleRender();\n }\n\n protected _onSelectionChange = (): void => {\n if (!this._$editor) {\n return;\n }\n\n const selection = saveSelection(this._$editor);\n\n if (selection) {\n this._savedSelection = selection;\n\n if (\n selection.anchorOffset === selection.focusOffset &&\n this._revealFoldAtOffset(selection.focusOffset)\n ) {\n return;\n }\n\n this.dispatchEvent(\n new CustomEvent('rc-textarea-select', {\n bubbles: true,\n composed: true,\n detail: {\n selectionStart: selection.anchorOffset,\n selectionEnd: selection.focusOffset,\n },\n }),\n );\n\n this._updateActiveLine();\n\n const start = Math.min(selection.anchorOffset, selection.focusOffset);\n const end = Math.max(selection.anchorOffset, selection.focusOffset);\n\n for (const callback of this._cursorCallbacks) {\n callback(start, end);\n }\n }\n };\n\n protected _updateActiveLine(): void {\n if (!this._$editor) {\n return;\n }\n\n let $line: HTMLElement | null = null;\n let $node = getSelectionFocusNode(this._$editor);\n\n while ($node && $node !== this._$editor) {\n if ($node instanceof HTMLElement && $node.classList.contains('line')) {\n $line = $node;\n\n break;\n }\n\n $node = $node.parentNode;\n }\n\n if ($line === this._$activeLine) {\n return;\n }\n\n this._$activeLine?.classList.remove('line--active');\n this._$activeLine = $line;\n this._$activeLine?.classList.add('line--active');\n\n // Update active line number highlight\n this._updateActiveGutterCell();\n }\n\n protected _updateActiveGutterCell(): void {\n if (!this._$gutterCells) {\n return;\n }\n\n // Find and remove previous active state\n const $previousActive = this._$gutterCells.querySelector('.gutter-cell--active');\n\n if ($previousActive) {\n $previousActive.classList.remove('gutter-cell--active');\n }\n\n // Find line index and highlight corresponding line number\n if (this._$activeLine) {\n if (!this._$editor) {\n return;\n }\n\n const $lines = this._$editor.querySelectorAll('.line');\n\n for (let i = 0; i < $lines.length; i++) {\n if ($lines[i] === this._$activeLine) {\n const $lineNumber = this._$gutterCells.children[i];\n\n if ($lineNumber) {\n $lineNumber.classList.add('gutter-cell--active');\n }\n\n break;\n }\n }\n }\n }\n\n protected _onKeyDown = (e: KeyboardEvent): void => {\n if (this.readOnly || this._isWidgetEvent(e)) {\n return;\n }\n\n // Native contenteditable line breaks do not reliably retain `.line`, so\n // apply physical-keyboard Enter through the plain-text model first.\n if (e.key === 'Enter' && !this._composing && !e.isComposing) {\n e.preventDefault();\n\n if (this._revealFoldForEdit('insertParagraph')) {\n return;\n }\n\n this._insertText('\\n');\n\n return;\n }\n\n // Tab inserts a tab character, so the editor must offer a way out\n // (WCAG 2.1.2): Escape releases the next Tab to move focus, as in\n // CodeMirror, and Shift+Tab always moves focus back.\n if (e.key === 'Escape') {\n this._tabMovesFocus = true;\n\n return;\n }\n\n const tabMovesFocus = this._tabMovesFocus;\n\n this._tabMovesFocus = false;\n\n if (e.key === 'Tab' && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {\n if (tabMovesFocus || this._$editor?.querySelector('.widget:not([aria-hidden])')) {\n return;\n }\n\n e.preventDefault();\n this._insertText('\\t');\n\n return;\n }\n\n const isUndo = (e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey;\n const isRedo =\n ((e.ctrlKey || e.metaKey) && e.key === 'y') ||\n ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'z');\n\n if (isUndo) {\n e.preventDefault();\n this._undo();\n\n return;\n }\n\n if (isRedo) {\n e.preventDefault();\n this._redo();\n }\n };\n\n protected _isWidgetEvent(event: Event): boolean {\n return event\n .composedPath()\n .some(($node) => $node instanceof HTMLElement && $node.classList.contains('widget'));\n }\n\n protected _insertText(text: string): void {\n if (!this._$editor) {\n return;\n }\n\n // Native multiline insertion and empty replacement can leave browser-owned\n // blocks or placeholder breaks. Apply these edits directly to the text model.\n if (text.includes('\\n') || text === '') {\n const selection = saveSelection(this._$editor) ?? this._savedSelection;\n const anchor = Math.min(selection?.anchorOffset ?? 0, selection?.focusOffset ?? 0);\n const focus = Math.max(selection?.anchorOffset ?? 0, selection?.focusOffset ?? 0);\n const oldValue = this._value;\n const newValue = oldValue.slice(0, anchor) + text + oldValue.slice(focus);\n const newCursorOffset = anchor + text.length;\n\n const mappedDecorations = remapDecorations(\n [...this._pluginDecorations.values()],\n oldValue,\n newValue,\n );\n\n this._pluginDecorations.clear();\n\n for (const decoration of mappedDecorations) {\n this._pluginDecorations.set(decoration.id, decoration);\n }\n\n this._value = newValue;\n this._syncTextareaValue(true);\n\n this._savedSelection = {\n anchorOffset: newCursorOffset,\n focusOffset: newCursorOffset,\n };\n\n if (this._undoStack.length === 0) {\n this._undoStack.push({\n value: oldValue,\n anchorOffset: selection?.anchorOffset ?? 0,\n focusOffset: selection?.focusOffset ?? 0,\n });\n\n this._undoIndex = 0;\n }\n\n this._pushUndo(this._savedSelection);\n this._dispatchChange(newValue);\n this._scheduleRender();\n\n return;\n }\n\n // Use execCommand for simple (single-line) insertions — maintains a minimal\n // undo step until our full rebuild fires on the next RAF.\n document.execCommand('insertText', false, text);\n this._onInput();\n }\n\n /**\n * Wrap the current selection with `prefix` and `suffix`.\n * No-op when the selection is collapsed (no text selected).\n *\n * Uses the model path directly (not `execCommand`) because callers such as\n * toolbar buttons move focus away from the editor before this fires, which\n * clears the DOM selection. `_savedSelection` retains the last model-level\n * anchor/focus offsets.\n */\n wrapSelection(prefix: string, suffix: string): void {\n if (!this._$editor) {\n return;\n }\n\n const selection = saveSelection(this._$editor) ?? this._savedSelection;\n\n if (!selection || selection.anchorOffset === selection.focusOffset) {\n return;\n }\n\n const start = Math.min(selection.anchorOffset, selection.focusOffset);\n const end = Math.max(selection.anchorOffset, selection.focusOffset);\n const selected = this._value.slice(start, end);\n const oldValue = this._value;\n const newValue = oldValue.slice(0, start) + prefix + selected + suffix + oldValue.slice(end);\n\n const mappedDecorations = remapDecorations(\n [...this._pluginDecorations.values()],\n oldValue,\n newValue,\n );\n\n this._pluginDecorations.clear();\n\n for (const decoration of mappedDecorations) {\n this._pluginDecorations.set(decoration.id, decoration);\n }\n\n this._value = newValue;\n this._syncTextareaValue(true);\n\n this._savedSelection = {\n anchorOffset: start + prefix.length,\n focusOffset: start + prefix.length + selected.length,\n };\n\n this._pushUndo(this._savedSelection);\n this._dispatchChange(newValue);\n this._scheduleRender();\n }\n\n /**\n * Replace the current selection with `text`.\n * When the selection is collapsed this is equivalent to `insertText`.\n */\n replaceSelection(text: string): void {\n this._insertText(text);\n }\n\n protected _onCopy = (event: ClipboardEvent): void => {\n if (\n !this._$editor ||\n this._isWidgetEvent(event) ||\n !event.clipboardData ||\n (!this._$editor.querySelector('.widget') && this._foldedRanges.length === 0)\n ) {\n return;\n }\n\n const selection = saveSelection(this._$editor);\n\n if (!selection || selection.anchorOffset === selection.focusOffset) {\n return;\n }\n\n const from = Math.min(selection.anchorOffset, selection.focusOffset);\n const to = Math.max(selection.anchorOffset, selection.focusOffset);\n\n event.clipboardData.setData('text/plain', getText(this._$editor).slice(from, to));\n event.preventDefault();\n\n if (event.type === 'cut' && !this.readOnly) {\n this._insertText('');\n }\n };\n\n protected _onPaste = (e: ClipboardEvent): void => {\n if (this.readOnly || this._isWidgetEvent(e)) {\n return;\n }\n\n e.preventDefault();\n\n if (this._revealFoldForEdit('insertFromPaste')) {\n return;\n }\n\n const text = e.clipboardData?.getData('text/plain') ?? '';\n\n if (!text) {\n return;\n }\n\n // Normalize line endings\n const normalized = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n this._insertText(normalized);\n };\n\n /** Reset the undo/redo history. Call when the field receives entirely new content. */\n clearHistory(): void {\n this._undoStack = [];\n this._undoIndex = -1;\n }\n\n protected _pushUndo(sel: SavedSelection | null): void {\n const entry: UndoEntry = {\n value: this._value,\n anchorOffset: sel?.anchorOffset ?? 0,\n focusOffset: sel?.focusOffset ?? 0,\n };\n\n // Truncate redo branch\n this._undoStack = this._undoStack.slice(0, this._undoIndex + 1);\n this._undoStack.push(entry);\n\n if (this._undoStack.length > MAX_UNDO) {\n this._undoStack.shift();\n }\n\n this._undoIndex = this._undoStack.length - 1;\n }\n\n protected _undo(): void {\n const entry = this._undoStack[this._undoIndex - 1];\n\n if (!entry) {\n return;\n }\n\n this._undoIndex--;\n this._applyUndoEntry(entry);\n }\n\n protected _redo(): void {\n const entry = this._undoStack[this._undoIndex + 1];\n\n if (!entry) {\n return;\n }\n\n this._undoIndex++;\n this._applyUndoEntry(entry);\n }\n\n protected _applyUndoEntry(entry: UndoEntry): void {\n this._value = entry.value;\n\n this._savedSelection = {\n anchorOffset: entry.anchorOffset,\n focusOffset: entry.focusOffset,\n };\n\n this._syncTextareaValue(true);\n this._dispatchChange(this._value);\n this._scheduleRender();\n }\n\n /**\n * Register and mount a plugin imperatively.\n * Replaces any currently active plugin. Prefer the `plugin` property for\n * reactive-framework integrations.\n */\n usePlugin(plugin: RCTextareaPlugin): void {\n this._plugin?.destroy?.();\n this._clearPluginSheets();\n this._pluginDecorations.clear();\n this._cursorCallbacks.clear();\n this._pluginSeq++;\n\n this._plugin = plugin;\n this._pluginApi = this._buildPluginApi();\n plugin.mount?.(this._pluginApi);\n\n this._scheduleRender();\n }\n\n /** Unmount the active plugin, clear its decorations, and release its stylesheets. */\n removePlugin(): void {\n this._plugin?.destroy?.();\n this._clearPluginSheets();\n this._plugin = null;\n this._pluginApi = null;\n this._pluginDecorations.clear();\n this._cursorCallbacks.clear();\n this._pluginSeq++;\n this._scheduleRender();\n }\n\n /**\n * Build the `RCTextareaPluginAPI` object passed to the active plugin's\n * `mount()` call. Each getter delegates to the component's live state so the\n * API stays accurate across render frames without needing to be rebuilt.\n */\n protected _buildPluginApi(): RCTextareaPluginAPI {\n // eslint-disable-next-line @typescript-eslint/no-this-alias -- getters below rebind this\n const component = this;\n\n return {\n get host() {\n return component;\n },\n get value() {\n return component._value;\n },\n get selectionStart() {\n const selection = component._savedSelection;\n\n return selection ? Math.min(selection.anchorOffset, selection.focusOffset) : 0;\n },\n get selectionEnd() {\n const selection = component._savedSelection;\n\n return selection ? Math.max(selection.anchorOffset, selection.focusOffset) : 0;\n },\n getCursorRect(): DOMRect | null {\n const selection = window.getSelection();\n\n if (!selection?.focusNode) {\n return null;\n }\n\n if (!component._$editor || !component._$editor.contains(selection.focusNode)) {\n return null;\n }\n\n try {\n const $range = document.createRange();\n\n $range.setStart(selection.focusNode, selection.focusOffset);\n $range.collapse(true);\n\n const rect = $range.getBoundingClientRect();\n\n return rect.height > 0 ? rect : null;\n } catch {\n return null;\n }\n },\n get contentDirection() {\n return component._contentDirection();\n },\n get contentLang() {\n return component._contentLang();\n },\n lineDirection(line: number): 'ltr' | 'rtl' {\n const text = component._value.split('\\n')[line - 1];\n const own =\n component.lineDirection === 'auto' && text !== undefined\n ? firstStrongDirection(text)\n : null;\n\n return own ?? component._contentDirection();\n },\n getWordAtCursor(): { word: string; from: number; to: number } | null {\n const offset = component._savedSelection?.focusOffset ?? 0;\n const text = component._value;\n\n if (!text) {\n return null;\n }\n\n const lineStart = text.lastIndexOf('\\n', offset - 1) + 1;\n const lineEnd = text.indexOf('\\n', offset);\n const line = text.slice(lineStart, lineEnd === -1 ? undefined : lineEnd);\n const word = wordAt(line, offset - lineStart, component._contentLang());\n\n if (!word) {\n return null;\n }\n\n const from = lineStart + word.from;\n const to = lineStart + word.to;\n\n return { word: text.slice(from, to), from, to };\n },\n onCursorMove(callback: (selectionStart: number, selectionEnd: number) => void): () => void {\n component._cursorCallbacks.add(callback);\n\n return () => {\n component._cursorCallbacks.delete(callback);\n };\n },\n\n addDecoration(d: DecorationInput): string {\n return addDecoration(component._pluginDecorations, d);\n },\n removeDecoration(id: string): void {\n component._pluginDecorations.delete(id);\n },\n clearDecorations(): void {\n component._pluginDecorations.clear();\n },\n setDecorations(decorations: DecorationInput[]): void {\n setDecorations(component._pluginDecorations, decorations);\n },\n getDecorations(): readonly Decoration[] {\n return [...component._pluginDecorations.values()];\n },\n scheduleUpdate(): void {\n if (!component._isRendering) {\n component._scheduleRender();\n }\n },\n adoptStyleSheet(sheetOrCssText: CSSStyleSheet | string): CSSStyleSheet {\n let sheet: CSSStyleSheet;\n\n if (typeof sheetOrCssText === 'string') {\n sheet = new CSSStyleSheet();\n sheet.replaceSync(sheetOrCssText);\n } else {\n sheet = sheetOrCssText;\n }\n\n const $shadowRoot = component.shadowRoot;\n\n if ($shadowRoot && !$shadowRoot.adoptedStyleSheets.includes(sheet)) {\n $shadowRoot.adoptedStyleSheets = [...$shadowRoot.adoptedStyleSheets, sheet];\n }\n\n component._pluginSheets.add(sheet);\n\n return sheet;\n },\n removeStyleSheet(sheet: CSSStyleSheet): void {\n const $shadowRoot = component.shadowRoot;\n\n if ($shadowRoot) {\n $shadowRoot.adoptedStyleSheets = $shadowRoot.adoptedStyleSheets.filter(\n (s) => s !== sheet,\n );\n }\n\n component._pluginSheets.delete(sheet);\n },\n parseDecorationsFromHtml(html: string): Omit<MarkDecoration, 'id'>[] {\n return parseDecorationsFromHtml(html);\n },\n decorationsFromTokens(\n tokens: Token[],\n themeMap: Record<string, Omit<MarkDecoration, 'id' | 'type' | 'from' | 'to'>>,\n ): Omit<MarkDecoration, 'id'>[] {\n const result: Omit<MarkDecoration, 'id'>[] = [];\n\n for (const token of tokens) {\n const style = themeMap[token.type];\n\n if (style) {\n result.push({\n type: 'mark',\n from: token.from,\n to: token.to,\n ...style,\n });\n }\n }\n\n return result;\n },\n insertText(text: string): void {\n component._insertText(text);\n },\n wrapSelection(prefix: string, suffix: string): void {\n component.wrapSelection(prefix, suffix);\n },\n replaceSelection(text: string): void {\n component.replaceSelection(text);\n },\n };\n }\n\n protected _clearPluginSheets(): void {\n if (this._pluginSheets.size === 0) {\n return;\n }\n\n const $shadowRoot = this.shadowRoot;\n\n if ($shadowRoot) {\n $shadowRoot.adoptedStyleSheets = $shadowRoot.adoptedStyleSheets.filter(\n (s) => !this._pluginSheets.has(s),\n );\n }\n\n this._pluginSheets.clear();\n }\n\n /**\n * Register a text pattern that generates decorations on every render pass.\n * Returns the pattern ID, which can be passed to `removePattern` to unregister it.\n *\n * @example\n * const id = editor.addPattern({ pattern: /TODO/g, className: 'highlight-todo' });\n * // Later:\n * editor.removePattern(id);\n */\n addPattern(pattern: Omit<TextPattern, 'id'>): string {\n const id = generateId();\n\n this._patterns.set(id, { ...pattern, id });\n this._scheduleRender();\n\n return id;\n }\n\n /** Remove a previously registered pattern by the ID returned from `addPattern`. */\n removePattern(id: string): void {\n this._patterns.delete(id);\n this._scheduleRender();\n }\n\n /** Remove all registered patterns and trigger a re-render. */\n clearPatterns(): void {\n this._patterns.clear();\n this._scheduleRender();\n }\n\n protected _scheduleRender(): void {\n if (this._rafHandle !== null) {\n return;\n }\n\n this._rafHandle = requestAnimationFrame(() => {\n this._rafHandle = null;\n void this._performRender();\n });\n }\n\n protected async _performRender(): Promise<void> {\n if (!this._document) {\n return;\n }\n\n this._isRendering = true;\n\n // Snapshot the sequence counter so we can detect if a newer render was\n // scheduled while we were awaiting an async plugin. If the counters\n // diverge on resume, discard this render's results.\n const renderSeq = ++this._pluginSeq;\n\n try {\n // Resolve display value: apply transform hook (read-only only) before everything else\n let renderValue = this._value;\n\n if (this._plugin && this._pluginApi && this._plugin.transform && this.readOnly) {\n const transformed = this._plugin.transform(this._value, this._pluginApi);\n\n if (typeof transformed === 'string') {\n renderValue = transformed;\n }\n }\n\n // Run pattern matcher\n const { markDecorations: patMarkDecs, lineDecorations: patLineDecs } = matchPatternResults(\n renderValue,\n [...this._patterns.values()],\n );\n\n this._patternDecorations = [\n ...patMarkDecs.map((d) => ({ ...d, id: generateId() })),\n ...patLineDecs.map((d) => ({ ...d, id: generateId() })),\n ];\n\n // Run plugin (update + highlight)\n if (this._plugin && this._pluginApi) {\n const api = this._pluginApi;\n\n if (this._plugin.update) {\n await this._plugin.update(renderValue, api);\n\n if (renderSeq !== this._pluginSeq) {\n return;\n }\n }\n\n if (this._plugin.highlight) {\n const html = await this._plugin.highlight(renderValue, api);\n\n if (renderSeq !== this._pluginSeq) {\n return;\n }\n\n if (typeof html === 'string') {\n const decorations = parseDecorationsFromHtml(html);\n\n // Add parsed decorations on top of existing plugin decorations\n for (const decoration of decorations) {\n addDecoration(this._pluginDecorations, decoration);\n }\n }\n }\n }\n\n // Merge all decoration sources\n const allDecorations: Decoration[] = [\n ...this._pluginDecorations.values(),\n ...this._patternDecorations,\n ...this._externalDecorations.map((d) => ({ ...d, id: generateId() })),\n ];\n\n this._foldedRanges = allDecorations.filter(\n (decoration): decoration is FoldDecoration => decoration.type === 'fold',\n );\n\n this._foldBounds = getFoldBounds(renderValue, this._foldedRanges);\n\n this._hiddenGutterLines = new Set(\n this._foldedRanges.flatMap((fold) =>\n Array.from(\n { length: Math.max(0, fold.toLine - fold.fromLine + 1) },\n (_, index) => fold.fromLine + index,\n ),\n ),\n );\n\n // Rebuild the Parchment tree\n if (!this._$editor) {\n return;\n }\n\n const $focusedWidget = this.shadowRoot?.activeElement;\n // A presentation refresh may run before selectionchange updates the saved\n // offsets. Preserve the live range unless a source edit has queued a new caret.\n let selectionToRestore =\n getText(this._$editor) === renderValue\n ? (saveSelection(this._$editor) ?? this._savedSelection)\n : this._savedSelection;\n\n if (selectionToRestore?.anchorOffset === selectionToRestore?.focusOffset) {\n const focusOffset = selectionToRestore?.focusOffset;\n const hidden = this._foldBounds.filter(\n (fold) => focusOffset !== undefined && focusOffset >= fold.from && focusOffset <= fold.to,\n );\n\n if (hidden.length > 0) {\n const anchorEnd = Math.min(...hidden.map((fold) => fold.anchorEnd));\n\n selectionToRestore = { anchorOffset: anchorEnd, focusOffset: anchorEnd };\n this._savedSelection = selectionToRestore;\n }\n }\n\n this._syncContentDirection();\n this._document.build(renderValue, allDecorations);\n this._syncLineDirections(renderValue);\n\n if (\n $focusedWidget instanceof HTMLElement &&\n $focusedWidget !== this._$editor &&\n $focusedWidget.isConnected &&\n this.shadowRoot?.activeElement !== $focusedWidget\n ) {\n $focusedWidget.focus({ preventScroll: true });\n }\n\n // Restore cursor\n if (selectionToRestore && this.shadowRoot?.activeElement === this._$editor) {\n restoreSelection(this._$editor, selectionToRestore);\n }\n\n // Re-apply active line (DOM was rebuilt; old reference is stale)\n this._$activeLine = null;\n this._updateActiveLine();\n\n // Update gutter\n this._syncGutter(this._computeGutterLabels(allDecorations, renderValue));\n this._syncGutterHeights();\n } finally {\n this._isRendering = false;\n }\n }\n\n /**\n * Compute the label string for each gutter cell based on the current gutter\n * mode (`lineNumbers`, `gutter`) and any\n * `LineDecoration.gutterContent` overrides in `allDecorations`.\n *\n * Returns one entry per line (same length as `value.split('\\n')`):\n * - `string` — the label to display\n * - `null` — render an empty cell\n */\n protected _computeGutterLabels(\n allDecorations: Decoration[],\n value = this._value,\n ): (string | HTMLElement | null | { number: string; content: string | HTMLElement })[] {\n const lines = value.split('\\n');\n\n const overrides = new Map<number, string | HTMLElement | null>();\n\n const accessibleLines = new Set<number>();\n const numberedOverrides = new Set<number>();\n\n for (const dec of allDecorations) {\n if (dec.type === 'line' && dec.gutterContent !== undefined) {\n overrides.set(dec.line, dec.gutterContent);\n\n if (dec.gutterAccessible) {\n accessibleLines.add(dec.line);\n } else {\n accessibleLines.delete(dec.line);\n }\n\n if (dec.gutterLineNumber) {\n numberedOverrides.add(dec.line);\n } else {\n numberedOverrides.delete(dec.line);\n }\n }\n }\n\n this._accessibleGutterLines = accessibleLines;\n\n const lineNumbers = numberFormat(this._localeController.locale, { useGrouping: false });\n\n return lines.map((_, i) => {\n const lineNum = i + 1;\n const content = overrides.get(lineNum);\n\n if (content !== undefined) {\n if (this.lineNumbers && numberedOverrides.has(lineNum) && content !== null) {\n return { number: lineNumbers.format(lineNum), content };\n }\n\n return content;\n }\n\n if (this.lineNumbers) {\n return lineNumbers.format(lineNum);\n }\n\n // `gutter` mode is empty by default, and plugins fill via overrides.\n return null;\n });\n }\n\n /**\n * Synchronize the block size of each gutter cell to match the\n * corresponding `.line` element in the editor.\n *\n * In non-word-wrap mode without block widgets the gutter uses a uniform\n * line height. Wrapped lines and block widgets use per-line heights instead.\n * Also copies the editor's computed block padding to the\n * gutter to compensate for browser UA overrides on contenteditable.\n */\n protected _syncGutterHeights(): void {\n if (!this._$gutterCells || !this._$editor) {\n return;\n }\n\n // Sync block padding from the editor's computed values.\n // Browser UA overrides (Chrome/Firefox on contenteditable) cause 0.5em to\n // resolve to different pixel values on the gutter vs the editor, producing\n // a constant vertical offset.\n const computedStyle = getComputedStyle(this._$editor);\n const paddingBlockStart = computedStyle.paddingBlockStart;\n const paddingBlockEnd = computedStyle.paddingBlockEnd;\n\n if (this._$gutterCells.style.paddingBlockStart !== paddingBlockStart) {\n this._$gutterCells.style.paddingBlockStart = paddingBlockStart;\n }\n\n if (this._$gutterCells.style.paddingBlockEnd !== paddingBlockEnd) {\n this._$gutterCells.style.paddingBlockEnd = paddingBlockEnd;\n }\n\n const $lineEls = this._$editor.querySelectorAll<HTMLElement>('.line');\n const $spans = this._$gutterCells.children;\n const flow = resolveFlow(this._$editor);\n const editorRect = this._$editor.getBoundingClientRect();\n const gutterZoom = cssZoom(this._$gutterCells);\n\n this._gutterBlockAxis = flow.block;\n\n if (!this.wordWrap && !this._$editor.querySelector('.widget--block')) {\n // Chrome UA overrides line-height on contenteditable (even via var() fallback,\n // but not inline styles), giving the editor a different natural cell height\n // than the gutter's CSS 1.5× value. Mirror the first line's actual block size.\n if ($lineEls.length > 0) {\n const lineHeightViewportPx = logicalRect(\n $lineEls[0].getBoundingClientRect(),\n editorRect,\n flow,\n ).blockSize;\n const lineHeight = `${lineHeightViewportPx / gutterZoom}px`;\n\n if (this._$gutterCells.style.lineHeight !== lineHeight) {\n this._$gutterCells.style.lineHeight = lineHeight;\n }\n }\n\n for (let i = 0; i < $spans.length; i++) {\n ($spans[i] as HTMLElement).style.blockSize = '';\n }\n\n return;\n }\n\n // word-wrap: per-span explicit block sizes drive alignment; clear any forced line-height.\n if (this._$gutterCells.style.lineHeight) {\n this._$gutterCells.style.lineHeight = '';\n }\n\n for (let i = 0; i < $lineEls.length && i < $spans.length; i++) {\n const blockSizeViewportPx = logicalRect(\n $lineEls.item(i).getBoundingClientRect(),\n editorRect,\n flow,\n ).blockSize;\n const blockSizeStyle = `${blockSizeViewportPx / gutterZoom}px`;\n const $span = $spans[i] as HTMLElement;\n\n if ($span.style.blockSize !== blockSizeStyle) {\n $span.style.blockSize = blockSizeStyle;\n }\n }\n }\n\n /**\n * Add, remove, or update `.gutter-cell` spans so their count and text\n * content match `labels`. When `labels` is provided the cached\n * `_gutterLabels` is updated first; otherwise the cached labels are reused\n * (called by the `ResizeObserver` without a new render pass).\n */\n protected _syncGutter(\n labels?: (string | HTMLElement | null | { number: string; content: string | HTMLElement })[],\n ): void {\n if (!this.lineNumbers && !this.gutter) {\n return;\n }\n\n if (!this._$gutterCells) {\n return;\n }\n\n if (labels !== undefined) {\n this._gutterLabels = labels;\n }\n\n const current = this._gutterLabels;\n\n const $gutter = this._$gutterCells.parentElement;\n\n if (this._accessibleGutterLines.size > 0) {\n $gutter?.removeAttribute('aria-hidden');\n } else {\n $gutter?.setAttribute('aria-hidden', 'true');\n }\n\n // Sync count\n while (this._$gutterCells.children.length < current.length) {\n const $span = document.createElement('span');\n\n $span.className = 'gutter-cell';\n this._$gutterCells.appendChild($span);\n }\n\n while (this._$gutterCells.children.length > current.length) {\n this._$gutterCells.lastChild?.remove();\n }\n\n // Sync content (only write when changed)\n for (let i = 0; i < current.length; i++) {\n const label = current[i] ?? '';\n const $span = this._$gutterCells.children[i] as HTMLElement;\n\n $span.setAttribute('aria-hidden', String(!this._accessibleGutterLines.has(i + 1)));\n $span.hidden = this._hiddenGutterLines.has(i + 1);\n\n if (typeof label === 'object' && label !== null && !(label instanceof HTMLElement)) {\n let $row = $span.firstElementChild;\n\n if (!$row?.classList.contains('gutter-cell-composite')) {\n $row = document.createElement('span');\n\n $row.className = 'gutter-cell-composite';\n\n const $number = document.createElement('span');\n\n $number.className = 'gutter-cell-number';\n\n const $content = document.createElement('span');\n\n $content.className = 'gutter-cell-content';\n\n $row.append($number, $content);\n $span.replaceChildren($row);\n }\n\n const $number = $row.querySelector(':scope > .gutter-cell-number');\n const $content = $row.querySelector(':scope > .gutter-cell-content');\n\n if (!$number || !$content) {\n continue;\n }\n\n if ($number.textContent !== label.number) {\n $number.textContent = label.number;\n }\n\n if (label.content instanceof HTMLElement) {\n if ($content.firstChild !== label.content) {\n $content.replaceChildren(label.content);\n }\n } else if ($content.textContent !== label.content || $content.firstElementChild) {\n $content.textContent = label.content;\n }\n } else if (label instanceof HTMLElement) {\n if ($span.firstChild !== label) {\n $span.replaceChildren(label);\n }\n } else if ($span.textContent !== label || $span.firstElementChild) {\n $span.textContent = label;\n }\n }\n }\n\n protected _syncLabel(): void {\n if (!this._$editor) {\n return;\n }\n\n const $textarea = this._$textareaRef?.deref();\n\n const ariaLabel = $textarea?.getAttribute('aria-label');\n\n if (ariaLabel) {\n this._$editor.setAttribute('aria-label', ariaLabel);\n\n return;\n }\n\n if ($textarea) {\n const labelText = Array.from($textarea.labels ?? [])\n .map(($l) => $l.textContent?.trim())\n .filter(Boolean)\n .join(' ');\n\n if (labelText) {\n this._$editor.setAttribute('aria-label', labelText);\n\n return;\n }\n }\n\n this._$editor.removeAttribute('aria-label');\n }\n\n protected _syncTypography($textarea: HTMLTextAreaElement): void {\n if (!this._$editor) {\n return;\n }\n\n const textareaStyle = window.getComputedStyle($textarea);\n const props: (keyof CSSStyleDeclaration)[] = [\n 'fontFamily',\n 'fontSize',\n 'fontWeight',\n 'fontStyle',\n 'fontVariant',\n 'lineHeight',\n 'letterSpacing',\n 'wordSpacing',\n 'textIndent',\n 'tabSize',\n ];\n\n // Only copy if the host hasn't set custom properties for these\n const hostStyle = window.getComputedStyle(this);\n\n if (!hostStyle.getPropertyValue('--rc-textarea-font-family')) {\n for (const prop of props) {\n const value = textareaStyle[prop];\n\n if (value && typeof value === 'string') {\n (this._$editor.style as unknown as Record<string, string>)[prop as string] = value;\n }\n }\n }\n }\n\n protected _syncTextareaValue(fromUser = false): void {\n const $textarea = this._$textareaRef?.deref();\n\n if ($textarea) {\n $textarea.value = this._value;\n\n if (fromUser) {\n $textarea.dispatchEvent(new InputEvent('input', { bubbles: true }));\n }\n }\n }\n\n protected _dispatchChange(value: string): void {\n this.dispatchEvent(\n new CustomEvent('rc-textarea-change', {\n bubbles: true,\n composed: true,\n detail: { value },\n }),\n );\n }\n}\n","import type {\n DecorationInput,\n LineDecoratorPlugin,\n MarkDecoration,\n RCTextareaPlugin,\n} from './types.js';\n\nexport interface LineDecoratorPluginOptions {\n /**\n * An array of subscriber setup functions for (e.g., reactive\n * signals).\n *\n * Each function receives a callback and should call it whenever an external\n * value changes . It may return an optional cleanup/unsubscribe function\n * called on plugin destroy.\n *\n * This is intentionally framework-agnostic. For Solid.js signals:\n * ```ts\n * watch: [\n * (cb) => createEffect(on(mySignal, cb, { defer: true })),\n * ]\n * ```\n */\n watch?: Array<(onChange: () => void) => (() => void) | void>;\n\n /**\n * Called once per update pass **after** all per-line decorations are built.\n *\n * Use this to merge in decorations that require the full document value\n * (e.g., diagnostics from a whole-document parser).\n */\n extraDecorations?: (value: string) => DecorationInput[];\n}\n\n/**\n * Factory that wraps a `LineDecoratorPlugin` in a full `RCTextareaPlugin`.\n *\n * Handles the boilerplate that every per-line decorator needs:\n *\n * - CSS injection via `api.adoptStyleSheet` on mount\n * - `lineStart` offset bookkeeping when converting line-relative offsets to\n * absolute document offsets\n * - Subscribing to external change signals and calling `api.scheduleUpdate()`\n * - Cleanup of subscribers on destroy\n *\n * @example\n * ```ts\n * const plugin = createLineDecoratorPlugin(\n * {\n * styles: '.kw { font-weight: bold; }',\n * decorateLine(line) {\n * const results: ReturnType<LineDecoratorPlugin['decorateLine']> = [];\n * for (const m of line.matchAll(/\\bfunction\\b/g)) {\n * results.push({ type: 'mark', from: m.index!, to: m.index! + m[0].length, className: 'kw' });\n * }\n * return results;\n * },\n * },\n * {\n * extraDecorations: (value) => getDiagnosticDecorations(value),\n * },\n * );\n * editor.usePlugin(plugin);\n * ```\n */\nexport function createLineDecoratorPlugin(\n decorator: LineDecoratorPlugin,\n options: LineDecoratorPluginOptions = {},\n): RCTextareaPlugin {\n const cleanups: (() => void)[] = [];\n\n return {\n mount(api) {\n if (decorator.styles) {\n api.adoptStyleSheet(decorator.styles);\n }\n\n for (const subscribe of options.watch ?? []) {\n const cleanup = subscribe(() => api.scheduleUpdate());\n\n if (cleanup) {\n cleanups.push(cleanup);\n }\n }\n },\n\n destroy() {\n for (const cleanup of cleanups) {\n cleanup();\n }\n\n cleanups.length = 0;\n },\n\n update(value, api) {\n const lines = value.split('\\n');\n const decorations: DecorationInput[] = [];\n\n let lineStart = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n for (const decoration of decorator.decorateLine(line, i)) {\n if (decoration.type === 'mark') {\n // Convert line-relative offsets to absolute document offsets\n decorations.push({\n ...(decoration as Omit<MarkDecoration, 'id'>),\n from: lineStart + decoration.from,\n to: lineStart + decoration.to,\n });\n } else {\n // LineDecoration already uses 1-based line numbers — pass through\n decorations.push(decoration);\n }\n }\n\n // +1 for the '\\n'\n lineStart += line.length + 1;\n }\n\n if (options.extraDecorations) {\n decorations.push(...options.extraDecorations(value));\n }\n\n api.setDecorations(decorations);\n },\n };\n}\n","import { isPhysicalReversed, resolveFlow } from '@rcarls/rc-common';\nimport type { RCTextareaPluginAPI, DecorationInput } from './types.js';\n\nexport interface LineAction {\n /** Stable identifier used for action-set change detection. */\n id: string;\n\n /** Human-readable label; used as button text and accessible name. */\n label: string;\n\n /** Icon name passed to `LineActionsOptions.createIcon`, e.g. `'mdi-lock-outline'`. */\n iconName?: string;\n\n /** Called when the action button is activated. */\n onClick: () => void;\n}\n\nexport interface LineActionsOptions {\n /** Where to place the inline widget. Default: `'append'`. */\n position?: 'append';\n\n /**\n * Create and return a DOM element for the given icon name (e.g. `'mdi-lock-outline'`),\n * such as an `<svg>` or an icon custom element. Called when `action.iconName` is set.\n * Return `null` to fall back to text label.\n *\n * @example\n * ```ts\n * createIcon: (name) => {\n * const $icon = document.createElement('iconify-icon');\n * $icon.setAttribute('icon', name);\n * return $icon;\n * }\n * ```\n */\n createIcon?: (iconName: string) => Element | null;\n\n /**\n * Full control over button content. Called instead of the default icon/label\n * logic. Use `createIcon` when you only need to swap the icon renderer —\n * `renderButton` is for cases that require full button customisation.\n */\n renderButton?: (action: LineAction, btn: HTMLButtonElement) => void;\n}\n\n// Constructed once at module level and shared across all controller instances\nconst WIDGET_SHEET = new CSSStyleSheet();\n\nWIDGET_SHEET.replaceSync(`\n .rc-line-actions {\n display: inline-flex;\n align-items: center;\n gap: var(--rc-line-actions-gap, 2px);\n margin-inline-start: var(--rc-line-actions-margin-start, 6px);\n vertical-align: middle;\n }\n .rc-line-action-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n padding: var(--rc-line-action-padding, 1px);\n border: var(--rc-line-action-border, none);\n border-radius: var(--rc-line-action-border-radius, 3px);\n background: var(--rc-line-action-bg, transparent);\n color: var(--rc-line-action-color, inherit);\n font-size: var(--rc-line-action-font-size, 1em);\n cursor: pointer;\n user-select: none;\n line-height: 1;\n opacity: var(--rc-line-action-opacity, 0.4);\n transition: opacity 0.1s;\n }\n .rc-line-action-btn:hover {\n opacity: var(--rc-line-action-hover-opacity, 1);\n background: var(--rc-line-action-hover-bg, transparent);\n color: var(--rc-line-action-hover-color, inherit);\n }\n`);\n\nconst POPOVER_STYLE_ID = 'rc-line-actions-popover-style';\n\nconst POPOVER_STYLES = `\n .rc-line-actions-popover {\n position: fixed;\n z-index: 9999;\n display: flex;\n align-items: center;\n gap: var(--rc-line-actions-gap, 4px);\n padding: 4px 8px;\n background: var(--rc-line-action-bg, Canvas);\n border: var(--rc-line-action-border, 1px solid ButtonBorder);\n border-radius: var(--rc-line-action-border-radius, 4px);\n box-shadow: var(\n --rc-line-action-shadow,\n 0 2px 8px color-mix(in srgb, CanvasText 15%, transparent)\n );\n }\n .rc-line-actions-popover .rc-line-action-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 4px;\n padding: var(--rc-line-action-padding, 4px 6px);\n border: var(--rc-line-action-border, none);\n border-radius: var(--rc-line-action-border-radius, 3px);\n background: var(--rc-line-action-bg, transparent);\n color: var(--rc-line-action-color, ButtonText);\n font-size: var(--rc-line-action-font-size, 0.85em);\n cursor: pointer;\n user-select: none;\n line-height: 1.4;\n white-space: nowrap;\n }\n .rc-line-actions-popover .rc-line-action-btn:hover {\n background: var(--rc-line-action-hover-bg, ButtonFace);\n }\n`;\n\n/**\n * Helper class for plugins that need to show inline action buttons next to a\n * line, or a floating popover panel anchored to the active line.\n *\n * Instantiate in `mount()`, call `getDecorations()` / `getDecorationsForLines()`\n * from `update()`, and call `destroy()` from the plugin's `destroy()`.\n *\n * @example\n * ```ts\n * editor.usePlugin({\n * mount(api) {\n * this._controller = new LineActionsController(api);\n * },\n * update(value, api) {\n * const lineIndex = LineActionsController.getActiveLineIndex(value, api.selectionStart);\n * const decs = this._controller.getDecorations(lineIndex, myActions, value, 'inline');\n * api.setDecorations(decs);\n * },\n * destroy() { this._controller.destroy(); },\n * });\n * ```\n */\nexport class LineActionsController {\n private readonly _api: RCTextareaPluginAPI;\n\n private readonly _options: LineActionsOptions;\n\n private _popover: HTMLDivElement | null = null;\n\n private _lastActionsKey = '';\n\n private readonly _blurHandler: () => void;\n\n constructor(api: RCTextareaPluginAPI, options?: LineActionsOptions) {\n this._api = api;\n this._options = options ?? {};\n\n api.adoptStyleSheet(WIDGET_SHEET);\n\n this._blurHandler = () => this._hidePopover();\n api.host.addEventListener('rc-textarea-blur', this._blurHandler);\n }\n\n /**\n * Call from plugin's `update()`. Pass the line index, its actions, the full\n * value, and the current render mode.\n *\n * - `'inline'`: returns a `WidgetDecoration[]` to merge into `setDecorations()`.\n * - `'popover'`: returns `[]` and manages a floating panel as a side effect.\n *\n * Passing an empty actions array hides the popover and returns `[]`.\n */\n getDecorations(\n lineIndex: number,\n actions: LineAction[],\n value: string,\n renderMode: 'inline' | 'popover',\n ): DecorationInput[] {\n if (renderMode === 'popover') {\n if (actions.length === 0) {\n this._hidePopover();\n } else {\n this._showPopover(actions);\n }\n\n return [];\n }\n\n // inline mode — always hide any lingering popover\n this._hidePopover();\n\n if (actions.length === 0) {\n return [];\n }\n\n const offset = LineActionsController._lineEndOffset(value, lineIndex);\n const actionsSnapshot = [...actions];\n const buttonOptions = {\n renderButton: this._options.renderButton,\n createIcon: this._options.createIcon,\n };\n\n return [\n {\n type: 'widget',\n offset,\n side: 'after',\n create(): HTMLElement {\n return buildWidgetContainer(actionsSnapshot, buttonOptions);\n },\n },\n ];\n }\n\n /**\n * Variant for `showOn: 'always'` — one entry per line with actions.\n *\n * In popover mode only the `activeLineIndex` line is shown; in inline mode\n * every line with non-empty actions gets a widget.\n */\n getDecorationsForLines(\n lineActions: Map<number, LineAction[]>,\n value: string,\n renderMode: 'inline' | 'popover',\n activeLineIndex?: number,\n ): DecorationInput[] {\n if (renderMode === 'popover') {\n if (activeLineIndex === undefined) {\n this._hidePopover();\n\n return [];\n }\n\n const actions = lineActions.get(activeLineIndex) ?? [];\n\n return this.getDecorations(activeLineIndex, actions, value, 'popover');\n }\n\n // inline mode — emit widget for each line that has actions\n this._hidePopover();\n\n const result: DecorationInput[] = [];\n\n for (const [lineIndex, actions] of lineActions) {\n if (actions.length > 0) {\n result.push(...this.getDecorations(lineIndex, actions, value, 'inline'));\n }\n }\n\n return result;\n }\n\n /** Remove the floating panel and detach all listeners. Call from plugin `destroy()`. */\n destroy(): void {\n this._hidePopover();\n this._api.host.removeEventListener('rc-textarea-blur', this._blurHandler);\n }\n\n /** Derive the 0-based line index from a plain-text character offset. */\n static getActiveLineIndex(value: string, selectionStart: number): number {\n return value.slice(0, selectionStart).split('\\n').length - 1;\n }\n\n /**\n * Character offset of the end of the given 0-based line (points at the\n * newline character, or end-of-string for the last line).\n */\n private static _lineEndOffset(value: string, lineIndex: number): number {\n const lines = value.split('\\n');\n let offset = 0;\n\n for (const line of lines.slice(0, lineIndex)) {\n // +1 for the '\\n'\n offset += line.length + 1;\n }\n\n return offset + (lines[lineIndex]?.length ?? 0);\n }\n\n private _showPopover(actions: LineAction[]): void {\n const actionsKey = actions.map((a) => a.id).join(',');\n\n // Inject global popover styles once per document\n if (!document.getElementById(POPOVER_STYLE_ID)) {\n const $style = document.createElement('style');\n\n $style.id = POPOVER_STYLE_ID;\n $style.textContent = POPOVER_STYLES;\n\n document.head.appendChild($style);\n }\n\n // Create the panel element if it does not exist yet\n if (!this._popover) {\n this._popover = document.createElement('div');\n this._popover.className = 'rc-line-actions-popover';\n this._popover.addEventListener('mousedown', (e) => e.preventDefault());\n\n document.body.appendChild(this._popover);\n }\n\n // Rebuild button contents only when the set of actions changes\n if (actionsKey !== this._lastActionsKey) {\n this._lastActionsKey = actionsKey;\n this._popover.innerHTML = '';\n\n buildPopoverButtons(this._popover, actions, this._options);\n }\n\n this._positionPopover();\n }\n\n private _positionPopover(): void {\n if (!this._popover) {\n return;\n }\n\n const cursorRect = this._api.getCursorRect();\n const hostRect = this._api.host.getBoundingClientRect();\n const panelHeight = this._popover.offsetHeight || 32;\n\n let top: number;\n\n if (cursorRect) {\n top = cursorRect.bottom + 4;\n\n if (top + panelHeight > window.innerHeight) {\n top = cursorRect.top - panelHeight - 4;\n }\n } else {\n top = hostRect.bottom + 4;\n }\n\n const panelWidth = this._popover.offsetWidth || 120;\n\n // Aligned to the host's inline start: its right edge in RTL.\n const startsRight = isPhysicalReversed('x', resolveFlow(this._api.host));\n\n let left = startsRight ? hostRect.right - panelWidth : hostRect.left;\n\n left = Math.min(left, window.innerWidth - panelWidth - 8);\n left = Math.max(left, 8);\n\n this._popover.style.top = `${top}px`;\n this._popover.style.left = `${left}px`;\n }\n\n private _hidePopover(): void {\n if (this._popover) {\n this._popover.remove();\n this._popover = null;\n this._lastActionsKey = '';\n }\n }\n}\n\nfunction buildButton(\n action: LineAction,\n options: Pick<LineActionsOptions, 'renderButton' | 'createIcon'>,\n): HTMLButtonElement {\n const $btn = document.createElement('button');\n\n $btn.className = 'rc-line-action-btn';\n $btn.type = 'button';\n $btn.setAttribute('title', action.label);\n\n if (options.renderButton) {\n options.renderButton(action, $btn);\n } else if (action.iconName) {\n const $icon = options.createIcon?.(action.iconName) ?? null;\n\n if ($icon) {\n $btn.setAttribute('aria-label', action.label);\n $btn.appendChild($icon);\n } else {\n // Fallback: data-icon attribute for hosts that process it externally\n $btn.dataset['icon'] = action.iconName;\n $btn.setAttribute('aria-label', action.label);\n }\n } else {\n $btn.textContent = action.label;\n }\n\n $btn.addEventListener('mousedown', (e) => e.preventDefault());\n $btn.addEventListener('click', () => action.onClick());\n\n return $btn;\n}\n\nfunction buildWidgetContainer(\n actions: LineAction[],\n options: Pick<LineActionsOptions, 'renderButton' | 'createIcon'>,\n): HTMLElement {\n const $container = document.createElement('span');\n\n $container.className = 'rc-line-actions';\n\n for (const action of actions) {\n $container.appendChild(buildButton(action, options));\n }\n\n return $container;\n}\n\nfunction buildPopoverButtons(\n $panel: HTMLDivElement,\n actions: LineAction[],\n options: Pick<LineActionsOptions, 'renderButton' | 'createIcon'>,\n): void {\n for (const action of actions) {\n $panel.appendChild(buildButton(action, options));\n }\n}\n"],"names":["Scope","Scope2","Attributor","attrName","keyName","options","attributeBit","node","item","value","_node","ParchmentError","message","_Registry","bubble","parentNode","scroll","input","match2","blotClass","blot","query","scope","name","definitions","definition","isBlot","isAttr","key","tagName","tag","Registry","match","prefix","ClassAttributor","ClassAttributor$1","camelize","parts","rest","part","StyleAttributor","StyleAttributor$1","AttributorStore","domNode","attribute","attributes","classes","styles","attr","target","AttributorStore$1","_ShadowBlot","rawValue","index","length","parent","def","ref","root","_context","replacement","_force","_mutations","wrapper","ShadowBlot","_LeafBlot","_domNode","offset","_inclusive","LeafBlot","LeafBlot$1","LinkedList","nodes","next","cur","refNode","curNode","ret","inclusive","callback","startNode","curIndex","curLength","memo","makeAttachedBlot","found","child","_ParentBlot","other","err","childLength","criteria","descendants","lengthLeft","childIndex","done","childBlot","refBlot","refDomNode","targetParent","context","position","force","after","_length","split","mutations","addedNodes","removedNodes","mutation","a","b","ParentBlot","ParentBlot$1","isEqual","obj1","obj2","prop","_InlineBlot","format","formats","InlineBlot","InlineBlot$1","_BlockBlot","BlockBlot","BlockBlot$1","_ContainerBlot","ContainerBlot","ContainerBlot$1","EmbedBlot","_scroll","EmbedBlot$1","OBSERVER_CONFIG","MAX_OPTIMIZE_ITERATIONS","_ScrollBlot","registry","mutationsMap","records","mark","markParent","optimize","remaining","i","grandChild","ScrollBlot","ScrollBlot$1","_TextBlot","_RCScrollBlot","_contextOrMutations","RCScrollBlot","_RCBlockBlot","RCBlockBlot","_RCInlineBlot","$el","applyInlineFormats","RCInlineBlot","cls","_RCWidgetBlot","RCWidgetBlot","createRegistry","buildLineContent","$line","lineText","lineStart","markDecorations","widgetDecorations","widget","createWidget","boundarySet","decoration","localOffset","boundaries","segmentStart","segmentEnd","segment","bestDecoration","bestSize","localFrom","localTo","size","$span","attrValue","RCDocument","$documentRoot","decorations","lines","$lines","lineDecorationsMap","foldedLines","lineDecorations","line","lineStartOffset","lineNum","lineEnd","marks","d","widgets","folded","signature","_id","$existing","getLineText","$block","diagnostics","text","getText","$editorEl","$lineEl","extractRawText","getNodeText","result","firstBlock","textModelLength","$node","len","$child","domToTextOffset","$root","$targetNode","targetNodeOffset","totalOffset","lineIdx","walkForOffset","currentOffset","$children","textOffsetToDom","targetOffset","lineLen","pos","walkToOffset","$textNode","readNativeSelectionEndpoints","selection","$range","readSelectionEndpoints","$rootNode","getShadowSelection","shadowEndpoints","globalSelection","globalEndpoints","$composedRange","getSelectionFocusNode","saveSelection","endpoints","restoreSelection","saved","anchor","focus","range","generateId","findEdit","oldValue","newValue","start","oldEnd","newEnd","remapMarkRange","from","to","edit","editEnd","delta","newFrom","newTo","countNewlinesBefore","count","mapDecorationsThroughChange","removedText","insertedText","linesRemoved","lineDelta","editStartLine","editEndLine","mapped","docoration","isLargeChange","changeSize","remapDecorations","addDecoration","map","id","setDecorations","inputs","matchPatternResults","patterns","pattern","flags","regex","groupIndices","groupName","style","groupStart","groupEnd","lineInput","css","getFoldBounds","folds","starts","fold","MAX_UNDO","STRONG_CHARACTER","RTL_CHARACTER","WORD_CHARACTER","WORD_CHARACTER_FALLBACK","firstStrongDirection","isolateDepth","character","wordSegmenters","wordSegmenter","lang","segmenter","wordAt","segments","parseDecorationsFromHtml","html","$tmp","charOffset","walk","isSpan","startOffset","_RCTextarea","LitElement","NativeChildController","$textarea","$previousTextarea","FlowController","LocaleController","event","end","e","tabMovesFocus","isUndo","isRedo","normalized","plugin","oldPlugin","val","changed","record","dir","resolved","resolveFlow","auto","readOnly","placeholder","$editor","inputType","intersects","entersHiddenLine","deletesIntoFold","insertsLineIntoFold","preEditSelection","mappedDecorations","$previousActive","$lineNumber","newCursorOffset","suffix","selected","sel","entry","component","rect","word","sheetOrCssText","sheet","$shadowRoot","s","tokens","themeMap","token","renderSeq","renderValue","transformed","patMarkDecs","patLineDecs","api","allDecorations","_","$focusedWidget","selectionToRestore","focusOffset","hidden","anchorEnd","overrides","accessibleLines","numberedOverrides","dec","lineNumbers","numberFormat","content","computedStyle","paddingBlockStart","paddingBlockEnd","$lineEls","$spans","flow","editorRect","gutterZoom","cssZoom","lineHeight","logicalRect","blockSizeStyle","labels","current","$gutter","label","$row","$number","$content","ariaLabel","labelText","$l","textareaStyle","props","fromUser","RCTextarea","__decorateClass","property","createLineDecoratorPlugin","decorator","cleanups","subscribe","cleanup","WIDGET_SHEET","POPOVER_STYLE_ID","POPOVER_STYLES","LineActionsController","lineIndex","actions","renderMode","actionsSnapshot","buttonOptions","buildWidgetContainer","lineActions","activeLineIndex","selectionStart","actionsKey","$style","buildPopoverButtons","cursorRect","hostRect","panelHeight","top","panelWidth","left","isPhysicalReversed","buildButton","action","$btn","$icon","$container","$panel"],"mappings":";;;AAAA,IAAIA,IAAyB,kBAACC,OAAYA,EAAOA,EAAO,OAAO,CAAC,IAAI,QAAQA,EAAOA,EAAO,QAAQ,EAAE,IAAI,SAASA,EAAOA,EAAO,YAAY,EAAE,IAAI,aAAaA,EAAOA,EAAO,OAAO,EAAE,IAAI,QAAQA,EAAOA,EAAO,SAAS,CAAC,IAAI,UAAUA,EAAOA,EAAO,QAAQ,EAAE,IAAI,SAASA,EAAOA,EAAO,aAAa,EAAE,IAAI,cAAcA,EAAOA,EAAO,cAAc,CAAC,IAAI,eAAeA,EAAOA,EAAO,kBAAkB,CAAC,IAAI,mBAAmBA,EAAOA,EAAO,mBAAmB,CAAC,IAAI,oBAAoBA,EAAOA,EAAO,MAAM,EAAE,IAAI,OAAOA,IAASD,KAAS,EAAE;AAClhB,MAAME,EAAW;AAAA,EACf,YAAYC,GAAUC,GAASC,IAAU,CAAA,GAAI;AAC3C,SAAK,WAAWF,GAAU,KAAK,UAAUC;AACzC,UAAME,IAAeN,EAAM,OAAOA,EAAM;AACxC,SAAK,QAAQK,EAAQ,SAAS;AAAA;AAAA,MAE5BA,EAAQ,QAAQL,EAAM,QAAQM;AAAA,QAC5BN,EAAM,WAAWK,EAAQ,aAAa,SAAS,KAAK,YAAYA,EAAQ;AAAA,EAC9E;AAAA,EACA,OAAO,KAAKE,GAAM;AAChB,WAAO,MAAM,KAAKA,EAAK,UAAU,EAAE,IAAI,CAACC,MAASA,EAAK,IAAI;AAAA,EAC5D;AAAA,EACA,IAAID,GAAME,GAAO;AACf,WAAO,KAAK,OAAOF,GAAME,CAAK,KAAKF,EAAK,aAAa,KAAK,SAASE,CAAK,GAAG,MAAM;AAAA,EACnF;AAAA,EACA,OAAOC,GAAOD,GAAO;AACn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