Skip to content

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

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

Bill Yang3c3555d38fde
diff --git a/client/src/api/analytics/useGetOverviewBucketed.ts b/client/src/api/analytics/useGetOverviewBucketed.ts
index c014791a9..3952114b7 100644
--- a/client/src/api/analytics/useGetOverviewBucketed.ts
+++ b/client/src/api/analytics/useGetOverviewBucketed.ts
@@ -14,8 +14,6 @@ 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 f640cb243..7bfedf6c3 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -2,25 +2,15 @@
import { TimeBucket } from "@rybbit/shared";
import { useNivoTheme } from "@/lib/nivo";
import { StatType, useStore } from "@/lib/store";
-import { ResponsiveLine } from "@nivo/line";
+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";
-import { formatter } from "../../../../../lib/utils";
-import { userLocale, hour12 } from "../../../../../lib/dateTimeUtils";
-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;
+import { formatSecondsAsMinutesAndSeconds, formatter } from "../../../../../lib/utils";
+import { userLocale, hour12, formatChartDateTime } from "../../../../../lib/dateTimeUtils";
+import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
const getMax = (time: Time, bucket: TimeBucket) => {
const now = DateTime.now();
@@ -32,7 +22,18 @@ const getMax = (time: Time, bucket: TimeBucket) => {
} else if (time.mode === "day") {
const dayDate = DateTime.fromISO(time.day)
.endOf("day")
- .minus({ minutes: getBucketMinutesOffset(bucket) });
+ .minus({
+ minutes:
+ bucket === "hour"
+ ? 59
+ : bucket === "fifteen_minutes"
+ ? 14
+ : bucket === "ten_minutes"
+ ? 9
+ : bucket === "five_minutes"
+ ? 4
+ : 0,
+ });
return now < dayDate ? dayDate.toJSDate() : undefined;
} else if (time.mode === "range") {
if (bucket === "day" || bucket === "week" || bucket === "month" || bucket === "year") {
@@ -40,21 +41,38 @@ const getMax = (time: Time, bucket: TimeBucket) => {
}
const rangeDate = DateTime.fromISO(time.endDate)
.endOf("day")
- .minus({ minutes: getBucketMinutesOffset(bucket) });
+ .minus({
+ minutes:
+ bucket === "hour"
+ ? 59
+ : bucket === "fifteen_minutes"
+ ? 14
+ : bucket === "ten_minutes"
+ ? 9
+ : bucket === "five_minutes"
+ ? 4
+ : 0,
+ });
return now < rangeDate ? rangeDate.toJSDate() : undefined;
} else if (time.mode === "week") {
- if (bucket !== "hour" && bucket !== "fifteen_minutes") {
- return undefined;
+ if (bucket === "hour") {
+ const endDate = DateTime.fromISO(time.week).endOf("week").minus({
+ minutes: 59,
+ });
+ return now < endDate ? endDate.toJSDate() : undefined;
}
- const endDate = DateTime.fromISO(time.week)
- .endOf("week")
- .minus({ minutes: getBucketMinutesOffset(bucket) });
- 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;
+ }
+ return undefined;
} else if (time.mode === "month") {
if (bucket === "hour") {
- const endDate = DateTime.fromISO(time.month)
- .endOf("month")
- .minus({ minutes: getBucketMinutesOffset(bucket) });
+ const endDate = DateTime.fromISO(time.month).endOf("month").minus({
+ minutes: 59,
+ });
return now < endDate ? endDate.toJSDate() : undefined;
}
const monthDate = DateTime.fromISO(time.month).endOf("month");
@@ -88,64 +106,17 @@ const getMin = (time: Time, bucket: TimeBucket) => {
return undefined;
};
-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;
+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 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 Y_TICK_VALUES = 5;
export function Chart({
data,
@@ -156,36 +127,9 @@ export function Chart({
previousData: APIResponse<GetOverviewBucketedResponse> | undefined;
max: number;
}) {
- const { time, bucket, selectedStat, showUsersSplit } = useStore();
+ const { time, bucket, selectedStat } = 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(--accent-200))",
- },
- ]
- : [
- {
- id: selectedStat,
- dataKey: selectedStat,
- label: SERIES_LABELS[selectedStat],
- color: "hsl(var(--dataviz))",
- },
- ];
const maxTicks = Math.round((width ?? Infinity) / 75);
@@ -193,6 +137,28 @@ 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 =
@@ -203,69 +169,79 @@ 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 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;
- }
-
- 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 = formattedData.length >= 2 && !shouldNotDisplay;
- const displayDashed = (seriesData[0]?.points.length ?? 0) >= 2 && !shouldNotDisplay;
+ const baseGradient = {
+ offset: 0,
+ color: "hsl(var(--dataviz))",
+ };
- const chartPropsData: { id: string; data: any[] }[] = [];
- const chartPropsDefs: any[] = [];
- const chartPropsFill: any[] = [];
- const colorMap: Record<string, string> = {};
+ const croppedData = formattedData.slice(0, -1);
- seriesData.forEach(series => {
- const baseId = `${series.id}-base`;
- const baseData = series.points;
+ // 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",
+ },
+ },
+ ];
+ // add dashed data and styles to chart
+ if (displayDashed) {
chartPropsData.push({
- id: baseId,
- data: baseData,
+ id: "dashedData",
+ data: [croppedData.at(-1)!, formattedData.at(-1)!],
});
- colorMap[baseId] = series.color;
-
chartPropsDefs.push({
- id: `${baseId}-gradient`,
+ id: "dashedData",
type: "linearGradient",
colors: [
- { offset: 0, color: series.color, opacity: 1 },
- { offset: 100, color: series.color, opacity: 0 },
+ { ...baseGradient, opacity: 0.35 },
+ { offset: 100, color: baseGradient.color, opacity: 0 },
],
});
chartPropsFill.push({
- id: `${baseId}-gradient`,
+ id: "dashedData",
match: {
- id: baseId,
+ id: "dashedData",
},
});
- });
+ }
- const StackedLines = createStackedLines(displayDashed);
- const DashedOverlay = createDashedOverlay(displayDashed);
+ 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 (
<ResponsiveLine
@@ -283,7 +259,7 @@ export function Chart({
yScale={{
type: "linear",
min: 0,
- stacked: showUserBreakdown,
+ stacked: false,
reverse: false,
max: Math.max(max, 1),
}}
@@ -331,32 +307,65 @@ export function Chart({
useMesh={true}
animate={false}
enableSlices={"x"}
- colors={({ id }) => colorMap[id as string] ?? "hsl(var(--dataviz))"}
+ colors={["hsl(var(--dataviz))"]}
enableArea={true}
areaBaselineValue={0}
areaOpacity={0.3}
defs={chartPropsDefs}
fill={chartPropsFill}
- sliceTooltip={({ slice }: any) => (
- <ChartSliceTooltip
- slice={slice}
- showUserBreakdown={showUserBreakdown}
- colorMap={colorMap}
- seriesConfig={seriesConfig}
- seriesData={seriesData as SeriesData[]}
- bucket={bucket}
- selectedStat={selectedStat}
- resolvedTheme={resolvedTheme}
- />
- )}
+ 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-[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)}
+ </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>
+ );
+ }}
layers={[
"grid",
"markers",
"axes",
"areas",
"crosshair",
- StackedLines,
- ...(displayDashed ? [DashedOverlay] : []),
+ displayDashed ? DashedLine : "lines",
+ // "lines",
"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
deleted file mode 100644
index 22ab8e16e..000000000
--- a/client/src/app/[site]/main/components/MainSection/ChartSliceTooltip.tsx
+++ /dev/null
@@ -1,200 +0,0 @@
-"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 c03dde38f..12086496f 100644
--- a/client/src/app/[site]/main/components/MainSection/MainSection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
@@ -1,20 +1,18 @@
"use client";
import { Card, CardContent, CardLoader } from "@/components/ui/card";
-import { User, Users } from "lucide-react";
import { Tilt_Warp } from "next/font/google";
+import Image from "next/image";
import Link from "next/link";
import { useGetOverview } from "../../../../../api/analytics/useGetOverview";
import { useGetOverviewBucketed } from "../../../../../api/analytics/useGetOverviewBucketed";
-import { BucketSelection } from "../../../../../components/BucketSelection";
-import { RybbitLogo } from "../../../../../components/RybbitLogo";
-import { Button } from "../../../../../components/ui/button";
-import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";
import { authClient } from "../../../../../lib/auth";
import { useStore } from "../../../../../lib/store";
import { cn } from "../../../../../lib/utils";
+import { BucketSelection } from "../../../../../components/BucketSelection";
import { Chart } from "./Chart";
import { Overview } from "./Overview";
import { PreviousChart } from "./PreviousChart";
+import { RybbitLogo } from "../../../../../components/RybbitLogo";
const SELECTED_STAT_MAP = {
pageviews: "Pageviews",
@@ -33,8 +31,7 @@ const tilt_wrap = Tilt_Warp({
export function MainSection() {
const session = authClient.useSession();
- const { selectedStat, time, site, bucket, showUsersSplit, setShowUsersSplit } = useStore();
- const showUserBreakdown = selectedStat === "users" && showUsersSplit;
+ const { selectedStat, time, site, bucket } = useStore();
// Current period data
const { data, isFetching, error } = useGetOverviewBucketed({
@@ -59,18 +56,10 @@ export function MainSection() {
periodTime: "previous",
});
- 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));
+ const maxOfDataAndPreviousData = Math.max(
+ Math.max(...(data?.data?.map((d: any) => d[selectedStat]) ?? [])),
+ Math.max(...(previousData?.data?.map((d: any) => d[selectedStat]) ?? []))
+ );
return (
<>
@@ -80,43 +69,22 @@ export function MainSection() {
</CardContent>
{(isOverviewFetching || isOverviewFetchingPrevious) && <CardLoader />}
</Card>
- <Card className="overflow-visible">
+ <Card>
{(isFetching || isPreviousFetching) && <CardLoader />}
<CardContent className="p-2 md:p-4 py-3 w-full">
- <div className="flex flex-col gap-2 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>
- <span className="absolute left-1/2 -translate-x-1/2 text-sm text-neutral-700 dark:text-neutral-200">
- {SELECTED_STAT_MAP[selectedStat]}
- </span>
- <div className="flex items-center gap-2 md:justify-end">
- {selectedStat === "users" && (
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <Tooltip>
- <TooltipTrigger>
- <Button variant="default" 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>
- )}
- <BucketSelection />
- </div>
+ <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>
+ <span className="text-sm text-neutral-700 dark:text-neutral-200">{SELECTED_STAT_MAP[selectedStat]}</span>
+ <BucketSelection />
</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 c370a66a9..6d37363bb 100644
--- a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
@@ -43,55 +43,20 @@ export function PreviousChart({
data: APIResponse<GetOverviewBucketedResponse> | undefined;
max: number;
}) {
- const { previousTime: time, selectedStat, bucket, showUsersSplit } = useStore();
+ const { previousTime: time, selectedStat, bucket } = useStore();
const { resolvedTheme } = useTheme();
const nivoTheme = useNivoTheme();
- const showUserBreakdown = selectedStat === "users" && showUsersSplit;
- const previousColors = showUserBreakdown
- ? resolvedTheme === "dark"
- ? ["hsl(var(--dataviz) / 0.32)", "hsl(var(--accent-800) / 0.35)"]
- : ["hsl(var(--dataviz) / 0.32)", "hsl(var(--accent-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 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 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 min = getMin(time, bucket);
const maxPastMinutes =
@@ -101,7 +66,12 @@ export function PreviousChart({
return (
<ResponsiveLine
- data={chartData}
+ data={[
+ {
+ id: "1",
+ data: formattedData ?? [],
+ },
+ ]}
theme={nivoTheme}
margin={{ top: 10, right: 15, bottom: 30, left: 40 }}
xScale={{
@@ -115,7 +85,7 @@ export function PreviousChart({
yScale={{
type: "linear",
min: 0,
- stacked: showUserBreakdown,
+ stacked: false,
reverse: false,
max: Math.max(max, 1),
}}
@@ -158,9 +128,7 @@ export function PreviousChart({
animate={false}
// motionConfig="stiff"
enableSlices={"x"}
- colors={({ id }) =>
- colorMap[id as string] ?? (resolvedTheme === "dark" ? "hsl(var(--neutral-700))" : "hsl(var(--neutral-100))")
- }
+ colors={[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 4f449cebb..41119548a 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 overflow-hidden pointer-events-none">
+ <div className="mt-[-15px] absolute top-0 left-0 w-full">
<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 98b396f07..74e2f94fe 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -17,8 +17,6 @@ type Store = {
setBucket: (bucket: TimeBucket) => void;
selectedStat: StatType;
setSelectedStat: (stat: StatType) => void;
- showUsersSplit: boolean;
- setShowUsersSplit: (split: boolean) => void;
filters: Filter[];
setFilters: (filters: Filter[]) => void;
};
@@ -56,7 +54,6 @@ export const useStore = create<Store>(set => ({
},
bucket: hasBucketInUrl ? state.bucket : "hour",
selectedStat: hasStatInUrl ? state.selectedStat : "users",
- showUsersSplit: false,
}));
},
privateKey: null,
@@ -146,19 +143,16 @@ 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, setShowUsersSplit } = useStore.getState();
+ const { setSite, setTime, setBucket, setSelectedStat, setFilters } = 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 064f8f93d..b4e0003aa 100644
--- a/server/src/api/analytics/getOverviewBucketed.ts
+++ b/server/src/api/analytics/getOverviewBucketed.ts
@@ -112,29 +112,6 @@ 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,
@@ -143,9 +120,7 @@ SELECT
session_stats.bounce_rate * 100 AS bounce_rate,
session_stats.session_duration,
page_stats.pageviews,
- page_stats.users,
- page_stats.new_users,
- page_stats.returning_users
+ page_stats.users
FROM
(
SELECT
@@ -160,12 +135,14 @@ FROM
FULL JOIN
(
SELECT
- bucket_time AS time,
+ toDateTime(${TimeBucketToFn[bucket]}(toTimeZone(timestamp, ${SqlString.escape(time_zone)}))) AS time,
countIf(type = 'pageview') AS pageviews,
- 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
+ COUNT(DISTINCT user_id) AS users
+ FROM events
+ WHERE
+ site_id = {siteId:Int32}
+ ${filterStatement}
+ ${getTimeStatement(params)}
GROUP BY time ORDER BY time ${isAllTime ? "" : getTimeStatementFill(params, bucket)}
) AS page_stats
USING time
@@ -174,17 +151,7 @@ ORDER BY time`;
return query;
};
-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;
-}[];
+type getOverviewBucketed = { time: string; pageviews: number }[];
export async function getOverviewBucketed(
req: FastifyRequest<{