Skip to content

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

Goal improvements (#1007)

Goldflaga6d70325f564
diff --git a/client/src/api/analytics/endpoints/goals.ts b/client/src/api/analytics/endpoints/goals.ts
index 8da7fb973..efed30989 100644
--- a/client/src/api/analytics/endpoints/goals.ts
+++ b/client/src/api/analytics/endpoints/goals.ts
@@ -1,5 +1,12 @@
import { authedFetch } from "../../utils";
-import { CommonApiParams, PaginationParams, SortParams, toQueryParams } from "./types";
+import {
+ BucketedParams,
+ CommonApiParams,
+ PaginationParams,
+ SortParams,
+ toBucketedQueryParams,
+ toQueryParams,
+} from "./types";
import type { GetSessionsResponse } from "./sessions";
// Goal type
@@ -39,12 +46,24 @@ export interface GoalsResponse {
meta: PaginationMeta;
}
+export interface GoalTimeSeriesPoint {
+ time: string;
+ goal_id: number;
+ conversions: number;
+ total_sessions: number;
+ conversion_rate: number;
+}
+
export interface GoalsParams extends CommonApiParams, PaginationParams, SortParams {
pageSize?: number;
sort?: "goalId" | "name" | "goalType" | "createdAt";
order?: "asc" | "desc";
}
+export interface GoalTimeSeriesParams extends BucketedParams {
+ goalIds: number[];
+}
+
export interface GoalSessionsParams extends CommonApiParams, PaginationParams {
goalId: number;
}
@@ -73,10 +92,7 @@ export interface UpdateGoalParams extends CreateGoalParams {
* Fetch goals with pagination
* GET /api/goals/:site
*/
-export async function fetchGoals(
- site: string | number,
- params: GoalsParams
-): Promise<GoalsResponse> {
+export async function fetchGoals(site: string | number, params: GoalsParams): Promise<GoalsResponse> {
const queryParams = {
...toQueryParams(params),
page: params.page,
@@ -89,6 +105,23 @@ export async function fetchGoals(
return response;
}
+/**
+ * Fetch bucketed conversion data for goals
+ * GET /api/goals/bucketed/:site
+ */
+export async function fetchGoalTimeSeries(
+ site: string | number,
+ params: GoalTimeSeriesParams
+): Promise<GoalTimeSeriesPoint[]> {
+ const queryParams = {
+ ...toBucketedQueryParams(params),
+ goal_ids: params.goalIds,
+ };
+
+ const response = await authedFetch<{ data: GoalTimeSeriesPoint[] }>(`/sites/${site}/goals/bucketed`, queryParams);
+ return response.data;
+}
+
/**
* Fetch sessions that completed a goal
* GET /api/goals/:goalId/sessions/:site
@@ -118,14 +151,10 @@ export async function createGoal(
site: string | number,
params: CreateGoalParams
): Promise<{ success: boolean; goalId: number }> {
- const response = await authedFetch<{ success: boolean; goalId: number }>(
- `/sites/${site}/goals`,
- undefined,
- {
- method: "POST",
- data: params,
- }
- );
+ const response = await authedFetch<{ success: boolean; goalId: number }>(`/sites/${site}/goals`, undefined, {
+ method: "POST",
+ data: params,
+ });
return response;
}
@@ -152,16 +181,9 @@ export async function updateGoal(
* Delete a goal
* DELETE /api/goals/:goalId/:site
*/
-export async function deleteGoal(
- site: string | number,
- goalId: number
-): Promise<{ success: boolean }> {
- const response = await authedFetch<{ success: boolean }>(
- `/sites/${site}/goals/${goalId}`,
- undefined,
- {
- method: "DELETE",
- }
- );
+export async function deleteGoal(site: string | number, goalId: number): Promise<{ success: boolean }> {
+ const response = await authedFetch<{ success: boolean }>(`/sites/${site}/goals/${goalId}`, undefined, {
+ method: "DELETE",
+ });
return response;
}
diff --git a/client/src/api/analytics/endpoints/index.ts b/client/src/api/analytics/endpoints/index.ts
index 2bd4882a9..f3965ceb5 100644
--- a/client/src/api/analytics/endpoints/index.ts
+++ b/client/src/api/analytics/endpoints/index.ts
@@ -34,7 +34,6 @@ export type {
SiteEventCountParams,
} from "./events";
-
// Errors endpoints
export { fetchErrorNames, fetchErrorEvents, fetchErrorBucketed } from "./errors";
export type {
@@ -51,12 +50,14 @@ export type {
} from "./errors";
// Goals endpoints
-export { fetchGoals, fetchGoalSessions, createGoal, updateGoal, deleteGoal } from "./goals";
+export { fetchGoals, fetchGoalTimeSeries, fetchGoalSessions, createGoal, updateGoal, deleteGoal } from "./goals";
export type {
Goal,
+ GoalTimeSeriesPoint,
PaginationMeta,
GoalsResponse,
GoalsParams,
+ GoalTimeSeriesParams,
GoalSessionsParams,
CreateGoalParams,
UpdateGoalParams,
diff --git a/client/src/api/analytics/hooks/goals/useCreateGoal.ts b/client/src/api/analytics/hooks/goals/useCreateGoal.ts
index c4ec8cce0..3e35090d5 100644
--- a/client/src/api/analytics/hooks/goals/useCreateGoal.ts
+++ b/client/src/api/analytics/hooks/goals/useCreateGoal.ts
@@ -34,6 +34,9 @@ export function useCreateGoal() {
queryClient.invalidateQueries({
queryKey: ["goals", variables.siteId.toString()],
});
+ queryClient.invalidateQueries({
+ queryKey: ["goal-time-series", variables.siteId.toString()],
+ });
},
});
}
diff --git a/client/src/api/analytics/hooks/goals/useDeleteGoal.ts b/client/src/api/analytics/hooks/goals/useDeleteGoal.ts
index 164e62966..dc5bcd950 100644
--- a/client/src/api/analytics/hooks/goals/useDeleteGoal.ts
+++ b/client/src/api/analytics/hooks/goals/useDeleteGoal.ts
@@ -15,6 +15,9 @@ export function useDeleteGoal() {
queryClient.invalidateQueries({
queryKey: ["goals", site],
});
+ queryClient.invalidateQueries({
+ queryKey: ["goal-time-series", site],
+ });
},
});
}
diff --git a/client/src/api/analytics/hooks/goals/useGetGoalTimeSeries.ts b/client/src/api/analytics/hooks/goals/useGetGoalTimeSeries.ts
new file mode 100644
index 000000000..2b4d66c3d
--- /dev/null
+++ b/client/src/api/analytics/hooks/goals/useGetGoalTimeSeries.ts
@@ -0,0 +1,25 @@
+import { useQuery } from "@tanstack/react-query";
+import { TimeBucket } from "@rybbit/shared";
+import { GOALS_PAGE_FILTERS } from "../../../../lib/filterGroups";
+import { getFilteredFilters, useStore } from "../../../../lib/store";
+import { buildApiParams } from "../../../utils";
+import { fetchGoalTimeSeries } from "../../endpoints";
+
+export function useGetGoalTimeSeries({ goalIds, bucket }: { goalIds: number[]; bucket?: TimeBucket }) {
+ const { site, time, bucket: storeBucket, timezone } = useStore();
+ const filteredFilters = getFilteredFilters(GOALS_PAGE_FILTERS);
+ const bucketToUse = bucket || storeBucket;
+ const params = buildApiParams(time, { filters: filteredFilters });
+
+ return useQuery({
+ queryKey: ["goal-time-series", site, time, bucketToUse, filteredFilters, goalIds, timezone],
+ queryFn: async () => {
+ return fetchGoalTimeSeries(site, {
+ ...params,
+ bucket: bucketToUse,
+ goalIds,
+ });
+ },
+ enabled: !!site && goalIds.length > 0,
+ });
+}
diff --git a/client/src/api/analytics/hooks/goals/useUpdateGoal.ts b/client/src/api/analytics/hooks/goals/useUpdateGoal.ts
index b73307cf8..ba0461aa5 100644
--- a/client/src/api/analytics/hooks/goals/useUpdateGoal.ts
+++ b/client/src/api/analytics/hooks/goals/useUpdateGoal.ts
@@ -43,6 +43,9 @@ export function useUpdateGoal() {
queryClient.invalidateQueries({
queryKey: ["goals", site],
});
+ queryClient.invalidateQueries({
+ queryKey: ["goal-time-series", site],
+ });
},
});
}
diff --git a/client/src/api/analytics/hooks/useGetMetric.ts b/client/src/api/analytics/hooks/useGetMetric.ts
index 67d91e634..e0eeb6211 100644
--- a/client/src/api/analytics/hooks/useGetMetric.ts
+++ b/client/src/api/analytics/hooks/useGetMetric.ts
@@ -129,16 +129,39 @@ export function useInfiniteMetric({
parameter,
limit = 25,
useFilters = true,
+ additionalFilters = [],
+ customFilters = [],
+ customTime,
}: {
parameter: FilterParameter;
limit?: number;
useFilters?: boolean;
+ additionalFilters?: Filter[];
+ customFilters?: Filter[];
+ customTime?: Time;
}): UseInfiniteQueryResult<InfiniteData<PaginatedResponse>> {
const { time, site, filters, timezone } = useStore();
- const params = buildApiParams(time, { filters: useFilters ? filters : undefined });
+ const timeToUse = customTime ?? time;
+ const combinedFilters = useFilters
+ ? customFilters.length > 0
+ ? customFilters
+ : [...filters, ...additionalFilters]
+ : undefined;
+ const params = buildApiParams(timeToUse, { filters: combinedFilters });
return useInfiniteQuery({
- queryKey: [parameter, time, site, filters, limit, "infinite-metric", timezone],
+ queryKey: [
+ parameter,
+ customTime,
+ time,
+ site,
+ filters,
+ limit,
+ additionalFilters,
+ customFilters,
+ "infinite-metric",
+ timezone,
+ ],
queryFn: async ({ pageParam = 1 }) => {
return fetchMetric(site, {
...params,
diff --git a/client/src/app/[site]/bots/components/BotSection.tsx b/client/src/app/[site]/bots/components/BotSection.tsx
index 03ec6287b..07debbce1 100644
--- a/client/src/app/[site]/bots/components/BotSection.tsx
+++ b/client/src/app/[site]/bots/components/BotSection.tsx
@@ -133,27 +133,7 @@ function BotRows({
);
}
-export function BotSection({
- title,
- dimension,
- getKey,
- getLabel,
- getValue,
- getLink,
- expanded,
- close,
- filterable = true,
-}: {
- title: string;
- dimension: BotDimensionKey;
- getKey: (item: BotDimensionItem) => string;
- getLabel: (item: BotDimensionItem) => ReactNode;
- getValue: (item: BotDimensionItem) => string;
- getLink?: (item: BotDimensionItem) => string | undefined;
- expanded: boolean;
- close: () => void;
- filterable?: boolean;
-}) {
+function useBotSectionData(dimension: BotDimensionKey) {
const { site } = useStore();
const { data, isLoading, isFetching, error, refetch } = useGetBotDimension({
site,
@@ -169,6 +149,90 @@ export function BotSection({
hostname: item.hostname == null ? undefined : String(item.hostname),
})) ?? [];
const ratio = items[0]?.percentage ? 100 / items[0].percentage : 1;
+
+ return { items, ratio, isLoading, isFetching, error, refetch };
+}
+
+function EmptyBotSection() {
+ return (
+ <div className="text-neutral-600 dark:text-neutral-300 w-full text-center mt-6 flex flex-row gap-2 items-center justify-center">
+ <Info className="w-5 h-5" />
+ No Data
+ </div>
+ );
+}
+
+export type BotSectionBaseProps = {
+ title: string;
+ dimension: BotDimensionKey;
+ getKey: (item: BotDimensionItem) => string;
+ getLabel: (item: BotDimensionItem) => ReactNode;
+ getValue: (item: BotDimensionItem) => string;
+ getLink?: (item: BotDimensionItem) => string | undefined;
+ filterable?: boolean;
+};
+
+type BotSectionProps = BotSectionBaseProps & {
+ expanded?: boolean;
+ close?: () => void;
+ renderDialog?: boolean;
+};
+
+export function BotSectionDialogBody({
+ dimension,
+ getKey,
+ getLabel,
+ getValue,
+ getLink,
+ filterable = true,
+}: BotSectionBaseProps) {
+ const { items, ratio, isLoading, error, refetch } = useBotSectionData(dimension);
+ const filterParameter = filterable ? (dimension as FilterParameter) : undefined;
+
+ if (isLoading) {
+ return (
+ <div className="flex flex-col gap-2">
+ <StandardSkeleton />
+ </div>
+ );
+ }
+
+ if (error) {
+ return <ErrorState title="Failed to load data" message={error.message} refetch={refetch} />;
+ }
+
+ if (!items.length) {
+ return <EmptyBotSection />;
+ }
+
+ return (
+ <ScrollArea className="h-full min-h-0 pr-3">
+ <BotRows
+ items={items}
+ ratio={ratio}
+ filterParameter={filterParameter}
+ getKey={getKey}
+ getLabel={getLabel}
+ getValue={getValue}
+ getLink={getLink}
+ />
+ </ScrollArea>
+ );
+}
+
+export function BotSection({
+ title,
+ dimension,
+ getKey,
+ getLabel,
+ getValue,
+ getLink,
+ expanded,
+ close,
+ filterable = true,
+ renderDialog = true,
+}: BotSectionProps) {
+ const { items, ratio, isLoading, isFetching, error, refetch } = useBotSectionData(dimension);
const filterParameter = filterable ? (dimension as FilterParameter) : undefined;
const content = (
@@ -204,30 +268,29 @@ export function BotSection({
) : items.length ? (
content
) : (
- <div className="text-neutral-600 dark:text-neutral-300 w-full text-center mt-6 flex flex-row gap-2 items-center justify-center">
- <Info className="w-5 h-5" />
- No Data
- </div>
+ <EmptyBotSection />
)}
</ScrollArea>
- <Dialog open={expanded} onOpenChange={open => !open && close()}>
- <DialogContent className="max-w-3xl">
- <DialogHeader>
- <DialogTitle>{title}</DialogTitle>
- </DialogHeader>
- <ScrollArea className="h-[70vh] pr-3">
- <BotRows
- items={items}
- ratio={ratio}
- filterParameter={filterParameter}
- getKey={getKey}
- getLabel={getLabel}
- getValue={getValue}
- getLink={getLink}
- />
- </ScrollArea>
- </DialogContent>
- </Dialog>
+ {renderDialog && close && (
+ <Dialog open={expanded} onOpenChange={open => !open && close()}>
+ <DialogContent className="max-w-3xl h-[calc(100vh-2rem)] flex flex-col">
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ </DialogHeader>
+ <div className="min-h-0 flex-1">
+ <BotSectionDialogBody
+ title={title}
+ dimension={dimension}
+ getKey={getKey}
+ getLabel={getLabel}
+ getValue={getValue}
+ getLink={getLink}
+ filterable={filterable}
+ />
+ </div>
+ </DialogContent>
+ </Dialog>
+ )}
</>
);
}
diff --git a/client/src/app/[site]/bots/components/BotSectionTabs.tsx b/client/src/app/[site]/bots/components/BotSectionTabs.tsx
new file mode 100644
index 000000000..a8c338870
--- /dev/null
+++ b/client/src/app/[site]/bots/components/BotSectionTabs.tsx
@@ -0,0 +1,34 @@
+"use client";
+
+import { ReactNode } from "react";
+import {
+ TabbedSectionCard,
+ type TabbedSectionCardProps,
+ type TabbedSectionItem,
+} from "../../components/shared/TabbedSectionCard";
+import { BotSection, BotSectionDialogBody, type BotSectionBaseProps } from "./BotSection";
+
+export type BotSectionTab<TValue extends string> = {
+ value: TValue;
+ label: ReactNode;
+ section: BotSectionBaseProps;
+ showInTabs?: boolean;
+ dialogTitle?: ReactNode;
+};
+
+type BotSectionTabsProps<TValue extends string> = Omit<TabbedSectionCardProps<TValue>, "tabs"> & {
+ tabs: BotSectionTab<TValue>[];
+};
+
+export function BotSectionTabs<TValue extends string>({ tabs, ...props }: BotSectionTabsProps<TValue>) {
+ const tabItems: TabbedSectionItem<TValue>[] = tabs.map(tab => ({
+ value: tab.value,
+ label: tab.label,
+ showInTabs: tab.showInTabs,
+ dialogTitle: tab.dialogTitle ?? tab.section.title,
+ content: <BotSection {...tab.section} renderDialog={false} />,
+ dialogContent: <BotSectionDialogBody {...tab.section} />,
+ }));
+
+ return <TabbedSectionCard {...props} tabs={tabItems} />;
+}
diff --git a/client/src/app/[site]/bots/components/sections/BotCountries.tsx b/client/src/app/[site]/bots/components/sections/BotCountries.tsx
index 1ae4f4847..71817343c 100644
--- a/client/src/app/[site]/bots/components/sections/BotCountries.tsx
+++ b/client/src/app/[site]/bots/components/sections/BotCountries.tsx
@@ -1,14 +1,10 @@
"use client";
-import { ChevronRight, Expand } from "lucide-react";
-import { useState } from "react";
+import { ChevronRight } from "lucide-react";
import { useSubdivisions } from "../../../../../lib/geo";
import { getCountryName } from "../../../../../lib/utils";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
-import { Button } from "../../../../../components/ui/button";
-import { Card, CardContent } from "../../../../../components/ui/card";
import { CountryFlag } from "../../../components/shared/icons/CountryFlag";
-import { BotSection } from "../BotSection";
+import { BotSectionTabs, type BotSectionTab } from "../BotSectionTabs";
type Tab = "countries" | "regions" | "cities";
@@ -22,98 +18,80 @@ function getCountryCity(value: string) {
}
export function BotCountries() {
- const [tab, setTab] = useState<Tab>("countries");
- const [expanded, setExpanded] = useState(false);
const { data: subdivisions } = useSubdivisions();
- return (
- <Card className="h-[405px]">
- <CardContent className="mt-2">
- <Tabs defaultValue="countries" value={tab} onValueChange={value => setTab(value as Tab)}>
- <div className="flex flex-row gap-2 justify-between items-center">
- <TabsList>
- <TabsTrigger value="countries">Countries</TabsTrigger>
- <TabsTrigger value="regions">Regions</TabsTrigger>
- <TabsTrigger value="cities">Cities</TabsTrigger>
- </TabsList>
- <div className="w-7">
- <Button size="smIcon" onClick={() => setExpanded(!expanded)}>
- <Expand className="w-4 h-4" />
- </Button>
- </div>
+ const tabs: BotSectionTab<Tab>[] = [
+ {
+ value: "countries",
+ label: "Countries",
+ section: {
+ dimension: "country",
+ title: "Countries",
+ getValue: item => item.value,
+ getKey: item => item.value || "unknown",
+ getLabel: item => (
+ <div className="flex gap-2 items-center">
+ {item.value && <CountryFlag country={item.value} />}
+ {item.value ? getCountryName(item.value) : "Unknown"}
</div>
- <TabsContent value="countries">
- <BotSection
- dimension="country"
- title="Countries"
- getValue={item => item.value}
- getKey={item => item.value || "unknown"}
- getLabel={item => (
- <div className="flex gap-2 items-center">
- {item.value && <CountryFlag country={item.value} />}
- {item.value ? getCountryName(item.value) : "Unknown"}
- </div>
- )}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- <TabsContent value="regions">
- <BotSection
- dimension="region"
- title="Regions"
- getValue={item => item.value}
- getKey={item => item.value || "unknown"}
- getLabel={item => {
- if (!item.value) return "Unknown";
- const region = subdivisions?.features.find(
- feature => feature.properties.iso_3166_2 === item.value
- )?.properties;
- const countryCode = item.value.split("-")[0];
+ ),
+ },
+ },
+ {
+ value: "regions",
+ label: "Regions",
+ section: {
+ dimension: "region",
+ title: "Regions",
+ getValue: item => item.value,
+ getKey: item => item.value || "unknown",
+ getLabel: item => {
+ if (!item.value) return "Unknown";
+ const region = subdivisions?.features.find(
+ feature => feature.properties.iso_3166_2 === item.value
+ )?.properties;
+ const countryCode = item.value.split("-")[0];
+
+ return (
+ <div className="flex gap-2 items-center">
+ <CountryFlag country={countryCode} />
+ {countryCode}
+ <ChevronRight className="w-4 h-4 mx-[-4px]" />
+ {region?.name ?? item.value.slice(3)}
+ </div>
+ );
+ },
+ },
+ },
+ {
+ value: "cities",
+ label: "Cities",
+ section: {
+ dimension: "city",
+ title: "Cities",
+ getValue: item => item.value,
+ getKey: item => item.value || "unknown",
+ getLabel: item => {
+ if (!item.value || item.value === "-") return "Unknown";
+ const { country, region, city } = getCountryCity(item.value);
+ const regionName = subdivisions?.features.find(
+ feature => feature.properties.iso_3166_2 === `${country}-${region}`
+ )?.properties.name;
- return (
- <div className="flex gap-2 items-center">
- <CountryFlag country={countryCode} />
- {countryCode}
- <ChevronRight className="w-4 h-4 mx-[-4px]" />
- {region?.name ?? item.value.slice(3)}
- </div>
- );
- }}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- <TabsContent value="cities">
- <BotSection
- dimension="city"
- title="Cities"
- getValue={item => item.value}
- getKey={item => item.value || "unknown"}
- getLabel={item => {
- if (!item.value || item.value === "-") return "Unknown";
- const { country, region, city } = getCountryCity(item.value);
- const regionName = subdivisions?.features.find(
- feature => feature.properties.iso_3166_2 === `${country}-${region}`
- )?.properties.name;
+ return (
+ <div className="flex gap-2 items-center">
+ <CountryFlag country={country} />
+ {country}
+ {regionName && <ChevronRight className="w-4 h-4 mx-[-4px]" />}
+ {regionName}
+ {city && <ChevronRight className="w-4 h-4 mx-[-4px]" />}
+ {city}
+ </div>
+ );
+ },
+ },
+ },
+ ];
- return (
- <div className="flex gap-2 items-center">
- <CountryFlag country={country} />
- {country}
- {regionName && <ChevronRight className="w-4 h-4 mx-[-4px]" />}
- {regionName}
- {city && <ChevronRight className="w-4 h-4 mx-[-4px]" />}
- {city}
- </div>
- );
- }}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- </Tabs>
- </CardContent>
- </Card>
- );
+ return <BotSectionTabs defaultValue="countries" tabs={tabs} />;
}
diff --git a/client/src/app/[site]/bots/components/sections/BotDevices.tsx b/client/src/app/[site]/bots/components/sections/BotDevices.tsx
index 02d6248e1..4bab82db7 100644
--- a/client/src/app/[site]/bots/components/sections/BotDevices.tsx
+++ b/client/src/app/[site]/bots/components/sections/BotDevices.tsx
@@ -1,141 +1,112 @@
"use client";
-import { Expand } from "lucide-react";
-import { useState } from "react";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
-import { Button } from "../../../../../components/ui/button";
-import { Card, CardContent } from "../../../../../components/ui/card";
import { Browser } from "../../../components/shared/icons/Browser";
import { DeviceIcon } from "../../../components/shared/icons/Device";
import { OperatingSystem } from "../../../components/shared/icons/OperatingSystem";
-import { BotSection } from "../BotSection";
+import { BotSectionTabs, type BotSectionTab } from "../BotSectionTabs";
type Tab = "browsers" | "browser_versions" | "devices" | "os" | "os_versions" | "dimensions";
export function BotDevices() {
- const [tab, setTab] = useState<Tab>("browsers");
- const [expanded, setExpanded] = useState(false);
-
- return (
- <Card className="h-[405px]">
- <CardContent className="mt-2">
- <Tabs defaultValue="browsers" value={tab} onValueChange={value => setTab(value as Tab)}>
- <div className="flex flex-row gap-2 justify-between items-center">
- <div className="overflow-x-auto">
- <TabsList>
- <TabsTrigger value="browsers">Browsers</TabsTrigger>
- <TabsTrigger value="browser_versions">Versions</TabsTrigger>
- <TabsTrigger value="devices">Devices</TabsTrigger>
- <TabsTrigger value="os">OS</TabsTrigger>
- <TabsTrigger value="os_versions">OS Versions</TabsTrigger>
- <TabsTrigger value="dimensions">Dimensions</TabsTrigger>
- </TabsList>
- </div>
- <div className="w-7">
- <Button size="smIcon" onClick={() => setExpanded(!expanded)}>
- <Expand className="w-4 h-4" />
- </Button>
+ const tabs: BotSectionTab<Tab>[] = [
+ {
+ value: "browsers",
+ label: "Browsers",
+ section: {
+ dimension: "browser",
+ title: "Browsers",
+ getValue: item => item.value,
+ getKey: item => item.value || "other",
+ getLabel: item => (
+ <div className="flex gap-2 items-center">
+ <Browser browser={item.value || "Other"} />
+ {item.value || "Other"}
+ </div>
+ ),
+ },
+ },
+ {
+ value: "browser_versions",
+ label: "Versions",
+ section: {
+ dimension: "browser_version",
+ title: "Browser Versions",
+ getValue: item => item.value,
+ getKey: item => item.value || "other",
+ getLabel: item => {
+ const browser = item.value.split(" ").slice(0, -1).join(" ");
+ return (
+ <div className="flex gap-2 items-center">
+ <Browser browser={browser || "Other"} />
+ {item.value || "Other"}
</div>
+ );
+ },
+ },
+ },
+ {
+ value: "devices",
+ label: "Devices",
+ section: {
+ dimension: "device_type",
+ title: "Devices",
+ getValue: item => item.value,
+ getKey: item => item.value || "other",
+ getLabel: item => (
+ <div className="flex gap-2 items-center">
+ <DeviceIcon deviceType={item.value || ""} size={16} />
+ {item.value || "Other"}
</div>
- <TabsContent value="browsers">
- <BotSection
- dimension="browser"
- title="Browsers"
- getValue={item => item.value}
- getKey={item => item.value || "other"}
- getLabel={item => (
- <div className="flex gap-2 items-center">
- <Browser browser={item.value || "Other"} />
- {item.value || "Other"}
- </div>
- )}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- <TabsContent value="browser_versions">
- <BotSection
- dimension="browser_version"
- title="Browser Versions"
- getValue={item => item.value}
- getKey={item => item.value || "other"}
- getLabel={item => {
- const browser = item.value.split(" ").slice(0, -1).join(" ");
- return (
- <div className="flex gap-2 items-center">
- <Browser browser={browser || "Other"} />
- {item.value || "Other"}
- </div>
- );
- }}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- <TabsContent value="devices">
- <BotSection
- dimension="device_type"
- title="Devices"
- getValue={item => item.value}
- getKey={item => item.value || "other"}
- getLabel={item => (
- <div className="flex gap-2 items-center">
- <DeviceIcon deviceType={item.value || ""} size={16} />
- {item.value || "Other"}
- </div>
- )}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- <TabsContent value="os">
- <BotSection
- dimension="operating_system"
- title="Operating Systems"
- getValue={item => item.value}
- getKey={item => item.value || "other"}
- getLabel={item => (
- <div className="flex gap-2 items-center">
- <OperatingSystem os={item.value || "Other"} />
- {item.value || "Other"}
- </div>
- )}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- <TabsContent value="os_versions">
- <BotSection
- dimension="operating_system_version"
- title="OS Versions"
- getValue={item => item.value}
- getKey={item => item.value || "other"}
- getLabel={item => {
- const os = item.value.split(" ").slice(0, -1).join(" ");
- return (
- <div className="flex gap-2 items-center">
- <OperatingSystem os={os || "Other"} />
- {item.value || "Other"}
- </div>
- );
- }}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- <TabsContent value="dimensions">
- <BotSection
- dimension="dimensions"
- title="Screen Dimensions"
- getValue={item => item.value}
- getKey={item => item.value || "other"}
- getLabel={item => item.value || "Other"}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- </Tabs>
- </CardContent>
- </Card>
- );
+ ),
+ },
+ },
+ {
+ value: "os",
+ label: "OS",
+ section: {
+ dimension: "operating_system",
+ title: "Operating Systems",
+ getValue: item => item.value,
+ getKey: item => item.value || "other",
+ getLabel: item => (
+ <div className="flex gap-2 items-center">
+ <OperatingSystem os={item.value || "Other"} />
+ {item.value || "Other"}
+ </div>
+ ),
+ },
+ },
+ {
+ value: "os_versions",
+ label: "OS Versions",
+ section: {
+ dimension: "operating_system_version",
+ title: "OS Versions",
+ getValue: item => item.value,
+ getKey: item => item.value || "other",
+ getLabel: item => {
+ const os = item.value.split(" ").slice(0, -1).join(" ");
+ return (
+ <div className="flex gap-2 items-center">
+ <OperatingSystem os={os || "Other"} />
+ {item.value || "Other"}
+ </div>
+ );
+ },
+ },
+ },
+ {
+ value: "dimensions",
+ label: "Dimensions",
+ section: {
+ dimension: "dimensions",
+ title: "Screen Dimensions",
+ getValue: item => item.value,
+ getKey: item => item.value || "other",
+ getLabel: item => item.value || "Other",
+ },
+ },
+ ];
+
+ return <BotSectionTabs defaultValue="browsers" tabs={tabs} />;
}
diff --git a/client/src/app/[site]/bots/components/sections/BotMetadata.tsx b/client/src/app/[site]/bots/components/sections/BotMetadata.tsx
index ec6f54eff..fd5bf13e6 100644
--- a/client/src/app/[site]/bots/components/sections/BotMetadata.tsx
+++ b/client/src/app/[site]/bots/components/sections/BotMetadata.tsx
@@ -1,12 +1,7 @@
"use client";
-import { Expand } from "lucide-react";
-import { useState } from "react";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
-import { Button } from "../../../../../components/ui/button";
-import { Card, CardContent } from "../../../../../components/ui/card";
import { truncateString } from "../../../../../lib/utils";
-import { BotSection } from "../BotSection";
+import { BotSectionTabs, type BotSectionTab } from "../BotSectionTabs";
type Tab = "asn_orgs" | "bot_categories" | "ua_patterns";
@@ -20,65 +15,44 @@ function formatBotCategory(value: string) {
}
export function BotMetadata() {
- const [tab, setTab] = useState<Tab>("asn_orgs");
- const [expanded, setExpanded] = useState(false);
+ const tabs: BotSectionTab<Tab>[] = [
+ {
+ value: "asn_orgs",
+ label: "ASN Orgs",
+ section: {
+ dimension: "asn_org",
+ title: "ASN Orgs",
+ getValue: item => item.value,
+ getKey: item => item.value || "unknown",
+ getLabel: item => item.value || "Unknown",
+ filterable: false,
+ },
+ },
+ {
+ value: "bot_categories",
+ label: "Categories",
+ section: {
+ dimension: "bot_category",
+ title: "Bot Categories",
+ getValue: item => item.value,
+ getKey: item => item.value || "uncategorized",
+ getLabel: item => formatBotCategory(item.value),
+ filterable: false,
+ },
+ },
+ {
+ value: "ua_patterns",
+ label: "UA Patterns",
+ section: {
+ dimension: "matched_ua_pattern",
+ title: "Matched UA Patterns",
+ getValue: item => item.value,
+ getKey: item => item.value || "none",
+ getLabel: item => truncateString(item.value, 70) || "No matched pattern",
+ filterable: false,
+ },
+ },
+ ];
- return (
- <Card className="h-[405px]">
- <CardContent className="mt-2">
- <Tabs defaultValue="asn_orgs" value={tab} onValueChange={value => setTab(value as Tab)}>
- <div className="flex flex-row gap-2 justify-between items-center">
- <div className="overflow-x-auto">
- <TabsList>
- <TabsTrigger value="asn_orgs">ASN Orgs</TabsTrigger>
- <TabsTrigger value="bot_categories">Categories</TabsTrigger>
- <TabsTrigger value="ua_patterns">UA Patterns</TabsTrigger>
- </TabsList>
- </div>
- <div className="w-7">
- <Button size="smIcon" onClick={() => setExpanded(!expanded)}>
- <Expand className="w-4 h-4" />
- </Button>
- </div>
- </div>
- <TabsContent value="asn_orgs">
- <BotSection
- dimension="asn_org"
- title="ASN Orgs"
- getValue={item => item.value}
- getKey={item => item.value || "unknown"}
- getLabel={item => item.value || "Unknown"}
- filterable={false}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- <TabsContent value="bot_categories">
- <BotSection
- dimension="bot_category"
- title="Bot Categories"
- getValue={item => item.value}
- getKey={item => item.value || "uncategorized"}
- getLabel={item => formatBotCategory(item.value)}
- filterable={false}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- <TabsContent value="ua_patterns">
- <BotSection
- dimension="matched_ua_pattern"
- title="Matched UA Patterns"
- getValue={item => item.value}
- getKey={item => item.value || "none"}
- getLabel={item => truncateString(item.value, 70) || "No matched pattern"}
- filterable={false}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- </Tabs>
- </CardContent>
- </Card>
- );
+ return <BotSectionTabs defaultValue="asn_orgs" tabs={tabs} />;
}
diff --git a/client/src/app/[site]/bots/components/sections/BotPages.tsx b/client/src/app/[site]/bots/components/sections/BotPages.tsx
index 6766333fd..90e986ec3 100644
--- a/client/src/app/[site]/bots/components/sections/BotPages.tsx
+++ b/client/src/app/[site]/bots/components/sections/BotPages.tsx
@@ -1,64 +1,42 @@
"use client";
-import { Expand } from "lucide-react";
-import { useState } from "react";
import { useGetSite } from "../../../../../api/admin/hooks/useSites";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
-import { Button } from "../../../../../components/ui/button";
-import { Card, CardContent } from "../../../../../components/ui/card";
import { truncateString } from "../../../../../lib/utils";
-import { BotSection } from "../BotSection";
+import { BotSectionTabs, type BotSectionTab } from "../BotSectionTabs";
type Tab = "pages" | "hostnames";
export function BotPages() {
const { data: siteMetadata } = useGetSite();
- const [tab, setTab] = useState<Tab>("pages");
- const [expanded, setExpanded] = useState(false);
- return (
- <Card className="h-[405px]">
- <CardContent className="mt-2">
- <Tabs defaultValue="pages" value={tab} onValueChange={value => setTab(value as Tab)}>
- <div className="flex flex-row gap-2 justify-between items-center">
- <TabsList>
- <TabsTrigger value="pages">Pages</TabsTrigger>
- <TabsTrigger value="hostnames">Hostnames</TabsTrigger>
- </TabsList>
- <div className="w-7">
- <Button size="smIcon" onClick={() => setExpanded(!expanded)}>
- <Expand className="w-4 h-4" />
- </Button>
- </div>
- </div>
- <TabsContent value="pages">
- <BotSection
- dimension="pathname"
- title="Pages"
- getValue={item => item.value}
- getKey={item => item.value || "unknown"}
- getLabel={item => truncateString(item.value, 50) || "Other"}
- getLink={item => {
- const host = item.hostname || siteMetadata?.domain;
- return host && item.value ? `https://${host}${item.value}` : undefined;
- }}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- <TabsContent value="hostnames">
- <BotSection
- dimension="hostname"
- title="Hostnames"
- getValue={item => item.value}
- getKey={item => item.value || "unknown"}
- getLabel={item => item.value || "Other"}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- </Tabs>
- </CardContent>
- </Card>
- );
+ const tabs: BotSectionTab<Tab>[] = [
+ {
+ value: "pages",
+ label: "Pages",
+ section: {
+ dimension: "pathname",
+ title: "Pages",
+ getValue: item => item.value,
+ getKey: item => item.value || "unknown",
+ getLabel: item => truncateString(item.value, 50) || "Other",
+ getLink: item => {
+ const host = item.hostname || siteMetadata?.domain;
+ return host && item.value ? `https://${host}${item.value}` : undefined;
+ },
+ },
+ },
+ {
+ value: "hostnames",
+ label: "Hostnames",
+ section: {
+ dimension: "hostname",
+ title: "Hostnames",
+ getValue: item => item.value,
+ getKey: item => item.value || "unknown",
+ getLabel: item => item.value || "Other",
+ },
+ },
+ ];
+
+ return <BotSectionTabs defaultValue="pages" tabs={tabs} />;
}
diff --git a/client/src/app/[site]/bots/components/sections/BotReferrers.tsx b/client/src/app/[site]/bots/components/sections/BotReferrers.tsx
index e9f342c25..901ba54cf 100644
--- a/client/src/app/[site]/bots/components/sections/BotReferrers.tsx
+++ b/client/src/app/[site]/bots/components/sections/BotReferrers.tsx
@@ -1,49 +1,30 @@
"use client";
-import { Expand } from "lucide-react";
-import { useState } from "react";
import { Favicon } from "../../../../../components/Favicon";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
-import { Button } from "../../../../../components/ui/button";
-import { Card, CardContent } from "../../../../../components/ui/card";
-import { BotSection } from "../BotSection";
+import { BotSectionTabs, type BotSectionTab } from "../BotSectionTabs";
-export function BotReferrers() {
- const [expanded, setExpanded] = useState(false);
+type Tab = "referrers";
- return (
- <Card className="h-[405px]">
- <CardContent className="mt-2">
- <Tabs defaultValue="referrers">
- <div className="flex flex-row gap-2 justify-between items-center">
- <TabsList>
- <TabsTrigger value="referrers">Referrers</TabsTrigger>
- </TabsList>
- <div className="w-7">
- <Button size="smIcon" onClick={() => setExpanded(!expanded)}>
- <Expand className="w-4 h-4" />
- </Button>
- </div>
+export function BotReferrers() {
+ const tabs: BotSectionTab<Tab>[] = [
+ {
+ value: "referrers",
+ label: "Referrers",
+ section: {
+ dimension: "referrer",
+ title: "Referrers",
+ getValue: item => item.value,
+ getKey: item => item.value || "direct",
+ getLink: item => (item.value ? `https://${item.value}` : undefined),
+ getLabel: item => (
+ <div className="flex items-center">
+ {item.value && <Favicon domain={item.value} className="w-4 mr-2" />}
+ {item.value || "Direct"}
</div>
- <TabsContent value="referrers">
- <BotSection
- dimension="referrer"
- title="Referrers"
- getValue={item => item.value}
- getKey={item => item.value || "direct"}
- getLink={item => (item.value ? `https://${item.value}` : undefined)}
- getLabel={item => (
- <div className="flex items-center">
- {item.value && <Favicon domain={item.value} className="w-4 mr-2" />}
- {item.value || "Direct"}
- </div>
- )}
- expanded={expanded}
- close={() => setExpanded(false)}
- />
- </TabsContent>
- </Tabs>
- </CardContent>
- </Card>
- );
+ ),
+ },
+ },
+ ];
+
+ return <BotSectionTabs defaultValue="referrers" tabs={tabs} />;
}
diff --git a/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx b/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx
index a48dfbd64..bbcd06364 100644
--- a/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx
+++ b/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx
@@ -19,6 +19,27 @@ import { Time } from "../../../../../components/DateSelector/types";
const MAX_ITEMS_TO_DISPLAY = 10;
+export type StandardSectionBaseProps = {
+ title: string;
+ getKey: (item: MetricResponse) => string;
+ getLabel: (item: MetricResponse) => ReactNode;
+ getValue: (item: MetricResponse) => string;
+ getFilterLabel?: (item: MetricResponse) => string;
+ getLink?: (item: MetricResponse) => string;
+ countLabel?: string;
+ filterParameter: FilterParameter;
+ hasSubrow?: boolean;
+ getSubrowLabel?: (item: MetricResponse) => ReactNode;
+ customFilters?: Filter[];
+ customTime?: Time;
+};
+
+type StandardSectionProps = StandardSectionBaseProps & {
+ expanded?: boolean;
+ close?: () => void;
+ renderDialog?: boolean;
+};
+
export function StandardSection({
title,
getKey,
@@ -34,22 +55,8 @@ export function StandardSection({
getSubrowLabel,
customFilters,
customTime,
-}: {
- title: string;
- getKey: (item: MetricResponse) => string;
- getLabel: (item: MetricResponse) => ReactNode;
- getValue: (item: MetricResponse) => string;
- getFilterLabel?: (item: MetricResponse) => string;
- getLink?: (item: MetricResponse) => string;
- countLabel?: string;
- filterParameter: FilterParameter;
- expanded: boolean;
- close: () => void;
- hasSubrow?: boolean;
- getSubrowLabel?: (item: MetricResponse) => ReactNode;
- customFilters?: Filter[];
- customTime?: Time;
-}) {
+ renderDialog = true,
+}: StandardSectionProps) {
const t = useExtracted();
const { data, isLoading, isFetching, error, refetch } = usePaginatedMetric({
parameter: filterParameter,
@@ -80,7 +87,11 @@ export function StandardSection({
</TooltipTrigger>
<TooltipContent>
{t("Geolocation by")}{" "}
- <Link href="https://www.maxmind.com/" target="_blank" className="text-emerald-400 hover:text-emerald-300">
+ <Link
+ href="https://www.maxmind.com/"
+ target="_blank"
+ className="text-emerald-400 hover:text-emerald-300"
+ >
Maxmind
</Link>
</TooltipContent>
@@ -122,11 +133,10 @@ export function StandardSection({
)}
</>
)}
- {!isLoading && !error && itemsForDisplay?.length ? (
+ {renderDialog && close && !isLoading && !error && itemsForDisplay?.length ? (
<div className="flex flex-row gap-2 justify-between items-center">
<StandardSectionDialog
title={title}
- ratio={ratio}
getKey={getKey}
getLabel={getLabel}
getValue={getValue}
@@ -136,6 +146,8 @@ export function StandardSection({
filterParameter={filterParameter}
expanded={expanded}
close={close}
+ customFilters={customFilters}
+ customTime={customTime}
/>
</div>
) : null}
diff --git a/client/src/app/[site]/components/shared/StandardSection/StandardSectionDialog.tsx b/client/src/app/[site]/components/shared/StandardSection/StandardSectionDialog.tsx
index f539e28d1..141c516d5 100644
--- a/client/src/app/[site]/components/shared/StandardSection/StandardSectionDialog.tsx
+++ b/client/src/app/[site]/components/shared/StandardSection/StandardSectionDialog.tsx
@@ -6,10 +6,9 @@ import {
} from "@/components/ui/responsive-dialog";
import { Input } from "@/components/ui/input";
import { TableSortIndicator } from "@/components/ui/table";
-import { FilterParameter } from "@rybbit/shared";
+import { Filter, FilterParameter } from "@rybbit/shared";
import {
ColumnDef,
- ColumnHelper,
createColumnHelper,
flexRender,
getCoreRowModel,
@@ -23,12 +22,13 @@ import { useExtracted } from "next-intl";
import { ReactNode, useEffect, useMemo, useState } from "react";
import { useInfiniteMetric } from "../../../../../api/analytics/hooks/useGetMetric";
import { MetricResponse } from "../../../../../api/analytics/endpoints";
+import { ErrorState } from "../../../../../components/ErrorState";
import { addFilter } from "../../../../../lib/store";
import { cn, formatSecondsAsMinutesAndSeconds } from "../../../../../lib/utils";
+import { Time } from "../../../../../components/DateSelector/types";
-interface StandardSectionDialogProps {
+export interface StandardSectionDialogBodyProps {
title: string;
- ratio: number;
getKey: (item: MetricResponse) => string;
getLabel: (item: MetricResponse) => ReactNode;
getValue: (item: MetricResponse) => string;
@@ -36,30 +36,35 @@ interface StandardSectionDialogProps {
getLink?: (item: MetricResponse) => string;
countLabel?: string;
filterParameter: FilterParameter;
+ customFilters?: Filter[];
+ customTime?: Time;
+}
+
+interface StandardSectionDialogProps extends StandardSectionDialogBodyProps {
expanded?: boolean;
close: () => void;
}
const columnHelper = createColumnHelper<MetricResponse>();
-export function StandardSectionDialog({
+export function StandardSectionDialogBody({
title,
- ratio,
- getKey,
getLabel,
getValue,
getFilterLabel,
getLink,
countLabel,
filterParameter,
- expanded,
- close,
-}: StandardSectionDialogProps) {
+ customFilters,
+ customTime,
+}: StandardSectionDialogBodyProps) {
const t = useExtracted();
- const { data, isLoading, isFetching, error, refetch, fetchNextPage, hasNextPage, isFetchingNextPage } =
+ const { data, isLoading, isError, error, refetch, fetchNextPage, hasNextPage, isFetchingNextPage } =
useInfiniteMetric({
parameter: filterParameter,
limit: 100,
+ customFilters,
+ customTime,
});
const [searchTerm, setSearchTerm] = useState("");
@@ -100,7 +105,12 @@ export function StandardSectionDialog({
<div className="flex flex-row gap-1 items-center text-left">
{getLabel(row.original)}
{getLink && (
- <a rel="noopener noreferrer" href={getLink(row.original)} target="_blank" onClick={e => e.stopPropagation()}>
+ <a
+ rel="noopener noreferrer"
+ href={getLink(row.original)}
+ target="_blank"
+ onClick={e => e.stopPropagation()}
+ >
<SquareArrowOutUpRight
className="ml-0.5 w-3.5 h-3.5 text-neutral-600 hover:text-neutral-900 dark:text-neutral-300 dark:hover:text-neutral-100"
strokeWidth={3}
@@ -111,7 +121,7 @@ export function StandardSectionDialog({
),
}),
columnHelper.accessor("count", {
- header: t("Sessions"),
+ header: countLabel || t("Sessions"),
cell: info => (
<div className="flex flex-row gap-1 items-center sm:justify-end">{info.getValue().toLocaleString()}</div>
),
@@ -173,7 +183,7 @@ export function StandardSectionDialog({
}
return cols;
- }, [filteredData, title, getLabel, getLink]);
+ }, [filteredData, title, getLabel, getLink, countLabel, t]);
// Fetch next page when intersection observer detects the target is visible
useEffect(() => {
@@ -196,109 +206,120 @@ export function StandardSectionDialog({
sortDescFirst: true,
});
+ if (isError) {
+ return (
+ <ErrorState
+ title={t("Failed to load data")}
+ message={error?.message || t("An error occurred while fetching data")}
+ refetch={refetch}
+ />
+ );
+ }
+
if (isLoading || !data) {
return (
- <ResponsiveDialog open={expanded} onOpenChange={close}>
- <ResponsiveDialogContent className="max-w-[1000px] w-[calc(100vw-2rem)] p-2 sm:p-4">
- <div className="flex justify-center items-center h-40">
- <Loader2 className="h-8 w-8 animate-spin text-neutral-600 dark:text-neutral-400" />
- </div>
- </ResponsiveDialogContent>
- </ResponsiveDialog>
+ <div className="flex justify-center items-center h-40">
+ <Loader2 className="h-8 w-8 animate-spin text-neutral-600 dark:text-neutral-400" />
+ </div>
);
}
- const totalCount = data.pages[0]?.totalCount || 0;
return (
- <ResponsiveDialog open={expanded} onOpenChange={close}>
- <ResponsiveDialogContent className="max-w-[1000px] w-screen max-h-[1000px] h-[calc(100vh-2rem)] p-2 sm:p-4 flex flex-col gap-2">
- <ResponsiveDialogHeader>
- <ResponsiveDialogTitle>{title}</ResponsiveDialogTitle>
- </ResponsiveDialogHeader>
- <Input
- type="text"
- placeholder={t("Filter {count} items...", { count: String(allItems.length) })}
- className="bg-white dark:bg-neutral-900 border-neutral-200 dark:border-neutral-700 text-xs"
- value={searchTerm}
- inputSize="sm"
- onChange={e => setSearchTerm(e.target.value)}
- />
- <div className="max-h-[85vh] overflow-auto relative overflow-x-auto">
- <table className="w-full text-xs text-left min-w-max">
- <thead className="sticky top-0 z-10 bg-neutral-100 dark:bg-neutral-850 [&_tr]:border-b-0">
- {table.getHeaderGroups().map(headerGroup => (
- <tr key={headerGroup.id} className="border-b-0">
- {headerGroup.headers.map((header, index) => (
- <th
- key={header.id}
+ <>
+ <Input
+ type="text"
+ placeholder={t("Filter {count} items...", { count: String(allItems.length) })}
+ className="bg-white dark:bg-neutral-900 border-neutral-200 dark:border-neutral-700 text-xs"
+ value={searchTerm}
+ inputSize="sm"
+ onChange={e => setSearchTerm(e.target.value)}
+ />
+ <div className="min-h-0 flex-1 overflow-auto relative overflow-x-auto">
+ <table className="w-full text-xs text-left min-w-max">
+ <thead className="sticky top-0 z-10 bg-neutral-100 dark:bg-neutral-850 [&_tr]:border-b-0">
+ {table.getHeaderGroups().map(headerGroup => (
+ <tr key={headerGroup.id} className="border-b-0">
+ {headerGroup.headers.map((header, index) => (
+ <th
+ key={header.id}
+ className={cn(
+ "h-8 px-2 text-left align-middle font-medium text-neutral-500 dark:text-neutral-400 first:rounded-l-lg last:rounded-r-lg",
+ "font-medium whitespace-nowrap cursor-pointer select-none",
+ index === 0 ? "text-left" : "text-right"
+ )}
+ style={{
+ minWidth: header.id === "user_id" ? "100px" : "auto",
+ }}
+ onClick={header.column.getToggleSortingHandler()}
+ >
+ <div className={cn("flex items-center gap-1", index !== 0 && "justify-end")}>
+ {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
+ <TableSortIndicator sortDirection={header.column.getIsSorted()} />
+ </div>
+ </th>
+ ))}
+ </tr>
+ ))}
+ </thead>
+ <tbody className="[&_tr:last-child]:border-0 bg-white dark:bg-neutral-900">
+ {table.getRowModel().rows.map(row => {
+ return (
+ <tr
+ key={row.id}
+ className="border-b border-b-neutral-100 transition-colors hover:bg-neutral-100/50 dark:border-b-neutral-800 dark:hover:bg-neutral-800/20 cursor-pointer group"
+ onClick={() =>
+ addFilter({
+ parameter: filterParameter,
+ value: [getValue(row.original)],
+ type: "equals",
+ })
+ }
+ >
+ {row.getVisibleCells().map((cell, cellIndex) => (
+ <td
+ key={cell.id}
className={cn(
- "h-8 px-2 text-left align-middle font-medium text-neutral-500 dark:text-neutral-400 first:rounded-l-lg last:rounded-r-lg",
- "font-medium whitespace-nowrap cursor-pointer select-none",
- index === 0 ? "text-left" : "text-right"
+ "p-2 align-middle [&:has([role=checkbox])]:pr-0 *:[role=checkbox]:translate-y-[2px]",
+ "relative",
+ cellIndex !== 0 && "text-right"
)}
- style={{
- minWidth: header.id === "user_id" ? "100px" : "auto",
- }}
- onClick={header.column.getToggleSortingHandler()}
>
- <div className={cn("flex items-center gap-1", index !== 0 && "justify-end")}>
- {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
- <TableSortIndicator sortDirection={header.column.getIsSorted()} />
- </div>
- </th>
+ <span className="relative z-0">{flexRender(cell.column.columnDef.cell, cell.getContext())}</span>
+ </td>
))}
</tr>
- ))}
- </thead>
- <tbody className="[&_tr:last-child]:border-0 bg-white dark:bg-neutral-900">
- {table.getRowModel().rows.map(row => {
- return (
- <tr
- key={row.id}
- className="border-b border-b-neutral-100 transition-colors hover:bg-neutral-100/50 dark:border-b-neutral-800 dark:hover:bg-neutral-800/20 cursor-pointer group"
- onClick={() =>
- addFilter({
- parameter: filterParameter,
- value: [getValue(row.original)],
- type: "equals",
- })
- }
- >
- {row.getVisibleCells().map((cell, cellIndex) => (
- <td
- key={cell.id}
- className={cn(
- "p-2 align-middle [&:has([role=checkbox])]:pr-0 *:[role=checkbox]:translate-y-[2px]",
- "relative",
- cellIndex !== 0 && "text-right"
- )}
- >
- <span className="relative z-0">
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </span>
- </td>
- ))}
- </tr>
- );
- })}
- </tbody>
- </table>
+ );
+ })}
+ </tbody>
+ </table>
- {/* Infinite scroll loading indicator and observer anchor */}
- {filteredData.length > 0 && (
- <div ref={ref} className="py-4 flex justify-center">
- {isFetchingNextPage && (
- <div className="flex items-center gap-2 text-neutral-600 dark:text-neutral-400 text-xs">
- <Loader2 className="h-4 w-4 animate-spin" />
- {t("Loading more...")}
- </div>
- )}
- {!hasNextPage && !isFetchingNextPage && (
- <div className="text-neutral-500 dark:text-neutral-500 text-xs">{t("All items loaded")}</div>
- )}
- </div>
- )}
- </div>
+ {/* Infinite scroll loading indicator and observer anchor */}
+ {filteredData.length > 0 && (
+ <div ref={ref} className="py-4 flex justify-center">
+ {isFetchingNextPage && (
+ <div className="flex items-center gap-2 text-neutral-600 dark:text-neutral-400 text-xs">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ {t("Loading more...")}
+ </div>
+ )}
+ {!hasNextPage && !isFetchingNextPage && (
+ <div className="text-neutral-500 dark:text-neutral-500 text-xs">{t("All items loaded")}</div>
+ )}
+ </div>
+ )}
+ </div>
+ </>
+ );
+}
+
+export function StandardSectionDialog({ expanded, close, ...bodyProps }: StandardSectionDialogProps) {
+ return (
+ <ResponsiveDialog open={expanded} onOpenChange={open => !open && close()}>
+ <ResponsiveDialogContent className="max-w-[1000px] w-screen max-h-[1000px] h-[calc(100vh-2rem)] p-2 sm:p-4 flex flex-col gap-2">
+ <ResponsiveDialogHeader>
+ <ResponsiveDialogTitle>{bodyProps.title}</ResponsiveDialogTitle>
+ </ResponsiveDialogHeader>
+ <StandardSectionDialogBody {...bodyProps} />
</ResponsiveDialogContent>
</ResponsiveDialog>
);
diff --git a/client/src/app/[site]/components/shared/StandardSection/StandardSectionTabs.tsx b/client/src/app/[site]/components/shared/StandardSection/StandardSectionTabs.tsx
new file mode 100644
index 000000000..c2796478c
--- /dev/null
+++ b/client/src/app/[site]/components/shared/StandardSection/StandardSectionTabs.tsx
@@ -0,0 +1,56 @@
+"use client";
+
+import { ReactNode } from "react";
+import { TabbedSectionCard, type TabbedSectionCardProps, type TabbedSectionItem } from "../TabbedSectionCard";
+import { StandardSection, type StandardSectionBaseProps } from "./StandardSection";
+import { StandardSectionDialogBody } from "./StandardSectionDialog";
+
+export type StandardSectionTab<TValue extends string> = {
+ value: TValue;
+ label: ReactNode;
+ showInTabs?: boolean;
+ dialogTitle?: ReactNode;
+} & (
+ | {
+ section: StandardSectionBaseProps;
+ content?: never;
+ dialogContent?: never;
+ }
+ | {
+ content: ReactNode;
+ dialogContent?: ReactNode;
+ section?: never;
+ }
+);
+
+type StandardSectionTabsProps<TValue extends string> = Omit<TabbedSectionCardProps<TValue>, "tabs"> & {
+ tabs: StandardSectionTab<TValue>[];
+};
+
+export function StandardSectionTabs<TValue extends string>({ tabs, ...props }: StandardSectionTabsProps<TValue>) {
+ const tabItems: TabbedSectionItem<TValue>[] = tabs.map(tab => {
+ if (tab.section) {
+ const { section } = tab;
+
+ return {
+ value: tab.value,
+ label: tab.label,
+ showInTabs: tab.showInTabs,
+ dialogTitle: tab.dialogTitle ?? section.title,
+ content: <StandardSection {...section} renderDialog={false} />,
+ dialogContent: <StandardSectionDialogBody {...section} />,
+ };
+ }
+
+ return {
+ value: tab.value,
+ label: tab.label,
+ showInTabs: tab.showInTabs,
+ dialogTitle: tab.dialogTitle,
+ content: tab.content,
+ dialogContent: tab.dialogContent,
+ };
+ });
+
+ return <TabbedSectionCard {...props} tabs={tabItems} />;
+}
diff --git a/client/src/app/[site]/components/shared/TabbedSectionCard.tsx b/client/src/app/[site]/components/shared/TabbedSectionCard.tsx
new file mode 100644
index 000000000..f8afd75f3
--- /dev/null
+++ b/client/src/app/[site]/components/shared/TabbedSectionCard.tsx
@@ -0,0 +1,132 @@
+"use client";
+
+import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
+import { Expand } from "lucide-react";
+import { ReactNode, useMemo, useState } from "react";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../components/ui/basic-tabs";
+import { Button } from "../../../../components/ui/button";
+import { Card, CardContent } from "../../../../components/ui/card";
+import {
+ ResponsiveDialog,
+ ResponsiveDialogContent,
+ ResponsiveDialogTitle,
+} from "../../../../components/ui/responsive-dialog";
+import { cn } from "../../../../lib/utils";
+
+export type TabbedSectionItem<TValue extends string> = {
+ value: TValue;
+ label: ReactNode;
+ content: ReactNode;
+ dialogContent?: ReactNode;
+ dialogTitle?: ReactNode;
+ showInTabs?: boolean;
+};
+
+export type TabbedSectionListContext<TValue extends string> = {
+ value: TValue;
+ setValue: (value: TValue) => void;
+ inDialog: boolean;
+};
+
+export type TabbedSectionCardProps<TValue extends string> = {
+ defaultValue: TValue;
+ tabs: TabbedSectionItem<TValue>[];
+ className?: string;
+ contentClassName?: string;
+ dialogClassName?: string;
+ renderTabsListEnd?: (context: TabbedSectionListContext<TValue>) => ReactNode;
+};
+
+export function TabbedSectionCard<TValue extends string>({
+ defaultValue,
+ tabs,
+ className,
+ contentClassName,
+ dialogClassName,
+ renderTabsListEnd,
+}: TabbedSectionCardProps<TValue>) {
+ const [value, setValue] = useState<TValue>(defaultValue);
+ const [expanded, setExpanded] = useState(false);
+
+ const visibleTabs = useMemo(() => tabs.filter(tab => tab.showInTabs !== false), [tabs]);
+ const dialogTabs = useMemo(() => tabs.filter(tab => tab.dialogContent), [tabs]);
+ const activeDialogTab = dialogTabs.find(tab => tab.value === value) ?? dialogTabs[0];
+ const dialogValue = activeDialogTab?.value ?? value;
+ const canExpand = dialogTabs.some(tab => tab.value === value);
+
+ const renderTabsList = (inDialog: boolean) => {
+ const listTabs = inDialog ? dialogTabs.filter(tab => tab.showInTabs !== false) : visibleTabs;
+
+ return (
+ <TabsList>
+ {listTabs.map(tab => (
+ <TabsTrigger key={tab.value} value={tab.value}>
+ {tab.label}
+ </TabsTrigger>
+ ))}
+ {renderTabsListEnd?.({ value, setValue, inDialog })}
+ </TabsList>
+ );
+ };
+
+ const handleOpenChange = (open: boolean) => {
+ setExpanded(open);
+ };
+
+ return (
+ <>
+ <Card className={cn("h-[405px]", className)}>
+ <CardContent className={cn("mt-2", contentClassName)}>
+ <Tabs defaultValue={defaultValue} value={value} onValueChange={nextValue => setValue(nextValue as TValue)}>
+ <div className="flex flex-row gap-2 justify-between items-center">
+ <div className="overflow-x-auto">{renderTabsList(false)}</div>
+ <div className="w-7">
+ {canExpand && (
+ <Button size="smIcon" onClick={() => setExpanded(true)} aria-label="Expand section">
+ <Expand className="w-4 h-4" />
+ </Button>
+ )}
+ </div>
+ </div>
+ {tabs.map(tab => (
+ <TabsContent key={tab.value} value={tab.value}>
+ {tab.content}
+ </TabsContent>
+ ))}
+ </Tabs>
+ </CardContent>
+ </Card>
+ {activeDialogTab && (
+ <ResponsiveDialog open={expanded} onOpenChange={handleOpenChange}>
+ <ResponsiveDialogContent
+ className={cn(
+ "max-w-[1000px] w-screen max-h-[1000px] h-[calc(100vh-2rem)] overflow-hidden p-2 sm:p-4 flex flex-col gap-2",
+ dialogClassName
+ )}
+ >
+ <VisuallyHidden>
+ <ResponsiveDialogTitle>{activeDialogTab.dialogTitle ?? activeDialogTab.label}</ResponsiveDialogTitle>
+ </VisuallyHidden>
+ <Tabs
+ defaultValue={defaultValue}
+ value={dialogValue}
+ onValueChange={nextValue => setValue(nextValue as TValue)}
+ className="min-h-0 flex flex-1 flex-col gap-2 overflow-hidden"
+ >
+ <div className="overflow-x-auto pr-8">{renderTabsList(true)}</div>
+ {dialogTabs.map(tab => (
+ <TabsContent
+ key={tab.value}
+ value={tab.value}
+ className="mt-0 min-h-0 flex-1 overflow-hidden data-[state=active]:flex data-[state=active]:flex-col"
+ >
+ {tab.dialogContent}
+ </TabsContent>
+ ))}
+ </Tabs>
+ </ResponsiveDialogContent>
+ </ResponsiveDialog>
+ )}
+ </>
+ );
+}
diff --git a/client/src/app/[site]/goals/components/GoalCard.tsx b/client/src/app/[site]/goals/components/GoalCard.tsx
index 99040fabd..ff57e5594 100644
--- a/client/src/app/[site]/goals/components/GoalCard.tsx
+++ b/client/src/app/[site]/goals/components/GoalCard.tsx
@@ -1,10 +1,11 @@
"use client";
import { useExtracted } from "next-intl";
-import { ChevronDown, ChevronUp, Copy, Edit, Trash2 } from "lucide-react";
-import { useState } from "react";
+import { ChevronDown, ChevronUp, Copy, Edit, MoreHorizontal, Trash2 } from "lucide-react";
+import { DateTime } from "luxon";
+import { useMemo, useState } from "react";
import { useDeleteGoal } from "../../../../api/analytics/hooks/goals/useDeleteGoal";
-import { Goal } from "../../../../api/analytics/endpoints";
+import { Goal, GoalTimeSeriesPoint } from "../../../../api/analytics/endpoints";
import { useGetGoalSessions } from "../../../../api/analytics/hooks/goals/useGetGoalSessions";
import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";
import { SessionsList } from "../../../../components/Sessions/SessionsList";
@@ -19,20 +20,144 @@ import {
AlertDialogTitle,
} from "../../../../components/ui/alert-dialog";
import { Button } from "../../../../components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "../../../../components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
-import { useStore } from "../../../../lib/store";
+import { formatChartDateTime } from "../../../../lib/dateTimeUtils";
+import { getTimezone, useStore } from "../../../../lib/store";
import GoalFormModal from "./GoalFormModal";
+import { GoalBarChartSkeleton } from "./skeleton";
interface GoalCardProps {
goal: Goal;
siteId: number;
+ timeSeries?: GoalTimeSeriesPoint[];
+ isLoadingTimeSeries: boolean;
}
const LIMIT = 25;
+const MAX_BARS = 44;
+
+type ChartMetric = "conversions" | "conversion_rate";
+type GoalMetricBar = {
+ value: number;
+ conversions: number;
+ sessions: number;
+ startTime: string;
+ endTime: string;
+};
+
+const formatMetricValue = (metric: ChartMetric, value: number) => {
+ if (metric === "conversion_rate") {
+ return `${(value * 100).toFixed(2)}%`;
+ }
+
+ return value.toLocaleString();
+};
+
+const formatBarTime = (bar: GoalMetricBar, bucket: ReturnType<typeof useStore.getState>["bucket"]) => {
+ const timezone = getTimezone();
+ const start = DateTime.fromSQL(bar.startTime, { zone: timezone });
+ const end = DateTime.fromSQL(bar.endTime, { zone: timezone });
+ const startLabel = formatChartDateTime(start, bucket);
+ const endLabel = formatChartDateTime(end, bucket);
+
+ return startLabel === endLabel ? startLabel : `${startLabel} - ${endLabel}`;
+};
+
+function GoalMetricBarChart({
+ data,
+ metric,
+ isLoading,
+}: {
+ data?: GoalTimeSeriesPoint[];
+ metric: ChartMetric;
+ isLoading: boolean;
+}) {
+ const t = useExtracted();
+ const { bucket } = useStore();
+
+ const bars = useMemo(() => {
+ if (!data?.length) return [];
+
+ const groupSize = Math.ceil(data.length / MAX_BARS);
+ const grouped: GoalMetricBar[] = [];
+
+ for (let i = 0; i < data.length; i += groupSize) {
+ const group = data.slice(i, i + groupSize);
+ const conversions = group.reduce((sum, point) => sum + point.conversions, 0);
+ const sessions = group.reduce((sum, point) => sum + point.total_sessions, 0);
+
+ grouped.push({
+ value: metric === "conversions" ? conversions : sessions > 0 ? conversions / sessions : 0,
+ conversions,
+ sessions,
+ startTime: group[0].time,
+ endTime: group[group.length - 1].time,
+ });
+ }
+
+ return grouped;
+ }, [data, metric]);
+
+ if (isLoading) {
+ return <GoalBarChartSkeleton />;
+ }
+
+ if (bars.length === 0) {
+ return <GoalBarChartSkeleton />;
+ }
+
+ const max = Math.max(...bars.map(bar => bar.value));
+ const metricLabel = metric === "conversions" ? t("Conversions") : t("Conversion Rate");
+
+ return (
+ <div className="hidden md:flex h-8 w-48 shrink-0 items-end gap-px">
+ {bars.map((bar, index) => {
+ const height = max > 0 ? Math.max(10, (bar.value / max) * 100) : 10;
+
+ return (
+ <Tooltip key={`${metric}-${index}`} delayDuration={100}>
+ <TooltipTrigger asChild>
+ <div
+ className={
+ metric === "conversions"
+ ? "flex-1 min-w-px rounded-t-sm bg-dataviz/70 dark:bg-dataviz/70"
+ : "flex-1 min-w-px rounded-t-sm bg-dataviz/70 dark:bg-dataviz/70"
+ }
+ style={{
+ height: `${height}%`,
+ opacity: max > 0 ? 1 : 0.35,
+ }}
+ onClick={event => event.stopPropagation()}
+ />
+ </TooltipTrigger>
+ <TooltipContent side="top" className="w-44">
+ <div className="space-y-1">
+ <div className="font-medium text-neutral-700 dark:text-neutral-200">{formatBarTime(bar, bucket)}</div>
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-neutral-500 dark:text-neutral-400">{metricLabel}</span>
+ <span className="font-semibold">{formatMetricValue(metric, bar.value)}</span>
+ </div>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ );
+ })}
+ </div>
+ );
+}
-export default function GoalCard({ goal, siteId }: GoalCardProps) {
+export default function GoalCard({ goal, siteId, timeSeries, isLoadingTimeSeries }: GoalCardProps) {
const t = useExtracted();
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
+ const [isEditModalOpen, setIsEditModalOpen] = useState(false);
+ const [isCloneModalOpen, setIsCloneModalOpen] = useState(false);
const [isExpanded, setIsExpanded] = useState(false);
const [page, setPage] = useState(1);
const deleteGoalMutation = useDeleteGoal();
@@ -73,12 +198,12 @@ export default function GoalCard({ goal, siteId }: GoalCardProps) {
<>
<div className="rounded-lg bg-white dark:bg-neutral-900 border border-neutral-100 dark:border-neutral-800 overflow-hidden relative">
<div
- className="px-4 py-3 flex items-center mb-1 cursor-pointer hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition-colors"
+ className="px-4 py-3 flex gap-3 flex-row items-center mb-1 cursor-pointer hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition-colors"
onClick={toggleExpansion}
>
{/* Left section - Title and type */}
- <div className="flex-1 pr-4">
- <h3 className="font-medium text-base flex items-center gap-2">
+ <div className="w-full min-w-0 md:flex-1 md:pr-4">
+ <h3 className="font-medium text-base flex items-center gap-2 min-w-0">
{goal.goalType === "path" ? (
<Tooltip>
<TooltipTrigger asChild>
@@ -98,12 +223,12 @@ export default function GoalCard({ goal, siteId }: GoalCardProps) {
</TooltipContent>
</Tooltip>
)}
- {goal.name || t("Goal #{goalId}", { goalId: String(goal.goalId) })}
+ <span className="truncate">{goal.name || t("Goal #{goalId}", { goalId: String(goal.goalId) })}</span>
</h3>
- <div className="mt-1">
+ <div className="mt-1 min-w-0">
<span className="text-xs text-neutral-500 dark:text-neutral-400 mr-2">{t("Pattern")}:</span>
- <code className="text-xs bg-neutral-100 dark:bg-neutral-800 px-1 py-0.5 rounded">
+ <code className="inline-block max-w-full truncate align-bottom text-xs bg-neutral-100 dark:bg-neutral-800 px-1 py-0.5 rounded">
{goal.goalType === "path" ? goal.config.pathPattern : goal.config.eventName}
</code>
@@ -117,71 +242,54 @@ export default function GoalCard({ goal, siteId }: GoalCardProps) {
)}
</div>
</div>
-
{/* Center section - Stats */}
- <div className="flex-1 flex justify-center">
- <div className="grid grid-cols-2 gap-4">
- <div className="text-center">
- <div className="font-bold text-base">{goal.total_conversions.toLocaleString()}</div>
- <div className="text-xs text-neutral-500 dark:text-neutral-400">{t("Conversions")}</div>
+ <div className="w-full md:flex-1 flex justify-start md:justify-center">
+ <div className="grid w-full grid-cols-1 gap-3 sm:grid-cols-2 md:w-auto md:gap-4">
+ <div className="flex items-center gap-3">
+ <GoalMetricBarChart data={timeSeries} metric="conversions" isLoading={isLoadingTimeSeries} />
+ <div className="min-w-[86px] text-left">
+ <div className="font-bold text-base">{goal.total_conversions.toLocaleString()}</div>
+ <div className="text-xs text-neutral-500 dark:text-neutral-400">{t("Conversions")}</div>
+ </div>
</div>
- <div className="text-center">
- <div className="font-bold text-base">{(goal.conversion_rate * 100).toFixed(2)}%</div>
- <div className="text-xs text-neutral-500 dark:text-neutral-400">{t("Conversion Rate")}</div>
+ <div className="flex items-center gap-3">
+ <GoalMetricBarChart data={timeSeries} metric="conversion_rate" isLoading={isLoadingTimeSeries} />
+ <div className="min-w-[104px] text-left">
+ <div className="font-bold text-base">{(goal.conversion_rate * 100).toFixed(2)}%</div>
+ <div className="text-xs text-neutral-500 dark:text-neutral-400">{t("Conversion Rate")}</div>
+ </div>
</div>
</div>
</div>
-
{/* Right section - Actions */}
- <div className="flex shrink-0 gap-1 pl-4">
+ <div className="flex shrink-0 justify-end gap-1 md:pl-4">
<div onClick={e => e.stopPropagation()}>
- <GoalFormModal
- siteId={siteId}
- goal={goal}
- trigger={
- <Tooltip>
- <TooltipTrigger asChild>
- <Button variant="ghost" size="smIcon">
- <Edit className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{t("Edit Goal")}</TooltipContent>
- </Tooltip>
- }
- />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild variant="ghost" size="smIcon" aria-label={t("Goal actions")}>
+ <Button variant="ghost" size="smIcon" aria-label={t("Goal actions")}>
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setIsEditModalOpen(true)}>
+ <Edit className="h-4 w-4" />
+ {t("Edit Goal")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setIsCloneModalOpen(true)}>
+ <Copy className="h-4 w-4" />
+ {t("Clone Goal")}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => setIsDeleteDialogOpen(true)}
+ className="text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400"
+ >
+ <Trash2 className="h-4 w-4" />
+ {t("Delete Goal")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
</div>
- <div onClick={e => e.stopPropagation()}>
- <GoalFormModal
- siteId={siteId}
- goal={goal}
- isCloneMode={true}
- trigger={
- <Tooltip>
- <TooltipTrigger asChild>
- <Button variant="ghost" size="smIcon">
- <Copy className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{t("Clone Goal")}</TooltipContent>
- </Tooltip>
- }
- />
- </div>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- onClick={e => {
- e.stopPropagation(); // Prevent expanding when clicking delete
- setIsDeleteDialogOpen(true);
- }}
- variant="ghost"
- size="smIcon"
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{t("Delete Goal")}</TooltipContent>
- </Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button variant="ghost" size="smIcon">
@@ -205,7 +313,9 @@ export default function GoalCard({ goal, siteId }: GoalCardProps) {
{/* Expanded Sessions Section */}
{isExpanded && (
<div className="border-t border-neutral-100 dark:border-neutral-800 bg-neutral-50 dark:bg-neutral-900/50 p-4">
- <h4 className="text-sm font-medium text-neutral-700 dark:text-neutral-200 mb-3">{t("Converted Sessions")}</h4>
+ <h4 className="text-sm font-medium text-neutral-700 dark:text-neutral-200 mb-3">
+ {t("Converted Sessions")}
+ </h4>
<SessionsList
sessions={sessions}
isLoading={isLoadingSessions}
@@ -218,7 +328,14 @@ export default function GoalCard({ goal, siteId }: GoalCardProps) {
</div>
)}
</div>
-
+ <GoalFormModal siteId={siteId} goal={goal} open={isEditModalOpen} onOpenChange={setIsEditModalOpen} />
+ <GoalFormModal
+ siteId={siteId}
+ goal={goal}
+ isCloneMode={true}
+ open={isCloneModalOpen}
+ onOpenChange={setIsCloneModalOpen}
+ />
{/* Delete Confirmation Dialog */}
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogContent>
diff --git a/client/src/app/[site]/goals/components/GoalFormModal.tsx b/client/src/app/[site]/goals/components/GoalFormModal.tsx
index 3d702bba4..26d03e26d 100644
--- a/client/src/app/[site]/goals/components/GoalFormModal.tsx
+++ b/client/src/app/[site]/goals/components/GoalFormModal.tsx
@@ -69,8 +69,7 @@ const formSchema = z
return true;
},
{
- message:
- "Enter a path (e.g., /checkout), not a full URL. The domain is already determined by your site.",
+ message: "Enter a path (e.g., /checkout), not a full URL. The domain is already determined by your site.",
path: ["config", "pathPattern"],
}
);
@@ -80,13 +79,29 @@ type FormValues = z.infer<typeof formSchema>;
interface GoalFormModalProps {
siteId: number;
goal?: Goal; // Optional goal for editing mode
- trigger: React.ReactNode;
+ trigger?: React.ReactNode;
isCloneMode?: boolean; // Optional clone mode flag
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
}
-export default function GoalFormModal({ siteId, goal, trigger, isCloneMode = false }: GoalFormModalProps) {
+export default function GoalFormModal({
+ siteId,
+ goal,
+ trigger,
+ isCloneMode = false,
+ open,
+ onOpenChange,
+}: GoalFormModalProps) {
const t = useExtracted();
- const [isOpen, setIsOpen] = useState(false);
+ const [internalOpen, setInternalOpen] = useState(false);
+ const isOpen = open ?? internalOpen;
+ const setIsOpen = (nextOpen: boolean) => {
+ if (open === undefined) {
+ setInternalOpen(nextOpen);
+ }
+ onOpenChange?.(nextOpen);
+ };
// Initialize useProperties based on either new propertyFilters or legacy properties
const hasProperties = !!(
@@ -258,9 +273,11 @@ export default function GoalFormModal({ siteId, goal, trigger, isCloneMode = fal
}
}}
>
- <DialogTrigger asChild>
- <div onClick={() => setIsOpen(true)}>{trigger}</div>
- </DialogTrigger>
+ {trigger && (
+ <DialogTrigger asChild>
+ <div onClick={() => setIsOpen(true)}>{trigger}</div>
+ </DialogTrigger>
+ )}
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>{isEditMode ? t("Edit Goal") : isCloneMode ? t("Clone Goal") : t("Create Goal")}</DialogTitle>
diff --git a/client/src/app/[site]/goals/components/GoalsList.tsx b/client/src/app/[site]/goals/components/GoalsList.tsx
index 2a9d0d543..629714d4f 100644
--- a/client/src/app/[site]/goals/components/GoalsList.tsx
+++ b/client/src/app/[site]/goals/components/GoalsList.tsx
@@ -1,18 +1,26 @@
"use client";
import GoalCard from "./GoalCard";
-import { Goal } from "../../../../api/analytics/endpoints";
+import { Goal, GoalTimeSeriesPoint } from "../../../../api/analytics/endpoints";
interface GoalsListProps {
goals: Goal[];
siteId: number;
+ timeSeriesByGoal: Map<number, GoalTimeSeriesPoint[]>;
+ isLoadingTimeSeries: boolean;
}
-export default function GoalsList({ goals, siteId }: GoalsListProps) {
+export default function GoalsList({ goals, siteId, timeSeriesByGoal, isLoadingTimeSeries }: GoalsListProps) {
return (
<div className="flex flex-col gap-3">
{goals.map(goal => (
- <GoalCard key={goal.goalId} goal={goal} siteId={siteId} />
+ <GoalCard
+ key={goal.goalId}
+ goal={goal}
+ siteId={siteId}
+ timeSeries={timeSeriesByGoal.get(goal.goalId)}
+ isLoadingTimeSeries={isLoadingTimeSeries}
+ />
))}
</div>
);
diff --git a/client/src/app/[site]/goals/components/skeleton.tsx b/client/src/app/[site]/goals/components/skeleton.tsx
new file mode 100644
index 000000000..74a0eba03
--- /dev/null
+++ b/client/src/app/[site]/goals/components/skeleton.tsx
@@ -0,0 +1,11 @@
+export const GoalBarChartSkeleton = () => (
+ <div className="hidden md:flex h-8 w-48 shrink-0 items-end gap-px">
+ {[12, 20, 14, 26, 18, 30, 22, 16, 28, 24, 18, 32].map((height, index) => (
+ <div
+ key={`${height}-${index}`}
+ className="flex-1 min-w-px rounded-t-sm bg-neutral-200 dark:bg-neutral-800"
+ style={{ height }}
+ />
+ ))}
+ </div>
+);
diff --git a/client/src/app/[site]/goals/page.tsx b/client/src/app/[site]/goals/page.tsx
index ab6729c20..d80c798ab 100644
--- a/client/src/app/[site]/goals/page.tsx
+++ b/client/src/app/[site]/goals/page.tsx
@@ -2,7 +2,10 @@
import { useExtracted } from "next-intl";
import { useMemo, useState } from "react";
+import { useGetGoalTimeSeries } from "../../../api/analytics/hooks/goals/useGetGoalTimeSeries";
import { useGetGoals } from "../../../api/analytics/hooks/goals/useGetGoals";
+import { GoalTimeSeriesPoint } from "../../../api/analytics/endpoints";
+import { BucketSelection } from "../../../components/BucketSelection";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { NothingFound } from "../../../components/NothingFound";
import { Pagination } from "../../../components/pagination";
@@ -15,13 +18,14 @@ import GoalsList from "./components/GoalsList";
import { Target } from "lucide-react";
import { Input } from "@/components/ui/input";
import { ExternalLink } from "../../../components/ExternalLink";
+import { GoalBarChartSkeleton } from "./components/skeleton";
// Goal card skeleton component
const GoalCardSkeleton = () => (
<div className="rounded-lg bg-white dark:bg-neutral-900 border border-neutral-100 dark:border-neutral-800 overflow-hidden relative animate-pulse">
- <div className="px-4 py-3 flex items-center mb-1">
+ <div className="px-4 py-3 flex gap-3 flex-row items-center mb-1">
{/* Left section skeleton */}
- <div className="flex-1 pr-4">
+ <div className="w-full min-w-0 md:flex-1 md:pr-4">
<div className="flex items-center gap-2">
<div className="w-4 h-4 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
<div className="h-5 bg-neutral-200 dark:bg-neutral-800 rounded w-36"></div>
@@ -33,23 +37,27 @@ const GoalCardSkeleton = () => (
</div>
{/* Center section skeleton */}
- <div className="flex-1 flex justify-center">
- <div className="grid grid-cols-2 gap-4 w-full">
- <div className="text-center">
- <div className="h-5 bg-neutral-200 dark:bg-neutral-800 rounded w-12 mx-auto"></div>
- <div className="h-3 bg-neutral-200 dark:bg-neutral-800 rounded w-16 mx-auto mt-1"></div>
+ <div className="w-full md:flex-1 flex justify-start md:justify-center">
+ <div className="grid w-full grid-cols-1 gap-3 sm:grid-cols-2 md:w-auto md:gap-4">
+ <div className="flex items-center gap-3">
+ <GoalBarChartSkeleton />
+ <div className="min-w-[86px] text-left">
+ <div className="h-5 bg-neutral-200 dark:bg-neutral-800 rounded w-14"></div>
+ <div className="h-3 bg-neutral-200 dark:bg-neutral-800 rounded w-20 mt-1"></div>
+ </div>
</div>
- <div className="text-center">
- <div className="h-5 bg-neutral-200 dark:bg-neutral-800 rounded w-12 mx-auto"></div>
- <div className="h-3 bg-neutral-200 dark:bg-neutral-800 rounded w-16 mx-auto mt-1"></div>
+ <div className="flex items-center gap-3">
+ <GoalBarChartSkeleton />
+ <div className="min-w-[104px] text-left">
+ <div className="h-5 bg-neutral-200 dark:bg-neutral-800 rounded w-16"></div>
+ <div className="h-3 bg-neutral-200 dark:bg-neutral-800 rounded w-24 mt-1"></div>
+ </div>
</div>
</div>
</div>
{/* Right section skeleton */}
- <div className="flex shrink-0 gap-1 pl-4">
- <div className="w-7 h-7 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
- <div className="w-7 h-7 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
+ <div className="flex shrink-0 justify-end gap-1 md:pl-4">
<div className="w-7 h-7 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
<div className="w-7 h-7 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
</div>
@@ -100,6 +108,24 @@ export default function GoalsPage() {
});
}, [goalsData?.data, searchQuery]);
+ const goalIds = useMemo(() => filteredGoals.map(goal => goal.goalId), [filteredGoals]);
+
+ const { data: goalTimeSeries, isLoading: isLoadingGoalTimeSeries } = useGetGoalTimeSeries({
+ goalIds,
+ });
+
+ const timeSeriesByGoal = useMemo(() => {
+ const map = new Map<number, GoalTimeSeriesPoint[]>();
+
+ for (const point of goalTimeSeries ?? []) {
+ const points = map.get(point.goal_id) ?? [];
+ points.push(point);
+ map.set(point.goal_id, points);
+ }
+
+ return map;
+ }, [goalTimeSeries]);
+
// Create pagination controller for TablePagination
const paginationController = {
getState: () => ({ pagination }),
@@ -134,23 +160,26 @@ export default function GoalsPage() {
// Transform data for TablePagination
const paginationData = goalsData
? {
- items: goalsData.data,
- total: goalsData.meta.total,
- }
+ items: goalsData.data,
+ total: goalsData.meta.total,
+ }
: undefined;
return (
<DisabledOverlay message="Goals" featurePath="goals" requiredPlan="basic">
<div className="p-2 md:p-4 max-w-[1400px] mx-auto space-y-3">
<SubHeader availableFilters={GOALS_PAGE_FILTERS} />
- <div className="flex items-center justify-between">
- <Input
- placeholder={t("Filter goals")}
- className="w-48"
- isSearch
- value={searchQuery}
- onChange={e => setSearchQuery(e.target.value)}
- />
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex items-center gap-2">
+ <Input
+ placeholder={t("Filter goals")}
+ className="w-48"
+ isSearch
+ value={searchQuery}
+ onChange={e => setSearchQuery(e.target.value)}
+ />
+ <BucketSelection size="default" />
+ </div>
<CreateGoalButton siteId={Number(site)} />
</div>
{/* if site is not loaded, show skeleton */}
@@ -166,7 +195,12 @@ export default function GoalsPage() {
<NothingFound
icon={<Target className="w-10 h-10" />}
title={t("No goals found")}
- description={<span>{t("Create your first conversion goal to start tracking important user actions.")} <ExternalLink href="https://rybbit.com/docs/goals">{t("Learn more")}</ExternalLink></span>}
+ description={
+ <span>
+ {t("Create your first conversion goal to start tracking important user actions.")}{" "}
+ <ExternalLink href="https://rybbit.com/docs/goals">{t("Learn more")}</ExternalLink>
+ </span>
+ }
action={<CreateGoalButton siteId={Number(site)} />}
/>
) : filteredGoals.length === 0 ? (
@@ -177,7 +211,12 @@ export default function GoalsPage() {
/>
) : (
<div className="space-y-6">
- <GoalsList goals={filteredGoals} siteId={Number(site)} />
+ <GoalsList
+ goals={filteredGoals}
+ siteId={Number(site)}
+ timeSeriesByGoal={timeSeriesByGoal}
+ isLoadingTimeSeries={isLoadingGoalTimeSeries}
+ />
{goalsData.meta.totalPages > 1 && !searchQuery && (
<Pagination
diff --git a/client/src/app/[site]/main/components/sections/Countries.tsx b/client/src/app/[site]/main/components/sections/Countries.tsx
index d5473b104..ac92ad253 100644
--- a/client/src/app/[site]/main/components/sections/Countries.tsx
+++ b/client/src/app/[site]/main/components/sections/Countries.tsx
@@ -1,14 +1,13 @@
"use client";
-import { ChevronRight, Expand, Globe } from "lucide-react";
+import { ChevronRight, Globe } from "lucide-react";
import { useExtracted } from "next-intl";
-import { useState } from "react";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
-import { Button } from "../../../../../components/ui/button";
-import { Card, CardContent } from "../../../../../components/ui/card";
import { useSubdivisions } from "../../../../../lib/geo";
import { getCountryName, getLanguageName } from "../../../../../lib/utils";
import { MapComponent } from "../../../components/shared/Map/MapComponent";
-import { StandardSection } from "../../../components/shared/StandardSection/StandardSection";
+import {
+ StandardSectionTabs,
+ type StandardSectionTab,
+} from "../../../components/shared/StandardSection/StandardSectionTabs";
import { CountryFlag } from "../../../components/shared/icons/CountryFlag";
type Tab = "countries" | "regions" | "languages" | "cities" | "map" | "timezones";
@@ -32,170 +31,127 @@ const getCountryFromLanguage = (languageCode: string): string | null => {
};
export function Countries() {
- const [tab, setTab] = useState<Tab>("countries");
- const [expanded, setExpanded] = useState(false);
const t = useExtracted();
- const close = () => {
- setExpanded(false);
- };
const { data: subdivisions } = useSubdivisions();
- return (
- <Card className="h-[405px]">
- <CardContent className="mt-2">
- <Tabs defaultValue="countries" value={tab} onValueChange={value => setTab(value as Tab)}>
- <div className="flex flex-row gap-2 justify-between items-center">
- <TabsList>
- <TabsTrigger value="countries">{t("Countries")}</TabsTrigger>
- <TabsTrigger value="regions">{t("Regions")}</TabsTrigger>
- <TabsTrigger value="cities">{t("Cities")}</TabsTrigger>
- <TabsTrigger value="languages">{t("Languages")}</TabsTrigger>
- <TabsTrigger value="map">{t("Map")}</TabsTrigger>
- <TabsTrigger value="timezones">{t("Timezones")}</TabsTrigger>
- </TabsList>
- {tab !== "map" && (
- <div className="w-7">
- <Button size="smIcon" onClick={() => setExpanded(!expanded)}>
- <Expand className="w-4 h-4" />
- </Button>
- </div>
- )}
+ const tabs: StandardSectionTab<Tab>[] = [
+ {
+ value: "countries",
+ label: t("Countries"),
+ section: {
+ filterParameter: "country",
+ title: t("Countries"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getFilterLabel: e => getCountryName(e.value),
+ getLabel: e => (
+ <div className="flex gap-2 items-center">
+ <CountryFlag country={e.value} />
+ {getCountryName(e.value)}
</div>
- <TabsContent value="countries">
- <StandardSection
- filterParameter="country"
- title={t("Countries")}
- getValue={e => e.value}
- getKey={e => e.value}
- getFilterLabel={e => getCountryName(e.value)}
- getLabel={e => {
- return (
- <div className="flex gap-2 items-center">
- <CountryFlag country={e.value} />
- {getCountryName(e.value)}
- </div>
- );
- }}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="regions">
- <StandardSection
- filterParameter="region"
- title={t("Regions")}
- getValue={e => e.value}
- getKey={e => e.value}
- getFilterLabel={e => {
- const region = subdivisions?.features.find(
- feature => feature.properties.iso_3166_2 === e.value
- )?.properties;
- return region?.name ?? "";
- }}
- getLabel={e => {
- if (!e.value) {
- return t("Unknown");
- }
-
- const region = subdivisions?.features.find(
- feature => feature.properties.iso_3166_2 === e.value
- )?.properties;
+ ),
+ },
+ },
+ {
+ value: "regions",
+ label: t("Regions"),
+ section: {
+ filterParameter: "region",
+ title: t("Regions"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getFilterLabel: e => {
+ const region = subdivisions?.features.find(feature => feature.properties.iso_3166_2 === e.value)?.properties;
+ return region?.name ?? "";
+ },
+ getLabel: e => {
+ if (!e.value) {
+ return t("Unknown");
+ }
- const countryCode = e.value.split("-")[0];
+ const region = subdivisions?.features.find(feature => feature.properties.iso_3166_2 === e.value)?.properties;
+ const countryCode = e.value.split("-")[0];
- return (
- <div className="flex gap-2 items-center">
- <CountryFlag country={countryCode} />
- {countryCode}
- <ChevronRight className="w-4 h-4 mx-[-4px]" />
- {region?.name ?? e.value.slice(3)}
- </div>
- );
- }}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="cities">
- <StandardSection
- filterParameter="city"
- title={t("Cities")}
- getValue={e => e.value}
- getKey={e => e.value}
- getLabel={e => {
- if (!e.value || e.value === "-") {
- return t("Unknown");
- }
+ return (
+ <div className="flex gap-2 items-center">
+ <CountryFlag country={countryCode} />
+ {countryCode}
+ <ChevronRight className="w-4 h-4 mx-[-4px]" />
+ {region?.name ?? e.value.slice(3)}
+ </div>
+ );
+ },
+ },
+ },
+ {
+ value: "cities",
+ label: t("Cities"),
+ section: {
+ filterParameter: "city",
+ title: t("Cities"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => {
+ if (!e.value || e.value === "-") {
+ return t("Unknown");
+ }
- const { country, region, city } = getCountryCity(e.value) ?? {};
+ const { country, region, city } = getCountryCity(e.value) ?? {};
+ const region_ = subdivisions?.features.find(
+ feature => feature.properties.iso_3166_2 === `${country}-${region}`
+ )?.properties;
- const region_ = subdivisions?.features.find(
- feature => feature.properties.iso_3166_2 === `${country}-${region}`
- )?.properties;
+ return (
+ <div className="flex gap-2 items-center">
+ <CountryFlag country={country} />
+ {country}
+ {region_?.name && <ChevronRight className="w-4 h-4 mx-[-4px]" />}
+ {region_?.name}
+ {city && <ChevronRight className="w-4 h-4 mx-[-4px]" />}
+ {city}
+ </div>
+ );
+ },
+ },
+ },
+ {
+ value: "languages",
+ label: t("Languages"),
+ section: {
+ filterParameter: "language",
+ title: t("Languages"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getFilterLabel: e => getLanguageName(e.value) ?? "",
+ getLabel: e => (
+ <div className="flex gap-2 items-center">
+ {getCountryFromLanguage(e.value) ? (
+ <CountryFlag country={getCountryFromLanguage(e.value)!} />
+ ) : (
+ <Globe className="w-5 h-5" />
+ )}
+ {getLanguageName(e.value)}
+ </div>
+ ),
+ },
+ },
+ {
+ value: "map",
+ label: t("Map"),
+ content: <MapComponent height="340px" />,
+ },
+ {
+ value: "timezones",
+ label: t("Timezones"),
+ section: {
+ filterParameter: "timezone",
+ title: t("Timezones"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => e.value,
+ },
+ },
+ ];
- return (
- <div className="flex gap-2 items-center">
- <CountryFlag country={country} />
- {country}
- {region_?.name && <ChevronRight className="w-4 h-4 mx-[-4px]" />}
- {region_?.name}
- {city && <ChevronRight className="w-4 h-4 mx-[-4px]" />}
- {city}
- </div>
- );
- }}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="languages">
- <StandardSection
- filterParameter="language"
- title={t("Languages")}
- getValue={e => e.value}
- getKey={e => e.value}
- getFilterLabel={e => getLanguageName(e.value) ?? ""}
- getLabel={e => (
- <div className="flex gap-2 items-center">
- {getCountryFromLanguage(e.value) ? (
- <CountryFlag country={getCountryFromLanguage(e.value)!} />
- ) : (
- <Globe className="w-5 h-5" />
- )}
- {getLanguageName(e.value)}
- </div>
- )}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="timezones">
- <StandardSection
- filterParameter="timezone"
- title={t("Timezones")}
- getValue={e => e.value}
- getKey={e => e.value}
- // getFilterLabel={e => getLanguageName(e.value) ?? ""}
- // getLabel={e => (
- // <div className="flex gap-2 items-center">
- // {getCountryFromLanguage(e.value) ? (
- // <CountryFlag country={getCountryFromLanguage(e.value)!} />
- // ) : (
- // <Globe className="w-5 h-5" />
- // )}
- // {getLanguageName(e.value)}
- // </div>
- // )}
- getLabel={e => e.value}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="map">
- <MapComponent height="340px" />
- </TabsContent>
- </Tabs>
- </CardContent>
- </Card>
- );
+ return <StandardSectionTabs defaultValue="countries" tabs={tabs} />;
}
diff --git a/client/src/app/[site]/main/components/sections/Devices.tsx b/client/src/app/[site]/main/components/sections/Devices.tsx
index cb026d86a..eb74fe78d 100644
--- a/client/src/app/[site]/main/components/sections/Devices.tsx
+++ b/client/src/app/[site]/main/components/sections/Devices.tsx
@@ -1,126 +1,100 @@
"use client";
-import { Expand, Monitor, Smartphone, Tablet } from "lucide-react";
import { useExtracted } from "next-intl";
-import { useState } from "react";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
-import { Card, CardContent } from "../../../../../components/ui/card";
-import { StandardSection } from "../../../components/shared/StandardSection/StandardSection";
+import {
+ StandardSectionTabs,
+ type StandardSectionTab,
+} from "../../../components/shared/StandardSection/StandardSectionTabs";
import { Browser } from "../../../components/shared/icons/Browser";
import { OperatingSystem } from "../../../components/shared/icons/OperatingSystem";
-import { Button } from "../../../../../components/ui/button";
import { DeviceIcon } from "../../../components/shared/icons/Device";
-type Tab = "devices" | "browsers" | "os" | "dimensions" | "browser_versions" | "os_versions";
+type Tab = "devices" | "browsers" | "os" | "dimensions";
export function Devices() {
- const [tab, setTab] = useState<Tab>("browsers");
- const [expanded, setExpanded] = useState(false);
const t = useExtracted();
- const close = () => {
- setExpanded(false);
- };
- return (
- <Card className="h-[405px]">
- <CardContent className="mt-2">
- <Tabs defaultValue="browsers" value={tab} onValueChange={value => setTab(value as Tab)}>
- <div className="flex flex-row gap-2 justify-between items-center">
- <div className="overflow-x-auto">
- <TabsList>
- <TabsTrigger value="browsers">{t("Browsers")}</TabsTrigger>
- <TabsTrigger value="devices">{t("Devices")}</TabsTrigger>
- <TabsTrigger value="os">{t("Operating Systems")}</TabsTrigger>
- <TabsTrigger value="dimensions">{t("Screen Dimensions")}</TabsTrigger>
- </TabsList>
- </div>
- <div className="w-7">
- <Button size="smIcon" onClick={() => setExpanded(!expanded)}>
- <Expand className="w-4 h-4" />
- </Button>
+ const tabs: StandardSectionTab<Tab>[] = [
+ {
+ value: "browsers",
+ label: t("Browsers"),
+ section: {
+ filterParameter: "browser",
+ title: t("Browsers"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => (
+ <div className="flex gap-2 items-center">
+ <Browser browser={e.value} />
+ {e.value || t("Other")}
+ </div>
+ ),
+ getSubrowLabel: e => {
+ const justBrowser = e.value.split(" ").slice(0, -1).join(" ");
+ return (
+ <div className="flex gap-2 items-center">
+ <Browser browser={justBrowser || "Other"} />
+ {e.value || t("Other")}
</div>
+ );
+ },
+ hasSubrow: true,
+ },
+ },
+ {
+ value: "devices",
+ label: t("Devices"),
+ section: {
+ filterParameter: "device_type",
+ title: t("Devices"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => (
+ <div className="flex gap-2 items-center">
+ <DeviceIcon deviceType={e.value || ""} size={16} />
+ {e.value || t("Other")}
+ </div>
+ ),
+ },
+ },
+ {
+ value: "os",
+ label: t("Operating Systems"),
+ section: {
+ title: t("Operating Systems"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => (
+ <div className="flex gap-2 items-center">
+ <OperatingSystem os={e.value || "Other"} />
+ {e.value || t("Other")}
</div>
- <TabsContent value="devices">
- <StandardSection
- filterParameter="device_type"
- title={t("Devices")}
- getValue={e => e.value}
- getKey={e => e.value}
- getLabel={e => (
- <div className="flex gap-2 items-center">
- <DeviceIcon deviceType={e.value || ""} size={16} />
- {e.value || t("Other")}
- </div>
- )}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="browsers">
- <StandardSection
- filterParameter="browser"
- title={t("Browsers")}
- getValue={e => e.value}
- getKey={e => e.value}
- getLabel={e => (
- <div className="flex gap-2 items-center">
- <Browser browser={e.value} />
- {e.value || t("Other")}
- </div>
- )}
- getSubrowLabel={e => {
- const justBrowser = e.value.split(" ").slice(0, -1).join(" ");
- return (
- <div className="flex gap-2 items-center">
- <Browser browser={justBrowser || "Other"} />
- {e.value || t("Other")}
- </div>
- );
- }}
- expanded={expanded}
- close={close}
- hasSubrow={true}
- />
- </TabsContent>
- <TabsContent value="os">
- <StandardSection
- title={t("Operating Systems")}
- getValue={e => e.value}
- getKey={e => e.value}
- getLabel={e => (
- <div className="flex gap-2 items-center">
- <OperatingSystem os={e.value || "Other"} />
- {e.value || t("Other")}
- </div>
- )}
- getSubrowLabel={e => {
- const justOS = e.value.split(" ").slice(0, -1).join(" ");
- return (
- <div className="flex gap-2 items-center">
- <OperatingSystem os={justOS || "Other"} />
- {e.value || t("Other")}
- </div>
- );
- }}
- filterParameter="operating_system"
- expanded={expanded}
- close={close}
- hasSubrow={true}
- />
- </TabsContent>
- <TabsContent value="dimensions">
- <StandardSection
- title={t("Screen Dimensions")}
- getValue={e => e.value}
- getKey={e => e.value}
- getLabel={e => <div className="flex gap-2 items-center">{e.value || t("Other")}</div>}
- filterParameter="dimensions"
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- </Tabs>
- </CardContent>
- </Card>
- );
+ ),
+ getSubrowLabel: e => {
+ const justOS = e.value.split(" ").slice(0, -1).join(" ");
+ return (
+ <div className="flex gap-2 items-center">
+ <OperatingSystem os={justOS || "Other"} />
+ {e.value || t("Other")}
+ </div>
+ );
+ },
+ filterParameter: "operating_system",
+ hasSubrow: true,
+ },
+ },
+ {
+ value: "dimensions",
+ label: t("Screen Dimensions"),
+ section: {
+ title: t("Screen Dimensions"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => <div className="flex gap-2 items-center">{e.value || t("Other")}</div>,
+ filterParameter: "dimensions",
+ },
+ },
+ ];
+
+ return <StandardSectionTabs defaultValue="browsers" tabs={tabs} />;
}
diff --git a/client/src/app/[site]/main/components/sections/Pages.tsx b/client/src/app/[site]/main/components/sections/Pages.tsx
index 01119203b..6498d38d3 100644
--- a/client/src/app/[site]/main/components/sections/Pages.tsx
+++ b/client/src/app/[site]/main/components/sections/Pages.tsx
@@ -1,121 +1,88 @@
"use client";
-import { useStore } from "@/lib/store";
-import { Expand } from "lucide-react";
import { useExtracted } from "next-intl";
-import { useState } from "react";
import { useGetSite } from "../../../../../api/admin/hooks/useSites";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
-import { Button } from "../../../../../components/ui/button";
-import { Card, CardContent } from "../../../../../components/ui/card";
-import { StandardSection } from "../../../components/shared/StandardSection/StandardSection";
+import {
+ StandardSectionTabs,
+ type StandardSectionTab,
+} from "../../../components/shared/StandardSection/StandardSectionTabs";
import { truncateString } from "../../../../../lib/utils";
type Tab = "pages" | "page_title" | "entry_pages" | "exit_pages" | "hostname";
export function Pages() {
const { data: siteMetadata } = useGetSite();
- const [tab, setTab] = useState<Tab>("pages");
- const [expanded, setExpanded] = useState(false);
const t = useExtracted();
- const close = () => {
- setExpanded(false);
- };
- return (
- <Card className="h-[405px]">
- <CardContent className="mt-2">
- <Tabs defaultValue="pages" value={tab} onValueChange={value => setTab(value as Tab)}>
- <div className="flex flex-row gap-2 justify-between items-center">
- <div className="overflow-x-auto">
- <TabsList>
- <TabsTrigger value="pages">{t("Pages")}</TabsTrigger>
- <TabsTrigger value="page_title">{t("Titles")}</TabsTrigger>
- <TabsTrigger value="entry_pages">{t("Entries")}</TabsTrigger>
- <TabsTrigger value="exit_pages">{t("Exits")}</TabsTrigger>
- <TabsTrigger value="hostname">{t("Hostnames")}</TabsTrigger>
- </TabsList>
- </div>
- <div className="w-7">
- <Button size="smIcon" onClick={() => setExpanded(!expanded)}>
- <Expand className="w-4 h-4" />
- </Button>
- </div>
- </div>
- <TabsContent value="pages">
- <StandardSection
- filterParameter="pathname"
- title={t("Pages")}
- getValue={e => e.value}
- getKey={e => e.value}
- getLabel={e => truncateString(e.value, 50) || t("Other")}
- getLink={e => {
- const host = e.hostname || siteMetadata?.domain;
- return host ? `https://${host}${e.value}` : "#";
- }}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="page_title">
- <StandardSection
- filterParameter="page_title"
- title={t("Page Title")}
- getValue={e => e.value}
- getKey={e => e.value}
- getLabel={e => truncateString(e.value, 50) || t("Other")}
- // getLink={(e) =>
- // e.pathname
- // ? `https://${siteMetadata?.domain}${e.pathname}`
- // : "#"
- // }
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="entry_pages">
- <StandardSection
- filterParameter="entry_page"
- title={t("Entry Pages")}
- getValue={e => e.value}
- getKey={e => e.value}
- getLabel={e => e.value || t("Other")}
- getLink={e => {
- const host = e.hostname || siteMetadata?.domain;
- return host ? `https://${host}${e.value}` : "#";
- }}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="exit_pages">
- <StandardSection
- filterParameter="exit_page"
- title={t("Exit Pages")}
- getValue={e => e.value}
- getKey={e => e.value}
- getLabel={e => e.value || t("Other")}
- getLink={e => {
- const host = e.hostname || siteMetadata?.domain;
- return host ? `https://${host}${e.value}` : "#";
- }}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="hostname">
- <StandardSection
- filterParameter="hostname"
- title={t("Hostnames")}
- getValue={e => e.value}
- getKey={e => e.value}
- getLabel={e => e.value}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- </Tabs>
- </CardContent>
- </Card>
- );
+ const tabs: StandardSectionTab<Tab>[] = [
+ {
+ value: "pages",
+ label: t("Pages"),
+ section: {
+ filterParameter: "pathname",
+ title: t("Pages"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => truncateString(e.value, 50) || t("Other"),
+ getLink: e => {
+ const host = e.hostname || siteMetadata?.domain;
+ return host ? `https://${host}${e.value}` : "#";
+ },
+ },
+ },
+ {
+ value: "page_title",
+ label: t("Titles"),
+ section: {
+ filterParameter: "page_title",
+ title: t("Page Title"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => truncateString(e.value, 50) || t("Other"),
+ },
+ },
+ {
+ value: "entry_pages",
+ label: t("Entries"),
+ section: {
+ filterParameter: "entry_page",
+ title: t("Entry Pages"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => e.value || t("Other"),
+ getLink: e => {
+ const host = e.hostname || siteMetadata?.domain;
+ return host ? `https://${host}${e.value}` : "#";
+ },
+ },
+ },
+ {
+ value: "exit_pages",
+ label: t("Exits"),
+ section: {
+ filterParameter: "exit_page",
+ title: t("Exit Pages"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => e.value || t("Other"),
+ getLink: e => {
+ const host = e.hostname || siteMetadata?.domain;
+ return host ? `https://${host}${e.value}` : "#";
+ },
+ },
+ },
+ {
+ value: "hostname",
+ label: t("Hostnames"),
+ section: {
+ filterParameter: "hostname",
+ title: t("Hostnames"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => e.value,
+ },
+ },
+ ];
+
+ return <StandardSectionTabs defaultValue="pages" tabs={tabs} />;
}
diff --git a/client/src/app/[site]/main/components/sections/Referrers.tsx b/client/src/app/[site]/main/components/sections/Referrers.tsx
index 28ead45cc..c197d82a1 100644
--- a/client/src/app/[site]/main/components/sections/Referrers.tsx
+++ b/client/src/app/[site]/main/components/sections/Referrers.tsx
@@ -1,167 +1,153 @@
"use client";
-import { Expand } from "lucide-react";
import { useExtracted } from "next-intl";
-import { useState } from "react";
import { ChannelIcon } from "../../../../../components/Channel";
import { Favicon } from "../../../../../components/Favicon";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
-import { Button } from "../../../../../components/ui/button";
-import { Card, CardContent } from "../../../../../components/ui/card";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "../../../../../components/ui/dropdown-menu";
-import { StandardSection } from "../../../components/shared/StandardSection/StandardSection";
+import { cn } from "../../../../../lib/utils";
+import {
+ StandardSectionTabs,
+ type StandardSectionTab,
+} from "../../../components/shared/StandardSection/StandardSectionTabs";
type Tab = "referrers" | "channels" | "utm_source" | "utm_medium" | "utm_campaign" | "utm_term" | "utm_content";
export function Referrers() {
- const [tab, setTab] = useState<Tab>("referrers");
- const [expanded, setExpanded] = useState(false);
const t = useExtracted();
- const close = () => {
- setExpanded(false);
- };
- return (
- <Card className="h-[405px]">
- <CardContent className="mt-2">
- <Tabs defaultValue="referrers" value={tab} onValueChange={value => setTab(value as Tab)}>
- <div className="flex flex-row gap-2 justify-between items-center">
- <div className="overflow-x-auto">
- <TabsList>
- <TabsTrigger value="referrers">{t("Referrers")}</TabsTrigger>
- <TabsTrigger value="channels">{t("Channels")}</TabsTrigger>
- <DropdownMenu>
- <DropdownMenuTrigger asChild unstyled>
- <div
- className={`inline-flex items-center justify-center whitespace-nowrap border-b-2 py-1 text-sm font-medium transition-all cursor-pointer ${
- tab.startsWith("utm_")
- ? "border-neutral-950 text-neutral-950 dark:border-neutral-100 dark:text-neutral-50"
- : "border-transparent text-neutral-600 dark:text-neutral-400"
- }`}
- >
- {tab === "utm_source" && t("Source")}
- {tab === "utm_medium" && t("Medium")}
- {tab === "utm_campaign" && t("Campaign")}
- {tab === "utm_term" && t("Term")}
- {tab === "utm_content" && t("Content")}
- {!tab.startsWith("utm_") && t("UTM")}
- </div>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- <DropdownMenuItem onClick={() => setTab("utm_source")}>{t("Source")}</DropdownMenuItem>
- <DropdownMenuItem onClick={() => setTab("utm_medium")}>{t("Medium")}</DropdownMenuItem>
- <DropdownMenuItem onClick={() => setTab("utm_campaign")}>{t("Campaign")}</DropdownMenuItem>
- <DropdownMenuItem onClick={() => setTab("utm_term")}>{t("Term")}</DropdownMenuItem>
- <DropdownMenuItem onClick={() => setTab("utm_content")}>{t("Content")}</DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- {/* <TabsTrigger value="utm_source">Source</TabsTrigger>
- <TabsTrigger value="utm_medium">Medium</TabsTrigger>
- <TabsTrigger value="utm_campaign">Campaign</TabsTrigger>
- <TabsTrigger value="utm_term">Term</TabsTrigger>
- <TabsTrigger value="utm_content">Content</TabsTrigger> */}
- </TabsList>
- </div>
- <div className="w-7">
- <Button size="smIcon" onClick={() => setExpanded(!expanded)}>
- <Expand className="w-4 h-4" />
- </Button>
- </div>
+ const tabs: StandardSectionTab<Tab>[] = [
+ {
+ value: "referrers",
+ label: t("Referrers"),
+ section: {
+ filterParameter: "referrer",
+ title: t("Referrers"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLink: e => `https://${e.value}`,
+ getLabel: e => (
+ <div className="flex items-center">
+ <Favicon domain={e.value} className="w-4 mr-2" />
+ {e.value ? e.value : t("Direct")}
</div>
- <TabsContent value="referrers">
- <StandardSection
- filterParameter="referrer"
- title={t("Referrers")}
- getValue={e => e.value}
- getKey={e => e.value}
- getLink={e => `https://${e.value}`}
- getLabel={e => (
- <div className="flex items-center">
- <Favicon domain={e.value} className="w-4 mr-2" />
- {e.value ? e.value : t("Direct")}
- </div>
- )}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="channels">
- <StandardSection
- filterParameter="channel"
- title={t("Channels")}
- getValue={e => e.value}
- getKey={e => e.value}
- // getLink={(e) => `https://${e.value}`}
- getLabel={e => (
- <div className="flex items-center gap-2">
- <ChannelIcon channel={e.value} /> {e.value}
- </div>
- )}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="utm_source">
- <StandardSection
- filterParameter="utm_source"
- title={t("UTM Source")}
- getKey={e => e.value}
- getLabel={e => e.value}
- getValue={e => e.value}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="utm_medium">
- <StandardSection
- filterParameter="utm_medium"
- title={t("UTM Medium")}
- getKey={e => e.value}
- getLabel={e => e.value}
- getValue={e => e.value}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="utm_campaign">
- <StandardSection
- filterParameter="utm_campaign"
- title={t("UTM Campaign")}
- getKey={e => e.value}
- getLabel={e => e.value}
- getValue={e => e.value}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="utm_content">
- <StandardSection
- filterParameter="utm_content"
- title={t("UTM Content")}
- getKey={e => e.value}
- getLabel={e => e.value}
- getValue={e => e.value}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- <TabsContent value="utm_term">
- <StandardSection
- filterParameter="utm_term"
- title={t("UTM Term")}
- getKey={e => e.value}
- getLabel={e => e.value}
- getValue={e => e.value}
- expanded={expanded}
- close={close}
- />
- </TabsContent>
- </Tabs>
- </CardContent>
- </Card>
+ ),
+ },
+ },
+ {
+ value: "channels",
+ label: t("Channels"),
+ section: {
+ filterParameter: "channel",
+ title: t("Channels"),
+ getValue: e => e.value,
+ getKey: e => e.value,
+ getLabel: e => (
+ <div className="flex items-center gap-2">
+ <ChannelIcon channel={e.value} /> {e.value}
+ </div>
+ ),
+ },
+ },
+ {
+ value: "utm_source",
+ label: t("Source"),
+ showInTabs: false,
+ section: {
+ filterParameter: "utm_source",
+ title: t("UTM Source"),
+ getKey: e => e.value,
+ getLabel: e => e.value,
+ getValue: e => e.value,
+ },
+ },
+ {
+ value: "utm_medium",
+ label: t("Medium"),
+ showInTabs: false,
+ section: {
+ filterParameter: "utm_medium",
+ title: t("UTM Medium"),
+ getKey: e => e.value,
+ getLabel: e => e.value,
+ getValue: e => e.value,
+ },
+ },
+ {
+ value: "utm_campaign",
+ label: t("Campaign"),
+ showInTabs: false,
+ section: {
+ filterParameter: "utm_campaign",
+ title: t("UTM Campaign"),
+ getKey: e => e.value,
+ getLabel: e => e.value,
+ getValue: e => e.value,
+ },
+ },
+ {
+ value: "utm_term",
+ label: t("Term"),
+ showInTabs: false,
+ section: {
+ filterParameter: "utm_term",
+ title: t("UTM Term"),
+ getKey: e => e.value,
+ getLabel: e => e.value,
+ getValue: e => e.value,
+ },
+ },
+ {
+ value: "utm_content",
+ label: t("Content"),
+ showInTabs: false,
+ section: {
+ filterParameter: "utm_content",
+ title: t("UTM Content"),
+ getKey: e => e.value,
+ getLabel: e => e.value,
+ getValue: e => e.value,
+ },
+ },
+ ];
+
+ const renderUtmMenu = (value: Tab, setValue: (value: Tab) => void) => (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild unstyled>
+ <div
+ className={cn(
+ "inline-flex items-center justify-center whitespace-nowrap border-b-2 py-1 text-sm font-medium transition-all cursor-pointer",
+ value.startsWith("utm_")
+ ? "border-neutral-950 text-neutral-950 dark:border-neutral-100 dark:text-neutral-50"
+ : "border-transparent text-neutral-600 dark:text-neutral-400"
+ )}
+ >
+ {value === "utm_source" && t("Source")}
+ {value === "utm_medium" && t("Medium")}
+ {value === "utm_campaign" && t("Campaign")}
+ {value === "utm_term" && t("Term")}
+ {value === "utm_content" && t("Content")}
+ {!value.startsWith("utm_") && t("UTM")}
+ </div>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuItem onClick={() => setValue("utm_source")}>{t("Source")}</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setValue("utm_medium")}>{t("Medium")}</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setValue("utm_campaign")}>{t("Campaign")}</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setValue("utm_term")}>{t("Term")}</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setValue("utm_content")}>{t("Content")}</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+
+ return (
+ <StandardSectionTabs
+ defaultValue="referrers"
+ tabs={tabs}
+ renderTabsListEnd={({ value, setValue }) => renderUtmMenu(value, setValue)}
+ />
);
}
diff --git a/client/src/components/BucketSelection.tsx b/client/src/components/BucketSelection.tsx
index cca88fda3..de1899b4f 100644
--- a/client/src/components/BucketSelection.tsx
+++ b/client/src/components/BucketSelection.tsx
@@ -68,7 +68,7 @@ const getRangeDurationMinutes = (time: Time): number | null => {
return null;
};
-export function BucketSelection() {
+export function BucketSelection({ size = "sm" }: { size?: "default" | "sm" }) {
const t = useExtracted();
const { bucket, setBucket, time } = useStore();
@@ -78,9 +78,9 @@ export function BucketSelection() {
);
return (
- <SelectContent>
+ <SelectContent size={size}>
{availableOptions.map(option => (
- <SelectItem key={option} size="sm" value={option}>
+ <SelectItem key={option} size={size} value={option}>
{getBucketLabel(option)}
</SelectItem>
))}
@@ -144,9 +144,9 @@ export function BucketSelection() {
const timezone = getTimezone();
const exactRangeMinutes = exactRange
? DateTime.fromISO(`${time.endDate}T${time.endTime}`, { zone: timezone }).diff(
- DateTime.fromISO(`${time.startDate}T${time.startTime}`, { zone: timezone }),
- "minutes"
- ).minutes
+ DateTime.fromISO(`${time.startDate}T${time.startTime}`, { zone: timezone }),
+ "minutes"
+ ).minutes
: undefined;
const timeRangeLength =
exactRangeMinutes !== undefined
@@ -171,9 +171,9 @@ export function BucketSelection() {
return (
<Select value={bucket} onValueChange={setBucket}>
- <SelectTrigger className="w-[90px]" size="sm">
+ <SelectTrigger className="w-[90px]" size={size}>
<div className="flex items-center gap-1">
- <TimerReset className="w-3 h-3" />
+ <TimerReset className={size === "sm" ? "w-3 h-3" : "w-4 h-4"} />
<SelectValue />
</div>
</SelectTrigger>
diff --git a/docs/src/components/LandingPageTemplate.tsx b/docs/src/components/LandingPageTemplate.tsx
index 59125be33..f9103b1ef 100644
--- a/docs/src/components/LandingPageTemplate.tsx
+++ b/docs/src/components/LandingPageTemplate.tsx
@@ -190,7 +190,7 @@ export function LandingPageTemplate({ title, subtitle, showEUFlag = true }: Land
<div className="max-w-[1200px] mx-auto px-4">
<div className="text-center mb-10 md:mb-12">
<p className="text-neutral-500 dark:text-neutral-400 text-sm uppercase tracking-wider font-medium">
- {t("Trusted by 4,000+ organizations worldwide")}
+ {t("Trusted by 10,000+ organizations worldwide")}
</p>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-8 items-center justify-items-center">
diff --git a/server/src/api/analytics/goals/getGoalTimeSeries.ts b/server/src/api/analytics/goals/getGoalTimeSeries.ts
new file mode 100644
index 000000000..b806c37fa
--- /dev/null
+++ b/server/src/api/analytics/goals/getGoalTimeSeries.ts
@@ -0,0 +1,150 @@
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { and, inArray, eq } from "drizzle-orm";
+import SqlString from "sqlstring";
+import { clickhouse } from "../../../db/clickhouse/clickhouse.js";
+import { db } from "../../../db/postgres/postgres.js";
+import { goals } from "../../../db/postgres/schema.js";
+import { TimeBucket } from "../types.js";
+import { getFilterStatement } from "../utils/getFilterStatement.js";
+import { getTimeStatement, processResults, TimeBucketToFn } from "../utils/utils.js";
+import { buildGoalCondition } from "./goalConditions.js";
+
+type GoalTimeSeriesPoint = {
+ time: string;
+ goal_id: number;
+ conversions: number;
+ total_sessions: number;
+ conversion_rate: number;
+};
+
+type GetGoalTimeSeriesRequest = {
+ Params: {
+ siteId: string;
+ };
+ Querystring: FilterParams<{
+ bucket: TimeBucket;
+ goal_ids?: string | number[];
+ }>;
+};
+
+const parseGoalIds = (value: string | number[] | undefined) => {
+ if (!value) return [];
+
+ if (Array.isArray(value)) {
+ return value.map(Number).filter(Number.isFinite);
+ }
+
+ try {
+ const parsed = JSON.parse(value);
+ if (Array.isArray(parsed)) {
+ return parsed.map(Number).filter(Number.isFinite);
+ }
+ } catch {
+ // Fall back to comma-separated values.
+ }
+
+ return value.split(",").map(Number).filter(Number.isFinite);
+};
+
+export async function getGoalTimeSeries(req: FastifyRequest<GetGoalTimeSeriesRequest>, res: FastifyReply) {
+ const siteId = Number(req.params.siteId);
+ const { bucket = "hour" } = req.query;
+ const timeZone = req.query.time_zone || "UTC";
+
+ if (!TimeBucketToFn[bucket]) {
+ return res.status(400).send({ error: `Invalid bucket value: ${bucket}` });
+ }
+
+ const goalIds = [...new Set(parseGoalIds(req.query.goal_ids))];
+ if (goalIds.length === 0) {
+ return res.send({ data: [] });
+ }
+
+ try {
+ const siteGoals = await db
+ .select()
+ .from(goals)
+ .where(and(eq(goals.siteId, siteId), inArray(goals.goalId, goalIds)));
+
+ if (siteGoals.length === 0) {
+ return res.send({ data: [] });
+ }
+
+ const timeStatement = getTimeStatement(req.query);
+ const filterStatement = getFilterStatement(req.query.filters, siteId, timeStatement);
+ const bucketFn = TimeBucketToFn[bucket];
+
+ const conversionQueries = siteGoals
+ .map(goal => {
+ const goalCondition = buildGoalCondition(goal);
+ if (!goalCondition) return null;
+
+ return `
+ SELECT
+ toDateTime(${bucketFn}(toTimeZone(timestamp, {timeZone:String}))) AS time,
+ ${SqlString.escape(goal.goalId)} AS goal_id,
+ COUNT(DISTINCT session_id) AS conversions
+ FROM events
+ WHERE
+ site_id = {siteId:Int32}
+ AND (${goalCondition})
+ ${timeStatement}
+ ${filterStatement}
+ GROUP BY time, goal_id
+ `;
+ })
+ .filter(Boolean);
+
+ if (conversionQueries.length === 0) {
+ return res.send({ data: [] });
+ }
+
+ const validGoalIds = siteGoals.map(goal => goal.goalId).join(", ");
+ const query = `
+ WITH
+ sessions_by_bucket AS (
+ SELECT
+ toDateTime(${bucketFn}(toTimeZone(timestamp, {timeZone:String}))) AS time,
+ COUNT(DISTINCT session_id) AS total_sessions
+ FROM events
+ WHERE
+ site_id = {siteId:Int32}
+ ${timeStatement}
+ ${filterStatement}
+ GROUP BY time
+ ),
+ goal_ids AS (
+ SELECT arrayJoin([${validGoalIds}]) AS goal_id
+ ),
+ conversions_by_goal AS (
+ ${conversionQueries.join("\nUNION ALL\n")}
+ )
+ SELECT
+ s.time AS time,
+ g.goal_id AS goal_id,
+ ifNull(c.conversions, 0) AS conversions,
+ s.total_sessions AS total_sessions,
+ if(s.total_sessions > 0, ifNull(c.conversions, 0) / s.total_sessions, 0) AS conversion_rate
+ FROM sessions_by_bucket s
+ CROSS JOIN goal_ids g
+ LEFT JOIN conversions_by_goal c ON c.time = s.time AND c.goal_id = g.goal_id
+ ORDER BY s.time ASC, g.goal_id ASC
+ `;
+
+ const result = await clickhouse.query({
+ query,
+ format: "JSONEachRow",
+ query_params: {
+ siteId,
+ timeZone,
+ },
+ });
+
+ const data = await processResults<GoalTimeSeriesPoint>(result);
+ return res.send({ data });
+ } catch (error) {
+ console.error("Error fetching goal time series:", error);
+ return res.status(500).send({ error: "Failed to fetch goal time series" });
+ }
+}
diff --git a/server/src/api/analytics/goals/goalConditions.ts b/server/src/api/analytics/goals/goalConditions.ts
new file mode 100644
index 000000000..6c3f0c8e8
--- /dev/null
+++ b/server/src/api/analytics/goals/goalConditions.ts
@@ -0,0 +1,68 @@
+import SqlString from "sqlstring";
+import { patternToRegex } from "../utils/utils.js";
+
+type GoalConfig = {
+ pathPattern?: string;
+ eventName?: string;
+ eventPropertyKey?: string;
+ eventPropertyValue?: string | number | boolean;
+ propertyFilters?: Array<{
+ key: string;
+ value: string | number | boolean;
+ }>;
+};
+
+type GoalConditionInput = {
+ goalType: string;
+ config: GoalConfig;
+};
+
+const getPropertyFilters = (config: GoalConfig) =>
+ config.propertyFilters ||
+ (config.eventPropertyKey && config.eventPropertyValue !== undefined
+ ? [{ key: config.eventPropertyKey, value: config.eventPropertyValue }]
+ : []);
+
+export function buildGoalCondition(goal: GoalConditionInput) {
+ if (goal.goalType === "path") {
+ const pathPattern = goal.config.pathPattern;
+ if (!pathPattern) return null;
+
+ const regex = patternToRegex(pathPattern);
+ let condition = `type = 'pageview' AND match(pathname, ${SqlString.escape(regex)})`;
+
+ for (const filter of getPropertyFilters(goal.config)) {
+ const propValueAccessor = `url_parameters[${SqlString.escape(filter.key)}]`;
+ condition += ` AND ${propValueAccessor} = ${SqlString.escape(String(filter.value))}`;
+ }
+
+ return condition;
+ }
+
+ if (goal.goalType === "event") {
+ const eventName = goal.config.eventName;
+ if (!eventName) return null;
+
+ let condition = `type = 'custom_event' AND event_name = ${SqlString.escape(eventName)}`;
+
+ for (const filter of getPropertyFilters(goal.config)) {
+ if (typeof filter.value === "string") {
+ condition += ` AND JSONExtractString(toString(props), ${SqlString.escape(filter.key)}) = ${SqlString.escape(
+ filter.value
+ )}`;
+ } else if (typeof filter.value === "number") {
+ condition += ` AND toFloat64(JSONExtractString(toString(props), ${SqlString.escape(
+ filter.key
+ )})) = ${SqlString.escape(filter.value)}`;
+ } else if (typeof filter.value === "boolean") {
+ condition += ` AND JSONExtractString(toString(props), ${SqlString.escape(filter.key)}) = ${SqlString.escape(
+ filter.value ? "true" : "false"
+ )}`;
+ }
+ }
+
+ return condition;
+ }
+
+ return null;
+}
diff --git a/server/src/api/analytics/index.ts b/server/src/api/analytics/index.ts
index 36efd2b2a..d2990b61e 100644
--- a/server/src/api/analytics/index.ts
+++ b/server/src/api/analytics/index.ts
@@ -18,6 +18,7 @@ export { createGoal } from "./goals/createGoal.js";
export { deleteGoal } from "./goals/deleteGoal.js";
export { getGoals } from "./goals/getGoals.js";
export { getGoalSessions } from "./goals/getGoalSessions.js";
+export { getGoalTimeSeries } from "./goals/getGoalTimeSeries.js";
export { updateGoal } from "./goals/updateGoal.js";
// Performance
diff --git a/server/src/index.ts b/server/src/index.ts
index f73b9a310..062072bbf 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -33,6 +33,7 @@ import {
getFunnelStepSessions,
getFunnels,
getGoalSessions,
+ getGoalTimeSeries,
getGoals,
getJourneys,
getLiveUsercount,
@@ -270,6 +271,7 @@ async function analyticsRoutes(fastify: FastifyInstance) {
fastify.post("/sites/:siteId/funnels", authSite, createFunnel);
fastify.delete("/sites/:siteId/funnels/:funnelId", authSite, deleteFunnel);
fastify.get("/sites/:siteId/goals", publicSite, getGoals);
+ fastify.get("/sites/:siteId/goals/bucketed", publicSite, getGoalTimeSeries);
fastify.get("/sites/:siteId/goals/:goalId/sessions", publicSite, getGoalSessions);
fastify.post("/sites/:siteId/goals", authSite, createGoal);
fastify.delete("/sites/:siteId/goals/:goalId", authSite, deleteGoal);