Skip to content

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

Refactor analytics time mode handling to support past minutes (#400)

Bill Yangfccb8505b3a9
diff --git a/client/src/api/analytics/events/useGetEventNames.ts b/client/src/api/analytics/events/useGetEventNames.ts
index 023fe2d31..97249116b 100644
--- a/client/src/api/analytics/events/useGetEventNames.ts
+++ b/client/src/api/analytics/events/useGetEventNames.ts
@@ -4,8 +4,7 @@ import {
getFilteredFilters,
EVENT_FILTERS,
} from "../../../lib/store";
-import { authedFetch } from "../../utils";
-import { getQueryTimeParams } from "../utils";
+import { authedFetch, getQueryParams } from "../../utils";
export type EventName = {
eventName: string;
@@ -15,7 +14,7 @@ export type EventName = {
export function useGetEventNames() {
const { site, time, filters } = useStore();
- const timeParams = getQueryTimeParams(time);
+ const timeParams = getQueryParams(time);
const filteredFilters = getFilteredFilters(EVENT_FILTERS);
return useQuery({
@@ -23,7 +22,7 @@ export function useGetEventNames() {
enabled: !!site,
queryFn: () => {
const params = {
- ...Object.fromEntries(new URLSearchParams(timeParams)),
+ ...timeParams,
filters: filteredFilters.length > 0 ? filteredFilters : undefined,
};
diff --git a/client/src/api/analytics/events/useGetEventProperties.ts b/client/src/api/analytics/events/useGetEventProperties.ts
index af4412f0e..214ba28cd 100644
--- a/client/src/api/analytics/events/useGetEventProperties.ts
+++ b/client/src/api/analytics/events/useGetEventProperties.ts
@@ -4,8 +4,7 @@ import {
getFilteredFilters,
EVENT_FILTERS,
} from "../../../lib/store";
-import { authedFetch } from "../../utils";
-import { getQueryTimeParams } from "../utils";
+import { authedFetch, getQueryParams } from "../../utils";
export type EventProperty = {
propertyKey: string;
@@ -16,7 +15,7 @@ export type EventProperty = {
export function useGetEventProperties(eventName: string | null) {
const { site, time, filters } = useStore();
- const timeParams = getQueryTimeParams(time);
+ const timeParams = getQueryParams(time);
const filteredFilters = getFilteredFilters(EVENT_FILTERS);
return useQuery({
@@ -30,7 +29,7 @@ export function useGetEventProperties(eventName: string | null) {
enabled: !!site && !!eventName,
queryFn: () => {
const params = {
- ...Object.fromEntries(new URLSearchParams(timeParams)),
+ ...timeParams,
eventName,
filters: filteredFilters.length > 0 ? filteredFilters : undefined,
};
diff --git a/client/src/api/analytics/goals/useGetGoals.ts b/client/src/api/analytics/goals/useGetGoals.ts
index 01be7fec7..2cd4d9e02 100644
--- a/client/src/api/analytics/goals/useGetGoals.ts
+++ b/client/src/api/analytics/goals/useGetGoals.ts
@@ -1,12 +1,10 @@
import { useQuery } from "@tanstack/react-query";
-import { timeZone } from "../../../lib/dateTimeUtils";
import {
getFilteredFilters,
GOALS_PAGE_FILTERS,
useStore,
} from "../../../lib/store";
-import { authedFetch } from "../../utils";
-import { getQueryTimeParams } from "../utils";
+import { authedFetch, getQueryParams } from "../../utils";
export interface Goal {
goalId: number;
@@ -37,48 +35,22 @@ interface GoalsResponse {
}
export function useGetGoals({
- startDate,
- endDate,
page = 1,
pageSize = 10,
sort = "createdAt",
order = "desc",
enabled = true,
- pastMinutesStart,
- pastMinutesEnd,
}: {
- startDate?: string;
- endDate?: string;
page?: number;
pageSize?: number;
sort?: "goalId" | "name" | "goalType" | "createdAt";
order?: "asc" | "desc";
enabled?: boolean;
- pastMinutesStart?: number;
- pastMinutesEnd?: number;
}) {
const { site, time } = useStore();
const filteredFilters = getFilteredFilters(GOALS_PAGE_FILTERS);
- // If startDate and endDate are not provided, use time from store
- let timeParams: Record<string, string> = {};
-
- if (pastMinutesStart !== undefined && pastMinutesEnd !== undefined) {
- // If past minutes range is explicitly provided, use it
- timeParams = {
- pastMinutesStart: pastMinutesStart.toString(),
- pastMinutesEnd: pastMinutesEnd.toString(),
- timeZone,
- };
- } else if (!startDate || !endDate) {
- // Otherwise get time parameters from the store's time
- // This will handle last-24-hours mode automatically
- const queryParams = getQueryTimeParams(time);
- timeParams = Object.fromEntries(new URLSearchParams(queryParams));
- } else {
- // Use explicitly provided dates if available
- timeParams = { startDate, endDate, timeZone };
- }
+ const timeParams = getQueryParams(time);
return useQuery({
queryKey: [
@@ -104,34 +76,3 @@ export function useGetGoals({
enabled: !!site && enabled,
});
}
-
-/**
- * Hook to get goals data for the past X minutes
- */
-export function useGetGoalsPastMinutes({
- pastMinutesStart = 24 * 60,
- pastMinutesEnd = 0,
- page = 1,
- pageSize = 10,
- sort = "createdAt",
- order = "desc",
- enabled = true,
-}: {
- pastMinutesStart?: number;
- pastMinutesEnd?: number;
- page?: number;
- pageSize?: number;
- sort?: "goalId" | "name" | "goalType" | "createdAt";
- order?: "asc" | "desc";
- enabled?: boolean;
-}) {
- return useGetGoals({
- pastMinutesStart,
- pastMinutesEnd,
- page,
- pageSize,
- sort,
- order,
- enabled,
- });
-}
diff --git a/client/src/api/analytics/performance/useGetPerformanceByDimension.ts b/client/src/api/analytics/performance/useGetPerformanceByDimension.ts
index 84160409a..5f7c7789f 100644
--- a/client/src/api/analytics/performance/useGetPerformanceByDimension.ts
+++ b/client/src/api/analytics/performance/useGetPerformanceByDimension.ts
@@ -91,7 +91,6 @@ export function useGetPerformanceByDimension({
selectedPercentile,
limit,
page,
- time.mode === "last-24-hours" ? "past-minutes" : "date-range",
additionalFilters,
sortBy,
sortOrder,
diff --git a/client/src/api/analytics/performance/useGetPerformanceOverview.ts b/client/src/api/analytics/performance/useGetPerformanceOverview.ts
index 8de2ae2a4..493ed9049 100644
--- a/client/src/api/analytics/performance/useGetPerformanceOverview.ts
+++ b/client/src/api/analytics/performance/useGetPerformanceOverview.ts
@@ -1,8 +1,7 @@
import { useQuery } from "@tanstack/react-query";
-import { useStore } from "../../../lib/store";
import { usePerformanceStore } from "../../../app/[site]/performance/performanceStore";
+import { useStore } from "../../../lib/store";
import { authedFetch, getQueryParams } from "../../utils";
-import { timeZone } from "../../../lib/dateTimeUtils";
export type GetPerformanceOverviewResponse = {
current: {
@@ -46,7 +45,6 @@ export function useGetPerformanceOverview({
site,
filters,
selectedPercentile,
- timeToUse.mode === "last-24-hours" ? "past-minutes" : "date-range",
],
queryFn: () => {
return authedFetch<{ data: GetPerformanceOverviewResponse }>(
diff --git a/client/src/api/analytics/performance/useGetPerformanceTimeSeries.ts b/client/src/api/analytics/performance/useGetPerformanceTimeSeries.ts
index 64961546c..d334be9e1 100644
--- a/client/src/api/analytics/performance/useGetPerformanceTimeSeries.ts
+++ b/client/src/api/analytics/performance/useGetPerformanceTimeSeries.ts
@@ -5,7 +5,6 @@ import {
useQuery,
} from "@tanstack/react-query";
import { usePerformanceStore } from "../../../app/[site]/performance/performanceStore";
-import { timeZone } from "../../../lib/dateTimeUtils";
import { useStore } from "../../../lib/store";
import { APIResponse } from "../../types";
import { authedFetch, getQueryParams } from "../../utils";
@@ -77,7 +76,6 @@ export function useGetPerformanceTimeSeries({
site,
combinedFilters,
selectedPerformanceMetric,
- timeToUse.mode === "last-24-hours" ? "past-minutes" : "date-range",
],
queryFn: () => {
return authedFetch<APIResponse<GetPerformanceTimeSeriesResponse>>(
diff --git a/client/src/api/analytics/useGetOverview.ts b/client/src/api/analytics/useGetOverview.ts
index 5199e7d7c..10c332d14 100644
--- a/client/src/api/analytics/useGetOverview.ts
+++ b/client/src/api/analytics/useGetOverview.ts
@@ -16,47 +16,15 @@ type PeriodTime = "current" | "previous";
type UseGetOverviewOptions = {
periodTime?: PeriodTime;
site?: number | string;
- // Optional parameters for custom past minutes (for backward compatibility)
- pastMinutesStart?: number;
- pastMinutesEnd?: number;
};
-export function useGetOverview({
- periodTime,
- site,
- pastMinutesStart,
- pastMinutesEnd,
-}: UseGetOverviewOptions) {
+export function useGetOverview({ periodTime, site }: UseGetOverviewOptions) {
const { time, previousTime, filters } = useStore();
const timeToUse = periodTime === "previous" ? previousTime : time;
- // Use custom past minutes if provided, otherwise use the time-based approach
- const queryParams =
- pastMinutesStart !== undefined && pastMinutesEnd !== undefined
- ? getQueryParams(
- timeToUse,
- { filters },
- { pastMinutesStart, pastMinutesEnd }
- )
- : getQueryParams(timeToUse, { filters });
+ const queryParams = getQueryParams(timeToUse, { filters });
- // Create appropriate query key based on the parameters used
- const queryKey =
- pastMinutesStart !== undefined && pastMinutesEnd !== undefined
- ? [
- "overview-past-minutes",
- pastMinutesStart,
- pastMinutesEnd,
- site,
- filters,
- ]
- : [
- "overview",
- timeToUse,
- site,
- filters,
- timeToUse.mode === "last-24-hours" ? "past-minutes" : "date-range",
- ];
+ const queryKey = ["overview", timeToUse, site, filters];
return useQuery({
queryKey,
@@ -66,7 +34,7 @@ export function useGetOverview({
queryParams
);
},
- staleTime: Infinity,
+ staleTime: 60_000,
placeholderData: (_, query: any) => {
if (!query?.queryKey) return undefined;
const prevQueryKey = query.queryKey;
diff --git a/client/src/api/analytics/useGetOverviewBucketed.ts b/client/src/api/analytics/useGetOverviewBucketed.ts
index 4fc611386..0303acfe3 100644
--- a/client/src/api/analytics/useGetOverviewBucketed.ts
+++ b/client/src/api/analytics/useGetOverviewBucketed.ts
@@ -27,8 +27,7 @@ export function useGetOverviewBucketed({
bucket = "hour",
dynamicFilters = [],
refetchInterval,
- pastMinutesStart,
- pastMinutesEnd,
+ overrideTime,
props,
}: {
periodTime?: PeriodTime;
@@ -36,41 +35,48 @@ export function useGetOverviewBucketed({
bucket?: TimeBucket;
dynamicFilters?: Filter[];
refetchInterval?: number;
- pastMinutesStart?: number;
- pastMinutesEnd?: number;
+ overrideTime?:
+ | { mode: "past-minutes"; pastMinutesStart: number; pastMinutesEnd: number }
+ | { mode: "range"; startDate: string; endDate: string };
props?: Partial<UseQueryOptions<APIResponse<GetOverviewBucketedResponse>>>;
}): UseQueryResult<APIResponse<GetOverviewBucketedResponse>> {
const { time, previousTime, filters: globalFilters } = useStore();
- const timeToUse = periodTime === "previous" ? previousTime : time;
+ // Use overrideTime if provided, otherwise use store time
+ const baseTime = overrideTime || time;
+ const timeToUse = periodTime === "previous" ? previousTime : baseTime;
const combinedFilters = [...globalFilters, ...dynamicFilters];
+ // For "previous" periods in past-minutes mode, we need to modify the time object
+ // to use doubled duration for the start and the original start as the end
+ const timeForQuery =
+ timeToUse.mode === "past-minutes" && periodTime === "previous"
+ ? {
+ ...timeToUse,
+ pastMinutesStart: timeToUse.pastMinutesStart * 2,
+ pastMinutesEnd: timeToUse.pastMinutesStart,
+ }
+ : timeToUse;
+
// Use getQueryParams utility to handle conditional logic
- const queryParams = getQueryParams(
- timeToUse,
- {
- timeZone,
- bucket,
- filters: combinedFilters,
- },
- {
- pastMinutesStart,
- pastMinutesEnd,
- }
- );
+ const queryParams = getQueryParams(timeForQuery, {
+ timeZone,
+ bucket,
+ filters: combinedFilters,
+ });
// Generate appropriate query key based on whether we're using past minutes or regular time
const queryKey =
- pastMinutesStart !== undefined && pastMinutesEnd !== undefined
+ timeForQuery.mode === "past-minutes"
? [
"overview-bucketed-past-minutes",
- pastMinutesStart,
- pastMinutesEnd,
+ timeForQuery.pastMinutesStart,
+ timeForQuery.pastMinutesEnd,
site,
bucket,
combinedFilters,
]
- : ["overview-bucketed", timeToUse, bucket, site, combinedFilters];
+ : ["overview-bucketed", timeForQuery, bucket, site, combinedFilters];
return useQuery({
queryKey,
@@ -92,7 +98,7 @@ export function useGetOverviewBucketed({
}
return undefined;
},
- staleTime: Infinity,
+ staleTime: 60_000,
...props,
});
}
diff --git a/client/src/api/analytics/useGetOverviewBucketedWithInView.ts b/client/src/api/analytics/useGetOverviewBucketedWithInView.ts
deleted file mode 100644
index 43cdf690d..000000000
--- a/client/src/api/analytics/useGetOverviewBucketedWithInView.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { TimeBucket } from "@rybbit/shared";
-import { useQuery } from "@tanstack/react-query";
-import { timeZone } from "../../lib/dateTimeUtils";
-import { APIResponse } from "../types";
-import { authedFetch } from "../utils";
-import { GetOverviewBucketedResponse } from "./useGetOverviewBucketed";
-
-/**
- * A wrapper around useGetOverviewBucketedPastMinutes that adds support for
- * conditional fetching based on viewport visibility
- */
-export function useGetOverviewBucketedWithInView({
- pastMinutes = 24 * 60,
- site,
- bucket = "hour",
- isInView = true,
- refetchInterval,
-}: {
- pastMinutes?: number;
- site?: number | string;
- bucket?: TimeBucket;
- isInView?: boolean;
- refetchInterval?: number;
-}) {
- return useQuery<APIResponse<GetOverviewBucketedResponse>>({
- queryKey: ["overview-bucketed-past-minutes", pastMinutes, site, bucket],
- queryFn: () => {
- return authedFetch<APIResponse<GetOverviewBucketedResponse>>(
- `/overview-bucketed/${site}`,
- {
- timeZone,
- bucket,
- pastMinutes,
- }
- );
- },
- refetchInterval: isInView ? refetchInterval : 0,
- enabled: isInView,
- staleTime: Infinity,
- placeholderData: (_, query: any) => {
- if (!query?.queryKey) return undefined;
- const prevQueryKey = query.queryKey as [string, string, string];
- const [, , prevSite] = prevQueryKey;
-
- if (prevSite === site) {
- return query.state.data;
- }
- return undefined;
- },
- });
-}
diff --git a/client/src/api/analytics/useGetPageTitles.ts b/client/src/api/analytics/useGetPageTitles.ts
index 976783259..ef4c7704c 100644
--- a/client/src/api/analytics/useGetPageTitles.ts
+++ b/client/src/api/analytics/useGetPageTitles.ts
@@ -1,7 +1,5 @@
-import { FilterParameter } from "@rybbit/shared";
-import { useQuery, UseQueryResult } from "@tanstack/react-query";
-import { timeZone } from "@/lib/dateTimeUtils";
import { useStore } from "@/lib/store";
+import { useQuery, UseQueryResult } from "@tanstack/react-query";
import { APIResponse } from "../types";
import { authedFetch, getQueryParams } from "../utils";
@@ -50,15 +48,7 @@ export function useGetPageTitlesPaginated({
};
return useQuery({
- queryKey: [
- "page-titles",
- time,
- site,
- filters,
- limit,
- page,
- time.mode === "last-24-hours" ? "past-minutes" : "date-range",
- ],
+ queryKey: ["page-titles", time, site, filters, limit, page],
queryFn: () => {
return authedFetch<APIResponse<PageTitlesPaginatedResponse>>(
`/page-titles/${site}`,
diff --git a/client/src/api/analytics/useInfiniteSingleCol.ts b/client/src/api/analytics/useInfiniteSingleCol.ts
index 475bbaa3b..959ad1a60 100644
--- a/client/src/api/analytics/useInfiniteSingleCol.ts
+++ b/client/src/api/analytics/useInfiniteSingleCol.ts
@@ -30,15 +30,7 @@ export function useInfiniteSingleCol({
const { time, site, filters } = useStore();
return useInfiniteQuery({
- queryKey: [
- parameter,
- time,
- site,
- filters,
- limit,
- time.mode === "last-24-hours" ? "past-minutes" : "date-range",
- "infinite-single-col",
- ],
+ queryKey: [parameter, time, site, filters, limit, "infinite-single-col"],
queryFn: async ({ pageParam = 1 }) => {
const queryParams = {
...getQueryParams(time),
@@ -68,6 +60,6 @@ export function useInfiniteSingleCol({
return allPages.length + 1;
},
- staleTime: Infinity,
+ staleTime: 60_000,
});
}
diff --git a/client/src/api/analytics/usePaginatedSingleCol.ts b/client/src/api/analytics/usePaginatedSingleCol.ts
index bb4ad014f..321657a1c 100644
--- a/client/src/api/analytics/usePaginatedSingleCol.ts
+++ b/client/src/api/analytics/usePaginatedSingleCol.ts
@@ -1,9 +1,8 @@
-import { Filter, FilterParameter } from "@rybbit/shared";
-import { useQuery, UseQueryResult } from "@tanstack/react-query";
import { SingleColResponse } from "@/api/analytics/useSingleCol";
import { authedFetch, getQueryParams } from "@/api/utils";
-import { timeZone } from "@/lib/dateTimeUtils";
import { useStore } from "@/lib/store";
+import { Filter, FilterParameter } from "@rybbit/shared";
+import { useQuery, UseQueryResult } from "@tanstack/react-query";
type UsePaginatedSingleColOptions = {
parameter: FilterParameter;
@@ -38,16 +37,7 @@ export function usePaginatedSingleCol({
};
return useQuery({
- queryKey: [
- parameter,
- time,
- site,
- filters,
- limit,
- page,
- time.mode === "last-24-hours" ? "past-minutes" : "date-range",
- additionalFilters,
- ],
+ queryKey: [parameter, time, site, filters, limit, page, additionalFilters],
queryFn: async () => {
const response = await authedFetch<{ data: PaginatedResponse }>(
`/single-col/${site}`,
@@ -55,7 +45,7 @@ export function usePaginatedSingleCol({
);
return response.data;
},
- staleTime: Infinity,
+ staleTime: 60_000,
placeholderData: (_, query: any) => {
if (!query?.queryKey) return undefined;
const prevQueryKey = query.queryKey;
diff --git a/client/src/api/analytics/useSingleCol.ts b/client/src/api/analytics/useSingleCol.ts
index a6e9ce06f..42a9f4288 100644
--- a/client/src/api/analytics/useSingleCol.ts
+++ b/client/src/api/analytics/useSingleCol.ts
@@ -30,29 +30,24 @@ export function useSingleCol({
const { time, previousTime, site, filters } = useStore();
const timeToUse = periodTime === "previous" ? previousTime : time;
- const queryParams = getQueryParams(
- timeToUse,
- {
- parameter,
- limit,
- filters: useFilters ? filters : undefined,
- },
- {
- pastMinutesStart: periodTime === "previous" ? 48 * 60 : 24 * 60,
- pastMinutesEnd: periodTime === "previous" ? 24 * 60 : 0,
- }
- );
+ // For "previous" periods in past-minutes mode, we need to modify the time object
+ // to use doubled duration for the start and the original start as the end
+ const timeForQuery =
+ timeToUse.mode === "past-minutes" && periodTime === "previous"
+ ? {
+ ...timeToUse,
+ pastMinutesStart: timeToUse.pastMinutesStart * 2,
+ pastMinutesEnd: timeToUse.pastMinutesStart,
+ }
+ : timeToUse;
- // Use a consistent query key format that includes the mode
- const queryKey = [
+ const queryParams = getQueryParams(timeForQuery, {
parameter,
- timeToUse,
- site,
- filters,
limit,
- useFilters,
- timeToUse.mode === "last-24-hours" ? "past-minutes" : "date-range",
- ];
+ filters: useFilters ? filters : undefined,
+ });
+
+ const queryKey = [parameter, timeForQuery, site, filters, limit, useFilters];
return useQuery({
queryKey,
@@ -62,7 +57,7 @@ export function useSingleCol({
}>(`/single-col/${site}`, queryParams);
return response.data;
},
- staleTime: Infinity,
+ staleTime: 60_000,
placeholderData: (_, query: any) => {
if (!query?.queryKey) return undefined;
const prevQueryKey = query.queryKey as [string, string, string];
diff --git a/client/src/api/analytics/userSessions.ts b/client/src/api/analytics/userSessions.ts
index 1502dcdd2..e4cebf0c3 100644
--- a/client/src/api/analytics/userSessions.ts
+++ b/client/src/api/analytics/userSessions.ts
@@ -6,8 +6,7 @@ import {
useStore,
} from "../../lib/store";
import { APIResponse } from "../types";
-import { authedFetch, getStartAndEndDate } from "../utils";
-import { getQueryTimeParams } from "./utils";
+import { authedFetch, getQueryParams } from "../utils";
export type UserSessionsResponse = {
session_id: string;
@@ -29,7 +28,7 @@ export type UserSessionsResponse = {
export function useGetUserSessions(userId: string) {
const { time, site, filters } = useStore();
- const { startDate, endDate } = getStartAndEndDate(time);
+ const timeParams = getQueryParams(time);
return useQuery({
queryKey: ["user-sessions", userId, time, site, filters],
@@ -37,9 +36,7 @@ export function useGetUserSessions(userId: string) {
return authedFetch<UserSessionsResponse>(
`/user/${userId}/sessions/${site}`,
{
- startDate,
- endDate,
- timeZone,
+ ...timeParams,
filters,
}
);
@@ -76,12 +73,9 @@ export type GetSessionsResponse = {
export function useGetSessionsInfinite(userId?: string) {
const { time, site, filters } = useStore();
- const isPast24HoursMode = time.mode === "last-24-hours";
- // Get the appropriate time parameters
- const timeParams = isPast24HoursMode
- ? Object.fromEntries(new URLSearchParams(getQueryTimeParams(time)))
- : getStartAndEndDate(time);
+ // Get the appropriate time parameters using getQueryParams
+ const timeParams = getQueryParams(time);
const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
@@ -101,8 +95,7 @@ export function useGetSessionsInfinite(userId?: string) {
}
// Add time parameters
- if (isPast24HoursMode) {
- // Add minutes parameter for last-24-hours mode
+ if (time.mode === "past-minutes") {
Object.assign(requestParams, timeParams);
} else if (!userId) {
// Only add date parameters if not filtering by userId
@@ -176,10 +169,15 @@ export interface SessionPageviewsAndEvents {
export function useGetSessionDetailsInfinite(sessionId: string | null) {
const { site, time } = useStore();
- const isPast24HoursMode = time.mode === "last-24-hours";
+ const pastMinutesMode = time.mode === "past-minutes";
- // Get minutes for last-24-hours mode
- const minutes = isPast24HoursMode ? 24 * 60 : undefined;
+ // Get minutes based on the time mode
+ let minutes: number | undefined;
+ if (pastMinutesMode) {
+ if (time.mode === "past-minutes") {
+ minutes = time.pastMinutesStart; // Use the dynamic value
+ }
+ }
return useInfiniteQuery<APIResponse<SessionPageviewsAndEvents>>({
queryKey: ["session-details-infinite", sessionId, site, minutes],
@@ -193,8 +191,7 @@ export function useGetSessionDetailsInfinite(sessionId: string | null) {
offset: pageParam,
};
- // Add minutes parameter for last-24-hours mode
- if (isPast24HoursMode && minutes) {
+ if (pastMinutesMode && minutes) {
queryParams.minutes = minutes;
}
diff --git a/client/src/api/analytics/users.ts b/client/src/api/analytics/users.ts
index 4e0a26f7c..f4a744d0f 100644
--- a/client/src/api/analytics/users.ts
+++ b/client/src/api/analytics/users.ts
@@ -8,7 +8,7 @@ import {
} from "../../lib/store";
import { authedFetch, getStartAndEndDate } from "../utils";
import { APIResponse } from "../types";
-import { getQueryTimeParams } from "./utils";
+import { getQueryParams } from "../utils";
export type UsersResponse = {
user_id: string;
@@ -36,12 +36,8 @@ export interface GetUsersOptions {
export function useGetUsers(options: GetUsersOptions) {
const { time, site } = useStore();
- const isPast24HoursMode = time.mode === "last-24-hours";
-
- // Get the appropriate time parameters
- const timeParams = isPast24HoursMode
- ? Object.fromEntries(new URLSearchParams(getQueryTimeParams(time)))
- : getStartAndEndDate(time);
+ // Get the appropriate time parameters using getQueryParams
+ const timeParams = getQueryParams(time);
const { page, pageSize, sortBy, sortOrder } = options;
const filteredFilters = getFilteredFilters(USER_PAGE_FILTERS);
@@ -74,14 +70,8 @@ export function useGetUsers(options: GetUsersOptions) {
sortOrder,
};
- // Add time parameters
- if (isPast24HoursMode) {
- // Add minutes parameter for last-24-hours mode
- Object.assign(requestParams, timeParams);
- } else {
- requestParams.startDate = timeParams.startDate;
- requestParams.endDate = timeParams.endDate;
- }
+ // Add time parameters (getQueryParams handles both past-minutes and regular modes)
+ Object.assign(requestParams, timeParams);
return authedFetch<
APIResponse<UsersResponse[]> & {
diff --git a/client/src/api/analytics/utils.ts b/client/src/api/analytics/utils.ts
deleted file mode 100644
index 81662494f..000000000
--- a/client/src/api/analytics/utils.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { Time } from "../../components/DateSelector/types";
-import { getStartAndEndDate } from "../utils";
-import { timeZone } from "../../lib/dateTimeUtils";
-
-/**
- * Generates URL query parameters for time filtering
- * @param time Time object from store
- * @returns URL query string with time parameters
- */
-export function getQueryTimeParams(time: Time): string {
- const params = new URLSearchParams();
-
- // Handle last-24-hours mode differently
- if (time.mode === "last-24-hours") {
- // Use pastMinutesStart/pastMinutesEnd parameters instead of date range
- params.append("pastMinutesStart", "1440"); // 24 hours ago (24 * 60 minutes)
- params.append("pastMinutesEnd", "0"); // now
- params.append("timeZone", timeZone);
- return params.toString();
- }
-
- // Regular date-based approach for other modes
- const { startDate, endDate } = getStartAndEndDate(time);
-
- if (startDate) params.append("startDate", startDate);
- if (endDate) params.append("endDate", endDate);
- params.append("timeZone", timeZone);
-
- return params.toString();
-}
diff --git a/client/src/api/utils.ts b/client/src/api/utils.ts
index 5cc7a5ede..e23ebbd6e 100644
--- a/client/src/api/utils.ts
+++ b/client/src/api/utils.ts
@@ -26,10 +26,7 @@ export function getStartAndEndDate(time: Time) {
endDate: DateTime.fromISO(time.year).endOf("year").toISODate(),
};
}
- if (time.mode === "all-time") {
- return { startDate: null, endDate: null };
- }
- if (time.mode === "last-24-hours") {
+ if (time.mode === "all-time" || time.mode === "past-minutes") {
return { startDate: null, endDate: null };
}
return { startDate: time.day, endDate: time.day };
@@ -37,26 +34,23 @@ export function getStartAndEndDate(time: Time) {
export function getQueryParams(
time: Time,
- additionalParams: Record<string, any> = {},
- options: {
- pastMinutesStart?: number;
- pastMinutesEnd?: number;
- } = {}
+ additionalParams: Record<string, any> = {}
): Record<string, any> {
- return options.pastMinutesStart || options.pastMinutesEnd
- ? {
- // Past minutes approach for last-24-hours mode
- timeZone,
- pastMinutesStart: options.pastMinutesStart ?? 24 * 60, // 24 hours ago by default
- pastMinutesEnd: options.pastMinutesEnd ?? 0, // now by default
- ...additionalParams,
- }
- : {
- // Regular date-based approach
- ...getStartAndEndDate(time),
- timeZone,
- ...additionalParams,
- };
+ if (time.mode === "past-minutes") {
+ return {
+ timeZone,
+ pastMinutesStart: time.pastMinutesStart,
+ pastMinutesEnd: time.pastMinutesEnd,
+ ...additionalParams,
+ };
+ }
+
+ // Regular date-based approach
+ return {
+ ...getStartAndEndDate(time),
+ timeZone,
+ ...additionalParams,
+ };
}
export async function authedFetch<T>(
diff --git a/client/src/app/[site]/components/SubHeader/SubHeader.tsx b/client/src/app/[site]/components/SubHeader/SubHeader.tsx
index 4321f82da..61ca08793 100644
--- a/client/src/app/[site]/components/SubHeader/SubHeader.tsx
+++ b/client/src/app/[site]/components/SubHeader/SubHeader.tsx
@@ -1,15 +1,14 @@
"use client";
+import { Button } from "@/components/ui/button";
+import { goBack, goForward, useStore } from "@/lib/store";
import { FilterParameter } from "@rybbit/shared";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DateTime } from "luxon";
-import { Button } from "@/components/ui/button";
-import { goBack, goForward, useStore } from "@/lib/store";
import { Filters } from "./Filters/Filters";
import { DateSelector } from "../../../../components/DateSelector/DateSelector";
import { Time } from "../../../../components/DateSelector/types";
import { MobileSidebar } from "../../../../components/MobileSidebar";
-import { useWindowSize } from "@uidotdev/usehooks";
const canGoForward = (time: Time) => {
const currentDay = DateTime.now().startOf("day");
@@ -94,7 +93,7 @@ export function SubHeader({
variant="outline"
size="icon"
onClick={goBack}
- disabled={time.mode === "last-24-hours"}
+ disabled={time.mode === "past-minutes"}
className="rounded-r-none h-8 w-8 sm:h-9 sm:w-9"
>
<ChevronLeft />
diff --git a/client/src/app/[site]/funnels/components/Funnel.tsx b/client/src/app/[site]/funnels/components/Funnel.tsx
index 3e63d2563..ef4fb19de 100644
--- a/client/src/app/[site]/funnels/components/Funnel.tsx
+++ b/client/src/app/[site]/funnels/components/Funnel.tsx
@@ -74,7 +74,7 @@ export function Funnel({
<DateSelector
time={time}
setTime={setTime}
- past24HoursEnabled={false}
+ pastMinutesEnabled={false}
/>
</div>
diff --git a/client/src/app/[site]/goals/page.tsx b/client/src/app/[site]/goals/page.tsx
index df6b0d90e..9628f5b54 100644
--- a/client/src/app/[site]/goals/page.tsx
+++ b/client/src/app/[site]/goals/page.tsx
@@ -1,10 +1,7 @@
"use client";
import { useState } from "react";
-import {
- useGetGoals,
- useGetGoalsPastMinutes,
-} from "../../../api/analytics/goals/useGetGoals";
+import { useGetGoals } from "../../../api/analytics/goals/useGetGoals";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { NothingFound } from "../../../components/NothingFound";
import { Pagination } from "../../../components/pagination";
@@ -17,23 +14,16 @@ import GoalsList from "./components/GoalsList";
export default function GoalsPage() {
useSetPageTitle("Rybbit · Goals");
- const { time, site } = useStore();
- const isPast24HoursMode = time.mode === "last-24-hours";
+ const { site } = useStore();
const [pagination, setPagination] = useState({
pageIndex: 0, // TablePagination uses 0-based indexing
pageSize: 10, // Show 10 goals per page
});
- // Use the appropriate hook based on the mode
- const { data: goalsData, isLoading } = isPast24HoursMode
- ? useGetGoalsPastMinutes({
- page: pagination.pageIndex + 1, // API uses 1-based indexing
- pageSize: pagination.pageSize,
- })
- : useGetGoals({
- page: pagination.pageIndex + 1, // API uses 1-based indexing
- pageSize: pagination.pageSize,
- });
+ const { data: goalsData, isLoading } = useGetGoals({
+ page: pagination.pageIndex + 1, // API uses 1-based indexing
+ pageSize: pagination.pageSize,
+ });
// Create pagination controller for TablePagination
const paginationController = {
diff --git a/client/src/app/[site]/journeys/page.tsx b/client/src/app/[site]/journeys/page.tsx
index c188561bf..f84adaa18 100644
--- a/client/src/app/[site]/journeys/page.tsx
+++ b/client/src/app/[site]/journeys/page.tsx
@@ -441,7 +441,7 @@ export default function JourneysPage() {
<DateSelector
time={time}
setTime={setTime}
- past24HoursEnabled={false}
+ pastMinutesEnabled={false}
/>
<Select
value={steps.toString()}
diff --git a/client/src/app/[site]/main/components/MainSection/BucketSelection.tsx b/client/src/app/[site]/main/components/MainSection/BucketSelection.tsx
deleted file mode 100644
index 6c3cd1945..000000000
--- a/client/src/app/[site]/main/components/MainSection/BucketSelection.tsx
+++ /dev/null
@@ -1,156 +0,0 @@
-"use client";
-
-import { useStore } from "@/lib/store";
-import {
- SelectItem,
- Select,
- SelectContent,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { DateTime } from "luxon";
-import { Time } from "../../../../../components/DateSelector/types";
-
-const getOptions = (time: Time) => {
- if (time.mode === "last-24-hours") {
- return (
- <SelectContent>
- <SelectItem size="sm" value="minute">
- Minute
- </SelectItem>
- <SelectItem size="sm" value="five_minutes">
- 5 Minutes
- </SelectItem>
- <SelectItem size="sm" value="fifteen_minutes">
- 15 Minutes
- </SelectItem>
- <SelectItem size="sm" value="hour">
- Hour
- </SelectItem>
- </SelectContent>
- );
- }
- if (time.mode === "day") {
- return (
- <SelectContent>
- <SelectItem size="sm" value="minute">
- Minute
- </SelectItem>
- <SelectItem size="sm" value="five_minutes">
- 5 Minutes
- </SelectItem>
- <SelectItem size="sm" value="fifteen_minutes">
- 15 Minutes
- </SelectItem>
- <SelectItem size="sm" value="hour">
- Hour
- </SelectItem>
- </SelectContent>
- );
- }
- if (time.mode === "week") {
- return (
- <SelectContent>
- <SelectItem size="sm" value="fifteen_minutes">
- 15 Minutes
- </SelectItem>
- <SelectItem size="sm" value="hour">
- Hour
- </SelectItem>
- <SelectItem size="sm" value="day">
- Day
- </SelectItem>
- </SelectContent>
- );
- }
- if (time.mode === "month") {
- return (
- <SelectContent>
- <SelectItem size="sm" value="hour">
- Hour
- </SelectItem>
- <SelectItem size="sm" value="day">
- Day
- </SelectItem>
- <SelectItem size="sm" value="week">
- Week
- </SelectItem>
- </SelectContent>
- );
- }
- if (time.mode === "year" || time.mode === "all-time") {
- return (
- <SelectContent>
- <SelectItem size="sm" value="day">
- Day
- </SelectItem>
- <SelectItem size="sm" value="week">
- Week
- </SelectItem>
- <SelectItem size="sm" value="month">
- Month
- </SelectItem>
- </SelectContent>
- );
- }
-
- if (time.mode === "range") {
- const timeRangeLength = DateTime.fromISO(time.endDate).diff(
- DateTime.fromISO(time.startDate),
- "days"
- ).days;
-
- return (
- <SelectContent>
- {timeRangeLength <= 7 && (
- <SelectItem size="sm" value="five_minutes">
- 5 Minutes
- </SelectItem>
- )}
- {timeRangeLength <= 14 && (
- <>
- <SelectItem size="sm" value="ten_minutes">
- 10 Minutes
- </SelectItem>
- <SelectItem size="sm" value="fifteen_minutes">
- 15 Minutes
- </SelectItem>
- </>
- )}
- {timeRangeLength <= 30 && (
- <SelectItem size="sm" value="hour">
- Hour
- </SelectItem>
- )}
- {timeRangeLength > 1 && (
- <SelectItem size="sm" value="day">
- Day
- </SelectItem>
- )}
- {timeRangeLength >= 28 && (
- <SelectItem size="sm" value="week">
- Week
- </SelectItem>
- )}
- {timeRangeLength >= 60 && (
- <SelectItem size="sm" value="month">
- Month
- </SelectItem>
- )}
- </SelectContent>
- );
- }
-};
-
-export function BucketSelection() {
- const { bucket, setBucket, time } = useStore();
-
- return (
- <Select value={bucket} onValueChange={setBucket}>
- <SelectTrigger className="w-[100px]" size="sm">
- <SelectValue />
- </SelectTrigger>
- {getOptions(time)}
- </Select>
- );
-}
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index 5a110d777..0da66e31e 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -20,8 +20,11 @@ export const formatter = Intl.NumberFormat(userLocale, { notation: "compact" });
const getMax = (time: Time, bucket: TimeBucket) => {
const now = DateTime.now();
- if (time.mode === "last-24-hours") {
- return DateTime.now().setZone("UTC").toJSDate();
+ if (time.mode === "past-minutes") {
+ if (bucket === "hour") {
+ return DateTime.now().setZone("UTC").startOf("hour").toJSDate();
+ }
+ return undefined;
} else if (time.mode === "day") {
const dayDate = DateTime.fromISO(time.day)
.endOf("day")
@@ -88,11 +91,10 @@ const getMax = (time: Time, bucket: TimeBucket) => {
};
const getMin = (time: Time, bucket: TimeBucket) => {
- if (time.mode === "last-24-hours") {
+ if (time.mode === "past-minutes") {
return DateTime.now()
- .setZone("UTC")
- .minus({ hours: 24 })
- .startOf("hour")
+ .minus({ minutes: time.pastMinutesStart })
+ .startOf(time.pastMinutesStart < 360 ? "minute" : "hour")
.toJSDate();
} else if (time.mode === "day") {
const dayDate = DateTime.fromISO(time.day).startOf("day");
@@ -185,8 +187,8 @@ export function Chart({
(time.mode === "range" && time.endDate !== currentDayStr) || // do not display in range mode if end date is not current day
(time.mode === "day" &&
(bucket === "minute" || bucket === "five_minutes")) || // do not display in day mode if bucket is minute or five_minutes
- (time.mode === "last-24-hours" &&
- (bucket === "minute" || bucket === "five_minutes")); // do not display in last-24-hours mode if bucket is minute or five_minutes
+ (time.mode === "past-minutes" &&
+ (bucket === "minute" || bucket === "five_minutes")); // do not display in 24-hour mode if bucket is minute or five_minutes
const displayDashed = formattedData.length >= 2 && !shouldNotDisplay;
const baseGradient = {
@@ -273,7 +275,7 @@ export function Chart({
<ResponsiveLine
data={chartPropsData}
theme={nivoTheme}
- margin={{ top: 10, right: 10, bottom: 25, left: 35 }}
+ margin={{ top: 10, right: 15, bottom: 25, left: 35 }}
xScale={{
type: "time",
format: "%Y-%m-%d %H:%M:%S",
@@ -302,13 +304,20 @@ export function Chart({
truncateTickAt: 0,
tickValues: Math.min(
maxTicks,
- time.mode === "day" || time.mode === "last-24-hours"
+ time.mode === "day" ||
+ (time.mode === "past-minutes" && time.pastMinutesStart === 1440)
? 24
: Math.min(12, data?.data?.length ?? 0)
),
format: (value) => {
const dt = DateTime.fromJSDate(value).setLocale(userLocale);
- if (time.mode === "day" || time.mode === "last-24-hours") {
+ if (time.mode === "past-minutes") {
+ if (time.pastMinutesStart < 1440) {
+ return dt.toFormat(hour12 ? "h:mm" : "HH:mm");
+ }
+ return dt.toFormat(hour12 ? "ha" : "HH:mm");
+ }
+ if (time.mode === "day") {
return dt.toFormat(hour12 ? "ha" : "HH:mm");
}
return dt.toFormat(hour12 ? "MMM d" : "dd MMM");
diff --git a/client/src/app/[site]/main/components/MainSection/MainSection.tsx b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
index 9231ae749..f4c5ec94b 100644
--- a/client/src/app/[site]/main/components/MainSection/MainSection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
@@ -32,76 +32,23 @@ export function MainSection() {
const { selectedStat, time, site, bucket } = useStore();
- // Use the past minutes API when in last-24-hours mode
- const isPast24HoursMode = time.mode === "last-24-hours";
-
- // Regular date-based queries
- const {
- data: regularData,
- isFetching: isRegularFetching,
- error: regularError,
- } = useGetOverviewBucketed({
+ // Current period data
+ const { data, isFetching, error } = useGetOverviewBucketed({
site,
bucket,
- props: {
- enabled: !isPast24HoursMode,
- },
});
+ // Previous period data
const {
- data: regularPreviousData,
- isFetching: isRegularPreviousFetching,
- error: regularPreviousError,
+ data: previousData,
+ isFetching: isPreviousFetching,
+ error: previousError,
} = useGetOverviewBucketed({
periodTime: "previous",
site,
bucket,
- props: {
- enabled: !isPast24HoursMode,
- },
- });
-
- // Past minutes-based queries (for 24 hour mode)
- const {
- data: pastMinutesData,
- isFetching: isPastMinutesFetching,
- error: pastMinutesError,
- } = useGetOverviewBucketed({
- pastMinutesStart: 24 * 60,
- pastMinutesEnd: 0,
- site,
- bucket,
- props: {
- enabled: isPast24HoursMode,
- },
- });
-
- const {
- data: pastMinutesPreviousData,
- isFetching: isPastMinutesPreviousFetching,
- error: pastMinutesPreviousError,
- } = useGetOverviewBucketed({
- pastMinutesStart: 48 * 60,
- pastMinutesEnd: 24 * 60,
- site,
- bucket,
- props: {
- enabled: isPast24HoursMode,
- },
});
- // Combine the data based on the mode
- const data = isPast24HoursMode ? pastMinutesData : regularData;
- const previousData = isPast24HoursMode
- ? pastMinutesPreviousData
- : regularPreviousData;
- const isFetching = isPast24HoursMode
- ? isPastMinutesFetching
- : isRegularFetching;
- const isPreviousFetching = isPast24HoursMode
- ? isPastMinutesPreviousFetching
- : isRegularPreviousFetching;
-
const { isFetching: isOverviewFetching } = useGetOverview({ site });
const { isFetching: isOverviewFetchingPrevious } = useGetOverview({
site,
diff --git a/client/src/app/[site]/main/components/MainSection/Overview.tsx b/client/src/app/[site]/main/components/MainSection/Overview.tsx
index d4fe2cd7f..82de32b05 100644
--- a/client/src/app/[site]/main/components/MainSection/Overview.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Overview.tsx
@@ -74,31 +74,25 @@ const Stat = ({
}) => {
const { selectedStat, setSelectedStat, site, bucket, time } = useStore();
const [isHovering, setIsHovering] = useState(false);
- const isPast24HoursMode = time.mode === "last-24-hours";
// Consolidated bucketed data for sparklines - automatically handles both modes
const { data } = useGetOverviewBucketed({
site,
bucket,
- // For past-24-hours mode, use custom past minutes; otherwise use regular time-based approach
- ...(isPast24HoursMode && {
- pastMinutesStart: 24 * 60,
- pastMinutesEnd: 0,
- }),
});
// Filter and format sparklines data
const sparklinesData =
data?.data
?.filter((d) => {
- // For last-24-hours mode, ensure we only show data within the last 24 hours
- if (isPast24HoursMode) {
+ // For past-minutes mode, ensure we only show data within the specified time range
+ if (time.mode === "past-minutes") {
const timestamp = new Date(d.time);
const now = new Date();
- const twentyFourHoursAgo = new Date(
- now.getTime() - 24 * 60 * 60 * 1000
+ const startTime = new Date(
+ now.getTime() - time.pastMinutesStart * 60 * 1000
);
- return timestamp >= twentyFourHoursAgo && timestamp <= now;
+ return timestamp >= startTime && timestamp <= now;
}
return true;
})
@@ -158,8 +152,7 @@ const Stat = ({
};
export function Overview() {
- const { site, time } = useStore();
- const isPast24HoursMode = time.mode === "last-24-hours";
+ const { site } = useStore();
// Current period - automatically handles both regular time-based and past-minutes queries
const {
@@ -169,26 +162,13 @@ export function Overview() {
error: overviewError,
} = useGetOverview({
site,
- // For past-24-hours mode, use custom past minutes; otherwise use regular time-based approach
- ...(isPast24HoursMode && {
- pastMinutesStart: 24 * 60,
- pastMinutesEnd: 0,
- }),
});
// Previous period - automatically handles both regular time-based and past-minutes queries
const { data: overviewDataPrevious, isLoading: isOverviewLoadingPrevious } =
useGetOverview({
site,
- // For past-24-hours mode, use previous 24-hour period; otherwise use regular previous period
- ...(isPast24HoursMode
- ? {
- pastMinutesStart: 48 * 60,
- pastMinutesEnd: 24 * 60,
- }
- : {
- periodTime: "previous",
- }),
+ periodTime: "previous",
});
const isLoading = isOverviewLoading || isOverviewLoadingPrevious;
diff --git a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
index c02f68605..91da2d32c 100644
--- a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
@@ -3,18 +3,21 @@ import { nivoTheme } from "@/lib/nivo";
import { useStore } from "@/lib/store";
import { ResponsiveLine } from "@nivo/line";
import { DateTime } from "luxon";
-import { useMemo } from "react";
import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGetOverviewBucketed";
import { APIResponse } from "../../../../../api/types";
import { Time } from "../../../../../components/DateSelector/types";
+import { TimeBucket } from "@rybbit/shared";
-const getMin = (time: Time) => {
- if (time.mode === "last-24-hours") {
- return DateTime.now()
- .setZone("UTC")
- .minus({ hours: 48 })
- .startOf("hour")
- .toJSDate();
+const getMin = (time: Time, bucket: TimeBucket) => {
+ if (time.mode === "past-minutes") {
+ if (bucket === "hour") {
+ return DateTime.now()
+ .setZone("UTC")
+ .minus({ minutes: time.pastMinutesStart * 2 })
+ .startOf("hour")
+ .toJSDate();
+ }
+ undefined;
} else if (time.mode === "day") {
const dayDate = DateTime.fromISO(time.day).startOf("day");
return dayDate.toJSDate();
@@ -42,7 +45,7 @@ export function PreviousChart({
data: APIResponse<GetOverviewBucketedResponse> | undefined;
max: number;
}) {
- const { previousTime: time, selectedStat } = useStore();
+ const { previousTime: time, selectedStat, bucket } = useStore();
const size = (data?.data.length ?? 0 / 2) + 1;
const formattedData = data?.data
@@ -55,10 +58,14 @@ export function PreviousChart({
})
.slice(0, size);
- const min = useMemo(() => getMin(time), [time]);
- const max24Hours =
- time.mode === "last-24-hours"
- ? DateTime.now().setZone("UTC").minus({ hours: 24 }).toJSDate()
+ const min = getMin(time, bucket);
+ const maxPastMinutes =
+ time.mode === "past-minutes" && bucket === "hour"
+ ? DateTime.now()
+ .setZone("UTC")
+ .minus({ minutes: time.pastMinutesStart })
+ .startOf("hour")
+ .toJSDate()
: undefined;
return (
@@ -70,14 +77,14 @@ export function PreviousChart({
},
]}
theme={nivoTheme}
- margin={{ top: 10, right: 10, bottom: 25, left: 35 }}
+ margin={{ top: 10, right: 15, bottom: 25, left: 35 }}
xScale={{
type: "time",
format: "%Y-%m-%d %H:%M:%S",
precision: "second",
useUTC: true,
min,
- max: max24Hours,
+ max: maxPastMinutes,
}}
yScale={{
type: "linear",
@@ -100,7 +107,10 @@ export function PreviousChart({
format: (value) => {
const localTime = DateTime.fromJSDate(value).toLocal();
- if (time.mode === "last-24-hours" || time.mode === "day") {
+ if (
+ (time.mode === "past-minutes" && time.pastMinutesStart >= 1440) ||
+ time.mode === "day"
+ ) {
return localTime.toFormat("ha");
} else if (time.mode === "range") {
return localTime.toFormat("MMM d");
diff --git a/client/src/app/[site]/main/components/sections/Weekdays.tsx b/client/src/app/[site]/main/components/sections/Weekdays.tsx
index 387e8c90b..b12d3508a 100644
--- a/client/src/app/[site]/main/components/sections/Weekdays.tsx
+++ b/client/src/app/[site]/main/components/sections/Weekdays.tsx
@@ -37,37 +37,14 @@ export function Weekdays() {
const { site, time } = useStore();
const [metric, setMetric] = useState<StatType>("users");
- // Use the past minutes API when in last-24-hours mode
- const isPast24HoursMode = time.mode === "last-24-hours";
-
const { data, isFetching, error } = useGetOverviewBucketed({
site,
bucket: "hour",
- props: {
- enabled: !isPast24HoursMode,
- },
- });
-
- // Past minutes-based queries (for 24 hour mode)
- const {
- data: past24HoursData,
- isFetching: isPast24HoursFetching,
- error: past24HoursError,
- } = useGetOverviewBucketed({
- pastMinutesStart: 24 * 60,
- pastMinutesEnd: 0,
- site,
- bucket: "hour",
- props: {
- enabled: isPast24HoursMode,
- },
});
- const dataToUse = isPast24HoursMode ? past24HoursData : data;
-
// Generate aggregated data for the heatmap
const heatmapData = useMemo(() => {
- if (!dataToUse?.data) return [];
+ if (!data?.data) return [];
// Initialize a 2D array for days (0-6) and hours (0-23)
const aggregated: number[][] = Array(7)
@@ -80,7 +57,7 @@ export function Weekdays() {
.map(() => Array(24).fill(0));
// Process each data point
- dataToUse.data.forEach((item) => {
+ data.data.forEach((item) => {
if (!item || !item.time) return;
// Parse the timestamp
@@ -108,7 +85,7 @@ export function Weekdays() {
}
return aggregated;
- }, [dataToUse, metric]);
+ }, [data, metric]);
// Find max value for color intensity scaling
const maxValue = useMemo(() => {
diff --git a/client/src/app/[site]/pages/components/PageListItem.tsx b/client/src/app/[site]/pages/components/PageListItem.tsx
index 6012524a6..c38ce089c 100644
--- a/client/src/app/[site]/pages/components/PageListItem.tsx
+++ b/client/src/app/[site]/pages/components/PageListItem.tsx
@@ -7,6 +7,7 @@ import { usePageMetadata } from "@/api/usePageMetadata";
import { Card, CardContent } from "@/components/ui/card";
import { Filter } from "@rybbit/shared";
import { useStore } from "@/lib/store";
+import { MINUTES_IN_24_HOURS } from "@/lib/const";
import { truncateString } from "@/lib/utils";
import { formatShortDuration } from "@/lib/dateTimeUtils";
import { ExternalLink } from "lucide-react";
@@ -31,7 +32,7 @@ export function PageListItem({
const { data: siteMetadata } = useGetSite();
const { site, time, bucket } = useStore(); // Get time and bucket from store
- const isPast24HoursMode = time.mode === "last-24-hours";
+ const isPastMinutesMode = time.mode === "past-minutes";
// Create a pathname filter for this specific page
const pageSpecificFilter: Filter = {
@@ -47,15 +48,13 @@ export function PageListItem({
bucket,
dynamicFilters: [pageSpecificFilter],
props: {
- enabled: !isPast24HoursMode,
+ enabled: !isPastMinutesMode,
},
});
// Past minutes data for sparklines
const { data: pastMinutesData, isLoading: isLoadingPastMinutes } =
useGetOverviewBucketed({
- pastMinutesStart: 24 * 60,
- pastMinutesEnd: 0,
site,
bucket,
dynamicFilters: [
@@ -66,13 +65,13 @@ export function PageListItem({
},
],
props: {
- enabled: isPast24HoursMode,
+ enabled: isPastMinutesMode,
},
});
// Use the appropriate data source based on mode
- const pageTrafficData = isPast24HoursMode ? pastMinutesData : regularData;
- const isLoadingTrafficData = isPast24HoursMode
+ const pageTrafficData = isPastMinutesMode ? pastMinutesData : regularData;
+ const isLoadingTrafficData = isPastMinutesMode
? isLoadingPastMinutes
: isLoadingRegular;
diff --git a/client/src/app/[site]/realtime/RealtimeChart/RealtimeChart.tsx b/client/src/app/[site]/realtime/RealtimeChart/RealtimeChart.tsx
index 370bcd25c..73b3fb39b 100644
--- a/client/src/app/[site]/realtime/RealtimeChart/RealtimeChart.tsx
+++ b/client/src/app/[site]/realtime/RealtimeChart/RealtimeChart.tsx
@@ -8,11 +8,17 @@ import { useStore } from "../../../../lib/store";
export function RealtimeChart() {
const { site } = useStore();
- const { data, isLoading } = useGetOverviewBucketed({
+ // Create a time object for the last 30 minutes for realtime data
+ const realtimeTime = {
+ mode: "past-minutes" as const,
pastMinutesStart: 30,
pastMinutesEnd: 0,
+ };
+
+ const { data, isLoading } = useGetOverviewBucketed({
site,
bucket: "minute",
+ overrideTime: realtimeTime,
refetchInterval: 10000,
});
diff --git a/client/src/components/BucketSelection.tsx b/client/src/components/BucketSelection.tsx
index 80bfc3336..7549bc9f6 100644
--- a/client/src/components/BucketSelection.tsx
+++ b/client/src/components/BucketSelection.tsx
@@ -12,21 +12,40 @@ import { DateTime } from "luxon";
import { Time } from "./DateSelector/types";
const getOptions = (time: Time) => {
- if (time.mode === "last-24-hours") {
+ if (time.mode === "past-minutes") {
+ if (time.pastMinutesStart >= 1440) {
+ return (
+ <SelectContent>
+ <SelectItem size="sm" value="minute">
+ Minute
+ </SelectItem>
+ <SelectItem size="sm" value="five_minutes">
+ 5 Minutes
+ </SelectItem>
+ <SelectItem size="sm" value="fifteen_minutes">
+ 15 Minutes
+ </SelectItem>
+ <SelectItem size="sm" value="hour">
+ Hour
+ </SelectItem>
+ </SelectContent>
+ );
+ }
+ if (time.pastMinutesStart >= 360) {
+ return (
+ <SelectContent>
+ <SelectItem size="sm" value="hour">
+ Hour
+ </SelectItem>
+ </SelectContent>
+ );
+ }
+ // For shorter durations, exclude hour buckets
return (
<SelectContent>
<SelectItem size="sm" value="minute">
Minute
</SelectItem>
- <SelectItem size="sm" value="five_minutes">
- 5 Minutes
- </SelectItem>
- <SelectItem size="sm" value="fifteen_minutes">
- 15 Minutes
- </SelectItem>
- <SelectItem size="sm" value="hour">
- Hour
- </SelectItem>
</SelectContent>
);
}
diff --git a/client/src/components/DateSelector/DateSelector.tsx b/client/src/components/DateSelector/DateSelector.tsx
index 18d172624..dea2231ab 100644
--- a/client/src/components/DateSelector/DateSelector.tsx
+++ b/client/src/components/DateSelector/DateSelector.tsx
@@ -24,8 +24,12 @@ const getLabel = (time: Time) => {
return `${startFormatted} - ${endFormatted}`;
}
- if (time.mode === "last-24-hours") {
- return "Past 24 Hours";
+ if (time.mode === "past-minutes") {
+ if (time.pastMinutesStart >= 60) {
+ const hours = Math.floor(time.pastMinutesStart / 60);
+ return `Last ${hours} ${hours === 1 ? "Hour" : "Hours"}`;
+ }
+ return `Last ${time.pastMinutesStart} minutes`;
}
if (time.mode === "day") {
@@ -79,11 +83,11 @@ const getLabel = (time: Time) => {
export function DateSelector({
time,
setTime,
- past24HoursEnabled = true,
+ pastMinutesEnabled = true,
}: {
time: Time;
setTime: (time: Time) => void;
- past24HoursEnabled?: boolean;
+ pastMinutesEnabled?: boolean;
}) {
return (
<DropdownMenu>
@@ -105,17 +109,6 @@ export function DateSelector({
>
Today
</DropdownMenuItem>
- {past24HoursEnabled && (
- <DropdownMenuItem
- onClick={() =>
- setTime({
- mode: "last-24-hours",
- })
- }
- >
- Last 24 Hours
- </DropdownMenuItem>
- )}
<DropdownMenuItem
onClick={() =>
setTime({
@@ -176,6 +169,55 @@ export function DateSelector({
>
Last 60 Days
</DropdownMenuItem>
+ {pastMinutesEnabled && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() =>
+ setTime({
+ mode: "past-minutes",
+ pastMinutesStart: 30,
+ pastMinutesEnd: 0,
+ })
+ }
+ >
+ Last 30 Minutes
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() =>
+ setTime({
+ mode: "past-minutes",
+ pastMinutesStart: 60,
+ pastMinutesEnd: 0,
+ })
+ }
+ >
+ Last 1 Hour
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() =>
+ setTime({
+ mode: "past-minutes",
+ pastMinutesStart: 360,
+ pastMinutesEnd: 0,
+ })
+ }
+ >
+ Last 6 Hours
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() =>
+ setTime({
+ mode: "past-minutes",
+ pastMinutesStart: 1440,
+ pastMinutesEnd: 0,
+ })
+ }
+ >
+ Last 24 Hours
+ </DropdownMenuItem>
+ </>
+ )}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() =>
diff --git a/client/src/components/DateSelector/types.ts b/client/src/components/DateSelector/types.ts
index 8ea58d8d8..41df06fb9 100644
--- a/client/src/components/DateSelector/types.ts
+++ b/client/src/components/DateSelector/types.ts
@@ -34,8 +34,10 @@ export type AllTimeMode = {
mode: "all-time";
};
-export type Past24HoursMode = {
- mode: "last-24-hours";
+export type PastMinutesMode = {
+ mode: "past-minutes";
+ pastMinutesStart: number;
+ pastMinutesEnd: number;
};
export type Time =
@@ -45,4 +47,4 @@ export type Time =
| MonthMode
| YearMode
| AllTimeMode
- | Past24HoursMode;
+ | PastMinutesMode;
diff --git a/client/src/components/DateSelector/utils.ts b/client/src/components/DateSelector/utils.ts
new file mode 100644
index 000000000..6ec9db87c
--- /dev/null
+++ b/client/src/components/DateSelector/utils.ts
@@ -0,0 +1,5 @@
+import { Time } from "./types";
+
+export function isPastMinutesMode(time: Time) {
+ return time.mode === "past-minutes";
+}
diff --git a/client/src/components/SiteCard.tsx b/client/src/components/SiteCard.tsx
index 5c30f4d16..b2ceae604 100644
--- a/client/src/components/SiteCard.tsx
+++ b/client/src/components/SiteCard.tsx
@@ -1,14 +1,14 @@
import { ArrowRight } from "lucide-react";
import Link from "next/link";
+import { useRef } from "react";
import { useGetOverview } from "../api/analytics/useGetOverview";
import { useGetOverviewBucketed } from "../api/analytics/useGetOverviewBucketed";
import { useInView } from "../hooks/useInView";
+import { MINUTES_IN_24_HOURS } from "../lib/const";
import { Favicon } from "./Favicon";
import { SiteSessionChart } from "./SiteSessionChart";
import { Button } from "./ui/button";
import { Skeleton } from "./ui/skeleton";
-import { SiteSettings } from "./SiteSettings/SiteSettings";
-import { useRef } from "react";
interface SiteCardProps {
siteId: number;
@@ -27,8 +27,6 @@ export function SiteCard({ siteId, domain }: SiteCardProps) {
const hasLoadedData = useRef(false);
const { data, isLoading, isSuccess } = useGetOverviewBucketed({
- pastMinutesStart: 24 * 60,
- pastMinutesEnd: 0,
site: siteId,
bucket: "hour",
props: {
@@ -42,8 +40,6 @@ export function SiteCard({ siteId, domain }: SiteCardProps) {
isSuccess: isOverviewSuccess,
} = useGetOverview({
site: siteId,
- pastMinutesStart: 24 * 60,
- pastMinutesEnd: 0,
});
// Update the hasLoadedData ref when data loads successfully
diff --git a/client/src/lib/const.ts b/client/src/lib/const.ts
index 9de3e47ab..1b8447a47 100644
--- a/client/src/lib/const.ts
+++ b/client/src/lib/const.ts
@@ -4,3 +4,6 @@ export const BACKEND_URL =
: `${process.env.NEXT_PUBLIC_BACKEND_URL}/api`;
export const IS_CLOUD = process.env.NEXT_PUBLIC_CLOUD === "true";
export const IS_DEMO = process.env.NEXT_PUBLIC_DEMO === "true";
+
+// Time constants
+export const MINUTES_IN_24_HOURS = 24 * 60; // 1440 minutes
diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts
index 1b34490b2..899550659 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -1,4 +1,4 @@
-import { Filter, FilterParameter, FilterType, TimeBucket } from "@rybbit/shared";
+import { Filter, FilterParameter, TimeBucket } from "@rybbit/shared";
import { DateTime } from "luxon";
import { create } from "zustand";
import { Time } from "../components/DateSelector/types";
@@ -156,10 +156,17 @@ export const useStore = create<Store>((set) => ({
mode: "day",
day: DateTime.fromISO(time.day).minus({ days: 1 }).toISODate() ?? "",
};
- } else if (time.mode === "last-24-hours") {
- bucketToUse = "hour";
+ } else if (time.mode === "past-minutes") {
+ const timeDiff = time.pastMinutesStart - time.pastMinutesEnd;
+
+ if (timeDiff <= 120) {
+ bucketToUse = "minute";
+ }
+
previousTime = {
- mode: "last-24-hours",
+ mode: "past-minutes",
+ pastMinutesStart: time.pastMinutesStart,
+ pastMinutesEnd: time.pastMinutesEnd,
};
} else if (time.mode === "range") {
const timeRangeLength =
diff --git a/client/src/lib/urlParams.ts b/client/src/lib/urlParams.ts
index 7ac2c57e3..f38eead6e 100644
--- a/client/src/lib/urlParams.ts
+++ b/client/src/lib/urlParams.ts
@@ -29,6 +29,9 @@ export const serializeStateToUrl = (
params.set("month", time.month);
} else if (time.mode === "year") {
params.set("year", time.year);
+ } else if (time.mode === "past-minutes") {
+ params.set("pastMinutesStart", time.pastMinutesStart.toString());
+ params.set("pastMinutesEnd", time.pastMinutesEnd.toString());
}
// Serialize bucket
@@ -64,8 +67,16 @@ export const deserializeUrlToState = (
// Deserialize time
const timeMode = searchParams.get("timeMode") as Time["mode"] | null;
if (timeMode) {
- if (timeMode === "last-24-hours") {
- result.time = { mode: "last-24-hours" };
+ if (timeMode === "past-minutes") {
+ const pastMinutesStart = searchParams.get("pastMinutesStart");
+ const pastMinutesEnd = searchParams.get("pastMinutesEnd");
+ if (pastMinutesStart && pastMinutesEnd) {
+ result.time = {
+ mode: "past-minutes",
+ pastMinutesStart: Number(pastMinutesStart),
+ pastMinutesEnd: Number(pastMinutesEnd),
+ };
+ }
} else if (timeMode === "day") {
const day = searchParams.get("day");
if (day) {