@carbon/ai-chat-components 1.13.0 → 1.14.0-rc.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.
Files changed (194) hide show
  1. package/custom-elements.json +1147 -462
  2. package/es/components/audio-player/src/audio-player.scss.js +1 -1
  3. package/es/components/audio-player/src/transcript.js +15 -0
  4. package/es/components/audio-player/src/transcript.js.map +1 -1
  5. package/es/components/card/src/card-footer.scss.js +1 -1
  6. package/es/components/card/src/card-steps.scss.js +1 -1
  7. package/es/components/card/src/card.scss.js +1 -1
  8. package/es/components/chat-button/src/chat-button.scss.js +1 -1
  9. package/es/components/chat-history/src/chat-history.scss.js +1 -1
  10. package/es/components/chat-shell/src/shell.scss.js +1 -1
  11. package/es/components/code-snippet/src/code-snippet.d.ts +3 -2
  12. package/es/components/code-snippet/src/code-snippet.js +4 -3
  13. package/es/components/code-snippet/src/code-snippet.js.map +1 -1
  14. package/es/components/code-snippet/src/code-snippet.scss.js +1 -1
  15. package/es/components/feedback/src/feedback.js +17 -3
  16. package/es/components/feedback/src/feedback.js.map +1 -1
  17. package/es/components/file-uploads/src/file-upload-item.scss.js +1 -1
  18. package/es/components/file-uploads/src/file-uploads.scss.js +1 -1
  19. package/es/components/launcher/src/launcher.scss.js +1 -1
  20. package/es/components/markdown/__tests__/inline-selection-fixture.d.ts +13 -0
  21. package/es/components/markdown/index.d.ts +2 -0
  22. package/es/components/markdown/index.js +3 -0
  23. package/es/components/markdown/index.js.map +1 -1
  24. package/es/components/markdown/src/inline-markdown.d.ts +41 -0
  25. package/es/components/markdown/src/inline-markdown.js +92 -0
  26. package/es/components/markdown/src/inline-markdown.js.map +1 -0
  27. package/es/components/markdown/src/inline-markdown.scss.js +13 -0
  28. package/es/components/markdown/src/inline-markdown.scss.js.map +1 -0
  29. package/es/components/markdown/src/inline-run-projection.scss.js +13 -0
  30. package/es/components/markdown/src/inline-run-projection.scss.js.map +1 -0
  31. package/es/components/markdown/src/markdown-renderer.js +131 -25
  32. package/es/components/markdown/src/markdown-renderer.js.map +1 -1
  33. package/es/components/markdown/src/markdown.js +1 -0
  34. package/es/components/markdown/src/markdown.js.map +1 -1
  35. package/es/components/markdown/src/markdown.scss.js +1 -1
  36. package/es/components/markdown/src/utils/inline-run-projection.d.ts +15 -0
  37. package/es/components/markdown/src/utils/inline-run-projection.js +196 -0
  38. package/es/components/markdown/src/utils/inline-run-projection.js.map +1 -0
  39. package/es/components/markdown/src/utils/inline-validation.d.ts +13 -0
  40. package/es/components/markdown/src/utils/inline-validation.js +97 -0
  41. package/es/components/markdown/src/utils/inline-validation.js.map +1 -0
  42. package/es/components/markdown/src/utils/plugin-fallback.js +20 -13
  43. package/es/components/markdown/src/utils/plugin-fallback.js.map +1 -1
  44. package/es/components/markdown/src/utils/plugin-host-container.d.ts +5 -6
  45. package/es/components/markdown/src/utils/plugin-host-container.js.map +1 -1
  46. package/es/components/messages-shell/index.d.ts +11 -0
  47. package/es/components/messages-shell/index.js +9 -0
  48. package/es/components/messages-shell/index.js.map +1 -0
  49. package/es/components/messages-shell/src/messages-shell.d.ts +57 -0
  50. package/es/components/messages-shell/src/messages-shell.js +141 -0
  51. package/es/components/messages-shell/src/messages-shell.js.map +1 -0
  52. package/es/components/messages-shell/src/messages-shell.scss.js +13 -0
  53. package/es/components/messages-shell/src/messages-shell.scss.js.map +1 -0
  54. package/es/components/processing/src/processing.scss.js +1 -1
  55. package/es/components/prompt-line/autocomplete/src/autocomplete.d.ts +26 -9
  56. package/es/components/prompt-line/autocomplete/src/autocomplete.js +116 -107
  57. package/es/components/prompt-line/autocomplete/src/autocomplete.js.map +1 -1
  58. package/es/components/prompt-line/autocomplete/src/autocomplete.scss.js +1 -1
  59. package/es/components/prompt-line/src/autocomplete-controller-element.js +13 -1
  60. package/es/components/prompt-line/src/autocomplete-controller-element.js.map +1 -1
  61. package/es/components/prompt-line/src/autocomplete-controller.js +9 -2
  62. package/es/components/prompt-line/src/autocomplete-controller.js.map +1 -1
  63. package/es/components/prompt-line/src/prompt-line-controller.d.ts +7 -0
  64. package/es/components/prompt-line/src/prompt-line-rich-runtime.js +17 -0
  65. package/es/components/prompt-line/src/prompt-line-rich-runtime.js.map +1 -1
  66. package/es/components/prompt-line/src/prompt-line-shell.scss.js +1 -1
  67. package/es/components/prompt-line/src/prompt-line-textarea-runtime.d.ts +1 -0
  68. package/es/components/prompt-line/src/prompt-line-textarea-runtime.js +3 -0
  69. package/es/components/prompt-line/src/prompt-line-textarea-runtime.js.map +1 -1
  70. package/es/components/prompt-line/src/prompt-line.d.ts +7 -0
  71. package/es/components/prompt-line/src/prompt-line.js +9 -0
  72. package/es/components/prompt-line/src/prompt-line.js.map +1 -1
  73. package/es/components/prompt-line/src/send-control.scss.js +1 -1
  74. package/es/components/prompt-line/src/stop-streaming-button.scss.js +1 -1
  75. package/es/components/prompt-line/src/tiptap/carbon-mention.js +43 -21
  76. package/es/components/prompt-line/src/tiptap/carbon-mention.js.map +1 -1
  77. package/es/components/prompt-line/src/tiptap/plain-text-paste.js +8 -3
  78. package/es/components/prompt-line/src/tiptap/plain-text-paste.js.map +1 -1
  79. package/es/components/prompt-line/src/tiptap/strip-presentation-fields.d.ts +3 -3
  80. package/es/components/prompt-line/src/tiptap/strip-presentation-fields.js.map +1 -1
  81. package/es/components/prompt-line/src/tiptap/types.d.ts +27 -11
  82. package/es/components/reasoning-steps/src/reasoning-step.d.ts +3 -3
  83. package/es/components/reasoning-steps/src/reasoning-step.js +4 -4
  84. package/es/components/reasoning-steps/src/reasoning-step.js.map +1 -1
  85. package/es/components/reasoning-steps/src/reasoning-step.scss.js +1 -1
  86. package/es/components/reasoning-steps/src/reasoning-steps-toggle.scss.js +1 -1
  87. package/es/components/reasoning-steps/src/reasoning-steps.d.ts +5 -4
  88. package/es/components/reasoning-steps/src/reasoning-steps.js +5 -4
  89. package/es/components/reasoning-steps/src/reasoning-steps.js.map +1 -1
  90. package/es/components/truncated-text/src/truncated-text.scss.js +1 -1
  91. package/es/components/video-player/src/video-player.scss.js +1 -1
  92. package/es/react/hooks/useChatAutocomplete.js +7 -1
  93. package/es/react/hooks/useChatAutocomplete.js.map +1 -1
  94. package/es/react/messages-shell.d.ts +3 -0
  95. package/es/react/messages-shell.js +32 -0
  96. package/es/react/messages-shell.js.map +1 -0
  97. package/es-custom/components/audio-player/src/audio-player.scss.js +1 -1
  98. package/es-custom/components/audio-player/src/transcript.js +15 -0
  99. package/es-custom/components/audio-player/src/transcript.js.map +1 -1
  100. package/es-custom/components/card/src/card-footer.scss.js +1 -1
  101. package/es-custom/components/card/src/card-steps.scss.js +1 -1
  102. package/es-custom/components/card/src/card.scss.js +1 -1
  103. package/es-custom/components/chat-button/src/chat-button.scss.js +1 -1
  104. package/es-custom/components/chat-history/src/chat-history.scss.js +1 -1
  105. package/es-custom/components/chat-shell/src/shell.scss.js +1 -1
  106. package/es-custom/components/code-snippet/src/code-snippet.d.ts +3 -2
  107. package/es-custom/components/code-snippet/src/code-snippet.js +4 -3
  108. package/es-custom/components/code-snippet/src/code-snippet.js.map +1 -1
  109. package/es-custom/components/code-snippet/src/code-snippet.scss.js +1 -1
  110. package/es-custom/components/feedback/src/feedback.js +17 -3
  111. package/es-custom/components/feedback/src/feedback.js.map +1 -1
  112. package/es-custom/components/file-uploads/src/file-upload-item.scss.js +1 -1
  113. package/es-custom/components/file-uploads/src/file-uploads.scss.js +1 -1
  114. package/es-custom/components/launcher/src/launcher.scss.js +1 -1
  115. package/es-custom/components/markdown/__tests__/inline-selection-fixture.d.ts +13 -0
  116. package/es-custom/components/markdown/index.d.ts +2 -0
  117. package/es-custom/components/markdown/index.js +3 -0
  118. package/es-custom/components/markdown/index.js.map +1 -1
  119. package/es-custom/components/markdown/src/inline-markdown.d.ts +41 -0
  120. package/es-custom/components/markdown/src/inline-markdown.js +92 -0
  121. package/es-custom/components/markdown/src/inline-markdown.js.map +1 -0
  122. package/es-custom/components/markdown/src/inline-markdown.scss.js +13 -0
  123. package/es-custom/components/markdown/src/inline-markdown.scss.js.map +1 -0
  124. package/es-custom/components/markdown/src/inline-run-projection.scss.js +13 -0
  125. package/es-custom/components/markdown/src/inline-run-projection.scss.js.map +1 -0
  126. package/es-custom/components/markdown/src/markdown-renderer.js +131 -25
  127. package/es-custom/components/markdown/src/markdown-renderer.js.map +1 -1
  128. package/es-custom/components/markdown/src/markdown.js +1 -0
  129. package/es-custom/components/markdown/src/markdown.js.map +1 -1
  130. package/es-custom/components/markdown/src/markdown.scss.js +1 -1
  131. package/es-custom/components/markdown/src/utils/inline-run-projection.d.ts +15 -0
  132. package/es-custom/components/markdown/src/utils/inline-run-projection.js +196 -0
  133. package/es-custom/components/markdown/src/utils/inline-run-projection.js.map +1 -0
  134. package/es-custom/components/markdown/src/utils/inline-validation.d.ts +13 -0
  135. package/es-custom/components/markdown/src/utils/inline-validation.js +97 -0
  136. package/es-custom/components/markdown/src/utils/inline-validation.js.map +1 -0
  137. package/es-custom/components/markdown/src/utils/plugin-fallback.js +20 -13
  138. package/es-custom/components/markdown/src/utils/plugin-fallback.js.map +1 -1
  139. package/es-custom/components/markdown/src/utils/plugin-host-container.d.ts +5 -6
  140. package/es-custom/components/markdown/src/utils/plugin-host-container.js.map +1 -1
  141. package/es-custom/components/messages-shell/index.d.ts +11 -0
  142. package/es-custom/components/messages-shell/index.js +9 -0
  143. package/es-custom/components/messages-shell/index.js.map +1 -0
  144. package/es-custom/components/messages-shell/src/messages-shell.d.ts +57 -0
  145. package/es-custom/components/messages-shell/src/messages-shell.js +141 -0
  146. package/es-custom/components/messages-shell/src/messages-shell.js.map +1 -0
  147. package/es-custom/components/messages-shell/src/messages-shell.scss.js +13 -0
  148. package/es-custom/components/messages-shell/src/messages-shell.scss.js.map +1 -0
  149. package/es-custom/components/processing/src/processing.scss.js +1 -1
  150. package/es-custom/components/prompt-line/autocomplete/src/autocomplete.d.ts +26 -9
  151. package/es-custom/components/prompt-line/autocomplete/src/autocomplete.js +116 -107
  152. package/es-custom/components/prompt-line/autocomplete/src/autocomplete.js.map +1 -1
  153. package/es-custom/components/prompt-line/autocomplete/src/autocomplete.scss.js +1 -1
  154. package/es-custom/components/prompt-line/src/autocomplete-controller-element.js +13 -1
  155. package/es-custom/components/prompt-line/src/autocomplete-controller-element.js.map +1 -1
  156. package/es-custom/components/prompt-line/src/autocomplete-controller.js +9 -2
  157. package/es-custom/components/prompt-line/src/autocomplete-controller.js.map +1 -1
  158. package/es-custom/components/prompt-line/src/prompt-line-controller.d.ts +7 -0
  159. package/es-custom/components/prompt-line/src/prompt-line-rich-runtime.js +17 -0
  160. package/es-custom/components/prompt-line/src/prompt-line-rich-runtime.js.map +1 -1
  161. package/es-custom/components/prompt-line/src/prompt-line-shell.scss.js +1 -1
  162. package/es-custom/components/prompt-line/src/prompt-line-textarea-runtime.d.ts +1 -0
  163. package/es-custom/components/prompt-line/src/prompt-line-textarea-runtime.js +3 -0
  164. package/es-custom/components/prompt-line/src/prompt-line-textarea-runtime.js.map +1 -1
  165. package/es-custom/components/prompt-line/src/prompt-line.d.ts +7 -0
  166. package/es-custom/components/prompt-line/src/prompt-line.js +9 -0
  167. package/es-custom/components/prompt-line/src/prompt-line.js.map +1 -1
  168. package/es-custom/components/prompt-line/src/send-control.scss.js +1 -1
  169. package/es-custom/components/prompt-line/src/stop-streaming-button.scss.js +1 -1
  170. package/es-custom/components/prompt-line/src/tiptap/carbon-mention.js +43 -21
  171. package/es-custom/components/prompt-line/src/tiptap/carbon-mention.js.map +1 -1
  172. package/es-custom/components/prompt-line/src/tiptap/plain-text-paste.js +8 -3
  173. package/es-custom/components/prompt-line/src/tiptap/plain-text-paste.js.map +1 -1
  174. package/es-custom/components/prompt-line/src/tiptap/strip-presentation-fields.d.ts +3 -3
  175. package/es-custom/components/prompt-line/src/tiptap/strip-presentation-fields.js.map +1 -1
  176. package/es-custom/components/prompt-line/src/tiptap/types.d.ts +27 -11
  177. package/es-custom/components/reasoning-steps/src/reasoning-step.d.ts +3 -3
  178. package/es-custom/components/reasoning-steps/src/reasoning-step.js +4 -4
  179. package/es-custom/components/reasoning-steps/src/reasoning-step.js.map +1 -1
  180. package/es-custom/components/reasoning-steps/src/reasoning-step.scss.js +1 -1
  181. package/es-custom/components/reasoning-steps/src/reasoning-steps-toggle.scss.js +1 -1
  182. package/es-custom/components/reasoning-steps/src/reasoning-steps.d.ts +5 -4
  183. package/es-custom/components/reasoning-steps/src/reasoning-steps.js +5 -4
  184. package/es-custom/components/reasoning-steps/src/reasoning-steps.js.map +1 -1
  185. package/es-custom/components/truncated-text/src/truncated-text.scss.js +1 -1
  186. package/es-custom/components/video-player/src/video-player.scss.js +1 -1
  187. package/es-custom/react/hooks/useChatAutocomplete.js +7 -1
  188. package/es-custom/react/hooks/useChatAutocomplete.js.map +1 -1
  189. package/es-custom/react/messages-shell.d.ts +3 -0
  190. package/es-custom/react/messages-shell.js +32 -0
  191. package/es-custom/react/messages-shell.js.map +1 -0
  192. package/package.json +4 -4
  193. package/scss/_markdown-inline.scss +138 -0
  194. package/telemetry.yml +4 -0
