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 column editing

Tim Wilsonc602e994e646
diff --git a/apps/web/ui/analytics/events/events-table-menu.tsx b/apps/web/ui/analytics/events/events-table-menu.tsx
new file mode 100644
index 0000000000..3b79e75e37
--- /dev/null
+++ b/apps/web/ui/analytics/events/events-table-menu.tsx
@@ -0,0 +1,90 @@
+import { AnimatedSizeContainer, Gear, Popover, useMediaQuery } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { Table } from "@tanstack/react-table";
+import { Command } from "cmdk";
+import { Ellipsis } from "lucide-react";
+import { RefObject, useEffect, useState } from "react";
+
+export default function EventsTableMenu({
+ table,
+ scrollContainer,
+}: {
+ table: Table<any>;
+ scrollContainer: RefObject<Element>;
+}) {
+ const { isMobile } = useMediaQuery();
+
+ const [isOpen, setIsOpen] = useState(false);
+ const [state, setState] = useState<"idle" | "columns">("idle");
+
+ useEffect(() => {
+ if (!isOpen) setState("idle");
+ }, [isOpen]);
+
+ return (
+ <Popover
+ openPopover={isOpen}
+ setOpenPopover={setIsOpen}
+ collisionBoundary={scrollContainer.current ?? undefined}
+ sticky="always"
+ content={
+ <AnimatedSizeContainer
+ width={!isMobile}
+ height
+ className="rounded-[inherit]"
+ style={{ transform: "translateZ(0)" }} // Fixes overflow on some browsers
+ >
+ <Command tabIndex={0} loop className="focus:outline-none">
+ <Command.List className="flex w-full w-screen flex-col gap-1 p-1 text-sm sm:w-auto sm:min-w-[130px]">
+ {state === "idle" && (
+ <Command.Item
+ className={cn(
+ "flex cursor-pointer items-center gap-3 whitespace-nowrap rounded-md px-3 py-2 text-left text-sm",
+ "data-[selected=true]:bg-gray-100",
+ )}
+ onSelect={() => setState("columns")}
+ >
+ <Gear className="h-4 w-4" />
+ Edit columns
+ </Command.Item>
+ )}
+ {state === "columns" && (
+ <>
+ {table
+ .getAllColumns()
+ .filter((c) => c.getCanHide())
+ .map((column) => (
+ <Command.Item
+ key={column.id}
+ className={cn(
+ "flex cursor-pointer items-center gap-2 whitespace-nowrap rounded-md px-3 py-1.5",
+ "data-[selected=true]:bg-gray-100",
+ )}
+ onSelect={() => column.toggleVisibility()}
+ >
+ <input
+ checked={column.getIsVisible()}
+ type="checkbox"
+ className="h-3 w-3 rounded-full border-gray-300 text-black focus:outline-none focus:ring-0"
+ disabled
+ />
+ {column.columnDef.header?.toString()}
+ </Command.Item>
+ ))}
+ </>
+ )}
+ </Command.List>
+ </Command>
+ </AnimatedSizeContainer>
+ }
+ align="end"
+ >
+ <button
+ type="button"
+ className="flex h-6 w-6 items-center justify-center rounded-md text-gray-600 hover:bg-gray-100 active:text-gray-950"
+ >
+ <Ellipsis className="h-4 w-4" />
+ </button>
+ </Popover>
+ );
+}
diff --git a/apps/web/ui/analytics/events/events-table.tsx b/apps/web/ui/analytics/events/events-table.tsx
index 719187d2cc..94a126f62d 100644
--- a/apps/web/ui/analytics/events/events-table.tsx
+++ b/apps/web/ui/analytics/events/events-table.tsx
@@ -25,16 +25,18 @@ import {
} from "@dub/utils";
import {
ColumnDef,
+ VisibilityState,
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
import { AnimatePresence, motion } from "framer-motion";
-import { useContext, useEffect, useMemo } from "react";
+import { useContext, useEffect, useMemo, useRef, useState } from "react";
import useSWR from "swr";
import z from "zod";
import { AnalyticsContext } from "../analytics-provider";
import DeviceIcon from "../device-icon";
+import EventsTableMenu from "./events-table-menu";
import usePagination from "./use-pagination";
const PAGE_SIZE = 500;
@@ -53,11 +55,30 @@ const eventColumns: Record<
{ all: string[]; defaultVisible: string[] }
> = {
clicks: {
- all: ["trigger", "link", "country", "device", "timestamp"],
+ all: [
+ "trigger",
+ "link",
+ "country",
+ "city",
+ "device",
+ "browser",
+ "os",
+ "timestamp",
+ ],
defaultVisible: ["trigger", "link", "country", "device", "timestamp"],
},
leads: {
- all: ["event", "link", "customer", "country", "device", "timestamp"],
+ all: [
+ "event",
+ "link",
+ "customer",
+ "country",
+ "city",
+ "device",
+ "browser",
+ "os",
+ "timestamp",
+ ],
defaultVisible: [
"event",
"link",
@@ -73,7 +94,10 @@ const eventColumns: Record<
"invoiceId",
"link",
"country",
+ "city",
"device",
+ "browser",
+ "os",
"amount",
"timestamp",
],
@@ -81,6 +105,14 @@ const eventColumns: Record<
},
};
+const getDefaultColumnVisibility = (event: EventType) =>
+ Object.fromEntries(
+ eventColumns[event].all.map((id) => [
+ id,
+ eventColumns[event].defaultVisible.includes(id),
+ ]),
+ );
+
export default function EventsTable() {
const { searchParams, queryParams } = useRouterStuff();
const tab = searchParams.get("tab") || "clicks";
@@ -90,6 +122,8 @@ export default function EventsTable() {
const { pagination, setPagination } = usePagination(PAGE_SIZE);
+ const scrollContainer = useRef<HTMLDivElement>(null);
+
const columns = useMemo<ColumnDef<Datum, any>[]>(
() =>
[
@@ -98,6 +132,7 @@ export default function EventsTable() {
id: "trigger",
header: "Event",
accessorKey: "qr",
+ enableHiding: false,
cell: ({ getValue }) => (
<div className="flex items-center gap-3">
{getValue() ? (
@@ -119,6 +154,7 @@ export default function EventsTable() {
id: "event",
header: "Event",
accessorKey: "event_name",
+ enableHiding: false,
cell: ({ getValue }) =>
getValue() || <span className="text-gray-400">-</span>,
},
@@ -183,6 +219,21 @@ export default function EventsTable() {
</div>
),
},
+ {
+ id: "city",
+ header: "City",
+ accessorKey: "city",
+ cell: ({ getValue, row }) => (
+ <div className="flex items-center gap-3">
+ <img
+ alt={row.original.country}
+ src={`https://hatscripts.github.io/circle-flags/flags/${row.original.country.toLowerCase()}.svg`}
+ className="h-4 w-4"
+ />
+ <span>{getValue()}</span>
+ </div>
+ ),
+ },
{
id: "device",
header: "Device",
@@ -198,11 +249,42 @@ export default function EventsTable() {
</div>
),
},
+ {
+ id: "browser",
+ header: "Browser",
+ accessorKey: "browser",
+ cell: ({ getValue }) => (
+ <div className="flex items-center gap-3">
+ <DeviceIcon
+ display={capitalize(getValue()) ?? getValue()}
+ tab="browsers"
+ className="h-4 w-4"
+ />
+ <span>{getValue()}</span>
+ </div>
+ ),
+ },
+ {
+ id: "os",
+ header: "OS",
+ accessorKey: "os",
+ cell: ({ getValue }) => (
+ <div className="flex items-center gap-3">
+ <DeviceIcon
+ display={capitalize(getValue()) ?? getValue()}
+ tab="os"
+ className="h-4 w-4"
+ />
+ <span>{getValue()}</span>
+ </div>
+ ),
+ },
// Date
{
id: "timestamp",
header: "Date",
accessorFn: (d) => new Date(d.timestamp),
+ enableHiding: false,
cell: ({ getValue }) => (
<Tooltip
content={getValue().toLocaleTimeString("en-US", {
@@ -232,6 +314,7 @@ export default function EventsTable() {
id: "amount",
header: "Sales Amount",
accessorKey: "amount",
+ enableHiding: false,
cell: ({ getValue }) => (
<div className="flex items-center gap-2">
<span>${nFormatter(getValue() / 100)}</span>
@@ -243,6 +326,15 @@ export default function EventsTable() {
[tab],
);
+ const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(
+ getDefaultColumnVisibility(tab as EventType),
+ );
+
+ useEffect(
+ () => setColumnVisibility(getDefaultColumnVisibility(tab as EventType)),
+ [tab],
+ );
+
const defaultData = useMemo(() => [], []);
const { queryString, totalEvents } = useContext(AnalyticsContext);
@@ -267,8 +359,10 @@ export default function EventsTable() {
getCoreRowModel: getCoreRowModel(),
rowCount: totalEvents?.[tab] ?? 0,
onPaginationChange: setPagination,
+ onColumnVisibilityChange: setColumnVisibility,
state: {
pagination,
+ columnVisibility,
},
manualPagination: true,
autoResetPageIndex: false,
@@ -284,7 +378,10 @@ export default function EventsTable() {
<div className="border border-gray-200 bg-white sm:rounded-xl">
<div className="relative rounded-[inherit]">
{(!error && !!data?.length) || isLoading ? (
- <div className="min-h-[400px] overflow-x-auto rounded-[inherit]">
+ <div
+ ref={scrollContainer}
+ className="min-h-[400px] overflow-x-auto rounded-[inherit]"
+ >
<table
className={cn(
"w-full border-separate border-spacing-0",
@@ -298,7 +395,7 @@ export default function EventsTable() {
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
- {headerGroup.headers.map((header) => {
+ {headerGroup.headers.map((header, columnIdx) => {
const isSortableColumn = ["timestamp", "amount"].includes(
header.column.id,
);
@@ -308,40 +405,50 @@ export default function EventsTable() {
className={cn(tableCellClassName, "font-medium")}
style={{ width: `${header.getSize()}px` }}
>
- <button
- className="flex items-center gap-2"
- disabled={!isSortableColumn}
- onClick={() =>
- queryParams({
- set: {
- sort: header.column.id,
- order:
- sortBy !== header.column.id
- ? "desc"
- : order === "asc"
+ <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"
- : "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
- }
+ : 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>
+ {columnIdx === headerGroup.headers.length - 1 && (
+ // Last column
+ <EventsTableMenu
+ table={table}
+ scrollContainer={scrollContainer}
/>
)}
- </button>
+ </div>
</th>
);
})}
diff --git a/packages/ui/src/icons/nucleo/gear.tsx b/packages/ui/src/icons/nucleo/gear.tsx
new file mode 100644
index 0000000000..973acb514c
--- /dev/null
+++ b/packages/ui/src/icons/nucleo/gear.tsx
@@ -0,0 +1,34 @@
+import { SVGProps } from "react";
+
+export function Gear(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ height="18"
+ width="18"
+ viewBox="0 0 18 18"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <g fill="#212121">
+ <circle
+ cx="9"
+ cy="9"
+ fill="none"
+ r="2.25"
+ stroke="#212121"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ <path
+ d="M16.25,9.355v-.71c0-.51-.383-.938-.89-.994l-1.094-.122-.503-1.214,.688-.859c.318-.398,.287-.971-.074-1.332l-.502-.502c-.36-.36-.934-.392-1.332-.074l-.859,.688-1.214-.503-.122-1.094c-.056-.506-.484-.89-.994-.89h-.71c-.51,0-.938,.383-.994,.89l-.122,1.094-1.214,.503-.859-.687c-.398-.318-.971-.287-1.332,.074l-.502,.502c-.36,.36-.392,.934-.074,1.332l.688,.859-.503,1.214-1.094,.122c-.506,.056-.89,.484-.89,.994v.71c0,.51,.383,.938,.89,.994l1.094,.122,.503,1.214-.687,.859c-.318,.398-.287,.972,.074,1.332l.502,.502c.36,.36,.934,.392,1.332,.074l.859-.688,1.214,.503,.122,1.094c.056,.506,.484,.89,.994,.89h.71c.51,0,.938-.383,.994-.89l.122-1.094,1.214-.503,.859,.688c.398,.318,.971,.287,1.332-.074l.502-.502c.36-.36,.392-.934,.074-1.332l-.687-.859,.503-1.214,1.094-.122c.506-.056,.89-.484,.89-.994Z"
+ fill="none"
+ stroke="#212121"
+ 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 63645e9884..cb9fe31e5f 100644
--- a/packages/ui/src/icons/nucleo/index.ts
+++ b/packages/ui/src/icons/nucleo/index.ts
@@ -3,6 +3,7 @@ export * from "./cube";
export * from "./cursor-rays";
export * from "./download";
export * from "./flag-wavy";
+export * from "./gear";
export * from "./globe";
export * from "./hyperlink";
export * from "./invoice-dollar";
diff --git a/packages/ui/src/popover.tsx b/packages/ui/src/popover.tsx
index d97a848340..0eeb19ccb2 100644
--- a/packages/ui/src/popover.tsx
+++ b/packages/ui/src/popover.tsx
@@ -13,6 +13,8 @@ export type PopoverProps = PropsWithChildren<{
setOpenPopover: (open: boolean) => void;
mobileOnly?: boolean;
popoverContentClassName?: string;
+ collisionBoundary?: Element | Element[];
+ sticky?: "partial" | "always";
onEscapeKeyDown?: (event: KeyboardEvent) => void;
}>;
@@ -24,10 +26,14 @@ export function Popover({
setOpenPopover,
mobileOnly,
popoverContentClassName,
+ collisionBoundary,
+ sticky,
onEscapeKeyDown,
}: PopoverProps) {
const { isMobile } = useMediaQuery();
+ if (collisionBoundary) console.log(collisionBoundary);
+
if (mobileOnly || isMobile) {
return (
<Drawer.Root open={openPopover} onOpenChange={setOpenPopover}>
@@ -66,6 +72,8 @@ export function Popover({
"animate-slide-up-fade z-50 items-center rounded-lg border border-gray-200 bg-white drop-shadow-lg sm:block",
popoverContentClassName,
)}
+ sticky={sticky}
+ collisionBoundary={collisionBoundary}
onEscapeKeyDown={onEscapeKeyDown}
>
{content}