🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
add previous chart
Bill Yang08e40185845e
diff --git a/client/src/app/components/MainSection/Chart.tsx b/client/src/app/components/MainSection/Chart.tsxindex 5e6f1bf2c..b6815e7bd 100644--- a/client/src/app/components/MainSection/Chart.tsx+++ b/client/src/app/components/MainSection/Chart.tsx@@ -1,56 +1,10 @@"use client";-import { Theme } from "@nivo/core";import { ResponsiveLine } from "@nivo/line";-import { DateTime } from "luxon";import { round } from "lodash";-import { Time, useTimeSelection } from "../../../lib/timeSelectionStore";+import { DateTime } from "luxon";import { APIResponse, GetPageViewsResponse } from "../../../hooks/api";--export const nivoTheme: Theme = {- axis: {- legend: {- text: {- fill: "hsl(var(--neutral-400))",- },- },- ticks: {- line: {},- text: {- fill: "hsl(var(--neutral-400))",- },- },- },- grid: {- line: {- stroke: "hsl(var(--neutral-800))",- strokeWidth: 1,- },- },- tooltip: {- basic: {- fontFamily: "Roboto Mono",- },- container: {- backdropFilter: "blur( 7px )",- background: "rgb(40, 40, 40, 0.8)",- color: "rgb(255, 255, 255)",- },- },- crosshair: { line: { stroke: "hsl(var(--neutral-50))" } },- annotations: {- text: {- fill: "hsl(var(--neutral-400))",- },- },- text: {- fill: "hsl(var(--neutral-400))",- },- labels: {- text: {- fill: "hsl(var(--neutral-400))",- },- },-};+import { nivoTheme } from "../../../lib/nivo";+import { Time, useTimeSelection } from "../../../lib/timeSelectionStore";export const formatter = Intl.NumberFormat("en", { notation: "compact" });@@ -78,15 +32,21 @@ const getMax = (time: Time) => {export function Chart({data,previousData,+ max,}: {data: APIResponse<GetPageViewsResponse> | undefined;previousData: APIResponse<GetPageViewsResponse> | undefined;+ max?: number;}) {const { time } = useTimeSelection();- const formattedData = data?.data?.map((e) => ({+ const formattedData = data?.data?.map((e, i) => ({x: DateTime.fromSQL(e.time).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),y: e.pageviews,+ previousY: previousData?.data?.[i]?.pageviews,++ currentTime: DateTime.fromSQL(e.time).toUTC(),+ previousTime: DateTime.fromSQL(previousData?.data?.[i]?.time ?? "").toUTC(),}));const timeRange =@@ -97,28 +57,16 @@ export function Chart({).days: 0;- const formattedPreviousData = previousData?.data?.map((e) => ({- x: DateTime.fromSQL(e.time)- .plus({ days: timeRange || 1 })- .toUTC()- .toFormat("yyyy-MM-dd HH:mm:ss"),- y: e.pageviews,- }));-return (<ResponsiveLinedata={[- {- id: "2",- data: formattedPreviousData ?? [],- },{id: "1",data: formattedData ?? [],},]}theme={nivoTheme}- margin={{ top: 20, right: 20, bottom: 20, left: 30 }}+ margin={{ top: 20, right: 20, bottom: 20, left: 40 }}xScale={{type: "time",format: "%Y-%m-%d %H:%M:%S",@@ -129,11 +77,12 @@ export function Chart({yScale={{type: "linear",min: 0,- max: "auto",stacked: false,reverse: false,+ max: max,}}enableGridX={false}+ enableGridY={true}yFormat=" >-.2f"axisTop={null}axisRight={null}@@ -169,7 +118,7 @@ export function Chart({useMesh={true}motionConfig="stiff"enableSlices={"x"}- colors={["hsl(var(--neutral-700))", "hsl(var(--fuchsia-400))"]}+ colors={["hsl(var(--fuchsia-400))"]}enableArea={true}areaBaselineValue={0}areaOpacity={0.3}@@ -184,21 +133,48 @@ export function Chart({},]}fill={[{ match: (d) => d.id === "1", id: "gradient" }]}- sliceTooltip={({ slice }) => {+ sliceTooltip={({ slice }: any) => {+ const currentY = Number(slice.points[0].data.yFormatted);+ const previousY = Number(slice.points[0].data.previousY);+ const currentTime = slice.points[0].data.currentTime as DateTime;+ const previousTime = slice.points[0].data.previousTime as DateTime;++ const diff = currentY - previousY;+ const diffPercentage = (diff / previousY) * 100;+return (<div className="text-sm bg-neutral-900 p-2 rounded-md">- <div>- {DateTime.fromJSDate(- slice.points[0].data.x as any- ).toLocaleString(DateTime.DATETIME_SHORT)}+ <div+ className="text-lg font-medium"+ style={{+ color:+ diffPercentage > 0+ ? "hsl(var(--green-400))"+ : "hsl(var(--red-400))",+ }}+ >+ {diffPercentage > 0 ? "+" : ""}+ {diffPercentage.toFixed(2)}%+ </div>+ <div className="flex justify-between text-sm w-36">+ <div>+ {time.mode === "day"+ ? currentTime.toFormat("M/d h a")+ : currentTime.toLocaleString()}+ </div>+ <div>{round(currentY).toLocaleString()}</div></div>- <div>- {round(Number(slice.points[0].data.yFormatted)).toLocaleString()}+ <div className="flex justify-between text-sm text-muted-foreground">+ <div>+ {time.mode === "day"+ ? previousTime.toFormat("M/d h a")+ : previousTime.toLocaleString()}+ </div>+ <div>{round(previousY).toLocaleString()}</div></div></div>);}}- // layers={["grid", "markers", "areas", "", "lines", "points", "slices", "axes", "legends"]}/>);}diff --git a/client/src/app/components/MainSection/MainSection.tsx b/client/src/app/components/MainSection/MainSection.tsxindex c5f06f2d7..e10374750 100644--- a/client/src/app/components/MainSection/MainSection.tsx+++ b/client/src/app/components/MainSection/MainSection.tsx@@ -3,6 +3,7 @@ import { Card, CardContent, CardLoader } from "@/components/ui/card";import { useGetOverview, useGetPageviews } from "../../../hooks/api";import { BucketSelection } from "./BucketSelection";import { Chart } from "./Chart";+import { PreviousChart } from "./PreviousChart";export function MainSection() {const { data, isFetching, error } = useGetPageviews();@@ -17,6 +18,11 @@ export function MainSection() {error: overviewError,} = useGetOverview();+ const maxOfDataAndPreviousData = Math.max(+ Math.max(...(data?.data?.map((d) => d.pageviews) ?? [])),+ Math.max(...(previousData?.data?.map((d) => d.pageviews) ?? []))+ );+return (<Card>{(isFetching || isOverviewFetching) && <CardLoader />}@@ -50,8 +56,17 @@ export function MainSection() {</div><BucketSelection /></div>- <div className="h-[350px]">- <Chart data={data} previousData={previousData} />+ <div className="h-[350px] relative">+ <div className="absolute top-0 left-0 w-full h-full">+ <PreviousChart data={previousData} />+ </div>+ <div className="absolute top-0 left-0 w-full h-full">+ <Chart+ data={data}+ max={maxOfDataAndPreviousData}+ previousData={previousData}+ />+ </div></div></CardContent></Card>diff --git a/client/src/app/components/MainSection/PreviousChart.tsx b/client/src/app/components/MainSection/PreviousChart.tsxnew file mode 100644index 000000000..7275e7113--- /dev/null+++ b/client/src/app/components/MainSection/PreviousChart.tsx@@ -0,0 +1,108 @@+"use client";+import { ResponsiveLine } from "@nivo/line";+import { DateTime } from "luxon";+import { APIResponse, GetPageViewsResponse } from "../../../hooks/api";+import { nivoTheme } from "../../../lib/nivo";+import { useTimeSelection } from "../../../lib/timeSelectionStore";++export function PreviousChart({+ data,+ max,+}: {+ data: APIResponse<GetPageViewsResponse> | undefined;+ max?: number;+}) {+ const { time } = useTimeSelection();++ const formattedData = data?.data?.map((e) => ({+ x: DateTime.fromSQL(e.time).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),+ y: e.pageviews,+ }));++ const timeRange =+ time.mode === "range"+ ? DateTime.fromISO(time.startDate).diff(+ DateTime.fromISO(time.endDate),+ "days"+ ).days+ : 0;++ return (+ <ResponsiveLine+ data={[+ {+ id: "1",+ data: formattedData ?? [],+ },+ ]}+ theme={nivoTheme}+ margin={{ top: 20, right: 20, bottom: 20, left: 40 }}+ xScale={{+ type: "time",+ format: "%Y-%m-%d %H:%M:%S",+ precision: "second",+ useUTC: true,+ }}+ yScale={{+ type: "linear",+ min: 0,+ stacked: false,+ reverse: false,+ max: max,+ }}+ enableGridX={false}+ enableGridY={false}+ yFormat=" >-.2f"+ axisTop={null}+ axisRight={null}+ axisBottom={{+ tickSize: 0,+ tickPadding: 10,+ tickRotation: 0,+ truncateTickAt: 0,+ tickValues: 0,+ format: (value) => {+ if (time.mode === "day") {+ return DateTime.fromJSDate(value).toFormat("ha");+ } else if (time.mode === "range") {+ return DateTime.fromJSDate(value).toFormat("MMM d");+ } else if (time.mode === "week") {+ return DateTime.fromJSDate(value).toFormat("MMM d");+ } else if (time.mode === "month") {+ return DateTime.fromJSDate(value).toFormat("MMM d");+ }+ },+ }}+ axisLeft={{+ tickSize: 0,+ tickPadding: 10,+ tickRotation: 0,+ truncateTickAt: 0,+ tickValues: 0,+ }}+ enableTouchCrosshair={true}+ enablePoints={false}+ useMesh={true}+ motionConfig="stiff"+ enableSlices={"x"}+ colors={["hsl(var(--neutral-700))"]}+ // sliceTooltip={({ slice }) => {+ // // if (isPrevious) return null;+ // return (+ // <div className="text-sm bg-neutral-900 p-2 rounded-md">+ // <div>+ // {DateTime.fromJSDate(+ // slice.points[0].data.x as any+ // ).toLocaleString(DateTime.DATETIME_SHORT)}+ // </div>+ // <div>+ // {round(Number(slice.points[0].data.yFormatted)).toLocaleString()}+ // </div>+ // </div>+ // );+ // }}++ // layers={["grid", "markers", "areas", "", "lines", "points", "slices", "axes", "legends"]}+ />+ );+}diff --git a/client/src/lib/nivo.ts b/client/src/lib/nivo.tsnew file mode 100644index 000000000..f4a97af30--- /dev/null+++ b/client/src/lib/nivo.ts@@ -0,0 +1,47 @@+import { Theme } from "@nivo/core";++export const nivoTheme: Theme = {+ axis: {+ legend: {+ text: {+ fill: "hsl(var(--neutral-400))",+ },+ },+ ticks: {+ line: {},+ text: {+ fill: "hsl(var(--neutral-400))",+ },+ },+ },+ grid: {+ line: {+ stroke: "hsl(var(--neutral-800))",+ strokeWidth: 1,+ },+ },+ tooltip: {+ basic: {+ fontFamily: "Roboto Mono",+ },+ container: {+ backdropFilter: "blur( 7px )",+ background: "rgb(40, 40, 40, 0.8)",+ color: "rgb(255, 255, 255)",+ },+ },+ crosshair: { line: { stroke: "hsl(var(--neutral-50))" } },+ annotations: {+ text: {+ fill: "hsl(var(--neutral-400))",+ },+ },+ text: {+ fill: "hsl(var(--neutral-400))",+ },+ labels: {+ text: {+ fill: "hsl(var(--neutral-400))",+ },+ },+};diff --git a/docker-compose.yml b/docker-compose.ymlindex c710eda54..07a3d6c41 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -33,7 +33,7 @@ services:ports:- "3001:3001"environment:- - NODE_ENV=development+ - NODE_ENV=production- CLICKHOUSE_HOST=http://clickhouse:8123- CLICKHOUSE_DB=analytics- POSTGRES_HOST=postgresdiff --git a/server/src/api/getPageViews.ts b/server/src/api/getPageViews.tsindex 8105cee77..f2a2968e6 100644--- a/server/src/api/getPageViews.ts+++ b/server/src/api/getPageViews.ts@@ -39,6 +39,8 @@ export async function getPageViews(time ASC`;+ console.info(query);+try {const result = await clickhouse.query({query,