🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Refactor Chart component for improved tooltip handling and bucket offset calculations
Bill Yang09ee61ea8786
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsxindex e2d3256ff..aa520afc2 100644--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx@@ -9,9 +9,18 @@ import { useTheme } from "next-themes";import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGetOverviewBucketed";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 { 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;const getMax = (time: Time, bucket: TimeBucket) => {const now = DateTime.now();@@ -21,59 +30,23 @@ const getMax = (time: Time, bucket: TimeBucket) => {}return undefined;} 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,- });+ const dayDate = DateTime.fromISO(time.day).endOf("day").minus({ minutes: getBucketMinutesOffset(bucket) });return now < dayDate ? dayDate.toJSDate() : undefined;} else if (time.mode === "range") {if (bucket === "day" || bucket === "week" || bucket === "month" || bucket === "year") {return undefined;}- 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,- });+ const rangeDate = DateTime.fromISO(time.endDate).endOf("day").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");@@ -107,16 +80,6 @@ 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> = {@@ -137,6 +100,45 @@ type SeriesConfig = {color: string;};+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 }}+ />+ );+ });+ };+export function Chart({data,previousData,@@ -254,40 +256,8 @@ export function Chart({});});- const StackedLines = ({ 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 DashedOverlay = ({ 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 StackedLines = createStackedLines(displayDashed);+ const DashedOverlay = createDashedOverlay(displayDashed);return (<ResponsiveLine@@ -359,149 +329,18 @@ export function Chart({areaOpacity={0.3}defs={chartPropsDefs}fill={chartPropsFill}- sliceTooltip={({ slice }: any) => {- // 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>- );- }}+ 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",diff --git a/client/src/app/[site]/main/components/MainSection/ChartSliceTooltip.tsx b/client/src/app/[site]/main/components/MainSection/ChartSliceTooltip.tsxnew file mode 100644index 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>+ );+}