@vitral/chat 0.2.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/LICENSE +165 -0
- package/LICENSE.GPL +674 -0
- package/README.md +50 -0
- package/dist/chat.d.ts +32 -0
- package/dist/chat.js +302 -0
- package/dist/chat.js.map +1 -0
- package/dist/engine/index.d.ts +6 -0
- package/dist/engine/index.js +2 -0
- package/dist/engine/state.d.ts +41 -0
- package/dist/engine/state.js +81 -0
- package/dist/engine/state.js.map +1 -0
- package/dist/engine/types.d.ts +164 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +4 -0
- package/dist/render/chat.d.ts +44 -0
- package/dist/render/chat.js +197 -0
- package/dist/render/chat.js.map +1 -0
- package/package.json +57 -0
package/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# @vitral/chat
|
|
2
|
+
|
|
3
|
+
A conversation with no framework in it: the engine and a DOM renderer, which
|
|
4
|
+
the Vue, React and Angular components wrap.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
import { createChat } from '@vitral/chat';
|
|
8
|
+
|
|
9
|
+
const chat = createChat(element, {
|
|
10
|
+
messages: [{ id: 1, role: 'assistant', content: 'How can I help?' }],
|
|
11
|
+
on: {
|
|
12
|
+
send: ({ text }) => answer(text),
|
|
13
|
+
'draft-change': (draft) => chat.update({ draft })
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
chat.update({ messages });
|
|
18
|
+
chat.destroy();
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
It draws a real list — one item a message, runs of one speaker grouped so a
|
|
22
|
+
thread reads as speech rather than as rows. The log is one tab stop with a
|
|
23
|
+
roving focus inside it (the arrows move a message, Home and End jump), so a
|
|
24
|
+
thread of two hundred messages does not bury the composer behind two hundred
|
|
25
|
+
tab presses.
|
|
26
|
+
|
|
27
|
+
A message marked `streaming` grows in place with a caret after the last
|
|
28
|
+
character, and is announced only once it settles: a live region that changed on
|
|
29
|
+
every token would say nothing a screen reader could follow.
|
|
30
|
+
|
|
31
|
+
The thread follows the newest message as messages arrive, but only while the
|
|
32
|
+
reader is already at the bottom — scrolling someone away from what they were
|
|
33
|
+
reading is the one thing an auto-scrolling log must never do. When they have
|
|
34
|
+
scrolled off, a button offers to take them back.
|
|
35
|
+
|
|
36
|
+
## Shapes
|
|
37
|
+
|
|
38
|
+
`variant` decides the shape, not the colours:
|
|
39
|
+
|
|
40
|
+
| variant | for |
|
|
41
|
+
| --- | --- |
|
|
42
|
+
| `basic` | the plain thread, for a page that is the conversation |
|
|
43
|
+
| `messenger` | two people: both sides get a bubble and an avatar |
|
|
44
|
+
| `copilot` | a narrow column beside the work; no bubbles, no avatars |
|
|
45
|
+
| `agent` | an assistant that uses tools, so the steps it took are shown |
|
|
46
|
+
| `widget` | a launcher and a panel that opens over the page |
|
|
47
|
+
| `captions` | a running transcript, for speech as it is recognised |
|
|
48
|
+
|
|
49
|
+
The classes and tokens are `@vitral/styles`' `chatStyle`, so a thread follows
|
|
50
|
+
whatever preset the page is themed with.
|
package/dist/chat.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Locale } from '@vitral/core';
|
|
2
|
+
import type { ChatConfig } from './engine/types';
|
|
3
|
+
/**
|
|
4
|
+
* A conversation with no framework in it: it is handed a configuration, it
|
|
5
|
+
* draws the thread into the element it is given, and it reports what the
|
|
6
|
+
* reader did.
|
|
7
|
+
*
|
|
8
|
+
* The log is one tab stop with a roving focus inside it — the arrows move a
|
|
9
|
+
* message, Home and End jump — so a thread of two hundred messages does not
|
|
10
|
+
* bury the composer behind two hundred tab presses. A message that is still
|
|
11
|
+
* arriving grows in place with a caret after it and is announced only once it
|
|
12
|
+
* settles, because a live region that changes on every token says nothing a
|
|
13
|
+
* screen reader can follow.
|
|
14
|
+
*
|
|
15
|
+
* It scrolls to the newest message as messages arrive, but only while the
|
|
16
|
+
* reader is already at the bottom: scrolling someone away from what they were
|
|
17
|
+
* reading is the one thing an auto-scrolling log must never do. When they have
|
|
18
|
+
* scrolled off, a button offers to take them back.
|
|
19
|
+
*/
|
|
20
|
+
export interface ChatHandle {
|
|
21
|
+
element: HTMLElement;
|
|
22
|
+
update(next: Partial<ChatConfig>): void;
|
|
23
|
+
setLocale(locale: Locale): void;
|
|
24
|
+
/** Puts the caret in the composer. */
|
|
25
|
+
focus(): void;
|
|
26
|
+
/** Moves the log to the newest message. */
|
|
27
|
+
scrollToBottom(smooth?: boolean): void;
|
|
28
|
+
/** Whether the reader is at the newest message. */
|
|
29
|
+
atBottom(): boolean;
|
|
30
|
+
destroy(): void;
|
|
31
|
+
}
|
|
32
|
+
export declare function createChat(element: HTMLElement, config?: ChatConfig): ChatHandle;
|
package/dist/chat.js
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { announcementOf, messageKeyTarget } from "./engine/state.js";
|
|
2
|
+
import { chatView } from "./render/chat.js";
|
|
3
|
+
import { en, isClient, loadStyle } from "@vitral/core";
|
|
4
|
+
import { createOverlay } from "@vitral/controls";
|
|
5
|
+
import { createRoot, h, iconNode, mergeAttrs, partResolver } from "@vitral/dom";
|
|
6
|
+
import { close, getIcon, messageSquare, paperclip, registerIcons, send } from "@vitral/icons";
|
|
7
|
+
import { baseStyle, chatStyle } from "@vitral/styles";
|
|
8
|
+
//#region src/chat.ts
|
|
9
|
+
var counter = 0;
|
|
10
|
+
function createChat(element, config = {}) {
|
|
11
|
+
let current = { ...config };
|
|
12
|
+
let destroyed = false;
|
|
13
|
+
const id = current.id ?? `vt-chat-${++counter}`;
|
|
14
|
+
const root = createRoot(element);
|
|
15
|
+
const locale = () => current.locale ?? en;
|
|
16
|
+
const part = partResolver({
|
|
17
|
+
style: chatStyle,
|
|
18
|
+
unstyled: () => !!current.unstyled,
|
|
19
|
+
classes: () => current.classes,
|
|
20
|
+
pt: () => current.pt,
|
|
21
|
+
props: () => current
|
|
22
|
+
});
|
|
23
|
+
if (!current.unstyled) {
|
|
24
|
+
const options = {
|
|
25
|
+
nonce: current.nonce,
|
|
26
|
+
cssLayer: current.cssLayer
|
|
27
|
+
};
|
|
28
|
+
loadStyle(baseStyle.name, baseStyle.css, options);
|
|
29
|
+
loadStyle(chatStyle.name, chatStyle.css, options);
|
|
30
|
+
}
|
|
31
|
+
registerIcons([
|
|
32
|
+
paperclip,
|
|
33
|
+
send,
|
|
34
|
+
close,
|
|
35
|
+
messageSquare
|
|
36
|
+
]);
|
|
37
|
+
const messages = () => current.messages ?? [];
|
|
38
|
+
const variant = () => current.variant ?? "basic";
|
|
39
|
+
let logEl = null;
|
|
40
|
+
let inputEl = null;
|
|
41
|
+
let fileEl = null;
|
|
42
|
+
/** The message that holds the log's tab stop. */
|
|
43
|
+
let tabIndex = 0;
|
|
44
|
+
/** The reader has scrolled off the newest message. */
|
|
45
|
+
let away = false;
|
|
46
|
+
let announcement = "";
|
|
47
|
+
/** The last message that had settled, so a stream is announced once it stops. */
|
|
48
|
+
let announcedId = null;
|
|
49
|
+
const emit = (name, ...args) => {
|
|
50
|
+
const handler = current.on?.[name];
|
|
51
|
+
handler?.(...args);
|
|
52
|
+
};
|
|
53
|
+
/** Within a few pixels of the end: a fractional scroll height must not read as "away". */
|
|
54
|
+
const isAtBottom = (el) => el.scrollHeight - el.scrollTop - el.clientHeight < 24;
|
|
55
|
+
function send$1() {
|
|
56
|
+
if (current.disabled || current.readonly) return;
|
|
57
|
+
const text = (current.draft ?? "").trim();
|
|
58
|
+
const attachments = current.attachments ?? [];
|
|
59
|
+
if (!text && attachments.length === 0) return;
|
|
60
|
+
emit("send", {
|
|
61
|
+
text,
|
|
62
|
+
attachments
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
const actions = {
|
|
66
|
+
send: send$1,
|
|
67
|
+
draft(text) {
|
|
68
|
+
current = {
|
|
69
|
+
...current,
|
|
70
|
+
draft: text
|
|
71
|
+
};
|
|
72
|
+
grow();
|
|
73
|
+
emit("draft-change", text);
|
|
74
|
+
render();
|
|
75
|
+
},
|
|
76
|
+
inputKeydown(event) {
|
|
77
|
+
if (event.key !== "Enter") return;
|
|
78
|
+
if (!(current.sendOnEnter === false ? event.ctrlKey || event.metaKey : !event.shiftKey)) return;
|
|
79
|
+
event.preventDefault();
|
|
80
|
+
send$1();
|
|
81
|
+
},
|
|
82
|
+
logKeydown(event) {
|
|
83
|
+
const list = messages();
|
|
84
|
+
const target = messageKeyTarget(tabIndex, event.key, list.length);
|
|
85
|
+
if (target < 0 || target === tabIndex) return;
|
|
86
|
+
event.preventDefault();
|
|
87
|
+
tabIndex = target;
|
|
88
|
+
render();
|
|
89
|
+
focusTabbed();
|
|
90
|
+
},
|
|
91
|
+
focusMessage(index) {
|
|
92
|
+
if (tabIndex === index) return;
|
|
93
|
+
tabIndex = index;
|
|
94
|
+
render();
|
|
95
|
+
},
|
|
96
|
+
retry(message) {
|
|
97
|
+
emit("retry", message);
|
|
98
|
+
},
|
|
99
|
+
suggest(text) {
|
|
100
|
+
emit("suggestion", text);
|
|
101
|
+
},
|
|
102
|
+
pickFiles() {
|
|
103
|
+
fileEl?.click();
|
|
104
|
+
},
|
|
105
|
+
filesPicked(files) {
|
|
106
|
+
if (files.length) emit("attach", files);
|
|
107
|
+
if (fileEl) fileEl.value = "";
|
|
108
|
+
},
|
|
109
|
+
detach(attachment, index) {
|
|
110
|
+
emit("detach", attachment, index);
|
|
111
|
+
},
|
|
112
|
+
scrolled(el) {
|
|
113
|
+
const bottom = isAtBottom(el);
|
|
114
|
+
if (bottom === !away) return;
|
|
115
|
+
away = !bottom;
|
|
116
|
+
emit("at-bottom-change", bottom);
|
|
117
|
+
render();
|
|
118
|
+
},
|
|
119
|
+
jump() {
|
|
120
|
+
handle.scrollToBottom(true);
|
|
121
|
+
},
|
|
122
|
+
toggleOpen() {
|
|
123
|
+
const open = !current.open;
|
|
124
|
+
current = {
|
|
125
|
+
...current,
|
|
126
|
+
open
|
|
127
|
+
};
|
|
128
|
+
emit("open-change", open);
|
|
129
|
+
render();
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
/** The composer grows with what is typed, up to `maxRows`, and then scrolls. */
|
|
133
|
+
function grow() {
|
|
134
|
+
if (!inputEl) return;
|
|
135
|
+
const max = current.maxRows ?? 6;
|
|
136
|
+
inputEl.style.height = "auto";
|
|
137
|
+
const line = parseFloat(getComputedStyle(inputEl).lineHeight) || 20;
|
|
138
|
+
const padding = inputEl.offsetHeight - inputEl.clientHeight + (parseFloat(getComputedStyle(inputEl).paddingTop) || 0) * 2;
|
|
139
|
+
inputEl.style.height = `${Math.min(inputEl.scrollHeight, line * max + padding)}px`;
|
|
140
|
+
}
|
|
141
|
+
function focusTabbed() {
|
|
142
|
+
if (!isClient) return;
|
|
143
|
+
logEl?.querySelector("[tabindex=\"0\"]")?.focus();
|
|
144
|
+
}
|
|
145
|
+
const context = () => ({
|
|
146
|
+
config: current,
|
|
147
|
+
locale: locale(),
|
|
148
|
+
variant: variant(),
|
|
149
|
+
messages: messages(),
|
|
150
|
+
ids: {
|
|
151
|
+
log: `${id}-log`,
|
|
152
|
+
input: `${id}-input`,
|
|
153
|
+
message: (index) => `${id}-m${index}`
|
|
154
|
+
},
|
|
155
|
+
part,
|
|
156
|
+
tabIndex: Math.min(tabIndex, Math.max(0, messages().length - 1)),
|
|
157
|
+
away,
|
|
158
|
+
announcement,
|
|
159
|
+
on: actions,
|
|
160
|
+
refs: {
|
|
161
|
+
log: (el) => logEl = el,
|
|
162
|
+
input: (el) => inputEl = el,
|
|
163
|
+
file: (el) => fileEl = el
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
let drawing = false;
|
|
167
|
+
function render() {
|
|
168
|
+
if (destroyed || drawing) return;
|
|
169
|
+
drawing = true;
|
|
170
|
+
try {
|
|
171
|
+
const widget = variant() === "widget";
|
|
172
|
+
root.attrs(part(widget ? "widget" : "root", {
|
|
173
|
+
variant: variant(),
|
|
174
|
+
readonly: current.readonly,
|
|
175
|
+
disabled: current.disabled
|
|
176
|
+
}));
|
|
177
|
+
root.render(widget ? widgetView() : chatView(context()));
|
|
178
|
+
if (!widget) panel.close();
|
|
179
|
+
else if (current.open) (panel.isOpen ? panel.update : panel.open)();
|
|
180
|
+
else panel.close();
|
|
181
|
+
} finally {
|
|
182
|
+
drawing = false;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The widget: a launcher, and the thread in a panel that opens over the
|
|
187
|
+
* page. The shell is the handle's rather than the view's, because it is the
|
|
188
|
+
* handle that owns whether the panel is open.
|
|
189
|
+
*
|
|
190
|
+
* The panel is hung from the launcher by an overlay rather than positioned
|
|
191
|
+
* inside it. A launcher is dropped wherever an application has room, and
|
|
192
|
+
* the first ancestor with a scrollbar or a hidden overflow would otherwise
|
|
193
|
+
* cut the panel in half — which is exactly what a panel that opens over the
|
|
194
|
+
* page must never let happen.
|
|
195
|
+
*/
|
|
196
|
+
let launcherEl = null;
|
|
197
|
+
const panel = createOverlay({
|
|
198
|
+
anchor: () => launcherEl,
|
|
199
|
+
placement: "top-end",
|
|
200
|
+
offset: 12,
|
|
201
|
+
target: () => current.overlayTarget,
|
|
202
|
+
zIndex: current.zIndex,
|
|
203
|
+
render: () => h("div", mergeAttrs({ id: `${id}-panel` }, part("root", { variant: "widget" }), part("panel")), ...chatView(context())),
|
|
204
|
+
onClose: () => {
|
|
205
|
+
if (!current.open) return;
|
|
206
|
+
current = {
|
|
207
|
+
...current,
|
|
208
|
+
open: false
|
|
209
|
+
};
|
|
210
|
+
emit("open-change", false);
|
|
211
|
+
render();
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
function widgetView() {
|
|
215
|
+
const open = !!current.open;
|
|
216
|
+
const custom = current.slots?.launcher?.({ open });
|
|
217
|
+
return [h("button", mergeAttrs({
|
|
218
|
+
key: "launcher",
|
|
219
|
+
type: "button"
|
|
220
|
+
}, part("launcher"), {
|
|
221
|
+
"aria-expanded": open ? "true" : "false",
|
|
222
|
+
"aria-controls": `${id}-panel`,
|
|
223
|
+
"aria-label": open ? locale().chat.closeChat : locale().chat.openChat,
|
|
224
|
+
ref: (el) => launcherEl = el,
|
|
225
|
+
onClick: actions.toggleOpen
|
|
226
|
+
}), custom !== null && custom !== void 0 ? custom : iconNode(getIcon(open ? "x" : "messageSquare")))];
|
|
227
|
+
}
|
|
228
|
+
function afterUpdate(previous) {
|
|
229
|
+
const list = messages();
|
|
230
|
+
const last = list[list.length - 1];
|
|
231
|
+
if (last && !last.streaming && last.id !== announcedId) {
|
|
232
|
+
announcedId = last.id;
|
|
233
|
+
const author = last.author ?? (last.role === "user" ? locale().chat.message : current.ariaLabel ?? locale().chat.conversation);
|
|
234
|
+
const words = announcementOf(last, author);
|
|
235
|
+
if (words) {
|
|
236
|
+
announcement = "";
|
|
237
|
+
render();
|
|
238
|
+
Promise.resolve().then(() => {
|
|
239
|
+
if (destroyed) return;
|
|
240
|
+
announcement = words;
|
|
241
|
+
render();
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const grew = list.length > (previous.messages?.length ?? 0);
|
|
246
|
+
const streaming = !!last?.streaming;
|
|
247
|
+
if ((grew || streaming) && !away) queueMicrotask(() => handle.scrollToBottom());
|
|
248
|
+
}
|
|
249
|
+
const handle = {
|
|
250
|
+
element,
|
|
251
|
+
update(next) {
|
|
252
|
+
if (destroyed) return;
|
|
253
|
+
const previous = current;
|
|
254
|
+
current = {
|
|
255
|
+
...current,
|
|
256
|
+
...next
|
|
257
|
+
};
|
|
258
|
+
tabIndex = Math.min(tabIndex, Math.max(0, messages().length - 1));
|
|
259
|
+
render();
|
|
260
|
+
grow();
|
|
261
|
+
afterUpdate(previous);
|
|
262
|
+
},
|
|
263
|
+
setLocale(next) {
|
|
264
|
+
handle.update({ locale: next });
|
|
265
|
+
},
|
|
266
|
+
focus() {
|
|
267
|
+
inputEl?.focus();
|
|
268
|
+
},
|
|
269
|
+
scrollToBottom(smooth = false) {
|
|
270
|
+
if (!logEl) return;
|
|
271
|
+
if (typeof logEl.scrollTo === "function") logEl.scrollTo({
|
|
272
|
+
top: logEl.scrollHeight,
|
|
273
|
+
behavior: smooth ? "smooth" : "auto"
|
|
274
|
+
});
|
|
275
|
+
else logEl.scrollTop = logEl.scrollHeight;
|
|
276
|
+
if (away) {
|
|
277
|
+
away = false;
|
|
278
|
+
emit("at-bottom-change", true);
|
|
279
|
+
render();
|
|
280
|
+
}
|
|
281
|
+
},
|
|
282
|
+
atBottom: () => !away,
|
|
283
|
+
destroy() {
|
|
284
|
+
if (destroyed) return;
|
|
285
|
+
destroyed = true;
|
|
286
|
+
panel.destroy();
|
|
287
|
+
root.clear();
|
|
288
|
+
logEl = null;
|
|
289
|
+
inputEl = null;
|
|
290
|
+
fileEl = null;
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
render();
|
|
294
|
+
queueMicrotask(() => {
|
|
295
|
+
if (!destroyed) handle.scrollToBottom();
|
|
296
|
+
});
|
|
297
|
+
return handle;
|
|
298
|
+
}
|
|
299
|
+
//#endregion
|
|
300
|
+
export { createChat };
|
|
301
|
+
|
|
302
|
+
//# sourceMappingURL=chat.js.map
|
package/dist/chat.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat.js","names":[],"sources":["../src/chat.ts"],"sourcesContent":["import { en, isClient, loadStyle, type Locale } from '@vitral/core';\nimport { createOverlay } from '@vitral/controls';\nimport { createRoot, h, iconNode, mergeAttrs, partResolver, type Child, type VElement } from '@vitral/dom';\n// Aliased: this module has a `send` of its own, and a bare `x` reads as a variable.\nimport { close as closeIcon, getIcon, messageSquare as messageSquareIcon, paperclip as paperclipIcon, registerIcons, send as sendIcon } from '@vitral/icons';\nimport { baseStyle, chatStyle } from '@vitral/styles';\nimport { announcementOf, messageKeyTarget, showsAvatars } from './engine/state';\nimport type { ChatAttachment, ChatConfig, ChatMessage, ChatVariant } from './engine/types';\nimport { chatView, type ChatActions, type ViewContext } from './render/chat';\n\n/**\n * A conversation with no framework in it: it is handed a configuration, it\n * draws the thread into the element it is given, and it reports what the\n * reader did.\n *\n * The log is one tab stop with a roving focus inside it — the arrows move a\n * message, Home and End jump — so a thread of two hundred messages does not\n * bury the composer behind two hundred tab presses. A message that is still\n * arriving grows in place with a caret after it and is announced only once it\n * settles, because a live region that changes on every token says nothing a\n * screen reader can follow.\n *\n * It scrolls to the newest message as messages arrive, but only while the\n * reader is already at the bottom: scrolling someone away from what they were\n * reading is the one thing an auto-scrolling log must never do. When they have\n * scrolled off, a button offers to take them back.\n */\n\nexport interface ChatHandle {\n element: HTMLElement;\n update(next: Partial<ChatConfig>): void;\n setLocale(locale: Locale): void;\n /** Puts the caret in the composer. */\n focus(): void;\n /** Moves the log to the newest message. */\n scrollToBottom(smooth?: boolean): void;\n /** Whether the reader is at the newest message. */\n atBottom(): boolean;\n destroy(): void;\n}\n\nlet counter = 0;\n\nexport function createChat(element: HTMLElement, config: ChatConfig = {}): ChatHandle {\n let current: ChatConfig = { ...config };\n let destroyed = false;\n\n const id = current.id ?? `vt-chat-${++counter}`;\n const root = createRoot(element);\n const locale = (): Locale => current.locale ?? en;\n const part = partResolver({\n style: chatStyle,\n unstyled: () => !!current.unstyled,\n classes: () => current.classes,\n pt: () => current.pt,\n props: () => current as Record<string, unknown>\n });\n\n if (!current.unstyled) {\n const options = { nonce: current.nonce, cssLayer: current.cssLayer };\n loadStyle(baseStyle.name, baseStyle.css, options);\n loadStyle(chatStyle.name, chatStyle.css, options);\n }\n\n // The composer and the launcher draw icons that are not in the base set,\n // so the addon brings its own rather than leaving an application to work\n // out which names it has to register before a chat will draw.\n registerIcons([paperclipIcon, sendIcon, closeIcon, messageSquareIcon]);\n\n // ---- what is on screen\n\n const messages = (): ChatMessage[] => current.messages ?? [];\n const variant = (): ChatVariant => current.variant ?? 'basic';\n\n let logEl: HTMLElement | null = null;\n let inputEl: HTMLTextAreaElement | null = null;\n let fileEl: HTMLInputElement | null = null;\n /** The message that holds the log's tab stop. */\n let tabIndex = 0;\n /** The reader has scrolled off the newest message. */\n let away = false;\n let announcement = '';\n /** The last message that had settled, so a stream is announced once it stops. */\n let announcedId: string | number | null = null;\n\n const emit = <K extends keyof NonNullable<ChatConfig['on']>>(name: K, ...args: Parameters<NonNullable<NonNullable<ChatConfig['on']>[K]>>) => {\n const handler = current.on?.[name] as ((...a: unknown[]) => void) | undefined;\n handler?.(...(args as unknown[]));\n };\n\n /** Within a few pixels of the end: a fractional scroll height must not read as \"away\". */\n const isAtBottom = (el: HTMLElement) => el.scrollHeight - el.scrollTop - el.clientHeight < 24;\n\n // ---- what the reader does\n\n function send() {\n if (current.disabled || current.readonly) return;\n const text = (current.draft ?? '').trim();\n const attachments = current.attachments ?? [];\n if (!text && attachments.length === 0) return;\n emit('send', { text, attachments });\n }\n\n const actions: ChatActions = {\n send,\n draft(text) {\n current = { ...current, draft: text };\n grow();\n emit('draft-change', text);\n render();\n },\n inputKeydown(event) {\n if (event.key !== 'Enter') return;\n // Enter sends and Shift+Enter breaks the line, unless the chat was\n // told otherwise — in which case the two swap over.\n const sends = current.sendOnEnter === false ? event.ctrlKey || event.metaKey : !event.shiftKey;\n if (!sends) return;\n event.preventDefault();\n send();\n },\n logKeydown(event) {\n const list = messages();\n const target = messageKeyTarget(tabIndex, event.key, list.length);\n if (target < 0 || target === tabIndex) return;\n event.preventDefault();\n tabIndex = target;\n render();\n focusTabbed();\n },\n focusMessage(index) {\n if (tabIndex === index) return;\n tabIndex = index;\n render();\n },\n retry(message) {\n emit('retry', message);\n },\n suggest(text) {\n emit('suggestion', text);\n },\n pickFiles() {\n fileEl?.click();\n },\n filesPicked(files) {\n if (files.length) emit('attach', files);\n // Cleared, or choosing the same file twice never fires again.\n if (fileEl) fileEl.value = '';\n },\n detach(attachment, index) {\n emit('detach', attachment, index);\n },\n scrolled(el) {\n const bottom = isAtBottom(el);\n if (bottom === !away) return;\n away = !bottom;\n emit('at-bottom-change', bottom);\n render();\n },\n jump() {\n handle.scrollToBottom(true);\n },\n toggleOpen() {\n const open = !current.open;\n current = { ...current, open };\n emit('open-change', open);\n render();\n }\n };\n\n /** The composer grows with what is typed, up to `maxRows`, and then scrolls. */\n function grow() {\n if (!inputEl) return;\n const max = current.maxRows ?? 6;\n inputEl.style.height = 'auto';\n const line = parseFloat(getComputedStyle(inputEl).lineHeight) || 20;\n const padding = inputEl.offsetHeight - inputEl.clientHeight + (parseFloat(getComputedStyle(inputEl).paddingTop) || 0) * 2;\n inputEl.style.height = `${Math.min(inputEl.scrollHeight, line * max + padding)}px`;\n }\n\n function focusTabbed() {\n if (!isClient) return;\n logEl?.querySelector<HTMLElement>('[tabindex=\"0\"]')?.focus();\n }\n\n // ---- drawing\n\n const context = (): ViewContext => ({\n config: current,\n locale: locale(),\n variant: variant(),\n messages: messages(),\n ids: { log: `${id}-log`, input: `${id}-input`, message: (index) => `${id}-m${index}` },\n part,\n tabIndex: Math.min(tabIndex, Math.max(0, messages().length - 1)),\n away,\n announcement,\n on: actions,\n refs: {\n log: (el) => (logEl = el as HTMLElement | null),\n input: (el) => (inputEl = el as HTMLTextAreaElement | null),\n file: (el) => (fileEl = el as HTMLInputElement | null)\n }\n });\n\n let drawing = false;\n function render() {\n if (destroyed || drawing) return;\n drawing = true;\n try {\n const widget = variant() === 'widget';\n root.attrs(part(widget ? 'widget' : 'root', { variant: variant(), readonly: current.readonly, disabled: current.disabled }));\n root.render(widget ? widgetView() : chatView(context()));\n if (!widget) panel.close();\n else if (current.open) (panel.isOpen ? panel.update : panel.open)();\n else panel.close();\n } finally {\n drawing = false;\n }\n }\n\n /**\n * The widget: a launcher, and the thread in a panel that opens over the\n * page. The shell is the handle's rather than the view's, because it is the\n * handle that owns whether the panel is open.\n *\n * The panel is hung from the launcher by an overlay rather than positioned\n * inside it. A launcher is dropped wherever an application has room, and\n * the first ancestor with a scrollbar or a hidden overflow would otherwise\n * cut the panel in half — which is exactly what a panel that opens over the\n * page must never let happen.\n */\n let launcherEl: HTMLElement | null = null;\n const panel = createOverlay({\n anchor: () => launcherEl,\n placement: 'top-end',\n offset: 12,\n target: () => current.overlayTarget,\n zIndex: current.zIndex,\n render: () => h('div', mergeAttrs({ id: `${id}-panel` }, part('root', { variant: 'widget' }), part('panel')), ...chatView(context())) as VElement,\n onClose: () => {\n if (!current.open) return;\n current = { ...current, open: false };\n emit('open-change', false);\n render();\n }\n });\n\n function widgetView(): Child[] {\n const open = !!current.open;\n const custom = current.slots?.launcher?.({ open });\n return [\n h(\n 'button',\n mergeAttrs({ key: 'launcher', type: 'button' }, part('launcher'), {\n 'aria-expanded': open ? 'true' : 'false',\n 'aria-controls': `${id}-panel`,\n 'aria-label': open ? locale().chat.closeChat : locale().chat.openChat,\n ref: (el: Element | null) => (launcherEl = el as HTMLElement | null),\n onClick: actions.toggleOpen\n }),\n custom !== null && custom !== undefined ? (custom as Child) : iconNode(getIcon(open ? 'x' : 'messageSquare'))\n )\n ];\n }\n\n // ---- what changed\n\n function afterUpdate(previous: ChatConfig) {\n const list = messages();\n const last = list[list.length - 1];\n\n // A message is announced once it has settled, not while it streams.\n if (last && !last.streaming && last.id !== announcedId) {\n announcedId = last.id;\n const author = last.author ?? (last.role === 'user' ? locale().chat.message : (current.ariaLabel ?? locale().chat.conversation));\n const words = announcementOf(last, author);\n if (words) {\n announcement = '';\n render();\n Promise.resolve().then(() => {\n if (destroyed) return;\n announcement = words;\n render();\n });\n }\n }\n\n // Follow the newest message, but only for a reader who was already there.\n const grew = list.length > (previous.messages?.length ?? 0);\n const streaming = !!last?.streaming;\n if ((grew || streaming) && !away) queueMicrotask(() => handle.scrollToBottom());\n }\n\n const handle: ChatHandle = {\n element,\n update(next) {\n if (destroyed) return;\n const previous = current;\n current = { ...current, ...next };\n // A thread that got shorter must not keep a tab stop past its end.\n tabIndex = Math.min(tabIndex, Math.max(0, messages().length - 1));\n render();\n grow();\n afterUpdate(previous);\n },\n setLocale(next) {\n handle.update({ locale: next });\n },\n focus() {\n inputEl?.focus();\n },\n scrollToBottom(smooth = false) {\n if (!logEl) return;\n // `scrollTo` with options is not everywhere — jsdom has no scrollTo\n // on an element at all — and this runs from a microtask, where a\n // throw goes unhandled and takes the next render with it.\n if (typeof logEl.scrollTo === 'function') logEl.scrollTo({ top: logEl.scrollHeight, behavior: smooth ? 'smooth' : 'auto' });\n else logEl.scrollTop = logEl.scrollHeight;\n if (away) {\n away = false;\n emit('at-bottom-change', true);\n render();\n }\n },\n atBottom: () => !away,\n destroy() {\n if (destroyed) return;\n destroyed = true;\n panel.destroy();\n root.clear();\n logEl = null;\n inputEl = null;\n fileEl = null;\n }\n };\n\n render();\n // The thread opens at its newest message, which is where a conversation is read from.\n queueMicrotask(() => {\n if (!destroyed) handle.scrollToBottom();\n });\n return handle;\n}\n"],"mappings":";;;;;;;;AAyCA,IAAI,UAAU;AAEd,SAAgB,WAAW,SAAsB,SAAqB,CAAC,GAAe;CAClF,IAAI,UAAsB,EAAE,GAAG,OAAO;CACtC,IAAI,YAAY;CAEhB,MAAM,KAAK,QAAQ,MAAM,WAAW,EAAE;CACtC,MAAM,OAAO,WAAW,OAAO;CAC/B,MAAM,eAAuB,QAAQ,UAAU;CAC/C,MAAM,OAAO,aAAa;EACtB,OAAO;EACP,gBAAgB,CAAC,CAAC,QAAQ;EAC1B,eAAe,QAAQ;EACvB,UAAU,QAAQ;EAClB,aAAa;CACjB,CAAC;CAED,IAAI,CAAC,QAAQ,UAAU;EACnB,MAAM,UAAU;GAAE,OAAO,QAAQ;GAAO,UAAU,QAAQ;EAAS;EACnE,UAAU,UAAU,MAAM,UAAU,KAAK,OAAO;EAChD,UAAU,UAAU,MAAM,UAAU,KAAK,OAAO;CACpD;CAKA,cAAc;EAAC;EAAe;EAAU;EAAW;CAAiB,CAAC;CAIrE,MAAM,iBAAgC,QAAQ,YAAY,CAAC;CAC3D,MAAM,gBAA6B,QAAQ,WAAW;CAEtD,IAAI,QAA4B;CAChC,IAAI,UAAsC;CAC1C,IAAI,SAAkC;;CAEtC,IAAI,WAA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c,UAAU,SAAS,WAAW;GAAO,CAAC;QACrH,MAAM,YAAY,MAAM;GAC7B,IAAI,MAAM;IACN,OAAO;IACP,KAAK,oBAAoB,IAAI;IAC7B,OAAO;GACX;EACJ;EACA,gBAAgB,CAAC;EACjB,UAAU;GACN,IAAI,WAAW;GACf,YAAY;GACZ,MAAM,QAAQ;GACd,KAAK,MAAM;GACX,QAAQ;GACR,UAAU;GACV,SAAS;EACb;CACJ;CAEA,OAAO;CAEP,qBAAqB;EACjB,IAAI,CAAC,WAAW,OAAO,eAAe;CAC1C,CAAC;CACD,OAAO;AACX"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { ChatMessage, ChatVariant } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* What to draw, worked out from what the chat was told. No DOM in it, so
|
|
4
|
+
* another renderer — or a test — can use the same answers.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* A run of messages from the same speaker, uninterrupted. The avatar and the
|
|
8
|
+
* name are drawn once for the run rather than once a message, which is what
|
|
9
|
+
* makes a thread read as speech instead of as a list.
|
|
10
|
+
*/
|
|
11
|
+
export interface ChatGroup {
|
|
12
|
+
/** Where the run starts in `messages`. */
|
|
13
|
+
start: number;
|
|
14
|
+
messages: ChatMessage[];
|
|
15
|
+
}
|
|
16
|
+
/** Two messages belong to one run when the same speaker sent them both. */
|
|
17
|
+
export declare function groupMessages(messages: readonly ChatMessage[]): ChatGroup[];
|
|
18
|
+
/** Which side a message sits on. A system note takes neither. */
|
|
19
|
+
export declare const sideOf: (role: ChatMessage["role"]) => "own" | "other" | "none";
|
|
20
|
+
/** The initials to fall back to when a speaker has no picture. */
|
|
21
|
+
export declare function initialsOf(message: ChatMessage): string;
|
|
22
|
+
/** A file's size in the units a person reads, or nothing when it is unknown. */
|
|
23
|
+
export declare function formatSize(bytes: number | undefined): string | undefined;
|
|
24
|
+
/** Which variants draw an avatar beside a message. */
|
|
25
|
+
export declare const showsAvatars: (variant: ChatVariant) => boolean;
|
|
26
|
+
/** Which variants put the words in a bubble rather than running them down the page. */
|
|
27
|
+
export declare const showsBubbles: (variant: ChatVariant) => boolean;
|
|
28
|
+
/**
|
|
29
|
+
* The message the tab stop belongs to after a key. The log is one tab stop and
|
|
30
|
+
* the arrows move inside it, so a long thread does not bury the composer
|
|
31
|
+
* behind a hundred tab presses.
|
|
32
|
+
*
|
|
33
|
+
* Returns the index to move to, or -1 when the key is not one of ours.
|
|
34
|
+
*/
|
|
35
|
+
export declare function messageKeyTarget(current: number, key: string, count: number): number;
|
|
36
|
+
/**
|
|
37
|
+
* What a screen reader is told once a message settles. A streaming message is
|
|
38
|
+
* announced when it stops, not while it grows: a live region that changes on
|
|
39
|
+
* every token says nothing anyone can follow.
|
|
40
|
+
*/
|
|
41
|
+
export declare function announcementOf(message: ChatMessage | undefined, author: string): string;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
//#region src/engine/state.ts
|
|
2
|
+
/** Two messages belong to one run when the same speaker sent them both. */
|
|
3
|
+
function groupMessages(messages) {
|
|
4
|
+
const groups = [];
|
|
5
|
+
messages.forEach((message, index) => {
|
|
6
|
+
const last = groups[groups.length - 1];
|
|
7
|
+
const previous = last?.messages[last.messages.length - 1];
|
|
8
|
+
if (previous && message.role !== "system" && previous.role === message.role && (previous.author ?? "") === (message.author ?? "")) last.messages.push(message);
|
|
9
|
+
else groups.push({
|
|
10
|
+
start: index,
|
|
11
|
+
messages: [message]
|
|
12
|
+
});
|
|
13
|
+
});
|
|
14
|
+
return groups;
|
|
15
|
+
}
|
|
16
|
+
/** Which side a message sits on. A system note takes neither. */
|
|
17
|
+
var sideOf = (role) => role === "user" ? "own" : role === "assistant" ? "other" : "none";
|
|
18
|
+
/** The initials to fall back to when a speaker has no picture. */
|
|
19
|
+
function initialsOf(message) {
|
|
20
|
+
if (message.initials) return message.initials;
|
|
21
|
+
const name = message.author?.trim();
|
|
22
|
+
if (!name) return message.role === "user" ? "You" : message.role === "assistant" ? "AI" : "";
|
|
23
|
+
const parts = name.split(/\s+/).filter(Boolean);
|
|
24
|
+
return parts.length > 1 ? `${parts[0][0]}${parts[parts.length - 1][0]}`.toUpperCase() : name.slice(0, 2).toUpperCase();
|
|
25
|
+
}
|
|
26
|
+
/** A file's size in the units a person reads, or nothing when it is unknown. */
|
|
27
|
+
function formatSize(bytes) {
|
|
28
|
+
if (bytes === void 0 || !Number.isFinite(bytes) || bytes < 0) return void 0;
|
|
29
|
+
if (bytes < 1e3) return `${bytes} B`;
|
|
30
|
+
const units = [
|
|
31
|
+
"kB",
|
|
32
|
+
"MB",
|
|
33
|
+
"GB",
|
|
34
|
+
"TB"
|
|
35
|
+
];
|
|
36
|
+
let value = bytes / 1e3;
|
|
37
|
+
let unit = 0;
|
|
38
|
+
while (value >= 1e3 && unit < units.length - 1) {
|
|
39
|
+
value /= 1e3;
|
|
40
|
+
unit++;
|
|
41
|
+
}
|
|
42
|
+
return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
|
|
43
|
+
}
|
|
44
|
+
/** Which variants draw an avatar beside a message. */
|
|
45
|
+
var showsAvatars = (variant) => variant === "basic" || variant === "messenger" || variant === "agent" || variant === "widget";
|
|
46
|
+
/** Which variants put the words in a bubble rather than running them down the page. */
|
|
47
|
+
var showsBubbles = (variant) => variant !== "captions" && variant !== "copilot";
|
|
48
|
+
/**
|
|
49
|
+
* The message the tab stop belongs to after a key. The log is one tab stop and
|
|
50
|
+
* the arrows move inside it, so a long thread does not bury the composer
|
|
51
|
+
* behind a hundred tab presses.
|
|
52
|
+
*
|
|
53
|
+
* Returns the index to move to, or -1 when the key is not one of ours.
|
|
54
|
+
*/
|
|
55
|
+
function messageKeyTarget(current, key, count) {
|
|
56
|
+
if (count === 0) return -1;
|
|
57
|
+
const clamp = (i) => Math.max(0, Math.min(count - 1, i));
|
|
58
|
+
switch (key) {
|
|
59
|
+
case "ArrowDown": return clamp(current + 1);
|
|
60
|
+
case "ArrowUp": return clamp(current - 1);
|
|
61
|
+
case "Home": return 0;
|
|
62
|
+
case "End": return count - 1;
|
|
63
|
+
case "PageDown": return clamp(current + 5);
|
|
64
|
+
case "PageUp": return clamp(current - 5);
|
|
65
|
+
default: return -1;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* What a screen reader is told once a message settles. A streaming message is
|
|
70
|
+
* announced when it stops, not while it grows: a live region that changes on
|
|
71
|
+
* every token says nothing anyone can follow.
|
|
72
|
+
*/
|
|
73
|
+
function announcementOf(message, author) {
|
|
74
|
+
if (!message || message.streaming) return "";
|
|
75
|
+
if (message.error) return `${author}: ${message.error}`;
|
|
76
|
+
return message.content ? `${author}: ${message.content}` : "";
|
|
77
|
+
}
|
|
78
|
+
//#endregion
|
|
79
|
+
export { announcementOf, formatSize, groupMessages, initialsOf, messageKeyTarget, showsAvatars, showsBubbles, sideOf };
|
|
80
|
+
|
|
81
|
+
//# sourceMappingURL=state.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"state.js","names":[],"sources":["../../src/engine/state.ts"],"sourcesContent":["import type { ChatMessage, ChatVariant } from './types';\n\n/**\n * What to draw, worked out from what the chat was told. No DOM in it, so\n * another renderer — or a test — can use the same answers.\n */\n\n/**\n * A run of messages from the same speaker, uninterrupted. The avatar and the\n * name are drawn once for the run rather than once a message, which is what\n * makes a thread read as speech instead of as a list.\n */\nexport interface ChatGroup {\n /** Where the run starts in `messages`. */\n start: number;\n messages: ChatMessage[];\n}\n\n/** Two messages belong to one run when the same speaker sent them both. */\nexport function groupMessages(messages: readonly ChatMessage[]): ChatGroup[] {\n const groups: ChatGroup[] = [];\n messages.forEach((message, index) => {\n const last = groups[groups.length - 1];\n const previous = last?.messages[last.messages.length - 1];\n // A system note never joins a run: it is about the conversation, not\n // part of it.\n const joins = previous && message.role !== 'system' && previous.role === message.role && (previous.author ?? '') === (message.author ?? '');\n if (joins) last!.messages.push(message);\n else groups.push({ start: index, messages: [message] });\n });\n return groups;\n}\n\n/** Which side a message sits on. A system note takes neither. */\nexport const sideOf = (role: ChatMessage['role']): 'own' | 'other' | 'none' => (role === 'user' ? 'own' : role === 'assistant' ? 'other' : 'none');\n\n/** The initials to fall back to when a speaker has no picture. */\nexport function initialsOf(message: ChatMessage): string {\n if (message.initials) return message.initials;\n const name = message.author?.trim();\n if (!name) return message.role === 'user' ? 'You' : message.role === 'assistant' ? 'AI' : '';\n const parts = name.split(/\\s+/).filter(Boolean);\n return parts.length > 1 ? `${parts[0]![0]}${parts[parts.length - 1]![0]}`.toUpperCase() : name.slice(0, 2).toUpperCase();\n}\n\n/** A file's size in the units a person reads, or nothing when it is unknown. */\nexport function formatSize(bytes: number | undefined): string | undefined {\n if (bytes === undefined || !Number.isFinite(bytes) || bytes < 0) return undefined;\n if (bytes < 1000) return `${bytes} B`;\n const units = ['kB', 'MB', 'GB', 'TB'];\n let value = bytes / 1000;\n let unit = 0;\n while (value >= 1000 && unit < units.length - 1) {\n value /= 1000;\n unit++;\n }\n return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;\n}\n\n/** Which variants draw an avatar beside a message. */\nexport const showsAvatars = (variant: ChatVariant): boolean => variant === 'basic' || variant === 'messenger' || variant === 'agent' || variant === 'widget';\n\n/** Which variants put the words in a bubble rather than running them down the page. */\nexport const showsBubbles = (variant: ChatVariant): boolean => variant !== 'captions' && variant !== 'copilot';\n\n/**\n * The message the tab stop belongs to after a key. The log is one tab stop and\n * the arrows move inside it, so a long thread does not bury the composer\n * behind a hundred tab presses.\n *\n * Returns the index to move to, or -1 when the key is not one of ours.\n */\nexport function messageKeyTarget(current: number, key: string, count: number): number {\n if (count === 0) return -1;\n const clamp = (i: number) => Math.max(0, Math.min(count - 1, i));\n switch (key) {\n case 'ArrowDown':\n return clamp(current + 1);\n case 'ArrowUp':\n return clamp(current - 1);\n case 'Home':\n return 0;\n case 'End':\n return count - 1;\n case 'PageDown':\n return clamp(current + 5);\n case 'PageUp':\n return clamp(current - 5);\n default:\n return -1;\n }\n}\n\n/**\n * What a screen reader is told once a message settles. A streaming message is\n * announced when it stops, not while it grows: a live region that changes on\n * every token says nothing anyone can follow.\n */\nexport function announcementOf(message: ChatMessage | undefined, author: string): string {\n if (!message || message.streaming) return '';\n if (message.error) return `${author}: ${message.error}`;\n return message.content ? `${author}: ${message.content}` : '';\n}\n"],"mappings":";;AAmBA,SAAgB,cAAc,UAA+C;CACzE,MAAM,SAAsB,CAAC;CAC7B,SAAS,SAAS,SAAS,UAAU;EACjC,MAAM,OAAO,OAAO,OAAO,SAAS;EACpC,MAAM,WAAW,MAAM,SAAS,KAAK,SAAS,SAAS;EAIvD,IADc,YAAY,QAAQ,SAAS,YAAY,SAAS,SAAS,QAAQ,SAAS,SAAS,UAAU,SAAS,QAAQ,UAAU,KAC7H,KAAM,SAAS,KAAK,OAAO;OACjC,OAAO,KAAK;GAAE,OAAO;GAAO,UAAU,CAAC,OAAO;EAAE,CAAC;CAC1D,CAAC;CACD,OAAO;AACX;;AAGA,IAAa,UAAU,SAAyD,SAAS,SAAS,QAAQ,SAAS,cAAc,UAAU;;AAG3I,SAAgB,WAAW,SAA8B;CACrD,IAAI,QAAQ,UAAU,OAAO,QAAQ;CACrC,MAAM,OAAO,QAAQ,QAAQ,KAAK;CAClC,IAAI,CAAC,MAAM,OAAO,QAAQ,SAAS,SAAS,QAAQ,QAAQ,SAAS,cAAc,OAAO;CAC1F,MAAM,QAAQ,KAAK,MAAM,KAAK,CAAC,CAAC,OAAO,OAAO;CAC9C,OAAO,MAAM,SAAS,IAAI,GAAG,MAAM,EAAE,CAAE,KAAK,MAAM,MAAM,SAAS,EAAE,CAAE,KAAK,YAAY,IAAI,KAAK,MAAM,GAAG,CAAC,CAAC,CAAC,YAAY;AAC3H;;AAGA,SAAgB,WAAW,OAA+C;CACtE,IAAI,UAAU,KAAA,KAAa,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GAAG,OAAO,KAAA;CACxE,IAAI,QAAQ,KAAM,OAA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