🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
"use client";
import type { Annotation } from "@rybbit/shared";
import { DateTime } from "luxon";
import { useExtracted } from "next-intl";
import { useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import type { GetOverviewBucketedResponse } from "../../../../../api/analytics/endpoints";
import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
import { TimeSeriesChart } from "../../../../../components/charts/TimeSeriesChart";
import type { TimeSeriesChartPoint } from "../../../../../components/charts/TimeSeriesChart";
import { bucketsBetween, getChartTimeBounds, shiftBuckets } from "../../../../../components/charts/timeSeriesChartUtils";
import { formatChartDateTime } from "../../../../../lib/dateTimeUtils";
import { getTimezone, useStore } from "../../../../../lib/store";
import type { StatType } from "../../../../../lib/store";
import { formatSecondsAsMinutesAndSeconds } from "../../../../../lib/utils";
import { useDeleteAnnotation } from "@/api/analytics/hooks/useAnnotations";
import { ConfirmationModal } from "@/components/ConfirmationModal";
import { toast } from "@/components/ui/sonner";
import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
import { AnnotationHoverCard, AnnotationPopoverContent } from "./annotations/AnnotationDetails";
import { AnnotationPins } from "./annotations/AnnotationPins";
import type { AnnotationCluster } from "./annotations/annotationUtils";
import { useAnnotationPermissions } from "./annotations/useAnnotationPermissions";
type Point = TimeSeriesChartPoint & {
currentTime: DateTime;
};
type PrevPoint = TimeSeriesChartPoint & {
originalTime: DateTime;
};
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();
};
type PinTarget = { cluster: AnnotationCluster; rect: DOMRect };
export function Chart({
data,
previousData,
max,
chartXMax,
annotations = [],
onCreateAnnotation,
onEditAnnotation,
}: {
data: GetOverviewBucketedResponse | undefined;
previousData: GetOverviewBucketedResponse | undefined;
max: number;
chartXMax: Date | undefined;
annotations?: Annotation[];
/** Set when the viewer may create; a click on the plot opens the form at that bucket. */
onCreateAnnotation?: (date: Date) => void;
onEditAnnotation?: (annotation: Annotation) => void;
}) {
const t = useExtracted();
const { time, bucket, selectedStat, previousTime, site } = useStore();
const { canManage } = useAnnotationPermissions();
const deleteAnnotation = useDeleteAnnotation();
const [hoveredPin, setHoveredPin] = useState<PinTarget | null>(null);
const [selectedPin, setSelectedPin] = useState<PinTarget | null>(null);
const [pendingDelete, setPendingDelete] = useState<Annotation | null>(null);
// The popover anchors to a snapshot of the pin's screen rect; once the
// window, bucket, site, or data changes the pin has moved or gone.
useEffect(() => {
setSelectedPin(null);
setHoveredPin(null);
}, [time, bucket, site, annotations]);
const confirmDelete = async () => {
if (!pendingDelete) return;
try {
await deleteAnnotation.mutateAsync({ siteId: site, annotationId: pendingDelete.annotationId });
toast.success(t("Annotation deleted"));
} catch (error) {
toast.error(error instanceof Error ? error.message : t("Could not delete the annotation"));
}
setPendingDelete(null);
setSelectedPin(null);
};
const timezone = getTimezone();
const isExactRange = time.mode === "range" && Boolean(time.startTime && time.endTime);
const { current, previous, chartMin, chartMax, displayDashed } = useMemo(() => {
const { min: cMin, max: boundsMax } = getChartTimeBounds(time, bucket, timezone);
const now = DateTime.now();
const lowerBoundMs = cMin?.getTime();
const upperBoundMs = (boundsMax ?? now.toJSDate()).getTime();
// Filter against strict period bounds so stale transition data does not
// bleed onto the new x-axis during goBack/goForward.
const currentPoints: Point[] = [];
data?.forEach(e => {
const ts = DateTime.fromSQL(e.time, { zone: timezone }).toUTC();
if (ts > now) return;
const tsMs = ts.toMillis();
if (lowerBoundMs !== undefined && tsMs < lowerBoundMs) return;
if (tsMs > upperBoundMs) return;
currentPoints.push({
x: ts.toJSDate(),
y: Number(e[selectedStat] ?? 0),
currentTime: ts,
});
});
// For all-time and other unbounded modes, derive the left edge from data
// so the x-axis is not a dummy [0,1] domain.
const dataMin = currentPoints.length ? currentPoints[0].x : undefined;
const dataMax = currentPoints.length ? currentPoints[currentPoints.length - 1].x : undefined;
const chartXMaxMs = chartXMax?.getTime();
const boundedChartXMax =
chartXMax &&
chartXMaxMs !== undefined &&
(lowerBoundMs === undefined || chartXMaxMs >= lowerBoundMs) &&
chartXMaxMs <= upperBoundMs
? chartXMax
: undefined;
const effChartMin = cMin ?? dataMin;
const effChartMax = boundedChartXMax ?? boundsMax ?? dataMax ?? now.toJSDate();
// Previous points are shifted onto the current period's x-axis by a whole
// number of buckets (first bucket onto first bucket), not by the period's
// length: a 60-day period is not a whole number of weeks or months, so a
// raw offset lands week/month buckets between the current ones. They keep
// originalTime so the tooltip can show the real previous date.
const prevMin = previousTime ? getChartTimeBounds(previousTime, bucket, timezone).min : undefined;
const bucketShift =
cMin && prevMin
? bucketsBetween(
DateTime.fromJSDate(prevMin, { zone: timezone }),
DateTime.fromJSDate(cMin, { zone: timezone }),
bucket
)
: 0;
const previousPoints: PrevPoint[] = [];
previousData?.forEach(e => {
const prevTs = DateTime.fromSQL(e.time, { zone: timezone }).toUTC();
const mappedMs = shiftBuckets(prevTs.setZone(timezone), bucket, bucketShift).toMillis();
if (lowerBoundMs !== undefined && mappedMs < lowerBoundMs) return;
if (mappedMs > upperBoundMs) return;
previousPoints.push({
x: new Date(mappedMs),
y: Number(e[selectedStat] ?? 0),
originalTime: prevTs,
});
});
const currentDayStr = DateTime.now().toISODate();
const currentMonthStr = DateTime.now().toFormat("yyyy-MM-01");
const shouldNotDisplay =
time.mode === "all-time" ||
isExactRange ||
time.mode === "year" ||
(time.mode === "month" && time.month !== currentMonthStr) ||
(time.mode === "day" && time.day !== currentDayStr) ||
(time.mode === "range" && time.endDate !== currentDayStr) ||
(time.mode === "day" && (bucket === "minute" || bucket === "five_minutes")) ||
(time.mode === "past-minutes" && (bucket === "minute" || bucket === "five_minutes"));
const dashed = currentPoints.length >= 2 && !shouldNotDisplay;
return {
current: currentPoints,
previous: previousPoints,
chartMin: effChartMin,
chartMax: effChartMax,
displayDashed: dashed,
};
}, [data, previousData, selectedStat, time, previousTime, bucket, timezone, chartXMax, isExactRange]);
const hoverLeft =
hoveredPin && typeof window !== "undefined" ? Math.min(hoveredPin.rect.right + 8, window.innerWidth - 272) : 0;
return (
<>
<TimeSeriesChart
current={current}
previous={previous}
max={max}
chartMin={chartMin}
chartMax={chartMax}
displayDashed={displayDashed}
onPlotClick={onCreateAnnotation}
renderOverlay={context =>
annotations.length ? (
<AnnotationPins
context={context}
annotations={annotations}
bucket={bucket}
selectedKey={selectedPin?.cluster.key ?? null}
onSelect={(cluster, rect) => {
setHoveredPin(null);
setSelectedPin({ cluster, rect });
}}
onHover={(cluster, rect) => setHoveredPin(cluster && rect ? { cluster, rect } : null)}
/>
) : null
}
renderTooltip={({ point, previousPoint, bucket }) => {
const hoverCurrentY = point.y;
const hoverPreviousY = previousPoint?.y ?? 0;
const hoverDiff = hoverCurrentY - hoverPreviousY;
const hoverDiffPct = previousPoint && hoverPreviousY ? (hoverDiff / hoverPreviousY) * 100 : null;
return (
<ChartTooltip>
{hoverDiffPct !== null && (
<div
className="text-base font-medium px-2 pt-1.5 pb-1"
style={{
color: hoverDiffPct > 0 ? "hsl(var(--green-400))" : "hsl(var(--red-400))",
}}
>
{hoverDiffPct > 0 ? "+" : ""}
{hoverDiffPct.toFixed(2)}%
</div>
)}
<div className="w-full h-px bg-neutral-100 dark:bg-neutral-750" />
<div className="m-2 flex flex-col gap-1">
<div className="flex justify-between gap-3 text-sm">
<div className="flex items-center gap-2 min-w-0">
<div className="w-1 h-3 rounded-[3px] bg-dataviz shrink-0" />
<span className="truncate">{formatChartDateTime(point.currentTime, bucket)}</span>
</div>
<div className="shrink-0">{formatTooltipValue(hoverCurrentY, selectedStat)}</div>
</div>
{previousPoint && (
<div className="flex justify-between gap-3 text-sm text-muted-foreground">
<div className="flex items-center gap-2 min-w-0">
<div className="w-1 h-3 rounded-[3px] bg-neutral-200 dark:bg-neutral-750 shrink-0" />
<span className="truncate">{formatChartDateTime(previousPoint.originalTime, bucket)}</span>
</div>
<div className="shrink-0">{formatTooltipValue(hoverPreviousY, selectedStat)}</div>
</div>
)}
</div>
</ChartTooltip>
);
}}
/>
{hoveredPin &&
!selectedPin &&
typeof document !== "undefined" &&
createPortal(
<div
style={{
position: "fixed",
left: hoverLeft,
top: Math.max(8, hoveredPin.rect.top - 6),
pointerEvents: "none",
zIndex: 9999,
}}
>
<AnnotationHoverCard cluster={hoveredPin.cluster} />
</div>,
document.body
)}
{selectedPin && (
<Popover open onOpenChange={open => !open && setSelectedPin(null)}>
<PopoverAnchor virtualRef={{ current: { getBoundingClientRect: () => selectedPin.rect } }} />
<PopoverContent side="top" align="start" className="w-80 p-0">
<AnnotationPopoverContent
cluster={selectedPin.cluster}
canManage={canManage}
onEdit={annotation => {
setSelectedPin(null);
onEditAnnotation?.(annotation);
}}
onDelete={annotation => setPendingDelete(annotation)}
/>
</PopoverContent>
</Popover>
)}
<ConfirmationModal
title={t("Delete annotation")}
description={
pendingDelete
? t("Delete “{title}”? This cannot be undone.", { title: pendingDelete.title })
: ""
}
isOpen={!!pendingDelete}
setIsOpen={open => !open && setPendingDelete(null)}
onConfirm={confirmDelete}
primaryAction={{ variant: "destructive", children: t("Delete") }}
/>
</>
);
}