@rcarls/rc-textarea 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +173 -1176
- package/dist/custom-elements.json +168 -72
- package/dist/{line-actions-controller-BsM6DJ0b.js → line-actions-controller-ChmbiQ-G.js} +573 -532
- package/dist/line-actions-controller-ChmbiQ-G.js.map +1 -0
- package/dist/rc-textarea-define.js +2 -2
- package/dist/rc-textarea.js +1 -1
- package/dist/types/packages/rc-textarea/src/blots.d.ts +7 -7
- package/dist/types/packages/rc-textarea/src/decoration.d.ts +5 -2
- package/dist/types/packages/rc-textarea/src/document.d.ts +7 -9
- package/dist/types/packages/rc-textarea/src/line-actions-controller.d.ts +12 -9
- package/dist/types/packages/rc-textarea/src/line-decorator.d.ts +9 -8
- package/dist/types/packages/rc-textarea/src/pattern-matcher.d.ts +4 -2
- package/dist/types/packages/rc-textarea/src/rc-textarea.d.ts +101 -32
- package/dist/types/packages/rc-textarea/src/selection.d.ts +17 -13
- package/dist/types/packages/rc-textarea/src/test-helpers.d.ts +6 -4
- package/dist/types/packages/rc-textarea/src/types.d.ts +119 -40
- package/package.json +7 -8
- package/dist/demo.css +0 -85
- package/dist/demo.js +0 -40
- package/dist/line-actions-controller-BsM6DJ0b.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"line-actions-controller-BsM6DJ0b.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 layout ──────────────────────────────────────────────────────── */\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\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\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(\n --rc-textarea-caret-color,\n var(--rc-textarea-color, FieldText)\n );\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 /* ── Slot (hidden lightDOM textarea) ──────────────────────────────────── */\n\n ::slotted(textarea) {\n /* Visually hidden but accessible to form submission.\n Inline styles applied via JS take precedence and are more reliable,\n but this provides a baseline in case of timing issues. */\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 structure ───────────────────────────────────────────────────── */\n\n .v2-line {\n position: relative;\n display: block;\n }\n\n /* Active line highlight — opt-in via CSS custom property. */\n .v2-line--active {\n background: var(--rc-textarea-active-line-bg, transparent);\n }\n\n /* Error-lens style end-of-line message via ::after pseudo-element.\n content: attr(data-message) is set when V2Document assigns data-message.\n Using ::after keeps the annotation completely outside the DOM selection\n and clipboard path — no user-select tricks needed. */\n .v2-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 /* ── Inline decoration spans ──────────────────────────────────────────── */\n\n .v2-mark {\n /* Base class; formatting applied via inline style by V2InlineBlot */\n border-radius: 2px;\n }\n\n /* ── Widget spans ─────────────────────────────────────────────────────── */\n\n .v2-widget {\n display: inline-block;\n user-select: none;\n cursor: default;\n vertical-align: middle;\n }\n\n /* ── Scrollbar sync between editor and gutter ─────────────────────────── */\n /* Gutter doesn't scroll independently; editor scroll is handled in JS */\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 V2Document.build() on each render frame.\n */\nimport {\n Registry,\n ScrollBlot,\n BlockBlot,\n InlineBlot,\n EmbedBlot,\n} from 'parchment';\nimport type { MarkDecoration } from './types.ts';\n\nexport { Registry };\n\n// ── V2ScrollBlot ─────────────────────────────────────────────────────────────\n\nexport class V2ScrollBlot extends ScrollBlot {\n static override blotName = 'v2-scroll';\n\n constructor(registry: Registry, domNode: HTMLDivElement) {\n super(registry, domNode);\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(\n _mutations: MutationRecord[],\n _context: Record<string, unknown>,\n ): void {}\n // Match ScrollBlot's two optimize overloads\n override optimize(context: { [key: string]: unknown }): void;\n override optimize(\n mutations: MutationRecord[],\n context: { [key: string]: unknown },\n ): void;\n override optimize(\n _contextOrMutations?: MutationRecord[] | { [key: string]: unknown },\n _context?: { [key: string]: unknown },\n ): void {}\n}\n\n// ── V2BlockBlot ──────────────────────────────────────────────────────────────\n\nexport class V2BlockBlot extends BlockBlot {\n static override blotName = 'v2-block';\n static override tagName = 'DIV';\n static override className = 'v2-line';\n}\n\n// ── V2InlineBlot ─────────────────────────────────────────────────────────────\n\ntype InlineFormats = Pick<\n MarkDecoration,\n | 'className'\n | 'bold'\n | 'italic'\n | 'color'\n | 'background'\n | 'underline'\n | 'underlineColor'\n>;\n\nexport class V2InlineBlot extends InlineBlot {\n static override blotName = 'v2-inline';\n static override tagName = 'SPAN';\n static override className = 'v2-mark';\n\n static override create(formats?: InlineFormats): HTMLElement {\n const el = super.create() as HTMLSpanElement;\n if (formats) applyInlineFormats(el, formats);\n return el;\n }\n}\n\n/**\n * Apply `MarkDecoration` style properties to a `.v2-mark` span element as\n * inline styles and extra CSS classes. Called by `V2InlineBlot.create()` and\n * by external code that needs to style a span to match a decoration.\n */\nexport function applyInlineFormats(\n el: HTMLSpanElement,\n formats: InlineFormats,\n): void {\n if (formats.className) {\n for (const cls of formats.className.split(/\\s+/).filter(Boolean)) {\n el.classList.add(cls);\n }\n }\n if (formats.bold) el.style.fontWeight = 'bold';\n if (formats.italic) el.style.fontStyle = 'italic';\n if (formats.color) el.style.color = formats.color;\n if (formats.background) el.style.backgroundColor = formats.background;\n if (formats.underline) {\n el.style.textDecoration = `${formats.underline} underline`;\n if (formats.underlineColor)\n el.style.textDecorationColor = formats.underlineColor;\n }\n}\n\n// ── V2WidgetBlot ─────────────────────────────────────────────────────────────\n\nexport class V2WidgetBlot extends EmbedBlot {\n static override blotName = 'v2-widget';\n static override tagName = 'SPAN';\n static override className = 'v2-widget';\n\n static override create(): HTMLElement {\n const el = super.create() as HTMLSpanElement;\n el.contentEditable = 'false';\n el.setAttribute('aria-hidden', 'true');\n return el;\n }\n}\n\n// ── Registry factory ──────────────────────────────────────────────────────────\n\nexport function createRegistry(): Registry {\n const registry = new Registry();\n // Register content blots — ScrollBlot is the root, not registered like others\n registry.register(V2BlockBlot, V2InlineBlot, V2WidgetBlot);\n return registry;\n}\n","/**\n * V2Document — manages the Parchment-backed contenteditable editor DOM.\n *\n * Maintains a V2ScrollBlot 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 */\nimport {\n V2ScrollBlot,\n V2BlockBlot,\n V2InlineBlot,\n V2WidgetBlot,\n createRegistry,\n} from './blots.ts';\nimport type {\n Decoration,\n MarkDecoration,\n LineDecoration,\n WidgetDecoration,\n} from './types.ts';\n\n// ── Inline content builder ───────────────────────────────────────────────────\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 lineEl: 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 lineEl.appendChild(document.createElement('br'));\n return;\n }\n\n // Collect segment boundary points from all mark decoration edges\n const boundarySet = new Set<number>([0, lineText.length]);\n for (const dec of markDecorations) {\n boundarySet.add(Math.max(0, dec.from - lineStart));\n boundarySet.add(Math.min(lineText.length, dec.to - lineStart));\n }\n for (const dec of widgetDecorations) {\n const localOffset = dec.offset - lineStart;\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 segStart = boundaries[i]!;\n const segEnd = boundaries[i + 1]!;\n\n // Insert widgets whose position falls at segStart ('before' side)\n for (const w of widgetDecorations) {\n const localOffset = w.offset - lineStart;\n if (localOffset === segStart && (w.side ?? 'before') === 'before') {\n lineEl.appendChild(createWidgetEl(w));\n }\n }\n\n const segText = lineText.slice(segStart, segEnd);\n if (!segText) continue;\n\n // Find the innermost (smallest) mark decoration fully covering [segStart, segEnd)\n let bestDec: MarkDecoration | undefined;\n let bestSize = Infinity;\n for (const dec of markDecorations) {\n const localFrom = dec.from - lineStart;\n const localTo = dec.to - lineStart;\n if (localFrom <= segStart && localTo >= segEnd) {\n const size = localTo - localFrom;\n if (size < bestSize) {\n bestSize = size;\n bestDec = dec;\n }\n }\n }\n\n if (bestDec) {\n const spanEl = V2InlineBlot.create(bestDec) as HTMLSpanElement;\n if (bestDec.attributes) {\n for (const [k, v] of Object.entries(bestDec.attributes)) {\n spanEl.setAttribute(k, v);\n }\n }\n spanEl.appendChild(document.createTextNode(segText));\n lineEl.appendChild(spanEl);\n } else {\n lineEl.appendChild(document.createTextNode(segText));\n }\n\n // Insert 'after' widgets at segEnd\n for (const w of widgetDecorations) {\n const localOffset = w.offset - lineStart;\n if (localOffset === segEnd && w.side === 'after') {\n lineEl.appendChild(createWidgetEl(w));\n }\n }\n }\n\n // Widgets at very end of line (default 'before' side)\n for (const w of widgetDecorations) {\n const localOffset = w.offset - lineStart;\n if (localOffset === lineText.length && (w.side ?? 'before') === 'before') {\n lineEl.appendChild(createWidgetEl(w));\n }\n }\n}\n\n/** Create the `.v2-widget` span wrapper for a `WidgetDecoration`. */\nfunction createWidgetEl(dec: WidgetDecoration): HTMLSpanElement {\n const spanEl = V2WidgetBlot.create() as HTMLSpanElement;\n spanEl.appendChild(dec.create());\n return spanEl;\n}\n\n// ── V2Document ───────────────────────────────────────────────────────────────\n\nexport class V2Document {\n private readonly scroll: V2ScrollBlot;\n\n constructor(editorEl: HTMLDivElement) {\n const registry = createRegistry();\n this.scroll = new V2ScrollBlot(registry, editorEl);\n }\n\n /**\n * Rebuild the document tree from `value` + `decorations`.\n * Reuses existing `.v2-line` elements in place to preserve DOM identity\n * across renders (fixes DevTools node tracking and mouse gesture continuity).\n * Only the children of each line are replaced; the line element itself survives.\n */\n build(value: string, decorations: Decoration[]): void {\n const editorEl = this.scroll.domNode as HTMLElement;\n\n const lines = value.split('\\n');\n\n // Snapshot existing line elements for reuse — preserves DOM identity so\n // DevTools node references survive re-renders and ongoing mouse gestures\n // (double-click, drag) are not interrupted by node replacement.\n const existingLineEls = Array.from(editorEl.querySelectorAll<HTMLElement>('.v2-line'));\n\n // Index decorations by type for fast per-line lookup\n const lineDecsByLine = new Map<number, LineDecoration[]>();\n const markDecs: MarkDecoration[] = [];\n const widgetDecs: WidgetDecoration[] = [];\n\n for (const dec of decorations) {\n if (dec.type === 'line') {\n const arr = lineDecsByLine.get(dec.line) ?? [];\n arr.push(dec);\n lineDecsByLine.set(dec.line, arr);\n } else if (dec.type === 'mark') {\n markDecs.push(dec);\n } else {\n widgetDecs.push(dec);\n }\n }\n\n markDecs.sort((a, b) => a.from - b.from || a.to - b.to);\n widgetDecs.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 // Reuse preserves DOM identity across renders.\n let blockDomNode: HTMLElement;\n if (i < existingLineEls.length) {\n blockDomNode = existingLineEls[i]!;\n // Remove all attributes so stale class names, data-*, and title don't bleed through\n while (blockDomNode.attributes.length > 0) {\n blockDomNode.removeAttribute(blockDomNode.attributes[0]!.name);\n }\n blockDomNode.className = 'v2-line';\n // Clear children\n while (blockDomNode.firstChild) {\n blockDomNode.removeChild(blockDomNode.firstChild);\n }\n } else {\n blockDomNode = V2BlockBlot.create() as HTMLElement;\n editorEl.appendChild(blockDomNode);\n }\n\n // Apply line decorations\n const lineDecs = lineDecsByLine.get(lineNum) ?? [];\n for (const ld of lineDecs) {\n if (ld.className) {\n for (const cls of ld.className.split(/\\s+/).filter(Boolean)) {\n blockDomNode.classList.add(cls);\n }\n }\n if (ld.attributes) {\n for (const [k, v] of Object.entries(ld.attributes)) {\n blockDomNode.setAttribute(k, v);\n }\n }\n }\n\n // Narrow decorations to those overlapping this line\n const lineMarkDecs = markDecs.filter(d => d.from < lineEnd && d.to > lineStart);\n const lineWidgetDecs = widgetDecs.filter(\n d => d.offset >= lineStart && d.offset <= lineEnd,\n );\n\n buildLineContent(blockDomNode, lineText, lineStart, lineMarkDecs, lineWidgetDecs);\n\n // Set error-lens message via data attribute — rendered by ::after pseudo-element\n // so it is completely outside the DOM selection and clipboard path.\n const msgLineDecs = lineDecs.filter(ld => ld.message);\n if (msgLineDecs.length > 0) {\n const text = msgLineDecs.map(ld => ld.message).join(' \\u00b7 ');\n blockDomNode.dataset.message = text;\n blockDomNode.title = text;\n const classes = [\n ...new Set(\n msgLineDecs.flatMap(ld =>\n ld.messageClassName ? ld.messageClassName.split(/\\s+/).filter(Boolean) : [],\n ),\n ),\n ];\n if (classes.length > 0) blockDomNode.dataset.messageClass = classes.join(' ');\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 (editorEl.children.length > lines.length) {\n editorEl.removeChild(editorEl.lastChild!);\n }\n }\n\n destroy(): void {\n const editorEl = this.scroll.domNode as HTMLElement;\n while (editorEl.firstChild) {\n editorEl.removeChild(editorEl.firstChild);\n }\n }\n}\n\n// ── Plain text extraction ─────────────────────────────────────────────────────\n\n/**\n * Extracts plain text directly from the editor's contenteditable DOM.\n * Handles our structured .v2-line divs as well as browser-inserted markup\n * from edits that happen between render frames.\n */\nexport function extractEditorText(editorEl: HTMLElement): string {\n const lines = Array.from(editorEl.querySelectorAll<HTMLElement>('.v2-line'));\n if (lines.length > 0) {\n return lines.map(lineEl => getLineText(lineEl)).join('\\n');\n }\n // Fallback: raw contenteditable DOM walk\n return extractRawText(editorEl);\n}\n\nfunction getLineText(lineEl: HTMLElement): string {\n let text = '';\n for (const node of lineEl.childNodes) text += getNodeText(node);\n return text;\n}\n\nfunction getNodeText(node: Node): string {\n if (node.nodeType === Node.TEXT_NODE) return (node as Text).data;\n if (!(node instanceof Element)) return '';\n if (node.classList.contains('v2-widget')) return '';\n if (node.classList.contains('v2-line-message')) return '';\n if (node.tagName === 'BR') return '';\n let text = '';\n for (const child of node.childNodes) text += getNodeText(child);\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 if (node.classList.contains('v2-widget')) continue;\n\n const isBlock = node.tagName === 'DIV' || node.tagName === 'P';\n if (isBlock && !firstBlock) result += '\\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 * WidgetDecoration spans (.v2-widget) are skipped — they are zero-width in\n * the text model (not part of the value string).\n * <br> elements (used to make empty lines editable) count as 0 characters.\n */\n\nexport interface SavedSelection {\n /** Anchor position as a character offset into the plain text value. */\n anchorOffset: number;\n /** Focus position as a character offset into the plain text value. */\n focusOffset: number;\n}\n\n// ── Text length helpers ───────────────────────────────────────────────────────\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) return (node as Text).length;\n if (!(node instanceof Element)) return 0;\n if (node.classList.contains('v2-widget')) return 0;\n if (node.tagName === 'BR') return 0;\n let len = 0;\n for (const child of node.childNodes) len += textModelLength(child);\n return len;\n}\n\n// ── DOM → text offset ─────────────────────────────────────────────────────────\n\n/**\n * Converts a DOM (node, nodeOffset) pair inside `root` to a plain-text offset.\n * Returns -1 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>('.v2-line'));\n let totalOffset = 0;\n\n for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {\n if (lineIdx > 0) totalOffset++; // \\n between lines\n\n const line = lines[lineIdx]!;\n const result = walkForOffset(\n line,\n targetNode,\n targetNodeOffset,\n totalOffset,\n );\n\n if (result.found) return result.offset;\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 // Found the target node\n if (node.nodeType === Node.TEXT_NODE) {\n return { found: true, offset: currentOffset + targetNodeOffset };\n }\n // Element node — targetNodeOffset is a child index\n let off = currentOffset;\n const children = Array.from(node.childNodes);\n for (let i = 0; i < targetNodeOffset && i < children.length; i++) {\n off += textModelLength(children[i]!);\n }\n return { found: true, offset: off };\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('v2-widget')) {\n return { found: false, offset: currentOffset };\n }\n if (node.tagName === 'BR') {\n return { found: false, offset: currentOffset };\n }\n\n let off = currentOffset;\n for (const child of node.childNodes) {\n const result = walkForOffset(child, targetNode, targetNodeOffset, off);\n if (result.found) return result;\n off = result.offset;\n }\n return { found: false, offset: off };\n }\n\n return { found: false, offset: currentOffset };\n}\n\n// ── Text offset → DOM position ────────────────────────────────────────────────\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 * Returns null if offset is out of range.\n */\nexport function textOffsetToDom(\n root: Element,\n targetOffset: number,\n): DomPosition | null {\n const lines = Array.from(root.querySelectorAll<HTMLElement>('.v2-line'));\n let remaining = targetOffset;\n\n for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {\n if (lineIdx > 0) {\n if (remaining === 0) {\n // Position at boundary between lines — place at start of this line\n const line = lines[lineIdx]!;\n return { node: line, offset: 0 };\n }\n remaining--; // consume the \\n\n }\n\n const line = lines[lineIdx]!;\n const lineLen = textModelLength(line);\n\n if (remaining <= lineLen) {\n const pos = walkToOffset(line, remaining);\n if (pos) return pos;\n // Cursor at end of line element\n return { node: line, offset: line.childNodes.length };\n }\n\n remaining -= lineLen;\n }\n\n // Beyond end of content — place at end of last line\n const lastLine = lines[lines.length - 1];\n if (lastLine) return { node: lastLine, offset: lastLine.childNodes.length };\n return { node: root, offset: root.childNodes.length };\n}\n\n/**\n * Walk `node`'s subtree to find the DOM position corresponding to\n * `remaining` 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, remaining: number): DomPosition | null {\n if (node.nodeType === Node.TEXT_NODE) {\n const textNode = node as Text;\n if (remaining <= textNode.length)\n return { node: textNode, offset: remaining };\n return null;\n }\n\n if (node instanceof Element) {\n if (node.classList.contains('v2-widget')) return null;\n if (node.tagName === 'BR') return null;\n\n let childOffset = 0;\n for (const child of node.childNodes) {\n const childLen = textModelLength(child);\n if (remaining <= childLen) {\n const result = walkToOffset(child, remaining);\n if (result) return result;\n // Target is at boundary inside this child\n return { node: node, offset: childOffset + 1 };\n }\n remaining -= childLen;\n childOffset++;\n }\n }\n\n return null;\n}\n\n// ── Save / Restore ────────────────────────────────────────────────────────────\n\n/**\n * Captures the current browser selection as plain-text offsets relative to `root`.\n * Returns null if there is no selection or the selection is outside `root`.\n */\nexport function saveSelection(root: Element): SavedSelection | null {\n // Chrome does not expose shadow-DOM selections via window.getSelection().\n // Use shadowRoot.getSelection() when available, falling back to window.getSelection().\n const rootNode = root.getRootNode();\n const sel =\n (rootNode as unknown as { getSelection?: () => Selection | null })\n .getSelection?.() ?? window.getSelection();\n if (!sel || sel.rangeCount === 0) return null;\n\n const range = sel.getRangeAt(0);\n if (!root.contains(range.commonAncestorContainer)) return null;\n\n const anchorOffset = domToTextOffset(\n root,\n range.startContainer,\n range.startOffset,\n );\n const focusOffset = domToTextOffset(\n root,\n range.endContainer,\n range.endOffset,\n );\n\n return { anchorOffset, focusOffset };\n}\n\n/**\n * Restores a previously saved selection inside `root`.\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 if (!anchor || !focus) return;\n\n try {\n const sel = window.getSelection();\n if (!sel) return;\n const range = document.createRange();\n range.setStart(anchor.node, anchor.offset);\n range.setEnd(focus.node, focus.offset);\n sel.removeAllRanges();\n sel.addRange(range);\n } catch {\n // setStart/setEnd can throw on invalid offsets — ignore gracefully\n }\n}\n","// ── Decoration types ─────────────────────────────────────────────────────────\n\n/**\n * A styled inline range over characters [from, to).\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 id: string;\n type: 'mark';\n /** Inclusive start offset (0-based character index into plain text). */\n from: number;\n /** Exclusive end offset. */\n to: number;\n className?: string;\n bold?: boolean;\n italic?: boolean;\n color?: string;\n background?: string;\n underline?: 'solid' | 'wavy' | 'dotted' | 'dashed';\n underlineColor?: string;\n attributes?: Record<string, string>;\n}\n\n/**\n * A decoration applied to an entire logical line.\n * Adds a CSS class and/or data attributes to the line div, and optionally\n * appends an error-lens style annotation message at the end of the line.\n */\nexport interface LineDecoration {\n id: string;\n type: 'line';\n /** 1-based logical line number. */\n line: number;\n className?: string;\n /**\n * Error-lens style annotation text shown at the end of the line.\n * Rendered via `::after` pseudo-element on the line div (not a real DOM node),\n * so it is completely excluded from selection and clipboard operations.\n */\n message?: string;\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 * .v2-line[data-message-class~=\"error\"][data-message]::after { color: red; }\n * ```\n */\n messageClassName?: string;\n attributes?: Record<string, string>;\n /**\n * Override the built-in gutter cell text for this line.\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`, `list-numbers`, etc.)\n */\n gutterContent?: string | null;\n}\n\n/**\n * A non-editable DOM element inserted at a character offset.\n * Widgets are purely visual and do not appear in the plain text value.\n */\nexport interface WidgetDecoration {\n id: string;\n type: 'widget';\n /** Character offset. Widget is placed before (or after) the character at this position. */\n offset: number;\n /** Factory called each render cycle. Must return a new element each time. */\n create(): HTMLElement;\n /** Whether to place the widget before or after the character at `offset`. Default: 'before'. */\n side?: 'before' | 'after';\n}\n\nexport type Decoration = MarkDecoration | LineDecoration | WidgetDecoration;\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 * 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 /** Exclusive end offset. */\n to: number;\n /** Semantic token type, e.g. `\"keyword\"`, `\"string\"`, `\"comment\"`. */\n type: string;\n /** Optional TextMate / VS Code scope list (e.g. `[\"keyword.control\", \"source.js\"]`). */\n scopes?: string[];\n}\n\n// ── Plugin types ─────────────────────────────────────────────────────────────\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 * // later:\n * api.setDecorations([...]);\n * api.scheduleUpdate();\n * ```\n */\nexport interface RCTextareaPluginAPI {\n /** The host rc-textarea element. */\n readonly host: HTMLElement;\n readonly value: string;\n\n /** Normalized selection start offset (always ≤ selectionEnd). */\n readonly selectionStart: number;\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 * or `null` if the editor is not focused or the cursor is outside the editor.\n * Useful for anchoring autocomplete popups or hover tooltips to the cursor.\n */\n getCursorRect(): DOMRect | null;\n\n /**\n * Returns the word at the current cursor position, 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 * Returns an unsubscribe function — call it in your plugin's `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(\n callback: (selectionStart: number, selectionEnd: number) => void,\n ): () => void;\n\n addDecoration(d: DecorationInput): string;\n removeDecoration(id: string): void;\n clearDecorations(): void;\n setDecorations(decorations: DecorationInput[]): void;\n /** Returns the decorations this plugin has currently set, in insertion order. */\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 * Pass a `CSSStyleSheet` object to share an already-constructed sheet (zero\n * extra parsing cost), or a raw CSS text string to compile and adopt a new one.\n * Returns the adopted `CSSStyleSheet` so it can be passed to `removeStyleSheet`\n * if explicit removal is needed before the plugin is unmounted.\n *\n * Adopted sheets are **automatically removed** when the plugin is unmounted\n * (via `removePlugin()` or `usePlugin()` with a replacement).\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 * The sheet does not need to have been adopted via `adoptStyleSheet` —\n * any sheet already present in `adoptedStyleSheets` may be removed.\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 * ```ts\n * editor.usePlugin({\n * highlight(value, api) {\n * const html = hljs.highlight(value, { language: 'js' }).value;\n * api.setDecorations(api.decorationsFromHtml(html));\n * },\n * });\n * ```\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 * ```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 * 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 * No-op when the selection is collapsed (no text selected).\n *\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 * 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 * hljs.registerLanguage('javascript', javascript);\n *\n * editor.usePlugin({\n * highlight(value, api) {\n * const html = hljs.highlight(value, { language: 'javascript' }).value;\n * api.setDecorations(api.decorationsFromHtml(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 * 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 /** Called when the plugin is replaced or the element disconnects. */\n destroy?(): void;\n /**\n * Display-layer value transform — called before `update`/`highlight` in\n * read-only mode. 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 * Return `null` or `void` to leave the value unchanged.\n */\n transform?(value: string, api: RCTextareaPluginAPI): string | null | void;\n /**\n * Imperative decoration API — called on each value change.\n * Use `api.setDecorations()` to apply decorations.\n */\n update?(value: string, api: RCTextareaPluginAPI): void | Promise<void>;\n /**\n * HTML-based compat — called on each value change.\n * Return an HTML string (e.g. from hljs/prism); it will be parsed via\n * `api.decorationsFromHtml()` and applied as mark decorations.\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// ── Pattern types ─────────────────────────────────────────────────────────────\n\n/**\n * The subset of `MarkDecoration` properties used for styling.\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 id: string;\n pattern: RegExp;\n className?: string;\n bold?: boolean;\n italic?: boolean;\n color?: string;\n background?: string;\n underline?: 'solid' | 'wavy' | 'dotted' | 'dashed';\n underlineColor?: string;\n attributes?: Record<string, string>;\n /**\n * Factory called for each regex match. Return a partial LineDecoration\n * (message, messageClassName, className, attributes) to add an error-lens\n * annotation on the matched line, or `null` to skip.\n */\n createLineDecoration?: (\n match: RegExpMatchArray,\n ) => Omit<LineDecoration, 'id' | 'type' | 'line'> | null;\n /**\n * Per-named-capture-group decoration styles. 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// ── Line decorator types ──────────────────────────────────────────────────────\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** — `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 * if (m) results.push({ type: 'mark', from: m.index, to: m.index + m[0].length, className: 'kw' });\n * return results;\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 /** 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 {\n Decoration,\n MarkDecoration,\n LineDecoration,\n DecorationInput,\n} from './types.ts';\nexport { generateId } from './types.ts';\n\n// ── Edit detection ────────────────────────────────────────────────────────────\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 /** Number of characters removed. */\n removed: number;\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 */\nexport function findEdit(oldValue: string, newValue: string): Edit {\n let start = 0;\n while (\n start < oldValue.length &&\n start < newValue.length &&\n oldValue[start] === newValue[start]\n ) {\n start++;\n }\n let oldEnd = oldValue.length;\n let newEnd = newValue.length;\n while (\n oldEnd > start &&\n newEnd > start &&\n oldValue[oldEnd - 1] === newValue[newEnd - 1]\n ) {\n oldEnd--;\n newEnd--;\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 */\nfunction remapMarkRange(\n from: number,\n to: number,\n edit: Edit,\n): { from: number; to: number } | null {\n const editEnd = edit.start + edit.removed;\n const delta = edit.inserted - edit.removed;\n\n if (to <= edit.start) return { from, to }; // entirely before edit\n if (from >= editEnd) return { from: from + delta, to: to + delta }; // entirely after\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 if (newFrom >= newTo) return null;\n return { from: newFrom, to: newTo };\n}\n\n/**\n * Count the number of `\\n` characters in `text` before `offset`.\n * Used to convert a character offset to a 1-based line number.\n */\nfunction countNewlinesBefore(text: string, offset: number): number {\n let count = 0;\n for (let i = 0; i < offset && i < text.length; i++) {\n if (text[i] === '\\n') count++;\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 dec of decorations) {\n if (dec.type === 'mark') {\n const result = remapMarkRange(dec.from, dec.to, edit);\n if (result) mapped.push({ ...dec, from: result.from, to: result.to });\n } else if (dec.type === 'line') {\n if (dec.line < editStartLine) {\n mapped.push(dec); // before edit — unchanged\n } else if (dec.line <= editEndLine) {\n // falls within deleted region — drop\n } else {\n mapped.push({ ...dec, line: dec.line + lineDelta }); // after edit — shift\n }\n } else {\n // WidgetDecoration: treat the offset like a mark's 'from'\n const result = remapMarkRange(dec.offset, dec.offset + 1, edit);\n if (result) mapped.push({ ...dec, offset: result.from });\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) return false;\n const changeSize = Math.max(edit.removed, edit.inserted);\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 mapOrClear(\n decorations: Decoration[],\n oldValue: string,\n newValue: string,\n): Decoration[] {\n const edit = findEdit(oldValue, newValue);\n if (isLargeChange(oldValue, edit)) return [];\n return mapDecorationsThroughChange(decorations, oldValue, newValue);\n}\n\n// ── Decoration ID management ──────────────────────────────────────────────────\n\n/**\n * Add a single decoration to `map`, assigning it a fresh UUID as its `id`.\n * Returns the assigned ID.\n */\nexport function addDecoration(\n map: Map<string, Decoration>,\n input: DecorationInput,\n): string {\n const id = crypto.randomUUID();\n map.set(id, { ...input, id } as Decoration);\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(\n map: Map<string, Decoration>,\n inputs: DecorationInput[],\n): void {\n map.clear();\n for (const input of inputs) {\n const id = crypto.randomUUID();\n map.set(id, { ...input, id } as Decoration);\n }\n}\n\n// Type helpers for extracting subtypes from Decoration union\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 * - 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 * Zero-length matches are skipped to prevent infinite loops.\n */\nexport function matchPatternResults(\n value: string,\n patterns: TextPattern[],\n): { markDecorations: Omit<MarkDecoration, 'id'>[]; lineDecorations: Omit<LineDecoration, 'id'>[] } {\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 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 continue;\n }\n\n const from = match.index;\n\n if (pattern.captureGroups) {\n // Per-group mode: emit one MarkDecoration per named capture group.\n // Unmatched optional groups (indices === undefined) are skipped.\n const groupIndices = match.indices?.groups;\n if (groupIndices) {\n for (const [groupName, style] of Object.entries(pattern.captureGroups)) {\n const range = groupIndices[groupName];\n if (range === undefined) continue;\n const [groupStart, groupEnd] = range;\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 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 if (lineInput) {\n const line = value.slice(0, from).split('\\n').length; // 1-based line number\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 } from 'lit/decorators.js';\n\nimport { styles } from './rc-textarea.styles.ts';\nimport { V2Document, extractEditorText } from './document.ts';\nimport {\n saveSelection,\n restoreSelection,\n type SavedSelection,\n} from './selection.ts';\nimport { mapOrClear, addDecoration, setDecorations } from './decoration.ts';\nimport { matchPatternResults } from './pattern-matcher.ts';\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\n// ── Undo entry ────────────────────────────────────────────────────────────────\n\ninterface UndoEntry {\n value: string;\n anchorOffset: number;\n focusOffset: number;\n}\n\nconst MAX_UNDO = 100;\n\n// ── decorationsFromHtml utility ───────────────────────────────────────────────\n\n/**\n * Parse a highlight.js / prism.js HTML string (a flat tree of\n * `<span class=\"token ...\">text</span>` elements) into `MarkDecoration`\n * objects covering the corresponding plain-text character ranges.\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. Nested spans produce decorations for every nesting level, so the\n * outermost span wins at render time via the \"smallest decoration\" rule in\n * `buildLineContent`.\n */\nfunction decorationsFromHtml(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 return;\n }\n if (!(node instanceof HTMLElement)) return;\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) walk(child);\n return result;\n}\n\n// ── RCTextarea ─────────────────────────────────────────────────────────────\n\n/**\n * Enhanced textarea with line decorations, gutter, and plugin API.\n *\n * @slot - Accepts a native `<textarea>` element for form wiring and progressive enhancement.\n * @fires rc-textarea-change - Fired when the editor value changes\n * @fires rc-textarea-blur - Fired when the editor loses focus\n * @cssprop [--rc-textarea-border=1px solid ButtonBorder] - Border around the editor\n * @cssprop [--rc-textarea-border-radius=2px] - Border radius of the editor\n * @cssprop [--rc-textarea-background=Field] - Background color of the editor\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 editor 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 // ── Observed properties ───────────────────────────────────────────────\n\n @property({ type: Boolean, attribute: 'line-numbers', reflect: true })\n lineNumbers = false;\n\n @property({ type: Boolean, attribute: 'list-numbers', reflect: true })\n listNumbers = false;\n\n @property({ type: Boolean, attribute: 'gutter', reflect: true })\n gutter = false;\n\n @property({ type: Boolean, attribute: 'word-wrap', reflect: true })\n wordWrap = false;\n\n @property({ type: Boolean, attribute: 'auto-grow', reflect: true })\n autoGrow = false;\n\n @property({ type: Boolean, attribute: 'read-only', reflect: true })\n readOnly = false;\n\n @property({ type: String })\n 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 if (plugin === oldPlugin) return;\n\n this._pluginProperty = plugin;\n\n if (plugin) this.usePlugin(plugin);\n else this.removePlugin();\n\n this.requestUpdate('plugin', oldPlugin);\n }\n\n /**\n * Reactive decorations — set from outside the component without registering a plugin.\n * Ideal for reactive frameworks (Solid, React 19+, Vue 3) where decorations are\n * computed as reactive state and passed directly as a property:\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 // ── Internal state ────────────────────────────────────────────────────\n\n private _value = '';\n private _defaultValue: string | undefined;\n private _initialValueResolved = false;\n private _valueSetByHost = false;\n private _document: V2Document | null = null;\n private _textareaRef: WeakRef<HTMLTextAreaElement> | null = null;\n\n /** Plugin-owned decorations (set via PluginAPI.setDecorations / addDecoration). */\n protected _pluginDecorations = new Map<string, Decoration>();\n /** Pattern-generated decorations (rebuilt on each value change). */\n private _patternDecorations: Decoration[] = [];\n /** Decorations set directly via the `decorations` property (reactive-framework-friendly). */\n private _externalDecorations: DecorationInput[] = [];\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 /** Sequence counter for async plugin safety (discard stale results). */\n private _pluginSeq = 0;\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 `.v2-line` element (active line). */\n private _activeLine: HTMLElement | null = null;\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) return;\n this._onSelectionChange();\n };\n\n /** Undo/redo stack — necessary because DOM rebuilds invalidate browser's native undo. */\n private _undoStack: UndoEntry[] = [];\n private _undoIndex = -1;\n\n private _resizeObserver: ResizeObserver | null = null;\n /** Cached per-line gutter labels from the last render — reused by ResizeObserver. */\n private _gutterLabels: (string | null)[] = [];\n\n // ── Public value property ─────────────────────────────────────────────\n\n @property({ type: String })\n get value(): string {\n return this._value;\n }\n\n set value(v: string) {\n const oldValue = this._value;\n\n if (v === this._value) return;\n\n this._valueSetByHost = true;\n this._initialValueResolved = true;\n this._value = v;\n this._syncTextareaValue();\n this._scheduleRender();\n this.requestUpdate('value', oldValue);\n }\n\n /** Initial uncontrolled editor value. */\n @property({ type: String })\n get defaultValue(): string | undefined {\n return this._defaultValue;\n }\n\n /** Initial uncontrolled editor value. */\n set defaultValue(v: string | undefined) {\n const oldValue = this._defaultValue;\n\n this._defaultValue = v;\n\n if (!this._valueSetByHost && !this._initialValueResolved && v !== undefined) {\n this._value = v;\n this._initialValueResolved = true;\n this._syncTextareaValue();\n this._scheduleRender();\n }\n\n this.requestUpdate('defaultValue', oldValue);\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────\n\n override connectedCallback(): void {\n super.connectedCallback();\n document.addEventListener(\n 'selectionchange',\n this._docSelectionChangeHandler,\n );\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n document.removeEventListener(\n 'selectionchange',\n this._docSelectionChangeHandler,\n );\n this._plugin?.destroy?.();\n this._plugin = null;\n this._pluginApi = null;\n this._clearPluginSheets();\n this._cursorCallbacks.clear();\n this._resizeObserver?.disconnect();\n if (this._rafHandle !== null) {\n cancelAnimationFrame(this._rafHandle);\n this._rafHandle = null;\n }\n }\n\n override firstUpdated(): void {\n const editorEl = this._getEditorEl();\n if (editorEl) {\n this._document = new V2Document(editorEl as HTMLDivElement);\n this._bindEditorEvents(editorEl);\n }\n this._resizeObserver = new ResizeObserver(() => {\n this._syncGutter();\n this._syncGutterHeights();\n });\n this._resizeObserver.observe(this);\n\n // Render any value already set via defaultValue/value before first update.\n // The slot-change path covers editable mode (slotted <textarea> triggers it);\n // read-only mode has no slotted element so the render must be seeded here.\n this._scheduleRender();\n }\n\n override updated(changed: Map<string, unknown>): void {\n if (changed.has('readOnly')) {\n const editorEl = this._getEditorEl();\n if (editorEl) editorEl.contentEditable = this.readOnly ? 'false' : 'true';\n this._syncGutterHeights(); // re-sync gutter padding (#editor padding: 0 in read-only)\n }\n if (changed.has('label')) {\n const editorEl = this._getEditorEl();\n if (editorEl && this.label)\n editorEl.setAttribute('aria-label', this.label);\n }\n }\n\n // ── Template ──────────────────────────────────────────────────────────\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 <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 aria-label=${this.label ?? ''}\n ></div>\n <slot @slotchange=${this._onSlotChange}></slot>\n </div>\n </div>\n `;\n }\n\n // ── Slot change — lightDOM textarea wiring ────────────────────────────\n\n private _onSlotChange(): void {\n const slot = this.shadowRoot?.querySelector(\n 'slot',\n ) as HTMLSlotElement | null;\n if (!slot) return;\n\n const textarea = slot\n .assignedElements({ flatten: true })\n .find(\n (el): el is HTMLTextAreaElement => el instanceof HTMLTextAreaElement,\n );\n\n if (!textarea) return;\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 textarea.setAttribute('aria-hidden', 'true');\n textarea.tabIndex = -1;\n\n // Sync attributes from textarea → editor ARIA / state\n const editorEl = this._getEditorEl();\n if (editorEl) {\n if (!this.label && textarea.getAttribute('aria-label')) {\n editorEl.setAttribute(\n 'aria-label',\n textarea.getAttribute('aria-label')!,\n );\n }\n const placeholder = textarea.getAttribute('placeholder');\n if (placeholder) editorEl.setAttribute('aria-placeholder', placeholder);\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', () => {\n const editorEl = this._getEditorEl();\n if (editorEl) editorEl.setAttribute('aria-invalid', 'true');\n });\n\n // Sync typography from textarea's computed style to editor\n this._syncTypography(textarea);\n\n this._scheduleRender();\n }\n\n // ── Editor event binding ──────────────────────────────────────────────\n\n private _bindEditorEvents(editorEl: HTMLElement): void {\n editorEl.addEventListener('compositionstart', () => {\n this._composing = true;\n });\n editorEl.addEventListener('compositionend', () => {\n this._composing = false;\n this._onInput();\n });\n editorEl.addEventListener('input', this._onInputEvent);\n editorEl.addEventListener('keydown', this._onKeyDown);\n editorEl.addEventListener('paste', this._onPaste);\n editorEl.addEventListener('focus', () => {\n this.dispatchEvent(\n new CustomEvent('rc-textarea-focus', {\n bubbles: true,\n composed: true,\n }),\n );\n });\n editorEl.addEventListener('blur', () => {\n this.dispatchEvent(\n new CustomEvent('rc-textarea-blur', {\n bubbles: true,\n composed: true,\n }),\n );\n // Clear active line when editor loses focus\n this._activeLine?.classList.remove('v2-line--active');\n this._activeLine = null;\n });\n // Selection tracking is handled by the document-level selectionchange listener\n // added in connectedCallback — covers arrow keys, mouse, touch, and programmatic changes.\n }\n\n private _onInputEvent = (): void => {\n if (!this._composing) this._onInput();\n };\n\n private _onInput(): void {\n const editorEl = this._getEditorEl();\n if (!editorEl) return;\n\n const newValue = extractEditorText(editorEl);\n if (newValue === this._value) return;\n\n const oldValue = this._value;\n const preEditSel = this._savedSelection; // capture before saveSelection() overwrites it\n\n // Map existing plugin decorations through the text change\n const mappedDecs = mapOrClear(\n [...this._pluginDecorations.values()],\n oldValue,\n newValue,\n );\n this._pluginDecorations.clear();\n for (const dec of mappedDecs) this._pluginDecorations.set(dec.id, dec);\n\n this._value = newValue;\n this._syncTextareaValue(true);\n\n // Save cursor position AFTER the browser has processed the input\n this._savedSelection = saveSelection(editorEl);\n\n // On the very first edit, capture the pre-edit state as the undo baseline so\n // that the first Ctrl+Z can restore it. Without this, _undoIndex would be 0\n // after the first push and _undo()'s `<= 0` guard would prevent any undo.\n // Note: selectionchange fires AFTER input, so _savedSelection still holds the\n // pre-edit cursor at this point (before saveSelection() overwrites it above).\n if (this._undoStack.length === 0) {\n this._undoStack.push({\n value: oldValue,\n anchorOffset: preEditSel?.anchorOffset ?? 0,\n focusOffset: preEditSel?.focusOffset ?? 0,\n });\n this._undoIndex = 0;\n }\n\n // Push to undo stack\n this._pushUndo(this._savedSelection);\n\n this._dispatchChange(newValue);\n\n this._scheduleRender();\n }\n\n private _onSelectionChange = (): void => {\n const editorEl = this._getEditorEl();\n if (!editorEl) return;\n const sel = saveSelection(editorEl);\n if (sel) {\n this._savedSelection = sel;\n this.dispatchEvent(\n new CustomEvent('rc-textarea-select', {\n bubbles: true,\n composed: true,\n detail: {\n selectionStart: sel.anchorOffset,\n selectionEnd: sel.focusOffset,\n },\n }),\n );\n this._updateActiveLine();\n const start = Math.min(sel.anchorOffset, sel.focusOffset);\n const end = Math.max(sel.anchorOffset, sel.focusOffset);\n for (const cb of this._cursorCallbacks) cb(start, end);\n }\n };\n\n private _updateActiveLine(): void {\n const editorEl = this._getEditorEl();\n if (!editorEl) return;\n // Chrome does not expose shadow-DOM selections via window.getSelection() —\n // use shadowRoot.getSelection() when available (Chrome 53+), falling back to\n // window.getSelection() for Firefox and other browsers.\n const sel =\n (this.shadowRoot as unknown as { getSelection?: () => Selection | null })\n .getSelection?.() ?? window.getSelection();\n let newActive: HTMLElement | null = null;\n if (sel?.focusNode && editorEl.contains(sel.focusNode)) {\n let node: Node | null = sel.focusNode;\n while (node && node !== editorEl) {\n if (node instanceof HTMLElement && node.classList.contains('v2-line')) {\n newActive = node;\n break;\n }\n node = node.parentNode;\n }\n }\n if (newActive === this._activeLine) return;\n this._activeLine?.classList.remove('v2-line--active');\n this._activeLine = newActive;\n this._activeLine?.classList.add('v2-line--active');\n\n // Update active line number highlight\n this._updateActiveGutterCell();\n }\n\n private _updateActiveGutterCell(): void {\n const gutterEl = this.shadowRoot?.getElementById('gutter-cells');\n if (!gutterEl) return;\n\n // Find and remove previous active state\n const prevActive = gutterEl.querySelector('.gutter-cell--active');\n if (prevActive) prevActive.classList.remove('gutter-cell--active');\n\n // Find line index and highlight corresponding line number\n if (this._activeLine) {\n const editorEl = this._getEditorEl();\n if (!editorEl) return;\n\n const allLines = editorEl.querySelectorAll('.v2-line');\n for (let i = 0; i < allLines.length; i++) {\n if (allLines[i] === this._activeLine) {\n const lineNumberEl = gutterEl.children[i];\n if (lineNumberEl) {\n lineNumberEl.classList.add('gutter-cell--active');\n }\n break;\n }\n }\n }\n }\n\n // ── Keyboard handling ─────────────────────────────────────────────────\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 const editorEl = this._getEditorEl();\n if (!editorEl) return;\n\n // execCommand('insertText') does not handle \\n — browsers create new divs\n // that lack the 'v2-line' class, so extractEditorText() loses all content\n // after the first newline. Apply multi-line inserts directly to the value model.\n if (text.includes('\\n')) {\n const sel = saveSelection(editorEl) ?? this._savedSelection;\n const anchor = Math.min(sel?.anchorOffset ?? 0, sel?.focusOffset ?? 0);\n const focus = Math.max(sel?.anchorOffset ?? 0, sel?.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 mappedDecs = mapOrClear(\n [...this._pluginDecorations.values()],\n oldValue,\n newValue,\n );\n this._pluginDecorations.clear();\n for (const dec of mappedDecs) this._pluginDecorations.set(dec.id, dec);\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: sel?.anchorOffset ?? 0,\n focusOffset: sel?.focusOffset ?? 0,\n });\n this._undoIndex = 0;\n }\n this._pushUndo(this._savedSelection);\n this._dispatchChange(newValue);\n this._scheduleRender();\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 const editorEl = this._getEditorEl();\n if (!editorEl) return;\n\n const sel = saveSelection(editorEl) ?? this._savedSelection;\n if (!sel || sel.anchorOffset === sel.focusOffset) return;\n\n const start = Math.min(sel.anchorOffset, sel.focusOffset);\n const end = Math.max(sel.anchorOffset, sel.focusOffset);\n const selected = this._value.slice(start, end);\n const oldValue = this._value;\n const newValue =\n oldValue.slice(0, start) + prefix + selected + suffix + oldValue.slice(end);\n\n const mapped = mapOrClear([...this._pluginDecorations.values()], oldValue, newValue);\n this._pluginDecorations.clear();\n for (const d of mapped) this._pluginDecorations.set(d.id, d);\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\n // ── Paste handling ────────────────────────────────────────────────────\n\n private _onPaste = (e: ClipboardEvent): void => {\n e.preventDefault();\n const text = e.clipboardData?.getData('text/plain') ?? '';\n if (!text) return;\n // Normalize line endings\n const normalized = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n this._insertText(normalized);\n };\n\n // ── Undo/Redo ─────────────────────────────────────────────────────────\n\n /** Reset the undo/redo history. Call when the editor 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 // Truncate redo branch\n this._undoStack = this._undoStack.slice(0, this._undoIndex + 1);\n this._undoStack.push(entry);\n if (this._undoStack.length > MAX_UNDO) this._undoStack.shift();\n this._undoIndex = this._undoStack.length - 1;\n }\n\n private _undo(): void {\n if (this._undoIndex <= 0) return;\n this._undoIndex--;\n this._applyUndoEntry(this._undoStack[this._undoIndex]!);\n }\n\n private _redo(): void {\n if (this._undoIndex >= this._undoStack.length - 1) return;\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 // ── Plugin API ────────────────────────────────────────────────────────\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 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 s = component._savedSelection;\n return s ? Math.min(s.anchorOffset, s.focusOffset) : 0;\n },\n get selectionEnd() {\n const s = component._savedSelection;\n return s ? Math.max(s.anchorOffset, s.focusOffset) : 0;\n },\n getCursorRect(): DOMRect | null {\n const sel = window.getSelection();\n if (!sel?.focusNode) return null;\n const editorEl = component._getEditorEl();\n if (!editorEl || !editorEl.contains(sel.focusNode)) return null;\n try {\n const range = document.createRange();\n range.setStart(sel.focusNode, sel.focusOffset);\n range.collapse(true);\n const rect = range.getBoundingClientRect();\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 if (!text) return null;\n let start = offset;\n while (start > 0 && /\\w/.test(text[start - 1]!)) start--;\n let end = offset;\n while (end < text.length && /\\w/.test(text[end]!)) end++;\n if (start === end) return null;\n return { word: text.slice(start, end), from: start, to: end };\n },\n onCursorMove(\n callback: (selectionStart: number, selectionEnd: number) => void,\n ): () => 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) component._scheduleRender();\n },\n adoptStyleSheet(sheetOrCssText: CSSStyleSheet | string): CSSStyleSheet {\n let sheet: CSSStyleSheet;\n if (typeof sheetOrCssText === 'string') {\n sheet = new CSSStyleSheet();\n sheet.replaceSync(sheetOrCssText);\n } else {\n sheet = sheetOrCssText;\n }\n const sr = component.shadowRoot;\n if (sr && !sr.adoptedStyleSheets.includes(sheet)) {\n sr.adoptedStyleSheets = [...sr.adoptedStyleSheets, sheet];\n }\n component._pluginSheets.add(sheet);\n return sheet;\n },\n removeStyleSheet(sheet: CSSStyleSheet): void {\n const sr = component.shadowRoot;\n if (sr) {\n sr.adoptedStyleSheets = sr.adoptedStyleSheets.filter(\n (s) => s !== sheet,\n );\n }\n component._pluginSheets.delete(sheet);\n },\n decorationsFromHtml(html: string): Omit<MarkDecoration, 'id'>[] {\n return decorationsFromHtml(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 for (const t of tokens) {\n const style = themeMap[t.type];\n if (style) result.push({ type: 'mark', from: t.from, to: t.to, ...style });\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) return;\n const sr = this.shadowRoot;\n if (sr) {\n sr.adoptedStyleSheets = sr.adoptedStyleSheets.filter(\n (s) => !this._pluginSheets.has(s),\n );\n }\n this._pluginSheets.clear();\n }\n\n // ── Pattern API ───────────────────────────────────────────────────────\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 removePattern(id: string): void {\n this._patterns.delete(id);\n this._scheduleRender();\n }\n\n clearPatterns(): void {\n this._patterns.clear();\n this._scheduleRender();\n }\n\n // ── Render pipeline ───────────────────────────────────────────────────\n\n protected _scheduleRender(): void {\n if (this._rafHandle !== null) return;\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) return;\n\n this._isRendering = true;\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 if (this._plugin && this._pluginApi && this._plugin.transform && this.readOnly) {\n const transformed = this._plugin.transform(this._value, this._pluginApi);\n if (typeof transformed === 'string') renderValue = transformed;\n }\n\n // Run pattern matcher\n const { markDecorations: patMarkDecs, lineDecorations: patLineDecs } =\n matchPatternResults(renderValue, [...this._patterns.values()]);\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 if (renderSeq !== this._pluginSeq) return; // stale — newer render started\n }\n\n if (this._plugin.highlight) {\n const html = await this._plugin.highlight(renderValue, api);\n if (renderSeq !== this._pluginSeq) return;\n if (typeof html === 'string') {\n const decs = decorationsFromHtml(html);\n // Add parsed decorations on top of existing plugin decorations\n for (const d of decs) {\n addDecoration(this._pluginDecorations, d);\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 const editorEl = this._getEditorEl();\n if (!editorEl) return;\n\n this._document.build(renderValue, allDecorations);\n\n // Restore cursor\n if (this._savedSelection) {\n restoreSelection(editorEl, 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 // ── Gutter ────────────────────────────────────────────────────────────\n\n /**\n * Compute the label string for each gutter cell based on the current gutter\n * mode (`lineNumbers`, `listNumbers`, `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(allDecorations: Decoration[], value = this._value): (string | null)[] {\n const lines = value.split('\\n');\n\n const overrides = new Map<number, string | null>();\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)) return overrides.get(lineNum)!;\n\n if (this.lineNumbers) return String(lineNum);\n\n if (this.listNumbers) {\n if (lineText.trim() === '') return null;\n counter++;\n return `${counter}.`;\n }\n\n return null; // `gutter` mode — empty by default, plugins fill via overrides\n });\n }\n\n /**\n * Synchronize the pixel height of each gutter cell to match the\n * corresponding `.v2-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 const gutterEl = this.shadowRoot?.getElementById('gutter-cells');\n const editorEl = this._getEditorEl();\n if (!gutterEl || !editorEl) return;\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 cs = getComputedStyle(editorEl);\n const pt = cs.paddingTop;\n const pb = cs.paddingBottom;\n if (gutterEl.style.paddingTop !== pt) gutterEl.style.paddingTop = pt;\n if (gutterEl.style.paddingBottom !== pb) gutterEl.style.paddingBottom = pb;\n\n const lineEls = editorEl.querySelectorAll<HTMLElement>('.v2-line');\n const spans = gutterEl.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 lhPx = `${lineEls[0].getBoundingClientRect().height}px`;\n if (gutterEl.style.lineHeight !== lhPx) gutterEl.style.lineHeight = lhPx;\n }\n for (let i = 0; i < spans.length; i++) {\n (spans[i] as HTMLElement).style.height = '';\n }\n return;\n }\n\n // word-wrap: per-span explicit heights drive alignment; clear any forced line-height.\n if (gutterEl.style.lineHeight) gutterEl.style.lineHeight = '';\n for (let i = 0; i < lineEls.length && i < spans.length; i++) {\n const h = lineEls[i]!.getBoundingClientRect().height;\n const hStr = `${h}px`;\n const span = spans[i] as HTMLElement;\n if (span.style.height !== hStr) span.style.height = hStr;\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) return;\n\n const gutterEl = this.shadowRoot?.getElementById('gutter-cells');\n if (!gutterEl) return;\n\n if (labels !== undefined) this._gutterLabels = labels;\n const current = this._gutterLabels;\n\n // Sync count\n while (gutterEl.children.length < current.length) {\n const span = document.createElement('span');\n span.className = 'gutter-cell';\n gutterEl.appendChild(span);\n }\n while (gutterEl.children.length > current.length) {\n gutterEl.removeChild(gutterEl.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 = gutterEl.children[i] as HTMLElement;\n if (span.textContent !== label) span.textContent = label;\n }\n }\n\n // ── Typography sync ───────────────────────────────────────────────────\n\n private _syncTypography(textarea: HTMLTextAreaElement): void {\n const editorEl = this._getEditorEl();\n if (!editorEl) return;\n\n const cs = 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 hostCs = window.getComputedStyle(this);\n if (!hostCs.getPropertyValue('--rc-textarea-font-family')) {\n for (const prop of props) {\n const value = cs[prop];\n if (value && typeof value === 'string') {\n (editorEl.style as unknown as Record<string, string>)[\n prop as string\n ] = value;\n }\n }\n }\n }\n\n // ── Form integration ──────────────────────────────────────────────────\n\n protected _syncTextareaValue(fromUser = false): void {\n const textarea = this._textareaRef?.deref();\n if (textarea) {\n textarea.value = this._value;\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 // ── Helpers ───────────────────────────────────────────────────────────\n\n private _getEditorEl(): HTMLElement | null {\n return this.shadowRoot?.getElementById('editor') as HTMLElement | null;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'rc-textarea': RCTextarea;\n }\n}\n","import type {\n DecorationInput,\n LineDecoratorPlugin,\n MarkDecoration,\n RCTextareaPlugin,\n} from './types.ts';\n\n/**\n * Options for `createLineDecoratorPlugin`.\n */\nexport interface LineDecoratorPluginOptions {\n /**\n * An array of subscriber setup functions. Each function receives a callback\n * and should call it whenever an external value changes (e.g. a reactive\n * signal). It may return an optional cleanup/unsubscribe function called on\n * 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 * 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 * - 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(a) {\n if (decorator.styles) a.adoptStyleSheet(decorator.styles);\n for (const subscribe of options.watch ?? []) {\n const cleanup = subscribe(() => a.scheduleUpdate());\n if (cleanup) cleanups.push(cleanup);\n }\n },\n\n destroy() {\n for (const cleanup of cleanups) cleanup();\n cleanups.length = 0;\n },\n\n update(value, a) {\n const lines = value.split('\\n');\n const allDecorations: DecorationInput[] = [];\n let lineStart = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n for (const d of decorator.decorateLine(line, i)) {\n if (d.type === 'mark') {\n // Convert line-relative offsets to absolute document offsets\n allDecorations.push({\n ...(d as Omit<MarkDecoration, 'id'>),\n from: lineStart + d.from,\n to: lineStart + d.to,\n });\n } else {\n // LineDecoration already uses 1-based line numbers — pass through\n allDecorations.push(d);\n }\n }\n lineStart += line.length + 1; // +1 for the '\\n'\n }\n\n if (options.extraDecorations) {\n allDecorations.push(...options.extraDecorations(value));\n }\n\n a.setDecorations(allDecorations);\n },\n };\n}\n","import type { RCTextareaPluginAPI, DecorationInput } from './types.ts';\n\n// ── Public types ──────────────────────────────────────────────────────────────\n\nexport interface LineAction {\n id: string;\n label: string;\n /** data-icon attribute — host renders via iconify or similar */\n icon?: string;\n onClick: () => void;\n}\n\nexport interface LineActionsOptions {\n /** Where to place the inline widget. Default: 'append'. */\n position?: 'append';\n /**\n * Create and return a DOM element for the given icon name (e.g. 'mdi-lock-outline').\n * Called when `action.icon` is set. Return `null` to fall back to text label.\n *\n * @example — iconify web component\n * ```ts\n * createIcon: (name) => {\n * const el = document.createElement('iconify-icon');\n * el.setAttribute('icon', name);\n * return el;\n * }\n * ```\n */\n createIcon?: (iconName: string) => HTMLElement | null;\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// ── Styles ────────────────────────────────────────────────────────────────────\n\n// Constructed once at module level and shared across all controller instances —\n// zero extra parsing cost per instantiation (Lit adoptedStyleSheets pattern).\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// ── LineActionsController ─────────────────────────────────────────────────────\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 private readonly _options: LineActionsOptions;\n private _popover: HTMLDivElement | null = null;\n private _lastActionsKey = '';\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 return [];\n }\n\n // inline mode — always hide any lingering popover\n this._hidePopover();\n\n if (actions.length === 0) return [];\n\n const offset = LineActionsController._lineEndOffset(value, lineIndex);\n const actionsSnapshot = [...actions];\n const buttonOptions = { renderButton: this._options.renderButton, createIcon: this._options.createIcon };\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 return [];\n }\n const actions = lineActions.get(activeLineIndex) ?? [];\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 const result: DecorationInput[] = [];\n for (const [lineIndex, actions] of lineActions) {\n if (actions.length > 0) {\n result.push(...this.getDecorations(lineIndex, actions, value, 'inline'));\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 // ── Private helpers ───────────────────────────────────────────────────────\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 for (let i = 0; i < lineIndex && i < lines.length; i++) {\n offset += lines[i]!.length + 1; // +1 for the '\\n'\n }\n if (lineIndex < lines.length) {\n offset += lines[lineIndex]!.length;\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 style.id = POPOVER_STYLE_ID;\n style.textContent = POPOVER_STYLES;\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 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 buildPopoverButtons(this._popover, actions, this._options);\n }\n\n this._positionPopover();\n }\n\n private _positionPopover(): void {\n if (!this._popover) return;\n\n const cursorRect = this._api.getCursorRect();\n const hostRect = this._api.host.getBoundingClientRect();\n\n let top: number;\n const panelHeight = this._popover.offsetHeight || 32;\n\n if (cursorRect) {\n top = cursorRect.bottom + 4;\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 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\n// ── DOM helpers (module-level so they can be used inside widget create() closures) ──\n\nfunction buildButton(\n action: LineAction,\n options: Pick<LineActionsOptions, 'renderButton' | 'createIcon'>,\n): HTMLButtonElement {\n const btn = document.createElement('button');\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.icon) {\n const iconEl = options.createIcon?.(action.icon) ?? null;\n if (iconEl) {\n btn.setAttribute('aria-label', action.label);\n btn.appendChild(iconEl);\n } else {\n // Fallback: data-icon attribute for hosts that process it externally\n btn.dataset['icon'] = action.icon;\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 return btn;\n}\n\nfunction buildWidgetContainer(\n actions: LineAction[],\n options: Pick<LineActionsOptions, 'renderButton' | 'createIcon'>,\n): HTMLElement {\n const container = document.createElement('span');\n container.className = 'rc-line-actions';\n for (const action of actions) {\n container.appendChild(buildButton(action, options));\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","_V2ScrollBlot","_contextOrMutations","V2ScrollBlot","_V2BlockBlot","V2BlockBlot","_V2InlineBlot","el","applyInlineFormats","V2InlineBlot","cls","_V2WidgetBlot","V2WidgetBlot","createRegistry","buildLineContent","lineEl","lineText","lineStart","markDecorations","widgetDecorations","boundarySet","dec","localOffset","boundaries","segStart","segEnd","w","createWidgetEl","segText","bestDec","bestSize","localFrom","localTo","size","spanEl","k","v","V2Document","editorEl","decorations","lines","existingLineEls","lineDecsByLine","markDecs","widgetDecs","arr","lineStartOffset","lineNum","lineEnd","blockDomNode","lineDecs","ld","lineMarkDecs","d","lineWidgetDecs","msgLineDecs","text","extractEditorText","getLineText","extractRawText","getNodeText","result","firstBlock","textModelLength","len","domToTextOffset","targetNode","targetNodeOffset","totalOffset","lineIdx","line","walkForOffset","currentOffset","off","children","textOffsetToDom","targetOffset","lineLen","pos","walkToOffset","lastLine","textNode","childOffset","childLen","saveSelection","sel","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","isLargeChange","changeSize","mapOrClear","addDecoration","map","id","setDecorations","inputs","matchPatternResults","patterns","lineDecorations","pattern","flags","regex","groupIndices","groupName","style","groupStart","groupEnd","lineInput","MAX_UNDO","decorationsFromHtml","html","tmp","charOffset","walk","isSpan","startOffset","_RCTextarea","LitElement","end","cb","e","isUndo","isRedo","normalized","plugin","oldPlugin","changed","slot","textarea","placeholder","preEditSel","mappedDecs","newActive","gutterEl","prevActive","allLines","lineNumberEl","newCursorOffset","suffix","selected","entry","component","s","rect","sheetOrCssText","sheet","sr","tokens","themeMap","t","renderSeq","renderValue","transformed","patMarkDecs","patLineDecs","api","decs","allDecorations","overrides","counter","cs","pt","pb","lineEls","spans","lhPx","hStr","span","labels","current","label","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","buildPopoverButtons","cursorRect","hostRect","top","panelHeight","panelWidth","left","buildButton","action","btn","iconEl","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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