@carbon/ai-chat-components 1.10.0-rc.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/custom-elements.json +3186 -3074
  2. package/es/components/markdown/index.d.ts +1 -0
  3. package/es/components/markdown/src/markdown-renderer.js +27 -1
  4. package/es/components/markdown/src/markdown-renderer.js.map +1 -1
  5. package/es/components/markdown/src/markdown-token-tree.js +6 -1
  6. package/es/components/markdown/src/markdown-token-tree.js.map +1 -1
  7. package/es/components/markdown/src/markdown.d.ts +5 -2
  8. package/es/components/markdown/src/markdown.js +66 -23
  9. package/es/components/markdown/src/markdown.js.map +1 -1
  10. package/es/components/markdown/src/utils/html-helpers.js +9 -2
  11. package/es/components/markdown/src/utils/html-helpers.js.map +1 -1
  12. package/es/components/markdown/src/utils/plugin-fallback.d.ts +6 -3
  13. package/es/components/markdown/src/utils/plugin-fallback.js +14 -5
  14. package/es/components/markdown/src/utils/plugin-fallback.js.map +1 -1
  15. package/es/components/markdown/src/utils/plugin-host-container.d.ts +160 -0
  16. package/es/components/markdown/src/utils/plugin-host-container.js +165 -0
  17. package/es/components/markdown/src/utils/plugin-host-container.js.map +1 -0
  18. package/es/components/markdown/src/utils/table-helpers.d.ts +10 -0
  19. package/es/components/markdown/src/utils/table-helpers.js.map +1 -1
  20. package/es/components/prompt-line/src/tiptap/build-extensions.d.ts +17 -0
  21. package/es/components/prompt-line/src/tiptap/build-extensions.js.map +1 -1
  22. package/es/components/prompt-line/src/tiptap/carbon-autocomplete.d.ts +12 -0
  23. package/es/components/prompt-line/src/tiptap/carbon-autocomplete.js.map +1 -1
  24. package/es/components/prompt-line/src/tiptap/render-token-chip.d.ts +12 -0
  25. package/es/components/prompt-line/src/tiptap/render-token-chip.js.map +1 -1
  26. package/es/components/prompt-line/src/tiptap/types.d.ts +2 -1
  27. package/es/react/markdown.js +2 -44
  28. package/es/react/markdown.js.map +1 -1
  29. package/es-custom/components/markdown/index.d.ts +1 -0
  30. package/es-custom/components/markdown/src/markdown-renderer.js +27 -1
  31. package/es-custom/components/markdown/src/markdown-renderer.js.map +1 -1
  32. package/es-custom/components/markdown/src/markdown-token-tree.js +6 -1
  33. package/es-custom/components/markdown/src/markdown-token-tree.js.map +1 -1
  34. package/es-custom/components/markdown/src/markdown.d.ts +5 -2
  35. package/es-custom/components/markdown/src/markdown.js +66 -23
  36. package/es-custom/components/markdown/src/markdown.js.map +1 -1
  37. package/es-custom/components/markdown/src/utils/html-helpers.js +9 -2
  38. package/es-custom/components/markdown/src/utils/html-helpers.js.map +1 -1
  39. package/es-custom/components/markdown/src/utils/plugin-fallback.d.ts +6 -3
  40. package/es-custom/components/markdown/src/utils/plugin-fallback.js +14 -5
  41. package/es-custom/components/markdown/src/utils/plugin-fallback.js.map +1 -1
  42. package/es-custom/components/markdown/src/utils/plugin-host-container.d.ts +160 -0
  43. package/es-custom/components/markdown/src/utils/plugin-host-container.js +165 -0
  44. package/es-custom/components/markdown/src/utils/plugin-host-container.js.map +1 -0
  45. package/es-custom/components/markdown/src/utils/table-helpers.d.ts +10 -0
  46. package/es-custom/components/markdown/src/utils/table-helpers.js.map +1 -1
  47. package/es-custom/components/prompt-line/src/tiptap/build-extensions.d.ts +17 -0
  48. package/es-custom/components/prompt-line/src/tiptap/build-extensions.js.map +1 -1
  49. package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.d.ts +12 -0
  50. package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.js.map +1 -1
  51. package/es-custom/components/prompt-line/src/tiptap/render-token-chip.d.ts +12 -0
  52. package/es-custom/components/prompt-line/src/tiptap/render-token-chip.js.map +1 -1
  53. package/es-custom/components/prompt-line/src/tiptap/types.d.ts +2 -1
  54. package/es-custom/react/markdown.js +2 -44
  55. package/es-custom/react/markdown.js.map +1 -1
  56. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"render-token-chip.js","sources":["../../../../../src/components/prompt-line/src/tiptap/render-token-chip.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Shared chip-rendering implementation used by both the editor's\n * `CarbonTokenNodeView` and the chat-side rich user message bubble. Builds\n * the wrapping `<span class=\"cds-aichat--token\">` container, honors a\n * consumer-supplied `renderCustomToken`, and delegates the light-DOM portal\n * handshake to `renderInLightDom` so React adapters can hydrate custom chip\n * content. This is a thin token-specific wrapper over `renderInLightDom`.\n */\n\nimport type { ReactNode } from 'react';\n\nimport { setVarsForSelector } from '../../../shared/dynamic-css-var-sheet.js';\nimport { renderInLightDom } from './render-in-light-dom.js';\nimport type { SuggestionItem, TriggerSuggestionConfig } from './types.js';\n\nlet tokenStyleRulesInstalled = false;\n\nfunction ensureTokenStyleRules(): void {\n if (tokenStyleRulesInstalled) {\n return;\n }\n setVarsForSelector('.cds-aichat--token', { 'white-space': 'normal' });\n setVarsForSelector('.cds-aichat--token[data-token-context=\"composer\"]', {\n color: 'var(--cds-tag-color-blue, #0043ce)',\n });\n setVarsForSelector(\n '.cds-aichat--token[data-token-context=\"composer\"]::selection',\n { 'background-color': 'var(--cds-tag-background-blue, #d0e2ff)' }\n );\n setVarsForSelector('.cds-aichat--token[data-token-context=\"historical\"]', {\n color: 'var(--cds-link-secondary, #0043ce)',\n });\n tokenStyleRulesInstalled = true;\n}\n\n/**\n * Attributes carried by a mention/command JSONContent node. Matches the\n * Tiptap mention shape (`id`, `label`) plus the carbon-specific `value`,\n * `data`, and `trigger` extensions added by `carbonMention`/`carbonCommand`.\n */\nexport interface TokenChipAttrs {\n id?: string;\n label?: string;\n value?: string;\n data?: unknown;\n /**\n * Trigger character to prefix onto the default chip text (e.g.\n * `/summarize` vs `summarize`). Set at insert time by\n * `resolveShowTriggerInChip` — defaults to command nodes only, but is\n * overridable per-config or per-item via `TriggerSuggestionConfig`/\n * `SuggestionItem`'s `showTriggerInChip`.\n */\n trigger?: string | null;\n}\n\nexport interface RenderTokenChipArgs {\n /** Node attrs in mention shape. */\n attrs: TokenChipAttrs;\n /**\n * Subset of the trigger-suggestion config relevant to chip rendering. Only\n * `renderCustomToken` is read; other config fields are ignored.\n */\n config?: Pick<TriggerSuggestionConfig, 'renderCustomToken'>;\n /** Token type — usually `\"mention\"` or `\"command\"`. */\n type: 'mention' | 'command' | string;\n /**\n * Where to dispatch the light-DOM portal event when `renderCustomToken`\n * returns custom content. The NodeView passes the editor's `view.dom`\n * (already mounted under the chat wrapper) so the event reaches the portal\n * listener synchronously. When omitted, the event fires from the portal\n * container element itself with `bubbles: true, composed: true` — callers\n * that mount the chip lazily must ensure it lives under a listener subtree\n * before connection.\n */\n dispatchTarget?: EventTarget;\n /**\n * Visual variant to render. `\"composer\"` is the live, being-typed token in\n * the prompt-line editor; `\"historical\"` is a token inside an already-sent\n * message in the transcript. Drives the default chip's color/highlight —\n * see `ensureTokenStyleRules`.\n */\n context: 'composer' | 'historical';\n}\n\nexport function renderTokenChip(args: RenderTokenChipArgs): HTMLElement {\n const dom = createTokenContainer(args.attrs, args.type, args.context);\n const renderer = args.config?.renderCustomToken;\n\n if (!renderer) {\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n const item: SuggestionItem = {\n id: typeof args.attrs.id === 'string' ? args.attrs.id : '',\n label: typeof args.attrs.label === 'string' ? args.attrs.label : '',\n ...((args.attrs.data ?? {}) as Record<string, unknown>),\n };\n\n let result: HTMLElement | ReactNode | undefined;\n try {\n result = renderer(item);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\n 'Error in renderCustomToken, falling back to default chip:',\n error\n );\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n if (result == null) {\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n // Bridge the custom chip into the page's light DOM via the shared portal\n // handshake. The default chip rides along as the `<slot>` fallback so the\n // token still shows something until the portal commits.\n const { container } = renderInLightDom({\n content: result,\n dispatchTarget: args.dispatchTarget ?? dom,\n fallback: createDefaultChip(args.attrs),\n });\n dom.appendChild(container);\n\n return dom;\n}\n\nfunction createTokenContainer(\n attrs: TokenChipAttrs,\n type: string,\n context: 'composer' | 'historical'\n): HTMLElement {\n ensureTokenStyleRules();\n const dom = document.createElement('span');\n const value = typeof attrs.value === 'string' ? attrs.value : null;\n const label = typeof attrs.label === 'string' ? attrs.label : null;\n dom.setAttribute('contenteditable', 'false');\n dom.setAttribute('data-token-type', type);\n dom.setAttribute('data-token-context', context);\n dom.setAttribute('data-raw-value', value ?? label ?? '');\n dom.className = 'cds-aichat--token';\n return dom;\n}\n\nfunction createDefaultChip(attrs: TokenChipAttrs): HTMLElement {\n const chip = document.createElement('span');\n const label = typeof attrs.label === 'string' ? attrs.label : null;\n const value = typeof attrs.value === 'string' ? attrs.value : null;\n const trigger = typeof attrs.trigger === 'string' ? attrs.trigger : '';\n chip.textContent = `${trigger}${label || value || ''}`;\n return chip;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAAA;;;;;;;AAOG;AAiBH,IAAI,wBAAwB,GAAG,KAAK;AAEpC,SAAS,qBAAqB,GAAA;IAC5B,IAAI,wBAAwB,EAAE;QAC5B;IACF;IACA,kBAAkB,CAAC,oBAAoB,EAAE,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC;IACrE,kBAAkB,CAAC,mDAAmD,EAAE;AACtE,QAAA,KAAK,EAAE,oCAAoC;AAC5C,KAAA,CAAC;IACF,kBAAkB,CAChB,8DAA8D,EAC9D,EAAE,kBAAkB,EAAE,yCAAyC,EAAE,CAClE;IACD,kBAAkB,CAAC,qDAAqD,EAAE;AACxE,QAAA,KAAK,EAAE,oCAAoC;AAC5C,KAAA,CAAC;IACF,wBAAwB,GAAG,IAAI;AACjC;AAmDM,SAAU,eAAe,CAAC,IAAyB,EAAA;AACvD,IAAA,MAAM,GAAG,GAAG,oBAAoB,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,I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G,CAAA,EAAG,OAAO,CAAA,EAAG,KAAK,IAAI,KAAK,IAAI,EAAE,CAAA,CAAE;AACtD,IAAA,OAAO,IAAI;AACb;;"}
