filesTable.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. "use client";
  2. import React, { useState, useEffect } from "react";
  3. import {
  4. ColumnDef,
  5. flexRender,
  6. getCoreRowModel,
  7. getPaginationRowModel,
  8. getSortedRowModel,
  9. useReactTable,
  10. SortingState,
  11. RowSelectionState,
  12. } from "@tanstack/react-table";
  13. import { useQuery, useQueryClient } from "@tanstack/react-query";
  14. import { Button } from "@/components/ui/button";
  15. import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
  16. import { Checkbox } from "@/components/ui/checkbox";
  17. import {
  18. Table,
  19. TableBody,
  20. TableCell,
  21. TableHead,
  22. TableHeader,
  23. TableRow,
  24. } from "@/components/ui/table";
  25. import { Skeleton } from "@/components/ui/skeleton";
  26. import { AlertCircle, Download, Trash2, RefreshCw } from "lucide-react";
  27. import { Input } from "@/components/ui/input";
  28. interface FileData {
  29. id: string;
  30. filename: string;
  31. mimetype: string;
  32. size: number;
  33. createdAt: string;
  34. updatedAt: string;
  35. }
  36. export function FilesTable() {
  37. const [sorting, setSorting] = useState<SortingState>([]);
  38. const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
  39. const [files, setFiles] = useState<FileData[]>([]);
  40. const [isUploading, setIsUploading] = useState(false);
  41. const queryClient = useQueryClient();
  42. const { data, isLoading, isError, error, refetch } = useQuery({
  43. queryKey: ["files"],
  44. queryFn: async () => {
  45. const response = await fetch("/api/files");
  46. if (!response.ok) {
  47. throw new Error("Failed to fetch files");
  48. }
  49. const data = await response.json();
  50. return data.files as FileData[];
  51. },
  52. });
  53. // Update local files state when data changes
  54. useEffect(() => {
  55. if (data) {
  56. setFiles(data);
  57. }
  58. }, [data]);
  59. const columns: ColumnDef<FileData>[] = [
  60. {
  61. id: "select",
  62. header: ({ table }) => (
  63. <Checkbox
  64. checked={
  65. table.getIsAllPageRowsSelected() ||
  66. (table.getIsSomePageRowsSelected() && "indeterminate")
  67. }
  68. onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
  69. aria-label="Select all"
  70. />
  71. ),
  72. cell: ({ row }) => (
  73. <Checkbox
  74. checked={row.getIsSelected()}
  75. onCheckedChange={(value) => row.toggleSelected(!!value)}
  76. aria-label="Select row"
  77. />
  78. ),
  79. enableSorting: false,
  80. enableHiding: false,
  81. },
  82. {
  83. accessorKey: "filename",
  84. header: "File Name",
  85. cell: ({ row }) => (
  86. <div className="font-medium">{row.getValue("filename")}</div>
  87. ),
  88. },
  89. {
  90. accessorKey: "mimetype",
  91. header: "Type",
  92. cell: ({ row }) => (
  93. <div className="text-sm text-muted-foreground">{row.getValue("mimetype")}</div>
  94. ),
  95. },
  96. {
  97. accessorKey: "size",
  98. header: "Size",
  99. cell: ({ row }) => {
  100. const bytes = row.getValue("size") as number;
  101. if (bytes === 0) return "0 Bytes";
  102. const k = 1024;
  103. const sizes = ["Bytes", "KB", "MB", "GB"];
  104. const i = Math.floor(Math.log(bytes) / Math.log(k));
  105. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  106. },
  107. },
  108. {
  109. accessorKey: "createdAt",
  110. header: "Created",
  111. cell: ({ row }) => {
  112. const date = new Date(row.getValue("createdAt"));
  113. return date.toLocaleDateString("en-US", {
  114. year: "numeric",
  115. month: "short",
  116. day: "numeric",
  117. hour: "2-digit",
  118. minute: "2-digit",
  119. });
  120. },
  121. },
  122. {
  123. accessorKey: "updatedAt",
  124. header: "Updated",
  125. cell: ({ row }) => {
  126. const date = new Date(row.getValue("updatedAt"));
  127. return date.toLocaleDateString("en-US", {
  128. year: "numeric",
  129. month: "short",
  130. day: "numeric",
  131. hour: "2-digit",
  132. minute: "2-digit",
  133. });
  134. },
  135. },
  136. {
  137. id: "actions",
  138. header: "Actions",
  139. cell: ({ row }) => (
  140. <div className="flex gap-2">
  141. <Button
  142. variant="ghost"
  143. size="sm"
  144. onClick={() => handleDownload(row.original.id, row.original.filename)}
  145. title="Download file"
  146. >
  147. <Download className="h-4 w-4" />
  148. </Button>
  149. <Button
  150. variant="ghost"
  151. size="sm"
  152. onClick={() => handleDeleteFile(row.original.id, row.original.filename)}
  153. title="Delete file"
  154. >
  155. <Trash2 className="h-4 w-4" />
  156. </Button>
  157. </div>
  158. ),
  159. enableSorting: false,
  160. },
  161. ];
  162. const table = useReactTable({
  163. data: files,
  164. columns,
  165. state: {
  166. sorting,
  167. rowSelection,
  168. },
  169. onSortingChange: setSorting,
  170. onRowSelectionChange: setRowSelection,
  171. getCoreRowModel: getCoreRowModel(),
  172. getPaginationRowModel: getPaginationRowModel(),
  173. getSortedRowModel: getSortedRowModel(),
  174. enableRowSelection: true,
  175. });
  176. const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
  177. const file = event.target.files?.[0];
  178. if (!file) return;
  179. setIsUploading(true);
  180. const formData = new FormData();
  181. formData.append("file", file);
  182. try {
  183. const response = await fetch("/api/upload", {
  184. method: "POST",
  185. body: formData,
  186. });
  187. const result = await response.json();
  188. if (result.success) {
  189. // Add new file to the beginning of the list
  190. setFiles(prevFiles => [result.file, ...prevFiles]);
  191. // Invalidate and refetch to ensure consistency
  192. await queryClient.invalidateQueries({ queryKey: ["files"] });
  193. // Reset file input
  194. event.target.value = '';
  195. } else {
  196. alert(`Upload failed: ${result.error || 'Unknown error'}`);
  197. }
  198. } catch (error) {
  199. console.error("Upload error:", error);
  200. alert("Failed to upload file");
  201. } finally {
  202. setIsUploading(false);
  203. }
  204. };
  205. const handleRefresh = () => {
  206. refetch();
  207. };
  208. const handleDownload = (fileId: string, filename: string) => {
  209. const downloadUrl = `/api/files/${fileId}`;
  210. const link = document.createElement('a');
  211. link.href = downloadUrl;
  212. link.download = filename;
  213. document.body.appendChild(link);
  214. link.click();
  215. document.body.removeChild(link);
  216. };
  217. const handleDownloadSelected = () => {
  218. const selectedRows = table.getSelectedRowModel().rows;
  219. if (selectedRows.length === 0) return;
  220. if (selectedRows.length === 1) {
  221. const selected = selectedRows[0];
  222. handleDownload(selected.original.id, selected.original.filename);
  223. } else {
  224. selectedRows.forEach((row, index) => {
  225. setTimeout(() => {
  226. handleDownload(row.original.id, row.original.filename);
  227. }, index * 500);
  228. });
  229. }
  230. };
  231. const handleDeleteSelected = async () => {
  232. const selectedRows = table.getSelectedRowModel().rows;
  233. if (selectedRows.length === 0) return;
  234. const confirmDelete = window.confirm(
  235. `Are you sure you want to delete ${selectedRows.length} file${selectedRows.length > 1 ? 's' : ''}? This action cannot be undone.`
  236. );
  237. if (!confirmDelete) return;
  238. try {
  239. const results = [];
  240. for (const row of selectedRows) {
  241. try {
  242. const response = await fetch(`/api/files/${row.original.id}`, {
  243. method: 'DELETE',
  244. });
  245. if (!response.ok) {
  246. const errorText = await response.text();
  247. results.push({ id: row.original.id, success: false, error: errorText });
  248. } else {
  249. results.push({ id: row.original.id, success: true });
  250. }
  251. } catch (error) {
  252. results.push({ id: row.original.id, success: false, error: String(error) });
  253. }
  254. }
  255. const successful = results.filter(r => r.success).length;
  256. const failed = results.filter(r => !r.success).length;
  257. if (failed > 0) {
  258. alert(`${successful} file(s) deleted successfully, ${failed} failed.`);
  259. } else {
  260. alert(`${successful} file(s) deleted successfully.`);
  261. }
  262. setRowSelection({});
  263. refetch();
  264. } catch (error) {
  265. console.error('Error in delete process:', error);
  266. alert('Failed to delete files. Please try again.');
  267. }
  268. };
  269. const handleDeleteFile = async (fileId: string, filename: string) => {
  270. const confirmDelete = window.confirm(
  271. `Are you sure you want to delete "${filename}"? This action cannot be undone.`
  272. );
  273. if (!confirmDelete) return;
  274. try {
  275. const response = await fetch(`/api/files/${fileId}`, {
  276. method: 'DELETE',
  277. });
  278. if (!response.ok) {
  279. throw new Error('Failed to delete file');
  280. }
  281. refetch();
  282. } catch (error) {
  283. console.error('Error deleting file:', error);
  284. alert('Failed to delete file. Please try again.');
  285. }
  286. };
  287. if (isLoading) {
  288. return (
  289. <Card>
  290. <CardHeader>
  291. <CardTitle>Files in Database</CardTitle>
  292. </CardHeader>
  293. <CardContent>
  294. <div className="space-y-3">
  295. {[...Array(5)].map((_, i) => (
  296. <div key={i} className="flex items-center space-x-4">
  297. <Skeleton className="h-12 w-full" />
  298. </div>
  299. ))}
  300. </div>
  301. </CardContent>
  302. </Card>
  303. );
  304. }
  305. if (isError) {
  306. return (
  307. <Card className="border-red-200">
  308. <CardContent className="pt-6">
  309. <div className="flex items-center text-red-700">
  310. <AlertCircle className="h-5 w-5 mr-2" />
  311. <span>Error: {error?.message || "Failed to load files"}</span>
  312. </div>
  313. <Button onClick={handleRefresh} className="mt-3" variant="outline">
  314. Retry
  315. </Button>
  316. </CardContent>
  317. </Card>
  318. );
  319. }
  320. if (!data || data.length === 0) {
  321. return (
  322. <Card>
  323. <CardContent className="pt-6">
  324. <div className="text-center">
  325. <div className="mx-auto h-12 w-12 text-gray-400">
  326. <svg fill="none" viewBox="0 0 24 24" stroke="currentColor">
  327. <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 13h6m-3-3v6m-9 1V7a2 2 0 012-2h6l2 2h6a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2z" />
  328. </svg>
  329. </div>
  330. <h3 className="mt-2 text-sm font-medium">No files found</h3>
  331. <p className="mt-1 text-sm text-muted-foreground">Upload some files to get started.</p>
  332. </div>
  333. </CardContent>
  334. </Card>
  335. );
  336. }
  337. return (
  338. <Card>
  339. <CardHeader>
  340. <div className="flex justify-between items-center">
  341. <CardTitle>Files in Database</CardTitle>
  342. <div className="flex gap-2">
  343. <div className="flex items-center gap-2">
  344. <Input
  345. type="file"
  346. onChange={handleFileUpload}
  347. disabled={isUploading}
  348. className="w-64 text-sm"
  349. />
  350. {isUploading && (
  351. <span className="text-sm text-muted-foreground">Uploading...</span>
  352. )}
  353. </div>
  354. <Button
  355. onClick={handleDownloadSelected}
  356. disabled={table.getSelectedRowModel().rows.length === 0 || isLoading}
  357. variant="outline"
  358. size="sm"
  359. >
  360. <Download className="h-4 w-4 mr-2" />
  361. Download Selected
  362. </Button>
  363. <Button
  364. onClick={handleDeleteSelected}
  365. disabled={table.getSelectedRowModel().rows.length === 0 || isLoading}
  366. variant="destructive"
  367. size="sm"
  368. >
  369. <Trash2 className="h-4 w-4 mr-2" />
  370. Delete Selected
  371. </Button>
  372. <Button
  373. onClick={handleRefresh}
  374. disabled={isLoading}
  375. variant="outline"
  376. size="sm"
  377. >
  378. <RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />
  379. Refresh
  380. </Button>
  381. </div>
  382. </div>
  383. </CardHeader>
  384. <CardContent>
  385. <div className="rounded-md border">
  386. <Table>
  387. <TableHeader>
  388. {table.getHeaderGroups().map((headerGroup) => (
  389. <TableRow key={headerGroup.id}>
  390. {headerGroup.headers.map((header) => (
  391. <TableHead
  392. key={header.id}
  393. onClick={header.column.getToggleSortingHandler()}
  394. className="cursor-pointer"
  395. >
  396. {flexRender(
  397. header.column.columnDef.header,
  398. header.getContext()
  399. )}
  400. {header.column.getIsSorted() && (
  401. <span className="ml-1">
  402. {header.column.getIsSorted() === "asc" ? "↑" : "↓"}
  403. </span>
  404. )}
  405. </TableHead>
  406. ))}
  407. </TableRow>
  408. ))}
  409. </TableHeader>
  410. <TableBody>
  411. {table.getRowModel().rows.map((row) => (
  412. <TableRow
  413. key={row.id}
  414. data-state={row.getIsSelected() && "selected"}
  415. >
  416. {row.getVisibleCells().map((cell) => (
  417. <TableCell key={cell.id}>
  418. {flexRender(cell.column.columnDef.cell, cell.getContext())}
  419. </TableCell>
  420. ))}
  421. </TableRow>
  422. ))}
  423. </TableBody>
  424. </Table>
  425. </div>
  426. <div className="flex items-center justify-between mt-4">
  427. <div className="text-sm text-muted-foreground">
  428. {table.getSelectedRowModel().rows.length} of {files.length} row(s) selected
  429. </div>
  430. <div className="flex gap-2">
  431. <Button
  432. onClick={() => table.previousPage()}
  433. disabled={!table.getCanPreviousPage()}
  434. variant="outline"
  435. size="sm"
  436. >
  437. Previous
  438. </Button>
  439. <Button
  440. onClick={() => table.nextPage()}
  441. disabled={!table.getCanNextPage()}
  442. variant="outline"
  443. size="sm"
  444. >
  445. Next
  446. </Button>
  447. </div>
  448. </div>
  449. </CardContent>
  450. </Card>
  451. );
  452. }