-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathpage.tsx
More file actions
455 lines (437 loc) · 17.9 KB
/
page.tsx
File metadata and controls
455 lines (437 loc) · 17.9 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
"use client";
import { useEffect, useState, useRef } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { MarkdownRenderer } from "@/components/markdown-renderer";
import { Input } from "@/components/ui/input";
import {
FileText,
Upload,
Eye,
Trash2,
Search,
FolderOpen,
File,
Plus,
Menu,
} from "lucide-react";
import { useSidebar } from "@/components/ui/sidebar";
import Image from "next/image";
interface KnowledgeFile {
name: string;
type: "pdf" | "txt";
}
interface FileContent {
content: string;
loading: boolean;
error: string;
}
export default function KnowledgeBasePage() {
const { toggleSidebar, isMobile } = useSidebar();
const [files, setFiles] = useState<KnowledgeFile[]>([]);
const [filteredFiles, setFilteredFiles] = useState<KnowledgeFile[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [searchTerm, setSearchTerm] = useState("");
const [selectedFile, setSelectedFile] = useState<KnowledgeFile | null>(null);
const [fileContent, setFileContent] = useState<FileContent | null>(null);
const [showUploadModal, setShowUploadModal] = useState(false);
const [uploading, setUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const fetchFiles = async () => {
try {
setLoading(true);
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/kb/files`, {
headers: { accept: "application/json" },
});
if (!res.ok) throw new Error("Failed to fetch files");
const data = await res.json();
if (!data.files || !Array.isArray(data.files))
throw new Error("Invalid response");
const files: KnowledgeFile[] = data.files.map((filename: string) => ({
name: filename,
type:
filename.split(".").pop()?.toLowerCase() === "pdf" ? "pdf" : "txt",
}));
setFiles(files);
setFilteredFiles(files);
} catch (err) {
setError("Failed to load knowledge base files");
} finally {
setLoading(false);
}
};
fetchFiles();
}, []);
useEffect(() => {
const filtered = files.filter((file) =>
file.name.toLowerCase().includes(searchTerm.toLowerCase()),
);
setFilteredFiles(filtered);
}, [searchTerm, files]);
const getFileIcon = (type: string) => {
switch (type) {
case "pdf":
return <FileText className="h-5 w-5 text-red-500" />;
case "txt":
return <FileText className="h-5 w-5 text-gray-500" />;
default:
return <File className="h-5 w-5 text-gray-500" />;
}
};
const handleFileUpload = async (
event: React.ChangeEvent<HTMLInputElement>,
) => {
const filesList = event.target.files;
if (!filesList || filesList.length === 0) return;
setUploading(true);
setError("");
const file = filesList[0];
const ext = file.name.split(".").pop()?.toLowerCase();
let endpoint = "";
if (ext === "pdf") {
endpoint = `${process.env.NEXT_PUBLIC_API_URL}/kb/upload-pdf`;
} else if (ext === "txt") {
endpoint = `${process.env.NEXT_PUBLIC_API_URL}/kb/upload-text`;
} else {
setError("Only PDF and TXT files are supported.");
setUploading(false);
return;
}
const formData = new FormData();
formData.append("file", file);
try {
const res = await fetch(endpoint, {
method: "POST",
body: formData,
});
if (!res.ok) throw new Error("Failed to upload file");
const data = await res.json();
if (data.status !== "success") throw new Error("Failed to upload file");
const newFile: KnowledgeFile = {
name: file.name,
type: ext === "pdf" ? "pdf" : "txt",
};
setFiles((prev) => [newFile, ...prev]);
setFilteredFiles((prev) => [newFile, ...prev]);
setShowUploadModal(false);
} catch (err) {
setError("Failed to upload file");
} finally {
setUploading(false);
}
};
const handleDeleteFile = async (fileName: string) => {
if (!confirm("Are you sure you want to delete this file?")) return;
try {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/kb/files/${encodeURIComponent(fileName)}`,
{
method: "DELETE",
headers: { accept: "application/json" },
},
);
if (!res.ok) throw new Error("Failed to delete file");
const data = await res.json();
if (data.status !== "success") throw new Error("Failed to delete file");
setFiles((prev) => prev.filter((file) => file.name !== fileName));
setFilteredFiles((prev) => prev.filter((file) => file.name !== fileName));
// If the deleted file is currently previewed, close the modal
if (selectedFile && selectedFile.name === fileName) {
setSelectedFile(null);
setFileContent(null);
}
} catch (err) {
setError("Failed to delete file");
}
};
const handleViewFile = async (file: KnowledgeFile) => {
setSelectedFile(file);
setFileContent({ content: "", loading: true, error: "" });
try {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/kb/files/${encodeURIComponent(file.name)}/chunks`,
{
headers: { accept: "application/json" },
},
);
if (!res.ok) throw new Error("Failed to fetch file content");
const data = await res.json();
if (!data.chunks || !Array.isArray(data.chunks))
throw new Error("Invalid response");
// Sort by chunk_index just in case
const sortedChunks = data.chunks.sort(
(a: { chunk_index: number }, b: { chunk_index: number }) =>
a.chunk_index - b.chunk_index,
);
const content = sortedChunks.map((c: any) => c.chunk).join("\n");
setFileContent({ content, loading: false, error: "" });
} catch (err) {
setFileContent({
content: "",
loading: false,
error: "Failed to load file content",
});
}
};
if (loading)
return <div className="p-8 text-center">Loading knowledge base...</div>;
if (error) return <div className="p-8 text-center text-red-600">{error}</div>;
return (
<div className="min-h-screen bg-slate-50">
{/* Mobile Header */}
{isMobile && (
<header className="bg-white border-b border-slate-200 px-4 py-3 flex items-center gap-3 flex-shrink-0">
<Button
variant="ghost"
size="sm"
onClick={toggleSidebar}
className="md:hidden"
>
<Menu className="h-5 w-5" />
</Button>
<div className="flex items-center gap-2">
<Image
src="/VCellLogo.png"
alt="VCell Logo"
width={40}
height={40}
className="rounded w-10 h-10 object-contain"
/>
<span className="text-lg font-semibold text-slate-900">
Knowledge Base
</span>
</div>
</header>
)}
<div className="container mx-auto p-4 sm:p-6 md:p-8 max-w-7xl">
{/* Header */}
<div className="mb-6 sm:mb-8">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div className="flex-1">
<h1 className="text-2xl sm:text-3xl font-extrabold text-blue-900 flex items-center gap-2 sm:gap-3">
<FolderOpen className="h-6 w-6 sm:h-8 sm:w-8 text-blue-500 flex-shrink-0" />
<span className="break-words">Knowledge Base Management</span>
</h1>
<p className="text-slate-600 mt-1 sm:mt-2 text-sm sm:text-base">
Upload, manage, and organize knowledge base files
</p>
</div>
<div className="flex flex-col sm:flex-row gap-2 sm:gap-3">
<Button
onClick={() => setShowUploadModal(true)}
className="inline-flex items-center justify-center gap-1 sm:gap-2 px-3 sm:px-4 py-2 rounded border border-green-600 text-green-700 bg-white font-semibold shadow-sm transition-colors hover:bg-green-50 text-sm whitespace-nowrap"
>
<Plus className="h-3 w-3 sm:h-4 sm:w-4" /> Upload File
</Button>
<Button
onClick={() => window.open("/admin", "_blank")}
className="inline-flex items-center justify-center gap-1 sm:gap-2 px-3 sm:px-4 py-2 rounded border border-blue-600 text-blue-700 bg-white font-semibold shadow-sm transition-colors hover:bg-blue-50 text-sm whitespace-nowrap"
>
<FileText className="h-3 w-3 sm:h-4 sm:w-4" /> Back to Dashboard
</Button>
</div>
</div>
</div>
{/* Search and Filters */}
<Card className="shadow-lg border-slate-200 mb-6 sm:mb-8">
<CardContent className="p-4 sm:p-5 md:p-6">
<div className="flex items-center gap-4">
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-slate-400" />
<Input
placeholder="Search files by name, description, or tags..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10"
/>
</div>
</div>
</CardContent>
</Card>
{/* Files Table */}
<Card className="shadow-lg border-slate-200">
<CardHeader className="bg-gradient-to-r from-blue-100 to-blue-50 border-b border-slate-200 px-4 sm:px-5 md:px-6 py-4 sm:py-5">
<CardTitle className="text-lg sm:text-xl md:text-2xl font-extrabold text-blue-900 flex flex-wrap items-center justify-between gap-2 sm:gap-3">
<div className="flex items-center gap-2 sm:gap-3">
<FileText className="h-5 w-5 sm:h-6 sm:w-6 text-blue-500 flex-shrink-0" />
<span>Knowledge Base Files</span>
</div>
<Badge className="bg-blue-600 text-white px-3 py-1.5 text-sm font-semibold rounded-md">
{files.length} files
</Badge>
</CardTitle>
</CardHeader>
<CardContent className="p-0">
{filteredFiles.length === 0 ? (
<div className="text-center py-16 px-6">
<FolderOpen className="h-16 w-16 text-slate-300 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-slate-600 mb-2">
No files uploaded yet
</h3>
<p className="text-slate-500 mb-6 max-w-md mx-auto">
Your knowledge base is empty. Upload your first file to get
started with building your knowledge base.
</p>
<Button
onClick={() => setShowUploadModal(true)}
className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 text-white font-semibold rounded-lg shadow-sm hover:bg-blue-700 transition-colors"
>
<Plus className="h-4 w-4" />
Upload Your First File
</Button>
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-slate-50 border-b border-slate-200">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
File
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
Type
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-slate-200">
{filteredFiles.map((file) => (
<tr key={file.name} className="hover:bg-slate-50">
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center">
<div className="flex-shrink-0 h-10 w-10">
<div className="h-10 w-10 rounded-lg bg-slate-100 flex items-center justify-center">
{getFileIcon(file.type)}
</div>
</div>
<div className="ml-4">
<div className="text-sm font-medium text-slate-900">
{file.name}
</div>
<div className="flex gap-1 mt-1"></div>
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-slate-900">
{file.type.toUpperCase()}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
<div className="flex gap-2">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 text-blue-600 hover:text-blue-800 hover:bg-blue-50"
title="View File"
onClick={() => handleViewFile(file)}
>
<Eye className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 text-red-600 hover:text-red-800 hover:bg-red-50"
title="Delete File"
onClick={() => handleDeleteFile(file.name)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
{/* Upload Modal */}
{showUploadModal && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg p-6 w-full max-w-md">
<h3 className="text-lg font-semibold mb-4">Upload File</h3>
<div className="space-y-4">
<div className="border-2 border-dashed border-slate-300 rounded-lg p-6 text-center">
<Upload className="h-8 w-8 text-slate-400 mx-auto mb-2" />
<p className="text-sm text-slate-600 mb-2">
Click to select or drag and drop
</p>
<input
ref={fileInputRef}
type="file"
onChange={handleFileUpload}
className="hidden"
accept=".pdf,.txt,application/pdf,text/plain"
/>
<Button
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
className="inline-flex items-center gap-2"
>
<Upload className="h-4 w-4" />
{uploading ? "Uploading..." : "Select File"}
</Button>
</div>
<div className="flex gap-2">
<Button
onClick={() => setShowUploadModal(false)}
variant="outline"
className="flex-1"
>
Cancel
</Button>
</div>
</div>
</div>
</div>
)}
{/* File Preview Modal */}
{selectedFile && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg p-6 w-full max-w-4xl max-h-[80vh] overflow-y-auto">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold flex items-center gap-2">
{getFileIcon(selectedFile.type)}
{selectedFile.name}
</h3>
<Button
variant="ghost"
size="sm"
onClick={() => {
setSelectedFile(null);
setFileContent(null);
}}
>
×
</Button>
</div>
<div className="space-y-4">
<div className="border-t pt-4">
<span className="font-medium">Content Preview:</span>
<div className="mt-2 p-4 bg-slate-50 rounded-lg text-sm min-h-[100px]">
{fileContent?.loading && (
<span className="text-slate-400">Loading...</span>
)}
{fileContent?.error && (
<span className="text-red-600">{fileContent.error}</span>
)}
{!fileContent?.loading &&
!fileContent?.error &&
fileContent?.content && (
<MarkdownRenderer content={fileContent.content} />
)}
</div>
</div>
</div>
</div>
</div>
)}
</div>
</div>
);
}