Skip to content

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

Add buckets

Bill Yangd393dd0f24e5
diff --git a/client/src/app/actions/getPageviews.ts b/client/src/app/actions/getPageviews.ts
index 5cf1845cf..fb71300d5 100644
--- a/client/src/app/actions/getPageviews.ts
+++ b/client/src/app/actions/getPageviews.ts
@@ -2,21 +2,31 @@
import { clickhouse } from "@/lib/clickhouse";
import { getTimeStatement } from "./utils";
+import { TimeBucket } from "../../lib/timeSelectionStore";
export type GetPageViewsResponse = { time: string; pageviews: number }[];
+const TimeBucketToFn = {
+ hour: "toStartOfHour",
+ day: "toStartOfDay",
+ week: "toStartOfWeek",
+ month: "toStartOfMonth",
+};
+
export async function getPageViews({
startDate,
endDate,
timezone = "America/Los_Angeles",
+ bucket,
}: {
startDate: string;
endDate: string;
timezone: string;
+ bucket: TimeBucket;
}): Promise<{ data?: GetPageViewsResponse; error?: string }> {
const query = `
SELECT
- toStartOfHour(toTimeZone(timestamp, '${timezone}')) AS time,
+ ${TimeBucketToFn[bucket]}(toTimeZone(timestamp, '${timezone}')) AS time,
count() AS pageviews
FROM pageviews
WHERE
diff --git a/client/src/app/components/MainSection/BucketSelection.tsx b/client/src/app/components/MainSection/BucketSelection.tsx
new file mode 100644
index 000000000..d9413df14
--- /dev/null
+++ b/client/src/app/components/MainSection/BucketSelection.tsx
@@ -0,0 +1,91 @@
+"use client";
+
+import { Time, useTimeSelection } from "../../../lib/timeSelectionStore";
+import {
+ SelectItem,
+ Select,
+ SelectContent,
+ SelectTrigger,
+ SelectValue,
+} from "../../../components/ui/select";
+import { DateTime } from "luxon";
+
+const getOptions = (time: Time) => {
+ if (time.mode === "date") {
+ return (
+ <SelectContent>
+ <SelectItem size="sm" value="hour">
+ Hour
+ </SelectItem>
+ </SelectContent>
+ );
+ }
+ if (time.mode === "week") {
+ return (
+ <SelectContent>
+ <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="day">
+ Day
+ </SelectItem>
+ <SelectItem size="sm" value="week">
+ Week
+ </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="hour">
+ Hour
+ </SelectItem>
+ )}
+ {timeRangeLength <= 31 && timeRangeLength > 1 && (
+ <SelectItem size="sm" value="day">
+ Day
+ </SelectItem>
+ )}
+ {timeRangeLength >= 28 && timeRangeLength <= 180 && (
+ <SelectItem size="sm" value="week">
+ Week
+ </SelectItem>
+ )}
+ {timeRangeLength >= 60 && timeRangeLength <= 365 && (
+ <SelectItem size="sm" value="month">
+ Month
+ </SelectItem>
+ )}
+ </SelectContent>
+ );
+ }
+};
+
+export function BucketSelection() {
+ const { bucket, setBucket, time } = useTimeSelection();
+
+ return (
+ <Select value={bucket} onValueChange={setBucket}>
+ <SelectTrigger className="w-[120px]" size="sm">
+ <SelectValue placeholder="Theme" />
+ </SelectTrigger>
+ {getOptions(time)}
+ </Select>
+ );
+}
diff --git a/client/src/app/components/MainSection/Chart.tsx b/client/src/app/components/MainSection/Chart.tsx
index b454882d0..d72351e5f 100644
--- a/client/src/app/components/MainSection/Chart.tsx
+++ b/client/src/app/components/MainSection/Chart.tsx
@@ -4,6 +4,7 @@ import { ResponsiveLine } from "@nivo/line";
import { GetPageViewsResponse } from "../../actions/getPageviews";
import { DateTime } from "luxon";
import { round } from "lodash";
+import { useTimeSelection } from "../../../lib/timeSelectionStore";
export const nivoTheme: Theme = {
axis: {
@@ -63,6 +64,8 @@ export function Chart({
}
| undefined;
}) {
+ const { time, bucket } = useTimeSelection();
+
return (
<ResponsiveLine
data={[
@@ -76,7 +79,7 @@ export function Chart({
},
]}
theme={nivoTheme}
- margin={{ top: 20, right: 30, bottom: 20, left: 40 }}
+ margin={{ top: 20, right: 20, bottom: 20, left: 30 }}
xScale={{
type: "time",
format: "%Y-%m-%d %H:%M:%S",
@@ -98,9 +101,20 @@ export function Chart({
tickPadding: 10,
tickRotation: 0,
truncateTickAt: 0,
- tickValues: 24,
+ tickValues:
+ time.mode === "date"
+ ? Math.min(24, data?.data?.length ?? 0)
+ : Math.min(12, data?.data?.length ?? 0),
format: (value) => {
- return DateTime.fromJSDate(value).toFormat("ha");
+ if (time.mode === "date") {
+ return DateTime.fromJSDate(value).toFormat("ha");
+ } else if (time.mode === "range") {
+ return DateTime.fromJSDate(value).toFormat("MMM d");
+ } else if (time.mode === "week") {
+ return DateTime.fromJSDate(value).toFormat("MMM d");
+ } else if (time.mode === "month") {
+ return DateTime.fromJSDate(value).toFormat("MMM d");
+ }
},
}}
axisLeft={{
@@ -108,12 +122,13 @@ export function Chart({
tickPadding: 10,
tickRotation: 0,
truncateTickAt: 0,
- tickValues: 5,
+ tickValues: 4,
format: formatter.format,
}}
enableTouchCrosshair={true}
enablePoints={false}
useMesh={true}
+ motionConfig="stiff"
enableSlices={"x"}
colors={["hsl(var(--fuchsia-400))"]}
enableArea={true}
diff --git a/client/src/app/components/MainSection/MainSection.tsx b/client/src/app/components/MainSection/MainSection.tsx
index 76c6c0ca7..5f8b332fd 100644
--- a/client/src/app/components/MainSection/MainSection.tsx
+++ b/client/src/app/components/MainSection/MainSection.tsx
@@ -2,17 +2,19 @@
import { Card, CardContent } from "@/components/ui/card";
import { useTimeSelection } from "../../../lib/timeSelectionStore";
import { useGetPageviews } from "../../hooks/useGetPageviews";
+import { BucketSelection } from "./BucketSelection";
import { Chart } from "./Chart";
export function MainSection() {
- const { time } = useTimeSelection();
-
const { data, isLoading, error } = useGetPageviews();
return (
<Card>
- <CardContent className="pt-4 sm:px-6 sm:pt-6 aspect-auto h-[350px] w-full">
- <Chart data={data} />
+ <CardContent className="pt-4 sm:px-6 sm:pt-6 w-full">
+ <BucketSelection />
+ <div className="h-[350px]">
+ <Chart data={data} />
+ </div>
</CardContent>
</Card>
);
diff --git a/client/src/app/components/shared/StandardCard.tsx b/client/src/app/components/shared/StandardCard.tsx
index 4959676c4..369c92930 100644
--- a/client/src/app/components/shared/StandardCard.tsx
+++ b/client/src/app/components/shared/StandardCard.tsx
@@ -42,7 +42,7 @@ export function StandardCard<T extends { percentage: number; count: number }>({
{data?.data?.slice(0, 10).map((e) => (
<div key={getKey(e)} className="relative">
<div
- className="absolute inset-0 bg-red-500 py-2 opacity-50"
+ className="absolute inset-0 bg-fuchsia-400 py-2 opacity-30 rounded-md"
style={{ width: `${e.percentage}%` }}
></div>
<div className="relative z-10 ml-1 flex justify-between items-center">
@@ -68,7 +68,7 @@ export function StandardCard<T extends { percentage: number; count: number }>({
{data?.data?.map((e) => (
<div key={getKey(e)} className="relative">
<div
- className="absolute inset-0 bg-red-500 py-2 opacity-50"
+ className="absolute inset-0 bg-fuchsia-400 py-2 opacity-30 rounded-md"
style={{ width: `${e.percentage}%` }}
></div>
<div className="relative z-10 ml-1 flex justify-between items-center pr-3">
diff --git a/client/src/app/hooks/useGetPageviews.ts b/client/src/app/hooks/useGetPageviews.ts
index c2d58afae..bdf4906b3 100644
--- a/client/src/app/hooks/useGetPageviews.ts
+++ b/client/src/app/hooks/useGetPageviews.ts
@@ -4,18 +4,19 @@ import { getPageViews } from "../actions/getPageviews";
import { getStartAndEndDate } from "./utils";
export function useGetPageviews() {
- const { time } = useTimeSelection();
+ const { time, bucket } = useTimeSelection();
const { startDate, endDate } = getStartAndEndDate(time);
return useQuery({
- queryKey: ["pageviews", time],
+ queryKey: ["pageviews", time, bucket],
queryFn: () => {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return getPageViews({
startDate,
endDate,
timezone,
+ bucket,
});
},
});
diff --git a/client/src/components/ui/select.tsx b/client/src/components/ui/select.tsx
index 8bb5d8029..50864a2a0 100644
--- a/client/src/components/ui/select.tsx
+++ b/client/src/components/ui/select.tsx
@@ -1,36 +1,46 @@
-"use client"
+"use client";
-import * as React from "react"
-import * as SelectPrimitive from "@radix-ui/react-select"
-import { Check, ChevronDown, ChevronUp } from "lucide-react"
+import * as React from "react";
+import * as SelectPrimitive from "@radix-ui/react-select";
+import { Check, ChevronDown, ChevronUp } from "lucide-react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
-const Select = SelectPrimitive.Root
+const Select = SelectPrimitive.Root;
-const SelectGroup = SelectPrimitive.Group
+const SelectGroup = SelectPrimitive.Group;
-const SelectValue = SelectPrimitive.Value
+const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
->(({ className, children, ...props }, ref) => (
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger> & {
+ size?: "default" | "sm";
+ }
+>(({ className, children, size = "default", ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
- "flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-neutral-200 bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-white placeholder:text-neutral-500 focus:outline-none focus:ring-1 focus:ring-neutral-950 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 dark:border-neutral-800 dark:ring-offset-neutral-950 dark:placeholder:text-neutral-400 dark:focus:ring-neutral-300",
+ "flex w-full items-center justify-between whitespace-nowrap rounded-md border border-neutral-200 bg-transparent px-3 text-sm shadow-sm ring-offset-white placeholder:text-neutral-500 focus:outline-none focus:ring-1 focus:ring-neutral-950 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 dark:border-neutral-800 dark:ring-offset-neutral-950 dark:placeholder:text-neutral-400 dark:focus:ring-neutral-300",
+ size === "default" && "h-9 py-2",
+ size === "sm" && "h-7 py-1 text-xs",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
- <ChevronDown className="h-4 w-4 opacity-50" />
+ <ChevronDown
+ className={cn(
+ "opacity-50",
+ size === "default" && "h-4 w-4",
+ size === "sm" && "h-3 w-3"
+ )}
+ />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
-))
-SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
+));
+SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
@@ -46,8 +56,8 @@ const SelectScrollUpButton = React.forwardRef<
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
-))
-SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
+));
+SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
@@ -63,75 +73,99 @@ const SelectScrollDownButton = React.forwardRef<
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
-))
+));
SelectScrollDownButton.displayName =
- SelectPrimitive.ScrollDownButton.displayName
+ SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
->(({ className, children, position = "popper", ...props }, ref) => (
- <SelectPrimitive.Portal>
- <SelectPrimitive.Content
- ref={ref}
- className={cn(
- "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border border-neutral-200 bg-white text-neutral-950 shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-50",
- position === "popper" &&
- "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
- className
- )}
- position={position}
- {...props}
- >
- <SelectScrollUpButton />
- <SelectPrimitive.Viewport
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content> & {
+ size?: "default" | "sm";
+ }
+>(
+ (
+ { className, children, position = "popper", size = "default", ...props },
+ ref
+ ) => (
+ <SelectPrimitive.Portal>
+ <SelectPrimitive.Content
+ ref={ref}
className={cn(
- "p-1",
+ "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border border-neutral-200 bg-white text-neutral-950 shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-neutral-800 dark:bg-neutral-900 dark:text-neutral-50",
position === "popper" &&
- "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
+ "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
+ size === "sm" && "text-xs",
+ className
)}
+ position={position}
+ {...props}
>
- {children}
- </SelectPrimitive.Viewport>
- <SelectScrollDownButton />
- </SelectPrimitive.Content>
- </SelectPrimitive.Portal>
-))
-SelectContent.displayName = SelectPrimitive.Content.displayName
+ <SelectScrollUpButton />
+ <SelectPrimitive.Viewport
+ className={cn(
+ "p-1",
+ position === "popper" &&
+ "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
+ )}
+ >
+ {children}
+ </SelectPrimitive.Viewport>
+ <SelectScrollDownButton />
+ </SelectPrimitive.Content>
+ </SelectPrimitive.Portal>
+ )
+);
+SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
->(({ className, ...props }, ref) => (
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label> & {
+ size?: "default" | "sm";
+ }
+>(({ className, size = "default", ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
- className={cn("px-2 py-1.5 text-sm font-semibold", className)}
+ className={cn(
+ "px-2 py-1.5 font-semibold",
+ size === "default" && "text-sm",
+ size === "sm" && "text-xs py-1",
+ className
+ )}
{...props}
/>
-))
-SelectLabel.displayName = SelectPrimitive.Label.displayName
+));
+SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
->(({ className, children, ...props }, ref) => (
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item> & {
+ size?: "default" | "sm";
+ }
+>(({ className, children, size = "default", ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
- "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-neutral-100 focus:text-neutral-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-neutral-800 dark:focus:text-neutral-50",
+ "relative flex w-full cursor-default select-none items-center rounded-sm pl-2 pr-8 outline-none focus:bg-neutral-100 focus:text-neutral-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-neutral-800 dark:focus:text-neutral-50",
+ size === "default" && "py-1.5 text-sm",
+ size === "sm" && "py-1 text-xs",
className
)}
{...props}
>
<span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
- <Check className="h-4 w-4" />
+ <Check
+ className={cn(
+ size === "default" && "h-4 w-4",
+ size === "sm" && "h-3 w-3"
+ )}
+ />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
-))
-SelectItem.displayName = SelectPrimitive.Item.displayName
+));
+SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
@@ -139,11 +173,14 @@ const SelectSeparator = React.forwardRef<
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
- className={cn("-mx-1 my-1 h-px bg-neutral-100 dark:bg-neutral-800", className)}
+ className={cn(
+ "-mx-1 my-1 h-px bg-neutral-100 dark:bg-neutral-800",
+ className
+ )}
{...props}
/>
-))
-SelectSeparator.displayName = SelectPrimitive.Separator.displayName
+));
+SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
@@ -156,4 +193,4 @@ export {
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
-}
+};
diff --git a/client/src/lib/timeSelectionStore.ts b/client/src/lib/timeSelectionStore.ts
index df71680ff..16079141b 100644
--- a/client/src/lib/timeSelectionStore.ts
+++ b/client/src/lib/timeSelectionStore.ts
@@ -12,6 +12,11 @@ type DateRangeMode = {
endDate: string;
};
+type WeekMode = {
+ mode: "week";
+ week: string;
+};
+
type MonthMode = {
mode: "month";
month: string;
@@ -22,11 +27,15 @@ type YearMode = {
year: string;
};
-export type Time = DateMode | DateRangeMode | MonthMode | YearMode;
+export type Time = DateMode | DateRangeMode | WeekMode | MonthMode | YearMode;
+
+export type TimeBucket = "hour" | "day" | "week" | "month";
type Store = {
time: Time;
setTime: (time: Time) => void;
+ bucket: TimeBucket;
+ setBucket: (bucket: TimeBucket) => void;
};
export const useTimeSelection = create<Store>((set) => ({
@@ -34,7 +43,31 @@ export const useTimeSelection = create<Store>((set) => ({
mode: "date",
date: DateTime.now().toISODate(),
},
- setTime: (time) => set({ time }),
+ setTime: (time) => {
+ let bucketToUse: TimeBucket = "hour";
+ if (time.mode === "date") {
+ bucketToUse = "hour";
+ } else if (time.mode === "range") {
+ const timeRangeLength = DateTime.fromISO(time.endDate).diff(
+ DateTime.fromISO(time.startDate),
+ "days"
+ ).days;
+
+ if (timeRangeLength > 180) {
+ bucketToUse = "month";
+ } else if (timeRangeLength > 31) {
+ bucketToUse = "week";
+ }
+ bucketToUse = "day";
+ } else if (time.mode === "month") {
+ bucketToUse = "day";
+ } else if (time.mode === "year") {
+ bucketToUse = "month";
+ }
+ set({ time, bucket: bucketToUse });
+ },
+ bucket: "hour",
+ setBucket: (bucket) => set({ bucket }),
}));
export const goBack = () => {