filesTable.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. "use client";
  2. import { useState } 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. interface FileData {
  15. id: string;
  16. filename: string;
  17. mimetype: string;
  18. size: number;
  19. createdAt: string;
  20. updatedAt: string;
  21. }
  22. export function FilesTable() {
  23. const [sorting, setSorting] = useState<SortingState>([]);
  24. const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
  25. const { data, isLoading, isError, error, refetch } = useQuery({
  26. queryKey: ["files"],
  27. queryFn: async () => {
  28. const response = await fetch("/api/files");
  29. if (!response.ok) {
  30. throw new Error("Failed to fetch files");
  31. }
  32. const data = await response.json();
  33. return data.files as FileData[];
  34. },
  35. });
  36. const columns: ColumnDef<FileData>[] = [
  37. {
  38. id: "select",
  39. header: ({ table }) => (
  40. <div className="px-6 py-3">
  41. <input
  42. type="checkbox"
  43. checked={table.getIsAllPageRowsSelected()}
  44. onChange={(e) => table.toggleAllPageRowsSelected(!!e.target.checked)}
  45. className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
  46. />
  47. </div>
  48. ),
  49. cell: ({ row }) => (
  50. <div className="px-6 py-4">
  51. <input
  52. type="checkbox"
  53. checked={row.getIsSelected()}
  54. onChange={(e) => row.toggleSelected(!!e.target.checked)}
  55. className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
  56. />
  57. </div>
  58. ),
  59. enableSorting: false,
  60. enableHiding: false,
  61. },
  62. {
  63. accessorKey: "filename",
  64. header: "File Name",
  65. cell: ({ row }) => (
  66. <div className="font-medium text-gray-900">{row.getValue("filename")}</div>
  67. ),
  68. },
  69. {
  70. accessorKey: "mimetype",
  71. header: "Type",
  72. cell: ({ row }) => (
  73. <div className="text-sm text-gray-600">{row.getValue("mimetype")}</div>
  74. ),
  75. },
  76. {
  77. accessorKey: "size",
  78. header: "Size",
  79. cell: ({ row }) => {
  80. const bytes = row.getValue("size") as number;
  81. if (bytes === 0) return "0 Bytes";
  82. const k = 1024;
  83. const sizes = ["Bytes", "KB", "MB", "GB"];
  84. const i = Math.floor(Math.log(bytes) / Math.log(k));
  85. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  86. },
  87. },
  88. {
  89. accessorKey: "createdAt",
  90. header: "Created",
  91. cell: ({ row }) => {
  92. const date = new Date(row.getValue("createdAt"));
  93. return date.toLocaleDateString("en-US", {
  94. year: "numeric",
  95. month: "short",
  96. day: "numeric",
  97. hour: "2-digit",
  98. minute: "2-digit",
  99. });
  100. },
  101. },
  102. {
  103. accessorKey: "updatedAt",
  104. header: "Updated",
  105. cell: ({ row }) => {
  106. const date = new Date(row.getValue("updatedAt"));
  107. return date.toLocaleDateString("en-US", {
  108. year: "numeric",
  109. month: "short",
  110. day: "numeric",
  111. hour: "2-digit",
  112. minute: "2-digit",
  113. });
  114. },
  115. },
  116. {
  117. id: "actions",
  118. header: "Actions",
  119. cell: ({ row }) => (
  120. <div className="flex gap-2">
  121. <button
  122. onClick={() => handleDeleteFile(row.original.id, row.original.filename)}
  123. className="text-red-600 hover:text-red-800 transition-colors"
  124. title="Delete file"
  125. >
  126. <svg
  127. className="w-5 h-5"
  128. fill="none"
  129. stroke="currentColor"
  130. viewBox="0 0 24 24"
  131. >
  132. <path
  133. strokeLinecap="round"
  134. strokeLinejoin="round"
  135. strokeWidth={2}
  136. d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
  137. />
  138. </svg>
  139. </button>
  140. </div>
  141. ),
  142. enableSorting: false,
  143. },
  144. ];
  145. const table = useReactTable({
  146. data: data || [],
  147. columns,
  148. state: {
  149. sorting,
  150. rowSelection,
  151. },
  152. onSortingChange: setSorting,
  153. onRowSelectionChange: setRowSelection,
  154. getCoreRowModel: getCoreRowModel(),
  155. getPaginationRowModel: getPaginationRowModel(),
  156. getSortedRowModel: getSortedRowModel(),
  157. enableRowSelection: true,
  158. });
  159. const handleRefresh = () => {
  160. refetch();
  161. };
  162. const handleDownload = (fileId: string, filename: string) => {
  163. const downloadUrl = `/api/files/${fileId}`;
  164. const link = document.createElement('a');
  165. link.href = downloadUrl;
  166. link.download = filename;
  167. document.body.appendChild(link);
  168. link.click();
  169. document.body.removeChild(link);
  170. };
  171. const handleDownloadSelected = () => {
  172. const selectedRows = table.getSelectedRowModel().rows;
  173. if (selectedRows.length === 0) return;
  174. if (selectedRows.length === 1) {
  175. // Single file download
  176. const selected = selectedRows[0];
  177. handleDownload(selected.original.id, selected.original.filename);
  178. } else {
  179. // Multiple files - download each one
  180. selectedRows.forEach((row, index) => {
  181. setTimeout(() => {
  182. handleDownload(row.original.id, row.original.filename);
  183. }, index * 500); // Stagger downloads by 500ms to avoid browser blocking
  184. });
  185. }
  186. };
  187. const handleDeleteSelected = async () => {
  188. const selectedRows = table.getSelectedRowModel().rows;
  189. if (selectedRows.length === 0) return;
  190. const confirmDelete = window.confirm(
  191. `Are you sure you want to delete ${selectedRows.length} file${selectedRows.length > 1 ? 's' : ''}? This action cannot be undone.`
  192. );
  193. if (!confirmDelete) return;
  194. try {
  195. const deletePromises = selectedRows.map(async (row) => {
  196. const response = await fetch(`/api/files/${row.original.id}`, {
  197. method: 'DELETE',
  198. });
  199. if (!response.ok) {
  200. throw new Error(`Failed to delete file: ${row.original.filename}`);
  201. }
  202. return row.original.id;
  203. });
  204. await Promise.all(deletePromises);
  205. // Clear selection and refresh the table
  206. setRowSelection({});
  207. refetch();
  208. } catch (error) {
  209. console.error('Error deleting files:', error);
  210. alert('Failed to delete some files. Please try again.');
  211. }
  212. };
  213. const handleDeleteFile = async (fileId: string, filename: string) => {
  214. const confirmDelete = window.confirm(
  215. `Are you sure you want to delete "${filename}"? This action cannot be undone.`
  216. );
  217. if (!confirmDelete) return;
  218. try {
  219. const response = await fetch(`/api/files/${fileId}`, {
  220. method: 'DELETE',
  221. });
  222. if (!response.ok) {
  223. throw new Error('Failed to delete file');
  224. }
  225. refetch();
  226. } catch (error) {
  227. console.error('Error deleting file:', error);
  228. alert('Failed to delete file. Please try again.');
  229. }
  230. };
  231. if (isLoading) {
  232. return (
  233. <div className="bg-white rounded-lg shadow-sm border border-gray-200">
  234. <div className="p-6">
  235. <div className="flex justify-between items-center mb-4">
  236. <h2 className="text-xl font-semibold text-gray-900">Files in Database</h2>
  237. <div className="h-8 w-24 bg-gray-200 rounded animate-pulse"></div>
  238. </div>
  239. <div className="space-y-3">
  240. {[...Array(5)].map((_, i) => (
  241. <div key={i} className="h-12 bg-gray-100 rounded animate-pulse"></div>
  242. ))}
  243. </div>
  244. </div>
  245. </div>
  246. );
  247. }
  248. if (isError) {
  249. return (
  250. <div className="bg-red-50 border border-red-200 rounded-lg p-6">
  251. <div className="flex items-center">
  252. <svg className="w-5 h-5 text-red-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
  253. <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
  254. </svg>
  255. <span className="text-red-700">Error: {error?.message || "Failed to load files"}</span>
  256. </div>
  257. <button
  258. onClick={handleRefresh}
  259. className="mt-3 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors"
  260. >
  261. Retry
  262. </button>
  263. </div>
  264. );
  265. }
  266. if (!data || data.length === 0) {
  267. return (
  268. <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
  269. <div className="text-center">
  270. <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
  271. <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" />
  272. </svg>
  273. <h3 className="mt-2 text-sm font-medium text-gray-900">No files found</h3>
  274. <p className="mt-1 text-sm text-gray-500">Upload some files to get started.</p>
  275. </div>
  276. </div>
  277. );
  278. }
  279. return (
  280. <div className="bg-white rounded-lg shadow-sm border border-gray-200">
  281. <div className="p-6">
  282. <div className="flex justify-between items-center mb-4">
  283. <h2 className="text-xl font-semibold text-gray-900">Files in Database</h2>
  284. <div className="flex gap-2">
  285. <button
  286. onClick={handleDownloadSelected}
  287. disabled={table.getSelectedRowModel().rows.length === 0 || isLoading}
  288. className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center"
  289. >
  290. <svg
  291. className="w-4 h-4 mr-2"
  292. fill="none"
  293. stroke="currentColor"
  294. viewBox="0 0 24 24"
  295. >
  296. <path
  297. strokeLinecap="round"
  298. strokeLinejoin="round"
  299. strokeWidth={2}
  300. d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
  301. />
  302. </svg>
  303. Download Selected
  304. </button>
  305. <button
  306. onClick={handleDeleteSelected}
  307. disabled={table.getSelectedRowModel().rows.length === 0 || isLoading}
  308. className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center"
  309. >
  310. <svg
  311. className="w-4 h-4 mr-2"
  312. fill="none"
  313. stroke="currentColor"
  314. viewBox="0 0 24 24"
  315. >
  316. <path
  317. strokeLinecap="round"
  318. strokeLinejoin="round"
  319. strokeWidth={2}
  320. d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
  321. />
  322. </svg>
  323. Delete Selected
  324. </button>
  325. <button
  326. onClick={handleRefresh}
  327. disabled={isLoading}
  328. className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center"
  329. >
  330. <svg
  331. className={`w-4 h-4 mr-2 ${isLoading ? "animate-spin" : ""}`}
  332. fill="none"
  333. stroke="currentColor"
  334. viewBox="0 0 24 24"
  335. >
  336. <path
  337. strokeLinecap="round"
  338. strokeLinejoin="round"
  339. strokeWidth={2}
  340. d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
  341. />
  342. </svg>
  343. Refresh
  344. </button>
  345. </div>
  346. </div>
  347. <div className="overflow-x-auto">
  348. <table className="min-w-full divide-y divide-gray-200">
  349. <thead className="bg-gray-50">
  350. {table.getHeaderGroups().map((headerGroup) => (
  351. <tr key={headerGroup.id}>
  352. {headerGroup.headers.map((header) => (
  353. <th
  354. key={header.id}
  355. className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
  356. onClick={header.column.getToggleSortingHandler()}
  357. >
  358. <div className="flex items-center">
  359. {flexRender(header.column.columnDef.header, header.getContext())}
  360. {header.column.getIsSorted() && (
  361. <span className="ml-1">
  362. {header.column.getIsSorted() === "asc" ? "↑" : "↓"}
  363. </span>
  364. )}
  365. </div>
  366. </th>
  367. ))}
  368. </tr>
  369. ))}
  370. </thead>
  371. <tbody className="bg-white divide-y divide-gray-200">
  372. {table.getRowModel().rows.map((row) => (
  373. <tr
  374. key={row.id}
  375. className={`hover:bg-gray-50 ${row.getIsSelected() ? 'bg-blue-50' : ''}`}
  376. >
  377. {row.getVisibleCells().map((cell) => (
  378. <td key={cell.id} className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
  379. {flexRender(cell.column.columnDef.cell, cell.getContext())}
  380. </td>
  381. ))}
  382. </tr>
  383. ))}
  384. </tbody>
  385. </table>
  386. </div>
  387. {/* Pagination */}
  388. <div className="flex items-center justify-between mt-4">
  389. <div className="text-sm text-gray-700">
  390. Showing {table.getRowModel().rows.length} of {data.length} results
  391. </div>
  392. <div className="flex gap-2">
  393. <button
  394. onClick={() => table.previousPage()}
  395. disabled={!table.getCanPreviousPage()}
  396. className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50"
  397. >
  398. Previous
  399. </button>
  400. <button
  401. onClick={() => table.nextPage()}
  402. disabled={!table.getCanNextPage()}
  403. className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50"
  404. >
  405. Next
  406. </button>
  407. </div>
  408. </div>
  409. </div>
  410. </div>
  411. );
  412. }