@rcarls/rc-textarea 0.3.0 → 0.3.1

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.
@@ -2136,13 +2136,13 @@ b([
2136
2136
  y({ attribute: !1 })
2137
2137
  ], _.prototype, "decorations", 1);
2138
2138
  b([
2139
- tt("#editor", !0)
2139
+ tt("#editor")
2140
2140
  ], _.prototype, "_$editor", 2);
2141
2141
  b([
2142
- tt("#gutter-cells", !0)
2142
+ tt("#gutter-cells")
2143
2143
  ], _.prototype, "_$gutterCells", 2);
2144
2144
  b([
2145
- tt("slot", !0)
2145
+ tt("slot")
2146
2146
  ], _.prototype, "_$slot", 2);
2147
2147
  b([
2148
2148
  y({ type: String })
@@ -2372,4 +2372,4 @@ export {
2372
2372
  we as c,
2373
2373
  ce as m
2374
2374
  };
2375
- //# sourceMappingURL=line-actions-controller-ChmbiQ-G.js.map
2375
+ //# sourceMappingURL=line-actions-controller-x4P2Yjd4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"line-actions-controller-x4P2Yjd4.js","sources":["../src/rc-textarea.styles.ts","../../../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.ts","../src/line-decorator.ts","../src/line-actions-controller.ts"],"sourcesContent":["import { css } from 'lit';\n\nexport const styles = css`\n :host {\n display: block;\n box-sizing: border-box;\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-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-right: var(--rc-textarea-gutter-border, 1px solid ButtonBorder);\n overflow: hidden;\n user-select: none;\n }\n\n :host([line-numbers]) #gutter,\n :host([list-numbers]) #gutter,\n :host([gutter]) #gutter {\n display: block;\n }\n\n #gutter-cells {\n padding: var(--rc-textarea-padding, 0.5em);\n padding-inline-end: var(--rc-textarea-gutter-padding-inline-end, 0.75em);\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 text-align: right;\n min-width: 2.5ch;\n }\n\n .gutter-cell {\n display: block;\n white-space: pre;\n }\n\n .gutter-cell--active {\n color: var(--rc-textarea-color, var(--rc-text, FieldText));\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: var(--rc-textarea-padding, 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-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 :host([read-only]) #root {\n border: none;\n background: transparent;\n border-radius: 0;\n }\n\n :host([read-only]) #editor {\n cursor: default;\n padding: 0;\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 /* Active line highlight — opt-in via CSS custom property. */\n .line--active {\n background: var(--rc-textarea-active-line-bg, transparent);\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-left: 4ch;\n white-space: nowrap;\n pointer-events: none;\n font-size: 0.875em;\n opacity: 0.8;\n font-style: italic;\n }\n\n .mark {\n border-radius: 2px;\n }\n\n .widget {\n display: inline-block;\n user-select: none;\n cursor: default;\n vertical-align: middle;\n }\n`;\n","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';\nimport type { MarkDecoration } from './types.ts';\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.ts';\nimport type { Decoration, MarkDecoration, LineDecoration, WidgetDecoration } from './types.ts';\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 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 for (let i = 0; i < boundaries.length - 1; i++) {\n const segmentStart = boundaries[i]!;\n const segmentEnd = boundaries[i + 1]!;\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 $span.appendChild(decoration.create());\n\n return $span;\n}\n\nexport class RCDocument {\n private readonly scroll: RCScrollBlot;\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\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 {\n widgetDecorations.push(decoration);\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 (let i = 0; i < lines.length; i++) {\n const lineText = lines[i]!;\n const lineNum = i + 1;\n const lineStart = lineStartOffset;\n const lineEnd = lineStart + lineText.length;\n\n // Reuse an existing line element when available, otherwise create a new one.\n let $block: HTMLElement;\n\n if (i < $lines.length) {\n $block = $lines[i]!;\n\n // Remove all attributes so stale class names, data-*, and title don't bleed through\n while ($block.attributes.length > 0) {\n $block.removeAttribute($block.attributes[0]!.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 const lineDecorations = lineDecorationsMap.get(lineNum) ?? [];\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 const marks = markDecorations.filter((d) => d.from < lineEnd && d.to > lineStart);\n const widgets = widgetDecorations.filter((d) => d.offset >= lineStart && d.offset <= lineEnd);\n\n buildLineContent($block, lineText, lineStart, marks, widgets);\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.removeChild($documentRoot.lastChild!);\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 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\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 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 for (let lineIdx = 0; lineIdx < $lines.length; lineIdx++) {\n if (lineIdx > 0) {\n totalOffset++; // \\n between lines\n }\n\n const $line = $lines[lineIdx]!;\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 for (let i = 0; i < targetNodeOffset && i < $children.length; i++) {\n offset += textModelLength($children[i]!);\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 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 for (let i = 0; i < $lines.length; i++) {\n if (i > 0) {\n if (localOffset === 0) {\n // Position at boundary between lines — place at start of this line\n const $line = $lines[i]!;\n\n return { node: $line, offset: 0 };\n }\n\n localOffset--; // consume the \\n\n }\n\n const $line = $lines[i]!;\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 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\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 $rootNode = $root.getRootNode();\n const selection =\n (\n $rootNode as unknown as { /* Chrome 53+ */ getSelection?: () => Selection | null }\n ).getSelection?.() ?? window.getSelection();\n\n if (!selection || selection.rangeCount === 0) {\n return null;\n }\n\n const range = selection.getRangeAt(0);\n\n if (!$root.contains(range.commonAncestorContainer)) {\n return null;\n }\n\n const anchorOffset = domToTextOffset($root, range.startContainer, range.startOffset);\n const focusOffset = domToTextOffset($root, range.endContainer, range.endOffset);\n\n return { anchorOffset, focusOffset };\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 text for this line.\n *\n * - `string` — custom label (e.g. `\"!\"`, `\"▶\"`)\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 | null;\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 /** Factory called each render cycle. Must return a new element each time. */\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\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;\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\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 * 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 * @returns the word and its `[from, to)` offsets, or `null` if the cursor is\n * not on a word character (`\\w` — alphanumeric + underscore)\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 * @deprecated Use `parseDecorationsFromHtml` instead.\n */\n decorationsFromHtml(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` in\n * read-only mode.\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.ts';\n\nexport { generateId } from './types.ts';\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 *\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 {\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 }\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 map.set(id, { ...input, id } as Decoration);\n }\n}\n\nexport type { MarkDecoration, LineDecoration };\n","import type { TextPattern, MarkDecoration, LineDecoration } from './types.ts';\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 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 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 { LitElement, html } from 'lit';\nimport type { CSSResultGroup } from 'lit';\nimport { property, query } from 'lit/decorators.js';\nimport { NativeChildController, warnMissingDirectChild } from '@rcarls/rc-common';\n\nimport { styles } from './rc-textarea.styles.ts';\nimport { RCDocument, getText } from './document.ts';\nimport { saveSelection, restoreSelection, type SavedSelection } from './selection.ts';\nimport { remapDecorations, addDecoration, setDecorations } from './decoration.ts';\nimport { matchPatternResults } from './pattern-matcher.ts';\n\nimport type {\n Decoration,\n DecorationInput,\n RCTextareaPlugin,\n RCTextareaPluginAPI,\n TextPattern,\n MarkDecoration,\n Token,\n} from './types.ts';\nimport { generateId } from './types.ts';\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\nconst MAX_UNDO = 100;\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 $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, inline widgets, 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 * @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-blur - Fired when the field loses focus\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=FieldText] - Text color; falls back through --rc-text\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=0.5em] - Padding inside the field area\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\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 */\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 * @deprecated Use a plugin with `LineDecoration.gutterContent` to implement\n * sparse line numbering. This property will be removed before v1.0.\n */\n @property({ type: Boolean, attribute: 'list-numbers', reflect: true })\n get listNumbers(): boolean {\n return this._listNumbers;\n }\n\n set listNumbers(value: boolean) {\n if (value) {\n console.warn(\n '[rc-textarea] `listNumbers` / `list-numbers` is deprecated and will be removed before v1.0. ' +\n 'Use a plugin with `LineDecoration.gutterContent` to implement sparse line numbering.',\n );\n }\n\n const old = this._listNumbers;\n\n this._listNumbers = value;\n this.requestUpdate('listNumbers', old);\n }\n\n private _listNumbers = 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 /** Disable editing. The field renders as a styled read-only display. */\n @property({ type: Boolean, attribute: 'read-only', reflect: true })\n readOnly = false;\n\n /**\n * @deprecated Set `aria-label` on the slotted `<textarea>` instead, or\n * associate a `<label>` element via its `for`/`id` pair. This property\n * will be removed before v1.0.\n */\n @property({ type: String })\n get label(): string | null {\n return this._label;\n }\n\n set label(value: string | null) {\n if (value) {\n console.warn(\n '[rc-textarea] `label` is deprecated and will be removed before v1.0. ' +\n 'Set `aria-label` on the slotted `<textarea>`, or associate a `<label>` ' +\n 'element via its `for`/`id` pair instead.',\n );\n }\n\n const old = this._label;\n\n this._label = value;\n\n this.requestUpdate('label', old);\n }\n\n private _label: string | 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 if (plugin) {\n this.usePlugin(plugin);\n } else {\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 private _document: RCDocument | null = null;\n private _$textareaRef: WeakRef<HTMLTextAreaElement> | null = null;\n\n private readonly _textareaController = new NativeChildController<HTMLTextAreaElement>(this, {\n selector: ':scope > textarea',\n observe: true,\n onChange: ($textarea, $previousTextarea) =>\n this._setupTextarea($textarea, $previousTextarea),\n onMissing: () => {\n if (import.meta.env.DEV && !this.readOnly) {\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 /** Plugin-owned decorations */\n protected _pluginDecorations = new Map<string, Decoration>();\n\n /** Pattern-generated decorations (rebuilt on each value change). */\n private _patternDecorations: Decoration[] = [];\n\n /** Imperative decorations (set directly via the `decorations` property) */\n private _externalDecorations: DecorationInput[] = [];\n\n /** Registered patterns. */\n private _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 private _pluginSeq = 0;\n\n /** Stylesheets adopted into the shadow root by the active plugin. */\n private _pluginSheets = new Set<CSSStyleSheet>();\n\n protected _savedSelection: SavedSelection | null = null;\n private _rafHandle: number | null = null;\n private _composing = false;\n private _isRendering = false;\n\n /** The currently highlighted `.line` element (active line). */\n private _$activeLine: HTMLElement | null = null;\n\n /** Callbacks registered via PluginAPI.onCursorMove(). */\n private _cursorCallbacks = new Set<(start: number, end: number) => void>();\n\n private _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 private _undoStack: UndoEntry[] = [];\n private _undoIndex = -1;\n\n private _resizeObserver: ResizeObserver | null = null;\n\n /** Cached per-line gutter labels from the last render — reused by ResizeObserver. */\n private _gutterLabels: (string | null)[] = [];\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 })\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 document.addEventListener('selectionchange', this._docSelectionChangeHandler);\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._$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 }\n\n this._resizeObserver = new ResizeObserver(() => {\n this._syncGutter();\n this._syncGutterHeights();\n });\n\n this._resizeObserver.observe(this);\n\n // In editable mode a slotted <textarea> fires slotchange, which calls\n // _onSlotChange → _scheduleRender. In read-only mode no textarea is\n // required, so slotchange may never fire; call _scheduleRender here to seed\n // the first render when value/defaultValue was set before upgrade or connection.\n this._scheduleRender();\n }\n\n override updated(changed: Map<string, unknown>): void {\n if (changed.has('readOnly')) {\n if (this._$editor) {\n this._$editor.contentEditable = this.readOnly ? 'false' : 'true';\n }\n\n this._syncGutterHeights();\n this._textareaController.sync();\n }\n\n if (changed.has('label')) {\n this._syncLabel();\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 private _onSlotChange(): void {\n this._textareaController.sync();\n }\n\n private _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 if (!$textarea) {\n this._$textareaRef = null;\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 // Sync typography from textarea's computed style to editor\n this._syncTypography($textarea);\n\n this._scheduleRender();\n }\n\n private _onTextareaInvalid = (): void => {\n if (this._$editor) {\n this._$editor.setAttribute('aria-invalid', 'true');\n }\n };\n\n private _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\n $editor.addEventListener('input', this._onInputEvent);\n $editor.addEventListener('keydown', this._onKeyDown);\n $editor.addEventListener('paste', this._onPaste);\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.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 private _onInputEvent = (): void => {\n if (!this._composing) {\n this._onInput();\n }\n };\n\n private _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 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 private _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 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 private _updateActiveLine(): void {\n if (!this._$editor) {\n return;\n }\n\n const selection =\n (\n this.shadowRoot as unknown as { /* (Chrome 53+) */ getSelection?: () => Selection | null }\n ).getSelection?.() ?? window.getSelection();\n\n let $line: HTMLElement | null = null;\n\n if (selection?.focusNode && this._$editor.contains(selection.focusNode)) {\n let node: Node | null = selection.focusNode;\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\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 private _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 private _onKeyDown = (e: KeyboardEvent): void => {\n if (e.key === 'Tab' && !e.ctrlKey && !e.metaKey && !e.altKey) {\n e.preventDefault();\n this._insertText('\\t');\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 return;\n }\n if (isRedo) {\n e.preventDefault();\n this._redo();\n }\n };\n\n protected _insertText(text: string): void {\n if (!this._$editor) {\n return;\n }\n\n // execCommand('insertText') does not handle \\n — browsers create new divs\n // that lack the 'line' class, so getText() loses all content\n // after the first newline. Apply multi-line inserts directly to the value model.\n if (text.includes('\\n')) {\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 this._savedSelection = {\n anchorOffset: newCursorOffset,\n focusOffset: newCursorOffset,\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 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 this._savedSelection = {\n anchorOffset: start + prefix.length,\n focusOffset: start + prefix.length + selected.length,\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 private _onPaste = (e: ClipboardEvent): void => {\n e.preventDefault();\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 private _undo(): void {\n if (this._undoIndex <= 0) {\n return;\n }\n\n this._undoIndex--;\n this._applyUndoEntry(this._undoStack[this._undoIndex]!);\n }\n\n private _redo(): void {\n if (this._undoIndex >= this._undoStack.length - 1) {\n return;\n }\n\n this._undoIndex++;\n this._applyUndoEntry(this._undoStack[this._undoIndex]!);\n }\n\n private _applyUndoEntry(entry: UndoEntry): void {\n this._value = entry.value;\n this._savedSelection = {\n anchorOffset: entry.anchorOffset,\n focusOffset: entry.focusOffset,\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 private _buildPluginApi(): RCTextareaPluginAPI {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const component = this;\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 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 let start = offset;\n\n while (start > 0 && /\\w/.test(text[start - 1]!)) {\n start--;\n }\n\n let end = offset;\n\n while (end < text.length && /\\w/.test(text[end]!)) {\n end++;\n }\n\n if (start === end) {\n return null;\n }\n\n return { word: text.slice(start, end), from: start, to: end };\n },\n onCursorMove(callback: (selectionStart: number, selectionEnd: number) => void): () => void {\n component._cursorCallbacks.add(callback);\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 /** @deprecated Use `parseDecorationsFromHtml` instead. */\n decorationsFromHtml(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 private _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 addPattern(pattern: Omit<TextPattern, 'id'>): string {\n const id = generateId();\n this._patterns.set(id, { ...pattern, id });\n this._scheduleRender();\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 private 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 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 // Rebuild the Parchment tree\n if (!this._$editor) {\n return;\n }\n\n this._document.build(renderValue, allDecorations);\n\n // Restore cursor\n if (this._savedSelection) {\n restoreSelection(this._$editor, this._savedSelection);\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`, `listNumbers` (deprecated), `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 private _computeGutterLabels(\n allDecorations: Decoration[],\n value = this._value,\n ): (string | null)[] {\n const lines = value.split('\\n');\n\n const overrides = new Map<number, string | null>();\n\n for (const dec of allDecorations) {\n if (dec.type === 'line' && dec.gutterContent !== undefined) {\n overrides.set(dec.line, dec.gutterContent);\n }\n }\n\n let counter = 0;\n return lines.map((lineText, i) => {\n const lineNum = i + 1;\n\n if (overrides.has(lineNum)) {\n return overrides.get(lineNum)!;\n }\n\n if (this.lineNumbers) {\n return String(lineNum);\n }\n\n if (this.listNumbers) {\n if (lineText.trim() === '') {\n return null;\n }\n\n counter++;\n\n return `${counter}.`;\n }\n\n // `gutter` mode is empty by default, and plugins fill via overrides.\n return null;\n });\n }\n\n /**\n * Synchronize the pixel height of each gutter cell to match the\n * corresponding `.line` element in the editor.\n *\n * In non-word-wrap mode the gutter uses a uniform `line-height` mirrored\n * from the editor's first line. In word-wrap mode each cell gets an explicit\n * `height` so wrapped lines stay vertically aligned with their gutter label.\n * Also copies the editor's computed `paddingTop`/`paddingBottom` to the\n * gutter to compensate for browser UA overrides on contenteditable.\n */\n private _syncGutterHeights(): void {\n if (!this._$gutterCells || !this._$editor) {\n return;\n }\n\n // Sync vertical 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. The read-only rule (padding: 0 on #editor)\n // also needs the gutter to match — this one call covers both cases.\n const computedStyle = getComputedStyle(this._$editor);\n const paddingTop = computedStyle.paddingTop;\n const paddingBottom = computedStyle.paddingBottom;\n\n if (this._$gutterCells.style.paddingTop !== paddingTop) {\n this._$gutterCells.style.paddingTop = paddingTop;\n }\n\n if (this._$gutterCells.style.paddingBottom !== paddingBottom) {\n this._$gutterCells.style.paddingBottom = paddingBottom;\n }\n\n const $lineEls = this._$editor.querySelectorAll<HTMLElement>('.line');\n const $spans = this._$gutterCells.children;\n\n if (!this.wordWrap) {\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 height.\n if ($lineEls.length > 0) {\n const lineHeight = `${$lineEls[0].getBoundingClientRect().height}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.height = '';\n }\n\n return;\n }\n\n // word-wrap: per-span explicit heights 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 height = $lineEls[i]!.getBoundingClientRect().height;\n const heightStyle = `${height}px`;\n const $span = $spans[i] as HTMLElement;\n\n if ($span.style.height !== heightStyle) {\n $span.style.height = heightStyle;\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 private _syncGutter(labels?: (string | null)[]): void {\n if (!this.lineNumbers && !this.listNumbers && !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 // 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.removeChild(this._$gutterCells.lastChild!);\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 if ($span.textContent !== label) {\n $span.textContent = label;\n }\n }\n }\n\n private _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 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 return;\n }\n }\n\n if (this._label) {\n this._$editor.setAttribute('aria-label', this._label);\n return;\n }\n\n this._$editor.removeAttribute('aria-label');\n }\n\n private _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.ts';\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) cleanup();\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 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 type { RCTextareaPluginAPI, DecorationInput } from './types.ts';\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 * Called when `action.iconName` is set. 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) => HTMLElement | 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();\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-left: 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 (let i = 0; i < lineIndex && i < lines.length; i++) {\n // +1 for the '\\n'\n offset += lines[i]!.length + 1;\n }\n\n if (lineIndex < lines.length) {\n offset += lines[lineIndex]!.length;\n }\n\n return offset;\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 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 let left = hostRect.left;\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":["styles","css","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","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","boundarySet","decoration","localOffset","boundaries","segmentStart","segmentEnd","widget","createWidget","segment","bestDecoration","bestSize","localFrom","localTo","size","$span","attrValue","RCDocument","$documentRoot","decorations","lines","$lines","lineDecorationsMap","lineDecorations","lineStartOffset","lineNum","lineEnd","$block","marks","d","widgets","diagnostics","text","getText","$editorEl","$lineEl","getLineText","extractRawText","getNodeText","result","firstBlock","textModelLength","$node","len","$child","domToTextOffset","$root","$targetNode","targetNodeOffset","totalOffset","lineIdx","walkForOffset","currentOffset","$children","textOffsetToDom","targetOffset","lineLen","pos","walkToOffset","$textNode","saveSelection","selection","range","anchorOffset","focusOffset","restoreSelection","saved","anchor","focus","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","line","MAX_UNDO","parseDecorationsFromHtml","html","$tmp","charOffset","walk","isSpan","startOffset","_RCTextarea","LitElement","NativeChildController","$textarea","$previousTextarea","end","e","isUndo","isRedo","normalized","old","plugin","oldPlugin","val","changed","placeholder","$editor","preEditSelection","mappedDecorations","$previousActive","$lineNumber","newCursorOffset","suffix","selected","sel","entry","component","$range","rect","sheetOrCssText","sheet","$shadowRoot","s","tokens","themeMap","token","renderSeq","renderValue","transformed","patMarkDecs","patLineDecs","api","allDecorations","overrides","dec","counter","computedStyle","paddingTop","paddingBottom","$lineEls","$spans","lineHeight","heightStyle","labels","current","label","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","buildButton","action","$btn","$icon","$container","$panel"],"mappings":";;;AAEO,MAAMA,KAASC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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OAAO,UACZA,EAAK,aAAa,SAASD,EAAO,KAAK,GAEnCvX,EAAQ;AACV,IAAAA,EAAQ,aAAauX,GAAQC,CAAI;AAAA,WACxBD,EAAO,UAAU;AAC1B,UAAME,IAAQzX,EAAQ,aAAauX,EAAO,QAAQ,KAAK;AAEvD,IAAIE,KACFD,EAAK,aAAa,cAAcD,EAAO,KAAK,GAC5CC,EAAK,YAAYC,CAAK,MAGtBD,EAAK,QAAQ,OAAUD,EAAO,UAC9BC,EAAK,aAAa,cAAcD,EAAO,KAAK;AAAA,EAEhD;AACE,IAAAC,EAAK,cAAcD,EAAO;AAG5B,SAAAC,EAAK,iBAAiB,aAAa,CAACxF,MAAMA,EAAE,gBAAgB,GAC5DwF,EAAK,iBAAiB,SAAS,MAAMD,EAAO,SAAS,GAE9CC;AACT;AAEA,SAASf,GACPJ,GACArW,GACa;AACb,QAAM0X,IAAa,SAAS,cAAc,MAAM;AAEhD,EAAAA,EAAW,YAAY;AAEvB,aAAWH,KAAUlB;AACnB,IAAAqB,EAAW,YAAYJ,GAAYC,GAAQvX,CAAO,CAAC;AAGrD,SAAO0X;AACT;AAEA,SAASX,GACPY,GACAtB,GACArW,GACM;AACN,aAAWuX,KAAUlB;AACnB,IAAAsB,EAAO,YAAYL,GAAYC,GAAQvX,CAAO,CAAC;AAEnD;","x_google_ignoreList":[1]}
@@ -1,5 +1,5 @@
1
- import { R as e } from "./line-actions-controller-ChmbiQ-G.js";
2
- import { L as o, c as s, m as c } from "./line-actions-controller-ChmbiQ-G.js";
1
+ import { R as e } from "./line-actions-controller-x4P2Yjd4.js";
2
+ import { L as o, c as s, m as c } from "./line-actions-controller-x4P2Yjd4.js";
3
3
  customElements.get("rc-textarea") || customElements.define("rc-textarea", e);
4
4
  export {
5
5
  o as LineActionsController,
@@ -1,4 +1,4 @@
1
- import { L as t, R as r, c as o, m as s } from "./line-actions-controller-ChmbiQ-G.js";
1
+ import { L as t, R as r, c as o, m as s } from "./line-actions-controller-x4P2Yjd4.js";
2
2
  export {
3
3
  t as LineActionsController,
4
4
  r as RCTextarea,
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.3.0",
6
+ "version": "0.3.1",
7
7
  "description": "Textarea wrapper with line decorations, gutter rendering, inline widgets, and plugin hooks.",
8
8
  "repository": {
9
9
  "type": "git",
@@ -1 +0,0 @@
1
- {"version":3,"file":"line-actions-controller-ChmbiQ-G.js","sources":["../src/rc-textarea.styles.ts","../../../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.ts","../src/line-decorator.ts","../src/line-actions-controller.ts"],"sourcesContent":["import { css } from 'lit';\n\nexport const styles = css`\n :host {\n display: block;\n box-sizing: border-box;\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-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-right: var(--rc-textarea-gutter-border, 1px solid ButtonBorder);\n overflow: hidden;\n user-select: none;\n }\n\n :host([line-numbers]) #gutter,\n :host([list-numbers]) #gutter,\n :host([gutter]) #gutter {\n display: block;\n }\n\n #gutter-cells {\n padding: var(--rc-textarea-padding, 0.5em);\n padding-inline-end: var(--rc-textarea-gutter-padding-inline-end, 0.75em);\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 text-align: right;\n min-width: 2.5ch;\n }\n\n .gutter-cell {\n display: block;\n white-space: pre;\n }\n\n .gutter-cell--active {\n color: var(--rc-textarea-color, var(--rc-text, FieldText));\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: var(--rc-textarea-padding, 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-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 :host([read-only]) #root {\n border: none;\n background: transparent;\n border-radius: 0;\n }\n\n :host([read-only]) #editor {\n cursor: default;\n padding: 0;\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 /* Active line highlight — opt-in via CSS custom property. */\n .line--active {\n background: var(--rc-textarea-active-line-bg, transparent);\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-left: 4ch;\n white-space: nowrap;\n pointer-events: none;\n font-size: 0.875em;\n opacity: 0.8;\n font-style: italic;\n }\n\n .mark {\n border-radius: 2px;\n }\n\n .widget {\n display: inline-block;\n user-select: none;\n cursor: default;\n vertical-align: middle;\n }\n`;\n","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';\nimport type { MarkDecoration } from './types.ts';\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.ts';\nimport type { Decoration, MarkDecoration, LineDecoration, WidgetDecoration } from './types.ts';\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 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 for (let i = 0; i < boundaries.length - 1; i++) {\n const segmentStart = boundaries[i]!;\n const segmentEnd = boundaries[i + 1]!;\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 $span.appendChild(decoration.create());\n\n return $span;\n}\n\nexport class RCDocument {\n private readonly scroll: RCScrollBlot;\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\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 {\n widgetDecorations.push(decoration);\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 (let i = 0; i < lines.length; i++) {\n const lineText = lines[i]!;\n const lineNum = i + 1;\n const lineStart = lineStartOffset;\n const lineEnd = lineStart + lineText.length;\n\n // Reuse an existing line element when available, otherwise create a new one.\n let $block: HTMLElement;\n\n if (i < $lines.length) {\n $block = $lines[i]!;\n\n // Remove all attributes so stale class names, data-*, and title don't bleed through\n while ($block.attributes.length > 0) {\n $block.removeAttribute($block.attributes[0]!.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 const lineDecorations = lineDecorationsMap.get(lineNum) ?? [];\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 const marks = markDecorations.filter((d) => d.from < lineEnd && d.to > lineStart);\n const widgets = widgetDecorations.filter((d) => d.offset >= lineStart && d.offset <= lineEnd);\n\n buildLineContent($block, lineText, lineStart, marks, widgets);\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.removeChild($documentRoot.lastChild!);\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 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\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 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 for (let lineIdx = 0; lineIdx < $lines.length; lineIdx++) {\n if (lineIdx > 0) {\n totalOffset++; // \\n between lines\n }\n\n const $line = $lines[lineIdx]!;\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 for (let i = 0; i < targetNodeOffset && i < $children.length; i++) {\n offset += textModelLength($children[i]!);\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 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 for (let i = 0; i < $lines.length; i++) {\n if (i > 0) {\n if (localOffset === 0) {\n // Position at boundary between lines — place at start of this line\n const $line = $lines[i]!;\n\n return { node: $line, offset: 0 };\n }\n\n localOffset--; // consume the \\n\n }\n\n const $line = $lines[i]!;\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 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\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 $rootNode = $root.getRootNode();\n const selection =\n (\n $rootNode as unknown as { /* Chrome 53+ */ getSelection?: () => Selection | null }\n ).getSelection?.() ?? window.getSelection();\n\n if (!selection || selection.rangeCount === 0) {\n return null;\n }\n\n const range = selection.getRangeAt(0);\n\n if (!$root.contains(range.commonAncestorContainer)) {\n return null;\n }\n\n const anchorOffset = domToTextOffset($root, range.startContainer, range.startOffset);\n const focusOffset = domToTextOffset($root, range.endContainer, range.endOffset);\n\n return { anchorOffset, focusOffset };\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 text for this line.\n *\n * - `string` — custom label (e.g. `\"!\"`, `\"▶\"`)\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 | null;\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 /** Factory called each render cycle. Must return a new element each time. */\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\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;\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\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 * 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 * @returns the word and its `[from, to)` offsets, or `null` if the cursor is\n * not on a word character (`\\w` — alphanumeric + underscore)\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 * @deprecated Use `parseDecorationsFromHtml` instead.\n */\n decorationsFromHtml(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` in\n * read-only mode.\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.ts';\n\nexport { generateId } from './types.ts';\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 *\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 {\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 }\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 map.set(id, { ...input, id } as Decoration);\n }\n}\n\nexport type { MarkDecoration, LineDecoration };\n","import type { TextPattern, MarkDecoration, LineDecoration } from './types.ts';\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 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 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 { LitElement, html } from 'lit';\nimport type { CSSResultGroup } from 'lit';\nimport { property, query } from 'lit/decorators.js';\nimport { NativeChildController, warnMissingDirectChild } from '@rcarls/rc-common';\n\nimport { styles } from './rc-textarea.styles.ts';\nimport { RCDocument, getText } from './document.ts';\nimport { saveSelection, restoreSelection, type SavedSelection } from './selection.ts';\nimport { remapDecorations, addDecoration, setDecorations } from './decoration.ts';\nimport { matchPatternResults } from './pattern-matcher.ts';\n\nimport type {\n Decoration,\n DecorationInput,\n RCTextareaPlugin,\n RCTextareaPluginAPI,\n TextPattern,\n MarkDecoration,\n Token,\n} from './types.ts';\nimport { generateId } from './types.ts';\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\nconst MAX_UNDO = 100;\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 $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, inline widgets, 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 * @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-blur - Fired when the field loses focus\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=FieldText] - Text color; falls back through --rc-text\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=0.5em] - Padding inside the field area\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\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 */\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 * @deprecated Use a plugin with `LineDecoration.gutterContent` to implement\n * sparse line numbering. This property will be removed before v1.0.\n */\n @property({ type: Boolean, attribute: 'list-numbers', reflect: true })\n get listNumbers(): boolean {\n return this._listNumbers;\n }\n\n set listNumbers(value: boolean) {\n if (value) {\n console.warn(\n '[rc-textarea] `listNumbers` / `list-numbers` is deprecated and will be removed before v1.0. ' +\n 'Use a plugin with `LineDecoration.gutterContent` to implement sparse line numbering.',\n );\n }\n\n const old = this._listNumbers;\n\n this._listNumbers = value;\n this.requestUpdate('listNumbers', old);\n }\n\n private _listNumbers = 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 /** Disable editing. The field renders as a styled read-only display. */\n @property({ type: Boolean, attribute: 'read-only', reflect: true })\n readOnly = false;\n\n /**\n * @deprecated Set `aria-label` on the slotted `<textarea>` instead, or\n * associate a `<label>` element via its `for`/`id` pair. This property\n * will be removed before v1.0.\n */\n @property({ type: String })\n get label(): string | null {\n return this._label;\n }\n\n set label(value: string | null) {\n if (value) {\n console.warn(\n '[rc-textarea] `label` is deprecated and will be removed before v1.0. ' +\n 'Set `aria-label` on the slotted `<textarea>`, or associate a `<label>` ' +\n 'element via its `for`/`id` pair instead.',\n );\n }\n\n const old = this._label;\n\n this._label = value;\n\n this.requestUpdate('label', old);\n }\n\n private _label: string | 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 if (plugin) {\n this.usePlugin(plugin);\n } else {\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', true)\n protected _$editor!: HTMLElement;\n\n @query('#gutter-cells', true)\n protected _$gutterCells!: HTMLElement;\n\n @query('slot', true)\n protected _$slot!: HTMLSlotElement;\n\n private _value = '';\n private _defaultValue: string | undefined;\n private _initialValueResolved = false;\n private _valueSetByHost = false;\n private _document: RCDocument | null = null;\n private _$textareaRef: WeakRef<HTMLTextAreaElement> | null = null;\n\n private readonly _textareaController = new NativeChildController<HTMLTextAreaElement>(this, {\n selector: ':scope > textarea',\n observe: true,\n onChange: ($textarea, $previousTextarea) =>\n this._setupTextarea($textarea, $previousTextarea),\n onMissing: () => {\n if (import.meta.env.DEV && !this.readOnly) {\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 /** Plugin-owned decorations */\n protected _pluginDecorations = new Map<string, Decoration>();\n\n /** Pattern-generated decorations (rebuilt on each value change). */\n private _patternDecorations: Decoration[] = [];\n\n /** Imperative decorations (set directly via the `decorations` property) */\n private _externalDecorations: DecorationInput[] = [];\n\n /** Registered patterns. */\n private _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 private _pluginSeq = 0;\n\n /** Stylesheets adopted into the shadow root by the active plugin. */\n private _pluginSheets = new Set<CSSStyleSheet>();\n\n protected _savedSelection: SavedSelection | null = null;\n private _rafHandle: number | null = null;\n private _composing = false;\n private _isRendering = false;\n\n /** The currently highlighted `.line` element (active line). */\n private _$activeLine: HTMLElement | null = null;\n\n /** Callbacks registered via PluginAPI.onCursorMove(). */\n private _cursorCallbacks = new Set<(start: number, end: number) => void>();\n\n private _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 private _undoStack: UndoEntry[] = [];\n private _undoIndex = -1;\n\n private _resizeObserver: ResizeObserver | null = null;\n\n /** Cached per-line gutter labels from the last render — reused by ResizeObserver. */\n private _gutterLabels: (string | null)[] = [];\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 })\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 document.addEventListener('selectionchange', this._docSelectionChangeHandler);\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._$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 }\n\n this._resizeObserver = new ResizeObserver(() => {\n this._syncGutter();\n this._syncGutterHeights();\n });\n\n this._resizeObserver.observe(this);\n\n // In editable mode a slotted <textarea> fires slotchange, which calls\n // _onSlotChange → _scheduleRender. In read-only mode no textarea is\n // required, so slotchange may never fire; call _scheduleRender here to seed\n // the first render when value/defaultValue was set before upgrade or connection.\n this._scheduleRender();\n }\n\n override updated(changed: Map<string, unknown>): void {\n if (changed.has('readOnly')) {\n if (this._$editor) {\n this._$editor.contentEditable = this.readOnly ? 'false' : 'true';\n }\n\n this._syncGutterHeights();\n this._textareaController.sync();\n }\n\n if (changed.has('label')) {\n this._syncLabel();\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 private _onSlotChange(): void {\n this._textareaController.sync();\n }\n\n private _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 if (!$textarea) {\n this._$textareaRef = null;\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 // Sync typography from textarea's computed style to editor\n this._syncTypography($textarea);\n\n this._scheduleRender();\n }\n\n private _onTextareaInvalid = (): void => {\n if (this._$editor) {\n this._$editor.setAttribute('aria-invalid', 'true');\n }\n };\n\n private _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\n $editor.addEventListener('input', this._onInputEvent);\n $editor.addEventListener('keydown', this._onKeyDown);\n $editor.addEventListener('paste', this._onPaste);\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.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 private _onInputEvent = (): void => {\n if (!this._composing) {\n this._onInput();\n }\n };\n\n private _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 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 private _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 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 private _updateActiveLine(): void {\n if (!this._$editor) {\n return;\n }\n\n const selection =\n (\n this.shadowRoot as unknown as { /* (Chrome 53+) */ getSelection?: () => Selection | null }\n ).getSelection?.() ?? window.getSelection();\n\n let $line: HTMLElement | null = null;\n\n if (selection?.focusNode && this._$editor.contains(selection.focusNode)) {\n let node: Node | null = selection.focusNode;\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\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 private _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 private _onKeyDown = (e: KeyboardEvent): void => {\n if (e.key === 'Tab' && !e.ctrlKey && !e.metaKey && !e.altKey) {\n e.preventDefault();\n this._insertText('\\t');\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 return;\n }\n if (isRedo) {\n e.preventDefault();\n this._redo();\n }\n };\n\n protected _insertText(text: string): void {\n if (!this._$editor) {\n return;\n }\n\n // execCommand('insertText') does not handle \\n — browsers create new divs\n // that lack the 'line' class, so getText() loses all content\n // after the first newline. Apply multi-line inserts directly to the value model.\n if (text.includes('\\n')) {\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 this._savedSelection = {\n anchorOffset: newCursorOffset,\n focusOffset: newCursorOffset,\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 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 this._savedSelection = {\n anchorOffset: start + prefix.length,\n focusOffset: start + prefix.length + selected.length,\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 private _onPaste = (e: ClipboardEvent): void => {\n e.preventDefault();\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 private _undo(): void {\n if (this._undoIndex <= 0) {\n return;\n }\n\n this._undoIndex--;\n this._applyUndoEntry(this._undoStack[this._undoIndex]!);\n }\n\n private _redo(): void {\n if (this._undoIndex >= this._undoStack.length - 1) {\n return;\n }\n\n this._undoIndex++;\n this._applyUndoEntry(this._undoStack[this._undoIndex]!);\n }\n\n private _applyUndoEntry(entry: UndoEntry): void {\n this._value = entry.value;\n this._savedSelection = {\n anchorOffset: entry.anchorOffset,\n focusOffset: entry.focusOffset,\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 private _buildPluginApi(): RCTextareaPluginAPI {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const component = this;\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 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 let start = offset;\n\n while (start > 0 && /\\w/.test(text[start - 1]!)) {\n start--;\n }\n\n let end = offset;\n\n while (end < text.length && /\\w/.test(text[end]!)) {\n end++;\n }\n\n if (start === end) {\n return null;\n }\n\n return { word: text.slice(start, end), from: start, to: end };\n },\n onCursorMove(callback: (selectionStart: number, selectionEnd: number) => void): () => void {\n component._cursorCallbacks.add(callback);\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 /** @deprecated Use `parseDecorationsFromHtml` instead. */\n decorationsFromHtml(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 private _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 addPattern(pattern: Omit<TextPattern, 'id'>): string {\n const id = generateId();\n this._patterns.set(id, { ...pattern, id });\n this._scheduleRender();\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 private 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 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 // Rebuild the Parchment tree\n if (!this._$editor) {\n return;\n }\n\n this._document.build(renderValue, allDecorations);\n\n // Restore cursor\n if (this._savedSelection) {\n restoreSelection(this._$editor, this._savedSelection);\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`, `listNumbers` (deprecated), `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 private _computeGutterLabels(\n allDecorations: Decoration[],\n value = this._value,\n ): (string | null)[] {\n const lines = value.split('\\n');\n\n const overrides = new Map<number, string | null>();\n\n for (const dec of allDecorations) {\n if (dec.type === 'line' && dec.gutterContent !== undefined) {\n overrides.set(dec.line, dec.gutterContent);\n }\n }\n\n let counter = 0;\n return lines.map((lineText, i) => {\n const lineNum = i + 1;\n\n if (overrides.has(lineNum)) {\n return overrides.get(lineNum)!;\n }\n\n if (this.lineNumbers) {\n return String(lineNum);\n }\n\n if (this.listNumbers) {\n if (lineText.trim() === '') {\n return null;\n }\n\n counter++;\n\n return `${counter}.`;\n }\n\n // `gutter` mode is empty by default, and plugins fill via overrides.\n return null;\n });\n }\n\n /**\n * Synchronize the pixel height of each gutter cell to match the\n * corresponding `.line` element in the editor.\n *\n * In non-word-wrap mode the gutter uses a uniform `line-height` mirrored\n * from the editor's first line. In word-wrap mode each cell gets an explicit\n * `height` so wrapped lines stay vertically aligned with their gutter label.\n * Also copies the editor's computed `paddingTop`/`paddingBottom` to the\n * gutter to compensate for browser UA overrides on contenteditable.\n */\n private _syncGutterHeights(): void {\n if (!this._$gutterCells || !this._$editor) {\n return;\n }\n\n // Sync vertical 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. The read-only rule (padding: 0 on #editor)\n // also needs the gutter to match — this one call covers both cases.\n const computedStyle = getComputedStyle(this._$editor);\n const paddingTop = computedStyle.paddingTop;\n const paddingBottom = computedStyle.paddingBottom;\n\n if (this._$gutterCells.style.paddingTop !== paddingTop) {\n this._$gutterCells.style.paddingTop = paddingTop;\n }\n\n if (this._$gutterCells.style.paddingBottom !== paddingBottom) {\n this._$gutterCells.style.paddingBottom = paddingBottom;\n }\n\n const $lineEls = this._$editor.querySelectorAll<HTMLElement>('.line');\n const $spans = this._$gutterCells.children;\n\n if (!this.wordWrap) {\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 height.\n if ($lineEls.length > 0) {\n const lineHeight = `${$lineEls[0].getBoundingClientRect().height}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.height = '';\n }\n\n return;\n }\n\n // word-wrap: per-span explicit heights 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 height = $lineEls[i]!.getBoundingClientRect().height;\n const heightStyle = `${height}px`;\n const $span = $spans[i] as HTMLElement;\n\n if ($span.style.height !== heightStyle) {\n $span.style.height = heightStyle;\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 private _syncGutter(labels?: (string | null)[]): void {\n if (!this.lineNumbers && !this.listNumbers && !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 // 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.removeChild(this._$gutterCells.lastChild!);\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 if ($span.textContent !== label) {\n $span.textContent = label;\n }\n }\n }\n\n private _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 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 return;\n }\n }\n\n if (this._label) {\n this._$editor.setAttribute('aria-label', this._label);\n return;\n }\n\n this._$editor.removeAttribute('aria-label');\n }\n\n private _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.ts';\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) cleanup();\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 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 type { RCTextareaPluginAPI, DecorationInput } from './types.ts';\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 * Called when `action.iconName` is set. 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) => HTMLElement | 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();\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-left: 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 (let i = 0; i < lineIndex && i < lines.length; i++) {\n // +1 for the '\\n'\n offset += lines[i]!.length + 1;\n }\n\n if (lineIndex < lines.length) {\n offset += lines[lineIndex]!.length;\n }\n\n return offset;\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 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 let left = hostRect.left;\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":["styles","css","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","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","boundarySet","decoration","localOffset","boundaries","segmentStart","segmentEnd","widget","createWidget","segment","bestDecoration","bestSize","localFrom","localTo","size","$span","attrValue","RCDocument","$documentRoot","decorations","lines","$lines","lineDecorationsMap","lineDecorations","lineStartOffset","lineNum","lineEnd","$block","marks","d","widgets","diagnostics","text","getText","$editorEl","$lineEl","getLineText","extractRawText","getNodeText","result","firstBlock","textModelLength","$node","len","$child","domToTextOffset","$root","$targetNode","targetNodeOffset","totalOffset","lineIdx","walkForOffset","currentOffset","$children","textOffsetToDom","targetOffset","lineLen","pos","walkToOffset","$textNode","saveSelection","selection","range","anchorOffset","focusOffset","restoreSelection","saved","anchor","focus","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","line","MAX_UNDO","parseDecorationsFromHtml","html","$tmp","charOffset","walk","isSpan","startOffset","_RCTextarea","LitElement","NativeChildController","$textarea","$previousTextarea","end","e","isUndo","isRedo","normalized","old","plugin","oldPlugin","val","changed","placeholder","$editor","preEditSelection","mappedDecorations","$previousActive","$lineNumber","newCursorOffset","suffix","selected","sel","entry","component","$range","rect","sheetOrCssText","sheet","$shadowRoot","s","tokens","themeMap","token","renderSeq","renderValue","transformed","patMarkDecs","patLineDecs","api","allDecorations","overrides","dec","counter","computedStyle","paddingTop","paddingBottom","$lineEls","$spans","lineHeight","heightStyle","labels","current","label","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","buildButton","action","$btn","$icon","$container","$panel"],"mappings":";;;AAEO,MAAMA,KAASC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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