filesTable.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. const columns: ColumnDef<FileData>[] = [
  23. {
  24. id: "select",
  25. header: ({ table }) => (
  26. <div className="px-6 py-3">
  27. <input
  28. type="checkbox"
  29. checked={table.getIsAllPageRowsSelected()}
  30. onChange={(e) => table.toggleAllPageRowsSelected(!!e.target.checked)}
  31. className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
  32. />
  33. </div>
  34. ),
  35. cell: ({ row }) => (
  36. <div className="px-6 py-4">
  37. <input
  38. type="checkbox"
  39. checked={row.getIsSelected()}
  40. onChange={(e) => row.toggleSelected(!!e.target.checked)}
  41. className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
  42. />
  43. </div>
  44. ),
  45. enableSorting: false,
  46. enableHiding: false,
  47. },
  48. {
  49. accessorKey: "filename",
  50. header: "File Name",
  51. cell: ({ row }) => (
  52. <div className="font-medium text-gray-900">{row.getValue("filename")}</div>
  53. ),
  54. },
  55. {
  56. accessorKey: "mimetype",
  57. header: "Type",
  58. cell: ({ row }) => (
  59. <div className="text-sm text-gray-600">{row.getValue("mimetype")}</div>
  60. ),
  61. },
  62. {
  63. accessorKey: "size",
  64. header: "Size",
  65. cell: ({ row }) => {
  66. const bytes = row.getValue("size") as number;
  67. if (bytes === 0) return "0 Bytes";
  68. const k = 1024;
  69. const sizes = ["Bytes", "KB", "MB", "GB"];
  70. const i = Math.floor(Math.log(bytes) / Math.log(k));
  71. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  72. },
  73. },
  74. {
  75. accessorKey: "createdAt",
  76. header: "Created",
  77. cell: ({ row }) => {
  78. const date = new Date(row.getValue("createdAt"));
  79. return date.toLocaleDateString("en-US", {
  80. year: "numeric",
  81. month: "short",
  82. day: "numeric",
  83. hour: "2-digit",
  84. minute: "2-digit",
  85. });
  86. },
  87. },
  88. {
  89. accessorKey: "updatedAt",
  90. header: "Updated",
  91. cell: ({ row }) => {
  92. const date = new Date(row.getValue("updatedAt"));
  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. export function FilesTable() {
  104. const [sorting, setSorting] = useState<SortingState>([]);
  105. const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
  106. const { data, isLoading, isError, error, refetch } = useQuery({
  107. queryKey: ["files"],
  108. queryFn: async () => {
  109. const response = await fetch("/api/files");
  110. if (!response.ok) {
  111. throw new Error("Failed to fetch files");
  112. }
  113. const data = await response.json();
  114. return data.files as FileData[];
  115. },
  116. });
  117. const table = useReactTable({
  118. data: data || [],
  119. columns,
  120. state: {
  121. sorting,
  122. rowSelection,
  123. },
  124. onSortingChange: setSorting,
  125. onRowSelectionChange: setRowSelection,
  126. getCoreRowModel: getCoreRowModel(),
  127. getPaginationRowModel: getPaginationRowModel(),
  128. getSortedRowModel: getSortedRowModel(),
  129. enableRowSelection: true,
  130. });
  131. const handleRefresh = () => {
  132. refetch();
  133. };
  134. const handleDownload = (fileId: string, filename: string) => {
  135. const downloadUrl = `/api/files/${fileId}`;
  136. const link = document.createElement('a');
  137. link.href = downloadUrl;
  138. link.download = filename;
  139. document.body.appendChild(link);
  140. link.click();
  141. document.body.removeChild(link);
  142. };
  143. const handleDownloadSelected = () => {
  144. const selectedRows = table.getSelectedRowModel().rows;
  145. if (selectedRows.length === 0) return;
  146. if (selectedRows.length === 1) {
  147. // Single file download
  148. const selected = selectedRows[0];
  149. handleDownload(selected.original.id, selected.original.filename);
  150. } else {
  151. // Multiple files - download each one
  152. selectedRows.forEach((row, index) => {
  153. setTimeout(() => {
  154. handleDownload(row.original.id, row.original.filename);
  155. }, index * 500); // Stagger downloads by 500ms to avoid browser blocking
  156. });
  157. }
  158. };
  159. if (isLoading) {
  160. return (
  161. <div className="bg-white rounded-lg shadow-sm border border-gray-200">
  162. <div className="p-6">
  163. <div className="flex justify-between items-center mb-4">
  164. <h2 className="text-xl font-semibold text-gray-900">Files in Database</h2>
  165. <div className="h-8 w-24 bg-gray-200 rounded animate-pulse"></div>
  166. </div>
  167. <div className="space-y-3">
  168. {[...Array(5)].map((_, i) => (
  169. <div key={i} className="h-12 bg-gray-100 rounded animate-pulse"></div>
  170. ))}
  171. </div>
  172. </div>
  173. </div>
  174. );
  175. }
  176. if (isError) {
  177. return (
  178. <div className="bg-red-50 border border-red-200 rounded-lg p-6">
  179. <div className="flex items-center">
  180. <svg className="w-5 h-5 text-red-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
  181. <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" />
  182. </svg>
  183. <span className="text-red-700">Error: {error?.message || "Failed to load files"}</span>
  184. </div>
  185. <button
  186. onClick={handleRefresh}
  187. className="mt-3 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors"
  188. >
  189. Retry
  190. </button>
  191. </div>
  192. );
  193. }
  194. if (!data || data.length === 0) {
  195. return (
  196. <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
  197. <div className="text-center">
  198. <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
  199. <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" />
  200. </svg>
  201. <h3 className="mt-2 text-sm font-medium text-gray-900">No files found</h3>
  202. <p className="mt-1 text-sm text-gray-500">Upload some files to get started.</p>
  203. </div>
  204. </div>
  205. );
  206. }
  207. return (
  208. <div className="bg-white rounded-lg shadow-sm border border-gray-200">
  209. <div className="p-6">
  210. <div className="flex justify-between items-center mb-4">
  211. <h2 className="text-xl font-semibold text-gray-900">Files in Database</h2>
  212. <div className="flex gap-2">
  213. <button
  214. onClick={handleDownloadSelected}
  215. disabled={table.getSelectedRowModel().rows.length === 0 || isLoading}
  216. 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"
  217. >
  218. <svg
  219. className="w-4 h-4 mr-2"
  220. fill="none"
  221. stroke="currentColor"
  222. viewBox="0 0 24 24"
  223. >
  224. <path
  225. strokeLinecap="round"
  226. strokeLinejoin="round"
  227. strokeWidth={2}
  228. 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"
  229. />
  230. </svg>
  231. Download Selected
  232. </button>
  233. <button
  234. onClick={handleRefresh}
  235. disabled={isLoading}
  236. 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"
  237. >
  238. <svg
  239. className={`w-4 h-4 mr-2 ${isLoading ? "animate-spin" : ""}`}
  240. fill="none"
  241. stroke="currentColor"
  242. viewBox="0 0 24 24"
  243. >
  244. <path
  245. strokeLinecap="round"
  246. strokeLinejoin="round"
  247. strokeWidth={2}
  248. 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"
  249. />
  250. </svg>
  251. Refresh
  252. </button>
  253. </div>
  254. </div>
  255. <div className="overflow-x-auto">
  256. <table className="min-w-full divide-y divide-gray-200">
  257. <thead className="bg-gray-50">
  258. {table.getHeaderGroups().map((headerGroup) => (
  259. <tr key={headerGroup.id}>
  260. {headerGroup.headers.map((header) => (
  261. <th
  262. key={header.id}
  263. className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
  264. onClick={header.column.getToggleSortingHandler()}
  265. >
  266. <div className="flex items-center">
  267. {flexRender(header.column.columnDef.header, header.getContext())}
  268. {header.column.getIsSorted() && (
  269. <span className="ml-1">
  270. {header.column.getIsSorted() === "asc" ? "↑" : "↓"}
  271. </span>
  272. )}
  273. </div>
  274. </th>
  275. ))}
  276. </tr>
  277. ))}
  278. </thead>
  279. <tbody className="bg-white divide-y divide-gray-200">
  280. {table.getRowModel().rows.map((row) => (
  281. <tr
  282. key={row.id}
  283. className={`hover:bg-gray-50 ${row.getIsSelected() ? 'bg-blue-50' : ''}`}
  284. >
  285. {row.getVisibleCells().map((cell) => (
  286. <td key={cell.id} className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
  287. {flexRender(cell.column.columnDef.cell, cell.getContext())}
  288. </td>
  289. ))}
  290. </tr>
  291. ))}
  292. </tbody>
  293. </table>
  294. </div>
  295. {/* Pagination */}
  296. <div className="flex items-center justify-between mt-4">
  297. <div className="text-sm text-gray-700">
  298. Showing {table.getRowModel().rows.length} of {data.length} results
  299. </div>
  300. <div className="flex gap-2">
  301. <button
  302. onClick={() => table.previousPage()}
  303. disabled={!table.getCanPreviousPage()}
  304. className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50"
  305. >
  306. Previous
  307. </button>
  308. <button
  309. onClick={() => table.nextPage()}
  310. disabled={!table.getCanNextPage()}
  311. className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50"
  312. >
  313. Next
  314. </button>
  315. </div>
  316. </div>
  317. </div>
  318. </div>
  319. );
  320. }