urls-table.tsx539 lines, 17 KB
| 1 | "use client"; |
| 2 | |
| 3 | import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; |
| 4 | import { Badge } from "@/components/ui/badge"; |
| 5 | import { Button } from "@/components/ui/button"; |
| 6 | import { |
| 7 | DropdownMenu, |
| 8 | DropdownMenuContent, |
| 9 | DropdownMenuItem, |
| 10 | DropdownMenuLabel, |
| 11 | DropdownMenuSeparator, |
| 12 | DropdownMenuTrigger, |
| 13 | } from "@/components/ui/dropdown-menu"; |
| 14 | import { |
| 15 | Pagination, |
| 16 | PaginationContent, |
| 17 | PaginationEllipsis, |
| 18 | PaginationItem, |
| 19 | PaginationLink, |
| 20 | PaginationNext, |
| 21 | PaginationPrevious, |
| 22 | } from "@/components/ui/pagination"; |
| 23 | import { |
| 24 | Table, |
| 25 | TableBody, |
| 26 | TableCell, |
| 27 | TableHead, |
| 28 | TableHeader, |
| 29 | TableRow, |
| 30 | } from "@/components/ui/table"; |
| 31 | import { UrlWithUser } from "@/server/actions/admin/urls/get-all-urls"; |
| 32 | import { manageFlaggedUrl } from "@/server/actions/admin/urls/manage-flagged-url"; |
| 33 | import { formatDistanceToNow } from "date-fns"; |
| 34 | import { |
| 35 | AlertTriangle, |
| 36 | ArrowDown, |
| 37 | ArrowUp, |
| 38 | ArrowUpDown, |
| 39 | Ban, |
| 40 | CheckCircle, |
| 41 | Copy, |
| 42 | ExternalLink, |
| 43 | Loader2, |
| 44 | MoreHorizontal, |
| 45 | User, |
| 46 | } from "lucide-react"; |
| 47 | import { useRouter } from "next/navigation"; |
| 48 | import { useState } from "react"; |
| 49 | import { toast } from "sonner"; |
| 50 | |
| 51 | interface UrlsTableProps { |
| 52 | urls: UrlWithUser[]; |
| 53 | total: number; |
| 54 | currentPage: number; |
| 55 | currentSearch: string; |
| 56 | currentSortBy: string; |
| 57 | currentSortOrder: string; |
| 58 | highlightStyle?: "security" | "inappropriate" | "other" | "none"; |
| 59 | } |
| 60 | |
| 61 | export function UrlsTable({ |
| 62 | urls, |
| 63 | total, |
| 64 | currentPage, |
| 65 | currentSearch, |
| 66 | currentSortBy, |
| 67 | currentSortOrder, |
| 68 | highlightStyle, |
| 69 | }: UrlsTableProps) { |
| 70 | const router = useRouter(); |
| 71 | const [copyingId, setCopyingId] = useState<number | null>(null); |
| 72 | const [actionLoading, setActionLoading] = useState<number | null>(null); |
| 73 | |
| 74 | // Get the current path from window location or default to /admin/urls |
| 75 | const basePath = |
| 76 | typeof window !== "undefined" ? window.location.pathname : "/admin/urls"; |
| 77 | |
| 78 | // Extract any additional query parameters that should be preserved |
| 79 | const preserveParams = () => { |
| 80 | if (typeof window === "undefined") return ""; |
| 81 | |
| 82 | const url = new URL(window.location.href); |
| 83 | const params = new URLSearchParams(url.search); |
| 84 | let paramString = ""; |
| 85 | |
| 86 | // Preserve filter parameter if it exists |
| 87 | if (params.has("filter")) { |
| 88 | paramString += `&filter=${params.get("filter")}`; |
| 89 | } |
| 90 | |
| 91 | return paramString; |
| 92 | }; |
| 93 | |
| 94 | const limit = 10; |
| 95 | const totalPage = Math.ceil(total / limit); |
| 96 | |
| 97 | const handleSort = (column: string) => { |
| 98 | const params = new URLSearchParams(); |
| 99 | |
| 100 | if (currentSearch) { |
| 101 | params.set("search", currentSearch); |
| 102 | } |
| 103 | |
| 104 | params.set("sortBy", column); |
| 105 | |
| 106 | if (currentSortBy === column) { |
| 107 | params.set("sortOrder", currentSortOrder === "asc" ? "desc" : "asc"); |
| 108 | } else { |
| 109 | params.set("sortOrder", "asc"); |
| 110 | } |
| 111 | |
| 112 | params.set("page", "1"); |
| 113 | |
| 114 | router.push(`${basePath}?${params.toString()}`); |
| 115 | }; |
| 116 | |
| 117 | const getPaginationItems = () => { |
| 118 | const items = []; |
| 119 | const additionalParams = preserveParams(); |
| 120 | |
| 121 | // always show first page |
| 122 | items.push( |
| 123 | <PaginationItem key={"first"}> |
| 124 | <PaginationLink |
| 125 | href={`${basePath}?page=1${ |
| 126 | currentSearch ? `&search=${currentSearch}` : "" |
| 127 | }${ |
| 128 | currentSortBy |
| 129 | ? `&sortBy=${currentSortBy}&sortOrder=${currentSortOrder}` |
| 130 | : "" |
| 131 | }${additionalParams}`} |
| 132 | isActive={currentPage === 1} |
| 133 | > |
| 134 | 1 |
| 135 | </PaginationLink> |
| 136 | </PaginationItem> |
| 137 | ); |
| 138 | |
| 139 | if (currentPage > 3) { |
| 140 | items.push( |
| 141 | <PaginationItem key={"ellipsis-1"}> |
| 142 | <PaginationEllipsis /> |
| 143 | </PaginationItem> |
| 144 | ); |
| 145 | } |
| 146 | |
| 147 | for ( |
| 148 | let i = Math.max(2, currentPage - 1); |
| 149 | i <= Math.min(totalPage - 1, currentPage + 1); |
| 150 | i++ |
| 151 | ) { |
| 152 | if (i === 1 || i === totalPage) continue; |
| 153 | |
| 154 | items.push( |
| 155 | <PaginationItem key={i}> |
| 156 | <PaginationLink |
| 157 | href={`${basePath}?page=${i}${ |
| 158 | currentSearch ? `&search=${currentSearch}` : "" |
| 159 | }${ |
| 160 | currentSortBy |
| 161 | ? `&sortBy=${currentSortBy}&sortOrder=${currentSortOrder}` |
| 162 | : "" |
| 163 | }${additionalParams}`} |
| 164 | isActive={currentPage === i} |
| 165 | > |
| 166 | {i} |
| 167 | </PaginationLink> |
| 168 | </PaginationItem> |
| 169 | ); |
| 170 | } |
| 171 | |
| 172 | if (currentPage < totalPage - 2) { |
| 173 | items.push( |
| 174 | <PaginationItem key={"ellipsis-2"}> |
| 175 | <PaginationEllipsis /> |
| 176 | </PaginationItem> |
| 177 | ); |
| 178 | } |
| 179 | |
| 180 | if (totalPage > 1) { |
| 181 | items.push( |
| 182 | <PaginationItem key={"last"}> |
| 183 | <PaginationLink |
| 184 | href={`${basePath}?page=${totalPage}${ |
| 185 | currentSearch ? `&search=${currentSearch}` : "" |
| 186 | }${ |
| 187 | currentSortBy |
| 188 | ? `&sortBy=${currentSortBy}&sortOrder=${currentSortOrder}` |
| 189 | : "" |
| 190 | }${additionalParams}`} |
| 191 | isActive={currentPage === totalPage} |
| 192 | > |
| 193 | {totalPage} |
| 194 | </PaginationLink> |
| 195 | </PaginationItem> |
| 196 | ); |
| 197 | } |
| 198 | |
| 199 | return items; |
| 200 | }; |
| 201 | |
| 202 | const getSortIcon = (column: string) => { |
| 203 | if (currentSortBy !== column) { |
| 204 | return <ArrowUpDown className="ml-2 size-4" />; |
| 205 | } |
| 206 | |
| 207 | return currentSortOrder === "asc" ? ( |
| 208 | <ArrowUp className="ml-2 size-4" /> |
| 209 | ) : ( |
| 210 | <ArrowDown className="ml-2 size-4" /> |
| 211 | ); |
| 212 | }; |
| 213 | |
| 214 | const getHighlightStyles = (url: UrlWithUser) => { |
| 215 | if (!url.flagged) return ""; |
| 216 | |
| 217 | switch (highlightStyle) { |
| 218 | case "security": |
| 219 | return "bg-red-50/50 dark:bg-red-900/10 hover:bg-red-50/80 dark:hover:bg-red-900/20"; |
| 220 | case "inappropriate": |
| 221 | return "bg-orange-50/50 dark:bg-orange-900/10 hover:bg-orange-50/80 dark:hover:bg-orange-900/20"; |
| 222 | case "other": |
| 223 | return "bg-yellow-50/50 dark:bg-yellow-900/10 hover:bg-yellow-50/80 dark:hover:bg-yellow-900/20"; |
| 224 | default: |
| 225 | return url.flagged ? "bg-yellow-50/50 dark:bg-yellow-900/10" : ""; |
| 226 | } |
| 227 | }; |
| 228 | |
| 229 | // Get flag icon color based on the type |
| 230 | const getFlagIconColor = () => { |
| 231 | switch (highlightStyle) { |
| 232 | case "security": |
| 233 | return "text-red-500 dark:text-red-400"; |
| 234 | case "inappropriate": |
| 235 | return "text-orange-500 dark:text-orange-400"; |
| 236 | case "other": |
| 237 | return "text-yellow-500 dark:text-yellow-400"; |
| 238 | default: |
| 239 | return "text-yellow-600 dark:text-yellow-400"; |
| 240 | } |
| 241 | }; |
| 242 | |
| 243 | const truncateUrl = (url: string, maxLenght = 50) => { |
| 244 | if (url.length <= maxLenght) return url; |
| 245 | return url.substring(0, maxLenght) + "..."; |
| 246 | }; |
| 247 | |
| 248 | const handleManageFlaggedUrl = async ( |
| 249 | urlId: number, |
| 250 | action: "approve" | "delete" |
| 251 | ) => { |
| 252 | try { |
| 253 | setActionLoading(urlId); |
| 254 | |
| 255 | const response = await manageFlaggedUrl(urlId, action); |
| 256 | if (response.success) { |
| 257 | toast.success( |
| 258 | action === "approve" |
| 259 | ? "URL approved successfully." |
| 260 | : "URL deleted successfully." |
| 261 | ); |
| 262 | |
| 263 | router.refresh(); |
| 264 | } else { |
| 265 | toast.error("Failed to manage flagged URL.", { |
| 266 | description: response.error || "Unknown error", |
| 267 | }); |
| 268 | } |
| 269 | } catch (error) { |
| 270 | console.error("Error managing flagged URL", error); |
| 271 | toast.error("Failed to manage flagged URL.", { |
| 272 | description: "Internal server error", |
| 273 | }); |
| 274 | } finally { |
| 275 | setActionLoading(null); |
| 276 | } |
| 277 | }; |
| 278 | |
| 279 | const copyToClipboard = async (id: number, shortCode: string) => { |
| 280 | try { |
| 281 | setCopyingId(id); |
| 282 | const shortUrl = `${window.location.origin}/r/${shortCode}`; |
| 283 | await navigator.clipboard.writeText(shortUrl); |
| 284 | toast.success("Short URL copied to clipboard."); |
| 285 | } catch (error) { |
| 286 | console.error("Error copying URL to clipboard", error); |
| 287 | toast.error("Failed to copy short URL to clipboard."); |
| 288 | } finally { |
| 289 | setTimeout(() => { |
| 290 | setCopyingId(null); |
| 291 | }, 1000); |
| 292 | } |
| 293 | }; |
| 294 | |
| 295 | return ( |
| 296 | <div className="space-y-4"> |
| 297 | <div className="rounded-md border"> |
| 298 | <Table> |
| 299 | <TableHeader> |
| 300 | <TableRow> |
| 301 | <TableHead className="w-[300px]"> |
| 302 | <button |
| 303 | className="flex items-center font-medium" |
| 304 | onClick={() => handleSort("originalUrl")} |
| 305 | > |
| 306 | Original URL |
| 307 | {getSortIcon("originalUrl")} |
| 308 | </button> |
| 309 | </TableHead> |
| 310 | <TableHead className="w-[150px]"> |
| 311 | <button |
| 312 | className="flex items-center font-medium" |
| 313 | onClick={() => handleSort("shortCode")} |
| 314 | > |
| 315 | Short Code |
| 316 | {getSortIcon("shortCode")} |
| 317 | </button> |
| 318 | </TableHead> |
| 319 | <TableHead className="w-[100px]"> |
| 320 | <button |
| 321 | className="flex items-center font-medium" |
| 322 | onClick={() => handleSort("clicks")} |
| 323 | > |
| 324 | Clicks |
| 325 | {getSortIcon("clicks")} |
| 326 | </button> |
| 327 | </TableHead> |
| 328 | <TableHead className="w-[150px]"> |
| 329 | <button |
| 330 | className="flex items-center font-medium" |
| 331 | onClick={() => handleSort("userName")} |
| 332 | > |
| 333 | Created By |
| 334 | {getSortIcon("userName")} |
| 335 | </button> |
| 336 | </TableHead> |
| 337 | <TableHead className="w-[150px]"> |
| 338 | <button |
| 339 | className="flex items-center font-medium" |
| 340 | onClick={() => handleSort("createdAt")} |
| 341 | > |
| 342 | Created |
| 343 | {getSortIcon("createdAt")} |
| 344 | </button> |
| 345 | </TableHead> |
| 346 | <TableHead className="w-[80px] text-right">Actions</TableHead> |
| 347 | </TableRow> |
| 348 | </TableHeader> |
| 349 | <TableBody> |
| 350 | {urls.length === 0 ? ( |
| 351 | <TableRow> |
| 352 | <TableCell> |
| 353 | {currentSearch |
| 354 | ? "No URLs found with the search term." |
| 355 | : "No URLs found."} |
| 356 | </TableCell> |
| 357 | </TableRow> |
| 358 | ) : ( |
| 359 | urls.map((url) => ( |
| 360 | <TableRow key={url.id} className={getHighlightStyles(url)}> |
| 361 | <TableCell className="font-medium"> |
| 362 | <div className="flex items-center gap-2"> |
| 363 | {url.flagged && ( |
| 364 | <div |
| 365 | className={getFlagIconColor()} |
| 366 | title={url.flagReason || "Flagged By AI"} |
| 367 | > |
| 368 | <AlertTriangle className="size-4" /> |
| 369 | </div> |
| 370 | )} |
| 371 | <a |
| 372 | href={url.originalUrl} |
| 373 | target="_blank" |
| 374 | rel="noopener noreferrer" |
| 375 | className="text-blue-600 hover:underline flex items-center gap-1 max-w-[250px] truncate" |
| 376 | > |
| 377 | {truncateUrl(url.originalUrl)} |
| 378 | <ExternalLink className="size-3" /> |
| 379 | </a> |
| 380 | </div> |
| 381 | {url.flagged && url.flagReason && ( |
| 382 | <div className="mt-1 text-xs text-yellow-600 dark:text-yellow-400 max-w-[250px] truncate"> |
| 383 | Reason: {url.flagReason} |
| 384 | </div> |
| 385 | )} |
| 386 | </TableCell> |
| 387 | <TableCell> |
| 388 | <div className="flex items-center gap-2"> |
| 389 | <code className="bg-muted px-1 py-0.5 rounded text-sm"> |
| 390 | {url.shortCode} |
| 391 | </code> |
| 392 | <Button |
| 393 | variant={"ghost"} |
| 394 | size={"icon"} |
| 395 | className="size-6" |
| 396 | onClick={() => copyToClipboard(url.id, url.shortCode)} |
| 397 | disabled={copyingId === url.id} |
| 398 | > |
| 399 | {copyingId === url.id ? ( |
| 400 | <Loader2 className="size-3 animate-spin" /> |
| 401 | ) : ( |
| 402 | <Copy className="size-3" /> |
| 403 | )} |
| 404 | </Button> |
| 405 | </div> |
| 406 | </TableCell> |
| 407 | <TableCell> |
| 408 | <Badge variant={"secondary"}>{url.clicks}</Badge> |
| 409 | </TableCell> |
| 410 | <TableCell> |
| 411 | {url.userId ? ( |
| 412 | <div className="flex items-center gap-2"> |
| 413 | <Avatar className="size-6"> |
| 414 | <AvatarImage |
| 415 | src={undefined} |
| 416 | alt={url.userName || "User"} |
| 417 | /> |
| 418 | <AvatarFallback className="text-xs"> |
| 419 | {url.userName?.substring(0, 2)} |
| 420 | </AvatarFallback> |
| 421 | </Avatar> |
| 422 | <span> |
| 423 | {url.userName || url.userEmail || "Unknown User"} |
| 424 | </span> |
| 425 | </div> |
| 426 | ) : ( |
| 427 | <span className="text-muted-foreground text-sm"> |
| 428 | Anyonymous |
| 429 | </span> |
| 430 | )} |
| 431 | </TableCell> |
| 432 | <TableCell> |
| 433 | {formatDistanceToNow(new Date(url.createdAt), { |
| 434 | addSuffix: true, |
| 435 | })} |
| 436 | </TableCell> |
| 437 | <TableCell className="text-right"> |
| 438 | <DropdownMenu> |
| 439 | <DropdownMenuTrigger asChild> |
| 440 | <Button variant={"ghost"} size={"icon"}> |
| 441 | <MoreHorizontal className="size-4" /> |
| 442 | </Button> |
| 443 | </DropdownMenuTrigger> |
| 444 | <DropdownMenuContent align="end"> |
| 445 | <DropdownMenuLabel>Actions</DropdownMenuLabel> |
| 446 | <DropdownMenuSeparator /> |
| 447 | <DropdownMenuItem |
| 448 | onClick={() => copyToClipboard(url.id, url.shortCode)} |
| 449 | > |
| 450 | Copy Short URL |
| 451 | </DropdownMenuItem> |
| 452 | <DropdownMenuItem asChild> |
| 453 | <a |
| 454 | href={url.originalUrl} |
| 455 | target="_blank" |
| 456 | rel="noopener noreferrer" |
| 457 | > |
| 458 | Visit Original URL |
| 459 | </a> |
| 460 | </DropdownMenuItem> |
| 461 | {url.flagged && ( |
| 462 | <> |
| 463 | <DropdownMenuSeparator /> |
| 464 | <DropdownMenuItem |
| 465 | className="text-green-600 dark:text-green-400" |
| 466 | onClick={() => |
| 467 | handleManageFlaggedUrl(url.id, "approve") |
| 468 | } |
| 469 | > |
| 470 | {actionLoading === url.id && ( |
| 471 | <Loader2 className="size-4 mr-1" /> |
| 472 | )} |
| 473 | <CheckCircle className="size-4 mr-1 text-green-700" /> |
| 474 | Approve URL |
| 475 | </DropdownMenuItem> |
| 476 | <DropdownMenuItem |
| 477 | className="text-red-600 dark:text-red-400" |
| 478 | onClick={() => |
| 479 | handleManageFlaggedUrl(url.id, "delete") |
| 480 | } |
| 481 | > |
| 482 | {actionLoading === url.id && ( |
| 483 | <Loader2 className="size-4 mr-1" /> |
| 484 | )} |
| 485 | <Ban className="size-4 mr-1 text-red-700" /> |
| 486 | Delete URL |
| 487 | </DropdownMenuItem> |
| 488 | </> |
| 489 | )} |
| 490 | </DropdownMenuContent> |
| 491 | </DropdownMenu> |
| 492 | </TableCell> |
| 493 | </TableRow> |
| 494 | )) |
| 495 | )} |
| 496 | </TableBody> |
| 497 | </Table> |
| 498 | </div> |
| 499 | |
| 500 | {totalPage > 1 && ( |
| 501 | <Pagination> |
| 502 | <PaginationContent> |
| 503 | <PaginationItem> |
| 504 | <PaginationPrevious |
| 505 | href={`${basePath}?page=${Math.max(1, currentPage - 1)}${ |
| 506 | currentSearch ? `&search=${currentSearch}` : "" |
| 507 | }${ |
| 508 | currentSortBy |
| 509 | ? `&sortBy=${currentSortBy}&sortOrder=${currentSortOrder}` |
| 510 | : "" |
| 511 | }${preserveParams()}`} |
| 512 | /> |
| 513 | </PaginationItem> |
| 514 | |
| 515 | {getPaginationItems()} |
| 516 | |
| 517 | <PaginationItem> |
| 518 | <PaginationNext |
| 519 | href={`${basePath}?page=${Math.min( |
| 520 | totalPage, |
| 521 | currentPage + 1 |
| 522 | )}${currentSearch ? `&search=${currentSearch}` : ""}${ |
| 523 | currentSortBy |
| 524 | ? `&sortBy=${currentSortBy}&sortOrder=${currentSortOrder}` |
| 525 | : "" |
| 526 | }${preserveParams()}`} |
| 527 | /> |
| 528 | </PaginationItem> |
| 529 | </PaginationContent> |
| 530 | </Pagination> |
| 531 | )} |
| 532 | |
| 533 | <div className="text-xs text-muted-foreground"> |
| 534 | Showing {urls.length} of {total} URLs. |
| 535 | {currentSearch && ` Search results for "${currentSearch}".`} |
| 536 | </div> |
| 537 | </div> |
| 538 | ); |
| 539 | } |