🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance time bucket functionality in Chart and BucketSelection components
Bill Yang82aa6923cc19
diff --git a/client/messages/cs.json b/client/messages/cs.jsonindex 29ff01334..9ebd92079 100644--- a/client/messages/cs.json+++ b/client/messages/cs.json@@ -963,12 +963,13 @@"B/KqCS": "Aktivní {time}","A4AHkc": "min","JIOFW/": "5 min",+ "6uQnsi": "10 min","IoiMPE": "15 min","b11WUZ": "Hodina","7pXrnq": "Den","sd2ieZ": "Týden","TBovrx": "Měsíc",- "6uQnsi": "10 min",+ "IFo1oo": "","CNXQN5": "Kopírovat kód","gQxpo2": "Organizace úspěšně vytvořena","bWerAD": "Název a slug organizace jsou povinné",diff --git a/client/messages/de.json b/client/messages/de.jsonindex b02b43f33..f5ef6ec60 100644--- a/client/messages/de.json+++ b/client/messages/de.json@@ -963,12 +963,13 @@"B/KqCS": "Aktiv {time}","A4AHkc": "Min","JIOFW/": "5 Min",+ "6uQnsi": "10 Min","IoiMPE": "15 Min","b11WUZ": "Stunde","7pXrnq": "Tag","sd2ieZ": "Woche","TBovrx": "Monat",- "6uQnsi": "10 Min",+ "IFo1oo": "","CNXQN5": "Code kopieren","gQxpo2": "Organisation erfolgreich erstellt","bWerAD": "Organisationsname und Slug sind erforderlich",diff --git a/client/messages/en.json b/client/messages/en.jsonindex eaa28f1ca..5f0e51ce9 100644--- a/client/messages/en.json+++ b/client/messages/en.json@@ -963,12 +963,13 @@"B/KqCS": "Active {time}","A4AHkc": "Min","JIOFW/": "5 Min",+ "6uQnsi": "10 Min","IoiMPE": "15 Min","b11WUZ": "Hour","7pXrnq": "Day","sd2ieZ": "Week","TBovrx": "Month",- "6uQnsi": "10 Min",+ "IFo1oo": "Year","CNXQN5": "Copy code","gQxpo2": "Organization created successfully","bWerAD": "Organization name and slug are required",diff --git a/client/messages/es.json b/client/messages/es.jsonindex 020ecae93..dc72718b3 100644--- a/client/messages/es.json+++ b/client/messages/es.json@@ -963,12 +963,13 @@"B/KqCS": "Activo {time}","A4AHkc": "min","JIOFW/": "5 min",+ "6uQnsi": "10 min","IoiMPE": "15 min","b11WUZ": "hora","7pXrnq": "día","sd2ieZ": "semana","TBovrx": "mes",- "6uQnsi": "10 min",+ "IFo1oo": "","CNXQN5": "Copiar código","gQxpo2": "Organización creada correctamente","bWerAD": "El nombre de la organización y el slug son obligatorios",diff --git a/client/messages/fr.json b/client/messages/fr.jsonindex 704738af0..a2e09cd60 100644--- a/client/messages/fr.json+++ b/client/messages/fr.json@@ -963,12 +963,13 @@"B/KqCS": "Actif {time}","A4AHkc": "min","JIOFW/": "5 min",+ "6uQnsi": "10 min","IoiMPE": "15 min","b11WUZ": "heure","7pXrnq": "jour","sd2ieZ": "semaine","TBovrx": "mois",- "6uQnsi": "10 min",+ "IFo1oo": "","CNXQN5": "Copier le code","gQxpo2": "Organisation créée avec succès","bWerAD": "Le nom et le slug de l'organisation sont requis",diff --git a/client/messages/it.json b/client/messages/it.jsonindex 7be490f9e..58b935adc 100644--- a/client/messages/it.json+++ b/client/messages/it.json@@ -963,12 +963,13 @@"B/KqCS": "Attivo {time}","A4AHkc": "min","JIOFW/": "5 min",+ "6uQnsi": "10 min","IoiMPE": "15 min","b11WUZ": "ora","7pXrnq": "giorno","sd2ieZ": "settimana","TBovrx": "mese",- "6uQnsi": "10 min",+ "IFo1oo": "","CNXQN5": "Copia codice","gQxpo2": "Organizzazione creata con successo","bWerAD": "Il nome e lo slug dell'organizzazione sono obbligatori",diff --git a/client/messages/ja.json b/client/messages/ja.jsonindex 43c97a038..b6fb37212 100644--- a/client/messages/ja.json+++ b/client/messages/ja.json@@ -963,12 +963,13 @@"B/KqCS": "{time}にアクティブ","A4AHkc": "分","JIOFW/": "5分",+ "6uQnsi": "10分","IoiMPE": "15分","b11WUZ": "時間","7pXrnq": "日","sd2ieZ": "週","TBovrx": "月",- "6uQnsi": "10分",+ "IFo1oo": "","CNXQN5": "コードをコピー","gQxpo2": "組織を作成しました","bWerAD": "組織名とスラッグは必須です",diff --git a/client/messages/ko.json b/client/messages/ko.jsonindex e6f04b830..41c4689a3 100644--- a/client/messages/ko.json+++ b/client/messages/ko.json@@ -963,12 +963,13 @@"B/KqCS": "{time} 활성","A4AHkc": "분","JIOFW/": "5분",+ "6uQnsi": "10분","IoiMPE": "15분","b11WUZ": "시간","7pXrnq": "일","sd2ieZ": "주","TBovrx": "월",- "6uQnsi": "10분",+ "IFo1oo": "","CNXQN5": "코드 복사","gQxpo2": "조직이 성공적으로 생성되었습니다","bWerAD": "조직 이름과 슬러그는 필수입니다",diff --git a/client/messages/pl.json b/client/messages/pl.jsonindex 6ede83a51..c843b21ad 100644--- a/client/messages/pl.json+++ b/client/messages/pl.json@@ -963,12 +963,13 @@"B/KqCS": "Aktywny {time}","A4AHkc": "min","JIOFW/": "5 min",+ "6uQnsi": "10 min","IoiMPE": "15 min","b11WUZ": "godzina","7pXrnq": "dzień","sd2ieZ": "tydzień","TBovrx": "miesiąc",- "6uQnsi": "10 min",+ "IFo1oo": "","CNXQN5": "Kopiuj kod","gQxpo2": "Organizacja utworzona pomyślnie","bWerAD": "Nazwa i identyfikator organizacji są wymagane",diff --git a/client/messages/pt.json b/client/messages/pt.jsonindex bd20317dc..91eeb7a1b 100644--- a/client/messages/pt.json+++ b/client/messages/pt.json@@ -963,12 +963,13 @@"B/KqCS": "Ativo {time}","A4AHkc": "min","JIOFW/": "5 min",+ "6uQnsi": "10 min","IoiMPE": "15 min","b11WUZ": "hora","7pXrnq": "dia","sd2ieZ": "semana","TBovrx": "mês",- "6uQnsi": "10 min",+ "IFo1oo": "","CNXQN5": "Copiar código","gQxpo2": "Organização criada com sucesso","bWerAD": "Nome e slug da organização são obrigatórios",diff --git a/client/messages/uk.json b/client/messages/uk.jsonindex df7a2f7be..a8606a141 100644--- a/client/messages/uk.json+++ b/client/messages/uk.json@@ -963,12 +963,13 @@"B/KqCS": "Активні {time}","A4AHkc": "Мін.","JIOFW/": "5 Мін.",+ "6uQnsi": "10 Мін.","IoiMPE": "15 Мін.","b11WUZ": "Година","7pXrnq": "День","sd2ieZ": "Тиждень","TBovrx": "Місяць",- "6uQnsi": "10 Мін.",+ "IFo1oo": "","CNXQN5": "Скопіювати код","gQxpo2": "Організацію успішно створено","bWerAD": "Назва організації та slug є обов'язковими",diff --git a/client/messages/zh.json b/client/messages/zh.jsonindex 0f1bbe827..2f4dd3aff 100644--- a/client/messages/zh.json+++ b/client/messages/zh.json@@ -963,12 +963,13 @@"B/KqCS": "活动时间:{time}","A4AHkc": "分钟","JIOFW/": "5 分钟",+ "6uQnsi": "10 分钟","IoiMPE": "15 分钟","b11WUZ": "小时","7pXrnq": "天","sd2ieZ": "周","TBovrx": "月",- "6uQnsi": "10 分钟",+ "IFo1oo": "","CNXQN5": "复制代码","gQxpo2": "组织创建成功","bWerAD": "组织名称和标识符是必需的",diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsxindex 17fd77cf2..1a4f9d094 100644--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx@@ -88,6 +88,53 @@ const floorToBucket = (dt: DateTime, bucket: TimeBucket): DateTime => {}};+const floorToMinuteInterval = (dt: DateTime, minutes: number): DateTime =>+ dt.set({+ minute: Math.floor(dt.minute / minutes) * minutes,+ second: 0,+ millisecond: 0,+ });++const bucketMinuteInterval = (bucket: TimeBucket): number | null => {+ switch (bucket) {+ case "minute":+ return 1;+ case "five_minutes":+ return 5;+ case "ten_minutes":+ return 10;+ case "fifteen_minutes":+ return 15;+ case "hour":+ return 60;+ default:+ return null;+ }+};++const bucketDurationMinutes = (bucket: TimeBucket): number => {+ switch (bucket) {+ case "minute":+ return 1;+ case "five_minutes":+ return 5;+ case "ten_minutes":+ return 10;+ case "fifteen_minutes":+ return 15;+ case "hour":+ return 60;+ case "day":+ return 24 * 60;+ case "week":+ return 7 * 24 * 60;+ case "month":+ return 31 * 24 * 60;+ case "year":+ return 366 * 24 * 60;+ }+};+const canDragSelectBucket = (bucket: TimeBucket) =>bucket === "minute" ||bucket === "five_minutes" ||@@ -101,17 +148,23 @@ const getDragZoomBucket = (endExclusive: DateTime,sourceBucket: TimeBucket): TimeBucket | null => {+ let desiredBucket: TimeBucket | null = null;+if (sourceBucket === "day") {const days = Math.round(endExclusive.startOf("day").diff(start.startOf("day"), "days").days);- return days <= 3 ? "hour" : null;+ desiredBucket = days <= 3 ? "hour" : null;+ } else {+ const minutes = endExclusive.diff(start, "minutes").minutes;+ if (minutes <= 60) desiredBucket = "minute";+ else if (minutes <= 3 * 24 * 60) desiredBucket = "hour";}- const minutes = endExclusive.diff(start, "minutes").minutes;- if (minutes <= 60) return "minute";- if (minutes <= 3 * 24 * 60) return "hour";- return null;+ if (!desiredBucket) return null;+ return bucketDurationMinutes(desiredBucket) < bucketDurationMinutes(sourceBucket)+ ? desiredBucket+ : null;};type Point = {@@ -141,11 +194,15 @@ const formatXTick = (mode: Time["mode"],bucket: TimeBucket,pastMinutesStart: number | undefined,- isExactRange: boolean+ isExactRange: boolean,+ showMinutePrecision: boolean) => {const dt = DateTime.fromJSDate(date, { zone: "utc" }).setZone(getTimezone()).setLocale(userLocale);+ if (showMinutePrecision) {+ return dt.toFormat(hour12 ? "h:mm" : "HH:mm");+ }if (mode === "past-minutes") {if ((pastMinutesStart ?? 0) < 1440) {return dt.toFormat(hour12 ? "h:mm" : "HH:mm");@@ -223,6 +280,30 @@ export function Chart({const isExactRange = time.mode === "range" && Boolean(time.startTime && time.endTime);const clipId = useId().replace(/:/g, "");+ useEffect(() => {+ if (time.mode !== "range" || !time.startTime || !time.endTime) return;++ const start = DateTime.fromISO(`${time.startDate}T${time.startTime}`, {+ zone: timezone,+ });+ const end = DateTime.fromISO(`${time.endDate}T${time.endTime}`, {+ zone: timezone,+ });+ const minutes = end.diff(start, "minutes").minutes;+ if (minutes <= 0) return;++ const nextBucket =+ minutes <= 60+ ? "minute"+ : minutes <= 3 * 24 * 60 && !bucketMinuteInterval(bucket)+ ? "hour"+ : null;++ if (nextBucket && nextBucket !== bucket) {+ setBucket(nextBucket);+ }+ }, [bucket, setBucket, time, timezone]);+const wrapperRef = useRef<HTMLDivElement>(null);const [size, setSize] = useState<{ width: number; height: number }>({width: 0,@@ -363,6 +444,27 @@ export function Chart({(time.mode === "past-minutes" && time.pastMinutesStart === 1440)? Math.min(maxTicks, 24): maxTicks;+ const minuteTickInterval = useMemo(() => {+ if (!W || !chartMin || !chartMax || xTickCount <= 0) return null;+ if (!isExactRange && time.mode !== "past-minutes") return null;++ const minInterval = bucketMinuteInterval(bucket);+ if (!minInterval) return null;++ const durationMinutes = Math.ceil(+ (chartMax.getTime() - chartMin.getTime()) / 60_000+ );+ if (durationMinutes <= 0 || durationMinutes > 6 * 60) return null;++ for (const interval of [1, 5, 10, 15, 30, 60]) {+ if (interval < minInterval) continue;+ if (Math.floor(durationMinutes / interval) + 1 <= xTickCount) {+ return interval;+ }+ }++ return durationMinutes <= 2 * 60 && minInterval <= 30 ? 30 : null;+ }, [W, chartMin, chartMax, xTickCount, isExactRange, time.mode, bucket]);// Generate ticks spanning [chartMin, chartMax] aligned to bucket boundaries.// Anchored on the first current data point so ticks land where the API's@@ -376,6 +478,29 @@ export function Chart({const chartMinMs = chartMin.getTime();const chartMaxMs = chartMax.getTime();+ if (minuteTickInterval) {+ const min = DateTime.fromMillis(chartMinMs, { zone: "utc" }).setZone(+ timezone+ );+ const max = DateTime.fromMillis(chartMaxMs, { zone: "utc" }).setZone(+ timezone+ );+ const ticks: Date[] = [];+ let t = floorToMinuteInterval(min, minuteTickInterval);+ if (t.toMillis() < min.toMillis()) {+ t = t.plus({ minutes: minuteTickInterval });+ }++ let safety = 0;+ while (t.toMillis() <= max.toMillis() && safety < 10000) {+ ticks.push(t.toUTC().toJSDate());+ t = t.plus({ minutes: minuteTickInterval });+ safety++;+ }++ return ticks;+ }+const anchorMs = current.length ? current[0].x.getTime() : chartMinMs;const anchor = DateTime.fromMillis(anchorMs, { zone: "utc" }).setZone(timezone@@ -402,7 +527,16 @@ export function Chart({if (ticks.length <= xTickCount) return ticks;const stride = Math.max(1, Math.ceil(ticks.length / xTickCount));return ticks.filter((_, i) => i % stride === 0);- }, [W, chartMin, chartMax, xTickCount, current, bucket, timezone]);+ }, [+ W,+ chartMin,+ chartMax,+ xTickCount,+ minuteTickInterval,+ current,+ bucket,+ timezone,+ ]);// Cap vertical gridlines at 8 so dense ranges don't get noisy. Subsample// from xTicks so every gridline still aligns with a real label.@@ -809,7 +943,8 @@ export function Chart({time.mode === "past-minutes"? time.pastMinutesStart: undefined,- isExactRange+ isExactRange,+ minuteTickInterval !== null)}</text></g>diff --git a/client/src/components/BucketSelection.tsx b/client/src/components/BucketSelection.tsxindex 62c4bfc6a..cca88fda3 100644--- a/client/src/components/BucketSelection.tsx+++ b/client/src/components/BucketSelection.tsx@@ -2,117 +2,141 @@import { getTimezone, useStore } from "@/lib/store";import { SelectItem, Select, SelectContent, SelectTrigger, SelectValue } from "@/components/ui/select";+import { TimeBucket } from "@rybbit/shared";import { DateTime } from "luxon";import { useExtracted } from "next-intl";import { Time } from "./DateSelector/types";import { TimerReset } from "lucide-react";+const bucketDurationMinutes = (bucket: TimeBucket): number => {+ switch (bucket) {+ case "minute":+ return 1;+ case "five_minutes":+ return 5;+ case "ten_minutes":+ return 10;+ case "fifteen_minutes":+ return 15;+ case "hour":+ return 60;+ case "day":+ return 1440;+ case "week":+ return 7 * 1440;+ case "month":+ return 30 * 1440;+ case "year":+ return 365 * 1440;+ }+};++const getRangeDurationMinutes = (time: Time): number | null => {+ const timezone = getTimezone();++ if (time.mode === "past-minutes") {+ return time.pastMinutesStart - (time.pastMinutesEnd ?? 0);+ }++ if (time.mode === "day") return 1440;+ if (time.mode === "week") return 7 * 1440;++ if (time.mode === "month") {+ const start = DateTime.fromISO(time.month, { zone: timezone }).startOf("month");+ return start.plus({ months: 1 }).diff(start, "minutes").minutes;+ }++ if (time.mode === "year") {+ const start = DateTime.fromISO(time.year, { zone: timezone }).startOf("year");+ return start.plus({ years: 1 }).diff(start, "minutes").minutes;+ }++ if (time.mode === "range") {+ if (time.startTime && time.endTime) {+ return DateTime.fromISO(`${time.endDate}T${time.endTime}`, { zone: timezone }).diff(+ DateTime.fromISO(`${time.startDate}T${time.startTime}`, { zone: timezone }),+ "minutes"+ ).minutes;+ }++ return DateTime.fromISO(time.endDate, { zone: timezone })+ .plus({ days: 1 })+ .startOf("day")+ .diff(DateTime.fromISO(time.startDate, { zone: timezone }).startOf("day"), "minutes").minutes;+ }++ return null;+};+export function BucketSelection() {const t = useExtracted();const { bucket, setBucket, time } = useStore();+ const renderOptions = (options: TimeBucket[], durationMinutes: number | null) => {+ const availableOptions = options.filter(+ option => durationMinutes === null || durationMinutes >= bucketDurationMinutes(option) * 2+ );++ return (+ <SelectContent>+ {availableOptions.map(option => (+ <SelectItem key={option} size="sm" value={option}>+ {getBucketLabel(option)}+ </SelectItem>+ ))}+ </SelectContent>+ );+ };++ const getBucketLabel = (bucket: TimeBucket) => {+ switch (bucket) {+ case "minute":+ return t("Min");+ case "five_minutes":+ return t("5 Min");+ case "ten_minutes":+ return t("10 Min");+ case "fifteen_minutes":+ return t("15 Min");+ case "hour":+ return t("Hour");+ case "day":+ return t("Day");+ case "week":+ return t("Week");+ case "month":+ return t("Month");+ case "year":+ return t("Year");+ }+ };+const getOptions = (time: Time) => {+ const durationMinutes = getRangeDurationMinutes(time);+if (time.mode === "past-minutes") {const timeDiff = time.pastMinutesStart - (time.pastMinutesEnd ?? 0);if (time.pastMinutesStart >= 1440) {- return (- <SelectContent>- <SelectItem size="sm" value="minute">- {t("Min")}- </SelectItem>- <SelectItem size="sm" value="five_minutes">- {t("5 Min")}- </SelectItem>- <SelectItem size="sm" value="fifteen_minutes">- {t("15 Min")}- </SelectItem>- <SelectItem size="sm" value="hour">- {t("Hour")}- </SelectItem>- </SelectContent>- );+ return renderOptions(["minute", "five_minutes", "fifteen_minutes", "hour"], durationMinutes);}if (timeDiff > 120) {- return (- <SelectContent>- <SelectItem size="sm" value="hour">- {t("Hour")}- </SelectItem>- </SelectContent>- );+ return renderOptions(["hour"], durationMinutes);}// For shorter durations, exclude hour buckets- return (- <SelectContent>- <SelectItem size="sm" value="minute">- {t("Min")}- </SelectItem>- </SelectContent>- );+ return renderOptions(["minute"], durationMinutes);}if (time.mode === "day") {- return (- <SelectContent>- <SelectItem size="sm" value="minute">- {t("Min")}- </SelectItem>- <SelectItem size="sm" value="five_minutes">- {t("5 Min")}- </SelectItem>- <SelectItem size="sm" value="fifteen_minutes">- {t("15 Min")}- </SelectItem>- <SelectItem size="sm" value="hour">- {t("Hour")}- </SelectItem>- </SelectContent>- );+ return renderOptions(["minute", "five_minutes", "fifteen_minutes", "hour"], durationMinutes);}if (time.mode === "week") {- return (- <SelectContent>- <SelectItem size="sm" value="fifteen_minutes">- {t("15 Min")}- </SelectItem>- <SelectItem size="sm" value="hour">- {t("Hour")}- </SelectItem>- <SelectItem size="sm" value="day">- {t("Day")}- </SelectItem>- </SelectContent>- );+ return renderOptions(["fifteen_minutes", "hour", "day"], durationMinutes);}if (time.mode === "month") {- return (- <SelectContent>- <SelectItem size="sm" value="hour">- {t("Hour")}- </SelectItem>- <SelectItem size="sm" value="day">- {t("Day")}- </SelectItem>- <SelectItem size="sm" value="week">- {t("Week")}- </SelectItem>- </SelectContent>- );+ return renderOptions(["hour", "day", "week"], durationMinutes);}if (time.mode === "year" || time.mode === "all-time") {- return (- <SelectContent>- <SelectItem size="sm" value="day">- {t("Day")}- </SelectItem>- <SelectItem size="sm" value="week">- {t("Week")}- </SelectItem>- <SelectItem size="sm" value="month">- {t("Month")}- </SelectItem>- </SelectContent>- );+ return renderOptions(["day", "week", "month"], durationMinutes);}if (time.mode === "range") {@@ -132,50 +156,16 @@ export function BucketSelection() {"days").days + 1;- return (- <SelectContent>- {exactRangeMinutes !== undefined && timeRangeLength <= 1 && (- <SelectItem size="sm" value="minute">- {t("Min")}- </SelectItem>- )}- {timeRangeLength <= 7 && (- <SelectItem size="sm" value="five_minutes">- {t("5 Min")}- </SelectItem>- )}- {timeRangeLength <= 14 && (- <>- <SelectItem size="sm" value="ten_minutes">- {t("10 Min")}- </SelectItem>- <SelectItem size="sm" value="fifteen_minutes">- {t("15 Min")}- </SelectItem>- </>- )}- {timeRangeLength <= 30 && (- <SelectItem size="sm" value="hour">- {t("Hour")}- </SelectItem>- )}- {timeRangeLength >= 1 && (- <SelectItem size="sm" value="day">- {t("Day")}- </SelectItem>- )}- {timeRangeLength >= 28 && (- <SelectItem size="sm" value="week">- {t("Week")}- </SelectItem>- )}- {timeRangeLength >= 60 && (- <SelectItem size="sm" value="month">- {t("Month")}- </SelectItem>- )}- </SelectContent>- );+ const options: TimeBucket[] = [];+ if (timeRangeLength <= 1) options.push("minute");+ if (timeRangeLength <= 7) options.push("five_minutes");+ if (timeRangeLength <= 14) options.push("ten_minutes", "fifteen_minutes");+ if (timeRangeLength <= 30) options.push("hour");+ if (timeRangeLength >= 1) options.push("day");+ if (timeRangeLength >= 28) options.push("week");+ if (timeRangeLength >= 60) options.push("month");++ return renderOptions(options, durationMinutes);}};