@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
|
@@ -104,8 +104,10 @@ declare class CDSAIChatMarkdown extends LitElement {
|
|
|
104
104
|
* default Carbon rendering. Returning the same element reference across
|
|
105
105
|
* renders avoids DOM churn.
|
|
106
106
|
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
107
|
+
* Inside a chat, a container relocates the returned element into its own
|
|
108
|
+
* light DOM — page DOM at the top of the chain — and this element forwards
|
|
109
|
+
* it back into the named slot, so consumer-loaded page CSS reaches it.
|
|
110
|
+
* Standalone (no chat ancestor), it stays a light-DOM child of this element.
|
|
109
111
|
*/
|
|
110
112
|
customRenderers?: MarkdownCustomRenderers;
|
|
111
113
|
private hasRenderedStreamingTableLoadingFrame;
|
|
@@ -125,6 +127,7 @@ declare class CDSAIChatMarkdown extends LitElement {
|
|
|
125
127
|
protected willUpdate(changed: PropertyValues<this>): void;
|
|
126
128
|
protected getUpdateComplete(): Promise<boolean>;
|
|
127
129
|
protected updated(changed: PropertyValues<this>): void;
|
|
130
|
+
private retireDelegatedSlot;
|
|
128
131
|
protected render(): TemplateResult<1>;
|
|
129
132
|
}
|
|
130
133
|
declare global {
|
|
@@ -157,6 +157,19 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
|
|
|
157
157
|
* @internal
|
|
158
158
|
*/
|
|
159
159
|
this.slotHosts = new Map();
|
|
160
|
+
/**
|
|
161
|
+
* `<slot name=X slot=X>` forwarders minted for {@link customRenderers} hosts
|
|
162
|
+
* an outer listener relocated into its own light DOM, keyed by slot name.
|
|
163
|
+
*
|
|
164
|
+
* Appended imperatively rather than rendered: Lit commits into the shadow
|
|
165
|
+
* root, and this hop has to be a light-DOM child of this element to gather
|
|
166
|
+
* the relocated host out of the chat element's light DOM and hand it to the
|
|
167
|
+
* shadow `<slot>` the renderer emitted. Minted where the claim is read
|
|
168
|
+
* rather than by a subscriber, because the mount event fires once per host
|
|
169
|
+
* and is never replayed — a listener that subscribes later cannot mint it.
|
|
170
|
+
* @internal
|
|
171
|
+
*/
|
|
172
|
+
this.rendererForwarders = new Map();
|
|
160
173
|
/**
|
|
161
174
|
* Namespace appended to every slot name this element mints, so two markdown
|
|
162
175
|
* elements rendering identical markdown never collide in the shared
|
|
@@ -171,8 +184,8 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
|
|
|
171
184
|
this.slotNamespace = nextMarkdownInstanceId();
|
|
172
185
|
/**
|
|
173
186
|
* Slot names whose host was created by an outer listener (a chat container
|
|
174
|
-
* that called `preventDefault()` on the host-mount event). We track these
|
|
175
|
-
*
|
|
187
|
+
* that called `preventDefault()` on the host-mount event). We track these so
|
|
188
|
+
* we can fire matching unmount events without trying to remove a host we
|
|
176
189
|
* never appended.
|
|
177
190
|
* @internal
|
|
178
191
|
*/
|
|
@@ -433,15 +446,12 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
|
|
|
433
446
|
host.remove();
|
|
434
447
|
}
|
|
435
448
|
this.slotHosts.clear();
|
|
436
|
-
// Ask any delegating chat container to drop its hosts too.
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
detail: { slotName },
|
|
442
|
-
}));
|
|
449
|
+
// Ask any delegating chat container to drop its hosts too. The loop above
|
|
450
|
+
// already detached every relocated node — `slotHosts` holds the reference
|
|
451
|
+
// wherever the node ended up — so this retires forwarders and announces.
|
|
452
|
+
for (const slotName of this.delegatedPluginSlots.keys()) {
|
|
453
|
+
this.retireDelegatedSlot(slotName);
|
|
443
454
|
}
|
|
444
|
-
this.delegatedPluginSlots.clear();
|
|
445
455
|
this.latestRendererDescriptors = [];
|
|
446
456
|
}
|
|
447
457
|
adoptLightDomMarkdown() {
|
|
@@ -586,6 +596,40 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
|
|
|
586
596
|
super.updated(changed);
|
|
587
597
|
this.reconcileCustomRendererHosts();
|
|
588
598
|
}
|
|
599
|
+
/**
|
|
600
|
+
* Drops a claim: retires the forwarder minted for it, if any, then tells the
|
|
601
|
+
* container to let go.
|
|
602
|
+
*
|
|
603
|
+
* The forwarder goes first. An assigned node suppresses the shadow slot's
|
|
604
|
+
* fallback content for as long as it exists, so a surviving forwarder turns
|
|
605
|
+
* a removed host into a blank region instead of the default rendering.
|
|
606
|
+
* @internal
|
|
607
|
+
*/
|
|
608
|
+
/**
|
|
609
|
+
* Records a claim and mints the innermost hop back to the host the listener
|
|
610
|
+
* just relocated. Called in the same pass that read the claim because the
|
|
611
|
+
* mount event fires once per host and is never replayed — minting here is
|
|
612
|
+
* what makes a claim without its forwarder unrepresentable.
|
|
613
|
+
* @internal
|
|
614
|
+
*/
|
|
615
|
+
adoptDelegatedSlot(slotName) {
|
|
616
|
+
this.delegatedPluginSlots.add(slotName);
|
|
617
|
+
const forwarder = document.createElement('slot');
|
|
618
|
+
forwarder.setAttribute('name', slotName);
|
|
619
|
+
forwarder.setAttribute('slot', slotName);
|
|
620
|
+
this.rendererForwarders.set(slotName, forwarder);
|
|
621
|
+
this.appendChild(forwarder);
|
|
622
|
+
}
|
|
623
|
+
retireDelegatedSlot(slotName) {
|
|
624
|
+
this.rendererForwarders.get(slotName)?.remove();
|
|
625
|
+
this.rendererForwarders.delete(slotName);
|
|
626
|
+
this.delegatedPluginSlots.delete(slotName);
|
|
627
|
+
this.dispatchEvent(new CustomEvent('cds-custom-aichat-markdown-plugin-host-unmount', {
|
|
628
|
+
bubbles: true,
|
|
629
|
+
composed: true,
|
|
630
|
+
detail: { slotName },
|
|
631
|
+
}));
|
|
632
|
+
}
|
|
589
633
|
/**
|
|
590
634
|
* Invoke the consumer's `customRenderers` callbacks once per descriptor and
|
|
591
635
|
* adopt their returned `HTMLElement` as a `<span slot="…">` (for inline
|
|
@@ -615,6 +659,7 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
|
|
|
615
659
|
composed: true,
|
|
616
660
|
cancelable: true,
|
|
617
661
|
detail: {
|
|
662
|
+
kind: 'pluginFallback',
|
|
618
663
|
slotName: descriptor.slotName,
|
|
619
664
|
html: descriptor.html,
|
|
620
665
|
isInline: descriptor.isInline,
|
|
@@ -622,7 +667,7 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
|
|
|
622
667
|
});
|
|
623
668
|
this.dispatchEvent(mountEvent);
|
|
624
669
|
if (mountEvent.defaultPrevented) {
|
|
625
|
-
this.
|
|
670
|
+
this.adoptDelegatedSlot(descriptor.slotName);
|
|
626
671
|
}
|
|
627
672
|
}
|
|
628
673
|
else if (alreadyDelegated) {
|
|
@@ -694,13 +739,15 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
|
|
|
694
739
|
// element's own light DOM sits inside the chat's shadow root, where it
|
|
695
740
|
// cannot. Mirrors the plugin-fallback path above, but forwards the live
|
|
696
741
|
// host element instead of an HTML string; the markdown element keeps
|
|
697
|
-
// ownership of the host's content across renders
|
|
698
|
-
//
|
|
742
|
+
// ownership of the host's content across renders, and mints the slot
|
|
743
|
+
// hop back to it below. If no ancestor takes over (standalone usage,
|
|
744
|
+
// e.g. storybook), host it locally.
|
|
699
745
|
const mountEvent = new CustomEvent('cds-custom-aichat-markdown-plugin-host-mount', {
|
|
700
746
|
bubbles: true,
|
|
701
747
|
composed: true,
|
|
702
748
|
cancelable: true,
|
|
703
749
|
detail: {
|
|
750
|
+
kind: 'customRenderer',
|
|
704
751
|
slotName: descriptor.slotName,
|
|
705
752
|
element: host,
|
|
706
753
|
isInline: false,
|
|
@@ -708,7 +755,7 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
|
|
|
708
755
|
});
|
|
709
756
|
this.dispatchEvent(mountEvent);
|
|
710
757
|
if (mountEvent.defaultPrevented) {
|
|
711
|
-
this.
|
|
758
|
+
this.adoptDelegatedSlot(descriptor.slotName);
|
|
712
759
|
}
|
|
713
760
|
else {
|
|
714
761
|
this.appendChild(host);
|
|
@@ -724,16 +771,12 @@ let CDSAIChatMarkdown = class CDSAIChatMarkdown extends LitElement {
|
|
|
724
771
|
this.slotHosts.delete(slotName);
|
|
725
772
|
}
|
|
726
773
|
}
|
|
727
|
-
//
|
|
728
|
-
//
|
|
729
|
-
|
|
774
|
+
// Drop claims whose descriptor disappeared (a streaming chunk removed a
|
|
775
|
+
// math node, a `customRenderers` callback returned null): the host was
|
|
776
|
+
// already detached above, so this retires the hop and announces.
|
|
777
|
+
for (const slotName of this.delegatedPluginSlots.keys()) {
|
|
730
778
|
if (!wanted.has(slotName)) {
|
|
731
|
-
this.
|
|
732
|
-
bubbles: true,
|
|
733
|
-
composed: true,
|
|
734
|
-
detail: { slotName },
|
|
735
|
-
}));
|
|
736
|
-
this.delegatedPluginSlots.delete(slotName);
|
|
779
|
+
this.retireDelegatedSlot(slotName);
|
|
737
780
|
}
|
|
738
781
|
}
|
|
739
782
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"markdown.js","sources":["../../../../src/components/markdown/src/markdown.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, LitElement, PropertyValues, TemplateResult } from 'lit';\nimport { property, state } from 'lit/decorators.js';\nimport { carbonElement } from '../../../globals/decorators/carbon-element.js';\nimport prefix from '../../../globals/settings.js';\nimport commonStyles from '../../../globals/scss/common.scss?lit';\nimport styles from './markdown.scss?lit';\nimport throttle from 'lodash-es/throttle.js';\nimport { IS_PHONE } from '../../../globals/utils/browser-utils.js';\n\nimport MarkdownIt from 'markdown-it';\n\nimport {\n markdownToTokenTree,\n type MarkdownItPlugin,\n type TokenTree,\n} from './markdown-token-tree.js';\nimport {\n renderMarkdownTree,\n type MarkdownCustomRenderers,\n type MarkdownRendererSlotDescriptor,\n} from './markdown-renderer.js';\nimport {\n hasLikelyPartialTableTail,\n hasNodeAfterTable,\n hasTrailingTableToken,\n} from './utils/streaming-table.js';\nimport { nextMarkdownInstanceId } from './utils/slot-names.js';\n\nconst CONSOLE_PREFIX = '[carbon-ai-chat-components]';\n\n/**\n * True if `node` is inside (or is) a light-DOM element with a `slot` attribute\n * set, up to (but not including) `boundary`. Portal hosts mounted by consumers\n * carry a `slot` attribute, so this is used to skip both `textContent`\n * contributions and observed mutations that originated inside a portal subtree.\n */\nfunction isInsidePortalHost(node: Node, boundary: Node): boolean {\n let cur: Node | null = node;\n while (cur && cur !== boundary) {\n if (cur instanceof Element && cur.hasAttribute('slot')) {\n return true;\n }\n cur = cur.parentNode;\n }\n return false;\n}\n\n/**\n * Concatenates the markdown source from `element`'s light-DOM children,\n * skipping any `<element slot=\"…\">` portal hosts so consumer-rendered overrides\n * don't contaminate the parsed markdown source.\n */\nfunction readLightDomMarkdownSource(element: Element): string {\n let out = '';\n for (const child of Array.from(element.childNodes)) {\n if (child instanceof Element && child.hasAttribute('slot')) {\n continue;\n }\n if (child.nodeType === Node.TEXT_NODE) {\n out += child.nodeValue ?? '';\n } else if (child instanceof Element) {\n out += child.textContent ?? '';\n }\n }\n return out.trim();\n}\n\n/**\n * Renders markdown as Carbon-styled DOM. Streaming-friendly: incremental updates reparse the markdown source into a `TokenTree`, diff it against the prior tree to reuse stable subtrees, then walk it into a Lit `TemplateResult` — Lit's `repeat` directive keys off the diffed nodes so unchanged DOM stays put.\n *\n * ### Lifecycle\n *\n * 1. A property setter (or a light-DOM mutation) lands. `willUpdate` decides whether the change requires a reparse (`markdown`, `removeHTML`, `markdownItPlugins`) or only a re-render (translated strings, `streaming`, `sanitizeHTML`, `customRenderers`).\n * 2. `scheduleRender` throttles bursts to 100ms (leading + trailing).\n * 3. `renderMarkdown` parses (if needed) via {@link markdownToTokenTree}, then calls {@link renderMarkdownTree} to produce both a `TemplateResult` and a batch of {@link MarkdownRendererSlotDescriptor} records.\n * 4. After Lit commits, `updated()` runs `reconcileCustomRendererHosts` — that is where consumer-supplied `customRenderers` callbacks fire and plugin-fallback HTML is adopted into light-DOM slot hosts.\n *\n * ### Extensibility\n *\n * - {@link markdownItPlugins} runs after the built-in markdown-it plugins (markdown-it-attrs, highlight, task-lists). A new array identity rebuilds the markdown-it instance and forces a full reparse. Tokens introduced by a plugin that the native dispatch can't handle — either an unknown tag, or a plugin-overridden rule on a curated allow-list of leaf tokens — route through `md.renderer.render()` via `./utils/plugin-fallback.ts` and surface as `pluginFallback` descriptors. Their rendered HTML is adopted into a light-DOM slot host so consumer-supplied CSS (e.g. a KaTeX stylesheet on the host page) reaches it.\n * - {@link customRenderers} overrides per-element rendering for `table` and `codeBlock`. The renderer emits a named `<slot>` placeholder; the reconciler invokes the consumer's callback with the parsed data and appends the returned `HTMLElement` as a `<div slot=\"…\">` light-DOM child. Returning the same element reference across renders avoids DOM churn.\n *\n * ### Light-DOM source adoption\n *\n * When the `markdown` property has never been set explicitly, the element treats its light-DOM text content as the initial source and watches for further mutations via a `MutationObserver`. Setting the property explicitly stops the observer — the property is then the authoritative source.\n *\n * ### Related files\n *\n * - `./markdown-token-tree.ts` — markdown-it parse + tree builder + streaming-aware diff (with `cachedHtml` carry-forward for plugin-delegated tokens).\n * - `./markdown-renderer.ts` — `TokenTree` → Lit `TemplateResult`, plus descriptor collection.\n * - `./markdown-renderer-types.ts` — public ({@link MarkdownCustomRenderers}) and internal ({@link MarkdownRendererSlotDescriptor}, `RenderTokenTreeOptions`) contracts.\n * - `./utils/plugin-fallback.ts` — delegation to `md.renderer.render()` for plugin-introduced tokens.\n * - `./utils/streaming-table.ts` — heuristics that hold a streaming table in a skeleton \"loading\" state until its tail stabilizes.\n *\n * @element cds-custom-aichat-markdown\n */\n@carbonElement(`${prefix}-markdown`)\nclass CDSAIChatMarkdown extends LitElement {\n static styles = [commonStyles, styles];\n\n /**\n * Sanitize any HTML included in the markdown. e.g. remove script tags, onclick handlers, etc.\n */\n @property({ type: Boolean, attribute: 'sanitize-html' })\n sanitizeHTML = false;\n\n /**\n * Remove all HTML from included markdown.\n */\n @property({ type: Boolean, attribute: 'remove-html' })\n removeHTML = false;\n\n /**\n * Internal storage for markdown content.\n * @internal\n */\n private _markdown = '';\n\n /**\n * Flag to temporarily allow internal markdown updates without marking as explicitly set.\n * @internal\n */\n private isInternalMarkdownUpdate = false;\n\n /**\n * Direct markdown source input.\n */\n @property({ type: String })\n get markdown(): string {\n return this._markdown;\n }\n set markdown(value: string) {\n const oldValue = this._markdown;\n this._markdown = value;\n\n // Track that markdown was explicitly set (not from Light DOM adoption)\n // Only mark as explicitly set if this is NOT an internal update\n if (!this.isInternalMarkdownUpdate) {\n this.markdownPropertyExplicitlySet = true;\n this.stopObservingLightDom();\n }\n\n this.requestUpdate('markdown', oldValue);\n }\n\n /**\n * If you are actively streaming, setting this to true can help prevent needless UI thrashing when writing\n * complex components (like a sortable and filterable table).\n */\n @property({ type: Boolean, attribute: 'streaming' })\n streaming = false;\n\n // Code snippet properties\n /** Enable syntax highlighting for any code fence blocks. */\n @property({ type: Boolean, attribute: 'code-snippet-highlight' })\n codeSnippetHighlight = true;\n\n /** Label for collapsing long code blocks. */\n @property({ type: String, attribute: 'code-snippet-show-less-text' })\n codeSnippetShowLessText = 'Show less';\n\n /** Label for expanding long code blocks. */\n @property({ type: String, attribute: 'code-snippet-show-more-text' })\n codeSnippetShowMoreText = 'Show more';\n\n /** Tooltip content for the copy action on code blocks. */\n @property({\n type: String,\n attribute: 'code-snippet-copy-button-tooltip-content',\n })\n codeSnippetCopyButtonTooltipContent = 'Copy code';\n\n /** Formatter for the code block line count. */\n @property({ type: Object, attribute: false })\n codeSnippetGetLineCountText?: ({ count }: { count: number }) => string;\n\n /** Aria-label for code snippets when in read-only mode. */\n @property({ type: String, attribute: 'code-snippet-aria-label-readonly' })\n codeSnippetAriaLabelReadOnly = 'Code snippet';\n\n /** Aria-label for code snippets when in editable mode. */\n @property({ type: String, attribute: 'code-snippet-aria-label-editable' })\n codeSnippetAriaLabelEditable = 'Code editor';\n\n // Table properties\n /** Placeholder text for table filters. */\n @property({ type: String, attribute: 'table-filter-placeholder-text' })\n tableFilterPlaceholderText = 'Filter table...';\n\n /** Label for the previous page control in tables. */\n @property({ type: String, attribute: 'table-previous-page-text' })\n tablePreviousPageText = 'Previous page';\n\n /** Label for the next page control in tables. */\n @property({ type: String, attribute: 'table-next-page-text' })\n tableNextPageText = 'Next page';\n\n /** Label for the items-per-page control in tables. */\n @property({ type: String, attribute: 'table-items-per-page-text' })\n tableItemsPerPageText = 'Items per page:';\n\n /** Label for download of CSV of table data. */\n @property({ type: String, attribute: 'table-download-label-text' })\n tableDownloadLabelText = 'Download table data';\n\n /** Locale used for table pagination and formatting. */\n @property({ type: String, attribute: 'table-locale' })\n tableLocale = 'en';\n\n /** Optional formatter for supplemental pagination text. */\n @property({ type: Object, attribute: false })\n tableGetPaginationSupplementalText?: ({ count }: { count: number }) => string;\n\n /** Optional formatter for pagination status text. */\n @property({ type: Object, attribute: false })\n tableGetPaginationStatusText?: ({\n start,\n end,\n count,\n }: {\n start: number;\n end: number;\n count: number;\n }) => string;\n\n /**\n * Markdown-it plugins applied after the built-in plugins\n * (markdown-it-attrs, markdown-it-highlight, markdown-it-task-lists).\n * Changes force a reparse. Memoize this array — a new reference each render\n * rebuilds the markdown-it instance.\n */\n @property({ type: Array, attribute: false })\n markdownItPlugins?: MarkdownItPlugin[];\n\n /**\n * Per-element render overrides. For each `kind` whose callback is provided,\n * the markdown element emits a named `<slot>` placeholder in its shadow\n * DOM, then — after each render — invokes the callback with the parsed\n * data and adopts the returned `HTMLElement` as a `<div slot=\"…\">`\n * light-DOM child of this element. Return `null` to fall back to the\n * default Carbon rendering. Returning the same element reference across\n * renders avoids DOM churn.\n *\n * The consumer's returned element lives in this element's light DOM, not\n * in its shadow root, so external CSS applies normally.\n */\n @property({ attribute: false })\n customRenderers?: MarkdownCustomRenderers;\n\n /**\n * Descriptors collected during the most recent render task; consumed by\n * the `updated()` reconcile to invoke {@link customRenderers} callbacks.\n * @internal\n */\n private latestRendererDescriptors: MarkdownRendererSlotDescriptor[] = [];\n\n /**\n * Light-DOM slot hosts adopted on behalf of {@link customRenderers}, keyed\n * by slot name. Reused across renders for stable identity.\n * @internal\n */\n private slotHosts: Map<string, HTMLElement> = new Map();\n\n /**\n * Namespace appended to every slot name this element mints, so two markdown\n * elements rendering identical markdown never collide in the shared\n * page-level host container a chat container hoists slot hosts into.\n *\n * Assigned in the field initializer (construction) rather than\n * `connectedCallback`, which runs again after a DOM move — the namespace, and\n * therefore every slot name and every adopted host, must survive a\n * disconnect/reconnect.\n * @internal\n */\n private readonly slotNamespace = nextMarkdownInstanceId();\n\n /**\n * Slot names whose host was created by an outer listener (a chat container\n * that called `preventDefault()` on the host-mount event). We track these\n * so we can fire matching unmount events without trying to remove a host we\n * never appended.\n * @internal\n */\n private delegatedPluginSlots: Set<string> = new Set();\n\n /**\n * The markdown-it instance produced by the most recent parse. Forwarded into\n * the renderer so unknown tokens can fall back to `md.renderer.render()`.\n * @internal\n */\n private markdownItInstance?: MarkdownIt;\n\n /**\n * @internal\n */\n private needsReparse = false;\n\n /**\n * Tracks the latest asynchronous rendering work so callers waiting on `updateComplete` know when throttled updates are done.\n *\n * @internal\n */\n private renderTask: Promise<void> | null = null;\n\n private hasRenderedStreamingTableLoadingFrame = false;\n /**\n * The most recent tree parsed while in streaming table loading mode, held back\n * from rendering. It seeds `previousTreeForDiff`, so the tick that leaves loading\n * mode without a reparse still renders the content staged during it.\n * @internal\n */\n private stagedStreamingTokenTree: TokenTree | null = null;\n\n /**\n * @internal\n */\n private isStreamingTableLoadingMode = false;\n\n /**\n * @internal\n */\n private hasConnected = false;\n\n /**\n * Tracks whether the markdown property has been explicitly set by the user.\n * When false, the component will monitor Light DOM changes.\n * @internal\n */\n private markdownPropertyExplicitlySet = false;\n\n /**\n * MutationObserver to monitor Light DOM changes when markdown property isn't explicitly set.\n * @internal\n */\n private lightDomObserver: MutationObserver | null = null;\n\n /**\n * Generation counter for Light DOM mutation processing. Incremented when a\n * mutation is observed and decremented when the resulting microtask\n * completes. `updateComplete` waits while the counter is non-zero.\n * @internal\n */\n private pendingLightDomMutations = 0;\n\n connectedCallback() {\n super.connectedCallback();\n this.hasConnected = true;\n\n if (IS_PHONE) {\n this.setAttribute('phone', '');\n }\n\n this.adoptLightDomMarkdown();\n\n // Task-list checkbox toggles bubble (composed) out of the rendered\n // `cds-custom-checkbox` elements; one delegated listener forwards them to a\n // consumer `checklist.onToggle`.\n this.addEventListener(\n 'cds-custom-checkbox-changed',\n this.handleChecklistToggle as EventListener\n );\n\n // Ensure we parse and render on initial mount, even if markdown was set before connection\n this.needsReparse = true;\n this.scheduleRender();\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this.removeEventListener(\n 'cds-custom-checkbox-changed',\n this.handleChecklistToggle as EventListener\n );\n this.stopObservingLightDom();\n // Tear down any adopted slot hosts so they don't leak across re-connect.\n for (const host of this.slotHosts.values()) {\n host.remove();\n }\n this.slotHosts.clear();\n // Ask any delegating chat container to drop its hosts too.\n for (const slotName of this.delegatedPluginSlots) {\n this.dispatchEvent(\n new CustomEvent('cds-custom-aichat-markdown-plugin-host-unmount', {\n bubbles: true,\n composed: true,\n detail: { slotName },\n })\n );\n }\n this.delegatedPluginSlots.clear();\n this.latestRendererDescriptors = [];\n }\n\n /**\n * Delegated handler for `cds-custom-checkbox-changed` from rendered task-list\n * checkboxes. Resolves the toggled checkbox via the composed event path (a\n * host listener would otherwise see a retargeted `event.target`), reads the\n * identity stamped by the task-list plugin, and forwards the new state to a\n * consumer `checklist.onToggle`.\n */\n private handleChecklistToggle = (event: Event): void => {\n const onToggle = this.customRenderers?.checklist?.onToggle;\n if (!onToggle) {\n return;\n }\n const checkbox = event\n .composedPath()\n .find(\n (target): target is HTMLElement =>\n target instanceof HTMLElement &&\n target.tagName.toLowerCase() === 'cds-custom-checkbox'\n );\n const id = checkbox?.getAttribute('data-cds-aichat-checklist-id');\n if (!checkbox || id == null) {\n // Not a stamped task-list checkbox — ignore unrelated cds-custom-checkboxes.\n return;\n }\n const checked = !!(event as CustomEvent<{ checked?: boolean }>).detail\n ?.checked;\n const label =\n checkbox.closest('cds-custom-list-item, li')?.textContent?.trim() ?? '';\n onToggle({ id, label, checked });\n };\n\n private adoptLightDomMarkdown() {\n // Backward compatibility: treat static light-DOM text as initial markdown\n // when the explicit `markdown` property was not provided.\n if (!this.markdownPropertyExplicitlySet) {\n const lightDomMarkdown = readLightDomMarkdownSource(this);\n if (lightDomMarkdown) {\n // Set markdown without triggering the \"explicitly set\" flag\n this.isInternalMarkdownUpdate = true;\n this.markdown = lightDomMarkdown;\n this.isInternalMarkdownUpdate = false;\n }\n\n // Start observing Light DOM changes only if markdown property wasn't explicitly set\n this.startObservingLightDom();\n }\n }\n\n private startObservingLightDom() {\n if (this.lightDomObserver || this.markdownPropertyExplicitlySet) {\n return;\n }\n\n this.lightDomObserver = new MutationObserver((records) => {\n // Only update from Light DOM if markdown property still hasn't been explicitly set\n if (!this.markdownPropertyExplicitlySet) {\n // Mutations that happened entirely inside a portal host (a light-DOM\n // child with a `slot` attribute) are noise from the consumer's\n // overrides re-rendering — they don't change the markdown source.\n const relevant = records.filter(\n (record) => !isInsidePortalHost(record.target, this)\n );\n if (relevant.length === 0) {\n return;\n }\n\n // Process the mutation in a microtask so the DOM has settled. Track\n // it via a counter so `updateComplete` can await any concurrent\n // mutations without the fragility of a single-slot promise field.\n this.pendingLightDomMutations += 1;\n Promise.resolve()\n .then(() => {\n const lightDomMarkdown = readLightDomMarkdownSource(this);\n if (this.markdown !== lightDomMarkdown) {\n this.isInternalMarkdownUpdate = true;\n this.markdown = lightDomMarkdown;\n this.isInternalMarkdownUpdate = false;\n }\n })\n .finally(() => {\n this.pendingLightDomMutations -= 1;\n });\n } else {\n // If markdown was explicitly set, stop observing\n this.stopObservingLightDom();\n }\n });\n\n this.lightDomObserver.observe(this, {\n childList: true,\n characterData: true,\n subtree: true,\n });\n }\n\n private stopObservingLightDom() {\n if (this.lightDomObserver) {\n this.lightDomObserver.disconnect();\n this.lightDomObserver = null;\n }\n }\n\n protected willUpdate(changed: PropertyValues<this>) {\n // Handle initial render case: if markdown was set before connectedCallback,\n // Lit won't report it as \"changed\" but we still need to parse it\n const isInitialRender = !this.hasConnected && this.markdown;\n\n if (\n changed.has('removeHTML') ||\n changed.has('markdown') ||\n changed.has('markdownItPlugins') ||\n isInitialRender\n ) {\n // Properties that affect token tree structure require full reparse\n // - removeHTML: toggles post-parse HTML-token stripping\n // - markdown: updates the source text to parse\n // - markdownItPlugins: swaps the markdown-it instance, new parser rules\n // - isInitialRender: ensures pre-set markdown gets parsed on first render\n this.needsReparse = true;\n this.scheduleRender();\n } else if (\n // Properties that only affect rendering can skip reparsing\n // - sanitizeHTML: applies DOMPurify during render, doesn't change tokens\n // - string properties: change translated strings in rendered output\n // - streaming: affects loading states in rendered output\n // - customRenderers: only changes which tokens emit a slot\n changed.has('sanitizeHTML') ||\n changed.has('streaming') ||\n changed.has('customRenderers') ||\n // Code snippet properties\n changed.has('codeSnippetHighlight') ||\n changed.has('codeSnippetShowLessText') ||\n changed.has('codeSnippetShowMoreText') ||\n changed.has('codeSnippetCopyButtonTooltipContent') ||\n changed.has('codeSnippetGetLineCountText') ||\n changed.has('codeSnippetAriaLabelReadOnly') ||\n changed.has('codeSnippetAriaLabelEditable') ||\n // Table properties\n changed.has('tableFilterPlaceholderText') ||\n changed.has('tablePreviousPageText') ||\n changed.has('tableNextPageText') ||\n changed.has('tableItemsPerPageText') ||\n changed.has('tableDownloadLabelText') ||\n changed.has('tableLocale') ||\n changed.has('tableGetPaginationSupplementalText') ||\n changed.has('tableGetPaginationStatusText')\n ) {\n this.scheduleRender();\n }\n }\n\n /**\n * @internal\n */\n @state()\n tokenTree: TokenTree = {\n key: 'root',\n token: {\n type: 'root',\n tag: '',\n nesting: 0,\n level: 0,\n content: '',\n attrs: null,\n children: null,\n markup: '',\n block: true,\n hidden: false,\n map: null,\n info: '',\n meta: null,\n },\n children: [],\n };\n\n /**\n * @internal\n */\n @state()\n renderedContent: TemplateResult | null = null;\n\n /**\n * Throttled function that updates the rendered content.\n * If needsReparse is true, parses markdown into a token tree first.\n * Otherwise, just re-renders the existing token tree with current settings.\n *\n * @internal\n */\n private renderMarkdown = async () => {\n try {\n const markdownContent = this.markdown ?? '';\n const previousTreeForDiff =\n this.stagedStreamingTokenTree ?? this.tokenTree;\n let nextTokenTree = previousTreeForDiff;\n\n if (this.needsReparse) {\n // First, we take the markdown we were given and use the markdown-it parser to turn is into a tree we can\n // transform into Lit components and compare smartly to avoid re-renders of components that were already\n // rendered when the markdown is updated (likely by streaming, but possibly by an edit somewhere in the\n // middle). It takes the current tokenTree as an argument for quick diffing to avoid re-creating parts\n // of the tree.\n const parsed = markdownToTokenTree(\n markdownContent,\n previousTreeForDiff,\n {\n removeHtml: this.removeHTML,\n markdownItPlugins: this.markdownItPlugins,\n }\n );\n nextTokenTree = parsed.tree;\n this.markdownItInstance = parsed.md;\n this.needsReparse = false;\n }\n\n const hasStreamingTailTable =\n Boolean(this.streaming) && hasTrailingTableToken(nextTokenTree);\n const hasParsedNodeAfterTable = hasNodeAfterTable(nextTokenTree);\n\n if (!this.streaming) {\n this.isStreamingTableLoadingMode = false;\n } else if (this.isStreamingTableLoadingMode) {\n if (\n hasParsedNodeAfterTable &&\n !hasLikelyPartialTableTail(markdownContent)\n ) {\n this.isStreamingTableLoadingMode = false;\n }\n } else if (hasStreamingTailTable) {\n this.isStreamingTableLoadingMode = true;\n }\n\n // Render-and-stash helper. Each invocation produces a fresh batch of\n // renderer-slot descriptors; the `updated()` reconcile then invokes\n // the consumer's `customRenderers` callbacks for each descriptor and\n // adopts the returned `HTMLElement` as a light-DOM slot host.\n const renderAndDispatch = (tree: TokenTree): void => {\n const { template, batch } = renderMarkdownTree(tree, {\n sanitize: this.sanitizeHTML,\n streaming: this.streaming,\n // Code snippet properties\n codeSnippetHighlight: this.codeSnippetHighlight,\n codeSnippetShowLessText: this.codeSnippetShowLessText,\n codeSnippetShowMoreText: this.codeSnippetShowMoreText,\n codeSnippetCopyButtonTooltipContent:\n this.codeSnippetCopyButtonTooltipContent,\n codeSnippetGetLineCountText: this.codeSnippetGetLineCountText,\n codeSnippetAriaLabelReadOnly: this.codeSnippetAriaLabelReadOnly,\n codeSnippetAriaLabelEditable: this.codeSnippetAriaLabelEditable,\n // Table properties\n tableFilterPlaceholderText: this.tableFilterPlaceholderText,\n tablePreviousPageText: this.tablePreviousPageText,\n tableNextPageText: this.tableNextPageText,\n tableItemsPerPageText: this.tableItemsPerPageText,\n tableDownloadLabelText: this.tableDownloadLabelText,\n tableLocale: this.tableLocale,\n tableGetPaginationSupplementalText:\n this.tableGetPaginationSupplementalText,\n tableGetPaginationStatusText: this.tableGetPaginationStatusText,\n // Custom-renderer hooks\n customRenderers: this.customRenderers,\n slotNamespace: this.slotNamespace,\n md: this.markdownItInstance,\n });\n this.renderedContent = template;\n this.latestRendererDescriptors = batch;\n };\n\n if (this.streaming && this.isStreamingTableLoadingMode) {\n if (!this.hasRenderedStreamingTableLoadingFrame) {\n if (nextTokenTree !== this.tokenTree) {\n this.tokenTree = nextTokenTree;\n }\n renderAndDispatch(nextTokenTree);\n this.hasRenderedStreamingTableLoadingFrame = true;\n this.stagedStreamingTokenTree = null;\n } else {\n this.stagedStreamingTokenTree = nextTokenTree;\n }\n return;\n }\n\n // Never prefer the staged tree here: when nothing was reparsed `nextTokenTree`\n // *is* the staged tree (see `previousTreeForDiff` above), and when something\n // was, it came from newer source.\n this.stagedStreamingTokenTree = null;\n this.hasRenderedStreamingTableLoadingFrame = false;\n if (nextTokenTree !== this.tokenTree) {\n this.tokenTree = nextTokenTree;\n }\n\n // Next we take that tree and transform it into Lit content to be rendered into the template.\n // this.renderedContent is what is rendered in the template directly.\n renderAndDispatch(nextTokenTree);\n } catch (error) {\n console.error(`${CONSOLE_PREFIX} Failed to parse markdown`, error);\n }\n };\n\n /**\n * @internal\n */\n private scheduleRender = throttle(\n () => {\n // Lit's getter/setter pipeline can schedule multiple renders quickly.\n // We capture the active render promise so we can report completion later.\n const task = this.renderMarkdown();\n const trackedTask = task.finally(() => {\n if (this.renderTask === trackedTask) {\n this.renderTask = null;\n }\n });\n\n this.renderTask = trackedTask;\n return trackedTask;\n },\n 100,\n { leading: true, trailing: true }\n );\n\n protected async getUpdateComplete(): Promise<boolean> {\n // `updateComplete` is Lit's public hook for consumers/tests to await\n // all pending work. Because we throttle renders, the base implementation\n // might resolve before the throttled callback runs. Overriding this\n // method lets us flush the throttle and await the render promise so\n // callers can reliably wait for `renderedContent` to update.\n const result = await super.getUpdateComplete();\n\n const flushResult = (\n this.scheduleRender as {\n flush?: () => Promise<void> | void;\n }\n ).flush?.();\n\n if (flushResult instanceof Promise) {\n await flushResult;\n }\n\n if (this.renderTask) {\n await this.renderTask;\n }\n\n // Drain any in-flight Light DOM mutation microtasks and their resulting\n // renders. Each iteration yields the event loop so newly enqueued\n // mutations can settle; the counter goes back to zero once everything\n // has flushed.\n while (this.pendingLightDomMutations > 0) {\n await Promise.resolve();\n\n const postMutationFlush = (\n this.scheduleRender as {\n flush?: () => Promise<void> | void;\n }\n ).flush?.();\n\n if (postMutationFlush instanceof Promise) {\n await postMutationFlush;\n }\n\n if (this.renderTask) {\n await this.renderTask;\n }\n }\n\n return result;\n }\n\n protected updated(changed: PropertyValues<this>) {\n super.updated(changed);\n this.reconcileCustomRendererHosts();\n }\n\n /**\n * Invoke the consumer's `customRenderers` callbacks once per descriptor and\n * adopt their returned `HTMLElement` as a `<span slot=\"…\">` (for inline\n * plugin tokens) or `<div slot=\"…\">` (block tokens and consumer renderers)\n * light-DOM child. Hosts persist across renders so a consumer returning the\n * same element reference produces no DOM churn; hosts whose slot names\n * dropped out of the latest descriptor batch are removed.\n *\n * @internal\n */\n private reconcileCustomRendererHosts() {\n const renderers = this.customRenderers;\n const descriptors = this.latestRendererDescriptors;\n const wanted = new Set<string>();\n\n for (const descriptor of descriptors) {\n if (descriptor.kind === 'pluginFallback') {\n wanted.add(descriptor.slotName);\n\n // Offer the slot to a chat-container ancestor first. The chain\n // appends the host to its OWN light DOM (page DOM at the top of the\n // chain) so external CSS (e.g. a KaTeX stylesheet on the host page)\n // reaches the plugin output. If a listener calls preventDefault, it\n // has taken over hosting and we skip the local appendChild path.\n const alreadyDelegated = this.delegatedPluginSlots.has(\n descriptor.slotName\n );\n if (!alreadyDelegated && !this.slotHosts.has(descriptor.slotName)) {\n const mountEvent = new CustomEvent(\n 'cds-custom-aichat-markdown-plugin-host-mount',\n {\n bubbles: true,\n composed: true,\n cancelable: true,\n detail: {\n slotName: descriptor.slotName,\n html: descriptor.html,\n isInline: descriptor.isInline,\n },\n }\n );\n this.dispatchEvent(mountEvent);\n if (mountEvent.defaultPrevented) {\n this.delegatedPluginSlots.add(descriptor.slotName);\n }\n } else if (alreadyDelegated) {\n // The chain owns this slot; push HTML updates through a second\n // event so streaming chunks reach the page-level host element.\n this.dispatchEvent(\n new CustomEvent('cds-custom-aichat-markdown-plugin-host-update', {\n bubbles: true,\n composed: true,\n detail: {\n slotName: descriptor.slotName,\n html: descriptor.html,\n },\n })\n );\n }\n\n if (this.delegatedPluginSlots.has(descriptor.slotName)) {\n continue;\n }\n\n // Fallback: no outer listener took over (standalone usage, e.g.\n // storybook). Adopt the host as our own light-DOM child, matching\n // the pre-event behavior so existing tests/stories keep working.\n let host = this.slotHosts.get(descriptor.slotName);\n if (!host) {\n const tag = descriptor.isInline ? 'span' : 'div';\n host = document.createElement(tag);\n host.setAttribute('slot', descriptor.slotName);\n this.slotHosts.set(descriptor.slotName, host);\n this.appendChild(host);\n }\n // Only rewrite innerHTML when the plugin output actually changed;\n // streaming re-renders frequently land here with the same HTML.\n if (host.innerHTML !== descriptor.html) {\n host.innerHTML = descriptor.html;\n }\n continue;\n }\n\n const callback = renderers?.[descriptor.kind];\n if (!callback) {\n continue;\n }\n let result: HTMLElement | null;\n try {\n result = (\n callback as (\n args: Parameters<NonNullable<typeof callback>>[0]\n ) => HTMLElement | null\n )({\n ...descriptor.data,\n token: descriptor.token,\n slotName: descriptor.slotName,\n });\n } catch (error) {\n console.error(\n `[carbon-ai-chat-components] customRenderers.${descriptor.kind} threw`,\n error\n );\n continue;\n }\n if (result == null) {\n const existing = this.slotHosts.get(descriptor.slotName);\n if (existing) {\n existing.remove();\n this.slotHosts.delete(descriptor.slotName);\n }\n continue;\n }\n wanted.add(descriptor.slotName);\n let host = this.slotHosts.get(descriptor.slotName);\n if (!host) {\n host = document.createElement('div');\n host.setAttribute('slot', descriptor.slotName);\n this.slotHosts.set(descriptor.slotName, host);\n\n // Offer the host to a chat-container ancestor so it lives in page\n // light DOM, where consumer-loaded global CSS (e.g. `@carbon/styles`\n // for a returned `@carbon/react` component) can reach it — the markdown\n // element's own light DOM sits inside the chat's shadow root, where it\n // cannot. Mirrors the plugin-fallback path above, but forwards the live\n // host element instead of an HTML string; the markdown element keeps\n // ownership of the host's content across renders. If no ancestor takes\n // over (standalone usage, e.g. storybook), host it locally.\n const mountEvent = new CustomEvent(\n 'cds-custom-aichat-markdown-plugin-host-mount',\n {\n bubbles: true,\n composed: true,\n cancelable: true,\n detail: {\n slotName: descriptor.slotName,\n element: host,\n isInline: false,\n },\n }\n );\n this.dispatchEvent(mountEvent);\n if (mountEvent.defaultPrevented) {\n this.delegatedPluginSlots.add(descriptor.slotName);\n } else {\n this.appendChild(host);\n }\n }\n if (host.firstChild !== result || host.childNodes.length !== 1) {\n host.replaceChildren(result);\n }\n }\n\n for (const [slotName, host] of this.slotHosts) {\n if (!wanted.has(slotName)) {\n host.remove();\n this.slotHosts.delete(slotName);\n }\n }\n\n // Tell any delegating chat container to drop hosts whose descriptor\n // disappeared (e.g. a streaming chunk removed a math node).\n for (const slotName of this.delegatedPluginSlots) {\n if (!wanted.has(slotName)) {\n this.dispatchEvent(\n new CustomEvent('cds-custom-aichat-markdown-plugin-host-unmount', {\n bubbles: true,\n composed: true,\n detail: { slotName },\n })\n );\n this.delegatedPluginSlots.delete(slotName);\n }\n }\n }\n\n protected render() {\n const { renderedContent } = this;\n return html`<div class=\"cds-custom-aichat-markdown-stack\">\n ${renderedContent}\n </div>`;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'cds-custom-aichat-markdown': CDSAIChatMarkdown;\n }\n}\n\nexport { CDSAIChatMarkdown };\nexport default CDSAIChatMarkdown;\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;AAOG;AA8BH,MA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AAA,CAAA;AAMF,UAAA,CAAA;AADC,IAAA,KAAK;AACwC,CAAA,EAAA,iBAAA,CAAA,SAAA,EAAA,iBAAA,EAAA,MAAA,CAAA;AA3d1C,iBAAiB,GAAA,UAAA,CAAA;AADtB,IAAA,aAAa,CAAC,CAAA,EAAG,MAAM,CAAA,SAAA,CAAW;AAC7B,CAAA,EAAA,iBAAiB,CAi1BtB;AASD,0BAAe,iBAAiB;;"}
|
|
1
|
+
{"version":3,"file":"markdown.js","sources":["../../../../src/components/markdown/src/markdown.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, LitElement, PropertyValues, TemplateResult } from 'lit';\nimport { property, state } from 'lit/decorators.js';\nimport { carbonElement } from '../../../globals/decorators/carbon-element.js';\nimport prefix from '../../../globals/settings.js';\nimport commonStyles from '../../../globals/scss/common.scss?lit';\nimport styles from './markdown.scss?lit';\nimport throttle from 'lodash-es/throttle.js';\nimport { IS_PHONE } from '../../../globals/utils/browser-utils.js';\n\nimport MarkdownIt from 'markdown-it';\n\nimport {\n markdownToTokenTree,\n type MarkdownItPlugin,\n type TokenTree,\n} from './markdown-token-tree.js';\nimport type {\n MarkdownCustomRendererMountDetail,\n MarkdownPluginFallbackMountDetail,\n} from './utils/plugin-host-container.js';\nimport {\n renderMarkdownTree,\n type MarkdownCustomRenderers,\n type MarkdownRendererSlotDescriptor,\n} from './markdown-renderer.js';\nimport {\n hasLikelyPartialTableTail,\n hasNodeAfterTable,\n hasTrailingTableToken,\n} from './utils/streaming-table.js';\nimport { nextMarkdownInstanceId } from './utils/slot-names.js';\n\nconst CONSOLE_PREFIX = '[carbon-ai-chat-components]';\n\n/**\n * True if `node` is inside (or is) a light-DOM element with a `slot` attribute\n * set, up to (but not including) `boundary`. Portal hosts mounted by consumers\n * carry a `slot` attribute, so this is used to skip both `textContent`\n * contributions and observed mutations that originated inside a portal subtree.\n */\nfunction isInsidePortalHost(node: Node, boundary: Node): boolean {\n let cur: Node | null = node;\n while (cur && cur !== boundary) {\n if (cur instanceof Element && cur.hasAttribute('slot')) {\n return true;\n }\n cur = cur.parentNode;\n }\n return false;\n}\n\n/**\n * Concatenates the markdown source from `element`'s light-DOM children,\n * skipping any `<element slot=\"…\">` portal hosts so consumer-rendered overrides\n * don't contaminate the parsed markdown source.\n */\nfunction readLightDomMarkdownSource(element: Element): string {\n let out = '';\n for (const child of Array.from(element.childNodes)) {\n if (child instanceof Element && child.hasAttribute('slot')) {\n continue;\n }\n if (child.nodeType === Node.TEXT_NODE) {\n out += child.nodeValue ?? '';\n } else if (child instanceof Element) {\n out += child.textContent ?? '';\n }\n }\n return out.trim();\n}\n\n/**\n * Renders markdown as Carbon-styled DOM. Streaming-friendly: incremental updates reparse the markdown source into a `TokenTree`, diff it against the prior tree to reuse stable subtrees, then walk it into a Lit `TemplateResult` — Lit's `repeat` directive keys off the diffed nodes so unchanged DOM stays put.\n *\n * ### Lifecycle\n *\n * 1. A property setter (or a light-DOM mutation) lands. `willUpdate` decides whether the change requires a reparse (`markdown`, `removeHTML`, `markdownItPlugins`) or only a re-render (translated strings, `streaming`, `sanitizeHTML`, `customRenderers`).\n * 2. `scheduleRender` throttles bursts to 100ms (leading + trailing).\n * 3. `renderMarkdown` parses (if needed) via {@link markdownToTokenTree}, then calls {@link renderMarkdownTree} to produce both a `TemplateResult` and a batch of {@link MarkdownRendererSlotDescriptor} records.\n * 4. After Lit commits, `updated()` runs `reconcileCustomRendererHosts` — that is where consumer-supplied `customRenderers` callbacks fire and plugin-fallback HTML is adopted into light-DOM slot hosts.\n *\n * ### Extensibility\n *\n * - {@link markdownItPlugins} runs after the built-in markdown-it plugins (markdown-it-attrs, highlight, task-lists). A new array identity rebuilds the markdown-it instance and forces a full reparse. Tokens introduced by a plugin that the native dispatch can't handle — either an unknown tag, or a plugin-overridden rule on a curated allow-list of leaf tokens — route through `md.renderer.render()` via `./utils/plugin-fallback.ts` and surface as `pluginFallback` descriptors. Their rendered HTML is adopted into a light-DOM slot host so consumer-supplied CSS (e.g. a KaTeX stylesheet on the host page) reaches it.\n * - {@link customRenderers} overrides per-element rendering for `table` and `codeBlock`. The renderer emits a named `<slot>` placeholder; the reconciler invokes the consumer's callback with the parsed data and appends the returned `HTMLElement` as a `<div slot=\"…\">` light-DOM child. Returning the same element reference across renders avoids DOM churn.\n *\n * ### Light-DOM source adoption\n *\n * When the `markdown` property has never been set explicitly, the element treats its light-DOM text content as the initial source and watches for further mutations via a `MutationObserver`. Setting the property explicitly stops the observer — the property is then the authoritative source.\n *\n * ### Related files\n *\n * - `./markdown-token-tree.ts` — markdown-it parse + tree builder + streaming-aware diff (with `cachedHtml` carry-forward for plugin-delegated tokens).\n * - `./markdown-renderer.ts` — `TokenTree` → Lit `TemplateResult`, plus descriptor collection.\n * - `./markdown-renderer-types.ts` — public ({@link MarkdownCustomRenderers}) and internal ({@link MarkdownRendererSlotDescriptor}, `RenderTokenTreeOptions`) contracts.\n * - `./utils/plugin-fallback.ts` — delegation to `md.renderer.render()` for plugin-introduced tokens.\n * - `./utils/streaming-table.ts` — heuristics that hold a streaming table in a skeleton \"loading\" state until its tail stabilizes.\n *\n * @element cds-custom-aichat-markdown\n */\n@carbonElement(`${prefix}-markdown`)\nclass CDSAIChatMarkdown extends LitElement {\n static styles = [commonStyles, styles];\n\n /**\n * Sanitize any HTML included in the markdown. e.g. remove script tags, onclick handlers, etc.\n */\n @property({ type: Boolean, attribute: 'sanitize-html' })\n sanitizeHTML = false;\n\n /**\n * Remove all HTML from included markdown.\n */\n @property({ type: Boolean, attribute: 'remove-html' })\n removeHTML = false;\n\n /**\n * Internal storage for markdown content.\n * @internal\n */\n private _markdown = '';\n\n /**\n * Flag to temporarily allow internal markdown updates without marking as explicitly set.\n * @internal\n */\n private isInternalMarkdownUpdate = false;\n\n /**\n * Direct markdown source input.\n */\n @property({ type: String })\n get markdown(): string {\n return this._markdown;\n }\n set markdown(value: string) {\n const oldValue = this._markdown;\n this._markdown = value;\n\n // Track that markdown was explicitly set (not from Light DOM adoption)\n // Only mark as explicitly set if this is NOT an internal update\n if (!this.isInternalMarkdownUpdate) {\n this.markdownPropertyExplicitlySet = true;\n this.stopObservingLightDom();\n }\n\n this.requestUpdate('markdown', oldValue);\n }\n\n /**\n * If you are actively streaming, setting this to true can help prevent needless UI thrashing when writing\n * complex components (like a sortable and filterable table).\n */\n @property({ type: Boolean, attribute: 'streaming' })\n streaming = false;\n\n // Code snippet properties\n /** Enable syntax highlighting for any code fence blocks. */\n @property({ type: Boolean, attribute: 'code-snippet-highlight' })\n codeSnippetHighlight = true;\n\n /** Label for collapsing long code blocks. */\n @property({ type: String, attribute: 'code-snippet-show-less-text' })\n codeSnippetShowLessText = 'Show less';\n\n /** Label for expanding long code blocks. */\n @property({ type: String, attribute: 'code-snippet-show-more-text' })\n codeSnippetShowMoreText = 'Show more';\n\n /** Tooltip content for the copy action on code blocks. */\n @property({\n type: String,\n attribute: 'code-snippet-copy-button-tooltip-content',\n })\n codeSnippetCopyButtonTooltipContent = 'Copy code';\n\n /** Formatter for the code block line count. */\n @property({ type: Object, attribute: false })\n codeSnippetGetLineCountText?: ({ count }: { count: number }) => string;\n\n /** Aria-label for code snippets when in read-only mode. */\n @property({ type: String, attribute: 'code-snippet-aria-label-readonly' })\n codeSnippetAriaLabelReadOnly = 'Code snippet';\n\n /** Aria-label for code snippets when in editable mode. */\n @property({ type: String, attribute: 'code-snippet-aria-label-editable' })\n codeSnippetAriaLabelEditable = 'Code editor';\n\n // Table properties\n /** Placeholder text for table filters. */\n @property({ type: String, attribute: 'table-filter-placeholder-text' })\n tableFilterPlaceholderText = 'Filter table...';\n\n /** Label for the previous page control in tables. */\n @property({ type: String, attribute: 'table-previous-page-text' })\n tablePreviousPageText = 'Previous page';\n\n /** Label for the next page control in tables. */\n @property({ type: String, attribute: 'table-next-page-text' })\n tableNextPageText = 'Next page';\n\n /** Label for the items-per-page control in tables. */\n @property({ type: String, attribute: 'table-items-per-page-text' })\n tableItemsPerPageText = 'Items per page:';\n\n /** Label for download of CSV of table data. */\n @property({ type: String, attribute: 'table-download-label-text' })\n tableDownloadLabelText = 'Download table data';\n\n /** Locale used for table pagination and formatting. */\n @property({ type: String, attribute: 'table-locale' })\n tableLocale = 'en';\n\n /** Optional formatter for supplemental pagination text. */\n @property({ type: Object, attribute: false })\n tableGetPaginationSupplementalText?: ({ count }: { count: number }) => string;\n\n /** Optional formatter for pagination status text. */\n @property({ type: Object, attribute: false })\n tableGetPaginationStatusText?: ({\n start,\n end,\n count,\n }: {\n start: number;\n end: number;\n count: number;\n }) => string;\n\n /**\n * Markdown-it plugins applied after the built-in plugins\n * (markdown-it-attrs, markdown-it-highlight, markdown-it-task-lists).\n * Changes force a reparse. Memoize this array — a new reference each render\n * rebuilds the markdown-it instance.\n */\n @property({ type: Array, attribute: false })\n markdownItPlugins?: MarkdownItPlugin[];\n\n /**\n * Per-element render overrides. For each `kind` whose callback is provided,\n * the markdown element emits a named `<slot>` placeholder in its shadow\n * DOM, then — after each render — invokes the callback with the parsed\n * data and adopts the returned `HTMLElement` as a `<div slot=\"…\">`\n * light-DOM child of this element. Return `null` to fall back to the\n * default Carbon rendering. Returning the same element reference across\n * renders avoids DOM churn.\n *\n * Inside a chat, a container relocates the returned element into its own\n * light DOM — page DOM at the top of the chain — and this element forwards\n * it back into the named slot, so consumer-loaded page CSS reaches it.\n * Standalone (no chat ancestor), it stays a light-DOM child of this element.\n */\n @property({ attribute: false })\n customRenderers?: MarkdownCustomRenderers;\n\n /**\n * Descriptors collected during the most recent render task; consumed by\n * the `updated()` reconcile to invoke {@link customRenderers} callbacks.\n * @internal\n */\n private latestRendererDescriptors: MarkdownRendererSlotDescriptor[] = [];\n\n /**\n * Light-DOM slot hosts adopted on behalf of {@link customRenderers}, keyed\n * by slot name. Reused across renders for stable identity.\n * @internal\n */\n private slotHosts: Map<string, HTMLElement> = new Map();\n\n /**\n * `<slot name=X slot=X>` forwarders minted for {@link customRenderers} hosts\n * an outer listener relocated into its own light DOM, keyed by slot name.\n *\n * Appended imperatively rather than rendered: Lit commits into the shadow\n * root, and this hop has to be a light-DOM child of this element to gather\n * the relocated host out of the chat element's light DOM and hand it to the\n * shadow `<slot>` the renderer emitted. Minted where the claim is read\n * rather than by a subscriber, because the mount event fires once per host\n * and is never replayed — a listener that subscribes later cannot mint it.\n * @internal\n */\n private rendererForwarders: Map<string, HTMLSlotElement> = new Map();\n\n /**\n * Namespace appended to every slot name this element mints, so two markdown\n * elements rendering identical markdown never collide in the shared\n * page-level host container a chat container hoists slot hosts into.\n *\n * Assigned in the field initializer (construction) rather than\n * `connectedCallback`, which runs again after a DOM move — the namespace, and\n * therefore every slot name and every adopted host, must survive a\n * disconnect/reconnect.\n * @internal\n */\n private readonly slotNamespace = nextMarkdownInstanceId();\n\n /**\n * Slot names whose host was created by an outer listener (a chat container\n * that called `preventDefault()` on the host-mount event). We track these so\n * we can fire matching unmount events without trying to remove a host we\n * never appended.\n * @internal\n */\n private delegatedPluginSlots: Set<string> = new Set();\n\n /**\n * The markdown-it instance produced by the most recent parse. Forwarded into\n * the renderer so unknown tokens can fall back to `md.renderer.render()`.\n * @internal\n */\n private markdownItInstance?: MarkdownIt;\n\n /**\n * @internal\n */\n private needsReparse = false;\n\n /**\n * Tracks the latest asynchronous rendering work so callers waiting on `updateComplete` know when throttled updates are done.\n *\n * @internal\n */\n private renderTask: Promise<void> | null = null;\n\n private hasRenderedStreamingTableLoadingFrame = false;\n /**\n * The most recent tree parsed while in streaming table loading mode, held back\n * from rendering. It seeds `previousTreeForDiff`, so the tick that leaves loading\n * mode without a reparse still renders the content staged during it.\n * @internal\n */\n private stagedStreamingTokenTree: TokenTree | null = null;\n\n /**\n * @internal\n */\n private isStreamingTableLoadingMode = false;\n\n /**\n * @internal\n */\n private hasConnected = false;\n\n /**\n * Tracks whether the markdown property has been explicitly set by the user.\n * When false, the component will monitor Light DOM changes.\n * @internal\n */\n private markdownPropertyExplicitlySet = false;\n\n /**\n * MutationObserver to monitor Light DOM changes when markdown property isn't explicitly set.\n * @internal\n */\n private lightDomObserver: MutationObserver | null = null;\n\n /**\n * Generation counter for Light DOM mutation processing. Incremented when a\n * mutation is observed and decremented when the resulting microtask\n * completes. `updateComplete` waits while the counter is non-zero.\n * @internal\n */\n private pendingLightDomMutations = 0;\n\n connectedCallback() {\n super.connectedCallback();\n this.hasConnected = true;\n\n if (IS_PHONE) {\n this.setAttribute('phone', '');\n }\n\n this.adoptLightDomMarkdown();\n\n // Task-list checkbox toggles bubble (composed) out of the rendered\n // `cds-custom-checkbox` elements; one delegated listener forwards them to a\n // consumer `checklist.onToggle`.\n this.addEventListener(\n 'cds-custom-checkbox-changed',\n this.handleChecklistToggle as EventListener\n );\n\n // Ensure we parse and render on initial mount, even if markdown was set before connection\n this.needsReparse = true;\n this.scheduleRender();\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this.removeEventListener(\n 'cds-custom-checkbox-changed',\n this.handleChecklistToggle as EventListener\n );\n this.stopObservingLightDom();\n // Tear down any adopted slot hosts so they don't leak across re-connect.\n for (const host of this.slotHosts.values()) {\n host.remove();\n }\n this.slotHosts.clear();\n // Ask any delegating chat container to drop its hosts too. The loop above\n // already detached every relocated node — `slotHosts` holds the reference\n // wherever the node ended up — so this retires forwarders and announces.\n for (const slotName of this.delegatedPluginSlots.keys()) {\n this.retireDelegatedSlot(slotName);\n }\n this.latestRendererDescriptors = [];\n }\n\n /**\n * Delegated handler for `cds-custom-checkbox-changed` from rendered task-list\n * checkboxes. Resolves the toggled checkbox via the composed event path (a\n * host listener would otherwise see a retargeted `event.target`), reads the\n * identity stamped by the task-list plugin, and forwards the new state to a\n * consumer `checklist.onToggle`.\n */\n private handleChecklistToggle = (event: Event): void => {\n const onToggle = this.customRenderers?.checklist?.onToggle;\n if (!onToggle) {\n return;\n }\n const checkbox = event\n .composedPath()\n .find(\n (target): target is HTMLElement =>\n target instanceof HTMLElement &&\n target.tagName.toLowerCase() === 'cds-custom-checkbox'\n );\n const id = checkbox?.getAttribute('data-cds-aichat-checklist-id');\n if (!checkbox || id == null) {\n // Not a stamped task-list checkbox — ignore unrelated cds-custom-checkboxes.\n return;\n }\n const checked = !!(event as CustomEvent<{ checked?: boolean }>).detail\n ?.checked;\n const label =\n checkbox.closest('cds-custom-list-item, li')?.textContent?.trim() ?? '';\n onToggle({ id, label, checked });\n };\n\n private adoptLightDomMarkdown() {\n // Backward compatibility: treat static light-DOM text as initial markdown\n // when the explicit `markdown` property was not provided.\n if (!this.markdownPropertyExplicitlySet) {\n const lightDomMarkdown = readLightDomMarkdownSource(this);\n if (lightDomMarkdown) {\n // Set markdown without triggering the \"explicitly set\" flag\n this.isInternalMarkdownUpdate = true;\n this.markdown = lightDomMarkdown;\n this.isInternalMarkdownUpdate = false;\n }\n\n // Start observing Light DOM changes only if markdown property wasn't explicitly set\n this.startObservingLightDom();\n }\n }\n\n private startObservingLightDom() {\n if (this.lightDomObserver || this.markdownPropertyExplicitlySet) {\n return;\n }\n\n this.lightDomObserver = new MutationObserver((records) => {\n // Only update from Light DOM if markdown property still hasn't been explicitly set\n if (!this.markdownPropertyExplicitlySet) {\n // Mutations that happened entirely inside a portal host (a light-DOM\n // child with a `slot` attribute) are noise from the consumer's\n // overrides re-rendering — they don't change the markdown source.\n const relevant = records.filter(\n (record) => !isInsidePortalHost(record.target, this)\n );\n if (relevant.length === 0) {\n return;\n }\n\n // Process the mutation in a microtask so the DOM has settled. Track\n // it via a counter so `updateComplete` can await any concurrent\n // mutations without the fragility of a single-slot promise field.\n this.pendingLightDomMutations += 1;\n Promise.resolve()\n .then(() => {\n const lightDomMarkdown = readLightDomMarkdownSource(this);\n if (this.markdown !== lightDomMarkdown) {\n this.isInternalMarkdownUpdate = true;\n this.markdown = lightDomMarkdown;\n this.isInternalMarkdownUpdate = false;\n }\n })\n .finally(() => {\n this.pendingLightDomMutations -= 1;\n });\n } else {\n // If markdown was explicitly set, stop observing\n this.stopObservingLightDom();\n }\n });\n\n this.lightDomObserver.observe(this, {\n childList: true,\n characterData: true,\n subtree: true,\n });\n }\n\n private stopObservingLightDom() {\n if (this.lightDomObserver) {\n this.lightDomObserver.disconnect();\n this.lightDomObserver = null;\n }\n }\n\n protected willUpdate(changed: PropertyValues<this>) {\n // Handle initial render case: if markdown was set before connectedCallback,\n // Lit won't report it as \"changed\" but we still need to parse it\n const isInitialRender = !this.hasConnected && this.markdown;\n\n if (\n changed.has('removeHTML') ||\n changed.has('markdown') ||\n changed.has('markdownItPlugins') ||\n isInitialRender\n ) {\n // Properties that affect token tree structure require full reparse\n // - removeHTML: toggles post-parse HTML-token stripping\n // - markdown: updates the source text to parse\n // - markdownItPlugins: swaps the markdown-it instance, new parser rules\n // - isInitialRender: ensures pre-set markdown gets parsed on first render\n this.needsReparse = true;\n this.scheduleRender();\n } else if (\n // Properties that only affect rendering can skip reparsing\n // - sanitizeHTML: applies DOMPurify during render, doesn't change tokens\n // - string properties: change translated strings in rendered output\n // - streaming: affects loading states in rendered output\n // - customRenderers: only changes which tokens emit a slot\n changed.has('sanitizeHTML') ||\n changed.has('streaming') ||\n changed.has('customRenderers') ||\n // Code snippet properties\n changed.has('codeSnippetHighlight') ||\n changed.has('codeSnippetShowLessText') ||\n changed.has('codeSnippetShowMoreText') ||\n changed.has('codeSnippetCopyButtonTooltipContent') ||\n changed.has('codeSnippetGetLineCountText') ||\n changed.has('codeSnippetAriaLabelReadOnly') ||\n changed.has('codeSnippetAriaLabelEditable') ||\n // Table properties\n changed.has('tableFilterPlaceholderText') ||\n changed.has('tablePreviousPageText') ||\n changed.has('tableNextPageText') ||\n changed.has('tableItemsPerPageText') ||\n changed.has('tableDownloadLabelText') ||\n changed.has('tableLocale') ||\n changed.has('tableGetPaginationSupplementalText') ||\n changed.has('tableGetPaginationStatusText')\n ) {\n this.scheduleRender();\n }\n }\n\n /**\n * @internal\n */\n @state()\n tokenTree: TokenTree = {\n key: 'root',\n token: {\n type: 'root',\n tag: '',\n nesting: 0,\n level: 0,\n content: '',\n attrs: null,\n children: null,\n markup: '',\n block: true,\n hidden: false,\n map: null,\n info: '',\n meta: null,\n },\n children: [],\n };\n\n /**\n * @internal\n */\n @state()\n renderedContent: TemplateResult | null = null;\n\n /**\n * Throttled function that updates the rendered content.\n * If needsReparse is true, parses markdown into a token tree first.\n * Otherwise, just re-renders the existing token tree with current settings.\n *\n * @internal\n */\n private renderMarkdown = async () => {\n try {\n const markdownContent = this.markdown ?? '';\n const previousTreeForDiff =\n this.stagedStreamingTokenTree ?? this.tokenTree;\n let nextTokenTree = previousTreeForDiff;\n\n if (this.needsReparse) {\n // First, we take the markdown we were given and use the markdown-it parser to turn is into a tree we can\n // transform into Lit components and compare smartly to avoid re-renders of components that were already\n // rendered when the markdown is updated (likely by streaming, but possibly by an edit somewhere in the\n // middle). It takes the current tokenTree as an argument for quick diffing to avoid re-creating parts\n // of the tree.\n const parsed = markdownToTokenTree(\n markdownContent,\n previousTreeForDiff,\n {\n removeHtml: this.removeHTML,\n markdownItPlugins: this.markdownItPlugins,\n }\n );\n nextTokenTree = parsed.tree;\n this.markdownItInstance = parsed.md;\n this.needsReparse = false;\n }\n\n const hasStreamingTailTable =\n Boolean(this.streaming) && hasTrailingTableToken(nextTokenTree);\n const hasParsedNodeAfterTable = hasNodeAfterTable(nextTokenTree);\n\n if (!this.streaming) {\n this.isStreamingTableLoadingMode = false;\n } else if (this.isStreamingTableLoadingMode) {\n if (\n hasParsedNodeAfterTable &&\n !hasLikelyPartialTableTail(markdownContent)\n ) {\n this.isStreamingTableLoadingMode = false;\n }\n } else if (hasStreamingTailTable) {\n this.isStreamingTableLoadingMode = true;\n }\n\n // Render-and-stash helper. Each invocation produces a fresh batch of\n // renderer-slot descriptors; the `updated()` reconcile then invokes\n // the consumer's `customRenderers` callbacks for each descriptor and\n // adopts the returned `HTMLElement` as a light-DOM slot host.\n const renderAndDispatch = (tree: TokenTree): void => {\n const { template, batch } = renderMarkdownTree(tree, {\n sanitize: this.sanitizeHTML,\n streaming: this.streaming,\n // Code snippet properties\n codeSnippetHighlight: this.codeSnippetHighlight,\n codeSnippetShowLessText: this.codeSnippetShowLessText,\n codeSnippetShowMoreText: this.codeSnippetShowMoreText,\n codeSnippetCopyButtonTooltipContent:\n this.codeSnippetCopyButtonTooltipContent,\n codeSnippetGetLineCountText: this.codeSnippetGetLineCountText,\n codeSnippetAriaLabelReadOnly: this.codeSnippetAriaLabelReadOnly,\n codeSnippetAriaLabelEditable: this.codeSnippetAriaLabelEditable,\n // Table properties\n tableFilterPlaceholderText: this.tableFilterPlaceholderText,\n tablePreviousPageText: this.tablePreviousPageText,\n tableNextPageText: this.tableNextPageText,\n tableItemsPerPageText: this.tableItemsPerPageText,\n tableDownloadLabelText: this.tableDownloadLabelText,\n tableLocale: this.tableLocale,\n tableGetPaginationSupplementalText:\n this.tableGetPaginationSupplementalText,\n tableGetPaginationStatusText: this.tableGetPaginationStatusText,\n // Custom-renderer hooks\n customRenderers: this.customRenderers,\n slotNamespace: this.slotNamespace,\n md: this.markdownItInstance,\n });\n this.renderedContent = template;\n this.latestRendererDescriptors = batch;\n };\n\n if (this.streaming && this.isStreamingTableLoadingMode) {\n if (!this.hasRenderedStreamingTableLoadingFrame) {\n if (nextTokenTree !== this.tokenTree) {\n this.tokenTree = nextTokenTree;\n }\n renderAndDispatch(nextTokenTree);\n this.hasRenderedStreamingTableLoadingFrame = true;\n this.stagedStreamingTokenTree = null;\n } else {\n this.stagedStreamingTokenTree = nextTokenTree;\n }\n return;\n }\n\n // Never prefer the staged tree here: when nothing was reparsed `nextTokenTree`\n // *is* the staged tree (see `previousTreeForDiff` above), and when something\n // was, it came from newer source.\n this.stagedStreamingTokenTree = null;\n this.hasRenderedStreamingTableLoadingFrame = false;\n if (nextTokenTree !== this.tokenTree) {\n this.tokenTree = nextTokenTree;\n }\n\n // Next we take that tree and transform it into Lit content to be rendered into the template.\n // this.renderedContent is what is rendered in the template directly.\n renderAndDispatch(nextTokenTree);\n } catch (error) {\n console.error(`${CONSOLE_PREFIX} Failed to parse markdown`, error);\n }\n };\n\n /**\n * @internal\n */\n private scheduleRender = throttle(\n () => {\n // Lit's getter/setter pipeline can schedule multiple renders quickly.\n // We capture the active render promise so we can report completion later.\n const task = this.renderMarkdown();\n const trackedTask = task.finally(() => {\n if (this.renderTask === trackedTask) {\n this.renderTask = null;\n }\n });\n\n this.renderTask = trackedTask;\n return trackedTask;\n },\n 100,\n { leading: true, trailing: true }\n );\n\n protected async getUpdateComplete(): Promise<boolean> {\n // `updateComplete` is Lit's public hook for consumers/tests to await\n // all pending work. Because we throttle renders, the base implementation\n // might resolve before the throttled callback runs. Overriding this\n // method lets us flush the throttle and await the render promise so\n // callers can reliably wait for `renderedContent` to update.\n const result = await super.getUpdateComplete();\n\n const flushResult = (\n this.scheduleRender as {\n flush?: () => Promise<void> | void;\n }\n ).flush?.();\n\n if (flushResult instanceof Promise) {\n await flushResult;\n }\n\n if (this.renderTask) {\n await this.renderTask;\n }\n\n // Drain any in-flight Light DOM mutation microtasks and their resulting\n // renders. Each iteration yields the event loop so newly enqueued\n // mutations can settle; the counter goes back to zero once everything\n // has flushed.\n while (this.pendingLightDomMutations > 0) {\n await Promise.resolve();\n\n const postMutationFlush = (\n this.scheduleRender as {\n flush?: () => Promise<void> | void;\n }\n ).flush?.();\n\n if (postMutationFlush instanceof Promise) {\n await postMutationFlush;\n }\n\n if (this.renderTask) {\n await this.renderTask;\n }\n }\n\n return result;\n }\n\n protected updated(changed: PropertyValues<this>) {\n super.updated(changed);\n this.reconcileCustomRendererHosts();\n }\n\n /**\n * Drops a claim: retires the forwarder minted for it, if any, then tells the\n * container to let go.\n *\n * The forwarder goes first. An assigned node suppresses the shadow slot's\n * fallback content for as long as it exists, so a surviving forwarder turns\n * a removed host into a blank region instead of the default rendering.\n * @internal\n */\n /**\n * Records a claim and mints the innermost hop back to the host the listener\n * just relocated. Called in the same pass that read the claim because the\n * mount event fires once per host and is never replayed — minting here is\n * what makes a claim without its forwarder unrepresentable.\n * @internal\n */\n private adoptDelegatedSlot(slotName: string) {\n this.delegatedPluginSlots.add(slotName);\n const forwarder = document.createElement('slot');\n forwarder.setAttribute('name', slotName);\n forwarder.setAttribute('slot', slotName);\n this.rendererForwarders.set(slotName, forwarder);\n this.appendChild(forwarder);\n }\n\n private retireDelegatedSlot(slotName: string) {\n this.rendererForwarders.get(slotName)?.remove();\n this.rendererForwarders.delete(slotName);\n this.delegatedPluginSlots.delete(slotName);\n this.dispatchEvent(\n new CustomEvent('cds-custom-aichat-markdown-plugin-host-unmount', {\n bubbles: true,\n composed: true,\n detail: { slotName },\n })\n );\n }\n\n /**\n * Invoke the consumer's `customRenderers` callbacks once per descriptor and\n * adopt their returned `HTMLElement` as a `<span slot=\"…\">` (for inline\n * plugin tokens) or `<div slot=\"…\">` (block tokens and consumer renderers)\n * light-DOM child. Hosts persist across renders so a consumer returning the\n * same element reference produces no DOM churn; hosts whose slot names\n * dropped out of the latest descriptor batch are removed.\n *\n * @internal\n */\n private reconcileCustomRendererHosts() {\n const renderers = this.customRenderers;\n const descriptors = this.latestRendererDescriptors;\n const wanted = new Set<string>();\n\n for (const descriptor of descriptors) {\n if (descriptor.kind === 'pluginFallback') {\n wanted.add(descriptor.slotName);\n\n // Offer the slot to a chat-container ancestor first. The chain\n // appends the host to its OWN light DOM (page DOM at the top of the\n // chain) so external CSS (e.g. a KaTeX stylesheet on the host page)\n // reaches the plugin output. If a listener calls preventDefault, it\n // has taken over hosting and we skip the local appendChild path.\n const alreadyDelegated = this.delegatedPluginSlots.has(\n descriptor.slotName\n );\n if (!alreadyDelegated && !this.slotHosts.has(descriptor.slotName)) {\n const mountEvent = new CustomEvent(\n 'cds-custom-aichat-markdown-plugin-host-mount',\n {\n bubbles: true,\n composed: true,\n cancelable: true,\n detail: {\n kind: 'pluginFallback',\n slotName: descriptor.slotName,\n html: descriptor.html,\n isInline: descriptor.isInline,\n } satisfies MarkdownPluginFallbackMountDetail,\n }\n );\n this.dispatchEvent(mountEvent);\n if (mountEvent.defaultPrevented) {\n this.adoptDelegatedSlot(descriptor.slotName);\n }\n } else if (alreadyDelegated) {\n // The chain owns this slot; push HTML updates through a second\n // event so streaming chunks reach the page-level host element.\n this.dispatchEvent(\n new CustomEvent('cds-custom-aichat-markdown-plugin-host-update', {\n bubbles: true,\n composed: true,\n detail: {\n slotName: descriptor.slotName,\n html: descriptor.html,\n },\n })\n );\n }\n\n if (this.delegatedPluginSlots.has(descriptor.slotName)) {\n continue;\n }\n\n // Fallback: no outer listener took over (standalone usage, e.g.\n // storybook). Adopt the host as our own light-DOM child, matching\n // the pre-event behavior so existing tests/stories keep working.\n let host = this.slotHosts.get(descriptor.slotName);\n if (!host) {\n const tag = descriptor.isInline ? 'span' : 'div';\n host = document.createElement(tag);\n host.setAttribute('slot', descriptor.slotName);\n this.slotHosts.set(descriptor.slotName, host);\n this.appendChild(host);\n }\n // Only rewrite innerHTML when the plugin output actually changed;\n // streaming re-renders frequently land here with the same HTML.\n if (host.innerHTML !== descriptor.html) {\n host.innerHTML = descriptor.html;\n }\n continue;\n }\n\n const callback = renderers?.[descriptor.kind];\n if (!callback) {\n continue;\n }\n let result: HTMLElement | null;\n try {\n result = (\n callback as (\n args: Parameters<NonNullable<typeof callback>>[0]\n ) => HTMLElement | null\n )({\n ...descriptor.data,\n token: descriptor.token,\n slotName: descriptor.slotName,\n });\n } catch (error) {\n console.error(\n `[carbon-ai-chat-components] customRenderers.${descriptor.kind} threw`,\n error\n );\n continue;\n }\n if (result == null) {\n const existing = this.slotHosts.get(descriptor.slotName);\n if (existing) {\n existing.remove();\n this.slotHosts.delete(descriptor.slotName);\n }\n continue;\n }\n wanted.add(descriptor.slotName);\n let host = this.slotHosts.get(descriptor.slotName);\n if (!host) {\n host = document.createElement('div');\n host.setAttribute('slot', descriptor.slotName);\n this.slotHosts.set(descriptor.slotName, host);\n\n // Offer the host to a chat-container ancestor so it lives in page\n // light DOM, where consumer-loaded global CSS (e.g. `@carbon/styles`\n // for a returned `@carbon/react` component) can reach it — the markdown\n // element's own light DOM sits inside the chat's shadow root, where it\n // cannot. Mirrors the plugin-fallback path above, but forwards the live\n // host element instead of an HTML string; the markdown element keeps\n // ownership of the host's content across renders, and mints the slot\n // hop back to it below. If no ancestor takes over (standalone usage,\n // e.g. storybook), host it locally.\n const mountEvent = new CustomEvent(\n 'cds-custom-aichat-markdown-plugin-host-mount',\n {\n bubbles: true,\n composed: true,\n cancelable: true,\n detail: {\n kind: 'customRenderer',\n slotName: descriptor.slotName,\n element: host,\n isInline: false,\n } satisfies MarkdownCustomRendererMountDetail,\n }\n );\n this.dispatchEvent(mountEvent);\n if (mountEvent.defaultPrevented) {\n this.adoptDelegatedSlot(descriptor.slotName);\n } else {\n this.appendChild(host);\n }\n }\n if (host.firstChild !== result || host.childNodes.length !== 1) {\n host.replaceChildren(result);\n }\n }\n\n for (const [slotName, host] of this.slotHosts) {\n if (!wanted.has(slotName)) {\n host.remove();\n this.slotHosts.delete(slotName);\n }\n }\n\n // Drop claims whose descriptor disappeared (a streaming chunk removed a\n // math node, a `customRenderers` callback returned null): the host was\n // already detached above, so this retires the hop and announces.\n for (const slotName of this.delegatedPluginSlots.keys()) {\n if (!wanted.has(slotName)) {\n this.retireDelegatedSlot(slotName);\n }\n }\n }\n\n protected render() {\n const { renderedContent } = this;\n return html`<div class=\"cds-custom-aichat-markdown-stack\">\n ${renderedContent}\n </div>`;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'cds-custom-aichat-markdown': CDSAIChatMarkdown;\n }\n}\n\nexport { CDSAIChatMarkdown };\nexport default CDSAIChatMarkdown;\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;AAOG;AAkCH,MAAM,cAAc,GAAG,6BAA6B;AAEpD;;;;;AAKG;AACH,SAAS,kBAAkB,CAAC,IAAU,EAAE,QAAc,EAAA;IACpD,IAAI,GAAG,GAAgB,IAAI;AAC3B,IAAA,OAAO,GA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C,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE;AAS/B,CAAA,EAAA,iBAAA,CAAA,SAAA,EAAA,8BAAA,EAAA,MAAA,CAAA;AASb,UAAA,CAAA;IADC,QAAQ,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE;AACJ,CAAA,EAAA,iBAAA,CAAA,SAAA,EAAA,mBAAA,EAAA,MAAA,CAAA;AAiBvC,UAAA,CAAA;AADC,IAAA,QAAQ,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE;AACY,CAAA,EAAA,iBAAA,CAAA,SAAA,EAAA,iBAAA,EAAA,MAAA,CAAA;AAsT1C,UAAA,CAAA;AADC,IAAA,KAAK;AAmBJ,CAAA,EAAA,iBAAA,CAAA,SAAA,EAAA,WAAA,EAAA,MAAA,CAAA;AAMF,UAAA,CAAA;AADC,IAAA,KAAK;AACwC,CAAA,EAAA,iBAAA,CAAA,SAAA,EAAA,iBAAA,EAAA,MAAA,CAAA;AAte1C,iBAAiB,GAAA,UAAA,CAAA;AADtB,IAAA,aAAa,CAAC,CAAA,EAAG,MAAM,CAAA,SAAA,CAAW;AAC7B,CAAA,EAAA,iBAAiB,CA+3BtB;AASD,0BAAe,iBAAiB;;"}
|
|
@@ -279,10 +279,17 @@ function combineSplitHtmlBlocks(children) {
|
|
|
279
279
|
function serializeInlineToken(tokenTree) {
|
|
280
280
|
const token = tokenTree.token;
|
|
281
281
|
const type = token.type ?? '';
|
|
282
|
+
// Break tokens carry no content — return the HTML void element directly so
|
|
283
|
+
// the merged node renders a visible line break instead of the empty string.
|
|
284
|
+
// Not `'<br />\n'` — the trailing newline would add a stray whitespace text
|
|
285
|
+
// node as the run's sibling. The merged node keeps `type: 'html_inline'` and
|
|
286
|
+
// still routes through sanitizeHtmlContent → unsafeHTML; DOMPurify's default
|
|
287
|
+
// allow-list keeps <br>, so the element survives sanitize-html.
|
|
288
|
+
if (type === 'softbreak' || type === 'hardbreak') {
|
|
289
|
+
return '<br />';
|
|
290
|
+
}
|
|
282
291
|
if (type === 'text' ||
|
|
283
292
|
type === 'code_inline' ||
|
|
284
|
-
type === 'softbreak' ||
|
|
285
|
-
type === 'hardbreak' ||
|
|
286
293
|
type === 'entity' ||
|
|
287
294
|
type === 'html_inline') {
|
|
288
295
|
return token.content ?? '';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"html-helpers.js","sources":["../../../../../src/components/markdown/src/utils/html-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 type { TokenTree } from '../markdown-token-tree';\n\n// HTML elements that never ship closing tags; treat them as self-closing so the stack logic does not wait for </tag>.\nconst SELF_CLOSING_HTML_TAGS = new Set<string>([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\n// Token types we can safely glue into the combined HTML chunk. Anything else (e.g., emphasis markers) should abort\n// the merge to avoid damaging markdown.\nconst INLINE_HTML_ALLOWED_TOKEN_TYPES = new Set<string>([\n 'html_inline',\n 'text',\n 'softbreak',\n 'hardbreak',\n 'code_inline',\n 'entity',\n 'link_open',\n 'link_close',\n]);\n\ntype HtmlInlineTag =\n | { kind: 'opening'; tagName: string; selfClosing: boolean }\n | { kind: 'closing'; tagName: string };\n\ntype HtmlBlockBoundary =\n { kind: 'opening'; tagName: string } | { kind: 'closing'; tagName: string };\n\n/** Marker element appended to opening HTML so markdown children mount inside the block. */\nexport const HTML_CONTAINER_SLOT = '<div data-aichat-markdown=\"\"></div>';\n\n// Detects html_block openers (e.g. \"<div>\\n<summary>…\") that markdown-it split from\n// their closing tag. Used by combineSplitHtmlBlocks to wrap later markdown siblings\n// back inside the HTML element. Returns null for closers, self-closing tags, or blocks\n// that already include a matching </tag>.\nfunction parseHtmlBlockOpening(\n content: string | undefined\n): HtmlBlockBoundary | null {\n const trimmed = (content ?? '').trim();\n\n if (\n !trimmed.startsWith('<') ||\n trimmed.startsWith('</') ||\n trimmed.startsWith('<!') ||\n trimmed.startsWith('<?') ||\n trimmed.startsWith('<%')\n ) {\n return null;\n }\n\n const openingMatch = trimmed.match(/^<\\s*([A-Za-z][\\w:-]*)\\b/);\n if (!openingMatch) {\n return null;\n }\n\n const tagName = openingMatch[1].toLowerCase();\n if (SELF_CLOSING_HTML_TAGS.has(tagName) || /\\/>\\s*$/.test(trimmed)) {\n return null;\n }\n\n const closePattern = new RegExp(`</\\\\s*${tagName}\\\\s*>`, 'i');\n if (closePattern.test(trimmed)) {\n return null;\n }\n\n return { kind: 'opening', tagName };\n}\n\nfunction parseHtmlBlockClosing(\n content: string | undefined\n): HtmlBlockBoundary | null {\n const trimmed = (content ?? '').trim();\n const closingMatch = trimmed.match(/^<\\/\\s*([A-Za-z][\\w:-]*)\\s*>$/);\n if (!closingMatch) {\n return null;\n }\n\n return { kind: 'closing', tagName: closingMatch[1].toLowerCase() };\n}\n\n// Minimal tag parser that ignores comments/entities (e.g., <!-- ... -->) and reports whether a tag opens, closes, or\n// self-closes a given element.\nfunction parseHtmlInlineTag(content: string | undefined): HtmlInlineTag | null {\n const trimmed = (content ?? '').trim();\n\n if (!trimmed.startsWith('<') || !trimmed.endsWith('>')) {\n // Not bracketed like \"<...>\"; definitely not a tag token.\n return null;\n }\n\n if (trimmed.startsWith('</')) {\n // Closing tag: extract the element name. Reject malformed endings.\n const closingMatch = trimmed.match(/^<\\/\\s*([A-Za-z][\\w:-]*)\\s*>$/);\n if (!closingMatch) {\n return null;\n }\n return { kind: 'closing', tagName: closingMatch[1].toLowerCase() };\n }\n\n // Skip comments/doctype/instruction fragments; they cannot help balance nesting.\n if (\n trimmed.startsWith('<!') ||\n trimmed.startsWith('<?') ||\n trimmed.startsWith('<%')\n ) {\n return null;\n }\n\n // Opening tag: grab the element name even if attributes trail after it.\n const openingMatch = trimmed.match(/^<\\s*([A-Za-z][\\w:-]*)\\b[\\s\\S]*>$/);\n if (!openingMatch) {\n return null;\n }\n\n const tagName = openingMatch[1].toLowerCase();\n // Treat `<tag/>` and the HTML void elements as self-contained so they do not\n // add entries to the stack.\n const selfClosing =\n trimmed.endsWith('/>') || SELF_CLOSING_HTML_TAGS.has(tagName);\n\n return { kind: 'opening', tagName, selfClosing };\n}\n\n// Collapses runs of html_inline tokens (possibly interleaved with text) into a\n// single token so the browser does not auto-close the first tag mid-render.\nexport function combineConsecutiveHtmlInline(\n children: TokenTree[]\n): TokenTree[] {\n if (children.length < 2) {\n return children;\n }\n\n const combinedChildren: TokenTree[] = [];\n let didCombine = false;\n\n for (let index = 0; index < children.length; index++) {\n const startNode = children[index];\n\n if (startNode.token.type !== 'html_inline') {\n combinedChildren.push(startNode);\n continue;\n }\n\n const openingTag = parseHtmlInlineTag(startNode.token.content);\n if (\n !openingTag ||\n openingTag.kind !== 'opening' ||\n openingTag.selfClosing\n ) {\n combinedChildren.push(startNode);\n continue;\n }\n\n const stack: string[] = [openingTag.tagName]; // Track nested openings we must close.\n const chunkTokens: TokenTree[] = [startNode]; // Collect tokens to merge if the stack clears.\n let content = startNode.token.content ?? '';\n let endIndex = index;\n let success = false;\n\n for (let lookahead = index + 1; lookahead < children.length; lookahead++) {\n const candidate = children[lookahead];\n const tokenType = candidate.token.type ?? '';\n\n if (!INLINE_HTML_ALLOWED_TOKEN_TYPES.has(tokenType)) {\n // Encountered formatting/inline constructs we do not know how to merge.\n break;\n }\n\n if (tokenType === 'html_inline') {\n const parsed = parseHtmlInlineTag(candidate.token.content);\n if (!parsed) {\n // Malformed tag; abandon the merge.\n break;\n }\n\n chunkTokens.push(candidate);\n content += candidate.token.content ?? '';\n\n if (parsed.kind === 'opening') {\n if (!parsed.selfClosing) {\n // Push nested openers so we wait for their matching closers too.\n stack.push(parsed.tagName);\n }\n } else {\n const expected = stack[stack.length - 1];\n if (expected !== parsed.tagName) {\n // Mismatched closing tag; bail before corrupting structure.\n break;\n }\n\n stack.pop();\n endIndex = lookahead;\n\n if (stack.length === 0) {\n // All openings matched; we can fuse the run.\n success = true;\n break;\n }\n }\n\n continue;\n }\n\n // Non-tag inline content (text, code, breaks, links) is safe to append.\n chunkTokens.push(candidate);\n content += serializeInlineToken(candidate);\n }\n\n if (!success) {\n // If we couldn't successfully combine, just add the original token and continue\n combinedChildren.push(startNode);\n continue;\n }\n\n if (stack.length === 0 && endIndex > index) {\n combinedChildren.push({\n key: chunkTokens.map((token) => token.key).join('|'),\n token: {\n ...startNode.token,\n content,\n },\n children: [],\n });\n index = endIndex; // Skip over tokens we already collapsed.\n didCombine = true;\n continue;\n }\n\n combinedChildren.push(startNode);\n }\n\n return didCombine ? combinedChildren : children;\n}\n\n// Wraps markdown block tokens that sit between a split html_block opener and\n// closer so rendered content stays inside the HTML element (e.g. <details>).\nexport function combineSplitHtmlBlocks(children: TokenTree[]): TokenTree[] {\n if (children.length < 2) {\n return children;\n }\n\n const combinedChildren: TokenTree[] = [];\n let didCombine = false;\n\n for (let index = 0; index < children.length; index++) {\n const startNode = children[index];\n\n if (startNode.token.type !== 'html_block') {\n combinedChildren.push(startNode);\n continue;\n }\n\n const openingTag = parseHtmlBlockOpening(startNode.token.content);\n if (!openingTag) {\n combinedChildren.push(startNode);\n continue;\n }\n\n const stack: string[] = [openingTag.tagName];\n const innerChildren: TokenTree[] = [];\n let endIndex = index;\n let closingHtml = '';\n let success = false;\n\n for (let lookahead = index + 1; lookahead < children.length; lookahead++) {\n const candidate = children[lookahead];\n\n if (candidate.token.type === 'html_block') {\n const nestedClosing = parseHtmlBlockClosing(candidate.token.content);\n if (nestedClosing) {\n const expected = stack[stack.length - 1];\n if (expected !== nestedClosing.tagName) {\n break;\n }\n\n stack.pop();\n endIndex = lookahead;\n\n if (stack.length === 0) {\n closingHtml = candidate.token.content ?? '';\n success = true;\n break;\n }\n\n innerChildren.push(candidate);\n continue;\n }\n\n const nestedOpening = parseHtmlBlockOpening(candidate.token.content);\n if (nestedOpening) {\n stack.push(nestedOpening.tagName);\n }\n\n innerChildren.push(candidate);\n continue;\n }\n\n innerChildren.push(candidate);\n }\n\n if (!success || endIndex <= index) {\n combinedChildren.push(startNode);\n continue;\n }\n\n combinedChildren.push({\n key: [\n startNode.key,\n ...innerChildren.map((child) => child.key),\n children[endIndex].key,\n ].join('|'),\n token: {\n ...startNode.token,\n type: 'html_container',\n tag: openingTag.tagName,\n meta: { closingHtml },\n },\n children: innerChildren,\n });\n index = endIndex;\n didCombine = true;\n }\n\n return didCombine ? combinedChildren : children;\n}\n\nfunction serializeInlineToken(tokenTree: TokenTree): string {\n const token = tokenTree.token;\n const type = token.type ?? '';\n\n if (\n type === 'text' ||\n type === 'code_inline' ||\n type === 'softbreak' ||\n type === 'hardbreak' ||\n type === 'entity' ||\n type === 'html_inline'\n ) {\n return token.content ?? '';\n }\n\n if (type === 'link_open') {\n const attrs = (token.attrs ?? []) as Array<\n [string, string | null | undefined]\n >;\n const attrString = attrs\n .map(([name, value]) => {\n if (!name) {\n return '';\n }\n if (value === undefined || value === null) {\n return name;\n }\n const escaped = String(value).replace(/\"/g, '"');\n return `${name}=\"${escaped}\"`;\n })\n .filter(Boolean)\n .join(' ');\n\n const childContent = (tokenTree.children ?? [])\n .map((child) => serializeInlineToken(child))\n .join('');\n\n const openTag = attrString.length ? `<a ${attrString}>` : '<a>';\n return `${openTag}${childContent}</a>`;\n }\n\n if (type === 'link_close') {\n return '';\n }\n\n return token.content ?? '';\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAIH;AACA,MAAM,sBAAsB,GAAG,IAAI,GAAG,CAAS;IAC7C,MAAM;IACN,MAAM;IACN,IAAI;IACJ,KAAK;IACL,OAAO;IACP,IAAI;IACJ,KAAK;IACL,OAAO;IACP,MAAM;IACN,MAAM;IACN,OAAO;IACP,QAAQ;IACR,OAAO;IACP,KAAK;AACN,CAAA,CAAC;AAEF;A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AAI,EAAE;AACT,gBAAA,OAAO,EAAE;YACX;YACA,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,EAAE;AACzC,gBAAA,OAAO,IAAI;YACb;AACA,YAAA,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC;AACrD,YAAA,OAAO,CAAA,EAAG,IAAI,CAAA,EAAA,EAAK,OAAO,GAAG;AAC/B,QAAA,CAAC;aACA,MAAM,CAAC,OAAO;aACd,IAAI,CAAC,GAAG,CAAC;QAEZ,MAAM,YAAY,GAAG,CAAC,SAAS,CAAC,QAAQ,IAAI,EAAE;aAC3C,GAAG,CAAC,CAAC,KAAK,KAAK,oBAAoB,CAAC,KAAK,CAAC;aAC1C,IAAI,CAAC,EAAE,CAAC;AAEX,QAAA,MAAM,OAAO,GAAG,UAAU,CAAC,MAAM,GAAG,CAAA,GAAA,EAAM,UAAU,CAAA,CAAA,CAAG,GAAG,KAAK;AAC/D,QAAA,OAAO,CAAA,EAAG,OAAO,CAAA,EAAG,YAAY,MAAM;IACxC;AAEA,IAAA,IAAI,IAAI,KAAK,YAAY,EAAE;AACzB,QAAA,OAAO,EAAE;IACX;AAEA,IAAA,OAAO,KAAK,CAAC,OAAO,IAAI,EAAE;AAC5B;;"}
|
|
1
|
+
{"version":3,"file":"html-helpers.js","sources":["../../../../../src/components/markdown/src/utils/html-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 type { TokenTree } from '../markdown-token-tree';\n\n// HTML elements that never ship closing tags; treat them as self-closing so the stack logic does not wait for </tag>.\nconst SELF_CLOSING_HTML_TAGS = new Set<string>([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\n// Token types we can safely glue into the combined HTML chunk. Anything else (e.g., emphasis markers) should abort\n// the merge to avoid damaging markdown.\nconst INLINE_HTML_ALLOWED_TOKEN_TYPES = new Set<string>([\n 'html_inline',\n 'text',\n 'softbreak',\n 'hardbreak',\n 'code_inline',\n 'entity',\n 'link_open',\n 'link_close',\n]);\n\ntype HtmlInlineTag =\n | { kind: 'opening'; tagName: string; selfClosing: boolean }\n | { kind: 'closing'; tagName: string };\n\ntype HtmlBlockBoundary =\n { kind: 'opening'; tagName: string } | { kind: 'closing'; tagName: string };\n\n/** Marker element appended to opening HTML so markdown children mount inside the block. */\nexport const HTML_CONTAINER_SLOT = '<div data-aichat-markdown=\"\"></div>';\n\n// Detects html_block openers (e.g. \"<div>\\n<summary>…\") that markdown-it split from\n// their closing tag. Used by combineSplitHtmlBlocks to wrap later markdown siblings\n// back inside the HTML element. Returns null for closers, self-closing tags, or blocks\n// that already include a matching </tag>.\nfunction parseHtmlBlockOpening(\n content: string | undefined\n): HtmlBlockBoundary | null {\n const trimmed = (content ?? '').trim();\n\n if (\n !trimmed.startsWith('<') ||\n trimmed.startsWith('</') ||\n trimmed.startsWith('<!') ||\n trimmed.startsWith('<?') ||\n trimmed.startsWith('<%')\n ) {\n return null;\n }\n\n const openingMatch = trimmed.match(/^<\\s*([A-Za-z][\\w:-]*)\\b/);\n if (!openingMatch) {\n return null;\n }\n\n const tagName = openingMatch[1].toLowerCase();\n if (SELF_CLOSING_HTML_TAGS.has(tagName) || /\\/>\\s*$/.test(trimmed)) {\n return null;\n }\n\n const closePattern = new RegExp(`</\\\\s*${tagName}\\\\s*>`, 'i');\n if (closePattern.test(trimmed)) {\n return null;\n }\n\n return { kind: 'opening', tagName };\n}\n\nfunction parseHtmlBlockClosing(\n content: string | undefined\n): HtmlBlockBoundary | null {\n const trimmed = (content ?? '').trim();\n const closingMatch = trimmed.match(/^<\\/\\s*([A-Za-z][\\w:-]*)\\s*>$/);\n if (!closingMatch) {\n return null;\n }\n\n return { kind: 'closing', tagName: closingMatch[1].toLowerCase() };\n}\n\n// Minimal tag parser that ignores comments/entities (e.g., <!-- ... -->) and reports whether a tag opens, closes, or\n// self-closes a given element.\nfunction parseHtmlInlineTag(content: string | undefined): HtmlInlineTag | null {\n const trimmed = (content ?? '').trim();\n\n if (!trimmed.startsWith('<') || !trimmed.endsWith('>')) {\n // Not bracketed like \"<...>\"; definitely not a tag token.\n return null;\n }\n\n if (trimmed.startsWith('</')) {\n // Closing tag: extract the element name. Reject malformed endings.\n const closingMatch = trimmed.match(/^<\\/\\s*([A-Za-z][\\w:-]*)\\s*>$/);\n if (!closingMatch) {\n return null;\n }\n return { kind: 'closing', tagName: closingMatch[1].toLowerCase() };\n }\n\n // Skip comments/doctype/instruction fragments; they cannot help balance nesting.\n if (\n trimmed.startsWith('<!') ||\n trimmed.startsWith('<?') ||\n trimmed.startsWith('<%')\n ) {\n return null;\n }\n\n // Opening tag: grab the element name even if attributes trail after it.\n const openingMatch = trimmed.match(/^<\\s*([A-Za-z][\\w:-]*)\\b[\\s\\S]*>$/);\n if (!openingMatch) {\n return null;\n }\n\n const tagName = openingMatch[1].toLowerCase();\n // Treat `<tag/>` and the HTML void elements as self-contained so they do not\n // add entries to the stack.\n const selfClosing =\n trimmed.endsWith('/>') || SELF_CLOSING_HTML_TAGS.has(tagName);\n\n return { kind: 'opening', tagName, selfClosing };\n}\n\n// Collapses runs of html_inline tokens (possibly interleaved with text) into a\n// single token so the browser does not auto-close the first tag mid-render.\nexport function combineConsecutiveHtmlInline(\n children: TokenTree[]\n): TokenTree[] {\n if (children.length < 2) {\n return children;\n }\n\n const combinedChildren: TokenTree[] = [];\n let didCombine = false;\n\n for (let index = 0; index < children.length; index++) {\n const startNode = children[index];\n\n if (startNode.token.type !== 'html_inline') {\n combinedChildren.push(startNode);\n continue;\n }\n\n const openingTag = parseHtmlInlineTag(startNode.token.content);\n if (\n !openingTag ||\n openingTag.kind !== 'opening' ||\n openingTag.selfClosing\n ) {\n combinedChildren.push(startNode);\n continue;\n }\n\n const stack: string[] = [openingTag.tagName]; // Track nested openings we must close.\n const chunkTokens: TokenTree[] = [startNode]; // Collect tokens to merge if the stack clears.\n let content = startNode.token.content ?? '';\n let endIndex = index;\n let success = false;\n\n for (let lookahead = index + 1; lookahead < children.length; lookahead++) {\n const candidate = children[lookahead];\n const tokenType = candidate.token.type ?? '';\n\n if (!INLINE_HTML_ALLOWED_TOKEN_TYPES.has(tokenType)) {\n // Encountered formatting/inline constructs we do not know how to merge.\n break;\n }\n\n if (tokenType === 'html_inline') {\n const parsed = parseHtmlInlineTag(candidate.token.content);\n if (!parsed) {\n // Malformed tag; abandon the merge.\n break;\n }\n\n chunkTokens.push(candidate);\n content += candidate.token.content ?? '';\n\n if (parsed.kind === 'opening') {\n if (!parsed.selfClosing) {\n // Push nested openers so we wait for their matching closers too.\n stack.push(parsed.tagName);\n }\n } else {\n const expected = stack[stack.length - 1];\n if (expected !== parsed.tagName) {\n // Mismatched closing tag; bail before corrupting structure.\n break;\n }\n\n stack.pop();\n endIndex = lookahead;\n\n if (stack.length === 0) {\n // All openings matched; we can fuse the run.\n success = true;\n break;\n }\n }\n\n continue;\n }\n\n // Non-tag inline content (text, code, breaks, links) is safe to append.\n chunkTokens.push(candidate);\n content += serializeInlineToken(candidate);\n }\n\n if (!success) {\n // If we couldn't successfully combine, just add the original token and continue\n combinedChildren.push(startNode);\n continue;\n }\n\n if (stack.length === 0 && endIndex > index) {\n combinedChildren.push({\n key: chunkTokens.map((token) => token.key).join('|'),\n token: {\n ...startNode.token,\n content,\n },\n children: [],\n });\n index = endIndex; // Skip over tokens we already collapsed.\n didCombine = true;\n continue;\n }\n\n combinedChildren.push(startNode);\n }\n\n return didCombine ? combinedChildren : children;\n}\n\n// Wraps markdown block tokens that sit between a split html_block opener and\n// closer so rendered content stays inside the HTML element (e.g. <details>).\nexport function combineSplitHtmlBlocks(children: TokenTree[]): TokenTree[] {\n if (children.length < 2) {\n return children;\n }\n\n const combinedChildren: TokenTree[] = [];\n let didCombine = false;\n\n for (let index = 0; index < children.length; index++) {\n const startNode = children[index];\n\n if (startNode.token.type !== 'html_block') {\n combinedChildren.push(startNode);\n continue;\n }\n\n const openingTag = parseHtmlBlockOpening(startNode.token.content);\n if (!openingTag) {\n combinedChildren.push(startNode);\n continue;\n }\n\n const stack: string[] = [openingTag.tagName];\n const innerChildren: TokenTree[] = [];\n let endIndex = index;\n let closingHtml = '';\n let success = false;\n\n for (let lookahead = index + 1; lookahead < children.length; lookahead++) {\n const candidate = children[lookahead];\n\n if (candidate.token.type === 'html_block') {\n const nestedClosing = parseHtmlBlockClosing(candidate.token.content);\n if (nestedClosing) {\n const expected = stack[stack.length - 1];\n if (expected !== nestedClosing.tagName) {\n break;\n }\n\n stack.pop();\n endIndex = lookahead;\n\n if (stack.length === 0) {\n closingHtml = candidate.token.content ?? '';\n success = true;\n break;\n }\n\n innerChildren.push(candidate);\n continue;\n }\n\n const nestedOpening = parseHtmlBlockOpening(candidate.token.content);\n if (nestedOpening) {\n stack.push(nestedOpening.tagName);\n }\n\n innerChildren.push(candidate);\n continue;\n }\n\n innerChildren.push(candidate);\n }\n\n if (!success || endIndex <= index) {\n combinedChildren.push(startNode);\n continue;\n }\n\n combinedChildren.push({\n key: [\n startNode.key,\n ...innerChildren.map((child) => child.key),\n children[endIndex].key,\n ].join('|'),\n token: {\n ...startNode.token,\n type: 'html_container',\n tag: openingTag.tagName,\n meta: { closingHtml },\n },\n children: innerChildren,\n });\n index = endIndex;\n didCombine = true;\n }\n\n return didCombine ? combinedChildren : children;\n}\n\nfunction serializeInlineToken(tokenTree: TokenTree): string {\n const token = tokenTree.token;\n const type = token.type ?? '';\n\n // Break tokens carry no content — return the HTML void element directly so\n // the merged node renders a visible line break instead of the empty string.\n // Not `'<br />\\n'` — the trailing newline would add a stray whitespace text\n // node as the run's sibling. The merged node keeps `type: 'html_inline'` and\n // still routes through sanitizeHtmlContent → unsafeHTML; DOMPurify's default\n // allow-list keeps <br>, so the element survives sanitize-html.\n if (type === 'softbreak' || type === 'hardbreak') {\n return '<br />';\n }\n\n if (\n type === 'text' ||\n type === 'code_inline' ||\n type === 'entity' ||\n type === 'html_inline'\n ) {\n return token.content ?? '';\n }\n\n if (type === 'link_open') {\n const attrs = (token.attrs ?? []) as Array<\n [string, string | null | undefined]\n >;\n const attrString = attrs\n .map(([name, value]) => {\n if (!name) {\n return '';\n }\n if (value === undefined || value === null) {\n return name;\n }\n const escaped = String(value).replace(/\"/g, '"');\n return `${name}=\"${escaped}\"`;\n })\n .filter(Boolean)\n .join(' ');\n\n const childContent = (tokenTree.children ?? [])\n .map((child) => serializeInlineToken(child))\n .join('');\n\n const openTag = attrString.length ? `<a ${attrString}>` : '<a>';\n return `${openTag}${childContent}</a>`;\n }\n\n if (type === 'link_close') {\n return '';\n }\n\n return token.content ?? '';\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAIH;AACA,MAAM,sBAAsB,GAAG,IAAI,GAAG,CAAS;IAC7C,MAAM;IACN,MAAM;IACN,IAAI;IACJ,KAAK;IACL,OAAO;IACP,IAAI;IACJ,KAAK;IACL,OAAO;IACP,MAAM;IACN,MAAM;IACN,OAAO;IACP,QAAQ;IACR,OAAO;IACP,KAAK;AACN,CAAA,CAAC;AAEF;AACA;AACA,MAAM,+BAA+B,GAAG,IAAI,GAAG,CAAS;IACtD,aAAa;IACb,MAAM;IACN,WAAW;IACX,WAAW;IACX,aAAa;IACb,QAAQ;IACR,WAAW;IACX,YAAY;AACb,CAAA,CAAC;AASF;AACO,MAAM,mBAAmB,GAAG;AAEnC;AACA;AACA;AACA;AACA,SAAS,qBAAqB,CAC5B,OAA2B,EAAA;IAE3B,MAAM,OAAO,GAAG,CAAC,OAAO,IAAI,EAAE,EAAE,IAAI,EAAE;AAEtC,IAAA,IACE,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;AACxB,QAAA,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC;AACxB,QAA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AC,SAAS,CAAC,QAAQ,IAAI,EAAE;aAC3C,GAAG,CAAC,CAAC,KAAK,KAAK,oBAAoB,CAAC,KAAK,CAAC;aAC1C,IAAI,CAAC,EAAE,CAAC;AAEX,QAAA,MAAM,OAAO,GAAG,UAAU,CAAC,MAAM,GAAG,CAAA,GAAA,EAAM,UAAU,CAAA,CAAA,CAAG,GAAG,KAAK;AAC/D,QAAA,OAAO,CAAA,EAAG,OAAO,CAAA,EAAG,YAAY,MAAM;IACxC;AAEA,IAAA,IAAI,IAAI,KAAK,YAAY,EAAE;AACzB,QAAA,OAAO,EAAE;IACX;AAEA,IAAA,OAAO,KAAK,CAAC,OAAO,IAAI,EAAE;AAC5B;;"}
|
|
@@ -18,9 +18,12 @@ export declare function isNativelyHandled(token: Partial<Token>): boolean;
|
|
|
18
18
|
export declare function shouldDelegateToPluginRule(token: Partial<Token>, md: MarkdownIt | undefined): boolean;
|
|
19
19
|
/**
|
|
20
20
|
* Renders an unknown token via markdown-it's HTML renderer and emits a named
|
|
21
|
-
* `<slot>` placeholder
|
|
22
|
-
* `<div slot="…">` host containing the
|
|
23
|
-
* CSS (e.g. KaTeX's stylesheet) reaches the
|
|
21
|
+
* `<slot>` placeholder carrying the token's text as its fallback content. The
|
|
22
|
+
* markdown element adopts a light-DOM `<div slot="…">` host containing the
|
|
23
|
+
* sanitized HTML so consumer-supplied CSS (e.g. KaTeX's stylesheet) reaches the
|
|
24
|
+
* rendered output; the fallback is what a reader sees if that host never
|
|
25
|
+
* arrives — a container claimed the slot and no forwarder was minted — so a
|
|
26
|
+
* stranded host degrades to plain text instead of vanishing.
|
|
24
27
|
*
|
|
25
28
|
* For leaf token types in {@link PLUGIN_DELEGABLE_TOKEN_TYPES} the rendered
|
|
26
29
|
* HTML is cached on the {@link TokenTree} node and inherited across
|