Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add sorting by date

Tim Wilson7b0de309dd9c
diff --git a/apps/web/app/api/analytics/events/route.ts b/apps/web/app/api/analytics/events/route.ts
index 50af28801b..901ad51e68 100644
--- a/apps/web/app/api/analytics/events/route.ts
+++ b/apps/web/app/api/analytics/events/route.ts
@@ -2,8 +2,7 @@ import { validDateRangeForPlan } from "@/lib/analytics/utils";
import { withWorkspace } from "@/lib/auth";
import { getDomainViaEdge } from "@/lib/planetscale";
import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";
-import { nanoid } from "@dub/utils";
-import { subDays, subMinutes } from "date-fns";
+import { addDays, addMinutes, subDays, subMinutes } from "date-fns";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -15,12 +14,24 @@ export const GET = withWorkspace(
z.object({
pageIndex: z.coerce.number(),
pageSize: z.coerce.number().min(1).max(100),
+ sortBy: z.enum(["date"]).default("date"),
+ sortOrder: z.enum(["asc", "desc"]).default("desc"),
}),
)
.parse(searchParams);
- let { event, domain, key, interval, start, end, pageIndex, pageSize } =
- parsedParams;
+ let {
+ event,
+ domain,
+ key,
+ interval,
+ start,
+ end,
+ pageIndex,
+ pageSize,
+ sortBy,
+ sortOrder,
+ } = parsedParams;
validDateRangeForPlan({
plan: workspace.plan,
@@ -36,16 +47,21 @@ export const GET = withWorkspace(
? await getDomainViaEdge(domain).then((d) => d?.id)
: null;
+ // Fake data
const response = {
events: [...Array(pageSize)].map((_, idx) => ({
+ type: event,
link: {
domain: "dub.localhost",
- key: nanoid(),
+ key: (12345 + (idx + pageIndex * pageSize) * 12345).toString(36),
url: "https://dub.co",
},
country: "US",
- device: Math.random() > 0.25 ? "Desktop" : "Mobile",
- date: subMinutes(subDays(new Date(), pageIndex), idx),
+ device: idx % 3 > 0 ? "Desktop" : "Mobile",
+ date:
+ sortOrder === "desc"
+ ? subMinutes(subDays(new Date(), pageIndex), idx)
+ : addMinutes(addDays(subDays(new Date(), 300), pageIndex), idx),
})),
totalRows: 4322,
};
diff --git a/apps/web/ui/analytics/events/events-table.tsx b/apps/web/ui/analytics/events/events-table.tsx
index bc15cc8120..a02fda96e2 100644
--- a/apps/web/ui/analytics/events/events-table.tsx
+++ b/apps/web/ui/analytics/events/events-table.tsx
@@ -1,23 +1,25 @@
"use client";
import useWorkspace from "@/lib/swr/use-workspace";
-import { Button, LinkLogo } from "@dub/ui";
+import { Button, LinkLogo, LoadingSpinner } from "@dub/ui";
import { COUNTRIES, capitalize, cn, fetcher, getApexDomain } from "@dub/utils";
import {
ColumnDef,
PaginationState,
+ SortingState,
flexRender,
getCoreRowModel,
- getPaginationRowModel,
useReactTable,
} from "@tanstack/react-table";
+import { AnimatePresence, motion } from "framer-motion";
+import { ChevronUp } from "lucide-react";
import { useMemo, useState } from "react";
import useSWR from "swr";
import DeviceIcon from "../device-icon";
-const PAGE_SIZE = 20;
+const PAGE_SIZE = 15;
const tableCellClassName =
- "border-r border-b border-gray-200 px-4 py-3 text-left text-sm leading-6";
+ "border-r border-b border-gray-200 px-4 py-2.5 text-left text-sm leading-6";
type FakeDatum = {
link: { domain: string; key: string; url: string };
@@ -27,12 +29,22 @@ type FakeDatum = {
};
export default function EventsTable() {
- const { id: workspaceId, slug, betaTester } = useWorkspace();
+ const { id: workspaceId } = useWorkspace();
+
+ const [pagination, setPagination] = useState<PaginationState>({
+ pageIndex: 0,
+ pageSize: PAGE_SIZE,
+ });
+
+ const [sorting, setSorting] = useState<SortingState>([
+ { id: "date", desc: true },
+ ]);
const columns = useMemo<ColumnDef<FakeDatum, any>[]>(
() => [
{
header: "Link",
+ enableSorting: false,
accessorKey: "link",
cell: ({ getValue }) => (
<div className="flex items-center gap-3">
@@ -51,6 +63,7 @@ export default function EventsTable() {
},
{
header: "Country",
+ enableSorting: false,
accessorKey: "country",
cell: ({ getValue }) => (
<div className="flex items-center gap-3">
@@ -65,6 +78,7 @@ export default function EventsTable() {
},
{
header: "Device",
+ enableSorting: false,
accessorKey: "device",
cell: ({ getValue }) => (
<div className="flex items-center gap-3">
@@ -78,7 +92,9 @@ export default function EventsTable() {
),
},
{
+ id: "date",
header: "Date",
+ enableSorting: true,
accessorFn: (d) =>
new Date(d.date).toLocaleTimeString("en-US", {
month: "short",
@@ -92,11 +108,6 @@ export default function EventsTable() {
[],
);
- const [pagination, setPagination] = useState<PaginationState>({
- pageIndex: 0,
- pageSize: PAGE_SIZE,
- });
-
const defaultData = useMemo(() => [], []);
const path = useMemo(
@@ -105,106 +116,152 @@ export default function EventsTable() {
...(workspaceId && { workspaceId }),
pageIndex: pagination.pageIndex.toString(),
pageSize: pagination.pageSize.toString(),
+ sortBy: sorting?.[0]?.id ?? "date",
+ sortOrder: sorting?.[0]?.desc ?? true ? "desc" : "asc",
}).toString()}`,
- [workspaceId, pagination],
+ [workspaceId, pagination, sorting],
);
- const { data } = useSWR<{ events: FakeDatum[]; totalRows: number }>(
- path,
- fetcher,
- );
+ const { data, isLoading } = useSWR<{
+ events: FakeDatum[];
+ totalRows: number;
+ }>(path, fetcher, {
+ keepPreviousData: true,
+ });
const table = useReactTable({
data: data?.events ?? defaultData,
columns,
getCoreRowModel: getCoreRowModel(),
- getPaginationRowModel: getPaginationRowModel(),
rowCount: data?.totalRows,
onPaginationChange: setPagination,
+ onSortingChange: setSorting,
state: {
pagination,
+ sorting,
},
+ manualPagination: true,
autoResetPageIndex: false,
+ manualSorting: true,
});
return (
<div className="border border-gray-200 bg-white sm:rounded-xl">
- <div className="scrollbar-hide max-h-[615px] overflow-y-auto rounded-[inherit]">
- <table
- className={cn(
- "relative w-full border-separate border-spacing-0",
+ <div className="relative rounded-[inherit]">
+ {/* Could make this scrollable */}
+ <div className="scrollbar-hide min-h-[400px] overflow-y-auto rounded-[inherit]">
+ <table
+ className={cn(
+ "w-full border-separate border-spacing-0",
- // Remove side borders from table to avoid interfering with outer border
- "[&_thead_tr:first-child>*]:border-t-0", // Top row
- "[&_tbody_tr:last-child>*]:border-b-0", // Bottom row
- "[&_tr>*:first-child]:border-l-0", // Left column
- "[&_tr>*:last-child]:border-r-0", // Right column
- )}
- >
- <thead className="sticky top-0 z-10 bg-white">
- {table.getHeaderGroups().map((headerGroup) => (
- <tr key={headerGroup.id}>
- {headerGroup.headers.map((header, idx) => (
- <th
- key={header.id}
- className={cn(tableCellClassName, "font-medium")}
- >
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
+ // Remove side borders from table to avoid interfering with outer border
+ "[&_thead_tr:first-child>*]:border-t-0", // Top row
+ "[&_tbody_tr:last-child>*]:border-b-0", // Bottom row
+ "[&_tr>*:first-child]:border-l-0", // Left column
+ "[&_tr>*:last-child]:border-r-0", // Right column
+ )}
+ >
+ <thead>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <tr key={headerGroup.id}>
+ {headerGroup.headers.map((header, idx) => (
+ <th
+ key={header.id}
+ className={cn(tableCellClassName, "font-medium")}
+ >
+ <button
+ className="flex items-center gap-1"
+ disabled={!header.column.getCanSort()}
+ onClick={() => header.column.toggleSorting()}
+ >
+ <span>
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+ </span>
+ {header.column.getIsSorted() && (
+ <span>
+ <ChevronUp
+ className={cn(
+ "h-3.5 w-3.5 transition-transform",
+ header.column.getIsSorted() === "desc" &&
+ "rotate-180",
+ )}
+ transform=""
+ />
+ </span>
)}
- </th>
- ))}
- </tr>
- ))}
- </thead>
- <tbody>
- {table.getRowModel().rows.map((row) => (
- <tr key={row.id}>
- {row.getVisibleCells().map((cell) => (
- <td
- key={cell.id}
- className={cn(tableCellClassName, "text-gray-600")}
- >
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </td>
- ))}
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- <div className="flex items-center justify-between border-t border-gray-200 px-4 py-3.5 text-sm leading-6 text-gray-600">
- <div>
- Viewing{" "}
- <span className="font-medium">
- {pagination.pageIndex * pagination.pageSize + 1}-
- {pagination.pageIndex * pagination.pageSize + pagination.pageSize}
- </span>{" "}
- of{" "}
- <span className="font-medium">
- {table.getRowCount().toLocaleString()}
- </span>{" "}
- events
+ </button>
+ </th>
+ ))}
+ </tr>
+ ))}
+ </thead>
+ <tbody>
+ {table.getRowModel().rows.map((row) => (
+ <tr key={row.id}>
+ {row.getVisibleCells().map((cell) => (
+ <td
+ key={cell.id}
+ className={cn(tableCellClassName, "text-gray-600")}
+ >
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
</div>
- <div className="flex items-center gap-2">
- <Button
- variant="secondary"
- text="Previous"
- className="h-7 px-2"
- onClick={() => table.previousPage()}
- disabled={!table.getCanPreviousPage()}
- />
- <Button
- variant="secondary"
- text="Next"
- className="h-7 px-2"
- onClick={() => table.nextPage()}
- disabled={!table.getCanNextPage()}
- />
+ <div className="sticky bottom-0 flex items-center justify-between rounded-b-[inherit] border-t border-gray-200 bg-white px-4 py-3.5 text-sm leading-6 text-gray-600">
+ <div>
+ Viewing{" "}
+ <span className="font-medium">
+ {pagination.pageIndex * pagination.pageSize + 1}-
+ {pagination.pageIndex * pagination.pageSize + pagination.pageSize}
+ </span>{" "}
+ of{" "}
+ <span className="font-medium">
+ {table.getRowCount().toLocaleString()}
+ </span>{" "}
+ events
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ variant="secondary"
+ text="Previous"
+ className="h-7 px-2"
+ onClick={() => table.previousPage()}
+ disabled={!table.getCanPreviousPage()}
+ />
+ <Button
+ variant="secondary"
+ text="Next"
+ className="h-7 px-2"
+ onClick={() => table.nextPage()}
+ disabled={!table.getCanNextPage()}
+ />
+ </div>
</div>
+
+ {/* Loading overlay */}
+ <AnimatePresence>
+ {isLoading && (
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ className="absolute inset-0 flex items-center justify-center bg-white/50"
+ >
+ <LoadingSpinner />
+ </motion.div>
+ )}
+ </AnimatePresence>
</div>
</div>
);
diff --git a/apps/web/ui/analytics/events/index.tsx b/apps/web/ui/analytics/events/index.tsx
index 9e0c68766c..0a28eaff19 100644
--- a/apps/web/ui/analytics/events/index.tsx
+++ b/apps/web/ui/analytics/events/index.tsx
@@ -17,11 +17,11 @@ export default function AnalyticsEvents({
}) {
return (
<AnalyticsProvider {...{ staticDomain, staticUrl, admin, demo }}>
- <div className="pb-3 pt-10">
+ <div className="py-10">
<Toggle heading="Events" />
- </div>
- <div className="mx-auto grid max-w-screen-xl gap-5 px-2.5 lg:px-20">
- <EventsTable />
+ <div className="mx-auto grid max-w-screen-xl gap-5 px-2.5 lg:px-20">
+ <EventsTable />
+ </div>
</div>
</AnalyticsProvider>
);