@carbon/ai-chat-components 1.13.0 → 1.14.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/custom-elements.json +1147 -462
- package/es/components/audio-player/src/audio-player.scss.js +1 -1
- package/es/components/audio-player/src/transcript.js +15 -0
- package/es/components/audio-player/src/transcript.js.map +1 -1
- package/es/components/card/src/card-footer.scss.js +1 -1
- package/es/components/card/src/card-steps.scss.js +1 -1
- package/es/components/card/src/card.scss.js +1 -1
- package/es/components/chat-button/src/chat-button.scss.js +1 -1
- package/es/components/chat-history/src/chat-history.scss.js +1 -1
- package/es/components/chat-shell/src/shell.scss.js +1 -1
- package/es/components/code-snippet/src/code-snippet.d.ts +3 -2
- package/es/components/code-snippet/src/code-snippet.js +4 -3
- package/es/components/code-snippet/src/code-snippet.js.map +1 -1
- package/es/components/code-snippet/src/code-snippet.scss.js +1 -1
- package/es/components/feedback/src/feedback.js +17 -3
- package/es/components/feedback/src/feedback.js.map +1 -1
- package/es/components/file-uploads/src/file-upload-item.scss.js +1 -1
- package/es/components/file-uploads/src/file-uploads.scss.js +1 -1
- package/es/components/launcher/src/launcher.scss.js +1 -1
- package/es/components/markdown/__tests__/inline-selection-fixture.d.ts +13 -0
- package/es/components/markdown/index.d.ts +2 -0
- package/es/components/markdown/index.js +3 -0
- package/es/components/markdown/index.js.map +1 -1
- package/es/components/markdown/src/inline-markdown.d.ts +41 -0
- package/es/components/markdown/src/inline-markdown.js +92 -0
- package/es/components/markdown/src/inline-markdown.js.map +1 -0
- package/es/components/markdown/src/inline-markdown.scss.js +13 -0
- package/es/components/markdown/src/inline-markdown.scss.js.map +1 -0
- package/es/components/markdown/src/inline-run-projection.scss.js +13 -0
- package/es/components/markdown/src/inline-run-projection.scss.js.map +1 -0
- package/es/components/markdown/src/markdown-renderer.js +131 -25
- package/es/components/markdown/src/markdown-renderer.js.map +1 -1
- package/es/components/markdown/src/markdown.js +1 -0
- package/es/components/markdown/src/markdown.js.map +1 -1
- package/es/components/markdown/src/markdown.scss.js +1 -1
- package/es/components/markdown/src/utils/inline-run-projection.d.ts +15 -0
- package/es/components/markdown/src/utils/inline-run-projection.js +196 -0
- package/es/components/markdown/src/utils/inline-run-projection.js.map +1 -0
- package/es/components/markdown/src/utils/inline-validation.d.ts +13 -0
- package/es/components/markdown/src/utils/inline-validation.js +97 -0
- package/es/components/markdown/src/utils/inline-validation.js.map +1 -0
- package/es/components/markdown/src/utils/plugin-fallback.js +20 -13
- package/es/components/markdown/src/utils/plugin-fallback.js.map +1 -1
- package/es/components/markdown/src/utils/plugin-host-container.d.ts +5 -6
- package/es/components/markdown/src/utils/plugin-host-container.js.map +1 -1
- package/es/components/messages-shell/index.d.ts +11 -0
- package/es/components/messages-shell/index.js +9 -0
- package/es/components/messages-shell/index.js.map +1 -0
- package/es/components/messages-shell/src/messages-shell.d.ts +57 -0
- package/es/components/messages-shell/src/messages-shell.js +141 -0
- package/es/components/messages-shell/src/messages-shell.js.map +1 -0
- package/es/components/messages-shell/src/messages-shell.scss.js +13 -0
- package/es/components/messages-shell/src/messages-shell.scss.js.map +1 -0
- package/es/components/processing/src/processing.scss.js +1 -1
- package/es/components/prompt-line/autocomplete/src/autocomplete.d.ts +26 -9
- package/es/components/prompt-line/autocomplete/src/autocomplete.js +116 -107
- package/es/components/prompt-line/autocomplete/src/autocomplete.js.map +1 -1
- package/es/components/prompt-line/autocomplete/src/autocomplete.scss.js +1 -1
- package/es/components/prompt-line/src/autocomplete-controller-element.js +13 -1
- package/es/components/prompt-line/src/autocomplete-controller-element.js.map +1 -1
- package/es/components/prompt-line/src/autocomplete-controller.js +9 -2
- package/es/components/prompt-line/src/autocomplete-controller.js.map +1 -1
- package/es/components/prompt-line/src/prompt-line-controller.d.ts +7 -0
- package/es/components/prompt-line/src/prompt-line-rich-runtime.js +17 -0
- package/es/components/prompt-line/src/prompt-line-rich-runtime.js.map +1 -1
- package/es/components/prompt-line/src/prompt-line-shell.scss.js +1 -1
- package/es/components/prompt-line/src/prompt-line-textarea-runtime.d.ts +1 -0
- package/es/components/prompt-line/src/prompt-line-textarea-runtime.js +3 -0
- package/es/components/prompt-line/src/prompt-line-textarea-runtime.js.map +1 -1
- package/es/components/prompt-line/src/prompt-line.d.ts +7 -0
- package/es/components/prompt-line/src/prompt-line.js +9 -0
- package/es/components/prompt-line/src/prompt-line.js.map +1 -1
- package/es/components/prompt-line/src/send-control.scss.js +1 -1
- package/es/components/prompt-line/src/stop-streaming-button.scss.js +1 -1
- package/es/components/prompt-line/src/tiptap/carbon-mention.js +43 -21
- package/es/components/prompt-line/src/tiptap/carbon-mention.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/plain-text-paste.js +8 -3
- package/es/components/prompt-line/src/tiptap/plain-text-paste.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/strip-presentation-fields.d.ts +3 -3
- package/es/components/prompt-line/src/tiptap/strip-presentation-fields.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/types.d.ts +27 -11
- package/es/components/reasoning-steps/src/reasoning-step.d.ts +3 -3
- package/es/components/reasoning-steps/src/reasoning-step.js +4 -4
- package/es/components/reasoning-steps/src/reasoning-step.js.map +1 -1
- package/es/components/reasoning-steps/src/reasoning-step.scss.js +1 -1
- package/es/components/reasoning-steps/src/reasoning-steps-toggle.scss.js +1 -1
- package/es/components/reasoning-steps/src/reasoning-steps.d.ts +5 -4
- package/es/components/reasoning-steps/src/reasoning-steps.js +5 -4
- package/es/components/reasoning-steps/src/reasoning-steps.js.map +1 -1
- package/es/components/truncated-text/src/truncated-text.scss.js +1 -1
- package/es/components/video-player/src/video-player.scss.js +1 -1
- package/es/react/hooks/useChatAutocomplete.js +7 -1
- package/es/react/hooks/useChatAutocomplete.js.map +1 -1
- package/es/react/messages-shell.d.ts +3 -0
- package/es/react/messages-shell.js +32 -0
- package/es/react/messages-shell.js.map +1 -0
- package/es-custom/components/audio-player/src/audio-player.scss.js +1 -1
- package/es-custom/components/audio-player/src/transcript.js +15 -0
- package/es-custom/components/audio-player/src/transcript.js.map +1 -1
- package/es-custom/components/card/src/card-footer.scss.js +1 -1
- package/es-custom/components/card/src/card-steps.scss.js +1 -1
- package/es-custom/components/card/src/card.scss.js +1 -1
- package/es-custom/components/chat-button/src/chat-button.scss.js +1 -1
- package/es-custom/components/chat-history/src/chat-history.scss.js +1 -1
- package/es-custom/components/chat-shell/src/shell.scss.js +1 -1
- package/es-custom/components/code-snippet/src/code-snippet.d.ts +3 -2
- package/es-custom/components/code-snippet/src/code-snippet.js +4 -3
- package/es-custom/components/code-snippet/src/code-snippet.js.map +1 -1
- package/es-custom/components/code-snippet/src/code-snippet.scss.js +1 -1
- package/es-custom/components/feedback/src/feedback.js +17 -3
- package/es-custom/components/feedback/src/feedback.js.map +1 -1
- package/es-custom/components/file-uploads/src/file-upload-item.scss.js +1 -1
- package/es-custom/components/file-uploads/src/file-uploads.scss.js +1 -1
- package/es-custom/components/launcher/src/launcher.scss.js +1 -1
- package/es-custom/components/markdown/__tests__/inline-selection-fixture.d.ts +13 -0
- package/es-custom/components/markdown/index.d.ts +2 -0
- package/es-custom/components/markdown/index.js +3 -0
- package/es-custom/components/markdown/index.js.map +1 -1
- package/es-custom/components/markdown/src/inline-markdown.d.ts +41 -0
- package/es-custom/components/markdown/src/inline-markdown.js +92 -0
- package/es-custom/components/markdown/src/inline-markdown.js.map +1 -0
- package/es-custom/components/markdown/src/inline-markdown.scss.js +13 -0
- package/es-custom/components/markdown/src/inline-markdown.scss.js.map +1 -0
- package/es-custom/components/markdown/src/inline-run-projection.scss.js +13 -0
- package/es-custom/components/markdown/src/inline-run-projection.scss.js.map +1 -0
- package/es-custom/components/markdown/src/markdown-renderer.js +131 -25
- package/es-custom/components/markdown/src/markdown-renderer.js.map +1 -1
- package/es-custom/components/markdown/src/markdown.js +1 -0
- package/es-custom/components/markdown/src/markdown.js.map +1 -1
- package/es-custom/components/markdown/src/markdown.scss.js +1 -1
- package/es-custom/components/markdown/src/utils/inline-run-projection.d.ts +15 -0
- package/es-custom/components/markdown/src/utils/inline-run-projection.js +196 -0
- package/es-custom/components/markdown/src/utils/inline-run-projection.js.map +1 -0
- package/es-custom/components/markdown/src/utils/inline-validation.d.ts +13 -0
- package/es-custom/components/markdown/src/utils/inline-validation.js +97 -0
- package/es-custom/components/markdown/src/utils/inline-validation.js.map +1 -0
- package/es-custom/components/markdown/src/utils/plugin-fallback.js +20 -13
- 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 +5 -6
- package/es-custom/components/markdown/src/utils/plugin-host-container.js.map +1 -1
- package/es-custom/components/messages-shell/index.d.ts +11 -0
- package/es-custom/components/messages-shell/index.js +9 -0
- package/es-custom/components/messages-shell/index.js.map +1 -0
- package/es-custom/components/messages-shell/src/messages-shell.d.ts +57 -0
- package/es-custom/components/messages-shell/src/messages-shell.js +141 -0
- package/es-custom/components/messages-shell/src/messages-shell.js.map +1 -0
- package/es-custom/components/messages-shell/src/messages-shell.scss.js +13 -0
- package/es-custom/components/messages-shell/src/messages-shell.scss.js.map +1 -0
- package/es-custom/components/processing/src/processing.scss.js +1 -1
- package/es-custom/components/prompt-line/autocomplete/src/autocomplete.d.ts +26 -9
- package/es-custom/components/prompt-line/autocomplete/src/autocomplete.js +116 -107
- package/es-custom/components/prompt-line/autocomplete/src/autocomplete.js.map +1 -1
- package/es-custom/components/prompt-line/autocomplete/src/autocomplete.scss.js +1 -1
- package/es-custom/components/prompt-line/src/autocomplete-controller-element.js +13 -1
- package/es-custom/components/prompt-line/src/autocomplete-controller-element.js.map +1 -1
- package/es-custom/components/prompt-line/src/autocomplete-controller.js +9 -2
- package/es-custom/components/prompt-line/src/autocomplete-controller.js.map +1 -1
- package/es-custom/components/prompt-line/src/prompt-line-controller.d.ts +7 -0
- package/es-custom/components/prompt-line/src/prompt-line-rich-runtime.js +17 -0
- package/es-custom/components/prompt-line/src/prompt-line-rich-runtime.js.map +1 -1
- package/es-custom/components/prompt-line/src/prompt-line-shell.scss.js +1 -1
- package/es-custom/components/prompt-line/src/prompt-line-textarea-runtime.d.ts +1 -0
- package/es-custom/components/prompt-line/src/prompt-line-textarea-runtime.js +3 -0
- package/es-custom/components/prompt-line/src/prompt-line-textarea-runtime.js.map +1 -1
- package/es-custom/components/prompt-line/src/prompt-line.d.ts +7 -0
- package/es-custom/components/prompt-line/src/prompt-line.js +9 -0
- package/es-custom/components/prompt-line/src/prompt-line.js.map +1 -1
- package/es-custom/components/prompt-line/src/send-control.scss.js +1 -1
- package/es-custom/components/prompt-line/src/stop-streaming-button.scss.js +1 -1
- package/es-custom/components/prompt-line/src/tiptap/carbon-mention.js +43 -21
- package/es-custom/components/prompt-line/src/tiptap/carbon-mention.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/plain-text-paste.js +8 -3
- package/es-custom/components/prompt-line/src/tiptap/plain-text-paste.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/strip-presentation-fields.d.ts +3 -3
- package/es-custom/components/prompt-line/src/tiptap/strip-presentation-fields.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/types.d.ts +27 -11
- package/es-custom/components/reasoning-steps/src/reasoning-step.d.ts +3 -3
- package/es-custom/components/reasoning-steps/src/reasoning-step.js +4 -4
- package/es-custom/components/reasoning-steps/src/reasoning-step.js.map +1 -1
- package/es-custom/components/reasoning-steps/src/reasoning-step.scss.js +1 -1
- package/es-custom/components/reasoning-steps/src/reasoning-steps-toggle.scss.js +1 -1
- package/es-custom/components/reasoning-steps/src/reasoning-steps.d.ts +5 -4
- package/es-custom/components/reasoning-steps/src/reasoning-steps.js +5 -4
- package/es-custom/components/reasoning-steps/src/reasoning-steps.js.map +1 -1
- package/es-custom/components/truncated-text/src/truncated-text.scss.js +1 -1
- package/es-custom/components/video-player/src/video-player.scss.js +1 -1
- package/es-custom/react/hooks/useChatAutocomplete.js +7 -1
- package/es-custom/react/hooks/useChatAutocomplete.js.map +1 -1
- package/es-custom/react/messages-shell.d.ts +3 -0
- package/es-custom/react/messages-shell.js +32 -0
- package/es-custom/react/messages-shell.js.map +1 -0
- package/package.json +4 -4
- package/scss/_markdown-inline.scss +138 -0
- package/telemetry.yml +4 -0
|
@@ -0,0 +1,97 @@
|
|
|
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
|
+
* Reports source or output that cannot join an inline paragraph.
|
|
18
|
+
* @category Messaging
|
|
19
|
+
*/
|
|
20
|
+
class InlineMarkdownError extends Error {
|
|
21
|
+
constructor(code, message) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = 'InlineMarkdownError';
|
|
24
|
+
this.code = code;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const PHRASING = new Set('a abbr audio b bdi bdo br button canvas cite code data datalist del dfn em embed i iframe img input ins kbd label map mark meter noscript object output picture progress q ruby rp rt s samp select small span strong sub sup textarea time u var video wbr'.split(' '));
|
|
28
|
+
const BLOCK_TAGS = new Set('address article aside blockquote body caption col colgroup dd details dialog div dl dt fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html legend li main menu nav ol p pre search section summary table tbody td tfoot th thead tr ul'.split(' '));
|
|
29
|
+
function invalidOutput() {
|
|
30
|
+
throw new InlineMarkdownError('non-inline-output', 'renderInlineMarkdown received non-inline output; use phrasing HTML without custom elements.');
|
|
31
|
+
}
|
|
32
|
+
function validateInlineTree(tree, source) {
|
|
33
|
+
// A source with text but no tokens, such as a link reference definition,
|
|
34
|
+
// would otherwise render nothing.
|
|
35
|
+
if (!tree.children.length && !/\S/.test(source)) {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
const paragraph = tree.children[0];
|
|
39
|
+
if (tree.children.length !== 1 ||
|
|
40
|
+
paragraph.token.type !== 'paragraph_open' ||
|
|
41
|
+
paragraph.token.tag !== 'p') {
|
|
42
|
+
throw new InlineMarkdownError('block-content', 'renderInlineMarkdown accepts one inline paragraph; render block content with the markdown element.');
|
|
43
|
+
}
|
|
44
|
+
const visit = ({ token, children }) => {
|
|
45
|
+
if ((token.block && token.type !== 'inline') ||
|
|
46
|
+
BLOCK_TAGS.has(token.tag?.toLowerCase() ?? '') ||
|
|
47
|
+
token.tag?.includes('-') ||
|
|
48
|
+
token.attrs?.some(([name]) => name.toLowerCase() === 'is') ||
|
|
49
|
+
['fence', 'code_block', 'html_block', 'html_container'].includes(token.type ?? '')) {
|
|
50
|
+
invalidOutput();
|
|
51
|
+
}
|
|
52
|
+
children.forEach(visit);
|
|
53
|
+
};
|
|
54
|
+
paragraph.children.forEach(visit);
|
|
55
|
+
return paragraph;
|
|
56
|
+
}
|
|
57
|
+
function validateInlineAttributes(attributes) {
|
|
58
|
+
if (Object.keys(attributes).some((name) => name.toLowerCase() === 'is')) {
|
|
59
|
+
invalidOutput();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// Elements that are phrasing content only inside these parents.
|
|
63
|
+
const CONTEXTUAL_PARENTS = new Map([
|
|
64
|
+
['source', ['picture', 'audio', 'video']],
|
|
65
|
+
['track', ['audio', 'video']],
|
|
66
|
+
['optgroup', ['select']],
|
|
67
|
+
['option', ['select', 'optgroup', 'datalist']],
|
|
68
|
+
]);
|
|
69
|
+
const FOREIGN_NAMESPACES = [
|
|
70
|
+
'http://www.w3.org/2000/svg',
|
|
71
|
+
'http://www.w3.org/1998/Math/MathML',
|
|
72
|
+
];
|
|
73
|
+
function isInlineElement(element) {
|
|
74
|
+
const tag = element.localName.toLowerCase();
|
|
75
|
+
if (tag.includes('-') || element.hasAttribute('is')) {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
if (element.namespaceURI === 'http://www.w3.org/1999/xhtml') {
|
|
79
|
+
const parent = element.parentElement?.localName ?? '';
|
|
80
|
+
return PHRASING.has(tag) || !!CONTEXTUAL_PARENTS.get(tag)?.includes(parent);
|
|
81
|
+
}
|
|
82
|
+
return (FOREIGN_NAMESPACES.includes(element.namespaceURI ?? '') &&
|
|
83
|
+
tag !== 'script' &&
|
|
84
|
+
!(tag === 'math' && element.getAttribute('display') === 'block'));
|
|
85
|
+
}
|
|
86
|
+
function validateInlineHTML(html) {
|
|
87
|
+
const template = document.createElement('template');
|
|
88
|
+
template.innerHTML = html;
|
|
89
|
+
for (const element of template.content.querySelectorAll('*')) {
|
|
90
|
+
if (!isInlineElement(element)) {
|
|
91
|
+
invalidOutput();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export { InlineMarkdownError, validateInlineAttributes, validateInlineHTML, validateInlineTree };
|
|
97
|
+
//# sourceMappingURL=inline-validation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inline-validation.js","sources":["../../../../../src/components/markdown/src/utils/inline-validation.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\nimport type { TokenTree } from '../markdown-token-tree.js';\n\n/**\n * Reports source or output that cannot join an inline paragraph.\n * @category Messaging\n */\nexport class InlineMarkdownError extends Error {\n /** Stable reason for rejecting the complete run. */\n readonly code: 'block-content' | 'non-inline-output';\n\n constructor(code: 'block-content' | 'non-inline-output', message: string) {\n super(message);\n this.name = 'InlineMarkdownError';\n this.code = code;\n }\n}\n\nconst PHRASING = new Set(\n 'a abbr audio b bdi bdo br button canvas cite code data datalist del dfn em embed i iframe img input ins kbd label map mark meter noscript object output picture progress q ruby rp rt s samp select small span strong sub sup textarea time u var video wbr'.split(\n ' '\n )\n);\nconst BLOCK_TAGS = new Set(\n 'address article aside blockquote body caption col colgroup dd details dialog div dl dt fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html legend li main menu nav ol p pre search section summary table tbody td tfoot th thead tr ul'.split(\n ' '\n )\n);\n\nfunction invalidOutput(): never {\n throw new InlineMarkdownError(\n 'non-inline-output',\n 'renderInlineMarkdown received non-inline output; use phrasing HTML without custom elements.'\n );\n}\n\nexport function validateInlineTree(\n tree: TokenTree,\n source: string\n): TokenTree | undefined {\n // A source with text but no tokens, such as a link reference definition,\n // would otherwise render nothing.\n if (!tree.children.length && !/\\S/.test(source)) {\n return undefined;\n }\n const paragraph = tree.children[0];\n if (\n tree.children.length !== 1 ||\n paragraph.token.type !== 'paragraph_open' ||\n paragraph.token.tag !== 'p'\n ) {\n throw new InlineMarkdownError(\n 'block-content',\n 'renderInlineMarkdown accepts one inline paragraph; render block content with the markdown element.'\n );\n }\n const visit = ({ token, children }: TokenTree) => {\n if (\n (token.block && token.type !== 'inline') ||\n BLOCK_TAGS.has(token.tag?.toLowerCase() ?? '') ||\n token.tag?.includes('-') ||\n token.attrs?.some(([name]) => name.toLowerCase() === 'is') ||\n ['fence', 'code_block', 'html_block', 'html_container'].includes(\n token.type ?? ''\n )\n ) {\n invalidOutput();\n }\n children.forEach(visit);\n };\n paragraph.children.forEach(visit);\n return paragraph;\n}\n\nexport function validateInlineAttributes(\n attributes: Record<string, string>\n): void {\n if (Object.keys(attributes).some((name) => name.toLowerCase() === 'is')) {\n invalidOutput();\n }\n}\n\n// Elements that are phrasing content only inside these parents.\nconst CONTEXTUAL_PARENTS = new Map([\n ['source', ['picture', 'audio', 'video']],\n ['track', ['audio', 'video']],\n ['optgroup', ['select']],\n ['option', ['select', 'optgroup', 'datalist']],\n]);\n\nconst FOREIGN_NAMESPACES = [\n 'http://www.w3.org/2000/svg',\n 'http://www.w3.org/1998/Math/MathML',\n];\n\nfunction isInlineElement(element: Element): boolean {\n const tag = element.localName.toLowerCase();\n if (tag.includes('-') || element.hasAttribute('is')) {\n return false;\n }\n if (element.namespaceURI === 'http://www.w3.org/1999/xhtml') {\n const parent = element.parentElement?.localName ?? '';\n return PHRASING.has(tag) || !!CONTEXTUAL_PARENTS.get(tag)?.includes(parent);\n }\n return (\n FOREIGN_NAMESPACES.includes(element.namespaceURI ?? '') &&\n tag !== 'script' &&\n !(tag === 'math' && element.getAttribute('display') === 'block')\n );\n}\n\nexport function validateInlineHTML(html: string): void {\n const template = document.createElement('template');\n template.innerHTML = html;\n for (const element of template.content.querySelectorAll('*')) {\n if (!isInlineElement(element)) {\n invalidOutput();\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAIH;;;AAGG;AACG,MAAO,mBAAoB,SAAQ,KAAK,CAAA;IAI5C,WAAA,CAAY,IAA2C,EAAE,OAAe,EAAA;QACtE,KAAK,CAAC,OAAO,CAAC;AACd,QAAA,IAAI,CAAC,IAAI,GAAG,qBAAqB;AACjC,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI;IAClB;AACD;AAED,MAAM,QAAQ,GAAG,IAAI,GAAG,CACtB,6PAA6P,CAAC,KAAK,CACjQ,GAAG,CACJ,CACF;AACD,MAAM,UAAU,GAAG,IAAI,GAAG,CACxB,wQAAwQ,CAAC,KAAK,CAC5Q,GAAG,CACJ,CACF;AAED,SAAS,aAAa,GAAA;AACpB,IAAA,MAAM,IAAI,mBAAmB,CAC3B,mBAAmB,EACnB,6FAA6F,CAC9F;AACH;AAEM,SAAU,kBAAkB,CAChC,IAAe,EACf,MAAc,EAAA;;;AAId,IAAA,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;AAC/C,QAAA,OAAO,SAAS;IAClB;IACA,MAAM,SAAS,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AG,IAAI;AACzB,IAAA,KAAK,MAAM,OAAO,IAAI,QAAQ,CAAC,OAAO,CAAC,gBAAgB,CAAC,GAAG,CAAC,EAAE;AAC5D,QAAA,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,EAAE;AAC7B,YAAA,aAAa,EAAE;QACjB;IACF;AACF;;"}
|
|
@@ -177,6 +177,23 @@ function sliceForFallback(token, node) {
|
|
|
177
177
|
}
|
|
178
178
|
return [token];
|
|
179
179
|
}
|
|
180
|
+
function renderPluginHTML(token, node, md, sanitize) {
|
|
181
|
+
let safe;
|
|
182
|
+
if (node?.cachedHtml && node.cachedHtml.md === md) {
|
|
183
|
+
safe = node.cachedHtml.html;
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
const slice = sliceForFallback(token, node);
|
|
187
|
+
const htmlStr = md.renderer.render(slice, md.options, {});
|
|
188
|
+
safe = sanitize ? sanitizeHtmlContent(htmlStr) : htmlStr;
|
|
189
|
+
if (node &&
|
|
190
|
+
typeof token.type === 'string' &&
|
|
191
|
+
PLUGIN_DELEGABLE_TOKEN_TYPES.has(token.type)) {
|
|
192
|
+
node.cachedHtml = { md, html: safe };
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return safe;
|
|
196
|
+
}
|
|
180
197
|
/**
|
|
181
198
|
* Renders an unknown token via markdown-it's HTML renderer and emits a named
|
|
182
199
|
* `<slot>` placeholder carrying the token's text as its fallback content. The
|
|
@@ -195,19 +212,9 @@ function sliceForFallback(token, node) {
|
|
|
195
212
|
* the cache automatically.
|
|
196
213
|
*/
|
|
197
214
|
function renderFallback(token, node, md, sanitize, options) {
|
|
198
|
-
|
|
199
|
-
if (
|
|
200
|
-
|
|
201
|
-
}
|
|
202
|
-
else {
|
|
203
|
-
const slice = sliceForFallback(token, node);
|
|
204
|
-
const htmlStr = md.renderer.render(slice, md.options, {});
|
|
205
|
-
safe = sanitize ? sanitizeHtmlContent(htmlStr) : htmlStr;
|
|
206
|
-
if (node &&
|
|
207
|
-
typeof token.type === 'string' &&
|
|
208
|
-
PLUGIN_DELEGABLE_TOKEN_TYPES.has(token.type)) {
|
|
209
|
-
node.cachedHtml = { md, html: safe };
|
|
210
|
-
}
|
|
215
|
+
const safe = renderPluginHTML(token, node, md, sanitize);
|
|
216
|
+
if (options.inline) {
|
|
217
|
+
return options.inline.renderHTML(safe, token);
|
|
211
218
|
}
|
|
212
219
|
const index = options.pluginSlotCounter?.next(node) ?? 0;
|
|
213
220
|
const slotName = withInstanceNamespace(`${PLUGIN_FALLBACK_SLOT_PREFIX}-${index}`, options);
|
|
@@ -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 */\nconst 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 'softbreak',\n 'hardbreak',\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;;;;;;;AAOG;AAcH;;;;;;;;AAQG;AACH,MAAM,2BAA2B,GAC/B,6CAA6C;AAE/C;AACA;AACA,MAAM,4BAA4B,GAAG,IAAI,GAAG,CAAS;IACnD,MAAM;IACN,MAAM;IACN,WAAW;IACX,WAAW;IACX,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,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E,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;;"}
|
|
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 */\nconst 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 'softbreak',\n 'hardbreak',\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\nfunction renderPluginHTML(\n token: Token,\n node: TokenTree,\n md: MarkdownIt,\n sanitize: boolean\n): string {\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 return safe;\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 const safe = renderPluginHTML(token, node, md, sanitize);\n if (options.inline) {\n return options.inline.renderHTML(safe, token);\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;AACH,MAAM,2BAA2B,GAC/B,6CAA6C;AAE/C;AACA;AACA,MAAM,4BAA4B,GAAG,IAAI,GAAG,CAAS;IACnD,MAAM;IACN,MAAM;IACN,WAAW;IACX,WAAW;IACX,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,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C,MAAM,CAAC,UAAU,CAAC,IAAI,EAAE,KAAK,CAAC;IAC/C;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;;"}
|
|
@@ -46,8 +46,8 @@ export interface MarkdownPluginFallbackMountDetail {
|
|
|
46
46
|
isInline: boolean;
|
|
47
47
|
}
|
|
48
48
|
/**
|
|
49
|
-
* Mount detail for a
|
|
50
|
-
*
|
|
49
|
+
* Mount detail for a live custom-renderer host or projected inline run. Its
|
|
50
|
+
* renderer creates the element, keeps writing to it across renders, and removes it.
|
|
51
51
|
* Claiming it means re-parenting that element into your own light DOM,
|
|
52
52
|
* synchronously, and nothing else: never rewrite its content, never style it,
|
|
53
53
|
* never remove it. The markdown element renders the `<slot>` hop that projects
|
|
@@ -71,10 +71,9 @@ export interface MarkdownCustomRendererMountDetail {
|
|
|
71
71
|
*/
|
|
72
72
|
element: HTMLElement;
|
|
73
73
|
/**
|
|
74
|
-
* True
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
* so a listener can read it before narrowing on `kind`.
|
|
74
|
+
* True for a projected inline run, false for a block custom-renderer host.
|
|
75
|
+
* The renderer supplies the host tag, so the claimant only moves it.
|
|
76
|
+
* Declared on both members so a listener can read it before narrowing on `kind`.
|
|
78
77
|
*/
|
|
79
78
|
isInline: boolean;
|
|
80
79
|
}
|
|
@@ -1 +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,MAAM;IACf;IACA,OAAO,SAAS,IAAI;UAChB,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,gBAAgB;UACnC,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,gBAAgB,EAAE;AAC3C;AAyCA,MAAM,KAAK,GAAG,uCAAuC;AACrD,MAAM,MAAM,GAAG,wCAAwC;AACvD,MAAM,OAAO,GAAG,yCAAyC;AAEzD;;;;;;;;;;;;;;;AAeG;SACa,kCAAkC,CAChD,MAAmB,EACnB,UAA+C,EAAE,EAAA;AAEjD,IAAA,MAAM,EAAE,iBAAiB,EAAE,WAAW,EAAE,GAAG,OAAO;;;;;;;AAOlD,IAAA,MAAM,KAAK,GAAG,IAAI,GAAG,EAAuB;IAC5C,IAAI,SAAS,GAAa,EAAE;;;;AAK5B,IAAA,MAAM,WAAW,GAAG,CAAC,KAAY,KAAI;AACnC,QAAA,MAAM,GAAG,GACP,KACD,CAAC,MAAM;AACR,QAAA,IAAI,CAAC,GAAG,EAAE,QAAQ,EAAE;YAClB;QACF;AACA,QAAA,MAAM,MAAM,GAAG,oCAAoC,CAAC,GAAG,CAAC;;;QAIxD,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE;YACxC,SAAS,GAAG,CAAC,GAAG,SAAS,EAAE,MAAM,CAAC,QAAQ,CAAC;AAC3C,YAAA,iBAAiB,GAAG,SAAS,CAAC;QAChC;AAC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AAC;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;;"}
|
|
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 live custom-renderer host or projected inline run. Its\n * renderer creates the element, keeps writing to it across renders, and removes it.\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 for a projected inline run, false for a block custom-renderer host.\n * The renderer supplies the host tag, so the claimant only moves it.\n * Declared on both members 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;AA6GH;;;;;;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,gBAAgB,EAAE;AAC3C;AAyCA,MAAM,KAAK,GAAG,uCAAuC;AACrD,MAAM,MAAM,GAAG,wCAAwC;AACvD,MAAM,OAAO,GAAG,yCAAyC;AAEzD;;;;;;;;;;;;;;;AAeG;SACa,kCAAkC,CAChD,MAAmB,EACnB,UAA+C,EAAE,EAAA;AAEjD,IAAA,MAAM,EAAE,iBAAiB,EAAE,WAAW,EAAE,GAAG,OAAO;;;;;;;AAOlD,IAAA,MAAM,KAAK,GAAG,IAAI,GAAG,EAAuB;IAC5C,IAAI,SAAS,GAAa,EAAE;;;;AAK5B,IAAA,MAAM,WAAW,GAAG,CAAC,KAAY,KAAI;AACnC,QAAA,MAAM,GAAG,GACP,KACD,CAAC,MAAM;AACR,QAAA,IAAI,CAAC,GAAG,EAAE,QAAQ,EAAE;YAClB;QACF;AACA,QAAA,MAAM,MAAM,GAAG,oCAAoC,CAAC,GAAG,CAAC;;;QAIxD,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE;YACxC,SAAS,GAAG,CAAC,GAAG,SAAS,EAAE,MAAM,CAAC,QAAQ,CAAC;AAC3C,YAAA,iBAAiB,GAAG,SAAS,CAAC;QAChC;AACA,QAAA,IAAI,WAAW,GAAG,KAAK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AI,KAAK,CAAC,MAAM,EAAE,EAAE;gBACjC,IAAI,CAAC,MAAM,EAAE;YACf;YACA,KAAK,CAAC,KAAK,EAAE;;;;;;;QAOf,CAAC;KACF;AACH;;"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
*
|
|
4
|
+
* Copyright IBM Corp. 2025, 2026
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the Apache-2.0 license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*/
|
|
9
|
+
import './src/messages-shell.js';
|
|
10
|
+
export { default as CDSAIChatMessagesShell } from './src/messages-shell.js';
|
|
11
|
+
export type { MessagesShellScrollDetail } from './src/messages-shell.js';
|
|
@@ -0,0 +1,9 @@
|
|
|
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
|
+
export { default as CDSAIChatMessagesShell } from './src/messages-shell.js';
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { LitElement } from 'lit';
|
|
2
|
+
/**
|
|
3
|
+
* Details sent with each scroll event from the message list.
|
|
4
|
+
*/
|
|
5
|
+
export interface MessagesShellScrollDetail {
|
|
6
|
+
/** How far the list is scrolled from the top, in pixels. */
|
|
7
|
+
scrollTop: number;
|
|
8
|
+
/** The full height of the content, in pixels. */
|
|
9
|
+
scrollHeight: number;
|
|
10
|
+
/** The visible height of the list, in pixels. */
|
|
11
|
+
clientHeight: number;
|
|
12
|
+
/** Whether the content is taller than the visible area. */
|
|
13
|
+
isScrollable: boolean;
|
|
14
|
+
/** Whether the list is scrolled to the bottom (within 1px). */
|
|
15
|
+
isAtBottom: boolean;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Layout container for the chat message list. It provides named slots for the
|
|
19
|
+
* rows and the controls around them, and reports scroll position. Autoscroll
|
|
20
|
+
* and row navigation are not part of this element yet.
|
|
21
|
+
*
|
|
22
|
+
* @experimental
|
|
23
|
+
* @element cds-aichat-messages-shell
|
|
24
|
+
*
|
|
25
|
+
* @slot notifications - Sticky notices above the scroller (e.g. human-agent banners).
|
|
26
|
+
* @slot - Default slot. Message rows go here, inside the scroll container.
|
|
27
|
+
* @slot processing - The typing / processing indicator, inside the scroll container.
|
|
28
|
+
* @slot scroll-down - The scroll-to-bottom control. Rendered sticky inside the scroller.
|
|
29
|
+
* @slot error - Footer errors anchored below the scroller.
|
|
30
|
+
*
|
|
31
|
+
* @fires {CustomEvent<MessagesShellScrollDetail>} cds-aichat-messages-shell-scroll -
|
|
32
|
+
* Fired on every scroll event. Detail carries position and geometry readings.
|
|
33
|
+
*/
|
|
34
|
+
declare class CDSAIChatMessagesShell extends LitElement {
|
|
35
|
+
static styles: any[];
|
|
36
|
+
/** Name of the event fired when the list scrolls. */
|
|
37
|
+
static get eventScroll(): string;
|
|
38
|
+
/**
|
|
39
|
+
* Visible and accessible label for the top scroll handle.
|
|
40
|
+
* Provide a translated string for the host's locale. The handle is omitted when empty.
|
|
41
|
+
*/
|
|
42
|
+
topHandleLabel: string;
|
|
43
|
+
/**
|
|
44
|
+
* Visible and accessible label for the bottom scroll handle.
|
|
45
|
+
* Provide a translated string for the host's locale. The handle is omitted when empty.
|
|
46
|
+
*/
|
|
47
|
+
bottomHandleLabel: string;
|
|
48
|
+
private _scroller;
|
|
49
|
+
private _handleScroll;
|
|
50
|
+
private _onHandleFocus;
|
|
51
|
+
private _onHandleBlur;
|
|
52
|
+
private _onHandleKeyDown;
|
|
53
|
+
private _renderScrollHandle;
|
|
54
|
+
render(): import("lit-html").TemplateResult<1>;
|
|
55
|
+
}
|
|
56
|
+
export { CDSAIChatMessagesShell };
|
|
57
|
+
export default CDSAIChatMessagesShell;
|
|
@@ -0,0 +1,141 @@
|
|
|
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
|
+
import { __decorate } from 'tslib';
|
|
9
|
+
import { LitElement, nothing, html } from 'lit';
|
|
10
|
+
import { property, query } from 'lit/decorators.js';
|
|
11
|
+
import { carbonElement } from '../../../globals/decorators/carbon-element.js';
|
|
12
|
+
import prefix from '../../../globals/settings.js';
|
|
13
|
+
import commonStyles from '../../../globals/scss/common.scss.js';
|
|
14
|
+
import styles from './messages-shell.scss.js';
|
|
15
|
+
|
|
16
|
+
/*
|
|
17
|
+
* Copyright IBM Corp. 2025, 2026
|
|
18
|
+
*
|
|
19
|
+
* This source code is licensed under the Apache-2.0 license found in the
|
|
20
|
+
* LICENSE file in the root directory of this source tree.
|
|
21
|
+
*
|
|
22
|
+
* @license
|
|
23
|
+
*/
|
|
24
|
+
var CDSAIChatMessagesShell_1;
|
|
25
|
+
const blockClass = `${prefix}-messages-shell`;
|
|
26
|
+
const focusClass = `${blockClass}__scroller--handle-focused`;
|
|
27
|
+
/**
|
|
28
|
+
* Layout container for the chat message list. It provides named slots for the
|
|
29
|
+
* rows and the controls around them, and reports scroll position. Autoscroll
|
|
30
|
+
* and row navigation are not part of this element yet.
|
|
31
|
+
*
|
|
32
|
+
* @experimental
|
|
33
|
+
* @element cds-aichat-messages-shell
|
|
34
|
+
*
|
|
35
|
+
* @slot notifications - Sticky notices above the scroller (e.g. human-agent banners).
|
|
36
|
+
* @slot - Default slot. Message rows go here, inside the scroll container.
|
|
37
|
+
* @slot processing - The typing / processing indicator, inside the scroll container.
|
|
38
|
+
* @slot scroll-down - The scroll-to-bottom control. Rendered sticky inside the scroller.
|
|
39
|
+
* @slot error - Footer errors anchored below the scroller.
|
|
40
|
+
*
|
|
41
|
+
* @fires {CustomEvent<MessagesShellScrollDetail>} cds-aichat-messages-shell-scroll -
|
|
42
|
+
* Fired on every scroll event. Detail carries position and geometry readings.
|
|
43
|
+
*/
|
|
44
|
+
let CDSAIChatMessagesShell = CDSAIChatMessagesShell_1 = class CDSAIChatMessagesShell extends LitElement {
|
|
45
|
+
constructor() {
|
|
46
|
+
super(...arguments);
|
|
47
|
+
/**
|
|
48
|
+
* Visible and accessible label for the top scroll handle.
|
|
49
|
+
* Provide a translated string for the host's locale. The handle is omitted when empty.
|
|
50
|
+
*/
|
|
51
|
+
this.topHandleLabel = '';
|
|
52
|
+
/**
|
|
53
|
+
* Visible and accessible label for the bottom scroll handle.
|
|
54
|
+
* Provide a translated string for the host's locale. The handle is omitted when empty.
|
|
55
|
+
*/
|
|
56
|
+
this.bottomHandleLabel = '';
|
|
57
|
+
this._handleScroll = () => {
|
|
58
|
+
const { scrollTop, scrollHeight, clientHeight } = this._scroller;
|
|
59
|
+
this.dispatchEvent(new CustomEvent(CDSAIChatMessagesShell_1.eventScroll, {
|
|
60
|
+
bubbles: true,
|
|
61
|
+
composed: true,
|
|
62
|
+
detail: {
|
|
63
|
+
scrollTop,
|
|
64
|
+
scrollHeight,
|
|
65
|
+
clientHeight,
|
|
66
|
+
isScrollable: scrollHeight > clientHeight,
|
|
67
|
+
// Allow 1px of slack, because scroll positions can be fractional.
|
|
68
|
+
isAtBottom: scrollHeight - scrollTop - clientHeight <= 1,
|
|
69
|
+
},
|
|
70
|
+
}));
|
|
71
|
+
};
|
|
72
|
+
// The focus ring is switched on and off by editing the class directly,
|
|
73
|
+
// not through reactive state. A re-render while the handle has focus
|
|
74
|
+
// can make the browser drop that focus.
|
|
75
|
+
this._onHandleFocus = () => {
|
|
76
|
+
this._scroller.classList.add(focusClass);
|
|
77
|
+
};
|
|
78
|
+
this._onHandleBlur = () => {
|
|
79
|
+
this._scroller.classList.remove(focusClass);
|
|
80
|
+
};
|
|
81
|
+
this._onHandleKeyDown = (event) => {
|
|
82
|
+
if (event.key === 'Escape') {
|
|
83
|
+
event.preventDefault();
|
|
84
|
+
event.currentTarget.blur();
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** Name of the event fired when the list scrolls. */
|
|
89
|
+
static get eventScroll() {
|
|
90
|
+
return `${blockClass}-scroll`;
|
|
91
|
+
}
|
|
92
|
+
_renderScrollHandle(label) {
|
|
93
|
+
if (!label) {
|
|
94
|
+
return nothing;
|
|
95
|
+
}
|
|
96
|
+
return html `
|
|
97
|
+
<button
|
|
98
|
+
type="button"
|
|
99
|
+
class="${blockClass}__scroll-handle"
|
|
100
|
+
aria-label=${label}
|
|
101
|
+
@focus=${this._onHandleFocus}
|
|
102
|
+
@blur=${this._onHandleBlur}
|
|
103
|
+
@keydown=${this._onHandleKeyDown}>
|
|
104
|
+
${label}
|
|
105
|
+
</button>
|
|
106
|
+
`;
|
|
107
|
+
}
|
|
108
|
+
render() {
|
|
109
|
+
return html `
|
|
110
|
+
<slot name="notifications" class="${blockClass}__notifications"></slot>
|
|
111
|
+
${this._renderScrollHandle(this.topHandleLabel)}
|
|
112
|
+
<div class="${blockClass}__scroller" @scroll=${this._handleScroll}>
|
|
113
|
+
<div class="${blockClass}__content">
|
|
114
|
+
<slot></slot>
|
|
115
|
+
<slot name="processing"></slot>
|
|
116
|
+
<div class="${blockClass}__spacer"></div>
|
|
117
|
+
<slot name="scroll-down"></slot>
|
|
118
|
+
</div>
|
|
119
|
+
</div>
|
|
120
|
+
${this._renderScrollHandle(this.bottomHandleLabel)}
|
|
121
|
+
<slot name="error" class="${blockClass}__error"></slot>
|
|
122
|
+
`;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
CDSAIChatMessagesShell.styles = [commonStyles, styles];
|
|
126
|
+
__decorate([
|
|
127
|
+
property({ attribute: 'top-handle-label' })
|
|
128
|
+
], CDSAIChatMessagesShell.prototype, "topHandleLabel", void 0);
|
|
129
|
+
__decorate([
|
|
130
|
+
property({ attribute: 'bottom-handle-label' })
|
|
131
|
+
], CDSAIChatMessagesShell.prototype, "bottomHandleLabel", void 0);
|
|
132
|
+
__decorate([
|
|
133
|
+
query(`.${blockClass}__scroller`)
|
|
134
|
+
], CDSAIChatMessagesShell.prototype, "_scroller", void 0);
|
|
135
|
+
CDSAIChatMessagesShell = CDSAIChatMessagesShell_1 = __decorate([
|
|
136
|
+
carbonElement(blockClass)
|
|
137
|
+
], CDSAIChatMessagesShell);
|
|
138
|
+
var CDSAIChatMessagesShell$1 = CDSAIChatMessagesShell;
|
|
139
|
+
|
|
140
|
+
export { CDSAIChatMessagesShell, CDSAIChatMessagesShell$1 as default };
|
|
141
|
+
//# sourceMappingURL=messages-shell.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"messages-shell.js","sources":["../../../../src/components/messages-shell/src/messages-shell.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 { LitElement, html, nothing } from 'lit';\nimport { property, query } from 'lit/decorators.js';\nimport { carbonElement } from '../../../globals/decorators/index.js';\nimport prefix from '../../../globals/settings.js';\nimport commonStyles from '../../../globals/scss/common.scss?lit';\nimport styles from './messages-shell.scss?lit';\n\nconst blockClass = `${prefix}-messages-shell`;\nconst focusClass = `${blockClass}__scroller--handle-focused`;\n\n/**\n * Details sent with each scroll event from the message list.\n */\nexport interface MessagesShellScrollDetail {\n /** How far the list is scrolled from the top, in pixels. */\n scrollTop: number;\n /** The full height of the content, in pixels. */\n scrollHeight: number;\n /** The visible height of the list, in pixels. */\n clientHeight: number;\n /** Whether the content is taller than the visible area. */\n isScrollable: boolean;\n /** Whether the list is scrolled to the bottom (within 1px). */\n isAtBottom: boolean;\n}\n\n/**\n * Layout container for the chat message list. It provides named slots for the\n * rows and the controls around them, and reports scroll position. Autoscroll\n * and row navigation are not part of this element yet.\n *\n * @experimental\n * @element cds-aichat-messages-shell\n *\n * @slot notifications - Sticky notices above the scroller (e.g. human-agent banners).\n * @slot - Default slot. Message rows go here, inside the scroll container.\n * @slot processing - The typing / processing indicator, inside the scroll container.\n * @slot scroll-down - The scroll-to-bottom control. Rendered sticky inside the scroller.\n * @slot error - Footer errors anchored below the scroller.\n *\n * @fires {CustomEvent<MessagesShellScrollDetail>} cds-aichat-messages-shell-scroll -\n * Fired on every scroll event. Detail carries position and geometry readings.\n */\n@carbonElement(blockClass)\nclass CDSAIChatMessagesShell extends LitElement {\n static styles = [commonStyles, styles];\n\n /** Name of the event fired when the list scrolls. */\n static get eventScroll() {\n return `${blockClass}-scroll`;\n }\n\n /**\n * Visible and accessible label for the top scroll handle.\n * Provide a translated string for the host's locale. The handle is omitted when empty.\n */\n @property({ attribute: 'top-handle-label' })\n topHandleLabel = '';\n\n /**\n * Visible and accessible label for the bottom scroll handle.\n * Provide a translated string for the host's locale. The handle is omitted when empty.\n */\n @property({ attribute: 'bottom-handle-label' })\n bottomHandleLabel = '';\n\n @query(`.${blockClass}__scroller`)\n private _scroller!: HTMLElement;\n\n private _handleScroll = (): void => {\n const { scrollTop, scrollHeight, clientHeight } = this._scroller;\n\n this.dispatchEvent(\n new CustomEvent<MessagesShellScrollDetail>(\n CDSAIChatMessagesShell.eventScroll,\n {\n bubbles: true,\n composed: true,\n detail: {\n scrollTop,\n scrollHeight,\n clientHeight,\n isScrollable: scrollHeight > clientHeight,\n // Allow 1px of slack, because scroll positions can be fractional.\n isAtBottom: scrollHeight - scrollTop - clientHeight <= 1,\n },\n }\n )\n );\n };\n\n // The focus ring is switched on and off by editing the class directly,\n // not through reactive state. A re-render while the handle has focus\n // can make the browser drop that focus.\n private _onHandleFocus = (): void => {\n this._scroller.classList.add(focusClass);\n };\n\n private _onHandleBlur = (): void => {\n this._scroller.classList.remove(focusClass);\n };\n\n private _onHandleKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') {\n event.preventDefault();\n (event.currentTarget as HTMLElement).blur();\n }\n };\n\n private _renderScrollHandle(label: string) {\n if (!label) {\n return nothing;\n }\n return html`\n <button\n type=\"button\"\n class=\"${blockClass}__scroll-handle\"\n aria-label=${label}\n @focus=${this._onHandleFocus}\n @blur=${this._onHandleBlur}\n @keydown=${this._onHandleKeyDown}>\n ${label}\n </button>\n `;\n }\n\n render() {\n return html`\n <slot name=\"notifications\" class=\"${blockClass}__notifications\"></slot>\n ${this._renderScrollHandle(this.topHandleLabel)}\n <div class=\"${blockClass}__scroller\" @scroll=${this._handleScroll}>\n <div class=\"${blockClass}__content\">\n <slot></slot>\n <slot name=\"processing\"></slot>\n <div class=\"${blockClass}__spacer\"></div>\n <slot name=\"scroll-down\"></slot>\n </div>\n </div>\n ${this._renderScrollHandle(this.bottomHandleLabel)}\n <slot name=\"error\" class=\"${blockClass}__error\"></slot>\n `;\n }\n}\n\nexport { CDSAIChatMessagesShell };\nexport default CDSAIChatMessagesShell;\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA;;;;;;;AAOG;;AASH,MAAM,UAAU,GAAG,CAAA,EAAG,MAAM,iBAAiB;AAC7C,MAAM,UAAU,GAAG,CAAA,EAAG,UAAU,4BAA4B;AAkB5D;;;;;;;;;;;;;;;;AAgBG;AAEH,IAAM,sBAAsB,GAAA,wBAAA,GAA5B,MAAM,sBAAuB,SAAQ,UAAU,CAAA;AAA/C,IAAA,WAAA,GAAA;;AAQE;;;AAGG;QAEH,IAAA,CAAA,cAAc,GAAG,EAAE;AAEnB;;;AAGG;QAEH,IAAA,CAAA,iBAAiB,GAAG,EAAE;QAKd,IAAA,CAAA,aAAa,GAAG,MAAW;YACjC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC,SAAS;YAEhE,IAAI,CAAC,aAAa,CAChB,IAAI,WAAW,CACb,wBAAsB,CAAC,WAAW,E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EAAA,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,cAAc,CAAC;oBACjC,UAAU,CAAA,oBAAA,EAAuB,IAAI,CAAC,aAAa,CAAA;sBACjD,UAAU,CAAA;;;wBAGR,UAAU,CAAA;;;;AAI1B,MAAA,EAAA,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,iBAAiB,CAAC;kCACtB,UAAU,CAAA;KACvC;IACH;;AAhGO,sBAAA,CAAA,MAAM,GAAG,CAAC,YAAY,EAAE,MAAM,CAAC;AAYtC,UAAA,CAAA;AADC,IAAA,QAAQ,CAAC,EAAE,SAAS,EAAE,kBAAkB,EAAE;AACvB,CAAA,EAAA,sBAAA,CAAA,SAAA,EAAA,gBAAA,EAAA,MAAA,CAAA;AAOpB,UAAA,CAAA;AADC,IAAA,QAAQ,CAAC,EAAE,SAAS,EAAE,qBAAqB,EAAE;AACvB,CAAA,EAAA,sBAAA,CAAA,SAAA,EAAA,mBAAA,EAAA,MAAA,CAAA;AAGf,UAAA,CAAA;AADP,IAAA,KAAK,CAAC,CAAA,CAAA,EAAI,UAAU,CAAA,UAAA,CAAY;AACD,CAAA,EAAA,sBAAA,CAAA,SAAA,EAAA,WAAA,EAAA,MAAA,CAAA;AAvB5B,sBAAsB,GAAA,wBAAA,GAAA,UAAA,CAAA;IAD3B,aAAa,CAAC,UAAU;AACnB,CAAA,EAAA,sBAAsB,CAkG3B;AAGD,+BAAe,sBAAsB;;"}
|
|
@@ -0,0 +1,13 @@
|
|
|
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
|
+
import { css } from 'lit';
|
|
9
|
+
|
|
10
|
+
var styles = css([":host(cds-aichat-messages-shell){block-size:100%;display:flex;flex-direction:column;inline-size:100%;min-block-size:0;overflow:hidden}slot[name=notifications]{display:block;flex-shrink:0}.cds-aichat-messages-shell__scroll-handle{background:none;block-size:1px;border:none;flex-shrink:0;margin:0;overflow:hidden;padding:0;position:absolute;clip:rect(0 0 0 0);clip-path:inset(50%);color:inherit;cursor:default;font:inherit;inline-size:1px;outline:none;white-space:nowrap}@media (hover:hover) and (pointer:fine){.cds-aichat-messages-shell__scroll-handle{block-size:0;overflow:hidden;padding:0 1rem;position:static;clip:auto;clip-path:none;inline-size:100%;margin-inline:auto;max-inline-size:var(--cds-aichat-messages-max-width,672px);pointer-events:none;white-space:normal}.cds-aichat-messages-shell__scroll-handle:focus-visible{block-size:auto;border:1px solid var(--cds-focus,#0f62fe);outline:none;padding-block:1rem;pointer-events:auto}}.cds-aichat-messages-shell__scroller{block-size:100%;flex:1 1 auto;inline-size:100%;min-block-size:0;overflow:hidden auto;overscroll-behavior:contain;position:relative}.cds-aichat-messages-shell__scroller--handle-focused{outline:2px solid var(--cds-focus,#0f62fe);outline-offset:-2px}.cds-aichat-messages-shell__content{block-size:100%;inline-size:100%}slot[name=processing]{display:block;min-block-size:2rem}slot[name=scroll-down]{display:block;inset-block-end:1rem;position:sticky;z-index:1}slot[name=error]{display:block;flex-shrink:0}"]);
|
|
11
|
+
|
|
12
|
+
export { styles as default };
|
|
13
|
+
//# sourceMappingURL=messages-shell.scss.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"messages-shell.scss.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;"}
|