@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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"carbon-autocomplete.js","sources":["../../../../../src/components/prompt-line/src/tiptap/carbon-autocomplete.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * `carbonAutocomplete` factory. Wraps `@tiptap/suggestion` directly (no\n * Mention node) — the `command` callback inserts plain text rather than a\n * schema node. Activates whenever the input has any non-empty text (the\n * legacy autocomplete contract).\n *\n * Dispatches `cds-custom-aichat-trigger-change` with `type: \"autocomplete\"` from\n * the suggestion-render lifecycle via the shared `dispatchTriggerChange`\n * helper.\n */\n\nimport { Extension } from '@tiptap/core';\nimport { PluginKey } from '@tiptap/pm/state';\nimport Suggestion from '@tiptap/suggestion';\n\nimport { dispatchTriggerChange } from './trigger-utils.js';\nimport type { AutocompleteConfig, SuggestionItem } from './types.js';\n\nexport interface ExcludedTrigger {\n char: string;\n position: 'anywhere' | 'start';\n}\n\nexport function carbonAutocomplete(\n config: AutocompleteConfig,\n excludeTriggers: ExcludedTrigger[] = []\n): Extension {\n const pluginKey = new PluginKey('carbonAutocompleteSuggestion');\n\n return Extension.create({\n name: 'carbonAutocomplete',\n\n addProseMirrorPlugins() {\n const editor = this.editor;\n let lastQuery: string | null = null;\n\n return [\n Suggestion<SuggestionItem>({\n editor,\n char: '',\n pluginKey,\n // Match any non-empty text as the autocomplete query.\n allowedPrefixes: null,\n findSuggestionMatch: ({ $position }) => {\n const text = $position.parent.textBetween(\n 0,\n $position.parentOffset,\n '\\n',\n '\\0'\n );\n if (!text || text.length === 0) {\n return null;\n }\n // Restrict the query to the trailing word (split on whitespace).\n const trailing = /\\S+$/.exec(text);\n if (!trailing) {\n return null;\n }\n const query = trailing[0];\n // Yield to co-installed mention/command extensions so they win\n // when their trigger char is active.\n for (const excluded of excludeTriggers) {\n if (!query.startsWith(excluded.char)) {\n continue;\n }\n if (excluded.position === 'anywhere') {\n return null;\n }\n if (text === query) {\n return null;\n }\n }\n const matchStart =\n $position.start() + $position.parentOffset - query.length;\n return {\n range: {\n from: matchStart,\n to: $position.start() + $position.parentOffset,\n },\n query,\n text: query,\n };\n },\n items: ({ query }) => resolveItems(config, query),\n command: ({ editor: ed, range, props }) => {\n const item = props as SuggestionItem;\n const insertText = item.value ?? item.label;\n ed.chain()\n .focus()\n .insertContentAt(range, [{ type: 'text', text: insertText }])\n .run();\n config.onSelect?.(item);\n },\n render: () => ({\n onStart: (props) => {\n lastQuery = props.query;\n dispatchTriggerChange(props.editor, {\n type: 'autocomplete',\n query: props.query,\n triggerOffset: props.range.from,\n });\n },\n onUpdate: (props) => {\n if (props.query === lastQuery) {\n return;\n }\n lastQuery = props.query;\n dispatchTriggerChange(props.editor, {\n type: 'autocomplete',\n query: props.query,\n triggerOffset: props.range.from,\n });\n },\n onExit: (props) => {\n lastQuery = null;\n dispatchTriggerChange(props.editor, null);\n },\n onKeyDown: () => false,\n }),\n }),\n ];\n },\n });\n}\n\nasync function resolveItems(\n config: AutocompleteConfig,\n query: string\n): Promise<SuggestionItem[]> {\n const minQueryLength = config.minQueryLength ?? 0;\n if (query.length < minQueryLength) {\n return [];\n }\n if (typeof config.items === 'function') {\n return Promise.resolve(config.items(query));\n }\n if (!query) {\n return config.items;\n }\n const lower = query.toLowerCase();\n return config.items.filter((item) =>\n item.label.toLowerCase().includes(lower)\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;AASG;
|
|
1
|
+
{"version":3,"file":"carbon-autocomplete.js","sources":["../../../../../src/components/prompt-line/src/tiptap/carbon-autocomplete.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * `carbonAutocomplete` factory. Wraps `@tiptap/suggestion` directly (no\n * Mention node) — the `command` callback inserts plain text rather than a\n * schema node. Activates whenever the input has any non-empty text (the\n * legacy autocomplete contract).\n *\n * Dispatches `cds-custom-aichat-trigger-change` with `type: \"autocomplete\"` from\n * the suggestion-render lifecycle via the shared `dispatchTriggerChange`\n * helper.\n */\n\nimport { Extension } from '@tiptap/core';\nimport { PluginKey } from '@tiptap/pm/state';\nimport Suggestion from '@tiptap/suggestion';\n\nimport { dispatchTriggerChange } from './trigger-utils.js';\nimport type { AutocompleteConfig, SuggestionItem } from './types.js';\n\n/**\n * A trigger character that autocomplete stands down for, so a co-installed\n * mention or command picker wins while its trigger is active. Pass a list of\n * these as the second argument to {@link carbonAutocomplete}.\n */\nexport interface ExcludedTrigger {\n /** The character to stand down for, such as `\"@\"` or `\"/\"`. */\n char: string;\n /**\n * Where that character has to sit. `\"anywhere\"` stands down for any word\n * starting with it; `\"start\"` stands down only when that word starts the\n * line. Mirrors the picker's own\n * {@link TriggerSuggestionConfig.triggerPosition}.\n */\n position: 'anywhere' | 'start';\n}\n\nexport function carbonAutocomplete(\n config: AutocompleteConfig,\n excludeTriggers: ExcludedTrigger[] = []\n): Extension {\n const pluginKey = new PluginKey('carbonAutocompleteSuggestion');\n\n return Extension.create({\n name: 'carbonAutocomplete',\n\n addProseMirrorPlugins() {\n const editor = this.editor;\n let lastQuery: string | null = null;\n\n return [\n Suggestion<SuggestionItem>({\n editor,\n char: '',\n pluginKey,\n // Match any non-empty text as the autocomplete query.\n allowedPrefixes: null,\n findSuggestionMatch: ({ $position }) => {\n const text = $position.parent.textBetween(\n 0,\n $position.parentOffset,\n '\\n',\n '\\0'\n );\n if (!text || text.length === 0) {\n return null;\n }\n // Restrict the query to the trailing word (split on whitespace).\n const trailing = /\\S+$/.exec(text);\n if (!trailing) {\n return null;\n }\n const query = trailing[0];\n // Yield to co-installed mention/command extensions so they win\n // when their trigger char is active.\n for (const excluded of excludeTriggers) {\n if (!query.startsWith(excluded.char)) {\n continue;\n }\n if (excluded.position === 'anywhere') {\n return null;\n }\n if (text === query) {\n return null;\n }\n }\n const matchStart =\n $position.start() + $position.parentOffset - query.length;\n return {\n range: {\n from: matchStart,\n to: $position.start() + $position.parentOffset,\n },\n query,\n text: query,\n };\n },\n items: ({ query }) => resolveItems(config, query),\n command: ({ editor: ed, range, props }) => {\n const item = props as SuggestionItem;\n const insertText = item.value ?? item.label;\n ed.chain()\n .focus()\n .insertContentAt(range, [{ type: 'text', text: insertText }])\n .run();\n config.onSelect?.(item);\n },\n render: () => ({\n onStart: (props) => {\n lastQuery = props.query;\n dispatchTriggerChange(props.editor, {\n type: 'autocomplete',\n query: props.query,\n triggerOffset: props.range.from,\n });\n },\n onUpdate: (props) => {\n if (props.query === lastQuery) {\n return;\n }\n lastQuery = props.query;\n dispatchTriggerChange(props.editor, {\n type: 'autocomplete',\n query: props.query,\n triggerOffset: props.range.from,\n });\n },\n onExit: (props) => {\n lastQuery = null;\n dispatchTriggerChange(props.editor, null);\n },\n onKeyDown: () => false,\n }),\n }),\n ];\n },\n });\n}\n\nasync function resolveItems(\n config: AutocompleteConfig,\n query: string\n): Promise<SuggestionItem[]> {\n const minQueryLength = config.minQueryLength ?? 0;\n if (query.length < minQueryLength) {\n return [];\n }\n if (typeof config.items === 'function') {\n return Promise.resolve(config.items(query));\n }\n if (!query) {\n return config.items;\n }\n const lower = query.toLowerCase();\n return config.items.filter((item) =>\n item.label.toLowerCase().includes(lower)\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;;AASG;SA0Ba,kBAAkB,CAChC,MAA0B,EAC1B,kBAAqC,EAAE,EAAA;AAEvC,IAAA,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,8BAA8B,CAAC;IAE/D,OAAO,SAAS,CAAC,MAAM,CAAC;AACtB,QAAA,IAAI,EAAE,oBAAoB;QAE1B,qBAAqB,GAAA;AACnB,YAAA,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM;YAC1B,IAAI,SAAS,GAAkB,IAAI;YAEnC,OAAO;AACL,gBAAA,UAAU,CAAiB;oBACzB,MAAM;AACN,oBAAA,IAAI,EAAE,EAAE;oBACR,SAAS;;AAET,oBAAA,eAAe,EAAE,IAAI;AACrB,oBAAA,mBAAmB,EAAE,CAAC,EAAE,SAAS,EAAE,KAAI;AACrC,wBAAA,MAAM,IAAI,GAAG,SAAS,CAAC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B,EAC1B,KAAa,EAAA;AAEb,IAAA,MAAM,cAAc,GAAG,MAAM,CAAC,cAAc,IAAI,CAAC;AACjD,IAAA,IAAI,KAAK,CAAC,MAAM,GAAG,cAAc,EAAE;AACjC,QAAA,OAAO,EAAE;IACX;AACA,IAAA,IAAI,OAAO,MAAM,CAAC,KAAK,KAAK,UAAU,EAAE;QACtC,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC7C;IACA,IAAI,CAAC,KAAK,EAAE;QACV,OAAO,MAAM,CAAC,KAAK;IACrB;AACA,IAAA,MAAM,KAAK,GAAG,KAAK,CAAC,WAAW,EAAE;IACjC,OAAO,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAC9B,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CACzC;AACH;;"}
|
|
@@ -13,9 +13,21 @@ import type { TriggerSuggestionConfig } from './types.js';
|
|
|
13
13
|
* `data`, and `trigger` extensions added by `carbonMention`/`carbonCommand`.
|
|
14
14
|
*/
|
|
15
15
|
export interface TokenChipAttrs {
|
|
16
|
+
/** Identifier of the item the chip came from. */
|
|
16
17
|
id?: string;
|
|
18
|
+
/** Text shown on the chip. */
|
|
17
19
|
label?: string;
|
|
20
|
+
/**
|
|
21
|
+
* String the chip contributes to the message text. Falls back to `label`
|
|
22
|
+
* when unset.
|
|
23
|
+
*/
|
|
18
24
|
value?: string;
|
|
25
|
+
/**
|
|
26
|
+
* Custom fields carried over from the selected item. Everything the
|
|
27
|
+
* suggestion item held beyond `id`, `label`, `value`, `avatar`,
|
|
28
|
+
* `description`, `disabled`, and `showTriggerInChip` lands here, so it
|
|
29
|
+
* survives a round trip through the editor's JSON.
|
|
30
|
+
*/
|
|
19
31
|
data?: unknown;
|
|
20
32
|
/**
|
|
21
33
|
* Trigger character to prefix onto the default chip text (e.g.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render-token-chip.js","sources":["../../../../../src/components/prompt-line/src/tiptap/render-token-chip.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Shared chip-rendering implementation used by both the editor's\n * `CarbonTokenNodeView` and the chat-side rich user message bubble. Builds\n * the wrapping `<span class=\"cds-custom-aichat--token\">` container, honors a\n * consumer-supplied `renderCustomToken`, and delegates the light-DOM portal\n * handshake to `renderInLightDom` so React adapters can hydrate custom chip\n * content. This is a thin token-specific wrapper over `renderInLightDom`.\n */\n\nimport type { ReactNode } from 'react';\n\nimport { setVarsForSelector } from '../../../shared/dynamic-css-var-sheet.js';\nimport { renderInLightDom } from './render-in-light-dom.js';\nimport type { SuggestionItem, TriggerSuggestionConfig } from './types.js';\n\nlet tokenStyleRulesInstalled = false;\n\nfunction ensureTokenStyleRules(): void {\n if (tokenStyleRulesInstalled) {\n return;\n }\n setVarsForSelector('.cds-custom-aichat--token', { 'white-space': 'normal' });\n setVarsForSelector('.cds-custom-aichat--token[data-token-context=\"composer\"]', {\n color: 'var(--cds-tag-color-blue, #0043ce)',\n });\n setVarsForSelector(\n '.cds-custom-aichat--token[data-token-context=\"composer\"]::selection',\n { 'background-color': 'var(--cds-tag-background-blue, #d0e2ff)' }\n );\n setVarsForSelector('.cds-custom-aichat--token[data-token-context=\"historical\"]', {\n color: 'var(--cds-link-secondary, #0043ce)',\n });\n tokenStyleRulesInstalled = true;\n}\n\n/**\n * Attributes carried by a mention/command JSONContent node. Matches the\n * Tiptap mention shape (`id`, `label`) plus the carbon-specific `value`,\n * `data`, and `trigger` extensions added by `carbonMention`/`carbonCommand`.\n */\nexport interface TokenChipAttrs {\n id?: string;\n label?: string;\n value?: string;\n data?: unknown;\n /**\n * Trigger character to prefix onto the default chip text (e.g.\n * `/summarize` vs `summarize`). Set at insert time by\n * `resolveShowTriggerInChip` — defaults to command nodes only, but is\n * overridable per-config or per-item via `TriggerSuggestionConfig`/\n * `SuggestionItem`'s `showTriggerInChip`.\n */\n trigger?: string | null;\n}\n\nexport interface RenderTokenChipArgs {\n /** Node attrs in mention shape. */\n attrs: TokenChipAttrs;\n /**\n * Subset of the trigger-suggestion config relevant to chip rendering. Only\n * `renderCustomToken` is read; other config fields are ignored.\n */\n config?: Pick<TriggerSuggestionConfig, 'renderCustomToken'>;\n /** Token type — usually `\"mention\"` or `\"command\"`. */\n type: 'mention' | 'command' | string;\n /**\n * Where to dispatch the light-DOM portal event when `renderCustomToken`\n * returns custom content. The NodeView passes the editor's `view.dom`\n * (already mounted under the chat wrapper) so the event reaches the portal\n * listener synchronously. When omitted, the event fires from the portal\n * container element itself with `bubbles: true, composed: true` — callers\n * that mount the chip lazily must ensure it lives under a listener subtree\n * before connection.\n */\n dispatchTarget?: EventTarget;\n /**\n * Visual variant to render. `\"composer\"` is the live, being-typed token in\n * the prompt-line editor; `\"historical\"` is a token inside an already-sent\n * message in the transcript. Drives the default chip's color/highlight —\n * see `ensureTokenStyleRules`.\n */\n context: 'composer' | 'historical';\n}\n\nexport function renderTokenChip(args: RenderTokenChipArgs): HTMLElement {\n const dom = createTokenContainer(args.attrs, args.type, args.context);\n const renderer = args.config?.renderCustomToken;\n\n if (!renderer) {\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n const item: SuggestionItem = {\n id: typeof args.attrs.id === 'string' ? args.attrs.id : '',\n label: typeof args.attrs.label === 'string' ? args.attrs.label : '',\n ...((args.attrs.data ?? {}) as Record<string, unknown>),\n };\n\n let result: HTMLElement | ReactNode | undefined;\n try {\n result = renderer(item);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\n 'Error in renderCustomToken, falling back to default chip:',\n error\n );\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n if (result == null) {\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n // Bridge the custom chip into the page's light DOM via the shared portal\n // handshake. The default chip rides along as the `<slot>` fallback so the\n // token still shows something until the portal commits.\n const { container } = renderInLightDom({\n content: result,\n dispatchTarget: args.dispatchTarget ?? dom,\n fallback: createDefaultChip(args.attrs),\n });\n dom.appendChild(container);\n\n return dom;\n}\n\nfunction createTokenContainer(\n attrs: TokenChipAttrs,\n type: string,\n context: 'composer' | 'historical'\n): HTMLElement {\n ensureTokenStyleRules();\n const dom = document.createElement('span');\n const value = typeof attrs.value === 'string' ? attrs.value : null;\n const label = typeof attrs.label === 'string' ? attrs.label : null;\n dom.setAttribute('contenteditable', 'false');\n dom.setAttribute('data-token-type', type);\n dom.setAttribute('data-token-context', context);\n dom.setAttribute('data-raw-value', value ?? label ?? '');\n dom.className = 'cds-custom-aichat--token';\n return dom;\n}\n\nfunction createDefaultChip(attrs: TokenChipAttrs): HTMLElement {\n const chip = document.createElement('span');\n const label = typeof attrs.label === 'string' ? attrs.label : null;\n const value = typeof attrs.value === 'string' ? attrs.value : null;\n const trigger = typeof attrs.trigger === 'string' ? attrs.trigger : '';\n chip.textContent = `${trigger}${label || value || ''}`;\n return chip;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAAA;;;;;;;AAOG;AAiBH,IAAI,wBAAwB,GAAG,KAAK;AAEpC,SAAS,qBAAqB,GAAA;IAC5B,IAAI,wBAAwB,EAAE;QAC5B;IACF;IACA,kBAAkB,CAAC,oBAAoB,EAAE,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC;IACrE,kBAAkB,CAAC,mDAAmD,EAAE;AACtE,QAAA,KAAK,EAAE,oCAAoC;AAC5C,KAAA,CAAC;IACF,kBAAkB,CAChB,8DAA8D,EAC9D,EAAE,kBAAkB,EAAE,yCAAyC,EAAE,CAClE;IACD,kBAAkB,CAAC,qDAAqD,EAAE;AACxE,QAAA,KAAK,EAAE,oCAAoC;AAC5C,KAAA,CAAC;IACF,wBAAwB,GAAG,IAAI;AACjC;
|
|
1
|
+
{"version":3,"file":"render-token-chip.js","sources":["../../../../../src/components/prompt-line/src/tiptap/render-token-chip.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Shared chip-rendering implementation used by both the editor's\n * `CarbonTokenNodeView` and the chat-side rich user message bubble. Builds\n * the wrapping `<span class=\"cds-custom-aichat--token\">` container, honors a\n * consumer-supplied `renderCustomToken`, and delegates the light-DOM portal\n * handshake to `renderInLightDom` so React adapters can hydrate custom chip\n * content. This is a thin token-specific wrapper over `renderInLightDom`.\n */\n\nimport type { ReactNode } from 'react';\n\nimport { setVarsForSelector } from '../../../shared/dynamic-css-var-sheet.js';\nimport { renderInLightDom } from './render-in-light-dom.js';\nimport type { SuggestionItem, TriggerSuggestionConfig } from './types.js';\n\nlet tokenStyleRulesInstalled = false;\n\nfunction ensureTokenStyleRules(): void {\n if (tokenStyleRulesInstalled) {\n return;\n }\n setVarsForSelector('.cds-custom-aichat--token', { 'white-space': 'normal' });\n setVarsForSelector('.cds-custom-aichat--token[data-token-context=\"composer\"]', {\n color: 'var(--cds-tag-color-blue, #0043ce)',\n });\n setVarsForSelector(\n '.cds-custom-aichat--token[data-token-context=\"composer\"]::selection',\n { 'background-color': 'var(--cds-tag-background-blue, #d0e2ff)' }\n );\n setVarsForSelector('.cds-custom-aichat--token[data-token-context=\"historical\"]', {\n color: 'var(--cds-link-secondary, #0043ce)',\n });\n tokenStyleRulesInstalled = true;\n}\n\n/**\n * Attributes carried by a mention/command JSONContent node. Matches the\n * Tiptap mention shape (`id`, `label`) plus the carbon-specific `value`,\n * `data`, and `trigger` extensions added by `carbonMention`/`carbonCommand`.\n */\nexport interface TokenChipAttrs {\n /** Identifier of the item the chip came from. */\n id?: string;\n /** Text shown on the chip. */\n label?: string;\n /**\n * String the chip contributes to the message text. Falls back to `label`\n * when unset.\n */\n value?: string;\n /**\n * Custom fields carried over from the selected item. Everything the\n * suggestion item held beyond `id`, `label`, `value`, `avatar`,\n * `description`, `disabled`, and `showTriggerInChip` lands here, so it\n * survives a round trip through the editor's JSON.\n */\n data?: unknown;\n /**\n * Trigger character to prefix onto the default chip text (e.g.\n * `/summarize` vs `summarize`). Set at insert time by\n * `resolveShowTriggerInChip` — defaults to command nodes only, but is\n * overridable per-config or per-item via `TriggerSuggestionConfig`/\n * `SuggestionItem`'s `showTriggerInChip`.\n */\n trigger?: string | null;\n}\n\nexport interface RenderTokenChipArgs {\n /** Node attrs in mention shape. */\n attrs: TokenChipAttrs;\n /**\n * Subset of the trigger-suggestion config relevant to chip rendering. Only\n * `renderCustomToken` is read; other config fields are ignored.\n */\n config?: Pick<TriggerSuggestionConfig, 'renderCustomToken'>;\n /** Token type — usually `\"mention\"` or `\"command\"`. */\n type: 'mention' | 'command' | string;\n /**\n * Where to dispatch the light-DOM portal event when `renderCustomToken`\n * returns custom content. The NodeView passes the editor's `view.dom`\n * (already mounted under the chat wrapper) so the event reaches the portal\n * listener synchronously. When omitted, the event fires from the portal\n * container element itself with `bubbles: true, composed: true` — callers\n * that mount the chip lazily must ensure it lives under a listener subtree\n * before connection.\n */\n dispatchTarget?: EventTarget;\n /**\n * Visual variant to render. `\"composer\"` is the live, being-typed token in\n * the prompt-line editor; `\"historical\"` is a token inside an already-sent\n * message in the transcript. Drives the default chip's color/highlight —\n * see `ensureTokenStyleRules`.\n */\n context: 'composer' | 'historical';\n}\n\nexport function renderTokenChip(args: RenderTokenChipArgs): HTMLElement {\n const dom = createTokenContainer(args.attrs, args.type, args.context);\n const renderer = args.config?.renderCustomToken;\n\n if (!renderer) {\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n const item: SuggestionItem = {\n id: typeof args.attrs.id === 'string' ? args.attrs.id : '',\n label: typeof args.attrs.label === 'string' ? args.attrs.label : '',\n ...((args.attrs.data ?? {}) as Record<string, unknown>),\n };\n\n let result: HTMLElement | ReactNode | undefined;\n try {\n result = renderer(item);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\n 'Error in renderCustomToken, falling back to default chip:',\n error\n );\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n if (result == null) {\n dom.appendChild(createDefaultChip(args.attrs));\n return dom;\n }\n\n // Bridge the custom chip into the page's light DOM via the shared portal\n // handshake. The default chip rides along as the `<slot>` fallback so the\n // token still shows something until the portal commits.\n const { container } = renderInLightDom({\n content: result,\n dispatchTarget: args.dispatchTarget ?? dom,\n fallback: createDefaultChip(args.attrs),\n });\n dom.appendChild(container);\n\n return dom;\n}\n\nfunction createTokenContainer(\n attrs: TokenChipAttrs,\n type: string,\n context: 'composer' | 'historical'\n): HTMLElement {\n ensureTokenStyleRules();\n const dom = document.createElement('span');\n const value = typeof attrs.value === 'string' ? attrs.value : null;\n const label = typeof attrs.label === 'string' ? attrs.label : null;\n dom.setAttribute('contenteditable', 'false');\n dom.setAttribute('data-token-type', type);\n dom.setAttribute('data-token-context', context);\n dom.setAttribute('data-raw-value', value ?? label ?? '');\n dom.className = 'cds-custom-aichat--token';\n return dom;\n}\n\nfunction createDefaultChip(attrs: TokenChipAttrs): HTMLElement {\n const chip = document.createElement('span');\n const label = typeof attrs.label === 'string' ? attrs.label : null;\n const value = typeof attrs.value === 'string' ? attrs.value : null;\n const trigger = typeof attrs.trigger === 'string' ? attrs.trigger : '';\n chip.textContent = `${trigger}${label || value || ''}`;\n return chip;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAAA;;;;;;;AAOG;AAiBH,IAAI,wBAAwB,GAAG,KAAK;AAEpC,SAAS,qBAAqB,GAAA;IAC5B,IAAI,wBAAwB,EAAE;QAC5B;IACF;IACA,kBAAkB,CAAC,oBAAoB,EAAE,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC;IACrE,kBAAkB,CAAC,mDAAmD,EAAE;AACtE,QAAA,KAAK,EAAE,oCAAoC;AAC5C,KAAA,CAAC;IACF,kBAAkB,CAChB,8DAA8D,EAC9D,EAAE,kBAAkB,EAAE,yCAAyC,EAA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AAI;AAClE,IAAA,MAAM,KAAK,GAAG,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,GAAG,KAAK,CAAC,KAAK,GAAG,IAAI;AAClE,IAAA,MAAM,OAAO,GAAG,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,GAAG,KAAK,CAAC,OAAO,GAAG,EAAE;AACtE,IAAA,IAAI,CAAC,WAAW,GAAG,CAAA,EAAG,OAAO,CAAA,EAAG,KAAK,IAAI,KAAK,IAAI,EAAE,CAAA,CAAE;AACtD,IAAA,OAAO,IAAI;AACb;;"}
|
|
@@ -166,7 +166,8 @@ export interface TriggerSuggestionConfig extends Omit<BaseSuggestionConfig, 'dis
|
|
|
166
166
|
* Note: only one autocomplete config per editor is supported, because Tiptap
|
|
167
167
|
* resolves extensions by name.
|
|
168
168
|
*/
|
|
169
|
-
export
|
|
169
|
+
export interface AutocompleteConfig extends BaseSuggestionConfig {
|
|
170
|
+
}
|
|
170
171
|
/**
|
|
171
172
|
* Configuration for starter prompts — shown when the editor is empty and
|
|
172
173
|
* focused. Extends {@link BaseSuggestionConfig} so consumers can supply a
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
|
|
9
9
|
import { createComponent } from '@lit/react';
|
|
10
|
-
import React, { forwardRef, useRef, useState, useCallback,
|
|
10
|
+
import React, { forwardRef, useRef, useState, useCallback, useMemo, useEffect } from 'react';
|
|
11
11
|
import { createPortal, flushSync } from 'react-dom';
|
|
12
12
|
import CDSAIChatMarkdown from '../components/markdown/src/markdown.js';
|
|
13
13
|
import { withWebComponentBridge } from './utils/withWebComponentBridge.js';
|
|
@@ -45,14 +45,6 @@ function isElement(value) {
|
|
|
45
45
|
const Markdown = forwardRef(function Markdown({ customRenderers, ...rest }, forwardedRef) {
|
|
46
46
|
const hostsRef = useRef(new Map());
|
|
47
47
|
const [portalEntries, setPortalEntries] = useState([]);
|
|
48
|
-
// Active plugin-fallback slot names that an outer chat container is hosting
|
|
49
|
-
// in page light DOM. When a chat-container ancestor catches the
|
|
50
|
-
// `cds-custom-aichat-markdown-plugin-host-mount` event (and calls preventDefault),
|
|
51
|
-
// the markdown element skips its own local-host fallback and relies on
|
|
52
|
-
// these forwarders to project the page-level host element through every
|
|
53
|
-
// shadow boundary into its named slot. Storybook standalone usage stays on
|
|
54
|
-
// the local-host path — no listener consumes the event there.
|
|
55
|
-
const [pluginSlotNames, setPluginSlotNames] = useState([]);
|
|
56
48
|
const markdownRef = useRef(null);
|
|
57
49
|
const setMarkdownRef = useCallback((node) => {
|
|
58
50
|
markdownRef.current = node;
|
|
@@ -63,40 +55,6 @@ const Markdown = forwardRef(function Markdown({ customRenderers, ...rest }, forw
|
|
|
63
55
|
forwardedRef.current = node;
|
|
64
56
|
}
|
|
65
57
|
}, [forwardedRef]);
|
|
66
|
-
useEffect(() => {
|
|
67
|
-
const node = markdownRef.current;
|
|
68
|
-
if (!node) {
|
|
69
|
-
return undefined;
|
|
70
|
-
}
|
|
71
|
-
const handleMount = (event) => {
|
|
72
|
-
const slotName = event.detail
|
|
73
|
-
?.slotName;
|
|
74
|
-
if (!slotName) {
|
|
75
|
-
return;
|
|
76
|
-
}
|
|
77
|
-
setPluginSlotNames((prev) => prev.includes(slotName) ? prev : [...prev, slotName]);
|
|
78
|
-
};
|
|
79
|
-
const handleUnmount = (event) => {
|
|
80
|
-
const slotName = event.detail
|
|
81
|
-
?.slotName;
|
|
82
|
-
if (!slotName) {
|
|
83
|
-
return;
|
|
84
|
-
}
|
|
85
|
-
setPluginSlotNames((prev) => prev.includes(slotName) ? prev.filter((n) => n !== slotName) : prev);
|
|
86
|
-
};
|
|
87
|
-
// Optimistic: we render a `<slot>` forwarder for every slot the markdown
|
|
88
|
-
// element emits. If a chat container ancestor takes over hosting (by
|
|
89
|
-
// calling `preventDefault()` on the mount event), the forwarder projects
|
|
90
|
-
// the page-level host through the chain. If nothing intercepts
|
|
91
|
-
// (standalone storybook), the markdown element creates its own local host
|
|
92
|
-
// alongside, and the empty forwarder is harmless.
|
|
93
|
-
node.addEventListener('cds-custom-aichat-markdown-plugin-host-mount', handleMount);
|
|
94
|
-
node.addEventListener('cds-custom-aichat-markdown-plugin-host-unmount', handleUnmount);
|
|
95
|
-
return () => {
|
|
96
|
-
node.removeEventListener('cds-custom-aichat-markdown-plugin-host-mount', handleMount);
|
|
97
|
-
node.removeEventListener('cds-custom-aichat-markdown-plugin-host-unmount', handleUnmount);
|
|
98
|
-
};
|
|
99
|
-
}, []);
|
|
100
58
|
const setPortalForSlot = useCallback((slotName, host, node) => {
|
|
101
59
|
setPortalEntries((prev) => {
|
|
102
60
|
const idx = prev.findIndex((e) => e.slotName === slotName);
|
|
@@ -198,7 +156,7 @@ const Markdown = forwardRef(function Markdown({ customRenderers, ...rest }, forw
|
|
|
198
156
|
cancelled = true;
|
|
199
157
|
};
|
|
200
158
|
});
|
|
201
|
-
return (jsxs(Fragment, { children: [jsx(BaseMarkdown, { ...rest, ref: setMarkdownRef, customRenderers: bridgedRenderers
|
|
159
|
+
return (jsxs(Fragment, { children: [jsx(BaseMarkdown, { ...rest, ref: setMarkdownRef, customRenderers: bridgedRenderers }), portalEntries.map((entry) => (jsx(React.Fragment, { children: createPortal(entry.node, entry.host) }, entry.slotName)))] }));
|
|
202
160
|
});
|
|
203
161
|
Markdown.displayName = 'Markdown';
|
|
204
162
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"markdown.js","sources":["../../src/react/markdown.tsx"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\nimport { createComponent } from '@lit/react';\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ComponentPropsWithoutRef,\n type ReactNode,\n} from 'react';\nimport { createPortal, flushSync } from 'react-dom';\n\n// Export the actual class for the component that will *directly* be wrapped with React.\nimport CDSAIChatMarkdown from '../components/markdown/src/markdown.js';\nimport type {\n MarkdownCustomRenderers,\n MarkdownRendererCodeBlockArgs,\n MarkdownRendererTableArgs,\n} from '../components/markdown/src/markdown-renderer-types.js';\nimport { withWebComponentBridge } from './utils/withWebComponentBridge';\n\nconst LitMarkdown = createComponent({\n tagName: 'cds-custom-aichat-markdown',\n elementClass: CDSAIChatMarkdown,\n react: React,\n});\n\nconst ForwardedBaseMarkdown = React.forwardRef<\n CDSAIChatMarkdown,\n React.ComponentProps<typeof LitMarkdown> & { markdown?: string }\n>(({ children, markdown, ...rest }, forwardedRef) => {\n const isTextChildren =\n typeof children === 'string' || typeof children === 'number';\n return React.createElement(\n LitMarkdown,\n {\n ...rest,\n ref: forwardedRef,\n markdown: markdown ?? (isTextChildren ? String(children) : undefined),\n },\n // Text children become the `markdown` prop; element children pass through\n // as light-DOM slot children (used by the React wrapper to mount plugin\n // slot forwarders inside the underlying `<cds-custom-aichat-markdown>`).\n isTextChildren ? null : children\n );\n});\n\nForwardedBaseMarkdown.displayName = 'BaseMarkdown';\n\n/**\n * Thin `@lit/react` bridge around `<cds-custom-aichat-markdown>`. Handles text vs.\n * element children and the web-component prop bridge, but performs no\n * React-specific `customRenderers` portaling — that is layered on by the\n * `Markdown` wrapper below.\n */\nconst BaseMarkdown = withWebComponentBridge(ForwardedBaseMarkdown);\n\n/**\n * React-flavored variant of {@link MarkdownCustomRenderers}. The element\n * replacements (`table`, `codeBlock`) may additionally return a `ReactNode`\n * (portaled into a light-DOM slot host) on top of the framework-neutral\n * `HTMLElement | null`. The attribute transforms (`link`, `image`) and the\n * `checklist` behavior hook return plain data, so they keep the base\n * signatures unchanged.\n */\nexport interface MarkdownReactCustomRenderers {\n /**\n * Override the default `cds-custom-aichat-table` rendering. Return a `ReactNode`\n * (rendered via portal into a light-DOM slot host) or an `HTMLElement`\n * (adopted into the slot host as-is); return `null` to fall back to the\n * default Carbon table renderer.\n */\n table?: (args: MarkdownRendererTableArgs) => ReactNode | HTMLElement | null;\n /**\n * Override the default `cds-custom-aichat-code-snippet` rendering. Return a\n * `ReactNode` (rendered via portal into a light-DOM slot host) or an\n * `HTMLElement` (adopted into the slot host as-is); return `null` to fall\n * back to the default Carbon code snippet renderer.\n */\n codeBlock?: (\n args: MarkdownRendererCodeBlockArgs\n ) => ReactNode | HTMLElement | null;\n /** Transform how links render. See {@link MarkdownCustomRenderers.link}. */\n link?: MarkdownCustomRenderers['link'];\n /** Transform how images render. See {@link MarkdownCustomRenderers.image}. */\n image?: MarkdownCustomRenderers['image'];\n /** Make task-list checkboxes actionable. See {@link MarkdownCustomRenderers.checklist}. */\n checklist?: MarkdownCustomRenderers['checklist'];\n}\n\ntype BaseMarkdownProps = Omit<\n ComponentPropsWithoutRef<typeof BaseMarkdown>,\n 'customRenderers'\n>;\n\n/**\n * Props for the React `<Markdown>` wrapper around `<cds-custom-aichat-markdown>`.\n */\nexport interface MarkdownProps extends BaseMarkdownProps {\n /**\n * Per-element render overrides. Each callback returns either a `ReactNode`\n * (rendered via portal into a light-DOM slot host) or an `HTMLElement`\n * (adopted into the slot host as-is). Return `null` to fall back to the\n * default Carbon rendering. Pass a stable reference (e.g. `useMemo`) — a\n * new object identity each render forces a full re-reconcile.\n */\n customRenderers?: MarkdownReactCustomRenderers;\n}\n\ntype PortalEntry = {\n slotName: string;\n host: HTMLDivElement;\n node: ReactNode;\n};\n\nfunction isElement(value: unknown): value is HTMLElement {\n return (\n typeof Element !== 'undefined' &&\n value instanceof Element &&\n 'tagName' in value\n );\n}\n\nconst Markdown = forwardRef<CDSAIChatMarkdown, MarkdownProps>(function Markdown(\n { customRenderers, ...rest },\n forwardedRef\n) {\n const hostsRef = useRef<Map<string, HTMLDivElement>>(new Map());\n const [portalEntries, setPortalEntries] = useState<PortalEntry[]>([]);\n\n // Active plugin-fallback slot names that an outer chat container is hosting\n // in page light DOM. When a chat-container ancestor catches the\n // `cds-custom-aichat-markdown-plugin-host-mount` event (and calls preventDefault),\n // the markdown element skips its own local-host fallback and relies on\n // these forwarders to project the page-level host element through every\n // shadow boundary into its named slot. Storybook standalone usage stays on\n // the local-host path — no listener consumes the event there.\n const [pluginSlotNames, setPluginSlotNames] = useState<string[]>([]);\n const markdownRef = useRef<CDSAIChatMarkdown | null>(null);\n const setMarkdownRef = useCallback(\n (node: CDSAIChatMarkdown | null) => {\n markdownRef.current = node;\n if (typeof forwardedRef === 'function') {\n forwardedRef(node);\n } else if (forwardedRef && 'current' in forwardedRef) {\n (\n forwardedRef as React.MutableRefObject<CDSAIChatMarkdown | null>\n ).current = node;\n }\n },\n [forwardedRef]\n );\n\n useEffect(() => {\n const node = markdownRef.current;\n if (!node) {\n return undefined;\n }\n const handleMount = (event: Event) => {\n const slotName = (event as CustomEvent<{ slotName: string }>).detail\n ?.slotName;\n if (!slotName) {\n return;\n }\n setPluginSlotNames((prev) =>\n prev.includes(slotName) ? prev : [...prev, slotName]\n );\n };\n const handleUnmount = (event: Event) => {\n const slotName = (event as CustomEvent<{ slotName: string }>).detail\n ?.slotName;\n if (!slotName) {\n return;\n }\n setPluginSlotNames((prev) =>\n prev.includes(slotName) ? prev.filter((n) => n !== slotName) : prev\n );\n };\n // Optimistic: we render a `<slot>` forwarder for every slot the markdown\n // element emits. If a chat container ancestor takes over hosting (by\n // calling `preventDefault()` on the mount event), the forwarder projects\n // the page-level host through the chain. If nothing intercepts\n // (standalone storybook), the markdown element creates its own local host\n // alongside, and the empty forwarder is harmless.\n node.addEventListener('cds-custom-aichat-markdown-plugin-host-mount', handleMount);\n node.addEventListener(\n 'cds-custom-aichat-markdown-plugin-host-unmount',\n handleUnmount\n );\n return () => {\n node.removeEventListener(\n 'cds-custom-aichat-markdown-plugin-host-mount',\n handleMount\n );\n node.removeEventListener(\n 'cds-custom-aichat-markdown-plugin-host-unmount',\n handleUnmount\n );\n };\n }, []);\n\n const setPortalForSlot = useCallback(\n (slotName: string, host: HTMLDivElement, node: ReactNode) => {\n setPortalEntries((prev) => {\n const idx = prev.findIndex((e) => e.slotName === slotName);\n if (idx >= 0 && prev[idx].node === node && prev[idx].host === host) {\n return prev;\n }\n if (idx >= 0) {\n const next = prev.slice();\n next[idx] = { slotName, host, node };\n return next;\n }\n return [...prev, { slotName, host, node }];\n });\n },\n []\n );\n\n const bridgedRenderers = useMemo<MarkdownCustomRenderers | undefined>(() => {\n if (!customRenderers) {\n return undefined;\n }\n const bridge = <Args extends { slotName: string }>(\n callback: (args: Args) => ReactNode | HTMLElement | null\n ) => {\n return (args: Args): HTMLElement | null => {\n const rendered = callback(args);\n if (rendered == null) {\n return null;\n }\n if (isElement(rendered)) {\n return rendered;\n }\n // Mint or reuse a stable host for this slot, then flush a portal\n // update synchronously so the host is populated before the Lit\n // element adopts it (no empty-host flash).\n let host = hostsRef.current.get(args.slotName);\n if (!host) {\n host = document.createElement('div');\n hostsRef.current.set(args.slotName, host);\n }\n flushSync(() => {\n setPortalForSlot(args.slotName, host as HTMLDivElement, rendered);\n });\n return host;\n };\n };\n\n const out: MarkdownCustomRenderers = {};\n if (customRenderers.table) {\n out.table = bridge(customRenderers.table);\n }\n if (customRenderers.codeBlock) {\n out.codeBlock = bridge(customRenderers.codeBlock);\n }\n // Attribute transforms / behavior hook return plain data (not DOM), so\n // they skip the portal bridge and pass straight through.\n if (customRenderers.link) {\n out.link = customRenderers.link;\n }\n if (customRenderers.image) {\n out.image = customRenderers.image;\n }\n if (customRenderers.checklist) {\n out.checklist = customRenderers.checklist;\n }\n return out;\n }, [customRenderers, setPortalForSlot]);\n\n // After every commit, prune portals whose host Lit has removed (its slot\n // dropped out of the descriptor batch, leaving the host detached). The\n // connectivity check is deferred to a microtask on purpose: `bridge` mints a\n // host, `flushSync`s the portal into it while it is still detached, and only\n // *returns* it to Lit — which appends it synchronously afterwards. That\n // `flushSync` runs this effect once while the host is not yet adopted, so a\n // synchronous `isConnected` check would prune the entry we just added and\n // leave the slot permanently empty (e.g. a streaming table custom renderer\n // flickering out as later content arrives). Reading `isConnected` a\n // microtask later lets Lit's adoption land first, so we only drop\n // genuinely-removed hosts.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(() => {\n let cancelled = false;\n queueMicrotask(() => {\n if (cancelled) {\n return;\n }\n let pruned = false;\n const aliveHosts = new Map<string, HTMLDivElement>();\n for (const [slotName, host] of hostsRef.current) {\n if (host.isConnected) {\n aliveHosts.set(slotName, host);\n } else {\n pruned = true;\n }\n }\n if (pruned) {\n hostsRef.current = aliveHosts;\n }\n setPortalEntries((prev) => {\n const filtered = prev.filter((e) => e.host.isConnected);\n return filtered.length === prev.length ? prev : filtered;\n });\n });\n return () => {\n cancelled = true;\n };\n });\n\n return (\n <>\n <BaseMarkdown\n {...rest}\n ref={setMarkdownRef as React.Ref<HTMLElement>}\n customRenderers={bridgedRenderers as never}>\n {pluginSlotNames.map((slotName) => (\n <slot key={slotName} name={slotName} slot={slotName} />\n ))}\n </BaseMarkdown>\n {portalEntries.map((entry) => (\n <React.Fragment key={entry.slotName}>\n {createPortal(entry.node, entry.host)}\n </React.Fragment>\n ))}\n </>\n );\n});\n\nMarkdown.displayName = 'Markdown';\n\nexport default Markdown;\n"],"names":["_jsxs","_Fragment","_jsx"],"mappings":";;;;;;;;;;;;;;AA+BA,MAAM,WAAW,GAAG,eAAe,CAAC;AAClC,IAAA,OAAO,EAAE,qBAAqB;AAC9B,IAAA,YAAY,EAAE,iBAAiB;AAC/B,IAAA,KAAK,EAAE,KAAK;AACb,CAAA,CAAC;AAEF,MAAM,qBAAqB,GAAG,KAAK,CAAC,UAAU,CAG5C,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,EAAE,YAAY,KAAI;IAClD,MAAM,cAAc,GAClB,OAAO,QAAQ,KAAK,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ;AAC9D,IAAA,OAAO,KAAK,CAAC,aAAa,CACxB,WAAW,EACX;AACE,QAAA,GAAG,IAAI;AACP,QAAA,GAAG,EAAE,YAAY;AACjB,QAAA,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AAC;gBAChC;qBAAO;oBACL,MAAM,GAAG,IAAI;gBACf;YACF;YACA,IAAI,MAAM,EAAE;AACV,gBAAA,QAAQ,CAAC,OAAO,GAAG,UAAU;YAC/B;AACA,YAAA,gBAAgB,CAAC,CAAC,IAAI,KAAI;AACxB,gBAAA,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC;AACvD,gBAAA,OAAO,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,GAAG,IAAI,GAAG,QAAQ;AAC1D,YAAA,CAAC,CAAC;AACJ,QAAA,CAAC,CAAC;AACF,QAAA,OAAO,MAAK;YACV,SAAS,GAAG,IAAI;AAClB,QAAA,CAAC;AACH,IAAA,CAAC,CAAC;AAEF,IAAA,QACEA,IAAA,CAAAC,QAAA,EAAA,EAAA,QAAA,EAAA,CACEC,GAAA,CAAC,YAAY,OACP,IAAI,EACR,GAAG,EAAE,cAAwC,EAC7C,eAAe,EAAE,gBAAyB,YACzC,eAAe,CAAC,GAAG,CAAC,CAAC,QAAQ,MAC5BA,GAAA,CAAA,MAAA,EAAA,EAAqB,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAA,EAAxC,QAAQ,CAAoC,CACxD,CAAC,EAAA,CACW,EACd,aAAa,CAAC,GAAG,CAAC,CAAC,KAAK,MACvBA,GAAA,CAAC,KAAK,CAAC,QAAQ,EAAA,EAAA,QAAA,EACZ,YAAY,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,EAAA,EADlB,KAAK,CAAC,QAAQ,CAElB,CAClB,CAAC,CAAA,EAAA,CACD;AAEP,CAAC;AAED,QAAQ,CAAC,WAAW,GAAG,UAAU;;"}
|
|
1
|
+
{"version":3,"file":"markdown.js","sources":["../../src/react/markdown.tsx"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\nimport { createComponent } from '@lit/react';\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ComponentPropsWithoutRef,\n type ReactNode,\n} from 'react';\nimport { createPortal, flushSync } from 'react-dom';\n\n// Export the actual class for the component that will *directly* be wrapped with React.\nimport CDSAIChatMarkdown from '../components/markdown/src/markdown.js';\nimport type {\n MarkdownCustomRenderers,\n MarkdownRendererCodeBlockArgs,\n MarkdownRendererTableArgs,\n} from '../components/markdown/src/markdown-renderer-types.js';\nimport { withWebComponentBridge } from './utils/withWebComponentBridge';\n\nconst LitMarkdown = createComponent({\n tagName: 'cds-custom-aichat-markdown',\n elementClass: CDSAIChatMarkdown,\n react: React,\n});\n\nconst ForwardedBaseMarkdown = React.forwardRef<\n CDSAIChatMarkdown,\n React.ComponentProps<typeof LitMarkdown> & { markdown?: string }\n>(({ children, markdown, ...rest }, forwardedRef) => {\n const isTextChildren =\n typeof children === 'string' || typeof children === 'number';\n return React.createElement(\n LitMarkdown,\n {\n ...rest,\n ref: forwardedRef,\n markdown: markdown ?? (isTextChildren ? String(children) : undefined),\n },\n // Text children become the `markdown` prop; element children pass through\n // as light-DOM slot children (used by the React wrapper to mount plugin\n // slot forwarders inside the underlying `<cds-custom-aichat-markdown>`).\n isTextChildren ? null : children\n );\n});\n\nForwardedBaseMarkdown.displayName = 'BaseMarkdown';\n\n/**\n * Thin `@lit/react` bridge around `<cds-custom-aichat-markdown>`. Handles text vs.\n * element children and the web-component prop bridge, but performs no\n * React-specific `customRenderers` portaling — that is layered on by the\n * `Markdown` wrapper below.\n */\nconst BaseMarkdown = withWebComponentBridge(ForwardedBaseMarkdown);\n\n/**\n * React-flavored variant of {@link MarkdownCustomRenderers}. The element\n * replacements (`table`, `codeBlock`) may additionally return a `ReactNode`\n * (portaled into a light-DOM slot host) on top of the framework-neutral\n * `HTMLElement | null`. The attribute transforms (`link`, `image`) and the\n * `checklist` behavior hook return plain data, so they keep the base\n * signatures unchanged.\n */\nexport interface MarkdownReactCustomRenderers {\n /**\n * Override the default `cds-custom-aichat-table` rendering. Return a `ReactNode`\n * (rendered via portal into a light-DOM slot host) or an `HTMLElement`\n * (adopted into the slot host as-is); return `null` to fall back to the\n * default Carbon table renderer.\n */\n table?: (args: MarkdownRendererTableArgs) => ReactNode | HTMLElement | null;\n /**\n * Override the default `cds-custom-aichat-code-snippet` rendering. Return a\n * `ReactNode` (rendered via portal into a light-DOM slot host) or an\n * `HTMLElement` (adopted into the slot host as-is); return `null` to fall\n * back to the default Carbon code snippet renderer.\n */\n codeBlock?: (\n args: MarkdownRendererCodeBlockArgs\n ) => ReactNode | HTMLElement | null;\n /** Transform how links render. See {@link MarkdownCustomRenderers.link}. */\n link?: MarkdownCustomRenderers['link'];\n /** Transform how images render. See {@link MarkdownCustomRenderers.image}. */\n image?: MarkdownCustomRenderers['image'];\n /** Make task-list checkboxes actionable. See {@link MarkdownCustomRenderers.checklist}. */\n checklist?: MarkdownCustomRenderers['checklist'];\n}\n\ntype BaseMarkdownProps = Omit<\n ComponentPropsWithoutRef<typeof BaseMarkdown>,\n 'customRenderers'\n>;\n\n/**\n * Props for the React `<Markdown>` wrapper around `<cds-custom-aichat-markdown>`.\n */\nexport interface MarkdownProps extends BaseMarkdownProps {\n /**\n * Per-element render overrides. Each callback returns either a `ReactNode`\n * (rendered via portal into a light-DOM slot host) or an `HTMLElement`\n * (adopted into the slot host as-is). Return `null` to fall back to the\n * default Carbon rendering. Pass a stable reference (e.g. `useMemo`) — a\n * new object identity each render forces a full re-reconcile.\n */\n customRenderers?: MarkdownReactCustomRenderers;\n}\n\ntype PortalEntry = {\n slotName: string;\n host: HTMLDivElement;\n node: ReactNode;\n};\n\nfunction isElement(value: unknown): value is HTMLElement {\n return (\n typeof Element !== 'undefined' &&\n value instanceof Element &&\n 'tagName' in value\n );\n}\n\nconst Markdown = forwardRef<CDSAIChatMarkdown, MarkdownProps>(function Markdown(\n { customRenderers, ...rest },\n forwardedRef\n) {\n const hostsRef = useRef<Map<string, HTMLDivElement>>(new Map());\n const [portalEntries, setPortalEntries] = useState<PortalEntry[]>([]);\n\n const markdownRef = useRef<CDSAIChatMarkdown | null>(null);\n const setMarkdownRef = useCallback(\n (node: CDSAIChatMarkdown | null) => {\n markdownRef.current = node;\n if (typeof forwardedRef === 'function') {\n forwardedRef(node);\n } else if (forwardedRef && 'current' in forwardedRef) {\n (\n forwardedRef as React.MutableRefObject<CDSAIChatMarkdown | null>\n ).current = node;\n }\n },\n [forwardedRef]\n );\n\n const setPortalForSlot = useCallback(\n (slotName: string, host: HTMLDivElement, node: ReactNode) => {\n setPortalEntries((prev) => {\n const idx = prev.findIndex((e) => e.slotName === slotName);\n if (idx >= 0 && prev[idx].node === node && prev[idx].host === host) {\n return prev;\n }\n if (idx >= 0) {\n const next = prev.slice();\n next[idx] = { slotName, host, node };\n return next;\n }\n return [...prev, { slotName, host, node }];\n });\n },\n []\n );\n\n const bridgedRenderers = useMemo<MarkdownCustomRenderers | undefined>(() => {\n if (!customRenderers) {\n return undefined;\n }\n const bridge = <Args extends { slotName: string }>(\n callback: (args: Args) => ReactNode | HTMLElement | null\n ) => {\n return (args: Args): HTMLElement | null => {\n const rendered = callback(args);\n if (rendered == null) {\n return null;\n }\n if (isElement(rendered)) {\n return rendered;\n }\n // Mint or reuse a stable host for this slot, then flush a portal\n // update synchronously so the host is populated before the Lit\n // element adopts it (no empty-host flash).\n let host = hostsRef.current.get(args.slotName);\n if (!host) {\n host = document.createElement('div');\n hostsRef.current.set(args.slotName, host);\n }\n flushSync(() => {\n setPortalForSlot(args.slotName, host as HTMLDivElement, rendered);\n });\n return host;\n };\n };\n\n const out: MarkdownCustomRenderers = {};\n if (customRenderers.table) {\n out.table = bridge(customRenderers.table);\n }\n if (customRenderers.codeBlock) {\n out.codeBlock = bridge(customRenderers.codeBlock);\n }\n // Attribute transforms / behavior hook return plain data (not DOM), so\n // they skip the portal bridge and pass straight through.\n if (customRenderers.link) {\n out.link = customRenderers.link;\n }\n if (customRenderers.image) {\n out.image = customRenderers.image;\n }\n if (customRenderers.checklist) {\n out.checklist = customRenderers.checklist;\n }\n return out;\n }, [customRenderers, setPortalForSlot]);\n\n // After every commit, prune portals whose host Lit has removed (its slot\n // dropped out of the descriptor batch, leaving the host detached). The\n // connectivity check is deferred to a microtask on purpose: `bridge` mints a\n // host, `flushSync`s the portal into it while it is still detached, and only\n // *returns* it to Lit — which appends it synchronously afterwards. That\n // `flushSync` runs this effect once while the host is not yet adopted, so a\n // synchronous `isConnected` check would prune the entry we just added and\n // leave the slot permanently empty (e.g. a streaming table custom renderer\n // flickering out as later content arrives). Reading `isConnected` a\n // microtask later lets Lit's adoption land first, so we only drop\n // genuinely-removed hosts.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(() => {\n let cancelled = false;\n queueMicrotask(() => {\n if (cancelled) {\n return;\n }\n let pruned = false;\n const aliveHosts = new Map<string, HTMLDivElement>();\n for (const [slotName, host] of hostsRef.current) {\n if (host.isConnected) {\n aliveHosts.set(slotName, host);\n } else {\n pruned = true;\n }\n }\n if (pruned) {\n hostsRef.current = aliveHosts;\n }\n setPortalEntries((prev) => {\n const filtered = prev.filter((e) => e.host.isConnected);\n return filtered.length === prev.length ? prev : filtered;\n });\n });\n return () => {\n cancelled = true;\n };\n });\n\n return (\n <>\n <BaseMarkdown\n {...rest}\n ref={setMarkdownRef as React.Ref<HTMLElement>}\n customRenderers={bridgedRenderers as never}\n />\n {portalEntries.map((entry) => (\n <React.Fragment key={entry.slotName}>\n {createPortal(entry.node, entry.host)}\n </React.Fragment>\n ))}\n </>\n );\n});\n\nMarkdown.displayName = 'Markdown';\n\nexport default Markdown;\n"],"names":["_jsxs","_jsx"],"mappings":";;;;;;;;;;;;;;AA+BA,MAAM,WAAW,GAAG,eAAe,CAAC;AAClC,IAAA,OAAO,EAAE,qBAAqB;AAC9B,IAAA,YAAY,EAAE,iBAAiB;AAC/B,I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AA,EAAA,CACD;AAEP,CAAC;AAED,QAAQ,CAAC,WAAW,GAAG,UAAU;;"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@carbon/ai-chat-components",
|
|
3
3
|
"description": "AI Chat Components",
|
|
4
|
-
"version": "1.10.0
|
|
4
|
+
"version": "1.10.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
7
|
"repository": {
|
|
@@ -159,5 +159,5 @@
|
|
|
159
159
|
"web-dev-server-plugin-lit-css": "^4.0.0",
|
|
160
160
|
"webpack-dev-server": "^5.2.5"
|
|
161
161
|
},
|
|
162
|
-
"gitHead": "
|
|
162
|
+
"gitHead": "f9776c4fee0d81e7561b1bf7c6690ed03c238704"
|
|
163
163
|
}
|