-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathBotBubble.tsx
More file actions
495 lines (465 loc) · 18.7 KB
/
BotBubble.tsx
File metadata and controls
495 lines (465 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
import { createEffect, Show, createSignal, onMount, For } from 'solid-js';
import { Avatar } from '../avatars/Avatar';
import { Marked } from '@ts-stack/markdown';
import { FeedbackRatingType, sendFeedbackQuery, sendFileDownloadQuery, updateFeedbackQuery } from '@/queries/sendMessageQuery';
import { FileUpload, IAction, MessageType } from '../Bot';
import { CopyToClipboardButton, ThumbsDownButton, ThumbsUpButton } from '../buttons/FeedbackButtons';
import FeedbackContentDialog from '../FeedbackContentDialog';
import { AgentReasoningBubble } from './AgentReasoningBubble';
import { TickIcon, XIcon } from '../icons';
import { SourceBubble } from '../bubbles/SourceBubble';
import { DateTimeToggleTheme } from '@/features/bubble/types';
type Props = {
message: MessageType;
chatflowid: string;
chatId: string;
apiHost?: string;
onRequest?: (request: RequestInit) => Promise<void>;
fileAnnotations?: any;
showAvatar?: boolean;
avatarSrc?: string;
backgroundColor?: string;
textColor?: string;
chatFeedbackStatus?: boolean;
fontSize?: number;
feedbackColor?: string;
isLoading: boolean;
dateTimeToggle?: DateTimeToggleTheme;
showAgentMessages?: boolean;
sourceDocsTitle?: string;
renderHTML?: boolean;
handleActionClick: (label: string, action: IAction | undefined | null) => void;
handleSourceDocumentsClick: (src: any) => void;
};
const defaultBackgroundColor = '#f7f8ff';
const defaultTextColor = '#303235';
const defaultFontSize = 16;
const defaultFeedbackColor = '#3B81F6';
export const BotBubble = (props: Props) => {
let botMessageEl: HTMLDivElement | undefined;
let botDetailsEl: HTMLDetailsElement | undefined;
Marked.setOptions({ isNoP: true, sanitize: props.renderHTML !== undefined ? !props.renderHTML : true });
const [rating, setRating] = createSignal('');
const [feedbackId, setFeedbackId] = createSignal('');
const [showFeedbackContentDialog, setShowFeedbackContentModal] = createSignal(false);
const [copiedMessage, setCopiedMessage] = createSignal(false);
const [thumbsUpColor, setThumbsUpColor] = createSignal(props.feedbackColor ?? defaultFeedbackColor); // default color
const [thumbsDownColor, setThumbsDownColor] = createSignal(props.feedbackColor ?? defaultFeedbackColor); // default color
const downloadFile = async (fileAnnotation: any) => {
try {
const response = await sendFileDownloadQuery({
apiHost: props.apiHost,
body: { fileName: fileAnnotation.fileName, chatflowId: props.chatflowid, chatId: props.chatId } as any,
onRequest: props.onRequest,
});
const blob = new Blob([response.data]);
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = fileAnnotation.fileName;
document.body.appendChild(link);
link.click();
link.remove();
} catch (error) {
console.error('Download failed:', error);
}
};
const copyMessageToClipboard = async () => {
try {
const text = botMessageEl ? botMessageEl?.textContent : '';
await navigator.clipboard.writeText(text || '');
setCopiedMessage(true);
setTimeout(() => {
setCopiedMessage(false);
}, 2000); // Hide the message after 2 seconds
} catch (error) {
console.error('Error copying to clipboard:', error);
}
};
const saveToLocalStorage = (rating: FeedbackRatingType) => {
const chatDetails = localStorage.getItem(`${props.chatflowid}_EXTERNAL`);
if (!chatDetails) return;
try {
const parsedDetails = JSON.parse(chatDetails);
const messages: MessageType[] = parsedDetails.chatHistory || [];
const message = messages.find((msg) => msg.messageId === props.message.messageId);
if (!message) return;
message.rating = rating;
localStorage.setItem(`${props.chatflowid}_EXTERNAL`, JSON.stringify({ ...parsedDetails, chatHistory: messages }));
} catch (e) {
return;
}
};
const isValidURL = (url: string): URL | undefined => {
try {
return new URL(url);
} catch (err) {
return undefined;
}
};
const removeDuplicateURL = (message: MessageType) => {
const visitedURLs: string[] = [];
const newSourceDocuments: any = [];
message.sourceDocuments.forEach((source: any) => {
if (isValidURL(source.metadata.source) && !visitedURLs.includes(source.metadata.source)) {
visitedURLs.push(source.metadata.source);
newSourceDocuments.push(source);
} else if (!isValidURL(source.metadata.source)) {
newSourceDocuments.push(source);
}
});
return newSourceDocuments;
};
const onThumbsUpClick = async () => {
if (rating() === '') {
const body = {
chatflowid: props.chatflowid,
chatId: props.chatId,
messageId: props.message?.messageId as string,
rating: 'THUMBS_UP' as FeedbackRatingType,
content: '',
};
const result = await sendFeedbackQuery({
chatflowid: props.chatflowid,
apiHost: props.apiHost,
body,
onRequest: props.onRequest,
});
if (result.data) {
const data = result.data as any;
let id = '';
if (data && data.id) id = data.id;
setRating('THUMBS_UP');
setFeedbackId(id);
setShowFeedbackContentModal(true);
// update the thumbs up color state
setThumbsUpColor('#006400');
saveToLocalStorage('THUMBS_UP');
}
}
};
const onThumbsDownClick = async () => {
if (rating() === '') {
const body = {
chatflowid: props.chatflowid,
chatId: props.chatId,
messageId: props.message?.messageId as string,
rating: 'THUMBS_DOWN' as FeedbackRatingType,
content: '',
};
const result = await sendFeedbackQuery({
chatflowid: props.chatflowid,
apiHost: props.apiHost,
body,
onRequest: props.onRequest,
});
if (result.data) {
const data = result.data as any;
let id = '';
if (data && data.id) id = data.id;
setRating('THUMBS_DOWN');
setFeedbackId(id);
setShowFeedbackContentModal(true);
// update the thumbs down color state
setThumbsDownColor('#8B0000');
saveToLocalStorage('THUMBS_DOWN');
}
}
};
const submitFeedbackContent = async (text: string) => {
const body = {
content: text,
};
const result = await updateFeedbackQuery({
id: feedbackId(),
apiHost: props.apiHost,
body,
onRequest: props.onRequest,
});
if (result.data) {
setFeedbackId('');
setShowFeedbackContentModal(false);
}
};
onMount(() => {
if (botMessageEl) {
botMessageEl.innerHTML = Marked.parse(props.message.message);
botMessageEl.querySelectorAll('a').forEach((link) => {
link.target = '_blank';
});
if (props.message.rating) {
setRating(props.message.rating);
if (props.message.rating === 'THUMBS_UP') {
setThumbsUpColor('#006400');
} else if (props.message.rating === 'THUMBS_DOWN') {
setThumbsDownColor('#8B0000');
}
}
if (props.fileAnnotations && props.fileAnnotations.length) {
for (const annotations of props.fileAnnotations) {
const button = document.createElement('button');
button.textContent = annotations.fileName;
button.className =
'py-2 px-4 mb-2 justify-center font-semibold text-white focus:outline-none flex items-center disabled:opacity-50 disabled:cursor-not-allowed disabled:brightness-100 transition-all filter hover:brightness-90 active:brightness-75 file-annotation-button';
button.addEventListener('click', function () {
downloadFile(annotations);
});
const svgContainer = document.createElement('div');
svgContainer.className = 'ml-2';
svgContainer.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-download" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="#ffffff" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2" /><path d="M7 11l5 5l5 -5" /><path d="M12 4l0 12" /></svg>`;
button.appendChild(svgContainer);
botMessageEl.appendChild(button);
}
}
}
if (botDetailsEl && props.isLoading) {
botDetailsEl.open = true;
}
});
createEffect(() => {
if (botDetailsEl && props.isLoading) {
botDetailsEl.open = true;
} else if (botDetailsEl && !props.isLoading) {
botDetailsEl.open = false;
}
});
const renderArtifacts = (item: Partial<FileUpload>) => {
return (
<>
<Show when={item.type === 'png' || item.type === 'jpeg'}>
<div class="flex items-center justify-center p-0 m-0">
<img
class="w-full h-full bg-cover"
src={(() => {
const isFileStorage = typeof item.data === 'string' && item.data.startsWith('FILE-STORAGE::');
return isFileStorage
? `${props.apiHost}/api/v1/get-upload-file?chatflowId=${props.chatflowid}&chatId=${props.chatId}&fileName=${(
item.data as string
).replace('FILE-STORAGE::', '')}`
: (item.data as string);
})()}
/>
</div>
</Show>
<Show when={item.type === 'html'}>
<div class="mt-2">
<div innerHTML={item.data as string} />
</div>
</Show>
<Show when={item.type !== 'png' && item.type !== 'jpeg' && item.type !== 'html'}>
<span
innerHTML={Marked.parse(item.data as string)}
class="prose"
style={{
'background-color': props.backgroundColor ?? defaultBackgroundColor,
color: props.textColor ?? defaultTextColor,
'border-radius': '6px',
'font-size': props.fontSize ? `${props.fontSize}px` : `${defaultFontSize}px`,
}}
/>
</Show>
</>
);
};
const formatDateTime = (dateTimeString: string | undefined, showDate: boolean | undefined, showTime: boolean | undefined) => {
if (!dateTimeString) return '';
try {
const date = new Date(dateTimeString);
// Check if the date is valid
if (isNaN(date.getTime())) {
console.error('Invalid ISO date string:', dateTimeString);
return '';
}
let formatted = '';
if (showDate) {
const dateFormatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
});
const [{ value: month }, , { value: day }, , { value: year }] = dateFormatter.formatToParts(date);
formatted = `${month.charAt(0).toUpperCase() + month.slice(1)} ${day}, ${year}`;
}
if (showTime) {
const timeFormatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
});
const timeString = timeFormatter.format(date).toLowerCase();
formatted = formatted ? `${formatted}, ${timeString}` : timeString;
}
return formatted;
} catch (error) {
console.error('Error formatting date:', error);
return '';
}
};
return (
<div>
<div class="flex flex-row justify-start mb-2 items-start host-container" style={{ 'margin-right': '50px' }}>
<Show when={props.showAvatar}>
<Avatar initialAvatarSrc={props.avatarSrc} />
</Show>
<div class="flex flex-col justify-start">
{props.showAgentMessages && props.message.agentReasoning && (
<details ref={botDetailsEl} class="mb-2 px-4 py-2 ml-2 chatbot-host-bubble rounded-[6px]">
<summary class="cursor-pointer">
<span class="italic">Agent Messages</span>
</summary>
<br />
<For each={props.message.agentReasoning}>
{(agent) => {
const agentMessages = agent.messages ?? [];
let msgContent = agent.instructions || (agentMessages.length > 1 ? agentMessages.join('\\n') : agentMessages[0]);
if (agentMessages.length === 0 && !agent.instructions) msgContent = `<p>Finished</p>`;
return (
<AgentReasoningBubble
agentName={agent.agentName ?? ''}
agentMessage={msgContent}
agentArtifacts={agent.artifacts}
backgroundColor={props.backgroundColor}
textColor={props.textColor}
fontSize={props.fontSize}
apiHost={props.apiHost}
chatflowid={props.chatflowid}
chatId={props.chatId}
renderHTML={props.renderHTML}
/>
);
}}
</For>
</details>
)}
{props.message.artifacts && props.message.artifacts.length > 0 && (
<div class="flex flex-row items-start flex-wrap w-full gap-2">
<For each={props.message.artifacts}>
{(item) => {
return item !== null ? <>{renderArtifacts(item)}</> : null;
}}
</For>
</div>
)}
{props.message.message && (
<span
ref={botMessageEl}
class="px-4 py-2 ml-2 max-w-full chatbot-host-bubble prose"
data-testid="host-bubble"
style={{
'background-color': props.backgroundColor ?? defaultBackgroundColor,
color: props.textColor ?? defaultTextColor,
'border-radius': '6px',
'font-size': props.fontSize ? `${props.fontSize}px` : `${defaultFontSize}px`,
}}
/>
)}
{props.message.action && (
<div class="px-4 py-2 flex flex-row justify-start space-x-2">
<For each={props.message.action.elements || []}>
{(action) => {
return (
<>
{action.type === 'approve-button' ? (
<button
type="button"
class="px-4 py-2 font-medium text-green-600 border border-green-600 rounded-full hover:bg-green-600 hover:text-white transition-colors duration-300 flex items-center space-x-2"
onClick={() => props.handleActionClick(action.label, props.message.action)}
>
<TickIcon />
{action.label}
</button>
) : action.type === 'reject-button' ? (
<button
type="button"
class="px-4 py-2 font-medium text-red-600 border border-red-600 rounded-full hover:bg-red-600 hover:text-white transition-colors duration-300 flex items-center space-x-2"
onClick={() => props.handleActionClick(action.label, props.message.action)}
>
<XIcon isCurrentColor={true} />
{action.label}
</button>
) : (
<button>{action.label}</button>
)}
</>
);
}}
</For>
</div>
)}
</div>
</div>
<div>
{props.message.sourceDocuments && props.message.sourceDocuments.length && (
<>
<Show when={props.sourceDocsTitle}>
<span class="px-2 py-[10px] font-semibold">{props.sourceDocsTitle}</span>
</Show>
<div style={{ display: 'flex', 'flex-direction': 'row', width: '100%', 'flex-wrap': 'wrap' }}>
<For each={[...removeDuplicateURL(props.message)]}>
{(src) => {
const URL = isValidURL(src.metadata.source);
return (
<SourceBubble
pageContent={src.metadata.title ? src.metadata.title : URL ? URL.pathname : src.pageContent}
metadata={src.metadata}
onSourceClick={() => {
if (URL) {
window.open(src.metadata.source, '_blank');
} else {
props.handleSourceDocumentsClick(src);
}
}}
/>
);
}}
</For>
</div>
</>
)}
</div>
<div>
{props.chatFeedbackStatus && props.message.messageId && (
<>
<div class={`flex items-center px-2 pb-2 ${props.showAvatar ? 'ml-10' : ''}`}>
<CopyToClipboardButton feedbackColor={props.feedbackColor} onClick={() => copyMessageToClipboard()} />
<Show when={copiedMessage()}>
<div class="copied-message" style={{ color: props.feedbackColor ?? defaultFeedbackColor }}>
Copied!
</div>
</Show>
{rating() === '' || rating() === 'THUMBS_UP' ? (
<ThumbsUpButton feedbackColor={thumbsUpColor()} isDisabled={rating() === 'THUMBS_UP'} rating={rating()} onClick={onThumbsUpClick} />
) : null}
{rating() === '' || rating() === 'THUMBS_DOWN' ? (
<ThumbsDownButton
feedbackColor={thumbsDownColor()}
isDisabled={rating() === 'THUMBS_DOWN'}
rating={rating()}
onClick={onThumbsDownClick}
/>
) : null}
<Show when={props.message.dateTime}>
<div class="text-sm text-gray-500 ml-2">
{formatDateTime(props.message.dateTime, props?.dateTimeToggle?.date, props?.dateTimeToggle?.time)}
</div>
</Show>
</div>
<Show when={showFeedbackContentDialog()}>
<FeedbackContentDialog
isOpen={showFeedbackContentDialog()}
onClose={() => setShowFeedbackContentModal(false)}
onSubmit={submitFeedbackContent}
backgroundColor={props.backgroundColor}
textColor={props.textColor}
/>
</Show>
</>
)}
</div>
</div>
);
};