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