Skip to content

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

fix(chart): align previous period on week/month buckets, keep first partial bucket (#1169)

Goldflag46d99acd06fb
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index 32c7b15a4..f4434d1be 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -10,7 +10,7 @@ import type { GetOverviewBucketedResponse } from "../../../../../api/analytics/e
import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
import { TimeSeriesChart } from "../../../../../components/charts/TimeSeriesChart";
import type { TimeSeriesChartPoint } from "../../../../../components/charts/TimeSeriesChart";
-import { getChartTimeBounds } from "../../../../../components/charts/timeSeriesChartUtils";
+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";
@@ -125,14 +125,24 @@ export function Chart({
const effChartMin = cMin ?? dataMin;
const effChartMax = boundedChartXMax ?? boundsMax ?? dataMax ?? now.toJSDate();
- // Previous points are time-shifted onto the current period's x-axis, but
- // keep originalTime so the tooltip can show the real previous date.
+ // 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 offsetMs = cMin && prevMin ? cMin.getTime() - prevMin.getTime() : 0;
+ 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 = prevTs.toMillis() + offsetMs;
+ const mappedMs = shiftBuckets(prevTs.setZone(timezone), bucket, bucketShift).toMillis();
if (lowerBoundMs !== undefined && mappedMs < lowerBoundMs) return;
if (mappedMs > upperBoundMs) return;
previousPoints.push({
diff --git a/client/src/components/charts/timeSeriesChartUtils.test.ts b/client/src/components/charts/timeSeriesChartUtils.test.ts
index ca80137c0..416a91f3a 100644
--- a/client/src/components/charts/timeSeriesChartUtils.test.ts
+++ b/client/src/components/charts/timeSeriesChartUtils.test.ts
@@ -1,7 +1,7 @@
import { DateTime } from "luxon";
import { describe, expect, it } from "vitest";
import { Time } from "../DateSelector/types";
-import { getChartTimeBounds } from "./timeSeriesChartUtils";
+import { bucketsBetween, getChartTimeBounds, shiftBuckets } from "./timeSeriesChartUtils";
const ZONE = "America/New_York";
@@ -61,6 +61,30 @@ describe("getChartTimeBounds", () => {
});
});
+ it("range: starts on the bucket holding the start date, for week and month buckets", () => {
+ // Last 60 days from 2026-09-02 starts on a Saturday; the API's first week
+ // bucket is the Sunday before it and the first month bucket is July 1.
+ const last60 = { mode: "range", startDate: "2026-07-05", endDate: "2026-09-02" } as const;
+ expect(boundsIso(last60, "week")).toEqual({
+ min: "2026-07-05T00:00:00.000-04:00",
+ max: "2026-08-31T00:00:00.000-04:00",
+ });
+ expect(boundsIso({ ...last60, startDate: "2026-07-04" }, "week").min).toBe("2026-06-28T00:00:00.000-04:00");
+ expect(boundsIso({ ...last60, startDate: "2026-07-04" }, "month")).toEqual({
+ min: "2026-07-01T00:00:00.000-04:00",
+ max: "2026-09-01T00:00:00.000-04:00",
+ });
+ });
+
+ it("exact range: starts on the hour bucket holding the start time", () => {
+ expect(
+ boundsIso(
+ { mode: "range", startDate: "2026-08-19", endDate: "2026-08-19", startTime: "09:15:00", endTime: "17:45:00" },
+ "hour"
+ ).min
+ ).toBe("2026-08-19T09:00:00.000-04:00");
+ });
+
it("exact range: ends on the last bucket inside the exclusive end", () => {
const exact = {
mode: "range",
@@ -75,3 +99,32 @@ describe("getChartTimeBounds", () => {
);
});
});
+
+describe("bucketsBetween / shiftBuckets", () => {
+ const at = (iso: string) => DateTime.fromISO(iso, { zone: ZONE });
+
+ it("counts whole weeks between the two periods' first buckets, whichever weekday convention floored them", () => {
+ // 60-day period starting Sat Jul 4 (first bucket Sun Jun 28) vs its
+ // previous period starting Tue May 5 (first bucket Sun May 3): 8 weeks,
+ // not 60 days.
+ expect(bucketsBetween(at("2026-05-03"), at("2026-06-28"), "week")).toBe(8);
+ expect(bucketsBetween(at("2026-05-04"), at("2026-06-28"), "week")).toBe(8);
+ });
+
+ it("shifts month buckets by calendar months so they land on month starts", () => {
+ expect(bucketsBetween(at("2026-05-01"), at("2026-07-01"), "month")).toBe(2);
+ expect(shiftBuckets(at("2026-05-01"), "month", 2).toISO()).toBe(at("2026-07-01").toISO());
+ expect(shiftBuckets(at("2026-06-01"), "month", 2).toISO()).toBe(at("2026-08-01").toISO());
+ expect(shiftBuckets(at("2026-07-01"), "month", 2).toISO()).toBe(at("2026-09-01").toISO());
+ });
+
+ it("keeps day buckets on midnight across a DST change", () => {
+ expect(shiftBuckets(at("2026-10-25"), "day", 14).toISO()).toBe("2026-11-08T00:00:00.000-05:00");
+ expect(bucketsBetween(at("2026-10-25"), at("2026-11-08"), "day")).toBe(14);
+ });
+
+ it("handles sub-hour buckets", () => {
+ expect(bucketsBetween(at("2026-08-19T09:00"), at("2026-08-19T09:30"), "five_minutes")).toBe(6);
+ expect(shiftBuckets(at("2026-08-19T09:00"), "fifteen_minutes", 2).toFormat("HH:mm")).toBe("09:30");
+ });
+});
diff --git a/client/src/components/charts/timeSeriesChartUtils.ts b/client/src/components/charts/timeSeriesChartUtils.ts
index 9e468d610..6910743ac 100644
--- a/client/src/components/charts/timeSeriesChartUtils.ts
+++ b/client/src/components/charts/timeSeriesChartUtils.ts
@@ -3,30 +3,52 @@ import { DateTime } from "luxon";
import type { Time } from "@/components/DateSelector/types";
-export const stepBucket = (dt: DateTime, bucket: TimeBucket, direction: 1 | -1): DateTime => {
- const n = direction;
+const bucketUnit = (bucket: TimeBucket): { unit: "minutes" | "hours" | "days" | "weeks" | "months" | "years"; size: number } => {
switch (bucket) {
case "minute":
- return dt.plus({ minutes: n });
+ return { unit: "minutes", size: 1 };
case "five_minutes":
- return dt.plus({ minutes: 5 * n });
+ return { unit: "minutes", size: 5 };
case "ten_minutes":
- return dt.plus({ minutes: 10 * n });
+ return { unit: "minutes", size: 10 };
case "fifteen_minutes":
- return dt.plus({ minutes: 15 * n });
+ return { unit: "minutes", size: 15 };
case "hour":
- return dt.plus({ hours: n });
+ return { unit: "hours", size: 1 };
case "day":
- return dt.plus({ days: n });
+ return { unit: "days", size: 1 };
case "week":
- return dt.plus({ weeks: n });
+ return { unit: "weeks", size: 1 };
case "month":
- return dt.plus({ months: n });
+ return { unit: "months", size: 1 };
case "year":
- return dt.plus({ years: n });
+ return { unit: "years", size: 1 };
}
};
+/**
+ * Moves `dt` by `n` whole buckets in calendar terms, so a month step lands on
+ * the next month's start and a day step survives a DST change — neither of
+ * which a millisecond offset does.
+ */
+export const shiftBuckets = (dt: DateTime, bucket: TimeBucket, n: number): DateTime => {
+ const { unit, size } = bucketUnit(bucket);
+ return dt.plus({ [unit]: n * size });
+};
+
+export const stepBucket = (dt: DateTime, bucket: TimeBucket, direction: 1 | -1): DateTime =>
+ shiftBuckets(dt, bucket, direction);
+
+/**
+ * How many whole buckets separate two bucket-aligned instants. Rounded, so the
+ * two week conventions (see `floorToWeekStart`) disagreeing by a day still
+ * count the same number of weeks.
+ */
+export const bucketsBetween = (from: DateTime, to: DateTime, bucket: TimeBucket): number => {
+ const { unit, size } = bucketUnit(bucket);
+ return Math.round(to.diff(from, unit).get(unit) / size);
+};
+
export const floorToBucket = (dt: DateTime, bucket: TimeBucket): DateTime => {
switch (bucket) {
case "minute":
@@ -158,6 +180,18 @@ const floorToWeekStart = (dt: DateTime): DateTime => {
const floorToBucketStart = (dt: DateTime, bucket: TimeBucket): DateTime =>
bucket === "week" ? floorToWeekStart(dt) : floorToBucket(dt, bucket);
+/**
+ * The start of the bucket holding `start` — the left edge of the x domain.
+ * A period rarely starts on a week or month boundary ("last 60 days"), and
+ * the API reports its first bucket at the boundary *before* the period start;
+ * anchoring the domain at the period start instead put that bucket left of
+ * the axis, where every chart drops it. Weeks floor to the Sunday the analytics
+ * queries use (`toStartOfWeek`); the Monday convention's first bucket then sits
+ * a day inside the edge, which is only a day of leading gutter.
+ */
+const firstBucketStart = (start: DateTime, bucket: TimeBucket): DateTime =>
+ bucket === "week" ? start.startOf("day").minus({ days: start.weekday % 7 }) : floorToBucket(start, bucket);
+
/**
* The start of the final bucket in `[start, endExclusive)`. Bounds end there
* rather than at the period's last millisecond so the closing tick sits on the
@@ -188,17 +222,19 @@ export const getChartTimeBounds = (time: Time, bucket: TimeBucket, timezone: str
if (time.mode === "day") {
const day = DateTime.fromISO(time.day, { zone: timezone }).startOf("day");
+ const min = firstBucketStart(day, bucket);
return {
- min: day.toJSDate(),
- max: lastBucketStart(day, day.plus({ days: 1 }), bucket),
+ min: min.toJSDate(),
+ max: lastBucketStart(min, day.plus({ days: 1 }), bucket),
};
}
if (time.mode === "week") {
const week = DateTime.fromISO(time.week, { zone: timezone }).startOf("week");
+ const min = firstBucketStart(week, bucket);
return {
- min: week.toJSDate(),
- max: lastBucketStart(week, week.plus({ weeks: 1 }), bucket),
+ min: min.toJSDate(),
+ max: lastBucketStart(min, week.plus({ weeks: 1 }), bucket),
};
}
@@ -206,17 +242,19 @@ export const getChartTimeBounds = (time: Time, bucket: TimeBucket, timezone: str
const month = DateTime.fromISO(time.month, {
zone: timezone,
}).startOf("month");
+ const min = firstBucketStart(month, bucket);
return {
- min: month.toJSDate(),
- max: lastBucketStart(month, month.plus({ months: 1 }), bucket),
+ min: min.toJSDate(),
+ max: lastBucketStart(min, month.plus({ months: 1 }), bucket),
};
}
if (time.mode === "year") {
const year = DateTime.fromISO(time.year, { zone: timezone }).startOf("year");
+ const min = firstBucketStart(year, bucket);
return {
- min: year.toJSDate(),
- max: lastBucketStart(year, year.plus({ years: 1 }), bucket),
+ min: min.toJSDate(),
+ max: lastBucketStart(min, year.plus({ years: 1 }), bucket),
};
}
@@ -226,17 +264,19 @@ export const getChartTimeBounds = (time: Time, bucket: TimeBucket, timezone: str
zone: timezone,
});
const endExclusive = DateTime.fromISO(`${time.endDate}T${time.endTime}`, { zone: timezone });
+ const min = firstBucketStart(start, bucket);
return {
- min: start.toJSDate(),
- max: lastBucketStart(start, endExclusive, bucket),
+ min: min.toJSDate(),
+ max: lastBucketStart(min, endExclusive, bucket),
};
}
const start = DateTime.fromISO(time.startDate, { zone: timezone }).startOf("day");
const endExclusive = DateTime.fromISO(time.endDate, { zone: timezone }).startOf("day").plus({ days: 1 });
+ const min = firstBucketStart(start, bucket);
return {
- min: start.toJSDate(),
- max: lastBucketStart(start, endExclusive, bucket),
+ min: min.toJSDate(),
+ max: lastBucketStart(min, endExclusive, bucket),
};
}