@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.
- package/custom-elements.json +3186 -3074
- 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/components/markdown/src/utils/table-helpers.d.ts +10 -0
- package/es/components/markdown/src/utils/table-helpers.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/build-extensions.d.ts +17 -0
- package/es/components/prompt-line/src/tiptap/build-extensions.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/carbon-autocomplete.d.ts +12 -0
- package/es/components/prompt-line/src/tiptap/carbon-autocomplete.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/render-token-chip.d.ts +12 -0
- package/es/components/prompt-line/src/tiptap/render-token-chip.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/types.d.ts +2 -1
- 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/components/markdown/src/utils/table-helpers.d.ts +10 -0
- package/es-custom/components/markdown/src/utils/table-helpers.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/build-extensions.d.ts +17 -0
- package/es-custom/components/prompt-line/src/tiptap/build-extensions.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.d.ts +12 -0
- package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/render-token-chip.d.ts +12 -0
- package/es-custom/components/prompt-line/src/tiptap/render-token-chip.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/types.d.ts +2 -1
- package/es-custom/react/markdown.js +2 -44
- package/es-custom/react/markdown.js.map +1 -1
- package/package.json +2 -2
|
@@ -177,9 +177,12 @@ function sliceForFallback(token, node) {
|
|
|
177
177
|
}
|
|
178
178
|
/**
|
|
179
179
|
* Renders an unknown token via markdown-it's HTML renderer and emits a named
|
|
180
|
-
* `<slot>` placeholder
|
|
181
|
-
* `<div slot="…">` host containing the
|
|
182
|
-
* CSS (e.g. KaTeX's stylesheet) reaches the
|
|
180
|
+
* `<slot>` placeholder carrying the token's text as its fallback content. The
|
|
181
|
+
* markdown element adopts a light-DOM `<div slot="…">` host containing the
|
|
182
|
+
* sanitized HTML so consumer-supplied CSS (e.g. KaTeX's stylesheet) reaches the
|
|
183
|
+
* rendered output; the fallback is what a reader sees if that host never
|
|
184
|
+
* arrives — a container claimed the slot and no forwarder was minted — so a
|
|
185
|
+
* stranded host degrades to plain text instead of vanishing.
|
|
183
186
|
*
|
|
184
187
|
* For leaf token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES} the rendered
|
|
185
188
|
* HTML is cached on the {@link TokenTree} node and inherited across
|
|
@@ -204,7 +207,7 @@ function renderFallback(token, node, md, sanitize, options) {
|
|
|
204
207
|
node.cachedHtml = { md, html: safe };
|
|
205
208
|
}
|
|
206
209
|
}
|
|
207
|
-
const index = options.pluginSlotCounter?.next() ?? 0;
|
|
210
|
+
const index = options.pluginSlotCounter?.next(node) ?? 0;
|
|
208
211
|
const slotName = withInstanceNamespace(`${PLUGIN_FALLBACK_SLOT_PREFIX}-${index}`, options);
|
|
209
212
|
options.recordCustomRender?.({
|
|
210
213
|
slotName,
|
|
@@ -213,7 +216,13 @@ function renderFallback(token, node, md, sanitize, options) {
|
|
|
213
216
|
html: safe,
|
|
214
217
|
isInline: token.block === false,
|
|
215
218
|
});
|
|
216
|
-
|
|
219
|
+
// Text, not `safe`: the rendered markup already exists once as the light-DOM
|
|
220
|
+
// host, and duplicating it inside the slot doubles the DOM of a plugin-heavy
|
|
221
|
+
// message — 40 KaTeX expressions measured 3,288 extra elements. Prefer the
|
|
222
|
+
// author's own source, which is what a formula or diagram token carries, and
|
|
223
|
+
// fall back to the output's text for marker tokens that carry no source.
|
|
224
|
+
const fallbackText = token.content || safe.replace(/<[^>]*>/g, '');
|
|
225
|
+
return html `<slot name=${slotName}>${fallbackText}</slot>`;
|
|
217
226
|
}
|
|
218
227
|
|
|
219
228
|
export { PLUGIN_FALLBACK_SLOT_PREFIX, isNativelyHandled, renderFallback, shouldDelegateToPluginRule };
|
|
@@ -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-custom-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-custom-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,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE;AAC9D,QAAA,OAAO,IAAI;IACb;AACA,IAAA,IAAI,KAAK,CAAC,GAAG,IAAI,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;A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ACxD,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-custom-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-custom-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;;;;;;;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,aA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AAC,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-custom-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-custom-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-custom-aichat-markdown-plugin-host-mount';
|
|
32
|
+
const UPDATE = 'cds-custom-aichat-markdown-plugin-host-update';
|
|
33
|
+
const UNMOUNT = 'cds-custom-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-custom-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-custom-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-custom-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-custom-aichat-markdown-plugin-host-mount';\nconst UPDATE = 'cds-custom-aichat-markdown-plugin-host-update';\nconst UNMOUNT = 'cds-custom-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-custom-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,MAAM;IACf;IACA,OAAO,SAAS,IAAI;UAChB,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,gBAAgB;UACnC,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,g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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;;"}
|
|
@@ -10,8 +10,18 @@ export declare const DEFAULT_PAGINATION_STATUS_TEXT: ({ start, end, count, }: {
|
|
|
10
10
|
end: number;
|
|
11
11
|
count: number;
|
|
12
12
|
}) => string;
|
|
13
|
+
/**
|
|
14
|
+
* One cell of a parsed markdown table. A custom table renderer reads these
|
|
15
|
+
* from the `headers` and `rows` it is handed.
|
|
16
|
+
*/
|
|
13
17
|
export interface TableCellData {
|
|
18
|
+
/** Plain text of the cell, with markdown syntax stripped. */
|
|
14
19
|
text: string;
|
|
20
|
+
/**
|
|
21
|
+
* Token tree for the cell's content, or `null` when the cell is plain
|
|
22
|
+
* text. Render it to keep the links, code spans, and emphasis that `text`
|
|
23
|
+
* drops.
|
|
24
|
+
*/
|
|
15
25
|
tokens: TokenTree[] | null;
|
|
16
26
|
}
|
|
17
27
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-helpers.js","sources":["../../../../../src/components/markdown/src/utils/table-helpers.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 { repeat } from 'lit/directives/repeat.js';\nimport type { Token } from 'markdown-it';\n\nimport type {\n TableCellContent,\n TableRowContent,\n} from '../../../table/src/table.js';\nimport { combineConsecutiveHtmlInline } from './html-helpers.js';\nimport { isTableAtStreamingTail } from './streaming-table.js';\nimport type { RenderTokenTreeOptions } from '../markdown-renderer-types.js';\nimport type { TokenTree } from '../markdown-token-tree';\n\n// Default localization functions for table pagination\nexport const DEFAULT_PAGINATION_SUPPLEMENTAL_TEXT = ({\n count,\n}: {\n count: number;\n}) => `${count} items`;\nexport const DEFAULT_PAGINATION_STATUS_TEXT = ({\n start,\n end,\n count,\n}: {\n start: number;\n end: number;\n count: number;\n}) => `${start}–${end} of ${count} items`;\n\nexport interface TableCellData {\n text: string;\n tokens: TokenTree[] | null;\n}\n\n/**\n * Extracts tabular data from a table TokenTree node.\n *\n * Converts the hierarchical markdown table structure into the flat\n * header/rows format expected by the cds-custom-aichat-table component while retaining\n * the TokenTree children required for rich rendering within cells.\n */\nexport function extractTableData(tableNode: TokenTree): {\n headers: TableCellData[];\n rows: TableCellData[][];\n} {\n const headers: TableCellData[] = [];\n const rows: TableCellData[][] = [];\n\n for (const child of tableNode.children) {\n if (child.token.tag === 'thead') {\n // Extract column headers\n for (const theadChild of child.children) {\n if (theadChild.token.tag === 'tr') {\n for (const thChild of theadChild.children) {\n if (thChild.token.tag === 'th') {\n headers.push(extractCellData(thChild));\n }\n }\n }\n }\n } else if (child.token.tag === 'tbody') {\n // Extract data rows\n for (const tbodyChild of child.children) {\n if (tbodyChild.token.tag === 'tr') {\n const row: TableCellData[] = [];\n for (const tdChild of tbodyChild.children) {\n if (tdChild.token.tag === 'td') {\n row.push(extractCellData(tdChild));\n }\n }\n rows.push(row);\n }\n }\n }\n }\n\n return { headers, rows };\n}\n\n/**\n * Recursively extracts plain text content from a TokenTree node.\n *\n * This is used for table cells and other contexts where we need the\n * text content without HTML formatting.\n */\nexport function extractTextContent(node: TokenTree): string {\n // Handle direct text tokens\n if (node.token.type === 'text') {\n return node.token.content || '';\n }\n\n // Handle inline code\n if (node.token.type === 'code_inline') {\n return node.token.content || '';\n }\n\n if (node.token.type === 'softbreak' || node.token.type === 'hardbreak') {\n return '\\n';\n }\n\n // Recursively extract text from child nodes\n let text = '';\n for (const child of node.children) {\n text += extractTextContent(child);\n }\n\n return text;\n}\n\nfunction extractCellData(node: TokenTree): TableCellData {\n const text = extractTextContent(node);\n const tokens = extractRenderableChildren(node);\n const hasRichContent = tokens.some((child) => child.token.type !== 'text');\n\n return {\n text,\n tokens: hasRichContent ? tokens : null,\n };\n}\n\nfunction extractRenderableChildren(node: TokenTree): TokenTree[] {\n if (node.children.length === 1) {\n const onlyChild = node.children[0];\n if (\n onlyChild.token.type === 'inline' &&\n onlyChild.children &&\n onlyChild.children.length\n ) {\n return onlyChild.children;\n }\n }\n\n return node.children;\n}\n\n/**\n * Renders the body of the `case \"table\"` branch of `renderWithStaticTag`.\n *\n * Lives outside the renderer's switch because it covers three flows: streaming\n * loading state, default Carbon-table rendering, and the `customRenderers.table`\n * slot override.\n *\n * `renderToken` is the recursive renderer the caller dispatched from, passed in\n * to avoid a cycle with `markdown-renderer.ts`. `slotName` is non-undefined when\n * the consumer registered a `table` custom renderer, in which case the result is\n * wrapped in a named `<slot>` and an override descriptor is reported via\n * `recordCustomRender`.\n */\nexport function renderTable(\n token: Token,\n node: TokenTree,\n attrs: Record<string, string>,\n options: RenderTokenTreeOptions,\n renderToken: (\n node: TokenTree,\n options: RenderTokenTreeOptions\n ) => TemplateResult,\n slotName: string | undefined\n): TemplateResult {\n const {\n streaming,\n forceTableLoading,\n context: parentContext,\n tableFilterPlaceholderText,\n tablePreviousPageText,\n tableNextPageText,\n tableItemsPerPageText,\n tableDownloadLabelText,\n tableLocale,\n tableGetPaginationSupplementalText,\n tableGetPaginationStatusText,\n } = options;\n\n // Determine if we should show loading state during streaming\n let isLoading = Boolean(forceTableLoading);\n if (\n !isLoading &&\n streaming &&\n parentContext?.parentChildren &&\n parentContext?.currentIndex !== undefined\n ) {\n isLoading = isTableAtStreamingTail(\n parentContext.parentChildren,\n parentContext.currentIndex\n );\n }\n\n const renderCellTokens = (tokens: TokenTree[], contextOverrides = {}) => {\n // Same as block/inline rendering: merge split raw HTML (e.g. `<a>…</a>`)\n // so each cell is not rendered as separate unsafeHTML + text chunks.\n const normalizedTokens = combineConsecutiveHtmlInline(tokens);\n return html`${repeat(\n normalizedTokens,\n (child, index) => `cell-${index}:${child.token.type}:${child.token.tag}`,\n (child, index) =>\n renderToken(child, {\n ...options,\n context: {\n ...options.context,\n ...contextOverrides,\n parentChildren: normalizedTokens,\n currentIndex: index,\n },\n })\n )}`;\n };\n\n const createCellContent = (\n cell: TableCellData,\n contextOverrides?: Record<string, unknown>\n ): TableCellContent => ({\n text: cell.text,\n template: cell.tokens\n ? renderCellTokens(cell.tokens, contextOverrides)\n : null,\n });\n\n // Only extract and process table data when not loading to avoid unnecessary work.\n // During loading, the table shows a skeleton and doesn't need the actual data.\n let headers: TableCellContent[] = [];\n let tableRows: TableRowContent[] = [];\n\n if (!isLoading) {\n const extractedData = extractTableData(node);\n headers = extractedData.headers.map((cell) =>\n createCellContent(cell, { isInThead: true })\n );\n tableRows = extractedData.rows.map((row) => ({\n cells: row.map((cell) => createCellContent(cell)),\n }));\n }\n\n // Always return the same structure to allow Lit to reuse the table element.\n // When isLoading is true, the table component will show a skeleton state.\n // When isLoading is false, it will show the actual data.\n // This prevents recreating the table element and preserves its internal state.\n const defaultTableTemplate = html`<div class=\"cds-custom-aichat-table--square\">\n <cds-custom-aichat-table\n data-rounded\n .headers=${headers}\n .rows=${tableRows}\n .loading=${isLoading}\n .filterPlaceholderText=${tableFilterPlaceholderText}\n .previousPageText=${tablePreviousPageText}\n .nextPageText=${tableNextPageText}\n .itemsPerPageText=${tableItemsPerPageText}\n .downloadLabelText=${tableDownloadLabelText}\n .locale=${tableLocale}\n .getPaginationSupplementalText=${tableGetPaginationSupplementalText}\n .getPaginationStatusText=${tableGetPaginationStatusText}\n ...=${attrs}></cds-custom-aichat-table>\n </div>`;\n\n if (slotName !== undefined) {\n // For the override path we pass the raw extracted cell data (not the\n // Lit-wrapped TableCellContent) so consumers can render however they\n // like. Extract once even when loading so the consumer always gets\n // the data — they can read `isLoading` to choose a skeleton state.\n const { headers: dataHeaders, rows: dataRows } = extractTableData(node);\n options.recordCustomRender?.({\n slotName,\n kind: 'table',\n token,\n data: {\n headers: dataHeaders,\n rows: dataRows,\n isStreaming: !!streaming,\n isLoading,\n },\n });\n return html`<slot name=${slotName}>${defaultTableTemplate}</slot>`;\n }\n\n return defaultTableTemplate;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;AAeH;AACO,MAAM,oCAAoC,GAAG,CAAC,EACnD,KAAK,GAGN,KAAK,CAAA,EAAG,KAAK;MACD,8BAA8B,GAAG,CAAC,EAC7C,KAAK,EACL,GAAG,EACH,KAAK,GAKN,KAAK,CAAA,EAAG,KAAK,IAAI,GAAG,CAAA,IAAA,EAAO,KAAK,CAAA,MAAA;AAOjC;;;;;;AAMG;AACG,SAAU,gBAAgB,CAAC,SAAoB,EAAA;IAInD,MAAM,OAAO,GAAoB,EAAE;IACnC,MAAM,IAAI,GAAsB,EAAE;AAElC,IAAA,KAAK,MAAM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A,CAAA,WAAA,EAAc,QAAQ,CAAA,CAAA,EAAI,oBAAoB,SAAS;IACpE;AAEA,IAAA,OAAO,oBAAoB;AAC7B;;"}
|
|
1
|
+
{"version":3,"file":"table-helpers.js","sources":["../../../../../src/components/markdown/src/utils/table-helpers.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 { repeat } from 'lit/directives/repeat.js';\nimport type { Token } from 'markdown-it';\n\nimport type {\n TableCellContent,\n TableRowContent,\n} from '../../../table/src/table.js';\nimport { combineConsecutiveHtmlInline } from './html-helpers.js';\nimport { isTableAtStreamingTail } from './streaming-table.js';\nimport type { RenderTokenTreeOptions } from '../markdown-renderer-types.js';\nimport type { TokenTree } from '../markdown-token-tree';\n\n// Default localization functions for table pagination\nexport const DEFAULT_PAGINATION_SUPPLEMENTAL_TEXT = ({\n count,\n}: {\n count: number;\n}) => `${count} items`;\nexport const DEFAULT_PAGINATION_STATUS_TEXT = ({\n start,\n end,\n count,\n}: {\n start: number;\n end: number;\n count: number;\n}) => `${start}–${end} of ${count} items`;\n\n/**\n * One cell of a parsed markdown table. A custom table renderer reads these\n * from the `headers` and `rows` it is handed.\n */\nexport interface TableCellData {\n /** Plain text of the cell, with markdown syntax stripped. */\n text: string;\n /**\n * Token tree for the cell's content, or `null` when the cell is plain\n * text. Render it to keep the links, code spans, and emphasis that `text`\n * drops.\n */\n tokens: TokenTree[] | null;\n}\n\n/**\n * Extracts tabular data from a table TokenTree node.\n *\n * Converts the hierarchical markdown table structure into the flat\n * header/rows format expected by the cds-custom-aichat-table component while retaining\n * the TokenTree children required for rich rendering within cells.\n */\nexport function extractTableData(tableNode: TokenTree): {\n headers: TableCellData[];\n rows: TableCellData[][];\n} {\n const headers: TableCellData[] = [];\n const rows: TableCellData[][] = [];\n\n for (const child of tableNode.children) {\n if (child.token.tag === 'thead') {\n // Extract column headers\n for (const theadChild of child.children) {\n if (theadChild.token.tag === 'tr') {\n for (const thChild of theadChild.children) {\n if (thChild.token.tag === 'th') {\n headers.push(extractCellData(thChild));\n }\n }\n }\n }\n } else if (child.token.tag === 'tbody') {\n // Extract data rows\n for (const tbodyChild of child.children) {\n if (tbodyChild.token.tag === 'tr') {\n const row: TableCellData[] = [];\n for (const tdChild of tbodyChild.children) {\n if (tdChild.token.tag === 'td') {\n row.push(extractCellData(tdChild));\n }\n }\n rows.push(row);\n }\n }\n }\n }\n\n return { headers, rows };\n}\n\n/**\n * Recursively extracts plain text content from a TokenTree node.\n *\n * This is used for table cells and other contexts where we need the\n * text content without HTML formatting.\n */\nexport function extractTextContent(node: TokenTree): string {\n // Handle direct text tokens\n if (node.token.type === 'text') {\n return node.token.content || '';\n }\n\n // Handle inline code\n if (node.token.type === 'code_inline') {\n return node.token.content || '';\n }\n\n if (node.token.type === 'softbreak' || node.token.type === 'hardbreak') {\n return '\\n';\n }\n\n // Recursively extract text from child nodes\n let text = '';\n for (const child of node.children) {\n text += extractTextContent(child);\n }\n\n return text;\n}\n\nfunction extractCellData(node: TokenTree): TableCellData {\n const text = extractTextContent(node);\n const tokens = extractRenderableChildren(node);\n const hasRichContent = tokens.some((child) => child.token.type !== 'text');\n\n return {\n text,\n tokens: hasRichContent ? tokens : null,\n };\n}\n\nfunction extractRenderableChildren(node: TokenTree): TokenTree[] {\n if (node.children.length === 1) {\n const onlyChild = node.children[0];\n if (\n onlyChild.token.type === 'inline' &&\n onlyChild.children &&\n onlyChild.children.length\n ) {\n return onlyChild.children;\n }\n }\n\n return node.children;\n}\n\n/**\n * Renders the body of the `case \"table\"` branch of `renderWithStaticTag`.\n *\n * Lives outside the renderer's switch because it covers three flows: streaming\n * loading state, default Carbon-table rendering, and the `customRenderers.table`\n * slot override.\n *\n * `renderToken` is the recursive renderer the caller dispatched from, passed in\n * to avoid a cycle with `markdown-renderer.ts`. `slotName` is non-undefined when\n * the consumer registered a `table` custom renderer, in which case the result is\n * wrapped in a named `<slot>` and an override descriptor is reported via\n * `recordCustomRender`.\n */\nexport function renderTable(\n token: Token,\n node: TokenTree,\n attrs: Record<string, string>,\n options: RenderTokenTreeOptions,\n renderToken: (\n node: TokenTree,\n options: RenderTokenTreeOptions\n ) => TemplateResult,\n slotName: string | undefined\n): TemplateResult {\n const {\n streaming,\n forceTableLoading,\n context: parentContext,\n tableFilterPlaceholderText,\n tablePreviousPageText,\n tableNextPageText,\n tableItemsPerPageText,\n tableDownloadLabelText,\n tableLocale,\n tableGetPaginationSupplementalText,\n tableGetPaginationStatusText,\n } = options;\n\n // Determine if we should show loading state during streaming\n let isLoading = Boolean(forceTableLoading);\n if (\n !isLoading &&\n streaming &&\n parentContext?.parentChildren &&\n parentContext?.currentIndex !== undefined\n ) {\n isLoading = isTableAtStreamingTail(\n parentContext.parentChildren,\n parentContext.currentIndex\n );\n }\n\n const renderCellTokens = (tokens: TokenTree[], contextOverrides = {}) => {\n // Same as block/inline rendering: merge split raw HTML (e.g. `<a>…</a>`)\n // so each cell is not rendered as separate unsafeHTML + text chunks.\n const normalizedTokens = combineConsecutiveHtmlInline(tokens);\n return html`${repeat(\n normalizedTokens,\n (child, index) => `cell-${index}:${child.token.type}:${child.token.tag}`,\n (child, index) =>\n renderToken(child, {\n ...options,\n context: {\n ...options.context,\n ...contextOverrides,\n parentChildren: normalizedTokens,\n currentIndex: index,\n },\n })\n )}`;\n };\n\n const createCellContent = (\n cell: TableCellData,\n contextOverrides?: Record<string, unknown>\n ): TableCellContent => ({\n text: cell.text,\n template: cell.tokens\n ? renderCellTokens(cell.tokens, contextOverrides)\n : null,\n });\n\n // Only extract and process table data when not loading to avoid unnecessary work.\n // During loading, the table shows a skeleton and doesn't need the actual data.\n let headers: TableCellContent[] = [];\n let tableRows: TableRowContent[] = [];\n\n if (!isLoading) {\n const extractedData = extractTableData(node);\n headers = extractedData.headers.map((cell) =>\n createCellContent(cell, { isInThead: true })\n );\n tableRows = extractedData.rows.map((row) => ({\n cells: row.map((cell) => createCellContent(cell)),\n }));\n }\n\n // Always return the same structure to allow Lit to reuse the table element.\n // When isLoading is true, the table component will show a skeleton state.\n // When isLoading is false, it will show the actual data.\n // This prevents recreating the table element and preserves its internal state.\n const defaultTableTemplate = html`<div class=\"cds-custom-aichat-table--square\">\n <cds-custom-aichat-table\n data-rounded\n .headers=${headers}\n .rows=${tableRows}\n .loading=${isLoading}\n .filterPlaceholderText=${tableFilterPlaceholderText}\n .previousPageText=${tablePreviousPageText}\n .nextPageText=${tableNextPageText}\n .itemsPerPageText=${tableItemsPerPageText}\n .downloadLabelText=${tableDownloadLabelText}\n .locale=${tableLocale}\n .getPaginationSupplementalText=${tableGetPaginationSupplementalText}\n .getPaginationStatusText=${tableGetPaginationStatusText}\n ...=${attrs}></cds-custom-aichat-table>\n </div>`;\n\n if (slotName !== undefined) {\n // For the override path we pass the raw extracted cell data (not the\n // Lit-wrapped TableCellContent) so consumers can render however they\n // like. Extract once even when loading so the consumer always gets\n // the data — they can read `isLoading` to choose a skeleton state.\n const { headers: dataHeaders, rows: dataRows } = extractTableData(node);\n options.recordCustomRender?.({\n slotName,\n kind: 'table',\n token,\n data: {\n headers: dataHeaders,\n rows: dataRows,\n isStreaming: !!streaming,\n isLoading,\n },\n });\n return html`<slot name=${slotName}>${defaultTableTemplate}</slot>`;\n }\n\n return defaultTableTemplate;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;AAeH;AACO,MAAM,oCAAoC,GAAG,CAAC,EACnD,KAAK,GAGN,KAAK,CAAA,EAAG,KAAK;MACD,8BAA8B,GAAG,CAAC,EAC7C,KAAK,EACL,GAAG,EACH,KAAK,GAKN,KAAK,CAAA,EAAG,KAAK,IAAI,GAAG,CAAA,IAAA,EAAO,KAAK,CAAA,MAAA;AAiBjC;;;;;;AAMG;AACG,SAAU,gBAAgB,CAAC,SAAoB,EAAA;IAInD,MAAM,OAAO,GAAoB,EAAE;IACnC,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AAA;AACF,SAAA,CAAC;AACF,QAAA,OAAO,IAAI,CAAA,CAAA,WAAA,EAAc,QAAQ,CAAA,CAAA,EAAI,oBAAoB,SAAS;IACpE;AAEA,IAAA,OAAO,oBAAoB;AAC7B;;"}
|
|
@@ -21,10 +21,27 @@
|
|
|
21
21
|
*/
|
|
22
22
|
import type { Extension } from '@tiptap/core';
|
|
23
23
|
import type { AutocompleteConfig, StartersConfig, TriggerSuggestionConfig } from './types.js';
|
|
24
|
+
/**
|
|
25
|
+
* The input configs {@link buildCarbonExtensions} turns into Tiptap
|
|
26
|
+
* extensions.
|
|
27
|
+
* Leave a field out to leave its extension out.
|
|
28
|
+
*/
|
|
24
29
|
export interface BuildCarbonExtensionsConfig {
|
|
30
|
+
/** Config for the `@`-style mention picker. Builds {@link carbonMention}. */
|
|
25
31
|
mention?: TriggerSuggestionConfig;
|
|
32
|
+
/** Config for the `/`-style command picker. Builds {@link carbonCommand}. */
|
|
26
33
|
command?: TriggerSuggestionConfig;
|
|
34
|
+
/**
|
|
35
|
+
* Config for live autocomplete. Builds {@link carbonAutocomplete}, set to
|
|
36
|
+
* stand down for whichever mention and command triggers you also pass.
|
|
37
|
+
*/
|
|
27
38
|
autocomplete?: AutocompleteConfig;
|
|
39
|
+
/**
|
|
40
|
+
* Config for the starter prompts shown while the editor is empty and
|
|
41
|
+
* focused. Builds {@link carbonStarterTrigger}. An empty `items` list still
|
|
42
|
+
* installs the extension, so you can fill the list later without
|
|
43
|
+
* recreating the editor.
|
|
44
|
+
*/
|
|
28
45
|
starters?: StartersConfig;
|
|
29
46
|
}
|
|
30
47
|
export declare function buildCarbonExtensions(configs: BuildCarbonExtensionsConfig): Extension[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-extensions.js","sources":["../../../../../src/components/prompt-line/src/tiptap/build-extensions.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 * Pure helper: translate the chat-domain configs surfaced on\n * `<cds-custom-aichat-prompt-line-shell>` (and `InputConfig`) into a curated Tiptap\n * extension list. Used by the shell's render logic and exposed publicly so\n * direct `<cds-custom-aichat-prompt-line>` consumers can call the same builder\n * without bringing the chrome along.\n *\n * Filters out `undefined` / empty configs so the returned list contains\n * exactly the extensions whose backing config was supplied. Enter-to-send is\n * **not** included here — `<cds-custom-aichat-prompt-line>` bakes `carbonChatEnter`\n * into its own base bundle, so both the textarea and rich surfaces send on\n * Enter without this builder.\n */\n\nimport type { Extension } from '@tiptap/core';\n\nimport {\n carbonAutocomplete,\n type ExcludedTrigger,\n} from './carbon-autocomplete.js';\nimport { carbonCommand, carbonMention } from './carbon-mention.js';\nimport { carbonStarterTrigger } from './carbon-starter-trigger.js';\nimport { tagExtensionSource } from './extension-equivalence.js';\nimport type {\n AutocompleteConfig,\n StartersConfig,\n TriggerSuggestionConfig,\n} from './types.js';\n\nexport interface BuildCarbonExtensionsConfig {\n mention?: TriggerSuggestionConfig;\n command?: TriggerSuggestionConfig;\n autocomplete?: AutocompleteConfig;\n starters?: StartersConfig;\n}\n\nexport function buildCarbonExtensions(\n configs: BuildCarbonExtensionsConfig\n): Extension[] {\n // Each entry is tagged with the config it was built from so the rich runtime\n // can tell a genuinely different extension set from a rebuilt-but-identical\n // one without recreating the editor. See ./extension-equivalence.ts.\n const out: Extension[] = [];\n if (configs.mention) {\n out.push(\n tagExtensionSource(\n carbonMention(configs.mention) as unknown as Extension,\n {\n kind: 'mention',\n config: configs.mention,\n }\n )\n );\n }\n if (configs.command) {\n out.push(\n tagExtensionSource(\n carbonCommand(configs.command) as unknown as Extension,\n {\n kind: 'command',\n config: configs.command,\n }\n )\n );\n }\n if (configs.autocomplete) {\n const excludeTriggers: ExcludedTrigger[] = [];\n if (configs.mention) {\n excludeTriggers.push({\n char: configs.mention.trigger,\n position:\n configs.mention.triggerPosition === 'start' ? 'start' : 'anywhere',\n });\n }\n if (configs.command) {\n excludeTriggers.push({\n char: configs.command.trigger,\n position:\n configs.command.triggerPosition === 'start' ? 'start' : 'anywhere',\n });\n }\n out.push(\n tagExtensionSource(\n carbonAutocomplete(configs.autocomplete, excludeTriggers),\n {\n kind: 'autocomplete',\n config: configs.autocomplete,\n }\n )\n );\n }\n // Installed whenever `starters` is configured, empty list included: it is how\n // `items`/`isOn` reach the live editor, and omitting it for an empty list\n // shortens the set, which the equivalence check rejects — recreating the\n // editor and dropping its undo history. `maybeEmit` stays silent when empty.\n if (configs.starters) {\n out.push(\n tagExtensionSource(\n carbonStarterTrigger(configs.starters.items, configs.starters.isOn),\n { kind: 'starters', config: configs.starters }\n )\n );\n }\n return out;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;
|
|
1
|
+
{"version":3,"file":"build-extensions.js","sources":["../../../../../src/components/prompt-line/src/tiptap/build-extensions.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 * Pure helper: translate the chat-domain configs surfaced on\n * `<cds-custom-aichat-prompt-line-shell>` (and `InputConfig`) into a curated Tiptap\n * extension list. Used by the shell's render logic and exposed publicly so\n * direct `<cds-custom-aichat-prompt-line>` consumers can call the same builder\n * without bringing the chrome along.\n *\n * Filters out `undefined` / empty configs so the returned list contains\n * exactly the extensions whose backing config was supplied. Enter-to-send is\n * **not** included here — `<cds-custom-aichat-prompt-line>` bakes `carbonChatEnter`\n * into its own base bundle, so both the textarea and rich surfaces send on\n * Enter without this builder.\n */\n\nimport type { Extension } from '@tiptap/core';\n\nimport {\n carbonAutocomplete,\n type ExcludedTrigger,\n} from './carbon-autocomplete.js';\nimport { carbonCommand, carbonMention } from './carbon-mention.js';\nimport { carbonStarterTrigger } from './carbon-starter-trigger.js';\nimport { tagExtensionSource } from './extension-equivalence.js';\nimport type {\n AutocompleteConfig,\n StartersConfig,\n TriggerSuggestionConfig,\n} from './types.js';\n\n/**\n * The input configs {@link buildCarbonExtensions} turns into Tiptap\n * extensions.\n * Leave a field out to leave its extension out.\n */\nexport interface BuildCarbonExtensionsConfig {\n /** Config for the `@`-style mention picker. Builds {@link carbonMention}. */\n mention?: TriggerSuggestionConfig;\n /** Config for the `/`-style command picker. Builds {@link carbonCommand}. */\n command?: TriggerSuggestionConfig;\n /**\n * Config for live autocomplete. Builds {@link carbonAutocomplete}, set to\n * stand down for whichever mention and command triggers you also pass.\n */\n autocomplete?: AutocompleteConfig;\n /**\n * Config for the starter prompts shown while the editor is empty and\n * focused. Builds {@link carbonStarterTrigger}. An empty `items` list still\n * installs the extension, so you can fill the list later without\n * recreating the editor.\n */\n starters?: StartersConfig;\n}\n\nexport function buildCarbonExtensions(\n configs: BuildCarbonExtensionsConfig\n): Extension[] {\n // Each entry is tagged with the config it was built from so the rich runtime\n // can tell a genuinely different extension set from a rebuilt-but-identical\n // one without recreating the editor. See ./extension-equivalence.ts.\n const out: Extension[] = [];\n if (configs.mention) {\n out.push(\n tagExtensionSource(\n carbonMention(configs.mention) as unknown as Extension,\n {\n kind: 'mention',\n config: configs.mention,\n }\n )\n );\n }\n if (configs.command) {\n out.push(\n tagExtensionSource(\n carbonCommand(configs.command) as unknown as Extension,\n {\n kind: 'command',\n config: configs.command,\n }\n )\n );\n }\n if (configs.autocomplete) {\n const excludeTriggers: ExcludedTrigger[] = [];\n if (configs.mention) {\n excludeTriggers.push({\n char: configs.mention.trigger,\n position:\n configs.mention.triggerPosition === 'start' ? 'start' : 'anywhere',\n });\n }\n if (configs.command) {\n excludeTriggers.push({\n char: configs.command.trigger,\n position:\n configs.command.triggerPosition === 'start' ? 'start' : 'anywhere',\n });\n }\n out.push(\n tagExtensionSource(\n carbonAutocomplete(configs.autocomplete, excludeTriggers),\n {\n kind: 'autocomplete',\n config: configs.autocomplete,\n }\n )\n );\n }\n // Installed whenever `starters` is configured, empty list included: it is how\n // `items`/`isOn` reach the live editor, and omitting it for an empty list\n // shortens the set, which the equivalence check rejects — recreating the\n // editor and dropping its undo history. `maybeEmit` stays silent when empty.\n if (configs.starters) {\n out.push(\n tagExtensionSource(\n carbonStarterTrigger(configs.starters.items, configs.starters.isOn),\n { kind: 'starters', config: configs.starters }\n )\n );\n }\n return out;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;AAuDG,SAAU,qBAAqB,CACnC,OAAoC,EAAA;;;;IAKpC,MAAM,GAAG,GAAgB,EAAE;AAC3B,IAAA,IAAI,OAAO,CAAC,OAAO,EAAE;QACnB,GAAG,CAAC,IAAI,CACN,kBAAkB,CAChB,aAAa,CAAC,OAAO,CAAC,OAAO,CAAyB,EACtD;AACE,YAAA,IAAI,EAAE,SAAS;YACf,MAAM,EAAE,OAAO,CAAC,OAAO;AACxB,SAAA,CACF,CACF;IACH;AACA,IAAA,IAAI,OAAO,CAAC,OAAO,EAAE;QACnB,GAAG,CAAC,IAAI,CACN,kBAAkB,CAChB,aAAa,CAAC,OAAO,CAAC,OAAO,CAAyB,EACtD;AACE,YAAA,IAAI,EAAE,SAAS;YACf,MAAM,EAAE,OAAO,CAAC,OAAO;AACxB,SAAA,CACF,CACF;IACH;AACA,IAAA,IAAI,OAAO,CAAC,YAAY,EAAE;QACxB,MAAM,eAAe,GAAsB,EAAE;AAC7C,QAAA,IAAI,OAAO,CAAC,OAAO,EAAE;YACnB,eAAe,CAAC,IAAI,CAAC;AACnB,gBAAA,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,OAAO;AAC7B,gBAAA,QAAQ,EACN,OAAO,CAAC,OAAO,CAAC,eAAe,KAAK,OAAO,GAAG,OAAO,GAAG,UAAU;AACrE,aAAA,CAAC;QACJ;AACA,QAAA,IAAI,OAAO,CAAC,OAAO,EAAE;YACnB,eAAe,CAAC,IAAI,CAAC;AACnB,gBAAA,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,OAAO;AAC7B,gBAAA,QAAQ,EACN,OAAO,CAAC,OAAO,CAAC,eAAe,KAAK,OAAO,GAAG,OAAO,GAAG,UAAU;AACrE,aAAA,CAAC;QACJ;AACA,QAAA,GAAG,CAAC,IAAI,CACN,kBAAkB,CAChB,kBAAkB,CAAC,OAAO,CAAC,YAAY,EAAE,eAAe,CAAC,EACzD;AACE,YAAA,IAAI,EAAE,cAAc;YACpB,MAAM,EAAE,OAAO,CAAC,YAAY;AAC7B,SAAA,CACF,CACF;IACH;;;;;AAKA,IAAA,IAAI,OAAO,CAAC,QAAQ,EAAE;AACpB,QAAA,GAAG,CAAC,IAAI,CACN,kBAAkB,CAChB,oBAAoB,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EACnE,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,QAAQ,EAAE,CAC/C,CACF;IACH;AACA,IAAA,OAAO,GAAG;AACZ;;"}
|
|
@@ -18,8 +18,20 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { Extension } from '@tiptap/core';
|
|
20
20
|
import type { AutocompleteConfig } from './types.js';
|
|
21
|
+
/**
|
|
22
|
+
* A trigger character that autocomplete stands down for, so a co-installed
|
|
23
|
+
* mention or command picker wins while its trigger is active. Pass a list of
|
|
24
|
+
* these as the second argument to {@link carbonAutocomplete}.
|
|
25
|
+
*/
|
|
21
26
|
export interface ExcludedTrigger {
|
|
27
|
+
/** The character to stand down for, such as `"@"` or `"/"`. */
|
|
22
28
|
char: string;
|
|
29
|
+
/**
|
|
30
|
+
* Where that character has to sit. `"anywhere"` stands down for any word
|
|
31
|
+
* starting with it; `"start"` stands down only when that word starts the
|
|
32
|
+
* line. Mirrors the picker's own
|
|
33
|
+
* {@link TriggerSuggestionConfig.triggerPosition}.
|
|
34
|
+
*/
|
|
23
35
|
position: 'anywhere' | 'start';
|
|
24
36
|
}
|
|
25
37
|
export declare function carbonAutocomplete(config: AutocompleteConfig, excludeTriggers?: ExcludedTrigger[]): Extension;
|