@carbon/ai-chat-components 1.10.0-rc.1 → 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.
- package/custom-elements.json +114 -2
- package/es/components/markdown/index.d.ts +1 -0
- package/es/components/markdown/src/markdown-renderer.js +27 -1
- package/es/components/markdown/src/markdown-renderer.js.map +1 -1
- package/es/components/markdown/src/markdown-token-tree.js +6 -1
- package/es/components/markdown/src/markdown-token-tree.js.map +1 -1
- package/es/components/markdown/src/markdown.d.ts +5 -2
- package/es/components/markdown/src/markdown.js +66 -23
- package/es/components/markdown/src/markdown.js.map +1 -1
- package/es/components/markdown/src/utils/html-helpers.js +9 -2
- package/es/components/markdown/src/utils/html-helpers.js.map +1 -1
- package/es/components/markdown/src/utils/plugin-fallback.d.ts +6 -3
- package/es/components/markdown/src/utils/plugin-fallback.js +14 -5
- package/es/components/markdown/src/utils/plugin-fallback.js.map +1 -1
- package/es/components/markdown/src/utils/plugin-host-container.d.ts +160 -0
- package/es/components/markdown/src/utils/plugin-host-container.js +165 -0
- package/es/components/markdown/src/utils/plugin-host-container.js.map +1 -0
- package/es/react/markdown.js +2 -44
- package/es/react/markdown.js.map +1 -1
- package/es-custom/components/markdown/index.d.ts +1 -0
- package/es-custom/components/markdown/src/markdown-renderer.js +27 -1
- package/es-custom/components/markdown/src/markdown-renderer.js.map +1 -1
- package/es-custom/components/markdown/src/markdown-token-tree.js +6 -1
- package/es-custom/components/markdown/src/markdown-token-tree.js.map +1 -1
- package/es-custom/components/markdown/src/markdown.d.ts +5 -2
- package/es-custom/components/markdown/src/markdown.js +66 -23
- package/es-custom/components/markdown/src/markdown.js.map +1 -1
- package/es-custom/components/markdown/src/utils/html-helpers.js +9 -2
- package/es-custom/components/markdown/src/utils/html-helpers.js.map +1 -1
- package/es-custom/components/markdown/src/utils/plugin-fallback.d.ts +6 -3
- package/es-custom/components/markdown/src/utils/plugin-fallback.js +14 -5
- package/es-custom/components/markdown/src/utils/plugin-fallback.js.map +1 -1
- package/es-custom/components/markdown/src/utils/plugin-host-container.d.ts +160 -0
- package/es-custom/components/markdown/src/utils/plugin-host-container.js +165 -0
- package/es-custom/components/markdown/src/utils/plugin-host-container.js.map +1 -0
- package/es-custom/react/markdown.js +2 -44
- package/es-custom/react/markdown.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-fallback.js","sources":["../../../../../src/components/markdown/src/utils/plugin-fallback.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\nimport { html, TemplateResult } from 'lit';\nimport MarkdownIt, { Token } from 'markdown-it';\n\nimport {\n getPluginOverriddenRules,\n PLUGIN_DELEGABLE_TOKEN_TYPES,\n type TokenTree,\n} from '../markdown-token-tree.js';\nimport { sanitizeHtmlContent } from './lit-directives.js';\nimport { withInstanceNamespace } from './slot-names.js';\nimport type { RenderTokenTreeOptions } from '../markdown-renderer-types.js';\n\n/**\n * Slot-name prefix shared by every plugin-fallback descriptor. A render-scoped\n * sequence number follows, then the owning element's namespace (see\n * `./slot-names.js`); the markdown component uses this prefix when adopting the\n * light-DOM host so external observers can target plugin output with CSS or\n * query selectors.\n *\n * @internal\n */\nexport const PLUGIN_FALLBACK_SLOT_PREFIX =\n 'cds-aichat-markdown-renderer-pluginFallback';\n\n// Token types our hand-written renderer handles natively (no markdown-it\n// fallback needed).\nconst NATIVELY_HANDLED_TOKEN_TYPES = new Set<string>([\n 'root',\n 'text',\n 'code_inline',\n 'fence',\n 'html_block',\n 'html_inline',\n 'html_container',\n 'inline',\n 'hr',\n 'thematic_break',\n]);\n\n// HTML tags whose paired open/close (or self-contained leaf) is rendered by\n// `renderWithStaticTag`. Anything else falls through to the markdown-it\n// renderer fallback.\nconst NATIVELY_HANDLED_TAGS = new Set<string>([\n 'p',\n 'blockquote',\n 'pre',\n 'hr',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'ul',\n 'ol',\n 'li',\n 'cds-checkbox',\n 'strong',\n 'em',\n 'code',\n 'del',\n 'sub',\n 'sup',\n 'span',\n 'i',\n 'b',\n 'small',\n 'mark',\n 'ins',\n 's',\n 'kbd',\n 'var',\n 'samp',\n 'cite',\n 'abbr',\n 'dfn',\n 'time',\n 'q',\n 'a',\n 'table',\n 'img',\n // Table internals — their open/close pairs are walked into via children.\n 'thead',\n 'tbody',\n 'tr',\n 'th',\n 'td',\n // Task-list checkbox input element produced by markdown-it-task-lists.\n 'input',\n]);\n\n/**\n * True when the renderer can dispatch `token` itself (hand-written Lit\n * template). False when an unknown plugin-introduced token type or tag should\n * route through `md.renderer.render()`.\n */\nexport function isNativelyHandled(token: Partial<Token>): boolean {\n if (token.type && NATIVELY_HANDLED_TOKEN_TYPES.has(token.type)) {\n return true;\n }\n if (token.tag && NATIVELY_HANDLED_TAGS.has(token.tag)) {\n return true;\n }\n return false;\n}\n\n/**\n * True when the token's type is in the curated delegation allow-list and a\n * user-supplied markdown-it plugin has overridden (or added) the matching\n * `md.renderer.rules[type]`. Native dispatch sites consult this to decide\n * whether to route through `md.renderer.render()` instead of the hand-written\n * Lit template.\n */\nexport function shouldDelegateToPluginRule(\n token: Partial<Token>,\n md: MarkdownIt | undefined\n): boolean {\n if (!token.type || !md) {\n return false;\n }\n if (!PLUGIN_DELEGABLE_TOKEN_TYPES.has(token.type)) {\n return false;\n }\n return getPluginOverriddenRules(md).has(token.type);\n}\n\nfunction synthesizeCloseToken(openToken: Token): Token {\n const closeType = openToken.type.replace(/_open$/, '_close');\n return {\n type: closeType,\n tag: openToken.tag,\n nesting: -1,\n level: Math.max(0, openToken.level - 1),\n content: '',\n attrs: null,\n children: null,\n markup: openToken.markup,\n block: openToken.block,\n hidden: false,\n map: null,\n info: '',\n meta: null,\n } as Token;\n}\n\n/**\n * Re-emits the original flat markdown-it token sequence beneath `node` so the\n * sequence can be passed to `md.renderer.render()`. `inline` tokens are emitted\n * as-is (markdown-it's renderer reads their `.children` directly).\n */\nfunction flattenSubtree(node: TokenTree): Token[] {\n const tokens: Token[] = [];\n for (const child of node.children) {\n const t = child.token as Token;\n if (t.type === 'inline') {\n tokens.push(t);\n } else if (t.nesting === 1) {\n tokens.push(t);\n tokens.push(...flattenSubtree(child));\n tokens.push(synthesizeCloseToken(t));\n } else {\n tokens.push(t);\n }\n }\n return tokens;\n}\n\n/**\n * Builds the flat token slice to hand to `md.renderer.render()` for a token the\n * native renderer doesn't handle. Leaf tokens render alone; paired-container\n * opens reassemble `[open, ...children, close]` from the tree.\n */\nfunction sliceForFallback(token: Token, node: TokenTree): Token[] {\n if (token.nesting === 1) {\n return [token, ...flattenSubtree(node), synthesizeCloseToken(token)];\n }\n return [token];\n}\n\n/**\n * Renders an unknown token via markdown-it's HTML renderer and emits a named\n * `<slot>` placeholder. The markdown element adopts a light-DOM\n * `<div slot=\"…\">` host containing the sanitized HTML so consumer-supplied\n * CSS (e.g. KaTeX's stylesheet) reaches the rendered output.\n *\n * For leaf token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES} the rendered\n * HTML is cached on the {@link TokenTree} node and inherited across\n * `diffTokenTree` calls when the underlying token is unchanged — so a stable\n * earlier-in-document fence/image/etc. doesn't re-invoke the plugin's rule on\n * every streaming chunk. The cache is tagged with the `MarkdownIt` instance\n * that produced it; a plugin swap (which builds a fresh instance) invalidates\n * the cache automatically.\n */\nexport function renderFallback(\n token: Token,\n node: TokenTree,\n md: MarkdownIt,\n sanitize: boolean,\n options: RenderTokenTreeOptions\n): TemplateResult {\n let safe: string;\n if (node?.cachedHtml && node.cachedHtml.md === md) {\n safe = node.cachedHtml.html;\n } else {\n const slice = sliceForFallback(token, node);\n const htmlStr = md.renderer.render(slice, md.options, {});\n safe = sanitize ? sanitizeHtmlContent(htmlStr) : htmlStr;\n if (\n node &&\n typeof token.type === 'string' &&\n PLUGIN_DELEGABLE_TOKEN_TYPES.has(token.type)\n ) {\n node.cachedHtml = { md, html: safe };\n }\n }\n\n const index = options.pluginSlotCounter?.next() ?? 0;\n const slotName = withInstanceNamespace(\n `${PLUGIN_FALLBACK_SLOT_PREFIX}-${index}`,\n options\n );\n options.recordCustomRender?.({\n slotName,\n kind: 'pluginFallback',\n token,\n html: safe,\n isInline: token.block === false,\n });\n return html`<slot name=${slotName}></slot>`;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;AAcH;;;;;;;;AAQG;AACI,MAAM,2BAA2B,GACtC;AAEF;AACA;AACA,MAAM,4BAA4B,GAAG,IAAI,GAAG,CAAS;IACnD,MAAM;IACN,MAAM;IACN,aAAa;IACb,OAAO;IACP,YAAY;IACZ,aAAa;IACb,gBAAgB;IAChB,QAAQ;IACR,IAAI;IACJ,gBAAgB;AACjB,CAAA,CAAC;AAEF;AACA;AACA;AACA,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAS;IAC5C,GAAG;IACH,YAAY;IACZ,KAAK;IACL,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,cAAc;IACd,QAAQ;IACR,IAAI;IACJ,MAAM;IACN,KAAK;IACL,KAAK;IACL,KAAK;IACL,MAAM;IACN,GAAG;IACH,GAAG;IACH,OAAO;IACP,MAAM;IACN,KAAK;IACL,GAAG;IACH,KAAK;IACL,KAAK;IACL,MAAM;IACN,MAAM;IACN,MAAM;IACN,KAAK;IACL,MAAM;IACN,GAAG;IACH,GAAG;IACH,OAAO;IACP,KAAK;;IAEL,OAAO;IACP,OAAO;IACP,IAAI;IACJ,IAAI;IACJ,IAAI;;IAEJ,OAAO;AACR,CAAA,CAAC;AAEF;;;;AAIG;AACG,SAAU,iBAAiB,CAAC,KAAqB,EAAA;AACrD,IAAA,IAAI,KAAK,CAAC,IAAI,IAAI,4BAA4B,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M,OAAO,GAAG,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC;AACzD,QAAA,IAAI,GAAG,QAAQ,GAAG,mBAAmB,CAAC,OAAO,CAAC,GAAG,OAAO;AACxD,QAAA,IACE,IAAI;AACJ,YAAA,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;YAC9B,4BAA4B,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAC5C;YACA,IAAI,CAAC,UAAU,GAAG,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE;QACtC;IACF;IAEA,MAAM,KAAK,GAAG,OAAO,CAAC,iBAAiB,EAAE,IAAI,EAAE,IAAI,CAAC;AACpD,IAAA,MAAM,QAAQ,GAAG,qBAAqB,CACpC,CAAA,EAAG,2BAA2B,CAAA,CAAA,EAAI,KAAK,CAAA,CAAE,EACzC,OAAO,CACR;IACD,OAAO,CAAC,kBAAkB,GAAG;QAC3B,QAAQ;AACR,QAAA,IAAI,EAAE,gBAAgB;QACtB,KAAK;AACL,QAAA,IAAI,EAAE,IAAI;AACV,QAAA,QAAQ,EAAE,KAAK,CAAC,KAAK,KAAK,KAAK;AAChC,KAAA,CAAC;AACF,IAAA,OAAO,IAAI,CAAA,CAAA,WAAA,EAAc,QAAQ,UAAU;AAC7C;;"}
|
|
1
|
+
{"version":3,"file":"plugin-fallback.js","sources":["../../../../../src/components/markdown/src/utils/plugin-fallback.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\nimport { html, TemplateResult } from 'lit';\nimport MarkdownIt, { Token } from 'markdown-it';\n\nimport {\n getPluginOverriddenRules,\n PLUGIN_DELEGABLE_TOKEN_TYPES,\n type TokenTree,\n} from '../markdown-token-tree.js';\nimport { sanitizeHtmlContent } from './lit-directives.js';\nimport { withInstanceNamespace } from './slot-names.js';\nimport type { RenderTokenTreeOptions } from '../markdown-renderer-types.js';\n\n/**\n * Slot-name prefix shared by every plugin-fallback descriptor. A render-scoped\n * sequence number follows, then the owning element's namespace (see\n * `./slot-names.js`); the markdown component uses this prefix when adopting the\n * light-DOM host so external observers can target plugin output with CSS or\n * query selectors.\n *\n * @internal\n */\nexport const PLUGIN_FALLBACK_SLOT_PREFIX =\n 'cds-aichat-markdown-renderer-pluginFallback';\n\n// Token types our hand-written renderer handles natively (no markdown-it\n// fallback needed).\nconst NATIVELY_HANDLED_TOKEN_TYPES = new Set<string>([\n 'root',\n 'text',\n 'code_inline',\n 'fence',\n 'html_block',\n 'html_inline',\n 'html_container',\n 'inline',\n 'hr',\n 'thematic_break',\n]);\n\n// HTML tags whose paired open/close (or self-contained leaf) is rendered by\n// `renderWithStaticTag`. Anything else falls through to the markdown-it\n// renderer fallback.\nconst NATIVELY_HANDLED_TAGS = new Set<string>([\n 'p',\n 'blockquote',\n 'pre',\n 'hr',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'ul',\n 'ol',\n 'li',\n 'cds-checkbox',\n 'strong',\n 'em',\n 'code',\n 'del',\n 'sub',\n 'sup',\n 'span',\n 'i',\n 'b',\n 'small',\n 'mark',\n 'ins',\n 's',\n 'kbd',\n 'var',\n 'samp',\n 'cite',\n 'abbr',\n 'dfn',\n 'time',\n 'q',\n 'a',\n 'table',\n 'img',\n // Table internals — their open/close pairs are walked into via children.\n 'thead',\n 'tbody',\n 'tr',\n 'th',\n 'td',\n // Task-list checkbox input element produced by markdown-it-task-lists.\n 'input',\n]);\n\n/**\n * True when the renderer can dispatch `token` itself (hand-written Lit\n * template). False when an unknown plugin-introduced token type or tag should\n * route through `md.renderer.render()`.\n */\nexport function isNativelyHandled(token: Partial<Token>): boolean {\n if (token.type && NATIVELY_HANDLED_TOKEN_TYPES.has(token.type)) {\n return true;\n }\n if (token.tag && NATIVELY_HANDLED_TAGS.has(token.tag)) {\n return true;\n }\n return false;\n}\n\n/**\n * True when the token's type is in the curated delegation allow-list and a\n * user-supplied markdown-it plugin has overridden (or added) the matching\n * `md.renderer.rules[type]`. Native dispatch sites consult this to decide\n * whether to route through `md.renderer.render()` instead of the hand-written\n * Lit template.\n */\nexport function shouldDelegateToPluginRule(\n token: Partial<Token>,\n md: MarkdownIt | undefined\n): boolean {\n if (!token.type || !md) {\n return false;\n }\n if (!PLUGIN_DELEGABLE_TOKEN_TYPES.has(token.type)) {\n return false;\n }\n return getPluginOverriddenRules(md).has(token.type);\n}\n\nfunction synthesizeCloseToken(openToken: Token): Token {\n const closeType = openToken.type.replace(/_open$/, '_close');\n return {\n type: closeType,\n tag: openToken.tag,\n nesting: -1,\n level: Math.max(0, openToken.level - 1),\n content: '',\n attrs: null,\n children: null,\n markup: openToken.markup,\n block: openToken.block,\n hidden: false,\n map: null,\n info: '',\n meta: null,\n } as Token;\n}\n\n/**\n * Re-emits the original flat markdown-it token sequence beneath `node` so the\n * sequence can be passed to `md.renderer.render()`. `inline` tokens are emitted\n * as-is (markdown-it's renderer reads their `.children` directly).\n */\nfunction flattenSubtree(node: TokenTree): Token[] {\n const tokens: Token[] = [];\n for (const child of node.children) {\n const t = child.token as Token;\n if (t.type === 'inline') {\n tokens.push(t);\n } else if (t.nesting === 1) {\n tokens.push(t);\n tokens.push(...flattenSubtree(child));\n tokens.push(synthesizeCloseToken(t));\n } else {\n tokens.push(t);\n }\n }\n return tokens;\n}\n\n/**\n * Builds the flat token slice to hand to `md.renderer.render()` for a token the\n * native renderer doesn't handle. Leaf tokens render alone; paired-container\n * opens reassemble `[open, ...children, close]` from the tree.\n */\nfunction sliceForFallback(token: Token, node: TokenTree): Token[] {\n if (token.nesting === 1) {\n return [token, ...flattenSubtree(node), synthesizeCloseToken(token)];\n }\n return [token];\n}\n\n/**\n * Renders an unknown token via markdown-it's HTML renderer and emits a named\n * `<slot>` placeholder carrying the token's text as its fallback content. The\n * markdown element adopts a light-DOM `<div slot=\"…\">` host containing the\n * sanitized HTML so consumer-supplied CSS (e.g. KaTeX's stylesheet) reaches the\n * rendered output; the fallback is what a reader sees if that host never\n * arrives — a container claimed the slot and no forwarder was minted — so a\n * stranded host degrades to plain text instead of vanishing.\n *\n * For leaf token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES} the rendered\n * HTML is cached on the {@link TokenTree} node and inherited across\n * `diffTokenTree` calls when the underlying token is unchanged — so a stable\n * earlier-in-document fence/image/etc. doesn't re-invoke the plugin's rule on\n * every streaming chunk. The cache is tagged with the `MarkdownIt` instance\n * that produced it; a plugin swap (which builds a fresh instance) invalidates\n * the cache automatically.\n */\nexport function renderFallback(\n token: Token,\n node: TokenTree,\n md: MarkdownIt,\n sanitize: boolean,\n options: RenderTokenTreeOptions\n): TemplateResult {\n let safe: string;\n if (node?.cachedHtml && node.cachedHtml.md === md) {\n safe = node.cachedHtml.html;\n } else {\n const slice = sliceForFallback(token, node);\n const htmlStr = md.renderer.render(slice, md.options, {});\n safe = sanitize ? sanitizeHtmlContent(htmlStr) : htmlStr;\n if (\n node &&\n typeof token.type === 'string' &&\n PLUGIN_DELEGABLE_TOKEN_TYPES.has(token.type)\n ) {\n node.cachedHtml = { md, html: safe };\n }\n }\n\n const index = options.pluginSlotCounter?.next(node) ?? 0;\n const slotName = withInstanceNamespace(\n `${PLUGIN_FALLBACK_SLOT_PREFIX}-${index}`,\n options\n );\n options.recordCustomRender?.({\n slotName,\n kind: 'pluginFallback',\n token,\n html: safe,\n isInline: token.block === false,\n });\n // Text, not `safe`: the rendered markup already exists once as the light-DOM\n // host, and duplicating it inside the slot doubles the DOM of a plugin-heavy\n // message — 40 KaTeX expressions measured 3,288 extra elements. Prefer the\n // author's own source, which is what a formula or diagram token carries, and\n // fall back to the output's text for marker tokens that carry no source.\n const fallbackText = token.content || safe.replace(/<[^>]*>/g, '');\n return html`<slot name=${slotName}>${fallbackText}</slot>`;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;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AAC,EAC5C;YACA,IAAI,CAAC,UAAU,GAAG,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE;QACtC;IACF;AAEA,IAAA,MAAM,KAAK,GAAG,OAAO,CAAC,iBAAiB,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;AACxD,IAAA,MAAM,QAAQ,GAAG,qBAAqB,CACpC,CAAA,EAAG,2BAA2B,CAAA,CAAA,EAAI,KAAK,CAAA,CAAE,EACzC,OAAO,CACR;IACD,OAAO,CAAC,kBAAkB,GAAG;QAC3B,QAAQ;AACR,QAAA,IAAI,EAAE,gBAAgB;QACtB,KAAK;AACL,QAAA,IAAI,EAAE,IAAI;AACV,QAAA,QAAQ,EAAE,KAAK,CAAC,KAAK,KAAK,KAAK;AAChC,KAAA,CAAC;;;;;;AAMF,IAAA,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;AAClE,IAAA,OAAO,IAAI,CAAA,CAAA,WAAA,EAAc,QAAQ,CAAA,CAAA,EAAI,YAAY,SAAS;AAC5D;;"}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The container half of the plugin-host protocol.
|
|
3
|
+
*
|
|
4
|
+
* `<cds-aichat-markdown>` offers a host for plugin output to whichever chat
|
|
5
|
+
* element is outermost, over three composed events — `-mount`, `-update` and
|
|
6
|
+
* `-unmount`. Accepting the offer means calling `preventDefault()` on the
|
|
7
|
+
* mount event and putting the host somewhere consumer-loaded CSS can reach it,
|
|
8
|
+
* which the markdown element's own light DOM is not: it sits inside the chat's
|
|
9
|
+
* shadow root. A plugin-fallback offer hands over an HTML string this
|
|
10
|
+
* controller renders into a host it creates; a `customRenderers` offer hands
|
|
11
|
+
* over a live element this controller only re-parents.
|
|
12
|
+
*
|
|
13
|
+
* A container supplies only the element hosts are appended to, and whatever
|
|
14
|
+
* policy the framework cannot infer.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Mount detail for plugin output the element hands over as an HTML string.
|
|
18
|
+
*/
|
|
19
|
+
export interface MarkdownPluginFallbackMountDetail {
|
|
20
|
+
/** Marks the payload as an HTML string rather than a live element. */
|
|
21
|
+
kind: 'pluginFallback';
|
|
22
|
+
/**
|
|
23
|
+
* Name to put on the host's `slot` attribute, and the key the matching
|
|
24
|
+
* `-update` and `-unmount` events arrive under. Unique across every markdown
|
|
25
|
+
* element on the page, and reused across renders while the token stays put,
|
|
26
|
+
* so a streaming message rewrites one host instead of growing a new one per
|
|
27
|
+
* chunk. Treat the value as opaque; its format is not part of the API.
|
|
28
|
+
*/
|
|
29
|
+
slotName: string;
|
|
30
|
+
/**
|
|
31
|
+
* The plugin rule's rendered HTML, to assign to the host's `innerHTML`.
|
|
32
|
+
*
|
|
33
|
+
* DOMPurify runs over it only when the markdown element has `sanitize-html`
|
|
34
|
+
* set, and that setting is off by default. `remove-html` does not stand in
|
|
35
|
+
* for it either — that one escapes HTML written in the markdown source and
|
|
36
|
+
* never filters what a plugin's renderer rule emits. Treat the string as
|
|
37
|
+
* exactly as trustworthy as the markdown-it plugins the page registered.
|
|
38
|
+
*/
|
|
39
|
+
html: string;
|
|
40
|
+
/**
|
|
41
|
+
* True when the plugin's token is inline, such as a `math_inline` span.
|
|
42
|
+
* Picks the host tag — `span` when true, so the output stays in paragraph
|
|
43
|
+
* flow, `div` when false — and gates the block spacing that matches the
|
|
44
|
+
* markdown element's own stack gap.
|
|
45
|
+
*/
|
|
46
|
+
isInline: boolean;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Mount detail for a `customRenderers` host. It carries a live element the
|
|
50
|
+
* markdown element created, keeps writing to across renders, and removes.
|
|
51
|
+
* Claiming it means re-parenting that element into your own light DOM,
|
|
52
|
+
* synchronously, and nothing else: never rewrite its content, never style it,
|
|
53
|
+
* never remove it. The markdown element renders the `<slot>` hop that projects
|
|
54
|
+
* it back.
|
|
55
|
+
*/
|
|
56
|
+
export interface MarkdownCustomRendererMountDetail {
|
|
57
|
+
/** Marks the payload as a live element rather than an HTML string. */
|
|
58
|
+
kind: 'customRenderer';
|
|
59
|
+
/**
|
|
60
|
+
* Name already set on `element`'s `slot` attribute, and the key the matching
|
|
61
|
+
* `-unmount` event arrives under. Page-unique, reused across renders and
|
|
62
|
+
* opaque, like the plugin-fallback name. No `-update` event follows this
|
|
63
|
+
* one: the markdown element writes the consumer's node into `element`
|
|
64
|
+
* itself.
|
|
65
|
+
*/
|
|
66
|
+
slotName: string;
|
|
67
|
+
/**
|
|
68
|
+
* The host to re-parent. The markdown element created it, replaces its
|
|
69
|
+
* children on every render, and removes it when the renderer stops matching
|
|
70
|
+
* — a claimant only moves it.
|
|
71
|
+
*/
|
|
72
|
+
element: HTMLElement;
|
|
73
|
+
/**
|
|
74
|
+
* True when the claimed output is inline flow content. Always `false` here:
|
|
75
|
+
* the markdown element hosts every `customRenderers` result in a `<div>` it
|
|
76
|
+
* created, so a claimant has no host tag to choose. Declared on both members
|
|
77
|
+
* so a listener can read it before narrowing on `kind`.
|
|
78
|
+
*/
|
|
79
|
+
isInline: boolean;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The `cds-aichat-markdown-plugin-host-mount` detail, discriminated on `kind`.
|
|
83
|
+
*
|
|
84
|
+
* Narrow on `kind`, never on which of `html` / `element` is present — the two
|
|
85
|
+
* members deliberately declare only their own fields, so reading the wrong one
|
|
86
|
+
* is a compile error rather than a silent `undefined`.
|
|
87
|
+
*/
|
|
88
|
+
export type MarkdownPluginHostMountDetail = MarkdownPluginFallbackMountDetail | MarkdownCustomRendererMountDetail;
|
|
89
|
+
/**
|
|
90
|
+
* A mount detail as it arrives on the wire, `kind` included or not.
|
|
91
|
+
*
|
|
92
|
+
* `kind` is newer than the events themselves, and `@carbon/ai-chat` depends on
|
|
93
|
+
* this package through a caret range, so a listener can still receive the
|
|
94
|
+
* original shape from an older build. Pass anything you receive through
|
|
95
|
+
* `resolveMarkdownPluginHostMountDetail`, exported from
|
|
96
|
+
* `@carbon/ai-chat-components/es/components/markdown/src/utils/plugin-host-container.js`,
|
|
97
|
+
* and narrow on the result.
|
|
98
|
+
*/
|
|
99
|
+
export type MarkdownPluginHostMountDetailInput = MarkdownPluginHostMountDetail | Omit<MarkdownPluginFallbackMountDetail, 'kind'> | Omit<MarkdownCustomRendererMountDetail, 'kind'>;
|
|
100
|
+
/**
|
|
101
|
+
* Fills in `kind` for a detail emitted before the field existed.
|
|
102
|
+
*
|
|
103
|
+
* The one place the payload's shape is still consulted, and only when there is
|
|
104
|
+
* nothing else to go on. Delete it once the floor on `@carbon/ai-chat-components`
|
|
105
|
+
* rises past the release that added `kind`.
|
|
106
|
+
*/
|
|
107
|
+
export declare function resolveMarkdownPluginHostMountDetail(detail: MarkdownPluginHostMountDetailInput): MarkdownPluginHostMountDetail;
|
|
108
|
+
export interface MarkdownPluginHostControllerOptions {
|
|
109
|
+
/**
|
|
110
|
+
* Called with a fresh array whenever the set of slot names this surface
|
|
111
|
+
* should forward inward changes. Surfaces one shadow boundary from the
|
|
112
|
+
* markdown element render no forwarder of their own and omit it — the React
|
|
113
|
+
* `ChatContainer` is the one in this repo.
|
|
114
|
+
*
|
|
115
|
+
* Both kinds, and including names this surface declined to host: a container
|
|
116
|
+
* nested inside an outer chat element still has to forward the slot the
|
|
117
|
+
* outer one is hosting. The innermost hop — into the markdown element's own
|
|
118
|
+
* shadow slot — is never one of these; the element mints that one, for
|
|
119
|
+
* either kind, in the pass that read the claim.
|
|
120
|
+
*/
|
|
121
|
+
onSlotNamesChange?: (slotNames: string[]) => void;
|
|
122
|
+
/**
|
|
123
|
+
* Return `true` to forward the slot without hosting it, because an outer
|
|
124
|
+
* chat element will. Omitted by surfaces that are always outermost.
|
|
125
|
+
*/
|
|
126
|
+
shouldDefer?: (event: Event) => boolean;
|
|
127
|
+
}
|
|
128
|
+
export interface MarkdownPluginHostController {
|
|
129
|
+
/** Subscribes to the three events. Safe to call again without disconnecting. */
|
|
130
|
+
connect(): void;
|
|
131
|
+
/**
|
|
132
|
+
* Unsubscribes and removes the hosts this controller created. Relocated
|
|
133
|
+
* `customRenderers` elements are left parented — they belong to the markdown
|
|
134
|
+
* element, and as children of `target` they ride along with a DOM move.
|
|
135
|
+
* Forwarded slot names survive too.
|
|
136
|
+
*/
|
|
137
|
+
disconnect(): void;
|
|
138
|
+
/**
|
|
139
|
+
* Plugin-fallback hosts this controller created, keyed by slot name.
|
|
140
|
+
* Relocated `customRenderers` elements are deliberately absent.
|
|
141
|
+
*/
|
|
142
|
+
readonly hosts: ReadonlyMap<string, HTMLElement>;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Answers the plugin-host offer on `target`'s behalf, hosting accepted offers
|
|
146
|
+
* as slot-attributed children of `target`.
|
|
147
|
+
*
|
|
148
|
+
* `target` is both the listener and the host parent because in every chat
|
|
149
|
+
* surface they are the same element — the offer is claimed by whichever chat
|
|
150
|
+
* element is outermost, and that is the element whose light DOM is page DOM.
|
|
151
|
+
*
|
|
152
|
+
* Not part of this package's advertised surface: it is deliberately absent from
|
|
153
|
+
* `components/markdown/index.ts`, where only the detail types above are
|
|
154
|
+
* exported. It is not marked with the internal JSDoc tag either — this package
|
|
155
|
+
* compiles with `stripInternal`, which would drop the declaration from the
|
|
156
|
+
* emitted `.d.ts`, and every caller lives in the sibling package and resolves
|
|
157
|
+
* its types through exactly that file. (Do not write that tag's name anywhere
|
|
158
|
+
* in this comment: `stripInternal` matches the string, not just a real tag.)
|
|
159
|
+
*/
|
|
160
|
+
export declare function createMarkdownPluginHostController(target: HTMLElement, options?: MarkdownPluginHostControllerOptions): MarkdownPluginHostController;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright IBM Corp. 2025
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the Apache-2.0 license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/*
|
|
9
|
+
* Copyright IBM Corp. 2026
|
|
10
|
+
*
|
|
11
|
+
* This source code is licensed under the Apache-2.0 license found in the
|
|
12
|
+
* LICENSE file in the root directory of this source tree.
|
|
13
|
+
*
|
|
14
|
+
* @license
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Fills in `kind` for a detail emitted before the field existed.
|
|
18
|
+
*
|
|
19
|
+
* The one place the payload's shape is still consulted, and only when there is
|
|
20
|
+
* nothing else to go on. Delete it once the floor on `@carbon/ai-chat-components`
|
|
21
|
+
* rises past the release that added `kind`.
|
|
22
|
+
*/
|
|
23
|
+
function resolveMarkdownPluginHostMountDetail(detail) {
|
|
24
|
+
if ('kind' in detail) {
|
|
25
|
+
return detail;
|
|
26
|
+
}
|
|
27
|
+
return 'element' in detail
|
|
28
|
+
? { ...detail, kind: 'customRenderer' }
|
|
29
|
+
: { ...detail, kind: 'pluginFallback' };
|
|
30
|
+
}
|
|
31
|
+
const MOUNT = 'cds-aichat-markdown-plugin-host-mount';
|
|
32
|
+
const UPDATE = 'cds-aichat-markdown-plugin-host-update';
|
|
33
|
+
const UNMOUNT = 'cds-aichat-markdown-plugin-host-unmount';
|
|
34
|
+
/**
|
|
35
|
+
* Answers the plugin-host offer on `target`'s behalf, hosting accepted offers
|
|
36
|
+
* as slot-attributed children of `target`.
|
|
37
|
+
*
|
|
38
|
+
* `target` is both the listener and the host parent because in every chat
|
|
39
|
+
* surface they are the same element — the offer is claimed by whichever chat
|
|
40
|
+
* element is outermost, and that is the element whose light DOM is page DOM.
|
|
41
|
+
*
|
|
42
|
+
* Not part of this package's advertised surface: it is deliberately absent from
|
|
43
|
+
* `components/markdown/index.ts`, where only the detail types above are
|
|
44
|
+
* exported. It is not marked with the internal JSDoc tag either — this package
|
|
45
|
+
* compiles with `stripInternal`, which would drop the declaration from the
|
|
46
|
+
* emitted `.d.ts`, and every caller lives in the sibling package and resolves
|
|
47
|
+
* its types through exactly that file. (Do not write that tag's name anywhere
|
|
48
|
+
* in this comment: `stripInternal` matches the string, not just a real tag.)
|
|
49
|
+
*/
|
|
50
|
+
function createMarkdownPluginHostController(target, options = {}) {
|
|
51
|
+
const { onSlotNamesChange, shouldDefer } = options;
|
|
52
|
+
// Keyed by slot name alone: the markdown element namespaces every name it
|
|
53
|
+
// mints per element (see `./slot-names.js`), so two messages rendering the
|
|
54
|
+
// same markdown can't collide here. Only hosts this controller created —
|
|
55
|
+
// a relocated `customRenderers` element is parented to `target` but never
|
|
56
|
+
// entered here, which is what keeps `handleUpdate` from clobbering a
|
|
57
|
+
// consumer's node and `disconnect()` from destroying one.
|
|
58
|
+
const hosts = new Map();
|
|
59
|
+
let slotNames = [];
|
|
60
|
+
// Built once, not per `connect()`: a Lit `connectedCallback` can fire again
|
|
61
|
+
// without an intervening disconnect, and fresh closures would register a
|
|
62
|
+
// second time and handle every mount twice.
|
|
63
|
+
const handleMount = (event) => {
|
|
64
|
+
const raw = event.detail;
|
|
65
|
+
if (!raw?.slotName) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const detail = resolveMarkdownPluginHostMountDetail(raw);
|
|
69
|
+
// Track before deferring: a container nested inside an outer chat element
|
|
70
|
+
// hosts nothing but still has to forward the slot inward.
|
|
71
|
+
if (!slotNames.includes(detail.slotName)) {
|
|
72
|
+
slotNames = [...slotNames, detail.slotName];
|
|
73
|
+
onSlotNamesChange?.(slotNames);
|
|
74
|
+
}
|
|
75
|
+
if (shouldDefer?.(event)) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
event.preventDefault();
|
|
79
|
+
if (detail.kind === 'customRenderer') {
|
|
80
|
+
// A live node the markdown element created, keeps writing to and
|
|
81
|
+
// removes: re-parent it and nothing else. No inline spacing — the stack
|
|
82
|
+
// gap lives on the `<slot>` placeholder in the element's own shadow CSS,
|
|
83
|
+
// and a style attribute here would outrank the page stylesheet this
|
|
84
|
+
// relocation exists to admit.
|
|
85
|
+
detail.element.setAttribute('slot', detail.slotName);
|
|
86
|
+
// Re-appending a node already parented here detaches and reattaches the
|
|
87
|
+
// consumer's whole subtree, running its disconnect/connect teardown.
|
|
88
|
+
if (detail.element.parentElement !== target) {
|
|
89
|
+
target.appendChild(detail.element);
|
|
90
|
+
}
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
let host = hosts.get(detail.slotName);
|
|
94
|
+
if (!host) {
|
|
95
|
+
host = document.createElement(detail.isInline ? 'span' : 'div');
|
|
96
|
+
host.setAttribute('slot', detail.slotName);
|
|
97
|
+
// Match `.cds-aichat-markdown-stack > *:not(:first-child)` spacing;
|
|
98
|
+
// shadow CSS doesn't reach a host in page light DOM, so apply it inline.
|
|
99
|
+
// Inline output flows with text and gets no extra spacing.
|
|
100
|
+
if (!detail.isInline) {
|
|
101
|
+
host.style.marginBlockStart = '1rem';
|
|
102
|
+
}
|
|
103
|
+
hosts.set(detail.slotName, host);
|
|
104
|
+
target.appendChild(host);
|
|
105
|
+
}
|
|
106
|
+
// `?? ''` here and in `handleUpdate`: `html` is typed `string`, but the
|
|
107
|
+
// emitter can be a third-party element this compiler never saw, and
|
|
108
|
+
// `innerHTML = undefined` writes the literal string "undefined".
|
|
109
|
+
if (host.innerHTML !== (detail.html ?? '')) {
|
|
110
|
+
host.innerHTML = detail.html ?? '';
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const handleUpdate = (event) => {
|
|
114
|
+
const detail = event.detail;
|
|
115
|
+
if (!detail?.slotName) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const host = hosts.get(detail.slotName);
|
|
119
|
+
if (host && host.innerHTML !== (detail.html ?? '')) {
|
|
120
|
+
host.innerHTML = detail.html ?? '';
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
const handleUnmount = (event) => {
|
|
124
|
+
const detail = event
|
|
125
|
+
.detail;
|
|
126
|
+
if (!detail?.slotName) {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (slotNames.includes(detail.slotName)) {
|
|
130
|
+
slotNames = slotNames.filter((name) => name !== detail.slotName);
|
|
131
|
+
onSlotNamesChange?.(slotNames);
|
|
132
|
+
}
|
|
133
|
+
const host = hosts.get(detail.slotName);
|
|
134
|
+
if (host) {
|
|
135
|
+
host.remove();
|
|
136
|
+
hosts.delete(detail.slotName);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
return {
|
|
140
|
+
hosts,
|
|
141
|
+
connect() {
|
|
142
|
+
target.addEventListener(MOUNT, handleMount);
|
|
143
|
+
target.addEventListener(UPDATE, handleUpdate);
|
|
144
|
+
target.addEventListener(UNMOUNT, handleUnmount);
|
|
145
|
+
},
|
|
146
|
+
disconnect() {
|
|
147
|
+
target.removeEventListener(MOUNT, handleMount);
|
|
148
|
+
target.removeEventListener(UPDATE, handleUpdate);
|
|
149
|
+
target.removeEventListener(UNMOUNT, handleUnmount);
|
|
150
|
+
for (const host of hosts.values()) {
|
|
151
|
+
host.remove();
|
|
152
|
+
}
|
|
153
|
+
hosts.clear();
|
|
154
|
+
// Slot names deliberately survive. `handleUpdate` drops an update whose
|
|
155
|
+
// host is missing, so retention would strand a slot if only this element
|
|
156
|
+
// cycled — it is safe because the markdown element is a shadow-including
|
|
157
|
+
// descendant, so it cycles too, clears its own claims and re-offers a
|
|
158
|
+
// mount rather than an update. Clearing here would also make that next
|
|
159
|
+
// mount replace the consumer's list rather than extend it.
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export { createMarkdownPluginHostController, resolveMarkdownPluginHostMountDetail };
|
|
165
|
+
//# sourceMappingURL=plugin-host-container.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin-host-container.js","sources":["../../../../../src/components/markdown/src/utils/plugin-host-container.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\n/**\n * The container half of the plugin-host protocol.\n *\n * `<cds-aichat-markdown>` offers a host for plugin output to whichever chat\n * element is outermost, over three composed events — `-mount`, `-update` and\n * `-unmount`. Accepting the offer means calling `preventDefault()` on the\n * mount event and putting the host somewhere consumer-loaded CSS can reach it,\n * which the markdown element's own light DOM is not: it sits inside the chat's\n * shadow root. A plugin-fallback offer hands over an HTML string this\n * controller renders into a host it creates; a `customRenderers` offer hands\n * over a live element this controller only re-parents.\n *\n * A container supplies only the element hosts are appended to, and whatever\n * policy the framework cannot infer.\n */\n\n/**\n * Mount detail for plugin output the element hands over as an HTML string.\n */\nexport interface MarkdownPluginFallbackMountDetail {\n /** Marks the payload as an HTML string rather than a live element. */\n kind: 'pluginFallback';\n /**\n * Name to put on the host's `slot` attribute, and the key the matching\n * `-update` and `-unmount` events arrive under. Unique across every markdown\n * element on the page, and reused across renders while the token stays put,\n * so a streaming message rewrites one host instead of growing a new one per\n * chunk. Treat the value as opaque; its format is not part of the API.\n */\n slotName: string;\n /**\n * The plugin rule's rendered HTML, to assign to the host's `innerHTML`.\n *\n * DOMPurify runs over it only when the markdown element has `sanitize-html`\n * set, and that setting is off by default. `remove-html` does not stand in\n * for it either — that one escapes HTML written in the markdown source and\n * never filters what a plugin's renderer rule emits. Treat the string as\n * exactly as trustworthy as the markdown-it plugins the page registered.\n */\n html: string;\n /**\n * True when the plugin's token is inline, such as a `math_inline` span.\n * Picks the host tag — `span` when true, so the output stays in paragraph\n * flow, `div` when false — and gates the block spacing that matches the\n * markdown element's own stack gap.\n */\n isInline: boolean;\n}\n\n/**\n * Mount detail for a `customRenderers` host. It carries a live element the\n * markdown element created, keeps writing to across renders, and removes.\n * Claiming it means re-parenting that element into your own light DOM,\n * synchronously, and nothing else: never rewrite its content, never style it,\n * never remove it. The markdown element renders the `<slot>` hop that projects\n * it back.\n */\nexport interface MarkdownCustomRendererMountDetail {\n /** Marks the payload as a live element rather than an HTML string. */\n kind: 'customRenderer';\n /**\n * Name already set on `element`'s `slot` attribute, and the key the matching\n * `-unmount` event arrives under. Page-unique, reused across renders and\n * opaque, like the plugin-fallback name. No `-update` event follows this\n * one: the markdown element writes the consumer's node into `element`\n * itself.\n */\n slotName: string;\n /**\n * The host to re-parent. The markdown element created it, replaces its\n * children on every render, and removes it when the renderer stops matching\n * — a claimant only moves it.\n */\n element: HTMLElement;\n /**\n * True when the claimed output is inline flow content. Always `false` here:\n * the markdown element hosts every `customRenderers` result in a `<div>` it\n * created, so a claimant has no host tag to choose. Declared on both members\n * so a listener can read it before narrowing on `kind`.\n */\n isInline: boolean;\n}\n\n/**\n * The `cds-aichat-markdown-plugin-host-mount` detail, discriminated on `kind`.\n *\n * Narrow on `kind`, never on which of `html` / `element` is present — the two\n * members deliberately declare only their own fields, so reading the wrong one\n * is a compile error rather than a silent `undefined`.\n */\nexport type MarkdownPluginHostMountDetail =\n MarkdownPluginFallbackMountDetail | MarkdownCustomRendererMountDetail;\n\n/**\n * A mount detail as it arrives on the wire, `kind` included or not.\n *\n * `kind` is newer than the events themselves, and `@carbon/ai-chat` depends on\n * this package through a caret range, so a listener can still receive the\n * original shape from an older build. Pass anything you receive through\n * `resolveMarkdownPluginHostMountDetail`, exported from\n * `@carbon/ai-chat-components/es/components/markdown/src/utils/plugin-host-container.js`,\n * and narrow on the result.\n */\nexport type MarkdownPluginHostMountDetailInput =\n | MarkdownPluginHostMountDetail\n | Omit<MarkdownPluginFallbackMountDetail, 'kind'>\n | Omit<MarkdownCustomRendererMountDetail, 'kind'>;\n\n/**\n * Fills in `kind` for a detail emitted before the field existed.\n *\n * The one place the payload's shape is still consulted, and only when there is\n * nothing else to go on. Delete it once the floor on `@carbon/ai-chat-components`\n * rises past the release that added `kind`.\n */\nexport function resolveMarkdownPluginHostMountDetail(\n detail: MarkdownPluginHostMountDetailInput\n): MarkdownPluginHostMountDetail {\n if ('kind' in detail) {\n return detail;\n }\n return 'element' in detail\n ? { ...detail, kind: 'customRenderer' }\n : { ...detail, kind: 'pluginFallback' };\n}\n\nexport interface MarkdownPluginHostControllerOptions {\n /**\n * Called with a fresh array whenever the set of slot names this surface\n * should forward inward changes. Surfaces one shadow boundary from the\n * markdown element render no forwarder of their own and omit it — the React\n * `ChatContainer` is the one in this repo.\n *\n * Both kinds, and including names this surface declined to host: a container\n * nested inside an outer chat element still has to forward the slot the\n * outer one is hosting. The innermost hop — into the markdown element's own\n * shadow slot — is never one of these; the element mints that one, for\n * either kind, in the pass that read the claim.\n */\n onSlotNamesChange?: (slotNames: string[]) => void;\n\n /**\n * Return `true` to forward the slot without hosting it, because an outer\n * chat element will. Omitted by surfaces that are always outermost.\n */\n shouldDefer?: (event: Event) => boolean;\n}\n\nexport interface MarkdownPluginHostController {\n /** Subscribes to the three events. Safe to call again without disconnecting. */\n connect(): void;\n /**\n * Unsubscribes and removes the hosts this controller created. Relocated\n * `customRenderers` elements are left parented — they belong to the markdown\n * element, and as children of `target` they ride along with a DOM move.\n * Forwarded slot names survive too.\n */\n disconnect(): void;\n /**\n * Plugin-fallback hosts this controller created, keyed by slot name.\n * Relocated `customRenderers` elements are deliberately absent.\n */\n readonly hosts: ReadonlyMap<string, HTMLElement>;\n}\n\nconst MOUNT = 'cds-aichat-markdown-plugin-host-mount';\nconst UPDATE = 'cds-aichat-markdown-plugin-host-update';\nconst UNMOUNT = 'cds-aichat-markdown-plugin-host-unmount';\n\n/**\n * Answers the plugin-host offer on `target`'s behalf, hosting accepted offers\n * as slot-attributed children of `target`.\n *\n * `target` is both the listener and the host parent because in every chat\n * surface they are the same element — the offer is claimed by whichever chat\n * element is outermost, and that is the element whose light DOM is page DOM.\n *\n * Not part of this package's advertised surface: it is deliberately absent from\n * `components/markdown/index.ts`, where only the detail types above are\n * exported. It is not marked with the internal JSDoc tag either — this package\n * compiles with `stripInternal`, which would drop the declaration from the\n * emitted `.d.ts`, and every caller lives in the sibling package and resolves\n * its types through exactly that file. (Do not write that tag's name anywhere\n * in this comment: `stripInternal` matches the string, not just a real tag.)\n */\nexport function createMarkdownPluginHostController(\n target: HTMLElement,\n options: MarkdownPluginHostControllerOptions = {}\n): MarkdownPluginHostController {\n const { onSlotNamesChange, shouldDefer } = options;\n // Keyed by slot name alone: the markdown element namespaces every name it\n // mints per element (see `./slot-names.js`), so two messages rendering the\n // same markdown can't collide here. Only hosts this controller created —\n // a relocated `customRenderers` element is parented to `target` but never\n // entered here, which is what keeps `handleUpdate` from clobbering a\n // consumer's node and `disconnect()` from destroying one.\n const hosts = new Map<string, HTMLElement>();\n let slotNames: string[] = [];\n\n // Built once, not per `connect()`: a Lit `connectedCallback` can fire again\n // without an intervening disconnect, and fresh closures would register a\n // second time and handle every mount twice.\n const handleMount = (event: Event) => {\n const raw = (\n event as CustomEvent<MarkdownPluginHostMountDetailInput | undefined>\n ).detail;\n if (!raw?.slotName) {\n return;\n }\n const detail = resolveMarkdownPluginHostMountDetail(raw);\n\n // Track before deferring: a container nested inside an outer chat element\n // hosts nothing but still has to forward the slot inward.\n if (!slotNames.includes(detail.slotName)) {\n slotNames = [...slotNames, detail.slotName];\n onSlotNamesChange?.(slotNames);\n }\n if (shouldDefer?.(event)) {\n return;\n }\n\n event.preventDefault();\n if (detail.kind === 'customRenderer') {\n // A live node the markdown element created, keeps writing to and\n // removes: re-parent it and nothing else. No inline spacing — the stack\n // gap lives on the `<slot>` placeholder in the element's own shadow CSS,\n // and a style attribute here would outrank the page stylesheet this\n // relocation exists to admit.\n detail.element.setAttribute('slot', detail.slotName);\n // Re-appending a node already parented here detaches and reattaches the\n // consumer's whole subtree, running its disconnect/connect teardown.\n if (detail.element.parentElement !== target) {\n target.appendChild(detail.element);\n }\n return;\n }\n let host = hosts.get(detail.slotName);\n if (!host) {\n host = document.createElement(detail.isInline ? 'span' : 'div');\n host.setAttribute('slot', detail.slotName);\n // Match `.cds-aichat-markdown-stack > *:not(:first-child)` spacing;\n // shadow CSS doesn't reach a host in page light DOM, so apply it inline.\n // Inline output flows with text and gets no extra spacing.\n if (!detail.isInline) {\n host.style.marginBlockStart = '1rem';\n }\n hosts.set(detail.slotName, host);\n target.appendChild(host);\n }\n // `?? ''` here and in `handleUpdate`: `html` is typed `string`, but the\n // emitter can be a third-party element this compiler never saw, and\n // `innerHTML = undefined` writes the literal string \"undefined\".\n if (host.innerHTML !== (detail.html ?? '')) {\n host.innerHTML = detail.html ?? '';\n }\n };\n\n const handleUpdate = (event: Event) => {\n const detail = (\n event as CustomEvent<{ slotName: string; html: string } | undefined>\n ).detail;\n if (!detail?.slotName) {\n return;\n }\n const host = hosts.get(detail.slotName);\n if (host && host.innerHTML !== (detail.html ?? '')) {\n host.innerHTML = detail.html ?? '';\n }\n };\n\n const handleUnmount = (event: Event) => {\n const detail = (event as CustomEvent<{ slotName: string } | undefined>)\n .detail;\n if (!detail?.slotName) {\n return;\n }\n if (slotNames.includes(detail.slotName)) {\n slotNames = slotNames.filter((name) => name !== detail.slotName);\n onSlotNamesChange?.(slotNames);\n }\n const host = hosts.get(detail.slotName);\n if (host) {\n host.remove();\n hosts.delete(detail.slotName);\n }\n };\n\n return {\n hosts,\n connect() {\n target.addEventListener(MOUNT, handleMount);\n target.addEventListener(UPDATE, handleUpdate);\n target.addEventListener(UNMOUNT, handleUnmount);\n },\n disconnect() {\n target.removeEventListener(MOUNT, handleMount);\n target.removeEventListener(UPDATE, handleUpdate);\n target.removeEventListener(UNMOUNT, handleUnmount);\n for (const host of hosts.values()) {\n host.remove();\n }\n hosts.clear();\n // Slot names deliberately survive. `handleUpdate` drops an update whose\n // host is missing, so retention would strand a slot if only this element\n // cycled — it is safe because the markdown element is a shadow-including\n // descendant, so it cycles too, clears its own claims and re-offers a\n // mount rather than an update. Clearing here would also make that next\n // mount replace the consumer's list rather than extend it.\n },\n };\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AA8GH;;;;;;AAMG;AACG,SAAU,oCAAoC,CAClD,MAA0C,EAAA;AAE1C,IAAA,IAAI,MAAM,IAAI,MAAM,EAAE;AACpB,QAAA,OAAO,M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AAQ,EAAE;YACrB;QACF;QACA,IAAI,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE;AACvC,YAAA,SAAS,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,IAAI,KAAK,IAAI,KAAK,MAAM,CAAC,QAAQ,CAAC;AAChE,YAAA,iBAAiB,GAAG,SAAS,CAAC;QAChC;QACA,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC;QACvC,IAAI,IAAI,EAAE;YACR,IAAI,CAAC,MAAM,EAAE;AACb,YAAA,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC;QAC/B;AACF,IAAA,CAAC;IAED,OAAO;QACL,KAAK;QACL,OAAO,GAAA;AACL,YAAA,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3C,YAAA,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,YAAY,CAAC;AAC7C,YAAA,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,aAAa,CAAC;QACjD,CAAC;QACD,UAAU,GAAA;AACR,YAAA,MAAM,CAAC,mBAAmB,CAAC,KAAK,EAAE,WAAW,CAAC;AAC9C,YAAA,MAAM,CAAC,mBAAmB,CAAC,MAAM,EAAE,YAAY,CAAC;AAChD,YAAA,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,aAAa,CAAC;YAClD,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE;gBACjC,IAAI,CAAC,MAAM,EAAE;YACf;YACA,KAAK,CAAC,KAAK,EAAE;;;;;;;QAOf,CAAC;KACF;AACH;;"}
|
package/es/react/markdown.js
CHANGED
|
@@ -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,
|
|
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
|
|
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
|
|
package/es/react/markdown.js.map
CHANGED
|
@@ -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,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AA,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,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;AAEtB;AAEA,MAAM,QAAQ,GAAG,UAAU,CAAmC,SAAS,QAAQ,CAC7E,EAAE,eAAe,EAAE,GAAG,IAAI,EAAE,EAC5B,YAAY,EAAA;IAEZ,MAAM,QA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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: {
|
|
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) {
|