filesTable.tsx 14 KB

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