-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathSidebar.tsx
More file actions
426 lines (385 loc) · 12.6 KB
/
Sidebar.tsx
File metadata and controls
426 lines (385 loc) · 12.6 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
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import toast from 'react-hot-toast';
import { Trans, useTranslation } from 'react-i18next';
import {
LuDownload,
LuEllipsisVertical,
LuPencil,
LuSquarePen,
LuTrash,
LuX,
} from 'react-icons/lu';
import { useNavigate } from 'react-router';
import { Button } from '../components/ui/button';
import { useChatContext } from '../context/chat';
import { useModals } from '../context/modal';
import IndexedDB from '../database/indexedDB';
import { Conversation } from '../types';
import { classNames } from '../utils';
import { downloadAsFile } from './common';
import { Label } from './ui/label';
export default function Sidebar() {
const navigate = useNavigate();
const { t, i18n } = useTranslation();
const toggleDrawerRef = useRef<HTMLInputElement>(null);
const [conversations, setConversations] = useState<Conversation[]>([]);
useEffect(() => {
const handleConversationChange = async () => {
setConversations(await IndexedDB.getAllConversations());
};
IndexedDB.onConversationChanged(handleConversationChange);
handleConversationChange();
return () => {
IndexedDB.offConversationChanged(handleConversationChange);
};
}, []);
const groupedConv = useMemo(
() => groupConversationsByDate(conversations, i18n.language),
[i18n.language, conversations]
);
const handleSelect = useCallback(() => {
const toggle = toggleDrawerRef.current;
if (toggle != null) {
toggle.click();
}
}, []);
return (
<>
<input
id="toggle-drawer"
type="checkbox"
className="drawer-toggle"
ref={toggleDrawerRef}
aria-label="Toggle sidebar"
/>
<div
className="drawer-side fixed inset-0 w-full z-50"
role="complementary"
aria-label="Sidebar"
tabIndex={0}
>
<div className="flex flex-col bg-base-300 h-full min-h-0 max-w-full xl:w-72 pb-4 px-4 xl:pl-2 xl:pr-0">
<div className="flex flex-row items-center justify-between xl:py-2">
{/* close sidebar button */}
<Label size="icon" className="max-xl:hidden" />
<Label
className="xl:hidden"
variant="btn-ghost"
size="icon-rounded"
htmlFor="toggle-drawer"
role="button"
title={t('sidebar.buttons.closeSideBar')}
aria-label={t('sidebar.buttons.closeSideBar')}
tabIndex={0}
>
<LuX className="lucide w-5 h-5" />
</Label>
<Label
variant="fake-btn"
className="font-bold tracking-wider leading-8"
aria-label={import.meta.env.VITE_APP_NAME}
role="button"
onClick={() => navigate('/')}
>
{import.meta.env.VITE_APP_NAME}
</Label>
{/* new conversation button */}
<Button
variant="ghost"
size="icon-rounded"
onClick={() => navigate('/')}
title={t('header.buttons.newConv')}
aria-label={t('header.ariaLabels.newConv')}
>
<LuSquarePen className="lucide w-5 h-5" />
</Button>
</div>
{/* scrollable conversation list */}
<div className="flex-1 overflow-y-auto overflow-x-hidden min-h-0">
{groupedConv.map((group) => (
<ConversationGroup
key={group.title}
group={group}
onItemSelect={handleSelect}
/>
))}
</div>
{/* Footer always at the bottom */}
<div className="text-center text-xs opacity-75 mx-4 pt-4">
<Trans i18nKey="sidebar.storageNote" />
</div>
</div>
</div>
</>
);
}
const ConversationGroup = memo(
({
group,
onItemSelect,
}: {
group: GroupedConversations;
onItemSelect: () => void;
}) => {
const { t } = useTranslation();
return (
<div role="group">
{/* group name (by date) */}
{/* we use btn class here to make sure that the padding/margin are aligned with the other items */}
<Label
className="px-2 mb-0 mt-6 opacity-75"
variant="group-title"
size="xs"
role="note"
aria-description={t(`sidebar.groups.${group.title}`, {
defaultValue: group.title,
})}
tabIndex={0}
>
<Trans
i18nKey={`sidebar.groups.${group.title}`}
defaults={group.title}
/>
</Label>
<ul>
{group.conversations.map((conv) => (
<ConversationItem
key={conv.id}
conv={conv}
onSelect={onItemSelect}
/>
))}
</ul>
</div>
);
}
);
const ConversationItem = memo(
({ conv, onSelect }: { conv: Conversation; onSelect: () => void }) => {
const navigate = useNavigate();
const { t } = useTranslation();
const { viewingChat, isGenerating } = useChatContext();
const { showConfirm, showPrompt } = useModals();
const isCurrent = useMemo(
() => viewingChat?.conv?.id === conv.id,
[conv.id, viewingChat?.conv?.id]
);
const isPending = useMemo(
() => isGenerating(conv.id),
[conv.id, isGenerating]
);
const handleSelect = () => {
onSelect();
navigate(`/chat/${conv.id}`);
};
const handleRename = async () => {
if (isPending) {
toast.error(t('sidebar.errors.renameOnGenerate'));
return;
}
const newName = await showPrompt(t('sidebar.actions.newName'), conv.name);
if (newName && newName.trim().length > 0) {
IndexedDB.updateConversationName(conv.id, newName);
}
};
const handleDownload = async () => {
if (isPending) {
toast.error(t('sidebar.errors.downloadOnGenerate'));
return;
}
return IndexedDB.exportDB(conv.id).then((data) =>
downloadAsFile(
[JSON.stringify(data, null, 2)],
`conversation_${conv.id}.json`
)
);
};
const handleDelete = async () => {
if (isPending) {
toast.error(t('sidebar.errors.deleteOnGenerate'));
return;
}
if (await showConfirm(t('sidebar.actions.deleteConfirm'))) {
toast.success(t('sidebar.actions.deleteSuccess'));
IndexedDB.deleteConversation(conv.id);
navigate('/');
}
};
return (
<li
role="menuitem"
tabIndex={0}
aria-label={conv.name}
className={classNames({
'group flex flex-row btn btn-ghost h-9 justify-start items-center font-normal px-2 xl:pr-0': true,
'btn-soft': isCurrent,
})}
>
<button
type="button"
key={conv.id}
className="w-full overflow-hidden truncate text-start"
onClick={handleSelect}
dir="auto"
title={conv.name}
aria-label={t('sidebar.ariaLabels.select', { name: conv.name })}
>
{conv.name}
</button>
<div tabIndex={0} className="dropdown dropdown-end">
<Button
// on mobile, we always show the ellipsis icon
// on desktop, we only show it when the user hovers over the conversation item
// we use opacity instead of hidden to avoid layout shift
className="h-auto w-auto opacity-100 xl:opacity-20 group-hover:opacity-100 border-none"
variant="ghost"
size="icon"
onClick={() => {}}
title={t('sidebar.buttons.more')}
aria-label={t('sidebar.ariaLabels.more')}
>
<LuEllipsisVertical className="lucide w-5 h-5" />
</Button>
{/* dropdown menu */}
<ul
aria-label={t('sidebar.ariaLabels.dropdown')}
role="menu"
tabIndex={-1}
className="dropdown-content menu bg-base-100 rounded-box z-[1] p-2 shadow"
>
<li role="menuitem" tabIndex={0} onClick={handleRename}>
<Button
variant="menu-item"
size="small"
title={t('sidebar.buttons.rename')}
aria-label={t('sidebar.ariaLabels.rename')}
>
<LuPencil className="lucide w-4 h-4" />
<Trans i18nKey="sidebar.buttons.rename" />
</Button>
</li>
<li role="menuitem" tabIndex={0} onClick={handleDownload}>
<Button
variant="menu-item"
size="small"
title={t('sidebar.buttons.download')}
aria-label={t('sidebar.ariaLabels.download')}
>
<LuDownload className="lucide w-4 h-4" />
<Trans i18nKey="sidebar.buttons.download" />
</Button>
</li>
<li
role="menuitem"
tabIndex={0}
className="text-error"
onClick={handleDelete}
>
<Button
variant="menu-item"
size="small"
title={t('sidebar.buttons.delete')}
aria-label={t('sidebar.ariaLabels.delete')}
>
<LuTrash className="lucide w-4 h-4" />
<Trans i18nKey="sidebar.buttons.delete" />
</Button>
</li>
</ul>
</div>
</li>
);
}
);
// WARN: vibe code below
export interface GroupedConversations {
title?: string;
conversations: Conversation[];
}
// TODO @ngxson : add test for this function
// Group conversations by date
// - "Previous 7 Days"
// - "Previous 30 Days"
// - "Month Year" (e.g., "April 2023")
export function groupConversationsByDate(
conversations: Conversation[],
language: string = 'default'
): GroupedConversations[] {
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); // Start of today
const yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
const sevenDaysAgo = new Date(today);
sevenDaysAgo.setDate(today.getDate() - 7);
const thirtyDaysAgo = new Date(today);
thirtyDaysAgo.setDate(today.getDate() - 30);
const groups: { [key: string]: Conversation[] } = {
Today: [],
Yesterday: [],
'Previous 7 Days': [],
'Previous 30 Days': [],
};
const monthlyGroups: { [key: string]: Conversation[] } = {}; // Key format: "Month Year" e.g., "April 2023"
// Sort conversations by lastModified date in descending order (newest first)
// This helps when adding to groups, but the final output order of groups is fixed.
const sortedConversations = [...conversations].sort(
(a, b) => b.lastModified - a.lastModified
);
for (const conv of sortedConversations) {
const convDate = new Date(conv.lastModified);
if (convDate >= today) {
groups['Today'].push(conv);
} else if (convDate >= yesterday) {
groups['Yesterday'].push(conv);
} else if (convDate >= sevenDaysAgo) {
groups['Previous 7 Days'].push(conv);
} else if (convDate >= thirtyDaysAgo) {
groups['Previous 30 Days'].push(conv);
} else {
const monthName = convDate.toLocaleString(language, { month: 'long' });
const year = convDate.getFullYear();
const monthYearKey = `${monthName} ${year}`;
if (!monthlyGroups[monthYearKey]) {
monthlyGroups[monthYearKey] = [];
}
monthlyGroups[monthYearKey].push(conv);
}
}
const result: GroupedConversations[] = [];
if (groups['Today'].length > 0) {
result.push({
title: 'Today',
conversations: groups['Today'],
});
}
if (groups['Yesterday'].length > 0) {
result.push({
title: 'Yesterday',
conversations: groups['Yesterday'],
});
}
if (groups['Previous 7 Days'].length > 0) {
result.push({
title: 'Previous 7 Days',
conversations: groups['Previous 7 Days'],
});
}
if (groups['Previous 30 Days'].length > 0) {
result.push({
title: 'Previous 30 Days',
conversations: groups['Previous 30 Days'],
});
}
// Sort monthly groups by date (most recent month first)
const sortedMonthKeys = Object.keys(monthlyGroups).sort((a, b) => {
const dateA = new Date(a); // "Month Year" can be parsed by Date constructor
const dateB = new Date(b);
return dateB.getTime() - dateA.getTime();
});
for (const monthKey of sortedMonthKeys) {
if (monthlyGroups[monthKey].length > 0) {
result.push({ title: monthKey, conversations: monthlyGroups[monthKey] });
}
}
return result;
}