@carbon/ai-chat-components 1.11.0 → 1.12.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/custom-elements.json +2358 -1973
  2. package/es/components/card/src/card-footer.scss.js +1 -1
  3. package/es/components/card/src/card-steps.scss.js +1 -1
  4. package/es/components/card/src/card.scss.js +1 -1
  5. package/es/components/chat-button/src/chat-button.scss.js +1 -1
  6. package/es/components/chat-history/src/history-panel-item-input.js +0 -1
  7. package/es/components/chat-history/src/history-panel-item-input.js.map +1 -1
  8. package/es/components/code-snippet/src/codemirror/language-controller.js +1 -1
  9. package/es/components/code-snippet/src/codemirror/language-controller.js.map +1 -1
  10. package/es/components/file-uploads/src/file-upload-item.d.ts +14 -1
  11. package/es/components/file-uploads/src/file-upload-item.js +78 -2
  12. package/es/components/file-uploads/src/file-upload-item.js.map +1 -1
  13. package/es/components/file-uploads/src/file-uploads.d.ts +29 -4
  14. package/es/components/file-uploads/src/file-uploads.js +69 -16
  15. package/es/components/file-uploads/src/file-uploads.js.map +1 -1
  16. package/es/components/launcher/src/launcher.scss.js +1 -1
  17. package/es/components/prompt-line/autocomplete/index.d.ts +1 -1
  18. package/es/components/prompt-line/autocomplete/src/autocomplete.d.ts +6 -0
  19. package/es/components/prompt-line/autocomplete/src/autocomplete.js +37 -11
  20. package/es/components/prompt-line/autocomplete/src/autocomplete.js.map +1 -1
  21. package/es/components/prompt-line/index.d.ts +3 -2
  22. package/es/components/prompt-line/index.js +2 -1
  23. package/es/components/prompt-line/index.js.map +1 -1
  24. package/es/components/prompt-line/src/__tests__/wait-for-rich.d.ts +20 -0
  25. package/es/components/prompt-line/src/autocomplete-controller-element.d.ts +84 -0
  26. package/es/components/prompt-line/src/autocomplete-controller-element.js +262 -0
  27. package/es/components/prompt-line/src/autocomplete-controller-element.js.map +1 -0
  28. package/es/components/prompt-line/src/autocomplete-controller.d.ts +10 -69
  29. package/es/components/prompt-line/src/autocomplete-controller.js +57 -251
  30. package/es/components/prompt-line/src/autocomplete-controller.js.map +1 -1
  31. package/es/components/prompt-line/src/prompt-line-rich-runtime.js +3 -0
  32. package/es/components/prompt-line/src/prompt-line-rich-runtime.js.map +1 -1
  33. package/es/components/prompt-line/src/prompt-line-shell.scss.js +1 -1
  34. package/es/components/prompt-line/src/prompt-line-textarea-runtime.js +0 -5
  35. package/es/components/prompt-line/src/prompt-line-textarea-runtime.js.map +1 -1
  36. package/es/components/prompt-line/src/prompt-line.js +1 -1
  37. package/es/components/prompt-line/src/prompt-line.js.map +1 -1
  38. package/es/components/prompt-line/src/send-control.d.ts +7 -0
  39. package/es/components/prompt-line/src/send-control.js +53 -5
  40. package/es/components/prompt-line/src/send-control.js.map +1 -1
  41. package/es/components/prompt-line/src/tiptap/build-extensions.js +1 -1
  42. package/es/components/prompt-line/src/tiptap/build-extensions.js.map +1 -1
  43. package/es/components/prompt-line/src/tiptap/carbon-autocomplete.d.ts +5 -6
  44. package/es/components/prompt-line/src/tiptap/carbon-autocomplete.js +24 -48
  45. package/es/components/prompt-line/src/tiptap/carbon-autocomplete.js.map +1 -1
  46. package/es/components/prompt-line/src/tiptap/carbon-mention.js +14 -48
  47. package/es/components/prompt-line/src/tiptap/carbon-mention.js.map +1 -1
  48. package/es/components/prompt-line/src/tiptap/carbon-starter-trigger.js +3 -4
  49. package/es/components/prompt-line/src/tiptap/carbon-starter-trigger.js.map +1 -1
  50. package/es/components/prompt-line/src/tiptap/keymap.d.ts +1 -1
  51. package/es/components/prompt-line/src/tiptap/keymap.js +3 -4
  52. package/es/components/prompt-line/src/tiptap/keymap.js.map +1 -1
  53. package/es/components/prompt-line/src/tiptap/render-token-chip.js +0 -1
  54. package/es/components/prompt-line/src/tiptap/render-token-chip.js.map +1 -1
  55. package/es/components/prompt-line/src/tiptap/resolve-config-items.d.ts +18 -0
  56. package/es/components/prompt-line/src/tiptap/resolve-config-items.js +32 -0
  57. package/es/components/prompt-line/src/tiptap/resolve-config-items.js.map +1 -0
  58. package/es/components/prompt-line/src/tiptap/strip-presentation-fields.d.ts +18 -0
  59. package/es/components/prompt-line/src/tiptap/strip-presentation-fields.js +22 -0
  60. package/es/components/prompt-line/src/tiptap/strip-presentation-fields.js.map +1 -0
  61. package/es/components/prompt-line/src/tiptap/trigger-utils.d.ts +12 -8
  62. package/es/components/prompt-line/src/tiptap/trigger-utils.js +16 -1
  63. package/es/components/prompt-line/src/tiptap/trigger-utils.js.map +1 -1
  64. package/es/components/prompt-line/src/tiptap/types.d.ts +11 -3
  65. package/es/components/toolbar/src/toolbar.d.ts +8 -0
  66. package/es/components/toolbar/src/toolbar.js +65 -19
  67. package/es/components/toolbar/src/toolbar.js.map +1 -1
  68. package/es/components/video-player/src/providers/vimeo-provider.js +1 -1
  69. package/es/components/video-player/src/providers/vimeo-provider.js.map +1 -1
  70. package/es/globals/decorators/carbon-element.js +2 -3
  71. package/es/globals/decorators/carbon-element.js.map +1 -1
  72. package/es/globals/utils/aria-announcer-manager.d.ts +56 -0
  73. package/es/globals/utils/aria-announcer-manager.js +46 -1
  74. package/es/globals/utils/aria-announcer-manager.js.map +1 -1
  75. package/es/globals/utils/focus-utils.js +1 -3
  76. package/es/globals/utils/focus-utils.js.map +1 -1
  77. package/es/globals/utils/iconTransform.d.ts +16 -2
  78. package/es/globals/utils/iconTransform.js +22 -1
  79. package/es/globals/utils/iconTransform.js.map +1 -1
  80. package/es/react/hooks/useChatAutocomplete.d.ts +5 -0
  81. package/es/react/hooks/useChatAutocomplete.js +26 -1
  82. package/es/react/hooks/useChatAutocomplete.js.map +1 -1
  83. package/es/react/markdown.js +0 -1
  84. package/es/react/markdown.js.map +1 -1
  85. package/es/typings/overflow-menu.d.ts +4 -0
  86. package/es-custom/components/card/src/card-footer.scss.js +1 -1
  87. package/es-custom/components/card/src/card-steps.scss.js +1 -1
  88. package/es-custom/components/card/src/card.scss.js +1 -1
  89. package/es-custom/components/chat-button/src/chat-button.scss.js +1 -1
  90. package/es-custom/components/chat-history/src/history-panel-item-input.js +0 -1
  91. package/es-custom/components/chat-history/src/history-panel-item-input.js.map +1 -1
  92. package/es-custom/components/code-snippet/src/codemirror/language-controller.js +1 -1
  93. package/es-custom/components/code-snippet/src/codemirror/language-controller.js.map +1 -1
  94. package/es-custom/components/file-uploads/src/file-upload-item.d.ts +14 -1
  95. package/es-custom/components/file-uploads/src/file-upload-item.js +78 -2
  96. package/es-custom/components/file-uploads/src/file-upload-item.js.map +1 -1
  97. package/es-custom/components/file-uploads/src/file-uploads.d.ts +29 -4
  98. package/es-custom/components/file-uploads/src/file-uploads.js +69 -16
  99. package/es-custom/components/file-uploads/src/file-uploads.js.map +1 -1
  100. package/es-custom/components/launcher/src/launcher.scss.js +1 -1
  101. package/es-custom/components/prompt-line/autocomplete/index.d.ts +1 -1
  102. package/es-custom/components/prompt-line/autocomplete/src/autocomplete.d.ts +6 -0
  103. package/es-custom/components/prompt-line/autocomplete/src/autocomplete.js +37 -11
  104. package/es-custom/components/prompt-line/autocomplete/src/autocomplete.js.map +1 -1
  105. package/es-custom/components/prompt-line/index.d.ts +3 -2
  106. package/es-custom/components/prompt-line/index.js +2 -1
  107. package/es-custom/components/prompt-line/index.js.map +1 -1
  108. package/es-custom/components/prompt-line/src/__tests__/wait-for-rich.d.ts +20 -0
  109. package/es-custom/components/prompt-line/src/autocomplete-controller-element.d.ts +84 -0
  110. package/es-custom/components/prompt-line/src/autocomplete-controller-element.js +262 -0
  111. package/es-custom/components/prompt-line/src/autocomplete-controller-element.js.map +1 -0
  112. package/es-custom/components/prompt-line/src/autocomplete-controller.d.ts +10 -69
  113. package/es-custom/components/prompt-line/src/autocomplete-controller.js +57 -251
  114. package/es-custom/components/prompt-line/src/autocomplete-controller.js.map +1 -1
  115. package/es-custom/components/prompt-line/src/prompt-line-rich-runtime.js +3 -0
  116. package/es-custom/components/prompt-line/src/prompt-line-rich-runtime.js.map +1 -1
  117. package/es-custom/components/prompt-line/src/prompt-line-shell.scss.js +1 -1
  118. package/es-custom/components/prompt-line/src/prompt-line-textarea-runtime.js +0 -5
  119. package/es-custom/components/prompt-line/src/prompt-line-textarea-runtime.js.map +1 -1
  120. package/es-custom/components/prompt-line/src/prompt-line.js +1 -1
  121. package/es-custom/components/prompt-line/src/prompt-line.js.map +1 -1
  122. package/es-custom/components/prompt-line/src/send-control.d.ts +7 -0
  123. package/es-custom/components/prompt-line/src/send-control.js +53 -5
  124. package/es-custom/components/prompt-line/src/send-control.js.map +1 -1
  125. package/es-custom/components/prompt-line/src/tiptap/build-extensions.js +1 -1
  126. package/es-custom/components/prompt-line/src/tiptap/build-extensions.js.map +1 -1
  127. package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.d.ts +5 -6
  128. package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.js +24 -48
  129. package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.js.map +1 -1
  130. package/es-custom/components/prompt-line/src/tiptap/carbon-mention.js +14 -48
  131. package/es-custom/components/prompt-line/src/tiptap/carbon-mention.js.map +1 -1
  132. package/es-custom/components/prompt-line/src/tiptap/carbon-starter-trigger.js +3 -4
  133. package/es-custom/components/prompt-line/src/tiptap/carbon-starter-trigger.js.map +1 -1
  134. package/es-custom/components/prompt-line/src/tiptap/keymap.d.ts +1 -1
  135. package/es-custom/components/prompt-line/src/tiptap/keymap.js +3 -4
  136. package/es-custom/components/prompt-line/src/tiptap/keymap.js.map +1 -1
  137. package/es-custom/components/prompt-line/src/tiptap/render-token-chip.js +0 -1
  138. package/es-custom/components/prompt-line/src/tiptap/render-token-chip.js.map +1 -1
  139. package/es-custom/components/prompt-line/src/tiptap/resolve-config-items.d.ts +18 -0
  140. package/es-custom/components/prompt-line/src/tiptap/resolve-config-items.js +32 -0
  141. package/es-custom/components/prompt-line/src/tiptap/resolve-config-items.js.map +1 -0
  142. package/es-custom/components/prompt-line/src/tiptap/strip-presentation-fields.d.ts +18 -0
  143. package/es-custom/components/prompt-line/src/tiptap/strip-presentation-fields.js +22 -0
  144. package/es-custom/components/prompt-line/src/tiptap/strip-presentation-fields.js.map +1 -0
  145. package/es-custom/components/prompt-line/src/tiptap/trigger-utils.d.ts +12 -8
  146. package/es-custom/components/prompt-line/src/tiptap/trigger-utils.js +16 -1
  147. package/es-custom/components/prompt-line/src/tiptap/trigger-utils.js.map +1 -1
  148. package/es-custom/components/prompt-line/src/tiptap/types.d.ts +11 -3
  149. package/es-custom/components/toolbar/src/toolbar.d.ts +8 -0
  150. package/es-custom/components/toolbar/src/toolbar.js +65 -19
  151. package/es-custom/components/toolbar/src/toolbar.js.map +1 -1
  152. package/es-custom/components/video-player/src/providers/vimeo-provider.js +1 -1
  153. package/es-custom/components/video-player/src/providers/vimeo-provider.js.map +1 -1
  154. package/es-custom/globals/decorators/carbon-element.js +2 -3
  155. package/es-custom/globals/decorators/carbon-element.js.map +1 -1
  156. package/es-custom/globals/utils/aria-announcer-manager.d.ts +56 -0
  157. package/es-custom/globals/utils/aria-announcer-manager.js +46 -1
  158. package/es-custom/globals/utils/aria-announcer-manager.js.map +1 -1
  159. package/es-custom/globals/utils/focus-utils.js +1 -3
  160. package/es-custom/globals/utils/focus-utils.js.map +1 -1
  161. package/es-custom/globals/utils/iconTransform.d.ts +16 -2
  162. package/es-custom/globals/utils/iconTransform.js +22 -1
  163. package/es-custom/globals/utils/iconTransform.js.map +1 -1
  164. package/es-custom/react/hooks/useChatAutocomplete.d.ts +5 -0
  165. package/es-custom/react/hooks/useChatAutocomplete.js +26 -1
  166. package/es-custom/react/hooks/useChatAutocomplete.js.map +1 -1
  167. package/es-custom/react/markdown.js +0 -1
  168. package/es-custom/react/markdown.js.map +1 -1
  169. package/es-custom/typings/overflow-menu.d.ts +4 -0
  170. package/package.json +6 -6
  171. package/scss/_custom-properties.scss +0 -17
  172. package/scss/_tokens-component.scss +1 -2
