@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
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The container half of the plugin-host protocol.
|
|
3
|
+
*
|
|
4
|
+
* `<cds-aichat-markdown>` offers a host for plugin output to whichever chat
|
|
5
|
+
* element is outermost, over three composed events — `-mount`, `-update` and
|
|
6
|
+
* `-unmount`. Accepting the offer means calling `preventDefault()` on the
|
|
7
|
+
* mount event and putting the host somewhere consumer-loaded CSS can reach it,
|
|
8
|
+
* which the markdown element's own light DOM is not: it sits inside the chat's
|
|
9
|
+
* shadow root. A plugin-fallback offer hands over an HTML string this
|
|
10
|
+
* controller renders into a host it creates; a `customRenderers` offer hands
|
|
11
|
+
* over a live element this controller only re-parents.
|
|
12
|
+
*
|
|
13
|
+
* A container supplies only the element hosts are appended to, and whatever
|
|
14
|
+
* policy the framework cannot infer.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Mount detail for plugin output the element hands over as an HTML string.
|
|
18
|
+
*/
|
|
19
|
+
export interface MarkdownPluginFallbackMountDetail {
|
|
20
|
+
/** Marks the payload as an HTML string rather than a live element. */
|
|
21
|
+
kind: 'pluginFallback';
|
|
22
|
+
/**
|
|
23
|
+
* Name to put on the host's `slot` attribute, and the key the matching
|
|
24
|
+
* `-update` and `-unmount` events arrive under. Unique across every markdown
|
|
25
|
+
* element on the page, and reused across renders while the token stays put,
|
|
26
|
+
* so a streaming message rewrites one host instead of growing a new one per
|
|
27
|
+
* chunk. Treat the value as opaque; its format is not part of the API.
|
|
28
|
+
*/
|
|
29
|
+
slotName: string;
|
|
30
|
+
/**
|
|
31
|
+
* The plugin rule's rendered HTML, to assign to the host's `innerHTML`.
|
|
32
|
+
*
|
|
33
|
+
* DOMPurify runs over it only when the markdown element has `sanitize-html`
|
|
34
|
+
* set, and that setting is off by default. `remove-html` does not stand in
|
|
35
|
+
* for it either — that one escapes HTML written in the markdown source and
|
|
36
|
+
* never filters what a plugin's renderer rule emits. Treat the string as
|
|
37
|
+
* exactly as trustworthy as the markdown-it plugins the page registered.
|
|
38
|
+
*/
|
|
39
|
+
html: string;
|
|
40
|
+
/**
|
|
41
|
+
* True when the plugin's token is inline, such as a `math_inline` span.
|
|
42
|
+
* Picks the host tag — `span` when true, so the output stays in paragraph
|
|
43
|
+
* flow, `div` when false — and gates the block spacing that matches the
|
|
44
|
+
* markdown element's own stack gap.
|
|
45
|
+
*/
|
|
46
|
+
isInline: boolean;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Mount detail for a `customRenderers` host. It carries a live element the
|
|
50
|
+
* markdown element created, keeps writing to across renders, and removes.
|
|
51
|
+
* Claiming it means re-parenting that element into your own light DOM,
|
|
52
|
+
* synchronously, and nothing else: never rewrite its content, never style it,
|
|
53
|
+
* never remove it. The markdown element renders the `<slot>` hop that projects
|
|
54
|
+
* it back.
|
|
55
|
+
*/
|
|
56
|
+
export interface MarkdownCustomRendererMountDetail {
|
|
57
|
+
/** Marks the payload as a live element rather than an HTML string. */
|
|
58
|
+
kind: 'customRenderer';
|
|
59
|
+
/**
|
|
60
|
+
* Name already set on `element`'s `slot` attribute, and the key the matching
|
|
61
|
+
* `-unmount` event arrives under. Page-unique, reused across renders and
|
|
62
|
+
* opaque, like the plugin-fallback name. No `-update` event follows this
|
|
63
|
+
* one: the markdown element writes the consumer's node into `element`
|
|
64
|
+
* itself.
|
|
65
|
+
*/
|
|
66
|
+
slotName: string;
|
|
67
|
+
/**
|
|
68
|
+
* The host to re-parent. The markdown element created it, replaces its
|
|
69
|
+
* children on every render, and removes it when the renderer stops matching
|
|
70
|
+
* — a claimant only moves it.
|
|
71
|
+
*/
|
|
72
|
+
element: HTMLElement;
|
|
73
|
+
/**
|
|
74
|
+
* True when the claimed output is inline flow content. Always `false` here:
|
|
75
|
+
* the markdown element hosts every `customRenderers` result in a `<div>` it
|
|
76
|
+
* created, so a claimant has no host tag to choose. Declared on both members
|
|
77
|
+
* so a listener can read it before narrowing on `kind`.
|
|
78
|
+
*/
|
|
79
|
+
isInline: boolean;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The `cds-aichat-markdown-plugin-host-mount` detail, discriminated on `kind`.
|
|
83
|
+
*
|
|
84
|
+
* Narrow on `kind`, never on which of `html` / `element` is present — the two
|
|
85
|
+
* members deliberately declare only their own fields, so reading the wrong one
|
|
86
|
+
* is a compile error rather than a silent `undefined`.
|
|
87
|
+
*/
|
|
88
|
+
export type MarkdownPluginHostMountDetail = MarkdownPluginFallbackMountDetail | MarkdownCustomRendererMountDetail;
|
|
89
|
+
/**
|
|
90
|
+
* A mount detail as it arrives on the wire, `kind` included or not.
|
|
91
|
+
*
|
|
92
|
+
* `kind` is newer than the events themselves, and `@carbon/ai-chat` depends on
|
|
93
|
+
* this package through a caret range, so a listener can still receive the
|
|
94
|
+
* original shape from an older build. Pass anything you receive through
|
|
95
|
+
* `resolveMarkdownPluginHostMountDetail`, exported from
|
|
96
|
+
* `@carbon/ai-chat-components/es/components/markdown/src/utils/plugin-host-container.js`,
|
|
97
|
+
* and narrow on the result.
|
|
98
|
+
*/
|
|
99
|
+
export type MarkdownPluginHostMountDetailInput = MarkdownPluginHostMountDetail | Omit<MarkdownPluginFallbackMountDetail, 'kind'> | Omit<MarkdownCustomRendererMountDetail, 'kind'>;
|
|
100
|
+
/**
|
|
101
|
+
* Fills in `kind` for a detail emitted before the field existed.
|
|
102
|
+
*
|
|
103
|
+
* The one place the payload's shape is still consulted, and only when there is
|
|
104
|
+
* nothing else to go on. Delete it once the floor on `@carbon/ai-chat-components`
|
|
105
|
+
* rises past the release that added `kind`.
|
|
106
|
+
*/
|
|
107
|
+
export declare function resolveMarkdownPluginHostMountDetail(detail: MarkdownPluginHostMountDetailInput): MarkdownPluginHostMountDetail;
|
|
108
|
+
export interface MarkdownPluginHostControllerOptions {
|
|
109
|
+
/**
|
|
110
|
+
* Called with a fresh array whenever the set of slot names this surface
|
|
111
|
+
* should forward inward changes. Surfaces one shadow boundary from the
|
|
112
|
+
* markdown element render no forwarder of their own and omit it — the React
|
|
113
|
+
* `ChatContainer` is the one in this repo.
|
|
114
|
+
*
|
|
115
|
+
* Both kinds, and including names this surface declined to host: a container
|
|
116
|
+
* nested inside an outer chat element still has to forward the slot the
|
|
117
|
+
* outer one is hosting. The innermost hop — into the markdown element's own
|
|
118
|
+
* shadow slot — is never one of these; the element mints that one, for
|
|
119
|
+
* either kind, in the pass that read the claim.
|
|
120
|
+
*/
|
|
121
|
+
onSlotNamesChange?: (slotNames: string[]) => void;
|
|
122
|
+
/**
|
|
123
|
+
* Return `true` to forward the slot without hosting it, because an outer
|
|
124
|
+
* chat element will. Omitted by surfaces that are always outermost.
|
|
125
|
+
*/
|
|
126
|
+
shouldDefer?: (event: Event) => boolean;
|
|
127
|
+
}
|
|
128
|
+
export interface MarkdownPluginHostController {
|
|
129
|
+
/** Subscribes to the three events. Safe to call again without disconnecting. */
|
|
130
|
+
connect(): void;
|
|
131
|
+
/**
|
|
132
|
+
* Unsubscribes and removes the hosts this controller created. Relocated
|
|
133
|
+
* `customRenderers` elements are left parented — they belong to the markdown
|
|
134
|
+
* element, and as children of `target` they ride along with a DOM move.
|
|
135
|
+
* Forwarded slot names survive too.
|
|
136
|
+
*/
|
|
137
|
+
disconnect(): void;
|
|
138
|
+
/**
|
|
139
|
+
* Plugin-fallback hosts this controller created, keyed by slot name.
|
|
140
|
+
* Relocated `customRenderers` elements are deliberately absent.
|
|
141
|
+
*/
|
|
142
|
+
readonly hosts: ReadonlyMap<string, HTMLElement>;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Answers the plugin-host offer on `target`'s behalf, hosting accepted offers
|
|
146
|
+
* as slot-attributed children of `target`.
|
|
147
|
+
*
|
|
148
|
+
* `target` is both the listener and the host parent because in every chat
|
|
149
|
+
* surface they are the same element — the offer is claimed by whichever chat
|
|
150
|
+
* element is outermost, and that is the element whose light DOM is page DOM.
|
|
151
|
+
*
|
|
152
|
+
* Not part of this package's advertised surface: it is deliberately absent from
|
|
153
|
+
* `components/markdown/index.ts`, where only the detail types above are
|
|
154
|
+
* exported. It is not marked with the internal JSDoc tag either — this package
|
|
155
|
+
* compiles with `stripInternal`, which would drop the declaration from the
|
|
156
|
+
* emitted `.d.ts`, and every caller lives in the sibling package and resolves
|
|
157
|
+
* its types through exactly that file. (Do not write that tag's name anywhere
|
|
158
|
+
* in this comment: `stripInternal` matches the string, not just a real tag.)
|
|
159
|
+
*/
|
|
160
|
+
export declare function createMarkdownPluginHostController(target: HTMLElement, options?: MarkdownPluginHostControllerOptions): MarkdownPluginHostController;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright IBM Corp. 2025
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the Apache-2.0 license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/*
|
|
9
|
+
* Copyright IBM Corp. 2026
|
|
10
|
+
*
|
|
11
|
+
* This source code is licensed under the Apache-2.0 license found in the
|
|
12
|
+
* LICENSE file in the root directory of this source tree.
|
|
13
|
+
*
|
|
14
|
+
* @license
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Fills in `kind` for a detail emitted before the field existed.
|
|
18
|
+
*
|
|
19
|
+
* The one place the payload's shape is still consulted, and only when there is
|
|
20
|
+
* nothing else to go on. Delete it once the floor on `@carbon/ai-chat-components`
|
|
21
|
+
* rises past the release that added `kind`.
|
|
22
|
+
*/
|
|
23
|
+
function resolveMarkdownPluginHostMountDetail(detail) {
|
|
24
|
+
if ('kind' in detail) {
|
|
25
|
+
return detail;
|
|
26
|
+
}
|
|
27
|
+
return 'element' in detail
|
|
28
|
+
? { ...detail, kind: 'customRenderer' }
|
|
29
|
+
: { ...detail, kind: 'pluginFallback' };
|
|
30
|
+
}
|
|
31
|
+
const MOUNT = 'cds-aichat-markdown-plugin-host-mount';
|
|
32
|
+
const UPDATE = 'cds-aichat-markdown-plugin-host-update';
|
|
33
|
+
const UNMOUNT = 'cds-aichat-markdown-plugin-host-unmount';
|
|
34
|
+
/**
|
|
35
|
+
* Answers the plugin-host offer on `target`'s behalf, hosting accepted offers
|
|
36
|
+
* as slot-attributed children of `target`.
|
|
37
|
+
*
|
|
38
|
+
* `target` is both the listener and the host parent because in every chat
|
|
39
|
+
* surface they are the same element — the offer is claimed by whichever chat
|
|
40
|
+
* element is outermost, and that is the element whose light DOM is page DOM.
|
|
41
|
+
*
|
|
42
|
+
* Not part of this package's advertised surface: it is deliberately absent from
|
|
43
|
+
* `components/markdown/index.ts`, where only the detail types above are
|
|
44
|
+
* exported. It is not marked with the internal JSDoc tag either — this package
|
|
45
|
+
* compiles with `stripInternal`, which would drop the declaration from the
|
|
46
|
+
* emitted `.d.ts`, and every caller lives in the sibling package and resolves
|
|
47
|
+
* its types through exactly that file. (Do not write that tag's name anywhere
|
|
48
|
+
* in this comment: `stripInternal` matches the string, not just a real tag.)
|
|
49
|
+
*/
|
|
50
|
+
function createMarkdownPluginHostController(target, options = {}) {
|
|
51
|
+
const { onSlotNamesChange, shouldDefer } = options;
|
|
52
|
+
// Keyed by slot name alone: the markdown element namespaces every name it
|
|
53
|
+
// mints per element (see `./slot-names.js`), so two messages rendering the
|
|
54
|
+
// same markdown can't collide here. Only hosts this controller created —
|
|
55
|
+
// a relocated `customRenderers` element is parented to `target` but never
|
|
56
|
+
// entered here, which is what keeps `handleUpdate` from clobbering a
|
|
57
|
+
// consumer's node and `disconnect()` from destroying one.
|
|
58
|
+
const hosts = new Map();
|
|
59
|
+
let slotNames = [];
|
|
60
|
+
// Built once, not per `connect()`: a Lit `connectedCallback` can fire again
|
|
61
|
+
// without an intervening disconnect, and fresh closures would register a
|
|
62
|
+
// second time and handle every mount twice.
|
|
63
|
+
const handleMount = (event) => {
|
|
64
|
+
const raw = event.detail;
|
|
65
|
+
if (!raw?.slotName) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const detail = resolveMarkdownPluginHostMountDetail(raw);
|
|
69
|
+
// Track before deferring: a container nested inside an outer chat element
|
|
70
|
+
// hosts nothing but still has to forward the slot inward.
|
|
71
|
+
if (!slotNames.includes(detail.slotName)) {
|
|
72
|
+
slotNames = [...slotNames, detail.slotName];
|
|
73
|
+
onSlotNamesChange?.(slotNames);
|
|
74
|
+
}
|
|
75
|
+
if (shouldDefer?.(event)) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
event.preventDefault();
|
|
79
|
+
if (detail.kind === 'customRenderer') {
|
|
80
|
+
// A live node the markdown element created, keeps writing to and
|
|
81
|
+
// removes: re-parent it and nothing else. No inline spacing — the stack
|
|
82
|
+
// gap lives on the `<slot>` placeholder in the element's own shadow CSS,
|
|
83
|
+
// and a style attribute here would outrank the page stylesheet this
|
|
84
|
+
// relocation exists to admit.
|
|
85
|
+
detail.element.setAttribute('slot', detail.slotName);
|
|
86
|
+
// Re-appending a node already parented here detaches and reattaches the
|
|
87
|
+
// consumer's whole subtree, running its disconnect/connect teardown.
|
|
88
|
+
if (detail.element.parentElement !== target) {
|
|
89
|
+
target.appendChild(detail.element);
|
|
90
|
+
}
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
let host = hosts.get(detail.slotName);
|
|
94
|
+
if (!host) {
|
|
95
|
+
host = document.createElement(detail.isInline ? 'span' : 'div');
|
|
96
|
+
host.setAttribute('slot', detail.slotName);
|
|
97
|
+
// Match `.cds-aichat-markdown-stack > *:not(:first-child)` spacing;
|
|
98
|
+
// shadow CSS doesn't reach a host in page light DOM, so apply it inline.
|
|
99
|
+
// Inline output flows with text and gets no extra spacing.
|
|
100
|
+
if (!detail.isInline) {
|
|
101
|
+
host.style.marginBlockStart = '1rem';
|
|
102
|
+
}
|
|
103
|
+
hosts.set(detail.slotName, host);
|
|
104
|
+
target.appendChild(host);
|
|
105
|
+
}
|
|
106
|
+
// `?? ''` here and in `handleUpdate`: `html` is typed `string`, but the
|
|
107
|
+
// emitter can be a third-party element this compiler never saw, and
|
|
108
|
+
// `innerHTML = undefined` writes the literal string "undefined".
|
|
109
|
+
if (host.innerHTML !== (detail.html ?? '')) {
|
|
110
|
+
host.innerHTML = detail.html ?? '';
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const handleUpdate = (event) => {
|
|
114
|
+
const detail = event.detail;
|
|
115
|
+
if (!detail?.slotName) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const host = hosts.get(detail.slotName);
|
|
119
|
+
if (host && host.innerHTML !== (detail.html ?? '')) {
|
|
120
|
+
host.innerHTML = detail.html ?? '';
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
const handleUnmount = (event) => {
|
|
124
|
+
const detail = event
|
|
125
|
+
.detail;
|
|
126
|
+
if (!detail?.slotName) {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (slotNames.includes(detail.slotName)) {
|
|
130
|
+
slotNames = slotNames.filter((name) => name !== detail.slotName);
|
|
131
|
+
onSlotNamesChange?.(slotNames);
|
|
132
|
+
}
|
|
133
|
+
const host = hosts.get(detail.slotName);
|
|
134
|
+
if (host) {
|
|
135
|
+
host.remove();
|
|
136
|
+
hosts.delete(detail.slotName);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
return {
|
|
140
|
+
hosts,
|
|
141
|
+
connect() {
|
|
142
|
+
target.addEventListener(MOUNT, handleMount);
|
|
143
|
+
target.addEventListener(UPDATE, handleUpdate);
|
|
144
|
+
target.addEventListener(UNMOUNT, handleUnmount);
|
|
145
|
+
},
|
|
146
|
+
disconnect() {
|
|
147
|
+
target.removeEventListener(MOUNT, handleMount);
|
|
148
|
+
target.removeEventListener(UPDATE, handleUpdate);
|
|
149
|
+
target.removeEventListener(UNMOUNT, handleUnmount);
|
|
150
|
+
for (const host of hosts.values()) {
|
|
151
|
+
host.remove();
|
|
152
|
+
}
|
|
153
|
+
hosts.clear();
|
|
154
|
+
// Slot names deliberately survive. `handleUpdate` drops an update whose
|
|
155
|
+
// host is missing, so retention would strand a slot if only this element
|
|
156
|
+
// cycled — it is safe because the markdown element is a shadow-including
|
|
157
|
+
// descendant, so it cycles too, clears its own claims and re-offers a
|
|
158
|
+
// mount rather than an update. Clearing here would also make that next
|
|
159
|
+
// mount replace the consumer's list rather than extend it.
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export { createMarkdownPluginHostController, resolveMarkdownPluginHostMountDetail };
|
|
165
|
+
//# sourceMappingURL=plugin-host-container.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin-host-container.js","sources":["../../../../../src/components/markdown/src/utils/plugin-host-container.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\n/**\n * The container half of the plugin-host protocol.\n *\n * `<cds-aichat-markdown>` offers a host for plugin output to whichever chat\n * element is outermost, over three composed events — `-mount`, `-update` and\n * `-unmount`. Accepting the offer means calling `preventDefault()` on the\n * mount event and putting the host somewhere consumer-loaded CSS can reach it,\n * which the markdown element's own light DOM is not: it sits inside the chat's\n * shadow root. A plugin-fallback offer hands over an HTML string this\n * controller renders into a host it creates; a `customRenderers` offer hands\n * over a live element this controller only re-parents.\n *\n * A container supplies only the element hosts are appended to, and whatever\n * policy the framework cannot infer.\n */\n\n/**\n * Mount detail for plugin output the element hands over as an HTML string.\n */\nexport interface MarkdownPluginFallbackMountDetail {\n /** Marks the payload as an HTML string rather than a live element. */\n kind: 'pluginFallback';\n /**\n * Name to put on the host's `slot` attribute, and the key the matching\n * `-update` and `-unmount` events arrive under. Unique across every markdown\n * element on the page, and reused across renders while the token stays put,\n * so a streaming message rewrites one host instead of growing a new one per\n * chunk. Treat the value as opaque; its format is not part of the API.\n */\n slotName: string;\n /**\n * The plugin rule's rendered HTML, to assign to the host's `innerHTML`.\n *\n * DOMPurify runs over it only when the markdown element has `sanitize-html`\n * set, and that setting is off by default. `remove-html` does not stand in\n * for it either — that one escapes HTML written in the markdown source and\n * never filters what a plugin's renderer rule emits. Treat the string as\n * exactly as trustworthy as the markdown-it plugins the page registered.\n */\n html: string;\n /**\n * True when the plugin's token is inline, such as a `math_inline` span.\n * Picks the host tag — `span` when true, so the output stays in paragraph\n * flow, `div` when false — and gates the block spacing that matches the\n * markdown element's own stack gap.\n */\n isInline: boolean;\n}\n\n/**\n * Mount detail for a `customRenderers` host. It carries a live element the\n * markdown element created, keeps writing to across renders, and removes.\n * Claiming it means re-parenting that element into your own light DOM,\n * synchronously, and nothing else: never rewrite its content, never style it,\n * never remove it. The markdown element renders the `<slot>` hop that projects\n * it back.\n */\nexport interface MarkdownCustomRendererMountDetail {\n /** Marks the payload as a live element rather than an HTML string. */\n kind: 'customRenderer';\n /**\n * Name already set on `element`'s `slot` attribute, and the key the matching\n * `-unmount` event arrives under. Page-unique, reused across renders and\n * opaque, like the plugin-fallback name. No `-update` event follows this\n * one: the markdown element writes the consumer's node into `element`\n * itself.\n */\n slotName: string;\n /**\n * The host to re-parent. The markdown element created it, replaces its\n * children on every render, and removes it when the renderer stops matching\n * — a claimant only moves it.\n */\n element: HTMLElement;\n /**\n * True when the claimed output is inline flow content. Always `false` here:\n * the markdown element hosts every `customRenderers` result in a `<div>` it\n * created, so a claimant has no host tag to choose. Declared on both members\n * so a listener can read it before narrowing on `kind`.\n */\n isInline: boolean;\n}\n\n/**\n * The `cds-aichat-markdown-plugin-host-mount` detail, discriminated on `kind`.\n *\n * Narrow on `kind`, never on which of `html` / `element` is present — the two\n * members deliberately declare only their own fields, so reading the wrong one\n * is a compile error rather than a silent `undefined`.\n */\nexport type MarkdownPluginHostMountDetail =\n MarkdownPluginFallbackMountDetail | MarkdownCustomRendererMountDetail;\n\n/**\n * A mount detail as it arrives on the wire, `kind` included or not.\n *\n * `kind` is newer than the events themselves, and `@carbon/ai-chat` depends on\n * this package through a caret range, so a listener can still receive the\n * original shape from an older build. Pass anything you receive through\n * `resolveMarkdownPluginHostMountDetail`, exported from\n * `@carbon/ai-chat-components/es/components/markdown/src/utils/plugin-host-container.js`,\n * and narrow on the result.\n */\nexport type MarkdownPluginHostMountDetailInput =\n | MarkdownPluginHostMountDetail\n | Omit<MarkdownPluginFallbackMountDetail, 'kind'>\n | Omit<MarkdownCustomRendererMountDetail, 'kind'>;\n\n/**\n * Fills in `kind` for a detail emitted before the field existed.\n *\n * The one place the payload's shape is still consulted, and only when there is\n * nothing else to go on. Delete it once the floor on `@carbon/ai-chat-components`\n * rises past the release that added `kind`.\n */\nexport function resolveMarkdownPluginHostMountDetail(\n detail: MarkdownPluginHostMountDetailInput\n): MarkdownPluginHostMountDetail {\n if ('kind' in detail) {\n return detail;\n }\n return 'element' in detail\n ? { ...detail, kind: 'customRenderer' }\n : { ...detail, kind: 'pluginFallback' };\n}\n\nexport interface MarkdownPluginHostControllerOptions {\n /**\n * Called with a fresh array whenever the set of slot names this surface\n * should forward inward changes. Surfaces one shadow boundary from the\n * markdown element render no forwarder of their own and omit it — the React\n * `ChatContainer` is the one in this repo.\n *\n * Both kinds, and including names this surface declined to host: a container\n * nested inside an outer chat element still has to forward the slot the\n * outer one is hosting. The innermost hop — into the markdown element's own\n * shadow slot — is never one of these; the element mints that one, for\n * either kind, in the pass that read the claim.\n */\n onSlotNamesChange?: (slotNames: string[]) => void;\n\n /**\n * Return `true` to forward the slot without hosting it, because an outer\n * chat element will. Omitted by surfaces that are always outermost.\n */\n shouldDefer?: (event: Event) => boolean;\n}\n\nexport interface MarkdownPluginHostController {\n /** Subscribes to the three events. Safe to call again without disconnecting. */\n connect(): void;\n /**\n * Unsubscribes and removes the hosts this controller created. Relocated\n * `customRenderers` elements are left parented — they belong to the markdown\n * element, and as children of `target` they ride along with a DOM move.\n * Forwarded slot names survive too.\n */\n disconnect(): void;\n /**\n * Plugin-fallback hosts this controller created, keyed by slot name.\n * Relocated `customRenderers` elements are deliberately absent.\n */\n readonly hosts: ReadonlyMap<string, HTMLElement>;\n}\n\nconst MOUNT = 'cds-aichat-markdown-plugin-host-mount';\nconst UPDATE = 'cds-aichat-markdown-plugin-host-update';\nconst UNMOUNT = 'cds-aichat-markdown-plugin-host-unmount';\n\n/**\n * Answers the plugin-host offer on `target`'s behalf, hosting accepted offers\n * as slot-attributed children of `target`.\n *\n * `target` is both the listener and the host parent because in every chat\n * surface they are the same element — the offer is claimed by whichever chat\n * element is outermost, and that is the element whose light DOM is page DOM.\n *\n * Not part of this package's advertised surface: it is deliberately absent from\n * `components/markdown/index.ts`, where only the detail types above are\n * exported. It is not marked with the internal JSDoc tag either — this package\n * compiles with `stripInternal`, which would drop the declaration from the\n * emitted `.d.ts`, and every caller lives in the sibling package and resolves\n * its types through exactly that file. (Do not write that tag's name anywhere\n * in this comment: `stripInternal` matches the string, not just a real tag.)\n */\nexport function createMarkdownPluginHostController(\n target: HTMLElement,\n options: MarkdownPluginHostControllerOptions = {}\n): MarkdownPluginHostController {\n const { onSlotNamesChange, shouldDefer } = options;\n // Keyed by slot name alone: the markdown element namespaces every name it\n // mints per element (see `./slot-names.js`), so two messages rendering the\n // same markdown can't collide here. Only hosts this controller created —\n // a relocated `customRenderers` element is parented to `target` but never\n // entered here, which is what keeps `handleUpdate` from clobbering a\n // consumer's node and `disconnect()` from destroying one.\n const hosts = new Map<string, HTMLElement>();\n let slotNames: string[] = [];\n\n // Built once, not per `connect()`: a Lit `connectedCallback` can fire again\n // without an intervening disconnect, and fresh closures would register a\n // second time and handle every mount twice.\n const handleMount = (event: Event) => {\n const raw = (\n event as CustomEvent<MarkdownPluginHostMountDetailInput | undefined>\n ).detail;\n if (!raw?.slotName) {\n return;\n }\n const detail = resolveMarkdownPluginHostMountDetail(raw);\n\n // Track before deferring: a container nested inside an outer chat element\n // hosts nothing but still has to forward the slot inward.\n if (!slotNames.includes(detail.slotName)) {\n slotNames = [...slotNames, detail.slotName];\n onSlotNamesChange?.(slotNames);\n }\n if (shouldDefer?.(event)) {\n return;\n }\n\n event.preventDefault();\n if (detail.kind === 'customRenderer') {\n // A live node the markdown element created, keeps writing to and\n // removes: re-parent it and nothing else. No inline spacing — the stack\n // gap lives on the `<slot>` placeholder in the element's own shadow CSS,\n // and a style attribute here would outrank the page stylesheet this\n // relocation exists to admit.\n detail.element.setAttribute('slot', detail.slotName);\n // Re-appending a node already parented here detaches and reattaches the\n // consumer's whole subtree, running its disconnect/connect teardown.\n if (detail.element.parentElement !== target) {\n target.appendChild(detail.element);\n }\n return;\n }\n let host = hosts.get(detail.slotName);\n if (!host) {\n host = document.createElement(detail.isInline ? 'span' : 'div');\n host.setAttribute('slot', detail.slotName);\n // Match `.cds-aichat-markdown-stack > *:not(:first-child)` spacing;\n // shadow CSS doesn't reach a host in page light DOM, so apply it inline.\n // Inline output flows with text and gets no extra spacing.\n if (!detail.isInline) {\n host.style.marginBlockStart = '1rem';\n }\n hosts.set(detail.slotName, host);\n target.appendChild(host);\n }\n // `?? ''` here and in `handleUpdate`: `html` is typed `string`, but the\n // emitter can be a third-party element this compiler never saw, and\n // `innerHTML = undefined` writes the literal string \"undefined\".\n if (host.innerHTML !== (detail.html ?? '')) {\n host.innerHTML = detail.html ?? '';\n }\n };\n\n const handleUpdate = (event: Event) => {\n const detail = (\n event as CustomEvent<{ slotName: string; html: string } | undefined>\n ).detail;\n if (!detail?.slotName) {\n return;\n }\n const host = hosts.get(detail.slotName);\n if (host && host.innerHTML !== (detail.html ?? '')) {\n host.innerHTML = detail.html ?? '';\n }\n };\n\n const handleUnmount = (event: Event) => {\n const detail = (event as CustomEvent<{ slotName: string } | undefined>)\n .detail;\n if (!detail?.slotName) {\n return;\n }\n if (slotNames.includes(detail.slotName)) {\n slotNames = slotNames.filter((name) => name !== detail.slotName);\n onSlotNamesChange?.(slotNames);\n }\n const host = hosts.get(detail.slotName);\n if (host) {\n host.remove();\n hosts.delete(detail.slotName);\n }\n };\n\n return {\n hosts,\n connect() {\n target.addEventListener(MOUNT, handleMount);\n target.addEventListener(UPDATE, handleUpdate);\n target.addEventListener(UNMOUNT, handleUnmount);\n },\n disconnect() {\n target.removeEventListener(MOUNT, handleMount);\n target.removeEventListener(UPDATE, handleUpdate);\n target.removeEventListener(UNMOUNT, handleUnmount);\n for (const host of hosts.values()) {\n host.remove();\n }\n hosts.clear();\n // Slot names deliberately survive. `handleUpdate` drops an update whose\n // host is missing, so retention would strand a slot if only this element\n // cycled — it is safe because the markdown element is a shadow-including\n // descendant, so it cycles too, clears its own claims and re-offers a\n // mount rather than an update. Clearing here would also make that next\n // mount replace the consumer's list rather than extend it.\n },\n };\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AA8GH;;;;;;AAMG;AACG,SAAU,oCAAoC,CAClD,MAA0C,EAAA;AAE1C,IAAA,IAAI,MAAM,IAAI,MAAM,EAAE;AACpB,QAAA,OAAO,MAAM;IACf;IACA,OAAO,SAAS,IAAI;UAChB,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,gBAAgB;UACnC,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,gBAAgB,EAAE;AAC3C;AAyCA,MAAM,KAAK,GAAG,uCAAuC;AACrD,MAAM,MAAM,GAAG,wCAAwC;AACvD,MAAM,OAAO,GAAG,yCAAyC;AAEzD;;;;;;;;;;;;;;;AAeG;SACa,kCAAkC,CAChD,MAAmB,EACnB,UAA+C,EAAE,EAAA;AAEjD,IAAA,MAAM,EAAE,iBAAiB,EAAE,WAAW,EAAE,GAAG,OAAO;;;;;;;AAOlD,IAAA,MAAM,KAAK,GAAG,IAAI,GAAG,EAAuB;IAC5C,IAAI,SAAS,GAAa,EAAE;;;;AAK5B,IAAA,MAAM,WAAW,GAAG,CAAC,KAAY,KAAI;AACnC,QAAA,MAAM,GAAG,GACP,KACD,CAAC,MAAM;AACR,QAAA,IAAI,CAAC,GAAG,EAAE,QAAQ,EAAE;YAClB;QACF;AACA,QAAA,MAAM,MAAM,GAAG,oCAAoC,CAAC,GAAG,CAAC;;;QAIxD,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE;YACxC,SAAS,GAAG,CAAC,GAAG,SAAS,EAAE,MAAM,CAAC,QAAQ,CAAC;AAC3C,YAAA,iBAAiB,GAAG,SAAS,CAAC;QAChC;AACA,QAAA,IAAI,WAAW,GAAG,KA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IAAI,KAAK,CAAC,MAAM,EAAE,EAAE;gBACjC,IAAI,CAAC,MAAM,EAAE;YACf;YACA,KAAK,CAAC,KAAK,EAAE;;;;;;;QAOf,CAAC;KACF;AACH;;"}
|
|
@@ -10,8 +10,18 @@ export declare const DEFAULT_PAGINATION_STATUS_TEXT: ({ start, end, count, }: {
|
|
|
10
10
|
end: number;
|
|
11
11
|
count: number;
|
|
12
12
|
}) => string;
|
|
13
|
+
/**
|
|
14
|
+
* One cell of a parsed markdown table. A custom table renderer reads these
|
|
15
|
+
* from the `headers` and `rows` it is handed.
|
|
16
|
+
*/
|
|
13
17
|
export interface TableCellData {
|
|
18
|
+
/** Plain text of the cell, with markdown syntax stripped. */
|
|
14
19
|
text: string;
|
|
20
|
+
/**
|
|
21
|
+
* Token tree for the cell's content, or `null` when the cell is plain
|
|
22
|
+
* text. Render it to keep the links, code spans, and emphasis that `text`
|
|
23
|
+
* drops.
|
|
24
|
+
*/
|
|
15
25
|
tokens: TokenTree[] | null;
|
|
16
26
|
}
|
|
17
27
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-helpers.js","sources":["../../../../../src/components/markdown/src/utils/table-helpers.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\nimport { html, TemplateResult } from 'lit';\nimport { repeat } from 'lit/directives/repeat.js';\nimport type { Token } from 'markdown-it';\n\nimport type {\n TableCellContent,\n TableRowContent,\n} from '../../../table/src/table.js';\nimport { combineConsecutiveHtmlInline } from './html-helpers.js';\nimport { isTableAtStreamingTail } from './streaming-table.js';\nimport type { RenderTokenTreeOptions } from '../markdown-renderer-types.js';\nimport type { TokenTree } from '../markdown-token-tree';\n\n// Default localization functions for table pagination\nexport const DEFAULT_PAGINATION_SUPPLEMENTAL_TEXT = ({\n count,\n}: {\n count: number;\n}) => `${count} items`;\nexport const DEFAULT_PAGINATION_STATUS_TEXT = ({\n start,\n end,\n count,\n}: {\n start: number;\n end: number;\n count: number;\n}) => `${start}–${end} of ${count} items`;\n\nexport interface TableCellData {\n text: string;\n tokens: TokenTree[] | null;\n}\n\n/**\n * Extracts tabular data from a table TokenTree node.\n *\n * Converts the hierarchical markdown table structure into the flat\n * header/rows format expected by the cds-aichat-table component while retaining\n * the TokenTree children required for rich rendering within cells.\n */\nexport function extractTableData(tableNode: TokenTree): {\n headers: TableCellData[];\n rows: TableCellData[][];\n} {\n const headers: TableCellData[] = [];\n const rows: TableCellData[][] = [];\n\n for (const child of tableNode.children) {\n if (child.token.tag === 'thead') {\n // Extract column headers\n for (const theadChild of child.children) {\n if (theadChild.token.tag === 'tr') {\n for (const thChild of theadChild.children) {\n if (thChild.token.tag === 'th') {\n headers.push(extractCellData(thChild));\n }\n }\n }\n }\n } else if (child.token.tag === 'tbody') {\n // Extract data rows\n for (const tbodyChild of child.children) {\n if (tbodyChild.token.tag === 'tr') {\n const row: TableCellData[] = [];\n for (const tdChild of tbodyChild.children) {\n if (tdChild.token.tag === 'td') {\n row.push(extractCellData(tdChild));\n }\n }\n rows.push(row);\n }\n }\n }\n }\n\n return { headers, rows };\n}\n\n/**\n * Recursively extracts plain text content from a TokenTree node.\n *\n * This is used for table cells and other contexts where we need the\n * text content without HTML formatting.\n */\nexport function extractTextContent(node: TokenTree): string {\n // Handle direct text tokens\n if (node.token.type === 'text') {\n return node.token.content || '';\n }\n\n // Handle inline code\n if (node.token.type === 'code_inline') {\n return node.token.content || '';\n }\n\n if (node.token.type === 'softbreak' || node.token.type === 'hardbreak') {\n return '\\n';\n }\n\n // Recursively extract text from child nodes\n let text = '';\n for (const child of node.children) {\n text += extractTextContent(child);\n }\n\n return text;\n}\n\nfunction extractCellData(node: TokenTree): TableCellData {\n const text = extractTextContent(node);\n const tokens = extractRenderableChildren(node);\n const hasRichContent = tokens.some((child) => child.token.type !== 'text');\n\n return {\n text,\n tokens: hasRichContent ? tokens : null,\n };\n}\n\nfunction extractRenderableChildren(node: TokenTree): TokenTree[] {\n if (node.children.length === 1) {\n const onlyChild = node.children[0];\n if (\n onlyChild.token.type === 'inline' &&\n onlyChild.children &&\n onlyChild.children.length\n ) {\n return onlyChild.children;\n }\n }\n\n return node.children;\n}\n\n/**\n * Renders the body of the `case \"table\"` branch of `renderWithStaticTag`.\n *\n * Lives outside the renderer's switch because it covers three flows: streaming\n * loading state, default Carbon-table rendering, and the `customRenderers.table`\n * slot override.\n *\n * `renderToken` is the recursive renderer the caller dispatched from, passed in\n * to avoid a cycle with `markdown-renderer.ts`. `slotName` is non-undefined when\n * the consumer registered a `table` custom renderer, in which case the result is\n * wrapped in a named `<slot>` and an override descriptor is reported via\n * `recordCustomRender`.\n */\nexport function renderTable(\n token: Token,\n node: TokenTree,\n attrs: Record<string, string>,\n options: RenderTokenTreeOptions,\n renderToken: (\n node: TokenTree,\n options: RenderTokenTreeOptions\n ) => TemplateResult,\n slotName: string | undefined\n): TemplateResult {\n const {\n streaming,\n forceTableLoading,\n context: parentContext,\n tableFilterPlaceholderText,\n tablePreviousPageText,\n tableNextPageText,\n tableItemsPerPageText,\n tableDownloadLabelText,\n tableLocale,\n tableGetPaginationSupplementalText,\n tableGetPaginationStatusText,\n } = options;\n\n // Determine if we should show loading state during streaming\n let isLoading = Boolean(forceTableLoading);\n if (\n !isLoading &&\n streaming &&\n parentContext?.parentChildren &&\n parentContext?.currentIndex !== undefined\n ) {\n isLoading = isTableAtStreamingTail(\n parentContext.parentChildren,\n parentContext.currentIndex\n );\n }\n\n const renderCellTokens = (tokens: TokenTree[], contextOverrides = {}) => {\n // Same as block/inline rendering: merge split raw HTML (e.g. `<a>…</a>`)\n // so each cell is not rendered as separate unsafeHTML + text chunks.\n const normalizedTokens = combineConsecutiveHtmlInline(tokens);\n return html`${repeat(\n normalizedTokens,\n (child, index) => `cell-${index}:${child.token.type}:${child.token.tag}`,\n (child, index) =>\n renderToken(child, {\n ...options,\n context: {\n ...options.context,\n ...contextOverrides,\n parentChildren: normalizedTokens,\n currentIndex: index,\n },\n })\n )}`;\n };\n\n const createCellContent = (\n cell: TableCellData,\n contextOverrides?: Record<string, unknown>\n ): TableCellContent => ({\n text: cell.text,\n template: cell.tokens\n ? renderCellTokens(cell.tokens, contextOverrides)\n : null,\n });\n\n // Only extract and process table data when not loading to avoid unnecessary work.\n // During loading, the table shows a skeleton and doesn't need the actual data.\n let headers: TableCellContent[] = [];\n let tableRows: TableRowContent[] = [];\n\n if (!isLoading) {\n const extractedData = extractTableData(node);\n headers = extractedData.headers.map((cell) =>\n createCellContent(cell, { isInThead: true })\n );\n tableRows = extractedData.rows.map((row) => ({\n cells: row.map((cell) => createCellContent(cell)),\n }));\n }\n\n // Always return the same structure to allow Lit to reuse the table element.\n // When isLoading is true, the table component will show a skeleton state.\n // When isLoading is false, it will show the actual data.\n // This prevents recreating the table element and preserves its internal state.\n const defaultTableTemplate = html`<div class=\"cds-aichat-table--square\">\n <cds-aichat-table\n data-rounded\n .headers=${headers}\n .rows=${tableRows}\n .loading=${isLoading}\n .filterPlaceholderText=${tableFilterPlaceholderText}\n .previousPageText=${tablePreviousPageText}\n .nextPageText=${tableNextPageText}\n .itemsPerPageText=${tableItemsPerPageText}\n .downloadLabelText=${tableDownloadLabelText}\n .locale=${tableLocale}\n .getPaginationSupplementalText=${tableGetPaginationSupplementalText}\n .getPaginationStatusText=${tableGetPaginationStatusText}\n ...=${attrs}></cds-aichat-table>\n </div>`;\n\n if (slotName !== undefined) {\n // For the override path we pass the raw extracted cell data (not the\n // Lit-wrapped TableCellContent) so consumers can render however they\n // like. Extract once even when loading so the consumer always gets\n // the data — they can read `isLoading` to choose a skeleton state.\n const { headers: dataHeaders, rows: dataRows } = extractTableData(node);\n options.recordCustomRender?.({\n slotName,\n kind: 'table',\n token,\n data: {\n headers: dataHeaders,\n rows: dataRows,\n isStreaming: !!streaming,\n isLoading,\n },\n });\n return html`<slot name=${slotName}>${defaultTableTemplate}</slot>`;\n }\n\n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P,IAAA,IAAI,QAAQ,KAAK,SAAS,EAAE;;;;;AAK1B,QAAA,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC;QACvE,OAAO,CAAC,kBAAkB,GAAG;YAC3B,QAAQ;AACR,YAAA,IAAI,EAAE,OAAO;YACb,KAAK;AACL,YAAA,IAAI,EAAE;AACJ,gBAAA,OAAO,EAAE,WAAW;AACpB,gBAAA,IAAI,EAAE,QAAQ;gBACd,WAAW,EAAE,CAAC,CAAC,SAAS;gBACxB,SAAS;AACV,aAAA;AACF,SAAA,CAAC;AACF,QAAA,OAAO,IAAI,CAAA,CAAA,WAAA,EAAc,QAAQ,CAAA,CAAA,EAAI,oBAAoB,SAAS;IACpE;AAEA,IAAA,OAAO,oBAAoB;AAC7B;;"}
|
|
1
|
+
{"version":3,"file":"table-helpers.js","sources":["../../../../../src/components/markdown/src/utils/table-helpers.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\nimport { html, TemplateResult } from 'lit';\nimport { repeat } from 'lit/directives/repeat.js';\nimport type { Token } from 'markdown-it';\n\nimport type {\n TableCellContent,\n TableRowContent,\n} from '../../../table/src/table.js';\nimport { combineConsecutiveHtmlInline } from './html-helpers.js';\nimport { isTableAtStreamingTail } from './streaming-table.js';\nimport type { RenderTokenTreeOptions } from '../markdown-renderer-types.js';\nimport type { TokenTree } from '../markdown-token-tree';\n\n// Default localization functions for table pagination\nexport const DEFAULT_PAGINATION_SUPPLEMENTAL_TEXT = ({\n count,\n}: {\n count: number;\n}) => `${count} items`;\nexport const DEFAULT_PAGINATION_STATUS_TEXT = ({\n start,\n end,\n count,\n}: {\n start: number;\n end: number;\n count: number;\n}) => `${start}–${end} of ${count} items`;\n\n/**\n * One cell of a parsed markdown table. A custom table renderer reads these\n * from the `headers` and `rows` it is handed.\n */\nexport interface TableCellData {\n /** Plain text of the cell, with markdown syntax stripped. */\n text: string;\n /**\n * Token tree for the cell's content, or `null` when the cell is plain\n * text. Render it to keep the links, code spans, and emphasis that `text`\n * drops.\n */\n tokens: TokenTree[] | null;\n}\n\n/**\n * Extracts tabular data from a table TokenTree node.\n *\n * Converts the hierarchical markdown table structure into the flat\n * header/rows format expected by the cds-aichat-table component while retaining\n * the TokenTree children required for rich rendering within cells.\n */\nexport function extractTableData(tableNode: TokenTree): {\n headers: TableCellData[];\n rows: TableCellData[][];\n} {\n const headers: TableCellData[] = [];\n const rows: TableCellData[][] = [];\n\n for (const child of tableNode.children) {\n if (child.token.tag === 'thead') {\n // Extract column headers\n for (const theadChild of child.children) {\n if (theadChild.token.tag === 'tr') {\n for (const thChild of theadChild.children) {\n if (thChild.token.tag === 'th') {\n headers.push(extractCellData(thChild));\n }\n }\n }\n }\n } else if (child.token.tag === 'tbody') {\n // Extract data rows\n for (const tbodyChild of child.children) {\n if (tbodyChild.token.tag === 'tr') {\n const row: TableCellData[] = [];\n for (const tdChild of tbodyChild.children) {\n if (tdChild.token.tag === 'td') {\n row.push(extractCellData(tdChild));\n }\n }\n rows.push(row);\n }\n }\n }\n }\n\n return { headers, rows };\n}\n\n/**\n * Recursively extracts plain text content from a TokenTree node.\n *\n * This is used for table cells and other contexts where we need the\n * text content without HTML formatting.\n */\nexport function extractTextContent(node: TokenTree): string {\n // Handle direct text tokens\n if (node.token.type === 'text') {\n return node.token.content || '';\n }\n\n // Handle inline code\n if (node.token.type === 'code_inline') {\n return node.token.content || '';\n }\n\n if (node.token.type === 'softbreak' || node.token.type === 'hardbreak') {\n return '\\n';\n }\n\n // Recursively extract text from child nodes\n let text = '';\n for (const child of node.children) {\n text += extractTextContent(child);\n }\n\n return text;\n}\n\nfunction extractCellData(node: TokenTree): TableCellData {\n const text = extractTextContent(node);\n const tokens = extractRenderableChildren(node);\n const hasRichContent = tokens.some((child) => child.token.type !== 'text');\n\n return {\n text,\n tokens: hasRichContent ? tokens : null,\n };\n}\n\nfunction extractRenderableChildren(node: TokenTree): TokenTree[] {\n if (node.children.length === 1) {\n const onlyChild = node.children[0];\n if (\n onlyChild.token.type === 'inline' &&\n onlyChild.children &&\n onlyChild.children.length\n ) {\n return onlyChild.children;\n }\n }\n\n return node.children;\n}\n\n/**\n * Renders the body of the `case \"table\"` branch of `renderWithStaticTag`.\n *\n * Lives outside the renderer's switch because it covers three flows: streaming\n * loading state, default Carbon-table rendering, and the `customRenderers.table`\n * slot override.\n *\n * `renderToken` is the recursive renderer the caller dispatched from, passed in\n * to avoid a cycle with `markdown-renderer.ts`. `slotName` is non-undefined when\n * the consumer registered a `table` custom renderer, in which case the result is\n * wrapped in a named `<slot>` and an override descriptor is reported via\n * `recordCustomRender`.\n */\nexport function renderTable(\n token: Token,\n node: TokenTree,\n attrs: Record<string, string>,\n options: RenderTokenTreeOptions,\n renderToken: (\n node: TokenTree,\n options: RenderTokenTreeOptions\n ) => TemplateResult,\n slotName: string | undefined\n): TemplateResult {\n const {\n streaming,\n forceTableLoading,\n context: parentContext,\n tableFilterPlaceholderText,\n tablePreviousPageText,\n tableNextPageText,\n tableItemsPerPageText,\n tableDownloadLabelText,\n tableLocale,\n tableGetPaginationSupplementalText,\n tableGetPaginationStatusText,\n } = options;\n\n // Determine if we should show loading state during streaming\n let isLoading = Boolean(forceTableLoading);\n if (\n !isLoading &&\n streaming &&\n parentContext?.parentChildren &&\n parentContext?.currentIndex !== undefined\n ) {\n isLoading = isTableAtStreamingTail(\n parentContext.parentChildren,\n parentContext.currentIndex\n );\n }\n\n const renderCellTokens = (tokens: TokenTree[], contextOverrides = {}) => {\n // Same as block/inline rendering: merge split raw HTML (e.g. `<a>…</a>`)\n // so each cell is not rendered as separate unsafeHTML + text chunks.\n const normalizedTokens = combineConsecutiveHtmlInline(tokens);\n return html`${repeat(\n normalizedTokens,\n (child, index) => `cell-${index}:${child.token.type}:${child.token.tag}`,\n (child, index) =>\n renderToken(child, {\n ...options,\n context: {\n ...options.context,\n ...contextOverrides,\n parentChildren: normalizedTokens,\n currentIndex: index,\n },\n })\n )}`;\n };\n\n const createCellContent = (\n cell: TableCellData,\n contextOverrides?: Record<string, unknown>\n ): TableCellContent => ({\n text: cell.text,\n template: cell.tokens\n ? renderCellTokens(cell.tokens, contextOverrides)\n : null,\n });\n\n // Only extract and process table data when not loading to avoid unnecessary work.\n // During loading, the table shows a skeleton and doesn't need the actual data.\n let headers: TableCellContent[] = [];\n let tableRows: TableRowContent[] = [];\n\n if (!isLoading) {\n const extractedData = extractTableData(node);\n headers = extractedData.headers.map((cell) =>\n createCellContent(cell, { isInThead: true })\n );\n tableRows = extractedData.rows.map((row) => ({\n cells: row.map((cell) => createCellContent(cell)),\n }));\n }\n\n // Always return the same structure to allow Lit to reuse the table element.\n // When isLoading is true, the table component will show a skeleton state.\n // When isLoading is false, it will show the actual data.\n // This prevents recreating the table element and preserves its internal state.\n const defaultTableTemplate = html`<div class=\"cds-aichat-table--square\">\n <cds-aichat-table\n data-rounded\n .headers=${headers}\n .rows=${tableRows}\n .loading=${isLoading}\n .filterPlaceholderText=${tableFilterPlaceholderText}\n .previousPageText=${tablePreviousPageText}\n .nextPageText=${tableNextPageText}\n .itemsPerPageText=${tableItemsPerPageText}\n .downloadLabelText=${tableDownloadLabelText}\n .locale=${tableLocale}\n .getPaginationSupplementalText=${tableGetPaginationSupplementalText}\n .getPaginationStatusText=${tableGetPaginationStatusText}\n ...=${attrs}></cds-aichat-table>\n </div>`;\n\n if (slotName !== undefined) {\n // For the override path we pass the raw extracted cell data (not the\n // Lit-wrapped TableCellContent) so consumers can render however they\n // like. Extract once even when loading so the consumer always gets\n // the data — they can read `isLoading` to choose a skeleton state.\n const { headers: dataHeaders, rows: dataRows } = extractTableData(node);\n options.recordCustomRender?.({\n slotName,\n kind: 'table',\n token,\n data: {\n headers: dataHeaders,\n rows: dataRows,\n isStreaming: !!streaming,\n isLoading,\n },\n });\n return html`<slot name=${slot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BAA4B;YACjD,KAAK,CAAA;SACR;AAEP,IAAA,IAAI,QAAQ,KAAK,SAAS,EAAE;;;;;AAK1B,QAAA,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC;QACvE,OAAO,CAAC,kBAAkB,GAAG;YAC3B,QAAQ;AACR,YAAA,IAAI,EAAE,OAAO;YACb,KAAK;AACL,YAAA,IAAI,EAAE;AACJ,gBAAA,OAAO,EAAE,WAAW;AACpB,gBAAA,IAAI,EAAE,QAAQ;gBACd,WAAW,EAAE,CAAC,CAAC,SAAS;gBACxB,SAAS;AACV,aAAA;AACF,SAAA,CAAC;AACF,QAAA,OAAO,IAAI,CAAA,CAAA,WAAA,EAAc,QAAQ,CAAA,CAAA,EAAI,oBAAoB,SAAS;IACpE;AAEA,IAAA,OAAO,oBAAoB;AAC7B;;"}
|
|
@@ -21,10 +21,27 @@
|
|
|
21
21
|
*/
|
|
22
22
|
import type { Extension } from '@tiptap/core';
|
|
23
23
|
import type { AutocompleteConfig, StartersConfig, TriggerSuggestionConfig } from './types.js';
|
|
24
|
+
/**
|
|
25
|
+
* The input configs {@link buildCarbonExtensions} turns into Tiptap
|
|
26
|
+
* extensions.
|
|
27
|
+
* Leave a field out to leave its extension out.
|
|
28
|
+
*/
|
|
24
29
|
export interface BuildCarbonExtensionsConfig {
|
|
30
|
+
/** Config for the `@`-style mention picker. Builds {@link carbonMention}. */
|
|
25
31
|
mention?: TriggerSuggestionConfig;
|
|
32
|
+
/** Config for the `/`-style command picker. Builds {@link carbonCommand}. */
|
|
26
33
|
command?: TriggerSuggestionConfig;
|
|
34
|
+
/**
|
|
35
|
+
* Config for live autocomplete. Builds {@link carbonAutocomplete}, set to
|
|
36
|
+
* stand down for whichever mention and command triggers you also pass.
|
|
37
|
+
*/
|
|
27
38
|
autocomplete?: AutocompleteConfig;
|
|
39
|
+
/**
|
|
40
|
+
* Config for the starter prompts shown while the editor is empty and
|
|
41
|
+
* focused. Builds {@link carbonStarterTrigger}. An empty `items` list still
|
|
42
|
+
* installs the extension, so you can fill the list later without
|
|
43
|
+
* recreating the editor.
|
|
44
|
+
*/
|
|
28
45
|
starters?: StartersConfig;
|
|
29
46
|
}
|
|
30
47
|
export declare function buildCarbonExtensions(configs: BuildCarbonExtensionsConfig): Extension[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-extensions.js","sources":["../../../../../src/components/prompt-line/src/tiptap/build-extensions.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Pure helper: translate the chat-domain configs surfaced on\n * `<cds-aichat-prompt-line-shell>` (and `InputConfig`) into a curated Tiptap\n * extension list. Used by the shell's render logic and exposed publicly so\n * direct `<cds-aichat-prompt-line>` consumers can call the same builder\n * without bringing the chrome along.\n *\n * Filters out `undefined` / empty configs so the returned list contains\n * exactly the extensions whose backing config was supplied. Enter-to-send is\n * **not** included here — `<cds-aichat-prompt-line>` bakes `carbonChatEnter`\n * into its own base bundle, so both the textarea and rich surfaces send on\n * Enter without this builder.\n */\n\nimport type { Extension } from '@tiptap/core';\n\nimport {\n carbonAutocomplete,\n type ExcludedTrigger,\n} from './carbon-autocomplete.js';\nimport { carbonCommand, carbonMention } from './carbon-mention.js';\nimport { carbonStarterTrigger } from './carbon-starter-trigger.js';\nimport { tagExtensionSource } from './extension-equivalence.js';\nimport type {\n AutocompleteConfig,\n StartersConfig,\n TriggerSuggestionConfig,\n} from './types.js';\n\nexport interface BuildCarbonExtensionsConfig {\n mention?: TriggerSuggestionConfig;\n command?: TriggerSuggestionConfig;\n autocomplete?: AutocompleteConfig;\n starters?: StartersConfig;\n}\n\nexport function buildCarbonExtensions(\n configs: BuildCarbonExtensionsConfig\n): Extension[] {\n // Each entry is tagged with the config it was built from so the rich runtime\n // can tell a genuinely different extension set from a rebuilt-but-identical\n // one without recreating the editor. See ./extension-equivalence.ts.\n const out: Extension[] = [];\n if (configs.mention) {\n out.push(\n tagExtensionSource(\n carbonMention(configs.mention) as unknown as Extension,\n {\n kind: 'mention',\n config: configs.mention,\n }\n )\n );\n }\n if (configs.command) {\n out.push(\n tagExtensionSource(\n carbonCommand(configs.command) as unknown as Extension,\n {\n kind: 'command',\n config: configs.command,\n }\n )\n );\n }\n if (configs.autocomplete) {\n const excludeTriggers: ExcludedTrigger[] = [];\n if (configs.mention) {\n excludeTriggers.push({\n char: configs.mention.trigger,\n position:\n configs.mention.triggerPosition === 'start' ? 'start' : 'anywhere',\n });\n }\n if (configs.command) {\n excludeTriggers.push({\n char: configs.command.trigger,\n position:\n configs.command.triggerPosition === 'start' ? 'start' : 'anywhere',\n });\n }\n out.push(\n tagExtensionSource(\n carbonAutocomplete(configs.autocomplete, excludeTriggers),\n {\n kind: 'autocomplete',\n config: configs.autocomplete,\n }\n )\n );\n }\n // Installed whenever `starters` is configured, empty list included: it is how\n // `items`/`isOn` reach the live editor, and omitting it for an empty list\n // shortens the set, which the equivalence check rejects — recreating the\n // editor and dropping its undo history. `maybeEmit` stays silent when empty.\n if (configs.starters) {\n out.push(\n tagExtensionSource(\n carbonStarterTrigger(configs.starters.items, configs.starters.isOn),\n { kind: 'starters', config: configs.starters }\n )\n );\n }\n return out;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;
|
|
1
|
+
{"version":3,"file":"build-extensions.js","sources":["../../../../../src/components/prompt-line/src/tiptap/build-extensions.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Pure helper: translate the chat-domain configs surfaced on\n * `<cds-aichat-prompt-line-shell>` (and `InputConfig`) into a curated Tiptap\n * extension list. Used by the shell's render logic and exposed publicly so\n * direct `<cds-aichat-prompt-line>` consumers can call the same builder\n * without bringing the chrome along.\n *\n * Filters out `undefined` / empty configs so the returned list contains\n * exactly the extensions whose backing config was supplied. Enter-to-send is\n * **not** included here — `<cds-aichat-prompt-line>` bakes `carbonChatEnter`\n * into its own base bundle, so both the textarea and rich surfaces send on\n * Enter without this builder.\n */\n\nimport type { Extension } from '@tiptap/core';\n\nimport {\n carbonAutocomplete,\n type ExcludedTrigger,\n} from './carbon-autocomplete.js';\nimport { carbonCommand, carbonMention } from './carbon-mention.js';\nimport { carbonStarterTrigger } from './carbon-starter-trigger.js';\nimport { tagExtensionSource } from './extension-equivalence.js';\nimport type {\n AutocompleteConfig,\n StartersConfig,\n TriggerSuggestionConfig,\n} from './types.js';\n\n/**\n * The input configs {@link buildCarbonExtensions} turns into Tiptap\n * extensions.\n * Leave a field out to leave its extension out.\n */\nexport interface BuildCarbonExtensionsConfig {\n /** Config for the `@`-style mention picker. Builds {@link carbonMention}. */\n mention?: TriggerSuggestionConfig;\n /** Config for the `/`-style command picker. Builds {@link carbonCommand}. */\n command?: TriggerSuggestionConfig;\n /**\n * Config for live autocomplete. Builds {@link carbonAutocomplete}, set to\n * stand down for whichever mention and command triggers you also pass.\n */\n autocomplete?: AutocompleteConfig;\n /**\n * Config for the starter prompts shown while the editor is empty and\n * focused. Builds {@link carbonStarterTrigger}. An empty `items` list still\n * installs the extension, so you can fill the list later without\n * recreating the editor.\n */\n starters?: StartersConfig;\n}\n\nexport function buildCarbonExtensions(\n configs: BuildCarbonExtensionsConfig\n): Extension[] {\n // Each entry is tagged with the config it was built from so the rich runtime\n // can tell a genuinely different extension set from a rebuilt-but-identical\n // one without recreating the editor. See ./extension-equivalence.ts.\n const out: Extension[] = [];\n if (configs.mention) {\n out.push(\n tagExtensionSource(\n carbonMention(configs.mention) as unknown as Extension,\n {\n kind: 'mention',\n config: configs.mention,\n }\n )\n );\n }\n if (configs.command) {\n out.push(\n tagExtensionSource(\n carbonCommand(configs.command) as unknown as Extension,\n {\n kind: 'command',\n config: configs.command,\n }\n )\n );\n }\n if (configs.autocomplete) {\n const excludeTriggers: ExcludedTrigger[] = [];\n if (configs.mention) {\n excludeTriggers.push({\n char: configs.mention.trigger,\n position:\n configs.mention.triggerPosition === 'start' ? 'start' : 'anywhere',\n });\n }\n if (configs.command) {\n excludeTriggers.push({\n char: configs.command.trigger,\n position:\n configs.command.triggerPosition === 'start' ? 'start' : 'anywhere',\n });\n }\n out.push(\n tagExtensionSource(\n carbonAutocomplete(configs.autocomplete, excludeTriggers),\n {\n kind: 'autocomplete',\n config: configs.autocomplete,\n }\n )\n );\n }\n // Installed whenever `starters` is configured, empty list included: it is how\n // `items`/`isOn` reach the live editor, and omitting it for an empty list\n // shortens the set, which the equivalence check rejects — recreating the\n // editor and dropping its undo history. `maybeEmit` stays silent when empty.\n if (configs.starters) {\n out.push(\n tagExtensionSource(\n carbonStarterTrigger(configs.starters.items, configs.starters.isOn),\n { kind: 'starters', config: configs.starters }\n )\n );\n }\n return out;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;AAOG;AAuDG,SAAU,qBAAqB,CACnC,OAAoC,EAAA;;;;IAKpC,MAAM,GAAG,GAAgB,EAAE;AAC3B,IAAA,IAAI,OAAO,CAAC,OAAO,EAAE;QACnB,GAAG,CAAC,IAAI,CACN,kBAAkB,CAChB,aAAa,CAAC,OAAO,CAAC,OAAO,CAAyB,EACtD;AACE,YAAA,IAAI,EAAE,SAAS;YACf,MAAM,EAAE,OAAO,CAAC,OAAO;AACxB,SAAA,CACF,CACF;IACH;AACA,IAAA,IAAI,OAAO,CAAC,OAAO,EAAE;QACnB,GAAG,CAAC,IAAI,CACN,kBAAkB,CAChB,aAAa,CAAC,OAAO,CAAC,OAAO,CAAyB,EACtD;AACE,YAAA,IAAI,EAAE,SAAS;YACf,MAAM,EAAE,OAAO,CAAC,OAAO;AACxB,SAAA,CACF,CACF;IACH;AACA,IAAA,IAAI,OAAO,CAAC,YAAY,EAAE;QACxB,MAAM,eAAe,GAAsB,EAAE;AAC7C,QAAA,IAAI,OAAO,CAAC,OAAO,EAAE;YACnB,eAAe,CAAC,IAAI,CAAC;AACnB,gBAAA,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,OAAO;AAC7B,gBAAA,QAAQ,EACN,OAAO,CAAC,OAAO,CAAC,eAAe,KAAK,OAAO,GAAG,OAAO,GAAG,UAAU;AACrE,aAAA,CAAC;QACJ;AACA,QAAA,IAAI,OAAO,CAAC,OAAO,EAAE;YACnB,eAAe,CAAC,IAAI,CAAC;AACnB,gBAAA,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,OAAO;AAC7B,gBAAA,QAAQ,EACN,OAAO,CAAC,OAAO,CAAC,eAAe,KAAK,OAAO,GAAG,OAAO,GAAG,UAAU;AACrE,aAAA,CAAC;QACJ;AACA,QAAA,GAAG,CAAC,IAAI,CACN,kBAAkB,CAChB,kBAAkB,CAAC,OAAO,CAAC,YAAY,EAAE,eAAe,CAAC,EACzD;AACE,YAAA,IAAI,EAAE,cAAc;YACpB,MAAM,EAAE,OAAO,CAAC,YAAY;AAC7B,SAAA,CACF,CACF;IACH;;;;;AAKA,IAAA,IAAI,OAAO,CAAC,QAAQ,EAAE;AACpB,QAAA,GAAG,CAAC,IAAI,CACN,kBAAkB,CAChB,oBAAoB,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EACnE,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,QAAQ,EAAE,CAC/C,CACF;IACH;AACA,IAAA,OAAO,GAAG;AACZ;;"}
|
|
@@ -18,8 +18,20 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { Extension } from '@tiptap/core';
|
|
20
20
|
import type { AutocompleteConfig } from './types.js';
|
|
21
|
+
/**
|
|
22
|
+
* A trigger character that autocomplete stands down for, so a co-installed
|
|
23
|
+
* mention or command picker wins while its trigger is active. Pass a list of
|
|
24
|
+
* these as the second argument to {@link carbonAutocomplete}.
|
|
25
|
+
*/
|
|
21
26
|
export interface ExcludedTrigger {
|
|
27
|
+
/** The character to stand down for, such as `"@"` or `"/"`. */
|
|
22
28
|
char: string;
|
|
29
|
+
/**
|
|
30
|
+
* Where that character has to sit. `"anywhere"` stands down for any word
|
|
31
|
+
* starting with it; `"start"` stands down only when that word starts the
|
|
32
|
+
* line. Mirrors the picker's own
|
|
33
|
+
* {@link TriggerSuggestionConfig.triggerPosition}.
|
|
34
|
+
*/
|
|
23
35
|
position: 'anywhere' | 'start';
|
|
24
36
|
}
|
|
25
37
|
export declare function carbonAutocomplete(config: AutocompleteConfig, excludeTriggers?: ExcludedTrigger[]): Extension;
|
|
@@ -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-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-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) =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ggestionConfig } 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.
|