Skip to content

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

Add "New vs Returning Users" toggle and chart breakdown to overview

Chris Rimmer41d71e2679f7
diff --git a/client/src/api/analytics/useGetOverviewBucketed.ts b/client/src/api/analytics/useGetOverviewBucketed.ts
index 3952114b7..c014791a9 100644
--- a/client/src/api/analytics/useGetOverviewBucketed.ts
+++ b/client/src/api/analytics/useGetOverviewBucketed.ts
@@ -14,6 +14,8 @@ export type GetOverviewBucketedResponse = {
bounce_rate: number;
session_duration: number;
users: number;
+ new_users: number;
+ returning_users: number;
}[];
export function useGetOverviewBucketed({
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index 7bfedf6c3..6482c9d44 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -5,6 +5,7 @@ import { StatType, useStore } from "@/lib/store";
import { LineCustomSvgLayer, LineCustomSvgLayerProps, LineSeries, ResponsiveLine } from "@nivo/line";
import { useWindowSize } from "@uidotdev/usehooks";
import { DateTime } from "luxon";
+import { useTheme } from "next-themes";
import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGetOverviewBucketed";
import { APIResponse } from "../../../../../api/types";
import { Time } from "../../../../../components/DateSelector/types";
@@ -118,6 +119,24 @@ const formatTooltipValue = (value: number, selectedStat: StatType): string => {
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",
+};
+
+type SeriesConfig = {
+ id: string;
+ dataKey: keyof GetOverviewBucketedResponse[number];
+ label: string;
+ color: string;
+};
+
export function Chart({
data,
previousData,
@@ -127,9 +146,36 @@ export function Chart({
previousData: APIResponse<GetOverviewBucketedResponse> | undefined;
max: number;
}) {
- const { time, bucket, selectedStat } = useStore();
+ const { time, bucket, selectedStat, showUsersSplit } = useStore();
const { width } = useWindowSize();
const nivoTheme = useNivoTheme();
+ const { resolvedTheme } = useTheme();
+
+ const showUserBreakdown = selectedStat === "users" && showUsersSplit;
+
+ const seriesConfig: SeriesConfig[] = showUserBreakdown
+ ? [
+ {
+ id: "new_users",
+ dataKey: "new_users",
+ label: SERIES_LABELS["new_users"],
+ color: "hsl(var(--dataviz))",
+ },
+ {
+ id: "returning_users",
+ dataKey: "returning_users",
+ label: SERIES_LABELS["returning_users"],
+ color: "hsl(var(--pink-400))",
+ },
+ ]
+ : [
+ {
+ id: selectedStat,
+ dataKey: selectedStat,
+ label: SERIES_LABELS[selectedStat],
+ color: "hsl(var(--dataviz))",
+ },
+ ];
const maxTicks = Math.round((width ?? Infinity) / 75);
@@ -137,28 +183,6 @@ export function Chart({
// 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();
-
- // filter out dates from the future
- if (timestamp > DateTime.now()) {
- return null;
- }
-
- 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) || [];
-
const currentDayStr = DateTime.now().toISODate();
const currentMonthStr = DateTime.now().toFormat("yyyy-MM-01");
const shouldNotDisplay =
@@ -169,62 +193,91 @@ 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 seriesData = seriesConfig.map(config => {
+ const points =
+ data?.data
+ ?.map((e, i) => {
+ // Parse timestamp properly
+ const timestamp = DateTime.fromSQL(e.time).toUTC();
- const baseGradient = {
- offset: 0,
- color: "hsl(var(--dataviz))",
- };
+ // filter out dates from the future
+ if (timestamp > DateTime.now()) {
+ return null;
+ }
- const croppedData = formattedData.slice(0, -1);
-
- // 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",
- },
- },
- ];
+ 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 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 displayDashed = (seriesData[0]?.points.length ?? 0) >= 2 && !shouldNotDisplay;
+
+ const chartPropsData: { id: string; data: any[] }[] = [];
+ const chartPropsDefs: any[] = [];
+ const chartPropsFill: any[] = [];
+ const colorMap: Record<string, string> = {};
+
+ seriesData.forEach(series => {
+ const baseId = `${series.id}-base`;
+ const hasEnoughPoints = series.points.length >= 2;
+ const baseData = displayDashed && hasEnoughPoints ? series.points.slice(0, -1) : 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: 1 },
+ { offset: 100, color: series.color, opacity: 0 },
],
});
chartPropsFill.push({
- id: "dashedData",
+ id: `${baseId}-gradient`,
match: {
- id: "dashedData",
+ id: baseId,
},
});
- }
+
+ if (displayDashed && hasEnoughPoints) {
+ const dashedId = `${series.id}-dashed`;
+ chartPropsData.push({
+ id: dashedId,
+ data: series.points.slice(-2),
+ });
+ colorMap[dashedId] = series.color;
+
+ chartPropsDefs.push({
+ id: `${dashedId}-gradient`,
+ type: "linearGradient",
+ colors: [
+ { offset: 0, color: series.color, opacity: 0.35 },
+ { offset: 100, color: series.color, opacity: 0 },
+ ],
+ });
+ chartPropsFill.push({
+ id: `${dashedId}-gradient`,
+ match: {
+ id: dashedId,
+ },
+ });
+ }
+ });
const DashedLine: LineCustomSvgLayer<LineSeries> = ({
series,
@@ -238,7 +291,7 @@ export function Chart({
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 }}
+ style={String(id).endsWith("-dashed") ? { strokeDasharray: "3, 6", strokeWidth: 3 } : { strokeWidth: 2 }}
/>
));
};
@@ -307,54 +360,200 @@ 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;
+ // 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"),
+ }));
- const diff = currentY - previousY;
- const diffPercentage = previousY ? (diff / previousY) * 100 : null;
+ if (!normalizedPoints.length) return 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-[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] bg-dataviz" />
- {formatChartDateTime(currentTime, bucket)}
+ // Single-series tooltip (unchanged)
+ 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>{formatTooltipValue(currentY, selectedStat)}</div>
- </div>
- {previousTime && (
- <div className="flex justify-between text-sm text-muted-foreground">
+ )}
+ <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] bg-neutral-200 dark:bg-neutral-750" />
- {formatChartDateTime(previousTime, bucket)}
+ <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>{formatTooltipValue(previousY, selectedStat)}</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 resolvedTheme === "dark" ? "hsl(var(--dataviz) / 0.28)" : "hsl(var(--dataviz) / 0.28)";
+ }
+ if (seriesId === "returning_users") {
+ return resolvedTheme === "dark" ? "hsl(var(--pink-800) / 0.35)" : "hsl(var(--pink-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);
+
+ if (!rows.length) {
+ // Fallback: show first available point to avoid empty tooltip
+ const p = normalizedPoints[0];
+ const currentY = Number(p.data.yFormatted ?? p.data.y ?? 0);
+ const previousY = Number(p.data.previousY ?? 0);
+ const diff = currentY - previousY;
+ const diffPercentage = previousY ? (diff / previousY) * 100 : null;
+ const color = colorMap[String(p.serieId)] ?? "hsl(var(--dataviz))";
+ const currentTime = p.data.currentTime as DateTime | undefined;
+ const previousTime = p.data.previousTime as DateTime | undefined;
+
+ return (
+ <ChartTooltip>
+ <div className="px-2 pt-1 text-xs font-semibold text-muted-foreground">Users</div>
+ {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>
+ <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-48">
+ <div className="flex items-center gap-2">
+ <div className="w-1 h-3 rounded-[3px]" style={{ backgroundColor: color }} />
+ {currentTime ? 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>
+ );
+ }
+
+ return (
+ <ChartTooltip>
+ {rows.map((row: any, idx: number) => (
+ <div key={row.id} className={idx < rows.length - 1 ? "pb-1.5 mb-1.5" : ""}>
+ <div className={`px-2 text-xs font-semibold text-muted-foreground ${idx === 0 ? "pt-2" : "pt-1"}`}>
+ {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 12086496f..2686cde46 100644
--- a/client/src/app/[site]/main/components/MainSection/MainSection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
@@ -13,6 +13,7 @@ import { Chart } from "./Chart";
import { Overview } from "./Overview";
import { PreviousChart } from "./PreviousChart";
import { RybbitLogo } from "../../../../../components/RybbitLogo";
+import { Switch } from "../../../../../components/ui/switch";
const SELECTED_STAT_MAP = {
pageviews: "Pageviews",
@@ -31,7 +32,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 +58,14 @@ 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?: { [key: string]: number }[] }) =>
+ Math.max(...(dataset?.data?.map(d => Math.max(...activeKeys.map(key => d?.[key] ?? 0))) ?? [0]));
+
+ const maxOfDataAndPreviousData = Math.max(getMaxValue(data), getMaxValue(previousData));
+
+ const statLabel = `${SELECTED_STAT_MAP[selectedStat]}${showUserBreakdown ? " (new vs returning)" : ""}`;
return (
<>
@@ -82,9 +88,31 @@ export function MainSection() {
rybbit.com
</Link>
</div>
- <span className="text-sm text-neutral-700 dark:text-neutral-200">{SELECTED_STAT_MAP[selectedStat]}</span>
- <BucketSelection />
+ <span className="text-sm text-neutral-700 dark:text-neutral-200">{statLabel}</span>
+ <div className="flex items-center gap-3">
+ {selectedStat === "users" && (
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Switch id="toggle-user-breakdown" checked={showUsersSplit} onCheckedChange={setShowUsersSplit} />
+ <label className="cursor-pointer" htmlFor="toggle-user-breakdown">
+ New vs returning
+ </label>
+ </div>
+ )}
+ <BucketSelection />
+ </div>
</div>
+ {showUserBreakdown && (
+ <div className="flex items-center gap-4 text-xs text-muted-foreground px-2 md:px-0 mt-2">
+ <div className="flex items-center gap-2">
+ <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: "hsl(var(--dataviz))" }} />
+ <span>New users</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: "hsl(var(--pink-400))" }} />
+ <span>Returning users</span>
+ </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 6d37363bb..1da9dac0d 100644
--- a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
@@ -43,20 +43,55 @@ 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 showUserBreakdown = selectedStat === "users" && showUsersSplit;
+ const previousColors = showUserBreakdown
+ ? resolvedTheme === "dark"
+ ? ["hsl(var(--dataviz) / 0.32)", "hsl(var(--pink-800) / 0.35)"]
+ : ["hsl(var(--dataviz) / 0.32)", "hsl(var(--pink-200) / 0.38)"]
+ : resolvedTheme === "dark"
+ ? ["hsl(var(--neutral-700))", "hsl(var(--neutral-500))"]
+ : ["hsl(var(--neutral-100))", "hsl(var(--neutral-300))"];
+
+ const seriesConfig: { id: string; dataKey: keyof GetOverviewBucketedResponse[number]; color: string }[] =
+ showUserBreakdown
+ ? [
+ { id: "new_users", dataKey: "new_users", color: previousColors[0] },
+ { id: "returning_users", dataKey: "returning_users", color: previousColors[1] },
+ ]
+ : [{ id: selectedStat, dataKey: selectedStat, color: previousColors[0] }];
+
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 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)
+ ?.slice(0, size) ?? [];
+
+ 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 +101,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={{
@@ -128,7 +158,7 @@ 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/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 b4e0003aa..064f8f93d 100644
--- a/server/src/api/analytics/getOverviewBucketed.ts
+++ b/server/src/api/analytics/getOverviewBucketed.ts
@@ -112,6 +112,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,
@@ -120,7 +143,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
@@ -135,14 +160,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
@@ -151,7 +174,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<{