Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Returning (#763)

Bill Yangce9f7e092b3b
diff --git a/client/src/api/analytics/endpoints/overview.ts b/client/src/api/analytics/endpoints/overview.ts
index ad028c014..5d8ecd308 100644
--- a/client/src/api/analytics/endpoints/overview.ts
+++ b/client/src/api/analytics/endpoints/overview.ts
@@ -27,6 +27,8 @@ export type GetOverviewBucketedResponse = {
bounce_rate: number;
session_duration: number;
users: number;
+ new_users: number;
+ returning_users: number;
}[];
// Metric response type
@@ -50,14 +52,8 @@ export interface LiveUserCountResponse {
* Fetch overview metrics for a site
* GET /api/overview/:site
*/
-export async function fetchOverview(
- site: string | number,
- params: CommonApiParams
-): Promise<GetOverviewResponse> {
- const response = await authedFetch<{ data: GetOverviewResponse }>(
- `/overview/${site}`,
- toQueryParams(params)
- );
+export async function fetchOverview(site: string | number, params: CommonApiParams): Promise<GetOverviewResponse> {
+ const response = await authedFetch<{ data: GetOverviewResponse }>(`/overview/${site}`, toQueryParams(params));
return response.data;
}
@@ -94,13 +90,7 @@ export async function fetchMetric(
* Fetch live user count
* GET /api/live-user-count/:site
*/
-export async function fetchLiveUserCount(
- site: string | number,
- minutes: number = 5
-): Promise<LiveUserCountResponse> {
- const response = await authedFetch<LiveUserCountResponse>(
- `/live-user-count/${site}`,
- { minutes }
- );
+export async function fetchLiveUserCount(site: string | number, minutes: number = 5): Promise<LiveUserCountResponse> {
+ const response = await authedFetch<LiveUserCountResponse>(`/live-user-count/${site}`, { minutes });
return response;
}
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index 2b7b86d36..815da7ad9 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -1,16 +1,26 @@
"use client";
-import { TimeBucket } from "@rybbit/shared";
import { useNivoTheme } from "@/lib/nivo";
import { StatType, useStore } from "@/lib/store";
-import { LineCustomSvgLayer, LineCustomSvgLayerProps, LineSeries, ResponsiveLine } from "@nivo/line";
+import { ResponsiveLine } from "@nivo/line";
+import { TimeBucket } from "@rybbit/shared";
import { useWindowSize } from "@uidotdev/usehooks";
import { DateTime } from "luxon";
+import { useTheme } from "next-themes";
import { GetOverviewBucketedResponse } from "../../../../../api/analytics/endpoints";
import { APIResponse } from "../../../../../api/types";
import { Time } from "../../../../../components/DateSelector/types";
-import { formatSecondsAsMinutesAndSeconds, formatter } from "../../../../../lib/utils";
-import { userLocale, hour12, formatChartDateTime } from "../../../../../lib/dateTimeUtils";
-import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
+import { hour12, userLocale } from "../../../../../lib/dateTimeUtils";
+import { formatter } from "../../../../../lib/utils";
+import { ChartSliceTooltip, SeriesData } from "./ChartSliceTooltip";
+
+const BUCKET_MINUTES_OFFSET: Partial<Record<TimeBucket, number>> = {
+ hour: 59,
+ fifteen_minutes: 14,
+ ten_minutes: 9,
+ five_minutes: 4,
+};
+
+const getBucketMinutesOffset = (bucket: TimeBucket): number => BUCKET_MINUTES_OFFSET[bucket] ?? 0;
const getMax = (time: Time, bucket: TimeBucket) => {
const now = DateTime.now();
@@ -22,18 +32,7 @@ const getMax = (time: Time, bucket: TimeBucket) => {
} else if (time.mode === "day") {
const dayDate = DateTime.fromISO(time.day)
.endOf("day")
- .minus({
- minutes:
- bucket === "hour"
- ? 59
- : bucket === "fifteen_minutes"
- ? 14
- : bucket === "ten_minutes"
- ? 9
- : bucket === "five_minutes"
- ? 4
- : 0,
- });
+ .minus({ minutes: getBucketMinutesOffset(bucket) });
return now < dayDate ? dayDate.toJSDate() : undefined;
} else if (time.mode === "range") {
if (bucket === "day" || bucket === "week" || bucket === "month" || bucket === "year") {
@@ -41,38 +40,21 @@ const getMax = (time: Time, bucket: TimeBucket) => {
}
const rangeDate = DateTime.fromISO(time.endDate)
.endOf("day")
- .minus({
- minutes:
- bucket === "hour"
- ? 59
- : bucket === "fifteen_minutes"
- ? 14
- : bucket === "ten_minutes"
- ? 9
- : bucket === "five_minutes"
- ? 4
- : 0,
- });
+ .minus({ minutes: getBucketMinutesOffset(bucket) });
return now < rangeDate ? rangeDate.toJSDate() : undefined;
} else if (time.mode === "week") {
- if (bucket === "hour") {
- const endDate = DateTime.fromISO(time.week).endOf("week").minus({
- minutes: 59,
- });
- return now < endDate ? endDate.toJSDate() : undefined;
- }
- if (bucket === "fifteen_minutes") {
- const endDate = DateTime.fromISO(time.week).endOf("week").minus({
- minutes: 14,
- });
- return now < endDate ? endDate.toJSDate() : undefined;
+ if (bucket !== "hour" && bucket !== "fifteen_minutes") {
+ return undefined;
}
- return undefined;
+ const endDate = DateTime.fromISO(time.week)
+ .endOf("week")
+ .minus({ minutes: getBucketMinutesOffset(bucket) });
+ return now < endDate ? endDate.toJSDate() : undefined;
} else if (time.mode === "month") {
if (bucket === "hour") {
- const endDate = DateTime.fromISO(time.month).endOf("month").minus({
- minutes: 59,
- });
+ const endDate = DateTime.fromISO(time.month)
+ .endOf("month")
+ .minus({ minutes: getBucketMinutesOffset(bucket) });
return now < endDate ? endDate.toJSDate() : undefined;
}
const monthDate = DateTime.fromISO(time.month).endOf("month");
@@ -106,58 +88,131 @@ const getMin = (time: Time, bucket: TimeBucket) => {
return undefined;
};
-const formatTooltipValue = (value: number, selectedStat: StatType): string => {
- if (selectedStat === "bounce_rate") {
- return `${value.toFixed(1)}%`;
- }
- if (selectedStat === "session_duration") {
- return formatSecondsAsMinutesAndSeconds(value);
- }
- return value.toLocaleString();
+const Y_TICK_VALUES = 5;
+
+const SERIES_LABELS: Record<StatType | "new_users" | "returning_users", string> = {
+ pageviews: "Pageviews",
+ sessions: "Sessions",
+ pages_per_session: "Pages per Session",
+ bounce_rate: "Bounce Rate",
+ session_duration: "Session Duration",
+ users: "Users",
+ new_users: "New Users",
+ returning_users: "Returning Users",
};
-const Y_TICK_VALUES = 5;
+type SeriesConfig = {
+ id: string;
+ dataKey: keyof GetOverviewBucketedResponse[number];
+ label: string;
+ color: string;
+};
-export function Chart({
+const createStackedLines =
+ (displayDashed: boolean) =>
+ ({ series, lineGenerator, xScale, yScale }: any) => {
+ return series.map(({ id, data, color }: any) => {
+ const usableData = displayDashed && data.length >= 2 ? data.slice(0, -1) : data;
+ const coords = usableData.map((d: any) => {
+ const stackedY = d.data.yStacked ?? d.data.y;
+ return { x: xScale(d.data.x), y: yScale(stackedY) };
+ });
+ const path = lineGenerator(coords);
+ if (!path) return null;
+ return <path key={`${id}-solid`} d={path} fill="none" stroke={color} style={{ strokeWidth: 2 }} />;
+ });
+ };
+
+const createDashedOverlay =
+ (displayDashed: boolean) =>
+ ({ series, lineGenerator, xScale, yScale }: any) => {
+ return series.map(({ id, data, color }: any) => {
+ if (!displayDashed || data.length < 2) return null;
+ const lastTwo = data.slice(-2);
+ const coords = lastTwo.map((d: any) => {
+ const stackedY = d.data.yStacked ?? d.data.y;
+ return { x: xScale(d.data.x), y: yScale(stackedY) };
+ });
+ const path = lineGenerator(coords);
+ if (!path) return null;
+ return (
+ <path
+ key={`${id}-dashed`}
+ d={path}
+ fill="none"
+ stroke={color}
+ style={{ strokeDasharray: "3, 6", strokeWidth: 3 }}
+ />
+ );
+ });
+ };
+
+const useChartData = ({
data,
previousData,
- max,
}: {
data: APIResponse<GetOverviewBucketedResponse> | undefined;
previousData: APIResponse<GetOverviewBucketedResponse> | undefined;
- max: number;
-}) {
- const { time, bucket, selectedStat } = useStore();
- const { width } = useWindowSize();
- const nivoTheme = useNivoTheme();
+}) => {
+ const { time, bucket, selectedStat, showUsersSplit } = useStore();
- const maxTicks = Math.round((width ?? Infinity) / 75);
+ const showUserBreakdown = selectedStat === "users" && showUsersSplit;
// When the current period has more datapoints than the previous period,
// we need to shift the previous datapoints to the right by the difference in length
const lengthDiff = Math.max((data?.data?.length ?? 0) - (previousData?.data?.length ?? 0), 0);
- const formattedData =
- data?.data
- ?.map((e, i) => {
- // Parse timestamp properly
- const timestamp = DateTime.fromSQL(e.time).toUTC();
+ const seriesConfig: SeriesConfig[] = showUserBreakdown
+ ? [
+ {
+ id: "returning_users",
+ dataKey: "returning_users",
+ label: SERIES_LABELS["returning_users"],
+ color: "hsl(var(--indigo-400))",
+ },
+ {
+ id: "new_users",
+ dataKey: "new_users",
+ label: SERIES_LABELS["new_users"],
+ color: "hsl(var(--dataviz))",
+ },
+ ]
+ : [
+ {
+ id: selectedStat,
+ dataKey: selectedStat,
+ label: SERIES_LABELS[selectedStat],
+ color: "hsl(var(--dataviz))",
+ },
+ ];
+
+ const seriesData = seriesConfig.map(config => {
+ const points =
+ data?.data
+ ?.map((e, i) => {
+ // Parse timestamp properly
+ const timestamp = DateTime.fromSQL(e.time).toUTC();
+
+ // filter out dates from the future
+ if (timestamp > DateTime.now()) {
+ return null;
+ }
- // filter out dates from the future
- if (timestamp > DateTime.now()) {
- return null;
- }
+ const previousEntry = i >= lengthDiff ? previousData?.data?.[i - lengthDiff] : undefined;
+ const previousTimestamp = previousEntry ? DateTime.fromSQL(previousEntry.time).toUTC() : undefined;
- return {
- x: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"),
- y: e[selectedStat],
- previousY: i >= lengthDiff && previousData?.data?.[i - lengthDiff][selectedStat],
- currentTime: timestamp,
- previousTime:
- i >= lengthDiff ? DateTime.fromSQL(previousData?.data?.[i - lengthDiff]?.time ?? "").toUTC() : undefined,
- };
- })
- .filter(e => e !== null) || [];
+ return {
+ x: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"),
+ y: (e as any)[config.dataKey] ?? 0,
+ previousY: previousEntry ? (previousEntry as any)[config.dataKey] : undefined,
+ currentTime: timestamp,
+ previousTime: previousTimestamp,
+ };
+ })
+ .filter(e => e !== null) ?? [];
+
+ return { ...config, points };
+ });
const currentDayStr = DateTime.now().toISODate();
const currentMonthStr = DateTime.now().toFormat("yyyy-MM-01");
@@ -169,79 +224,75 @@ export function Chart({
(time.mode === "range" && time.endDate !== currentDayStr) || // do not display in range mode if end date is not current day
(time.mode === "day" && (bucket === "minute" || bucket === "five_minutes")) || // do not display in day mode if bucket is minute or five_minutes
(time.mode === "past-minutes" && (bucket === "minute" || bucket === "five_minutes")); // do not display in 24-hour mode if bucket is minute or five_minutes
- const displayDashed = formattedData.length >= 2 && !shouldNotDisplay;
- const baseGradient = {
- offset: 0,
- color: "hsl(var(--dataviz))",
- };
+ const displayDashed = (seriesData[0]?.points.length ?? 0) >= 2 && !shouldNotDisplay;
- const croppedData = formattedData.slice(0, -1);
+ const chartPropsData: { id: string; data: any[] }[] = [];
+ const chartPropsDefs: any[] = [];
+ const chartPropsFill: any[] = [];
+ const colorMap: Record<string, string> = {};
- // add original data and styles to chart
- const chartPropsData = [
- {
- id: "croppedData",
- data: displayDashed ? croppedData : formattedData,
- },
- ];
- const chartPropsDefs = [
- {
- id: "croppedData",
- type: "linearGradient",
- colors: [
- { ...baseGradient, opacity: 1 },
- { offset: 100, color: baseGradient.color, opacity: 0 },
- ],
- },
- ];
- const chartPropsFill = [
- {
- id: "croppedData",
- match: {
- id: "croppedData",
- },
- },
- ];
+ seriesData.forEach(series => {
+ const baseId = `${series.id}-base`;
+ const baseData = series.points;
- // add dashed data and styles to chart
- if (displayDashed) {
chartPropsData.push({
- id: "dashedData",
- data: [croppedData.at(-1)!, formattedData.at(-1)!],
+ id: baseId,
+ data: baseData,
});
+ colorMap[baseId] = series.color;
+
chartPropsDefs.push({
- id: "dashedData",
+ id: `${baseId}-gradient`,
type: "linearGradient",
colors: [
- { ...baseGradient, opacity: 0.35 },
- { offset: 100, color: baseGradient.color, opacity: 0 },
+ { offset: 0, color: series.color, opacity: showUserBreakdown ? 0.5 : 0.7 },
+ { offset: 100, color: series.color, opacity: 0 },
],
});
chartPropsFill.push({
- id: "dashedData",
+ id: `${baseId}-gradient`,
match: {
- id: "dashedData",
+ id: baseId,
},
});
- }
-
- const DashedLine: LineCustomSvgLayer<LineSeries> = ({
- series,
- lineGenerator,
- xScale,
- yScale,
- }: LineCustomSvgLayerProps<LineSeries>) => {
- return series.map(({ id, data, color }) => (
- <path
- key={id}
- d={lineGenerator(data.map(d => ({ x: xScale(d.data.x), y: yScale(d.data.y) })))!}
- fill="none"
- stroke={color}
- style={id === "dashedData" ? { strokeDasharray: "3, 6", strokeWidth: 3 } : { strokeWidth: 2 }}
- />
- ));
+ });
+ return {
+ seriesData,
+ displayDashed,
+ chartPropsData,
+ chartPropsDefs,
+ chartPropsFill,
+ colorMap,
+ seriesConfig,
};
+};
+
+export function Chart({
+ data,
+ previousData,
+ max,
+}: {
+ data: APIResponse<GetOverviewBucketedResponse> | undefined;
+ previousData: APIResponse<GetOverviewBucketedResponse> | undefined;
+ max: number;
+}) {
+ const { time, bucket, selectedStat, showUsersSplit } = useStore();
+ const { width } = useWindowSize();
+ const maxTicks = Math.round((width ?? Infinity) / 75);
+ const nivoTheme = useNivoTheme();
+ const { resolvedTheme } = useTheme();
+
+ const showUserBreakdown = selectedStat === "users" && showUsersSplit;
+
+ const { displayDashed, chartPropsData, chartPropsDefs, chartPropsFill, colorMap, seriesConfig, seriesData } =
+ useChartData({
+ data,
+ previousData,
+ });
+
+ const StackedLines = createStackedLines(displayDashed);
+ const DashedOverlay = createDashedOverlay(displayDashed);
return (
<ResponsiveLine
@@ -259,7 +310,7 @@ export function Chart({
yScale={{
type: "linear",
min: 0,
- stacked: false,
+ stacked: showUserBreakdown,
reverse: false,
max: Math.max(max, 1),
}}
@@ -307,65 +358,32 @@ export function Chart({
useMesh={true}
animate={false}
enableSlices={"x"}
- colors={["hsl(var(--dataviz))"]}
+ colors={({ id }) => colorMap[id as string] ?? "hsl(var(--dataviz))"}
enableArea={true}
areaBaselineValue={0}
areaOpacity={0.3}
defs={chartPropsDefs}
fill={chartPropsFill}
- sliceTooltip={({ slice }: any) => {
- const currentY = Number(slice.points[0].data.yFormatted);
- const previousY = Number(slice.points[0].data.previousY) || 0;
- const currentTime = slice.points[0].data.currentTime as DateTime;
- const previousTime = slice.points[0].data.previousTime as DateTime;
-
- const diff = currentY - previousY;
- const diffPercentage = previousY ? (diff / previousY) * 100 : null;
-
- return (
- <ChartTooltip>
- {diffPercentage !== null && (
- <div
- className="text-base font-medium px-2 pt-1.5 pb-1"
- style={{
- color: diffPercentage > 0 ? "hsl(var(--green-400))" : "hsl(var(--red-400))",
- }}
- >
- {diffPercentage > 0 ? "+" : ""}
- {diffPercentage.toFixed(2)}%
- </div>
- )}
- <div className="w-full h-px bg-neutral-100 dark:bg-neutral-750"></div>
-
- <div className="m-2">
- <div className="flex justify-between text-sm w-40">
- <div className="flex items-center gap-2">
- <div className="w-1 h-3 rounded-[3px] bg-dataviz" />
- {formatChartDateTime(currentTime, bucket)}
- </div>
- <div>{formatTooltipValue(currentY, selectedStat)}</div>
- </div>
- {previousTime && (
- <div className="flex justify-between text-sm text-muted-foreground">
- <div className="flex items-center gap-2">
- <div className="w-1 h-3 rounded-[3px] bg-neutral-200 dark:bg-neutral-750" />
- {formatChartDateTime(previousTime, bucket)}
- </div>
- <div>{formatTooltipValue(previousY, selectedStat)}</div>
- </div>
- )}
- </div>
- </ChartTooltip>
- );
- }}
+ sliceTooltip={({ slice }: any) => (
+ <ChartSliceTooltip
+ slice={slice}
+ showUserBreakdown={showUserBreakdown}
+ colorMap={colorMap}
+ seriesConfig={seriesConfig}
+ seriesData={seriesData as SeriesData[]}
+ bucket={bucket}
+ selectedStat={selectedStat}
+ resolvedTheme={resolvedTheme}
+ />
+ )}
layers={[
"grid",
"markers",
"axes",
"areas",
"crosshair",
- displayDashed ? DashedLine : "lines",
- // "lines",
+ StackedLines,
+ ...(displayDashed ? [DashedOverlay] : []),
"slices",
"points",
"mesh",
diff --git a/client/src/app/[site]/main/components/MainSection/ChartSliceTooltip.tsx b/client/src/app/[site]/main/components/MainSection/ChartSliceTooltip.tsx
new file mode 100644
index 000000000..22ab8e16e
--- /dev/null
+++ b/client/src/app/[site]/main/components/MainSection/ChartSliceTooltip.tsx
@@ -0,0 +1,200 @@
+"use client";
+import { TimeBucket } from "@rybbit/shared";
+import { DateTime } from "luxon";
+import { StatType } from "@/lib/store";
+import { formatSecondsAsMinutesAndSeconds } from "../../../../../lib/utils";
+import { formatChartDateTime } from "../../../../../lib/dateTimeUtils";
+import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
+
+const formatTooltipValue = (value: number, selectedStat: StatType): string => {
+ if (selectedStat === "bounce_rate") {
+ return `${value.toFixed(1)}%`;
+ }
+ if (selectedStat === "session_duration") {
+ return formatSecondsAsMinutesAndSeconds(value);
+ }
+ return value.toLocaleString();
+};
+
+export type SeriesConfig = {
+ id: string;
+ dataKey: string;
+ label: string;
+ color: string;
+};
+
+export type SeriesDataPoint = {
+ x: string;
+ y: number;
+ previousY: number | undefined;
+ currentTime: DateTime;
+ previousTime: DateTime | undefined;
+};
+
+export type SeriesData = SeriesConfig & {
+ points: SeriesDataPoint[];
+};
+
+type ChartSliceTooltipProps = {
+ slice: any;
+ showUserBreakdown: boolean;
+ colorMap: Record<string, string>;
+ seriesConfig: SeriesConfig[];
+ seriesData: SeriesData[];
+ bucket: TimeBucket;
+ selectedStat: StatType;
+ resolvedTheme: string | undefined;
+};
+
+export function ChartSliceTooltip({
+ slice,
+ showUserBreakdown,
+ colorMap,
+ seriesConfig,
+ seriesData,
+ bucket,
+ selectedStat,
+ resolvedTheme,
+}: ChartSliceTooltipProps) {
+ // Normalize dashed series ids back to their base ids so we always find a point
+ const normalizedPoints = slice.points.map((point: any) => ({
+ ...point,
+ originalSerieId: String(point.serieId),
+ serieId: String(point.serieId).replace(/-dashed$/, "-base"),
+ }));
+
+ if (!normalizedPoints.length) return null;
+
+ // Single-series tooltip
+ if (!showUserBreakdown) {
+ const currentTime = normalizedPoints[0].data.currentTime as DateTime;
+ const previousTime = normalizedPoints[0].data.previousTime as DateTime;
+ const currentY = Number(normalizedPoints[0].data.yFormatted ?? normalizedPoints[0].data.y);
+ const previousY = Number(normalizedPoints[0].data.previousY) || 0;
+ const diff = currentY - previousY;
+ const diffPercentage = previousY ? (diff / previousY) * 100 : null;
+ const primaryColor = colorMap[`${seriesConfig[0].id}-base`] ?? "hsl(var(--dataviz))";
+
+ return (
+ <ChartTooltip>
+ {diffPercentage !== null && (
+ <div
+ className="text-base font-medium px-2 pt-1.5 pb-1"
+ style={{
+ color: diffPercentage > 0 ? "hsl(var(--green-400))" : "hsl(var(--red-400))",
+ }}
+ >
+ {diffPercentage > 0 ? "+" : ""}
+ {diffPercentage.toFixed(2)}%
+ </div>
+ )}
+ <div className="w-full h-[1px] bg-neutral-100 dark:bg-neutral-750"></div>
+
+ <div className="m-2">
+ <div className="flex justify-between text-sm w-40">
+ <div className="flex items-center gap-2">
+ <div className="w-1 h-3 rounded-[3px]" style={{ backgroundColor: primaryColor }} />
+ {formatChartDateTime(currentTime, bucket)}
+ </div>
+ <div>{formatTooltipValue(currentY, selectedStat)}</div>
+ </div>
+ {previousTime && (
+ <div className="flex justify-between text-sm text-muted-foreground">
+ <div className="flex items-center gap-2">
+ <div className="w-1 h-3 rounded-[3px] bg-neutral-200 dark:bg-neutral-750" />
+ {formatChartDateTime(previousTime, bucket)}
+ </div>
+ <div>{formatTooltipValue(previousY, selectedStat)}</div>
+ </div>
+ )}
+ </div>
+ </ChartTooltip>
+ );
+ }
+
+ // Two-series tooltip (new vs returning) using the slice's timestamp to fetch both series points
+ const targetTime = (normalizedPoints[0].data.currentTime as DateTime | undefined)?.toMillis();
+
+ const previousColorFor = (seriesId: string) => {
+ if (seriesId === "new_users") {
+ return "hsl(var(--dataviz) / 0.28)";
+ }
+ if (seriesId === "returning_users") {
+ return resolvedTheme === "dark" ? "hsl(var(--accent-800) / 0.35)" : "hsl(var(--accent-200) / 0.38)";
+ }
+ return resolvedTheme === "dark" ? "hsl(var(--neutral-700))" : "hsl(var(--neutral-200))";
+ };
+
+ const rows = seriesConfig
+ .map(series => {
+ const match = seriesData
+ .find(s => s.id === series.id)
+ ?.points.find(p => {
+ const t = (p.currentTime as DateTime | undefined)?.toMillis();
+ return targetTime !== undefined && t === targetTime;
+ });
+
+ if (!match) return null;
+
+ const currentY = Number(match.y ?? 0);
+ const previousY = Number(match.previousY ?? 0);
+ const diff = currentY - previousY;
+ const diffPercentage = previousY ? (diff / previousY) * 100 : null;
+
+ return {
+ id: series.id,
+ color: series.color,
+ label: series.label,
+ currentTime: match.currentTime as DateTime | undefined,
+ previousTime: match.previousTime as DateTime | undefined,
+ currentY,
+ previousY,
+ diffPercentage,
+ previousColor: previousColorFor(series.id),
+ };
+ })
+ .filter(Boolean);
+
+ return (
+ <ChartTooltip>
+ {rows.toReversed().map((row: any, idx: number) => (
+ <div key={row.id} className={idx < rows.length - 1 ? "pb-0.5 mb-1.5" : ""}>
+ <div className={`px-2 text-xs font-semibold text-muted-foreground ${idx === 0 ? "pt-2" : ""}`}>
+ {row.label}
+ </div>
+ {row.diffPercentage !== null && (
+ <div
+ className="text-base font-medium px-2 pt-1.5 pb-1"
+ style={{
+ color: row.diffPercentage > 0 ? "hsl(var(--green-400))" : "hsl(var(--red-400))",
+ }}
+ >
+ {row.diffPercentage > 0 ? "+" : ""}
+ {row.diffPercentage.toFixed(2)}%
+ </div>
+ )}
+ {row.diffPercentage !== null && <div className="w-full h-[1px] bg-neutral-100 dark:bg-neutral-750" />}
+
+ <div className="m-2">
+ <div className="flex justify-between text-sm w-48">
+ <div className="flex items-center gap-2">
+ <div className="w-1 h-3 rounded-[3px]" style={{ backgroundColor: row.color }} />
+ {row.currentTime ? formatChartDateTime(row.currentTime, bucket) : ""}
+ </div>
+ <div>{formatTooltipValue(row.currentY, selectedStat)}</div>
+ </div>
+ {row.previousTime && (
+ <div className="flex justify-between text-sm text-muted-foreground">
+ <div className="flex items-center gap-2">
+ <div className="w-1 h-3 rounded-[3px]" style={{ backgroundColor: row.previousColor }} />
+ {formatChartDateTime(row.previousTime, bucket)}
+ </div>
+ <div>{formatTooltipValue(row.previousY, selectedStat)}</div>
+ </div>
+ )}
+ </div>
+ </div>
+ ))}
+ </ChartTooltip>
+ );
+}
diff --git a/client/src/app/[site]/main/components/MainSection/MainSection.tsx b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
index b95054557..b395f937c 100644
--- a/client/src/app/[site]/main/components/MainSection/MainSection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
@@ -1,5 +1,6 @@
"use client";
import { Card, CardContent, CardLoader } from "@/components/ui/card";
+import { User, Users } from "lucide-react";
import { Tilt_Warp } from "next/font/google";
import Link from "next/link";
import { useGetOverview } from "../../../../../api/analytics/hooks/useGetOverview";
@@ -13,6 +14,8 @@ import { ExportButton } from "../ExportButton";
import { Chart } from "./Chart";
import { Overview } from "./Overview";
import { PreviousChart } from "./PreviousChart";
+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";
+import { Button } from "../../../../../components/ui/button";
const SELECTED_STAT_MAP = {
pageviews: "Pageviews",
@@ -31,7 +34,8 @@ const tilt_wrap = Tilt_Warp({
export function MainSection() {
const session = authClient.useSession();
- const { selectedStat, time, site, bucket } = useStore();
+ const { selectedStat, time, site, bucket, showUsersSplit, setShowUsersSplit } = useStore();
+ const showUserBreakdown = selectedStat === "users" && showUsersSplit;
// Current period data
const { data, isFetching, error } = useGetOverviewBucketed({
@@ -56,10 +60,18 @@ export function MainSection() {
periodTime: "previous",
});
- const maxOfDataAndPreviousData = Math.max(
- Math.max(...(data?.data?.map((d: any) => d[selectedStat]) ?? [])),
- Math.max(...(previousData?.data?.map((d: any) => d[selectedStat]) ?? []))
- );
+ const activeKeys = showUserBreakdown ? (["new_users", "returning_users"] as const) : ([selectedStat] as const);
+
+ const getMaxValue = (dataset?: { data?: Record<string, number | string>[] }) =>
+ Math.max(
+ ...(dataset?.data?.map(d =>
+ showUserBreakdown
+ ? Number(d?.["new_users"] ?? 0) + Number(d?.["returning_users"] ?? 0)
+ : Math.max(...activeKeys.map(key => Number(d?.[key] ?? 0)))
+ ) ?? [0])
+ );
+
+ const maxOfDataAndPreviousData = Math.max(getMaxValue(data), getMaxValue(previousData));
return (
<>
@@ -69,25 +81,44 @@ export function MainSection() {
</CardContent>
{(isOverviewFetching || isOverviewFetchingPrevious) && <CardLoader />}
</Card>
- <Card>
+ <Card className="overflow-visible">
{(isFetching || isPreviousFetching) && <CardLoader />}
<CardContent className="p-2 md:p-4 py-3 w-full">
- <div className="flex items-center justify-between px-2 md:px-0">
- <div className="flex items-center space-x-4">
- <Link
- href={session.data ? "/" : "https://rybbit.com"}
- className={cn("text-lg font-semibold flex items-center gap-1.5 opacity-75", tilt_wrap.className)}
- >
- <RybbitLogo width={20} height={20} />
- rybbit.com
- </Link>
+ <div className="flex gap-2 justify-between items-center px-2 md:px-0 relative">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center space-x-4">
+ <Link
+ href={session.data ? "/" : "https://rybbit.com"}
+ className={cn("text-lg font-semibold flex items-center gap-1.5 opacity-75", tilt_wrap.className)}
+ >
+ <RybbitLogo width={20} height={20} />
+ rybbit.com
+ </Link>
+ </div>
</div>
<span className="text-sm text-neutral-700 dark:text-neutral-200">{SELECTED_STAT_MAP[selectedStat]}</span>
- <div className="flex items-center gap-2">
+ <div className="flex items-center">
+ {selectedStat === "users" && (
+ <div className="flex items-center text-xs text-muted-foreground">
+ <Tooltip>
+ <TooltipTrigger>
+ <Button variant="ghost" size="smIcon" onClick={() => setShowUsersSplit(!showUsersSplit)}>
+ {showUsersSplit ? <Users /> : <User />}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{showUsersSplit ? "Hide new vs returning users" : "Show new vs returning users"}</p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ )}
<ExportButton />
- <BucketSelection />
+ <div className="pl-1">
+ <BucketSelection />
+ </div>
</div>
</div>
+
<div className="h-[200px] md:h-[290px] relative">
<div className="absolute top-0 left-0 w-full h-full">
<PreviousChart data={previousData} max={maxOfDataAndPreviousData} />
diff --git a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
index 93e45df1a..adbe5d87b 100644
--- a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
@@ -43,20 +43,52 @@ export function PreviousChart({
data: APIResponse<GetOverviewBucketedResponse> | undefined;
max: number;
}) {
- const { previousTime: time, selectedStat, bucket } = useStore();
+ const { previousTime: time, selectedStat, bucket, showUsersSplit } = useStore();
const { resolvedTheme } = useTheme();
const nivoTheme = useNivoTheme();
- const size = (data?.data.length ?? 0 / 2) + 1;
- const formattedData = data?.data
- ?.map(e => {
- const timestamp = DateTime.fromSQL(e.time).toUTC();
- return {
- x: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"),
- y: e[selectedStat],
- };
- })
- .slice(0, size);
+ const showUserBreakdown = selectedStat === "users" && showUsersSplit;
+ const previousColors = showUserBreakdown
+ ? resolvedTheme === "dark"
+ ? ["hsl(var(--neutral-700) / 0.5)", "hsl(var(--neutral-700) / 0.5)"]
+ : ["hsl(var(--neutral-100) / 0.5)", "hsl(var(--neutral-100) / 0.5)"]
+ : resolvedTheme === "dark"
+ ? ["hsl(var(--neutral-700))"]
+ : ["hsl(var(--neutral-100))"];
+
+ const seriesConfig: { id: string; dataKey: keyof GetOverviewBucketedResponse[number]; color: string }[] =
+ showUserBreakdown
+ ? [
+ { id: "returning_users", dataKey: "returning_users", color: previousColors[1] },
+ { id: "new_users", dataKey: "new_users", color: previousColors[0] },
+ ]
+ : [{ id: selectedStat, dataKey: selectedStat, color: previousColors[0] }];
+
+ const chartData = seriesConfig.map(series => {
+ const points = data?.data
+ ?.map(e => {
+ const timestamp = DateTime.fromSQL(e.time).toUTC();
+ if (timestamp > DateTime.now()) {
+ return null;
+ }
+
+ return {
+ x: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"),
+ y: (e as any)[series.dataKey] ?? 0,
+ };
+ })
+ ?.filter(point => point !== null);
+
+ return {
+ id: series.id,
+ data: points ?? [],
+ };
+ });
+
+ const colorMap = seriesConfig.reduce<Record<string, string>>((acc, series) => {
+ acc[series.id] = series.color;
+ return acc;
+ }, {});
const min = getMin(time, bucket);
const maxPastMinutes =
@@ -66,12 +98,7 @@ export function PreviousChart({
return (
<ResponsiveLine
- data={[
- {
- id: "1",
- data: formattedData ?? [],
- },
- ]}
+ data={chartData}
theme={nivoTheme}
margin={{ top: 10, right: 15, bottom: 30, left: 40 }}
xScale={{
@@ -85,7 +112,7 @@ export function PreviousChart({
yScale={{
type: "linear",
min: 0,
- stacked: false,
+ stacked: showUserBreakdown,
reverse: false,
max: Math.max(max, 1),
}}
@@ -128,7 +155,9 @@ export function PreviousChart({
animate={false}
// motionConfig="stiff"
enableSlices={"x"}
- colors={[resolvedTheme === "dark" ? "hsl(var(--neutral-700))" : "hsl(var(--neutral-100))"]}
+ colors={({ id }) =>
+ colorMap[id as string] ?? (resolvedTheme === "dark" ? "hsl(var(--neutral-700))" : "hsl(var(--neutral-100))")
+ }
/>
);
}
diff --git a/client/src/components/ui/card.tsx b/client/src/components/ui/card.tsx
index 41119548a..4f449cebb 100644
--- a/client/src/components/ui/card.tsx
+++ b/client/src/components/ui/card.tsx
@@ -25,7 +25,7 @@ const CardLoader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDiv
const loaderColor = theme === "dark" ? "hsl(var(--neutral-400))" : "hsl(var(--neutral-200))";
return (
- <div className="mt-[-15px] absolute top-0 left-0 w-full">
+ <div className="mt-[-15px] absolute top-0 left-0 w-full overflow-hidden pointer-events-none">
<Zoomies size={1400} stroke="3" bg-opacity="0.1" speed="1.4" color={loaderColor} />
</div>
);
diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts
index 74e2f94fe..98b396f07 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -17,6 +17,8 @@ type Store = {
setBucket: (bucket: TimeBucket) => void;
selectedStat: StatType;
setSelectedStat: (stat: StatType) => void;
+ showUsersSplit: boolean;
+ setShowUsersSplit: (split: boolean) => void;
filters: Filter[];
setFilters: (filters: Filter[]) => void;
};
@@ -54,6 +56,7 @@ export const useStore = create<Store>(set => ({
},
bucket: hasBucketInUrl ? state.bucket : "hour",
selectedStat: hasStatInUrl ? state.selectedStat : "users",
+ showUsersSplit: false,
}));
},
privateKey: null,
@@ -143,16 +146,19 @@ export const useStore = create<Store>(set => ({
setBucket: bucket => set({ bucket }),
selectedStat: "users",
setSelectedStat: stat => set({ selectedStat: stat }),
+ showUsersSplit: false,
+ setShowUsersSplit: split => set({ showUsersSplit: split }),
filters: [],
setFilters: filters => set({ filters }),
}));
export const resetStore = () => {
- const { setSite, setTime, setBucket, setSelectedStat, setFilters } = useStore.getState();
+ const { setSite, setTime, setBucket, setSelectedStat, setFilters, setShowUsersSplit } = useStore.getState();
setSite("");
setTime({ mode: "day", day: DateTime.now().toISODate(), wellKnown: "today" });
setBucket("hour");
setSelectedStat("users");
+ setShowUsersSplit(false);
setFilters([]);
};
diff --git a/server/src/api/analytics/getOverviewBucketed.ts b/server/src/api/analytics/getOverviewBucketed.ts
index 1558a1bae..f4313572d 100644
--- a/server/src/api/analytics/getOverviewBucketed.ts
+++ b/server/src/api/analytics/getOverviewBucketed.ts
@@ -113,6 +113,29 @@ SessionsWithPageviews AS (
asp.total_pageviews_in_session
FROM FilteredSessions fs
LEFT JOIN AllSessionPageviews asp ON fs.session_id = asp.session_id
+),
+-- Determine the first visit bucket per user (site-wide, no filters)
+UserFirstVisits AS (
+ SELECT
+ user_id,
+ toDateTime(${TimeBucketToFn[bucket]}(toTimeZone(min(timestamp), ${SqlString.escape(time_zone)}))) AS first_visit_bucket
+ FROM events
+ WHERE site_id = {siteId:Int32}
+ GROUP BY user_id
+),
+-- Attach first visit info to filtered events for new vs returning splits
+EventsWithFirstVisit AS (
+ SELECT
+ toDateTime(${TimeBucketToFn[bucket]}(toTimeZone(timestamp, ${SqlString.escape(time_zone)}))) AS bucket_time,
+ type,
+ user_id,
+ first_visit_bucket
+ FROM events
+ LEFT JOIN UserFirstVisits USING (user_id)
+ WHERE
+ site_id = {siteId:Int32}
+ ${filterStatement}
+ ${getTimeStatement(params)}
)
SELECT
session_stats.time AS time,
@@ -121,7 +144,9 @@ SELECT
session_stats.bounce_rate * 100 AS bounce_rate,
session_stats.session_duration,
page_stats.pageviews,
- page_stats.users
+ page_stats.users,
+ page_stats.new_users,
+ page_stats.returning_users
FROM
(
SELECT
@@ -136,14 +161,12 @@ FROM
FULL JOIN
(
SELECT
- toDateTime(${TimeBucketToFn[bucket]}(toTimeZone(timestamp, ${SqlString.escape(time_zone)}))) AS time,
+ bucket_time AS time,
countIf(type = 'pageview') AS pageviews,
- COUNT(DISTINCT user_id) AS users
- FROM events
- WHERE
- site_id = {siteId:Int32}
- ${filterStatement}
- ${getTimeStatement(params)}
+ uniqExact(user_id) AS users,
+ uniqExactIf(user_id, first_visit_bucket = bucket_time) AS new_users,
+ uniqExactIf(user_id, first_visit_bucket < bucket_time) AS returning_users
+ FROM EventsWithFirstVisit
GROUP BY time ORDER BY time ${isAllTime ? "" : getTimeStatementFill(params, bucket)}
) AS page_stats
USING time
@@ -152,7 +175,17 @@ ORDER BY time`;
return query;
};
-type getOverviewBucketed = { time: string; pageviews: number }[];
+type getOverviewBucketed = {
+ time: string;
+ pageviews: number;
+ sessions: number;
+ pages_per_session: number;
+ bounce_rate: number;
+ session_duration: number;
+ users: number;
+ new_users: number;
+ returning_users: number;
+}[];
export async function getOverviewBucketed(
req: FastifyRequest<{