@@ -1 +1 @@
1
- {"version":3,"file":"prompt-line.js","sources":["../../../../src/components/prompt-line/src/prompt-line.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * `<cds-aichat-prompt-line>` — the editing-surface layer of the chat input\n * stack.\n *\n * It renders a lightweight `<textarea>` by default and **never statically\n * imports `@tiptap/*`**, so chats that don't use advanced input features ship\n * no Tiptap. When the `rich` property is set, or `ensureEditor()` is called,\n * the element dynamically imports a Tiptap runtime and upgrades the surface in\n * place — text, caret, and focus carry over because the textarea holds plain\n * text. Host `extensions` alone do not trigger it; they are staged for whichever\n * surface mounts. The upgrade is **sticky**: once rich, the element stays rich\n * for the rest of its life.\n *\n * Both modes expose the same imperative API (`getEditor`, `setContent`,\n * `insertContent`, …) and emit the same events, so the React wrapper and\n * `@carbon/ai-chat`'s `Input` are mode-agnostic. `getEditor()` returns `null`\n * in textarea mode (it's a probe — it never triggers a load); call\n * `ensureEditor()` to force the upgrade and resolve with the live editor.\n *\n * The Carbon Tiptap bundle the rich editor installs — schema, value-sync,\n * typing-indicator, plain-text paste, keymap (`Mod-Enter`/`Enter` →\n * `cds-aichat-prompt-send-intent`), placeholder, undo/redo — lives in\n * [./prompt-line-rich-runtime.ts]. Non-chat hosts wanting Tiptap inside Lit\n * should compose their own element against `@tiptap/core` directly.\n *\n * @element cds-aichat-prompt-line\n *\n * @experimental\n */\n\nimport type { Editor, Extension, JSONContent } from '@tiptap/core';\nimport { css, html, LitElement, unsafeCSS } from 'lit';\nimport { property } from 'lit/decorators.js';\n\nimport { carbonElement } from '../../../globals/decorators/carbon-element.js';\nimport prefix from '../../../globals/settings.js';\nimport { adoptOnRoot } from '../../shared/dynamic-css-var-sheet.js';\nimport type {\n PromptLineController,\n PromptLineControllerInit,\n SetContentUpdater,\n} from './prompt-line-controller.js';\nimport { TextareaController } from './prompt-line-textarea-runtime.js';\nimport {\n getRichRuntimeIfLoaded,\n loadRichRuntime,\n} from './prompt-line-rich-loader.js';\nimport { getRawText, textOffsetToDocPos } from './tiptap/json-utils.js';\n\nimport styles from './prompt-line.scss?lit';\n\n@carbonElement(`${prefix}-prompt-line`)\nclass PromptLineElement extends LitElement {\n static styles = css`\n ${unsafeCSS(styles)}\n `;\n\n /**\n * Host-supplied Tiptap extensions, appended to the carbon bundle when the\n * rich editor mounts. These are *staged*, not a rich-mode trigger: setting\n * them while in textarea mode does not load Tiptap. Select rich explicitly\n * with `rich` or call `ensureEditor()`; the upgrade mounts with these\n * already installed.\n *\n * A new array is compared by value against the set last supplied, so a config\n * update that rebuilds an equivalent one leaves the live editor and its undo\n * history in place, writing any starter `items`/`isOn` through to storage.\n * Only a genuinely different set recreates the editor, preserving content,\n * selection, and focus but resetting history.\n * Extensions built by `buildCarbonExtensions` compare by their source\n * config; anything you supply directly compares by reference, so memoize\n * those (a fresh instance each render reads as a real change).\n */\n @property({ type: Array, attribute: false })\n extensions: Extension[] = [];\n\n /**\n * Initial / current content. Accepts Tiptap-native JSONContent or a plain\n * string. In textarea mode JSONContent is flattened to plain text.\n */\n @property({ type: Object, attribute: false })\n content?: JSONContent | string;\n\n /**\n * Selects the rich Tiptap editor. The element lazy-loads Tiptap and upgrades\n * the textarea in place; the upgrade is sticky (clearing `rich` later keeps\n * the editor). Defaults to the textarea.\n */\n @property({ type: Boolean, reflect: true })\n rich = false;\n\n /** Disables editing. The surface stays mounted but non-editable. */\n @property({ type: Boolean, reflect: true })\n disabled = false;\n\n /** Placeholder text shown when the surface is empty. */\n @property({ type: String })\n placeholder = '';\n\n /** Accessible label for the editing surface. */\n @property({ type: String, attribute: 'aria-label', reflect: true })\n override ariaLabel = 'Message';\n\n /** Test id, applied to the inner editable element. */\n @property({ type: String, attribute: 'test-id' })\n testId = '';\n\n /** Focus the surface on mount. */\n @property({ type: Boolean })\n override autofocus = false;\n\n private _controller: PromptLineController | null = null;\n private _mode: 'textarea' | 'rich' = 'textarea';\n private _editorHost: HTMLElement | null = null;\n private _lastExtensionsRef: Extension[] | null = null;\n /**\n * The `content` value the current surface was seeded with, and whether that\n * seed is still unconsumed. Both are needed: the value catches the echo, and\n * the latch releases after one `updated()` so a later change back to the same\n * value still lands. Comparing on the value alone suppressed it for the life\n * of the surface, dropping `a` in an `a` -> `b` -> `a` sequence.\n */\n private _seededContent?: JSONContent | string;\n private _seedPending = false;\n /** Pending deferred teardown, cancelled if the element is reattached. */\n private _pendingTeardownTimer: ReturnType<typeof setTimeout> | null = null;\n private _focusedWithKeyboard: boolean | null = null;\n /** Sticky latch — once rich is wanted it never reverts. */\n private _richLatched = false;\n private _upgrading = false;\n /**\n * The element owns the host's composition listeners for both layers — it\n * gates its own textarea→rich upgrade on this, and pushes the state to the\n * active controller via `setComposing` so rich mode can withhold a recreate.\n * One observer, so the two layers cannot disagree.\n */\n private _isComposing = false;\n private _pendingUpgrade = false;\n /**\n * Shared promise for in-flight `ensureEditor()` callers. Created lazily on the\n * first `ensureEditor()` call that needs an upgrade, settled once the rich\n * editor is mounted (`_swapToRich`) or the upgrade can't complete.\n */\n private _richReady: Promise<Editor> | null = null;\n private _resolveRichReady: ((editor: Editor) => void) | null = null;\n private _rejectRichReady: ((reason: Error) => void) | null = null;\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n override firstUpdated(): void {\n this._initializeSurface();\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n if (this._pendingTeardownTimer !== null) {\n // Reattached before the deferred teardown ran — a move, not an unmount.\n // The controller and its editor host traveled with the element, so the\n // Tiptap instance (and its undo history) survives untouched.\n //\n // Unlike `_teardownSurface`, this deliberately leaves `_isComposing` /\n // `_pendingUpgrade` alone: the host div and its composition listeners are\n // still attached, so a later `compositionend` reaches them and releases\n // whatever was parked. Teardown has to reset eagerly only because it\n // discards the listeners that would otherwise do it.\n clearTimeout(this._pendingTeardownTimer);\n this._pendingTeardownTimer = null;\n const root = this._editorHost?.getRootNode();\n if (root instanceof ShadowRoot || root instanceof Document) {\n adoptOnRoot(root);\n }\n this._controller?.getEditor()?.view.updateRoot();\n const activeElement = this.ownerDocument.activeElement;\n if (\n this._focusedWithKeyboard !== null &&\n (!activeElement || activeElement === this.ownerDocument.body)\n ) {\n this._controller?.focus(this._focusedWithKeyboard, true);\n } else {\n this._focusedWithKeyboard = null;\n }\n if (this._richLatched && this._mode === 'textarea') {\n void this._requestRichUpgrade();\n }\n return;\n }\n // Reattached after a real teardown. `firstUpdated` is a one-shot, so\n // without this the element would come back permanently inert.\n if (this._isTornDown()) {\n this._initializeSurface();\n }\n }\n\n override updated(changed: Map<string | number | symbol, unknown>): void {\n if (!this._controller) {\n return;\n }\n if (\n (changed.has('rich') || changed.has('extensions')) &&\n this._wantsRich()\n ) {\n this._richLatched = true;\n if (this._mode === 'textarea') {\n void this._requestRichUpgrade();\n }\n }\n if (\n changed.has('extensions') &&\n this.extensions !== this._lastExtensionsRef\n ) {\n this._lastExtensionsRef = this.extensions;\n if (this._mode === 'rich') {\n this._controller.setExtensions(this.extensions);\n }\n }\n if (changed.has('disabled')) {\n this._controller.setEditable(!this.disabled);\n }\n // The seed echo is skipped once — re-applying it would emit a spurious\n // host-origin change event. Every later update lands, including one that\n // returns to the seed value, and including one alongside an extensions\n // change (which may no-op or recreate; either way the seed is the previous\n // doc).\n if (changed.has('content')) {\n const echoesSeed =\n this._seedPending && this.content === this._seededContent;\n this._seedPending = false;\n if (!echoesSeed) {\n this._controller.setContent(this.content ?? '');\n }\n }\n if (changed.has('placeholder')) {\n this._controller.setPlaceholder(this.placeholder);\n }\n if (changed.has('testId')) {\n this._controller.setTestId(this.testId);\n }\n if (changed.has('ariaLabel')) {\n this._controller.setAriaLabel(this.ariaLabel);\n }\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n if (!this._controller || this._pendingTeardownTimer !== null) {\n return;\n }\n // Deferred by a task so a reparent — remove and re-append in the same\n // frame — keeps the live editor instead of destroying and rebuilding it.\n // A macrotask rather than a microtask because the reconnect can be\n // scheduled separately from the removal, and rather than a frame callback\n // because those never fire in a background tab, which would leak the\n // editor of a chat that really was unmounted.\n this._pendingTeardownTimer = setTimeout(() => {\n this._pendingTeardownTimer = null;\n this._teardownSurface();\n }, 0);\n }\n\n /** Destroy the editing surface. Deferred from `disconnectedCallback`. */\n private _teardownSurface(): void {\n this._focusedWithKeyboard = null;\n this._failRichReady(new Error('Input is not currently rendered'));\n this._controller?.destroy();\n this._controller = null;\n this._editorHost?.remove();\n this._editorHost = null;\n this._lastExtensionsRef = null;\n // Back to the default surface. `_richLatched` is the sticky flag, so a late\n // reconnect still comes back rich; leaving `_mode` on 'rich' with no\n // controller would just be a field outliving what it describes.\n this._mode = 'textarea';\n // The host div (and its composition listeners) is gone, so a composition\n // that was in flight can never fire its `compositionend`. Left set, these\n // would park the first upgrade after a reattach forever.\n this._isComposing = false;\n this._pendingUpgrade = false;\n }\n\n /** Mount the editing surface. Runs on first render and on a late reconnect. */\n private _initializeSurface(): void {\n // Guard against Lit running the pending first update on an element that was\n // appended and removed in a single task before the update flushed. Without\n // this check the editor mounts on a detached host with no disconnectedCallback\n // left to clean it up, because the callback already ran before the update.\n if (!this.isConnected) {\n return;\n }\n const host = this._mountEditorHost();\n this._lastExtensionsRef = this.extensions;\n this._seededContent = this.content;\n this._seedPending = true;\n this._richLatched = this._wantsRich();\n\n const warmRuntime = this._richLatched ? getRichRuntimeIfLoaded() : null;\n if (warmRuntime) {\n // Runtime already loaded (e.g. preloaded at boot) — mount rich directly,\n // no textarea flash.\n this._mode = 'rich';\n this._controller = warmRuntime.createRichController();\n this._controller.mount(host, this._makeInit());\n } else {\n this._mode = 'textarea';\n this._controller = new TextareaController();\n this._controller.mount(host, this._makeInit());\n if (this._richLatched) {\n void this._requestRichUpgrade();\n }\n }\n\n if (this.autofocus) {\n // Defer so consumer listeners are attached first.\n Promise.resolve().then(() => this._controller?.focus(false));\n }\n }\n\n override render() {\n return html`\n <div class=\"frame\">\n <slot name=\"editor\"></slot>\n </div>\n `;\n }\n\n // ---------------------------------------------------------------------------\n // Public methods (delegate to the active controller)\n // ---------------------------------------------------------------------------\n\n /** Returns the live Tiptap editor, or `null` in textarea mode. */\n getEditor(): Editor | null {\n return this._controller?.getEditor() ?? null;\n }\n\n /**\n * Lazily load Tiptap (if not already loaded), upgrade the textarea to the\n * rich editor in place, and resolve with the live editor. Resolves\n * immediately when already rich. Rejects when the surface isn't mounted or\n * the runtime can't load (SSR). Concurrent callers share one in-flight\n * upgrade.\n */\n ensureEditor(): Promise<Editor> {\n if (!this.isConnected || this._pendingTeardownTimer !== null) {\n return Promise.reject(new Error('Input is not currently rendered'));\n }\n if (this._mode === 'rich') {\n const editor = this._controller?.getEditor();\n if (editor) {\n return Promise.resolve(editor);\n }\n }\n // Connected but not yet rendered, or already torn down — nothing to upgrade.\n if (!this._editorHost || !this._controller) {\n return Promise.reject(new Error('Input is not currently rendered'));\n }\n this._richLatched = true;\n if (!this._richReady) {\n this._richReady = new Promise<Editor>((resolve, reject) => {\n this._resolveRichReady = resolve;\n this._rejectRichReady = reject;\n });\n }\n // Capture the promise before starting the upgrade: _requestRichUpgrade may\n // run synchronously (warm runtime path) and call _failRichReady, which\n // nulls this._richReady. Returning the captured reference keeps the\n // rejection visible to the caller.\n const promise = this._richReady;\n void this._requestRichUpgrade();\n return promise;\n }\n\n /**\n * Current plain-text value. Works in both modes (in rich mode this mirrors\n * `getEditor()?.getText()`), so callers don't need to branch on `getEditor()`\n * being `null`.\n */\n getValue(): string {\n return this._controller?.getValue() ?? '';\n }\n\n override focus(): void {\n this._controller?.focus(false);\n }\n\n override blur(): void {\n this._focusedWithKeyboard = null;\n this._controller?.blur();\n }\n\n /** Returns `true` if the editing surface currently holds focus. */\n hasFocus(): boolean {\n return this._controller?.hasFocus() ?? false;\n }\n\n clearContent(): void {\n this._controller?.clearContent();\n }\n\n setContent(next: JSONContent | string | SetContentUpdater): void {\n this._controller?.setContent(next);\n }\n\n insertContent(\n content: JSONContent | string,\n opts: { at?: number } = {}\n ): void {\n this._controller?.insertContent(content, opts);\n }\n\n setTextSelection(pos: number | { from: number; to: number }): void {\n this._controller?.setTextSelection(pos);\n }\n\n selectAll(): void {\n this._controller?.selectAll();\n }\n\n undo(): boolean {\n return this._controller?.undo() ?? false;\n }\n\n redo(): boolean {\n return this._controller?.redo() ?? false;\n }\n\n // ---------------------------------------------------------------------------\n // Internals\n // ---------------------------------------------------------------------------\n\n private _wantsRich(): boolean {\n return this._richLatched || this.rich;\n }\n\n /**\n * Rendered once and then torn down — the element is inert until something\n * re-runs the mount path. Distinct from \"not yet rendered\", where Lit's own\n * `firstUpdated` still has it.\n */\n private _isTornDown(): boolean {\n return this.hasUpdated && !this._controller;\n }\n\n private _mountEditorHost(): HTMLElement {\n const host = document.createElement('div');\n host.setAttribute('slot', 'editor');\n host.dataset.aichatEditorHost = '';\n this.appendChild(host);\n this._editorHost = host;\n\n // Defer an upgrade requested mid-IME-composition so we don't tear the\n // field out from under the user.\n host.addEventListener('compositionstart', this._onCompositionStart);\n host.addEventListener('compositionend', this._onCompositionEnd);\n host.addEventListener('cds-aichat-prompt-focus', (event) => {\n this._focusedWithKeyboard = (event as CustomEvent).detail.keyboard;\n });\n host.addEventListener('cds-aichat-prompt-blur', () => {\n // Chromium blurs a removed ancestor's descendants before disconnecting\n // them. Wait until the DOM move finishes before treating this as a blur.\n queueMicrotask(() => {\n if (this.isConnected && !this._controller?.hasFocus()) {\n this._focusedWithKeyboard = null;\n }\n });\n });\n\n const root = host.getRootNode();\n if (root instanceof ShadowRoot || root instanceof Document) {\n adoptOnRoot(root);\n }\n return host;\n }\n\n private _onCompositionStart = (): void => {\n this._isComposing = true;\n this._controller?.setComposing(true);\n };\n\n private _onCompositionEnd = (): void => {\n this._isComposing = false;\n this._controller?.setComposing(false);\n if (this._pendingUpgrade) {\n this._pendingUpgrade = false;\n void this._requestRichUpgrade();\n }\n };\n\n /** Build the controller init from current props (rich seed by default). */\n private _makeInit(valueOverride?: string): PromptLineControllerInit {\n const value =\n valueOverride ??\n (typeof this.content === 'string'\n ? this.content\n : this.content\n ? getRawText(this.content)\n : '');\n return {\n value,\n // On an upgrade we seed losslessly from the textarea's plain text, so\n // the structured `content` prop is only used for the initial mount.\n content: valueOverride === undefined ? this.content : undefined,\n placeholder: this.placeholder,\n disabled: this.disabled,\n ariaLabel: this.ariaLabel,\n testId: this.testId,\n extensions: this.extensions,\n };\n }\n\n /** Resolve any pending `ensureEditor()` callers with the live editor. */\n private _settleRichReady(): void {\n const editor = this._controller?.getEditor();\n if (editor && this._resolveRichReady) {\n this._resolveRichReady(editor);\n this._resolveRichReady = null;\n this._rejectRichReady = null;\n }\n }\n\n /**\n * Reject any pending `ensureEditor()` callers and clear the shared promise so\n * a later call can retry.\n */\n private _failRichReady(reason: Error): void {\n if (this._rejectRichReady) {\n this._rejectRichReady(reason);\n }\n this._resolveRichReady = null;\n this._rejectRichReady = null;\n this._richReady = null;\n }\n\n /**\n * Request a textarea→rich upgrade. The upgrade may be declined or deferred:\n * returns without upgrading when already rich, when a concurrent upgrade is\n * in flight, when a teardown is pending (element scheduled for removal), when\n * a composition is in flight, or when the runtime is unavailable (SSR).\n */\n private async _requestRichUpgrade(): Promise<void> {\n if (this._mode === 'rich' || this._upgrading) {\n return;\n }\n this._upgrading = true;\n try {\n const module = getRichRuntimeIfLoaded() ?? (await loadRichRuntime());\n // After the async import, re-check all bail conditions — any of them can\n // have changed while the runtime was loading:\n // - `_pendingTeardownTimer`: element disconnected during the import; the\n // teardown is scheduled but hasn't run yet, so _editorHost and\n // _controller are still set. Mounting here would build an editor that\n // is destroyed a macrotask later, and resolve any pending ensureEditor()\n // with a dead editor. Reject instead.\n // - `_editorHost` / `_controller` null: real teardown already ran.\n // - `module` null: SSR or runtime load failed.\n if (!module || !this._editorHost || !this._controller) {\n this._failRichReady(\n new Error(\n module\n ? 'Input is not currently rendered'\n : 'Input editor runtime is unavailable'\n )\n );\n return;\n }\n if (this._pendingTeardownTimer !== null) {\n // Teardown is deferred but imminent. Reject so callers get a clear\n // error rather than a live editor that disappears one task later.\n this._failRichReady(new Error('Input is not currently rendered'));\n return;\n }\n if (this._isComposing) {\n // Defer until composition ends; `_richReady` stays pending and settles\n // when `_onCompositionEnd` re-runs the upgrade.\n this._pendingUpgrade = true;\n return;\n }\n this._swapToRich(module.createRichController());\n } catch (error) {\n // A failed runtime load or mount must reject pending `ensureEditor()`\n // callers rather than leave them hanging.\n this._failRichReady(\n error instanceof Error ? error : new Error(String(error))\n );\n } finally {\n this._upgrading = false;\n }\n }\n\n private _swapToRich(rich: PromptLineController): void {\n const previous = this._controller;\n const host = this._editorHost;\n if (!previous || !host) {\n return;\n }\n const value = previous.getValue();\n const selection = previous.getSelection();\n const hadFocus = previous.hasFocus();\n const hadKeyboardFocus = previous.getKeyboardFocus();\n\n previous.destroy();\n this._controller = rich;\n this._mode = 'rich';\n // Seeded losslessly from the textarea's text, which already reflects\n // `content`, so an in-flight identical `content` update stays a no-op.\n this._seededContent = this.content;\n this._seedPending = true;\n rich.mount(host, this._makeInit(value));\n\n rich.setTextSelection({\n from: textOffsetToDocPos(value, selection.from),\n to: textOffsetToDocPos(value, selection.to),\n });\n if (hadFocus) {\n rich.focus(hadKeyboardFocus, true);\n }\n this._settleRichReady();\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'cds-aichat-prompt-line': PromptLineElement;\n }\n}\n\nexport default PromptLineElement;\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA;;;;;;;AAOG;AAsDH,IAAM,iBAAiB,GAAvB,MAAM,iBAAkB,SAAQ,UAAU,CAAA;AAA1C,IAAA,WAAA,GAAA;;AAKE;;;;;;;;;;;;;;;AAeG;QAEH,IAAA,CAAA,UAAU,GAAgB,EAAE;AAS5B;;;;AAIG;QAEH,IAAA,CAAA,IAAI,GAAG,KAAK;;QAIZ,IAAA,CAAA,QAAQ,GAAG,KAAK;;QAIhB,IAAA,CAAA,WAAW,GAAG,EAAE;;QAIP,IAAA,CAAA,SAAS,GAAG,SAAS;;QAI9B,IAAA,CAAA,MAAM,GAAG,EAAE;;QAIF,IAAA,CAAA,SAAS,GAAG,KAAK;QAElB,IAAA,CAAA,WAAW,GAAgC,IAAI;QAC/C,IAAA,CAAA,KAAK,GAAwB,UAAU;QACvC,IAAA,CAAA,WAAW,GAAuB,IAAI;QACtC,IAAA,CAAA,kBAAkB,GAAuB,IAAI;QAS7C,IAAA,CAAA,YAAY,GAAG,KAAK;;QAEpB,IAAA,CAAA,qBAAqB,GAAyC,IAAI;QAClE,IAAA,CAAA,oBAAoB,GAAmB,IAAI;;QAE3C,IAAA,CAAA,YAAY,GAAG,KAAK;QACpB,IAAA,CAAA,UAAU,GAAG,KAAK;AAC1B;;;;;AAKG;QACK,IAAA,CAAA,YAAY,GAAG,KAAK;QACpB,IAAA,CAAA,eAAe,GAAG,KAAK;AAC/B;;;;AAIG;QACK,IAAA,CAAA,UA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C,QAAQ,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE;AACzB,CAAA,EAAA,iBAAA,CAAA,SAAA,EAAA,UAAA,EAAA,MAAA,CAAA;AAIjB,UAAA,CAAA;AADC,IAAA,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE;AACT,CAAA,EAAA,iBAAA,CAAA,SAAA,EAAA,aAAA,EAAA,MAAA,CAAA;AAIR,UAAA,CAAA;AADR,IAAA,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE;AACnC,CAAA,EAAA,iBAAA,CAAA,SAAA,EAAA,WAAA,EAAA,MAAA,CAAA;AAI/B,UAAA,CAAA;IADC,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE;AACpC,CAAA,EAAA,iBAAA,CAAA,SAAA,EAAA,QAAA,EAAA,MAAA,CAAA;AAIH,UAAA,CAAA;AADR,IAAA,QAAQ,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE;AACA,CAAA,EAAA,iBAAA,CAAA,SAAA,EAAA,WAAA,EAAA,MAAA,CAAA;AAzDvB,iBAAiB,GAAA,UAAA,CAAA;AADtB,IAAA,aAAa,CAAC,CAAA,EAAG,MAAM,CAAA,YAAA,CAAc;AAChC,CAAA,EAAA,iBAAiB,CAsjBtB;AAQD,0BAAe,iBAAiB;;"}
1
+ {"version":3,"file":"prompt-line.js","sources":["../../../../src/components/prompt-line/src/prompt-line.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * `<cds-aichat-prompt-line>` — the editing-surface layer of the chat input\n * stack.\n *\n * It renders a lightweight `<textarea>` by default and **never statically\n * imports `@tiptap/*`**, so chats that don't use advanced input features ship\n * no Tiptap. When the `rich` property is set, or `ensureEditor()` is called,\n * the element dynamically imports a Tiptap runtime and upgrades the surface in\n * place — text, caret, and focus carry over because the textarea holds plain\n * text. Host `extensions` alone do not trigger it; they are staged for whichever\n * surface mounts. The upgrade is **sticky**: once rich, the element stays rich\n * for the rest of its life.\n *\n * Both modes expose the same imperative API (`getEditor`, `setContent`,\n * `insertContent`, …) and emit the same events, so the React wrapper and\n * `@carbon/ai-chat`'s `Input` are mode-agnostic. `getEditor()` returns `null`\n * in textarea mode (it's a probe — it never triggers a load); call\n * `ensureEditor()` to force the upgrade and resolve with the live editor.\n *\n * The Carbon Tiptap bundle the rich editor installs — schema, value-sync,\n * typing-indicator, plain-text paste, keymap (`Mod-Enter`/`Enter` →\n * `cds-aichat-prompt-send-intent`), placeholder, undo/redo — lives in\n * [./prompt-line-rich-runtime.ts]. Non-chat hosts wanting Tiptap inside Lit\n * should compose their own element against `@tiptap/core` directly.\n *\n * @element cds-aichat-prompt-line\n *\n * @experimental\n */\n\nimport type { Editor, Extension, JSONContent } from '@tiptap/core';\nimport { css, html, LitElement, unsafeCSS } from 'lit';\nimport { property } from 'lit/decorators.js';\n\nimport { carbonElement } from '../../../globals/decorators/carbon-element.js';\nimport prefix from '../../../globals/settings.js';\nimport { adoptOnRoot } from '../../shared/dynamic-css-var-sheet.js';\nimport type {\n PromptLineController,\n PromptLineControllerInit,\n SetContentUpdater,\n} from './prompt-line-controller.js';\nimport { TextareaController } from './prompt-line-textarea-runtime.js';\nimport {\n getRichRuntimeIfLoaded,\n loadRichRuntime,\n} from './prompt-line-rich-loader.js';\nimport { getRawText, textOffsetToDocPos } from './tiptap/json-utils.js';\n\nimport styles from './prompt-line.scss?lit';\n\n@carbonElement(`${prefix}-prompt-line`)\nclass PromptLineElement extends LitElement {\n static styles = css`\n ${unsafeCSS(styles)}\n `;\n\n /**\n * Host-supplied Tiptap extensions, appended to the carbon bundle when the\n * rich editor mounts. These are *staged*, not a rich-mode trigger: setting\n * them while in textarea mode does not load Tiptap. Select rich explicitly\n * with `rich` or call `ensureEditor()`; the upgrade mounts with these\n * already installed.\n *\n * A new array is compared by value against the set last supplied, so a config\n * update that rebuilds an equivalent one leaves the live editor and its undo\n * history in place, writing any starter `items`/`isOn` through to storage.\n * Only a genuinely different set recreates the editor, preserving content,\n * selection, and focus but resetting history.\n * Extensions built by `buildCarbonExtensions` compare by their source\n * config; anything you supply directly compares by reference, so memoize\n * those (a fresh instance each render reads as a real change).\n */\n @property({ type: Array, attribute: false })\n extensions: Extension[] = [];\n\n /**\n * Initial / current content. Accepts Tiptap-native JSONContent or a plain\n * string. In textarea mode JSONContent is flattened to plain text.\n */\n @property({ type: Object, attribute: false })\n content?: JSONContent | string;\n\n /**\n * Selects the rich Tiptap editor. The element lazy-loads Tiptap and upgrades\n * the textarea in place; the upgrade is sticky (clearing `rich` later keeps\n * the editor). Defaults to the textarea.\n */\n @property({ type: Boolean, reflect: true })\n rich = false;\n\n /** Disables editing. The surface stays mounted but non-editable. */\n @property({ type: Boolean, reflect: true })\n disabled = false;\n\n /** Placeholder text shown when the surface is empty. */\n @property({ type: String })\n placeholder = '';\n\n /** Accessible label for the editing surface. */\n @property({ type: String, attribute: 'aria-label', reflect: true })\n override ariaLabel = 'Message';\n\n /** Test id, applied to the inner editable element. */\n @property({ type: String, attribute: 'test-id' })\n testId = '';\n\n /** Focus the surface on mount. */\n @property({ type: Boolean })\n override autofocus = false;\n\n private _controller: PromptLineController | null = null;\n private _mode: 'textarea' | 'rich' = 'textarea';\n private _editorHost: HTMLElement | null = null;\n private _lastExtensionsRef: Extension[] | null = null;\n /**\n * The `content` value the current surface was seeded with, and whether that\n * seed is still unconsumed. Both are needed: the value catches the echo, and\n * the latch releases after one `updated()` so a later change back to the same\n * value still lands. Comparing on the value alone suppressed it for the life\n * of the surface, dropping `a` in an `a` -> `b` -> `a` sequence.\n */\n private _seededContent?: JSONContent | string;\n private _seedPending = false;\n /** Pending deferred teardown, cancelled if the element is reattached. */\n private _pendingTeardownTimer: ReturnType<typeof setTimeout> | null = null;\n private _focusedWithKeyboard: boolean | null = null;\n /** Sticky latch — once rich is wanted it never reverts. */\n private _richLatched = false;\n private _upgrading = false;\n /**\n * The element owns the host's composition listeners for both layers — it\n * gates its own textarea→rich upgrade on this, and pushes the state to the\n * active controller via `setComposing` so rich mode can withhold a recreate.\n * One observer, so the two layers cannot disagree.\n */\n private _isComposing = false;\n private _pendingUpgrade = false;\n /**\n * Shared promise for in-flight `ensureEditor()` callers. Created lazily on the\n * first `ensureEditor()` call that needs an upgrade, settled once the rich\n * editor is mounted (`_swapToRich`) or the upgrade can't complete.\n */\n private _richReady: Promise<Editor> | null = null;\n private _resolveRichReady: ((editor: Editor) => void) | null = null;\n private _rejectRichReady: ((reason: Error) => void) | null = null;\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n override firstUpdated(): void {\n this._initializeSurface();\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n if (this._pendingTeardownTimer !== null) {\n // Reattached before the deferred teardown ran — a move, not an unmount.\n // The controller and its editor host traveled with the element, so the\n // Tiptap instance (and its undo history) survives untouched.\n //\n // Unlike `_teardownSurface`, this deliberately leaves `_isComposing` /\n // `_pendingUpgrade` alone: the host div and its composition listeners are\n // still attached, so a later `compositionend` reaches them and releases\n // whatever was parked. Teardown has to reset eagerly only because it\n // discards the listeners that would otherwise do it.\n clearTimeout(this._pendingTeardownTimer);\n this._pendingTeardownTimer = null;\n const root = this._editorHost?.getRootNode();\n if (root instanceof ShadowRoot || root instanceof Document) {\n adoptOnRoot(root);\n }\n this._controller?.getEditor()?.view.updateRoot();\n const activeElement = this.ownerDocument.activeElement;\n if (\n this._focusedWithKeyboard !== null &&\n (!activeElement || activeElement === this.ownerDocument.body)\n ) {\n this._controller?.focus(this._focusedWithKeyboard, true);\n } else {\n this._focusedWithKeyboard = null;\n }\n if (this._richLatched && this._mode === 'textarea') {\n void this._requestRichUpgrade();\n }\n return;\n }\n // Reattached after a real teardown. `firstUpdated` is a one-shot, so\n // without this the element would come back permanently inert.\n if (this._isTornDown()) {\n this._initializeSurface();\n }\n }\n\n override updated(changed: Map<string | number | symbol, unknown>): void {\n if (!this._controller) {\n return;\n }\n if (\n (changed.has('rich') || changed.has('extensions')) &&\n this._wantsRich()\n ) {\n this._richLatched = true;\n if (this._mode === 'textarea') {\n void this._requestRichUpgrade();\n }\n }\n if (\n changed.has('extensions') &&\n this.extensions !== this._lastExtensionsRef\n ) {\n this._lastExtensionsRef = this.extensions;\n if (this._mode === 'rich') {\n this._controller.setExtensions(this.extensions);\n }\n }\n if (changed.has('disabled')) {\n this._controller.setEditable(!this.disabled);\n }\n // The seed echo is skipped once — re-applying it would emit a spurious\n // host-origin change event. Every later update lands, including one that\n // returns to the seed value, and including one alongside an extensions\n // change (which may no-op or recreate; either way the seed is the previous\n // doc).\n if (changed.has('content')) {\n const echoesSeed =\n this._seedPending && this.content === this._seededContent;\n this._seedPending = false;\n if (!echoesSeed) {\n this._controller.setContent(this.content ?? '');\n }\n }\n if (changed.has('placeholder')) {\n this._controller.setPlaceholder(this.placeholder);\n }\n if (changed.has('testId')) {\n this._controller.setTestId(this.testId);\n }\n if (changed.has('ariaLabel')) {\n this._controller.setAriaLabel(this.ariaLabel);\n }\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n if (!this._controller || this._pendingTeardownTimer !== null) {\n return;\n }\n // Deferred by a task so a reparent — remove and re-append in the same\n // frame — keeps the live editor instead of destroying and rebuilding it.\n // A macrotask rather than a microtask because the reconnect can be\n // scheduled separately from the removal, and rather than a frame callback\n // because those never fire in a background tab, which would leak the\n // editor of a chat that really was unmounted.\n this._pendingTeardownTimer = setTimeout(() => {\n this._pendingTeardownTimer = null;\n this._teardownSurface();\n }, 0);\n }\n\n /** Destroy the editing surface. Deferred from `disconnectedCallback`. */\n private _teardownSurface(): void {\n this._focusedWithKeyboard = null;\n this._failRichReady(new Error('Input is not currently rendered'));\n this._controller?.destroy();\n this._controller = null;\n this._editorHost?.remove();\n this._editorHost = null;\n this._lastExtensionsRef = null;\n // Back to the default surface. `_richLatched` is the sticky flag, so a late\n // reconnect still comes back rich; leaving `_mode` on 'rich' with no\n // controller would just be a field outliving what it describes.\n this._mode = 'textarea';\n // The host div (and its composition listeners) is gone, so a composition\n // that was in flight can never fire its `compositionend`. Left set, these\n // would park the first upgrade after a reattach forever.\n this._isComposing = false;\n this._pendingUpgrade = false;\n }\n\n /** Mount the editing surface. Runs on first render and on a late reconnect. */\n private _initializeSurface(): void {\n // Guard against Lit running the pending first update on an element that was\n // appended and removed in a single task before the update flushed. Without\n // this check the editor mounts on a detached host with no disconnectedCallback\n // left to clean it up, because the callback already ran before the update.\n if (!this.isConnected) {\n return;\n }\n const host = this._mountEditorHost();\n this._lastExtensionsRef = this.extensions;\n this._seededContent = this.content;\n this._seedPending = true;\n this._richLatched = this._wantsRich();\n\n const warmRuntime = this._richLatched ? getRichRuntimeIfLoaded() : null;\n if (warmRuntime) {\n // Runtime already loaded (e.g. preloaded at boot) — mount rich directly,\n // no textarea flash.\n this._mode = 'rich';\n this._controller = warmRuntime.createRichController();\n this._controller.mount(host, this._makeInit());\n } else {\n this._mode = 'textarea';\n this._controller = new TextareaController();\n this._controller.mount(host, this._makeInit());\n if (this._richLatched) {\n void this._requestRichUpgrade();\n }\n }\n\n if (this.autofocus) {\n // Defer so consumer listeners are attached first.\n Promise.resolve().then(() => this._controller?.focus(false));\n }\n }\n\n override render() {\n return html`\n <div class=\"frame\">\n <slot name=\"editor\"></slot>\n </div>\n `;\n }\n\n // ---------------------------------------------------------------------------\n // Public methods (delegate to the active controller)\n // ---------------------------------------------------------------------------\n\n /** Returns the live Tiptap editor, or `null` in textarea mode. */\n getEditor(): Editor | null {\n return this._controller?.getEditor() ?? null;\n }\n\n /**\n * Lazily load Tiptap (if not already loaded), upgrade the textarea to the\n * rich editor in place, and resolve with the live editor. Resolves\n * immediately when already rich. Rejects when the surface isn't mounted or\n * the runtime can't load (SSR). Concurrent callers share one in-flight\n * upgrade.\n */\n ensureEditor(): Promise<Editor> {\n if (!this.isConnected || this._pendingTeardownTimer !== null) {\n return Promise.reject(new Error('Input is not currently rendered'));\n }\n if (this._mode === 'rich') {\n const editor = this._controller?.getEditor();\n if (editor) {\n return Promise.resolve(editor);\n }\n }\n // Connected but not yet rendered, or already torn down — nothing to upgrade.\n if (!this._editorHost || !this._controller) {\n return Promise.reject(new Error('Input is not currently rendered'));\n }\n this._richLatched = true;\n if (!this._richReady) {\n this._richReady = new Promise<Editor>((resolve, reject) => {\n this._resolveRichReady = resolve;\n this._rejectRichReady = reject;\n });\n }\n // Capture the promise before starting the upgrade: _requestRichUpgrade may\n // run synchronously (warm runtime path) and call _failRichReady, which\n // nulls this._richReady. Returning the captured reference keeps the\n // rejection visible to the caller.\n const promise = this._richReady;\n void this._requestRichUpgrade();\n return promise;\n }\n\n /**\n * Current plain-text value. Works in both modes (in rich mode this mirrors\n * `getEditor()?.getText()`), so callers don't need to branch on `getEditor()`\n * being `null`.\n */\n getValue(): string {\n return this._controller?.getValue() ?? '';\n }\n\n override focus(): void {\n this._controller?.focus(false);\n }\n\n override blur(): void {\n this._focusedWithKeyboard = null;\n this._controller?.blur();\n }\n\n /** Returns `true` if the editing surface currently holds focus. */\n hasFocus(): boolean {\n return this._controller?.hasFocus() ?? false;\n }\n\n clearContent(): void {\n this._controller?.clearContent();\n }\n\n setContent(next: JSONContent | string | SetContentUpdater): void {\n this._controller?.setContent(next);\n }\n\n insertContent(\n content: JSONContent | string,\n opts: { at?: number } = {}\n ): void {\n this._controller?.insertContent(content, opts);\n }\n\n setTextSelection(pos: number | { from: number; to: number }): void {\n this._controller?.setTextSelection(pos);\n }\n\n selectAll(): void {\n this._controller?.selectAll();\n }\n\n undo(): boolean {\n return this._controller?.undo() ?? false;\n }\n\n redo(): boolean {\n return this._controller?.redo() ?? false;\n }\n\n /**\n * Drops the editor's undo and redo history, keeping the live editor,\n * its focus, and its plugin state. Emits Tiptap's `transaction` event but\n * no `update`, value-change, typing, or token events. No-op in plain\n * textarea mode.\n */\n resetHistory(): void {\n this._controller?.resetHistory();\n }\n\n // ---------------------------------------------------------------------------\n // Internals\n // ---------------------------------------------------------------------------\n\n private _wantsRich(): boolean {\n return this._richLatched || this.rich;\n }\n\n /**\n * Rendered once and then torn down — the element is inert until something\n * re-runs the mount path. Distinct from \"not yet rendered\", where Lit's own\n * `firstUpdated` still has it.\n */\n private _isTornDown(): boolean {\n return this.hasUpdated && !this._controller;\n }\n\n private _mountEditorHost(): HTMLElement {\n const host = document.createElement('div');\n host.setAttribute('slot', 'editor');\n host.dataset.aichatEditorHost = '';\n this.appendChild(host);\n this._editorHost = host;\n\n // Defer an upgrade requested mid-IME-composition so we don't tear the\n // field out from under the user.\n host.addEventListener('compositionstart', this._onCompositionStart);\n host.addEventListener('compositionend', this._onCompositionEnd);\n host.addEventListener('cds-aichat-prompt-focus', (event) => {\n this._focusedWithKeyboard = (event as CustomEvent).detail.keyboard;\n });\n host.addEventListener('cds-aichat-prompt-blur', () => {\n // Chromium blurs a removed ancestor's descendants before disconnecting\n // them. Wait until the DOM move finishes before treating this as a blur.\n queueMicrotask(() => {\n if (this.isConnected && !this._controller?.hasFocus()) {\n this._focusedWithKeyboard = null;\n }\n });\n });\n\n const root = host.getRootNode();\n if (root instanceof ShadowRoot || root instanceof Document) {\n adoptOnRoot(root);\n }\n return host;\n }\n\n private _onCompositionStart = (): void => {\n this._isComposing = true;\n this._controller?.setComposing(true);\n };\n\n private _onCompositionEnd = (): void => {\n this._isComposing = false;\n this._controller?.setComposing(false);\n if (this._pendingUpgrade) {\n this._pendingUpgrade = false;\n void this._requestRichUpgrade();\n }\n };\n\n /** Build the controller init from current props (rich seed by default). */\n private _makeInit(valueOverride?: string): PromptLineControllerInit {\n const value =\n valueOverride ??\n (typeof this.content === 'string'\n ? this.content\n : this.content\n ? getRawText(this.content)\n : '');\n return {\n value,\n // On an upgrade we seed losslessly from the textarea's plain text, so\n // the structured `content` prop is only used for the initial mount.\n content: valueOverride === undefined ? this.content : undefined,\n placeholder: this.placeholder,\n disabled: this.disabled,\n ariaLabel: this.ariaLabel,\n testId: this.testId,\n extensions: this.extensions,\n };\n }\n\n /** Resolve any pending `ensureEditor()` callers with the live editor. */\n private _settleRichReady(): void {\n const editor = this._controller?.getEditor();\n if (editor && this._resolveRichReady) {\n this._resolveRichReady(editor);\n this._resolveRichReady = null;\n this._rejectRichReady = null;\n }\n }\n\n /**\n * Reject any pending `ensureEditor()` callers and clear the shared promise so\n * a later call can retry.\n */\n private _failRichReady(reason: Error): void {\n if (this._rejectRichReady) {\n this._rejectRichReady(reason);\n }\n this._resolveRichReady = null;\n this._rejectRichReady = null;\n this._richReady = null;\n }\n\n /**\n * Request a textarea→rich upgrade. The upgrade may be declined or deferred:\n * returns without upgrading when already rich, when a concurrent upgrade is\n * in flight, when a teardown is pending (element scheduled for removal), when\n * a composition is in flight, or when the runtime is unavailable (SSR).\n */\n private async _requestRichUpgrade(): Promise<void> {\n if (this._mode === 'rich' || this._upgrading) {\n return;\n }\n this._upgrading = true;\n try {\n const module = getRichRuntimeIfLoaded() ?? (await loadRichRuntime());\n // After the async import, re-check all bail conditions — any of them can\n // have changed while the runtime was loading:\n // - `_pendingTeardownTimer`: element disconnected during the import; the\n // teardown is scheduled but hasn't run yet, so _editorHost and\n // _controller are still set. Mounting here would build an editor that\n // is destroyed a macrotask later, and resolve any pending ensureEditor()\n // with a dead editor. Reject instead.\n // - `_editorHost` / `_controller` null: real teardown already ran.\n // - `module` null: SSR or runtime load failed.\n if (!module || !this._editorHost || !this._controller) {\n this._failRichReady(\n new Error(\n module\n ? 'Input is not currently rendered'\n : 'Input editor runtime is unavailable'\n )\n );\n return;\n }\n if (this._pendingTeardownTimer !== null) {\n // Teardown is deferred but imminent. Reject so callers get a clear\n // error rather than a live editor that disappears one task later.\n this._failRichReady(new Error('Input is not currently rendered'));\n return;\n }\n if (this._isComposing) {\n // Defer until composition ends; `_richReady` stays pending and settles\n // when `_onCompositionEnd` re-runs the upgrade.\n this._pendingUpgrade = true;\n return;\n }\n this._swapToRich(module.createRichController());\n } catch (error) {\n // A failed runtime load or mount must reject pending `ensureEditor()`\n // callers rather than leave them hanging.\n this._failRichReady(\n error instanceof Error ? error : new Error(String(error))\n );\n } finally {\n this._upgrading = false;\n }\n }\n\n private _swapToRich(rich: PromptLineController): void {\n const previous = this._controller;\n const host = this._editorHost;\n if (!previous || !host) {\n return;\n }\n const value = previous.getValue();\n const selection = previous.getSelection();\n const hadFocus = previous.hasFocus();\n const hadKeyboardFocus = previous.getKeyboardFocus();\n\n previous.destroy();\n this._controller = rich;\n this._mode = 'rich';\n // Seeded losslessly from the textarea's text, which already reflects\n // `content`, so an in-flight identical `content` update stays a no-op.\n this._seededContent = this.content;\n this._seedPending = true;\n rich.mount(host, this._makeInit(value));\n\n rich.setTextSelection({\n from: textOffsetToDocPos(value, selection.from),\n to: textOffsetToDocPos(value, selection.to),\n });\n if (hadFocus) {\n rich.focus(hadKeyboardFocus, true);\n }\n this._settleRichReady();\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'cds-aichat-prompt-line': PromptLineElement;\n }\n}\n\nexport default PromptLineElement;\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA;;;;;;;AAOG;AAsDH,IAAM,iBAAiB,GAAvB,MAAM,iBAAkB,SAAQ,UAAU,CAAA;AAA1C,IAAA,WAAA,GAAA;;AAKE;;;;;;;;;;;;;;;AAeG;QAEH,IAAA,CAAA,UAAU,GAAgB,EAAE;AAS5B;;;;AAIG;QAEH,IAAA,CAAA,IAAI,GAAG,KAAK;;QAIZ,IAAA,CAAA,QAAQ,GAAG,KAAK;;QAIhB,IAAA,CAAA,WAAW,GAAG,EAAE;;QAIP,IAAA,CAAA,SAAS,GAAG,SAAS;;QAI9B,IAAA,CAAA,MAAM,GAAG,EAAE;;QAIF,IAAA,CAAA,SAAS,GAAG,KAAK;QAElB,IAAA,CAAA,WAAW,GAAgC,IAAI;QAC/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BAAA,CAAA,SAAA,EAAA,WAAA,EAAA,MAAA,CAAA;AAzDvB,iBAAiB,GAAA,UAAA,CAAA;AADtB,IAAA,aAAa,CAAC,CAAA,EAAG,MAAM,CAAA,YAAA,CAAc;AAChC,CAAA,EAAA,iBAAiB,CAgkBtB;AAQD,0BAAe,iBAAiB;;"}
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { css } from 'lit';
9
9
 
10
- var styles = css([":host{align-self:flex-start;display:flex;flex:0 1}cds-button.cds-aichat--input-send-button svg{fill:var(--cds-interactive,#0f62fe);block-size:1rem;cursor:inherit;inline-size:1rem}cds-button.cds-aichat--input-send-button[disabled] svg{fill:var(--cds-icon-disabled,hsla(0,0%,9%,.25))}cds-button.cds-aichat--input-send-button:not([disabled]):active svg,cds-button.cds-aichat--input-send-button:not([disabled]):focus svg{fill:var(--cds-interactive,#0f62fe)}:host(:dir(rtl)) cds-button.cds-aichat--input-send-button svg{transform:scaleX(-1)}"]);
10
+ var styles = css([":host{align-self:flex-start;display:flex;flex:0 1}cds-button.cds-aichat--input-send-button svg{block-size:1rem;cursor:inherit;fill:var(--cds-interactive,#0f62fe);inline-size:1rem}cds-button.cds-aichat--input-send-button[disabled] svg{fill:var(--cds-icon-disabled,rgba(22,22,22,.25))}cds-button.cds-aichat--input-send-button:not([disabled]):active svg,cds-button.cds-aichat--input-send-button:not([disabled]):focus svg{fill:var(--cds-interactive,#0f62fe)}:host(:dir(rtl)) cds-button.cds-aichat--input-send-button svg{transform:scaleX(-1)}"]);
11
11
 
12
12
  export { styles as default };
13
13
  //# sourceMappingURL=send-control.scss.js.map
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { css } from 'lit';
9
9
 
10
- var styles = css([".cds-aichat--stop-icon svg{padding-block-start:4px}.cds-aichat--stop-icon--disabled svg{fill:var(--cds-icon-disabled,hsla(0,0%,9%,.25))}"]);
10
+ var styles = css([".cds-aichat--stop-icon svg{padding-block-start:4px}.cds-aichat--stop-icon--disabled svg{fill:var(--cds-icon-disabled,rgba(22,22,22,.25))}"]);
11
11
 
12
12
  export { styles as default };
13
13
  //# sourceMappingURL=stop-streaming-button.scss.js.map
@@ -7,6 +7,7 @@
7
7
 
8
8
  import Mention from '@tiptap/extension-mention';
9
9
  import { PluginKey, Plugin } from '@tiptap/pm/state';
10
+ import isEqual from 'lodash-es/isEqual.js';
10
11
  import { isHostOrigin } from './origin-meta.js';
11
12
  import { CarbonTokenNodeView } from './token-node-view.js';
12
13
  import { dispatchTriggerChange } from './trigger-utils.js';
@@ -46,20 +47,20 @@ function buildTriggerExtension(config, build) {
46
47
  addProseMirrorPlugins() {
47
48
  const parentPlugins = this.parent?.() ?? [];
48
49
  const onRemove = config.onRemove;
49
- if (!onRemove) {
50
+ const onInsert = config.onSelect;
51
+ if (!onRemove && !onInsert) {
50
52
  return parentPlugins;
51
53
  }
52
- // Fire `onRemove` once per token node of this type that leaves the doc
53
- // via a USER edit. `appendTransaction` records whether the batch was
54
- // host-origin — `some`, where typing-indicator uses `every` — and the
55
- // view's `update` runs the diff (after state is applied, so host
56
- // callbacks never re-enter `dispatch`). Host-origin batches — the
57
- // framework's post-send clear and any `getEditor()`/`updateContent`
58
- // mutation — are skipped, symmetric with `onSelect` firing only on user
59
- // popup selection.
54
+ // Fire `onRemove` / `onSelect` once per token node of this type that
55
+ // leaves or enters the doc via a USER edit (e.g. deletion, undo, redo).
56
+ // `appendTransaction` records whether the batch was host-origin — `some`,
57
+ // where typing-indicator uses `every` — and the view's `update` runs the diff
58
+ // (after state is applied, so host callbacks never re-enter `dispatch`).
59
+ // Host-origin batches — the framework's post-send clear and any
60
+ // `getEditor()`/`updateContent` mutation — are skipped.
60
61
  let lastBatchIsHost = false;
61
- const removalPlugin = new Plugin({
62
- key: new PluginKey(`${name}_removal`),
62
+ const lifecyclePlugin = new Plugin({
63
+ key: new PluginKey(`${name}_lifecycle`),
63
64
  appendTransaction(transactions) {
64
65
  lastBatchIsHost = transactions.some((tr) => isHostOrigin(tr));
65
66
  return null;
@@ -69,14 +70,22 @@ function buildTriggerExtension(config, build) {
69
70
  if (view.state.doc === prevState.doc || lastBatchIsHost) {
70
71
  return;
71
72
  }
72
- const removed = diffRemovedTokens(prevState.doc, view.state.doc, name);
73
- for (const item of removed) {
74
- onRemove(item);
73
+ if (onRemove) {
74
+ const removed = diffRemovedTokens(prevState.doc, view.state.doc, name);
75
+ for (const item of removed) {
76
+ onRemove(item);
77
+ }
78
+ }
79
+ if (onInsert) {
80
+ const added = diffAddedTokens(prevState.doc, view.state.doc, name);
81
+ for (const item of added) {
82
+ onInsert(item);
83
+ }
75
84
  }
76
85
  },
77
86
  }),
78
87
  });
79
- return [...parentPlugins, removalPlugin];
88
+ return [...parentPlugins, lifecyclePlugin];
80
89
  },
81
90
  }).configure({
82
91
  HTMLAttributes: { 'data-token-type': name },
@@ -166,16 +175,29 @@ function attrsToItem(attrs) {
166
175
  * duplicate).
167
176
  */
168
177
  function diffRemovedTokens(before, after, name) {
178
+ return diffAddedTokens(after, before, name);
179
+ }
180
+ /**
181
+ * Diff token nodes named `name` between `before` and `after`, returning the
182
+ * reconstructed items for each added token node instance.
183
+ */
184
+ function diffAddedTokens(before, after, name) {
169
185
  const beforeById = collectTokenAttrsById(before, name);
170
186
  const afterById = collectTokenAttrsById(after, name);
171
- const removed = [];
172
- for (const [id, beforeAttrs] of beforeById) {
173
- const afterCount = afterById.get(id)?.length ?? 0;
174
- for (let i = afterCount; i < beforeAttrs.length; i += 1) {
175
- removed.push(attrsToItem(beforeAttrs[i]));
187
+ const added = [];
188
+ for (const [id, afterAttrs] of afterById) {
189
+ const unmatchedBefore = [...(beforeById.get(id) ?? [])];
190
+ for (const attrs of afterAttrs) {
191
+ const match = unmatchedBefore.findIndex((beforeAttrs) => isEqual(beforeAttrs, attrs));
192
+ if (match === -1) {
193
+ added.push(attrsToItem(attrs));
194
+ }
195
+ else {
196
+ unmatchedBefore.splice(match, 1);
197
+ }
176
198
  }
177
199
  }
178
- return removed;
200
+ return added;
179
201
  }
180
202
  /**
181
203
  * Resolve whether a selected item's chip should be prefixed with the
@@ -1 +1 @@
1
- {"version":3,"file":"carbon-mention.js","sources":["../../../../../src/components/prompt-line/src/tiptap/carbon-mention.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * `carbonMention` and `carbonCommand` factories. Both wrap\n * `@tiptap/extension-mention` with carbon-specific:\n * - chip rendering via `CarbonTokenNodeView` (uses the light-DOM portal\n * handshake so React portal consumers render in light DOM).\n * - extra schema attrs (`value`, `data`, `trigger`) layered on top of\n * Mention's default `id` + `label`.\n * - direct `cds-aichat-trigger-change` dispatch from the suggestion-render\n * lifecycle via the shared `dispatchTriggerChange` helper.\n * - an `onRemove` callback fired when a user edit deletes a token node, the\n * mirror of the suggestion `onSelect` (see the removal ProseMirror plugin).\n *\n * They share an internal builder. The two exports differ only in their\n * default schema-node name (`\"mention\"` vs `\"command\"`), the dispatched\n * trigger type, the default chip color (handled inside the NodeView), and\n * the default for whether the trigger char is stored on inserted nodes —\n * `carbonCommand` defaults to on, `carbonMention` to off, so command chips\n * default to reading as `/summarize` while mention chips stay a bare name.\n * Either default can be overridden per-config (`TriggerSuggestionConfig.\n * showTriggerInChip`) or per-item (`SuggestionItem.showTriggerInChip`, which\n * wins when set — e.g. a single `@` picker mixing people and agents).\n * Each chat supports one mention trigger and one command trigger, because\n * Tiptap resolves extensions by name.\n */\n\nimport type { Editor, Range } from '@tiptap/core';\nimport Mention from '@tiptap/extension-mention';\nimport type { Node as PMNode } from '@tiptap/pm/model';\nimport { Plugin, PluginKey } from '@tiptap/pm/state';\n\nimport { isHostOrigin } from './origin-meta.js';\nimport { CarbonTokenNodeView } from './token-node-view.js';\nimport { dispatchTriggerChange } from './trigger-utils.js';\nimport type { SuggestionItem, TriggerSuggestionConfig } from './types.js';\n\ninterface BuildOptions {\n defaultName: 'mention' | 'command';\n defaultPluginKeyName: string;\n}\n\nfunction buildTriggerExtension(\n config: TriggerSuggestionConfig,\n build: BuildOptions\n) {\n const name = build.defaultName;\n const pluginKey = new PluginKey(`${build.defaultPluginKeyName}_${name}`);\n\n return Mention.extend({\n name,\n\n addAttributes() {\n const parent = (this.parent?.() ?? {}) as Record<string, unknown>;\n return {\n ...parent,\n mentionSuggestionChar: { default: config.trigger },\n value: { default: null },\n // Host custom fields, held in editor state only: they survive the JSON\n // round-trip, undo/redo, and moves within the document, and never\n // reach HTML. Tiptap's default attribute rendering would stringify the\n // object into the markup as \"[object Object]\".\n data: { default: null, renderHTML: () => ({}) },\n trigger: { default: null },\n };\n },\n\n addNodeView() {\n return ({ node, editor }) =>\n new CarbonTokenNodeView(node, editor.view, {\n renderCustomToken: config.renderCustomToken,\n });\n },\n\n addProseMirrorPlugins() {\n const parentPlugins = this.parent?.() ?? [];\n const onRemove = config.onRemove;\n if (!onRemove) {\n return parentPlugins;\n }\n\n // Fire `onRemove` once per token node of this type that leaves the doc\n // via a USER edit. `appendTransaction` records whether the batch was\n // host-origin — `some`, where typing-indicator uses `every` — and the\n // view's `update` runs the diff (after state is applied, so host\n // callbacks never re-enter `dispatch`). Host-origin batches — the\n // framework's post-send clear and any `getEditor()`/`updateContent`\n // mutation — are skipped, symmetric with `onSelect` firing only on user\n // popup selection.\n let lastBatchIsHost = false;\n\n const removalPlugin = new Plugin({\n key: new PluginKey(`${name}_removal`),\n appendTransaction(transactions) {\n lastBatchIsHost = transactions.some((tr) => isHostOrigin(tr));\n return null;\n },\n view: () => ({\n update(view, prevState) {\n if (view.state.doc === prevState.doc || lastBatchIsHost) {\n return;\n }\n const removed = diffRemovedTokens(\n prevState.doc,\n view.state.doc,\n name\n );\n for (const item of removed) {\n onRemove(item);\n }\n },\n }),\n });\n\n return [...parentPlugins, removalPlugin];\n },\n }).configure({\n HTMLAttributes: { 'data-token-type': name },\n suggestion: {\n char: config.trigger,\n pluginKey,\n startOfLine: config.triggerPosition === 'start',\n render: () => {\n let lastQuery: string | null = null;\n return {\n onStart: (props) =>\n emitTrigger(props.editor, name, props.query, props.range, () => {\n lastQuery = props.query;\n }),\n onUpdate: (props) => {\n if (props.query === lastQuery) {\n return;\n }\n lastQuery = props.query;\n emitTrigger(props.editor, name, props.query, props.range);\n },\n onExit: (props) => {\n lastQuery = null;\n dispatchTriggerChange(props.editor, null, name);\n },\n onKeyDown: () => false,\n };\n },\n },\n });\n}\n\nfunction emitTrigger(\n editor: Editor,\n type: string,\n query: string,\n range: Range,\n postEmit?: () => void\n): void {\n dispatchTriggerChange(editor, {\n type,\n query,\n triggerOffset: range.from,\n });\n postEmit?.();\n}\n\n/**\n * Collect the attrs of every node named `name` in `doc`, grouped by id and\n * kept in document order, so a multiset diff can tell which specific node\n * instances were removed (duplicate chips with the same id are tracked by\n * count, not collapsed).\n */\nfunction collectTokenAttrsById(\n doc: PMNode,\n name: string\n): Map<string, Record<string, unknown>[]> {\n const byId = new Map<string, Record<string, unknown>[]>();\n doc.descendants((node) => {\n if (node.type.name !== name) {\n return;\n }\n const attrs = node.attrs as Record<string, unknown>;\n const id = String(attrs.id);\n const bucket = byId.get(id);\n if (bucket) {\n bucket.push(attrs);\n } else {\n byId.set(id, [attrs]);\n }\n });\n return byId;\n}\n\n/**\n * Reconstruct a {@link SuggestionItem} from a removed token node's attrs.\n * Presentation-only fields were stripped at insert time, so only `id`,\n * `label`, `value`, and any custom fields stashed in `data` survive.\n */\nfunction attrsToItem(attrs: Record<string, unknown>): SuggestionItem {\n // `data` holds whatever a caller put in the node's attrs, and\n // `insertContent()` takes a raw node spec — so a host can land a string or\n // an array here. Spreading either yields index keys ({...'abc'} → {0:'a'}),\n // which would then reach onRemove as if the host had set them.\n const raw = attrs.data;\n const data =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {};\n return {\n ...data,\n id: String(attrs.id),\n label: attrs.label as string,\n value: (attrs.value ?? undefined) as string | undefined,\n };\n}\n\n/**\n * Diff token nodes named `name` between `before` and `after`, returning the\n * reconstructed items for each removed node instance (one entry per removed\n * duplicate).\n */\nfunction diffRemovedTokens(\n before: PMNode,\n after: PMNode,\n name: string\n): SuggestionItem[] {\n const beforeById = collectTokenAttrsById(before, name);\n const afterById = collectTokenAttrsById(after, name);\n const removed: SuggestionItem[] = [];\n for (const [id, beforeAttrs] of beforeById) {\n const afterCount = afterById.get(id)?.length ?? 0;\n for (let i = afterCount; i < beforeAttrs.length; i += 1) {\n removed.push(attrsToItem(beforeAttrs[i]));\n }\n }\n return removed;\n}\n\n/**\n * Resolve whether a selected item's chip should be prefixed with the\n * trigger character: the item's own {@link SuggestionItem.showTriggerInChip}\n * wins when set, then the config's\n * {@link TriggerSuggestionConfig.showTriggerInChip}, then the\n * command/mention default.\n */\nexport function resolveShowTriggerInChip(\n item: SuggestionItem,\n config: Pick<TriggerSuggestionConfig, 'showTriggerInChip'>,\n isCommand: boolean\n): boolean {\n return item.showTriggerInChip ?? config.showTriggerInChip ?? isCommand;\n}\n\nexport function carbonMention(config: TriggerSuggestionConfig) {\n return buildTriggerExtension(config, {\n defaultName: 'mention',\n defaultPluginKeyName: 'carbonMentionSuggestion',\n });\n}\n\nexport function carbonCommand(config: TriggerSuggestionConfig) {\n return buildTriggerExtension(config, {\n defaultName: 'command',\n defaultPluginKeyName: 'carbonCommandSuggestion',\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AAAA;;;;;;;AAOG;AA0CH,SAAS,qBAAqB,CAC5B,MAA+B,EAC/B,KAAmB,EAAA;AAEnB,IAAA,MAAM,IAAI,GAAG,KAAK,CAAC,WAAW;AAC9B,IAAA,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,CAAA,EAAG,KAAK,CAAC,oBAAoB,CAAA,CAAA,EAAI,IAAI,CAAA,CAAE,CAAC;IAExE,OAAO,OAAO,CAAC,MAAM,CAAC;QACpB,IAAI;QAEJ,aAAa,GAAA;YACX,MAAM,MAAM,IAAI,IAAI,CAAC,MA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AoB,EAAE,yBAAyB;AAChD,KAAA,CAAC;AACJ;;"}
1
+ {"version":3,"file":"carbon-mention.js","sources":["../../../../../src/components/prompt-line/src/tiptap/carbon-mention.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * `carbonMention` and `carbonCommand` factories. Both wrap\n * `@tiptap/extension-mention` with carbon-specific:\n * - chip rendering via `CarbonTokenNodeView` (uses the light-DOM portal\n * handshake so React portal consumers render in light DOM).\n * - extra schema attrs (`value`, `data`, `trigger`) layered on top of\n * Mention's default `id` + `label`.\n * - direct `cds-aichat-trigger-change` dispatch from the suggestion-render\n * lifecycle via the shared `dispatchTriggerChange` helper.\n * - `onSelect` / `onRemove` callbacks fired when a token node enters or leaves\n * the doc via any user edit (autocomplete selection, undo, redo, delete).\n *\n * They share an internal builder. The two exports differ only in their\n * default schema-node name (`\"mention\"` vs `\"command\"`), the dispatched\n * trigger type, the default chip color (handled inside the NodeView), and\n * the default for whether the trigger char is stored on inserted nodes —\n * `carbonCommand` defaults to on, `carbonMention` to off, so command chips\n * default to reading as `/summarize` while mention chips stay a bare name.\n * Either default can be overridden per-config (`TriggerSuggestionConfig.\n * showTriggerInChip`) or per-item (`SuggestionItem.showTriggerInChip`, which\n * wins when set — e.g. a single `@` picker mixing people and agents).\n * Each chat supports one mention trigger and one command trigger, because\n * Tiptap resolves extensions by name.\n */\n\nimport type { Editor, Range } from '@tiptap/core';\nimport Mention from '@tiptap/extension-mention';\nimport type { Node as PMNode } from '@tiptap/pm/model';\nimport { Plugin, PluginKey } from '@tiptap/pm/state';\nimport isEqual from 'lodash-es/isEqual.js';\n\nimport { isHostOrigin } from './origin-meta.js';\nimport { CarbonTokenNodeView } from './token-node-view.js';\nimport { dispatchTriggerChange } from './trigger-utils.js';\nimport type { SuggestionItem, TriggerSuggestionConfig } from './types.js';\n\ninterface BuildOptions {\n defaultName: 'mention' | 'command';\n defaultPluginKeyName: string;\n}\n\nfunction buildTriggerExtension(\n config: TriggerSuggestionConfig,\n build: BuildOptions\n) {\n const name = build.defaultName;\n const pluginKey = new PluginKey(`${build.defaultPluginKeyName}_${name}`);\n\n return Mention.extend({\n name,\n\n addAttributes() {\n const parent = (this.parent?.() ?? {}) as Record<string, unknown>;\n return {\n ...parent,\n mentionSuggestionChar: { default: config.trigger },\n value: { default: null },\n // Host custom fields, held in editor state only: they survive the JSON\n // round-trip, undo/redo, and moves within the document, and never\n // reach HTML. Tiptap's default attribute rendering would stringify the\n // object into the markup as \"[object Object]\".\n data: { default: null, renderHTML: () => ({}) },\n trigger: { default: null },\n };\n },\n\n addNodeView() {\n return ({ node, editor }) =>\n new CarbonTokenNodeView(node, editor.view, {\n renderCustomToken: config.renderCustomToken,\n });\n },\n\n addProseMirrorPlugins() {\n const parentPlugins = this.parent?.() ?? [];\n const onRemove = config.onRemove;\n const onInsert = config.onSelect;\n if (!onRemove && !onInsert) {\n return parentPlugins;\n }\n\n // Fire `onRemove` / `onSelect` once per token node of this type that\n // leaves or enters the doc via a USER edit (e.g. deletion, undo, redo).\n // `appendTransaction` records whether the batch was host-origin — `some`,\n // where typing-indicator uses `every` — and the view's `update` runs the diff\n // (after state is applied, so host callbacks never re-enter `dispatch`).\n // Host-origin batches — the framework's post-send clear and any\n // `getEditor()`/`updateContent` mutation — are skipped.\n let lastBatchIsHost = false;\n\n const lifecyclePlugin = new Plugin({\n key: new PluginKey(`${name}_lifecycle`),\n appendTransaction(transactions) {\n lastBatchIsHost = transactions.some((tr) => isHostOrigin(tr));\n return null;\n },\n view: () => ({\n update(view, prevState) {\n if (view.state.doc === prevState.doc || lastBatchIsHost) {\n return;\n }\n if (onRemove) {\n const removed = diffRemovedTokens(\n prevState.doc,\n view.state.doc,\n name\n );\n for (const item of removed) {\n onRemove(item);\n }\n }\n if (onInsert) {\n const added = diffAddedTokens(\n prevState.doc,\n view.state.doc,\n name\n );\n for (const item of added) {\n onInsert(item);\n }\n }\n },\n }),\n });\n\n return [...parentPlugins, lifecyclePlugin];\n },\n }).configure({\n HTMLAttributes: { 'data-token-type': name },\n suggestion: {\n char: config.trigger,\n pluginKey,\n startOfLine: config.triggerPosition === 'start',\n render: () => {\n let lastQuery: string | null = null;\n return {\n onStart: (props) =>\n emitTrigger(props.editor, name, props.query, props.range, () => {\n lastQuery = props.query;\n }),\n onUpdate: (props) => {\n if (props.query === lastQuery) {\n return;\n }\n lastQuery = props.query;\n emitTrigger(props.editor, name, props.query, props.range);\n },\n onExit: (props) => {\n lastQuery = null;\n dispatchTriggerChange(props.editor, null, name);\n },\n onKeyDown: () => false,\n };\n },\n },\n });\n}\n\nfunction emitTrigger(\n editor: Editor,\n type: string,\n query: string,\n range: Range,\n postEmit?: () => void\n): void {\n dispatchTriggerChange(editor, {\n type,\n query,\n triggerOffset: range.from,\n });\n postEmit?.();\n}\n\n/**\n * Collect the attrs of every node named `name` in `doc`, grouped by id and\n * kept in document order, so a multiset diff can tell which specific node\n * instances were removed (duplicate chips with the same id are tracked by\n * count, not collapsed).\n */\nfunction collectTokenAttrsById(\n doc: PMNode,\n name: string\n): Map<string, Record<string, unknown>[]> {\n const byId = new Map<string, Record<string, unknown>[]>();\n doc.descendants((node) => {\n if (node.type.name !== name) {\n return;\n }\n const attrs = node.attrs as Record<string, unknown>;\n const id = String(attrs.id);\n const bucket = byId.get(id);\n if (bucket) {\n bucket.push(attrs);\n } else {\n byId.set(id, [attrs]);\n }\n });\n return byId;\n}\n\n/**\n * Reconstruct a {@link SuggestionItem} from a removed token node's attrs.\n * Presentation-only fields were stripped at insert time, so only `id`,\n * `label`, `value`, and any custom fields stashed in `data` survive.\n */\nfunction attrsToItem(attrs: Record<string, unknown>): SuggestionItem {\n // `data` holds whatever a caller put in the node's attrs, and\n // `insertContent()` takes a raw node spec — so a host can land a string or\n // an array here. Spreading either yields index keys ({...'abc'} → {0:'a'}),\n // which would then reach onRemove as if the host had set them.\n const raw = attrs.data;\n const data =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {};\n return {\n ...data,\n id: String(attrs.id),\n label: attrs.label as string,\n value: (attrs.value ?? undefined) as string | undefined,\n };\n}\n\n/**\n * Diff token nodes named `name` between `before` and `after`, returning the\n * reconstructed items for each removed node instance (one entry per removed\n * duplicate).\n */\nfunction diffRemovedTokens(\n before: PMNode,\n after: PMNode,\n name: string\n): SuggestionItem[] {\n return diffAddedTokens(after, before, name);\n}\n\n/**\n * Diff token nodes named `name` between `before` and `after`, returning the\n * reconstructed items for each added token node instance.\n */\nfunction diffAddedTokens(\n before: PMNode,\n after: PMNode,\n name: string\n): SuggestionItem[] {\n const beforeById = collectTokenAttrsById(before, name);\n const afterById = collectTokenAttrsById(after, name);\n const added: SuggestionItem[] = [];\n for (const [id, afterAttrs] of afterById) {\n const unmatchedBefore = [...(beforeById.get(id) ?? [])];\n for (const attrs of afterAttrs) {\n const match = unmatchedBefore.findIndex((beforeAttrs) =>\n isEqual(beforeAttrs, attrs)\n );\n if (match === -1) {\n added.push(attrsToItem(attrs));\n } else {\n unmatchedBefore.splice(match, 1);\n }\n }\n }\n return added;\n}\n\n/**\n * Resolve whether a selected item's chip should be prefixed with the\n * trigger character: the item's own {@link SuggestionItem.showTriggerInChip}\n * wins when set, then the config's\n * {@link TriggerSuggestionConfig.showTriggerInChip}, then the\n * command/mention default.\n */\nexport function resolveShowTriggerInChip(\n item: SuggestionItem,\n config: Pick<TriggerSuggestionConfig, 'showTriggerInChip'>,\n isCommand: boolean\n): boolean {\n return item.showTriggerInChip ?? config.showTriggerInChip ?? isCommand;\n}\n\nexport function carbonMention(config: TriggerSuggestionConfig) {\n return buildTriggerExtension(config, {\n defaultName: 'mention',\n defaultPluginKeyName: 'carbonMentionSuggestion',\n });\n}\n\nexport function carbonCommand(config: TriggerSuggestionConfig) {\n return buildTriggerExtension(config, {\n defaultName: 'command',\n defaultPluginKeyName: 'carbonCommandSuggestion',\n });\n}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CAAC;IACpD,MAAM,KAAK,GAAqB,EAAE;IAClC,KAAK,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,IAAI,SAAS,EAAE;AACxC,QAAA,MAAM,eAAe,GAAG,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;AACvD,QAAA,KAAK,MAAM,KAAK,IAAI,UAAU,EAAE;AAC9B,YAAA,MAAM,KAAK,GAAG,eAAe,CAAC,SAAS,CAAC,CAAC,WAAW,KAClD,OAAO,CAAC,WAAW,EAAE,KAAK,CAAC,CAC5B;AACD,YAAA,IAAI,KAAK,KAAK,EAAE,EAAE;gBAChB,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;YAChC;iBAAO;AACL,gBAAA,eAAe,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;YAClC;QACF;IACF;AACA,IAAA,OAAO,KAAK;AACd;AAEA;;;;;;AAMG;SACa,wBAAwB,CACtC,IAAoB,EACpB,MAA0D,EAC1D,SAAkB,EAAA;IAElB,OAAO,IAAI,CAAC,iBAAiB,IAAI,MAAM,CAAC,iBAAiB,IAAI,SAAS;AACxE;AAEM,SAAU,aAAa,CAAC,MAA+B,EAAA;IAC3D,OAAO,qBAAqB,CAAC,MAAM,EAAE;AACnC,QAAA,WAAW,EAAE,SAAS;AACtB,QAAA,oBAAoB,EAAE,yBAAyB;AAChD,KAAA,CAAC;AACJ;AAEM,SAAU,aAAa,CAAC,MAA+B,EAAA;IAC3D,OAAO,qBAAqB,CAAC,MAAM,EAAE;AACnC,QAAA,WAAW,EAAE,SAAS;AACtB,QAAA,oBAAoB,EAAE,yBAAyB;AAChD,KAAA,CAAC;AACJ;;"}
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { Extension } from '@tiptap/core';
9
+ import { Slice, Fragment } from '@tiptap/pm/model';
9
10
  import { Plugin } from '@tiptap/pm/state';
10
11
 
11
12
  /**
@@ -41,8 +42,11 @@ function createPastePlugin() {
41
42
  const { schema } = view.state;
42
43
  const lines = text.replace(/\r\n?/g, '\n').split('\n');
43
44
  const nodes = linesToNodes(schema, lines);
44
- const { from, to } = view.state.selection;
45
- const tr = view.state.tr.replaceWith(from, to, nodes);
45
+ // openStart=1/openEnd=1 marks the boundary paragraphs as open so
46
+ // ProseMirror merges them into the surrounding content rather than
47
+ // inserting closed blocks that would split the enclosing paragraph.
48
+ const slice = new Slice(Fragment.from(nodes), 1, 1);
49
+ const tr = view.state.tr.replaceSelection(slice);
46
50
  view.dispatch(tr.scrollIntoView());
47
51
  return true;
48
52
  },
@@ -66,7 +70,8 @@ function createPastePlugin() {
66
70
  if (!pos) {
67
71
  return true;
68
72
  }
69
- const tr = view.state.tr.replaceWith(pos.pos, pos.pos, nodes);
73
+ const slice = new Slice(Fragment.from(nodes), 1, 1);
74
+ const tr = view.state.tr.replace(pos.pos, pos.pos, slice);
70
75
  view.dispatch(tr.scrollIntoView());
71
76
  event.preventDefault();
72
77
  return true;
@@ -1 +1 @@
1
- {"version":3,"file":"plain-text-paste.js","sources":["../../../../../src/components/prompt-line/src/tiptap/plain-text-paste.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Tiptap plain-text-paste extension. Intercepts paste/drop events,\n * extracts plain text, and inserts it as paragraph nodes split on\n * newlines. Schema-agnostic — only requires `paragraph` and `text`\n * nodes.\n */\n\nimport { Extension } from '@tiptap/core';\nimport type { Schema } from '@tiptap/pm/model';\nimport { Plugin } from '@tiptap/pm/state';\n\nfunction linesToNodes(schema: Schema, lines: string[]) {\n return lines.map((line) => {\n if (line.length === 0) {\n return schema.nodes.paragraph.create();\n }\n return schema.nodes.paragraph.create(null, schema.text(line));\n });\n}\n\nfunction createPastePlugin(): Plugin {\n return new Plugin({\n props: {\n handlePaste(view, event, _slice) {\n const text = event.clipboardData?.getData('text/plain');\n if (text == null) {\n return false;\n }\n\n const { schema } = view.state;\n const lines = text.replace(/\\r\\n?/g, '\\n').split('\\n');\n const nodes = linesToNodes(schema, lines);\n\n const { from, to } = view.state.selection;\n const tr = view.state.tr.replaceWith(from, to, nodes);\n view.dispatch(tr.scrollIntoView());\n return true;\n },\n\n handleDrop(view, event, _slice, moved) {\n // Allow internal drag-and-drop (moved content within the editor)\n if (moved) {\n return false;\n }\n\n // Block external drops to prevent rich content\n const text = event.dataTransfer?.getData('text/plain');\n if (!text) {\n return true; // block the drop\n }\n\n const { schema } = view.state;\n const lines = text.replace(/\\r\\n?/g, '\\n').split('\\n');\n const nodes = linesToNodes(schema, lines);\n\n const pos = view.posAtCoords({\n left: event.clientX,\n top: event.clientY,\n });\n if (!pos) {\n return true;\n }\n\n const tr = view.state.tr.replaceWith(pos.pos, pos.pos, nodes);\n view.dispatch(tr.scrollIntoView());\n event.preventDefault();\n return true;\n },\n },\n });\n}\n\nexport const PlainTextPaste = Extension.create({\n name: 'carbonPlainTextPaste',\n\n addProseMirrorPlugins() {\n return [createPastePlugin()];\n },\n});\n"],"names":[],"mappings":";;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;AAKG;AAMH,SAAS,YAAY,CAAC,MAAc,EAAE,KAAe,EAAA;AACnD,IAAA,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAI;AACxB,QAAA,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;YACrB,OAAO,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,EAAE;QACxC;AACA,QAAA,OAAO,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC/D,IAAA,CAAC,CAAC;AACJ;AAEA,SAAS,iBAAiB,GAAA;IACxB,OAAO,IAAI,MAAM,CAAC;AAChB,QAAA,KAAK,EAAE;AACL,YAAA,WAAW,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A,MAAM,GAAG,GAAG,IAAI,CAAC,WAAW,CAAC;oBAC3B,IAAI,EAAE,KAAK,CAAC,OAAO;oBACnB,GAAG,EAAE,KAAK,CAAC,OAAO;AACnB,iBAAA,CAAC;gBACF,IAAI,CAAC,GAAG,EAAE;AACR,oBAAA,OAAO,IAAI;gBACb;gBAEA,MAAM,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC;gBAC7D,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,cAAc,EAAE,CAAC;gBAClC,KAAK,CAAC,cAAc,EAAE;AACtB,gBAAA,OAAO,IAAI;YACb,CAAC;AACF,SAAA;AACF,KAAA,CAAC;AACJ;AAEO,MAAM,cAAc,GAAG,SAAS,CAAC,MAAM,CAAC;AAC7C,IAAA,IAAI,EAAE,sBAAsB;IAE5B,qBAAqB,GAAA;AACnB,QAAA,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAC9B,CAAC;AACF,CAAA;;"}
1
+ {"version":3,"file":"plain-text-paste.js","sources":["../../../../../src/components/prompt-line/src/tiptap/plain-text-paste.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Tiptap plain-text-paste extension. Intercepts paste/drop events,\n * extracts plain text, and inserts it as paragraph nodes split on\n * newlines. Schema-agnostic — only requires `paragraph` and `text`\n * nodes.\n */\n\nimport { Extension } from '@tiptap/core';\nimport { Fragment, Slice } from '@tiptap/pm/model';\nimport type { Schema } from '@tiptap/pm/model';\nimport { Plugin } from '@tiptap/pm/state';\n\nfunction linesToNodes(schema: Schema, lines: string[]) {\n return lines.map((line) => {\n if (line.length === 0) {\n return schema.nodes.paragraph.create();\n }\n return schema.nodes.paragraph.create(null, schema.text(line));\n });\n}\n\nfunction createPastePlugin(): Plugin {\n return new Plugin({\n props: {\n handlePaste(view, event, _slice) {\n const text = event.clipboardData?.getData('text/plain');\n if (text == null) {\n return false;\n }\n\n const { schema } = view.state;\n const lines = text.replace(/\\r\\n?/g, '\\n').split('\\n');\n const nodes = linesToNodes(schema, lines);\n\n // openStart=1/openEnd=1 marks the boundary paragraphs as open so\n // ProseMirror merges them into the surrounding content rather than\n // inserting closed blocks that would split the enclosing paragraph.\n const slice = new Slice(Fragment.from(nodes), 1, 1);\n const tr = view.state.tr.replaceSelection(slice);\n view.dispatch(tr.scrollIntoView());\n return true;\n },\n\n handleDrop(view, event, _slice, moved) {\n // Allow internal drag-and-drop (moved content within the editor)\n if (moved) {\n return false;\n }\n\n // Block external drops to prevent rich content\n const text = event.dataTransfer?.getData('text/plain');\n if (!text) {\n return true; // block the drop\n }\n\n const { schema } = view.state;\n const lines = text.replace(/\\r\\n?/g, '\\n').split('\\n');\n const nodes = linesToNodes(schema, lines);\n\n const pos = view.posAtCoords({\n left: event.clientX,\n top: event.clientY,\n });\n if (!pos) {\n return true;\n }\n\n const slice = new Slice(Fragment.from(nodes), 1, 1);\n const tr = view.state.tr.replace(pos.pos, pos.pos, slice);\n view.dispatch(tr.scrollIntoView());\n event.preventDefault();\n return true;\n },\n },\n });\n}\n\nexport const PlainTextPaste = Extension.create({\n name: 'carbonPlainTextPaste',\n\n addProseMirrorPlugins() {\n return [createPastePlugin()];\n },\n});\n"],"names":[],"mappings":";;;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;AAKG;AAOH,SAAS,YAAY,CAAC,MAAc,EAAE,KAAe,EAAA;AACnD,IAAA,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAI;AACxB,QAAA,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;YACrB,OAAO,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,EAAE;QACxC;AACA,QAAA,OAAO,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,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AAG,IAAI,CAAC,KAAK;AAC7B,gBAAA,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC;gBACtD,MAAM,KAAK,GAAG,YAAY,CAAC,MAAM,EAAE,KAAK,CAAC;AAEzC,gBAAA,MAAM,GAAG,GAAG,IAAI,CAAC,WAAW,CAAC;oBAC3B,IAAI,EAAE,KAAK,CAAC,OAAO;oBACnB,GAAG,EAAE,KAAK,CAAC,OAAO;AACnB,iBAAA,CAAC;gBACF,IAAI,CAAC,GAAG,EAAE;AACR,oBAAA,OAAO,IAAI;gBACb;AAEA,gBAAA,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;gBACnD,MAAM,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC;gBACzD,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,cAAc,EAAE,CAAC;gBAClC,KAAK,CAAC,cAAc,EAAE;AACtB,gBAAA,OAAO,IAAI;YACb,CAAC;AACF,SAAA;AACF,KAAA,CAAC;AACJ;AAEO,MAAM,cAAc,GAAG,SAAS,CAAC,MAAM,CAAC;AAC7C,IAAA,IAAI,EAAE,sBAAsB;IAE5B,qBAAqB,GAAA;AACnB,QAAA,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAC9B,CAAC;AACF,CAAA;;"}
@@ -10,9 +10,9 @@
10
10
  * Drops the fields a chip renders from its own attrs: `id`, `label`, `value`,
11
11
  * and the presentation-only `avatar`, `description`, `disabled`, and
12
12
  * `showTriggerInChip`. Grouping metadata (`groupId`, `groupTitle`) survives,
13
- * matching what `TriggerSuggestionConfig.onRemove` documents as retained.
14
- * Used by AutocompleteController at insert time to fill the token node's
15
- * `data` attr, so `onRemove` can hand those fields back.
13
+ * matching what `TriggerSuggestionConfig.onSelect`/`onRemove` document as
14
+ * retained. Used by AutocompleteController at insert time to fill the token
15
+ * node's `data` attr, so `onSelect`/`onRemove` can hand those fields back.
16
16
  */
17
17
  import type { SuggestionItem } from './types.js';
18
18
  export declare function stripPresentationFields(item: SuggestionItem): Record<string, unknown>;
@@ -1 +1 @@
1
- {"version":3,"file":"strip-presentation-fields.js","sources":["../../../../../src/components/prompt-line/src/tiptap/strip-presentation-fields.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Drops the fields a chip renders from its own attrs: `id`, `label`, `value`,\n * and the presentation-only `avatar`, `description`, `disabled`, and\n * `showTriggerInChip`. Grouping metadata (`groupId`, `groupTitle`) survives,\n * matching what `TriggerSuggestionConfig.onRemove` documents as retained.\n * Used by AutocompleteController at insert time to fill the token node's\n * `data` attr, so `onRemove` can hand those fields back.\n */\n\nimport type { SuggestionItem } from './types.js';\n\nexport function stripPresentationFields(\n item: SuggestionItem\n): Record<string, unknown> {\n const {\n id: _id,\n label: _label,\n value: _value,\n avatar: _avatar,\n description: _description,\n disabled: _disabled,\n showTriggerInChip: _showTriggerInChip,\n ...rest\n } = item;\n void _id;\n void _label;\n void _value;\n void _avatar;\n void _description;\n void _disabled;\n void _showTriggerInChip;\n return rest;\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAaG,SAAU,uBAAuB,CACrC,IAAoB,EAAA;AAEpB,IAAA,MAAM,EACJ,EAAE,EAAE,GAAG,EACP,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,OAAO,EACf,WAAW,EAAE,YAAY,EACzB,QAAQ,EAAE,SAAS,EACnB,iBAAiB,EAAE,kBAAkB,EACrC,GAAG,IAAI,EACR,GAAG,IAAI;AAQR,IAAA,OAAO,IAAI;AACb;;"}
1
+ {"version":3,"file":"strip-presentation-fields.js","sources":["../../../../../src/components/prompt-line/src/tiptap/strip-presentation-fields.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Drops the fields a chip renders from its own attrs: `id`, `label`, `value`,\n * and the presentation-only `avatar`, `description`, `disabled`, and\n * `showTriggerInChip`. Grouping metadata (`groupId`, `groupTitle`) survives,\n * matching what `TriggerSuggestionConfig.onSelect`/`onRemove` document as\n * retained. Used by AutocompleteController at insert time to fill the token\n * node's `data` attr, so `onSelect`/`onRemove` can hand those fields back.\n */\n\nimport type { SuggestionItem } from './types.js';\n\nexport function stripPresentationFields(\n item: SuggestionItem\n): Record<string, unknown> {\n const {\n id: _id,\n label: _label,\n value: _value,\n avatar: _avatar,\n description: _description,\n disabled: _disabled,\n showTriggerInChip: _showTriggerInChip,\n ...rest\n } = item;\n void _id;\n void _label;\n void _value;\n void _avatar;\n void _description;\n void _disabled;\n void _showTriggerInChip;\n return rest;\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAaG,SAAU,uBAAuB,CACrC,IAAoB,EAAA;AAEpB,IAAA,MAAM,EACJ,EAAE,EAAE,GAAG,EACP,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,OAAO,EACf,WAAW,EAAE,YAAY,EACzB,QAAQ,EAAE,SAAS,EACnB,iBAAiB,EAAE,kBAAkB,EACrC,GAAG,IAAI,EACR,GAAG,IAAI;AAQR,IAAA,OAAO,IAAI;AACb;;"}
@@ -136,7 +136,7 @@ export interface BaseSuggestionConfig {
136
136
  * `disableDirectSend` is always `true` for these triggers and is therefore
137
137
  * omitted so it cannot be set or overridden.
138
138
  */
139
- export interface TriggerSuggestionConfig extends Omit<BaseSuggestionConfig, 'disableDirectSend'> {
139
+ export interface TriggerSuggestionConfig extends Omit<BaseSuggestionConfig, 'disableDirectSend' | 'onSelect'> {
140
140
  /** Character that activates the suggestion (e.g. "@", "/"). */
141
141
  trigger: string;
142
142
  /** Whether the trigger must appear at the start of the input/line, or
@@ -145,19 +145,35 @@ export interface TriggerSuggestionConfig extends Omit<BaseSuggestionConfig, 'dis
145
145
  /** Replace the visual element rendered inside the token chip. */
146
146
  renderCustomToken?: (item: SuggestionItem) => HTMLElement | ReactNode;
147
147
  /**
148
- * Called when a previously-inserted token for this trigger is removed from
149
- * the input by a user edit (backspace, delete, cut, select-all, undo, ...).
150
- * The mirror of {@link BaseSuggestionConfig}'s `onSelect`: fires once per
151
- * removed node instance, so deleting one of two identical chips fires
152
- * exactly once. Use it to keep host-owned structured data in sync with the
153
- * editor.
148
+ * Called whenever a token chip for this trigger **enters** the editor via
149
+ * any user edit: selecting from the autocomplete, undo restoring a deleted chip,
150
+ * or redo. Fires once per added node instance (duplicate chips with
151
+ * the same id are tracked individually).
154
152
  *
155
153
  * The item is reconstructed from the node's stored attributes (`id`,
156
154
  * `label`, `value`, plus any custom fields preserved in `data`);
157
- * presentation-only fields (`icon`, `avatar`, `description`, `disabled`) are
158
- * not retained on the node and are absent. Programmatic removals (via
159
- * `getEditor()`/`updateContent`) are host-origin and do NOT fire `onRemove`,
160
- * symmetric with `onSelect` not firing on programmatic inserts.
155
+ * presentation-only fields (`avatar`, `description`, `disabled`,
156
+ * `showTriggerInChip`) are not retained on the node and are absent.
157
+ * `updateContent` tags host-origin transactions and suppresses `onSelect`.
158
+ * Raw `getEditor()` commands require explicit `setHostOriginMeta` tagging.
159
+ *
160
+ * Use the symmetric {@link TriggerSuggestionConfig.onRemove} to keep
161
+ * host-owned structured data in sync in both directions.
162
+ */
163
+ onSelect?: (item: SuggestionItem) => void;
164
+ /**
165
+ * Called when a token chip for this trigger **leaves** the editor via any
166
+ * user edit: backspace, delete, cut, select-all+type, undo of an insert, ....
167
+ * Fires once per removed node instance, so deleting one of two identical
168
+ * chips fires exactly once. Use it to keep host-owned structured data in sync
169
+ * with the editor.
170
+ *
171
+ * The item is reconstructed from the node's stored attributes (`id`,
172
+ * `label`, `value`, plus any custom fields preserved in `data`);
173
+ * presentation-only fields (`avatar`, `description`, `disabled`,
174
+ * `showTriggerInChip`) are not retained on the node and are absent.
175
+ * `updateContent` tags host-origin transactions and suppresses `onRemove`.
176
+ * Raw `getEditor()` commands require explicit `setHostOriginMeta` tagging.
161
177
  */
162
178
  onRemove?: (item: SuggestionItem) => void;
163
179
  /**
@@ -23,9 +23,9 @@ declare class CDSAIChatReasoningStep extends LitElement {
23
23
  private renderStaticHeader;
24
24
  /**
25
25
  * The panel animates `grid-template-rows` when the step expands/collapses. We wait for
26
- * any in-flight transition on the panel to finish, then emit a composed event so
27
- * consumers (e.g. the message list's scroll manager) can recalculate scroll geometry
28
- * against the settled layout.
26
+ * any in-flight transition on the panel to finish, then emit a composed event so host
27
+ * listeners can recalculate layout against the settled geometry. The event is public; the
28
+ * message list's scroll controller no longer listens to it.
29
29
  *
30
30
  * Using the Web Animations API (`getAnimations`) handles both cases with one path: when a
31
31
  * transition runs we resolve on its `finished` promise, and when nothing animates (reduced
@@ -70,7 +70,7 @@ let CDSAIChatReasoningStep = class CDSAIChatReasoningStep extends LitElement {
70
70
  changedProperties.has('hasBodyContent')) {
71
71
  this.updatePanelInertState();
72
72
  }
73
- // Announce when a real open/close toggle has settled so the scroll manager can
73
+ // Announce when a real open/close toggle has settled so host listeners can
74
74
  // recalculate geometry. Skip the initial render (no previous value).
75
75
  if (changedProperties.has('open') &&
76
76
  changedProperties.get('open') !== undefined) {
@@ -186,9 +186,9 @@ let CDSAIChatReasoningStep = class CDSAIChatReasoningStep extends LitElement {
186
186
  }
187
187
  /**
188
188
  * The panel animates `grid-template-rows` when the step expands/collapses. We wait for
189
- * any in-flight transition on the panel to finish, then emit a composed event so
190
- * consumers (e.g. the message list's scroll manager) can recalculate scroll geometry
191
- * against the settled layout.
189
+ * any in-flight transition on the panel to finish, then emit a composed event so host
190
+ * listeners can recalculate layout against the settled geometry. The event is public; the
191
+ * message list's scroll controller no longer listens to it.
192
192
  *
193
193
  * Using the Web Animations API (`getAnimations`) handles both cases with one path: when a
194
194
  * transition runs we resolve on its `finished` promise, and when nothing animates (reduced