Skip to content

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

add other stats to mainsection

Bill Yang6657b914e189
diff --git a/client/package-lock.json b/client/package-lock.json
index 7bdac3d9b..0e3635c63 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -32,6 +32,7 @@
"country-flag-icons": "^1.5.14",
"date-fns": "^4.1.0",
"geojson": "^0.5.0",
+ "jotai": "^2.12.1",
"ldrs": "^1.0.2",
"leaflet": "^1.9.4",
"lodash": "^4.17.21",
@@ -4391,6 +4392,26 @@
"url": "https://github.com/sponsors/panva"
}
},
+ "node_modules/jotai": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/jotai/-/jotai-2.12.1.tgz",
+ "integrity": "sha512-VUW0nMPYIru5g89tdxwr9ftiVdc/nGV9jvHISN8Ucx+m1vI9dBeHemfqYzEuw5XSkmYjD/MEyApN9k6yrATsZQ==",
+ "engines": {
+ "node": ">=12.20.0"
+ },
+ "peerDependencies": {
+ "@types/react": ">=17.0.0",
+ "react": ">=17.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
diff --git a/client/package.json b/client/package.json
index 2b09e96df..aee69a3db 100644
--- a/client/package.json
+++ b/client/package.json
@@ -33,6 +33,7 @@
"country-flag-icons": "^1.5.14",
"date-fns": "^4.1.0",
"geojson": "^0.5.0",
+ "jotai": "^2.12.1",
"ldrs": "^1.0.2",
"leaflet": "^1.9.4",
"lodash": "^4.17.21",
diff --git a/client/src/app/[site]/components/MainSection/Chart.tsx b/client/src/app/[site]/components/MainSection/Chart.tsx
index fc347bcf6..f8b78bce6 100644
--- a/client/src/app/[site]/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/components/MainSection/Chart.tsx
@@ -1,10 +1,10 @@
"use client";
-import { ResponsiveLine } from "@nivo/line";
-import { round } from "lodash";
-import { DateTime } from "luxon";
import { APIResponse, GetOverviewBucketedResponse } from "@/hooks/api";
import { nivoTheme } from "@/lib/nivo";
-import { Time, TimeBucket, useStore } from "@/lib/store";
+import { StatType, Time, TimeBucket, useStore } from "@/lib/store";
+import { ResponsiveLine } from "@nivo/line";
+import { DateTime } from "luxon";
+import { formatSecondsAsMinutesAndSeconds } from "../../../../lib/utils";
export const formatter = Intl.NumberFormat("en", { notation: "compact" });
@@ -62,6 +62,16 @@ const getMin = (time: Time, bucket: TimeBucket) => {
return undefined;
};
+const formatTooltipValue = (value: number, selectedStat: StatType) => {
+ if (selectedStat === "bounce_rate") {
+ return `${value.toFixed(1)}%`;
+ }
+ if (selectedStat === "session_duration") {
+ return formatSecondsAsMinutesAndSeconds(value);
+ }
+ return value.toLocaleString();
+};
+
export function Chart({
data,
previousData,
@@ -71,7 +81,7 @@ export function Chart({
previousData: APIResponse<GetOverviewBucketedResponse> | undefined;
max: number;
}) {
- const { time, bucket } = useStore();
+ const { time, bucket, selectedStat } = useStore();
// 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
@@ -89,9 +99,9 @@ export function Chart({
return {
x: DateTime.fromSQL(e.time).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
- y: e.pageviews,
+ y: e[selectedStat],
previousY:
- i >= lengthDiff && previousData?.data?.[i - lengthDiff]?.pageviews,
+ i >= lengthDiff && previousData?.data?.[i - lengthDiff][selectedStat],
currentTime: DateTime.fromSQL(e.time),
previousTime:
i >= lengthDiff
@@ -209,7 +219,7 @@ export function Chart({
? currentTime.toFormat("M/d h a")
: currentTime.toLocaleString()}
</div>
- <div>{round(currentY).toLocaleString()}</div>
+ <div>{formatTooltipValue(currentY, selectedStat)}</div>
</div>
{previousTime && (
<div className="flex justify-between text-sm text-muted-foreground">
@@ -218,7 +228,7 @@ export function Chart({
? previousTime.toFormat("M/d h a")
: previousTime.toLocaleString()}
</div>
- <div>{round(previousY).toLocaleString()}</div>
+ <div>{formatTooltipValue(previousY, selectedStat)}</div>
</div>
)}
</div>
diff --git a/client/src/app/[site]/components/MainSection/MainSection.tsx b/client/src/app/[site]/components/MainSection/MainSection.tsx
index e590f4565..025637850 100644
--- a/client/src/app/[site]/components/MainSection/MainSection.tsx
+++ b/client/src/app/[site]/components/MainSection/MainSection.tsx
@@ -5,8 +5,11 @@ import { BucketSelection } from "./BucketSelection";
import { Chart } from "./Chart";
import { Overview } from "./Overview";
import { PreviousChart } from "./PreviousChart";
+import { useStore } from "../../../../lib/store";
export function MainSection() {
+ const { selectedStat } = useStore();
+
const { data, isFetching, error } = useGetOverviewBucketed();
const {
data: previousData,
@@ -17,8 +20,8 @@ export function MainSection() {
const { isFetching: isOverviewFetchingPrevious } = useGetOverview("previous");
const maxOfDataAndPreviousData = Math.max(
- Math.max(...(data?.data?.map((d) => d.pageviews) ?? [])),
- Math.max(...(previousData?.data?.map((d) => d.pageviews) ?? []))
+ Math.max(...(data?.data?.map((d) => d[selectedStat]) ?? [])),
+ Math.max(...(previousData?.data?.map((d) => d[selectedStat]) ?? []))
);
return (
diff --git a/client/src/app/[site]/components/MainSection/Overview.tsx b/client/src/app/[site]/components/MainSection/Overview.tsx
index ded1287f1..01e7beb12 100644
--- a/client/src/app/[site]/components/MainSection/Overview.tsx
+++ b/client/src/app/[site]/components/MainSection/Overview.tsx
@@ -1,10 +1,10 @@
"use client";
-import { Duration } from "luxon";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { useGetOverview } from "@/hooks/api";
-import { formatter } from "@/lib/utils";
+import { cn, formatSecondsAsMinutesAndSeconds, formatter } from "@/lib/utils";
+import { StatType, useStore } from "../../../../lib/store";
const ChangePercentage = ({
current,
@@ -48,21 +48,30 @@ const ChangePercentage = ({
const Stat = ({
title,
+ id,
value,
previous,
valueFormatter,
isLoading,
}: {
title: string;
+ id: StatType;
value: number;
previous: number;
valueFormatter?: (value: number) => string;
isLoading: boolean;
}) => {
+ const { selectedStat, setSelectedStat } = useStore();
return (
- <div className="flex flex-col gap-1">
+ <div
+ className={cn(
+ "flex flex-col hover:bg-neutral-800 rounded-md px-3 py-2 cursor-pointer",
+ selectedStat === id && "bg-neutral-850"
+ )}
+ onClick={() => setSelectedStat(id)}
+ >
<div className="text-sm font-medium text-muted-foreground">{title}</div>
- <div className="text-3xl font-medium flex gap-2 items-center">
+ <div className="text-2xl font-medium flex gap-2 items-center">
{isLoading ? (
<>
<Skeleton className="w-[60px] h-7 rounded-md" />
@@ -112,9 +121,10 @@ export function Overview() {
overviewDataPrevious?.data?.session_duration ?? 0;
return (
- <div className="flex gap-6 items-center">
+ <div className="flex gap-0 items-center">
<Stat
title="Unique Users"
+ id="users"
value={currentUsers}
previous={previousUsers}
isLoading={isLoading}
@@ -122,6 +132,7 @@ export function Overview() {
/>
<Stat
title="Sessions"
+ id="sessions"
value={currentSessions}
previous={previousSessions}
isLoading={isLoading}
@@ -129,6 +140,7 @@ export function Overview() {
/>
<Stat
title="Pageviews"
+ id="pageviews"
value={currentPageviews}
previous={previousPageviews}
isLoading={isLoading}
@@ -136,6 +148,7 @@ export function Overview() {
/>
<Stat
title="Pages per Session"
+ id="pages_per_session"
value={currentPagesPerSession}
previous={previousPagesPerSession}
isLoading={isLoading}
@@ -143,30 +156,19 @@ export function Overview() {
/>
<Stat
title="Bounce Rate"
+ id="bounce_rate"
value={currentBounceRate}
previous={previousBounceRate}
isLoading={isLoading}
- valueFormatter={(value) => `${(value * 100).toFixed(1)}%`}
+ valueFormatter={(value) => `${value.toFixed(1)}%`}
/>
<Stat
title="Session Duration"
+ id="session_duration"
value={currentSessionDuration}
previous={previousSessionDuration}
isLoading={isLoading}
- valueFormatter={(value) => {
- const duration = Duration.fromMillis(value * 1000);
- const hours = Math.floor(duration.as("hours"));
- const minutes = Math.floor(duration.as("minutes") % 60);
- const seconds = Math.floor(duration.as("seconds") % 60);
-
- if (hours > 0) {
- return `${hours}hr ${minutes}min`;
- } else if (minutes > 0) {
- return `${minutes}m ${seconds}s`;
- } else {
- return `${seconds}s`;
- }
- }}
+ valueFormatter={formatSecondsAsMinutesAndSeconds}
/>
</div>
);
diff --git a/client/src/app/[site]/components/MainSection/PreviousChart.tsx b/client/src/app/[site]/components/MainSection/PreviousChart.tsx
index d882ce6c6..1383d0a40 100644
--- a/client/src/app/[site]/components/MainSection/PreviousChart.tsx
+++ b/client/src/app/[site]/components/MainSection/PreviousChart.tsx
@@ -1,9 +1,9 @@
"use client";
-import { ResponsiveLine } from "@nivo/line";
-import { DateTime } from "luxon";
import { APIResponse, GetOverviewBucketedResponse } from "@/hooks/api";
import { nivoTheme } from "@/lib/nivo";
import { Time, useStore } from "@/lib/store";
+import { ResponsiveLine } from "@nivo/line";
+import { DateTime } from "luxon";
import { useMemo } from "react";
const getMin = (time: Time) => {
@@ -34,11 +34,11 @@ export function PreviousChart({
data: APIResponse<GetOverviewBucketedResponse> | undefined;
max: number;
}) {
- const { previousTime: time } = useStore();
+ const { previousTime: time, selectedStat } = useStore();
const formattedData = data?.data?.map((e) => ({
x: DateTime.fromSQL(e.time).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
- y: e.pageviews,
+ y: e[selectedStat],
}));
const min = useMemo(() => getMin(time), [data]);
diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts
index beecea4c2..450ef7437 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -37,6 +37,14 @@ export type Time = DateMode | DateRangeMode | WeekMode | MonthMode | YearMode;
export type TimeBucket = "hour" | "day" | "week" | "month" | "year";
+export type StatType =
+ | "pageviews"
+ | "sessions"
+ | "users"
+ | "pages_per_session"
+ | "bounce_rate"
+ | "session_duration";
+
type Store = {
site: string;
setSite: (site: string) => void;
@@ -45,6 +53,8 @@ type Store = {
setTime: (time: Time, changeBucket?: boolean) => void;
bucket: TimeBucket;
setBucket: (bucket: TimeBucket) => void;
+ selectedStat: StatType;
+ setSelectedStat: (stat: StatType) => void;
};
export const useStore = create<Store>((set) => ({
@@ -61,6 +71,7 @@ export const useStore = create<Store>((set) => ({
day: DateTime.now().minus({ days: 1 }).toISODate(),
},
bucket: "hour",
+ selectedStat: "users",
});
},
time: {
@@ -135,6 +146,8 @@ export const useStore = create<Store>((set) => ({
},
bucket: "hour",
setBucket: (bucket) => set({ bucket }),
+ selectedStat: "users",
+ setSelectedStat: (stat) => set({ selectedStat: stat }),
}));
export const goBack = () => {
diff --git a/client/src/lib/utils.ts b/client/src/lib/utils.ts
index 51216a322..9daa8ef2e 100644
--- a/client/src/lib/utils.ts
+++ b/client/src/lib/utils.ts
@@ -1,4 +1,5 @@
import { clsx, type ClassValue } from "clsx";
+import { Duration } from "luxon";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
@@ -8,3 +9,18 @@ export function cn(...inputs: ClassValue[]) {
export const formatter = Intl.NumberFormat("en", {
notation: "compact",
}).format;
+
+export function formatSecondsAsMinutesAndSeconds(value: number) {
+ const duration = Duration.fromMillis(value * 1000);
+ const hours = Math.floor(duration.as("hours"));
+ const minutes = Math.floor(duration.as("minutes") % 60);
+ const seconds = Math.floor(duration.as("seconds") % 60);
+
+ if (hours > 0) {
+ return `${hours}hr ${minutes}min`;
+ } else if (minutes > 0) {
+ return `${minutes}m ${seconds}s`;
+ } else {
+ return `${seconds}s`;
+ }
+}
diff --git a/server/src/api/getOverview.ts b/server/src/api/getOverview.ts
index 1a210f8a2..99c002a21 100644
--- a/server/src/api/getOverview.ts
+++ b/server/src/api/getOverview.ts
@@ -21,7 +21,7 @@ export async function getOverview(
const query = `SELECT
session_stats.sessions,
session_stats.pages_per_session,
- session_stats.bounce_rate,
+ session_stats.bounce_rate * 100 AS bounce_rate,
session_stats.session_duration,
page_stats.pageviews,
page_stats.users
diff --git a/server/src/api/getOverviewBucketed.ts b/server/src/api/getOverviewBucketed.ts
index 00a1c6e31..ce771b883 100644
--- a/server/src/api/getOverviewBucketed.ts
+++ b/server/src/api/getOverviewBucketed.ts
@@ -58,7 +58,7 @@ export async function getOverviewBucketed(
session_stats.time AS time,
session_stats.sessions,
session_stats.pages_per_session,
- session_stats.bounce_rate,
+ session_stats.bounce_rate * 100 AS bounce_rate,
session_stats.session_duration,
page_stats.pageviews,
page_stats.users