1
+ {"version":3,"file":"render-token-chip.js","sources":["../../../../../src/components/prompt-line/src/tiptap/render-token-chip.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Shared chip-rendering implementation used by both the editor's\n * `CarbonTokenNodeView` and the chat-side rich user message bubble. Builds\n * the wrapping `<span class=\"cds-aichat--token\">` container, honors a\n * consumer-supplied `renderCustomToken`, and delegates the light-DOM portal\n * handshake to `renderInLightDom` so React adapters can hydrate custom chip\n * content. This is a thin token-specific wrapper over `renderInLightDom`.\n */\n\nimport type { ReactNode } from 'react';\n\nimport { setVarsForSelector } from '../../../shared/dynamic-css-var-sheet.js';\nimport { renderInLightDom } from './render-in-light-dom.js';\nimport type { SuggestionItem, TriggerSuggestionConfig } from './types.js';\n\nlet tokenStyleRulesInstalled = false;\n\nfunction ensureTokenStyleRules(): void {\n if (tokenStyleRulesInstalled) {\n return;\n }\n setVarsForSelector('.cds-aichat--token', { 'white-space': 'normal' });\n setVarsForSelector('.cds-aichat--token[data-token-context=\"composer\"]', {\n color: 'var(--cds-tag-color-blue, #0043ce)',\n });\n setVarsForSelector(\n '.cds-aichat--token[data-token-context=\"composer\"]::selection',\n { 'background-color': 'var(--cds-tag-background-blue, #d0e2ff)' }\n );\n setVarsForSelector('.cds-aichat--token[data-token-context=\"historical\"]', {\n color: 'var(--cds-link-secondary, #0043ce)',\n });\n tokenStyleRulesInstalled = true;\n}\n\n/**\n * Attributes carried by a mention/command JSONContent node. Matches the\n * Tiptap mention shape (`id`, `label`) plus the carbon-specific `value`,\n * `data`, and `trigger` extensions added by `carbonMention`/`carbonCommand`.\n */\nexport interface TokenChipAttrs {\n /** Identifier of the item the chip came from. */\n id?: string;\n /** Text shown on the chip. */\n label?: string;\n /**\n * String the chip contributes to the message text. Falls back to `label`\n * when unset.\n */\n value?: string;\n /**\n * Custom fields carried over from the selected item. Everything the\n * suggestion item held beyond `id`, `label`, `value`, `avatar`,\n * `description`, `disabled`, and `showTriggerInChip` lands here, so it\n * survives a round trip through the editor's JSON.\n */\n data?: unknown;\n /**\n * Trigger character to prefix onto the default chip text (e.g.\n * `/summarize` vs `summarize`). Set at insert time by\n * `resolveShowTriggerInChip` — defaults to command nodes only, but is\n * overridable per-config or per-item via `TriggerSuggestionConfig`/\n * `SuggestionItem`'s `showTriggerInChip`.\n */\n trigger?: string | null;\n}\n\nexport interface RenderTokenChipArgs {\n /** Node attrs in mention shape. */\n attrs: TokenChipAttrs;\n /**\n * Subset of the trigger-suggestion config relevant to chip rendering. Only\n * `renderCustomToken` is read; other config fields are ignored.\n */\n config?: Pick<TriggerSuggestionConfig, 'renderCustomToken'>;\n /** Token type — usually `\"mention\"` or `\"command\"`. */\n type: 'mention' | 'command' | string;\n /**\n * Where to dispatch the light-DOM portal event when `renderCustomToken`\n * returns custom content. The NodeView passes the editor's `view.dom`\n * (already mounted under the chat wrapper) so the event reaches the portal\n * listener synchronously. When omitted, the event fires from the portal\n * container element itself with `bubbles: true, composed: true` — callers\n * that mount the chip lazily must ensure it lives under a listener subtree\n * before connection.\n */\n dispatchTarget?: EventTarget;\n /**\n * Visual variant to render. `\"composer\"` is the live, being-typed token in\n * the prompt-line editor; `\"historical\"` is a token inside an already-sent\n * message in the transcript. Drives the default chip's color/highlight —\n * see `ensureTokenStyleRules`.\n */\n context: 'composer' | 'historical';\n}\n\nexport function renderTokenChip(args: RenderTokenChipArgs): HTMLElement {\n const dom = createTokenContainer(args.attrs, args.type, args.context);\n const renderer = args.config?.renderCustomToken;\n\n if (!renderer) {\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n const item: SuggestionItem = {\n id: typeof args.attrs.id === 'string' ? args.attrs.id : '',\n label: typeof args.attrs.label === 'string' ? args.attrs.label : '',\n ...((args.attrs.data ?? {}) as Record<string, unknown>),\n };\n\n let result: HTMLElement | ReactNode | undefined;\n try {\n result = renderer(item);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\n 'Error in renderCustomToken, falling back to default chip:',\n error\n );\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n if (result == null) {\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n // Bridge the custom chip into the page's light DOM via the shared portal\n // handshake. The default chip rides along as the `<slot>` fallback so the\n // token still shows something until the portal commits.\n const { container } = renderInLightDom({\n content: result,\n dispatchTarget: args.dispatchTarget ?? dom,\n fallback: createDefaultChip(args.attrs),\n });\n dom.appendChild(container);\n\n return dom;\n}\n\nfunction createTokenContainer(\n attrs: TokenChipAttrs,\n type: string,\n context: 'composer' | 'historical'\n): HTMLElement {\n ensureTokenStyleRules();\n const dom = document.createElement('span');\n const value = typeof attrs.value === 'string' ? attrs.value : null;\n const label = typeof attrs.label === 'string' ? attrs.label : null;\n dom.setAttribute('contenteditable', 'false');\n dom.setAttribute('data-token-type', type);\n dom.setAttribute('data-token-context', context);\n dom.setAttribute('data-raw-value', value ?? label ?? '');\n dom.className = 'cds-aichat--token';\n return dom;\n}\n\nfunction createDefaultChip(attrs: TokenChipAttrs): HTMLElement {\n const chip = document.createElement('span');\n const label = typeof attrs.label === 'string' ? attrs.label : null;\n const value = typeof attrs.value === 'string' ? attrs.value : null;\n const trigger = typeof attrs.trigger === 'string' ? attrs.trigger : '';\n chip.textContent = `${trigger}${label || value || ''}`;\n return chip;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAAA;;;;;;;AAOG;AAiBH,IAAI,wBAAwB,GAAG,KAAK;AAEpC,SAAS,qBAAqB,GAAA;IAC5B,IAAI,wBAAwB,EAAE;QAC5B;IACF;IACA,kBAAkB,CAAC,oBAAoB,EAAE,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC;IACrE,kBAAkB,CAAC,mDAAmD,E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aAAa,CAAC,MAAM,CAAC;AAC3C,IAAA,MAAM,KAAK,GAAG,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,GAAG,KAAK,CAAC,KAAK,GAAG,IAAI;AAClE,IAAA,MAAM,KAAK,GAAG,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,GAAG,KAAK,CAAC,KAAK,GAAG,IAAI;AAClE,IAAA,MAAM,OAAO,GAAG,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,GAAG,KAAK,CAAC,OAAO,GAAG,EAAE;AACtE,IAAA,IAAI,CAAC,WAAW,GAAG,CAAA,EAAG,OAAO,CAAA,EAAG,KAAK,IAAI,KAAK,IAAI,EAAE,CAAA,CAAE;AACtD,IAAA,OAAO,IAAI;AACb;;"}
@@ -166,7 +166,8 @@ export interface TriggerSuggestionConfig extends Omit<BaseSuggestionConfig, 'dis
166
166
  * Note: only one autocomplete config per editor is supported, because Tiptap
167
167
  * resolves extensions by name.
168
168
  */
169
- export type AutocompleteConfig = BaseSuggestionConfig;
169
+ export interface AutocompleteConfig extends BaseSuggestionConfig {
170
+ }
170
171
  /**
171
172
  * Configuration for starter prompts — shown when the editor is empty and
172
173
  * focused. Extends {@link BaseSuggestionConfig} so consumers can supply a
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
9
9
  import { createComponent } from '@lit/react';
10
- import React, { forwardRef, useRef, useState, useCallback, useEffect, useMemo } from 'react';
10
+ import React, { forwardRef, useRef, useState, useCallback, useMemo, useEffect } from 'react';
11
11
  import { createPortal, flushSync } from 'react-dom';
12
12
  import CDSAIChatMarkdown from '../components/markdown/src/markdown.js';
13
13
  import { withWebComponentBridge } from './utils/withWebComponentBridge.js';
@@ -45,14 +45,6 @@ function isElement(value) {
45
45
  const Markdown = forwardRef(function Markdown({ customRenderers, ...rest }, forwardedRef) {
46
46
  const hostsRef = useRef(new Map());
47
47
  const [portalEntries, setPortalEntries] = useState([]);
48
- // Active plugin-fallback slot names that an outer chat container is hosting
49
- // in page light DOM. When a chat-container ancestor catches the
50
- // `cds-aichat-markdown-plugin-host-mount` event (and calls preventDefault),
51
- // the markdown element skips its own local-host fallback and relies on
52
- // these forwarders to project the page-level host element through every
53
- // shadow boundary into its named slot. Storybook standalone usage stays on
54
- // the local-host path — no listener consumes the event there.
55
- const [pluginSlotNames, setPluginSlotNames] = useState([]);
56
48
  const markdownRef = useRef(null);
57
49
  const setMarkdownRef = useCallback((node) => {
58
50
  markdownRef.current = node;
@@ -63,40 +55,6 @@ const Markdown = forwardRef(function Markdown({ customRenderers, ...rest }, forw
63
55
  forwardedRef.current = node;
64
56
  }
65
57
  }, [forwardedRef]);
66
- useEffect(() => {
67
- const node = markdownRef.current;
68
- if (!node) {
69
- return undefined;
70
- }
71
- const handleMount = (event) => {
72
- const slotName = event.detail
73
- ?.slotName;
74
- if (!slotName) {
75
- return;
76
- }
77
- setPluginSlotNames((prev) => prev.includes(slotName) ? prev : [...prev, slotName]);
78
- };
79
- const handleUnmount = (event) => {
80
- const slotName = event.detail
81
- ?.slotName;
82
- if (!slotName) {
83
- return;
84
- }
85
- setPluginSlotNames((prev) => prev.includes(slotName) ? prev.filter((n) => n !== slotName) : prev);
86
- };
87
- // Optimistic: we render a `<slot>` forwarder for every slot the markdown
88
- // element emits. If a chat container ancestor takes over hosting (by
89
- // calling `preventDefault()` on the mount event), the forwarder projects
90
- // the page-level host through the chain. If nothing intercepts
91
- // (standalone storybook), the markdown element creates its own local host
92
- // alongside, and the empty forwarder is harmless.
93
- node.addEventListener('cds-aichat-markdown-plugin-host-mount', handleMount);
94
- node.addEventListener('cds-aichat-markdown-plugin-host-unmount', handleUnmount);
95
- return () => {
96
- node.removeEventListener('cds-aichat-markdown-plugin-host-mount', handleMount);
97
- node.removeEventListener('cds-aichat-markdown-plugin-host-unmount', handleUnmount);
98
- };
99
- }, []);
100
58
  const setPortalForSlot = useCallback((slotName, host, node) => {
101
59
  setPortalEntries((prev) => {
102
60
  const idx = prev.findIndex((e) => e.slotName === slotName);
@@ -198,7 +156,7 @@ const Markdown = forwardRef(function Markdown({ customRenderers, ...rest }, forw
198
156
  cancelled = true;
199
157
  };
200
158
  });
201
- return (jsxs(Fragment, { children: [jsx(BaseMarkdown, { ...rest, ref: setMarkdownRef, customRenderers: bridgedRenderers, children: pluginSlotNames.map((slotName) => (jsx("slot", { name: slotName, slot: slotName }, slotName))) }), portalEntries.map((entry) => (jsx(React.Fragment, { children: createPortal(entry.node, entry.host) }, entry.slotName)))] }));
159
+ return (jsxs(Fragment, { children: [jsx(BaseMarkdown, { ...rest, ref: setMarkdownRef, customRenderers: bridgedRenderers }), portalEntries.map((entry) => (jsx(React.Fragment, { children: createPortal(entry.node, entry.host) }, entry.slotName)))] }));
202
160
  });
203
161
  Markdown.displayName = 'Markdown';
204
162
 
@@ -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 // Active plugin-fallback slot names that an outer chat container is hosting\n // in page light DOM. When a chat-container ancestor catches the\n // `cds-aichat-markdown-plugin-host-mount` event (and calls preventDefault),\n // the markdown element skips its own local-host fallback and relies on\n // these forwarders to project the page-level host element through every\n // shadow boundary into its named slot. Storybook standalone usage stays on\n // the local-host path — no listener consumes the event there.\n const [pluginSlotNames, setPluginSlotNames] = useState<string[]>([]);\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 useEffect(() => {\n const node = markdownRef.current;\n if (!node) {\n return undefined;\n }\n const handleMount = (event: Event) => {\n const slotName = (event as CustomEvent<{ slotName: string }>).detail\n ?.slotName;\n if (!slotName) {\n return;\n }\n setPluginSlotNames((prev) =>\n prev.includes(slotName) ? prev : [...prev, slotName]\n );\n };\n const handleUnmount = (event: Event) => {\n const slotName = (event as CustomEvent<{ slotName: string }>).detail\n ?.slotName;\n if (!slotName) {\n return;\n }\n setPluginSlotNames((prev) =>\n prev.includes(slotName) ? prev.filter((n) => n !== slotName) : prev\n );\n };\n // Optimistic: we render a `<slot>` forwarder for every slot the markdown\n // element emits. If a chat container ancestor takes over hosting (by\n // calling `preventDefault()` on the mount event), the forwarder projects\n // the page-level host through the chain. If nothing intercepts\n // (standalone storybook), the markdown element creates its own local host\n // alongside, and the empty forwarder is harmless.\n node.addEventListener('cds-aichat-markdown-plugin-host-mount', handleMount);\n node.addEventListener(\n 'cds-aichat-markdown-plugin-host-unmount',\n handleUnmount\n );\n return () => {\n node.removeEventListener(\n 'cds-aichat-markdown-plugin-host-mount',\n handleMount\n );\n node.removeEventListener(\n 'cds-aichat-markdown-plugin-host-unmount',\n handleUnmount\n );\n };\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 {pluginSlotNames.map((slotName) => (\n <slot key={slotName} name={slotName} slot={slotName} />\n ))}\n </BaseMarkdown>\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","_Fragment","_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,KAAI;IAClD,MAAM,cAAc,GAClB,OAAO,QAAQ,KAAK,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ;AAC9D,IAAA,OAAO,KAAK,CAAC,aAAa,CACxB,WAAW,EACX;AACE,QAAA,GAAG,IAAI;AACP,QAAA,GAAG,EAAE,YAAY;AACjB,QAAA,QAAQ,EAAE,QAAQ,KAAK,cAAc,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,SAAS,CAAC;AACtE,KAAA;;;;IAID,cAAc,GAAG,IAAI,GAAG,QAAQ,CACjC;AACH,CAAC,CAAC;AAEF,qBAAqB,CAAC,WAAW,GAAG,cAAc;AAElD;;;;;AAKG;AACH,MAAM,YAAY,GAAG,sBAAsB,CAAC,qBAAqB,CAAC;AA4DlE,SAAS,SAAS,CAAC,KAAc,EAAA;AAC/B,IAAA,QACE,OAAO,OAAO,KAAK,WAAW;AAC9B,QAAA,KAAK,YAAY,OAAO;QACxB,SAAS,IAAI,KAAK;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,QAAA,CAAC,CAAC;AACF,QAAA,OAAO,MAAK;YACV,SAAS,GAAG,IAAI;AAClB,QAAA,CAAC;AACH,IAAA,CAAC,CAAC;AAEF,IAAA,QACEA,IAAA,CAAAC,QAAA,EAAA,EAAA,QAAA,EAAA,CACEC,GAAA,CAAC,YAAY,OACP,IAAI,EACR,GAAG,EAAE,cAAwC,EAC7C,eAAe,EAAE,gBAAyB,YACzC,eAAe,CAAC,GAAG,CAAC,CAAC,QAAQ,MAC5BA,GAAA,CAAA,MAAA,EAAA,EAAqB,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAA,EAAxC,QAAQ,CAAoC,CACxD,CAAC,EAAA,CACW,EACd,aAAa,CAAC,GAAG,CAAC,CAAC,KAAK,MACvBA,GAAA,CAAC,KAAK,CAAC,QAAQ,EAAA,EAAA,QAAA,EACZ,YAAY,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,EAAA,EADlB,KAAK,CAAC,QAAQ,CAElB,CAClB,CAAC,CAAA,EAAA,CACD;AAEP,CAAC;AAED,QAAQ,CAAC,WAAW,GAAG,UAAU;;"}
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,KAAI;IAClD,MAAM,cAAc,GAClB,OAAO,QAAQ,KAAK,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ;AAC9D,IAAA,OAAO,KAAK,CAAC,aAAa,CACxB,WAAW,EACX;AACE,QAAA,GAAG,IAAI;AACP,QAAA,GAAG,EAAE,YAAY;AACjB,QAAA,QAAQ,EAAE,QAAQ,KAAK,cAAc,GAAG,MAAM,CAAC,QAAQ,CAA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,GAAG,IAAI;gBACf;YACF;YACA,IAAI,MAAM,EAAE;AACV,gBAAA,QAAQ,CAAC,OAAO,GAAG,UAAU;YAC/B;AACA,YAAA,gBAAgB,CAAC,CAAC,IAAI,KAAI;AACxB,gBAAA,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC;AACvD,gBAAA,OAAO,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,GAAG,IAAI,GAAG,QAAQ;AAC1D,YAAA,CAAC,CAAC;AACJ,QAAA,CAAC,CAAC;AACF,QAAA,OAAO,MAAK;YACV,SAAS,GAAG,IAAI;AAClB,QAAA,CAAC;AACH,IAAA,CAAC,CAAC;IAEF,QACEA,4BACEC,GAAA,CAAC,YAAY,OACP,IAAI,EACR,GAAG,EAAE,cAAwC,EAC7C,eAAe,EAAE,gBAAyB,EAAA,CAC1C,EACD,aAAa,CAAC,GAAG,CAAC,CAAC,KAAK,MACvBA,GAAA,CAAC,KAAK,CAAC,QAAQ,EAAA,EAAA,QAAA,EACZ,YAAY,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,EAAA,EADlB,KAAK,CAAC,QAAQ,CAElB,CAClB,CAAC,CAAA,EAAA,CACD;AAEP,CAAC;AAED,QAAQ,CAAC,WAAW,GAAG,UAAU;;"}
@@ -1,5 +1,6 @@
1
1
  import './src/markdown.js';
2
2
  export { default, CDSAIChatMarkdown } from './src/markdown.js';
3
3
  export type { MarkdownCustomRenderers, MarkdownRendererChecklist, MarkdownRendererChecklistItemArgs, MarkdownRendererChecklistToggleArgs, MarkdownRendererCodeBlockArgs, MarkdownRendererCodeBlockData, MarkdownRendererImageArgs, MarkdownRendererImageResult, MarkdownRendererLinkArgs, MarkdownRendererLinkResult, MarkdownRendererTableArgs, MarkdownRendererTableData, } from './src/markdown-renderer-types.js';
4
+ export type { MarkdownCustomRendererMountDetail, MarkdownPluginFallbackMountDetail, MarkdownPluginHostMountDetail, MarkdownPluginHostMountDetailInput, } from './src/utils/plugin-host-container.js';
4
5
  export type { MarkdownItPlugin, TokenTree } from './src/markdown-token-tree.js';
5
6
  export { markdownToMarkdownItTokens } from './src/markdown-token-tree.js';
@@ -131,10 +131,28 @@ function renderChildTokenTrees(children, options, childContext) {
131
131
  function renderMarkdownTree(node, options) {
132
132
  const batch = [];
133
133
  let pluginSlotIndex = 0;
134
+ // Memoized per node, not just counted. `renderFallback` runs inside a
135
+ // lit-html `repeat()` callback, so it evaluates when lit-html commits the
136
+ // template — and one render result gets committed again on any later Lit
137
+ // update that leaves `renderedContent` alone. A bare counter would hand the
138
+ // same token a fresh index on each commit, minting a second slot the very
139
+ // next reconcile retires. First evaluation still assigns 0, 1, 2 in walk
140
+ // order, so a single-commit render is unchanged.
141
+ const pluginSlotIndexes = new WeakMap();
134
142
  const template = renderTokenTree(node, {
135
143
  ...options,
136
144
  recordCustomRender: (descriptor) => batch.push(descriptor),
137
- pluginSlotCounter: { next: () => pluginSlotIndex++ },
145
+ pluginSlotCounter: {
146
+ next: (forNode) => {
147
+ const existing = pluginSlotIndexes.get(forNode);
148
+ if (existing !== undefined) {
149
+ return existing;
150
+ }
151
+ const index = pluginSlotIndex++;
152
+ pluginSlotIndexes.set(forNode, index);
153
+ return index;
154
+ },
155
+ },
138
156
  });
139
157
  return { template, batch };
140
158
  }
@@ -175,6 +193,14 @@ function renderTokenTree(node, options) {
175
193
  if (token.type === 'text') {
176
194
  return html `${token.content}`;
177
195
  }
196
+ // Hard and soft line breaks. Handled before the tag-based dispatch because
197
+ // hardbreak has tag="br", which `renderWithStaticTag` does not know and would
198
+ // route through the plugin-fallback slot machinery.
199
+ if (token.type === 'hardbreak' || token.type === 'softbreak') {
200
+ return token.type === 'softbreak' && options.md?.options.breaks === false
201
+ ? html `${'\n'}`
202
+ : html `<br />`;
203
+ }
178
204
  // Handle inline code spans
179
205
  if (token.type === 'code_inline') {
180
206
  if (shouldDelegateToPluginRule(token, options.md) && options.md) {
@@ -1 +1 @@
1
- {"version":3,"file":"markdown-renderer.js","sources":["../../../../src/components/markdown/src/markdown-renderer.ts"],"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 * Walks a `TokenTree` and emits a Lit `TemplateResult` plus a batch of {@link MarkdownRendererSlotDescriptor} records the markdown element consumes during its `updated()` reconcile. External callers should go through {@link renderMarkdownTree} so the batch isn't accidentally dropped.\n *\n * ### Dispatch precedence\n *\n * Per token, in order:\n *\n * 1. **Consumer override** — `options.customRenderers`. For `table`/`codeBlock` the renderer emits a named `<slot>` placeholder and records a descriptor; the markdown element's `updated()` invokes the consumer callback later. For `link`/`image` the callback runs synchronously here as an attribute transform (no slot, no descriptor); `checklist` adjusts the rendered `cds-custom-checkbox` (its toggles are delivered by a listener on the markdown element).\n * 2. **Plugin-overridden rule** — `shouldDelegateToPluginRule(token, md)` is true when a user-supplied markdown-it plugin overrode the renderer rule for one of the curated leaf tokens in `PLUGIN_DELEGABLE_TOKEN_TYPES` (`fence`, `image`, `code_inline`, `html_block`). The token routes through `renderFallback` and surfaces as a `pluginFallback` descriptor.\n * 3. **Native Lit dispatch** — the hand-written `renderWithStaticTag` switch. Kept flat (rather than a tag-to-renderer map) so the per-tag exceptions — task-list passthrough, Carbon `cds-custom-unordered-list` / `cds-custom-ordered-list` wrappers, automatic `target=\"_blank\"` on `<a>`, image plugin delegation — stay easy to grep.\n * 4. **Unknown plugin-introduced token** — anything not natively handled falls through to `renderFallback`, so plugins that register `md.renderer.rules[type]` (footnote, deflist, custom containers, emoji) just work.\n *\n * ### Slot contract\n *\n * {@link MarkdownRendererSlotDescriptor} (defined in `./markdown-renderer-types.ts`) is the bridge between this module and `./markdown.ts`. This module appends descriptors via `recordCustomRender`; the markdown element's `reconcileCustomRendererHosts` consumes them, invokes consumer callbacks (or adopts plugin-fallback HTML) and attaches the result as a light-DOM `<div slot=\"…\">` host (or `<span>` for inline plugin output).\n */\n\nimport DOMPurify from 'dompurify';\nimport { html, TemplateResult } from 'lit';\nimport { repeat } from 'lit/directives/repeat.js';\nimport { unsafeHTML } from 'lit/directives/unsafe-html.js';\nimport { Token } from 'markdown-it';\nimport '@carbon/web-components/es-custom/components/list/index.js';\nimport '@carbon/web-components/es-custom/components/checkbox/index.js';\nimport '../../code-snippet/index.js';\nimport '../../card/index.js';\nimport '../../table/index.js';\nimport { defaultLineCountText } from '../../code-snippet/src/formatters.js';\n\nimport { renderTable } from './utils/table-helpers.js';\nimport {\n combineConsecutiveHtmlInline,\n combineSplitHtmlBlocks,\n} from './utils/html-helpers.js';\nimport {\n htmlContainer,\n sanitizeHtmlContent,\n spread,\n} from './utils/lit-directives.js';\nimport {\n isNativelyHandled,\n renderFallback,\n shouldDelegateToPluginRule,\n} from './utils/plugin-fallback.js';\nimport {\n MARKDOWN_SLOT_PREFIX,\n withInstanceNamespace,\n} from './utils/slot-names.js';\nimport { type TokenTree } from './markdown-token-tree.js';\nimport type {\n MarkdownRendererLinkResult,\n MarkdownRendererSlotDescriptor,\n RenderTokenTreeOptions,\n} from './markdown-renderer-types.js';\n\n// Re-export types so existing imports of these from this module keep working.\nexport type {\n MarkdownCustomRenderers,\n MarkdownRendererChecklist,\n MarkdownRendererChecklistItemArgs,\n MarkdownRendererChecklistToggleArgs,\n MarkdownRendererCodeBlockArgs,\n MarkdownRendererCodeBlockData,\n MarkdownRendererImageArgs,\n MarkdownRendererImageResult,\n MarkdownRendererLinkArgs,\n MarkdownRendererLinkResult,\n MarkdownRendererSlotDescriptor,\n MarkdownRendererTableArgs,\n MarkdownRendererTableData,\n RenderTokenTreeOptions,\n} from './markdown-renderer-types.js';\n\n/**\n * Slot name for an overridable token — unique across the page, stable across\n * streaming ticks. Three parts:\n *\n * - `startLine` (not the full `token.map`) so the name doesn't change when the\n * token's `endLine` advances during streaming;\n * - `currentIndex` from the parent context, disambiguating siblings that share\n * a start line (rare but possible);\n * - the owning element's namespace, because slot hosts from every markdown\n * element on the page are hoisted into one shared light-DOM container and\n * projected back by name (see `./utils/slot-names.js`).\n */\nfunction slotNameFor(\n kind: 'table' | 'codeBlock',\n token: Token,\n options: RenderTokenTreeOptions\n): string {\n const startLine = token.map?.[0] ?? 0;\n const index = options.context?.currentIndex ?? 0;\n return withInstanceNamespace(\n `${MARKDOWN_SLOT_PREFIX}-${kind}-${startLine}-${index}`,\n options\n );\n}\n\n/**\n * Drops attributes DOMPurify considers unsafe (event handlers, `javascript:`\n * URLs, etc.) from a plain attr object. Used both for the parsed token attrs\n * and for attributes a consumer `link`/`image` renderer merges in — the latter\n * bypass the token-attr pass, so they must be re-checked here.\n */\nfunction sanitizeAttrs(attrs: Record<string, string>): Record<string, string> {\n return Object.fromEntries(\n Object.entries(attrs).filter(([key, value]) => {\n // Use DOMPurify to check if attribute is safe\n const fragment = DOMPurify.sanitize(`<a ${key}=\"${value}\">`, {\n RETURN_DOM: true,\n });\n const element = fragment.firstChild as Element | null;\n return element?.getAttribute(key) !== null;\n })\n );\n}\n\n/**\n * Concatenates the plain-text content of a node's descendants. A lossy\n * convenience for consumer `link`/`checklist` callbacks that want the visible\n * text; the rich children still render through the normal dispatch.\n */\nfunction extractText(node: TokenTree): string {\n const { token, children } = node;\n if (children && children.length > 0) {\n return children.map(extractText).join('');\n }\n return token.content ?? '';\n}\n\nfunction renderChildTokenTrees(\n children: TokenTree[],\n options: RenderTokenTreeOptions,\n childContext?: RenderTokenTreeOptions['context']\n): TemplateResult {\n const normalizedChildren = combineConsecutiveHtmlInline(\n combineSplitHtmlBlocks(children)\n );\n\n // Multiple or complex children: use repeat for stable keying\n return html`${repeat(\n normalizedChildren,\n (child, index) => {\n // Key by start line + type + tag rather than array index so blocks keep\n // a stable identity when earlier siblings transiently merge/split during\n // streaming re-parses (which would otherwise re-key and remount later\n // blocks — e.g. remounting a code snippet and reloading its editor). We\n // use `token.map?.[0]` (start line, like `slotNameFor`) rather than the\n // node's `key`/`generateKey`, whose embedded end line advances every tick.\n const startLine = child.token.map?.[0] ?? index;\n const stableKey = `${startLine}:${child.token.type}:${child.token.tag}`;\n\n if (child.token.type?.includes('table')) {\n return `table-${stableKey}`;\n }\n\n return `stable-${stableKey}`;\n },\n (child, index) => {\n const result = renderTokenTree(child, {\n ...options,\n context: {\n ...childContext,\n parentChildren: normalizedChildren,\n currentIndex: index,\n },\n });\n // Ensure we never return undefined, which Lit would render as the string \"undefined\"\n return result ?? html``;\n }\n )}`;\n}\n\n/**\n * Top-level entry: renders a markdown token tree to a Lit `TemplateResult`\n * and returns the batch of custom-renderer slot descriptors collected along\n * the way. Callers receive both pieces in one call so the batch can't be\n * accidentally dropped.\n */\nexport function renderMarkdownTree(\n node: TokenTree,\n options: RenderTokenTreeOptions\n): {\n template: TemplateResult;\n batch: MarkdownRendererSlotDescriptor[];\n} {\n const batch: MarkdownRendererSlotDescriptor[] = [];\n let pluginSlotIndex = 0;\n const template = renderTokenTree(node, {\n ...options,\n recordCustomRender: (descriptor) => batch.push(descriptor),\n pluginSlotCounter: { next: () => pluginSlotIndex++ },\n });\n return { template, batch };\n}\n\n/**\n * Converts TokenTree to Lit TemplateResult.\n *\n * Recursive renderer; external callers should use {@link renderMarkdownTree}\n * which collects the slot-descriptor batch.\n */\nexport function renderTokenTree(\n node: TokenTree,\n options: RenderTokenTreeOptions\n): TemplateResult {\n const { token, children } = node;\n const { context, sanitize } = options;\n\n // Handle raw HTML blocks and inline HTML\n if (token.type === 'html_block' || token.type === 'html_inline') {\n // Plugin-overridden html_block rules (rare but supported) — route through\n // the plugin's renderer before our default unsafeHTML pass-through.\n if (\n token.type === 'html_block' &&\n shouldDelegateToPluginRule(token, options.md) &&\n options.md\n ) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n\n let content = token.content || '';\n\n // Apply HTML sanitization if requested\n if (sanitize && content) {\n content = sanitizeHtmlContent(content);\n }\n\n return html`${unsafeHTML(content)}`;\n }\n\n // Handle split HTML blocks that wrap markdown siblings (e.g. <details>…</details>).\n if (token.type === 'html_container') {\n const openingHtml = token.content ?? '';\n const innerContent = renderChildTokenTrees(children, options, context);\n\n return html`<div\n class=\"cds-custom-aichat-markdown-html-container\"\n ${htmlContainer(openingHtml, innerContent, sanitize)}></div>`;\n }\n\n // Handle plain text content\n if (token.type === 'text') {\n return html`${token.content}`;\n }\n\n // Handle inline code spans\n if (token.type === 'code_inline') {\n if (shouldDelegateToPluginRule(token, options.md) && options.md) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n return html`<code>${token.content}</code>`;\n }\n\n // Handle fenced code blocks\n if (token.type === 'fence') {\n const language = token.info?.trim() ?? '';\n const {\n codeSnippetHighlight = true,\n codeSnippetShowLessText,\n codeSnippetShowMoreText,\n codeSnippetCopyButtonTooltipContent,\n codeSnippetGetLineCountText = defaultLineCountText,\n codeSnippetAriaLabelReadOnly,\n codeSnippetAriaLabelEditable,\n } = options;\n\n const defaultTemplate = html`<cds-custom-aichat-card is-flush>\n <div slot=\"body\">\n <cds-custom-aichat-code-snippet\n data-rounded\n .language=${language}\n .highlight=${codeSnippetHighlight}\n .detectLanguage=${true}\n .showLessText=${codeSnippetShowLessText}\n .showMoreText=${codeSnippetShowMoreText}\n .copyButtonTooltipContent=${codeSnippetCopyButtonTooltipContent}\n .getLineCountText=${codeSnippetGetLineCountText}\n .ariaLabelReadOnly=${codeSnippetAriaLabelReadOnly}\n .ariaLabelEditable=${codeSnippetAriaLabelEditable}\n .code=${token.content}></cds-custom-aichat-code-snippet>\n </div>\n </cds-custom-aichat-card>`;\n\n if (options.customRenderers?.codeBlock) {\n const slotName = slotNameFor('codeBlock', token as Token, options);\n options.recordCustomRender?.({\n slotName,\n kind: 'codeBlock',\n token: token as Token,\n data: {\n language,\n code: token.content ?? '',\n isStreaming: !!options.streaming,\n },\n });\n return html`<slot name=${slotName}>${defaultTemplate}</slot>`;\n }\n\n // Honor user-plugin `fence` overrides (markdown-it-mermaid, syntax\n // highlighters, etc.). customRenderer slot above wins when set.\n if (shouldDelegateToPluginRule(token, options.md) && options.md) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n\n return defaultTemplate;\n }\n\n // Handle structural elements (paragraphs, headings, lists, etc.)\n const tag = token.tag;\n\n // Convert markdown-it attributes (array of [key, value]) into an object.\n const rawAttrs = (token.attrs || []).reduce(\n (acc, [key, value]) => {\n acc[key] = value;\n return acc;\n },\n {} as Record<string, string>\n );\n\n // Apply attribute sanitization if requested\n let attrs = rawAttrs;\n const isCustomElement = !!token.tag && token.tag.includes('-');\n if (sanitize && !isCustomElement) {\n attrs = sanitizeAttrs(rawAttrs);\n }\n\n // Set up context for child rendering\n let childContext = context;\n if (tag === 'thead') {\n childContext = { ...context, isInThead: true };\n }\n\n // Render child content\n let content: TemplateResult;\n\n if (children.length === 1 && children[0].token.type === 'text') {\n // Optimization: single text child doesn't need repeat wrapper\n content = html`${children[0].token.content}`;\n } else {\n content = renderChildTokenTrees(children, options, childContext);\n }\n\n // Unknown plugin-introduced tokens (no tag we recognize) — defer to\n // markdown-it's renderer so plugins that register md.renderer.rules[type]\n // (footnote, emoji, deflist, container, etc.) just work.\n if (!tag && options.md && !isNativelyHandled(token)) {\n return renderFallback(token as Token, node, options.md, sanitize, options);\n }\n\n // Handle tokens without HTML tags (just return content)\n if (!tag) {\n return content;\n }\n\n // Render the final HTML element with appropriate tag\n return renderWithStaticTag(\n tag,\n token as Token,\n content,\n attrs,\n options,\n childContext,\n node\n );\n}\n\n/**\n * Renders HTML elements with static tag names.\n */\nfunction renderWithStaticTag(\n tag: string,\n token: Token,\n content: TemplateResult,\n attrs: Record<string, string>,\n options: RenderTokenTreeOptions,\n _context?: { isInThead?: boolean },\n node?: TokenTree\n): TemplateResult {\n // Handle root token specially\n if (token.type === 'root') {\n return content;\n }\n\n const hasTaskListItems = (listNode?: TokenTree) =>\n !!listNode?.children?.some((child) => {\n if (child.token.type !== 'list_item_open') {\n return false;\n }\n\n const classAttr = child.token.attrs?.find(([key]) => key === 'class');\n return classAttr?.[1]?.split(/\\s+/).includes('task-list-item');\n });\n\n switch (tag) {\n // Basic block elements\n case 'p':\n return html`<p ${spread(attrs)}>${content}</p>`;\n\n case 'blockquote':\n return html`<blockquote ${spread(attrs)}>${content}</blockquote>`;\n\n case 'pre':\n return html`<pre ${spread(attrs)}>${content}</pre>`;\n\n case 'hr':\n return html`<hr ${spread(attrs)} />`;\n\n // Headings\n case 'h1':\n return html`<h1 ${spread(attrs)}>${content}</h1>`;\n case 'h2':\n return html`<h2 ${spread(attrs)}>${content}</h2>`;\n case 'h3':\n return html`<h3 ${spread(attrs)}>${content}</h3>`;\n case 'h4':\n return html`<h4 ${spread(attrs)}>${content}</h4>`;\n case 'h5':\n return html`<h5 ${spread(attrs)}>${content}</h5>`;\n case 'h6':\n return html`<h6 ${spread(attrs)}>${content}</h6>`;\n\n // Lists with Carbon components\n case 'ul': {\n const nested = token.level > 1;\n if (hasTaskListItems(node)) {\n return html`<ul ${spread(attrs)}>\n ${content}\n </ul>`;\n }\n return html`<p>\n <cds-custom-unordered-list ?nested=${nested} ${spread(attrs)}>\n ${content}\n </cds-custom-unordered-list>\n </p>`;\n }\n\n case 'ol': {\n const nested = token.level > 1;\n if (hasTaskListItems(node)) {\n return html`<ol ${spread(attrs)}>\n ${content}\n </ol>`;\n }\n return html`<p>\n <cds-custom-ordered-list native ?nested=${nested} ${spread(attrs)}>\n ${content}\n </cds-custom-ordered-list>\n </p>`;\n }\n\n case 'li': {\n const classList = attrs.class?.split(/\\s+/) ?? [];\n if (classList.includes('task-list-item')) {\n return html`<li ${spread(attrs)}>${content}</li>`;\n }\n return html`<cds-custom-list-item ${spread(attrs)}>${content}</cds-custom-list-item>`;\n }\n\n case 'cds-custom-checkbox': {\n const { checked, disabled, ...otherAttrs } = attrs;\n let isChecked = checked === 'true';\n\n // A configured `checklist` renderer can supply the checked state\n // (so a persisted toggle survives streaming re-renders) and makes the\n // boxes interactive.\n const checklist = options.customRenderers?.checklist;\n if (checklist?.getChecked && node) {\n const override = checklist.getChecked({\n id: otherAttrs['data-cds-aichat-checklist-id'] ?? '',\n label: extractText(node),\n checked: isChecked,\n token,\n });\n if (typeof override === 'boolean') {\n isChecked = override;\n }\n }\n\n const isDisabled = checklist\n ? false\n : disabled === undefined\n ? false\n : disabled === '' || disabled === 'true';\n\n return html`<cds-custom-checkbox\n ?checked=${isChecked}\n ?disabled=${isDisabled}\n ${spread(otherAttrs)}\n >${content}</cds-custom-checkbox\n >`;\n }\n\n // Inline formatting\n case 'strong':\n return html`<strong ${spread(attrs)}>${content}</strong>`;\n case 'em':\n return html`<em ${spread(attrs)}>${content}</em>`;\n case 'code':\n return html`<code ${spread(attrs)}>${content}</code>`;\n case 'del':\n return html`<del ${spread(attrs)}>${content}</del>`;\n case 'sub':\n return html`<sub ${spread(attrs)}>${content}</sub>`;\n case 'sup':\n return html`<sup ${spread(attrs)}>${content}</sup>`;\n case 'span':\n return html`<span ${spread(attrs)}>${content}</span>`;\n case 'i':\n return html`<i ${spread(attrs)}>${content}</i>`;\n case 'b':\n return html`<b ${spread(attrs)}>${content}</b>`;\n case 'small':\n return html`<small ${spread(attrs)}>${content}</small>`;\n case 'mark':\n return html`<mark ${spread(attrs)}>${content}</mark>`;\n case 'ins':\n return html`<ins ${spread(attrs)}>${content}</ins>`;\n case 's':\n return html`<s ${spread(attrs)}>${content}</s>`;\n case 'kbd':\n return html`<kbd ${spread(attrs)}>${content}</kbd>`;\n case 'var':\n return html`<var ${spread(attrs)}>${content}</var>`;\n case 'samp':\n return html`<samp ${spread(attrs)}>${content}</samp>`;\n case 'cite':\n return html`<cite ${spread(attrs)}>${content}</cite>`;\n case 'abbr':\n return html`<abbr ${spread(attrs)}>${content}</abbr>`;\n case 'dfn':\n return html`<dfn ${spread(attrs)}>${content}</dfn>`;\n case 'time':\n return html`<time ${spread(attrs)}>${content}</time>`;\n case 'q':\n return html`<q ${spread(attrs)}>${content}</q>`;\n\n // Links: optional consumer attribute transform, then automatic\n // target=\"_blank\" safety default.\n case 'a': {\n let linkAttrs: Record<string, string> = {\n ...attrs,\n target: attrs.target ?? '_blank',\n };\n\n let onClickHandler: MarkdownRendererLinkResult['onClick'];\n\n const linkRenderer = options.customRenderers?.link;\n\n if (linkRenderer && node) {\n const result = linkRenderer({\n href: attrs.href ?? '',\n title: attrs.title,\n text: extractText(node),\n attributes: { ...attrs },\n token,\n });\n\n if (result) {\n linkAttrs = {\n ...linkAttrs,\n ...(result.attributes ?? {}),\n };\n\n if (result.href !== undefined) {\n linkAttrs.href = result.href;\n }\n if (result.target !== undefined) {\n linkAttrs.target = result.target;\n }\n if (result.rel !== undefined) {\n linkAttrs.rel = result.rel;\n }\n\n // Consumer-supplied attributes are merged after the initial token\n // sanitization pass, so sanitize the final attribute set again.\n if (options.sanitize) {\n linkAttrs = sanitizeAttrs(linkAttrs);\n }\n\n onClickHandler = result.onClick;\n }\n }\n\n return html`<a ${spread(linkAttrs)} @click=${onClickHandler}\n >${content}</a\n >`;\n }\n\n // Self-closing image. A consumer `image` transform wins first (mirroring\n // how `codeBlock` wins over plugin `fence` rules); otherwise\n // plugin-introduced wrappers (e.g. image-figures) route through\n // `shouldDelegateToPluginRule` before falling back to a plain `<img>`.\n case 'img': {\n const imageRenderer = options.customRenderers?.image;\n if (imageRenderer && node) {\n let imgAttrs: Record<string, string> = attrs;\n const result = imageRenderer({\n src: attrs.src ?? '',\n alt: attrs.alt,\n title: attrs.title,\n attributes: { ...attrs },\n token,\n });\n if (result) {\n imgAttrs = { ...attrs, ...(result.attributes ?? {}) };\n if (result.src !== undefined) {\n imgAttrs.src = result.src;\n }\n if (options.sanitize) {\n imgAttrs = sanitizeAttrs(imgAttrs);\n }\n }\n return html`<img ${spread(imgAttrs)} />`;\n }\n if (node && options.md && shouldDelegateToPluginRule(token, options.md)) {\n return renderFallback(\n token,\n node,\n options.md,\n options.sanitize,\n options\n );\n }\n return html`<img ${spread(attrs)} />`;\n }\n\n // Tables with Carbon component and streaming support\n case 'table': {\n if (!node) {\n return html`<div>Error: Missing table data</div>`;\n }\n const slotName = options.customRenderers?.table\n ? slotNameFor('table', token, options)\n : undefined;\n return renderTable(\n token,\n node,\n attrs,\n options,\n renderTokenTree,\n slotName\n );\n }\n\n // Fallback for unknown tags. If we have the markdown-it instance available,\n // defer to its renderer for plugin-introduced container tags (footnote_block,\n // dl/dt/dd from deflist, custom containers, etc.). Otherwise fall back to\n // a generic <div>.\n default:\n if (options.md && node && !isNativelyHandled(token)) {\n return renderFallback(\n token,\n node,\n options.md,\n options.sanitize,\n options\n );\n }\n return html`<div ${spread(attrs)}>${content}</div>`;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;;;;;;;AAeG;AA0DH;;;;;;;;;;;AAWG;AACH,SAAS,WAAW,CAClB,IAA2B,EAC3B,KAAY,EACZ,OAA+B,EAAA;IAE/B,MAAM,SAAS,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC;IACrC,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,EAAE,YAAY,IAAI,CAAC;AAChD,IAAA,OAAO,qBAAqB,CAC1B,CAAA,EAAG,oBAAoB,IAAI,IAAI,CAAA,CAAA,EAAI,SAAS,CAAA,CAAA,EAAI,KAAK,CAAA,CAAE,EACvD,OAAO,CACR;AACH;AAEA;;;;;AAKG;AACH,SAAS,aAAa,CAAC,KAA6B,EAAA;IAClD,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,KAAI;;QAE5C,MAAM,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAA,GAAA,EAAM,GAAG,CAAA,EAAA,EAAK,KAAK,CAAA,EAAA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;;"}
1
+ {"version":3,"file":"markdown-renderer.js","sources":["../../../../src/components/markdown/src/markdown-renderer.ts"],"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 * Walks a `TokenTree` and emits a Lit `TemplateResult` plus a batch of {@link MarkdownRendererSlotDescriptor} records the markdown element consumes during its `updated()` reconcile. External callers should go through {@link renderMarkdownTree} so the batch isn't accidentally dropped.\n *\n * ### Dispatch precedence\n *\n * Per token, in order:\n *\n * 1. **Consumer override** — `options.customRenderers`. For `table`/`codeBlock` the renderer emits a named `<slot>` placeholder and records a descriptor; the markdown element's `updated()` invokes the consumer callback later. For `link`/`image` the callback runs synchronously here as an attribute transform (no slot, no descriptor); `checklist` adjusts the rendered `cds-custom-checkbox` (its toggles are delivered by a listener on the markdown element).\n * 2. **Plugin-overridden rule** — `shouldDelegateToPluginRule(token, md)` is true when a user-supplied markdown-it plugin overrode the renderer rule for one of the curated leaf tokens in `PLUGIN_DELEGABLE_TOKEN_TYPES` (`fence`, `image`, `code_inline`, `html_block`). The token routes through `renderFallback` and surfaces as a `pluginFallback` descriptor.\n * 3. **Native Lit dispatch** — the hand-written `renderWithStaticTag` switch. Kept flat (rather than a tag-to-renderer map) so the per-tag exceptions — task-list passthrough, Carbon `cds-custom-unordered-list` / `cds-custom-ordered-list` wrappers, automatic `target=\"_blank\"` on `<a>`, image plugin delegation — stay easy to grep.\n * 4. **Unknown plugin-introduced token** — anything not natively handled falls through to `renderFallback`, so plugins that register `md.renderer.rules[type]` (footnote, deflist, custom containers, emoji) just work.\n *\n * ### Slot contract\n *\n * {@link MarkdownRendererSlotDescriptor} (defined in `./markdown-renderer-types.ts`) is the bridge between this module and `./markdown.ts`. This module appends descriptors via `recordCustomRender`; the markdown element's `reconcileCustomRendererHosts` consumes them, invokes consumer callbacks (or adopts plugin-fallback HTML) and attaches the result as a light-DOM `<div slot=\"…\">` host (or `<span>` for inline plugin output).\n */\n\nimport DOMPurify from 'dompurify';\nimport { html, TemplateResult } from 'lit';\nimport { repeat } from 'lit/directives/repeat.js';\nimport { unsafeHTML } from 'lit/directives/unsafe-html.js';\nimport { Token } from 'markdown-it';\nimport '@carbon/web-components/es-custom/components/list/index.js';\nimport '@carbon/web-components/es-custom/components/checkbox/index.js';\nimport '../../code-snippet/index.js';\nimport '../../card/index.js';\nimport '../../table/index.js';\nimport { defaultLineCountText } from '../../code-snippet/src/formatters.js';\n\nimport { renderTable } from './utils/table-helpers.js';\nimport {\n combineConsecutiveHtmlInline,\n combineSplitHtmlBlocks,\n} from './utils/html-helpers.js';\nimport {\n htmlContainer,\n sanitizeHtmlContent,\n spread,\n} from './utils/lit-directives.js';\nimport {\n isNativelyHandled,\n renderFallback,\n shouldDelegateToPluginRule,\n} from './utils/plugin-fallback.js';\nimport {\n MARKDOWN_SLOT_PREFIX,\n withInstanceNamespace,\n} from './utils/slot-names.js';\nimport { type TokenTree } from './markdown-token-tree.js';\nimport type {\n MarkdownRendererLinkResult,\n MarkdownRendererSlotDescriptor,\n RenderTokenTreeOptions,\n} from './markdown-renderer-types.js';\n\n// Re-export types so existing imports of these from this module keep working.\nexport type {\n MarkdownCustomRenderers,\n MarkdownRendererChecklist,\n MarkdownRendererChecklistItemArgs,\n MarkdownRendererChecklistToggleArgs,\n MarkdownRendererCodeBlockArgs,\n MarkdownRendererCodeBlockData,\n MarkdownRendererImageArgs,\n MarkdownRendererImageResult,\n MarkdownRendererLinkArgs,\n MarkdownRendererLinkResult,\n MarkdownRendererSlotDescriptor,\n MarkdownRendererTableArgs,\n MarkdownRendererTableData,\n RenderTokenTreeOptions,\n} from './markdown-renderer-types.js';\n\n/**\n * Slot name for an overridable token — unique across the page, stable across\n * streaming ticks. Three parts:\n *\n * - `startLine` (not the full `token.map`) so the name doesn't change when the\n * token's `endLine` advances during streaming;\n * - `currentIndex` from the parent context, disambiguating siblings that share\n * a start line (rare but possible);\n * - the owning element's namespace, because slot hosts from every markdown\n * element on the page are hoisted into one shared light-DOM container and\n * projected back by name (see `./utils/slot-names.js`).\n */\nfunction slotNameFor(\n kind: 'table' | 'codeBlock',\n token: Token,\n options: RenderTokenTreeOptions\n): string {\n const startLine = token.map?.[0] ?? 0;\n const index = options.context?.currentIndex ?? 0;\n return withInstanceNamespace(\n `${MARKDOWN_SLOT_PREFIX}-${kind}-${startLine}-${index}`,\n options\n );\n}\n\n/**\n * Drops attributes DOMPurify considers unsafe (event handlers, `javascript:`\n * URLs, etc.) from a plain attr object. Used both for the parsed token attrs\n * and for attributes a consumer `link`/`image` renderer merges in — the latter\n * bypass the token-attr pass, so they must be re-checked here.\n */\nfunction sanitizeAttrs(attrs: Record<string, string>): Record<string, string> {\n return Object.fromEntries(\n Object.entries(attrs).filter(([key, value]) => {\n // Use DOMPurify to check if attribute is safe\n const fragment = DOMPurify.sanitize(`<a ${key}=\"${value}\">`, {\n RETURN_DOM: true,\n });\n const element = fragment.firstChild as Element | null;\n return element?.getAttribute(key) !== null;\n })\n );\n}\n\n/**\n * Concatenates the plain-text content of a node's descendants. A lossy\n * convenience for consumer `link`/`checklist` callbacks that want the visible\n * text; the rich children still render through the normal dispatch.\n */\nfunction extractText(node: TokenTree): string {\n const { token, children } = node;\n if (children && children.length > 0) {\n return children.map(extractText).join('');\n }\n return token.content ?? '';\n}\n\nfunction renderChildTokenTrees(\n children: TokenTree[],\n options: RenderTokenTreeOptions,\n childContext?: RenderTokenTreeOptions['context']\n): TemplateResult {\n const normalizedChildren = combineConsecutiveHtmlInline(\n combineSplitHtmlBlocks(children)\n );\n\n // Multiple or complex children: use repeat for stable keying\n return html`${repeat(\n normalizedChildren,\n (child, index) => {\n // Key by start line + type + tag rather than array index so blocks keep\n // a stable identity when earlier siblings transiently merge/split during\n // streaming re-parses (which would otherwise re-key and remount later\n // blocks — e.g. remounting a code snippet and reloading its editor). We\n // use `token.map?.[0]` (start line, like `slotNameFor`) rather than the\n // node's `key`/`generateKey`, whose embedded end line advances every tick.\n const startLine = child.token.map?.[0] ?? index;\n const stableKey = `${startLine}:${child.token.type}:${child.token.tag}`;\n\n if (child.token.type?.includes('table')) {\n return `table-${stableKey}`;\n }\n\n return `stable-${stableKey}`;\n },\n (child, index) => {\n const result = renderTokenTree(child, {\n ...options,\n context: {\n ...childContext,\n parentChildren: normalizedChildren,\n currentIndex: index,\n },\n });\n // Ensure we never return undefined, which Lit would render as the string \"undefined\"\n return result ?? html``;\n }\n )}`;\n}\n\n/**\n * Top-level entry: renders a markdown token tree to a Lit `TemplateResult`\n * and returns the batch of custom-renderer slot descriptors collected along\n * the way. Callers receive both pieces in one call so the batch can't be\n * accidentally dropped.\n */\nexport function renderMarkdownTree(\n node: TokenTree,\n options: RenderTokenTreeOptions\n): {\n template: TemplateResult;\n batch: MarkdownRendererSlotDescriptor[];\n} {\n const batch: MarkdownRendererSlotDescriptor[] = [];\n let pluginSlotIndex = 0;\n // Memoized per node, not just counted. `renderFallback` runs inside a\n // lit-html `repeat()` callback, so it evaluates when lit-html commits the\n // template — and one render result gets committed again on any later Lit\n // update that leaves `renderedContent` alone. A bare counter would hand the\n // same token a fresh index on each commit, minting a second slot the very\n // next reconcile retires. First evaluation still assigns 0, 1, 2 in walk\n // order, so a single-commit render is unchanged.\n const pluginSlotIndexes = new WeakMap<TokenTree, number>();\n const template = renderTokenTree(node, {\n ...options,\n recordCustomRender: (descriptor) => batch.push(descriptor),\n pluginSlotCounter: {\n next: (forNode: TokenTree) => {\n const existing = pluginSlotIndexes.get(forNode);\n if (existing !== undefined) {\n return existing;\n }\n const index = pluginSlotIndex++;\n pluginSlotIndexes.set(forNode, index);\n return index;\n },\n },\n });\n return { template, batch };\n}\n\n/**\n * Converts TokenTree to Lit TemplateResult.\n *\n * Recursive renderer; external callers should use {@link renderMarkdownTree}\n * which collects the slot-descriptor batch.\n */\nexport function renderTokenTree(\n node: TokenTree,\n options: RenderTokenTreeOptions\n): TemplateResult {\n const { token, children } = node;\n const { context, sanitize } = options;\n\n // Handle raw HTML blocks and inline HTML\n if (token.type === 'html_block' || token.type === 'html_inline') {\n // Plugin-overridden html_block rules (rare but supported) — route through\n // the plugin's renderer before our default unsafeHTML pass-through.\n if (\n token.type === 'html_block' &&\n shouldDelegateToPluginRule(token, options.md) &&\n options.md\n ) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n\n let content = token.content || '';\n\n // Apply HTML sanitization if requested\n if (sanitize && content) {\n content = sanitizeHtmlContent(content);\n }\n\n return html`${unsafeHTML(content)}`;\n }\n\n // Handle split HTML blocks that wrap markdown siblings (e.g. <details>…</details>).\n if (token.type === 'html_container') {\n const openingHtml = token.content ?? '';\n const innerContent = renderChildTokenTrees(children, options, context);\n\n return html`<div\n class=\"cds-custom-aichat-markdown-html-container\"\n ${htmlContainer(openingHtml, innerContent, sanitize)}></div>`;\n }\n\n // Handle plain text content\n if (token.type === 'text') {\n return html`${token.content}`;\n }\n\n // Hard and soft line breaks. Handled before the tag-based dispatch because\n // hardbreak has tag=\"br\", which `renderWithStaticTag` does not know and would\n // route through the plugin-fallback slot machinery.\n if (token.type === 'hardbreak' || token.type === 'softbreak') {\n return token.type === 'softbreak' && options.md?.options.breaks === false\n ? html`${'\\n'}`\n : html`<br />`;\n }\n\n // Handle inline code spans\n if (token.type === 'code_inline') {\n if (shouldDelegateToPluginRule(token, options.md) && options.md) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n return html`<code>${token.content}</code>`;\n }\n\n // Handle fenced code blocks\n if (token.type === 'fence') {\n const language = token.info?.trim() ?? '';\n const {\n codeSnippetHighlight = true,\n codeSnippetShowLessText,\n codeSnippetShowMoreText,\n codeSnippetCopyButtonTooltipContent,\n codeSnippetGetLineCountText = defaultLineCountText,\n codeSnippetAriaLabelReadOnly,\n codeSnippetAriaLabelEditable,\n } = options;\n\n const defaultTemplate = html`<cds-custom-aichat-card is-flush>\n <div slot=\"body\">\n <cds-custom-aichat-code-snippet\n data-rounded\n .language=${language}\n .highlight=${codeSnippetHighlight}\n .detectLanguage=${true}\n .showLessText=${codeSnippetShowLessText}\n .showMoreText=${codeSnippetShowMoreText}\n .copyButtonTooltipContent=${codeSnippetCopyButtonTooltipContent}\n .getLineCountText=${codeSnippetGetLineCountText}\n .ariaLabelReadOnly=${codeSnippetAriaLabelReadOnly}\n .ariaLabelEditable=${codeSnippetAriaLabelEditable}\n .code=${token.content}></cds-custom-aichat-code-snippet>\n </div>\n </cds-custom-aichat-card>`;\n\n if (options.customRenderers?.codeBlock) {\n const slotName = slotNameFor('codeBlock', token as Token, options);\n options.recordCustomRender?.({\n slotName,\n kind: 'codeBlock',\n token: token as Token,\n data: {\n language,\n code: token.content ?? '',\n isStreaming: !!options.streaming,\n },\n });\n return html`<slot name=${slotName}>${defaultTemplate}</slot>`;\n }\n\n // Honor user-plugin `fence` overrides (markdown-it-mermaid, syntax\n // highlighters, etc.). customRenderer slot above wins when set.\n if (shouldDelegateToPluginRule(token, options.md) && options.md) {\n return renderFallback(\n token as Token,\n node,\n options.md,\n sanitize,\n options\n );\n }\n\n return defaultTemplate;\n }\n\n // Handle structural elements (paragraphs, headings, lists, etc.)\n const tag = token.tag;\n\n // Convert markdown-it attributes (array of [key, value]) into an object.\n const rawAttrs = (token.attrs || []).reduce(\n (acc, [key, value]) => {\n acc[key] = value;\n return acc;\n },\n {} as Record<string, string>\n );\n\n // Apply attribute sanitization if requested\n let attrs = rawAttrs;\n const isCustomElement = !!token.tag && token.tag.includes('-');\n if (sanitize && !isCustomElement) {\n attrs = sanitizeAttrs(rawAttrs);\n }\n\n // Set up context for child rendering\n let childContext = context;\n if (tag === 'thead') {\n childContext = { ...context, isInThead: true };\n }\n\n // Render child content\n let content: TemplateResult;\n\n if (children.length === 1 && children[0].token.type === 'text') {\n // Optimization: single text child doesn't need repeat wrapper\n content = html`${children[0].token.content}`;\n } else {\n content = renderChildTokenTrees(children, options, childContext);\n }\n\n // Unknown plugin-introduced tokens (no tag we recognize) — defer to\n // markdown-it's renderer so plugins that register md.renderer.rules[type]\n // (footnote, emoji, deflist, container, etc.) just work.\n if (!tag && options.md && !isNativelyHandled(token)) {\n return renderFallback(token as Token, node, options.md, sanitize, options);\n }\n\n // Handle tokens without HTML tags (just return content)\n if (!tag) {\n return content;\n }\n\n // Render the final HTML element with appropriate tag\n return renderWithStaticTag(\n tag,\n token as Token,\n content,\n attrs,\n options,\n childContext,\n node\n );\n}\n\n/**\n * Renders HTML elements with static tag names.\n */\nfunction renderWithStaticTag(\n tag: string,\n token: Token,\n content: TemplateResult,\n attrs: Record<string, string>,\n options: RenderTokenTreeOptions,\n _context?: { isInThead?: boolean },\n node?: TokenTree\n): TemplateResult {\n // Handle root token specially\n if (token.type === 'root') {\n return content;\n }\n\n const hasTaskListItems = (listNode?: TokenTree) =>\n !!listNode?.children?.some((child) => {\n if (child.token.type !== 'list_item_open') {\n return false;\n }\n\n const classAttr = child.token.attrs?.find(([key]) => key === 'class');\n return classAttr?.[1]?.split(/\\s+/).includes('task-list-item');\n });\n\n switch (tag) {\n // Basic block elements\n case 'p':\n return html`<p ${spread(attrs)}>${content}</p>`;\n\n case 'blockquote':\n return html`<blockquote ${spread(attrs)}>${content}</blockquote>`;\n\n case 'pre':\n return html`<pre ${spread(attrs)}>${content}</pre>`;\n\n case 'hr':\n return html`<hr ${spread(attrs)} />`;\n\n // Headings\n case 'h1':\n return html`<h1 ${spread(attrs)}>${content}</h1>`;\n case 'h2':\n return html`<h2 ${spread(attrs)}>${content}</h2>`;\n case 'h3':\n return html`<h3 ${spread(attrs)}>${content}</h3>`;\n case 'h4':\n return html`<h4 ${spread(attrs)}>${content}</h4>`;\n case 'h5':\n return html`<h5 ${spread(attrs)}>${content}</h5>`;\n case 'h6':\n return html`<h6 ${spread(attrs)}>${content}</h6>`;\n\n // Lists with Carbon components\n case 'ul': {\n const nested = token.level > 1;\n if (hasTaskListItems(node)) {\n return html`<ul ${spread(attrs)}>\n ${content}\n </ul>`;\n }\n return html`<p>\n <cds-custom-unordered-list ?nested=${nested} ${spread(attrs)}>\n ${content}\n </cds-custom-unordered-list>\n </p>`;\n }\n\n case 'ol': {\n const nested = token.level > 1;\n if (hasTaskListItems(node)) {\n return html`<ol ${spread(attrs)}>\n ${content}\n </ol>`;\n }\n return html`<p>\n <cds-custom-ordered-list native ?nested=${nested} ${spread(attrs)}>\n ${content}\n </cds-custom-ordered-list>\n </p>`;\n }\n\n case 'li': {\n const classList = attrs.class?.split(/\\s+/) ?? [];\n if (classList.includes('task-list-item')) {\n return html`<li ${spread(attrs)}>${content}</li>`;\n }\n return html`<cds-custom-list-item ${spread(attrs)}>${content}</cds-custom-list-item>`;\n }\n\n case 'cds-custom-checkbox': {\n const { checked, disabled, ...otherAttrs } = attrs;\n let isChecked = checked === 'true';\n\n // A configured `checklist` renderer can supply the checked state\n // (so a persisted toggle survives streaming re-renders) and makes the\n // boxes interactive.\n const checklist = options.customRenderers?.checklist;\n if (checklist?.getChecked && node) {\n const override = checklist.getChecked({\n id: otherAttrs['data-cds-aichat-checklist-id'] ?? '',\n label: extractText(node),\n checked: isChecked,\n token,\n });\n if (typeof override === 'boolean') {\n isChecked = override;\n }\n }\n\n const isDisabled = checklist\n ? false\n : disabled === undefined\n ? false\n : disabled === '' || disabled === 'true';\n\n return html`<cds-custom-checkbox\n ?checked=${isChecked}\n ?disabled=${isDisabled}\n ${spread(otherAttrs)}\n >${content}</cds-custom-checkbox\n >`;\n }\n\n // Inline formatting\n case 'strong':\n return html`<strong ${spread(attrs)}>${content}</strong>`;\n case 'em':\n return html`<em ${spread(attrs)}>${content}</em>`;\n case 'code':\n return html`<code ${spread(attrs)}>${content}</code>`;\n case 'del':\n return html`<del ${spread(attrs)}>${content}</del>`;\n case 'sub':\n return html`<sub ${spread(attrs)}>${content}</sub>`;\n case 'sup':\n return html`<sup ${spread(attrs)}>${content}</sup>`;\n case 'span':\n return html`<span ${spread(attrs)}>${content}</span>`;\n case 'i':\n return html`<i ${spread(attrs)}>${content}</i>`;\n case 'b':\n return html`<b ${spread(attrs)}>${content}</b>`;\n case 'small':\n return html`<small ${spread(attrs)}>${content}</small>`;\n case 'mark':\n return html`<mark ${spread(attrs)}>${content}</mark>`;\n case 'ins':\n return html`<ins ${spread(attrs)}>${content}</ins>`;\n case 's':\n return html`<s ${spread(attrs)}>${content}</s>`;\n case 'kbd':\n return html`<kbd ${spread(attrs)}>${content}</kbd>`;\n case 'var':\n return html`<var ${spread(attrs)}>${content}</var>`;\n case 'samp':\n return html`<samp ${spread(attrs)}>${content}</samp>`;\n case 'cite':\n return html`<cite ${spread(attrs)}>${content}</cite>`;\n case 'abbr':\n return html`<abbr ${spread(attrs)}>${content}</abbr>`;\n case 'dfn':\n return html`<dfn ${spread(attrs)}>${content}</dfn>`;\n case 'time':\n return html`<time ${spread(attrs)}>${content}</time>`;\n case 'q':\n return html`<q ${spread(attrs)}>${content}</q>`;\n\n // Links: optional consumer attribute transform, then automatic\n // target=\"_blank\" safety default.\n case 'a': {\n let linkAttrs: Record<string, string> = {\n ...attrs,\n target: attrs.target ?? '_blank',\n };\n\n let onClickHandler: MarkdownRendererLinkResult['onClick'];\n\n const linkRenderer = options.customRenderers?.link;\n\n if (linkRenderer && node) {\n const result = linkRenderer({\n href: attrs.href ?? '',\n title: attrs.title,\n text: extractText(node),\n attributes: { ...attrs },\n token,\n });\n\n if (result) {\n linkAttrs = {\n ...linkAttrs,\n ...(result.attributes ?? {}),\n };\n\n if (result.href !== undefined) {\n linkAttrs.href = result.href;\n }\n if (result.target !== undefined) {\n linkAttrs.target = result.target;\n }\n if (result.rel !== undefined) {\n linkAttrs.rel = result.rel;\n }\n\n // Consumer-supplied attributes are merged after the initial token\n // sanitization pass, so sanitize the final attribute set again.\n if (options.sanitize) {\n linkAttrs = sanitizeAttrs(linkAttrs);\n }\n\n onClickHandler = result.onClick;\n }\n }\n\n return html`<a ${spread(linkAttrs)} @click=${onClickHandler}\n >${content}</a\n >`;\n }\n\n // Self-closing image. A consumer `image` transform wins first (mirroring\n // how `codeBlock` wins over plugin `fence` rules); otherwise\n // plugin-introduced wrappers (e.g. image-figures) route through\n // `shouldDelegateToPluginRule` before falling back to a plain `<img>`.\n case 'img': {\n const imageRenderer = options.customRenderers?.image;\n if (imageRenderer && node) {\n let imgAttrs: Record<string, string> = attrs;\n const result = imageRenderer({\n src: attrs.src ?? '',\n alt: attrs.alt,\n title: attrs.title,\n attributes: { ...attrs },\n token,\n });\n if (result) {\n imgAttrs = { ...attrs, ...(result.attributes ?? {}) };\n if (result.src !== undefined) {\n imgAttrs.src = result.src;\n }\n if (options.sanitize) {\n imgAttrs = sanitizeAttrs(imgAttrs);\n }\n }\n return html`<img ${spread(imgAttrs)} />`;\n }\n if (node && options.md && shouldDelegateToPluginRule(token, options.md)) {\n return renderFallback(\n token,\n node,\n options.md,\n options.sanitize,\n options\n );\n }\n return html`<img ${spread(attrs)} />`;\n }\n\n // Tables with Carbon component and streaming support\n case 'table': {\n if (!node) {\n return html`<div>Error: Missing table data</div>`;\n }\n const slotName = options.customRenderers?.table\n ? slotNameFor('table', token, options)\n : undefined;\n return renderTable(\n token,\n node,\n attrs,\n options,\n renderTokenTree,\n slotName\n );\n }\n\n // Fallback for unknown tags. If we have the markdown-it instance available,\n // defer to its renderer for plugin-introduced container tags (footnote_block,\n // dl/dt/dd from deflist, custom containers, etc.). Otherwise fall back to\n // a generic <div>.\n default:\n if (options.md && node && !isNativelyHandled(token)) {\n return renderFallback(\n token,\n node,\n options.md,\n options.sanitize,\n options\n );\n }\n return html`<div ${spread(attrs)}>${content}</div>`;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;;;;;;;AAeG;AA0DH;;;;;;;;;;;AAWG;AACH,SAAS,WAAW,CAClB,IAA2B,EAC3B,KAAY,EACZ,OAA+B,EAAA;IAE/B,MAAM,SAAS,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,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/markdown-it-task-lists.js';
48
48
  * elements (cds-custom-unordered-list, cds-custom-list-item, cds-custom-aichat-table) and break
49
49
  * streaming-friendly per-child diffing for the subtree. Link tokens are
50
50
  * excluded because the native `<a>` dispatch injects `target="_blank"` for
51
- * chat-link safety.
51
+ * chat-link safety. Break tokens (softbreak, hardbreak) are excluded because
52
+ * delegation is priced per token — a slot host and a mount/unmount event pair
53
+ * for every line break — and because `./utils/html-helpers.ts` folds breaks
54
+ * into merged inline-HTML runs and `./utils/table-helpers.ts` flattens them to
55
+ * text, so the override would be honored in some positions and silently
56
+ * dropped in others.
52
57
  *
53
58
  * @internal
54
59
  */
@@ -1 +1 @@
1
- {"version":3,"file":"markdown-token-tree.js","sources":["../../../../src/components/markdown/src/markdown-token-tree.ts"],"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 * The parse/diff layer between raw markdown source and the renderer. Parses with markdown-it (built-in plugins plus any caller-supplied `markdownItPlugins`), builds a nested {@link TokenTree}, and diffs it against the previous tree so streaming updates can reuse stable subtrees.\n *\n * ### Why diff\n *\n * `diffTokenTree` reuses old nodes by `key` whenever the key matches. This is what lets `./markdown-renderer.ts`'s use of Lit's `repeat` directive keep DOM stable during streaming: each incoming chunk re-parses the full source, but matched keys reuse the prior subtree, so only the genuinely new tail differs.\n *\n * ### Why `cachedHtml`\n *\n * For the leaf token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES}, when a user plugin's renderer rule produces the HTML (via `./utils/plugin-fallback.ts`), the result is cached on the `TokenTree` node and carried forward by `diffTokenTree` whenever the underlying token's `content` / `attrs` / `info` are unchanged. A stable earlier-in-document fence/image/etc. therefore isn't re-rendered through the plugin's rule on every streaming chunk. The cache is tagged with the `MarkdownIt` instance that produced it; a plugin swap (which builds a fresh instance) invalidates the cache on read.\n *\n * The block comment on {@link PLUGIN_DELEGABLE_TOKEN_TYPES} explains why only those four token types are eligible for delegation.\n *\n * ### Related files\n *\n * - `./markdown-renderer.ts` — consumes the `TokenTree` and produces a Lit `TemplateResult`.\n * - `./utils/plugin-fallback.ts` — reads `cachedHtml` and {@link getPluginOverriddenRules} to drive the delegated-render flow.\n */\n\nimport MarkdownIt, { Token } from 'markdown-it';\n\nimport { markdownItAttrs } from './plugins/markdown-it-attrs';\nimport { markdownItHighlight } from './plugins/markdown-it-highlight';\nimport { markdownItTaskLists } from './plugins/markdown-it-task-lists';\n\n/**\n * Represents a node in the token tree structure.\n */\nexport interface TokenTree {\n /** Unique identifier for this node, used for efficient diffing */\n key: string;\n /** The original markdown-it token data */\n token: Partial<Token>;\n /** Child nodes for nested content */\n children: TokenTree[];\n /**\n * Cached HTML produced by `md.renderer.render()` for leaf tokens whose\n * renderer rule was overridden by a user plugin. Tagged with the\n * `MarkdownIt` instance that produced it so a plugin swap (which builds a\n * fresh instance) invalidates the cache on read. Inherited across\n * {@link diffTokenTree} when the token's content and attrs are unchanged so\n * the plugin's rule isn't re-invoked on every streaming chunk. Only\n * populated for token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES}.\n * @internal\n */\n cachedHtml?: { md: MarkdownIt; html: string };\n}\n\n/**\n * Token types whose renderer rule, when overridden by a user-supplied\n * markdown-it plugin, will be honored — instead of the native Lit dispatch.\n * All four are leaf tokens (`nesting === 0`) so the slice handed to\n * `md.renderer.render()` is a single token and the rendered HTML can be\n * safely cached on the {@link TokenTree} node.\n *\n * Container tokens (paragraph_open, heading_open, list_*_open, table_open)\n * are intentionally excluded: delegating them would erase Carbon custom\n * elements (cds-custom-unordered-list, cds-custom-list-item, cds-custom-aichat-table) and break\n * streaming-friendly per-child diffing for the subtree. Link tokens are\n * excluded because the native `<a>` dispatch injects `target=\"_blank\"` for\n * chat-link safety.\n *\n * @internal\n */\nexport const PLUGIN_DELEGABLE_TOKEN_TYPES: ReadonlySet<string> = new Set([\n 'fence',\n 'image',\n 'code_inline',\n 'html_block',\n]);\n\n/**\n * A markdown-it plugin reference. Either a bare plugin function or a\n * `[plugin, options]` / `[plugin, ...params]` tuple matching\n * `MarkdownIt.use(...)`.\n */\nexport type MarkdownItPlugin =\n | MarkdownIt.PluginSimple\n | [MarkdownIt.PluginWithOptions<unknown>, unknown]\n | [MarkdownIt.PluginWithParams, ...unknown[]];\n\n// Per-instance set of renderer-rule keys that user plugins overrode (or\n// added) relative to the snapshot taken after our built-in plugins ran.\n// WeakMap so cleanup follows the MarkdownIt instance's lifetime.\nconst pluginOverriddenRulesByMd = new WeakMap<\n MarkdownIt,\n ReadonlySet<string>\n>();\n\nconst EMPTY_RULE_SET: ReadonlySet<string> = new Set<string>();\n\n/**\n * Returns the set of renderer-rule keys that user-supplied plugins overrode\n * (or freshly added) on the given markdown-it instance, relative to the\n * baseline established after our built-in plugins (markdownItAttrs,\n * markdownItHighlight, markdownItTaskLists) ran. The renderer uses this to\n * decide which token types to route through `md.renderer.render()` instead\n * of native Lit dispatch. Returns an empty set for instances we didn't build.\n *\n * @internal\n */\nexport function getPluginOverriddenRules(md: MarkdownIt): ReadonlySet<string> {\n return pluginOverriddenRulesByMd.get(md) ?? EMPTY_RULE_SET;\n}\n\n/**\n * Builds a new markdown-it instance with the built-in plugins and any user-supplied\n * plugins applied on top. `options.html` selects whether raw HTML is parsed as HTML\n * (`true`, the default) or neutralized to inert escaped text (`false`, used when\n * {@link CDSAIChatMarkdown.removeHTML} is set). Both variants are built through this\n * same path so plugin application and overridden-rule snapshotting stay identical.\n *\n * Snapshots `md.renderer.rules` after the built-in plugins but before the user\n * plugins, then records the keys whose function reference changed (or whose\n * key was added) into {@link pluginOverriddenRulesByMd}.\n */\nfunction createMarkdownIt(\n plugins?: MarkdownItPlugin[],\n options: { html?: boolean } = {}\n): MarkdownIt {\n const md = new MarkdownIt('commonmark', {\n html: options.html ?? true,\n breaks: true,\n linkify: true,\n })\n .enable('table')\n .enable('strikethrough')\n .enable('linkify')\n .use(markdownItAttrs)\n .use(markdownItHighlight)\n .use(markdownItTaskLists);\n\n const baselineRules: Record<string, unknown> = {\n ...(md.renderer.rules as Record<string, unknown>),\n };\n\n for (const plugin of plugins ?? []) {\n if (Array.isArray(plugin)) {\n const [fn, ...args] = plugin;\n (md as MarkdownIt).use(fn as MarkdownIt.PluginWithParams, ...args);\n } else {\n md.use(plugin);\n }\n }\n\n const currentRules = md.renderer.rules as Record<string, unknown>;\n const overridden = new Set<string>();\n const allKeys = new Set<string>([\n ...Object.keys(baselineRules),\n ...Object.keys(currentRules),\n ]);\n for (const key of allKeys) {\n if (currentRules[key] !== baselineRules[key]) {\n overridden.add(key);\n }\n }\n pluginOverriddenRulesByMd.set(md, overridden);\n\n return md;\n}\n\n// Each plugin identity caches both an html-enabled and an html-disabled instance,\n// built lazily on first use. `removeHTML` selects the no-html variant.\ninterface MarkdownItVariants {\n html?: MarkdownIt;\n noHtml?: MarkdownIt;\n}\n\n// Cache for the no-plugins default instances.\nconst defaultMarkdownIt: MarkdownItVariants = {};\n\n// Cache keyed by plugin-array identity. WeakMap so plugin arrays that go out of\n// scope can be collected.\nconst markdownItCache = new WeakMap<MarkdownItPlugin[], MarkdownItVariants>();\n\n/**\n * Returns a (cached) markdown-it instance for the given plugin set, choosing the\n * html-enabled variant or the html-disabled (HTML-neutralizing) variant based on\n * `removeHtml`. Calling with the same `plugins` reference and `removeHtml` returns\n * the same instance.\n */\nexport function getMarkdownIt(\n plugins?: MarkdownItPlugin[],\n removeHtml = false\n): MarkdownIt {\n const variants =\n !plugins || plugins.length === 0\n ? defaultMarkdownIt\n : (markdownItCache.get(plugins) ??\n (() => {\n const created: MarkdownItVariants = {};\n markdownItCache.set(plugins, created);\n return created;\n })());\n\n const slot = removeHtml ? 'noHtml' : 'html';\n if (!variants[slot]) {\n variants[slot] = createMarkdownIt(plugins, { html: !removeHtml });\n }\n return variants[slot] as MarkdownIt;\n}\n\n// markdown-it treats a closing HTML tag and the next markdown line (ie. </div>\\n##Heading) as one HTML\n// block when there is no blank line between them. Insert an extra newline so the\n// following markdown is parsed as markdown, not swallowed into the HTML token.\nfunction normalizeHtmlBlockBoundaries(markdown: string): string {\n return markdown.replace(\n /(^|\\n)(\\s*<\\/\\s*[A-Za-z][\\w:-]*\\s*>)(\\r?\\n)(?=\\S)/g,\n '$1$2$3$3'\n );\n}\n\n// Fallback for html_block tokens that still bundle a closing tag with trailing\n// markdown on the next line. Split them so the closer stays HTML and the rest\n// is re-parsed as markdown.\nfunction splitHtmlBlockTrailingMarkdown(\n tokens: Token[],\n md: MarkdownIt\n): Token[] {\n return tokens.flatMap((token) => {\n if (token.type !== 'html_block') {\n return [token];\n }\n\n const trailingMarkdownMatch = token.content.match(\n /^(\\s*<\\/\\s*[A-Za-z][\\w:-]*\\s*>)(\\s*\\n)([\\s\\S]*\\S[\\s\\S]*)$/\n );\n\n if (!trailingMarkdownMatch) {\n return [token];\n }\n\n const [, closingHtml, leadingWhitespace, trailingMarkdown] =\n trailingMarkdownMatch;\n const htmlToken = {\n ...token,\n content: closingHtml,\n map: token.map ? [token.map[0], token.map[0] + 1] : token.map,\n } as Token;\n\n return [\n htmlToken,\n ...md.parse(`${leadingWhitespace}${trailingMarkdown}`, {}),\n ];\n });\n}\n\n/**\n * Parses markdown text into a flat array of markdown-it tokens using the given instance.\n *\n * When `removeHtml` is set, `md` is the html-disabled instance: raw HTML is\n * neutralized to inert escaped text (content preserved) and there are no HTML\n * blocks to normalize or split, so the boundary fixups are skipped.\n */\nfunction parseMarkdown(\n fullText: string,\n md: MarkdownIt,\n removeHtml: boolean\n): Token[] {\n if (removeHtml) {\n return md.parse(fullText, {});\n }\n const normalizedText = normalizeHtmlBlockBoundaries(fullText);\n return splitHtmlBlockTrailingMarkdown(md.parse(normalizedText, {}), md);\n}\n\n/**\n * Generates a unique string key for a markdown-it token.\n *\n * The key combines the token type, HTML tag, and source position to create\n * a stable identifier that can be used by Lit's repeat() directive for\n * efficient DOM updates.\n */\nfunction generateKey(token: Token): string {\n const map = token.map ? token.map.join('-') : '';\n return `${token.type}:${token.tag}:${map}`;\n}\n\n/**\n * Converts a flat list of markdown-it tokens into a tree.\n */\nexport function buildTokenTree(tokens: Token[]): TokenTree {\n // Create the root node that will contain all top-level content\n const root: TokenTree = {\n key: 'root',\n token: {\n type: 'root',\n tag: '',\n nesting: 0,\n level: 0,\n content: '',\n attrs: null,\n children: null,\n markup: '',\n block: true,\n hidden: false,\n map: null,\n info: '',\n meta: null,\n },\n children: [],\n };\n\n // Stack tracks the current nesting context while building the tree\n const stack: TokenTree[] = [root];\n\n tokens.forEach((token) => {\n // Create a new node for this token\n const node: TokenTree = {\n key: generateKey(token),\n token,\n children: [],\n };\n\n // Handle inline tokens that contain their own child tokens\n // (e.g., a paragraph containing bold, italic, and text tokens)\n if (token.type === 'inline' && token.children?.length) {\n node.children = buildTokenTree(token.children).children;\n }\n\n const current = stack[stack.length - 1];\n\n if (token.nesting === 1) {\n // Opening tag: add node to current container and descend into it\n current.children.push(node);\n stack.push(node);\n } else if (token.nesting === -1) {\n // Closing tag: exit current container\n stack.pop();\n } else {\n // Self-contained token: add to current container\n current.children.push(node);\n }\n });\n\n return root;\n}\n\nfunction attrsEqual(\n a: Token['attrs'] | undefined,\n b: Token['attrs'] | undefined\n): boolean {\n if (a === b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i][0] !== b[i][0] || a[i][1] !== b[i][1]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Compares two TokenTree structures and creates a new tree that reuses\n * unchanged nodes from the old tree.\n *\n * This optimization is crucial for performance when content is being streamed\n * or updated incrementally.\n */\nexport function diffTokenTree(\n oldTree: TokenTree | undefined,\n newTree: TokenTree\n): TokenTree {\n // If keys don't match, the entire subtree changed - use new tree\n if (!oldTree || oldTree.key !== newTree.key) {\n return newTree;\n }\n\n // Keys match so create merged tree reusing unchanged children\n const merged: TokenTree = {\n key: newTree.key,\n token: newTree.token,\n children: [],\n };\n\n // Carry forward the rendered-HTML cache for leaf tokens delegated to the\n // markdown-it renderer. Skip when the underlying token content, attrs, or\n // info changed (info is the fence's language string and drives the rendered\n // output for plugins like markdown-it-mermaid / syntax highlighters).\n if (\n oldTree.cachedHtml !== undefined &&\n typeof newTree.token.type === 'string' &&\n PLUGIN_DELEGABLE_TOKEN_TYPES.has(newTree.token.type) &&\n oldTree.token.content === newTree.token.content &&\n oldTree.token.info === newTree.token.info &&\n attrsEqual(\n oldTree.token.attrs ?? undefined,\n newTree.token.attrs ?? undefined\n )\n ) {\n merged.cachedHtml = oldTree.cachedHtml;\n }\n\n // Create lookup map of old children by key for efficient comparison\n const oldChildrenByKey = new Map(\n oldTree.children.map((child) => [child.key, child])\n );\n\n // Process each new child, reusing old ones where possible\n newTree.children.forEach((newChild) => {\n const oldChild = oldChildrenByKey.get(newChild.key);\n\n if (oldChild) {\n // Recursively diff matching children\n merged.children.push(diffTokenTree(oldChild, newChild));\n } else {\n // Use new child as-is\n merged.children.push(newChild);\n }\n });\n\n return merged;\n}\n\n/**\n * Result of {@link markdownToTokenTree}. Returns the parsed tree plus the\n * markdown-it instance used to produce it so the renderer can fall back to\n * `md.renderer.render()` for plugin-introduced tokens. The set of\n * plugin-overridden rules is read from the per-instance WeakMap via\n * {@link getPluginOverriddenRules} as needed.\n */\nexport interface MarkdownToTokenTreeResult {\n tree: TokenTree;\n md: MarkdownIt;\n}\n\n/**\n * Converts markdown into a tree with keys on it for Lit. The returned `md` is the\n * (cached) markdown-it instance keyed by `markdownItPlugins` identity and the\n * `removeHtml` flag (html-enabled vs html-neutralizing variant).\n */\nexport function markdownToTokenTree(\n markdown: string,\n lastTree: TokenTree | undefined,\n opts: { removeHtml?: boolean; markdownItPlugins?: MarkdownItPlugin[] } = {}\n): MarkdownToTokenTreeResult {\n const removeHtml = opts.removeHtml ?? false;\n const md = getMarkdownIt(opts.markdownItPlugins, removeHtml);\n const tokens = parseMarkdown(markdown, md, removeHtml);\n const tree = diffTokenTree(lastTree, buildTokenTree(tokens));\n return { tree, md };\n}\n\n/**\n * Parses markdown text into a flat array of markdown-it tokens using the default\n * plugin set. `allowHtml` is the inverse of the renderer's `removeHtml` flag.\n *\n * Used by the chat-side rich user message bubble (inline markdown rendering),\n * which needs the raw markdown-it tokens rather than a {@link TokenTree}.\n */\nexport function markdownToMarkdownItTokens(\n fullText: string,\n allowHtml = true\n): Token[] {\n const removeHtml = !allowHtml;\n return parseMarkdown(\n fullText,\n getMarkdownIt(undefined, removeHtml),\n removeHtml\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;;;;;;;;;AAiBG;AA+BH;;;;;;;;;;;;;;;AAeG;AACI,MAAM,4BAA4B,GAAwB,IAAI,GAAG,CAAC;IACvE,OAAO;IACP,OAAO;IACP,aAAa;IACb,YAAY;AACb,CAAA;AAYD;AACA;AACA;AACA,MAAM,yBAAyB,GAAG,IAAI,OAAO,EAG1C;AAEH,MAAM,cAAc,GAAwB,IAAI,GAAG,EAAU;AAE7D;;;;;;;;;AASG;AACG,SAAU,wBAAwB,CAAC,EAAc,EAAA;IACrD,OAAO,yBAAyB,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,cAAc;AAC5D;AAEA;;;;;;;;;;AAUG;AACH,SAAS,gBAAgB,CACvB,OAA4B,EAC5B,UAA8B,EAAE,EAAA;AAEhC,IAAA,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,YAAY,EAAE;AACtC,QAAA,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,IAAI;AAC1B,QAAA,MAAM,EAAE,IAAI;AACZ,QAAA,OAAO,EAAE,IAAI;KACd;SACE,MAAM,CAAC,OAAO;SACd,MAAM,CAAC,eAAe;SACtB,MAAM,CAAC,SAAS;SAChB,GAAG,CAAC,eAAe;SACnB,GAAG,CAAC,mBAAmB;SACvB,GAAG,CAAC,mBAAmB,CAAC;AAE3B,IAAA,MAAM,aAAa,GAA4B;AAC7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ACpC,UAAU,CACX;AACH;;"}
1
+ {"version":3,"file":"markdown-token-tree.js","sources":["../../../../src/components/markdown/src/markdown-token-tree.ts"],"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 * The parse/diff layer between raw markdown source and the renderer. Parses with markdown-it (built-in plugins plus any caller-supplied `markdownItPlugins`), builds a nested {@link TokenTree}, and diffs it against the previous tree so streaming updates can reuse stable subtrees.\n *\n * ### Why diff\n *\n * `diffTokenTree` reuses old nodes by `key` whenever the key matches. This is what lets `./markdown-renderer.ts`'s use of Lit's `repeat` directive keep DOM stable during streaming: each incoming chunk re-parses the full source, but matched keys reuse the prior subtree, so only the genuinely new tail differs.\n *\n * ### Why `cachedHtml`\n *\n * For the leaf token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES}, when a user plugin's renderer rule produces the HTML (via `./utils/plugin-fallback.ts`), the result is cached on the `TokenTree` node and carried forward by `diffTokenTree` whenever the underlying token's `content` / `attrs` / `info` are unchanged. A stable earlier-in-document fence/image/etc. therefore isn't re-rendered through the plugin's rule on every streaming chunk. The cache is tagged with the `MarkdownIt` instance that produced it; a plugin swap (which builds a fresh instance) invalidates the cache on read.\n *\n * The block comment on {@link PLUGIN_DELEGABLE_TOKEN_TYPES} explains why only those four token types are eligible for delegation.\n *\n * ### Related files\n *\n * - `./markdown-renderer.ts` — consumes the `TokenTree` and produces a Lit `TemplateResult`.\n * - `./utils/plugin-fallback.ts` — reads `cachedHtml` and {@link getPluginOverriddenRules} to drive the delegated-render flow.\n */\n\nimport MarkdownIt, { Token } from 'markdown-it';\n\nimport { markdownItAttrs } from './plugins/markdown-it-attrs';\nimport { markdownItHighlight } from './plugins/markdown-it-highlight';\nimport { markdownItTaskLists } from './plugins/markdown-it-task-lists';\n\n/**\n * Represents a node in the token tree structure.\n */\nexport interface TokenTree {\n /** Unique identifier for this node, used for efficient diffing */\n key: string;\n /** The original markdown-it token data */\n token: Partial<Token>;\n /** Child nodes for nested content */\n children: TokenTree[];\n /**\n * Cached HTML produced by `md.renderer.render()` for leaf tokens whose\n * renderer rule was overridden by a user plugin. Tagged with the\n * `MarkdownIt` instance that produced it so a plugin swap (which builds a\n * fresh instance) invalidates the cache on read. Inherited across\n * {@link diffTokenTree} when the token's content and attrs are unchanged so\n * the plugin's rule isn't re-invoked on every streaming chunk. Only\n * populated for token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES}.\n * @internal\n */\n cachedHtml?: { md: MarkdownIt; html: string };\n}\n\n/**\n * Token types whose renderer rule, when overridden by a user-supplied\n * markdown-it plugin, will be honored — instead of the native Lit dispatch.\n * All four are leaf tokens (`nesting === 0`) so the slice handed to\n * `md.renderer.render()` is a single token and the rendered HTML can be\n * safely cached on the {@link TokenTree} node.\n *\n * Container tokens (paragraph_open, heading_open, list_*_open, table_open)\n * are intentionally excluded: delegating them would erase Carbon custom\n * elements (cds-custom-unordered-list, cds-custom-list-item, cds-custom-aichat-table) and break\n * streaming-friendly per-child diffing for the subtree. Link tokens are\n * excluded because the native `<a>` dispatch injects `target=\"_blank\"` for\n * chat-link safety. Break tokens (softbreak, hardbreak) are excluded because\n * delegation is priced per token — a slot host and a mount/unmount event pair\n * for every line break — and because `./utils/html-helpers.ts` folds breaks\n * into merged inline-HTML runs and `./utils/table-helpers.ts` flattens them to\n * text, so the override would be honored in some positions and silently\n * dropped in others.\n *\n * @internal\n */\nexport const PLUGIN_DELEGABLE_TOKEN_TYPES: ReadonlySet<string> = new Set([\n 'fence',\n 'image',\n 'code_inline',\n 'html_block',\n]);\n\n/**\n * A markdown-it plugin reference. Either a bare plugin function or a\n * `[plugin, options]` / `[plugin, ...params]` tuple matching\n * `MarkdownIt.use(...)`.\n */\nexport type MarkdownItPlugin =\n | MarkdownIt.PluginSimple\n | [MarkdownIt.PluginWithOptions<unknown>, unknown]\n | [MarkdownIt.PluginWithParams, ...unknown[]];\n\n// Per-instance set of renderer-rule keys that user plugins overrode (or\n// added) relative to the snapshot taken after our built-in plugins ran.\n// WeakMap so cleanup follows the MarkdownIt instance's lifetime.\nconst pluginOverriddenRulesByMd = new WeakMap<\n MarkdownIt,\n ReadonlySet<string>\n>();\n\nconst EMPTY_RULE_SET: ReadonlySet<string> = new Set<string>();\n\n/**\n * Returns the set of renderer-rule keys that user-supplied plugins overrode\n * (or freshly added) on the given markdown-it instance, relative to the\n * baseline established after our built-in plugins (markdownItAttrs,\n * markdownItHighlight, markdownItTaskLists) ran. The renderer uses this to\n * decide which token types to route through `md.renderer.render()` instead\n * of native Lit dispatch. Returns an empty set for instances we didn't build.\n *\n * @internal\n */\nexport function getPluginOverriddenRules(md: MarkdownIt): ReadonlySet<string> {\n return pluginOverriddenRulesByMd.get(md) ?? EMPTY_RULE_SET;\n}\n\n/**\n * Builds a new markdown-it instance with the built-in plugins and any user-supplied\n * plugins applied on top. `options.html` selects whether raw HTML is parsed as HTML\n * (`true`, the default) or neutralized to inert escaped text (`false`, used when\n * {@link CDSAIChatMarkdown.removeHTML} is set). Both variants are built through this\n * same path so plugin application and overridden-rule snapshotting stay identical.\n *\n * Snapshots `md.renderer.rules` after the built-in plugins but before the user\n * plugins, then records the keys whose function reference changed (or whose\n * key was added) into {@link pluginOverriddenRulesByMd}.\n */\nfunction createMarkdownIt(\n plugins?: MarkdownItPlugin[],\n options: { html?: boolean } = {}\n): MarkdownIt {\n const md = new MarkdownIt('commonmark', {\n html: options.html ?? true,\n breaks: true,\n linkify: true,\n })\n .enable('table')\n .enable('strikethrough')\n .enable('linkify')\n .use(markdownItAttrs)\n .use(markdownItHighlight)\n .use(markdownItTaskLists);\n\n const baselineRules: Record<string, unknown> = {\n ...(md.renderer.rules as Record<string, unknown>),\n };\n\n for (const plugin of plugins ?? []) {\n if (Array.isArray(plugin)) {\n const [fn, ...args] = plugin;\n (md as MarkdownIt).use(fn as MarkdownIt.PluginWithParams, ...args);\n } else {\n md.use(plugin);\n }\n }\n\n const currentRules = md.renderer.rules as Record<string, unknown>;\n const overridden = new Set<string>();\n const allKeys = new Set<string>([\n ...Object.keys(baselineRules),\n ...Object.keys(currentRules),\n ]);\n for (const key of allKeys) {\n if (currentRules[key] !== baselineRules[key]) {\n overridden.add(key);\n }\n }\n pluginOverriddenRulesByMd.set(md, overridden);\n\n return md;\n}\n\n// Each plugin identity caches both an html-enabled and an html-disabled instance,\n// built lazily on first use. `removeHTML` selects the no-html variant.\ninterface MarkdownItVariants {\n html?: MarkdownIt;\n noHtml?: MarkdownIt;\n}\n\n// Cache for the no-plugins default instances.\nconst defaultMarkdownIt: MarkdownItVariants = {};\n\n// Cache keyed by plugin-array identity. WeakMap so plugin arrays that go out of\n// scope can be collected.\nconst markdownItCache = new WeakMap<MarkdownItPlugin[], MarkdownItVariants>();\n\n/**\n * Returns a (cached) markdown-it instance for the given plugin set, choosing the\n * html-enabled variant or the html-disabled (HTML-neutralizing) variant based on\n * `removeHtml`. Calling with the same `plugins` reference and `removeHtml` returns\n * the same instance.\n */\nexport function getMarkdownIt(\n plugins?: MarkdownItPlugin[],\n removeHtml = false\n): MarkdownIt {\n const variants =\n !plugins || plugins.length === 0\n ? defaultMarkdownIt\n : (markdownItCache.get(plugins) ??\n (() => {\n const created: MarkdownItVariants = {};\n markdownItCache.set(plugins, created);\n return created;\n })());\n\n const slot = removeHtml ? 'noHtml' : 'html';\n if (!variants[slot]) {\n variants[slot] = createMarkdownIt(plugins, { html: !removeHtml });\n }\n return variants[slot] as MarkdownIt;\n}\n\n// markdown-it treats a closing HTML tag and the next markdown line (ie. </div>\\n##Heading) as one HTML\n// block when there is no blank line between them. Insert an extra newline so the\n// following markdown is parsed as markdown, not swallowed into the HTML token.\nfunction normalizeHtmlBlockBoundaries(markdown: string): string {\n return markdown.replace(\n /(^|\\n)(\\s*<\\/\\s*[A-Za-z][\\w:-]*\\s*>)(\\r?\\n)(?=\\S)/g,\n '$1$2$3$3'\n );\n}\n\n// Fallback for html_block tokens that still bundle a closing tag with trailing\n// markdown on the next line. Split them so the closer stays HTML and the rest\n// is re-parsed as markdown.\nfunction splitHtmlBlockTrailingMarkdown(\n tokens: Token[],\n md: MarkdownIt\n): Token[] {\n return tokens.flatMap((token) => {\n if (token.type !== 'html_block') {\n return [token];\n }\n\n const trailingMarkdownMatch = token.content.match(\n /^(\\s*<\\/\\s*[A-Za-z][\\w:-]*\\s*>)(\\s*\\n)([\\s\\S]*\\S[\\s\\S]*)$/\n );\n\n if (!trailingMarkdownMatch) {\n return [token];\n }\n\n const [, closingHtml, leadingWhitespace, trailingMarkdown] =\n trailingMarkdownMatch;\n const htmlToken = {\n ...token,\n content: closingHtml,\n map: token.map ? [token.map[0], token.map[0] + 1] : token.map,\n } as Token;\n\n return [\n htmlToken,\n ...md.parse(`${leadingWhitespace}${trailingMarkdown}`, {}),\n ];\n });\n}\n\n/**\n * Parses markdown text into a flat array of markdown-it tokens using the given instance.\n *\n * When `removeHtml` is set, `md` is the html-disabled instance: raw HTML is\n * neutralized to inert escaped text (content preserved) and there are no HTML\n * blocks to normalize or split, so the boundary fixups are skipped.\n */\nfunction parseMarkdown(\n fullText: string,\n md: MarkdownIt,\n removeHtml: boolean\n): Token[] {\n if (removeHtml) {\n return md.parse(fullText, {});\n }\n const normalizedText = normalizeHtmlBlockBoundaries(fullText);\n return splitHtmlBlockTrailingMarkdown(md.parse(normalizedText, {}), md);\n}\n\n/**\n * Generates a unique string key for a markdown-it token.\n *\n * The key combines the token type, HTML tag, and source position to create\n * a stable identifier that can be used by Lit's repeat() directive for\n * efficient DOM updates.\n */\nfunction generateKey(token: Token): string {\n const map = token.map ? token.map.join('-') : '';\n return `${token.type}:${token.tag}:${map}`;\n}\n\n/**\n * Converts a flat list of markdown-it tokens into a tree.\n */\nexport function buildTokenTree(tokens: Token[]): TokenTree {\n // Create the root node that will contain all top-level content\n const root: TokenTree = {\n key: 'root',\n token: {\n type: 'root',\n tag: '',\n nesting: 0,\n level: 0,\n content: '',\n attrs: null,\n children: null,\n markup: '',\n block: true,\n hidden: false,\n map: null,\n info: '',\n meta: null,\n },\n children: [],\n };\n\n // Stack tracks the current nesting context while building the tree\n const stack: TokenTree[] = [root];\n\n tokens.forEach((token) => {\n // Create a new node for this token\n const node: TokenTree = {\n key: generateKey(token),\n token,\n children: [],\n };\n\n // Handle inline tokens that contain their own child tokens\n // (e.g., a paragraph containing bold, italic, and text tokens)\n if (token.type === 'inline' && token.children?.length) {\n node.children = buildTokenTree(token.children).children;\n }\n\n const current = stack[stack.length - 1];\n\n if (token.nesting === 1) {\n // Opening tag: add node to current container and descend into it\n current.children.push(node);\n stack.push(node);\n } else if (token.nesting === -1) {\n // Closing tag: exit current container\n stack.pop();\n } else {\n // Self-contained token: add to current container\n current.children.push(node);\n }\n });\n\n return root;\n}\n\nfunction attrsEqual(\n a: Token['attrs'] | undefined,\n b: Token['attrs'] | undefined\n): boolean {\n if (a === b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i][0] !== b[i][0] || a[i][1] !== b[i][1]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Compares two TokenTree structures and creates a new tree that reuses\n * unchanged nodes from the old tree.\n *\n * This optimization is crucial for performance when content is being streamed\n * or updated incrementally.\n */\nexport function diffTokenTree(\n oldTree: TokenTree | undefined,\n newTree: TokenTree\n): TokenTree {\n // If keys don't match, the entire subtree changed - use new tree\n if (!oldTree || oldTree.key !== newTree.key) {\n return newTree;\n }\n\n // Keys match so create merged tree reusing unchanged children\n const merged: TokenTree = {\n key: newTree.key,\n token: newTree.token,\n children: [],\n };\n\n // Carry forward the rendered-HTML cache for leaf tokens delegated to the\n // markdown-it renderer. Skip when the underlying token content, attrs, or\n // info changed (info is the fence's language string and drives the rendered\n // output for plugins like markdown-it-mermaid / syntax highlighters).\n if (\n oldTree.cachedHtml !== undefined &&\n typeof newTree.token.type === 'string' &&\n PLUGIN_DELEGABLE_TOKEN_TYPES.has(newTree.token.type) &&\n oldTree.token.content === newTree.token.content &&\n oldTree.token.info === newTree.token.info &&\n attrsEqual(\n oldTree.token.attrs ?? undefined,\n newTree.token.attrs ?? undefined\n )\n ) {\n merged.cachedHtml = oldTree.cachedHtml;\n }\n\n // Create lookup map of old children by key for efficient comparison\n const oldChildrenByKey = new Map(\n oldTree.children.map((child) => [child.key, child])\n );\n\n // Process each new child, reusing old ones where possible\n newTree.children.forEach((newChild) => {\n const oldChild = oldChildrenByKey.get(newChild.key);\n\n if (oldChild) {\n // Recursively diff matching children\n merged.children.push(diffTokenTree(oldChild, newChild));\n } else {\n // Use new child as-is\n merged.children.push(newChild);\n }\n });\n\n return merged;\n}\n\n/**\n * Result of {@link markdownToTokenTree}. Returns the parsed tree plus the\n * markdown-it instance used to produce it so the renderer can fall back to\n * `md.renderer.render()` for plugin-introduced tokens. The set of\n * plugin-overridden rules is read from the per-instance WeakMap via\n * {@link getPluginOverriddenRules} as needed.\n */\nexport interface MarkdownToTokenTreeResult {\n tree: TokenTree;\n md: MarkdownIt;\n}\n\n/**\n * Converts markdown into a tree with keys on it for Lit. The returned `md` is the\n * (cached) markdown-it instance keyed by `markdownItPlugins` identity and the\n * `removeHtml` flag (html-enabled vs html-neutralizing variant).\n */\nexport function markdownToTokenTree(\n markdown: string,\n lastTree: TokenTree | undefined,\n opts: { removeHtml?: boolean; markdownItPlugins?: MarkdownItPlugin[] } = {}\n): MarkdownToTokenTreeResult {\n const removeHtml = opts.removeHtml ?? false;\n const md = getMarkdownIt(opts.markdownItPlugins, removeHtml);\n const tokens = parseMarkdown(markdown, md, removeHtml);\n const tree = diffTokenTree(lastTree, buildTokenTree(tokens));\n return { tree, md };\n}\n\n/**\n * Parses markdown text into a flat array of markdown-it tokens using the default\n * plugin set. `allowHtml` is the inverse of the renderer's `removeHtml` flag.\n *\n * Used by the chat-side rich user message bubble (inline markdown rendering),\n * which needs the raw markdown-it tokens rather than a {@link TokenTree}.\n */\nexport function markdownToMarkdownItTokens(\n fullText: string,\n allowHtml = true\n): Token[] {\n const removeHtml = !allowHtml;\n return parseMarkdown(\n fullText,\n getMarkdownIt(undefined, removeHtml),\n removeHtml\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;;;;;;;;;AAiBG;AA+BH;;;;;;;;;;;;;;;;;;;;AAoBG;AACI,MAAM,4BAA4B,GAAwB,IAAI,GAAG,CAAC;IACvE,OAAO;IACP,OAAO;IACP,aAAa;IACb,YAAY;AACb,CAAA;AAYD;AACA;AACA;AACA,MAAM,yBAAyB,GAAG,IAAI,OAAO,EAG1C;AAEH,MAAM,cAAc,GAAwB,IAAI,GAAG,EAAU;AAE7D;;;;;;;;;AASG;AACG,SAAU,wBAAwB,CAAC,EAAc,EAAA;IACrD,OAAO,yBAAyB,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,cAAc;AAC5D;AAEA;;;;;;;;;;AAUG;AACH,SAAS,gBAAgB,CACvB,OAA4B,EAC5B,UAA8B,EAAE,EAAA;AAEhC,IAAA,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,YAAY,EAAE;AACtC,QAAA,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,IAAI;AAC1B,QAAA,MAAM,EAAE,IAAI;AACZ,QAAA,OAAO,EAAE,IAAI;KACd;SACE,MAAM,CAAC,OAAO;SACd,MAAM,CAAC,eAAe;SACtB,MAAM,CAAC,SAAS;SAChB,GAAG,CAAC,eAAe;SACnB,GAAG,CAAC,mBAAmB;SACvB,GAAG,CAAC,mBAAmB,CAAC;AAE3B,IAAA,MAAM,aAAa,GAA4B;AAC7C,QAAA,GAAI,EAAE,CAAC,QAAQ,CAAC,KAAiC;KAClD;AAED,IAAA,KAAK,MAAM,MAAM,IAAI,OAAO,IAAI,EAAE,EAAE;AAClC,QAAA,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;YACzB,MAAM,CAAC,EAAE,EAAE,GAAG,I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