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.

Stacked usage charts (#3150)

Tim Wilsonfad10fd06ed0
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/usage/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/usage/route.ts
index 69f4e7e7f0..dbb57fc726 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/usage/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/usage/route.ts
@@ -1,12 +1,23 @@
+import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
import { withWorkspace } from "@/lib/auth";
import { tb } from "@/lib/tinybird";
import { usageQuerySchema, usageResponse } from "@/lib/zod/schemas/usage";
+import { prisma } from "@dub/prisma";
+import { subYears } from "date-fns";
import { NextResponse } from "next/server";
import { z } from "zod";
export const GET = withWorkspace(async ({ searchParams, workspace }) => {
- const { resource, folderId, domain, start, end, timezone } =
- usageQuerySchema.parse(searchParams);
+ const {
+ resource,
+ folderId,
+ domain,
+ groupBy,
+ interval,
+ start,
+ end,
+ timezone,
+ } = usageQuerySchema.parse(searchParams);
const pipe = tb.buildPipe({
pipe: "v3_usage",
@@ -18,15 +29,77 @@ export const GET = withWorkspace(async ({ searchParams, workspace }) => {
data: usageResponse,
});
+ const { startDate, endDate } = getStartEndDates({
+ interval,
+ start,
+ end,
+ dataAvailableFrom: subYears(new Date(), 1),
+ timezone,
+ });
+
const response = await pipe({
resource,
workspaceId: workspace.id,
- start,
- end,
+ start: startDate.toISOString().replace("T", " ").replace("Z", ""),
+ end: endDate.toISOString().replace("T", " ").replace("Z", ""),
timezone,
...(folderId && { folderId }),
...(domain && { domain }),
+ ...(groupBy && { groupBy }),
});
- return NextResponse.json(response.data);
+ let data = response.data;
+
+ if (groupBy) {
+ const dates = [...new Set(response.data.map((d) => d.date))];
+ const groupIds = [...new Set(response.data.map((d) => d[groupBy] ?? ""))];
+
+ const where = {
+ projectId: workspace.id,
+ id: {
+ in: groupIds,
+ },
+ };
+
+ const groupMeta = await (groupBy === "folder_id"
+ ? prisma.folder.findMany({
+ select: {
+ id: true,
+ name: true,
+ },
+ where,
+ })
+ : prisma.domain.findMany({
+ select: {
+ id: true,
+ slug: true,
+ },
+ where,
+ }));
+
+ data = dates.map((date) => {
+ const groups = groupIds.map((groupId) => ({
+ id: groupId,
+ name:
+ groupMeta.find((g) => g.id === groupId)?.[
+ groupBy === "folder_id" ? "name" : "slug"
+ ] ?? groupId,
+ usage: sum(
+ response.data
+ .filter((d) => d.date === date && d[groupBy] === groupId)
+ .map((d) => d.value),
+ ),
+ }));
+
+ return {
+ date,
+ value: sum(groups.map((g) => g.usage)),
+ groups,
+ };
+ });
+ }
+
+ return NextResponse.json(data);
});
+
+const sum = (arr: number[]) => arr.reduce((acc, curr) => acc + curr, 0);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx
index 4e03ec3956..9aa6bd6b98 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx
@@ -64,6 +64,7 @@ export default function PlanUsage() {
const { partnersCount } = usePartnersCount<number>({
programId: defaultProgramId ?? undefined,
status: "approved",
+ ignoreParams: true,
});
const { groupsCount } = useGroupsCount();
@@ -330,11 +331,11 @@ function UsageTabCard({
</Tooltip>
)}
</div>
- <div className="mt-2">
+ <div className="mt-1.5">
{!loading ? (
<NumberFlow
value={usage}
- className="text-xl leading-none text-neutral-900"
+ className="text-2xl font-medium leading-none text-neutral-900"
format={
unit === "$"
? {
@@ -353,7 +354,7 @@ function UsageTabCard({
<div className="h-5 w-16 animate-pulse rounded-md bg-neutral-200" />
)}
</div>
- <div className="mt-5">
+ <div className="mt-4">
<div
className={cn(
"h-1 w-full overflow-hidden rounded-full bg-neutral-900/10 transition-colors",
@@ -368,9 +369,7 @@ function UsageTabCard({
<div
className={cn(
"size-full rounded-full",
- requiresUpgrade
- ? "bg-neutral-900/10"
- : "bg-gradient-to-r from-blue-500/80 to-blue-600",
+ requiresUpgrade ? "bg-neutral-900/10" : "bg-neutral-800",
warning && "from-neutral-900/10 via-red-500 to-red-600",
)}
style={{
@@ -383,7 +382,7 @@ function UsageTabCard({
</div>
<div className="mt-2 leading-none">
{!loading ? (
- <span className="text-xs leading-none text-neutral-600">
+ <span className="text-xs font-medium leading-none text-neutral-600">
{unlimited
? "Unlimited"
: `${prefix}${nFormatter(remaining, { full: true })} remaining of ${prefix}${nFormatter(limit, { full: limit < INFINITY_NUMBER })}`}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/usage-chart.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/usage-chart.tsx
index 82b1f0f899..180e1d69f0 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/usage-chart.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/usage-chart.tsx
@@ -1,20 +1,45 @@
import useDomains from "@/lib/swr/use-domains";
import useFolders from "@/lib/swr/use-folders";
import useUsage from "@/lib/swr/use-usage";
+import { BarList } from "@/ui/analytics/bar-list";
import { FolderIcon } from "@/ui/folders/folder-icon";
+import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
import {
AnimatedSizeContainer,
BlurImage,
EmptyState,
Filter,
LoadingSpinner,
+ Modal,
+ ToggleGroup,
useRouterStuff,
} from "@dub/ui";
import { Bars, TimeSeriesChart, XAxis, YAxis } from "@dub/ui/charts";
import { CursorRays, Folder, Globe2, Hyperlink } from "@dub/ui/icons";
import { cn, formatDate, GOOGLE_FAVICON_URL, nFormatter } from "@dub/utils";
-import { LinearGradient } from "@visx/gradient";
-import { ComponentProps, Fragment, useEffect, useMemo } from "react";
+import NumberFlow, { NumberFlowGroup } from "@number-flow/react";
+import {
+ ComponentProps,
+ Fragment,
+ useCallback,
+ useDeferredValue,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+
+const BAR_COLORS = [
+ "text-blue-500",
+ "text-indigo-500",
+ "text-red-500",
+ "text-emerald-500",
+ "text-purple-500",
+ "text-sky-500",
+ "text-orange-500",
+ "text-lime-500",
+ "text-pink-500",
+];
const RESOURCES = ["links", "events"] as const;
const resourceEmptyStates: Record<
@@ -24,35 +49,33 @@ const resourceEmptyStates: Record<
links: {
icon: Hyperlink,
title: "Links Created",
- description:
- "No short links have been created in the current billing cycle.",
+ description: "No short links have been created in the selected date range.",
},
events: {
icon: CursorRays,
title: "Events Tracked",
- description: "No events have been tracked in the current billing cycle.",
+ description: "No events have been tracked in the selected date range.",
},
};
export function UsageChart() {
const { queryParams, searchParamsObj } = useRouterStuff();
- const { usage, loading, activeResource } = useUsage();
+ const {
+ usage,
+ loading,
+ isValidating,
+ activeResource,
+ start,
+ end,
+ interval,
+ groupBy,
+ } = useUsage();
// Get filter values from URL params
const folderId = searchParamsObj.folderId;
const domain = searchParamsObj.domain;
- // Clear folder and domain filters when switching away from "links" tab
- useEffect(() => {
- if (activeResource !== "links" && (folderId || domain)) {
- queryParams({
- del: ["folderId", "domain"],
- scroll: false,
- });
- }
- }, [activeResource, folderId, domain, queryParams]);
-
// Fetch folders and domains for filter options
const { folders } = useFolders();
const { allDomains: domains } = useDomains({ ignoreParams: true });
@@ -79,11 +102,8 @@ export function UsageChart() {
});
};
- // Define filters (only show folder and domain filters when resource is "links")
- const filters = useMemo(() => {
- if (activeResource !== "links") return [];
-
- return [
+ const filters = useMemo(
+ () => [
{
key: "folderId",
icon: Folder,
@@ -120,68 +140,234 @@ export function UsageChart() {
),
})) ?? [],
},
- ];
- }, [activeResource, folders, domains]);
+ ],
+ [activeResource, folders, domains],
+ );
// Active filters
const activeFilters = useMemo(() => {
const filters: { key: string; value: string }[] = [];
- if (folderId) {
- filters.push({ key: "folderId", value: folderId });
- }
- if (domain) {
- filters.push({ key: "domain", value: domain });
- }
+ if (folderId) filters.push({ key: "folderId", value: folderId });
+ if (domain) filters.push({ key: "domain", value: domain });
return filters;
}, [folderId, domain]);
const chartData = useMemo(
() =>
- usage?.map(({ date, value }) => ({
+ usage?.map(({ date, value, groups }) => ({
date: new Date(date),
- values: { usage: value },
+ values: {
+ usage: value,
+ ...Object.fromEntries(groups.map((group) => [group.id, group.usage])),
+ },
})),
[usage, activeResource],
);
+ const groupsMeta = useMemo(
+ () =>
+ Object.fromEntries(
+ usage?.[0]?.groups?.map((g, idx) => [
+ g.id,
+ {
+ name: g.name,
+ colorClassName: BAR_COLORS[idx % BAR_COLORS.length],
+ total: usage.reduce(
+ (sum, { groups }) =>
+ sum + (groups.find(({ id }) => id === g.id)?.usage ?? 0),
+ 0,
+ ),
+ },
+ ]) ?? [],
+ ),
+ [usage],
+ );
+
+ const totalUsage = useMemo(
+ () => usage?.reduce((sum, { value }) => sum + value, 0) ?? 0,
+ [usage],
+ );
+
+ // Map dates to indices for O(1) hover lookups
+ const usageIndexByDate = useMemo(() => {
+ if (!usage) return null;
+ const map = new Map<number, number>();
+ usage.forEach((u, index) => {
+ map.set(new Date(u.date).getTime(), index);
+ });
+ return map;
+ }, [usage]);
+
+ const [hoveredDate, setHoveredDate] = useState<Date | null>(null);
+
+ // Throttle hover updates to animation frames to avoid excessive rerenders
+ const hoverRafRef = useRef<number | null>(null);
+ const handleHoverDateChange = useCallback((date: Date | null) => {
+ if (hoverRafRef.current !== null) return;
+
+ hoverRafRef.current = window.requestAnimationFrame(() => {
+ hoverRafRef.current = null;
+ setHoveredDate(date);
+ });
+ }, []);
+
+ useEffect(
+ () => () => {
+ if (hoverRafRef.current !== null) {
+ window.cancelAnimationFrame(hoverRafRef.current);
+ }
+ },
+ [],
+ );
+
+ const hoveredGroupsMeta = useMemo(() => {
+ if (!hoveredDate || !usage || !usageIndexByDate) return null;
+
+ const index = usageIndexByDate.get(hoveredDate.getTime());
+ if (index == null) return null;
+
+ const dayUsage = usage[index];
+
+ return Object.fromEntries(
+ dayUsage.groups.map((g, idx) => [
+ g.id,
+ {
+ name: g.name,
+ colorClassName: BAR_COLORS[idx % BAR_COLORS.length],
+ total: g.usage,
+ },
+ ]),
+ );
+ }, [hoveredDate, usage, usageIndexByDate]);
+
+ const hoveredTotalUsage = useMemo(() => {
+ if (!hoveredDate || !usage || !usageIndexByDate) return null;
+
+ const index = usageIndexByDate.get(hoveredDate.getTime());
+ if (index == null) return null;
+
+ return usage[index].value;
+ }, [hoveredDate, usage, usageIndexByDate]);
+
+ // Defer updates to the breakdown list below so tooltip + chart hover stay snappy
+ const deferredHoveredGroupsMeta = useDeferredValue(hoveredGroupsMeta);
+ const deferredHoveredTotalUsage = useDeferredValue(hoveredTotalUsage);
+
const allZeroes = useMemo(
() => chartData?.every(({ values }) => values.usage === 0),
[chartData],
);
+ const sortedGroupEntries = useMemo(
+ () =>
+ groupsMeta
+ ? Object.entries(groupsMeta).sort((a, b) => b[1].total - a[1].total)
+ : [],
+ [groupsMeta],
+ );
+
+ const [showGroupsModal, setShowGroupsModal] = useState(false);
+
+ const hasMoreGroups = sortedGroupEntries.length > 12;
+
+ const barListTabLabel =
+ groupBy === "folderId"
+ ? "Folder"
+ : groupBy === "domain"
+ ? "Domain"
+ : "Group";
+
+ const barListData = useMemo(
+ () =>
+ sortedGroupEntries.map(([id, meta]) => {
+ let href: string | undefined;
+
+ if (groupBy === "folderId" || groupBy === "domain") {
+ const hasFilter = searchParamsObj?.[groupBy] === id;
+ href = queryParams({
+ ...(hasFilter
+ ? { del: groupBy }
+ : {
+ set: {
+ [groupBy]: id,
+ },
+ }),
+ getNewPath: true,
+ }) as string;
+ }
+
+ return {
+ icon: (
+ <div
+ className={cn(
+ "size-2 rounded-full bg-current",
+ meta.colorClassName,
+ )}
+ />
+ ),
+ title: meta.name || "Unsorted",
+ href,
+ value: meta.total,
+ };
+ }),
+ [sortedGroupEntries, groupBy, queryParams, searchParamsObj],
+ );
+
+ const maxGroupTotal = useMemo(
+ () =>
+ sortedGroupEntries.length > 0
+ ? Math.max(...sortedGroupEntries.map(([, meta]) => meta.total))
+ : 0,
+ [sortedGroupEntries],
+ );
+
return (
- <div
- className={cn(
- "space-y-4 pt-6 md:pt-8",
- activeResource === "links" && "pt-4 md:pt-4",
- )}
- >
- {/* Filters - only show when resource is "links" */}
- {activeResource === "links" && (
- <div className="flex flex-col gap-3">
- <Filter.Select
- className="w-full md:w-fit"
- filters={filters}
- activeFilters={activeFilters}
- onSelect={onSelect}
- onRemove={onRemove}
+ <div className="space-y-4 pt-8">
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <Filter.Select
+ className="h-9 w-full md:w-fit"
+ filters={filters}
+ activeFilters={activeFilters}
+ onSelect={onSelect}
+ onRemove={onRemove}
+ />
+ <SimpleDateRangePicker
+ presets={["7d", "30d", "90d", "1y", "mtd", "qtd", "ytd"]}
+ values={{ start, end, interval }}
+ className="h-9"
+ />
+ </div>
+ <ToggleGroup
+ options={[
+ { value: "folderId", label: "Folder" },
+ { value: "domain", label: "Domain" },
+ ]}
+ selected={groupBy}
+ selectAction={(id) => queryParams({ set: { groupBy: id } })}
+ className="rounded-lg border-transparent bg-neutral-100 p-0.5"
+ optionClassName="text-xs text-neutral-800 data-[selected=true]:text-neutral-800 px-3 sm:px-5 py-2 leading-none"
+ indicatorClassName="bg-white border-neutral-200 rounded-md"
/>
- <AnimatedSizeContainer height>
- {activeFilters.length > 0 && (
- <Filter.List
- filters={filters}
- activeFilters={activeFilters}
- onSelect={onSelect}
- onRemove={onRemove}
- onRemoveAll={onRemoveAll}
- />
- )}
- </AnimatedSizeContainer>
</div>
- )}
+ <AnimatedSizeContainer height>
+ {activeFilters.length > 0 && (
+ <Filter.List
+ filters={filters}
+ activeFilters={activeFilters}
+ onSelect={onSelect}
+ onRemove={onRemove}
+ onRemoveAll={onRemoveAll}
+ />
+ )}
+ </AnimatedSizeContainer>
+ </div>
{/* Chart */}
- <div className="h-64">
+ <div
+ className={cn("h-64 transition-opacity", isValidating && "opacity-50")}
+ >
{chartData && chartData.length > 0 ? (
!allZeroes ? (
<TimeSeriesChart
@@ -193,47 +379,72 @@ export function UsageChart() {
id: "usage",
valueAccessor: (d) => d.values.usage,
colorClassName: "text-violet-500",
- isActive: true,
+ isActive: false,
},
+ ...(usage?.[0]?.groups?.map((group) => ({
+ id: group.id,
+ valueAccessor: (d) => d.values[group.id],
+ colorClassName: groupsMeta[group.id]?.colorClassName,
+ isActive: true,
+ })) ?? []),
]}
- tooltipClassName="p-0"
+ tooltipClassName="p-0 overflow-hidden max-w-64"
+ onHoverDateChange={handleHoverDateChange}
tooltipContent={(d) => {
+ const topGroups = usage?.[0]?.groups
+ ?.filter((group) => (d.values[group.id] ?? 0) > 0)
+ .sort((a, b) => (d.values[b.id] ?? 0) - (d.values[a.id] ?? 0))
+ .slice(0, 8);
+
return (
<>
- <p className="border-b border-neutral-200 px-4 py-3 text-sm text-neutral-900">
- {formatDate(d.date)}
- </p>
- <div className="grid grid-cols-2 gap-x-6 gap-y-2 px-4 py-3 text-sm">
- <Fragment key={activeResource}>
- <div className="flex items-center gap-2">
- <div className="h-2 w-2 rounded-sm bg-violet-500 shadow-[inset_0_0_0_1px_#0003]" />
- <p className="capitalize text-neutral-600">
- {activeResource}
- </p>
- </div>
- <p className="text-right font-medium text-neutral-900">
- {nFormatter(d.values.usage, { full: true })}
- </p>
- </Fragment>
+ <div className="flex items-center justify-between gap-4 px-4 py-3 text-xs">
+ <span className="text-content-emphasis font-semibold">
+ {formatDate(d.date, { month: "short" })}
+ </span>
+ <span className="text-content-default font-medium">
+ {nFormatter(d.values.usage, { full: true })}
+ </span>
</div>
+ {Boolean(topGroups?.length) && (
+ <div className="border-border-subtle relative grid grid-cols-[minmax(0,1fr),min-content] gap-x-6 gap-y-2 overflow-hidden border-t px-4 py-3 text-xs">
+ {topGroups?.map((group) => {
+ const value = d.values[group.id];
+ if (!value) return null;
+
+ return (
+ <Fragment key={group.id}>
+ <div className="flex items-center gap-2">
+ <div
+ className={cn(
+ "size-2 shrink-0 rounded-full bg-current",
+ groupsMeta[group.id]?.colorClassName,
+ )}
+ />
+ <span
+ className={cn(
+ "min-w-0 truncate text-neutral-600",
+ !group.name && "text-content-subtle",
+ )}
+ >
+ {group.name || "Unsorted"}
+ </span>
+ </div>
+ <span className="text-right font-medium text-neutral-900">
+ {nFormatter(value, { full: true })}
+ </span>
+ </Fragment>
+ );
+ })}
+ </div>
+ )}
</>
);
}}
>
- <LinearGradient id="usage-bar-gradient">
- <stop stopColor="#2563eb" stopOpacity={1} offset="20%" />
- <stop stopColor="#3b82f6" stopOpacity={0.9} offset="100%" />
- </LinearGradient>
<XAxis highlightLast={false} />
<YAxis showGridLines tickFormat={nFormatter} />
- <Bars
- seriesStyles={[
- {
- id: "usage",
- barFill: "url(#usage-bar-gradient)",
- },
- ]}
- />
+ <Bars />
</TimeSeriesChart>
) : (
<div className="flex size-full items-center justify-center">
@@ -246,6 +457,133 @@ export function UsageChart() {
</div>
)}
</div>
+
+ <div className="relative">
+ <div
+ className={cn(
+ "flex flex-col transition-opacity",
+ isValidating && "opacity-50",
+ )}
+ >
+ <NumberFlowGroup>
+ {sortedGroupEntries.length > 0 ? (
+ <>
+ {sortedGroupEntries.slice(0, 12).map(([id, meta]) => {
+ const hoveredMeta = deferredHoveredGroupsMeta?.[id];
+ const displayTotal = hoveredMeta?.total ?? meta.total;
+
+ return (
+ <button
+ key={id}
+ type="button"
+ onClick={() => queryParams({ set: { [groupBy]: id } })}
+ disabled={!id}
+ className="flex items-center justify-between gap-4 rounded-lg px-3 py-2 text-xs font-medium enabled:hover:bg-black/[0.03] enabled:active:bg-black/5"
+ >
+ <div className="flex items-center gap-2">
+ <div
+ className={cn(
+ "size-2 rounded-full bg-current",
+ meta.colorClassName,
+ )}
+ />
+ <span
+ className={cn(
+ "text-content-emphasis",
+ !meta.name && "text-content-subtle",
+ )}
+ >
+ {meta.name || "Unsorted"}
+ </span>
+ </div>
+ <div className="flex items-center gap-2 tabular-nums">
+ <NumberFlow
+ value={displayTotal}
+ className="text-content-default text-right font-medium"
+ />
+ {usage && (
+ <span className="text-content-muted min-w-12 text-right font-medium">
+ <NumberFlow
+ value={
+ (displayTotal /
+ ((deferredHoveredTotalUsage ?? totalUsage) ||
+ 1)) *
+ 100
+ }
+ format={{ maximumFractionDigits: 0 }}
+ />
+ %
+ </span>
+ )}
+ </div>
+ </button>
+ );
+ })}
+ </>
+ ) : (
+ <>
+ {loading ? (
+ [...Array(3)].map((_, idx) => (
+ <div
+ key={idx}
+ className="flex animate-pulse items-center justify-between gap-4 px-3 py-2 text-xs font-medium"
+ >
+ <div className="flex items-center gap-2">
+ <div className="size-2 rounded-full bg-neutral-200" />
+ <div className="h-4 w-32 min-w-0 rounded-md bg-neutral-200" />
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="h-4 w-8 rounded-md bg-neutral-200" />
+ <div className="h-4 w-6 rounded-md bg-neutral-200" />
+ </div>
+ </div>
+ ))
+ ) : (
+ <p className="text-content-subtle flex size-full items-center justify-center py-5 text-sm">
+ Failed to load usage data
+ </p>
+ )}
+ </>
+ )}
+ </NumberFlowGroup>
+ </div>
+
+ {hasMoreGroups && (
+ <div className="absolute bottom-0 left-0 flex w-full items-end">
+ <div className="pointer-events-none absolute bottom-0 left-0 h-20 w-full bg-gradient-to-t from-white" />
+ <button
+ type="button"
+ onClick={() => setShowGroupsModal(true)}
+ className="z-10 mx-auto rounded-md border border-neutral-200 bg-white px-2.5 py-1 text-sm text-neutral-950 hover:bg-neutral-100 active:border-neutral-300"
+ >
+ View all
+ </button>
+ </div>
+ )}
+ </div>
+
+ {hasMoreGroups && (
+ <Modal showModal={showGroupsModal} setShowModal={setShowGroupsModal}>
+ <div className="w-full max-w-md bg-white">
+ <div className="border-b border-neutral-200 px-5 py-4">
+ <h3 className="text-sm font-semibold text-neutral-900">
+ Usage breakdown by {barListTabLabel.toLowerCase()}
+ </h3>
+ </div>
+ <div className="max-h-[70vh] overflow-hidden">
+ <BarList
+ tab={barListTabLabel.toLowerCase()}
+ unit={activeResource}
+ data={barListData}
+ maxValue={maxGroupTotal}
+ barBackground="bg-violet-100"
+ hoverBackground="hover:bg-gradient-to-r hover:from-violet-50 hover:to-transparent hover:border-violet-500"
+ setShowModal={setShowGroupsModal}
+ />
+ </div>
+ </div>
+ </Modal>
+ )}
</div>
);
}
diff --git a/apps/web/lib/swr/use-partners-count.ts b/apps/web/lib/swr/use-partners-count.ts
index edba77a4dd..84824e81ac 100644
--- a/apps/web/lib/swr/use-partners-count.ts
+++ b/apps/web/lib/swr/use-partners-count.ts
@@ -21,8 +21,7 @@ export default function usePartnersCount<T>({
const queryString = ignoreParams
? // @ts-ignore
`?${new URLSearchParams({
- ...(params.groupBy && { groupBy: params.groupBy }),
- ...(params.status && { status: params.status }),
+ ...params,
workspaceId,
}).toString()}`
: getQueryString(
diff --git a/apps/web/lib/swr/use-usage.ts b/apps/web/lib/swr/use-usage.ts
index f25805cf29..244b2211f4 100644
--- a/apps/web/lib/swr/use-usage.ts
+++ b/apps/web/lib/swr/use-usage.ts
@@ -1,8 +1,8 @@
import { fetcher, getFirstAndLastDay } from "@dub/utils";
+import { endOfDay, startOfDay } from "date-fns";
import { useSearchParams } from "next/navigation";
import { useMemo } from "react";
import useSWR from "swr";
-import { UsageResponse } from "../types";
import useWorkspace from "./use-workspace";
// here we're using disabledWhenNoFilters for the special case where we need to
@@ -26,7 +26,7 @@ export default function useUsage({
const activeResource = useMemo(() => {
const tab = searchParams.get("tab");
if (tab && ["links", "events"].includes(tab)) {
- return tab;
+ return tab as "links" | "events";
}
return defaultActiveTab;
}, [searchParams, defaultActiveTab]);
@@ -36,30 +36,60 @@ export default function useUsage({
const domain = searchParams.get("domain");
const hasActiveFilters = folderId || domain ? true : false;
+ const { start, end, interval } = useMemo(() => {
+ if (searchParams.has("interval"))
+ return {
+ interval: searchParams.get("interval") || "30d",
+ start: undefined,
+ end: undefined,
+ };
+
+ return {
+ start: searchParams.get("start") || firstDay.toISOString(),
+ end: searchParams.get("end") || lastDay.toISOString(),
+ interval: undefined,
+ };
+ }, [searchParams, firstDay, lastDay]);
+
+ const groupBy: "folderId" | "domain" =
+ (["folderId", "domain"] as const).find(
+ (gb) => gb === searchParams.get("groupBy"),
+ ) ?? "folderId";
+
const {
data: usage,
error,
isValidating,
- } = useSWR<UsageResponse[]>(
+ } = useSWR<
+ {
+ date: string;
+ value: number;
+ groups: { id: string; name: string; usage: number }[];
+ }[]
+ >(
workspaceId &&
(disabledWhenNoFilters ? hasActiveFilters : true) &&
`/api/workspaces/${workspaceId}/billing/usage?${new URLSearchParams({
resource: activeResource,
- start: firstDay.toISOString().replace("T", " ").replace("Z", ""),
- // get end of the day (11:59:59 PM)
- end: new Date(lastDay.getTime() + 86399999)
- .toISOString()
- .replace("T", " ")
- .replace("Z", ""),
+ ...(start &&
+ end && {
+ start: startOfDay(new Date(start)).toISOString(),
+ end: endOfDay(new Date(end)).toISOString(),
+ }),
+ ...(interval && { interval }),
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
...(folderId && { folderId }),
...(domain && { domain }),
+ ...(groupBy && {
+ groupBy: groupBy === "folderId" ? "folder_id" : "domain",
+ }),
...(disabledWhenNoFilters &&
hasActiveFilters && { cacheKey: "disabledWhenNoFilters" }),
}).toString()}`,
fetcher,
{
dedupingInterval: 60000,
+ revalidateOnFocus: false,
keepPreviousData: true,
},
);
@@ -68,6 +98,10 @@ export default function useUsage({
usage,
activeResource,
hasActiveFilters,
+ start,
+ end,
+ interval,
+ groupBy,
loading: !usage && !error,
isValidating,
};
diff --git a/apps/web/lib/zod/schemas/usage.ts b/apps/web/lib/zod/schemas/usage.ts
index 523ceaade0..e617198fc8 100644
--- a/apps/web/lib/zod/schemas/usage.ts
+++ b/apps/web/lib/zod/schemas/usage.ts
@@ -1,15 +1,20 @@
+import { DATE_RANGE_INTERVAL_PRESETS } from "@/lib/analytics/constants";
import z from "@/lib/zod";
export const usageQuerySchema = z.object({
resource: z.enum(["links", "events", "revenue"]),
folderId: z.string().optional(),
domain: z.string().optional(),
- start: z.string(),
- end: z.string(),
+ groupBy: z.enum(["folder_id", "domain"]).optional(),
+ interval: z.enum(DATE_RANGE_INTERVAL_PRESETS).optional(),
+ start: z.string().optional(),
+ end: z.string().optional(),
timezone: z.string().optional().default("UTC"),
});
export const usageResponse = z.object({
date: z.string(),
value: z.number(),
+ folder_id: z.string().optional(),
+ domain: z.string().optional(),
});
diff --git a/apps/web/ui/analytics/analytics-card.tsx b/apps/web/ui/analytics/analytics-card.tsx
index 8f82a8dc12..654630b194 100644
--- a/apps/web/ui/analytics/analytics-card.tsx
+++ b/apps/web/ui/analytics/analytics-card.tsx
@@ -89,7 +89,7 @@ export function AnalyticsCard<T extends string>({
</Modal>
<div
className={cn(
- "group relative z-0 h-[400px] overflow-hidden border border-neutral-200 bg-white rounded-lg sm:rounded-xl",
+ "group relative z-0 h-[400px] overflow-hidden rounded-lg border border-neutral-200 bg-white sm:rounded-xl",
className,
)}
>
diff --git a/apps/web/ui/shared/simple-date-range-picker.tsx b/apps/web/ui/shared/simple-date-range-picker.tsx
index f3bd2a938c..65843d2d76 100644
--- a/apps/web/ui/shared/simple-date-range-picker.tsx
+++ b/apps/web/ui/shared/simple-date-range-picker.tsx
@@ -1,24 +1,33 @@
-import { INTERVAL_DISPLAYS } from "@/lib/analytics/constants";
+import {
+ DATE_RANGE_INTERVAL_PRESETS,
+ INTERVAL_DISPLAYS,
+} from "@/lib/analytics/constants";
import { getIntervalData } from "@/lib/analytics/utils";
import { DateRangePicker, useRouterStuff } from "@dub/ui";
+type Values = {
+ start?: string;
+ end?: string;
+ interval?: string;
+};
+
export default function SimpleDateRangePicker({
className,
align = "center",
defaultInterval = "30d",
+ values,
disabled,
+ presets,
}: {
className?: string;
align?: "start" | "center" | "end";
defaultInterval?: string;
+ values?: Values;
disabled?: boolean;
+ presets?: (typeof DATE_RANGE_INTERVAL_PRESETS)[number][];
}) {
const { queryParams, searchParamsObj } = useRouterStuff();
- const { start, end, interval } = searchParamsObj as {
- start?: string;
- end?: string;
- interval?: string;
- };
+ const { start, end, interval } = values ?? (searchParamsObj as Values);
return (
<DateRangePicker
@@ -58,7 +67,12 @@ export default function SimpleDateRangePicker({
scroll: false,
});
}}
- presets={INTERVAL_DISPLAYS.map(({ display, value, shortcut }) => {
+ presets={(presets
+ ? INTERVAL_DISPLAYS.filter(({ value }) =>
+ (presets as string[]).includes(value),
+ )
+ : INTERVAL_DISPLAYS
+ ).map(({ display, value, shortcut }) => {
const start = getIntervalData(value).startDate;
const end = new Date();
diff --git a/packages/tinybird/pipes/v3_usage_latest.pipe b/packages/tinybird/pipes/v3_usage_latest.pipe
new file mode 100644
index 0000000000..be600a137b
--- /dev/null
+++ b/packages/tinybird/pipes/v3_usage_latest.pipe
@@ -0,0 +1,148 @@
+NODE day_intervals
+SQL >
+
+ %
+ WITH
+ toStartOfDay(
+ toDateTime64({{ DateTime64(start, '2025-09-03 00:00:00.000') }}, 3),
+ {{ String(timezone, 'UTC') }}
+ ) AS start,
+ toStartOfDay(
+ toDateTime64({{ DateTime64(end, '2025-10-03 00:00:00.000') }}, 3),
+ {{ String(timezone, 'UTC') }}
+ ) AS
+ end
+ SELECT
+ arrayJoin(
+ arrayMap(
+ x -> toDateTime64(toStartOfDay(toDateTime64(x, 3), {{ String(timezone, 'UTC') }}), 3),
+ range(toUInt32(start + 86400), toUInt32(end + 86400),
+ 86400
+ )
+ )
+ ) as interval
+
+
+
+NODE usage_events_data
+SQL >
+
+ %
+ SELECT
+ toDateTime64(toStartOfDay(timestamp, {{ String(timezone, 'UTC') }}), 3) AS interval,
+ {% if defined(groupBy) %} {% if groupBy == 'folder_id' %} folder_id {% else %} domain {% end %}, {% end %}
+ uniq(*) AS events
+ FROM
+ (
+ -- Click events
+ SELECT e.timestamp{% if defined(groupBy) %}, {% if groupBy == 'folder_id' %} m.folder_id {% else %} e.domain {% end %}, {% end %}
+ FROM dub_click_events_mv e
+ {% if groupBy == 'folder_id' or defined(folderId) %} LEFT JOIN dub_links_metadata_latest m ON m.link_id = e.link_id {% end %}
+ WHERE
+ workspace_id
+ = {{
+ String(
+ workspaceId,
+ 'cl7pj5kq4006835rbjlt2ofka',
+ description="The unique ID for the workspace",
+ required=True,
+ )
+ }}
+ AND timestamp >= {{ DateTime(start, '2025-09-03 00:00:00') }}
+ AND timestamp < {{ DateTime(end, '2025-10-03 00:00:00') }}
+ {% if defined(folderId) %} AND folder_id = {{ folderId }} {% end %}
+ {% if defined(domain) %} AND domain IN {{ Array(domain, 'String') }} {% end %}
+
+ UNION ALL
+
+ -- Lead events
+ SELECT e.timestamp{% if defined(groupBy) %}, {% if groupBy == 'folder_id' %} m.folder_id {% else %} e.domain {% end %}, {% end %}
+ FROM dub_lead_events_mv e
+ {% if groupBy == 'folder_id' or defined(folderId) %} LEFT JOIN dub_links_metadata_latest m ON m.link_id = e.link_id {% end %}
+ WHERE
+ workspace_id = {{ String(workspaceId, 'cl7pj5kq4006835rbjlt2ofka') }}
+ AND timestamp >= {{ DateTime(start, '2025-09-03 00:00:00') }}
+ AND timestamp < {{ DateTime(end, '2025-10-03 00:00:00') }}
+ {% if defined(folderId) %} AND folder_id = {{ folderId }} {% end %}
+ {% if defined(domain) %} AND domain IN {{ Array(domain, 'String') }} {% end %}
+
+ UNION ALL
+
+ -- Sale events
+ SELECT e.timestamp{% if defined(groupBy) %}, {% if groupBy == 'folder_id' %} m.folder_id {% else %} e.domain {% end %}, {% end %}
+ FROM dub_sale_events_mv e
+ {% if groupBy == 'folder_id' or defined(folderId) %} LEFT JOIN dub_links_metadata_latest m ON m.link_id = e.link_id {% end %}
+ WHERE
+ workspace_id = {{ String(workspaceId, 'cl7pj5kq4006835rbjlt2ofka') }}
+ AND timestamp >= {{ DateTime(start, '2025-09-03 00:00:00') }}
+ AND timestamp < {{ DateTime(end, '2025-10-03 00:00:00') }}
+ {% if defined(folderId) %} AND folder_id = {{ folderId }} {% end %}
+ {% if defined(domain) %} AND domain IN {{ Array(domain, 'String') }} {% end %}
+ )
+ GROUP BY interval{% if defined(groupBy) %}, {% if groupBy == 'folder_id' %} folder_id {% else %} domain {% end %} {% end %}
+ ORDER BY interval
+
+
+
+NODE usage_events
+SQL >
+
+ %
+ SELECT
+ formatDateTime(interval, '%FT%T.000%z') as date,
+ {% if defined(groupBy) %} {% if groupBy == 'folder_id' %} folder_id {% else %} domain {% end %}, {% end %}
+ events as value
+ FROM day_intervals
+ LEFT JOIN usage_events_data USING interval
+
+
+
+NODE usage_links_data
+SQL >
+
+ %
+ SELECT
+ toDateTime64(toStartOfDay(timestamp, {{ String(timezone, 'UTC') }}), 3) AS interval,
+ {% if defined(groupBy) %} {% if groupBy == 'folder_id' %} folder_id {% else %} domain {% end %}, {% end %}
+ uniq(*) as links
+ FROM dub_links_metadata_latest FINAL
+ WHERE
+ workspace_id
+ = {{
+ String(
+ workspaceId,
+ 'clrei1gld0002vs9mzn93p8ik',
+ description="The ID of the workspace",
+ required=True,
+ )
+ }}
+ AND created_at >= {{ DateTime(start, '2025-09-03 00:00:00') }}
+ AND created_at < {{ DateTime(end, '2025-10-03 00:00:00') }}
+ {% if defined(folderId) %} AND folder_id = {{ folderId }}
+ {% end %}
+ {% if defined(domain) %} AND domain IN {{ Array(domain, 'String') }} {% end %}
+ GROUP BY interval{% if defined(groupBy) %}, {% if groupBy == 'folder_id' %} folder_id {% else %} domain {% end %} {% end %}
+ ORDER BY interval
+
+
+
+NODE usage_links
+SQL >
+
+ %
+ SELECT
+ formatDateTime(interval, '%FT%T.000%z') as date,
+ {% if defined(groupBy) %} {% if groupBy == 'folder_id' %} folder_id {% else %} domain {% end %}, {% end %}
+ links as value
+ FROM day_intervals
+ LEFT JOIN usage_links_data USING interval
+
+
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT * FROM {% if resource == 'events' %} usage_events {% else %} usage_links {% end %}
+
+
diff --git a/packages/ui/src/charts/bars.tsx b/packages/ui/src/charts/bars.tsx
index 0ff30a5fd7..ed69580e2b 100644
--- a/packages/ui/src/charts/bars.tsx
+++ b/packages/ui/src/charts/bars.tsx
@@ -1,6 +1,5 @@
import { cn } from "@dub/utils";
import { RectClipPath } from "@visx/clip-path";
-import { LinearGradient } from "@visx/gradient";
import { Group } from "@visx/group";
import { BarRounded } from "@visx/shape";
import { AnimatePresence, motion } from "motion/react";
@@ -9,13 +8,14 @@ import { useChartContext } from "./chart-context";
export function Bars({
seriesStyles,
+ radius = 2,
}: {
seriesStyles?: {
id: string;
- gradientClassName?: string;
barClassName?: string;
barFill?: string;
}[];
+ radius?: number;
}) {
const clipPathId = useId();
const {
@@ -33,75 +33,71 @@ export function Bars({
if (!("bandwidth" in xScale))
throw new Error("Bars require a band scale (type=bar)");
+ const activeSeries = series.filter(({ isActive }) => isActive);
+
return (
<Group left={margin.left} top={margin.top}>
<RectClipPath id={clipPathId} x={0} y={0} width={width} height={height} />
<AnimatePresence>
- {series
- .filter(({ isActive }) => isActive)
- .map((s) => {
- const styles = seriesStyles?.find(({ id }) => id === s.id);
- return (
- // Prevent ugly x-scale animations when start/end dates change with unique key
- <motion.g
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- transition={{ duration: 0.1 }}
- key={`${s.id}_${startDate.toString()}_${endDate.toString()}`}
- clipPath={`url(#${clipPathId})`}
- >
- {/* Bar gradient */}
- <LinearGradient
- className={cn(
- s.colorClassName ?? "text-blue-500",
- styles?.gradientClassName,
- )}
- id={`${s.id}-background`}
- fromOffset="0%"
- from="currentColor"
- fromOpacity={0.01}
- toOffset="40%"
- to="currentColor"
- toOpacity={1}
- x1={0}
- x2={0}
- y1={1}
- />
+ <motion.g
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: 0.1 }}
+ key={`${activeSeries.map((s) => s.id).join(",")}_${startDate.toString()}_${endDate.toString()}`}
+ clipPath={`url(#${clipPathId})`}
+ >
+ {data.map((d) => {
+ const barWidth = xScale.bandwidth();
+ const x = xScale(d.date) ?? 0;
+
+ const sortedSeries = activeSeries
+ .filter((s) => s.valueAccessor(d) > 0)
+ .sort((a, b) => b.valueAccessor(d) - a.valueAccessor(d));
- {/* Bars */}
- <motion.g
- initial={{ y: 100 }}
- animate={{ y: 0 }}
- transition={{ duration: 0.15, ease: "easeOut" }}
- >
- {data.map((d) => {
- const barWidth = xScale.bandwidth();
- const x = xScale(d.date) ?? 0;
- const y = yScale(s.valueAccessor(d) ?? 0);
- const barHeight = height - y;
- const radius = Math.min(barWidth, barHeight) / 2;
- return barHeight > 0 ? (
- <BarRounded
- key={d.date.toString()}
- x={x}
- y={y}
- width={barWidth}
- height={barHeight}
- radius={1000}
- top
- className={cn(
- s.colorClassName ?? "text-blue-700",
- styles?.barClassName,
- )}
- fill={styles?.barFill ?? `url(#${s.id}-background)`}
- />
- ) : null;
- })}
- </motion.g>
- </motion.g>
+ const bars = sortedSeries.reduce((acc, s) => {
+ const stackHeight = acc.reduce((sum, b) => sum + b.height, 0);
+ const value = s.valueAccessor(d) ?? 0;
+ const y = yScale(value);
+
+ return [
+ ...acc,
+ {
+ id: s.id,
+ value,
+ colorClassName: s.colorClassName,
+ styles: seriesStyles?.find(({ id }) => id === s.id),
+ y: stackHeight, // y from x axis to bottom of bar
+ height: height - y, // height from bottom to top of bar
+ },
+ ];
+ }, [] as any[]);
+
+ return (
+ <g key={d.date.toString()}>
+ {bars.map((b, idx) => {
+ return (
+ <BarRounded
+ key={b.id}
+ x={x}
+ y={height - b.height - b.y}
+ width={barWidth}
+ height={b.height}
+ className={cn(
+ b.colorClassName ?? "text-blue-700",
+ b.styles?.barClassName,
+ )}
+ fill={b.styles?.barFill || "currentColor"}
+ {...(idx === bars.length - 1
+ ? { top: true, radius: radius }
+ : { radius: 0 })}
+ />
+ );
+ })}
+ </g>
);
})}
+ </motion.g>
</AnimatePresence>
</Group>
);
diff --git a/packages/ui/src/charts/time-series-chart.tsx b/packages/ui/src/charts/time-series-chart.tsx
index b055d7bdd1..b0628c71ec 100644
--- a/packages/ui/src/charts/time-series-chart.tsx
+++ b/packages/ui/src/charts/time-series-chart.tsx
@@ -10,7 +10,7 @@ import {
Datum,
type ChartContext as ChartContextType,
} from "./types";
-import { useTooltip } from "./useTooltip";
+import { useTooltip } from "./use-tooltip";
type TimeSeriesChartProps<T extends Datum> = PropsWithChildren<ChartProps<T>>;
@@ -41,6 +41,7 @@ function TimeSeriesChartInner<T extends Datum>({
tooltipContent = (d) => series[0].valueAccessor(d).toString(),
tooltipClassName = "",
defaultTooltipIndex = null,
+ onHoverDateChange,
margin: marginProp = {
top: 12,
right: 5,
@@ -78,10 +79,14 @@ function TimeSeriesChartInner<T extends Datum>({
}, [data]);
const { minY, maxY } = useMemo(() => {
- const values = series
- .filter(({ isActive }) => isActive !== false)
- .map(({ valueAccessor }) => data.map((d) => valueAccessor(d)))
- .flat()
+ const activeSeries = series.filter(({ isActive }) => isActive !== false);
+ const values = data
+ .flatMap((d) =>
+ type === "bar"
+ ? // Sum values for stacked bars
+ activeSeries.reduce((sum, s) => sum + s.valueAccessor(d), 0)
+ : activeSeries.map((s) => s.valueAccessor(d)),
+ )
.filter((v): v is number => v != null);
return {
@@ -89,7 +94,7 @@ function TimeSeriesChartInner<T extends Datum>({
minY: type === "area" ? Math.min(...values) : Math.min(0, ...values),
maxY: Math.max(...values),
};
- }, [data, series]);
+ }, [data, series, type]);
const { yScale, xScale } = useMemo(() => {
const rangeY = maxY - minY;
@@ -112,7 +117,7 @@ function TimeSeriesChartInner<T extends Datum>({
: scaleBand({
domain: data.map(({ date }) => date),
range: [0, width],
- padding: Math.min(0.75, (width / data.length) * 0.02),
+ padding: 0.15,
align: 0.5,
}),
};
@@ -135,6 +140,7 @@ function TimeSeriesChartInner<T extends Datum>({
tooltipContent,
tooltipClassName,
defaultTooltipIndex,
+ onHoverDateChange,
leftAxisMargin,
setLeftAxisMargin,
};
@@ -142,6 +148,7 @@ function TimeSeriesChartInner<T extends Datum>({
const tooltipContext = useTooltip({
seriesId: series[0].id,
chartContext,
+ onHoverDateChange,
defaultIndex: defaultTooltipIndex ?? undefined,
});
@@ -226,7 +233,11 @@ function TimeSeriesChartInner<T extends Datum>({
key={tooltipData.date.toString()}
left={(tooltipLeft ?? 0) + margin.left}
top={(tooltipTop ?? 0) + margin.top}
- offsetLeft={"bandwidth" in xScale ? xScale.bandwidth() + 8 : 8}
+ offsetLeft={
+ "bandwidth" in xScale
+ ? xScale.bandwidth() * (1 + xScale.padding())
+ : 8
+ }
offsetTop={12}
className="absolute"
unstyled={true}
diff --git a/packages/ui/src/charts/types.ts b/packages/ui/src/charts/types.ts
index 920da50e93..91f53ff838 100644
--- a/packages/ui/src/charts/types.ts
+++ b/packages/ui/src/charts/types.ts
@@ -34,6 +34,11 @@ type ChartOptionalProps<T extends Datum = any> = {
tooltipContent?: (datum: TimeSeriesDatum<T>) => ReactElement<any> | string;
tooltipClassName?: string;
defaultTooltipIndex?: number | null;
+ /**
+ * Called when the hovered x-value (date) changes, or when hover is cleared.
+ * Useful for syncing external UI to the currently hovered datum.
+ */
+ onHoverDateChange?: (date: Date | null) => void;
/**
* Absolute pixel values for margins around the chart area.
@@ -58,7 +63,9 @@ type ChartOptionalProps<T extends Datum = any> = {
export type ChartProps<T extends Datum = any> = ChartRequiredProps<T> &
ChartOptionalProps<T>;
-export type ChartContext<T extends Datum = any> = Required<ChartProps<T>> & {
+export type ChartContext<T extends Datum = any> = Required<
+ Omit<ChartProps<T>, "onHoverDateChange">
+> & {
width: number;
height: number;
startDate: Date;
@@ -71,6 +78,10 @@ export type ChartContext<T extends Datum = any> = Required<ChartProps<T>> & {
maxY: number;
leftAxisMargin?: number;
setLeftAxisMargin: Dispatch<SetStateAction<number | undefined>>;
+ /**
+ * Optional callback invoked when the hovered x-value (date) changes.
+ */
+ onHoverDateChange?: (date: Date | null) => void;
};
export type ChartTooltipContext<T extends Datum = any> = {
diff --git a/packages/ui/src/charts/useTooltip.ts b/packages/ui/src/charts/use-tooltip.ts
similarity index 69%
rename from packages/ui/src/charts/useTooltip.ts
rename to packages/ui/src/charts/use-tooltip.ts
index 3a1a83b141..a11a58aebd 100644
--- a/packages/ui/src/charts/useTooltip.ts
+++ b/packages/ui/src/charts/use-tooltip.ts
@@ -5,7 +5,7 @@ import {
useTooltip as useVisxTooltip,
} from "@visx/tooltip";
import { bisector } from "d3-array";
-import { useCallback, useContext, useEffect, useMemo } from "react";
+import { useCallback, useContext, useEffect, useMemo, useRef } from "react";
import { ChartTooltipSyncContext } from "./tooltip-sync";
import {
ChartContext,
@@ -24,6 +24,7 @@ export type TooltipOptions<T extends Datum> = {
snapToX?: boolean;
snapToY?: boolean;
defaultIndex?: number;
+ onHoverDateChange?: (date: Date | null) => void;
};
export function useTooltip<T extends Datum>({
@@ -33,6 +34,7 @@ export function useTooltip<T extends Datum>({
snapToY = false,
snapToX = true,
defaultIndex,
+ onHoverDateChange,
}: TooltipOptions<T>): ChartTooltipContext {
const { series, data, xScale, yScale, margin } = chartContext;
@@ -67,9 +69,57 @@ export function useTooltip<T extends Datum>({
const visxTooltip = useVisxTooltip<TimeSeriesDatum<T>>();
+ // Throttle tooltip updates to animation frames to avoid excessive React
+ // state updates on every mousemove event.
+ const tooltipFrameRef = useRef<number | null>(null);
+ const pendingTooltipRef = useRef<{
+ tooltipData: TimeSeriesDatum<T>;
+ tooltipLeft: number;
+ tooltipTop: number;
+ } | null>(null);
+
+ const scheduleTooltipUpdate = useCallback(
+ (next: {
+ tooltipData: TimeSeriesDatum<T>;
+ tooltipLeft: number;
+ tooltipTop: number;
+ }) => {
+ pendingTooltipRef.current = next;
+
+ if (tooltipFrameRef.current !== null) return;
+
+ tooltipFrameRef.current = window.requestAnimationFrame(() => {
+ tooltipFrameRef.current = null;
+ const current = pendingTooltipRef.current;
+ if (!current) return;
+ visxTooltip.showTooltip({
+ tooltipData: current.tooltipData,
+ tooltipLeft: current.tooltipLeft ?? 0,
+ tooltipTop: current.tooltipTop,
+ });
+ });
+ },
+ [visxTooltip.showTooltip],
+ );
+
+ useEffect(
+ () => () => {
+ if (tooltipFrameRef.current !== null) {
+ window.cancelAnimationFrame(tooltipFrameRef.current);
+ }
+ },
+ [],
+ );
+
useEffect(() => {
- if (defaultTooltipData) visxTooltip.showTooltip(defaultTooltipData);
- }, [defaultTooltipData]);
+ if (defaultTooltipData) {
+ scheduleTooltipUpdate({
+ tooltipData: defaultTooltipData.tooltipData,
+ tooltipLeft: defaultTooltipData.tooltipLeft ?? 0,
+ tooltipTop: defaultTooltipData.tooltipTop,
+ });
+ }
+ }, [defaultTooltipData, scheduleTooltipUpdate]);
// Sync w/ other charts within the same ChartTooltipSync context
useEffect(() => {
@@ -83,18 +133,20 @@ export function useTooltip<T extends Datum>({
);
if (!d) return;
- visxTooltip.showTooltip({
+ scheduleTooltipUpdate({
tooltipData: d,
- tooltipLeft: xScale(d.date),
+ tooltipLeft: xScale(d.date) ?? 0,
tooltipTop: snapToY
? yScale(series.find((s) => s.id === seriesId)!.valueAccessor(d))
: 0,
});
+ onHoverDateChange?.(d.date);
} else if (
tooltipSyncContext.tooltipDate === null &&
visxTooltip.tooltipData?.date
) {
visxTooltip.hideTooltip();
+ onHoverDateChange?.(null);
}
}, [
tooltipSyncContext.tooltipDate,
@@ -136,15 +188,16 @@ export function useTooltip<T extends Datum>({
? d1
: d0;
}
- visxTooltip.showTooltip({
+ scheduleTooltipUpdate({
tooltipData: d,
- tooltipLeft: snapToX ? xScale(d.date) : x,
+ tooltipLeft: snapToX ? xScale(d.date) ?? 0 : x,
tooltipTop: snapToY
? yScale(series.find((s) => s.id === seriesId)!.valueAccessor(d))
: 0,
});
tooltipSyncContext.setTooltipDate?.(d.date);
+ onHoverDateChange?.(d.date);
},
[
seriesId,
@@ -153,7 +206,7 @@ export function useTooltip<T extends Datum>({
yScale,
series,
defaultTooltipData,
- visxTooltip.showTooltip,
+ scheduleTooltipUpdate,
tooltipSyncContext.setTooltipDate,
],
);
@@ -173,6 +226,7 @@ export function useTooltip<T extends Datum>({
defaultTooltipData
? visxTooltip.showTooltip(defaultTooltipData)
: visxTooltip.hideTooltip();
+ onHoverDateChange?.(null);
},
};
}