filesTable.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 } 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. interface FileData {
  28. id: string;
  29. filename: string;
  30. mimetype: string;
  31. size: number;
  32. createdAt: string;
  33. updatedAt: string;
  34. }
  35. interface FilesTableProps {
  36. onFileAdded?: (file: FileData) => void;
  37. }
  38. export function FilesTable({}: FilesTableProps) {
  39. const [sorting, setSorting] = useState<SortingState>([]);
  40. const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
  41. const [files, setFiles] = useState<FileData[]>([]);
  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 handleRefresh = () => {
  177. refetch();
  178. };
  179. const handleDownload = (fileId: string, filename: string) => {
  180. const downloadUrl = `/api/files/${fileId}`;
  181. const link = document.createElement('a');
  182. link.href = downloadUrl;
  183. link.download = filename;
  184. document.body.appendChild(link);
  185. link.click();
  186. document.body.removeChild(link);
  187. };
  188. const handleDownloadSelected = () => {
  189. const selectedRows = table.getSelectedRowModel().rows;
  190. if (selectedRows.length === 0) return;
  191. if (selectedRows.length === 1) {
  192. const selected = selectedRows[0];
  193. handleDownload(selected.original.id, selected.original.filename);
  194. } else {
  195. selectedRows.forEach((row, index) => {
  196. setTimeout(() => {
  197. handleDownload(row.original.id, row.original.filename);
  198. }, index * 500);
  199. });
  200. }
  201. };
  202. const handleDeleteSelected = async () => {
  203. const selectedRows = table.getSelectedRowModel().rows;
  204. if (selectedRows.length === 0) return;
  205. const confirmDelete = window.confirm(
  206. `Are you sure you want to delete ${selectedRows.length} file${selectedRows.length > 1 ? 's' : ''}? This action cannot be undone.`
  207. );
  208. if (!confirmDelete) return;
  209. try {
  210. const results = [];
  211. for (const row of selectedRows) {
  212. try {
  213. const response = await fetch(`/api/files/${row.original.id}`, {
  214. method: 'DELETE',
  215. });
  216. if (!response.ok) {
  217. const errorText = await response.text();
  218. results.push({ id: row.original.id, success: false, error: errorText });
  219. } else {
  220. results.push({ id: row.original.id, success: true });
  221. }
  222. } catch (error) {
  223. results.push({ id: row.original.id, success: false, error: String(error) });
  224. }
  225. }
  226. const successful = results.filter(r => r.success).length;
  227. const failed = results.filter(r => !r.success).length;
  228. if (failed > 0) {
  229. alert(`${successful} file(s) deleted successfully, ${failed} failed.`);
  230. } else {
  231. alert(`${successful} file(s) deleted successfully.`);
  232. }
  233. setRowSelection({});
  234. refetch();
  235. } catch (error) {
  236. console.error('Error in delete process:', error);
  237. alert('Failed to delete files. Please try again.');
  238. }
  239. };
  240. const handleDeleteFile = async (fileId: string, filename: string) => {
  241. const confirmDelete = window.confirm(
  242. `Are you sure you want to delete "${filename}"? This action cannot be undone.`
  243. );
  244. if (!confirmDelete) return;
  245. try {
  246. const response = await fetch(`/api/files/${fileId}`, {
  247. method: 'DELETE',
  248. });
  249. if (!response.ok) {
  250. throw new Error('Failed to delete file');
  251. }
  252. refetch();
  253. } catch (error) {
  254. console.error('Error deleting file:', error);
  255. alert('Failed to delete file. Please try again.');
  256. }
  257. };
  258. if (isLoading) {
  259. return (
  260. <Card>
  261. <CardHeader>
  262. <CardTitle>Files in Database</CardTitle>
  263. </CardHeader>
  264. <CardContent>
  265. <div className="space-y-3">
  266. {[...Array(5)].map((_, i) => (
  267. <div key={i} className="flex items-center space-x-4">
  268. <Skeleton className="h-12 w-full" />
  269. </div>
  270. ))}
  271. </div>
  272. </CardContent>
  273. </Card>
  274. );
  275. }
  276. if (isError) {
  277. return (
  278. <Card className="border-red-200">
  279. <CardContent className="pt-6">
  280. <div className="flex items-center text-red-700">
  281. <AlertCircle className="h-5 w-5 mr-2" />
  282. <span>Error: {error?.message || "Failed to load files"}</span>
  283. </div>
  284. <Button onClick={handleRefresh} className="mt-3" variant="outline">
  285. Retry
  286. </Button>
  287. </CardContent>
  288. </Card>
  289. );
  290. }
  291. if (!data || data.length === 0) {
  292. return (
  293. <Card>
  294. <CardContent className="pt-6">
  295. <div className="text-center">
  296. <div className="mx-auto h-12 w-12 text-gray-400">
  297. <svg fill="none" viewBox="0 0 24 24" stroke="currentColor">
  298. <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" />
  299. </svg>
  300. </div>
  301. <h3 className="mt-2 text-sm font-medium">No files found</h3>
  302. <p className="mt-1 text-sm text-muted-foreground">Upload some files to get started.</p>
  303. </div>
  304. </CardContent>
  305. </Card>
  306. );
  307. }
  308. return (
  309. <Card>
  310. <CardHeader>
  311. <div className="flex justify-between items-center">
  312. <CardTitle>Files in Database</CardTitle>
  313. <div className="flex gap-2">
  314. <Button
  315. onClick={handleDownloadSelected}
  316. disabled={table.getSelectedRowModel().rows.length === 0 || isLoading}
  317. variant="outline"
  318. size="sm"
  319. >
  320. <Download className="h-4 w-4 mr-2" />
  321. Download Selected
  322. </Button>
  323. <Button
  324. onClick={handleDeleteSelected}
  325. disabled={table.getSelectedRowModel().rows.length === 0 || isLoading}
  326. variant="destructive"
  327. size="sm"
  328. >
  329. <Trash2 className="h-4 w-4 mr-2" />
  330. Delete Selected
  331. </Button>
  332. <Button
  333. onClick={handleRefresh}
  334. disabled={isLoading}
  335. variant="outline"
  336. size="sm"
  337. >
  338. <RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />
  339. Refresh
  340. </Button>
  341. </div>
  342. </div>
  343. </CardHeader>
  344. <CardContent>
  345. <div className="rounded-md border">
  346. <Table>
  347. <TableHeader>
  348. {table.getHeaderGroups().map((headerGroup) => (
  349. <TableRow key={headerGroup.id}>
  350. {headerGroup.headers.map((header) => (
  351. <TableHead
  352. key={header.id}
  353. onClick={header.column.getToggleSortingHandler()}
  354. className="cursor-pointer"
  355. >
  356. {flexRender(
  357. header.column.columnDef.header,
  358. header.getContext()
  359. )}
  360. {header.column.getIsSorted() && (
  361. <span className="ml-1">
  362. {header.column.getIsSorted() === "asc" ? "↑" : "↓"}
  363. </span>
  364. )}
  365. </TableHead>
  366. ))}
  367. </TableRow>
  368. ))}
  369. </TableHeader>
  370. <TableBody>
  371. {table.getRowModel().rows.map((row) => (
  372. <TableRow
  373. key={row.id}
  374. data-state={row.getIsSelected() && "selected"}
  375. >
  376. {row.getVisibleCells().map((cell) => (
  377. <TableCell key={cell.id}>
  378. {flexRender(cell.column.columnDef.cell, cell.getContext())}
  379. </TableCell>
  380. ))}
  381. </TableRow>
  382. ))}
  383. </TableBody>
  384. </Table>
  385. </div>
  386. <div className="flex items-center justify-between mt-4">
  387. <div className="text-sm text-muted-foreground">
  388. {table.getRowModel().rows.length} of {files.length} row(s) selected
  389. </div>
  390. <div className="flex gap-2">
  391. <Button
  392. onClick={() => table.previousPage()}
  393. disabled={!table.getCanPreviousPage()}
  394. variant="outline"
  395. size="sm"
  396. >
  397. Previous
  398. </Button>
  399. <Button
  400. onClick={() => table.nextPage()}
  401. disabled={!table.getCanNextPage()}
  402. variant="outline"
  403. size="sm"
  404. >
  405. Next
  406. </Button>
  407. </div>
  408. </div>
  409. </CardContent>
  410. </Card>
  411. );
  412. }