@vettvangur/ai-sdk 0.1.13 → 0.2.1
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/README.md +78 -3
- package/dist/index.d.ts +122 -10
- package/dist/index.js +382 -79
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,12 +3,20 @@
|
|
|
3
3
|
Framework-agnostic, unstyled AI chat primitives for server-rendered shells.
|
|
4
4
|
|
|
5
5
|
It exports protocol-v1 contracts, parsing and SSE stream-reading primitives, a headless chat session,
|
|
6
|
-
|
|
6
|
+
a DOM binding for a server-rendered shell, and generic cards a host can draw tool results with. It
|
|
7
|
+
ships no styles: every element it renders carries a BEM class, and the project styles those.
|
|
7
8
|
|
|
8
9
|
```html
|
|
9
10
|
<section data-ai-chat data-ai-chat-endpoint="/webapi/aichat/stream"
|
|
10
|
-
data-ai-chat-antiforgery-header="RequestVerificationToken" data-ai-chat-antiforgery-token="…"
|
|
11
|
-
|
|
11
|
+
data-ai-chat-antiforgery-header="RequestVerificationToken" data-ai-chat-antiforgery-token="…"
|
|
12
|
+
data-ai-chat-offset=".header"
|
|
13
|
+
data-ai-chat-label-error="Something went wrong."
|
|
14
|
+
data-ai-chat-tool-find-offices="Looking up offices">
|
|
15
|
+
<div data-ai-chat-scroll>
|
|
16
|
+
<div data-ai-chat-thread>
|
|
17
|
+
<button type="button" data-ai-chat-suggestion="Where is my shipment?">Where is my shipment?</button>
|
|
18
|
+
</div>
|
|
19
|
+
</div>
|
|
12
20
|
<form data-ai-chat-form><textarea data-ai-chat-input></textarea><button data-ai-chat-send>Send</button></form>
|
|
13
21
|
<button type="button" data-ai-chat-reset>Reset</button>
|
|
14
22
|
</section>
|
|
@@ -28,6 +36,32 @@ const chat = bindChat(document.querySelector('[data-ai-chat]')!, { registry })
|
|
|
28
36
|
// Call chat.destroy() when its server-rendered shell is removed.
|
|
29
37
|
```
|
|
30
38
|
|
|
39
|
+
## The shell
|
|
40
|
+
|
|
41
|
+
`bindChat` needs the form, input and thread; the rest is optional.
|
|
42
|
+
|
|
43
|
+
| Markup | What the binding does with it |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| `data-ai-chat-suggestion` | Asks its value (or its text) as the question. |
|
|
46
|
+
| `data-ai-chat-reset` | Clears the thread back to how the server rendered it and starts a new conversation. |
|
|
47
|
+
| `data-ai-chat-scroll` | The element the thread scrolls in. While an answer arrives, the latest question is held at its top; scrolling by hand lets go until the next question. |
|
|
48
|
+
| `data-ai-chat-offset` | A selector for the element the shell sits under, such as a fixed header. Its height is kept in `--vv-ai-chat-offset` on the root. `offsetElement` does the same from script. |
|
|
49
|
+
| `data-ai-chat-label-*` | Labels, in kebab case: `error`, `timeout`, `tool-running`, `tool-complete`, `tool-failed`, `tool-interrupted`, `sources`, `details`, `table`, `table-scroll`. The `labels` option wins over the attribute. |
|
|
50
|
+
| `data-ai-chat-tool-*` | The progress label for one tool, with underscores in its name written as hyphens. Other tools show `tool-running`. The `toolLabels` option wins over the attribute. |
|
|
51
|
+
|
|
52
|
+
The binding also keeps `--vv-ai-chat-keyboard` on the root at the height an on-screen keyboard
|
|
53
|
+
covers, grows the input to fit what is typed, sets `aria-busy` on the root while a turn is in flight,
|
|
54
|
+
and sends a `conversationId` context value that changes on every reset.
|
|
55
|
+
|
|
56
|
+
Elements it adds carry classes under `CHAT_CLASS` (`vv-ai-chat`): `__message` with `--user` or
|
|
57
|
+
`--assistant`, `__text`, `__tool` with `--done` and `--failed`, `__tool-dot`, `__tool-label`,
|
|
58
|
+
`__tool-status`, `__result` around a rendered tool result, and `__error`.
|
|
59
|
+
|
|
60
|
+
`binding.setFormContext(name, summary, followUp)` sends what a visitor entered into an embedded form
|
|
61
|
+
with every later question. An unchanged summary is not sent again, and `followUp` is added as an
|
|
62
|
+
assistant reply only the first time. Renderers and surfaces receive the resolved `labels`, as does
|
|
63
|
+
`binding.labels`.
|
|
64
|
+
|
|
31
65
|
`createChatSession()` is available when a host owns its own rendering. It sends JSON POST requests
|
|
32
66
|
to the configured same-origin endpoint and reads its SSE response. Supply the antiforgery header
|
|
33
67
|
through `bindChat` options or the root attributes; blank header names or tokens are omitted.
|
|
@@ -38,6 +72,47 @@ from authored `data-ai-action` markup and receive an optional authored `data-ai-
|
|
|
38
72
|
Neither server payloads nor model output become executable markup. Generic answer cards, links and
|
|
39
73
|
Markdown are rendered as safe DOM nodes. Host callbacks must return DOM nodes, not HTML strings.
|
|
40
74
|
|
|
75
|
+
## Surfaces
|
|
76
|
+
|
|
77
|
+
`createTemplateItemSurface({ template, attribute, key })` shows one item from an authored list
|
|
78
|
+
template: it clones `template[data-template]` and removes every element carrying `attribute` whose
|
|
79
|
+
value is not the payload's `key` field. Register it with `registry.registerSurface`.
|
|
80
|
+
|
|
81
|
+
## Cards
|
|
82
|
+
|
|
83
|
+
A host maps a tool's payload onto these and registers the result as that tool's renderer. Each
|
|
84
|
+
returns null when there is nothing to show.
|
|
85
|
+
|
|
86
|
+
- `renderContactCard` (`vv-ai-contact-card`): name, subtitle, image (such as a flag), address, phone
|
|
87
|
+
and email links, and labelled groups of hours. Parts: `__head`, `__image`, `__title`, `__name`,
|
|
88
|
+
`__subtitle`, `__address`, `__links`, `__link`, `__hours`, `__hours-label`, `__hours-row`,
|
|
89
|
+
`__hours-days`, `__hours-time`, `__hours-note`.
|
|
90
|
+
- `renderMediaCard` (`vv-ai-media-card`, `--with-image`): a title and facts led by an image. Parts:
|
|
91
|
+
`__figure`, `__image`, `__body`, `__title`, `__facts`, `__fact`, `__fact-label`, `__fact-value`.
|
|
92
|
+
- `renderActions` (`vv-ai-actions`): buttons that run a registered action and safe links, each
|
|
93
|
+
`__action` with `--primary` or `--secondary`.
|
|
94
|
+
- `renderCardList` (`vv-ai-card-list`, `--{modifier}`): several cards from one result.
|
|
95
|
+
|
|
96
|
+
`createSafeImage`, `createSafeLink` and `createPart` are the builders these use, exported for a
|
|
97
|
+
host's own renderers.
|
|
98
|
+
|
|
99
|
+
## Answer cards
|
|
100
|
+
|
|
101
|
+
`renderAnswerCard()` draws a `kind: 'answer'` payload as DOM, or returns null when it breaks any
|
|
102
|
+
limit; the whole card is refused, not trimmed. `isAnswerCard()` applies the same check and the
|
|
103
|
+
`MAX_ANSWER_CARD_*` constants name the limits, so a server or a test can hold its cards to them.
|
|
104
|
+
|
|
105
|
+
Every element carries a BEM class under `ANSWER_CARD_CLASS` (`vv-ai-answer-card`): `__title`,
|
|
106
|
+
`__summary`, `__highlight`, `__section`, `__section-title`, `__text`, `__facts`, `__fact-label`,
|
|
107
|
+
`__fact-value`, `__table-region`, `__table-hint`, `__table`, `__table-header`, `__table-cell`,
|
|
108
|
+
`__links`, `__link`, `__note`, `__details`, `__details-summary`, `__actions`, `__sources`,
|
|
109
|
+
`__sources-title`, `__sources-list`, `__source-note`, and `--generic` on the card drawn for a payload
|
|
110
|
+
of plain fields. Style by these classes rather than by element order.
|
|
111
|
+
|
|
112
|
+
`summary` and section `text` are Markdown. Titles, facts, table cells, `note` and `sourceNote` are
|
|
113
|
+
plain text; a link belongs in `links`, `actions` or `sources`. `isSafeLinkUrl()` is the rule every
|
|
114
|
+
link passes, exported so a host's own renderers can apply it too.
|
|
115
|
+
|
|
41
116
|
The package accepts protocol-v1 events (`delta`, `tool`, `tool_result`, `tool_done`, `done`, and
|
|
42
117
|
`error`). Host-specific card rendering, embedded-component activation and styling remain host
|
|
43
118
|
responsibilities. Eimskip migration is deliberately outside this package.
|
package/dist/index.d.ts
CHANGED
|
@@ -127,6 +127,7 @@ type AiChatExtensionContext = {
|
|
|
127
127
|
tool: string;
|
|
128
128
|
data: unknown;
|
|
129
129
|
reply: string | null;
|
|
130
|
+
labels: AiChatLabels;
|
|
130
131
|
};
|
|
131
132
|
type AiChatRenderer = (context: AiChatExtensionContext) => Node | null;
|
|
132
133
|
type AiChatSurface = (context: AiChatExtensionContext) => Node | null;
|
|
@@ -153,34 +154,136 @@ type AiChatBindings = {
|
|
|
153
154
|
antiforgeryToken?: string;
|
|
154
155
|
timeoutMs?: number;
|
|
155
156
|
labels?: Partial<AiChatLabels>;
|
|
156
|
-
|
|
157
|
+
toolLabels?: Record<string, string>;
|
|
158
|
+
offsetElement?: HTMLElement | null;
|
|
157
159
|
registry?: AiChatRegistry;
|
|
158
160
|
onEmbedded?: (element: HTMLElement) => void;
|
|
159
161
|
onError?: (error: Error) => void;
|
|
160
162
|
};
|
|
161
|
-
type AiChatClasses = {
|
|
162
|
-
messageUser: string;
|
|
163
|
-
messageAssistant: string;
|
|
164
|
-
text: string;
|
|
165
|
-
tool: string;
|
|
166
|
-
card: string;
|
|
167
|
-
error: string;
|
|
168
|
-
};
|
|
169
163
|
type AiChatBinding = {
|
|
170
164
|
session: AiChatSession;
|
|
165
|
+
labels: Readonly<AiChatLabels>;
|
|
171
166
|
appendAssistantReply(text: string): void;
|
|
167
|
+
setFormContext(name: string, summary: string, followUp?: string | null): void;
|
|
172
168
|
destroy(): void;
|
|
173
169
|
};
|
|
170
|
+
type AiCardImage = {
|
|
171
|
+
url: string;
|
|
172
|
+
url2x?: string | null;
|
|
173
|
+
alt?: string | null;
|
|
174
|
+
width?: number | null;
|
|
175
|
+
height?: number | null;
|
|
176
|
+
};
|
|
177
|
+
type AiContactCardHoursRow = {
|
|
178
|
+
label: string;
|
|
179
|
+
value: string;
|
|
180
|
+
note?: string | null;
|
|
181
|
+
};
|
|
182
|
+
type AiContactCardHours = {
|
|
183
|
+
label?: string | null;
|
|
184
|
+
rows: AiContactCardHoursRow[];
|
|
185
|
+
};
|
|
186
|
+
type AiContactCard = {
|
|
187
|
+
name: string;
|
|
188
|
+
subtitle?: string | null;
|
|
189
|
+
image?: AiCardImage | null;
|
|
190
|
+
address?: string | null;
|
|
191
|
+
phone?: string | null;
|
|
192
|
+
email?: string | null;
|
|
193
|
+
hours?: AiContactCardHours[] | null;
|
|
194
|
+
};
|
|
195
|
+
type AiMediaCard = {
|
|
196
|
+
title: string;
|
|
197
|
+
image?: AiCardImage | null;
|
|
198
|
+
facts?: AiAnswerCardFact[] | null;
|
|
199
|
+
};
|
|
200
|
+
type AiChatActionItem = {
|
|
201
|
+
label: string;
|
|
202
|
+
action?: string | null;
|
|
203
|
+
value?: string | null;
|
|
204
|
+
url?: string | null;
|
|
205
|
+
primary?: boolean;
|
|
206
|
+
};
|
|
207
|
+
type AiTemplateItemSurfaceOptions = {
|
|
208
|
+
template: string;
|
|
209
|
+
attribute: string;
|
|
210
|
+
key: string;
|
|
211
|
+
};
|
|
174
212
|
//#endregion
|
|
175
213
|
//#region src/answer-card.d.ts
|
|
214
|
+
declare const MAX_ANSWER_CARD_SECTIONS = 12;
|
|
215
|
+
declare const MAX_ANSWER_CARD_FACTS = 24;
|
|
216
|
+
declare const MAX_ANSWER_CARD_LINKS = 24;
|
|
217
|
+
declare const MAX_ANSWER_CARD_TABLES = 8;
|
|
218
|
+
declare const MAX_ANSWER_CARD_TABLE_ROWS = 50;
|
|
219
|
+
declare const MAX_ANSWER_CARD_TABLE_CELLS = 12;
|
|
220
|
+
declare const MAX_ANSWER_CARD_TEXT_LENGTH = 8000;
|
|
221
|
+
declare const MAX_ANSWER_CARD_URL_LENGTH = 2048;
|
|
222
|
+
declare const MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS = 24000;
|
|
223
|
+
declare const MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS = 512;
|
|
224
|
+
declare const MAX_ANSWER_CARD_TOTAL_TABLE_CELLS = 512;
|
|
225
|
+
/**
|
|
226
|
+
* Every element an answer card renders carries a class under this block, so a host styles the card
|
|
227
|
+
* by class rather than by the order its elements happen to come in.
|
|
228
|
+
*/
|
|
229
|
+
declare const ANSWER_CARD_CLASS = "vv-ai-answer-card";
|
|
230
|
+
/**
|
|
231
|
+
* Whether `renderAnswerCard` will draw `value` as a card. A host that builds cards elsewhere, a
|
|
232
|
+
* server or a test, can hold its output to the same limits the renderer applies.
|
|
233
|
+
*/
|
|
234
|
+
declare function isAnswerCard(value: unknown): value is AiAnswerCard;
|
|
176
235
|
declare function renderAnswerCard(document: Document, data: unknown, labels: AiAnswerCardLabels): HTMLElement | null;
|
|
177
236
|
//#endregion
|
|
178
237
|
//#region src/bind.d.ts
|
|
238
|
+
/**
|
|
239
|
+
* Every element the binding adds to the thread carries a class under this block, so a host styles
|
|
240
|
+
* the chat by class rather than by the order its elements happen to come in.
|
|
241
|
+
*/
|
|
242
|
+
declare const CHAT_CLASS = "vv-ai-chat";
|
|
179
243
|
declare function bindChat(root: HTMLElement, options?: AiChatBindings): AiChatBinding;
|
|
180
244
|
//#endregion
|
|
245
|
+
//#region src/cards.d.ts
|
|
246
|
+
/** Block classes of the cards below. Every element a card renders carries a class under its block. */
|
|
247
|
+
declare const CARD_LIST_CLASS = "vv-ai-card-list";
|
|
248
|
+
declare const CONTACT_CARD_CLASS = "vv-ai-contact-card";
|
|
249
|
+
declare const MEDIA_CARD_CLASS = "vv-ai-media-card";
|
|
250
|
+
declare const ACTIONS_CLASS = "vv-ai-actions";
|
|
251
|
+
/**
|
|
252
|
+
* Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
|
|
253
|
+
* Items that render nothing are skipped, and a list with nothing in it is null.
|
|
254
|
+
*/
|
|
255
|
+
declare function renderCardList<T>(document: Document, items: unknown, render: (item: T) => Node | null, modifier?: string): HTMLElement | null;
|
|
256
|
+
/**
|
|
257
|
+
* A place or person to get in touch with: name, an optional subtitle and image (such as a flag),
|
|
258
|
+
* address, phone and email links, and any number of labelled groups of hours. Null without a name.
|
|
259
|
+
*/
|
|
260
|
+
declare function renderContactCard(document: Document, data: unknown): HTMLElement | null;
|
|
261
|
+
/**
|
|
262
|
+
* A thing best recognised by its picture, with labelled facts beside it. The image leads, and the
|
|
263
|
+
* card carries `--with-image` when it has one. Null without a title.
|
|
264
|
+
*/
|
|
265
|
+
declare function renderMediaCard(document: Document, data: unknown): HTMLElement | null;
|
|
266
|
+
/**
|
|
267
|
+
* A row of things the visitor can do next. An item with `action` is a button that runs the action
|
|
268
|
+
* registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
|
|
269
|
+
* link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
|
|
270
|
+
*/
|
|
271
|
+
declare function renderActions(document: Document, items: readonly AiChatActionItem[]): HTMLElement | null;
|
|
272
|
+
//#endregion
|
|
181
273
|
//#region src/chat.d.ts
|
|
182
274
|
declare function createChatSession(options: AiChatSessionOptions): AiChatSession;
|
|
183
275
|
//#endregion
|
|
276
|
+
//#region src/dom.d.ts
|
|
277
|
+
declare function isSafeLinkUrl(url: string): boolean;
|
|
278
|
+
declare function createSafeLink(document: Document, label: string, url: string): HTMLAnchorElement | null;
|
|
279
|
+
/**
|
|
280
|
+
* An image only from a site-relative or web URL; anything else is left out rather than loaded. The
|
|
281
|
+
* width and height, when given, let the browser reserve the space before the image arrives.
|
|
282
|
+
*/
|
|
283
|
+
declare function createSafeImage(document: Document, image: AiCardImage | null | undefined): HTMLImageElement | null;
|
|
284
|
+
/** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
|
|
285
|
+
declare function createPart<K extends keyof HTMLElementTagNameMap>(document: Document, tag: K, block: string, part?: string | null, text?: string | null): HTMLElementTagNameMap[K];
|
|
286
|
+
//#endregion
|
|
184
287
|
//#region src/protocol.d.ts
|
|
185
288
|
declare const AI_CHAT_PROTOCOL_VERSION = 1;
|
|
186
289
|
declare function parseStreamEvent(name: string, data: unknown): AiChatStreamEvent | null;
|
|
@@ -191,4 +294,13 @@ declare function createAiChatRegistry(): AiChatRegistry;
|
|
|
191
294
|
//#region src/stream.d.ts
|
|
192
295
|
declare function readEventStream(response: Response, signal: AbortSignal): AsyncGenerator<AiChatStreamEvent>;
|
|
193
296
|
//#endregion
|
|
194
|
-
|
|
297
|
+
//#region src/surfaces.d.ts
|
|
298
|
+
/**
|
|
299
|
+
* A surface that shows one item out of an authored list template. The template is cloned, every
|
|
300
|
+
* element carrying `attribute` whose value is not the payload's `key` field is removed, and the
|
|
301
|
+
* rest of the template stays as authored, so one item is the same markup the whole list shows.
|
|
302
|
+
* Null when the template is missing or no item matches.
|
|
303
|
+
*/
|
|
304
|
+
declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: AiChatExtensionContext) => DocumentFragment | null;
|
|
305
|
+
//#endregion
|
|
306
|
+
export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, type AiAnswerCard, type AiAnswerCardFact, type AiAnswerCardLabels, type AiAnswerCardLink, type AiAnswerCardSection, type AiAnswerCardTable, type AiCardImage, type AiChatAction, type AiChatActionItem, type AiChatBinding, type AiChatBindings, type AiChatContext, type AiChatExtensionContext, type AiChatMessage, type AiChatRegistry, type AiChatRenderer, type AiChatRequest, type AiChatSession, type AiChatSessionOptions, type AiChatSessionResult, type AiChatSessionStatus, type AiChatStreamEvent, type AiChatSurface, type AiContactCard, type AiContactCardHours, type AiContactCardHoursRow, type AiMediaCard, type AiTemplateItemSurfaceOptions, CARD_LIST_CLASS, CHAT_CLASS, CONTACT_CARD_CLASS, MAX_ANSWER_CARD_FACTS, MAX_ANSWER_CARD_LINKS, MAX_ANSWER_CARD_SECTIONS, MAX_ANSWER_CARD_TABLES, MAX_ANSWER_CARD_TABLE_CELLS, MAX_ANSWER_CARD_TABLE_ROWS, MAX_ANSWER_CARD_TEXT_LENGTH, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, MAX_ANSWER_CARD_URL_LENGTH, MEDIA_CARD_CLASS, bindChat, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createTemplateItemSurface, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderContactCard, renderMediaCard };
|
package/dist/index.js
CHANGED
|
@@ -33,6 +33,31 @@ function isPlainObject(value) {
|
|
|
33
33
|
const prototype = Object.getPrototypeOf(value);
|
|
34
34
|
return prototype === Object.prototype || prototype === null;
|
|
35
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* An image only from a site-relative or web URL; anything else is left out rather than loaded. The
|
|
38
|
+
* width and height, when given, let the browser reserve the space before the image arrives.
|
|
39
|
+
*/
|
|
40
|
+
function createSafeImage(document, image) {
|
|
41
|
+
if (!image || typeof image.url !== "string" || !/^(https?:\/\/|\/)/i.test(image.url) || !isSafeLinkUrl(image.url)) return null;
|
|
42
|
+
const element = document.createElement("img");
|
|
43
|
+
element.src = image.url;
|
|
44
|
+
element.alt = typeof image.alt === "string" ? image.alt : "";
|
|
45
|
+
element.loading = "lazy";
|
|
46
|
+
element.decoding = "async";
|
|
47
|
+
if (typeof image.url2x === "string" && /^(https?:\/\/|\/)/i.test(image.url2x) && isSafeLinkUrl(image.url2x)) element.srcset = `${image.url} 1x, ${image.url2x} 2x`;
|
|
48
|
+
if (image.width && image.height) {
|
|
49
|
+
element.width = image.width;
|
|
50
|
+
element.height = image.height;
|
|
51
|
+
}
|
|
52
|
+
return element;
|
|
53
|
+
}
|
|
54
|
+
/** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
|
|
55
|
+
function createPart(document, tag, block, part, text) {
|
|
56
|
+
const element = document.createElement(tag);
|
|
57
|
+
element.className = part ? `${block}__${part}` : block;
|
|
58
|
+
if (text) element.textContent = text;
|
|
59
|
+
return element;
|
|
60
|
+
}
|
|
36
61
|
//#endregion
|
|
37
62
|
//#region src/markdown.ts
|
|
38
63
|
const MAX_MARKDOWN_CHARACTERS = 8e3;
|
|
@@ -291,7 +316,22 @@ const TABLE_KEYS = /* @__PURE__ */ new Set([
|
|
|
291
316
|
"rows"
|
|
292
317
|
]);
|
|
293
318
|
const LINK_KEYS = /* @__PURE__ */ new Set(["label", "url"]);
|
|
319
|
+
const MAX_ANSWER_CARD_SECTIONS = 12;
|
|
320
|
+
const MAX_ANSWER_CARD_FACTS = 24;
|
|
321
|
+
const MAX_ANSWER_CARD_LINKS = 24;
|
|
322
|
+
const MAX_ANSWER_CARD_TABLES = 8;
|
|
323
|
+
const MAX_ANSWER_CARD_TABLE_ROWS = 50;
|
|
324
|
+
const MAX_ANSWER_CARD_TABLE_CELLS = 12;
|
|
325
|
+
const MAX_ANSWER_CARD_TEXT_LENGTH = 8e3;
|
|
326
|
+
const MAX_ANSWER_CARD_URL_LENGTH = 2048;
|
|
294
327
|
const MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS = 24e3;
|
|
328
|
+
const MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS = 512;
|
|
329
|
+
const MAX_ANSWER_CARD_TOTAL_TABLE_CELLS = 512;
|
|
330
|
+
/**
|
|
331
|
+
* Every element an answer card renders carries a class under this block, so a host styles the card
|
|
332
|
+
* by class rather than by the order its elements happen to come in.
|
|
333
|
+
*/
|
|
334
|
+
const ANSWER_CARD_CLASS = "vv-ai-answer-card";
|
|
295
335
|
function hasOnlyKeys(value, keys) {
|
|
296
336
|
let keyCount = 0;
|
|
297
337
|
for (const key in value) {
|
|
@@ -359,6 +399,10 @@ function isSection(value, budget) {
|
|
|
359
399
|
if (!isPlainObject(value) || !hasOnlyKeys(value, SECTION_KEYS) || !consumeStructuralItems(budget, 1)) return false;
|
|
360
400
|
return hasOptionalNullableText(value, "title", budget) && hasOptionalNullableMarkdown(value, "text", budget) && hasOptionalNullableArray(value, "facts", 24, (fact) => isFact(fact, budget)) && hasOptionalNullableArray(value, "tables", 8, (table) => isTable(table, budget)) && hasOptionalNullableArray(value, "links", 24, (link) => isLink(link, budget)) && hasOptionalNullableText(value, "note", budget) && hasOptionalBoolean(value, "collapsible");
|
|
361
401
|
}
|
|
402
|
+
/**
|
|
403
|
+
* Whether `renderAnswerCard` will draw `value` as a card. A host that builds cards elsewhere, a
|
|
404
|
+
* server or a test, can hold its output to the same limits the renderer applies.
|
|
405
|
+
*/
|
|
362
406
|
function isAnswerCard(value) {
|
|
363
407
|
const budget = {
|
|
364
408
|
textCharacters: 0,
|
|
@@ -367,45 +411,55 @@ function isAnswerCard(value) {
|
|
|
367
411
|
};
|
|
368
412
|
return isPlainObject(value) && hasOnlyKeys(value, ANSWER_CARD_KEYS) && value.kind === "answer" && consumeStructuralItems(budget, 1) && isAnswerCardText(value.title, budget) && hasOptionalNullableMarkdown(value, "summary", budget) && (!Object.hasOwn(value, "highlight") || value.highlight === null || isFact(value.highlight, budget) && hasOnlyKeys(value.highlight, HIGHLIGHT_KEYS)) && hasOptionalNullableArray(value, "sections", 12, (section) => isSection(section, budget)) && hasOptionalNullableText(value, "note", budget) && hasOptionalNullableArray(value, "actions", 24, (link) => isLink(link, budget)) && hasOptionalNullableArray(value, "sources", 24, (link) => isLink(link, budget)) && hasOptionalNullableText(value, "sourceNote", budget);
|
|
369
413
|
}
|
|
370
|
-
function
|
|
371
|
-
|
|
414
|
+
function cardElement(document, tag, part) {
|
|
415
|
+
const created = document.createElement(tag);
|
|
416
|
+
created.className = part ? `${ANSWER_CARD_CLASS}__${part}` : ANSWER_CARD_CLASS;
|
|
417
|
+
return created;
|
|
418
|
+
}
|
|
419
|
+
function appendMarkdown(document, parent, text, part) {
|
|
420
|
+
if (text !== null && text !== void 0) {
|
|
421
|
+
const wrapper = cardElement(document, "div", part);
|
|
422
|
+
wrapper.append(renderMarkdown(document, text));
|
|
423
|
+
parent.append(wrapper);
|
|
424
|
+
}
|
|
372
425
|
}
|
|
373
|
-
function appendFacts(document, parent, facts) {
|
|
426
|
+
function appendFacts(document, parent, facts, part = "facts") {
|
|
374
427
|
if (facts.length === 0) return;
|
|
375
|
-
const definitions = document
|
|
428
|
+
const definitions = cardElement(document, "dl", part);
|
|
376
429
|
for (const fact of facts) {
|
|
377
|
-
const term = document
|
|
430
|
+
const term = cardElement(document, "dt", "fact-label");
|
|
378
431
|
term.append(document.createTextNode(fact.label));
|
|
379
|
-
const definition = document
|
|
432
|
+
const definition = cardElement(document, "dd", "fact-value");
|
|
380
433
|
definition.append(document.createTextNode(fact.value));
|
|
381
434
|
definitions.append(term, definition);
|
|
382
435
|
}
|
|
383
436
|
parent.append(definitions);
|
|
384
437
|
}
|
|
385
|
-
function appendLinks(document, parent, links) {
|
|
438
|
+
function appendLinks(document, parent, links, part) {
|
|
386
439
|
if (links.length === 0) return;
|
|
387
|
-
const list = document
|
|
440
|
+
const list = cardElement(document, "ul", part);
|
|
388
441
|
for (const item of links) {
|
|
389
|
-
const listItem = document
|
|
442
|
+
const listItem = cardElement(document, "li", `${part}-item`);
|
|
390
443
|
const link = createSafeLink(document, item.label, item.url);
|
|
444
|
+
link?.classList.add(`${ANSWER_CARD_CLASS}__link`);
|
|
391
445
|
listItem.append(link ?? document.createTextNode(item.label));
|
|
392
446
|
list.append(listItem);
|
|
393
447
|
}
|
|
394
448
|
parent.append(list);
|
|
395
449
|
}
|
|
396
|
-
function appendNote(document, parent, note) {
|
|
450
|
+
function appendNote(document, parent, note, part = "note") {
|
|
397
451
|
if (note === null || note === void 0) return;
|
|
398
|
-
const paragraph = document
|
|
452
|
+
const paragraph = cardElement(document, "p", part);
|
|
399
453
|
paragraph.append(document.createTextNode(note));
|
|
400
454
|
parent.append(paragraph);
|
|
401
455
|
}
|
|
402
456
|
function createTable(document, table) {
|
|
403
|
-
const element = document
|
|
457
|
+
const element = cardElement(document, "table", "table");
|
|
404
458
|
if (table.headers.length > 0) {
|
|
405
459
|
const head = document.createElement("thead");
|
|
406
460
|
const row = document.createElement("tr");
|
|
407
461
|
for (const header of table.headers) {
|
|
408
|
-
const cell = document
|
|
462
|
+
const cell = cardElement(document, "th", "table-header");
|
|
409
463
|
cell.scope = "col";
|
|
410
464
|
cell.append(document.createTextNode(header));
|
|
411
465
|
row.append(cell);
|
|
@@ -418,7 +472,7 @@ function createTable(document, table) {
|
|
|
418
472
|
for (const cells of table.rows) {
|
|
419
473
|
const row = document.createElement("tr");
|
|
420
474
|
for (const value of cells) {
|
|
421
|
-
const cell = document
|
|
475
|
+
const cell = cardElement(document, "td", "table-cell");
|
|
422
476
|
cell.append(document.createTextNode(value));
|
|
423
477
|
row.append(cell);
|
|
424
478
|
}
|
|
@@ -448,14 +502,13 @@ function appendTables(document, parent, tables, sectionTitle, labels, names) {
|
|
|
448
502
|
const ordinal = (names.ordinals.get(name) ?? 0) + 1;
|
|
449
503
|
names.ordinals.set(name, ordinal);
|
|
450
504
|
const element = createTable(document, table);
|
|
451
|
-
const region = document
|
|
452
|
-
region.className = "vv-ai-answer-card__table-region";
|
|
505
|
+
const region = cardElement(document, "div", "table-region");
|
|
453
506
|
region.setAttribute("data-ai-table-region", "true");
|
|
454
507
|
region.setAttribute("role", "region");
|
|
455
508
|
region.setAttribute("tabindex", "0");
|
|
456
509
|
region.setAttribute("aria-label", (names.counts.get(name) ?? 0) > 1 ? `${name} (${ordinal})` : name);
|
|
457
510
|
region.style.overflowX = "auto";
|
|
458
|
-
const hint = document
|
|
511
|
+
const hint = cardElement(document, "p", "table-hint");
|
|
459
512
|
hint.append(document.createTextNode(labels.tableScroll));
|
|
460
513
|
region.append(hint);
|
|
461
514
|
region.append(element);
|
|
@@ -463,45 +516,45 @@ function appendTables(document, parent, tables, sectionTitle, labels, names) {
|
|
|
463
516
|
}
|
|
464
517
|
}
|
|
465
518
|
function appendSection(document, article, section, labels, names) {
|
|
466
|
-
const content = document
|
|
519
|
+
const content = cardElement(document, "section", "section");
|
|
467
520
|
if (!section.collapsible && section.title !== null && section.title !== void 0) {
|
|
468
|
-
const heading = document
|
|
521
|
+
const heading = cardElement(document, "h3", "section-title");
|
|
469
522
|
heading.append(document.createTextNode(section.title));
|
|
470
523
|
content.append(heading);
|
|
471
524
|
}
|
|
472
|
-
appendMarkdown(document, content, section.text);
|
|
525
|
+
appendMarkdown(document, content, section.text, "text");
|
|
473
526
|
appendFacts(document, content, section.facts ?? []);
|
|
474
527
|
appendTables(document, content, section.tables ?? [], section.title, labels, names);
|
|
475
|
-
appendLinks(document, content, section.links ?? []);
|
|
528
|
+
appendLinks(document, content, section.links ?? [], "links");
|
|
476
529
|
appendNote(document, content, section.note);
|
|
477
530
|
if (!section.collapsible) {
|
|
478
531
|
article.append(content);
|
|
479
532
|
return;
|
|
480
533
|
}
|
|
481
|
-
const details = document
|
|
482
|
-
const summary = document
|
|
534
|
+
const details = cardElement(document, "details", "details");
|
|
535
|
+
const summary = cardElement(document, "summary", "details-summary");
|
|
483
536
|
summary.append(document.createTextNode(section.title?.trim() ? section.title : labels.details));
|
|
484
537
|
details.append(summary, content);
|
|
485
538
|
article.append(details);
|
|
486
539
|
}
|
|
487
540
|
function renderKnownAnswerCard(document, card, labels) {
|
|
488
|
-
const article = document
|
|
489
|
-
const heading = document
|
|
541
|
+
const article = cardElement(document, "article", "");
|
|
542
|
+
const heading = cardElement(document, "h2", "title");
|
|
490
543
|
heading.append(document.createTextNode(card.title));
|
|
491
544
|
article.append(heading);
|
|
492
|
-
appendMarkdown(document, article, card.summary);
|
|
493
|
-
if (card.highlight) appendFacts(document, article, [card.highlight]);
|
|
545
|
+
appendMarkdown(document, article, card.summary, "summary");
|
|
546
|
+
if (card.highlight) appendFacts(document, article, [card.highlight], "highlight");
|
|
494
547
|
const names = tableRegionNames(card.sections ?? [], labels);
|
|
495
548
|
for (const section of card.sections ?? []) appendSection(document, article, section, labels, names);
|
|
496
549
|
appendNote(document, article, card.note);
|
|
497
|
-
appendLinks(document, article, card.actions ?? []);
|
|
550
|
+
appendLinks(document, article, card.actions ?? [], "actions");
|
|
498
551
|
if ((card.sources?.length ?? 0) > 0 || card.sourceNote !== null && card.sourceNote !== void 0) {
|
|
499
|
-
const sources = document
|
|
500
|
-
const sourceHeading = document
|
|
552
|
+
const sources = cardElement(document, "section", "sources");
|
|
553
|
+
const sourceHeading = cardElement(document, "h3", "sources-title");
|
|
501
554
|
sourceHeading.append(document.createTextNode(labels.sources));
|
|
502
555
|
sources.append(sourceHeading);
|
|
503
|
-
appendLinks(document, sources, card.sources ?? []);
|
|
504
|
-
appendNote(document, sources, card.sourceNote);
|
|
556
|
+
appendLinks(document, sources, card.sources ?? [], "sources-list");
|
|
557
|
+
appendNote(document, sources, card.sourceNote, "source-note");
|
|
505
558
|
article.append(sources);
|
|
506
559
|
}
|
|
507
560
|
return article;
|
|
@@ -552,10 +605,11 @@ function genericEntries(data) {
|
|
|
552
605
|
function renderGenericAnswerCard(document, data) {
|
|
553
606
|
const entries = genericEntries(data);
|
|
554
607
|
if (entries.length === 0) return null;
|
|
555
|
-
const article = document
|
|
556
|
-
|
|
608
|
+
const article = cardElement(document, "article", "");
|
|
609
|
+
article.classList.add(`${ANSWER_CARD_CLASS}--generic`);
|
|
610
|
+
const list = cardElement(document, "ul", "entries");
|
|
557
611
|
for (const fields of entries) {
|
|
558
|
-
const item = document
|
|
612
|
+
const item = cardElement(document, "li", "entry");
|
|
559
613
|
appendFacts(document, item, fields);
|
|
560
614
|
list.append(item);
|
|
561
615
|
}
|
|
@@ -907,14 +961,24 @@ const defaultLabels = {
|
|
|
907
961
|
table: "Published table",
|
|
908
962
|
tableScroll: "Scroll sideways to see all columns"
|
|
909
963
|
};
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
}
|
|
964
|
+
/**
|
|
965
|
+
* Every element the binding adds to the thread carries a class under this block, so a host styles
|
|
966
|
+
* the chat by class rather than by the order its elements happen to come in.
|
|
967
|
+
*/
|
|
968
|
+
const CHAT_CLASS = "vv-ai-chat";
|
|
969
|
+
const CONVERSATION_CONTEXT = "conversationId";
|
|
970
|
+
function part(name) {
|
|
971
|
+
return `${CHAT_CLASS}__${name}`;
|
|
972
|
+
}
|
|
973
|
+
function kebab(name) {
|
|
974
|
+
return name.replace(/[A-Z_]/g, (character) => character === "_" ? "-" : `-${character.toLowerCase()}`);
|
|
975
|
+
}
|
|
976
|
+
/** Labels from `data-ai-chat-label-*` on the root, under the options and over the defaults. */
|
|
977
|
+
function readLabels(root, labels) {
|
|
978
|
+
const read = {};
|
|
979
|
+
for (const key of Object.keys(defaultLabels)) read[key] = labels?.[key] || root.getAttribute(`data-ai-chat-label-${kebab(key)}`) || defaultLabels[key];
|
|
980
|
+
return read;
|
|
981
|
+
}
|
|
918
982
|
function dataString(data, name) {
|
|
919
983
|
if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
|
|
920
984
|
const value = data[name];
|
|
@@ -927,14 +991,7 @@ function bindChat(root, options = {}) {
|
|
|
927
991
|
const send = root.querySelector("[data-ai-chat-send]");
|
|
928
992
|
if (!form || !input || !thread) throw new Error("AI chat shell requires form, input and thread elements");
|
|
929
993
|
const chatThread = thread;
|
|
930
|
-
const labels =
|
|
931
|
-
...defaultLabels,
|
|
932
|
-
...options.labels
|
|
933
|
-
};
|
|
934
|
-
const classes = {
|
|
935
|
-
...defaultClasses,
|
|
936
|
-
...options.classes
|
|
937
|
-
};
|
|
994
|
+
const labels = readLabels(root, options.labels);
|
|
938
995
|
const initialThread = chatThread.cloneNode(true);
|
|
939
996
|
let initialNodes = Array.from(chatThread.childNodes);
|
|
940
997
|
const endpoint = options.endpoint ?? root.dataset.aiChatEndpoint ?? form.action;
|
|
@@ -946,23 +1003,32 @@ function bindChat(root, options = {}) {
|
|
|
946
1003
|
let activeTextContent = "";
|
|
947
1004
|
let pendingTool = null;
|
|
948
1005
|
let destroyed = false;
|
|
1006
|
+
const formContexts = /* @__PURE__ */ new Map();
|
|
1007
|
+
const cleanups = [];
|
|
949
1008
|
const session = createChatSession({
|
|
950
1009
|
endpoint,
|
|
951
1010
|
provider: options.provider ?? root.dataset.aiChatProvider,
|
|
952
1011
|
headers,
|
|
953
1012
|
timeoutMs: options.timeoutMs
|
|
954
1013
|
});
|
|
1014
|
+
function startConversation() {
|
|
1015
|
+
session.setContext(CONVERSATION_CONTEXT, crypto.randomUUID());
|
|
1016
|
+
}
|
|
1017
|
+
function listen(target, type, listener, options) {
|
|
1018
|
+
target.addEventListener(type, listener, options);
|
|
1019
|
+
cleanups.push(() => target.removeEventListener(type, listener, options));
|
|
1020
|
+
}
|
|
955
1021
|
function appendMessage(role) {
|
|
956
1022
|
const message = root.ownerDocument.createElement("div");
|
|
957
1023
|
message.dataset.aiChatMessage = role;
|
|
958
|
-
message.className =
|
|
1024
|
+
message.className = `${part("message")} ${part(`message--${role}`)}`;
|
|
959
1025
|
chatThread.append(message);
|
|
960
1026
|
return message;
|
|
961
1027
|
}
|
|
962
1028
|
function appendMarkdown(parent, text) {
|
|
963
1029
|
const bubble = root.ownerDocument.createElement("div");
|
|
964
1030
|
bubble.dataset.aiChatText = "true";
|
|
965
|
-
bubble.className =
|
|
1031
|
+
bubble.className = part("text");
|
|
966
1032
|
bubble.append(renderMarkdown(root.ownerDocument, text));
|
|
967
1033
|
parent.append(bubble);
|
|
968
1034
|
}
|
|
@@ -971,7 +1037,7 @@ function bindChat(root, options = {}) {
|
|
|
971
1037
|
if (!activeText) {
|
|
972
1038
|
activeText = root.ownerDocument.createElement("div");
|
|
973
1039
|
activeText.dataset.aiChatText = "true";
|
|
974
|
-
activeText.className =
|
|
1040
|
+
activeText.className = part("text");
|
|
975
1041
|
activeAssistant.append(activeText);
|
|
976
1042
|
}
|
|
977
1043
|
activeTextContent += text;
|
|
@@ -981,21 +1047,26 @@ function bindChat(root, options = {}) {
|
|
|
981
1047
|
options.onError?.(error);
|
|
982
1048
|
const message = root.ownerDocument.createElement("p");
|
|
983
1049
|
message.setAttribute("role", "alert");
|
|
984
|
-
message.className =
|
|
1050
|
+
message.className = part("error");
|
|
985
1051
|
message.append(error.name === "TimeoutError" ? labels.timeout : labels.error);
|
|
986
1052
|
chatThread.append(message);
|
|
987
1053
|
}
|
|
988
|
-
function
|
|
1054
|
+
function toolLabel(name) {
|
|
1055
|
+
if (!/^[\w-]{1,64}$/.test(name)) return labels.toolRunning;
|
|
1056
|
+
return options.toolLabels?.[name] || root.getAttribute(`data-ai-chat-tool-${kebab(name)}`) || labels.toolRunning;
|
|
1057
|
+
}
|
|
1058
|
+
function tool(id, name) {
|
|
989
1059
|
const element = root.ownerDocument.createElement("div");
|
|
990
1060
|
element.dataset.aiChatTool = id;
|
|
991
|
-
element.className =
|
|
1061
|
+
element.className = part("tool");
|
|
992
1062
|
const dot = root.ownerDocument.createElement("span");
|
|
993
|
-
dot.className = "
|
|
1063
|
+
dot.className = part("tool-dot");
|
|
994
1064
|
dot.setAttribute("aria-hidden", "true");
|
|
995
1065
|
const label = root.ownerDocument.createElement("span");
|
|
996
|
-
label.
|
|
1066
|
+
label.className = part("tool-label");
|
|
1067
|
+
label.append(root.ownerDocument.createTextNode(toolLabel(name)));
|
|
997
1068
|
const status = root.ownerDocument.createElement("span");
|
|
998
|
-
status.className = "
|
|
1069
|
+
status.className = part("tool-status");
|
|
999
1070
|
element.append(dot, label, status);
|
|
1000
1071
|
activeAssistant?.append(element);
|
|
1001
1072
|
return element;
|
|
@@ -1006,14 +1077,14 @@ function bindChat(root, options = {}) {
|
|
|
1006
1077
|
}
|
|
1007
1078
|
function finishTool(id, failed, interrupted = false) {
|
|
1008
1079
|
const element = activeAssistant?.querySelector(`[data-ai-chat-tool="${CSS.escape(id)}"]`);
|
|
1080
|
+
finishToolElement(element, failed, interrupted);
|
|
1081
|
+
}
|
|
1082
|
+
function finishToolElement(element, failed, interrupted) {
|
|
1009
1083
|
if (element) {
|
|
1010
|
-
element.classList.add("
|
|
1011
|
-
element.classList.toggle("
|
|
1012
|
-
const status = element.querySelector("
|
|
1013
|
-
if (status)
|
|
1014
|
-
status.textContent = interrupted ? labels.toolInterrupted : failed ? labels.toolFailed : labels.toolComplete;
|
|
1015
|
-
status.classList.remove("sr-only");
|
|
1016
|
-
}
|
|
1084
|
+
element.classList.add(part("tool--done"));
|
|
1085
|
+
element.classList.toggle(part("tool--failed"), failed || interrupted);
|
|
1086
|
+
const status = element.querySelector(`.${part("tool-status")}`);
|
|
1087
|
+
if (status) status.textContent = interrupted ? labels.toolInterrupted : failed ? labels.toolFailed : labels.toolComplete;
|
|
1017
1088
|
}
|
|
1018
1089
|
}
|
|
1019
1090
|
function renderResult(event) {
|
|
@@ -1025,7 +1096,8 @@ function bindChat(root, options = {}) {
|
|
|
1025
1096
|
root,
|
|
1026
1097
|
tool: event.data.name,
|
|
1027
1098
|
data: event.data.data,
|
|
1028
|
-
reply: event.data.reply
|
|
1099
|
+
reply: event.data.reply,
|
|
1100
|
+
labels
|
|
1029
1101
|
};
|
|
1030
1102
|
let content = null;
|
|
1031
1103
|
try {
|
|
@@ -1041,7 +1113,7 @@ function bindChat(root, options = {}) {
|
|
|
1041
1113
|
if (content) {
|
|
1042
1114
|
const wrapper = root.ownerDocument.createElement("div");
|
|
1043
1115
|
wrapper.dataset.aiChatCard = "true";
|
|
1044
|
-
wrapper.className =
|
|
1116
|
+
wrapper.className = part("result");
|
|
1045
1117
|
wrapper.append(content);
|
|
1046
1118
|
activeAssistant.append(wrapper);
|
|
1047
1119
|
options.onEmbedded?.(wrapper);
|
|
@@ -1061,11 +1133,16 @@ function bindChat(root, options = {}) {
|
|
|
1061
1133
|
} else if (event.name === "tool_done") finishTool(event.data.id, event.data.isError);
|
|
1062
1134
|
else if (event.name === "done" || event.name === "error") clearPendingTool();
|
|
1063
1135
|
});
|
|
1136
|
+
const resizeInput = () => {
|
|
1137
|
+
input.style.height = "auto";
|
|
1138
|
+
input.style.height = `${input.scrollHeight}px`;
|
|
1139
|
+
};
|
|
1064
1140
|
const submit = async (event) => {
|
|
1065
1141
|
event?.preventDefault();
|
|
1066
1142
|
const question = input.value.trim();
|
|
1067
1143
|
if (!question || session.status !== "idle") return;
|
|
1068
1144
|
input.value = "";
|
|
1145
|
+
resizeInput();
|
|
1069
1146
|
for (const node of initialNodes) node.remove();
|
|
1070
1147
|
appendMarkdown(appendMessage("user"), question);
|
|
1071
1148
|
activeAssistant = appendMessage("assistant");
|
|
@@ -1078,8 +1155,8 @@ function bindChat(root, options = {}) {
|
|
|
1078
1155
|
root.removeAttribute("aria-busy");
|
|
1079
1156
|
if (send) send.disabled = false;
|
|
1080
1157
|
if (result.error && !result.canceled) report(result.error);
|
|
1081
|
-
if (result.canceled) activeAssistant?.querySelectorAll(
|
|
1082
|
-
item
|
|
1158
|
+
if (result.canceled) activeAssistant?.querySelectorAll(`[data-ai-chat-tool]:not(.${part("tool--done")})`).forEach((item) => {
|
|
1159
|
+
finishToolElement(item, false, true);
|
|
1083
1160
|
});
|
|
1084
1161
|
};
|
|
1085
1162
|
const click = (event) => {
|
|
@@ -1095,10 +1172,13 @@ function bindChat(root, options = {}) {
|
|
|
1095
1172
|
chatThread.replaceChildren(...Array.from(initialThread.childNodes, (node) => node.cloneNode(true)));
|
|
1096
1173
|
initialNodes = Array.from(chatThread.childNodes);
|
|
1097
1174
|
input.value = "";
|
|
1175
|
+
resizeInput();
|
|
1098
1176
|
activeAssistant = null;
|
|
1099
1177
|
activeText = null;
|
|
1100
1178
|
activeTextContent = "";
|
|
1101
1179
|
pendingTool = null;
|
|
1180
|
+
formContexts.clear();
|
|
1181
|
+
startConversation();
|
|
1102
1182
|
return;
|
|
1103
1183
|
}
|
|
1104
1184
|
const actionElement = target?.closest("[data-ai-action]");
|
|
@@ -1118,27 +1198,250 @@ function bindChat(root, options = {}) {
|
|
|
1118
1198
|
submit();
|
|
1119
1199
|
}
|
|
1120
1200
|
};
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1201
|
+
function followAnswer() {
|
|
1202
|
+
const scroller = root.querySelector("[data-ai-chat-scroll]");
|
|
1203
|
+
if (!scroller) return;
|
|
1204
|
+
let question = null;
|
|
1205
|
+
let following = false;
|
|
1206
|
+
const release = () => {
|
|
1207
|
+
following = false;
|
|
1208
|
+
};
|
|
1209
|
+
listen(scroller, "wheel", release, { passive: true });
|
|
1210
|
+
listen(scroller, "touchmove", release, { passive: true });
|
|
1211
|
+
const observer = new MutationObserver(() => {
|
|
1212
|
+
const questions = chatThread.querySelectorAll("[data-ai-chat-message=\"user\"]");
|
|
1213
|
+
const latest = questions[questions.length - 1] ?? null;
|
|
1214
|
+
if (latest !== question) {
|
|
1215
|
+
question = latest;
|
|
1216
|
+
following = true;
|
|
1217
|
+
}
|
|
1218
|
+
if (!question || !following || root.getAttribute("aria-busy") !== "true") return;
|
|
1219
|
+
const top = question.getBoundingClientRect().top - chatThread.getBoundingClientRect().top - Number.parseFloat(getComputedStyle(chatThread).paddingTop || "0");
|
|
1220
|
+
following = top > scroller.scrollHeight - scroller.clientHeight;
|
|
1221
|
+
scroller.scrollTo({ top });
|
|
1222
|
+
});
|
|
1223
|
+
observer.observe(chatThread, {
|
|
1224
|
+
childList: true,
|
|
1225
|
+
subtree: true
|
|
1226
|
+
});
|
|
1227
|
+
cleanups.push(() => observer.disconnect());
|
|
1228
|
+
}
|
|
1229
|
+
function trackKeyboard() {
|
|
1230
|
+
const viewport = root.ownerDocument.defaultView?.visualViewport;
|
|
1231
|
+
if (!viewport) return;
|
|
1232
|
+
const apply = () => {
|
|
1233
|
+
const covered = window.innerHeight - viewport.height - viewport.offsetTop;
|
|
1234
|
+
root.style.setProperty(`--${CHAT_CLASS}-keyboard`, `${Math.max(0, covered)}px`);
|
|
1235
|
+
};
|
|
1236
|
+
apply();
|
|
1237
|
+
listen(viewport, "resize", apply);
|
|
1238
|
+
listen(viewport, "scroll", apply);
|
|
1239
|
+
}
|
|
1240
|
+
function trackOffset() {
|
|
1241
|
+
const selector = root.dataset.aiChatOffset;
|
|
1242
|
+
const element = options.offsetElement ?? (selector ? root.ownerDocument.querySelector(selector) : null);
|
|
1243
|
+
if (!element) return;
|
|
1244
|
+
const apply = () => root.style.setProperty(`--${CHAT_CLASS}-offset`, `${element.offsetHeight}px`);
|
|
1245
|
+
apply();
|
|
1246
|
+
const observer = new ResizeObserver(apply);
|
|
1247
|
+
observer.observe(element);
|
|
1248
|
+
cleanups.push(() => observer.disconnect());
|
|
1249
|
+
}
|
|
1250
|
+
listen(form, "submit", submit);
|
|
1251
|
+
listen(root, "click", click);
|
|
1252
|
+
listen(input, "keydown", keydown);
|
|
1253
|
+
listen(input, "input", resizeInput);
|
|
1254
|
+
followAnswer();
|
|
1255
|
+
trackKeyboard();
|
|
1256
|
+
trackOffset();
|
|
1257
|
+
startConversation();
|
|
1258
|
+
const binding = {
|
|
1125
1259
|
session,
|
|
1260
|
+
labels,
|
|
1126
1261
|
appendAssistantReply(text) {
|
|
1127
1262
|
const content = text.trim();
|
|
1128
1263
|
if (!content) return;
|
|
1129
1264
|
appendMarkdown(appendMessage("assistant"), content);
|
|
1130
1265
|
session.addAssistantReply(content);
|
|
1131
1266
|
},
|
|
1267
|
+
setFormContext(name, summary, followUp) {
|
|
1268
|
+
const content = summary.trim();
|
|
1269
|
+
if (!content || formContexts.get(name) === content) return;
|
|
1270
|
+
const first = !formContexts.has(name);
|
|
1271
|
+
formContexts.set(name, content);
|
|
1272
|
+
session.setContextMessage(name, content);
|
|
1273
|
+
if (first && followUp) binding.appendAssistantReply(followUp);
|
|
1274
|
+
},
|
|
1132
1275
|
destroy() {
|
|
1133
1276
|
if (destroyed) return;
|
|
1134
1277
|
destroyed = true;
|
|
1135
1278
|
unsubscribe();
|
|
1136
1279
|
session.dispose();
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1280
|
+
for (const cleanup of cleanups.splice(0)) cleanup();
|
|
1281
|
+
}
|
|
1282
|
+
};
|
|
1283
|
+
return binding;
|
|
1284
|
+
}
|
|
1285
|
+
//#endregion
|
|
1286
|
+
//#region src/cards.ts
|
|
1287
|
+
/** Block classes of the cards below. Every element a card renders carries a class under its block. */
|
|
1288
|
+
const CARD_LIST_CLASS = "vv-ai-card-list";
|
|
1289
|
+
const CONTACT_CARD_CLASS = "vv-ai-contact-card";
|
|
1290
|
+
const MEDIA_CARD_CLASS = "vv-ai-media-card";
|
|
1291
|
+
const ACTIONS_CLASS = "vv-ai-actions";
|
|
1292
|
+
function text(value) {
|
|
1293
|
+
return typeof value === "string" && value.trim() ? value : null;
|
|
1294
|
+
}
|
|
1295
|
+
/**
|
|
1296
|
+
* Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
|
|
1297
|
+
* Items that render nothing are skipped, and a list with nothing in it is null.
|
|
1298
|
+
*/
|
|
1299
|
+
function renderCardList(document, items, render, modifier) {
|
|
1300
|
+
if (!Array.isArray(items)) return null;
|
|
1301
|
+
const cards = items.map(render).filter((card) => card !== null);
|
|
1302
|
+
if (!cards.length) return null;
|
|
1303
|
+
const list = createPart(document, "div", CARD_LIST_CLASS);
|
|
1304
|
+
if (modifier) list.classList.add(`${CARD_LIST_CLASS}--${modifier}`);
|
|
1305
|
+
list.append(...cards);
|
|
1306
|
+
return list;
|
|
1307
|
+
}
|
|
1308
|
+
function appendHours(document, card, hours) {
|
|
1309
|
+
const rows = Array.isArray(hours.rows) ? hours.rows.filter((row) => isPlainObject(row) && text(row.value)) : [];
|
|
1310
|
+
if (!rows.length) return;
|
|
1311
|
+
const block = createPart(document, "div", CONTACT_CARD_CLASS, "hours");
|
|
1312
|
+
const label = text(hours.label);
|
|
1313
|
+
if (label) block.append(createPart(document, "span", CONTACT_CARD_CLASS, "hours-label", label));
|
|
1314
|
+
for (const row of rows) {
|
|
1315
|
+
const line = createPart(document, "div", CONTACT_CARD_CLASS, "hours-row");
|
|
1316
|
+
const time = createPart(document, "span", CONTACT_CARD_CLASS, "hours-time", row.value);
|
|
1317
|
+
const note = text(row.note);
|
|
1318
|
+
if (note) time.append(" ", createPart(document, "span", CONTACT_CARD_CLASS, "hours-note", note));
|
|
1319
|
+
line.append(createPart(document, "span", CONTACT_CARD_CLASS, "hours-days", text(row.label)), time);
|
|
1320
|
+
block.append(line);
|
|
1321
|
+
}
|
|
1322
|
+
card.append(block);
|
|
1323
|
+
}
|
|
1324
|
+
/**
|
|
1325
|
+
* A place or person to get in touch with: name, an optional subtitle and image (such as a flag),
|
|
1326
|
+
* address, phone and email links, and any number of labelled groups of hours. Null without a name.
|
|
1327
|
+
*/
|
|
1328
|
+
function renderContactCard(document, data) {
|
|
1329
|
+
if (!isPlainObject(data)) return null;
|
|
1330
|
+
const contact = data;
|
|
1331
|
+
const name = text(contact.name);
|
|
1332
|
+
if (!name) return null;
|
|
1333
|
+
const card = createPart(document, "article", CONTACT_CARD_CLASS);
|
|
1334
|
+
const head = createPart(document, "header", CONTACT_CARD_CLASS, "head");
|
|
1335
|
+
const image = createSafeImage(document, contact.image);
|
|
1336
|
+
if (image) {
|
|
1337
|
+
image.className = `${CONTACT_CARD_CLASS}__image`;
|
|
1338
|
+
head.append(image);
|
|
1339
|
+
}
|
|
1340
|
+
const title = createPart(document, "span", CONTACT_CARD_CLASS, "title");
|
|
1341
|
+
title.append(createPart(document, "span", CONTACT_CARD_CLASS, "name", name));
|
|
1342
|
+
const subtitle = text(contact.subtitle);
|
|
1343
|
+
if (subtitle) title.append(createPart(document, "span", CONTACT_CARD_CLASS, "subtitle", subtitle));
|
|
1344
|
+
head.append(title);
|
|
1345
|
+
card.append(head);
|
|
1346
|
+
const address = text(contact.address);
|
|
1347
|
+
if (address) card.append(createPart(document, "p", CONTACT_CARD_CLASS, "address", address));
|
|
1348
|
+
const links = createPart(document, "p", CONTACT_CARD_CLASS, "links");
|
|
1349
|
+
const phone = text(contact.phone);
|
|
1350
|
+
const email = text(contact.email);
|
|
1351
|
+
for (const link of [phone ? createSafeLink(document, phone, `tel:${phone.replace(/[^+\d]/g, "")}`) : null, email ? createSafeLink(document, email, `mailto:${email.trim()}`) : null]) if (link) {
|
|
1352
|
+
link.className = `${CONTACT_CARD_CLASS}__link`;
|
|
1353
|
+
links.append(link);
|
|
1354
|
+
}
|
|
1355
|
+
if (links.children.length) card.append(links);
|
|
1356
|
+
for (const hours of Array.isArray(contact.hours) ? contact.hours : []) if (isPlainObject(hours)) appendHours(document, card, hours);
|
|
1357
|
+
return card;
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* A thing best recognised by its picture, with labelled facts beside it. The image leads, and the
|
|
1361
|
+
* card carries `--with-image` when it has one. Null without a title.
|
|
1362
|
+
*/
|
|
1363
|
+
function renderMediaCard(document, data) {
|
|
1364
|
+
if (!isPlainObject(data)) return null;
|
|
1365
|
+
const media = data;
|
|
1366
|
+
const title = text(media.title);
|
|
1367
|
+
if (!title) return null;
|
|
1368
|
+
const card = createPart(document, "article", MEDIA_CARD_CLASS);
|
|
1369
|
+
const image = createSafeImage(document, media.image);
|
|
1370
|
+
if (image) {
|
|
1371
|
+
image.className = `${MEDIA_CARD_CLASS}__image`;
|
|
1372
|
+
const figure = createPart(document, "div", MEDIA_CARD_CLASS, "figure");
|
|
1373
|
+
figure.append(image);
|
|
1374
|
+
card.classList.add(`${MEDIA_CARD_CLASS}--with-image`);
|
|
1375
|
+
card.append(figure);
|
|
1376
|
+
}
|
|
1377
|
+
const body = createPart(document, "div", MEDIA_CARD_CLASS, "body");
|
|
1378
|
+
body.append(createPart(document, "h3", MEDIA_CARD_CLASS, "title", title));
|
|
1379
|
+
const facts = (Array.isArray(media.facts) ? media.facts : []).filter((fact) => isPlainObject(fact) && text(fact.value));
|
|
1380
|
+
if (facts.length) {
|
|
1381
|
+
const list = createPart(document, "div", MEDIA_CARD_CLASS, "facts");
|
|
1382
|
+
for (const fact of facts) {
|
|
1383
|
+
const row = createPart(document, "div", MEDIA_CARD_CLASS, "fact");
|
|
1384
|
+
row.append(createPart(document, "span", MEDIA_CARD_CLASS, "fact-label", text(fact.label)), createPart(document, "span", MEDIA_CARD_CLASS, "fact-value", fact.value));
|
|
1385
|
+
list.append(row);
|
|
1386
|
+
}
|
|
1387
|
+
body.append(list);
|
|
1388
|
+
}
|
|
1389
|
+
card.append(body);
|
|
1390
|
+
return card;
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* A row of things the visitor can do next. An item with `action` is a button that runs the action
|
|
1394
|
+
* registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
|
|
1395
|
+
* link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
|
|
1396
|
+
*/
|
|
1397
|
+
function renderActions(document, items) {
|
|
1398
|
+
const elements = [];
|
|
1399
|
+
for (const item of items) {
|
|
1400
|
+
const label = text(item?.label);
|
|
1401
|
+
if (!label) continue;
|
|
1402
|
+
let element = null;
|
|
1403
|
+
const action = text(item.action);
|
|
1404
|
+
const url = text(item.url);
|
|
1405
|
+
if (action) {
|
|
1406
|
+
const button = createPart(document, "button", ACTIONS_CLASS, "action", label);
|
|
1407
|
+
button.type = "button";
|
|
1408
|
+
button.dataset.aiAction = action;
|
|
1409
|
+
const value = text(item.value);
|
|
1410
|
+
if (value) button.dataset.aiActionValue = value;
|
|
1411
|
+
element = button;
|
|
1412
|
+
} else if (url) {
|
|
1413
|
+
element = createSafeLink(document, label, url.trim());
|
|
1414
|
+
if (element) element.className = `${ACTIONS_CLASS}__action`;
|
|
1415
|
+
}
|
|
1416
|
+
if (element) {
|
|
1417
|
+
element.classList.add(`${ACTIONS_CLASS}__action--${item.primary ? "primary" : "secondary"}`);
|
|
1418
|
+
elements.push(element);
|
|
1140
1419
|
}
|
|
1420
|
+
}
|
|
1421
|
+
if (!elements.length) return null;
|
|
1422
|
+
const actions = createPart(document, "div", ACTIONS_CLASS);
|
|
1423
|
+
actions.append(...elements);
|
|
1424
|
+
return actions;
|
|
1425
|
+
}
|
|
1426
|
+
//#endregion
|
|
1427
|
+
//#region src/surfaces.ts
|
|
1428
|
+
/**
|
|
1429
|
+
* A surface that shows one item out of an authored list template. The template is cloned, every
|
|
1430
|
+
* element carrying `attribute` whose value is not the payload's `key` field is removed, and the
|
|
1431
|
+
* rest of the template stays as authored, so one item is the same markup the whole list shows.
|
|
1432
|
+
* Null when the template is missing or no item matches.
|
|
1433
|
+
*/
|
|
1434
|
+
function createTemplateItemSurface(options) {
|
|
1435
|
+
return ({ root, data }) => {
|
|
1436
|
+
const value = isPlainObject(data) ? data[options.key] : null;
|
|
1437
|
+
const template = root.querySelector(`template[data-template="${CSS.escape(options.template)}"]`);
|
|
1438
|
+
if (typeof value !== "string" || !template) return null;
|
|
1439
|
+
const content = template.content.cloneNode(true);
|
|
1440
|
+
let found = false;
|
|
1441
|
+
for (const item of content.querySelectorAll(`[${CSS.escape(options.attribute)}]`)) if (item.getAttribute(options.attribute) === value) found = true;
|
|
1442
|
+
else item.remove();
|
|
1443
|
+
return found ? content : null;
|
|
1141
1444
|
};
|
|
1142
1445
|
}
|
|
1143
1446
|
//#endregion
|
|
1144
|
-
export { AI_CHAT_PROTOCOL_VERSION, bindChat, createAiChatRegistry, createChatSession, parseStreamEvent, readEventStream, renderAnswerCard };
|
|
1447
|
+
export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, CARD_LIST_CLASS, CHAT_CLASS, CONTACT_CARD_CLASS, MAX_ANSWER_CARD_FACTS, MAX_ANSWER_CARD_LINKS, MAX_ANSWER_CARD_SECTIONS, MAX_ANSWER_CARD_TABLES, MAX_ANSWER_CARD_TABLE_CELLS, MAX_ANSWER_CARD_TABLE_ROWS, MAX_ANSWER_CARD_TEXT_LENGTH, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, MAX_ANSWER_CARD_URL_LENGTH, MEDIA_CARD_CLASS, bindChat, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createTemplateItemSurface, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderContactCard, renderMediaCard };
|