@@ -1 +1 @@
1
- {"version":3,"file":"aria-announcer-manager.js","sources":["../../../src/globals/utils/aria-announcer-manager.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2025, 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 * Politeness of a live-region announcement.\n *\n * - `polite` — status/content updates the user benefits from but shouldn't have\n * interrupted. The default.\n * - `assertive` — errors that block the user's progress; interrupts whatever the\n * screen reader is currently reading. Use sparingly.\n */\ntype AnnouncerPoliteness = 'polite' | 'assertive';\n\n/**\n * One live-region channel: the regions it rotates through plus the pending-queue\n * and timer state used to coalesce same-tick announcements.\n */\ninterface AnnouncerChannel {\n regions: HTMLDivElement[];\n currentIndex: number;\n pendingAnnouncements: string[];\n announcementTimeoutId: number | null;\n}\n\nfunction createChannel(): AnnouncerChannel {\n return {\n regions: [],\n currentIndex: 0,\n pendingAnnouncements: [],\n announcementTimeoutId: null,\n };\n}\n\n/**\n * Manages ARIA live region announcements for screen readers.\n *\n * Rotates writes across N visually-hidden live regions. Rotation forces\n * assistive tech to re-announce identical messages and lets us clear\n * previous content without racing the announcement.\n *\n * Two independent channels are maintained — `polite` and `assertive` — each with\n * its own regions, rotation, and coalescing queue, so an assertive (blocking)\n * message never coalesces with a polite one. Assertive is opt-in: pass assertive\n * regions to {@link connect} and a politeness to {@link announce}. The politeness\n * of the rendered region (its `aria-live` value) is owned by the consumer's\n * markup; the channel only routes text to the right set of regions.\n *\n * `chat-shell` connects two polite regions; the React announcer in\n * `@carbon/ai-chat` connects three polite regions (the extra region helps NVDA +\n * JAWS reliably pick up back-to-back identical messages) plus assertive regions.\n *\n * Both consumers share this implementation so a fix to the screen-reader\n * workarounds (250 ms NVDA delay, dual-clear pattern) propagates to both.\n */\nexport class AriaAnnouncerManager {\n private polite = createChannel();\n private assertive = createChannel();\n\n /**\n * Initialize the manager with the live-region elements it should rotate\n * through. `politeRegions` must contain at least one element; two or three is\n * typical. `assertiveRegions` is optional — omit it for polite-only consumers.\n */\n connect(\n politeRegions: HTMLDivElement[],\n assertiveRegions: HTMLDivElement[] = []\n ): void {\n this.polite.regions = politeRegions.slice();\n this.polite.currentIndex = 0;\n this.assertive.regions = assertiveRegions.slice();\n this.assertive.currentIndex = 0;\n }\n\n /**\n * Cancel any pending announcements and detach from the regions.\n */\n disconnect(): void {\n this.clearChannel(this.polite);\n this.clearChannel(this.assertive);\n this.polite.regions = [];\n this.assertive.regions = [];\n }\n\n /**\n * Queue a message to be announced on the next tick. Multiple calls in the\n * same tick (and politeness) are coalesced into a single announcement.\n * Defaults to polite; falls back to polite if assertive is requested but no\n * assertive regions are connected.\n */\n announce(message: string, politeness: AnnouncerPoliteness = 'polite'): void {\n if (!message || typeof window === 'undefined') {\n return;\n }\n\n const channel =\n politeness === 'assertive' && this.assertive.regions.length > 0\n ? this.assertive\n : this.polite;\n\n channel.pendingAnnouncements.push(message);\n\n if (channel.announcementTimeoutId === null) {\n // 250 ms delay works around an NVDA bug: a focus change at the same\n // time as a live-region update can drop the announcement entirely.\n // Smaller numbers were less reliable in testing.\n channel.announcementTimeoutId = window.setTimeout(() => {\n this.doAnnouncements(channel);\n }, 250);\n }\n }\n\n private clearChannel(channel: AnnouncerChannel): void {\n if (\n channel.announcementTimeoutId !== null &&\n typeof window !== 'undefined'\n ) {\n window.clearTimeout(channel.announcementTimeoutId);\n channel.announcementTimeoutId = null;\n }\n channel.pendingAnnouncements = [];\n }\n\n private doAnnouncements(channel: AnnouncerChannel): void {\n channel.announcementTimeoutId = null;\n\n if (\n channel.pendingAnnouncements.length === 0 ||\n channel.regions.length === 0\n ) {\n channel.pendingAnnouncements = [];\n return;\n }\n\n const message = channel.pendingAnnouncements.join(' ');\n channel.pendingAnnouncements = [];\n\n const writeRegion = channel.regions[channel.currentIndex];\n if (writeRegion) {\n writeRegion.textContent = message;\n }\n\n // Clear every other region so the active one stands out as the change.\n channel.regions.forEach((region, index) => {\n if (index !== channel.currentIndex && region) {\n region.textContent = '';\n }\n });\n\n channel.currentIndex = (channel.currentIndex + 1) % channel.regions.length;\n }\n}\n"],"names":[],"mappings":";;;;;;;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AAC,YAAY,IAAI,MAAM,EAAE;AAC5C,gBAAA,MAAM,CAAC,WAAW,GAAG,EAAE;YACzB;AACF,QAAA,CAAC,CAAC;AAEF,QAAA,OAAO,CAAC,YAAY,GAAG,CAAC,OAAO,CAAC,YAAY,GAAG,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,MAAM;IAC5E;AACD;;"}
1
+ {"version":3,"file":"aria-announcer-manager.js","sources":["../../../src/globals/utils/aria-announcer-manager.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2025, 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 * Politeness of a live-region announcement.\n *\n * - `polite` — status/content updates the user benefits from but shouldn't have\n * interrupted. The default.\n * - `assertive` — errors that block the user's progress; interrupts whatever the\n * screen reader is currently reading. Use sparingly.\n */\ntype AnnouncerPoliteness = 'polite' | 'assertive';\n\n/**\n * Options for {@link mountAriaAnnouncer}.\n */\nexport interface AriaAnnouncerOptions {\n /**\n * Number of polite `aria-live=\"polite\"` regions to create and rotate through.\n * Default `1`. The React `AriaAnnouncerProvider` passes `3` explicitly: in\n * earlier testing FF + JAWS occasionally re-read entire region contents on\n * append; a third region ensures there is always a fresh region for the next\n * announcement.\n */\n politeCount?: number;\n /**\n * Number of `aria-live=\"assertive\"` regions to create.\n * Default 0 (polite-only).\n */\n assertiveCount?: number;\n /**\n * Sets `aria-atomic` on every created region. Default `false`.\n *\n * Note: `aria-atomic` is intentionally left off by default. With it, FF +\n * JAWS read some messages cleanly but Chrome stops announcing buttons inside\n * the region. Without it, FF + JAWS sometimes double-read parts but Chrome\n * handles buttons. The default (off) is the lesser evil.\n */\n ariaAtomic?: boolean;\n}\n\n/**\n * Handle returned by {@link mountAriaAnnouncer}. Call `disconnect` when the\n * host element is removed from the DOM to cancel pending timers and clean up\n * the created regions.\n */\nexport interface AriaAnnouncerHandle {\n /**\n * Queue a message for announcement on the next tick. Multiple same-tick calls\n * for the same politeness are coalesced into a single write. Defaults to\n * `\"polite\"`; falls back to polite if assertive regions were not created.\n */\n announce(message: string, politeness?: AnnouncerPoliteness): void;\n /**\n * Cancel pending announcements, disconnect the manager, and remove the\n * created live regions from `container`.\n */\n disconnect(): void;\n}\n\n/**\n * One live-region channel: the regions it rotates through plus the pending-queue\n * and timer state used to coalesce same-tick announcements.\n */\ninterface AnnouncerChannel {\n regions: HTMLDivElement[];\n currentIndex: number;\n pendingAnnouncements: string[];\n announcementTimeoutId: number | null;\n}\n\nfunction createChannel(): AnnouncerChannel {\n return {\n regions: [],\n currentIndex: 0,\n pendingAnnouncements: [],\n announcementTimeoutId: null,\n };\n}\n\n/**\n * Manages ARIA live region announcements for screen readers.\n *\n * Rotates writes across N visually-hidden live regions. Rotation forces\n * assistive tech to re-announce identical messages and lets us clear\n * previous content without racing the announcement.\n *\n * Two independent channels are maintained — `polite` and `assertive` — each with\n * its own regions, rotation, and coalescing queue, so an assertive (blocking)\n * message never coalesces with a polite one. Assertive is opt-in: pass assertive\n * regions to {@link connect} and a politeness to {@link announce}. The politeness\n * of the rendered region (its `aria-live` value) is owned by the consumer's\n * markup; the channel only routes text to the right set of regions.\n *\n * `chat-shell` connects two polite regions; the React announcer in\n * `@carbon/ai-chat` connects three polite regions (the extra region helps NVDA +\n * JAWS reliably pick up back-to-back identical messages) plus assertive regions.\n *\n * Both consumers share this implementation so a fix to the screen-reader\n * workarounds (250 ms NVDA delay, dual-clear pattern) propagates to both.\n */\nexport class AriaAnnouncerManager {\n private polite = createChannel();\n private assertive = createChannel();\n\n /**\n * Initialize the manager with the live-region elements it should rotate\n * through. `politeRegions` must contain at least one element; two or three is\n * typical. `assertiveRegions` is optional — omit it for polite-only consumers.\n */\n connect(\n politeRegions: HTMLDivElement[],\n assertiveRegions: HTMLDivElement[] = []\n ): void {\n this.polite.regions = politeRegions.slice();\n this.polite.currentIndex = 0;\n this.assertive.regions = assertiveRegions.slice();\n this.assertive.currentIndex = 0;\n }\n\n /**\n * Cancel any pending announcements and detach from the regions.\n */\n disconnect(): void {\n this.clearChannel(this.polite);\n this.clearChannel(this.assertive);\n this.polite.regions = [];\n this.assertive.regions = [];\n }\n\n /**\n * Queue a message to be announced on the next tick. Multiple calls in the\n * same tick (and politeness) are coalesced into a single announcement.\n * Defaults to polite; falls back to polite if assertive is requested but no\n * assertive regions are connected.\n */\n announce(message: string, politeness: AnnouncerPoliteness = 'polite'): void {\n if (!message || typeof window === 'undefined') {\n return;\n }\n\n const channel =\n politeness === 'assertive' && this.assertive.regions.length > 0\n ? this.assertive\n : this.polite;\n\n channel.pendingAnnouncements.push(message);\n\n if (channel.announcementTimeoutId === null) {\n // 250 ms delay works around an NVDA bug: a focus change at the same\n // time as a live-region update can drop the announcement entirely.\n // Smaller numbers were less reliable in testing.\n channel.announcementTimeoutId = window.setTimeout(() => {\n this.doAnnouncements(channel);\n }, 250);\n }\n }\n\n private clearChannel(channel: AnnouncerChannel): void {\n if (\n channel.announcementTimeoutId !== null &&\n typeof window !== 'undefined'\n ) {\n window.clearTimeout(channel.announcementTimeoutId);\n channel.announcementTimeoutId = null;\n }\n channel.pendingAnnouncements = [];\n }\n\n private doAnnouncements(channel: AnnouncerChannel): void {\n channel.announcementTimeoutId = null;\n\n if (\n channel.pendingAnnouncements.length === 0 ||\n channel.regions.length === 0\n ) {\n channel.pendingAnnouncements = [];\n return;\n }\n\n const message = channel.pendingAnnouncements.join(' ');\n channel.pendingAnnouncements = [];\n\n const writeRegion = channel.regions[channel.currentIndex];\n if (writeRegion) {\n writeRegion.textContent = message;\n }\n\n // Clear every other region so the active one stands out as the change.\n channel.regions.forEach((region, index) => {\n if (index !== channel.currentIndex && region) {\n region.textContent = '';\n }\n });\n\n channel.currentIndex = (channel.currentIndex + 1) % channel.regions.length;\n }\n}\n\n/**\n * Create visually-hidden `aria-live` regions inside `container`, wire them to\n * a new {@link AriaAnnouncerManager}, and return a handle. The caller is\n * responsible for hiding the container (e.g. with a visually-hidden wrapper or\n * CSS class); this function only creates the live regions themselves.\n *\n * @param container - The element to append the live regions into.\n * @param options - Region counts and aria-atomic setting. All fields have\n * sensible defaults; pass `{}` for a single polite region.\n */\nexport function mountAriaAnnouncer(\n container: HTMLElement,\n options: AriaAnnouncerOptions = {}\n): AriaAnnouncerHandle {\n const { politeCount = 1, assertiveCount = 0, ariaAtomic = false } = options;\n\n function createRegion(politeness: AnnouncerPoliteness): HTMLDivElement {\n const el = document.createElement('div');\n el.setAttribute('aria-live', politeness);\n if (ariaAtomic) {\n el.setAttribute('aria-atomic', 'true');\n }\n container.appendChild(el);\n return el;\n }\n\n const politeRegions: HTMLDivElement[] = [];\n for (let i = 0; i < politeCount; i++) {\n politeRegions.push(createRegion('polite'));\n }\n\n const assertiveRegions: HTMLDivElement[] = [];\n for (let i = 0; i < assertiveCount; i++) {\n assertiveRegions.push(createRegion('assertive'));\n }\n\n const manager = new AriaAnnouncerManager();\n manager.connect(politeRegions, assertiveRegions);\n\n return {\n announce(message: string, politeness: AnnouncerPoliteness = 'polite') {\n manager.announce(message, politeness);\n },\n disconnect() {\n manager.disconnect();\n [...politeRegions, ...assertiveRegions].forEach((el) => {\n if (el.parentNode) {\n el.parentNode.removeChild(el);\n }\n });\n },\n };\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAsEH,SAAS,aAAa,GAAA;IACpB,OAAO;AACL,QAAA,OAAO,EAAE,EAAE;AACX,QAAA,YAAY,EAAE,CAAC;AACf,QAAA,oBAAoB,EAAE,EAAE;AACxB,QAAA,qBAAqB,EAAE,IAAI;KAC5B;AACH;AAEA;;;;;;;;;;;;;;;;;;;;AAoBG;MACU,oBAAoB,CAAA;AAAjC,IAAA,WAAA,GAAA;QACU,IAAA,CAAA,MAAM,GAAG,aAAa,EAAE;QACxB,IAAA,CAAA,SAAS,GAAG,aAAa,EAAE;IA8FrC;AA5FE;;;;AAIG;AACH,IAAA,OAAO,CACL,aAA+B,EAC/B,gBAAA,GAAqC,EAAE,EAAA;QAEv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 -147,9 +147,7 @@ function* walkComposedTree(node, whatToShow = 0, filter = () => true, skipNode =
147
147
  if (filter(node)) {
148
148
  yield node;
149
149
  }
150
- const children =
151
- // eslint-disable-next-line no-nested-ternary
152
- node instanceof HTMLElement && node.shadowRoot
150
+ const children = node instanceof HTMLElement && node.shadowRoot
153
151
  ? node.shadowRoot.children
154
152
  : node instanceof HTMLSlotElement
155
153
  ? node.assignedNodes({ flatten: true })
@@ -1 +1 @@
1
- {"version":3,"file":"focus-utils.js","sources":["../../../src/globals/utils/focus-utils.ts"],"sourcesContent":["/*\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 * @license\n */\n\n/**\n * Gets the deepest active element, traversing through all shadow DOM boundaries.\n * This handles nested shadow roots, slotted elements, and will return the actual\n * focused element regardless of how many shadow DOM levels exist.\n *\n * @returns The deepest active element, or null if no element has focus\n */\nfunction getDeepActiveElement(): Element | null {\n let activeElement = document.activeElement;\n\n // Traverse through all shadow DOM levels and handle slotted elements\n while (activeElement) {\n // If the active element is a slot, get the actual assigned element that has focus\n if (activeElement instanceof HTMLSlotElement) {\n const assignedElements = activeElement.assignedElements({\n flatten: true,\n });\n // Find which assigned element actually has focus\n const focusedAssigned = assignedElements.find((el) => {\n if ((el as any).shadowRoot?.activeElement) {\n return true;\n }\n return (\n el === document.activeElement || el.contains(document.activeElement)\n );\n });\n if (focusedAssigned) {\n activeElement = focusedAssigned;\n continue;\n }\n }\n\n // Check if there's a shadow root with an active element\n const shadowRoot = (activeElement as any).shadowRoot;\n if (shadowRoot?.activeElement) {\n activeElement = shadowRoot.activeElement;\n continue;\n }\n\n // No deeper level found\n break;\n }\n\n return activeElement;\n}\n\n/**\n * Checks if an element should be ignored due to visibility or accessibility attributes.\n *\n * @param element - The DOM element to check\n * @param exceptions - Array of selectors to ignore when checking the element (e.g., 'dialog', '[popover]')\n * @returns True if the element should be ignored by focus management, false otherwise\n */\nfunction isElementInvisible(\n element: Element,\n exceptions: string[] = ['dialog', '[popover]']\n): boolean {\n if (!element || !(element instanceof HTMLElement)) {\n return false;\n }\n\n if (exceptions.length > 0 && element.matches(exceptions.join(','))) {\n return false;\n }\n\n const computedStyle = window.getComputedStyle(element);\n const isStyleHidden =\n computedStyle.display === 'none' || computedStyle.visibility === 'hidden';\n const isAttributeHidden = element.matches(\n '[disabled], [hidden], [inert], [aria-hidden=\"true\"]'\n );\n\n return isStyleHidden || isAttributeHidden;\n}\n\n/**\n * Checks if an element is focusable. An element is considered focusable if it matches\n * standard focusable elements criteria (such as buttons, inputs, etc., that are not disabled\n * and do not have a negative tabindex) or is a custom element with a shadow root that delegates focus.\n * Based on https://gist.github.com/oscarmarina/9ce95f491a4c53ed01d989de4a87c0c9\n *\n * @param element - The DOM element to check for focusability\n * @returns True if the element is focusable, false otherwise\n */\nfunction isFocusable(element: Element): boolean {\n if (!(element instanceof HTMLElement)) {\n return false;\n }\n\n // https://stackoverflow.com/a/30753870/76472\n const knownFocusableElements =\n 'a[href],area[href],button:not([disabled]),details,iframe,object,input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[contentEditable=\"true\"],[tabindex]:not([tabindex^=\"-\"])';\n\n if (element.matches(knownFocusableElements)) {\n return true;\n }\n\n const isDisabledCustomElement =\n element.localName.includes('-') &&\n element.matches('[disabled], [aria-disabled=\"true\"]');\n\n if (isDisabledCustomElement) {\n return false;\n }\n\n return element.shadowRoot?.delegatesFocus ?? false;\n}\n\n/**\n * Attempts to focus an element if it's focusable, visible, and not disabled.\n * This is an enhanced version that checks visibility, accessibility attributes,\n * and proper focusability before attempting to set focus. It is shadow DOM aware\n * and handles slotted elements correctly.\n *\n * @param element - The element to attempt to focus\n * @param exceptions - Array of selectors to ignore when checking visibility (e.g., 'dialog', '[popover]')\n * @returns True if focus was successfully set, false otherwise\n */\nfunction tryFocus(\n element: Element | null | undefined,\n exceptions?: string[]\n): boolean {\n if (!element || !(element instanceof HTMLElement)) {\n return false;\n }\n\n // Check if element is invisible or should be ignored\n if (isElementInvisible(element, exceptions)) {\n return false;\n }\n\n // Check if element is focusable\n if (!isFocusable(element)) {\n return false;\n }\n\n // Get the current deep active element (shadow DOM aware)\n const previousActiveElement = getDeepActiveElement();\n\n // Only call focus if the element doesn't already have focus\n if (previousActiveElement !== element) {\n element.focus();\n }\n\n // Verify focus was actually set by checking the deep active element\n // This works across shadow DOM boundaries, with slotted elements, and delegatesFocus configurations\n const currentActiveElement = getDeepActiveElement();\n return (\n currentActiveElement === element || element.contains(currentActiveElement)\n );\n}\n\n/**\n * Traverse the composed tree from the root, selecting elements that meet the provided filter criteria.\n * This function properly handles Shadow DOM boundaries.\n * Based on https://github.com/JanMiksovsky/elix/blob/main/src/core/dom.js#L320\n *\n * @param node - The root node for traversal\n * @param whatToShow - NodeFilter code for node types to include (use 0 to retrieve all nodes)\n * @param filter - Filters nodes. Child nodes are considered even if parent does not satisfy the filter\n * @param skipNode - Determines whether to skip a node and its children\n * @returns An iterator yielding nodes meeting the filter criteria\n */\nfunction* walkComposedTree(\n node: Node,\n whatToShow = 0,\n filter: (node: Node) => boolean = () => true,\n skipNode: (node: Node) => boolean = () => false\n): IterableIterator<Node> {\n if ((whatToShow && node.nodeType !== whatToShow) || skipNode(node)) {\n return;\n }\n\n if (filter(node)) {\n yield node;\n }\n\n const children =\n // eslint-disable-next-line no-nested-ternary\n node instanceof HTMLElement && node.shadowRoot\n ? node.shadowRoot.children\n : node instanceof HTMLSlotElement\n ? node.assignedNodes({ flatten: true })\n : node.childNodes;\n\n for (const child of children) {\n yield* walkComposedTree(child, whatToShow, filter, skipNode);\n }\n}\n\n/**\n * Retrieves the first and last focusable children of a node using a TreeWalker.\n *\n * @param walker - The TreeWalker object used to traverse the node's children\n * @returns A tuple containing the first and last focusable children. If no focusable children are found, `null` is returned for both\n */\nfunction getFirstAndLastFocusableChildren(\n walker: IterableIterator<HTMLElement>\n): [first: HTMLElement | null, last: HTMLElement | null] {\n let firstFocusableChild: HTMLElement | null = null;\n let lastFocusableChild: HTMLElement | null = null;\n\n for (const currentNode of walker) {\n if (!firstFocusableChild) {\n firstFocusableChild = currentNode;\n }\n lastFocusableChild = currentNode;\n }\n\n return [firstFocusableChild, lastFocusableChild];\n}\n\n/**\n * Finds a descendant of `searchRoot` via `selector` and focuses it after the next\n * two animation frames. Use when DOM updates (Lit, React, reorder) replace or move\n * nodes so the previous focused element is detached (e.g. list pin/unpin).\n *\n * Tries {@link tryFocus} first for visibility/focusability checks; if that does\n * not take focus (e.g. some custom element hosts), falls back to {@link HTMLElement.focus}.\n *\n * @param searchRoot - Root to query (`Element`, `ShadowRoot`, `Document`, or `DocumentFragment`, e.g. Lit `renderRoot`)\n * @param selector - CSS selector that resolves to the node to focus.\n */\nfunction focusElementAfterRepaint(\n searchRoot: Document | Element | ShadowRoot | DocumentFragment,\n selector: string\n): void {\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n const el = searchRoot.querySelector(selector);\n if (!(el instanceof HTMLElement)) {\n return;\n }\n if (!tryFocus(el)) {\n el.focus();\n }\n });\n });\n}\n\nexport {\n getDeepActiveElement,\n isElementInvisible,\n isFocusable,\n tryFocus,\n walkComposedTree,\n getFirstAndLastFocusableChildren,\n focusElementAfterRepaint,\n};\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;AAMG;AACH,SAAS,oBAAoB,GAAA;AAC3B,IAAA,IAAI,aAAa,GAAG,QAAQ,CAAC,aAAa;;IAG1C,OAAO,aAAa,EAAE;;AAEpB,QAAA,IAAI,aAAa,YAAY,eAAe,EAAE;AAC5C,YAAA,MAAM,gBAAgB,GAAG,aAAa,CAAC,gBAAgB,CAAC;AACtD,gBAAA,OAAO,EAAE,IAAI;AACd,aAAA,CAAC;;YAEF,MAAM,eAAe,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC,EAAE,KAAI;AACnD,gBAAA,IAAK,EAAU,CAAC,UAAU,EAAE,aAAa,EAAE;AACzC,oBAAA,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,MAAM,IAAI;IACZ;AAEA,IAAA,MAAM,QAAQ;;AAEZ,IAAA,IAAI,YAAY,WAAW,IAAI,IAAI,CAAC;AAClC,UAAE,IAAI,CAAC,UAAU,CAAC;UAChB,IAAI,YAAY;cACd,IAAI,CAAC,aAAa,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE;AACtC,cAAE,IAAI,CAAC,UAAU;AAEvB,IAAA,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE;AAC5B,QAAA,OAAO,gBAAgB,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC;IAC9D;AACF;AAEA;;;;;AAKG;AACH,SAAS,gCAAgC,CACvC,MAAqC,EAAA;IAErC,IAAI,mBAAmB,GAAuB,IAAI;IAClD,IAAI,kBAAkB,GAAuB,IAAI;AAEjD,IAAA,KAAK,MAAM,WAAW,IAAI,MAAM,EAAE;QAChC,IAAI,CAAC,mBAAmB,EAAE;YACxB,mBAAmB,GAAG,WAAW;QACnC;QACA,kBAAkB,GAAG,WAAW;IAClC;AAEA,IAAA,OAAO,CAAC,mBAAmB,EAAE,kBAAkB,CAAC;AAClD;AAEA;;;;;;;;;;AAUG;AACH,SAAS,wBAAwB,CAC/B,UAA8D,EAC9D,QAAgB,EAAA;IAEhB,qBAAqB,CAAC,MAAK;QACzB,qBAAqB,CAAC,MAAK;YACzB,MAAM,EAAE,GAAG,UAAU,CAAC,aAAa,CAAC,QAAQ,CAAC;AAC7C,YAAA,IAAI,EAAE,EAAE,YAAY,WAAW,CAAC,EAAE;gBAChC;YACF;AACA,YAAA,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE;gBACjB,EAAE,CAAC,KAAK,EAAE;YACZ;AACF,QAAA,CAAC,CAAC;AACJ,IAAA,CAAC,CAAC;AACJ;;"}
1
+ {"version":3,"file":"focus-utils.js","sources":["../../../src/globals/utils/focus-utils.ts"],"sourcesContent":["/*\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 * @license\n */\n\n/**\n * Gets the deepest active element, traversing through all shadow DOM boundaries.\n * This handles nested shadow roots, slotted elements, and will return the actual\n * focused element regardless of how many shadow DOM levels exist.\n *\n * @returns The deepest active element, or null if no element has focus\n */\nfunction getDeepActiveElement(): Element | null {\n let activeElement = document.activeElement;\n\n // Traverse through all shadow DOM levels and handle slotted elements\n while (activeElement) {\n // If the active element is a slot, get the actual assigned element that has focus\n if (activeElement instanceof HTMLSlotElement) {\n const assignedElements = activeElement.assignedElements({\n flatten: true,\n });\n // Find which assigned element actually has focus\n const focusedAssigned = assignedElements.find((el) => {\n if ((el as any).shadowRoot?.activeElement) {\n return true;\n }\n return (\n el === document.activeElement || el.contains(document.activeElement)\n );\n });\n if (focusedAssigned) {\n activeElement = focusedAssigned;\n continue;\n }\n }\n\n // Check if there's a shadow root with an active element\n const shadowRoot = (activeElement as any).shadowRoot;\n if (shadowRoot?.activeElement) {\n activeElement = shadowRoot.activeElement;\n continue;\n }\n\n // No deeper level found\n break;\n }\n\n return activeElement;\n}\n\n/**\n * Checks if an element should be ignored due to visibility or accessibility attributes.\n *\n * @param element - The DOM element to check\n * @param exceptions - Array of selectors to ignore when checking the element (e.g., 'dialog', '[popover]')\n * @returns True if the element should be ignored by focus management, false otherwise\n */\nfunction isElementInvisible(\n element: Element,\n exceptions: string[] = ['dialog', '[popover]']\n): boolean {\n if (!element || !(element instanceof HTMLElement)) {\n return false;\n }\n\n if (exceptions.length > 0 && element.matches(exceptions.join(','))) {\n return false;\n }\n\n const computedStyle = window.getComputedStyle(element);\n const isStyleHidden =\n computedStyle.display === 'none' || computedStyle.visibility === 'hidden';\n const isAttributeHidden = element.matches(\n '[disabled], [hidden], [inert], [aria-hidden=\"true\"]'\n );\n\n return isStyleHidden || isAttributeHidden;\n}\n\n/**\n * Checks if an element is focusable. An element is considered focusable if it matches\n * standard focusable elements criteria (such as buttons, inputs, etc., that are not disabled\n * and do not have a negative tabindex) or is a custom element with a shadow root that delegates focus.\n * Based on https://gist.github.com/oscarmarina/9ce95f491a4c53ed01d989de4a87c0c9\n *\n * @param element - The DOM element to check for focusability\n * @returns True if the element is focusable, false otherwise\n */\nfunction isFocusable(element: Element): boolean {\n if (!(element instanceof HTMLElement)) {\n return false;\n }\n\n // https://stackoverflow.com/a/30753870/76472\n const knownFocusableElements =\n 'a[href],area[href],button:not([disabled]),details,iframe,object,input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[contentEditable=\"true\"],[tabindex]:not([tabindex^=\"-\"])';\n\n if (element.matches(knownFocusableElements)) {\n return true;\n }\n\n const isDisabledCustomElement =\n element.localName.includes('-') &&\n element.matches('[disabled], [aria-disabled=\"true\"]');\n\n if (isDisabledCustomElement) {\n return false;\n }\n\n return element.shadowRoot?.delegatesFocus ?? false;\n}\n\n/**\n * Attempts to focus an element if it's focusable, visible, and not disabled.\n * This is an enhanced version that checks visibility, accessibility attributes,\n * and proper focusability before attempting to set focus. It is shadow DOM aware\n * and handles slotted elements correctly.\n *\n * @param element - The element to attempt to focus\n * @param exceptions - Array of selectors to ignore when checking visibility (e.g., 'dialog', '[popover]')\n * @returns True if focus was successfully set, false otherwise\n */\nfunction tryFocus(\n element: Element | null | undefined,\n exceptions?: string[]\n): boolean {\n if (!element || !(element instanceof HTMLElement)) {\n return false;\n }\n\n // Check if element is invisible or should be ignored\n if (isElementInvisible(element, exceptions)) {\n return false;\n }\n\n // Check if element is focusable\n if (!isFocusable(element)) {\n return false;\n }\n\n // Get the current deep active element (shadow DOM aware)\n const previousActiveElement = getDeepActiveElement();\n\n // Only call focus if the element doesn't already have focus\n if (previousActiveElement !== element) {\n element.focus();\n }\n\n // Verify focus was actually set by checking the deep active element\n // This works across shadow DOM boundaries, with slotted elements, and delegatesFocus configurations\n const currentActiveElement = getDeepActiveElement();\n return (\n currentActiveElement === element || element.contains(currentActiveElement)\n );\n}\n\n/**\n * Traverse the composed tree from the root, selecting elements that meet the provided filter criteria.\n * This function properly handles Shadow DOM boundaries.\n * Based on https://github.com/JanMiksovsky/elix/blob/main/src/core/dom.js#L320\n *\n * @param node - The root node for traversal\n * @param whatToShow - NodeFilter code for node types to include (use 0 to retrieve all nodes)\n * @param filter - Filters nodes. Child nodes are considered even if parent does not satisfy the filter\n * @param skipNode - Determines whether to skip a node and its children\n * @returns An iterator yielding nodes meeting the filter criteria\n */\nfunction* walkComposedTree(\n node: Node,\n whatToShow = 0,\n filter: (node: Node) => boolean = () => true,\n skipNode: (node: Node) => boolean = () => false\n): IterableIterator<Node> {\n if ((whatToShow && node.nodeType !== whatToShow) || skipNode(node)) {\n return;\n }\n\n if (filter(node)) {\n yield node;\n }\n\n const children =\n node instanceof HTMLElement && node.shadowRoot\n ? node.shadowRoot.children\n : node instanceof HTMLSlotElement\n ? node.assignedNodes({ flatten: true })\n : node.childNodes;\n\n for (const child of children) {\n yield* walkComposedTree(child, whatToShow, filter, skipNode);\n }\n}\n\n/**\n * Retrieves the first and last focusable children of a node using a TreeWalker.\n *\n * @param walker - The TreeWalker object used to traverse the node's children\n * @returns A tuple containing the first and last focusable children. If no focusable children are found, `null` is returned for both\n */\nfunction getFirstAndLastFocusableChildren(\n walker: IterableIterator<HTMLElement>\n): [first: HTMLElement | null, last: HTMLElement | null] {\n let firstFocusableChild: HTMLElement | null = null;\n let lastFocusableChild: HTMLElement | null = null;\n\n for (const currentNode of walker) {\n if (!firstFocusableChild) {\n firstFocusableChild = currentNode;\n }\n lastFocusableChild = currentNode;\n }\n\n return [firstFocusableChild, lastFocusableChild];\n}\n\n/**\n * Finds a descendant of `searchRoot` via `selector` and focuses it after the next\n * two animation frames. Use when DOM updates (Lit, React, reorder) replace or move\n * nodes so the previous focused element is detached (e.g. list pin/unpin).\n *\n * Tries {@link tryFocus} first for visibility/focusability checks; if that does\n * not take focus (e.g. some custom element hosts), falls back to {@link HTMLElement.focus}.\n *\n * @param searchRoot - Root to query (`Element`, `ShadowRoot`, `Document`, or `DocumentFragment`, e.g. Lit `renderRoot`)\n * @param selector - CSS selector that resolves to the node to focus.\n */\nfunction focusElementAfterRepaint(\n searchRoot: Document | Element | ShadowRoot | DocumentFragment,\n selector: string\n): void {\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n const el = searchRoot.querySelector(selector);\n if (!(el instanceof HTMLElement)) {\n return;\n }\n if (!tryFocus(el)) {\n el.focus();\n }\n });\n });\n}\n\nexport {\n getDeepActiveElement,\n isElementInvisible,\n isFocusable,\n tryFocus,\n walkComposedTree,\n getFirstAndLastFocusableChildren,\n focusElementAfterRepaint,\n};\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;AAMG;AACH,SAAS,oBAAoB,GAAA;AAC3B,IAAA,IAAI,aAAa,GAAG,QAAQ,CAAC,aAAa;;IAG1C,OAAO,aAAa,EAAE;;AAEpB,QAAA,IAAI,aAAa,YAAY,eAAe,EAAE;AAC5C,YAAA,MAAM,gBAAgB,GAAG,aAAa,CAAC,gBAAgB,CAAC;AACtD,gBAAA,OAAO,EAAE,IAAI;AACd,aAAA,CAAC;;YAEF,MAAM,eAAe,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC,EAAE,KAAI;AACnD,gBAAA,IAAK,EAAU,CAAC,UAAU,EAAE,aAAa,EAAE;AACzC,oBAAA,OAAO,IAAI;gBACb;AACA,gBAAA,QACE,EAAE,KAAK,QAAQ,CAAC,aAAa,IAAI,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,aAAa,CAAC;AAExE,YAAA,CAAC,CAAC;YACF,IAAI,eAAe,EAAE;gBACnB,aAAa,GAAG,eAAe;gBAC/B;YACF;QACF;;AAGA,QAAA,MAAM,UAAU,GAAI,aAAqB,CAAC,UAAU;AACpD,QAAA,IAAI,UAAU,EAAE,aAAa,EAAE;AAC7B,YAAA,aAAa,GAAG,UAAU,CAAC,aAAa;YACxC;QACF;;QAGA;IACF;AAEA,IAAA,OAAO,aAAa;AACtB;AAEA;;;;;;AAMG;A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AA;IAErC,IAAI,mBAAmB,GAAuB,IAAI;IAClD,IAAI,kBAAkB,GAAuB,IAAI;AAEjD,IAAA,KAAK,MAAM,WAAW,IAAI,MAAM,EAAE;QAChC,IAAI,CAAC,mBAAmB,EAAE;YACxB,mBAAmB,GAAG,WAAW;QACnC;QACA,kBAAkB,GAAG,WAAW;IAClC;AAEA,IAAA,OAAO,CAAC,mBAAmB,EAAE,kBAAkB,CAAC;AAClD;AAEA;;;;;;;;;;AAUG;AACH,SAAS,wBAAwB,CAC/B,UAA8D,EAC9D,QAAgB,EAAA;IAEhB,qBAAqB,CAAC,MAAK;QACzB,qBAAqB,CAAC,MAAK;YACzB,MAAM,EAAE,GAAG,UAAU,CAAC,aAAa,CAAC,QAAQ,CAAC;AAC7C,YAAA,IAAI,EAAE,EAAE,YAAY,WAAW,CAAC,EAAE;gBAChC;YACF;AACA,YAAA,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE;gBACjB,EAAE,CAAC,KAAK,EAAE;YACZ;AACF,QAAA,CAAC,CAAC;AACJ,IAAA,CAAC,CAAC;AACJ;;"}
@@ -22,8 +22,12 @@
22
22
  * // carbonIcon is now in CarbonIcon format, ready for web components
23
23
  * ```
24
24
  */
25
- import React from 'react';
26
- import { CarbonIcon } from '@carbon/web-components/es/globals/internal/icon-loader-utils';
25
+ import React, { FunctionComponent } from 'react';
26
+ import { CarbonIcon, CarbonIconDescriptor } from '@carbon/web-components/es/globals/internal/icon-loader-utils';
27
+ type CarbonIconProps = React.SVGProps<SVGSVGElement> & {
28
+ slot?: string;
29
+ [key: string]: unknown;
30
+ };
27
31
  /**
28
32
  * Type guard to detect if icon is already a CarbonIcon descriptor.
29
33
  * If true, the icon should be passed through unchanged (no-op).
@@ -35,3 +39,13 @@ export declare function isCarbonIcon(icon: any): icon is CarbonIcon;
35
39
  * Caches results to avoid repeated transformations.
36
40
  */
37
41
  export declare function transformReactIconToCarbonIcon(icon: CarbonIcon | React.ComponentType<any>, size?: number): CarbonIcon;
42
+ /**
43
+ * Creates a React component from a `CarbonIconDescriptor` (a raw `@carbon/icons` import).
44
+ *
45
+ * @example
46
+ * import Launch16 from '@carbon/icons/es/launch/16';
47
+ * const LaunchIcon = carbonIconToReact(Launch16);
48
+ * <LaunchIcon aria-label="Launch" className="icon" />
49
+ */
50
+ export declare function carbonIconToReact(icon: CarbonIconDescriptor): FunctionComponent<CarbonIconProps>;
51
+ export {};
@@ -170,6 +170,27 @@ function extractIconName(props) {
170
170
  // Try various properties that might contain the icon name
171
171
  return props['data-icon-name'] || props['aria-label'] || props.name || 'icon';
172
172
  }
173
+ /**
174
+ * Creates a React component from a `CarbonIconDescriptor` (a raw `@carbon/icons` import).
175
+ *
176
+ * @example
177
+ * import Launch16 from '@carbon/icons/es/launch/16';
178
+ * const LaunchIcon = carbonIconToReact(Launch16);
179
+ * <LaunchIcon aria-label="Launch" className="icon" />
180
+ */
181
+ function carbonIconToReact(icon) {
182
+ return function IconComponent(props = {}) {
183
+ return React.createElement('svg', {
184
+ ...icon.attrs,
185
+ width: icon.attrs.width || 16,
186
+ height: icon.attrs.height || 16,
187
+ fill: icon.attrs.fill || 'currentColor',
188
+ focusable: 'false',
189
+ style: { pointerEvents: 'none' },
190
+ ...props,
191
+ }, icon.content.map((child, i) => React.createElement(child.elem, { key: i, ...(child.attrs || {}) })));
192
+ };
193
+ }
173
194
 
174
- export { isCarbonIcon, transformReactIconToCarbonIcon };
195
+ export { carbonIconToReact, isCarbonIcon, transformReactIconToCarbonIcon };
175
196
  //# sourceMappingURL=iconTransform.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"iconTransform.js","sources":["../../../src/globals/utils/iconTransform.tsx"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 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 * @license\n */\n\n/**\n * Icon Transformation Utility\n *\n * This module provides utilities to transform React icon components from @carbon/icons-react\n * into the CarbonIcon descriptor format used by @carbon/icons. This enables React developers\n * to use their familiar React icon components while maintaining compatibility with web components\n * that expect the plain JavaScript CarbonIcon format.\n *\n * Key features:\n * - Automatic transformation of React icon components to CarbonIcon descriptors\n * - No-op pass-through for CarbonIcon objects (already in correct format)\n * - Global caching to prevent redundant transformations\n * - Type guards for runtime icon format detection\n * - Support for forwardRef and memo-wrapped components\n *\n * Usage:\n * ```tsx\n * import { Add } from '@carbon/icons-react';\n * import { transformReactIconToCarbonIcon } from './iconTransform';\n *\n * const carbonIcon = transformReactIconToCarbonIcon(Add);\n * // carbonIcon is now in CarbonIcon format, ready for web components\n * ```\n */\n\nimport React from 'react';\nimport { CarbonIcon } from '@carbon/web-components/es/globals/internal/icon-loader-utils';\n\n// Global cache for transformed icons using WeakMap to key by component reference\nconst iconCache = new WeakMap<\n React.ComponentType<any>,\n Map<number, CarbonIcon>\n>();\n\n/**\n * Type guard to detect if icon is already a CarbonIcon descriptor.\n * If true, the icon should be passed through unchanged (no-op).\n */\nexport function isCarbonIcon(icon: any): icon is CarbonIcon {\n return Boolean(\n icon &&\n typeof icon === 'object' &&\n 'elem' in icon &&\n 'attrs' in icon &&\n 'content' in icon &&\n icon.elem === 'svg'\n );\n}\n\n/**\n * Transforms a React icon component to CarbonIcon format.\n * Returns the icon unchanged if it's already a CarbonIcon (no-op).\n * Caches results to avoid repeated transformations.\n */\nexport function transformReactIconToCarbonIcon(\n icon: CarbonIcon | React.ComponentType<any>,\n size = 16\n): CarbonIcon {\n // No-op: If already a CarbonIcon, return unchanged\n if (isCarbonIcon(icon)) {\n return icon;\n }\n\n const ReactIcon = icon as React.ComponentType<any>;\n\n // Get or create size map for this component\n let sizeMap = iconCache.get(ReactIcon);\n if (!sizeMap) {\n sizeMap = new Map<number, CarbonIcon>();\n iconCache.set(ReactIcon, sizeMap);\n }\n\n // Return cached result if available for this size\n const cached = sizeMap.get(size);\n if (cached) {\n return cached;\n }\n\n try {\n // Call the React component to get the React element\n const element = React.createElement(ReactIcon, { size });\n\n // Extract CarbonIcon descriptor from React element\n const descriptor = extractCarbonIconFromReactElement(element, size);\n\n // Validate descriptor\n if (!isValidCarbonIcon(descriptor)) {\n throw new Error('Generated descriptor is invalid');\n }\n\n // Cache and return\n sizeMap.set(size, descriptor);\n return descriptor;\n } catch (error) {\n const iconName = ReactIcon.displayName || ReactIcon.name || 'Unknown';\n throw new Error(\n `Failed to transform React icon \"${iconName}\": ${error instanceof Error ? error.message : String(error)}`\n );\n }\n}\n\n/**\n * Extracts CarbonIcon descriptor from a React element tree\n */\nfunction extractCarbonIconFromReactElement(\n element: React.ReactElement,\n size: number\n): CarbonIcon {\n // The element should be an SVG or Icon component\n // Navigate through forwardRef and other wrappers if needed\n let currentElement = element;\n\n // Handle forwardRef wrapper\n if (\n typeof currentElement.type === 'object' &&\n 'render' in currentElement.type\n ) {\n // This is a forwardRef, call the render function\n const renderFn = (currentElement.type as any).render;\n currentElement = renderFn(currentElement.props, null);\n }\n\n // Now we should have the actual Icon element\n const props = currentElement.props as any;\n\n if (!props) {\n throw new Error('Unable to extract props from React element');\n }\n\n // Extract SVG attributes from props\n const attrs: Record<string, string | number> = {\n xmlns: props.xmlns || 'http://www.w3.org/2000/svg',\n viewBox: props.viewBox || '0 0 32 32',\n fill: props.fill || 'currentColor',\n width: size,\n height: size,\n };\n\n // Extract children (paths, circles, etc.)\n const content: any[] = [];\n const children = React.Children.toArray(props.children);\n\n children.forEach((child) => {\n if (React.isValidElement(child)) {\n const childElement = child as React.ReactElement;\n const contentItem: any = {\n elem:\n typeof childElement.type === 'string' ? childElement.type : 'path',\n attrs: {},\n };\n\n // Copy all props as attributes\n if (childElement.props) {\n Object.entries(childElement.props).forEach(([key, value]) => {\n // Skip children and other React-specific props\n if (key !== 'children' && value !== undefined && value !== null) {\n contentItem.attrs[key] = value;\n }\n });\n }\n\n content.push(contentItem);\n }\n });\n\n return {\n elem: 'svg',\n attrs,\n content,\n name: extractIconName(props),\n size,\n };\n}\n\n/**\n * Validates that a descriptor has all required CarbonIcon fields\n */\nfunction isValidCarbonIcon(descriptor: any): descriptor is CarbonIcon {\n return (\n descriptor &&\n descriptor.elem === 'svg' &&\n descriptor.attrs &&\n typeof descriptor.attrs === 'object' &&\n Array.isArray(descriptor.content) &&\n descriptor.content.length > 0 &&\n typeof descriptor.name === 'string' &&\n typeof descriptor.size === 'number'\n );\n}\n\n/**\n * Attempts to extract icon name from props\n */\nfunction extractIconName(props: any): string {\n // Try various properties that might contain the icon name\n return props['data-icon-name'] || props['aria-label'] || props.name || 'icon';\n}\n"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;;;;;;;;;;;;;;;AAuBG;AAKH;AACA,MAAM,SAAS,GAAG,IAAI,OAAO,EAG1B;AAEH;;;AAGG;AACG,SAAU,YAAY,CAAC,IAAS,EAAA;IACpC,OAAO,OAAO,CACZ,IAAI;QACJ,OAAO,IAAI,KAAK,QAAQ;AACxB,QAAA,MAAM,IAAI,IAAI;AACd,QAAA,OAAO,IAAI,IAAI;AACf,QAAA,SAAS,IAAI,IAAI;AACjB,QAAA,IAAI,CAAC,IAAI,KAAK,KAAK,CACpB;AACH;AAEA;;;;AAIG;SACa,8BAA8B,CAC5C,IAA2C,EAC3C,IAAI,GAAG,EAAE,EAAA;;AAGT,IAAA,IAAI,YAAY,CAAC,IAAI,CAAC,EAAE;AACtB,QAAA,OAAO,IAAI;IACb;IAEA,MAAM,SAAS,GAAG,IAAgC;;IAGlD,IAAI,OAAO,GAAG,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC;IACtC,IAAI,CAAC,OAAO,EAAE;AACZ,QAAA,OAAO,GAAG,IAAI,GAAG,EAAsB;AACvC,QAAA,SAAS,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC;IACnC;;IAGA,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;IAChC,IAAI,MAAM,EAAE;AACV,QAAA,OAAO,MAAM;IACf;AAEA,IAAA,IAAI;;AAEF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IAAI,KAAK,KAAK;AACzB,QAAA,UAAU,CAAC,KAAK;AAChB,QAAA,OAAO,UAAU,CAAC,KAAK,KAAK,QAAQ;AACpC,QAAA,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC;AACjC,QAAA,UAAU,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC;AAC7B,QAAA,OAAO,UAAU,CAAC,IAAI,KAAK,QAAQ;AACnC,QAAA,OAAO,UAAU,CAAC,IAAI,KAAK,QAAQ;AAEvC;AAEA;;AAEG;AACH,SAAS,eAAe,CAAC,KAAU,EAAA;;AAEjC,IAAA,OAAO,KAAK,CAAC,gBAAgB,CAAC,IAAI,KAAK,CAAC,YAAY,CAAC,IAAI,KAAK,CAAC,IAAI,IAAI,MAAM;AAC/E;;"}
1
+ {"version":3,"file":"iconTransform.js","sources":["../../../src/globals/utils/iconTransform.tsx"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 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 * @license\n */\n\n/**\n * Icon Transformation Utility\n *\n * This module provides utilities to transform React icon components from @carbon/icons-react\n * into the CarbonIcon descriptor format used by @carbon/icons. This enables React developers\n * to use their familiar React icon components while maintaining compatibility with web components\n * that expect the plain JavaScript CarbonIcon format.\n *\n * Key features:\n * - Automatic transformation of React icon components to CarbonIcon descriptors\n * - No-op pass-through for CarbonIcon objects (already in correct format)\n * - Global caching to prevent redundant transformations\n * - Type guards for runtime icon format detection\n * - Support for forwardRef and memo-wrapped components\n *\n * Usage:\n * ```tsx\n * import { Add } from '@carbon/icons-react';\n * import { transformReactIconToCarbonIcon } from './iconTransform';\n *\n * const carbonIcon = transformReactIconToCarbonIcon(Add);\n * // carbonIcon is now in CarbonIcon format, ready for web components\n * ```\n */\n\nimport React, { FunctionComponent } from 'react';\nimport {\n CarbonIcon,\n CarbonIconDescriptor,\n} from '@carbon/web-components/es/globals/internal/icon-loader-utils';\n\ntype CarbonIconProps = React.SVGProps<SVGSVGElement> & {\n slot?: string;\n [key: string]: unknown;\n};\n\n// Global cache for transformed icons using WeakMap to key by component reference\nconst iconCache = new WeakMap<\n React.ComponentType<any>,\n Map<number, CarbonIcon>\n>();\n\n/**\n * Type guard to detect if icon is already a CarbonIcon descriptor.\n * If true, the icon should be passed through unchanged (no-op).\n */\nexport function isCarbonIcon(icon: any): icon is CarbonIcon {\n return Boolean(\n icon &&\n typeof icon === 'object' &&\n 'elem' in icon &&\n 'attrs' in icon &&\n 'content' in icon &&\n icon.elem === 'svg'\n );\n}\n\n/**\n * Transforms a React icon component to CarbonIcon format.\n * Returns the icon unchanged if it's already a CarbonIcon (no-op).\n * Caches results to avoid repeated transformations.\n */\nexport function transformReactIconToCarbonIcon(\n icon: CarbonIcon | React.ComponentType<any>,\n size = 16\n): CarbonIcon {\n // No-op: If already a CarbonIcon, return unchanged\n if (isCarbonIcon(icon)) {\n return icon;\n }\n\n const ReactIcon = icon as React.ComponentType<any>;\n\n // Get or create size map for this component\n let sizeMap = iconCache.get(ReactIcon);\n if (!sizeMap) {\n sizeMap = new Map<number, CarbonIcon>();\n iconCache.set(ReactIcon, sizeMap);\n }\n\n // Return cached result if available for this size\n const cached = sizeMap.get(size);\n if (cached) {\n return cached;\n }\n\n try {\n // Call the React component to get the React element\n const element = React.createElement(ReactIcon, { size });\n\n // Extract CarbonIcon descriptor from React element\n const descriptor = extractCarbonIconFromReactElement(element, size);\n\n // Validate descriptor\n if (!isValidCarbonIcon(descriptor)) {\n throw new Error('Generated descriptor is invalid');\n }\n\n // Cache and return\n sizeMap.set(size, descriptor);\n return descriptor;\n } catch (error) {\n const iconName = ReactIcon.displayName || ReactIcon.name || 'Unknown';\n throw new Error(\n `Failed to transform React icon \"${iconName}\": ${error instanceof Error ? error.message : String(error)}`\n );\n }\n}\n\n/**\n * Extracts CarbonIcon descriptor from a React element tree\n */\nfunction extractCarbonIconFromReactElement(\n element: React.ReactElement,\n size: number\n): CarbonIcon {\n // The element should be an SVG or Icon component\n // Navigate through forwardRef and other wrappers if needed\n let currentElement = element;\n\n // Handle forwardRef wrapper\n if (\n typeof currentElement.type === 'object' &&\n 'render' in currentElement.type\n ) {\n // This is a forwardRef, call the render function\n const renderFn = (currentElement.type as any).render;\n currentElement = renderFn(currentElement.props, null);\n }\n\n // Now we should have the actual Icon element\n const props = currentElement.props as any;\n\n if (!props) {\n throw new Error('Unable to extract props from React element');\n }\n\n // Extract SVG attributes from props\n const attrs: Record<string, string | number> = {\n xmlns: props.xmlns || 'http://www.w3.org/2000/svg',\n viewBox: props.viewBox || '0 0 32 32',\n fill: props.fill || 'currentColor',\n width: size,\n height: size,\n };\n\n // Extract children (paths, circles, etc.)\n const content: any[] = [];\n const children = React.Children.toArray(props.children);\n\n children.forEach((child) => {\n if (React.isValidElement(child)) {\n const childElement = child as React.ReactElement;\n const contentItem: any = {\n elem:\n typeof childElement.type === 'string' ? childElement.type : 'path',\n attrs: {},\n };\n\n // Copy all props as attributes\n if (childElement.props) {\n Object.entries(childElement.props).forEach(([key, value]) => {\n // Skip children and other React-specific props\n if (key !== 'children' && value !== undefined && value !== null) {\n contentItem.attrs[key] = value;\n }\n });\n }\n\n content.push(contentItem);\n }\n });\n\n return {\n elem: 'svg',\n attrs,\n content,\n name: extractIconName(props),\n size,\n };\n}\n\n/**\n * Validates that a descriptor has all required CarbonIcon fields\n */\nfunction isValidCarbonIcon(descriptor: any): descriptor is CarbonIcon {\n return (\n descriptor &&\n descriptor.elem === 'svg' &&\n descriptor.attrs &&\n typeof descriptor.attrs === 'object' &&\n Array.isArray(descriptor.content) &&\n descriptor.content.length > 0 &&\n typeof descriptor.name === 'string' &&\n typeof descriptor.size === 'number'\n );\n}\n\n/**\n * Attempts to extract icon name from props\n */\nfunction extractIconName(props: any): string {\n // Try various properties that might contain the icon name\n return props['data-icon-name'] || props['aria-label'] || props.name || 'icon';\n}\n\n/**\n * Creates a React component from a `CarbonIconDescriptor` (a raw `@carbon/icons` import).\n *\n * @example\n * import Launch16 from '@carbon/icons/es/launch/16';\n * const LaunchIcon = carbonIconToReact(Launch16);\n * <LaunchIcon aria-label=\"Launch\" className=\"icon\" />\n */\nexport function carbonIconToReact(\n icon: CarbonIconDescriptor\n): FunctionComponent<CarbonIconProps> {\n return function IconComponent(props: CarbonIconProps = {}) {\n return React.createElement(\n 'svg',\n {\n ...icon.attrs,\n width: icon.attrs.width || 16,\n height: icon.attrs.height || 16,\n fill: icon.attrs.fill || 'currentColor',\n focusable: 'false',\n style: { pointerEvents: 'none' },\n ...props,\n },\n icon.content.map((child, i) =>\n React.createElement(child.elem, { key: i, ...(child.attrs || {}) })\n )\n );\n };\n}\n"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;;;;;;;;;;;;;;;AAuBG;AAaH;AACA,MAAM,SAAS,GAAG,IAAI,OAAO,EAG1B;AAEH;;;AAGG;AACG,SAAU,YAAY,CAAC,IAAS,EAAA;IACpC,OAAO,OAAO,CACZ,IAAI;QACJ,OAAO,IAAI,KAAK,QAAQ;AACxB,QAAA,MAAM,IAAI,IAAI;AACd,QAAA,OAAO,IAAI,IAAI;AACf,QAAA,SAAS,IAAI,IAAI;AACjB,QAAA,IAAI,CAAC,IAAI,KAAK,KAAK,CACpB;AACH;AAEA;;;;AAIG;SACa,8BAA8B,CAC5C,IAA2C,EAC3C,IAAI,GAAG,EAAE,EAAA;;AAGT,IAAA,IAAI,YAAY,CAAC,IAAI,CAAC,EAAE;AACtB,QAAA,OAAO,IAAI;IACb;IAEA,MAAM,SAAS,GAAG,IAAgC;;IAGlD,IAAI,OAAO,GAAG,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC;IACtC,IAAI,CAAC,OAAO,EAAE;AACZ,QAAA,OAAO,GAAG,IAAI,GAAG,EAAsB;AACvC,QAAA,SAAS,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC;IACnC;;IAGA,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAA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AAE,CAAC,EAAE,IAAI,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC,CACpE,CACF;AACH,IAAA,CAAC;AACH;;"}
@@ -42,5 +42,10 @@ export interface UseChatAutocompleteResult {
42
42
  * `null` while no trigger is active.
43
43
  */
44
44
  autocompleteContent: ReactNode;
45
+ /**
46
+ * `true` while the user has navigated into the autocomplete list with arrow
47
+ * keys. Use to disable the prompt send button while a list item is active.
48
+ */
49
+ isListNavigated: boolean;
45
50
  }
46
51
  export declare function useChatAutocomplete(options: UseChatAutocompleteOptions): UseChatAutocompleteResult;
@@ -17,6 +17,7 @@ function useChatAutocomplete(options) {
17
17
  trigger: null,
18
18
  items: [],
19
19
  });
20
+ const [isListNavigated, setIsListNavigated] = React.useState(false);
20
21
  // Keep the controller stable for the hook's lifetime — set in a layout
21
22
  // effect so it's wired before any event handler can fire.
22
23
  const controllerRef = React.useRef(null);
@@ -84,7 +85,13 @@ function useChatAutocomplete(options) {
84
85
  // Register / unregister the rendered list element with the controller so
85
86
  // arrow / Enter / Escape on the editor DOM get forwarded to it.
86
87
  // Also set the max-height CSS variable if provided.
88
+ const navigatedListenerRef = React.useRef(null);
87
89
  const setListElement = React.useCallback((el) => {
90
+ // Remove the previous navigation listener before swapping elements.
91
+ if (navigatedListenerRef.current) {
92
+ navigatedListenerRef.current.el.removeEventListener('cds-aichat-autocomplete-navigated', navigatedListenerRef.current.handler);
93
+ navigatedListenerRef.current = null;
94
+ }
88
95
  controllerRef.current?.setListElement(el);
89
96
  // Pass the editor DOM as anchorElement so outside-click detection on the
90
97
  // autocomplete element doesn't dismiss the list when the user clicks the
@@ -96,6 +103,24 @@ function useChatAutocomplete(options) {
96
103
  if (el && maxHeight) {
97
104
  el.style.setProperty('--cds-aichat-autocomplete-max-height', maxHeight);
98
105
  }
106
+ if (el) {
107
+ const handler = (e) => {
108
+ setIsListNavigated(e.detail
109
+ .navigated);
110
+ };
111
+ el.addEventListener('cds-aichat-autocomplete-navigated', handler);
112
+ navigatedListenerRef.current = { el, handler };
113
+ }
114
+ else {
115
+ setIsListNavigated(false);
116
+ // Fire a synthetic clear event on the prompt-line's shell ancestor so
117
+ // the send-control's internal guard (`_autocompleteListNavigated`) also
118
+ // resets. This covers cases where the list is removed from the DOM
119
+ // without the autocomplete element dispatching its own clear event
120
+ // (e.g. the user deletes the trigger character).
121
+ const shell = promptLineRef.current?.closest('cds-aichat-prompt-line-shell');
122
+ shell?.dispatchEvent(new CustomEvent('cds-aichat-autocomplete-navigated', { detail: { navigated: false }, bubbles: false, composed: false }));
123
+ }
99
124
  }, [maxHeight, promptLineRef]);
100
125
  // Prevent mousedown on the autocomplete container from stealing focus from
101
126
  // the editor.
@@ -133,7 +158,7 @@ function useChatAutocomplete(options) {
133
158
  attached,
134
159
  handleContainerMousedown,
135
160
  ]);
136
- return { onTriggerChange, autocompleteContent };
161
+ return { onTriggerChange, autocompleteContent, isListNavigated };
137
162
  }
138
163
  /** Mounts a host-provided HTMLElement into the React tree at `slot`. */
139
164
  function CustomElementHost({ slot, element, onMount, onMousedown, }) {
@@ -1 +1 @@
1
- {"version":3,"file":"useChatAutocomplete.js","sources":["../../../src/react/hooks/useChatAutocomplete.tsx"],"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 * React hook for the chat-input autocomplete overlay. Thin wrapper around\n * the framework-agnostic `AutocompleteController` co-located in\n * [../../components/prompt-line/src/autocomplete-controller.ts] (which also exports\n * the `<cds-aichat-autocomplete-controller>` element). The controller owns\n * trigger handling, async resolution, and selection routing; this hook\n * adapts those callbacks into React state and returns a JSX node to slot\n * into `<PromptLineShell>`.\n */\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport type { JSX, ReactNode, RefObject } from 'react';\n\nimport Autocomplete from '../autocomplete.js';\nimport type PromptLineElement from '../../components/prompt-line/src/prompt-line.js';\nimport {\n AutocompleteController,\n itemsToGroups,\n type AutocompleteControllerState,\n} from '../../components/prompt-line/src/autocomplete-controller.js';\nimport type {\n AutocompleteConfig,\n StartersConfig,\n SuggestionItem,\n TriggerChangeEventDetail,\n TriggerSuggestionConfig,\n} from '../../components/prompt-line/src/tiptap/types.js';\n\nexport interface UseChatAutocompleteOptions {\n mention?: TriggerSuggestionConfig;\n command?: TriggerSuggestionConfig;\n autocomplete?: AutocompleteConfig;\n starters?: StartersConfig;\n /** Ref to the slotted `<cds-aichat-prompt-line>`. */\n promptLineRef: RefObject<PromptLineElement | null>;\n /** When true, starter selection inserts the text but does not auto-send. */\n isSendDisabled?: boolean;\n /** Fired after a starter is selected and inserted (used to trigger send). */\n onStarterSelected?: (text: string) => void;\n /**\n * Fired when an autocomplete suggestion item is selected.\n * Called after the controller has already inserted the item.\n */\n onSelectItem?: (item: SuggestionItem) => void;\n /**\n * Fired when the send button inside an autocomplete suggestion item is clicked.\n */\n onSendItem?: (text: string) => void;\n /** Whether the autocomplete is attached to the input (affects corner rounding). */\n attached?: boolean;\n /** Maximum height for the autocomplete popover */\n maxHeight?: string;\n}\n\nexport interface UseChatAutocompleteResult {\n /** Attach to `<PromptLine onTriggerChange={...} />`. */\n onTriggerChange: (\n event: CustomEvent<TriggerChangeEventDetail | null>\n ) => void;\n /**\n * JSX to render with `slot=\"autocomplete-content\"` inside `<PromptLineShell>`.\n * `null` while no trigger is active.\n */\n autocompleteContent: ReactNode;\n}\n\nexport function useChatAutocomplete(\n options: UseChatAutocompleteOptions\n): UseChatAutocompleteResult {\n const {\n mention,\n command,\n autocomplete,\n starters,\n promptLineRef,\n isSendDisabled,\n onStarterSelected,\n onSelectItem,\n onSendItem,\n attached = true,\n maxHeight,\n } = options;\n\n const [state, setState] = React.useState<AutocompleteControllerState>({\n trigger: null,\n items: [],\n });\n\n // Keep the controller stable for the hook's lifetime — set in a layout\n // effect so it's wired before any event handler can fire.\n const controllerRef = React.useRef<AutocompleteController | null>(null);\n // Latest config / callback values; the controller stores its own copies\n // but reading them out of refs avoids re-instantiation churn.\n const onStarterRef = React.useRef(onStarterSelected);\n onStarterRef.current = onStarterSelected;\n const onSelectItemRef = React.useRef(onSelectItem);\n onSelectItemRef.current = onSelectItem;\n const onSendItemRef = React.useRef(onSendItem);\n onSendItemRef.current = onSendItem;\n\n if (!controllerRef.current) {\n controllerRef.current = new AutocompleteController({\n mention,\n command,\n autocomplete,\n starters,\n isSendDisabled,\n onStarterSelected: (text) => onStarterRef.current?.(text),\n onChange: setState,\n });\n }\n\n // Push prop changes into the controller without recreating it.\n React.useEffect(() => {\n controllerRef.current?.setConfigs({\n mention,\n command,\n autocomplete,\n starters,\n isSendDisabled,\n });\n }, [mention, command, autocomplete, starters, isSendDisabled]);\n\n // Keep the controller pointed at the live prompt-line element.\n React.useEffect(() => {\n controllerRef.current?.setPromptLine(promptLineRef.current);\n });\n\n React.useEffect(() => {\n return () => {\n controllerRef.current?.destroy();\n controllerRef.current = null;\n };\n }, []);\n\n const onTriggerChange = React.useCallback(\n (event: CustomEvent<TriggerChangeEventDetail | null>) => {\n // Pin the controller to the current prompt-line ref before handing\n // off the detail — the React caller's ref is authoritative.\n controllerRef.current?.setPromptLine(promptLineRef.current);\n controllerRef.current?.handleTriggerChange(event.detail ?? null);\n },\n [promptLineRef]\n );\n\n const handleSelect = React.useCallback((item: SuggestionItem) => {\n controllerRef.current?.select(item);\n onSelectItemRef.current?.(item);\n }, []);\n\n const isSendDisabledRef = React.useRef(isSendDisabled);\n isSendDisabledRef.current = isSendDisabled;\n\n const handleSend = React.useCallback((text: string) => {\n if (!text || isSendDisabledRef.current) {\n return;\n }\n controllerRef.current?.dismiss(true);\n onSendItemRef.current?.(text);\n }, []);\n\n const dismiss = React.useCallback(() => {\n controllerRef.current?.dismiss();\n }, []);\n\n // Register / unregister the rendered list element with the controller so\n // arrow / Enter / Escape on the editor DOM get forwarded to it.\n // Also set the max-height CSS variable if provided.\n const setListElement = React.useCallback(\n (el: HTMLElement | null) => {\n controllerRef.current?.setListElement(el);\n // Pass the editor DOM as anchorElement so outside-click detection on the\n // autocomplete element doesn't dismiss the list when the user clicks the\n // editor (the editor is not inside the autocomplete element).\n if (el && 'anchorElement' in el) {\n (el as HTMLElement & { anchorElement: Element | null }).anchorElement =\n promptLineRef.current?.getEditor?.()?.view.dom ?? null;\n }\n if (el && maxHeight) {\n el.style.setProperty('--cds-aichat-autocomplete-max-height', maxHeight);\n }\n },\n [maxHeight, promptLineRef]\n );\n\n // Prevent mousedown on the autocomplete container from stealing focus from\n // the editor.\n const handleContainerMousedown = React.useCallback(\n (e: Event | React.MouseEvent) => {\n e.preventDefault();\n },\n []\n );\n\n const autocompleteContent = React.useMemo<ReactNode>(() => {\n if (!state.trigger || state.items.length === 0) {\n return null;\n }\n const { items: flatItems, groups } = itemsToGroups(state.items);\n if (state.renderCustomList) {\n const result = state.renderCustomList({\n items: state.items,\n query: state.trigger.query,\n onDismiss: dismiss,\n onSelect: handleSelect,\n onSend: handleSend,\n });\n if (result == null) {\n return null;\n }\n if (result instanceof HTMLElement) {\n return (\n <CustomElementHost\n slot=\"autocomplete-content\"\n element={result}\n onMount={setListElement}\n onMousedown={handleContainerMousedown}\n />\n );\n }\n return (\n <CustomReactNodePortal\n slot=\"autocomplete-content\"\n node={result as ReactNode}\n onMount={setListElement}\n onMousedown={handleContainerMousedown}\n />\n );\n }\n return (\n <Autocomplete\n ref={setListElement}\n slot=\"autocomplete-content\"\n items={flatItems}\n groups={groups}\n attached={attached}\n disableDirectSend={state.disableDirectSend}\n onDismiss={dismiss}\n onSelect={(e: CustomEvent<{ item: SuggestionItem }>) =>\n handleSelect(e.detail.item)\n }\n onSend={(e: CustomEvent<{ text: string }>) =>\n handleSend(e.detail?.text)\n }\n />\n );\n }, [\n state,\n handleSelect,\n handleSend,\n dismiss,\n setListElement,\n attached,\n handleContainerMousedown,\n ]);\n\n return { onTriggerChange, autocompleteContent };\n}\n\ninterface CustomElementHostProps {\n slot: string;\n element: HTMLElement;\n /** Notify the parent which element is the key-forwarding target. */\n onMount?: (el: HTMLElement | null) => void;\n onMousedown?: (e: React.MouseEvent) => void;\n}\n\n/** Mounts a host-provided HTMLElement into the React tree at `slot`. */\nfunction CustomElementHost({\n slot,\n element,\n onMount,\n onMousedown,\n}: CustomElementHostProps): JSX.Element {\n const containerRef = React.useRef<HTMLDivElement | null>(null);\n React.useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return undefined;\n }\n container.appendChild(element);\n onMount?.(element);\n return () => {\n onMount?.(null);\n if (element.parentNode === container) {\n container.removeChild(element);\n }\n };\n }, [element, onMount]);\n return (\n <div\n ref={containerRef}\n role=\"presentation\"\n slot={slot}\n onMouseDown={onMousedown}\n />\n );\n}\n\ninterface CustomReactNodePortalProps {\n slot: string;\n node: ReactNode;\n onMount?: (el: HTMLElement | null) => void;\n onMousedown?: (e: MouseEvent) => void;\n}\n\nlet autocompletePortalCounter = 0;\n\n/**\n * Projects a consumer-supplied React node into the page's light DOM via a\n * two-level slot/host pair so external `<style>` tags reach it. The rendered\n * `<div>` is a slot-projected anchor in the shell's `autocomplete-content`\n * slot; a sibling `<div slot=\"…\">` is appended to the chatWrapper (the host\n * of the surrounding shadow root) and receives the React node via\n * `createPortal`. Without this hop the node would mount inside the chat's\n * shadow root, hidden from page CSS.\n */\nfunction CustomReactNodePortal({\n slot,\n node,\n onMount,\n onMousedown,\n}: CustomReactNodePortalProps): JSX.Element {\n const containerRef = React.useRef<HTMLDivElement | null>(null);\n const [hostElement, setHostElement] = React.useState<HTMLElement | null>(\n null\n );\n\n React.useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return undefined;\n }\n const rootNode = container.getRootNode();\n const chatWrapper =\n rootNode instanceof ShadowRoot ? (rootNode.host as HTMLElement) : null;\n if (!chatWrapper) {\n return undefined;\n }\n\n const slotName = `cds-aichat-autocomplete-${++autocompletePortalCounter}`;\n const slotEl = document.createElement('slot');\n slotEl.setAttribute('name', slotName);\n container.appendChild(slotEl);\n\n const hostEl = document.createElement('div');\n hostEl.setAttribute('slot', slotName);\n if (onMousedown) {\n hostEl.addEventListener('mousedown', onMousedown);\n }\n chatWrapper.appendChild(hostEl);\n\n setHostElement(hostEl);\n return () => {\n onMount?.(null);\n if (onMousedown) {\n hostEl.removeEventListener('mousedown', onMousedown);\n }\n slotEl.remove();\n hostEl.remove();\n setHostElement(null);\n };\n // Empty deps: the slot/host pair is owned by this mount cycle and should\n // not churn as `node` updates — React's portal reconciliation handles\n // those updates in place.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // After the portal content is committed into hostElement, hand the first\n // child element to the controller. This is typically a custom element (e.g.\n // <cds-aichat-autocomplete>) whose properties (anchorElement, keydown\n // forwarding) only work on the element itself — not on the plain <div>\n // wrapper that createPortal renders into. Custom elements are defined\n // synchronously at module load, so by the time useEffect fires (post-paint)\n // the element is fully upgraded and its properties are available.\n React.useEffect(() => {\n if (!hostElement) {\n return;\n }\n const child = hostElement.firstElementChild as HTMLElement | null;\n onMount?.(child ?? hostElement);\n }, [hostElement, onMount]);\n\n return (\n <div slot={slot} ref={containerRef}>\n {hostElement ? ReactDOM.createPortal(node, hostElement) : null}\n </div>\n );\n}\n"],"names":["_jsx","Autocomplete"],"mappings":";;;;;;;;;;;;;AA4EM,SAAU,mBAAmB,CACjC,OAAmC,EAAA;IAEnC,MAAM,EACJ,OAAO,EACP,OAAO,EACP,YAAY,EACZ,QAAQ,EACR,aAAa,EACb,cAAc,EACd,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,QAAQ,GAAG,IAAI,EACf,SAAS,GACV,GAAG,OAAO;IAEX,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,KAAK,CAAC,QAAQ,CAA8B;AACpE,QAAA,OAAO,EAAE,IAAI;AACb,QAAA,KAAK,EAAE,EAAE;AACV,KAAA,CAAC;;;IAIF,MAAM,aAAa,GAAG,KAAK,CAAC,MAAM,CAAgC,IAAI,CAAC;;;IAGvE,MAAM,YAAY,GAAG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AA,MAAM,CAAC,YAAY,CAAC,MAAM,EAAE,QAAQ,CAAC;QACrC,IAAI,WAAW,EAAE;AACf,YAAA,MAAM,CAAC,gBAAgB,CAAC,WAAW,EAAE,WAAW,CAAC;QACnD;AACA,QAAA,WAAW,CAAC,WAAW,CAAC,MAAM,CAAC;QAE/B,cAAc,CAAC,MAAM,CAAC;AACtB,QAAA,OAAO,MAAK;AACV,YAAA,OAAO,GAAG,IAAI,CAAC;YACf,IAAI,WAAW,EAAE;AACf,gBAAA,MAAM,CAAC,mBAAmB,CAAC,WAAW,EAAE,WAAW,CAAC;YACtD;YACA,MAAM,CAAC,MAAM,EAAE;YACf,MAAM,CAAC,MAAM,EAAE;YACf,cAAc,CAAC,IAAI,CAAC;AACtB,QAAA,CAAC;;;;;IAKH,CAAC,EAAE,EAAE,CAAC;;;;;;;;AASN,IAAA,KAAK,CAAC,SAAS,CAAC,MAAK;QACnB,IAAI,CAAC,WAAW,EAAE;YAChB;QACF;AACA,QAAA,MAAM,KAAK,GAAG,WAAW,CAAC,iBAAuC;AACjE,QAAA,OAAO,GAAG,KAAK,IAAI,WAAW,CAAC;AACjC,IAAA,CAAC,EAAE,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;AAE1B,IAAA,QACEA,GAAA,CAAA,KAAA,EAAA,EAAK,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,YAAY,EAAA,QAAA,EAC/B,WAAW,GAAG,QAAQ,CAAC,YAAY,CAAC,IAAI,EAAE,WAAW,CAAC,GAAG,IAAI,EAAA,CAC1D;AAEV;;"}
1
+ {"version":3,"file":"useChatAutocomplete.js","sources":["../../../src/react/hooks/useChatAutocomplete.tsx"],"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 * React hook for the chat-input autocomplete overlay. Thin wrapper around\n * the framework-agnostic `AutocompleteController` in\n * [../../components/prompt-line/src/autocomplete-controller.ts]. That module\n * holds no Lit and registers no custom element, so reaching the controller\n * costs this hook neither. It still loads `<cds-aichat-autocomplete>` — it\n * renders that list itself — but never\n * `<cds-aichat-autocomplete-controller>`, the other surface on the same\n * class. The controller owns\n * trigger handling, async resolution, and selection routing; this hook\n * adapts those callbacks into React state and returns a JSX node to slot\n * into `<PromptLineShell>`.\n */\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport type { JSX, ReactNode, RefObject } from 'react';\n\nimport Autocomplete from '../autocomplete.js';\nimport type PromptLineElement from '../../components/prompt-line/src/prompt-line.js';\nimport {\n AutocompleteController,\n itemsToGroups,\n type AutocompleteControllerState,\n} from '../../components/prompt-line/src/autocomplete-controller.js';\nimport type { AutocompleteNavigatedEventDetail } from '../../components/prompt-line/autocomplete/src/autocomplete.js';\nimport type {\n AutocompleteConfig,\n StartersConfig,\n SuggestionItem,\n TriggerChangeEventDetail,\n TriggerSuggestionConfig,\n} from '../../components/prompt-line/src/tiptap/types.js';\n\nexport interface UseChatAutocompleteOptions {\n mention?: TriggerSuggestionConfig;\n command?: TriggerSuggestionConfig;\n autocomplete?: AutocompleteConfig;\n starters?: StartersConfig;\n /** Ref to the slotted `<cds-aichat-prompt-line>`. */\n promptLineRef: RefObject<PromptLineElement | null>;\n /** When true, starter selection inserts the text but does not auto-send. */\n isSendDisabled?: boolean;\n /** Fired after a starter is selected and inserted (used to trigger send). */\n onStarterSelected?: (text: string) => void;\n /**\n * Fired when an autocomplete suggestion item is selected.\n * Called after the controller has already inserted the item.\n */\n onSelectItem?: (item: SuggestionItem) => void;\n /**\n * Fired when the send button inside an autocomplete suggestion item is clicked.\n */\n onSendItem?: (text: string) => void;\n /** Whether the autocomplete is attached to the input (affects corner rounding). */\n attached?: boolean;\n /** Maximum height for the autocomplete popover */\n maxHeight?: string;\n}\n\nexport interface UseChatAutocompleteResult {\n /** Attach to `<PromptLine onTriggerChange={...} />`. */\n onTriggerChange: (\n event: CustomEvent<TriggerChangeEventDetail | null>\n ) => void;\n /**\n * JSX to render with `slot=\"autocomplete-content\"` inside `<PromptLineShell>`.\n * `null` while no trigger is active.\n */\n autocompleteContent: ReactNode;\n /**\n * `true` while the user has navigated into the autocomplete list with arrow\n * keys. Use to disable the prompt send button while a list item is active.\n */\n isListNavigated: boolean;\n}\n\nexport function useChatAutocomplete(\n options: UseChatAutocompleteOptions\n): UseChatAutocompleteResult {\n const {\n mention,\n command,\n autocomplete,\n starters,\n promptLineRef,\n isSendDisabled,\n onStarterSelected,\n onSelectItem,\n onSendItem,\n attached = true,\n maxHeight,\n } = options;\n\n const [state, setState] = React.useState<AutocompleteControllerState>({\n trigger: null,\n items: [],\n });\n\n const [isListNavigated, setIsListNavigated] = React.useState(false);\n\n // Keep the controller stable for the hook's lifetime — set in a layout\n // effect so it's wired before any event handler can fire.\n const controllerRef = React.useRef<AutocompleteController | null>(null);\n // Latest config / callback values; the controller stores its own copies\n // but reading them out of refs avoids re-instantiation churn.\n const onStarterRef = React.useRef(onStarterSelected);\n onStarterRef.current = onStarterSelected;\n const onSelectItemRef = React.useRef(onSelectItem);\n onSelectItemRef.current = onSelectItem;\n const onSendItemRef = React.useRef(onSendItem);\n onSendItemRef.current = onSendItem;\n\n if (!controllerRef.current) {\n controllerRef.current = new AutocompleteController({\n mention,\n command,\n autocomplete,\n starters,\n isSendDisabled,\n onStarterSelected: (text) => onStarterRef.current?.(text),\n onChange: setState,\n });\n }\n\n // Push prop changes into the controller without recreating it.\n React.useEffect(() => {\n controllerRef.current?.setConfigs({\n mention,\n command,\n autocomplete,\n starters,\n isSendDisabled,\n });\n }, [mention, command, autocomplete, starters, isSendDisabled]);\n\n // Keep the controller pointed at the live prompt-line element.\n React.useEffect(() => {\n controllerRef.current?.setPromptLine(promptLineRef.current);\n });\n\n React.useEffect(() => {\n return () => {\n controllerRef.current?.destroy();\n controllerRef.current = null;\n };\n }, []);\n\n const onTriggerChange = React.useCallback(\n (event: CustomEvent<TriggerChangeEventDetail | null>) => {\n // Pin the controller to the current prompt-line ref before handing\n // off the detail — the React caller's ref is authoritative.\n controllerRef.current?.setPromptLine(promptLineRef.current);\n controllerRef.current?.handleTriggerChange(event.detail ?? null);\n },\n [promptLineRef]\n );\n\n const handleSelect = React.useCallback((item: SuggestionItem) => {\n controllerRef.current?.select(item);\n onSelectItemRef.current?.(item);\n }, []);\n\n const isSendDisabledRef = React.useRef(isSendDisabled);\n isSendDisabledRef.current = isSendDisabled;\n\n const handleSend = React.useCallback((text: string) => {\n if (!text || isSendDisabledRef.current) {\n return;\n }\n controllerRef.current?.dismiss(true);\n onSendItemRef.current?.(text);\n }, []);\n\n const dismiss = React.useCallback(() => {\n controllerRef.current?.dismiss();\n }, []);\n\n // Register / unregister the rendered list element with the controller so\n // arrow / Enter / Escape on the editor DOM get forwarded to it.\n // Also set the max-height CSS variable if provided.\n const navigatedListenerRef = React.useRef<{\n el: HTMLElement;\n handler: (e: Event) => void;\n } | null>(null);\n\n const setListElement = React.useCallback(\n (el: HTMLElement | null) => {\n // Remove the previous navigation listener before swapping elements.\n if (navigatedListenerRef.current) {\n navigatedListenerRef.current.el.removeEventListener(\n 'cds-aichat-autocomplete-navigated',\n navigatedListenerRef.current.handler\n );\n navigatedListenerRef.current = null;\n }\n\n controllerRef.current?.setListElement(el);\n // Pass the editor DOM as anchorElement so outside-click detection on the\n // autocomplete element doesn't dismiss the list when the user clicks the\n // editor (the editor is not inside the autocomplete element).\n if (el && 'anchorElement' in el) {\n (el as HTMLElement & { anchorElement: Element | null }).anchorElement =\n promptLineRef.current?.getEditor?.()?.view.dom ?? null;\n }\n if (el && maxHeight) {\n el.style.setProperty('--cds-aichat-autocomplete-max-height', maxHeight);\n }\n if (el) {\n const handler = (e: Event) => {\n setIsListNavigated(\n (e as CustomEvent<AutocompleteNavigatedEventDetail>).detail\n .navigated\n );\n };\n el.addEventListener('cds-aichat-autocomplete-navigated', handler);\n navigatedListenerRef.current = { el, handler };\n } else {\n setIsListNavigated(false);\n // Fire a synthetic clear event on the prompt-line's shell ancestor so\n // the send-control's internal guard (`_autocompleteListNavigated`) also\n // resets. This covers cases where the list is removed from the DOM\n // without the autocomplete element dispatching its own clear event\n // (e.g. the user deletes the trigger character).\n const shell = promptLineRef.current?.closest(\n 'cds-aichat-prompt-line-shell'\n );\n shell?.dispatchEvent(\n new CustomEvent<AutocompleteNavigatedEventDetail>(\n 'cds-aichat-autocomplete-navigated',\n { detail: { navigated: false }, bubbles: false, composed: false }\n )\n );\n }\n },\n [maxHeight, promptLineRef]\n );\n\n // Prevent mousedown on the autocomplete container from stealing focus from\n // the editor.\n const handleContainerMousedown = React.useCallback(\n (e: Event | React.MouseEvent) => {\n e.preventDefault();\n },\n []\n );\n\n const autocompleteContent = React.useMemo<ReactNode>(() => {\n if (!state.trigger || state.items.length === 0) {\n return null;\n }\n const { items: flatItems, groups } = itemsToGroups(state.items);\n if (state.renderCustomList) {\n const result = state.renderCustomList({\n items: state.items,\n query: state.trigger.query,\n onDismiss: dismiss,\n onSelect: handleSelect,\n onSend: handleSend,\n });\n if (result == null) {\n return null;\n }\n if (result instanceof HTMLElement) {\n return (\n <CustomElementHost\n slot=\"autocomplete-content\"\n element={result}\n onMount={setListElement}\n onMousedown={handleContainerMousedown}\n />\n );\n }\n return (\n <CustomReactNodePortal\n slot=\"autocomplete-content\"\n node={result as ReactNode}\n onMount={setListElement}\n onMousedown={handleContainerMousedown}\n />\n );\n }\n return (\n <Autocomplete\n ref={setListElement}\n slot=\"autocomplete-content\"\n items={flatItems}\n groups={groups}\n attached={attached}\n disableDirectSend={state.disableDirectSend}\n onDismiss={dismiss}\n onSelect={(e: CustomEvent<{ item: SuggestionItem }>) =>\n handleSelect(e.detail.item)\n }\n onSend={(e: CustomEvent<{ text: string }>) =>\n handleSend(e.detail?.text)\n }\n />\n );\n }, [\n state,\n handleSelect,\n handleSend,\n dismiss,\n setListElement,\n attached,\n handleContainerMousedown,\n ]);\n\n return { onTriggerChange, autocompleteContent, isListNavigated };\n}\n\ninterface CustomElementHostProps {\n slot: string;\n element: HTMLElement;\n /** Notify the parent which element is the key-forwarding target. */\n onMount?: (el: HTMLElement | null) => void;\n onMousedown?: (e: React.MouseEvent) => void;\n}\n\n/** Mounts a host-provided HTMLElement into the React tree at `slot`. */\nfunction CustomElementHost({\n slot,\n element,\n onMount,\n onMousedown,\n}: CustomElementHostProps): JSX.Element {\n const containerRef = React.useRef<HTMLDivElement | null>(null);\n React.useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return undefined;\n }\n container.appendChild(element);\n onMount?.(element);\n return () => {\n onMount?.(null);\n if (element.parentNode === container) {\n container.removeChild(element);\n }\n };\n }, [element, onMount]);\n return (\n <div\n ref={containerRef}\n role=\"presentation\"\n slot={slot}\n onMouseDown={onMousedown}\n />\n );\n}\n\ninterface CustomReactNodePortalProps {\n slot: string;\n node: ReactNode;\n onMount?: (el: HTMLElement | null) => void;\n onMousedown?: (e: MouseEvent) => void;\n}\n\nlet autocompletePortalCounter = 0;\n\n/**\n * Projects a consumer-supplied React node into the page's light DOM via a\n * two-level slot/host pair so external `<style>` tags reach it. The rendered\n * `<div>` is a slot-projected anchor in the shell's `autocomplete-content`\n * slot; a sibling `<div slot=\"…\">` is appended to the chatWrapper (the host\n * of the surrounding shadow root) and receives the React node via\n * `createPortal`. Without this hop the node would mount inside the chat's\n * shadow root, hidden from page CSS.\n */\nfunction CustomReactNodePortal({\n slot,\n node,\n onMount,\n onMousedown,\n}: CustomReactNodePortalProps): JSX.Element {\n const containerRef = React.useRef<HTMLDivElement | null>(null);\n const [hostElement, setHostElement] = React.useState<HTMLElement | null>(\n null\n );\n\n React.useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return undefined;\n }\n const rootNode = container.getRootNode();\n const chatWrapper =\n rootNode instanceof ShadowRoot ? (rootNode.host as HTMLElement) : null;\n if (!chatWrapper) {\n return undefined;\n }\n\n const slotName = `cds-aichat-autocomplete-${++autocompletePortalCounter}`;\n const slotEl = document.createElement('slot');\n slotEl.setAttribute('name', slotName);\n container.appendChild(slotEl);\n\n const hostEl = document.createElement('div');\n hostEl.setAttribute('slot', slotName);\n if (onMousedown) {\n hostEl.addEventListener('mousedown', onMousedown);\n }\n chatWrapper.appendChild(hostEl);\n\n setHostElement(hostEl);\n return () => {\n onMount?.(null);\n if (onMousedown) {\n hostEl.removeEventListener('mousedown', onMousedown);\n }\n slotEl.remove();\n hostEl.remove();\n setHostElement(null);\n };\n // Empty deps: the slot/host pair is owned by this mount cycle and should\n // not churn as `node` updates — React's portal reconciliation handles\n // those updates in place.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // After the portal content is committed into hostElement, hand the first\n // child element to the controller. This is typically a custom element (e.g.\n // <cds-aichat-autocomplete>) whose properties (anchorElement, keydown\n // forwarding) only work on the element itself — not on the plain <div>\n // wrapper that createPortal renders into. Custom elements are defined\n // synchronously at module load, so by the time useEffect fires (post-paint)\n // the element is fully upgraded and its properties are available.\n React.useEffect(() => {\n if (!hostElement) {\n return;\n }\n const child = hostElement.firstElementChild as HTMLElement | null;\n onMount?.(child ?? hostElement);\n }, [hostElement, onMount]);\n\n return (\n <div slot={slot} ref={containerRef}>\n {hostElement ? ReactDOM.createPortal(node, hostElement) : null}\n </div>\n );\n}\n"],"names":["_jsx","Autocomplete"],"mappings":";;;;;;;;;;;;;AAsFM,SAAU,mBAAmB,CACjC,OAAmC,EAAA;IAEnC,MAAM,EACJ,OAAO,EACP,OAAO,EACP,YAAY,EACZ,QAAQ,EACR,aAAa,EACb,cAAc,EACd,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,QAAQ,GAAG,IAAI,EACf,SAAS,GACV,GAAG,OAAO;IAEX,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,KAAK,CAAC,QAAQ,CAA8B;AACpE,QAAA,OAAO,EAAE,IAAI;AACb,QAAA,KAAK,EAAE,EAAE;AACV,KAAA,CAAC;AAEF,IAAA,MAAM,CAAC,eAAe,EAAE,kBAAkB,CAAC,GAAG,KA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AO,MAAK;AACV,YAAA,OAAO,GAAG,IAAI,CAAC;YACf,IAAI,WAAW,EAAE;AACf,gBAAA,MAAM,CAAC,mBAAmB,CAAC,WAAW,EAAE,WAAW,CAAC;YACtD;YACA,MAAM,CAAC,MAAM,EAAE;YACf,MAAM,CAAC,MAAM,EAAE;YACf,cAAc,CAAC,IAAI,CAAC;AACtB,QAAA,CAAC;;;;;IAKH,CAAC,EAAE,EAAE,CAAC;;;;;;;;AASN,IAAA,KAAK,CAAC,SAAS,CAAC,MAAK;QACnB,IAAI,CAAC,WAAW,EAAE;YAChB;QACF;AACA,QAAA,MAAM,KAAK,GAAG,WAAW,CAAC,iBAAuC;AACjE,QAAA,OAAO,GAAG,KAAK,IAAI,WAAW,CAAC;AACjC,IAAA,CAAC,EAAE,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;AAE1B,IAAA,QACEA,GAAA,CAAA,KAAA,EAAA,EAAK,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,YAAY,EAAA,QAAA,EAC/B,WAAW,GAAG,QAAQ,CAAC,YAAY,CAAC,IAAI,EAAE,WAAW,CAAC,GAAG,IAAI,EAAA,CAC1D;AAEV;;"}
@@ -127,7 +127,6 @@ const Markdown = forwardRef(function Markdown({ customRenderers, ...rest }, forw
127
127
  // flickering out as later content arrives). Reading `isConnected` a
128
128
  // microtask later lets Lit's adoption land first, so we only drop
129
129
  // genuinely-removed hosts.
130
- // eslint-disable-next-line react-hooks/exhaustive-deps
131
130
  useEffect(() => {
132
131
  let cancelled = false;
133
132
  queueMicrotask(() => {
@@ -1 +1 @@
1
- {"version":3,"file":"markdown.js","sources":["../../src/react/markdown.tsx"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 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 * @license\n */\n\nimport { createComponent } from '@lit/react';\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ComponentPropsWithoutRef,\n type ReactNode,\n} from 'react';\nimport { createPortal, flushSync } from 'react-dom';\n\n// Export the actual class for the component that will *directly* be wrapped with React.\nimport CDSAIChatMarkdown from '../components/markdown/src/markdown.js';\nimport type {\n MarkdownCustomRenderers,\n MarkdownRendererCodeBlockArgs,\n MarkdownRendererTableArgs,\n} from '../components/markdown/src/markdown-renderer-types.js';\nimport { withWebComponentBridge } from './utils/withWebComponentBridge';\n\nconst LitMarkdown = createComponent({\n tagName: 'cds-aichat-markdown',\n elementClass: CDSAIChatMarkdown,\n react: React,\n});\n\nconst ForwardedBaseMarkdown = React.forwardRef<\n CDSAIChatMarkdown,\n React.ComponentProps<typeof LitMarkdown> & { markdown?: string }\n>(({ children, markdown, ...rest }, forwardedRef) => {\n const isTextChildren =\n typeof children === 'string' || typeof children === 'number';\n return React.createElement(\n LitMarkdown,\n {\n ...rest,\n ref: forwardedRef,\n markdown: markdown ?? (isTextChildren ? String(children) : undefined),\n },\n // Text children become the `markdown` prop; element children pass through\n // as light-DOM slot children (used by the React wrapper to mount plugin\n // slot forwarders inside the underlying `<cds-aichat-markdown>`).\n isTextChildren ? null : children\n );\n});\n\nForwardedBaseMarkdown.displayName = 'BaseMarkdown';\n\n/**\n * Thin `@lit/react` bridge around `<cds-aichat-markdown>`. Handles text vs.\n * element children and the web-component prop bridge, but performs no\n * React-specific `customRenderers` portaling — that is layered on by the\n * `Markdown` wrapper below.\n */\nconst BaseMarkdown = withWebComponentBridge(ForwardedBaseMarkdown);\n\n/**\n * React-flavored variant of {@link MarkdownCustomRenderers}. The element\n * replacements (`table`, `codeBlock`) may additionally return a `ReactNode`\n * (portaled into a light-DOM slot host) on top of the framework-neutral\n * `HTMLElement | null`. The attribute transforms (`link`, `image`) and the\n * `checklist` behavior hook return plain data, so they keep the base\n * signatures unchanged.\n */\nexport interface MarkdownReactCustomRenderers {\n /**\n * Override the default `cds-aichat-table` rendering. Return a `ReactNode`\n * (rendered via portal into a light-DOM slot host) or an `HTMLElement`\n * (adopted into the slot host as-is); return `null` to fall back to the\n * default Carbon table renderer.\n */\n table?: (args: MarkdownRendererTableArgs) => ReactNode | HTMLElement | null;\n /**\n * Override the default `cds-aichat-code-snippet` rendering. Return a\n * `ReactNode` (rendered via portal into a light-DOM slot host) or an\n * `HTMLElement` (adopted into the slot host as-is); return `null` to fall\n * back to the default Carbon code snippet renderer.\n */\n codeBlock?: (\n args: MarkdownRendererCodeBlockArgs\n ) => ReactNode | HTMLElement | null;\n /** Transform how links render. See {@link MarkdownCustomRenderers.link}. */\n link?: MarkdownCustomRenderers['link'];\n /** Transform how images render. See {@link MarkdownCustomRenderers.image}. */\n image?: MarkdownCustomRenderers['image'];\n /** Make task-list checkboxes actionable. See {@link MarkdownCustomRenderers.checklist}. */\n checklist?: MarkdownCustomRenderers['checklist'];\n}\n\ntype BaseMarkdownProps = Omit<\n ComponentPropsWithoutRef<typeof BaseMarkdown>,\n 'customRenderers'\n>;\n\n/**\n * Props for the React `<Markdown>` wrapper around `<cds-aichat-markdown>`.\n */\nexport interface MarkdownProps extends BaseMarkdownProps {\n /**\n * Per-element render overrides. Each callback returns either a `ReactNode`\n * (rendered via portal into a light-DOM slot host) or an `HTMLElement`\n * (adopted into the slot host as-is). Return `null` to fall back to the\n * default Carbon rendering. Pass a stable reference (e.g. `useMemo`) — a\n * new object identity each render forces a full re-reconcile.\n */\n customRenderers?: MarkdownReactCustomRenderers;\n}\n\ntype PortalEntry = {\n slotName: string;\n host: HTMLDivElement;\n node: ReactNode;\n};\n\nfunction isElement(value: unknown): value is HTMLElement {\n return (\n typeof Element !== 'undefined' &&\n value instanceof Element &&\n 'tagName' in value\n );\n}\n\nconst Markdown = forwardRef<CDSAIChatMarkdown, MarkdownProps>(function Markdown(\n { customRenderers, ...rest },\n forwardedRef\n) {\n const hostsRef = useRef<Map<string, HTMLDivElement>>(new Map());\n const [portalEntries, setPortalEntries] = useState<PortalEntry[]>([]);\n\n const markdownRef = useRef<CDSAIChatMarkdown | null>(null);\n const setMarkdownRef = useCallback(\n (node: CDSAIChatMarkdown | null) => {\n markdownRef.current = node;\n if (typeof forwardedRef === 'function') {\n forwardedRef(node);\n } else if (forwardedRef && 'current' in forwardedRef) {\n (\n forwardedRef as React.MutableRefObject<CDSAIChatMarkdown | null>\n ).current = node;\n }\n },\n [forwardedRef]\n );\n\n const setPortalForSlot = useCallback(\n (slotName: string, host: HTMLDivElement, node: ReactNode) => {\n setPortalEntries((prev) => {\n const idx = prev.findIndex((e) => e.slotName === slotName);\n if (idx >= 0 && prev[idx].node === node && prev[idx].host === host) {\n return prev;\n }\n if (idx >= 0) {\n const next = prev.slice();\n next[idx] = { slotName, host, node };\n return next;\n }\n return [...prev, { slotName, host, node }];\n });\n },\n []\n );\n\n const bridgedRenderers = useMemo<MarkdownCustomRenderers | undefined>(() => {\n if (!customRenderers) {\n return undefined;\n }\n const bridge = <Args extends { slotName: string }>(\n callback: (args: Args) => ReactNode | HTMLElement | null\n ) => {\n return (args: Args): HTMLElement | null => {\n const rendered = callback(args);\n if (rendered == null) {\n return null;\n }\n if (isElement(rendered)) {\n return rendered;\n }\n // Mint or reuse a stable host for this slot, then flush a portal\n // update synchronously so the host is populated before the Lit\n // element adopts it (no empty-host flash).\n let host = hostsRef.current.get(args.slotName);\n if (!host) {\n host = document.createElement('div');\n hostsRef.current.set(args.slotName, host);\n }\n flushSync(() => {\n setPortalForSlot(args.slotName, host as HTMLDivElement, rendered);\n });\n return host;\n };\n };\n\n const out: MarkdownCustomRenderers = {};\n if (customRenderers.table) {\n out.table = bridge(customRenderers.table);\n }\n if (customRenderers.codeBlock) {\n out.codeBlock = bridge(customRenderers.codeBlock);\n }\n // Attribute transforms / behavior hook return plain data (not DOM), so\n // they skip the portal bridge and pass straight through.\n if (customRenderers.link) {\n out.link = customRenderers.link;\n }\n if (customRenderers.image) {\n out.image = customRenderers.image;\n }\n if (customRenderers.checklist) {\n out.checklist = customRenderers.checklist;\n }\n return out;\n }, [customRenderers, setPortalForSlot]);\n\n // After every commit, prune portals whose host Lit has removed (its slot\n // dropped out of the descriptor batch, leaving the host detached). The\n // connectivity check is deferred to a microtask on purpose: `bridge` mints a\n // host, `flushSync`s the portal into it while it is still detached, and only\n // *returns* it to Lit — which appends it synchronously afterwards. That\n // `flushSync` runs this effect once while the host is not yet adopted, so a\n // synchronous `isConnected` check would prune the entry we just added and\n // leave the slot permanently empty (e.g. a streaming table custom renderer\n // flickering out as later content arrives). Reading `isConnected` a\n // microtask later lets Lit's adoption land first, so we only drop\n // genuinely-removed hosts.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(() => {\n let cancelled = false;\n queueMicrotask(() => {\n if (cancelled) {\n return;\n }\n let pruned = false;\n const aliveHosts = new Map<string, HTMLDivElement>();\n for (const [slotName, host] of hostsRef.current) {\n if (host.isConnected) {\n aliveHosts.set(slotName, host);\n } else {\n pruned = true;\n }\n }\n if (pruned) {\n hostsRef.current = aliveHosts;\n }\n setPortalEntries((prev) => {\n const filtered = prev.filter((e) => e.host.isConnected);\n return filtered.length === prev.length ? prev : filtered;\n });\n });\n return () => {\n cancelled = true;\n };\n });\n\n return (\n <>\n <BaseMarkdown\n {...rest}\n ref={setMarkdownRef as React.Ref<HTMLElement>}\n customRenderers={bridgedRenderers as never}\n />\n {portalEntries.map((entry) => (\n <React.Fragment key={entry.slotName}>\n {createPortal(entry.node, entry.host)}\n </React.Fragment>\n ))}\n </>\n );\n});\n\nMarkdown.displayName = 'Markdown';\n\nexport default Markdown;\n"],"names":["_jsxs","_jsx"],"mappings":";;;;;;;;;;;;;;AA+BA,MAAM,WAAW,GAAG,eAAe,CAAC;AAClC,IAAA,OAAO,EAAE,qBAAqB;AAC9B,IAAA,YAAY,EAAE,iBAAiB;AAC/B,IAAA,KAAK,EAAE,KAAK;AACb,CAAA,CAAC;AAEF,MAAM,qBAAqB,GAAG,KAAK,CAAC,UAAU,CAG5C,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,EAAE,YAAY,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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 * @license\n */\n\nimport { createComponent } from '@lit/react';\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ComponentPropsWithoutRef,\n type ReactNode,\n} from 'react';\nimport { createPortal, flushSync } from 'react-dom';\n\n// Export the actual class for the component that will *directly* be wrapped with React.\nimport CDSAIChatMarkdown from '../components/markdown/src/markdown.js';\nimport type {\n MarkdownCustomRenderers,\n MarkdownRendererCodeBlockArgs,\n MarkdownRendererTableArgs,\n} from '../components/markdown/src/markdown-renderer-types.js';\nimport { withWebComponentBridge } from './utils/withWebComponentBridge';\n\nconst LitMarkdown = createComponent({\n tagName: 'cds-aichat-markdown',\n elementClass: CDSAIChatMarkdown,\n react: React,\n});\n\nconst ForwardedBaseMarkdown = React.forwardRef<\n CDSAIChatMarkdown,\n React.ComponentProps<typeof LitMarkdown> & { markdown?: string }\n>(({ children, markdown, ...rest }, forwardedRef) => {\n const isTextChildren =\n typeof children === 'string' || typeof children === 'number';\n return React.createElement(\n LitMarkdown,\n {\n ...rest,\n ref: forwardedRef,\n markdown: markdown ?? (isTextChildren ? String(children) : undefined),\n },\n // Text children become the `markdown` prop; element children pass through\n // as light-DOM slot children (used by the React wrapper to mount plugin\n // slot forwarders inside the underlying `<cds-aichat-markdown>`).\n isTextChildren ? null : children\n );\n});\n\nForwardedBaseMarkdown.displayName = 'BaseMarkdown';\n\n/**\n * Thin `@lit/react` bridge around `<cds-aichat-markdown>`. Handles text vs.\n * element children and the web-component prop bridge, but performs no\n * React-specific `customRenderers` portaling — that is layered on by the\n * `Markdown` wrapper below.\n */\nconst BaseMarkdown = withWebComponentBridge(ForwardedBaseMarkdown);\n\n/**\n * React-flavored variant of {@link MarkdownCustomRenderers}. The element\n * replacements (`table`, `codeBlock`) may additionally return a `ReactNode`\n * (portaled into a light-DOM slot host) on top of the framework-neutral\n * `HTMLElement | null`. The attribute transforms (`link`, `image`) and the\n * `checklist` behavior hook return plain data, so they keep the base\n * signatures unchanged.\n */\nexport interface MarkdownReactCustomRenderers {\n /**\n * Override the default `cds-aichat-table` rendering. Return a `ReactNode`\n * (rendered via portal into a light-DOM slot host) or an `HTMLElement`\n * (adopted into the slot host as-is); return `null` to fall back to the\n * default Carbon table renderer.\n */\n table?: (args: MarkdownRendererTableArgs) => ReactNode | HTMLElement | null;\n /**\n * Override the default `cds-aichat-code-snippet` rendering. Return a\n * `ReactNode` (rendered via portal into a light-DOM slot host) or an\n * `HTMLElement` (adopted into the slot host as-is); return `null` to fall\n * back to the default Carbon code snippet renderer.\n */\n codeBlock?: (\n args: MarkdownRendererCodeBlockArgs\n ) => ReactNode | HTMLElement | null;\n /** Transform how links render. See {@link MarkdownCustomRenderers.link}. */\n link?: MarkdownCustomRenderers['link'];\n /** Transform how images render. See {@link MarkdownCustomRenderers.image}. */\n image?: MarkdownCustomRenderers['image'];\n /** Make task-list checkboxes actionable. See {@link MarkdownCustomRenderers.checklist}. */\n checklist?: MarkdownCustomRenderers['checklist'];\n}\n\ntype BaseMarkdownProps = Omit<\n ComponentPropsWithoutRef<typeof BaseMarkdown>,\n 'customRenderers'\n>;\n\n/**\n * Props for the React `<Markdown>` wrapper around `<cds-aichat-markdown>`.\n */\nexport interface MarkdownProps extends BaseMarkdownProps {\n /**\n * Per-element render overrides. Each callback returns either a `ReactNode`\n * (rendered via portal into a light-DOM slot host) or an `HTMLElement`\n * (adopted into the slot host as-is). Return `null` to fall back to the\n * default Carbon rendering. Pass a stable reference (e.g. `useMemo`) — a\n * new object identity each render forces a full re-reconcile.\n */\n customRenderers?: MarkdownReactCustomRenderers;\n}\n\ntype PortalEntry = {\n slotName: string;\n host: HTMLDivElement;\n node: ReactNode;\n};\n\nfunction isElement(value: unknown): value is HTMLElement {\n return (\n typeof Element !== 'undefined' &&\n value instanceof Element &&\n 'tagName' in value\n );\n}\n\nconst Markdown = forwardRef<CDSAIChatMarkdown, MarkdownProps>(function Markdown(\n { customRenderers, ...rest },\n forwardedRef\n) {\n const hostsRef = useRef<Map<string, HTMLDivElement>>(new Map());\n const [portalEntries, setPortalEntries] = useState<PortalEntry[]>([]);\n\n const markdownRef = useRef<CDSAIChatMarkdown | null>(null);\n const setMarkdownRef = useCallback(\n (node: CDSAIChatMarkdown | null) => {\n markdownRef.current = node;\n if (typeof forwardedRef === 'function') {\n forwardedRef(node);\n } else if (forwardedRef && 'current' in forwardedRef) {\n (\n forwardedRef as React.MutableRefObject<CDSAIChatMarkdown | null>\n ).current = node;\n }\n },\n [forwardedRef]\n );\n\n const setPortalForSlot = useCallback(\n (slotName: string, host: HTMLDivElement, node: ReactNode) => {\n setPortalEntries((prev) => {\n const idx = prev.findIndex((e) => e.slotName === slotName);\n if (idx >= 0 && prev[idx].node === node && prev[idx].host === host) {\n return prev;\n }\n if (idx >= 0) {\n const next = prev.slice();\n next[idx] = { slotName, host, node };\n return next;\n }\n return [...prev, { slotName, host, node }];\n });\n },\n []\n );\n\n const bridgedRenderers = useMemo<MarkdownCustomRenderers | undefined>(() => {\n if (!customRenderers) {\n return undefined;\n }\n const bridge = <Args extends { slotName: string }>(\n callback: (args: Args) => ReactNode | HTMLElement | null\n ) => {\n return (args: Args): HTMLElement | null => {\n const rendered = callback(args);\n if (rendered == null) {\n return null;\n }\n if (isElement(rendered)) {\n return rendered;\n }\n // Mint or reuse a stable host for this slot, then flush a portal\n // update synchronously so the host is populated before the Lit\n // element adopts it (no empty-host flash).\n let host = hostsRef.current.get(args.slotName);\n if (!host) {\n host = document.createElement('div');\n hostsRef.current.set(args.slotName, host);\n }\n flushSync(() => {\n setPortalForSlot(args.slotName, host as HTMLDivElement, rendered);\n });\n return host;\n };\n };\n\n const out: MarkdownCustomRenderers = {};\n if (customRenderers.table) {\n out.table = bridge(customRenderers.table);\n }\n if (customRenderers.codeBlock) {\n out.codeBlock = bridge(customRenderers.codeBlock);\n }\n // Attribute transforms / behavior hook return plain data (not DOM), so\n // they skip the portal bridge and pass straight through.\n if (customRenderers.link) {\n out.link = customRenderers.link;\n }\n if (customRenderers.image) {\n out.image = customRenderers.image;\n }\n if (customRenderers.checklist) {\n out.checklist = customRenderers.checklist;\n }\n return out;\n }, [customRenderers, setPortalForSlot]);\n\n // After every commit, prune portals whose host Lit has removed (its slot\n // dropped out of the descriptor batch, leaving the host detached). The\n // connectivity check is deferred to a microtask on purpose: `bridge` mints a\n // host, `flushSync`s the portal into it while it is still detached, and only\n // *returns* it to Lit — which appends it synchronously afterwards. That\n // `flushSync` runs this effect once while the host is not yet adopted, so a\n // synchronous `isConnected` check would prune the entry we just added and\n // leave the slot permanently empty (e.g. a streaming table custom renderer\n // flickering out as later content arrives). Reading `isConnected` a\n // microtask later lets Lit's adoption land first, so we only drop\n // genuinely-removed hosts.\n\n useEffect(() => {\n let cancelled = false;\n queueMicrotask(() => {\n if (cancelled) {\n return;\n }\n let pruned = false;\n const aliveHosts = new Map<string, HTMLDivElement>();\n for (const [slotName, host] of hostsRef.current) {\n if (host.isConnected) {\n aliveHosts.set(slotName, host);\n } else {\n pruned = true;\n }\n }\n if (pruned) {\n hostsRef.current = aliveHosts;\n }\n setPortalEntries((prev) => {\n const filtered = prev.filter((e) => e.host.isConnected);\n return filtered.length === prev.length ? prev : filtered;\n });\n });\n return () => {\n cancelled = true;\n };\n });\n\n return (\n <>\n <BaseMarkdown\n {...rest}\n ref={setMarkdownRef as React.Ref<HTMLElement>}\n customRenderers={bridgedRenderers as never}\n />\n {portalEntries.map((entry) => (\n <React.Fragment key={entry.slotName}>\n {createPortal(entry.node, entry.host)}\n </React.Fragment>\n ))}\n </>\n );\n});\n\nMarkdown.displayName = 'Markdown';\n\nexport default Markdown;\n"],"names":["_jsxs","_jsx"],"mappings":";;;;;;;;;;;;;;AA+BA,MAAM,WAAW,GAAG,eAAe,CAAC;AAClC,IAAA,OAAO,EAAE,qBAAqB;AAC9B,IAAA,YAAY,EAAE,iBAAiB;AAC/B,IAAA,KAAK,EAAE,KAAK;AACb,CAAA,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Q,CAAC,WAAW,GAAG,UAAU;;"}
@@ -27,4 +27,8 @@ export interface BaseOverflowMenuItem extends Partial<Pick<CDSOverflowMenuItem,
27
27
  * Optional data-testid string for e2e testing.
28
28
  */
29
29
  testId?: string;
30
+ /**
31
+ * Optional ID
32
+ */
33
+ id?: string;
30
34
  }