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 menu buttons, rework column sizing, move export button

Tim Wilsone65bd7f39f78
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/events/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/events/page.tsx
index 0c5888f1cf..c09ea5ad56 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/events/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/events/page.tsx
@@ -1,4 +1,5 @@
import Events from "@/ui/analytics/events";
+import { EventsProvider } from "@/ui/analytics/events/events-provider";
import LayoutLoader from "@/ui/layout/layout-loader";
import { Suspense } from "react";
import AnalyticsClient from "../analytics/client";
@@ -7,7 +8,9 @@ export default function WorkspaceAnalyticsEvents() {
return (
<Suspense fallback={<LayoutLoader />}>
<AnalyticsClient>
- <Events />
+ <EventsProvider>
+ <Events />
+ </EventsProvider>
</AnalyticsClient>
</Suspense>
);
diff --git a/apps/web/tailwind.config.ts b/apps/web/tailwind.config.ts
index e64caca328..2b570d3ad8 100644
--- a/apps/web/tailwind.config.ts
+++ b/apps/web/tailwind.config.ts
@@ -20,6 +20,9 @@ const config: Pick<Config, "presets"> = {
"infinite-scroll": "infinite-scroll 22s linear infinite",
// Text appear animation
"text-appear": "text-appear 0.15s ease",
+ // Table pinned column shadow animation
+ "table-pinned-shadow":
+ "table-pinned-shadow cubic-bezier(0, 0, 1, 0)",
},
keyframes: {
...sharedConfig?.theme?.extend?.keyframes,
@@ -39,6 +42,11 @@ const config: Pick<Config, "presets"> = {
transform: "rotateX(0deg) scale(1)",
},
},
+ // Table pinned column shadow animation
+ "table-pinned-shadow": {
+ "0%": { filter: "drop-shadow(rgba(0, 0, 0, 0.1) -2px 10px 6px)" },
+ "100%": { filter: "drop-shadow(rgba(0, 0, 0, 0) -2px 10px 6px)" },
+ },
},
},
},
diff --git a/apps/web/ui/analytics/events/edit-columns-button.tsx b/apps/web/ui/analytics/events/edit-columns-button.tsx
index 59252c2527..0f44dd9560 100644
--- a/apps/web/ui/analytics/events/edit-columns-button.tsx
+++ b/apps/web/ui/analytics/events/edit-columns-button.tsx
@@ -42,10 +42,9 @@ export default function EditColumnsButton({ table }: { table: Table<any> }) {
>
<Button
type="button"
- className="h-8 whitespace-nowrap px-3"
- variant="secondary"
+ className="h-8 whitespace-nowrap px-2"
+ variant="outline"
icon={<Gear className="h-4 w-4 shrink-0" />}
- text="Edit columns"
/>
</Popover>
);
diff --git a/apps/web/ui/analytics/events/events-options.tsx b/apps/web/ui/analytics/events/events-options.tsx
new file mode 100644
index 0000000000..ee0f4512c9
--- /dev/null
+++ b/apps/web/ui/analytics/events/events-options.tsx
@@ -0,0 +1,32 @@
+import { Button, Popover, useMediaQuery } from "@dub/ui";
+import { useContext, useState } from "react";
+import { ThreeDots } from "../../shared/icons";
+import { EventsContext } from "./events-provider";
+import ExportButton from "./export-button";
+
+export default function EventsOptions() {
+ const { isMobile } = useMediaQuery();
+ const [openPopover, setOpenPopover] = useState(false);
+ const { exportQueryString } = useContext(EventsContext);
+
+ return (
+ <Popover
+ align="end"
+ content={
+ <div className="grid w-screen gap-px p-2 sm:w-48">
+ <ExportButton onClick={() => setOpenPopover(false)} />
+ </div>
+ }
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ <Button
+ onClick={() => setOpenPopover(!openPopover)}
+ variant="secondary"
+ className="w-auto px-1.5"
+ disabled={!exportQueryString}
+ icon={<ThreeDots className="h-5 w-5 text-gray-500" />}
+ />
+ </Popover>
+ );
+}
diff --git a/apps/web/ui/analytics/events/events-provider.tsx b/apps/web/ui/analytics/events/events-provider.tsx
new file mode 100644
index 0000000000..4b65482f34
--- /dev/null
+++ b/apps/web/ui/analytics/events/events-provider.tsx
@@ -0,0 +1,18 @@
+"use client";
+
+import { PropsWithChildren, createContext, useState } from "react";
+
+export const EventsContext = createContext<{
+ exportQueryString?: string;
+ setExportQueryString?: (queryString: string) => void;
+}>({});
+
+export function EventsProvider({ children }: PropsWithChildren) {
+ const [exportQueryString, setExportQueryString] = useState<string>();
+
+ return (
+ <EventsContext.Provider value={{ exportQueryString, setExportQueryString }}>
+ {children}
+ </EventsContext.Provider>
+ );
+}
diff --git a/apps/web/ui/analytics/events/events-table.tsx b/apps/web/ui/analytics/events/events-table.tsx
index 26e1da462f..3378d5fa99 100644
--- a/apps/web/ui/analytics/events/events-table.tsx
+++ b/apps/web/ui/analytics/events/events-table.tsx
@@ -23,25 +23,29 @@ import {
} from "@dub/utils";
import { Cell, ColumnDef } from "@tanstack/react-table";
import Link from "next/link";
-import { useContext, useMemo } from "react";
+import { useContext, useEffect, useMemo } from "react";
import useSWR from "swr";
import z from "zod";
import { AnalyticsContext } from "../analytics-provider";
import DeviceIcon from "../device-icon";
import EditColumnsButton from "./edit-columns-button";
+import { EventsContext } from "./events-provider";
import { exampleData } from "./example-data";
-import ExportButton from "./export-button";
+import { RowMenuButton } from "./row-menu-button";
import { eventColumns, useColumnVisibility } from "./use-column-visibility";
import usePagination from "./use-pagination";
-type Datum =
+export const eventTypes = ["clicks", "leads", "sales"] as const;
+export type EventType = (typeof eventTypes)[number];
+
+export type EventDatum =
| z.infer<typeof clickEventEnrichedSchema>
| z.infer<typeof leadEventEnrichedSchema>
| z.infer<typeof saleEventEnrichedSchema>;
type ColumnMeta = {
filterParams?: (
- args: Pick<Cell<Datum, any>, "getValue">,
+ args: Pick<Cell<EventDatum, any>, "getValue">,
) => Record<string, any>;
};
@@ -49,7 +53,7 @@ const FilterButton = ({ set }: { set: Record<string, any> }) => {
const { queryParams } = useRouterStuff();
return (
- <div className="relative h-[1.25rem] w-0 shrink-0 opacity-0 transition-all group-hover:w-[1.25rem] group-hover:opacity-100">
+ <div className="absolute right-1 top-0 flex h-full shrink-0 translate-x-3 items-center justify-center bg-[linear-gradient(to_right,transparent,white_10%)] p-2 opacity-0 transition-all group-hover:translate-x-0 group-hover:opacity-100">
<Link
href={
queryParams({
@@ -58,7 +62,7 @@ const FilterButton = ({ set }: { set: Record<string, any> }) => {
getNewPath: true,
}) as string
}
- className="absolute left-0 top-0 rounded-md border border-transparent bg-white p-0.5 text-gray-600 transition-colors hover:border-gray-200 hover:bg-gray-100 hover:text-gray-950"
+ className="block rounded-md border border-transparent bg-white p-0.5 text-gray-600 transition-colors hover:border-gray-200 hover:bg-gray-100 hover:text-gray-950"
>
<span className="sr-only">Filter</span>
<FilterBars className="h-3.5 w-3.5" />
@@ -70,12 +74,13 @@ const FilterButton = ({ set }: { set: Record<string, any> }) => {
export default function EventsTable() {
const { id: workspaceId } = useWorkspace();
const { searchParams, queryParams } = useRouterStuff();
+ const { setExportQueryString } = useContext(EventsContext);
const { tab, columnVisibility, setColumnVisibility } = useColumnVisibility();
const sortBy = searchParams.get("sort") || "timestamp";
const order = searchParams.get("order") === "asc" ? "asc" : "desc";
- const columns = useMemo<ColumnDef<Datum, any>[]>(
+ const columns = useMemo<ColumnDef<EventDatum, any>[]>(
() =>
[
// Click trigger
@@ -84,7 +89,6 @@ export default function EventsTable() {
header: "Event",
accessorKey: "qr",
enableHiding: false,
- size: 130,
meta: {
filterParams: ({ getValue }) => ({
qr: !!getValue(),
@@ -112,7 +116,6 @@ export default function EventsTable() {
header: "Event",
accessorKey: "event_name",
enableHiding: false,
- size: 120,
cell: ({ getValue }) =>
getValue() || <span className="text-gray-400">-</span>,
},
@@ -121,7 +124,7 @@ export default function EventsTable() {
id: "invoiceId",
header: "Invoice ID",
accessorKey: "invoice_id",
- size: 120,
+ maxSize: 200,
cell: ({ getValue }) =>
getValue() || <span className="text-gray-400">-</span>,
},
@@ -129,7 +132,8 @@ export default function EventsTable() {
id: "link",
header: "Link",
accessorKey: "link",
- size: 200,
+ minSize: 250,
+ maxSize: 200,
meta: {
filterParams: ({ getValue }) => ({
domain: getValue().domain,
@@ -200,6 +204,7 @@ export default function EventsTable() {
id: "city",
header: "City",
accessorKey: "city",
+ minSize: 160,
cell: ({ getValue, row }) => (
<div className="flex items-center gap-3">
<img
@@ -304,7 +309,17 @@ export default function EventsTable() {
</div>
),
},
- ].filter((c) => eventColumns[tab].all.includes(c.id)),
+ // Menu
+ {
+ id: "menu",
+ enableHiding: false,
+ minSize: 43,
+ size: 43,
+ maxSize: 43,
+ header: ({ table }) => <EditColumnsButton table={table} />,
+ cell: ({ row }) => <RowMenuButton row={row} />,
+ },
+ ].filter((c) => c.id === "menu" || eventColumns[tab].all.includes(c.id)),
[tab],
);
@@ -326,7 +341,24 @@ export default function EventsTable() {
[originalQueryString, tab, pagination, sortBy, order],
);
- const { data, isLoading, error } = useSWR<Datum[]>(
+ // Update export query string
+ useEffect(() => {
+ console.log("setting export query string with", setExportQueryString);
+ setExportQueryString?.(
+ editQueryString(
+ queryString,
+ {
+ columns: Object.entries(columnVisibility[tab])
+ .filter(([, visible]) => visible)
+ .map(([id]) => id)
+ .join(","),
+ },
+ ["page"],
+ ),
+ );
+ }, [setExportQueryString, queryString, columnVisibility, tab]);
+
+ const { data, isLoading, error } = useSWR<EventDatum[]>(
`/api/analytics/events?${queryString}`,
fetcher,
{
@@ -357,6 +389,7 @@ export default function EventsTable() {
...(sortOrder && { order: sortOrder }),
},
}),
+ columnPinning: { right: ["menu"] },
cellRight: (cell) => {
const meta = cell.column.columnDef.meta as ColumnMeta | undefined;
@@ -376,50 +409,22 @@ export default function EventsTable() {
resourceName: (plural) => `event${plural ? "s" : ""}`,
});
- const exportQueryString = useMemo(
- () =>
- editQueryString(
- queryString,
- {
- columns: table
- .getVisibleFlatColumns()
- .map((c) => c.id)
- .join(","),
- },
- ["page"],
- ),
- [queryString, table.getVisibleFlatColumns()],
- );
-
return (
- <div>
- <div className="flex justify-end">
- <div className="flex gap-1">
- <ExportButton
- queryString={exportQueryString}
- disabled={error || !data?.length}
- />
- <EditColumnsButton table={table} />
- </div>
- </div>
- <div className="mt-3">
- <Table {...tableProps} table={table}>
- {needsHigherPlan && (
- <>
- <div className="absolute inset-0 flex touch-pan-y items-center justify-center bg-gradient-to-t from-[#fff_70%] to-[#fff6]">
- <EmptyState
- icon={Menu3}
- title="Real-time Events Stream"
- description={`Want more data on your ${tab === "clicks" ? "link clicks & QR code scans" : tab}? Upgrade to our Business Plan to get a detailed, real-time stream of events in your workspace.`}
- buttonText="Upgrade to Business"
- buttonLink={`/${workspaceId}/settings/billing?upgrade=business`}
- />
- </div>
- <div className="h-[400px]" />
- </>
- )}
- </Table>
- </div>
- </div>
+ <Table {...tableProps} table={table}>
+ {needsHigherPlan && (
+ <>
+ <div className="absolute inset-0 flex touch-pan-y items-center justify-center bg-gradient-to-t from-[#fff_70%] to-[#fff6]">
+ <EmptyState
+ icon={Menu3}
+ title="Real-time Events Stream"
+ description={`Want more data on your ${tab === "clicks" ? "link clicks & QR code scans" : tab}? Upgrade to our Business Plan to get a detailed, real-time stream of events in your workspace.`}
+ buttonText="Upgrade to Business"
+ buttonLink={`/${workspaceId}/settings/billing?upgrade=business`}
+ />
+ </div>
+ <div className="h-[400px]" />
+ </>
+ )}
+ </Table>
);
}
diff --git a/apps/web/ui/analytics/events/export-button.tsx b/apps/web/ui/analytics/events/export-button.tsx
index 7bcb045029..a65eefc3b2 100644
--- a/apps/web/ui/analytics/events/export-button.tsx
+++ b/apps/web/ui/analytics/events/export-button.tsx
@@ -1,61 +1,48 @@
import { Button, Download } from "@dub/ui";
-import { useState } from "react";
+import { useContext } from "react";
import { toast } from "sonner";
+import { EventsContext } from "./events-provider";
-export default function ExportButton({
- queryString,
- disabled = false,
-}: {
- queryString: string;
- disabled?: boolean;
-}) {
- const [loading, setLoading] = useState(false);
+export default function ExportButton({ onClick }: { onClick?: () => void }) {
+ const { exportQueryString } = useContext(EventsContext);
async function exportData() {
- setLoading(true);
- try {
- const response = await fetch(
- `/api/analytics/events/export?${queryString}`,
- {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- },
+ const response = await fetch(
+ `/api/analytics/events/export?${exportQueryString}`,
+ {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
},
- );
+ },
+ );
- if (!response.ok) {
- setLoading(false);
- throw new Error(response.statusText);
- }
-
- const blob = await response.blob();
- const url = window.URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = `Dub Events Export - ${new Date().toISOString()}.csv`;
- a.click();
- } catch (error) {
- throw new Error(error);
+ if (!response.ok) {
+ throw new Error(response.statusText);
}
- setLoading(false);
+
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `Dub Events Export - ${new Date().toISOString()}.csv`;
+ a.click();
}
return (
<Button
- className="h-8 whitespace-nowrap px-3"
- variant="secondary"
+ variant="outline"
icon={<Download className="h-4 w-4 shrink-0" />}
- text="Export"
+ className="h-9 justify-start px-2 text-black"
+ text="Download as CSV"
onClick={() => {
toast.promise(exportData(), {
loading: "Exporting file...",
success: "Exported successfully",
error: (error) => error,
});
+ onClick?.();
}}
- disabled={disabled}
- loading={loading}
/>
);
}
diff --git a/apps/web/ui/analytics/events/row-menu-button.tsx b/apps/web/ui/analytics/events/row-menu-button.tsx
new file mode 100644
index 0000000000..1b08d49028
--- /dev/null
+++ b/apps/web/ui/analytics/events/row-menu-button.tsx
@@ -0,0 +1,77 @@
+import { Button, Icon, Popover } from "@dub/ui";
+import { Copy, Dots } from "@dub/ui/src/icons";
+import { cn } from "@dub/utils";
+import { Row } from "@tanstack/react-table";
+import { Command } from "cmdk";
+import { useState } from "react";
+import { toast } from "sonner";
+import { EventDatum } from "./events-table";
+
+export function RowMenuButton({ row }: { row: Row<EventDatum> }) {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <Popover
+ openPopover={isOpen}
+ setOpenPopover={setIsOpen}
+ content={
+ <Command tabIndex={0} loop className="focus:outline-none">
+ <Command.List className="flex w-screen flex-col gap-1 p-1 text-sm sm:w-auto sm:min-w-[130px]">
+ {"event_id" in row.original && (
+ <MenuItem
+ icon={Copy}
+ label="Copy event ID"
+ onSelect={() => {
+ if (!("event_id" in row.original)) return;
+ navigator.clipboard.writeText(row.original.event_id);
+ toast.success("Copied to clipboard");
+ setIsOpen(false);
+ }}
+ />
+ )}
+ <MenuItem
+ icon={Copy}
+ label="Copy click ID"
+ onSelect={() => {
+ navigator.clipboard.writeText(row.original.click_id);
+ toast.success("Copied to clipboard");
+ setIsOpen(false);
+ }}
+ />
+ </Command.List>
+ </Command>
+ }
+ align="end"
+ >
+ <Button
+ type="button"
+ className="h-8 whitespace-nowrap px-2"
+ variant="outline"
+ icon={<Dots className="h-4 w-4 shrink-0" />}
+ />
+ </Popover>
+ );
+}
+
+function MenuItem({
+ icon: Icon,
+ label,
+ onSelect,
+}: {
+ icon: Icon;
+ label: string;
+ onSelect: () => void;
+}) {
+ return (
+ <Command.Item
+ className={cn(
+ "flex cursor-pointer select-none items-center gap-2 whitespace-nowrap rounded-md px-3.5 py-2 text-sm text-gray-950",
+ "data-[selected=true]:bg-gray-100",
+ )}
+ onSelect={onSelect}
+ >
+ <Icon className="h-4 w-4 shrink-0 text-gray-600" />
+ {label}
+ </Command.Item>
+ );
+}
diff --git a/apps/web/ui/analytics/events/use-column-visibility.ts b/apps/web/ui/analytics/events/use-column-visibility.ts
index 39d790d99c..24682b215e 100644
--- a/apps/web/ui/analytics/events/use-column-visibility.ts
+++ b/apps/web/ui/analytics/events/use-column-visibility.ts
@@ -1,8 +1,6 @@
import { useLocalStorage, useRouterStuff } from "@dub/ui";
import { VisibilityState } from "@tanstack/react-table";
-
-const eventTypes = ["clicks", "leads", "sales"] as const;
-type EventType = (typeof eventTypes)[number];
+import { EventType, eventTypes } from "./events-table";
export const eventColumns: Record<
EventType,
diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsx
index 9e94d2eb07..e8d435a42f 100644
--- a/apps/web/ui/analytics/toggle.tsx
+++ b/apps/web/ui/analytics/toggle.tsx
@@ -63,6 +63,7 @@ import { COLORS_LIST } from "../links/tag-badge";
import AnalyticsOptions from "./analytics-options";
import { AnalyticsContext } from "./analytics-provider";
import DeviceIcon from "./device-icon";
+import EventsOptions from "./events/events-options";
import RefererIcon from "./referer-icon";
import { useAnalyticsFilterOption } from "./utils";
@@ -634,6 +635,7 @@ export default function Toggle({
{!isPublicStatsPage && page === "analytics" && (
<AnalyticsOptions />
)}
+ {page === "events" && <EventsOptions />}
</div>
</div>
</div>
diff --git a/packages/ui/src/icons/nucleo/dots.tsx b/packages/ui/src/icons/nucleo/dots.tsx
new file mode 100644
index 0000000000..c7dd10cd1d
--- /dev/null
+++ b/packages/ui/src/icons/nucleo/dots.tsx
@@ -0,0 +1,46 @@
+import { SVGProps } from "react";
+
+export function Dots(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ height="18"
+ width="18"
+ viewBox="0 0 18 18"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <g fill="currentColor">
+ <circle
+ cx="9"
+ cy="9"
+ fill="currentColor"
+ r=".5"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ <circle
+ cx="3.25"
+ cy="9"
+ fill="currentColor"
+ r=".5"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ <circle
+ cx="14.75"
+ cy="9"
+ fill="currentColor"
+ r=".5"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ </g>
+ </svg>
+ );
+}
diff --git a/packages/ui/src/icons/nucleo/index.ts b/packages/ui/src/icons/nucleo/index.ts
index 1b0c6f6bfc..5ed01a52f6 100644
--- a/packages/ui/src/icons/nucleo/index.ts
+++ b/packages/ui/src/icons/nucleo/index.ts
@@ -21,6 +21,7 @@ export * from "./crosshairs";
export * from "./cube";
export * from "./cursor-rays";
export * from "./desktop";
+export * from "./dots";
export * from "./download";
export * from "./earth-position";
export * from "./eye-slash";
diff --git a/packages/ui/src/table/table.tsx b/packages/ui/src/table/table.tsx
index 0cf38451f4..5a51d728f2 100644
--- a/packages/ui/src/table/table.tsx
+++ b/packages/ui/src/table/table.tsx
@@ -1,7 +1,9 @@
import { cn, deepEqual } from "@dub/utils";
import {
Cell,
+ Column,
ColumnDef,
+ ColumnPinningState,
PaginationState,
Table as TableType,
VisibilityState,
@@ -11,21 +13,23 @@ import {
} from "@tanstack/react-table";
import { AnimatePresence, motion } from "framer-motion";
import {
+ CSSProperties,
Dispatch,
PropsWithChildren,
ReactNode,
SetStateAction,
useEffect,
- useMemo,
useState,
} from "react";
import { Button } from "../button";
import { LoadingSpinner, SortOrder } from "../icons";
-const tableCellClassName = cn([
- "py-2.5 text-left text-sm leading-6 whitespace-nowrap border-gray-200 px-4 relative",
- "border-r border-b", // Right and left borders, removed from outer columns above
-]);
+const tableCellClassName = (columnId: string) =>
+ cn([
+ "py-2.5 text-left text-sm leading-6 whitespace-nowrap border-gray-200 px-4 relative",
+ "border-l border-b",
+ columnId === "menu" && "bg-white border-l-transparent py-0 px-1",
+ ]);
type UseTableProps<T> = {
columns: ColumnDef<T, any>[];
@@ -44,7 +48,7 @@ type UseTableProps<T> = {
sortableColumns?: string[];
columnVisibility?: VisibilityState;
onColumnVisibilityChange?: (visibility: VisibilityState) => void;
- resizeColumns?: boolean;
+ columnPinning?: ColumnPinningState;
resourceName?: (plural: boolean) => string;
className?: string;
@@ -72,7 +76,7 @@ export function useTable<T extends any>(
rowCount,
columns,
defaultColumn,
- resizeColumns = true,
+ columnPinning,
pagination,
onPaginationChange,
} = props;
@@ -100,18 +104,18 @@ export function useTable<T extends any>(
rowCount,
columns,
defaultColumn: {
- minSize: 60,
- size: 150,
- maxSize: 250,
+ minSize: 120,
+ size: 0,
+ maxSize: 300,
...defaultColumn,
},
- columnResizeMode: resizeColumns ? "onChange" : undefined,
getCoreRowModel: getCoreRowModel(),
onPaginationChange,
onColumnVisibilityChange: (visibility) => setColumnVisibility(visibility),
state: {
pagination: pagination,
columnVisibility,
+ columnPinning: { left: [], right: [], ...columnPinning },
},
manualPagination: true,
autoResetPageIndex: false,
@@ -121,7 +125,6 @@ export function useTable<T extends any>(
return {
...props,
columnVisibility,
- resizeColumns,
table,
};
}
@@ -137,8 +140,6 @@ export function Table<T>({
sortOrder,
onSortChange,
sortableColumns = [],
- resizeColumns,
- columnVisibility = {},
className,
thClassName,
tdClassName,
@@ -148,23 +149,6 @@ export function Table<T>({
rowCount,
children,
}: 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="relative border border-gray-200 bg-white sm:rounded-xl">
{(!error && !!data?.length) || loading ? (
@@ -172,14 +156,13 @@ export function Table<T>({
<table
className={cn(
[
- "group/table w-full table-fixed border-separate border-spacing-0 transition-[border-spacing,margin-top]",
+ "group/table w-full border-separate border-spacing-0 transition-[border-spacing,margin-top]",
// Remove side borders from table to avoid interfering with outer border
"[&_tr>*:first-child]:border-l-transparent", // Left column
"[&_tr>*:last-child]:border-r-transparent", // Right column
],
className,
)}
- style={columnSizeVars}
>
<thead>
{table.getHeaderGroups().map((headerGroup) => (
@@ -188,35 +171,45 @@ export function Table<T>({
const isSortableColumn = sortableColumns.includes(
header.column.id,
);
+ const ButtonOrDiv = isSortableColumn ? "button" : "div";
+
return (
<th
key={header.id}
className={cn(
- tableCellClassName,
+ tableCellClassName(header.id),
"select-none font-medium",
+ getCommonPinningClassNames(
+ header.column,
+ !table.getRowModel().rows.length,
+ ),
thClassName,
)}
style={{
- width: `calc(var(--header-${header?.id}-size) * 1px)`,
+ minWidth: header.column.columnDef.minSize,
+ maxWidth: header.column.columnDef.maxSize,
+ width: header.column.columnDef.size || "auto",
+ ...getCommonPinningStyles(header.column),
}}
>
<div className="flex items-center justify-between gap-6 !pr-0">
- <button
- type="button"
+ <ButtonOrDiv
className="flex items-center gap-2"
- disabled={!isSortableColumn}
- onClick={() =>
- onSortChange?.({
- sortBy: header.column.id,
- sortOrder:
- sortBy !== header.column.id
- ? "desc"
- : sortOrder === "asc"
+ {...(isSortableColumn && {
+ type: "button",
+ disabled: !isSortableColumn,
+ "aria-label": "Sort by column",
+ onClick: () =>
+ onSortChange?.({
+ sortBy: header.column.id,
+ sortOrder:
+ sortBy !== header.column.id
? "desc"
- : "asc",
- })
- }
- aria-label="Sort by column"
+ : sortOrder === "asc"
+ ? "desc"
+ : "asc",
+ }),
+ })}
>
<span>
{header.isPlaceholder
@@ -235,19 +228,8 @@ export function Table<T>({
}
/>
)}
- </button>
+ </ButtonOrDiv>
</div>
- {resizeColumns &&
- header.index < headerGroup.headers.length - 1 && (
- <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>
);
})}
@@ -261,12 +243,19 @@ export function Table<T>({
<td
key={cell.id}
className={cn(
- tableCellClassName,
+ tableCellClassName(cell.column.id),
"group text-gray-600",
+ getCommonPinningClassNames(
+ cell.column,
+ row.index === table.getRowModel().rows.length - 1,
+ ),
tdClassName,
)}
style={{
- width: `calc(var(--col-${cell.column.id}-size) * 1px)`,
+ minWidth: cell.column.columnDef.minSize,
+ maxWidth: cell.column.columnDef.maxSize,
+ width: cell.column.columnDef.size || "auto",
+ ...getCommonPinningStyles(cell.column),
}}
>
<div className="flex w-full items-center justify-between overflow-hidden truncate">
@@ -345,3 +334,25 @@ export function Table<T>({
</div>
);
}
+
+const getCommonPinningClassNames = (
+ column: Column<any>,
+ isLastRow: boolean,
+): string => {
+ const isPinned = column.getIsPinned();
+ return cn(
+ isPinned &&
+ !isLastRow &&
+ "animate-table-pinned-shadow [animation-timeline:scroll(inline)]",
+ );
+};
+
+const getCommonPinningStyles = (column: Column<any>): CSSProperties => {
+ const isPinned = column.getIsPinned();
+
+ return {
+ left: isPinned === "left" ? `${column.getStart("left")}px` : undefined,
+ right: isPinned === "right" ? `${column.getAfter("right")}px` : undefined,
+ position: isPinned ? "sticky" : "relative",
+ };
+};