@sveda-ai/react 0.3.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.
Files changed (65) hide show
  1. package/LICENSE +557 -0
  2. package/README.md +18 -0
  3. package/dist/appearance.d.ts +12 -0
  4. package/dist/appearance.d.ts.map +1 -0
  5. package/dist/components/SvedaChat.d.ts +14 -0
  6. package/dist/components/SvedaChat.d.ts.map +1 -0
  7. package/dist/components/shell/ChatHistoryList.d.ts +10 -0
  8. package/dist/components/shell/ChatHistoryList.d.ts.map +1 -0
  9. package/dist/components/shell/ChatMessageList.d.ts +7 -0
  10. package/dist/components/shell/ChatMessageList.d.ts.map +1 -0
  11. package/dist/components/shell/SvedaComposer.d.ts +11 -0
  12. package/dist/components/shell/SvedaComposer.d.ts.map +1 -0
  13. package/dist/components/shell/SvedaFrameTicks.d.ts +2 -0
  14. package/dist/components/shell/SvedaFrameTicks.d.ts.map +1 -0
  15. package/dist/components/shell/SvedaMinimizedTrigger.d.ts +9 -0
  16. package/dist/components/shell/SvedaMinimizedTrigger.d.ts.map +1 -0
  17. package/dist/components/shell/SvedaResizeHandles.d.ts +9 -0
  18. package/dist/components/shell/SvedaResizeHandles.d.ts.map +1 -0
  19. package/dist/components/shell/SvedaTabs.d.ts +13 -0
  20. package/dist/components/shell/SvedaTabs.d.ts.map +1 -0
  21. package/dist/components/shell/SvedaToolbar.d.ts +21 -0
  22. package/dist/components/shell/SvedaToolbar.d.ts.map +1 -0
  23. package/dist/hooks/useSvedaChat.d.ts +33 -0
  24. package/dist/hooks/useSvedaChat.d.ts.map +1 -0
  25. package/dist/hooks/useSvedaChatLayout.d.ts +25 -0
  26. package/dist/hooks/useSvedaChatLayout.d.ts.map +1 -0
  27. package/dist/hooks/useSvedaStreaming.d.ts +43 -0
  28. package/dist/hooks/useSvedaStreaming.d.ts.map +1 -0
  29. package/dist/i18n.d.ts +14 -0
  30. package/dist/i18n.d.ts.map +1 -0
  31. package/dist/index.d.ts +25 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +1238 -0
  34. package/dist/launcherIcons.d.ts +5 -0
  35. package/dist/launcherIcons.d.ts.map +1 -0
  36. package/dist/lib/utils.d.ts +3 -0
  37. package/dist/lib/utils.d.ts.map +1 -0
  38. package/dist/provider.d.ts +15 -0
  39. package/dist/provider.d.ts.map +1 -0
  40. package/dist/styles.css +3 -0
  41. package/dist/types.d.ts +58 -0
  42. package/dist/types.d.ts.map +1 -0
  43. package/package.json +74 -0
  44. package/src/appearance.ts +81 -0
  45. package/src/components/SvedaChat.tsx +428 -0
  46. package/src/components/shell/ChatHistoryList.tsx +151 -0
  47. package/src/components/shell/ChatMessageList.tsx +52 -0
  48. package/src/components/shell/SvedaComposer.tsx +100 -0
  49. package/src/components/shell/SvedaFrameTicks.tsx +22 -0
  50. package/src/components/shell/SvedaMinimizedTrigger.tsx +41 -0
  51. package/src/components/shell/SvedaResizeHandles.tsx +51 -0
  52. package/src/components/shell/SvedaTabs.tsx +106 -0
  53. package/src/components/shell/SvedaToolbar.tsx +132 -0
  54. package/src/hooks/useSvedaChat.ts +91 -0
  55. package/src/hooks/useSvedaChatLayout.ts +281 -0
  56. package/src/hooks/useSvedaStreaming.ts +139 -0
  57. package/src/i18n.ts +51 -0
  58. package/src/index.ts +116 -0
  59. package/src/launcherIcons.ts +43 -0
  60. package/src/lib/utils.ts +6 -0
  61. package/src/markdown.css +96 -0
  62. package/src/provider.tsx +179 -0
  63. package/src/styles.css +6 -0
  64. package/src/theme.css +137 -0
  65. package/src/types.ts +70 -0
