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.

Pull table stuff into reusable component

Tim Wilsonf48389dadf57
diff --git a/apps/web/ui/analytics/events/events-table.tsx b/apps/web/ui/analytics/events/events-table.tsx
index d26c7d4653..211716a460 100644
--- a/apps/web/ui/analytics/events/events-table.tsx
+++ b/apps/web/ui/analytics/events/events-table.tsx
@@ -5,34 +5,25 @@ import { clickEventEnrichedSchema } from "@/lib/zod/schemas/clicks";
import { leadEventEnrichedSchema } from "@/lib/zod/schemas/leads";
import { saleEventEnrichedSchema } from "@/lib/zod/schemas/sales";
import {
- Button,
CursorRays,
LinkLogo,
- LoadingSpinner,
QRCode,
+ Table,
Tooltip,
useRouterStuff,
+ useTable,
} from "@dub/ui";
-import { FilterBars, SortOrder } from "@dub/ui/src/icons";
+import { FilterBars } from "@dub/ui/src/icons";
import {
COUNTRIES,
capitalize,
- cn,
fetcher,
getApexDomain,
nFormatter,
} from "@dub/utils";
-import {
- Cell,
- ColumnDef,
- VisibilityState,
- flexRender,
- getCoreRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-import { AnimatePresence, motion } from "framer-motion";
+import { Cell, ColumnDef, VisibilityState } from "@tanstack/react-table";
import Link from "next/link";
-import { useContext, useEffect, useMemo, useRef, useState } from "react";
+import { useContext, useEffect, useMemo, useState } from "react";
import useSWR from "swr";
import z from "zod";
import { AnalyticsContext } from "../analytics-provider";
@@ -43,8 +34,6 @@ import ExportButton from "./export-button";
import usePagination from "./use-pagination";
const PAGE_SIZE = 100;
-const tableCellClassName =
- "border-r border-b border-gray-200 px-4 py-2.5 text-left text-sm leading-6 whitespace-nowrap";
type EventType = "clicks" | "leads" | "sales";
@@ -150,10 +139,6 @@ export default function EventsTable() {
const sortBy = searchParams.get("sort") || "timestamp";
const order = searchParams.get("order") === "asc" ? "asc" : "desc";
- const { pagination, setPagination } = usePagination(PAGE_SIZE);
-
- const scrollContainer = useRef<HTMLDivElement>(null);
-
const columns = useMemo<ColumnDef<Datum, any>[]>(
() =>
[
@@ -397,6 +382,8 @@ export default function EventsTable() {
const defaultData = useMemo(() => [], []);
+ const { pagination, setPagination } = usePagination(PAGE_SIZE);
+
const { queryString: originalQueryString, totalEvents } =
useContext(AnalyticsContext);
@@ -420,26 +407,35 @@ export default function EventsTable() {
},
);
- const table = useReactTable({
+ const { table, ...tableProps } = useTable({
data: data ?? defaultData,
- rowCount: totalEvents?.[tab] ?? 0,
+ loading: isLoading,
+ error: error ? "Failed to fetch events." : undefined,
columns,
- defaultColumn: {
- minSize: 60,
- size: 150,
- maxSize: 250,
- },
- columnResizeMode: "onChange",
- getCoreRowModel: getCoreRowModel(),
+ pagination,
onPaginationChange: setPagination,
- onColumnVisibilityChange: setColumnVisibility,
- state: {
- pagination,
- columnVisibility,
+ rowCount: totalEvents?.[tab] ?? 0,
+ columnVisibility,
+ sortableColumns: ["timestamp", "amount"],
+ sortBy: sortBy,
+ sortOrder: order,
+ onSortChange: ({ sortBy, sortOrder }) =>
+ queryParams({
+ set: {
+ ...(sortBy && { sort: sortBy }),
+ ...(sortOrder && { order: sortOrder }),
+ },
+ }),
+ cellRight: (cell) => {
+ const meta = cell.column.columnDef.meta as ColumnMeta | undefined;
+
+ return (
+ <>
+ {meta?.filterParams && <FilterButton set={meta.filterParams(cell)} />}
+ </>
+ );
},
- manualPagination: true,
- autoResetPageIndex: false,
- manualSorting: true,
+ emptyState: <EmptyState />,
});
const exportQueryString = useMemo(
@@ -457,23 +453,6 @@ export default function EventsTable() {
[queryString, table.getVisibleFlatColumns()],
);
- // Memoize column sizes to pass to table as CSS variables
- const columnSizeVars = useMemo(() => {
- const headers = table.getFlatHeaders();
- const colSizes: { [key: string]: number } = {};
- for (let i = 0; i < headers.length; i++) {
- const header = headers[i]!;
- colSizes[`--header-${header.id}-size`] = header.getSize();
- colSizes[`--col-${header.column.id}-size`] = header.column.getSize();
- }
- return colSizes;
- }, [
- columns,
- columnVisibility,
- table.getState().columnSizingInfo,
- table.getState().columnSizing,
- ]);
-
return (
<div>
<div className="flex justify-end">
@@ -485,192 +464,7 @@ export default function EventsTable() {
<EditColumnsButton table={table} />
</div>
</div>
- <div className="mt-3 border border-gray-200 bg-white sm:rounded-xl">
- <div className="relative rounded-[inherit]">
- {(!error && !!data?.length) || isLoading ? (
- <div
- ref={scrollContainer}
- className="min-h-[400px] overflow-x-auto rounded-[inherit]"
- >
- <table
- className={cn(
- "w-full table-fixed 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
- "[&_tr>*:first-child]:border-l-0", // Left column
- "[&_tr>*:last-child]:border-r-0", // Right column
- )}
- style={columnSizeVars}
- >
- <thead>
- {table.getHeaderGroups().map((headerGroup) => (
- <tr key={headerGroup.id}>
- {headerGroup.headers.map((header, columnIdx) => {
- const isSortableColumn = [
- "timestamp",
- "amount",
- ].includes(header.column.id);
- return (
- <th
- key={`${tab}-${header.id}`}
- className={cn(
- tableCellClassName,
- "relative select-none font-medium",
- )}
- style={{
- width: `calc(var(--header-${header?.id}-size) * 1px)`,
- }}
- >
- <div className="flex items-center justify-between gap-6 !pr-0">
- <button
- type="button"
- className="flex items-center gap-2"
- disabled={!isSortableColumn}
- onClick={() =>
- queryParams({
- set: {
- sort: header.column.id,
- order:
- sortBy !== header.column.id
- ? "desc"
- : order === "asc"
- ? "desc"
- : "asc",
- },
- })
- }
- aria-label="Sort by column"
- >
- <span>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </span>
- {isSortableColumn && (
- <SortOrder
- order={
- sortBy === header.column.id ? order : null
- }
- />
- )}
- </button>
- </div>
- <div
- className="absolute -right-[4px] top-0 z-[1] h-full w-[7px] cursor-col-resize"
- {...{
- onDoubleClick: () => header.column.resetSize(),
- onMouseDown: header.getResizeHandler(),
- onTouchStart: header.getResizeHandler(),
- }}
- />
- </th>
- );
- })}
- </tr>
- ))}
- </thead>
- <tbody>
- {table.getRowModel().rows.map((row) => (
- <tr key={row.id}>
- {row.getVisibleCells().map((cell) => {
- const meta = cell.column.columnDef.meta as
- | ColumnMeta
- | undefined;
-
- return (
- <td
- key={`${tab}-${cell.id}`}
- className={cn(
- tableCellClassName,
- "group relative text-gray-600",
- )}
- style={{
- width: `calc(var(--col-${cell.column.id}-size) * 1px)`,
- }}
- >
- <div className="flex w-full items-center justify-between overflow-hidden truncate">
- <div className="min-w-0 shrink">
- {flexRender(
- cell.column.columnDef.cell,
- cell.getContext(),
- )}
- </div>
- {meta?.filterParams && (
- <FilterButton set={meta.filterParams(cell)} />
- )}
- </div>
- </td>
- );
- })}
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- ) : (
- <div className="flex h-96 w-full items-center justify-center text-sm text-gray-500">
- {error ? (
- "Failed to fetch data"
- ) : tab === "clicks" ? (
- "No data available"
- ) : (
- <EmptyState />
- )}
- </div>
- )}
- <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>
- <span className="hidden sm:inline-block">Viewing</span>{" "}
- <span className="font-medium">
- {pagination.pageIndex * pagination.pageSize + 1}-
- {Math.min(
- pagination.pageIndex * pagination.pageSize +
- pagination.pageSize,
- table.getRowCount(),
- )}
- </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/error 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>
+ <Table {...tableProps} table={table} />
</div>
);
}
diff --git a/apps/web/ui/analytics/events/use-pagination.ts b/apps/web/ui/analytics/events/use-pagination.ts
index 65eaa33cf5..ef745a5b5b 100644
--- a/apps/web/ui/analytics/events/use-pagination.ts
+++ b/apps/web/ui/analytics/events/use-pagination.ts
@@ -1,37 +1,37 @@
-import { useRouterStuff } from "@dub/ui";
-import { PaginationState } from "@tanstack/react-table";
-import { useEffect, useState } from "react";
+import { useRouterStuff, useTablePagination } from "@dub/ui";
+import { useEffect, useMemo } from "react";
export default function usePagination(pageSize: number) {
const { searchParams, queryParams } = useRouterStuff();
- const [pagination, setPagination] = useState<PaginationState>({
- pageIndex: 0,
+ const offset = useMemo(
+ () => parseInt(searchParams.get("offset") || "0") || 0,
+ [searchParams.get("offset")],
+ );
+
+ const { pagination, setPagination } = useTablePagination({
pageSize,
+ offset,
+ onOffsetChange: (offset) => {
+ queryParams(
+ offset === 0
+ ? { del: "offset" }
+ : {
+ set: {
+ offset: offset.toString(),
+ },
+ },
+ );
+ },
});
// Update state when URL parameter changes
useEffect(() => {
- const offset = parseInt(searchParams.get("offset") || "0") || 0;
setPagination((p) => ({
...p,
pageIndex: Math.floor(offset / p.pageSize),
}));
- }, [searchParams.get("offset")]);
-
- // Update URL parameter when state changes
- useEffect(() => {
- const offset = pagination.pageIndex * pagination.pageSize;
- queryParams(
- offset === 0
- ? { del: "offset" }
- : {
- set: {
- offset: offset.toString(),
- },
- },
- );
- }, [pagination]);
+ }, [offset]);
return { pagination, setPagination };
}
diff --git a/packages/ui/package.json b/packages/ui/package.json
index a51246735b..19040f5ce9 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -50,6 +50,7 @@
"@radix-ui/react-tooltip": "^1.0.7",
"@react-aria/datepicker": "^3.10.0",
"@react-stately/datepicker": "^3.9.3",
+ "@tanstack/react-table": "^8.17.3",
"class-variance-authority": "^0.7.0",
"cmdk": "^0.2.0",
"date-fns": "^3.6.0",
diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsx
index 01618b6eec..13229eca51 100644
--- a/packages/ui/src/index.tsx
+++ b/packages/ui/src/index.tsx
@@ -17,6 +17,7 @@ export * from "./modal";
export * from "./popover";
export * from "./radio-group";
export * from "./switch";
+export * from "./table";
export * from "./tooltip";
// hooks
diff --git a/packages/ui/src/table/index.ts b/packages/ui/src/table/index.ts
new file mode 100644
index 0000000000..bd022d2ad5
--- /dev/null
+++ b/packages/ui/src/table/index.ts
@@ -0,0 +1,2 @@
+export * from "./table";
+export * from "./use-table-pagination";
diff --git a/packages/ui/src/table/table.tsx b/packages/ui/src/table/table.tsx
new file mode 100644
index 0000000000..5b7284fbbd
--- /dev/null
+++ b/packages/ui/src/table/table.tsx
@@ -0,0 +1,320 @@
+import { cn } from "@dub/utils";
+import {
+ Cell,
+ ColumnDef,
+ PaginationState,
+ Table as TableType,
+ VisibilityState,
+ flexRender,
+ getCoreRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+import { AnimatePresence, motion } from "framer-motion";
+import {
+ Dispatch,
+ ReactNode,
+ SetStateAction,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import { Button } from "../button";
+import { LoadingSpinner, SortOrder } from "../icons";
+
+const tableCellClassName =
+ "border-r border-b border-gray-200 px-4 py-2.5 text-left text-sm leading-6 whitespace-nowrap";
+
+type UseTableProps<T> = {
+ columns: ColumnDef<T, any>[];
+ data: T[];
+ loading?: boolean;
+ error?: string;
+ emptyState?: ReactNode;
+ cellRight?: (cell: Cell<T, any>) => ReactNode;
+ defaultColumn?: Partial<ColumnDef<T, any>>;
+ sortBy?: string;
+ sortOrder?: "asc" | "desc";
+ onSortChange?: (props: {
+ sortBy?: string;
+ sortOrder?: "asc" | "desc";
+ }) => void;
+ sortableColumns?: string[];
+ columnVisibility?: VisibilityState;
+ resizeColumns?: boolean;
+
+ thClassName?: string;
+ tdClassName?: string;
+} & (
+ | {
+ pagination: PaginationState;
+ onPaginationChange?: Dispatch<SetStateAction<PaginationState>>;
+ rowCount: number;
+ }
+ | { pagination?: never; onPaginationChange?: never; rowCount?: never }
+);
+
+type TableProps<T> = UseTableProps<T> & {
+ table: TableType<T>;
+};
+
+export function useTable<T extends any>(
+ props: UseTableProps<T>,
+): TableProps<T> & { table: TableType<T> } {
+ const {
+ data,
+ rowCount,
+ columns,
+ defaultColumn,
+ resizeColumns,
+ pagination,
+ onPaginationChange,
+ } = props;
+
+ const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(
+ props.columnVisibility ?? {},
+ );
+
+ // Update internal columnVisibility when prop value changes
+ useEffect(() => {
+ setColumnVisibility(props.columnVisibility ?? {});
+ }, [props.columnVisibility]);
+
+ const table = useReactTable({
+ data,
+ rowCount,
+ columns,
+ defaultColumn: {
+ minSize: 60,
+ size: 150,
+ maxSize: 250,
+ ...defaultColumn,
+ },
+ columnResizeMode: resizeColumns ? "onChange" : undefined,
+ getCoreRowModel: getCoreRowModel(),
+ onPaginationChange,
+ onColumnVisibilityChange: setColumnVisibility,
+ state: {
+ pagination: pagination,
+ columnVisibility,
+ },
+ manualPagination: true,
+ autoResetPageIndex: false,
+ manualSorting: true,
+ });
+
+ return {
+ ...props,
+ columnVisibility,
+ table,
+ };
+}
+
+export function Table<T>({
+ columns,
+ data,
+ loading,
+ error,
+ emptyState,
+ cellRight,
+ sortBy,
+ sortOrder,
+ onSortChange,
+ sortableColumns = [],
+ columnVisibility = {},
+ thClassName,
+ tdClassName,
+ table,
+ pagination,
+}: TableProps<T>) {
+ // Memoize column sizes to pass to table as CSS variables
+ const columnSizeVars = useMemo(() => {
+ const headers = table.getFlatHeaders();
+ const colSizes: { [key: string]: number } = {};
+ for (let i = 0; i < headers.length; i++) {
+ const header = headers[i]!;
+ colSizes[`--header-${header.id}-size`] = header.getSize();
+ colSizes[`--col-${header.column.id}-size`] = header.column.getSize();
+ }
+ return colSizes;
+ }, [
+ columns,
+ columnVisibility,
+ table.getState().columnSizingInfo,
+ table.getState().columnSizing,
+ ]);
+
+ return (
+ <div className="mt-3 border border-gray-200 bg-white sm:rounded-xl">
+ <div className="relative rounded-[inherit]">
+ {(!error && !!data?.length) || loading ? (
+ <div className="min-h-[400px] overflow-x-auto rounded-[inherit]">
+ <table
+ className={cn(
+ "w-full table-fixed 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
+ "[&_tr>*:first-child]:border-l-0", // Left column
+ "[&_tr>*:last-child]:border-r-0", // Right column
+ )}
+ style={columnSizeVars}
+ >
+ <thead>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <tr key={headerGroup.id}>
+ {headerGroup.headers.map((header, columnIdx) => {
+ const isSortableColumn = sortableColumns.includes(
+ header.column.id,
+ );
+ return (
+ <th
+ key={header.id}
+ className={cn(
+ tableCellClassName,
+ "relative select-none font-medium",
+ thClassName,
+ )}
+ style={{
+ width: `calc(var(--header-${header?.id}-size) * 1px)`,
+ }}
+ >
+ <div className="flex items-center justify-between gap-6 !pr-0">
+ <button
+ type="button"
+ className="flex items-center gap-2"
+ disabled={!isSortableColumn}
+ onClick={() =>
+ onSortChange?.({
+ sortBy: header.column.id,
+ sortOrder:
+ sortBy !== header.column.id
+ ? "desc"
+ : sortOrder === "asc"
+ ? "desc"
+ : "asc",
+ })
+ }
+ aria-label="Sort by column"
+ >
+ <span>
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+ </span>
+ {isSortableColumn && (
+ <SortOrder
+ order={
+ sortBy === header.column.id
+ ? sortOrder || "desc"
+ : null
+ }
+ />
+ )}
+ </button>
+ </div>
+ <div
+ className="absolute -right-[4px] top-0 z-[1] h-full w-[7px] cursor-col-resize"
+ {...{
+ onDoubleClick: () => header.column.resetSize(),
+ onMouseDown: header.getResizeHandler(),
+ onTouchStart: header.getResizeHandler(),
+ }}
+ />
+ </th>
+ );
+ })}
+ </tr>
+ ))}
+ </thead>
+ <tbody>
+ {table.getRowModel().rows.map((row) => (
+ <tr key={row.id}>
+ {row.getVisibleCells().map((cell) => (
+ <td
+ key={cell.id}
+ className={cn(
+ tableCellClassName,
+ "group relative text-gray-600",
+ tdClassName,
+ )}
+ style={{
+ width: `calc(var(--col-${cell.column.id}-size) * 1px)`,
+ }}
+ >
+ <div className="flex w-full items-center justify-between overflow-hidden truncate">
+ <div className="min-w-0 shrink">
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+ </div>
+ {cellRight?.(cell)}
+ </div>
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ ) : (
+ <div className="flex h-96 w-full items-center justify-center text-sm text-gray-500">
+ {error || emptyState || "Failed to load data."}
+ </div>
+ )}
+ {pagination && (
+ <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>
+ <span className="hidden sm:inline-block">Viewing</span>{" "}
+ <span className="font-medium">
+ {pagination.pageIndex * pagination.pageSize + 1}-
+ {Math.min(
+ pagination.pageIndex * pagination.pageSize +
+ pagination.pageSize,
+ table.getRowCount(),
+ )}
+ </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>
+ {loading && (
+ <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/packages/ui/src/table/use-table-pagination.tsx b/packages/ui/src/table/use-table-pagination.tsx
new file mode 100644
index 0000000000..f7dde5b07f
--- /dev/null
+++ b/packages/ui/src/table/use-table-pagination.tsx
@@ -0,0 +1,30 @@
+import { PaginationState } from "@tanstack/react-table";
+import { useEffect, useState } from "react";
+
+export function useTablePagination({
+ pageSize,
+ offset,
+ onOffsetChange,
+}: {
+ pageSize: number;
+ offset: number;
+ onOffsetChange?: (offset: number) => void;
+}) {
+ const [pagination, setPagination] = useState<PaginationState>({
+ pageIndex: 0,
+ pageSize,
+ });
+
+ useEffect(() => {
+ setPagination((p) => ({
+ ...p,
+ pageIndex: Math.floor(offset / p.pageSize),
+ }));
+ }, [offset]);
+
+ useEffect(() => {
+ onOffsetChange?.(pagination.pageIndex * pagination.pageSize);
+ }, [pagination]);
+
+ return { pagination, setPagination };
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6194e9bd7c..1308da6ba6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -462,6 +462,9 @@ importers:
'@react-stately/datepicker':
specifier: ^3.9.3
version: 3.9.4([email protected])
+ '@tanstack/react-table':
+ specifier: ^8.17.3
'@vercel/analytics':
specifier: ^1.0.0
version: 1.0.0([email protected])