@@ -0,0 +1,428 @@
1
+ import {
2
+ getSvedaLauncherSnapshot,
3
+ subscribeSvedaAppearance,
4
+ } from '../appearance';
5
+ import type { SvedaModelOption, SvedaQuickPrompt } from '../types';
6
+ import { getSvedaChatStore } from '@sveda-ai/chat';
7
+ import { useSvedaChat } from '../hooks/useSvedaChat';
8
+ import { useSvedaChatLayout } from '../hooks/useSvedaChatLayout';
9
+ import { useSvedaStreaming } from '../hooks/useSvedaStreaming';
10
+ import { useSvedaConfig, useSvedaContext, useSvedaT } from '../provider';
11
+ import { Plus } from 'lucide-react';
12
+ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
13
+ import { ChatHistoryList } from './shell/ChatHistoryList';
14
+ import { ChatMessageList } from './shell/ChatMessageList';
15
+ import { SvedaComposer } from './shell/SvedaComposer';
16
+ import { SvedaFrameTicks } from './shell/SvedaFrameTicks';
17
+ import { SvedaMinimizedTrigger } from './shell/SvedaMinimizedTrigger';
18
+ import { SvedaResizeHandles } from './shell/SvedaResizeHandles';
19
+ import { SvedaTabs } from './shell/SvedaTabs';
20
+ import { SvedaToolbar } from './shell/SvedaToolbar';
21
+ import { cn } from '../lib/utils';
22
+
23
+ export interface SvedaChatProps {
24
+ models?: SvedaModelOption[];
25
+ quickPrompts?: SvedaQuickPrompt[];
26
+ brandName?: string;
27
+ brandLogo?: string;
28
+ pageUrl?: string;
29
+ onNavigate?: (url: string) => void;
30
+ notify?: (kind: string, message: string) => void;
31
+ agentTasksSubscribe?: (handler: (payload: unknown) => void) => () => void;
32
+ }
33
+
34
+ export function SvedaChat({
35
+ models: _modelsProp,
36
+ quickPrompts: _quickPromptsProp,
37
+ brandName,
38
+ brandLogo,
39
+ pageUrl = '',
40
+ notify,
41
+ }: SvedaChatProps) {
42
+ const config = useSvedaConfig();
43
+ const { hideLauncher, fillHost, hostEmbed } = useSvedaContext();
44
+ const t = useSvedaT();
45
+ const chat = useSvedaChat();
46
+ const layout = useSvedaChatLayout(chat.isMinimized, hostEmbed, fillHost);
47
+ const [inputMessage, setInputMessage] = useState('');
48
+ const [showHistorySidebar, setShowHistorySidebar] = useState(false);
49
+ const [pendingDeleteChatId, setPendingDeleteChatId] = useState<string | null>(null);
50
+ const [pendingRenameChatId, setPendingRenameChatId] = useState<string | null>(null);
51
+ const [renameTitle, setRenameTitle] = useState('');
52
+ const launcher = useSyncExternalStore(
53
+ subscribeSvedaAppearance,
54
+ getSvedaLauncherSnapshot,
55
+ getSvedaLauncherSnapshot
56
+ );
57
+
58
+ const brandDisplayName = brandName ?? config.brand.name;
59
+ const brandLogoUrl = brandLogo ?? config.brand.logoUrl ?? '';
60
+ const launcherLabel = launcher.label.trim() !== '' ? launcher.label : brandDisplayName;
61
+ const launcherImage =
62
+ launcher.image.trim() !== '' ? launcher.image : brandLogoUrl;
63
+
64
+ const scrollToBottom = useCallback((_options?: { behavior?: string; onlyIfNearBottom?: boolean }) => {}, []);
65
+
66
+ const chatRef = useRef(chat);
67
+ chatRef.current = chat;
68
+
69
+ const streamingStore = useMemo(
70
+ () => ({
71
+ get currentChat() {
72
+ return chatRef.current.currentChat;
73
+ },
74
+ setChatMessages: (...args: Parameters<typeof chat.setChatMessages>) =>
75
+ chatRef.current.setChatMessages(...args),
76
+ setChatTitle: (...args: Parameters<typeof chat.setChatTitle>) =>
77
+ chatRef.current.setChatTitle(...args),
78
+ refreshChatTitleFromServer: (...args: Parameters<typeof chat.refreshChatTitleFromServer>) =>
79
+ chatRef.current.refreshChatTitleFromServer(...args),
80
+ incrementChatTokens: (...args: Parameters<typeof chat.incrementChatTokens>) =>
81
+ chatRef.current.incrementChatTokens(...args),
82
+ setChatContextWindowTokens: (...args: Parameters<typeof chat.setChatContextWindowTokens>) =>
83
+ chatRef.current.setChatContextWindowTokens(...args),
84
+ }),
85
+ []
86
+ );
87
+
88
+ const streaming = useSvedaStreaming(streamingStore, scrollToBottom, {
89
+ onError: (_chatId, error) => {
90
+ const message = error instanceof Error ? error.message : t('errorSendingMessage');
91
+ notify?.('error', message);
92
+ },
93
+ });
94
+
95
+ useEffect(() => {
96
+ if (chat.isMinimized || getSvedaChatStore().getState().currentChat) {
97
+ return;
98
+ }
99
+ chat.createNewChat();
100
+ }, [chat.isMinimized, chat.currentChat, chat.createNewChat]);
101
+
102
+ const handleSend = async () => {
103
+ const text = inputMessage.trim();
104
+ if (!text) {
105
+ return;
106
+ }
107
+ setInputMessage('');
108
+ await streaming.sendMessage(text, pageUrl ? { pageUrl } : undefined);
109
+ };
110
+
111
+ const handleNewChat = () => {
112
+ chat.createNewChat();
113
+ if (layout.isMobile) {
114
+ setShowHistorySidebar(false);
115
+ }
116
+ };
117
+
118
+ const handleSelectChat = (chatId: string) => {
119
+ void chat.setCurrentChat(chatId);
120
+ if (layout.isMobile) {
121
+ setShowHistorySidebar(false);
122
+ }
123
+ };
124
+
125
+ const confirmDelete = () => {
126
+ if (pendingDeleteChatId) {
127
+ void chat.deleteChat(pendingDeleteChatId);
128
+ }
129
+ setPendingDeleteChatId(null);
130
+ };
131
+
132
+ const confirmRename = () => {
133
+ const title = renameTitle.trim();
134
+ if (pendingRenameChatId && title) {
135
+ chat.renameChat(pendingRenameChatId, title);
136
+ }
137
+ setPendingRenameChatId(null);
138
+ setRenameTitle('');
139
+ };
140
+
141
+ const headerTitle = chat.currentChat?.title || t('chatTitle');
142
+
143
+ const historyAsideClass = cn(
144
+ 'sveda-chat-surface flex min-h-0 w-80 shrink-0 flex-col overflow-hidden bg-background',
145
+ layout.isMobile
146
+ ? 'h-full max-w-[88vw] border-r border-border'
147
+ : fillHost
148
+ ? 'h-full border-r border-border'
149
+ : layout.viewMode === 'fixed'
150
+ ? 'absolute right-full top-0 z-10 h-full border-r border-border'
151
+ : 'h-full rounded-[var(--sveda-radius)] border border-border'
152
+ );
153
+
154
+ const nonImmersiveShellClass =
155
+ layout.isMobile || layout.viewMode === 'fixed'
156
+ ? 'relative flex h-full min-h-0 min-w-0 flex-1 flex-row'
157
+ : fillHost
158
+ ? 'relative flex h-full min-h-0 min-w-0 w-full flex-row items-stretch overflow-hidden'
159
+ : 'relative flex min-h-0 flex-row items-stretch gap-2';
160
+
161
+ const floatShellStyle =
162
+ fillHost
163
+ ? { height: '100%', minHeight: 0 }
164
+ : layout.isMobile || layout.viewMode !== 'floating'
165
+ ? undefined
166
+ : { height: `${layout.chatHeight}px`, minHeight: 0 };
167
+
168
+ const cardClass = cn(
169
+ 'sveda-chat-surface relative flex min-h-0 flex-col overflow-visible',
170
+ layout.viewMode === 'floating' && !layout.isMobile && !fillHost && 'sveda-chat-frame',
171
+ (fillHost || layout.isMobile) && 'border-0',
172
+ layout.isMobile && 'h-full min-w-0 flex-1 rounded-none',
173
+ layout.viewMode === 'fixed' &&
174
+ !layout.isMobile &&
175
+ 'h-full min-w-0 flex-1 rounded-none border-b-0 border-l border-r-0 border-t-0 border-border',
176
+ layout.viewMode === 'floating' && 'rounded-[var(--sveda-radius)]',
177
+ (layout.isMobile || layout.viewMode === 'fixed') && 'rounded-none',
178
+ layout.viewMode === 'floating' && !layout.isMobile && !fillHost && 'min-w-0 shrink-0',
179
+ layout.viewMode === 'floating' && !layout.isMobile && fillHost && 'h-full min-w-0 flex-1'
180
+ );
181
+
182
+ const panel = (
183
+ <>
184
+ <SvedaToolbar
185
+ title={headerTitle}
186
+ isMobile={layout.isMobile}
187
+ viewMode={layout.viewMode}
188
+ isImmersiveDesktop={layout.isImmersiveDesktop}
189
+ showHistorySidebar={showHistorySidebar}
190
+ viewModeFloatingLabel={t('viewModeFloating')}
191
+ viewModeFixedLabel={t('viewModeFixed')}
192
+ immersiveEnterLabel={t('immersiveModeEnter')}
193
+ immersiveExitLabel={t('immersiveModeExit')}
194
+ immersiveBrandName={brandDisplayName}
195
+ immersiveBrandLogo={brandLogoUrl}
196
+ onToggleHistory={() => setShowHistorySidebar((open) => !open)}
197
+ onEnterImmersive={layout.enterImmersiveMode}
198
+ onExitImmersive={layout.exitImmersiveMode}
199
+ onToggleViewMode={layout.toggleViewMode}
200
+ onMinimize={() => chat.minimizeChat()}
201
+ />
202
+ <SvedaTabs
203
+ tabs={chat.openChatTabs}
204
+ currentChatId={chat.currentChat?.id}
205
+ streamingChatIds={streaming.streamingChatIds}
206
+ unreadChatIds={streaming.unreadChatIds}
207
+ compact
208
+ onSelectChat={handleSelectChat}
209
+ onCloseTab={(chatId) => {
210
+ void chat.closeChatTab(chatId);
211
+ }}
212
+ onNewChat={handleNewChat}
213
+ />
214
+ <ChatMessageList messages={chat.currentChat?.messages ?? []} />
215
+ <SvedaComposer
216
+ value={inputMessage}
217
+ onChange={setInputMessage}
218
+ onSend={() => {
219
+ void handleSend();
220
+ }}
221
+ onStop={() => streaming.stopStreaming()}
222
+ isLoading={chat.isLoading || chat.isLoadingChatHistory}
223
+ isStreaming={streaming.isStreaming}
224
+ />
225
+ </>
226
+ );
227
+
228
+ const newChatButton = (
229
+ <button
230
+ type="button"
231
+ className="inline-flex w-full items-center justify-center gap-2 bg-primary px-3 py-2 font-mono text-[11px] tracking-[0.14em] text-primary-foreground"
232
+ onClick={handleNewChat}
233
+ >
234
+ <Plus className="h-4 w-4" />
235
+ {t('newChat')}
236
+ </button>
237
+ );
238
+
239
+ const historyList = (
240
+ <ChatHistoryList
241
+ histories={chat.sortedHistories}
242
+ currentChatId={chat.currentChat?.id}
243
+ onSelectChat={handleSelectChat}
244
+ onDeleteChat={(chatId) => setPendingDeleteChatId(chatId)}
245
+ onRenameChat={(chatId) => {
246
+ const history = chat.sortedHistories.find((item) => item.id === chatId);
247
+ setPendingRenameChatId(chatId);
248
+ setRenameTitle(history?.title ?? '');
249
+ }}
250
+ />
251
+ );
252
+
253
+ return (
254
+ <div
255
+ className={layout.chatShellClass}
256
+ style={layout.chatShellStyle}
257
+ data-testid="sveda-chat"
258
+ >
259
+ {!chat.isMinimized ? (
260
+ <div
261
+ className={
262
+ layout.isMobile || layout.viewMode === 'fixed' || fillHost
263
+ ? 'flex h-full min-h-0 w-full min-w-0 flex-1'
264
+ : layout.viewMode === 'immersive'
265
+ ? 'flex h-full min-h-0 w-full min-w-0 flex-1 flex-col'
266
+ : 'flex gap-2'
267
+ }
268
+ >
269
+ {layout.isImmersiveDesktop ? (
270
+ <div className="sveda-chat-surface flex h-full min-h-0 w-full flex-1 flex-col">
271
+ <SvedaToolbar
272
+ title={headerTitle}
273
+ isMobile={layout.isMobile}
274
+ viewMode={layout.viewMode}
275
+ isImmersiveDesktop
276
+ showHistorySidebar={showHistorySidebar}
277
+ viewModeFloatingLabel={t('viewModeFloating')}
278
+ viewModeFixedLabel={t('viewModeFixed')}
279
+ immersiveEnterLabel={t('immersiveModeEnter')}
280
+ immersiveExitLabel={t('immersiveModeExit')}
281
+ immersiveBrandName={brandDisplayName}
282
+ immersiveBrandLogo={brandLogoUrl}
283
+ onToggleHistory={() => setShowHistorySidebar((open) => !open)}
284
+ onEnterImmersive={layout.enterImmersiveMode}
285
+ onExitImmersive={layout.exitImmersiveMode}
286
+ onToggleViewMode={layout.toggleViewMode}
287
+ onMinimize={() => chat.minimizeChat()}
288
+ />
289
+ <div className="flex min-h-0 flex-1 flex-row">
290
+ <aside className="sveda-chat-surface flex w-[min(20rem,33vw)] shrink-0 flex-col border-r border-border">
291
+ <div className="border-b border-border/50 p-3">{newChatButton}</div>
292
+ <div className="min-h-0 flex-1">{historyList}</div>
293
+ </aside>
294
+ <div className="sveda-chat-surface flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
295
+ <SvedaTabs
296
+ tabs={chat.openChatTabs}
297
+ currentChatId={chat.currentChat?.id}
298
+ streamingChatIds={streaming.streamingChatIds}
299
+ unreadChatIds={streaming.unreadChatIds}
300
+ onSelectChat={handleSelectChat}
301
+ onCloseTab={(chatId) => {
302
+ void chat.closeChatTab(chatId);
303
+ }}
304
+ onNewChat={handleNewChat}
305
+ />
306
+ <div className="mx-auto flex min-h-0 w-full max-w-7xl flex-1 flex-col overflow-hidden px-4 md:px-6">
307
+ <ChatMessageList messages={chat.currentChat?.messages ?? []} />
308
+ <SvedaComposer
309
+ value={inputMessage}
310
+ onChange={setInputMessage}
311
+ onSend={() => {
312
+ void handleSend();
313
+ }}
314
+ onStop={() => streaming.stopStreaming()}
315
+ isLoading={chat.isLoading || chat.isLoadingChatHistory}
316
+ isStreaming={streaming.isStreaming}
317
+ />
318
+ </div>
319
+ </div>
320
+ </div>
321
+ </div>
322
+ ) : (
323
+ <div className={nonImmersiveShellClass} style={floatShellStyle}>
324
+ {showHistorySidebar && !layout.isMobile ? (
325
+ <aside className={historyAsideClass}>
326
+ <div className="border-b border-border/50 p-3">{newChatButton}</div>
327
+ <div className="min-h-0 flex-1">{historyList}</div>
328
+ </aside>
329
+ ) : null}
330
+ <div className={cardClass} style={layout.chatCardStyle}>
331
+ <div className="sveda-chat-surface relative flex flex-1 flex-col overflow-hidden p-0">
332
+ <div className="flex min-h-0 flex-1 flex-col">{panel}</div>
333
+ </div>
334
+ {layout.viewMode === 'floating' && !layout.isMobile && !fillHost ? <SvedaFrameTicks /> : null}
335
+ <SvedaResizeHandles
336
+ isMobile={layout.isMobile}
337
+ viewMode={layout.viewMode}
338
+ onStartResize={layout.startResize}
339
+ />
340
+ </div>
341
+ </div>
342
+ )}
343
+ </div>
344
+ ) : null}
345
+
346
+ {layout.isMobile && showHistorySidebar && !chat.isMinimized ? (
347
+ <div className="fixed inset-0 z-[60] flex bg-black/40" onClick={() => setShowHistorySidebar(false)}>
348
+ <aside
349
+ className="sveda-chat-surface flex h-full w-80 max-w-[88vw] flex-col bg-background"
350
+ onClick={(event) => event.stopPropagation()}
351
+ >
352
+ <div className="border-b border-border/50 p-3">{newChatButton}</div>
353
+ <div className="min-h-0 flex-1">{historyList}</div>
354
+ </aside>
355
+ </div>
356
+ ) : null}
357
+
358
+ {chat.isMinimized && !layout.isMobile && !hideLauncher ? (
359
+ <SvedaMinimizedTrigger
360
+ label={launcherLabel}
361
+ icon={launcher.icon}
362
+ logoSrc={launcherImage}
363
+ logoAlt={t('assistantLogoAlt')}
364
+ onOpen={() => {
365
+ void chat.openChat();
366
+ }}
367
+ />
368
+ ) : null}
369
+
370
+ {pendingDeleteChatId ? (
371
+ <div className="fixed inset-0 z-[70] flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true">
372
+ <div className="w-full max-w-sm border border-border bg-card p-4 text-card-foreground shadow-lg">
373
+ <h3 className="text-base font-semibold">{t('commonDelete')}</h3>
374
+ <p className="mt-2 text-sm text-muted-foreground">{t('confirmDeleteChat')}</p>
375
+ <div className="mt-4 flex justify-end gap-2">
376
+ <button
377
+ type="button"
378
+ className="border border-border px-3 py-2 text-sm"
379
+ onClick={() => setPendingDeleteChatId(null)}
380
+ >
381
+ {t('commonCancel')}
382
+ </button>
383
+ <button type="button" className="bg-primary px-3 py-2 text-sm text-primary-foreground" onClick={confirmDelete}>
384
+ {t('commonDelete')}
385
+ </button>
386
+ </div>
387
+ </div>
388
+ </div>
389
+ ) : null}
390
+
391
+ {pendingRenameChatId ? (
392
+ <div className="fixed inset-0 z-[70] flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true">
393
+ <div className="w-full max-w-sm border border-border bg-card p-4 text-card-foreground shadow-lg">
394
+ <h3 className="text-base font-semibold">{t('renameChat')}</h3>
395
+ <input
396
+ value={renameTitle}
397
+ placeholder={t('renameChatPlaceholder')}
398
+ className="mt-3 h-10 w-full border border-input bg-input px-3 text-sm outline-none"
399
+ onChange={(event) => setRenameTitle(event.target.value)}
400
+ onKeyDown={(event) => {
401
+ if (event.key === 'Enter') {
402
+ confirmRename();
403
+ }
404
+ }}
405
+ />
406
+ <div className="mt-4 flex justify-end gap-2">
407
+ <button
408
+ type="button"
409
+ className="border border-border px-3 py-2 text-sm"
410
+ onClick={() => {
411
+ setPendingRenameChatId(null);
412
+ setRenameTitle('');
413
+ }}
414
+ >
415
+ {t('commonCancel')}
416
+ </button>
417
+ <button type="button" className="bg-primary px-3 py-2 text-sm text-primary-foreground" onClick={confirmRename}>
418
+ {t('commonSave')}
419
+ </button>
420
+ </div>
421
+ </div>
422
+ </div>
423
+ ) : null}
424
+ </div>
425
+ );
426
+ }
427
+
428
+ export default SvedaChat;
@@ -0,0 +1,151 @@
1
+ import type { SvedaChatHistory } from '@sveda-ai/chat';
2
+ import { getUserMessageText } from '@sveda-ai/chat';
3
+ import { Search, SquarePen, Trash2 } from 'lucide-react';
4
+ import { useMemo, useState } from 'react';
5
+ import { useSvedaT } from '../../provider';
6
+ import { cn } from '../../lib/utils';
7
+
8
+ export interface ChatHistoryListProps {
9
+ histories: SvedaChatHistory[];
10
+ currentChatId?: string | null;
11
+ onSelectChat: (chatId: string) => void;
12
+ onDeleteChat: (chatId: string) => void;
13
+ onRenameChat: (chatId: string) => void;
14
+ }
15
+
16
+ const dayDiff = (timestamp: number) => {
17
+ const targetDate = new Date(Number(timestamp) || Date.now());
18
+ const now = new Date();
19
+ const targetStart = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate()).getTime();
20
+ const nowStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
21
+ return Math.max(0, Math.floor((nowStart - targetStart) / 86400000));
22
+ };
23
+
24
+ export function ChatHistoryList({
25
+ histories,
26
+ currentChatId = null,
27
+ onSelectChat,
28
+ onDeleteChat,
29
+ onRenameChat,
30
+ }: ChatHistoryListProps) {
31
+ const t = useSvedaT();
32
+ const [searchQuery, setSearchQuery] = useState('');
33
+
34
+ const previewFor = (chat: SvedaChatHistory) => {
35
+ if (typeof chat.preview === 'string' && chat.preview.trim()) {
36
+ return chat.preview.trim();
37
+ }
38
+ const message = chat.messages?.find((item) => item.role === 'user');
39
+ return message ? getUserMessageText(message) : '';
40
+ };
41
+
42
+ const filtered = useMemo(() => {
43
+ const query = searchQuery.trim().toLowerCase();
44
+ if (!query) {
45
+ return histories;
46
+ }
47
+ return histories.filter((chat) => {
48
+ const preview = previewFor(chat);
49
+ return chat.title.toLowerCase().includes(query) || preview.toLowerCase().includes(query);
50
+ });
51
+ }, [histories, searchQuery]);
52
+
53
+ const groups = useMemo(() => {
54
+ const grouped: { label: string; chats: SvedaChatHistory[] }[] = [];
55
+ const indexByLabel = new Map<string, number>();
56
+ for (const chat of filtered) {
57
+ const diff = dayDiff(chat.updatedAt);
58
+ const label =
59
+ diff === 0 ? t('today') : diff === 1 ? t('yesterday') : diff === 2 ? t('dayBeforeYesterday') : t('daysAgo', { count: diff });
60
+ const index = indexByLabel.get(label);
61
+ if (index === undefined) {
62
+ indexByLabel.set(label, grouped.length);
63
+ grouped.push({ label, chats: [chat] });
64
+ } else {
65
+ grouped[index].chats.push(chat);
66
+ }
67
+ }
68
+ return grouped;
69
+ }, [filtered, t]);
70
+
71
+ return (
72
+ <div className="flex h-full min-h-0 w-full flex-col bg-background">
73
+ <div className="shrink-0 border-b border-border p-3">
74
+ <div className="mb-3 flex items-center justify-between">
75
+ <p className="text-sm font-semibold">{t('chatHistory')}</p>
76
+ </div>
77
+ <div className="flex h-10 items-center gap-2 rounded-[var(--sveda-radius)] border border-border bg-input px-3">
78
+ <Search className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
79
+ <input
80
+ value={searchQuery}
81
+ type="text"
82
+ autoComplete="off"
83
+ placeholder={t('searchChats')}
84
+ className="h-full min-w-0 flex-1 border-0 bg-transparent p-0 text-sm text-card-foreground outline-none placeholder:text-muted-foreground"
85
+ onChange={(event) => setSearchQuery(event.target.value)}
86
+ />
87
+ </div>
88
+ </div>
89
+ <div className="min-h-0 flex-1 overflow-y-auto p-2">
90
+ {groups.length === 0 ? (
91
+ <div className="px-2 py-6 text-center text-sm text-muted-foreground">{t('noChatsFound')}</div>
92
+ ) : (
93
+ groups.map((group) => (
94
+ <div key={group.label} className="mb-3 last:mb-1">
95
+ <p className="px-2 pb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">{group.label}</p>
96
+ {group.chats.map((chat) => (
97
+ <div
98
+ key={chat.id}
99
+ role="button"
100
+ tabIndex={0}
101
+ className={cn(
102
+ 'group relative cursor-pointer px-2 py-2 transition-colors hover:bg-muted',
103
+ currentChatId === chat.id ? 'bg-primary/10' : ''
104
+ )}
105
+ onClick={() => onSelectChat(chat.id)}
106
+ onKeyDown={(event) => {
107
+ if (event.key === 'Enter' || event.key === ' ') {
108
+ event.preventDefault();
109
+ onSelectChat(chat.id);
110
+ }
111
+ }}
112
+ >
113
+ <div className="flex items-start justify-between gap-2">
114
+ <div className="min-w-0 flex-1">
115
+ <p className="truncate text-sm font-medium">{chat.title}</p>
116
+ <p className="truncate text-xs text-muted-foreground">{previewFor(chat)}</p>
117
+ </div>
118
+ <div className="flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100">
119
+ <button
120
+ type="button"
121
+ className="inline-flex h-6 w-6 items-center justify-center"
122
+ aria-label={t('renameChat')}
123
+ onClick={(event) => {
124
+ event.stopPropagation();
125
+ onRenameChat(chat.id);
126
+ }}
127
+ >
128
+ <SquarePen className="h-3 w-3" />
129
+ </button>
130
+ <button
131
+ type="button"
132
+ className="inline-flex h-6 w-6 items-center justify-center"
133
+ aria-label={t('delete')}
134
+ onClick={(event) => {
135
+ event.stopPropagation();
136
+ onDeleteChat(chat.id);
137
+ }}
138
+ >
139
+ <Trash2 className="h-3 w-3" />
140
+ </button>
141
+ </div>
142
+ </div>
143
+ </div>
144
+ ))}
145
+ </div>
146
+ ))
147
+ )}
148
+ </div>
149
+ </div>
150
+ );
151
+ }
@@ -0,0 +1,52 @@
1
+ import type { SvedaDisplayMessage } from '@sveda-ai/core';
2
+ import { getUserMessageText } from '@sveda-ai/chat';
3
+ import { cn } from '../../lib/utils';
4
+
5
+ const getAssistantText = (message: SvedaDisplayMessage): string => {
6
+ if (!Array.isArray(message.parts)) {
7
+ return '';
8
+ }
9
+
10
+ return message.parts
11
+ .filter((part): part is { type: 'text'; text: string } => part.type === 'text' && typeof (part as { text?: string }).text === 'string')
12
+ .map((part) => part.text)
13
+ .join('');
14
+ };
15
+
16
+ export interface ChatMessageListProps {
17
+ messages: SvedaDisplayMessage[];
18
+ className?: string;
19
+ }
20
+
21
+ export function ChatMessageList({ messages, className }: ChatMessageListProps) {
22
+ return (
23
+ <div
24
+ className={cn('flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-4 py-3', className)}
25
+ data-testid="sveda-message-list"
26
+ >
27
+ <div className="mt-auto flex flex-col gap-3">
28
+ {messages.map((message) => {
29
+ const isUser = message.role === 'user';
30
+ const text = isUser ? getUserMessageText(message) : getAssistantText(message);
31
+ if (!text.trim()) {
32
+ return null;
33
+ }
34
+
35
+ return (
36
+ <div
37
+ key={message.id}
38
+ className={cn(
39
+ 'max-w-[90%] whitespace-pre-wrap break-words font-sans text-sm leading-relaxed',
40
+ isUser
41
+ ? 'ml-auto border border-border bg-secondary px-3 py-2 text-secondary-foreground'
42
+ : 'mr-auto text-foreground'
43
+ )}
44
+ >
45
+ {text}
46
+ </div>
47
+ );
48
+ })}
49
+ </div>
50
+ </div>
51
+ );
52
+ }