Skip to content

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

Shared pieces for the site page redesign: stat band, analysis bar, pivots (#1280)

Goldflag7c7493363d9a
diff --git a/client/src/api/analytics/endpoints/events.ts b/client/src/api/analytics/endpoints/events.ts
index f852b486a..86143470c 100644
--- a/client/src/api/analytics/endpoints/events.ts
+++ b/client/src/api/analytics/endpoints/events.ts
@@ -47,6 +47,44 @@ export type EventName = {
count: number;
};
+// One row of the events page's names table: count, users, last occurrence and
+// the count per trend bucket (aligned to EventNameStats.buckets)
+export type EventNameStat = {
+ eventName: string;
+ count: number;
+ users: number;
+ lastSeen: string;
+ trend: number[];
+};
+
+export type EventTrendBucket = "hour" | "day" | "week" | "month";
+
+export type EventNameStats = {
+ // Bucket start times in the request's timezone, oldest first
+ buckets: string[];
+ events: EventNameStat[];
+};
+
+// The events page's stat band, for one period
+export type EventsOverview = {
+ events: number;
+ users_with_events: number;
+ users: number;
+ sessions: number;
+ sessions_with_events: number;
+ event_names: number;
+ autocaptured: number;
+};
+
+// A custom event that fired on most days and then stopped
+export type SilentEvent = {
+ eventName: string;
+ lastSeen: string;
+ total: number;
+ activeDays: number;
+ spanDays: number;
+};
+
// Event property key-value pair
export type EventProperty = {
propertyKey: string;
diff --git a/client/src/api/analytics/endpoints/funnels.ts b/client/src/api/analytics/endpoints/funnels.ts
index 2fadd5ed6..0b75c8491 100644
--- a/client/src/api/analytics/endpoints/funnels.ts
+++ b/client/src/api/analytics/endpoints/funnels.ts
@@ -60,8 +60,27 @@ export interface SavedFunnel {
steps: FunnelStep[];
createdAt: string;
updatedAt: string;
- conversionRate: number | null;
- totalVisitors: number | null;
+}
+
+// One saved funnel over one period, from GET /sites/:site/funnels/summary
+export interface FunnelSummary {
+ funnel_id: number;
+ steps: {
+ sessions: number;
+ // Median time from reaching this step to reaching the next; null on the
+ // last step and when nobody continued
+ median_seconds_to_next: number | null;
+ }[];
+ // Median time from the first step to the last
+ median_seconds_to_convert: number | null;
+}
+
+export interface FunnelSummariesResponse {
+ // Distinct sessions that reached the first step of at least one saved funnel
+ sessions_entered_any: number;
+ funnels: FunnelSummary[];
+ // The site has more saved funnels than one summary covers
+ truncated: boolean;
}
export interface AnalyzeFunnelParams extends CommonApiParams {
diff --git a/client/src/api/analytics/endpoints/goals.ts b/client/src/api/analytics/endpoints/goals.ts
index 4123ec6f7..41f1fa649 100644
--- a/client/src/api/analytics/endpoints/goals.ts
+++ b/client/src/api/analytics/endpoints/goals.ts
@@ -54,6 +54,33 @@ export interface GoalTimeSeriesPoint {
conversion_rate: number;
}
+/**
+ * Every goal of the site (up to the server's bound) with its conversions in
+ * the window, most conversions first, plus the totals the summary band shows.
+ */
+export interface GoalsSummary {
+ goals: Goal[];
+ total_sessions: number;
+ /** Sessions that completed at least one goal. */
+ converting_sessions: number;
+ /** Goals the site has; larger than `goals.length` when the bound was hit. */
+ total_goals: number;
+}
+
+/** A goal before it is saved: its type and what it matches. */
+export interface GoalDefinition {
+ goalType: GoalType;
+ config: GoalConfig;
+}
+
+/** What an unsaved goal would have counted in the window. */
+export interface GoalPreview {
+ conversions: number;
+ total_sessions: number;
+ conversion_rate: number;
+ series: { time: string; conversions: number }[];
+}
+
export interface GoalsParams extends CommonApiParams, PaginationParams, SortParams {
pageSize?: number;
sort?: "goalId" | "name" | "goalType" | "createdAt";
diff --git a/client/src/api/analytics/endpoints/index.ts b/client/src/api/analytics/endpoints/index.ts
index 565e5727f..e5be72ba2 100644
--- a/client/src/api/analytics/endpoints/index.ts
+++ b/client/src/api/analytics/endpoints/index.ts
@@ -17,6 +17,11 @@ export type {
NewEventsResponse,
CursorEventsResponse,
EventName,
+ EventNameStat,
+ EventNameStats,
+ EventTrendBucket,
+ EventsOverview,
+ SilentEvent,
EventProperty,
AutocaptureEvent,
AutocaptureValue,
@@ -57,6 +62,9 @@ export type {
Goal,
GoalType,
GoalConfig,
+ GoalDefinition,
+ GoalPreview,
+ GoalsSummary,
GoalTimeSeriesPoint,
PaginationMeta,
GoalsResponse,
@@ -104,6 +112,8 @@ export type {
FunnelRequest,
SaveFunnelRequest,
FunnelResponse,
+ FunnelSummary,
+ FunnelSummariesResponse,
AnalyzeFunnelParams,
FunnelStepSessionsParams,
SaveFunnelParams,
@@ -118,6 +128,7 @@ export type {
PerformanceTimeSeriesParams,
PerformanceByDimensionParams,
PaginatedPerformanceResponse,
+ WebVitalRatingCounts,
} from "./performance";
// Bots types
@@ -144,7 +155,12 @@ export type {
SessionDetails,
SessionEvent,
SessionEventProps,
+ SessionGoal,
SessionPageviewsAndEvents,
+ SessionSort,
+ SessionsSummary,
+ SessionView,
+ SessionViewCounts,
LiveSessionLocation,
SessionsParams,
SessionDetailsParams,
@@ -161,6 +177,7 @@ export type {
LinkedDevice,
UserSessionCountResponse,
UsersListResponse,
+ UsersSummary,
IdentifyUserPayload,
} from "./users";
@@ -171,6 +188,8 @@ export type {
RetentionMode,
Journey,
JourneysResponse,
+ JourneyGrouping,
+ JourneySummary,
RetentionParams,
JourneysParams,
PageTitleItem,
@@ -193,16 +212,7 @@ export type {
} from "./sessionReplay";
// User Traits types
-export type {
- TraitKey,
- TraitKeysResponse,
- TraitValue,
- TraitValuesResponse,
- TraitValuesParams,
- TraitValueUser,
- TraitValueUsersResponse,
- TraitValueUsersParams,
-} from "./userTraits";
+export type { TraitKey, TraitKeysResponse, TraitGroupStats, TraitValueGroup, TraitBreakdown } from "./userTraits";
// Export endpoints
export { exportPdfReport } from "./export";
diff --git a/client/src/api/analytics/endpoints/misc.ts b/client/src/api/analytics/endpoints/misc.ts
index 24ede32ea..32fa0327d 100644
--- a/client/src/api/analytics/endpoints/misc.ts
+++ b/client/src/api/analytics/endpoints/misc.ts
@@ -3,10 +3,23 @@ import { CommonApiParams, PaginationParams } from "./types";
// Retention types
export interface ProcessedRetentionData {
- cohorts: Record<string, { size: number; percentages: (number | null)[] }>;
+ // Keyed by the cohort period's first day (YYYY-MM-DD); empty cohorts are left
+ // out. `percentages` and `counts` are per period since the first visit, null
+ // past the end of the window.
+ cohorts: Record<string, { size: number; percentages: (number | null)[]; counts: (number | null)[] }>;
maxPeriods: number;
mode: "day" | "week";
range: number;
+ // Every cohort period in the window, oldest first.
+ periods: string[];
+ windowStart: string;
+ windowEnd: string;
+ timeZone: string;
+ firstPeriodPartial: boolean;
+ lastPeriodPartial: boolean;
+ lastPeriodInProgress: boolean;
+ truncated: boolean;
+ lookbackDays: number;
}
export type RetentionMode = "day" | "week";
@@ -15,11 +28,28 @@ export type RetentionMode = "day" | "week";
export interface Journey {
path: string[];
count: number;
+ /** Share of the sessions with two or more pages, 0–100. */
percentage: number;
+ /** Sessions on this path that completed the requested goal; absent without a goal. */
+ conversions?: number;
}
export interface JourneysResponse {
journeys: Journey[];
+ /** Sessions with two or more pages in the period, before any step filter. */
+ totalSessions: number;
+}
+
+/** "section" collapses the pages under a first-level folder into one step, e.g. /docs/**. */
+export type JourneyGrouping = "path" | "section";
+
+export interface JourneySummary {
+ /** Sessions that visited two or more pages. */
+ sessions: number;
+ avgPathLength: number;
+ /** Null when no goal was requested. */
+ conversions: number | null;
+ topExit: { page: string; sessions: number } | null;
}
// Page title types
diff --git a/client/src/api/analytics/endpoints/performance.ts b/client/src/api/analytics/endpoints/performance.ts
index b0dfd1245..8555fb054 100644
--- a/client/src/api/analytics/endpoints/performance.ts
+++ b/client/src/api/analytics/endpoints/performance.ts
@@ -1,23 +1,20 @@
-import { TimeBucket } from "@rybbit/shared";
+import type { PercentileLevel, TimeBucket, WebVitalMetric } from "@rybbit/shared";
import { CommonApiParams, PaginationParams, SortParams } from "./types";
+type WebVitalPercentiles = {
+ [K in WebVitalMetric as `${K}_${PercentileLevel}`]: number | null;
+};
+
+/** Loads that reported each metric, and how many of those were good and poor. */
+export type WebVitalRatingCounts = {
+ [K in WebVitalMetric as `${K}_${"count" | "good" | "poor"}`]: number;
+};
+
// Performance Overview Response
-export type GetPerformanceOverviewResponse = {
- current: {
- lcp: number;
- cls: number;
- inp: number;
- fcp: number;
- ttfb: number;
+export type GetPerformanceOverviewResponse = WebVitalPercentiles &
+ WebVitalRatingCounts & {
+ total_performance_events: number;
};
- previous: {
- lcp: number;
- cls: number;
- inp: number;
- fcp: number;
- ttfb: number;
- };
-};
// Performance Time Series Response
export type GetPerformanceTimeSeriesResponse = {
@@ -74,22 +71,16 @@ export type PerformanceByDimensionItem = {
ttfb_p75: number | null;
ttfb_p90: number | null;
ttfb_p99: number | null;
-};
+} & WebVitalRatingCounts;
-export interface PerformanceOverviewParams extends CommonApiParams {
- percentile?: number | string;
-}
+export type PerformanceOverviewParams = CommonApiParams;
export interface PerformanceTimeSeriesParams extends CommonApiParams {
bucket: TimeBucket;
}
-export interface PerformanceByDimensionParams
- extends CommonApiParams,
- PaginationParams,
- SortParams {
+export interface PerformanceByDimensionParams extends CommonApiParams, PaginationParams, SortParams {
dimension: string;
- percentile?: number | string;
}
export interface PaginatedPerformanceResponse {
diff --git a/client/src/api/analytics/endpoints/sessions.ts b/client/src/api/analytics/endpoints/sessions.ts
index 99c00d0b0..73e3aefac 100644
--- a/client/src/api/analytics/endpoints/sessions.ts
+++ b/client/src/api/analytics/endpoints/sessions.ts
@@ -1,6 +1,13 @@
import { authedFetch } from "../../utils";
import { CommonApiParams, PaginationParams, toQueryParams } from "./types";
+// A goal a session or one of its events completed. `name` is null for an
+// unnamed goal.
+export interface SessionGoal {
+ id: number;
+ name: string | null;
+}
+
// Session response type
export type GetSessionsResponse = {
session_id: string;
@@ -45,8 +52,34 @@ export type GetSessionsResponse = {
lat: number;
lon: number;
has_replay: number;
+ // Goals the session completed, the most recent conversion first. Only the
+ // sessions list returns it, and only when asked to (include_goals).
+ converted_goals?: SessionGoal[];
}[];
+// The saved views of the Sessions page
+export type SessionView = "all" | "identified" | "replay" | "converted" | "bounced" | "errors";
+
+export type SessionSort = "started" | "ended" | "duration" | "pageviews" | "events" | "errors";
+
+// How many sessions each view holds. `converted` is null on a site with no goals.
+export type SessionViewCounts = Record<Exclude<SessionView, "converted">, number> & { converted: number | null };
+
+// Sessions summary response type
+export interface SessionsSummary {
+ // The period at a glance, whatever the pageview/event/duration ranges are set to
+ sessions: number;
+ session_duration: number;
+ pages_per_session: number;
+ bounce_rate: number;
+ converted: number | null;
+ with_errors: number;
+ // The same sessions narrowed by the ranges, per view
+ matching: SessionViewCounts;
+ // `matching` by the day each session started (YYYY-MM-DD in the request's timezone), newest first
+ days: ({ day: string } & SessionViewCounts)[];
+}
+
// Session details type
export interface SessionDetails {
session_id: string;
@@ -93,6 +126,8 @@ export interface SessionEvent {
type: string;
event_name?: string;
props?: SessionEventProps;
+ // Goals this event completed
+ goals?: SessionGoal[];
}
// Session pageviews and events response
@@ -121,8 +156,15 @@ export interface SessionsParams extends CommonApiParams, PaginationParams {
sessionId?: string;
identifiedOnly?: boolean;
minPageviews?: number;
+ maxPageviews?: number;
minEvents?: number;
+ maxEvents?: number;
minDuration?: number;
+ maxDuration?: number;
+ view?: SessionView;
+ sortBy?: SessionSort;
+ sortOrder?: "asc" | "desc";
+ includeGoals?: boolean;
}
export interface SessionDetailsParams {
@@ -148,8 +190,15 @@ export async function fetchSessions(
session_id: params.sessionId,
identified_only: params.identifiedOnly,
min_pageviews: params.minPageviews,
+ max_pageviews: params.maxPageviews,
min_events: params.minEvents,
+ max_events: params.maxEvents,
min_duration: params.minDuration,
+ max_duration: params.maxDuration,
+ view: params.view,
+ sort_by: params.sortBy,
+ sort_order: params.sortOrder,
+ include_goals: params.includeGoals || undefined,
};
const response = await authedFetch<{ data: GetSessionsResponse }>(
diff --git a/client/src/api/analytics/endpoints/userProfile.ts b/client/src/api/analytics/endpoints/userProfile.ts
new file mode 100644
index 000000000..b1ef8a0c9
--- /dev/null
+++ b/client/src/api/analytics/endpoints/userProfile.ts
@@ -0,0 +1,58 @@
+import { Filter } from "@rybbit/shared";
+
+// Response shapes of the user profile's own endpoints (/sites/:site/users/:userId/…).
+
+/** The stat band for one window. A window with no sessions is all zeros. */
+export interface UserSummary {
+ sessions: number;
+ pageviews: number;
+ events: number;
+ /** Average session length in seconds. */
+ duration: number;
+ /** Days, in the dashboard's timezone, on which the user started a session. */
+ active_days: number;
+}
+
+export interface UserGoal {
+ goalId: number;
+ name: string | null;
+ goalType: string;
+ /** Sessions in the window in which this user completed the goal. */
+ sessions: number;
+ /** Latest completion in the window, UTC SQL datetime. Null when there is none. */
+ last_completed: string | null;
+}
+
+export interface UserSessionGoals {
+ session_id: string;
+ goal_ids: number[];
+}
+
+export interface UserSegmentMatch {
+ segmentId: number;
+ name: string;
+ /** The segment's own filters, for linking to the sessions it selects. */
+ filters: Filter[];
+ /** Sessions of this user, in the window, that the segment's filters select. */
+ sessions: number;
+}
+
+export interface UserSegments {
+ segments: UserSegmentMatch[];
+ /** This user's sessions in the window: what each count is out of. */
+ total_sessions: number;
+ /** The site has more segments than one request evaluates. */
+ truncated: boolean;
+}
+
+/** The latest session in the window in which one error message was thrown twice or more. */
+export interface UserRepeatedError {
+ message: string;
+ session_id: string;
+ occurrences: number;
+ /** Page the first of them was thrown on. */
+ pathname: string;
+ first_seen: string;
+ last_seen: string;
+ has_replay: boolean;
+}
diff --git a/client/src/api/analytics/endpoints/userTraits.ts b/client/src/api/analytics/endpoints/userTraits.ts
index 26a65dec0..3feffc715 100644
--- a/client/src/api/analytics/endpoints/userTraits.ts
+++ b/client/src/api/analytics/endpoints/userTraits.ts
@@ -7,45 +7,31 @@ export interface TraitKeysResponse {
keys: TraitKey[];
}
-export interface TraitValue {
- value: string;
- userCount: number;
-}
-
-export interface TraitValuesResponse {
- values: TraitValue[];
- total: number;
- hasMore: boolean;
-}
-
-export interface TraitValuesParams {
- key: string;
- limit?: number;
- offset?: number;
-}
-
-export interface TraitValueUser {
- user_id: string;
- identified_user_id: string;
- traits: Record<string, unknown> | null;
- country: string;
- region: string;
- city: string;
- browser: string;
- operating_system: string;
- device_type: string;
+// Totals for a set of users. Sessions, pageviews and events are sums.
+export interface TraitGroupStats {
+ users: number;
sessions: number;
+ pageviews: number;
+ events: number;
}
-export interface TraitValueUsersResponse {
- users: TraitValueUser[];
- total: number;
- hasMore: boolean;
+export interface TraitValueGroup extends TraitGroupStats {
+ value: string;
}
-export interface TraitValueUsersParams {
+// The period's users grouped by one trait. Every user is in exactly one of
+// groups, other or none.
+export interface TraitBreakdown {
key: string;
- value: string;
- limit?: number;
- offset?: number;
+ // Too many identified users were active to join to their traits; the rest is empty
+ limited: boolean;
+ limit: number;
+ totals: (TraitGroupStats & { identified: number }) | null;
+ // The largest values, by users
+ groups: TraitValueGroup[];
+ // Every value past the largest ones, together
+ other: (TraitGroupStats & { values: number }) | null;
+ // Users with no value for the key: anonymous, or identified without it
+ none: TraitGroupStats | null;
+ searchLimited?: boolean;
}
diff --git a/client/src/api/analytics/endpoints/users.ts b/client/src/api/analytics/endpoints/users.ts
index a75421e4f..d0e68d456 100644
--- a/client/src/api/analytics/endpoints/users.ts
+++ b/client/src/api/analytics/endpoints/users.ts
@@ -111,6 +111,29 @@ export interface UsersListResponse {
totalCount: number;
page: number;
pageSize: number;
+ // More profiles matched a name, username or email search than the server
+ // looks up at once; the list covers the most recently updated of them.
+ searchLimited?: boolean;
+ // A trait group was asked for in a period with too many identified users to
+ // join to their traits.
+ breakdownLimited?: boolean;
+}
+
+// The Users page's stat band figures for one period
+export interface UsersSummary {
+ users: number;
+ identified_users: number;
+ // Sum of every user's session count
+ sessions: number;
+ identified_sessions: number;
+ // Null for an all-time period, which has no earlier window to look back over
+ new_users: number | null;
+ returning_users: number | null;
+ // How far back "new" looks, in days
+ lookback_days: number;
+ // Users with at least power_min_sessions sessions in the period
+ power_users: number;
+ power_min_sessions: number;
}
export interface IdentifyUserPayload {
diff --git a/client/src/api/analytics/hooks/events/useGetEventNameStats.ts b/client/src/api/analytics/hooks/events/useGetEventNameStats.ts
new file mode 100644
index 000000000..b87159473
--- /dev/null
+++ b/client/src/api/analytics/hooks/events/useGetEventNameStats.ts
@@ -0,0 +1,19 @@
+import { EVENT_FILTERS } from "../../../../lib/filterGroups";
+import { getFilteredFilters } from "../../../../lib/store";
+import { EventNameStats, EventTrendBucket } from "../../endpoints";
+import { useAnalyticsQuery } from "../../useAnalyticsQuery";
+
+// Every custom event name in the period with its count, users, last occurrence
+// and trend: one request for the whole table.
+export function useGetEventNameStats({ trendBucket }: { trendBucket: EventTrendBucket }) {
+ const filteredFilters = getFilteredFilters(EVENT_FILTERS);
+
+ return useAnalyticsQuery<EventNameStats>({
+ key: "event-name-stats",
+ path: "events/names/stats",
+ // Only event-relevant filters go on the wire; when none apply, send no filters.
+ useFilters: filteredFilters.length > 0,
+ customFilters: filteredFilters,
+ params: { trend_bucket: trendBucket },
+ });
+}
diff --git a/client/src/api/analytics/hooks/events/useGetEventNames.ts b/client/src/api/analytics/hooks/events/useGetEventNames.ts
index 07804d3f8..bbb7ba7e3 100644
--- a/client/src/api/analytics/hooks/events/useGetEventNames.ts
+++ b/client/src/api/analytics/hooks/events/useGetEventNames.ts
@@ -3,12 +3,13 @@ import { getFilteredFilters } from "../../../../lib/store";
import { EventName } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
-export function useGetEventNames() {
+export function useGetEventNames({ periodTime }: { periodTime?: "current" | "previous" } = {}) {
const filteredFilters = getFilteredFilters(EVENT_FILTERS);
return useAnalyticsQuery<EventName[]>({
key: "event-names",
path: "events/names",
+ periodTime,
// Only event-relevant filters go on the wire; when none apply, send no filters.
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
diff --git a/client/src/api/analytics/hooks/events/useGetEventsOverview.ts b/client/src/api/analytics/hooks/events/useGetEventsOverview.ts
new file mode 100644
index 000000000..f45b32cf4
--- /dev/null
+++ b/client/src/api/analytics/hooks/events/useGetEventsOverview.ts
@@ -0,0 +1,17 @@
+import { EVENT_FILTERS } from "../../../../lib/filterGroups";
+import { getFilteredFilters } from "../../../../lib/store";
+import { EventsOverview } from "../../endpoints";
+import { useAnalyticsQuery } from "../../useAnalyticsQuery";
+
+export function useGetEventsOverview({ periodTime }: { periodTime?: "current" | "previous" } = {}) {
+ const filteredFilters = getFilteredFilters(EVENT_FILTERS);
+
+ return useAnalyticsQuery<EventsOverview>({
+ key: "events-overview",
+ path: "events/overview",
+ periodTime,
+ // Only event-relevant filters go on the wire; when none apply, send no filters.
+ useFilters: filteredFilters.length > 0,
+ customFilters: filteredFilters,
+ });
+}
diff --git a/client/src/api/analytics/hooks/events/useGetSilentEvents.ts b/client/src/api/analytics/hooks/events/useGetSilentEvents.ts
new file mode 100644
index 000000000..94129c315
--- /dev/null
+++ b/client/src/api/analytics/hooks/events/useGetSilentEvents.ts
@@ -0,0 +1,15 @@
+import { SilentEvent } from "../../endpoints";
+import { useAnalyticsQuery } from "../../useAnalyticsQuery";
+
+// Custom events that fired on most days and then stopped. A statement about
+// the site right now: it ignores the selected period and filters, so it does
+// not refetch when either changes.
+export function useGetSilentEvents() {
+ return useAnalyticsQuery<SilentEvent[]>({
+ key: "silent-events",
+ path: "events/silent",
+ useTime: false,
+ useFilters: false,
+ staleTime: 5 * 60_000,
+ });
+}
diff --git a/client/src/api/analytics/hooks/events/useGetSiteEventCount.ts b/client/src/api/analytics/hooks/events/useGetSiteEventCount.ts
index 9048c2c1a..7537ee248 100644
--- a/client/src/api/analytics/hooks/events/useGetSiteEventCount.ts
+++ b/client/src/api/analytics/hooks/events/useGetSiteEventCount.ts
@@ -3,13 +3,14 @@ import { getFilteredFilters, useStore } from "../../../../lib/store";
import { type SiteEventCountPoint } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
-export function useGetSiteEventCount() {
+export function useGetSiteEventCount({ periodTime }: { periodTime?: "current" | "previous" } = {}) {
const bucket = useStore(state => state.bucket);
const filteredFilters = getFilteredFilters(EVENT_FILTERS);
return useAnalyticsQuery<SiteEventCountPoint[]>({
key: "site-event-count",
path: "events/count",
+ periodTime,
// Only event-relevant filters go on the wire; when none apply, send no filters.
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
diff --git a/client/src/api/analytics/hooks/funnels/useGetFunnelGoals.ts b/client/src/api/analytics/hooks/funnels/useGetFunnelGoals.ts
new file mode 100644
index 000000000..de61ef257
--- /dev/null
+++ b/client/src/api/analytics/hooks/funnels/useGetFunnelGoals.ts
@@ -0,0 +1,21 @@
+import { GoalsResponse } from "../../endpoints";
+import { useAnalyticsQuery } from "../../useAnalyticsQuery";
+
+// The goals endpoint's largest page.
+const MAX_GOALS = 100;
+
+/**
+ * The site's goals, for linking a funnel's last step to the goal that measures
+ * the same thing. Only the definitions are read, so no filters are sent.
+ */
+export function useGetFunnelGoals({ enabled = true }: { enabled?: boolean } = {}) {
+ return useAnalyticsQuery<GoalsResponse>({
+ // Same prefix as the goals list, so creating or editing a goal refreshes this too.
+ key: "goals",
+ path: "goals",
+ unwrap: false,
+ useFilters: false,
+ params: { page: 1, page_size: MAX_GOALS, sort: "createdAt", order: "desc" },
+ enabled,
+ });
+}
diff --git a/client/src/api/analytics/hooks/funnels/useGetFunnelStepSessions.ts b/client/src/api/analytics/hooks/funnels/useGetFunnelStepSessions.ts
index b037059a5..0be9c072b 100644
--- a/client/src/api/analytics/hooks/funnels/useGetFunnelStepSessions.ts
+++ b/client/src/api/analytics/hooks/funnels/useGetFunnelStepSessions.ts
@@ -12,6 +12,7 @@ export function useGetFunnelStepSessions({
mode,
page = 1,
limit = 25,
+ replaysOnly = false,
enabled = false,
}: {
steps: FunnelStep[];
@@ -21,6 +22,8 @@ export function useGetFunnelStepSessions({
mode: "reached" | "dropped";
page?: number;
limit?: number;
+ /** Lists only the sessions that have a replay. */
+ replaysOnly?: boolean;
enabled?: boolean;
}) {
// Only the funnel page's filter parameters apply; an empty subset means no
@@ -34,7 +37,7 @@ export function useGetFunnelStepSessions({
overrideTime: time,
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- params: { mode, page, limit },
+ params: { mode, page, limit, replays_only: replaysOnly ? "true" : undefined },
body: () => ({ steps }),
enabled: !!steps && steps.length >= 2 && enabled,
});
diff --git a/client/src/api/analytics/hooks/funnels/useGetFunnelSummaries.ts b/client/src/api/analytics/hooks/funnels/useGetFunnelSummaries.ts
new file mode 100644
index 000000000..8ddf55be6
--- /dev/null
+++ b/client/src/api/analytics/hooks/funnels/useGetFunnelSummaries.ts
@@ -0,0 +1,25 @@
+import { FUNNEL_PAGE_FILTERS } from "../../../../lib/filterGroups";
+import { getFilteredFilters } from "../../../../lib/store";
+import { FunnelSummariesResponse } from "../../endpoints";
+import { useAnalyticsQuery } from "../../useAnalyticsQuery";
+
+/**
+ * Step counts and step-to-step medians for every saved funnel of the site, in
+ * one request per period. `periodTime: "previous"` asks about the comparison
+ * period and stays idle while the comparison is off.
+ */
+export function useGetFunnelSummaries({ periodTime }: { periodTime?: "current" | "previous" } = {}) {
+ // Only the funnel page's filter parameters apply; an empty subset means no
+ // filters at all (not the store's full filter list).
+ const filteredFilters = getFilteredFilters(FUNNEL_PAGE_FILTERS);
+
+ return useAnalyticsQuery<FunnelSummariesResponse>({
+ // Same prefix as the saved funnel list, so saving or deleting a funnel
+ // refreshes its numbers along with its definition.
+ key: "funnels",
+ path: "funnels/summary",
+ periodTime,
+ useFilters: filteredFilters.length > 0,
+ customFilters: filteredFilters,
+ });
+}
diff --git a/client/src/api/analytics/hooks/goals/useCreateGoal.ts b/client/src/api/analytics/hooks/goals/useCreateGoal.ts
index 9def65649..dac2719e4 100644
--- a/client/src/api/analytics/hooks/goals/useCreateGoal.ts
+++ b/client/src/api/analytics/hooks/goals/useCreateGoal.ts
@@ -29,6 +29,9 @@ export function useCreateGoal() {
queryClient.invalidateQueries({
queryKey: ["goals", variables.siteId.toString()],
});
+ queryClient.invalidateQueries({
+ queryKey: ["goals-summary", 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 dc5bcd950..8c269e7fb 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: ["goals-summary", site],
+ });
queryClient.invalidateQueries({
queryKey: ["goal-time-series", site],
});
diff --git a/client/src/api/analytics/hooks/goals/useGetGoalPreview.ts b/client/src/api/analytics/hooks/goals/useGetGoalPreview.ts
new file mode 100644
index 000000000..99d883737
--- /dev/null
+++ b/client/src/api/analytics/hooks/goals/useGetGoalPreview.ts
@@ -0,0 +1,30 @@
+import { GOALS_PAGE_FILTERS } from "../../../../lib/filterGroups";
+import { getFilteredFilters, useStore } from "../../../../lib/store";
+import { GoalDefinition, GoalPreview } from "../../endpoints";
+import { useAnalyticsQuery } from "../../useAnalyticsQuery";
+
+/**
+ * What a goal that has not been saved would have counted in the selected
+ * period. Pass null while the definition is incomplete; debounce the
+ * definition before passing it, since every distinct one is a request.
+ */
+export function useGetGoalPreview(definition: GoalDefinition | null) {
+ const bucket = useStore(state => state.bucket);
+ // The same filters the ledger applies, so the preview and the saved goal agree.
+ const filteredFilters = getFilteredFilters(GOALS_PAGE_FILTERS);
+
+ return useAnalyticsQuery<GoalPreview>({
+ key: "goal-preview",
+ path: "goals/preview",
+ useFilters: filteredFilters.length > 0,
+ customFilters: filteredFilters,
+ params: { bucket },
+ body: () => definition,
+ enabled: definition !== null,
+ // A preview of another definition is not a stand-in for this one.
+ placeholder: false,
+ // A preview that failed (a pattern the server refuses, the rate limit) is
+ // reported as unavailable rather than asked for again.
+ props: { retry: false },
+ });
+}
diff --git a/client/src/api/analytics/hooks/goals/useGetGoalTimeSeries.ts b/client/src/api/analytics/hooks/goals/useGetGoalTimeSeries.ts
index 1fc9c6330..5bb58c1f8 100644
--- a/client/src/api/analytics/hooks/goals/useGetGoalTimeSeries.ts
+++ b/client/src/api/analytics/hooks/goals/useGetGoalTimeSeries.ts
@@ -4,7 +4,18 @@ import { getFilteredFilters, useStore } from "../../../../lib/store";
import { GoalTimeSeriesPoint } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
-export function useGetGoalTimeSeries({ goalIds, bucket }: { goalIds: number[]; bucket?: TimeBucket }) {
+export function useGetGoalTimeSeries({
+ goalIds,
+ bucket,
+ periodTime,
+ enabled = true,
+}: {
+ goalIds: number[];
+ bucket?: TimeBucket;
+ /** "previous" asks for the comparison period; the query stops when comparison is off. */
+ periodTime?: "current" | "previous";
+ enabled?: boolean;
+}) {
const storeBucket = useStore(state => state.bucket);
// Only the goals page's filter parameters apply; an empty subset means no
// filters at all (not the store's full filter list).
@@ -13,9 +24,10 @@ export function useGetGoalTimeSeries({ goalIds, bucket }: { goalIds: number[]; b
return useAnalyticsQuery<GoalTimeSeriesPoint[]>({
key: "goal-time-series",
path: "goals/time-series",
+ periodTime,
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
params: { bucket: bucket || storeBucket, goal_ids: goalIds },
- enabled: goalIds.length > 0,
+ enabled: enabled && goalIds.length > 0,
});
}
diff --git a/client/src/api/analytics/hooks/goals/useGetGoalsSummary.ts b/client/src/api/analytics/hooks/goals/useGetGoalsSummary.ts
new file mode 100644
index 000000000..ea5aafc08
--- /dev/null
+++ b/client/src/api/analytics/hooks/goals/useGetGoalsSummary.ts
@@ -0,0 +1,23 @@
+import { GOALS_PAGE_FILTERS } from "../../../../lib/filterGroups";
+import { getFilteredFilters } from "../../../../lib/store";
+import { GoalsSummary } from "../../endpoints";
+import { useAnalyticsQuery } from "../../useAnalyticsQuery";
+
+/**
+ * Every goal with its conversions, and the sessions that completed at least
+ * one. `periodTime: "previous"` asks the same question of the comparison
+ * period and stops when comparison is turned off.
+ */
+export function useGetGoalsSummary({ periodTime }: { periodTime?: "current" | "previous" } = {}) {
+ // Only the goals page's filter parameters apply; an empty subset means no
+ // filters at all (not the store's full filter list).
+ const filteredFilters = getFilteredFilters(GOALS_PAGE_FILTERS);
+
+ return useAnalyticsQuery<GoalsSummary>({
+ key: "goals-summary",
+ path: "goals/summary",
+ periodTime,
+ useFilters: filteredFilters.length > 0,
+ customFilters: filteredFilters,
+ });
+}
diff --git a/client/src/api/analytics/hooks/goals/useUpdateGoal.ts b/client/src/api/analytics/hooks/goals/useUpdateGoal.ts
index e3aa1b137..c05c24ea4 100644
--- a/client/src/api/analytics/hooks/goals/useUpdateGoal.ts
+++ b/client/src/api/analytics/hooks/goals/useUpdateGoal.ts
@@ -29,14 +29,20 @@ export function useUpdateGoal() {
config: goalData.config,
});
},
- onSuccess: () => {
+ onSuccess: (_, goalData) => {
// Invalidate goals query to refetch with the updated goal
queryClient.invalidateQueries({
queryKey: ["goals", site],
});
+ queryClient.invalidateQueries({
+ queryKey: ["goals-summary", site],
+ });
queryClient.invalidateQueries({
queryKey: ["goal-time-series", site],
});
+ queryClient.invalidateQueries({
+ queryKey: ["goal-sessions", goalData.goalId],
+ });
},
});
}
diff --git a/client/src/api/analytics/hooks/performance/useGetPerformanceByDimension.ts b/client/src/api/analytics/hooks/performance/useGetPerformanceByDimension.ts
index 4ac15a75c..69496f2f5 100644
--- a/client/src/api/analytics/hooks/performance/useGetPerformanceByDimension.ts
+++ b/client/src/api/analytics/hooks/performance/useGetPerformanceByDimension.ts
@@ -1,46 +1,51 @@
import { Filter } from "@rybbit/shared";
import { UseQueryResult } from "@tanstack/react-query";
-import { usePerformanceStore } from "../../../../app/[site]/performance/performanceStore";
import { PaginatedPerformanceResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
+type PeriodTime = "current" | "previous";
+
type UseGetPerformanceByDimensionOptions = {
site: number | string;
dimension: string;
+ periodTime?: PeriodTime;
limit?: number;
page?: number;
useFilters?: boolean;
additionalFilters?: Filter[];
sortBy?: string;
sortOrder?: "asc" | "desc";
+ enabled?: boolean;
};
+// The response carries every percentile, so the percentile picker never refetches.
export function useGetPerformanceByDimension({
site,
dimension,
+ periodTime,
limit = 10,
page = 1,
useFilters = true,
additionalFilters = [],
sortBy,
sortOrder,
+ enabled,
}: UseGetPerformanceByDimensionOptions): UseQueryResult<PaginatedPerformanceResponse> {
- const { selectedPercentile } = usePerformanceStore();
-
return useAnalyticsQuery<PaginatedPerformanceResponse>({
key: "performance-by-dimension",
path: "performance/by-dimension",
site,
+ periodTime,
useFilters,
additionalFilters,
params: {
dimension,
limit,
page,
- percentile: selectedPercentile,
sort_by: sortBy,
sort_order: sortOrder,
},
staleTime: Infinity,
+ enabled,
});
}
diff --git a/client/src/api/analytics/hooks/performance/useGetPerformanceOverview.ts b/client/src/api/analytics/hooks/performance/useGetPerformanceOverview.ts
index 771baeb97..ab7e79f22 100644
--- a/client/src/api/analytics/hooks/performance/useGetPerformanceOverview.ts
+++ b/client/src/api/analytics/hooks/performance/useGetPerformanceOverview.ts
@@ -1,18 +1,15 @@
-import { usePerformanceStore } from "../../../../app/[site]/performance/performanceStore";
import { GetPerformanceOverviewResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
type PeriodTime = "current" | "previous";
+// The response carries every percentile, so the percentile picker never refetches.
export function useGetPerformanceOverview({ periodTime, site }: { periodTime?: PeriodTime; site?: number | string }) {
- const { selectedPercentile } = usePerformanceStore();
-
return useAnalyticsQuery<GetPerformanceOverviewResponse>({
key: "performance-overview",
path: "performance/overview",
site,
periodTime,
- params: { percentile: selectedPercentile },
staleTime: Infinity,
});
}
diff --git a/client/src/api/analytics/hooks/useGetJourneys.ts b/client/src/api/analytics/hooks/useGetJourneys.ts
index cdee30238..5325b698c 100644
--- a/client/src/api/analytics/hooks/useGetJourneys.ts
+++ b/client/src/api/analytics/hooks/useGetJourneys.ts
@@ -1,40 +1,155 @@
import { Filter } from "@rybbit/shared";
import { Time } from "../../../components/DateSelector/types";
import { JOURNEY_PAGE_FILTERS } from "../../../lib/filterGroups";
-import { getFilteredFilters } from "../../../lib/store";
-import { JourneysResponse } from "../endpoints";
+import { useStore } from "../../../lib/store";
+import {
+ GetOverviewResponse,
+ GetSessionsResponse,
+ JourneyGrouping,
+ JourneysResponse,
+ JourneySummary,
+ MetricResponse,
+} from "../endpoints";
import { useAnalyticsQuery } from "../useAnalyticsQuery";
-export interface JourneyParams {
- siteId?: number;
+type PeriodTime = "current" | "previous";
+
+/** The options that decide which sessions become which journey. */
+export interface JourneyShape {
steps?: number;
+ stepFilters?: Record<number, string>;
+ /** Path pattern the journeys must reach; they are cut at the first visit to it. */
+ endsAt?: string;
+ groupBy?: JourneyGrouping;
+}
+
+export interface JourneyParams extends JourneyShape {
+ siteId?: number;
timeZone?: string;
- time: Time;
+ /** Left out, the store's period is used. */
+ time?: Time;
+ /** "previous" asks for the comparison period instead (and runs only while one is set). */
+ periodTime?: PeriodTime;
limit?: number;
- stepFilters?: Record<number, string>;
+ /** Adds each journey's count of sessions that completed this goal. */
+ goalId?: number;
// Merged with the store filters (e.g. scoping journeys to a single user)
additionalFilters?: Filter[];
+ enabled?: boolean;
}
-export const useJourneys = ({ siteId, steps = 3, time, limit = 100, stepFilters, additionalFilters }: JourneyParams) => {
- const filteredFilters = getFilteredFilters(JOURNEY_PAGE_FILTERS);
- const combinedFilters = additionalFilters?.length ? [...filteredFilters, ...additionalFilters] : filteredFilters;
+/**
+ * The store's filters narrowed to the ones the journeys endpoints honour. An
+ * empty subset has to switch filters off: `customFilters` falls back to the
+ * store's full list when it is empty.
+ */
+function useJourneyFilters(additionalFilters?: Filter[]) {
+ const filters = useStore(state => state.filters);
+ const pageFilters = filters.filter(filter => JOURNEY_PAGE_FILTERS.includes(filter.parameter));
+ const customFilters = additionalFilters?.length ? [...pageFilters, ...additionalFilters] : pageFilters;
+ return { useFilters: customFilters.length > 0, customFilters };
+}
+const journeyShapeParams = ({ steps = 3, stepFilters, endsAt, groupBy }: JourneyShape) => ({
+ steps,
+ stepFilters: stepFilters && Object.keys(stepFilters).length > 0 ? JSON.stringify(stepFilters) : undefined,
+ endsAt: endsAt || undefined,
+ groupBy: groupBy && groupBy !== "path" ? groupBy : undefined,
+});
+
+export const useJourneys = ({
+ siteId,
+ time,
+ periodTime,
+ limit = 100,
+ goalId,
+ additionalFilters,
+ enabled = true,
+ ...shape
+}: JourneyParams) => {
return useAnalyticsQuery<JourneysResponse>({
key: "journeys",
path: "journeys",
unwrap: false,
site: siteId,
overrideTime: time,
- // customFilters fall back to the store filters when empty; disable filters
- // entirely instead so an empty page-filter set stays unfiltered.
- useFilters: combinedFilters.length > 0,
- customFilters: combinedFilters,
+ periodTime,
+ ...useJourneyFilters(additionalFilters),
+ params: { ...journeyShapeParams(shape), limit, goalId },
+ enabled: enabled && siteId !== undefined,
+ });
+};
+
+/** Page-level figures for the journeys page: multi-page sessions, path length, top exit, goal reach. */
+export const useJourneySummary = ({
+ goalId,
+ periodTime,
+ enabled = true,
+}: {
+ goalId?: number;
+ periodTime?: PeriodTime;
+ enabled?: boolean;
+}) => {
+ return useAnalyticsQuery<JourneySummary>({
+ key: "journey-summary",
+ path: "journeys/summary",
+ periodTime,
+ ...useJourneyFilters(),
+ params: { goalId },
+ enabled,
+ });
+};
+
+/** The sessions counted in one journeys row. `shape` must be the one the row was fetched with. */
+export const useJourneySessions = ({
+ path,
+ replaysOnly = false,
+ page = 1,
+ limit = 25,
+ enabled = true,
+ ...shape
+}: JourneyShape & {
+ path: string[];
+ replaysOnly?: boolean;
+ page?: number;
+ limit?: number;
+ enabled?: boolean;
+}) => {
+ return useAnalyticsQuery<GetSessionsResponse>({
+ key: "journey-sessions",
+ path: "journeys/sessions",
+ // Another path's sessions must never stand in while this path's load.
+ placeholder: false,
+ ...useJourneyFilters(),
params: {
- steps,
+ ...journeyShapeParams(shape),
+ path: JSON.stringify(path),
+ replays_only: replaysOnly ? "true" : undefined,
+ page,
limit,
- stepFilters: stepFilters && Object.keys(stepFilters).length > 0 ? JSON.stringify(stepFilters) : undefined,
},
- enabled: siteId !== undefined,
+ enabled: enabled && path.length > 0,
});
};
+
+/**
+ * All sessions and the most common entry page, from the endpoints the main
+ * dashboard reads, under the journeys page's filters, so the figures the stat
+ * band borrows match the ones shown there.
+ */
+export const useJourneyContext = () => {
+ const filters = useJourneyFilters();
+ const overview = useAnalyticsQuery<GetOverviewResponse>({ key: "overview", path: "overview", ...filters });
+ const entryPages = useAnalyticsQuery<{ data: MetricResponse[]; totalCount: number }>({
+ key: "entry_page",
+ path: "metric",
+ ...filters,
+ params: { parameter: "entry_page", limit: 1 },
+ });
+
+ return {
+ sessions: overview.data?.sessions,
+ topEntry: entryPages.data?.data[0],
+ isLoading: overview.isLoading || entryPages.isLoading,
+ };
+};
diff --git a/client/src/api/analytics/hooks/useGetPageTitles.ts b/client/src/api/analytics/hooks/useGetPageTitles.ts
deleted file mode 100644
index 2ce7fd9bc..000000000
--- a/client/src/api/analytics/hooks/useGetPageTitles.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { UseQueryResult } from "@tanstack/react-query";
-import { PageTitlesPaginatedResponse } from "../endpoints";
-import { useAnalyticsQuery } from "../useAnalyticsQuery";
-
-type PeriodTime = "current" | "previous";
-
-type UseGetPageTitlesOptions = {
- limit?: number;
- page?: number;
- useFilters?: boolean;
- periodTime?: PeriodTime;
-};
-
-// Hook for paginated fetching (e.g., for a dedicated "All Page Titles" screen)
-export function useGetPageTitlesPaginated({
- limit = 10,
- page = 1,
- useFilters = true,
- periodTime = "current",
-}: UseGetPageTitlesOptions): UseQueryResult<PageTitlesPaginatedResponse> {
- return useAnalyticsQuery<PageTitlesPaginatedResponse>({
- key: "page-titles",
- path: "page-titles",
- periodTime,
- useFilters,
- params: { limit, page },
- staleTime: Infinity,
- });
-}
diff --git a/client/src/api/analytics/hooks/useGetPages.ts b/client/src/api/analytics/hooks/useGetPages.ts
new file mode 100644
index 000000000..927bac6d1
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetPages.ts
@@ -0,0 +1,143 @@
+import { TimeBucket } from "@rybbit/shared";
+import { InfiniteData, UseInfiniteQueryResult, UseQueryResult } from "@tanstack/react-query";
+import { nextPageByTotalCount, useAnalyticsInfiniteQuery, useAnalyticsQuery } from "../useAnalyticsQuery";
+
+type PeriodTime = "current" | "previous";
+
+export type PagesGroup = "page" | "section";
+export type PagesMode = "all" | "entry" | "exit";
+export type PagesSort = "pageviews" | "sessions" | "entries" | "exits" | "time_on_page" | "bounce_rate";
+export type PagesSortOrder = "asc" | "desc";
+
+export interface PageRow {
+ /** A section row rolls up two or more pages; a section with one page is listed as that page. */
+ kind: "page" | "section";
+ /** The path of a page row, the first path segment of a section row ("/docs"). */
+ key: string;
+ /** The page's most recent title; empty for sections and untitled pages. */
+ title: string;
+ section: string;
+ pages: number;
+ pageviews: number;
+ sessions: number;
+ entries: number;
+ exits: number;
+ bounced_entries: number;
+ /** Average seconds to the next pageview. Exit views have none and are left out. */
+ time_on_page_seconds: number | null;
+ /** Share of the sessions that started here and viewed nothing else, 0–100. */
+ bounce_rate: number | null;
+}
+
+export interface PagesResponse {
+ data: PageRow[];
+ totalCount: number;
+}
+
+export interface SectionViews {
+ section: string;
+ pageviews: number;
+ pages: number;
+}
+
+export interface PagesSummary {
+ pageviews: number;
+ /** Sessions with at least one pageview. */
+ sessions: number;
+ /** Distinct paths viewed. */
+ pages: number;
+ bounced_sessions: number;
+ bounce_rate: number | null;
+ time_on_page_seconds: number | null;
+ views_per_session: number | null;
+ /** Views per section, largest first, capped by the server. */
+ sections: SectionViews[];
+ /** How many sections exist; above `sections.length` when the list was capped. */
+ sectionCount: number;
+}
+
+export interface PageTrend {
+ kind: "page" | "section";
+ key: string;
+ /** Views in the whole period: the sum of `series`. */
+ pageviews: number;
+ series: { time: string; pageviews: number }[];
+}
+
+export interface PagesListOptions {
+ mode: PagesMode;
+ sort: PagesSort;
+ order: PagesSortOrder;
+}
+
+/** The page list, or the section rollups when `group` is "section". */
+export function useGetPages({
+ group,
+ mode,
+ sort,
+ order,
+ search,
+ limit,
+ page,
+}: PagesListOptions & {
+ group: PagesGroup;
+ search?: string;
+ limit: number;
+ page: number;
+}): UseQueryResult<PagesResponse> {
+ return useAnalyticsQuery<PagesResponse>({
+ key: "pages",
+ path: "pages",
+ params: { group, mode, sort, order, search: search || undefined, limit, page },
+ });
+}
+
+/** The pages inside one section, loaded a page at a time. */
+export function useGetSectionPages({
+ section,
+ mode,
+ sort,
+ order,
+ limit,
+}: PagesListOptions & { section: string; limit: number }): UseInfiniteQueryResult<InfiniteData<PagesResponse>> {
+ return useAnalyticsInfiniteQuery<PagesResponse>({
+ key: "pages",
+ path: "pages",
+ params: { group: "page", section, mode, sort, order, limit },
+ initialPageParam: 1,
+ pageParams: page => ({ page }),
+ getNextPageParam: nextPageByTotalCount,
+ });
+}
+
+export function useGetPagesSummary({ periodTime }: { periodTime?: PeriodTime } = {}): UseQueryResult<PagesSummary> {
+ return useAnalyticsQuery<PagesSummary>({
+ key: "pages-summary",
+ path: "pages/summary",
+ periodTime,
+ });
+}
+
+/**
+ * Views over time for a batch of rows in one request. Asked for the previous
+ * period, each trend's `pageviews` is the row's baseline for its change.
+ */
+export function useGetPageTrends({
+ paths,
+ sections,
+ bucket,
+ periodTime,
+}: {
+ paths: string[];
+ sections: string[];
+ bucket: TimeBucket;
+ periodTime?: PeriodTime;
+}): UseQueryResult<PageTrend[]> {
+ return useAnalyticsQuery<PageTrend[]>({
+ key: "page-trends",
+ path: "pages/trends",
+ periodTime,
+ enabled: paths.length + sections.length > 0,
+ params: { bucket, paths, sections },
+ });
+}
diff --git a/client/src/api/analytics/hooks/useGetRetention.ts b/client/src/api/analytics/hooks/useGetRetention.ts
index a0f1c1fff..23ff9a3d8 100644
--- a/client/src/api/analytics/hooks/useGetRetention.ts
+++ b/client/src/api/analytics/hooks/useGetRetention.ts
@@ -1,17 +1,23 @@
import { ProcessedRetentionData, RetentionMode } from "../endpoints";
import { useAnalyticsQuery } from "../useAnalyticsQuery";
-export function useGetRetention(mode: RetentionMode = "week", range: number = 90) {
+/**
+ * Cohort retention for the selected period and filters. `periodTime:
+ * "previous"` asks for the comparison period instead, and is disabled while
+ * the comparison is off.
+ */
+export function useGetRetention(
+ mode: RetentionMode,
+ options: { periodTime?: "current" | "previous"; enabled?: boolean } = {}
+) {
return useAnalyticsQuery<ProcessedRetentionData>({
key: "retention",
path: "retention",
- // Retention spans its own cohort range, not the selected period.
- useTime: false,
- useFilters: false,
- params: { mode, range },
- // Keyed by mode/range: refetch on mount and don't show the previous
- // cohort grid while the new one loads.
- staleTime: 0,
+ params: { mode },
+ periodTime: options.periodTime,
+ enabled: options.enabled,
+ // A new mode or range changes the grid's shape, so the old grid is not
+ // kept on screen while the new one loads.
placeholder: false,
});
}
diff --git a/client/src/api/analytics/hooks/useGetSessionsSummary.ts b/client/src/api/analytics/hooks/useGetSessionsSummary.ts
new file mode 100644
index 000000000..f6db913ce
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetSessionsSummary.ts
@@ -0,0 +1,53 @@
+import { SESSION_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { getFilteredFilters } from "../../../lib/store";
+import { SessionsSummary } from "../endpoints";
+import { useAnalyticsQuery } from "../useAnalyticsQuery";
+
+/**
+ * The Sessions page's numbers for one period: the stat band's figures, how
+ * many sessions each saved view holds once the ranges are applied, and the
+ * same counts per day. It takes the filters the sessions list takes, so its
+ * totals are totals of that list.
+ *
+ * `periodTime: "previous"` asks for the comparison period and stops running
+ * when the comparison is turned off.
+ */
+export function useGetSessionsSummary({
+ periodTime,
+ minPageviews,
+ maxPageviews,
+ minEvents,
+ maxEvents,
+ minDuration,
+ maxDuration,
+}: {
+ periodTime?: "current" | "previous";
+ minPageviews?: number;
+ maxPageviews?: number;
+ minEvents?: number;
+ maxEvents?: number;
+ minDuration?: number;
+ maxDuration?: number;
+} = {}) {
+ const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
+
+ return useAnalyticsQuery<SessionsSummary>({
+ key: "sessions-summary",
+ path: "sessions/summary",
+ periodTime,
+ // customFilters fall back to the store filters when empty; disable filters
+ // entirely instead so an empty page-filter set stays unfiltered.
+ useFilters: filteredFilters.length > 0,
+ customFilters: filteredFilters,
+ params: {
+ min_pageviews: minPageviews,
+ max_pageviews: maxPageviews,
+ min_events: minEvents,
+ max_events: maxEvents,
+ min_duration: minDuration,
+ max_duration: maxDuration,
+ },
+ // As long-lived as the sessions list, so the totals stay those of the rows on screen.
+ staleTime: Infinity,
+ });
+}
diff --git a/client/src/api/analytics/hooks/useGetUserSessions.ts b/client/src/api/analytics/hooks/useGetUserSessions.ts
index 8d85d63fa..8efdb2820 100644
--- a/client/src/api/analytics/hooks/useGetUserSessions.ts
+++ b/client/src/api/analytics/hooks/useGetUserSessions.ts
@@ -1,7 +1,13 @@
import { Time } from "../../../components/DateSelector/types";
import { SESSION_PAGE_FILTERS, USER_DETAIL_PAGE_FILTERS } from "../../../lib/filterGroups";
import { getFilteredFilters, useStore } from "../../../lib/store";
-import { GetSessionsResponse, SessionPageviewsAndEvents, UserSessionCountResponse } from "../endpoints";
+import {
+ GetSessionsResponse,
+ SessionPageviewsAndEvents,
+ SessionSort,
+ SessionView,
+ UserSessionCountResponse,
+} from "../endpoints";
import { useAnalyticsInfiniteQuery, useAnalyticsQuery } from "../useAnalyticsQuery";
export function useGetSessions({
@@ -11,8 +17,15 @@ export function useGetSessions({
identifiedOnly = false,
timeOverride,
minPageviews,
+ maxPageviews,
minEvents,
+ maxEvents,
minDuration,
+ maxDuration,
+ view,
+ sortBy,
+ sortOrder,
+ includeGoals,
}: {
userId?: string;
page?: number;
@@ -20,8 +33,16 @@ export function useGetSessions({
identifiedOnly?: boolean;
timeOverride?: Time;
minPageviews?: number;
+ maxPageviews?: number;
minEvents?: number;
+ maxEvents?: number;
minDuration?: number;
+ maxDuration?: number;
+ view?: SessionView;
+ sortBy?: SessionSort;
+ sortOrder?: "asc" | "desc";
+ // Ask for each session's completed goals (`converted_goals`).
+ includeGoals?: boolean;
}) {
const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
@@ -39,8 +60,15 @@ export function useGetSessions({
user_id: userId,
identified_only: identifiedOnly,
min_pageviews: minPageviews,
+ max_pageviews: maxPageviews,
min_events: minEvents,
+ max_events: maxEvents,
min_duration: minDuration,
+ max_duration: maxDuration,
+ view,
+ sort_by: sortBy,
+ sort_order: sortOrder,
+ include_goals: includeGoals || undefined,
},
staleTime: Infinity,
});
diff --git a/client/src/api/analytics/hooks/useGetUserTraits.ts b/client/src/api/analytics/hooks/useGetUserTraits.ts
index 8362e19d5..0bc881fa1 100644
--- a/client/src/api/analytics/hooks/useGetUserTraits.ts
+++ b/client/src/api/analytics/hooks/useGetUserTraits.ts
@@ -1,10 +1,10 @@
-import { TraitKeysResponse, TraitValuesResponse, TraitValueUsersResponse } from "../endpoints";
-import { useAnalyticsInfiniteQuery, useAnalyticsQuery } from "../useAnalyticsQuery";
+import { TraitBreakdown, TraitKeysResponse } from "../endpoints";
+import { useAnalyticsQuery } from "../useAnalyticsQuery";
+import { narrowingParams, UsersNarrowing, useUserPageFilters } from "./useGetUsers";
-const VALUES_LIMIT = 1000;
-const USERS_LIMIT = 250;
+type PeriodTime = "current" | "previous";
-// Trait keys and values describe the whole site, not the selected period.
+// Trait keys describe the whole site, not the selected period.
const TRAIT_CONTEXT = { useTime: false, useFilters: false } as const;
export function useGetUserTraitKeys() {
@@ -18,34 +18,30 @@ export function useGetUserTraitKeys() {
});
}
-export function useGetUserTraitValues(key: string | null) {
- return useAnalyticsInfiniteQuery<TraitValuesResponse>({
- key: ["user-trait-values", key],
- path: "user-traits/values",
- unwrap: false,
- ...TRAIT_CONTEXT,
- params: { key, limit: VALUES_LIMIT },
- staleTime: 0,
- initialPageParam: 0,
- pageParams: offset => ({ offset }),
- getNextPageParam: (lastPage, allPages) =>
- lastPage.hasMore ? allPages.reduce((total, page) => total + page.values.length, 0) : undefined,
- enabled: !!key,
- });
-}
-
-export function useGetUserTraitValueUsers(key: string | null, value: string | null) {
- return useAnalyticsInfiniteQuery<TraitValueUsersResponse>({
- key: ["user-trait-value-users", key, value],
- path: "user-traits/users",
- unwrap: false,
- ...TRAIT_CONTEXT,
- params: { key, value, limit: USERS_LIMIT },
+/**
+ * The period's users grouped by one trait. Takes the same narrowing as the
+ * users list (never a trait group of its own), so a group's count matches the
+ * rows that open under it.
+ */
+export function useGetUserTraitBreakdown({
+ traitKey,
+ periodTime,
+ narrowing,
+ enabled = true,
+}: {
+ traitKey: string | null;
+ periodTime?: PeriodTime;
+ narrowing: Omit<UsersNarrowing, "traitGroup">;
+ enabled?: boolean;
+}) {
+ return useAnalyticsQuery<TraitBreakdown>({
+ // Under the "users" prefix so the mutations that invalidate the list refresh this too.
+ key: ["users", "trait-breakdown"],
+ path: "user-traits/breakdown",
+ periodTime,
+ ...useUserPageFilters(),
+ params: { key: traitKey ?? undefined, ...narrowingParams(narrowing) },
staleTime: 0,
- initialPageParam: 0,
- pageParams: offset => ({ offset }),
- getNextPageParam: (lastPage, allPages) =>
- lastPage.hasMore ? allPages.reduce((total, page) => total + page.users.length, 0) : undefined,
- enabled: !!key && value !== null,
+ enabled: enabled && !!traitKey,
});
}
diff --git a/client/src/api/analytics/hooks/useGetUsers.test.ts b/client/src/api/analytics/hooks/useGetUsers.test.ts
new file mode 100644
index 000000000..28d10471f
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetUsers.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+import { narrowingParams } from "./useGetUsers";
+
+const sent = (params: Record<string, unknown>) =>
+ Object.fromEntries(Object.entries(params).filter(([, value]) => value !== undefined));
+
+describe("narrowingParams", () => {
+ it("sends nothing for an unnarrowed list", () => {
+ expect(sent(narrowingParams({}))).toEqual({});
+ expect(sent(narrowingParams({ identifiedOnly: false, newOnly: false, search: "", searchField: "name" }))).toEqual(
+ {}
+ );
+ });
+
+ it("names the quick filters as the API does", () => {
+ expect(sent(narrowingParams({ identifiedOnly: true, newOnly: true, minSessions: 4 }))).toEqual({
+ identified_only: true,
+ new_only: true,
+ min_sessions: 4,
+ });
+ });
+
+ it("sends the search field only with a search", () => {
+ expect(sent(narrowingParams({ search: "mara", searchField: "email" }))).toEqual({
+ search: "mara",
+ search_field: "email",
+ });
+ });
+
+ it("asks for a trait value, including the empty one", () => {
+ expect(sent(narrowingParams({ traitGroup: { key: "plan", value: "Pro" } }))).toEqual({
+ trait_key: "plan",
+ trait_value: "Pro",
+ });
+ expect(sent(narrowingParams({ traitGroup: { key: "plan", value: "" } }))).toEqual({
+ trait_key: "plan",
+ trait_value: "",
+ });
+ });
+
+ it("asks for the users without the trait", () => {
+ expect(sent(narrowingParams({ traitGroup: { key: "plan", missing: true } }))).toEqual({
+ trait_key: "plan",
+ trait_missing: true,
+ });
+ });
+});
diff --git a/client/src/api/analytics/hooks/useGetUsers.ts b/client/src/api/analytics/hooks/useGetUsers.ts
index f948b4ef2..a7a3e1206 100644
--- a/client/src/api/analytics/hooks/useGetUsers.ts
+++ b/client/src/api/analytics/hooks/useGetUsers.ts
@@ -1,44 +1,112 @@
-import { Filter } from "@rybbit/shared";
import { USER_PAGE_FILTERS } from "../../../lib/filterGroups";
import { getFilteredFilters } from "../../../lib/store";
-import { UsersListResponse } from "../endpoints";
-import { useAnalyticsQuery } from "../useAnalyticsQuery";
+import { UsersListResponse, UsersSummary } from "../endpoints";
+import { nextPageByTotalCount, useAnalyticsInfiniteQuery, useAnalyticsQuery } from "../useAnalyticsQuery";
-export interface GetUsersOptions {
+type PeriodTime = "current" | "previous";
+
+/** One group of a trait breakdown: a value of the trait, or the users with no value for it. */
+export type TraitGroupSelector = { key: string; value: string } | { key: string; missing: true };
+
+/** Which users the list shows, on top of the period and the page's filters. */
+export interface UsersNarrowing {
+ identifiedOnly?: boolean;
+ /** Only users with no visit in the lookback before the period. */
+ newOnly?: boolean;
+ /** Only users with at least this many sessions in the period. */
+ minSessions?: number;
+ search?: string;
+ searchField?: string;
+ traitGroup?: TraitGroupSelector;
+}
+
+export interface GetUsersOptions extends UsersNarrowing {
page: number;
pageSize: number;
sortBy: string;
sortOrder: string;
- filters?: Filter[];
- identifiedOnly?: boolean;
- search?: string;
- searchField?: string;
+ enabled?: boolean;
}
-export function useGetUsers(options: GetUsersOptions) {
- const { page, pageSize, sortBy, sortOrder, identifiedOnly = false, search, searchField } = options;
+/**
+ * The filter context every Users-page read shares. `customFilters` falls back
+ * to the store's filters when empty, so filters are switched off instead when
+ * none of the store's apply to this page.
+ */
+export function useUserPageFilters() {
const filteredFilters = getFilteredFilters(USER_PAGE_FILTERS);
+ return { useFilters: filteredFilters.length > 0, customFilters: filteredFilters };
+}
+
+/** The wire params for a narrowing; shared by the list and the trait breakdown so they cannot drift. */
+export function narrowingParams(narrowing: UsersNarrowing): Record<string, unknown> {
+ const { identifiedOnly, newOnly, minSessions, search, searchField, traitGroup } = narrowing;
+ return {
+ identified_only: identifiedOnly || undefined,
+ new_only: newOnly || undefined,
+ min_sessions: minSessions,
+ search: search || undefined,
+ search_field: search ? searchField || undefined : undefined,
+ trait_key: traitGroup?.key,
+ trait_value: traitGroup && "value" in traitGroup ? traitGroup.value : undefined,
+ trait_missing: traitGroup && "missing" in traitGroup ? true : undefined,
+ };
+}
+
+export function useGetUsers(options: GetUsersOptions) {
+ const { page, pageSize, sortBy, sortOrder, enabled, ...narrowing } = options;
return useAnalyticsQuery<UsersListResponse>({
key: "users",
path: "users",
unwrap: false,
- // customFilters fall back to the store filters when empty; disable filters
- // entirely instead so an empty page-filter set stays unfiltered.
- useFilters: filteredFilters.length > 0,
- customFilters: filteredFilters,
+ ...useUserPageFilters(),
params: {
page,
page_size: pageSize,
sort_by: sortBy,
sort_order: sortOrder,
- identified_only: identifiedOnly,
- search: search || undefined,
- search_field: searchField || undefined,
+ ...narrowingParams(narrowing),
},
// Use default staleTime (0) for real-time data
staleTime: 0,
+ enabled,
// Enable refetching when the window regains focus
props: { refetchOnWindowFocus: true },
});
}
+
+/** The same list, loaded a page at a time: the rows under one trait group. */
+export function useGetUsersInfinite(options: Omit<GetUsersOptions, "page">) {
+ const { pageSize, sortBy, sortOrder, enabled, ...narrowing } = options;
+
+ return useAnalyticsInfiniteQuery<UsersListResponse>({
+ key: ["users", "group"],
+ path: "users",
+ unwrap: false,
+ ...useUserPageFilters(),
+ params: {
+ page_size: pageSize,
+ sort_by: sortBy,
+ sort_order: sortOrder,
+ ...narrowingParams(narrowing),
+ },
+ initialPageParam: 1,
+ pageParams: page => ({ page }),
+ getNextPageParam: nextPageByTotalCount,
+ staleTime: 0,
+ enabled,
+ });
+}
+
+/** The stat band's figures for the selected period, or for the one it is compared with. */
+export function useGetUsersSummary({ periodTime, enabled }: { periodTime?: PeriodTime; enabled?: boolean } = {}) {
+ return useAnalyticsQuery<UsersSummary>({
+ // Under the "users" prefix so the mutations that invalidate the list refresh this too.
+ key: ["users", "summary"],
+ path: "users/summary",
+ periodTime,
+ ...useUserPageFilters(),
+ enabled,
+ });
+}
diff --git a/client/src/api/analytics/hooks/useUserProfile.ts b/client/src/api/analytics/hooks/useUserProfile.ts
new file mode 100644
index 000000000..97747af29
--- /dev/null
+++ b/client/src/api/analytics/hooks/useUserProfile.ts
@@ -0,0 +1,91 @@
+import { Query } from "@tanstack/react-query";
+import { Time } from "../../../components/DateSelector/types";
+import { USER_DETAIL_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { getFilteredFilters } from "../../../lib/store";
+import { UserGoal, UserRepeatedError, UserSegments, UserSessionGoals, UserSummary } from "../endpoints/userProfile";
+import { useAnalyticsQuery } from "../useAnalyticsQuery";
+
+// Every profile panel applies the page's own filter set, the way useUserInfo
+// does: an empty set must mean "no filters", not "the store's filters".
+const profileFilters = () => {
+ const filters = getFilteredFilters(USER_DETAIL_PAGE_FILTERS);
+ return { useFilters: filters.length > 0, customFilters: filters };
+};
+
+const userPath = (userId: string, panel: string) => `users/${encodeURIComponent(userId)}/${panel}`;
+
+/**
+ * Placeholder policy for queries keyed `[name, userId, …]`: keep the previous
+ * result on screen while a date or filter change refetches, but never carry
+ * one user's numbers over to the next user. The shared same-site policy would,
+ * and stepping between profiles makes that visible.
+ */
+export const sameUserPlaceholder =
+ <TData>(userId: string) =>
+ (previousData: TData | undefined, previousQuery: Query<TData, Error> | undefined) =>
+ previousQuery?.queryKey?.[1] === userId ? previousData : undefined;
+
+/**
+ * The stat band's numbers for the selected period, or for the comparison
+ * period. The comparison query is disabled when the comparison is off, so its
+ * data is undefined and the deltas drop out.
+ */
+export function useUserSummary(userId: string, periodTime: "current" | "previous" = "current") {
+ return useAnalyticsQuery<UserSummary>({
+ key: ["user-summary", userId, periodTime],
+ path: userPath(userId, "summary"),
+ periodTime,
+ ...profileFilters(),
+ enabled: !!userId,
+ props: { placeholderData: sameUserPlaceholder<UserSummary>(userId) },
+ });
+}
+
+export function useUserGoals(userId: string) {
+ return useAnalyticsQuery<UserGoal[]>({
+ key: ["user-goals", userId],
+ path: userPath(userId, "goals"),
+ ...profileFilters(),
+ enabled: !!userId,
+ props: { placeholderData: sameUserPlaceholder<UserGoal[]>(userId) },
+ });
+}
+
+/**
+ * Which goals each listed session completed. `time` must be the window the
+ * session list itself was fetched with (the selected period, or the one day
+ * picked on the activity calendar).
+ */
+export function useUserSessionGoals(userId: string, sessionIds: string[], time?: Time) {
+ return useAnalyticsQuery<UserSessionGoals[]>({
+ key: ["user-session-goals", userId],
+ path: userPath(userId, "session-goals"),
+ overrideTime: time,
+ ...profileFilters(),
+ params: { session_ids: sessionIds },
+ // Markers belong to the exact sessions asked about: no stand-in from another page.
+ placeholder: false,
+ enabled: !!userId && sessionIds.length > 0,
+ });
+}
+
+export function useUserSegments(userId: string) {
+ return useAnalyticsQuery<UserSegments>({
+ key: ["user-segments", userId],
+ path: userPath(userId, "segments"),
+ ...profileFilters(),
+ enabled: !!userId,
+ props: { placeholderData: sameUserPlaceholder<UserSegments>(userId) },
+ });
+}
+
+export function useUserRepeatedError(userId: string) {
+ return useAnalyticsQuery<UserRepeatedError | null>({
+ key: ["user-repeated-error", userId],
+ path: userPath(userId, "repeated-error"),
+ ...profileFilters(),
+ // An insight about one period must not linger over the next.
+ placeholder: false,
+ enabled: !!userId,
+ });
+}
diff --git a/client/src/api/analytics/hooks/userGetInfo.ts b/client/src/api/analytics/hooks/userGetInfo.ts
index 9b0e6988a..790e0700b 100644
--- a/client/src/api/analytics/hooks/userGetInfo.ts
+++ b/client/src/api/analytics/hooks/userGetInfo.ts
@@ -1,9 +1,17 @@
+import { Time } from "../../../components/DateSelector/types";
import { USER_DETAIL_PAGE_FILTERS } from "../../../lib/filterGroups";
import { getFilteredFilters } from "../../../lib/store";
import { UserInfo } from "../endpoints";
import { useAnalyticsQuery } from "../useAnalyticsQuery";
+import { sameUserPlaceholder } from "./useUserProfile";
-export function useUserInfo(siteId: number, userId: string) {
+export function useUserInfo(
+ siteId: number,
+ userId: string,
+ // `time` asks about a specific window instead of the selected period; the
+ // profile uses it to read the user's first day for first-touch attribution.
+ options: { time?: Time; enabled?: boolean } = {}
+) {
const filteredFilters = getFilteredFilters(USER_DETAIL_PAGE_FILTERS);
return useAnalyticsQuery<UserInfo>({
@@ -11,10 +19,17 @@ export function useUserInfo(siteId: number, userId: string) {
key: ["user-info", userId],
path: `users/${encodeURIComponent(userId)}`,
site: siteId,
+ overrideTime: options.time,
// customFilters fall back to the store filters when empty; disable filters
// entirely instead so an empty page-filter set stays unfiltered.
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- enabled: !!siteId && !!userId,
+ enabled: !!siteId && !!userId && (options.enabled ?? true),
+ // Stepping to another user must not show the previous user's profile while
+ // the new one loads; a date or filter change keeps the current one up. A
+ // pinned window gets no stand-in at all: the selected period's answer is
+ // not an approximation of another window's.
+ placeholder: false,
+ props: options.time ? undefined : { placeholderData: sameUserPlaceholder<UserInfo>(userId) },
});
}
diff --git a/client/src/app/[site]/api-playground/utils/endpointConfig.ts b/client/src/app/[site]/api-playground/utils/endpointConfig.ts
index 2cbcde38a..3f7b31b7b 100644
--- a/client/src/app/[site]/api-playground/utils/endpointConfig.ts
+++ b/client/src/app/[site]/api-playground/utils/endpointConfig.ts
@@ -825,7 +825,7 @@ export const endpointCategories: EndpointCategory[] = [
path: "/sites/:site/retention",
name: "Get Retention",
description: "Returns cohort-based retention analysis",
- hasCommonParams: false,
+ hasCommonParams: true,
specificParams: ["mode", "range"],
parameterMetadata: {
mode: { label: "Mode", type: "select", options: ["day", "week"] },
diff --git a/client/src/app/[site]/components/SubHeader/Filters/SegmentDialog.tsx b/client/src/app/[site]/components/SubHeader/Filters/SegmentDialog.tsx
index 23c357755..e3c55f0d4 100644
--- a/client/src/app/[site]/components/SubHeader/Filters/SegmentDialog.tsx
+++ b/client/src/app/[site]/components/SubHeader/Filters/SegmentDialog.tsx
@@ -81,6 +81,12 @@ export interface SegmentDialogProps {
/** Starting filters for a new segment, e.g. the dashboard's current chips. */
initialFilters?: Filter[];
availableFilters?: FilterParameter[];
+ /**
+ * Whether a newly created segment is applied to the dashboard. Defaults to
+ * true; a pivot saves the people behind one row without narrowing the page
+ * to them, so it passes false.
+ */
+ applyOnCreate?: boolean;
}
/**
@@ -108,7 +114,14 @@ export function SegmentDialog(props: SegmentDialogProps) {
);
}
-function SegmentForm({ onOpenChange, siteId, segment, initialFilters, availableFilters }: SegmentDialogProps) {
+function SegmentForm({
+ onOpenChange,
+ siteId,
+ segment,
+ initialFilters,
+ availableFilters,
+ applyOnCreate = true,
+}: SegmentDialogProps) {
const t = useExtracted();
const { data: site } = useGetSite(siteId);
const { data: activeOrganization } = authClient.useActiveOrganization();
@@ -189,7 +202,7 @@ function SegmentForm({ onOpenChange, siteId, segment, initialFilters, availableF
toast.success(t("Saved segment “{name}”", { name: updated.name }));
} else {
const created = await createSegment({ siteId, body });
- applySegment(created, appliedSegment?.filters);
+ if (applyOnCreate) applySegment(created, appliedSegment?.filters);
toast.success(t("Saved segment “{name}”", { name: created.name }));
}
onOpenChange(false);
diff --git a/client/src/app/[site]/events/components/ChartLegend.test.tsx b/client/src/app/[site]/events/components/ChartLegend.test.tsx
new file mode 100644
index 000000000..7e671f104
--- /dev/null
+++ b/client/src/app/[site]/events/components/ChartLegend.test.tsx
@@ -0,0 +1,82 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { percentDelta } from "@/lib/delta";
+import { ChartLegend, LegendRow } from "./ChartLegend";
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => (message: string) => message,
+}));
+
+const rows: LegendRow[] = [
+ { id: "custom_event", label: "Custom events", color: "red", total: 38620, delta: percentDelta(38620, 33120) },
+ { id: "error", label: "Errors", color: "grey", total: 1284, delta: percentDelta(1284, 1400), upIsGood: false },
+ { id: "pageview", label: "Pageviews", color: "blue", total: 212940, delta: percentDelta(212940, 187447) },
+];
+
+const renderLegend = (props: Partial<Parameters<typeof ChartLegend>[0]> = {}) => {
+ const onToggle = vi.fn();
+ render(
+ <ChartLegend
+ rows={rows}
+ hidden={new Set(["pageview"])}
+ onToggle={onToggle}
+ nameLabel="Type"
+ showDelta={true}
+ {...props}
+ />
+ );
+ return onToggle;
+};
+
+describe("ChartLegend", () => {
+ afterEach(cleanup);
+
+ it("draws each series as a switch that says whether its line is shown", () => {
+ renderLegend();
+
+ expect(screen.getByRole("switch", { name: /Custom events/ }).getAttribute("aria-checked")).toBe("true");
+ expect(screen.getByRole("switch", { name: /Pageviews/ }).getAttribute("aria-checked")).toBe("false");
+ });
+
+ it("toggles the series that was clicked", () => {
+ const onToggle = renderLegend();
+
+ fireEvent.click(screen.getByRole("switch", { name: /Pageviews/ }));
+
+ expect(onToggle).toHaveBeenCalledWith("pageview");
+ });
+
+ it("shows the exact total on hover and the change against the comparison period", () => {
+ renderLegend();
+
+ expect(screen.getByTitle((38620).toLocaleString())).toBeTruthy();
+ expect(screen.getByText("+16.6%")).toBeTruthy();
+ expect(screen.getByText("-8.3%")).toBeTruthy();
+ });
+
+ it("colours a fall in errors as good news", () => {
+ renderLegend();
+
+ expect(screen.getByText("-8.3%").parentElement?.className).toContain("emerald");
+ expect(screen.getByText("+16.6%").parentElement?.className).toContain("emerald");
+ });
+
+ it("drops the change column when the comparison is off", () => {
+ renderLegend({ showDelta: false });
+
+ expect(screen.queryByText("Change")).toBeNull();
+ expect(screen.queryByText("+16.6%")).toBeNull();
+ });
+
+ it("shows placeholders instead of rows while loading", () => {
+ renderLegend({ isLoading: true });
+
+ expect(screen.queryByRole("switch")).toBeNull();
+ });
+
+ it("prints the note under the rows", () => {
+ renderLegend({ note: "Pageviews are hidden by default." });
+
+ expect(screen.getByText("Pageviews are hidden by default.")).toBeTruthy();
+ });
+});
diff --git a/client/src/app/[site]/events/components/ChartLegend.tsx b/client/src/app/[site]/events/components/ChartLegend.tsx
index b1349b854..9f560e957 100644
--- a/client/src/app/[site]/events/components/ChartLegend.tsx
+++ b/client/src/app/[site]/events/components/ChartLegend.tsx
@@ -1,38 +1,128 @@
"use client";
-export interface LegendItem {
+import { useExtracted } from "next-intl";
+import { ReactNode } from "react";
+import { Delta } from "@/components/site/Delta";
+import { Skeleton } from "@/components/ui/skeleton";
+import { DeltaValue } from "@/lib/delta";
+import { cn, formatter } from "@/lib/utils";
+
+export interface LegendRow {
id: string;
+ label: string;
color: string;
+ /** A 14px mark between the dot and the label. */
+ icon?: ReactNode;
+ /** The series' total over the period. */
+ total: number;
+ /** Change against the comparison period; null draws nothing. */
+ delta?: DeltaValue | null;
+ upIsGood?: boolean;
}
interface ChartLegendProps {
- items: LegendItem[];
- hiddenItems: Set<string>;
+ rows: LegendRow[];
+ hidden: ReadonlySet<string>;
onToggle: (id: string) => void;
+ /** Heading of the name column: "Type", "Event". */
+ nameLabel: string;
+ /** Draws the change column. False when the comparison is turned off. */
+ showDelta: boolean;
+ /** Reserves the icon column. */
+ hasIcons?: boolean;
+ isLoading?: boolean;
+ note?: ReactNode;
}
-export function ChartLegend({ items, hiddenItems, onToggle }: ChartLegendProps) {
- if (items.length === 0) return null;
+/**
+ * The chart's legend as a small table: every series with its total for the
+ * period and its change, and a click to show or hide its line.
+ */
+export function ChartLegend({
+ rows,
+ hidden,
+ onToggle,
+ nameLabel,
+ showDelta,
+ hasIcons = false,
+ isLoading = false,
+ note,
+}: ChartLegendProps) {
+ const t = useExtracted();
+ const columns = cn(
+ "grid items-center gap-2",
+ hasIcons
+ ? showDelta
+ ? "grid-cols-[8px_14px_minmax(0,1fr)_44px_60px]"
+ : "grid-cols-[8px_14px_minmax(0,1fr)_44px]"
+ : showDelta
+ ? "grid-cols-[8px_minmax(0,1fr)_44px_60px]"
+ : "grid-cols-[8px_minmax(0,1fr)_44px]"
+ );
return (
- <div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 px-2 md:px-0 text-xs text-neutral-500 dark:text-neutral-400">
- {items.map(item => {
- const isHidden = hiddenItems.has(item.id);
- return (
- <button
- key={item.id}
- type="button"
- onClick={() => onToggle(item.id)}
- className={`flex items-center gap-2 max-w-[200px] text-left transition-opacity cursor-pointer ${isHidden ? "opacity-40" : "opacity-100"
- }`}
- >
- <span className="h-2 w-2 rounded-full" style={{ backgroundColor: item.color }} />
- <span className={`truncate ${isHidden ? "line-through" : ""}`} title={item.id}>
- {item.id}
- </span>
- </button>
- );
- })}
+ <div>
+ <div className={cn(columns, "h-8 px-2 text-xs font-medium text-neutral-500 dark:text-neutral-400")}>
+ <span />
+ {hasIcons && <span />}
+ <span>{nameLabel}</span>
+ <span className="text-right">{t("Events")}</span>
+ {showDelta && <span className="text-right">{t("Change")}</span>}
+ </div>
+
+ {isLoading
+ ? Array.from({ length: 5 }).map((_, index) => (
+ <div key={index} className="flex h-7 items-center px-2">
+ <Skeleton className="h-3 w-full rounded" />
+ </div>
+ ))
+ : rows.map(row => {
+ const isHidden = hidden.has(row.id);
+ return (
+ <button
+ key={row.id}
+ type="button"
+ role="switch"
+ aria-checked={!isHidden}
+ onClick={() => onToggle(row.id)}
+ className={cn(
+ columns,
+ "h-7 w-full cursor-pointer rounded-md px-2 text-left text-xs transition-colors hover:bg-neutral-100 dark:hover:bg-neutral-800/60",
+ isHidden && "opacity-50"
+ )}
+ >
+ {isHidden ? (
+ <span className="h-2 w-2 rounded-full border border-neutral-400 dark:border-neutral-500" />
+ ) : (
+ <span className="h-2 w-2 rounded-full" style={{ backgroundColor: row.color }} />
+ )}
+ {hasIcons && <span className="flex items-center">{row.icon}</span>}
+ <span
+ className={cn("truncate text-neutral-700 dark:text-neutral-200", isHidden && "line-through")}
+ title={row.label}
+ >
+ {row.label}
+ </span>
+ <span
+ className="text-right font-medium tabular-nums text-neutral-900 dark:text-neutral-50"
+ title={row.total.toLocaleString()}
+ >
+ {formatter(row.total)}
+ </span>
+ {showDelta && (
+ <span className="flex justify-end">
+ <Delta value={row.delta} upIsGood={row.upIsGood} />
+ </span>
+ )}
+ </button>
+ );
+ })}
+
+ {note && (
+ <div className="mt-1 border-t border-neutral-100 px-2 pt-2 text-xs text-neutral-500 dark:border-neutral-850 dark:text-neutral-400">
+ {note}
+ </div>
+ )}
</div>
);
}
diff --git a/client/src/app/[site]/events/components/ChartPanel.tsx b/client/src/app/[site]/events/components/ChartPanel.tsx
new file mode 100644
index 000000000..b5c954d87
--- /dev/null
+++ b/client/src/app/[site]/events/components/ChartPanel.tsx
@@ -0,0 +1,78 @@
+"use client";
+
+import { TimeBucket } from "@rybbit/shared";
+import { useExtracted } from "next-intl";
+import { ReactNode } from "react";
+import { Skeleton } from "@/components/ui/skeleton";
+import { useStore, useTimezone } from "@/lib/store";
+import { getAbsoluteBounds } from "@/lib/time";
+
+interface ChartPanelProps {
+ title: string;
+ isLoading: boolean;
+ /** Shown in place of the chart: nothing in the period, or every series hidden. */
+ placeholder?: { title: string; description?: string } | null;
+ chart: ReactNode;
+ legend: ReactNode;
+}
+
+/** "Sep 1 – Sep 30", or one date for a single day. Null for all time. */
+function useRangeLabel(): string | null {
+ const time = useStore(state => state.time);
+ const zone = useTimezone();
+ const bounds = getAbsoluteBounds(time, zone);
+ if (!bounds) return null;
+
+ const start = bounds.start.toFormat("MMM d");
+ const end = bounds.end.minus({ minutes: 1 }).toFormat("MMM d");
+ return start === end ? start : `${start} – ${end}`;
+}
+
+/** The chart card's two halves: the plot under its title, and the legend table beside it. */
+export function ChartPanel({ title, isLoading, placeholder, chart, legend }: ChartPanelProps) {
+ const t = useExtracted();
+ const bucket = useStore(state => state.bucket);
+ const range = useRangeLabel();
+
+ const perBucket: Record<TimeBucket, string> = {
+ minute: t("per minute"),
+ five_minutes: t("per 5 minutes"),
+ ten_minutes: t("per 10 minutes"),
+ fifteen_minutes: t("per 15 minutes"),
+ hour: t("per hour"),
+ day: t("per day"),
+ week: t("per week"),
+ month: t("per month"),
+ year: t("per year"),
+ };
+
+ return (
+ <div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_300px]">
+ <div className="min-w-0 p-2 pb-3 md:p-4 md:pb-3">
+ <div className="mb-1 flex flex-wrap items-baseline gap-x-2 gap-y-1 px-2 pt-2 md:px-0 md:pt-0">
+ <h2 className="text-base font-semibold leading-none tracking-tight">{title}</h2>
+ <span className="text-xs text-neutral-500 dark:text-neutral-400">
+ {range ? `${perBucket[bucket]}, ${range}` : perBucket[bucket]}
+ </span>
+ </div>
+ <div className="h-[260px] w-full">
+ {isLoading ? (
+ <div className="flex h-full items-end pb-7 pl-10 pr-5 pt-3">
+ <Skeleton className="h-full w-full rounded-md" />
+ </div>
+ ) : placeholder ? (
+ <div className="flex h-full items-center justify-center">
+ <div className="text-center text-neutral-500 dark:text-neutral-400">
+ <p className="text-sm font-medium">{placeholder.title}</p>
+ {placeholder.description && <p className="text-xs">{placeholder.description}</p>}
+ </div>
+ </div>
+ ) : (
+ chart
+ )}
+ </div>
+ </div>
+ <div className="border-t border-neutral-100 p-2 dark:border-neutral-850 lg:border-l lg:border-t-0">{legend}</div>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/events/components/CustomEventsChart.tsx b/client/src/app/[site]/events/components/CustomEventsChart.tsx
index 9fcb8f14f..fd96f599d 100644
--- a/client/src/app/[site]/events/components/CustomEventsChart.tsx
+++ b/client/src/app/[site]/events/components/CustomEventsChart.tsx
@@ -1,56 +1,32 @@
"use client";
-import { ResponsiveLine, SliceTooltipProps } from "@nivo/line";
-import { useWindowSize } from "@uidotdev/usehooks";
import { DateTime } from "luxon";
-import { useEffect, useMemo, useState } from "react";
-
import { useExtracted } from "next-intl";
-import { useGetEventBucketed } from "@/api/analytics/hooks/events/useGetEventBucketed";
-import { ChartTooltip } from "@/components/charts/ChartTooltip";
-import { CardLoader } from "@/components/ui/card";
-import { ChartLegend } from "./ChartLegend";
-import { formatChartDateTime, hour12, userLocale } from "@/lib/dateTimeUtils";
-import { useNivoTheme } from "@/lib/nivo";
-import { getTimezone, useStore } from "@/lib/store";
-import { formatter } from "@/lib/utils";
-
-const COLOR_PALETTE = [
- "hsl(var(--dataviz))",
- "hsl(var(--green-400))",
- "hsl(var(--amber-400))",
- "hsl(var(--red-400))",
- "hsl(var(--teal-400))",
- "hsl(var(--cyan-400))",
- "hsl(var(--orange-400))",
- "hsl(var(--blue-400))",
- "hsl(var(--indigo-400))",
- "hsl(var(--violet-400))",
-];
-
-type EventPoint = {
- x: string;
- y: number;
- currentTime: DateTime;
-};
-
-type EventSeries = {
- id: string;
- color: string;
- data: EventPoint[];
-};
+import { useState } from "react";
+import { useGetEventBucketed } from "@/api/analytics/hooks/events/useGetEventBucketed";
+import { useGetEventNames } from "@/api/analytics/hooks/events/useGetEventNames";
+import { percentDelta } from "@/lib/delta";
+import { getTimezone, useComparisonEnabled } from "@/lib/store";
+import { seriesColor } from "../utils/eventTypes";
+import { ChartLegend, LegendRow } from "./ChartLegend";
+import { ChartPanel } from "./ChartPanel";
+import { ChartSeries, EventSeriesChart } from "./EventSeriesChart";
+
+/** The most-fired custom events, one line each. Remount (key) to reset the hidden lines when the limit changes. */
export function CustomEventsChart({ eventLimit }: { eventLimit: number }) {
const t = useExtracted();
- const { bucket } = useStore();
- const { data, isLoading } = useGetEventBucketed({ limit: eventLimit });
- const { width } = useWindowSize();
- const nivoTheme = useNivoTheme();
const timezone = getTimezone();
- const [hiddenEventNames, setHiddenEventNames] = useState<Set<string>>(new Set());
-
- const toggleEventVisibility = (eventName: string) => {
- setHiddenEventNames(prev => {
+ const comparisonEnabled = useComparisonEnabled();
+ // Pending, not loading: the query waits for the site, and "no events" is not true yet.
+ const { data, isPending: isLoading, isError } = useGetEventBucketed({ limit: eventLimit });
+ const { data: previousNames } = useGetEventNames({ periodTime: "previous" });
+ // A disabled query keeps its last result, so the switch is read here.
+ const previous = comparisonEnabled ? previousNames : undefined;
+ const [hidden, setHidden] = useState<ReadonlySet<string>>(new Set());
+
+ const toggle = (eventName: string) => {
+ setHidden(prev => {
const next = new Set(prev);
if (next.has(eventName)) {
next.delete(eventName);
@@ -61,175 +37,80 @@ export function CustomEventsChart({ eventLimit }: { eventLimit: number }) {
});
};
- useEffect(() => {
- setHiddenEventNames(new Set());
- }, [eventLimit]);
-
- const { series, legendItems, maxValue, totalPoints } = useMemo(() => {
- if (!data || data.length === 0) {
- return { series: [] as EventSeries[], legendItems: [], maxValue: 1, totalPoints: 0 };
- }
-
- const timeLookup = new Map<string, DateTime>();
- const countsByEvent = new Map<string, Map<string, number>>();
- const totalsByEvent = new Map<string, number>();
-
- data.forEach(item => {
- const timestamp = DateTime.fromSQL(item.time, { zone: timezone }).toUTC();
- if (!timestamp.isValid || timestamp > DateTime.now().toUTC()) {
- return;
- }
-
- const timeKey = timestamp.toFormat("yyyy-MM-dd HH:mm:ss");
- timeLookup.set(timeKey, timestamp);
-
- if (!countsByEvent.has(item.event_name)) {
- countsByEvent.set(item.event_name, new Map());
+ const now = DateTime.now().toUTC();
+ const times = new Map<string, DateTime>();
+ const countsByEvent = new Map<string, Map<string, number>>();
+ const totalsByEvent = new Map<string, number>();
+
+ for (const item of data ?? []) {
+ const time = DateTime.fromSQL(item.time, { zone: timezone }).toUTC();
+ if (!time.isValid || time > now) continue;
+
+ const key = time.toFormat("yyyy-MM-dd HH:mm:ss");
+ const name = String(item.event_name);
+ times.set(key, time);
+ if (!countsByEvent.has(name)) countsByEvent.set(name, new Map());
+ countsByEvent.get(name)!.set(key, item.event_count);
+ totalsByEvent.set(name, (totalsByEvent.get(name) ?? 0) + item.event_count);
+ }
+
+ const sortedTimes = Array.from(times.entries()).sort((a, b) => a[1].toMillis() - b[1].toMillis());
+ const names = Array.from(countsByEvent.keys()).sort(
+ (a, b) => (totalsByEvent.get(b) ?? 0) - (totalsByEvent.get(a) ?? 0)
+ );
+ // Fixed by rank, so hiding a line does not recolour the others.
+ const colors = new Map(names.map((name, index) => [name, seriesColor(index)]));
+
+ const series: ChartSeries[] = names
+ .filter(name => !hidden.has(name))
+ .map(name => ({
+ id: name,
+ color: colors.get(name)!,
+ data: sortedTimes.map(([key, time], index) => ({
+ x: key,
+ y: countsByEvent.get(name)!.get(key) ?? 0,
+ currentTime: time,
+ index,
+ })),
+ }));
+
+ const previousCounts = new Map((previous ?? []).map(event => [String(event.eventName), event.count]));
+ const legendRows: LegendRow[] = names.map(name => ({
+ id: name,
+ label: name,
+ color: colors.get(name)!,
+ total: totalsByEvent.get(name) ?? 0,
+ delta: previous ? percentDelta(totalsByEvent.get(name) ?? 0, previousCounts.get(name) ?? 0) : null,
+ }));
+
+ const placeholder = isError
+ ? {
+ title: t("Failed to load events"),
+ description: t("There was a problem fetching the events. Please try again later."),
}
-
- countsByEvent.get(item.event_name)!.set(timeKey, item.event_count);
- totalsByEvent.set(item.event_name, (totalsByEvent.get(item.event_name) ?? 0) + item.event_count);
- });
-
- const sortedTimes = Array.from(timeLookup.entries()).sort((a, b) => a[1].toMillis() - b[1].toMillis());
- const sortedEventNames = Array.from(countsByEvent.keys()).sort(
- (a, b) => (totalsByEvent.get(b) ?? 0) - (totalsByEvent.get(a) ?? 0)
- );
-
- const seriesData = sortedEventNames.map((eventName, index) => {
- const counts = countsByEvent.get(eventName)!;
- return {
- id: eventName,
- color: COLOR_PALETTE[index % COLOR_PALETTE.length],
- data: sortedTimes.map(([timeKey, timeValue]) => ({
- x: timeKey,
- y: counts.get(timeKey) ?? 0,
- currentTime: timeValue,
- })),
- };
- });
-
- const values = seriesData.flatMap(serie => serie.data.map(point => point.y));
- const maxValue = values.length > 0 ? Math.max(...values) : 1;
-
- return {
- series: seriesData,
- legendItems: seriesData.map(serie => ({ id: serie.id, color: serie.color })),
- maxValue,
- totalPoints: sortedTimes.length,
- };
- }, [data, timezone]);
-
- const maxTicks = Math.round((width ?? 900) / 85);
- const visibleSeries = series.filter(serie => !hiddenEventNames.has(serie.id));
- const visibleValues = visibleSeries.flatMap(serie => serie.data.map(point => point.y));
- const visibleMaxValue = visibleValues.length > 0 ? Math.max(...visibleValues) : maxValue;
- const isAllHidden = series.length > 0 && visibleSeries.length === 0;
-
- const formatXAxisValue = (value: Date) => {
- const dt = DateTime.fromJSDate(value, { zone: "utc" }).setZone(timezone).setLocale(userLocale);
- if (["minute", "five_minutes", "ten_minutes", "fifteen_minutes", "hour"].includes(bucket)) {
- return dt.toFormat(hour12 ? "h:mm" : "HH:mm");
- }
- return dt.toFormat(hour12 ? "MMM d" : "dd MMM");
- };
+ : names.length === 0
+ ? { title: t("No custom events in this period"), description: t("Try a different date range or filter") }
+ : series.length === 0
+ ? { title: t("All event series hidden"), description: t("Click an event to show it") }
+ : null;
return (
- <>
- {isLoading && (
- <div className="absolute top-[-54px] left-0 w-full h-full">
- <CardLoader />
- </div>
- )}
-
- {isAllHidden ? (
- <div className="h-[260px] w-full flex items-center justify-center">
- <div className="text-center text-neutral-500">
- <p className="text-sm font-medium">{t("All event series hidden")}</p>
- <p className="text-xs">{t("Click a legend item to show it")}</p>
- </div>
- </div>
- ) : (
- <div className="h-[260px] w-full">
- <ResponsiveLine
- data={visibleSeries}
- theme={nivoTheme}
- margin={{ top: 10, right: 20, bottom: 30, left: 40 }}
- xScale={{
- type: "time",
- format: "%Y-%m-%d %H:%M:%S",
- precision: "second",
- useUTC: true,
- }}
- yScale={{
- type: "linear",
- min: 0,
- stacked: false,
- reverse: false,
- max: Math.max(visibleMaxValue, 1),
- }}
- enableGridX={true}
- enableGridY={true}
- gridYValues={5}
- axisTop={null}
- axisRight={null}
- axisBottom={{
- tickSize: 5,
- tickPadding: 10,
- tickRotation: 0,
- truncateTickAt: 0,
- tickValues: totalPoints > 0 ? Math.min(maxTicks, totalPoints) : undefined,
- format: formatXAxisValue,
- }}
- axisLeft={{
- tickSize: 5,
- tickPadding: 10,
- tickRotation: 0,
- truncateTickAt: 0,
- tickValues: 5,
- format: formatter,
- }}
- colors={datum => datum.color}
- enableTouchCrosshair={true}
- enablePoints={false}
- useMesh={true}
- animate={false}
- enableSlices="x"
- lineWidth={2}
- sliceTooltip={({ slice }: SliceTooltipProps<EventSeries>) => {
- const currentTime = slice.points[0]?.data.currentTime as DateTime | undefined;
- const sortedPoints = slice.points.toSorted(
- (a, b) => Number(b.data.yFormatted) - Number(a.data.yFormatted)
- );
-
- return (
- <ChartTooltip>
- <div className="p-3 min-w-[160px]">
- {currentTime && <div className="mb-2">{formatChartDateTime(currentTime, bucket)}</div>}
- <div className="space-y-1">
- {sortedPoints.map(point => (
- <div key={point.id} className="flex justify-between items-center gap-4">
- <div className="flex items-center gap-2">
- <div className="w-1 h-3 rounded-[3px]" style={{ backgroundColor: point.seriesColor }} />
- <span className="text-neutral-600 dark:text-neutral-300 max-w-[140px] truncate">
- {point.seriesId}
- </span>
- </div>
- <span className="font-medium text-neutral-700 dark:text-neutral-200">
- {formatter(Number(point.data.yFormatted))}
- </span>
- </div>
- ))}
- </div>
- </div>
- </ChartTooltip>
- );
- }}
- />
- </div>
- )}
-
- <ChartLegend items={legendItems} hiddenItems={hiddenEventNames} onToggle={toggleEventVisibility} />
- </>
+ <ChartPanel
+ title={t("Events by name")}
+ isLoading={isLoading}
+ placeholder={placeholder}
+ chart={<EventSeriesChart series={series} />}
+ legend={
+ <ChartLegend
+ rows={legendRows}
+ hidden={hidden}
+ onToggle={toggle}
+ nameLabel={t("Event")}
+ showDelta={comparisonEnabled}
+ isLoading={isLoading}
+ note={names.length === 0 ? undefined : t("Click an event to show or hide it.")}
+ />
+ }
+ />
);
}
diff --git a/client/src/app/[site]/events/components/EventLog/EventDetailsSheet.tsx b/client/src/app/[site]/events/components/EventLog/EventDetailsSheet.tsx
index 287712167..69b944bdf 100644
--- a/client/src/app/[site]/events/components/EventLog/EventDetailsSheet.tsx
+++ b/client/src/app/[site]/events/components/EventLog/EventDetailsSheet.tsx
@@ -6,19 +6,19 @@ import { DateTime } from "luxon";
import Link from "next/link";
import { Event } from "../../../../../api/analytics/endpoints";
import { fetchSessions } from "../../../../../api/analytics/endpoints/sessions";
-import { EventTypeIcon } from "../../../../../components/EventIcons";
import { CopyButton } from "../../../../../components/interior/copy-button";
import { SessionCard, SessionCardSkeleton } from "../../../../../components/Sessions/SessionCard";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "../../../../../components/ui/sheet";
import { hour12, userLocale } from "../../../../../lib/dateTimeUtils";
import { getRegionName } from "../../../../../lib/geo";
-import { getTimezone } from "../../../../../lib/store";
+import { getTimezone, useStore } from "../../../../../lib/store";
import { getCountryName, getUserDisplayName, truncateString } from "../../../../../lib/utils";
import { Browser } from "../../../components/shared/icons/Browser";
import { CountryFlag } from "../../../components/shared/icons/CountryFlag";
import { DeviceIcon } from "../../../components/shared/icons/Device";
import { OperatingSystem } from "../../../components/shared/icons/OperatingSystem";
-import { buildEventPath, getEventTypeLabel, parseEventProperties } from "./eventLogUtils";
+import { EventTypeMark, useEventTypeLabels } from "../EventTypeMark";
+import { buildEventPath, parseEventProperties } from "./eventLogUtils";
interface EventDetailsSheetProps {
open: boolean;
@@ -29,6 +29,9 @@ interface EventDetailsSheetProps {
export function EventDetailsSheet({ open, onOpenChange, event, site }: EventDetailsSheetProps) {
const t = useExtracted();
+ const { singular: typeLabels } = useEventTypeLabels();
+ // Set on a private-link view, so the user link stays inside it.
+ const privateKey = useStore(state => state.privateKey);
const selectedEventProperties = event ? parseEventProperties(event) : {};
const propertiesJson =
Object.keys(selectedEventProperties).length > 0 ? JSON.stringify(selectedEventProperties, null, 2) : "";
@@ -63,8 +66,12 @@ export function EventDetailsSheet({ open, onOpenChange, event, site }: EventDeta
<SheetHeader className="mb-4">
<SheetTitle>
<div className="flex items-center gap-2">
- <EventTypeIcon type={event?.type || ""} className="w-5 h-5" />
- <span className="font-medium">{getEventTypeLabel(event?.type || "")}</span>
+ <EventTypeMark type={event?.type || ""} className="w-5 h-5" />
+ <span className="font-medium">
+ {event?.type === "custom_event" && event.event_name
+ ? event.event_name
+ : (typeLabels[event?.type || ""] ?? typeLabels.custom_event)}
+ </span>
</div>
</SheetTitle>
</SheetHeader>
@@ -83,7 +90,7 @@ export function EventDetailsSheet({ open, onOpenChange, event, site }: EventDeta
<div className="flex items-center justify-between border-b border-neutral-50 dark:border-neutral-850 pb-1.5">
<span className="text-neutral-500 dark:text-neutral-400">{t("User")}</span>
<Link
- href={`/${site}/user/${encodeURIComponent(event.identified_user_id || event.user_id)}`}
+ href={`/${site}/${privateKey ? `${privateKey}/` : ""}user/${encodeURIComponent(event.identified_user_id || event.user_id)}`}
className="hover:underline"
>
{getUserDisplayName({
diff --git a/client/src/app/[site]/events/components/EventLog/EventLog.tsx b/client/src/app/[site]/events/components/EventLog/EventLog.tsx
index 023d23738..d6116a810 100644
--- a/client/src/app/[site]/events/components/EventLog/EventLog.tsx
+++ b/client/src/app/[site]/events/components/EventLog/EventLog.tsx
@@ -1,19 +1,26 @@
"use client";
-import { useExtracted } from "next-intl";
import { useVirtualizer } from "@tanstack/react-virtual";
+import { useExtracted } from "next-intl";
import { useParams } from "next/navigation";
-import { useCallback, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import { NewItemsPill } from "@/components/interior/new-items-pill";
import { Event } from "../../../../../api/analytics/endpoints";
-import { EVENT_TYPE_CONFIG } from "../../../../../lib/events";
-import { EventTypeFilter } from "../../../../../components/EventTypeFilter";
-import { NothingFound } from "../../../../../components/NothingFound";
import { ErrorState } from "../../../../../components/ErrorState";
+import { NothingFound } from "../../../../../components/NothingFound";
+import { ToggleChip } from "../../../../../components/ToggleChip";
+import { Button } from "../../../../../components/ui/button";
+import { Card } from "../../../../../components/ui/card";
+import { Input } from "../../../../../components/ui/input";
import { ScrollArea } from "../../../../../components/ui/scroll-area";
+import { Skeleton } from "../../../../../components/ui/skeleton";
+import { EVENT_TYPE_CONFIG } from "../../../../../lib/events";
+import { useStore } from "../../../../../lib/store";
+import { cn, getUserDisplayName } from "../../../../../lib/utils";
+import { EventTypeMark, useEventTypeLabels } from "../EventTypeMark";
import { EventDetailsSheet } from "./EventDetailsSheet";
-import { getEventKey } from "./eventLogUtils";
-import { EventRow } from "./EventRow";
+import { getEventKey, matchesEventSearch } from "./eventLogUtils";
+import { EVENT_LOG_GRID, EVENT_LOG_ROW_HEIGHT, EVENT_LOG_WIDE, EVENT_LOG_WIDEST, EventRow } from "./EventRow";
import { RealtimeToggle } from "./RealtimeToggle";
import { useEventLogState } from "./useEventLogState";
@@ -21,10 +28,13 @@ const ALL_EVENT_TYPES = new Set(EVENT_TYPE_CONFIG.map(c => c.value as string));
export function EventLog() {
const t = useExtracted();
- const { site } = useParams();
+ const { site } = useParams<{ site: string }>();
+ const privateKey = useStore(state => state.privateKey);
+ const { singular: typeLabels } = useEventTypeLabels();
const [sheetOpen, setSheetOpen] = useState(false);
const [selectedEvent, setSelectedEvent] = useState<Event | null>(null);
const [visibleTypes, setVisibleTypes] = useState<Set<string>>(ALL_EVENT_TYPES);
+ const [search, setSearch] = useState("");
const handleToggleType = useCallback((type: string) => {
setVisibleTypes(prev => {
@@ -57,6 +67,26 @@ export function EventLog() {
arrivals,
} = useEventLogState({ visibleTypes });
+ // The search reads the rows already loaded: name, type, properties, page and user.
+ const query = search.trim().toLowerCase();
+ const events = useMemo(() => {
+ if (!query) return allEvents;
+ return allEvents.filter(event =>
+ matchesEventSearch(
+ event,
+ query,
+ typeLabels[event.type] ?? "",
+ getUserDisplayName({
+ identified_user_id: event.identified_user_id || undefined,
+ user_id: event.user_id,
+ traits: event.traits,
+ })
+ )
+ );
+ // typeLabels is rebuilt every render; its content only changes with the locale.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [allEvents, query]);
+
const jumpToNewEvents = () => {
flushAndScrollToTop();
// The pill unmounts with the click; keep keyboard focus in the list instead of dropping it on <body>.
@@ -64,84 +94,126 @@ export function EventLog() {
};
const rowVirtualizer = useVirtualizer({
- count: allEvents.length,
+ count: events.length,
getScrollElement: () => scrollElement,
- estimateSize: () => 28,
+ estimateSize: () => EVENT_LOG_ROW_HEIGHT,
overscan: 12,
});
const virtualItems = rowVirtualizer.getVirtualItems();
// --- Infinite scroll trigger ---
+ // Not while searching: a search that matches little would otherwise pull page after page of
+ // history to fill the list. The footer offers the next page instead.
const lastItem = virtualItems[virtualItems.length - 1];
- if (lastItem && lastItem.index >= allEvents.length - 5 && hasNextPage && !isFetchingNextPage && !isLoading) {
+ if (!query && lastItem && lastItem.index >= events.length - 5 && hasNextPage && !isFetchingNextPage && !isLoading) {
fetchNextPage();
}
- const showBody = !isLoading && !isError && allEvents.length > 0;
+ const showBody = !isLoading && !isError && events.length > 0;
return (
<>
- <div className="flex items-center gap-3 mb-2">
- <RealtimeToggle isRealtime={isRealtime} onToggle={toggleRealtime} />
- {!isLoading && (
- <EventTypeFilter visibleTypes={visibleTypes} onToggle={handleToggleType} events={unfilteredEvents} />
- )}
- </div>
+ <Card>
+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2 px-3 pb-2 pt-3 md:px-4">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ <h2 className="text-base font-semibold leading-none tracking-tight">{t("Event log")}</h2>
+ <RealtimeToggle isRealtime={isRealtime} onToggle={toggleRealtime} />
+ <span className="text-xs text-neutral-500 dark:text-neutral-400">
+ {isRealtime
+ ? t("Newest first, checks every 2 seconds. Scroll down to pause.")
+ : t("Newest first, within the selected period.")}
+ </span>
+ </div>
+ <div className="w-full sm:w-64">
+ <Input
+ isSearch
+ inputSize="sm"
+ className="h-8"
+ value={search}
+ onChange={event => setSearch(event.target.value)}
+ placeholder={t("Search name, property or user")}
+ aria-label={t("Search name, property or user")}
+ />
+ </div>
+ </div>
- <div className="relative">
- {/* Events that arrived while scrolled away from the top wait in a buffer; the pill brings them in. */}
- <NewItemsPill
- className="top-10"
- count={isRealtime && !isLive ? bufferedCount : 0}
- onJump={jumpToNewEvents}
- describe={count => t("{count, plural, one {# new event} other {# new events}}", { count })}
- label={(count, ticker) =>
- t.rich("{count, plural, one {<ticker>#</ticker> new event} other {<ticker>#</ticker> new events}}", {
- count,
- ticker: () => ticker,
- })
- }
- />
-
- <ScrollArea
- className="h-[90vh] border border-neutral-100 dark:border-neutral-800 rounded-lg"
- ref={scrollAreaCallbackRef}
- >
- <div className="relative h-full pr-2 font-mono text-[11px] leading-4">
- <div className="sticky top-0 z-20 bg-neutral-50/95 dark:bg-neutral-850/95 backdrop-blur border-b border-neutral-100 dark:border-neutral-800">
- <div className="grid grid-cols-[28px_145px_180px_100px_1fr_1fr] px-2 py-1.5 uppercase tracking-wide text-[10px] text-neutral-500 dark:text-neutral-400">
- <div></div>
- <div>{t("Timestamp")}</div>
- <div>{t("User")}</div>
- <div>{t("Device Info")}</div>
- <div>{t("Page")}</div>
- <div>{t("Data")}</div>
- </div>
- </div>
+ <div className="flex items-center gap-1.5 overflow-x-auto px-3 pb-3 md:px-4">
+ {EVENT_TYPE_CONFIG.map(option => (
+ <ToggleChip
+ key={option.value}
+ isSelected={visibleTypes.has(option.value)}
+ onClick={() => handleToggleType(option.value)}
+ indicator={<EventTypeMark type={option.value} className="h-3 w-3" />}
+ label={typeLabels[option.value] ?? option.label}
+ />
+ ))}
+ </div>
+
+ <div className="@container relative border-t border-neutral-100 dark:border-neutral-800">
+ {/* Events that arrived while scrolled away from the top wait in a buffer; the pill brings them in. */}
+ <NewItemsPill
+ className="top-10"
+ count={isRealtime && !isLive ? bufferedCount : 0}
+ onJump={jumpToNewEvents}
+ describe={count => t("{count, plural, one {# new event} other {# new events}}", { count })}
+ label={(count, ticker) =>
+ t.rich("{count, plural, one {<ticker>#</ticker> new event} other {<ticker>#</ticker> new events}}", {
+ count,
+ ticker: () => ticker,
+ })
+ }
+ />
- {isLoading && (
- <div>
- {Array.from({ length: 24 }).map((_, index) => (
- <EventLogItemSkeleton key={index} showProperties={index % 3 === 0} />
- ))}
+ <ScrollArea className="h-[70vh] min-h-[360px]" ref={scrollAreaCallbackRef}>
+ <div className="relative h-full">
+ <div
+ className={cn(
+ EVENT_LOG_GRID,
+ "sticky top-0 z-20 h-8 border-b border-neutral-100 bg-neutral-50 text-xs font-medium text-neutral-500 dark:border-neutral-800 dark:bg-neutral-850 dark:text-neutral-400"
+ )}
+ >
+ <span>{t("Time")}</span>
+ <span>{t("Event")}</span>
+ <span className={EVENT_LOG_WIDE}>{t("Properties")}</span>
+ <span>{t("User")}</span>
+ <span className={EVENT_LOG_WIDEST}>{t("Page")}</span>
+ <span className={EVENT_LOG_WIDE}>{t("Device")}</span>
</div>
- )}
- {isError && (
- <ErrorState
- title={t("Failed to load events")}
- message={t("There was a problem fetching the events. Please try again later.")}
- />
- )}
+ {isLoading && (
+ <div>
+ {Array.from({ length: 16 }).map((_, index) => (
+ <EventLogRowSkeleton key={index} wide={index % 3 === 0} />
+ ))}
+ </div>
+ )}
- {isFetched && !isError && allEvents.length === 0 && (
- <NothingFound title={t("No events found")} description={t("Try a different date range or filter")} />
- )}
+ {isError && (
+ <ErrorState
+ title={t("Failed to load events")}
+ message={t("There was a problem fetching the events. Please try again later.")}
+ />
+ )}
- {showBody && (
- <>
- <div className="relative">
+ {isFetched && !isError && events.length === 0 && (
+ <NothingFound
+ title={t("No events found")}
+ description={
+ query
+ ? t('None of the {count} loaded events match "{search}".', {
+ count: allEvents.length.toLocaleString(),
+ search: search.trim(),
+ })
+ : unfilteredEvents.length > 0
+ ? t("No loaded events are of the selected types.")
+ : t("Try a different date range or filter")
+ }
+ />
+ )}
+
+ {showBody && (
+ <>
<div
style={{
height: rowVirtualizer.getTotalSize(),
@@ -149,7 +221,7 @@ export function EventLog() {
}}
>
{virtualItems.map(virtualRow => {
- const event = allEvents[virtualRow.index];
+ const event = events[virtualRow.index];
if (!event) return null;
return (
@@ -165,7 +237,9 @@ export function EventLog() {
>
<EventRow
event={event}
- site={site as string}
+ site={site}
+ privateKey={privateKey}
+ typeLabel={typeLabels[event.type] ?? typeLabels.custom_event}
arrivedAt={arrivals.size ? arrivals.get(getEventKey(event)) : undefined}
onClick={selected => {
setSelectedEvent(selected);
@@ -176,20 +250,42 @@ export function EventLog() {
);
})}
</div>
- </div>
- {isFetchingNextPage && (
- <div className="py-2">
- {Array.from({ length: 3 }).map((_, index) => (
- <EventLogItemSkeleton key={`next-page-${index}`} />
- ))}
- </div>
- )}
- </>
+ {isFetchingNextPage && (
+ <div>
+ {Array.from({ length: 3 }).map((_, index) => (
+ <EventLogRowSkeleton key={`next-page-${index}`} />
+ ))}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </ScrollArea>
+ </div>
+
+ {query && !isLoading && !isError && (
+ <div className="flex flex-wrap items-center justify-between gap-2 border-t border-neutral-100 px-4 py-2 text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400">
+ <span>
+ {t("{matches} of the {count} loaded events match. The search does not reach older events.", {
+ matches: events.length.toLocaleString(),
+ count: allEvents.length.toLocaleString(),
+ })}
+ </span>
+ {hasNextPage && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ loading={isFetchingNextPage}
+ onClick={() => fetchNextPage()}
+ >
+ {t("Load older events")}
+ </Button>
)}
</div>
- </ScrollArea>
- </div>
+ )}
+ </Card>
<EventDetailsSheet
open={sheetOpen}
@@ -198,35 +294,32 @@ export function EventLog() {
if (!open) setSelectedEvent(null);
}}
event={selectedEvent}
- site={site as string}
+ site={site}
/>
</>
);
}
-function EventLogItemSkeleton({ showProperties }: { showProperties?: boolean }) {
+function EventLogRowSkeleton({ wide }: { wide?: boolean }) {
return (
- <div className="grid grid-cols-[28px_145px_180px_100px_1fr_1fr] border-b border-neutral-100 dark:border-neutral-800 px-2 py-1">
- <div className="flex items-center justify-center">
- <div className="h-4 w-4 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" />
- </div>
- <div className="flex items-center px-2">
- <div className="h-3 w-24 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" />
- </div>
- <div className="flex items-center gap-2 px-2">
- <div className="h-[18px] w-[18px] rounded-full bg-neutral-200 dark:bg-neutral-700 animate-pulse" />
- <div className="h-3 w-20 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" />
+ <div className={cn(EVENT_LOG_GRID, "h-8 border-b border-neutral-100 dark:border-neutral-800")}>
+ <Skeleton className="h-3 w-14 rounded" />
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-3.5 w-3.5 rounded" />
+ <Skeleton className="h-3 w-24 rounded" />
</div>
- <div className="flex items-center gap-1 px-2">
- <div className="h-4 w-4 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" />
- <div className="h-4 w-4 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" />
- <div className="h-4 w-4 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" />
+ <div className={EVENT_LOG_WIDE}>{wide && <Skeleton className="h-3 w-48 rounded" />}</div>
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-[18px] w-[18px] rounded-full" />
+ <Skeleton className="h-3 w-16 rounded" />
</div>
- <div className="flex items-center px-2">
- <div className="h-3 w-28 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" />
+ <div className={EVENT_LOG_WIDEST}>
+ <Skeleton className="h-3 w-24 rounded" />
</div>
- <div className="flex items-center px-2">
- {showProperties && <div className="h-3 w-32 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" />}
+ <div className={cn(EVENT_LOG_WIDE, "items-center gap-1")}>
+ <Skeleton className="h-3.5 w-3.5 rounded" />
+ <Skeleton className="h-3.5 w-3.5 rounded" />
+ <Skeleton className="h-3.5 w-3.5 rounded" />
</div>
</div>
);
diff --git a/client/src/app/[site]/events/components/EventLog/EventRow.tsx b/client/src/app/[site]/events/components/EventLog/EventRow.tsx
index e66db86b5..a9e3498b5 100644
--- a/client/src/app/[site]/events/components/EventLog/EventRow.tsx
+++ b/client/src/app/[site]/events/components/EventLog/EventRow.tsx
@@ -1,45 +1,77 @@
"use client";
+import { IdCard } from "lucide-react";
+import { DateTime } from "luxon";
import { useExtracted } from "next-intl";
import Link from "next/link";
-import { DateTime } from "luxon";
import { useRef } from "react";
import { useArrivalHighlight } from "@/components/interior/use-arrival-highlight";
import { Event } from "../../../../../api/analytics/endpoints";
import { Avatar } from "../../../../../components/Avatar";
-import { EventTypeIcon } from "../../../../../components/EventIcons";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";
import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
-import { useEventDisplayName } from "../../../../../lib/events";
import { getTimezone } from "../../../../../lib/store";
-import { getCountryName, getUserDisplayName, truncateString } from "../../../../../lib/utils";
+import { cn, getCountryName, getUserDisplayName } from "../../../../../lib/utils";
import { Browser } from "../../../components/shared/icons/Browser";
import { CountryFlag } from "../../../components/shared/icons/CountryFlag";
-import { OperatingSystem } from "../../../components/shared/icons/OperatingSystem";
-import { buildEventPath, getEventTypeLabel, getMainData, parseEventProperties } from "./eventLogUtils";
import { DeviceIcon } from "../../../components/shared/icons/Device";
+import { OperatingSystem } from "../../../components/shared/icons/OperatingSystem";
+import { EventTypeMark } from "../EventTypeMark";
+import { buildEventPath, getEventRowData, parseEventProperties, PropertyToken } from "./eventLogUtils";
+
+/**
+ * The log's columns, shared by the header and every row so they line up. They
+ * follow the width of the log itself (its `@container`), not the window: a
+ * narrow log keeps time, event and user; properties and device join at 760px,
+ * the page at 980px. Everything is still in the details sheet a row opens.
+ */
+export const EVENT_LOG_GRID =
+ "grid items-center gap-x-2 px-3 md:gap-x-3 md:px-4 grid-cols-[92px_minmax(0,1fr)_minmax(0,112px)] @min-[760px]:grid-cols-[104px_minmax(0,172px)_minmax(0,1fr)_150px_84px] @min-[980px]:grid-cols-[104px_minmax(0,172px)_minmax(0,1fr)_150px_minmax(0,164px)_84px]";
+/** Shown from the width the properties and device columns appear at. */
+export const EVENT_LOG_WIDE = "hidden @min-[760px]:flex";
+/** Shown from the width the page column appears at. */
+export const EVENT_LOG_WIDEST = "hidden @min-[980px]:block";
+
+export const EVENT_LOG_ROW_HEIGHT = 32;
+
+function Token({ token }: { token: PropertyToken }) {
+ return (
+ <span
+ className="inline-flex shrink-0 items-center whitespace-nowrap rounded border border-neutral-200 bg-neutral-50 px-1.5 py-px font-mono text-[11px] leading-4 dark:border-neutral-800 dark:bg-neutral-850"
+ title={`${token.key}=${token.value}`}
+ >
+ <span className="text-neutral-500 dark:text-neutral-400">{token.key}</span>
+ <span className="px-px text-neutral-400 dark:text-neutral-500">=</span>
+ <span className="max-w-[28ch] truncate text-neutral-900 dark:text-neutral-100">{token.value}</span>
+ </span>
+ );
+}
interface EventRowProps {
event: Event;
site: string;
+ /** Set on a private-link view, so the user link stays inside it. */
+ privateKey: string | null;
+ /** The event's type as a word, for rows that have no name of their own. */
+ typeLabel: string;
onClick: (event: Event) => void;
/** performance.now() when the row arrived from a poll; it gets a brief neutral highlight. */
arrivedAt?: number;
}
-export function EventRow({ event, site, onClick, arrivedAt }: EventRowProps) {
+export function EventRow({ event, site, privateKey, typeLabel, onClick, arrivedAt }: EventRowProps) {
const t = useExtracted();
const rowRef = useRef<HTMLDivElement>(null);
useArrivalHighlight(rowRef, arrivedAt);
- const getEventDisplayName = useEventDisplayName();
const { locale, hour12, formatRelative } = useDateTimeFormat();
const eventProperties = parseEventProperties(event);
const eventTime = DateTime.fromSQL(event.timestamp, { zone: "utc" }).setLocale(locale).setZone(getTimezone());
+ const isToday = eventTime.hasSame(DateTime.now().setZone(getTimezone()), "day");
const pagePath = buildEventPath(event);
const pageUrl = `https://${event.hostname}${pagePath}`;
- const isPageview = event.type === "pageview";
- const eventData = isPageview ? null : getMainData(event, eventProperties, getEventDisplayName);
+ const data = getEventRowData(event, eventProperties);
const userProfileId = event.identified_user_id || event.user_id;
+ const userHref = `/${site}/${privateKey ? `${privateKey}/` : ""}user/${encodeURIComponent(userProfileId)}`;
const displayName = getUserDisplayName({
identified_user_id: event.identified_user_id || undefined,
user_id: event.user_id,
@@ -49,47 +81,94 @@ export function EventRow({ event, site, onClick, arrivedAt }: EventRowProps) {
return (
<div
ref={rowRef}
- className="grid grid-cols-[28px_145px_180px_100px_1fr_1fr] border-b border-neutral-100 dark:border-neutral-800 hover:bg-neutral-50/60 dark:hover:bg-neutral-800/40 cursor-pointer [--arrival-bg:hsl(var(--neutral-100))] dark:[--arrival-bg:hsl(var(--neutral-800))]"
+ className={cn(
+ EVENT_LOG_GRID,
+ "h-8 cursor-pointer border-b border-neutral-100 text-xs hover:bg-neutral-50 dark:border-neutral-800 dark:hover:bg-neutral-800/40 [--arrival-bg:hsl(var(--neutral-100))] dark:[--arrival-bg:hsl(var(--neutral-800))]"
+ )}
onClick={() => onClick(event)}
>
- <div className="flex items-center justify-center py-1">
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <EventTypeIcon type={event.type} />
- </div>
- </TooltipTrigger>
- <TooltipContent>
- <span>{getEventTypeLabel(event.type)}</span>
- </TooltipContent>
- </Tooltip>
- </div>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="truncate tabular-nums text-neutral-500 dark:text-neutral-400">
+ {/* Today's rows drop the date: in the live log it would repeat on every line. */}
+ {isToday
+ ? eventTime.toFormat(hour12 ? "h:mm:ss a" : "HH:mm:ss")
+ : eventTime.toFormat(hour12 ? "MMM d, h:mm a" : "dd MMM, HH:mm")}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span>
+ {eventTime.toFormat(hour12 ? "MMM d, h:mm:ss a" : "dd MMM, HH:mm:ss")} · {formatRelative(eventTime)}
+ </span>
+ </TooltipContent>
+ </Tooltip>
- <div className="text-neutral-500 dark:text-neutral-400 px-2 py-1 flex items-center">
- <Tooltip>
- <TooltipTrigger asChild>
- <span>{eventTime.toFormat(hour12 ? "MMM d, h:mm:ss a" : "dd MMM, HH:mm:ss")}</span>
- </TooltipTrigger>
- <TooltipContent>
- <span>{formatRelative(eventTime)}</span>
- </TooltipContent>
- </Tooltip>
+ <div className="flex min-w-0 items-center gap-2">
+ <EventTypeMark type={event.type} className="h-3.5 w-3.5" />
+ {event.type === "custom_event" && event.event_name ? (
+ <span className="truncate font-medium text-neutral-900 dark:text-neutral-100" title={event.event_name}>
+ {event.event_name}
+ </span>
+ ) : (
+ <span className="truncate text-neutral-600 dark:text-neutral-300">{typeLabel}</span>
+ )}
</div>
- <div className="px-2 py-1">
- <Link
- href={`/${site}/user/${encodeURIComponent(userProfileId)}`}
- onClick={e => e.stopPropagation()}
- className="flex items-center gap-2"
- >
- <Avatar size={18} id={event.user_id} lastActiveTime={eventTime} />
- <div className="text-neutral-700 dark:text-neutral-200 truncate max-w-[160px] hover:underline">
- {displayName}
- </div>
- </Link>
+ <div
+ className={cn(
+ EVENT_LOG_WIDE,
+ "min-w-0 items-center gap-1.5 overflow-hidden",
+ // Tokens keep their width and fade out where they run past the column; the sheet has them all.
+ data.kind === "tokens" && "[mask-image:linear-gradient(to_right,black_calc(100%-28px),transparent)]"
+ )}
+ >
+ {data.kind === "link" ? (
+ <Link
+ href={data.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={e => e.stopPropagation()}
+ className="truncate text-neutral-600 hover:underline dark:text-neutral-300"
+ title={data.url}
+ >
+ {data.url.replace(/^https?:\/\//, "")}
+ </Link>
+ ) : data.kind === "message" ? (
+ <span className="truncate font-mono text-[11px] text-neutral-600 dark:text-neutral-300" title={data.text}>
+ {data.text}
+ </span>
+ ) : (
+ data.tokens.map(token => <Token key={token.key} token={token} />)
+ )}
</div>
- <div className="flex space-x-1 items-center px-2 py-1">
+ <Link
+ href={userHref}
+ onClick={e => e.stopPropagation()}
+ className="flex min-w-0 items-center gap-2 hover:underline"
+ >
+ <Avatar size={18} id={event.user_id} lastActiveTime={eventTime} />
+ <span className="truncate text-neutral-700 dark:text-neutral-200">{displayName}</span>
+ {event.identified_user_id && (
+ <IdCard
+ className="h-3 w-3 shrink-0 text-emerald-600 dark:text-emerald-400"
+ aria-label={t("Identified user")}
+ />
+ )}
+ </Link>
+
+ <Link
+ href={pageUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={e => e.stopPropagation()}
+ className={cn(EVENT_LOG_WIDEST, "truncate text-neutral-600 hover:underline dark:text-neutral-300")}
+ title={pagePath}
+ >
+ {pagePath}
+ </Link>
+
+ <div className={cn(EVENT_LOG_WIDE, "items-center gap-1")}>
{event.country && (
<Tooltip>
<TooltipTrigger asChild>
@@ -133,37 +212,6 @@ export function EventRow({ event, site, onClick, arrivedAt }: EventRowProps) {
</TooltipContent>
</Tooltip>
</div>
-
- <div className="text-neutral-600 dark:text-neutral-300 px-2 py-1 truncate">
- <Link
- href={pageUrl}
- target="_blank"
- rel="noopener noreferrer"
- onClick={e => e.stopPropagation()}
- className="hover:underline"
- title={pagePath}
- >
- {truncateString(pagePath, 60)}
- </Link>
- </div>
-
- <div className="text-neutral-600 dark:text-neutral-300 px-2 py-1 truncate">
- {eventData &&
- (eventData.url ? (
- <Link
- href={eventData.url}
- target="_blank"
- rel="noopener noreferrer"
- onClick={e => e.stopPropagation()}
- className="hover:underline"
- title={eventData.label}
- >
- {truncateString(eventData.label, 60)}
- </Link>
- ) : (
- <span title={eventData.label}>{truncateString(eventData.label, 60)}</span>
- ))}
- </div>
</div>
);
}
diff --git a/client/src/app/[site]/events/components/EventLog/RealtimeToggle.tsx b/client/src/app/[site]/events/components/EventLog/RealtimeToggle.tsx
index fc2339061..97da6c95b 100644
--- a/client/src/app/[site]/events/components/EventLog/RealtimeToggle.tsx
+++ b/client/src/app/[site]/events/components/EventLog/RealtimeToggle.tsx
@@ -1,28 +1,20 @@
-export function RealtimeToggle({
- isRealtime,
- onToggle,
-}: {
- isRealtime: boolean;
- onToggle: () => void;
-}) {
+"use client";
+
+import { useExtracted } from "next-intl";
+import { useId } from "react";
+import { Switch } from "../../../../../components/ui/switch";
+
+/** Switches the log between following new events as they arrive and reading the selected period. */
+export function RealtimeToggle({ isRealtime, onToggle }: { isRealtime: boolean; onToggle: () => void }) {
+ const t = useExtracted();
+ const id = useId();
+
return (
- <div className="flex items-center gap-2 shrink-0">
- <button
- onClick={onToggle}
- className={`flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium transition-colors cursor-pointer ${
- isRealtime
- ? "bg-emerald-500/15 text-emerald-500 hover:bg-emerald-500/25"
- : "bg-neutral-100 dark:bg-neutral-800 text-neutral-500 hover:bg-neutral-200 dark:hover:bg-neutral-700"
- }`}
- >
- {isRealtime && (
- <span className="relative flex h-2 w-2">
- <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
- <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500" />
- </span>
- )}
- Realtime
- </button>
+ <div className="flex shrink-0 items-center gap-2">
+ <Switch id={id} checked={isRealtime} onCheckedChange={onToggle} />
+ <label htmlFor={id} className="cursor-pointer text-xs font-medium text-neutral-700 dark:text-neutral-200">
+ {t("Live")}
+ </label>
</div>
);
}
diff --git a/client/src/app/[site]/events/components/EventLog/eventLogUtils.test.ts b/client/src/app/[site]/events/components/EventLog/eventLogUtils.test.ts
new file mode 100644
index 000000000..0eda233c8
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventLog/eventLogUtils.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, it } from "vitest";
+import { Event } from "../../../../../api/analytics/endpoints";
+import { formatPropertyValue, getEventRowData, matchesEventSearch, parseEventProperties } from "./eventLogUtils";
+
+const event = (overrides: Partial<Event> = {}): Event => ({
+ timestamp: "2026-09-30 14:32:22",
+ event_name: "",
+ properties: "{}",
+ session_id: "session-1",
+ user_id: "a1d7b800719f",
+ identified_user_id: "",
+ hostname: "rybbit.com",
+ pathname: "/pricing",
+ querystring: "",
+ page_title: "",
+ referrer: "",
+ browser: "Chrome",
+ browser_version: "",
+ operating_system: "macOS",
+ operating_system_version: "",
+ language: "en",
+ country: "US",
+ region: "",
+ city: "",
+ lat: 0,
+ lon: 0,
+ screen_width: 0,
+ screen_height: 0,
+ device_type: "Desktop",
+ type: "custom_event",
+ ...overrides,
+});
+
+describe("formatPropertyValue", () => {
+ it("keeps strings as they are and prints everything else on one line", () => {
+ expect(formatPropertyValue("google")).toBe("google");
+ expect(formatPropertyValue(42)).toBe("42");
+ expect(formatPropertyValue(false)).toBe("false");
+ expect(formatPropertyValue(null)).toBe("null");
+ expect(formatPropertyValue({ plan: "pro", seats: 3 })).toBe('{"plan":"pro","seats":3}');
+ expect(formatPropertyValue(["a", "b"])).toBe('["a","b"]');
+ });
+});
+
+describe("getEventRowData", () => {
+ const data = (overrides: Partial<Event>) => {
+ const row = event(overrides);
+ return getEventRowData(row, parseEventProperties(row));
+ };
+
+ it("shows a custom event's properties as key=value tokens, in the order they were sent", () => {
+ expect(
+ data({ event_name: "signup", properties: JSON.stringify({ method: "google", plan_intent: "standard" }) })
+ ).toEqual({
+ kind: "tokens",
+ tokens: [
+ { key: "method", value: "google" },
+ { key: "plan_intent", value: "standard" },
+ ],
+ });
+ });
+
+ it("shows an outbound click as its link", () => {
+ expect(
+ data({ type: "outbound", properties: JSON.stringify({ url: "https://github.com/rybbit-io/rybbit" }) })
+ ).toEqual({ kind: "link", url: "https://github.com/rybbit-io/rybbit" });
+ });
+
+ it("shows an error as its message", () => {
+ expect(
+ data({ type: "error", properties: JSON.stringify({ message: "TypeError: x is undefined", stack: "at …" }) })
+ ).toEqual({ kind: "message", text: "TypeError: x is undefined" });
+ });
+
+ it("falls back to tokens for an outbound click or an error without the expected property", () => {
+ expect(data({ type: "outbound", properties: JSON.stringify({ text: "GitHub" }) })).toEqual({
+ kind: "tokens",
+ tokens: [{ key: "text", value: "GitHub" }],
+ });
+ expect(data({ type: "error" })).toEqual({ kind: "tokens", tokens: [] });
+ });
+
+ it("has nothing to show for a pageview", () => {
+ expect(data({ type: "pageview" })).toEqual({ kind: "tokens", tokens: [] });
+ });
+
+ it("stops at the tokens one line can hold", () => {
+ const properties = Object.fromEntries(Array.from({ length: 12 }, (_, index) => [`key${index}`, index]));
+ const row = data({ properties: JSON.stringify(properties) });
+
+ expect(row.kind === "tokens" && row.tokens).toHaveLength(6);
+ });
+
+ it("survives properties that are not valid JSON", () => {
+ const row = event({ properties: "{not json" });
+
+ expect(parseEventProperties(row)).toEqual({});
+ });
+});
+
+describe("matchesEventSearch", () => {
+ const signup = event({
+ event_name: "signup",
+ properties: JSON.stringify({ method: "google", referral_code: "HN-LAUNCH" }),
+ identified_user_id: "usr_8f2kq1",
+ });
+
+ it("matches everything for an empty query", () => {
+ expect(matchesEventSearch(signup, "", "Event", "Mara Lindqvist")).toBe(true);
+ });
+
+ it.each([
+ ["the event name", "sign"],
+ ["a property key", "referral_code"],
+ ["a property value", "hn-launch"],
+ ["the page", "/pric"],
+ ["the user's name", "lindqvist"],
+ ["the anonymous id", "a1d7b8"],
+ ["the identified id", "usr_8f2"],
+ ["the type label", "event"],
+ ])("matches on %s", (_field, query) => {
+ expect(matchesEventSearch(signup, query, "Event", "Mara Lindqvist")).toBe(true);
+ });
+
+ it("does not match text the event does not have", () => {
+ expect(matchesEventSearch(signup, "checkout", "Event", "Mara Lindqvist")).toBe(false);
+ });
+
+ it("finds an autocaptured event by its type", () => {
+ const click = event({ type: "button_click", properties: JSON.stringify({ text: "Start free trial" }) });
+
+ expect(matchesEventSearch(click, "button", "Button click", "Apricot Viper")).toBe(true);
+ expect(matchesEventSearch(click, "free trial", "Button click", "Apricot Viper")).toBe(true);
+ });
+});
diff --git a/client/src/app/[site]/events/components/EventLog/eventLogUtils.tsx b/client/src/app/[site]/events/components/EventLog/eventLogUtils.tsx
index 8e2269c05..46895f5b1 100644
--- a/client/src/app/[site]/events/components/EventLog/eventLogUtils.tsx
+++ b/client/src/app/[site]/events/components/EventLog/eventLogUtils.tsx
@@ -1,7 +1,6 @@
"use client";
import { Event } from "../../../../../api/analytics/endpoints";
-import { EVENT_TYPE_CONFIG, EventDisplayNameFormatter } from "../../../../../lib/events";
export function getEventKey(event: Event) {
return `${event.timestamp}-${event.session_id}-${event.user_id}-${event.type}-${event.event_name ?? ""}-${event.pathname}`;
@@ -18,50 +17,57 @@ export function parseEventProperties(event: Event): Record<string, any> {
return {};
}
-// EVENT_TYPE_CONFIG labels are display strings ("Pageview", "Input Change"), not
-// message keys, so they must not be passed to t() — doing so throws MISSING_MESSAGE
-// and breaks the events page. Return them as-is.
-export function getEventTypeLabel(type: string) {
- return EVENT_TYPE_CONFIG.find(item => item.value === type)?.label ?? "Event";
-}
-
export function buildEventPath(event: Event) {
return `${event.pathname}${event.querystring ? `${event.querystring}` : ""}`;
}
-export function getMainData(
- event: Event,
- props: Record<string, any>,
- getEventDisplayName: EventDisplayNameFormatter
-) {
- const isPageview = event.type === "pageview";
- const isOutbound = event.type === "outbound";
- const isButtonClick = event.type === "button_click";
- const isCopy = event.type === "copy";
- const isFormSubmit = event.type === "form_submit";
- const isInputChange = event.type === "input_change";
+/** A property value as one line of text: strings as they are, everything else as JSON. */
+export function formatPropertyValue(value: unknown): string {
+ if (typeof value === "string") return value;
+ if (value === null || value === undefined) return String(value);
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
+}
- if (isPageview) {
- return {
- label: buildEventPath(event),
- url: `https://${event.hostname}${buildEventPath(event)}`,
- };
- }
+export type PropertyToken = { key: string; value: string };
- if (isOutbound && props.url) {
- return {
- label: props.url as string,
- url: props.url as string,
- };
- }
+/** What a log row shows of an event's payload, besides its name and page. */
+export type EventRowData =
+ | { kind: "link"; url: string }
+ | { kind: "message"; text: string }
+ | { kind: "tokens"; tokens: PropertyToken[] };
- if (isButtonClick || isCopy || isFormSubmit || isInputChange) {
- return {
- label: getEventDisplayName({ type: event.type, event_name: event.event_name, props }),
- };
- }
+// A row is one line: this many key=value tokens is already more than it can show.
+const MAX_ROW_TOKENS = 6;
+export function getEventRowData(event: Event, props: Record<string, any>): EventRowData {
+ if (event.type === "outbound" && typeof props.url === "string" && props.url) {
+ return { kind: "link", url: props.url };
+ }
+ if (event.type === "error" && props.message) {
+ return { kind: "message", text: formatPropertyValue(props.message) };
+ }
return {
- label: event.event_name || "Event",
+ kind: "tokens",
+ tokens: Object.entries(props)
+ .slice(0, MAX_ROW_TOKENS)
+ .map(([key, value]) => ({ key, value: formatPropertyValue(value) })),
};
}
+
+/**
+ * Whether a loaded event matches the log's search box: its name, its type, any
+ * property key or value, the page, or the user (display name or either id).
+ * `query` is already trimmed and lower-cased.
+ */
+export function matchesEventSearch(event: Event, query: string, typeLabel: string, userName: string): boolean {
+ if (!query) return true;
+ return [
+ event.event_name,
+ typeLabel,
+ event.properties,
+ event.pathname,
+ userName,
+ event.user_id,
+ event.identified_user_id,
+ ].some(field => !!field && field.toLowerCase().includes(query));
+}
diff --git a/client/src/app/[site]/events/components/EventNames/AutocaptureTable.tsx b/client/src/app/[site]/events/components/EventNames/AutocaptureTable.tsx
new file mode 100644
index 000000000..66a48267e
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventNames/AutocaptureTable.tsx
@@ -0,0 +1,110 @@
+"use client";
+
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+
+import { Favicon } from "@/components/Favicon";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
+import { getTimezone } from "@/lib/store";
+import { truncateString, truncateUrl } from "@/lib/utils";
+import { formatShare } from "../../utils/properties";
+
+export interface AutocaptureRow {
+ /** What the events are grouped by: a URL, a button's text, a form's name, the copied text. */
+ value: string;
+ count: number;
+ /** UTC, as ClickHouse prints it. */
+ lastSeen: string;
+}
+
+interface AutocaptureTableProps {
+ rows: AutocaptureRow[];
+ /** The largest count among every row, so bars keep their scale when the list is cut or searched. */
+ maxCount: number;
+ /** The total the shares are out of. */
+ total: number;
+ valueLabel: string;
+ /** The values are URLs: draw them as links with a favicon. */
+ links?: boolean;
+}
+
+const hostnameOf = (url: string): string | null => {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return null;
+ }
+};
+
+/** Autocaptured events of one type, grouped by what was clicked, submitted or copied. */
+export function AutocaptureTable({ rows, maxCount, total, valueLabel, links = false }: AutocaptureTableProps) {
+ const t = useExtracted();
+ const { formatRelative } = useDateTimeFormat();
+ const timezone = getTimezone();
+
+ return (
+ <div className="@container">
+ <Table className="table-fixed">
+ <TableHeader>
+ <TableRow className="hover:bg-transparent dark:hover:bg-transparent">
+ <TableHead className="rounded-none pl-4 first:rounded-none">{valueLabel}</TableHead>
+ <TableHead className="w-[120px] @min-[480px]:w-[220px]">{t("Events")}</TableHead>
+ <TableHead className="hidden w-[128px] rounded-none pr-4 last:rounded-none @min-[640px]:table-cell">
+ {t("Last seen")}
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map(row => {
+ const share = total > 0 ? row.count / total : 0;
+ const lastSeen = DateTime.fromSQL(row.lastSeen, { zone: "utc" }).setZone(timezone);
+ const hostname = links ? hostnameOf(row.value) : null;
+
+ return (
+ <TableRow key={row.value} className="h-10">
+ <TableCell className="pl-4">
+ {hostname ? (
+ <div className="flex min-w-0 items-center gap-2">
+ <Favicon domain={hostname} className="h-4 w-4 shrink-0" />
+ <a
+ href={row.value}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={row.value}
+ className="truncate font-medium text-neutral-900 hover:underline dark:text-neutral-100"
+ >
+ {truncateUrl(row.value)}
+ </a>
+ </div>
+ ) : (
+ <div className="truncate font-medium text-neutral-900 dark:text-neutral-100" title={row.value}>
+ {truncateString(row.value, 120)}
+ </div>
+ )}
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2.5">
+ <span className="min-w-11 text-right font-medium tabular-nums">{row.count.toLocaleString()}</span>
+ <div className="relative hidden h-1.5 min-w-0 flex-1 rounded-full bg-neutral-100 dark:bg-neutral-800 @min-[480px]:block">
+ <div
+ className="absolute inset-y-0 left-0 rounded-full bg-dataviz"
+ style={{ width: `${maxCount > 0 ? (row.count / maxCount) * 100 : 0}%` }}
+ />
+ </div>
+ <span className="w-11 text-right text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
+ {formatShare(share)}
+ </span>
+ </div>
+ </TableCell>
+ <TableCell className="hidden whitespace-nowrap pr-4 text-xs tabular-nums text-neutral-600 dark:text-neutral-300 @min-[640px]:table-cell">
+ {lastSeen.isValid ? formatRelative(lastSeen) : "—"}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/events/components/EventNames/CreateGoalPopover.tsx b/client/src/app/[site]/events/components/EventNames/CreateGoalPopover.tsx
new file mode 100644
index 000000000..d1aa47666
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventNames/CreateGoalPopover.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+import { Plus } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { FormEvent, useId, useState } from "react";
+
+import { useCreateGoal } from "@/api/analytics/hooks/goals/useCreateGoal";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { toast } from "@/components/ui/sonner";
+import { useStore } from "@/lib/store";
+
+/**
+ * Turns a custom event into a goal from its row. The event is already chosen,
+ * so all that is left to decide is the goal's name: an event goal on this
+ * name, created through the same mutation as the Goals page.
+ */
+export function CreateGoalPopover({ eventName }: { eventName: string }) {
+ const t = useExtracted();
+ const site = useStore(state => state.site);
+ const createGoal = useCreateGoal();
+ const [open, setOpen] = useState(false);
+ const [name, setName] = useState(eventName);
+ const inputId = useId();
+
+ const submit = async (event: FormEvent) => {
+ event.preventDefault();
+ try {
+ await createGoal.mutateAsync({
+ siteId: Number(site),
+ name: name.trim() || undefined,
+ goalType: "event",
+ config: { eventName },
+ });
+ toast.success(t("Goal created"));
+ setOpen(false);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : t("Failed to save goal"));
+ }
+ };
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={next => {
+ setOpen(next);
+ if (next) setName(eventName);
+ }}
+ >
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ className="-ml-1.5 gap-1 font-normal text-neutral-500 dark:text-neutral-400"
+ >
+ <Plus />
+ {t("Create goal")}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-72">
+ <form onSubmit={submit} className="space-y-3">
+ <div className="space-y-1.5">
+ <Label htmlFor={inputId}>{t("Goal name")}</Label>
+ <Input
+ id={inputId}
+ value={name}
+ onChange={event => setName(event.target.value)}
+ placeholder={eventName}
+ autoComplete="off"
+ />
+ </div>
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">
+ {t.rich("A session converts when <name></name> fires in it.", {
+ name: () => <span className="font-mono text-neutral-900 dark:text-neutral-100">{eventName}</span>,
+ })}
+ </p>
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="outline" size="sm" onClick={() => setOpen(false)}>
+ {t("Cancel")}
+ </Button>
+ <Button
+ type="submit"
+ variant="accent"
+ size="sm"
+ loading={createGoal.isPending}
+ loadingLabel={t("Saving...")}
+ >
+ {t("Create goal")}
+ </Button>
+ </div>
+ </form>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/client/src/app/[site]/events/components/EventNames/EventNamesCard.tsx b/client/src/app/[site]/events/components/EventNames/EventNamesCard.tsx
new file mode 100644
index 000000000..35efb665b
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventNames/EventNamesCard.tsx
@@ -0,0 +1,306 @@
+"use client";
+
+import { BookOpen, ChevronDown, ChevronUp } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { ReactNode, useState } from "react";
+
+import { EventTrendBucket } from "@/api/analytics/endpoints";
+import { useGetAutocaptureEvents } from "@/api/analytics/hooks/events/useGetAutocaptureEvents";
+import { useGetOutboundLinks } from "@/api/analytics/hooks/events/useGetOutboundLinks";
+import { useGetFunnels } from "@/api/analytics/hooks/funnels/useGetFunnels";
+import { useGetGoals } from "@/api/analytics/hooks/goals/useGetGoals";
+import { ErrorState } from "@/components/ErrorState";
+import { ExternalLink } from "@/components/ExternalLink";
+import { SegmentedControl } from "@/components/interior/segmented-control";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { useCanOnSite } from "@/hooks/usePermissions";
+import { useComparisonEnabled, useStore } from "@/lib/store";
+import { EventNameRow, EventNameSortKey, filterEventNameRows, sortEventNameRows } from "../../utils/eventNameRows";
+import { formatShare } from "../../utils/properties";
+import { AutocaptureRow, AutocaptureTable } from "./AutocaptureTable";
+import { EventNamesSort, EventNamesTable, EventNamesTableSkeleton } from "./EventNamesTable";
+
+type Kind = "events" | "outbound" | "button_click" | "form_submit" | "copy";
+
+// Rows on show before "Show all".
+const ROW_LIMIT = 8;
+// The goals endpoint's largest page.
+const GOALS_PAGE_SIZE = 100;
+
+// The first click on a column sorts it this way: biggest first, except names.
+const FIRST_DIRECTION: Record<EventNameSortKey, "asc" | "desc"> = {
+ name: "asc",
+ count: "desc",
+ users: "desc",
+ perUser: "desc",
+ change: "desc",
+ lastSeen: "desc",
+};
+
+function Message({ title, children }: { title: string; children?: ReactNode }) {
+ return (
+ <div className="flex flex-col items-center justify-center gap-1 px-4 py-10 text-center">
+ <p className="text-sm font-medium text-neutral-900 dark:text-neutral-100">{title}</p>
+ {children && <div className="text-sm text-neutral-500 dark:text-neutral-400">{children}</div>}
+ </div>
+ );
+}
+
+/** "8 of 24. The other 16 account for …" and the switch between the short list and all of it. */
+function ListFooter({
+ shown,
+ total,
+ restEvents,
+ restShare,
+ expanded,
+ onToggle,
+}: {
+ shown: number;
+ total: number;
+ /** Events in the rows that are not on show. */
+ restEvents: number;
+ restShare: number;
+ expanded: boolean;
+ onToggle: () => void;
+}) {
+ const t = useExtracted();
+ if (total <= ROW_LIMIT) return null;
+
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-2 border-t border-neutral-100 px-4 py-2 text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400">
+ <span>
+ {expanded
+ ? t("All {total} shown.", { total: total.toLocaleString() })
+ : t("{shown} of {total}. The other {rest} account for {events} events ({share}).", {
+ shown: shown.toLocaleString(),
+ total: total.toLocaleString(),
+ rest: (total - shown).toLocaleString(),
+ events: restEvents.toLocaleString(),
+ share: formatShare(restShare),
+ })}
+ </span>
+ <Button type="button" variant="ghost" size="xs" className="gap-1" onClick={onToggle}>
+ {expanded ? t("Show fewer") : t("Show all {total}", { total: total.toLocaleString() })}
+ {expanded ? <ChevronUp /> : <ChevronDown />}
+ </Button>
+ </div>
+ );
+}
+
+interface EventNamesCardProps {
+ /** Every custom event name in the period, biggest first. */
+ rows: EventNameRow[];
+ /** No answer yet, including while the request waits for the site. */
+ isLoading: boolean;
+ isError: boolean;
+ trendBucket: EventTrendBucket;
+ /** Names that used to fire daily and have stopped. */
+ silentEvents: ReadonlySet<string>;
+}
+
+/**
+ * What fired in the period: the custom event names with who fired them and how
+ * that is moving, and the autocaptured events grouped by what was clicked,
+ * submitted or copied.
+ */
+export function EventNamesCard({ rows, isLoading, isError, trendBucket, silentEvents }: EventNamesCardProps) {
+ const t = useExtracted();
+ const privateKey = useStore(state => state.privateKey);
+ const comparisonEnabled = useComparisonEnabled();
+ const canWriteGoals = useCanOnSite("goals:write");
+
+ const [kind, setKind] = useState<Kind>("events");
+ const [search, setSearch] = useState("");
+ const [expanded, setExpanded] = useState(false);
+ const [sort, setSort] = useState<EventNamesSort>({ key: "count", direction: "desc" });
+
+ const goals = useGetGoals({ pageSize: GOALS_PAGE_SIZE });
+ const funnels = useGetFunnels();
+ const outbound = useGetOutboundLinks();
+ const buttons = useGetAutocaptureEvents("button_click");
+ const forms = useGetAutocaptureEvents("form_submit");
+ const copies = useGetAutocaptureEvents("copy");
+
+ const autocapture: Record<
+ Exclude<Kind, "events">,
+ { rows: AutocaptureRow[] | undefined; isLoading: boolean; isError: boolean; valueLabel: string }
+ > = {
+ outbound: {
+ rows: outbound.data?.map(link => ({ value: String(link.url), count: link.count, lastSeen: link.lastClicked })),
+ isLoading: outbound.isPending,
+ isError: outbound.isError,
+ valueLabel: t("Link"),
+ },
+ button_click: {
+ rows: buttons.data?.map(row => ({ value: row.value, count: row.count, lastSeen: row.lastOccurred })),
+ isLoading: buttons.isPending,
+ isError: buttons.isError,
+ valueLabel: t("Button text"),
+ },
+ form_submit: {
+ rows: forms.data?.map(row => ({ value: row.value, count: row.count, lastSeen: row.lastOccurred })),
+ isLoading: forms.isPending,
+ isError: forms.isError,
+ valueLabel: t("Form"),
+ },
+ copy: {
+ rows: copies.data?.map(row => ({ value: row.value, count: row.count, lastSeen: row.lastOccurred })),
+ isLoading: copies.isPending,
+ isError: copies.isError,
+ valueLabel: t("Copied text"),
+ },
+ };
+
+ const tab = (label: string, count: number | undefined) => (
+ <>
+ {label}
+ {count !== undefined && <span className="tabular-nums opacity-60">{count.toLocaleString()}</span>}
+ </>
+ );
+ const options: { value: Kind; label: ReactNode }[] = [
+ { value: "events", label: tab(t("Custom events"), isLoading || isError ? undefined : rows.length) },
+ { value: "outbound", label: tab(t("Outbound links"), autocapture.outbound.rows?.length) },
+ { value: "button_click", label: tab(t("Button clicks"), autocapture.button_click.rows?.length) },
+ { value: "form_submit", label: tab(t("Form submits"), autocapture.form_submit.rows?.length) },
+ { value: "copy", label: tab(t("Copies"), autocapture.copy.rows?.length) },
+ ];
+
+ const changeSort = (key: EventNameSortKey) =>
+ setSort(current =>
+ current.key === key
+ ? { key, direction: current.direction === "asc" ? "desc" : "asc" }
+ : { key, direction: FIRST_DIRECTION[key] }
+ );
+
+ const errorState = (
+ <ErrorState
+ title={t("Failed to load events")}
+ message={t("There was a problem fetching the events. Please try again later.")}
+ />
+ );
+ const noMatch = <Message title={t('Nothing matches "{search}"', { search: search.trim() })} />;
+
+ let body: ReactNode;
+ if (kind === "events") {
+ const matching = sortEventNameRows(filterEventNameRows(rows, search), sort.key, sort.direction);
+ const shown = expanded ? matching : matching.slice(0, ROW_LIMIT);
+ const total = rows.reduce((sum, row) => sum + row.count, 0);
+ const restEvents = matching.slice(shown.length).reduce((sum, row) => sum + row.count, 0);
+
+ body = isLoading ? (
+ <EventNamesTableSkeleton />
+ ) : isError ? (
+ errorState
+ ) : rows.length === 0 ? (
+ <Message title={t("No custom events in this period")}>
+ <p>{t("Try a different date range or filter.")}</p>
+ <ExternalLink href="https://www.rybbit.com/docs/track-events" className="mt-2 inline-flex items-center gap-1">
+ <BookOpen className="h-4 w-4" />
+ {t("Learn how to track events")}
+ </ExternalLink>
+ </Message>
+ ) : matching.length === 0 ? (
+ noMatch
+ ) : (
+ <>
+ <EventNamesTable
+ rows={shown}
+ maxCount={Math.max(...rows.map(row => row.count), 0)}
+ sort={sort}
+ onSort={changeSort}
+ trendBucket={trendBucket}
+ goals={goals.data?.data}
+ funnels={funnels.data}
+ isLoadingUsedIn={goals.isLoading || funnels.isLoading}
+ // Without the goal list there is no telling whether the event already has one.
+ canCreateGoal={canWriteGoals && !privateKey && goals.isSuccess}
+ silentEvents={silentEvents}
+ showChange={comparisonEnabled}
+ />
+ <ListFooter
+ shown={shown.length}
+ total={matching.length}
+ restEvents={restEvents}
+ restShare={total > 0 ? restEvents / total : 0}
+ expanded={expanded}
+ onToggle={() => setExpanded(current => !current)}
+ />
+ </>
+ );
+ } else {
+ const list = autocapture[kind];
+ const all = list.rows ?? [];
+ const query = search.trim().toLowerCase();
+ const matching = query ? all.filter(row => row.value.toLowerCase().includes(query)) : all;
+ const shown = expanded ? matching : matching.slice(0, ROW_LIMIT);
+ const total = all.reduce((sum, row) => sum + row.count, 0);
+ const restEvents = matching.slice(shown.length).reduce((sum, row) => sum + row.count, 0);
+
+ body = list.isLoading ? (
+ <EventNamesTableSkeleton />
+ ) : list.isError ? (
+ errorState
+ ) : all.length === 0 ? (
+ <Message title={t("Nothing captured in this period")}>
+ <p>{t("Try a different date range or filter.")}</p>
+ </Message>
+ ) : matching.length === 0 ? (
+ noMatch
+ ) : (
+ <>
+ <AutocaptureTable
+ rows={shown}
+ maxCount={Math.max(...all.map(row => row.count), 0)}
+ total={total}
+ valueLabel={list.valueLabel}
+ links={kind === "outbound"}
+ />
+ <ListFooter
+ shown={shown.length}
+ total={matching.length}
+ restEvents={restEvents}
+ restShare={total > 0 ? restEvents / total : 0}
+ expanded={expanded}
+ onToggle={() => setExpanded(current => !current)}
+ />
+ </>
+ );
+ }
+
+ return (
+ <Card>
+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2 px-3 py-2.5">
+ <div className="flex min-w-0 max-w-full flex-wrap items-center gap-x-3 gap-y-2">
+ <h2 className="pl-1 text-base font-semibold leading-none tracking-tight">{t("Event names")}</h2>
+ <div className="max-w-full overflow-x-auto">
+ <SegmentedControl
+ size="sm"
+ aria-label={t("Kind of event")}
+ options={options}
+ value={kind}
+ onValueChange={next => {
+ setKind(next);
+ setExpanded(false);
+ setSearch("");
+ }}
+ />
+ </div>
+ </div>
+ <div className="w-full sm:w-56">
+ <Input
+ isSearch
+ inputSize="sm"
+ className="h-8"
+ value={search}
+ onChange={event => setSearch(event.target.value)}
+ placeholder={kind === "events" ? t("Search event names") : t("Search")}
+ aria-label={kind === "events" ? t("Search event names") : t("Search")}
+ />
+ </div>
+ </div>
+ {body}
+ </Card>
+ );
+}
diff --git a/client/src/app/[site]/events/components/EventNames/EventNamesTable.tsx b/client/src/app/[site]/events/components/EventNames/EventNamesTable.tsx
new file mode 100644
index 000000000..d950cdf20
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventNames/EventNamesTable.tsx
@@ -0,0 +1,328 @@
+"use client";
+
+import { Filter } from "@rybbit/shared";
+import { useMeasure } from "@uidotdev/usehooks";
+import { ArrowDown, ArrowUp, ChevronDown, ChevronRight, TriangleAlert } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { Fragment, ReactNode, useState } from "react";
+
+import { EventTrendBucket, Goal, SavedFunnel } from "@/api/analytics/endpoints";
+import { Delta } from "@/components/site/Delta";
+import { PivotActions } from "@/components/site/PivotActions";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
+import { percentDelta } from "@/lib/delta";
+import { addFilter, getTimezone } from "@/lib/store";
+import { cn } from "@/lib/utils";
+import { EventNameRow, EventNameSortKey, SortDirection } from "../../utils/eventNameRows";
+import { formatShare } from "../../utils/properties";
+import { funnelsForEvent, goalsForEvent } from "../../utils/usedIn";
+import { COLUMN, visibleColumnCount } from "./columns";
+import { EventPropertyBreakdown } from "./EventPropertyBreakdown";
+import { EventSparkline } from "./EventSparkline";
+import { UsedIn } from "./UsedIn";
+
+const eventFilter = (eventName: string): Filter[] => [{ parameter: "event_name", type: "equals", value: [eventName] }];
+
+export interface EventNamesSort {
+ key: EventNameSortKey;
+ direction: SortDirection;
+}
+
+interface EventNamesTableProps {
+ rows: EventNameRow[];
+ /** The largest count among every name, so bars keep their scale when the list is cut or searched. */
+ maxCount: number;
+ sort: EventNamesSort;
+ onSort: (key: EventNameSortKey) => void;
+ trendBucket: EventTrendBucket;
+ /** Undefined while loading, or when the viewer may not read them. */
+ goals: Goal[] | undefined;
+ funnels: SavedFunnel[] | undefined;
+ isLoadingUsedIn: boolean;
+ canCreateGoal: boolean;
+ /** Names that used to fire daily and have stopped. */
+ silentEvents: ReadonlySet<string>;
+ /** The comparison is on: draw the change column. */
+ showChange: boolean;
+}
+
+function SortHeader({
+ label,
+ sortKey,
+ sort,
+ onSort,
+ align = "left",
+}: {
+ label: string;
+ sortKey: EventNameSortKey;
+ sort: EventNamesSort;
+ onSort: (key: EventNameSortKey) => void;
+ align?: "left" | "right";
+}) {
+ const active = sort.key === sortKey;
+ const Arrow = sort.direction === "asc" ? ArrowUp : ArrowDown;
+
+ return (
+ <button
+ type="button"
+ onClick={() => onSort(sortKey)}
+ className={cn(
+ "inline-flex cursor-pointer items-center gap-1 whitespace-nowrap hover:text-neutral-900 dark:hover:text-neutral-100",
+ align === "right" && "flex-row-reverse",
+ active && "text-neutral-900 dark:text-neutral-100"
+ )}
+ >
+ {label}
+ {active && <Arrow className="h-3 w-3" aria-hidden="true" />}
+ </button>
+ );
+}
+
+export function EventNamesTable({
+ rows,
+ maxCount,
+ sort,
+ onSort,
+ trendBucket,
+ goals,
+ funnels,
+ isLoadingUsedIn,
+ canCreateGoal,
+ silentEvents,
+ showChange,
+}: EventNamesTableProps) {
+ const t = useExtracted();
+ const { formatRelative, formatDateTime } = useDateTimeFormat();
+ const [expanded, setExpanded] = useState<string | null>(null);
+ const [containerRef, { width: containerWidth }] = useMeasure<HTMLDivElement>();
+ const timezone = getTimezone();
+
+ const trendLabels: Record<EventTrendBucket, string> = {
+ hour: t("Events per hour"),
+ day: t("Events per day"),
+ week: t("Events per week"),
+ month: t("Events per month"),
+ };
+
+ const header = (key: EventNameSortKey, label: string, align: "left" | "right" = "left"): ReactNode => (
+ <SortHeader label={label} sortKey={key} sort={sort} onSort={onSort} align={align} />
+ );
+ const ariaSort = (key: EventNameSortKey) =>
+ sort.key === key ? (sort.direction === "asc" ? "ascending" : "descending") : undefined;
+
+ return (
+ <div ref={containerRef} className="@container">
+ <Table className="table-fixed">
+ <TableHeader>
+ <TableRow className="hover:bg-transparent dark:hover:bg-transparent">
+ <TableHead className="rounded-none pl-3 first:rounded-none" aria-sort={ariaSort("name")}>
+ {header("name", t("Event"))}
+ </TableHead>
+ <TableHead className="w-[120px] @min-[480px]:w-[196px]" aria-sort={ariaSort("count")}>
+ {header("count", t("Events"))}
+ </TableHead>
+ <TableHead className={cn("w-[72px] text-right", COLUMN.users)} aria-sort={ariaSort("users")}>
+ {header("users", t("Users"), "right")}
+ </TableHead>
+ <TableHead className={cn("w-[84px] text-right", COLUMN.perUser)} aria-sort={ariaSort("perUser")}>
+ {header("perUser", t("Per user"), "right")}
+ </TableHead>
+ <TableHead className={cn("w-[112px] pl-4", COLUMN.trend)}>{t("Trend")}</TableHead>
+ {showChange && (
+ <TableHead className={cn("w-[84px]", COLUMN.change)} aria-sort={ariaSort("change")}>
+ {header("change", t("Change"))}
+ </TableHead>
+ )}
+ <TableHead className={cn("w-[112px]", COLUMN.lastSeen)} aria-sort={ariaSort("lastSeen")}>
+ {header("lastSeen", t("Last seen"))}
+ </TableHead>
+ <TableHead className={cn("w-[232px]", COLUMN.usedIn)}>{t("Used in")}</TableHead>
+ <TableHead className={cn("w-[84px] rounded-none pr-3 text-right last:rounded-none", COLUMN.people)}>
+ {t("People")}
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map(row => {
+ const isOpen = expanded === row.eventName;
+ const isSilent = silentEvents.has(row.eventName);
+ const eventGoals = goalsForEvent(goals, row.eventName);
+ const eventFunnels = funnelsForEvent(funnels, row.eventName);
+ const lastSeen = row.lastSeen?.setZone(timezone) ?? null;
+ const peak = Math.max(...row.trend, 0);
+ const usedIn = (
+ <UsedIn
+ eventName={row.eventName}
+ goals={eventGoals}
+ funnels={eventFunnels}
+ isLoading={isLoadingUsedIn}
+ canCreateGoal={canCreateGoal}
+ />
+ );
+
+ return (
+ <Fragment key={row.eventName}>
+ <TableRow
+ className={cn(
+ "group h-11",
+ isOpen &&
+ "border-b-0 bg-neutral-50 hover:bg-neutral-50 dark:bg-neutral-850/50 dark:hover:bg-neutral-850/50"
+ )}
+ >
+ <TableCell className="pl-3">
+ <div className="flex min-w-0 items-center gap-2">
+ <button
+ type="button"
+ aria-expanded={isOpen}
+ aria-label={
+ isOpen
+ ? t("Hide the properties of {name}", { name: row.eventName })
+ : t("Show the properties of {name}", { name: row.eventName })
+ }
+ onClick={() => setExpanded(isOpen ? null : row.eventName)}
+ className="shrink-0 cursor-pointer text-neutral-500 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-neutral-100"
+ >
+ {isOpen ? (
+ <ChevronDown className="h-4 w-4" strokeWidth={2.5} />
+ ) : (
+ <ChevronRight className="h-4 w-4" strokeWidth={2.5} />
+ )}
+ </button>
+ <button
+ type="button"
+ title={t("Filter by {name}", { name: row.eventName })}
+ onClick={() => addFilter(eventFilter(row.eventName)[0])}
+ className="min-w-0 cursor-pointer truncate text-left font-medium text-neutral-900 hover:underline dark:text-neutral-100"
+ >
+ {row.eventName}
+ </button>
+ </div>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2.5">
+ <span className="min-w-11 text-right font-medium tabular-nums" title={row.count.toLocaleString()}>
+ {row.count.toLocaleString()}
+ </span>
+ <div className="relative hidden h-1.5 min-w-0 flex-1 rounded-full bg-neutral-100 dark:bg-neutral-800 @min-[480px]:block">
+ <div
+ className="absolute inset-y-0 left-0 rounded-full bg-dataviz"
+ style={{ width: `${maxCount > 0 ? (row.count / maxCount) * 100 : 0}%` }}
+ />
+ </div>
+ <span className="w-11 text-right text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
+ {formatShare(row.share)}
+ </span>
+ </div>
+ </TableCell>
+ <TableCell className={cn("text-right tabular-nums", COLUMN.users)}>
+ {row.users.toLocaleString()}
+ </TableCell>
+ <TableCell
+ className={cn("text-right tabular-nums text-neutral-600 dark:text-neutral-300", COLUMN.perUser)}
+ >
+ {row.perUser.toFixed(2)}
+ </TableCell>
+ <TableCell className={cn("pl-4", COLUMN.trend)}>
+ <EventSparkline
+ values={row.trend}
+ muted={isSilent}
+ label={t("{metric}, peak {peak}", {
+ metric: trendLabels[trendBucket],
+ peak: peak.toLocaleString(),
+ })}
+ />
+ </TableCell>
+ {showChange && (
+ <TableCell className={COLUMN.change}>
+ <Delta value={percentDelta(row.count, row.previousCount)} />
+ </TableCell>
+ )}
+ <TableCell className={cn("whitespace-nowrap text-xs tabular-nums", COLUMN.lastSeen)}>
+ {lastSeen ? (
+ <span
+ title={formatDateTime(lastSeen, {
+ dateStyle: "medium",
+ timeStyle: "medium",
+ timeZone: timezone,
+ })}
+ className={cn(
+ "inline-flex items-center gap-1",
+ isSilent
+ ? "font-medium text-yellow-600 dark:text-yellow-400"
+ : "text-neutral-600 dark:text-neutral-300"
+ )}
+ >
+ {isSilent && <TriangleAlert className="h-3 w-3" aria-hidden="true" />}
+ {formatRelative(lastSeen)}
+ </span>
+ ) : (
+ <span className="text-neutral-400 dark:text-neutral-500">—</span>
+ )}
+ </TableCell>
+ <TableCell className={COLUMN.usedIn}>{usedIn}</TableCell>
+ <TableCell className={cn("pr-3", COLUMN.people)}>
+ <PivotActions
+ filters={eventFilter(row.eventName)}
+ showLabels={false}
+ className="flex-nowrap justify-end opacity-60 transition-opacity focus-within:opacity-100 group-hover:opacity-100"
+ />
+ </TableCell>
+ </TableRow>
+ {isOpen && (
+ <TableRow className="bg-neutral-50 hover:bg-neutral-50 dark:bg-neutral-850/50 dark:hover:bg-neutral-850/50">
+ <TableCell colSpan={visibleColumnCount(containerWidth, showChange)} className="p-0">
+ <div className="space-y-3 px-3 pb-3.5 pt-1 md:pl-9">
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1">
+ <div className="text-xs text-neutral-500 dark:text-neutral-400">
+ {t.rich("Properties sent with <name></name>, as a share of its events.", {
+ name: () => (
+ <span className="font-medium text-neutral-800 dark:text-neutral-200">
+ {row.eventName}
+ </span>
+ ),
+ })}
+ </div>
+ <PivotActions
+ filters={eventFilter(row.eventName)}
+ actions={["sessions", "users", "replays", "segment"]}
+ />
+ </div>
+ {/* The column that holds these is hidden at this width. */}
+ <div className="flex items-center gap-2 text-xs text-neutral-500 dark:text-neutral-400 @min-[1120px]:hidden">
+ <span className="shrink-0">{t("Used in")}</span>
+ {usedIn}
+ </div>
+ <EventPropertyBreakdown eventName={row.eventName} eventCount={row.count} />
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </Fragment>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
+
+export function EventNamesTableSkeleton({ rows = 8 }: { rows?: number }) {
+ return (
+ <div>
+ <div className="h-8 bg-neutral-50 dark:bg-neutral-850" />
+ {Array.from({ length: rows }).map((_, index) => (
+ <div
+ key={index}
+ className="flex h-11 items-center gap-4 border-b border-neutral-100 px-3 last:border-b-0 dark:border-neutral-800"
+ >
+ <Skeleton className="h-4 w-4 rounded" />
+ <Skeleton className="h-4 rounded" style={{ width: `${28 - index * 2}%` }} />
+ <Skeleton className="ml-auto h-4 w-40 rounded" />
+ <Skeleton className="hidden h-4 w-64 rounded md:block" />
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/events/components/EventNames/EventPropertyBreakdown.tsx b/client/src/app/[site]/events/components/EventNames/EventPropertyBreakdown.tsx
new file mode 100644
index 000000000..ba960e6ef
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventNames/EventPropertyBreakdown.tsx
@@ -0,0 +1,140 @@
+"use client";
+
+import { useExtracted } from "next-intl";
+import { useState } from "react";
+
+import { useGetEventProperties } from "@/api/analytics/hooks/events/useGetEventProperties";
+import { Skeleton } from "@/components/ui/skeleton";
+import { formatShare, groupProperties, PropertyGroup } from "../../utils/properties";
+
+// The properties endpoint stops at this many (key, value) rows.
+const PROPERTY_ROW_LIMIT = 500;
+const VALUES_SHOWN = 5;
+
+function PropertyColumn({
+ group,
+ eventCount,
+ showCoverage,
+}: {
+ group: PropertyGroup;
+ eventCount: number;
+ showCoverage: boolean;
+}) {
+ const t = useExtracted();
+ const [showAll, setShowAll] = useState(false);
+ const values = showAll ? group.values : group.values.slice(0, VALUES_SHOWN);
+ const more = group.values.length - VALUES_SHOWN;
+ // An event carries one value per key, so the values add up to the events that sent the key.
+ const coverage = eventCount > 0 ? Math.min(group.total / eventCount, 1) : 0;
+
+ return (
+ <div className="min-w-0">
+ <div className="flex items-center justify-between gap-2 border-b border-neutral-100 pb-1.5 text-xs dark:border-neutral-800">
+ <span className="truncate font-mono font-medium text-neutral-900 dark:text-neutral-100" title={group.key}>
+ {group.key}
+ </span>
+ <span className="shrink-0 text-neutral-500 dark:text-neutral-400">
+ {showCoverage
+ ? t("{count, plural, one {# value} other {# values}} · on {share} of events", {
+ count: group.values.length,
+ share: formatShare(coverage),
+ })
+ : t("{count, plural, one {# value} other {# values}}", { count: group.values.length })}
+ </span>
+ </div>
+ <div className="mt-1.5 space-y-1">
+ {values.map(property => {
+ const share = eventCount > 0 ? Math.min(property.count / eventCount, 1) : 0;
+ const value = String(property.propertyValue);
+ return (
+ <div key={value} className="relative flex h-7 items-center rounded-md px-2 text-xs">
+ <div
+ className="absolute inset-y-0 left-0 rounded-md bg-dataviz opacity-25"
+ style={{ width: `${share * 100}%` }}
+ />
+ <div className="relative flex w-full items-center justify-between gap-2">
+ <span className="truncate text-neutral-900 dark:text-neutral-100" title={value}>
+ {value === "" ? t("(empty)") : value}
+ </span>
+ <span className="flex shrink-0 gap-2 tabular-nums text-neutral-900 dark:text-neutral-100">
+ <span>{formatShare(share)}</span>
+ <span className="min-w-10 text-right font-medium">{property.count.toLocaleString()}</span>
+ </span>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ {more > 0 && (
+ <button
+ type="button"
+ onClick={() => setShowAll(current => !current)}
+ className="mt-1 cursor-pointer px-2 text-xs text-neutral-500 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-neutral-100"
+ >
+ {showAll
+ ? t("Show fewer")
+ : t("{count, plural, one {Show # more value} other {Show # more values}}", { count: more })}
+ </button>
+ )}
+ </div>
+ );
+}
+
+interface EventPropertyBreakdownProps {
+ eventName: string;
+ /** The event's count in the period: what the value shares are out of. */
+ eventCount: number;
+}
+
+/** What an event was sent with: each property key and how its values split. */
+export function EventPropertyBreakdown({ eventName, eventCount }: EventPropertyBreakdownProps) {
+ const t = useExtracted();
+ const { data, isLoading, isError } = useGetEventProperties(eventName);
+
+ if (isLoading) {
+ return (
+ <div className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
+ {Array.from({ length: 3 }).map((_, column) => (
+ <div key={column} className="space-y-1.5">
+ <Skeleton className="h-4 w-28 rounded" />
+ {Array.from({ length: 3 }).map((_, row) => (
+ <Skeleton key={row} className="h-7 w-full rounded-md" />
+ ))}
+ </div>
+ ))}
+ </div>
+ );
+ }
+
+ if (isError) {
+ return <p className="text-xs text-neutral-500 dark:text-neutral-400">{t("Could not load the properties.")}</p>;
+ }
+
+ const groups = groupProperties(data ?? []);
+ if (groups.length === 0) {
+ return (
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">
+ {t("No properties were sent with this event in this period.")}
+ </p>
+ );
+ }
+
+ // Past the cap the last keys are cut short, so neither their value counts
+ // nor their coverage can be trusted.
+ const truncated = (data?.length ?? 0) >= PROPERTY_ROW_LIMIT;
+
+ return (
+ <div>
+ <div className="grid grid-cols-1 gap-x-6 gap-y-4 md:grid-cols-2 xl:grid-cols-3">
+ {groups.map(group => (
+ <PropertyColumn key={group.key} group={group} eventCount={eventCount} showCoverage={!truncated} />
+ ))}
+ </div>
+ {truncated && (
+ <p className="mt-3 text-xs text-neutral-500 dark:text-neutral-400">
+ {t("Showing the first {count} property values.", { count: PROPERTY_ROW_LIMIT.toLocaleString() })}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/events/components/EventNames/EventSparkline.tsx b/client/src/app/[site]/events/components/EventNames/EventSparkline.tsx
new file mode 100644
index 000000000..86b7337a4
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventNames/EventSparkline.tsx
@@ -0,0 +1,62 @@
+import { cn } from "@/lib/utils";
+
+const WIDTH = 84;
+const HEIGHT = 24;
+// Keeps the stroke inside the box at the peak and at zero.
+const PAD = 2;
+
+interface EventSparklineProps {
+ /** One value per bucket, oldest first. */
+ values: number[];
+ /** Read out in place of the drawing, e.g. "Events per day, peak 142". */
+ label: string;
+ /** Draws in neutral instead of the data hue: an event that has stopped. */
+ muted?: boolean;
+ className?: string;
+}
+
+/**
+ * A row's trend. Plain SVG rather than a chart instance: the table can hold a
+ * thousand of these, and they need neither axes nor a tooltip.
+ */
+export function EventSparkline({ values, label, muted = false, className }: EventSparklineProps) {
+ if (values.length < 2) {
+ return (
+ <div
+ className={cn("h-px w-[84px] bg-neutral-200 dark:bg-neutral-800", className)}
+ role="img"
+ aria-label={label}
+ />
+ );
+ }
+
+ const max = Math.max(...values, 1);
+ const step = WIDTH / (values.length - 1);
+ const points = values.map((value, index) => {
+ const x = index * step;
+ const y = HEIGHT - PAD - (value / max) * (HEIGHT - PAD * 2);
+ return `${x.toFixed(2)},${y.toFixed(2)}`;
+ });
+ const color = muted ? "hsl(var(--neutral-400))" : "hsl(var(--dataviz))";
+
+ return (
+ <svg
+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}
+ width={WIDTH}
+ height={HEIGHT}
+ className={cn("block overflow-visible", className)}
+ role="img"
+ aria-label={label}
+ >
+ <title>{label}</title>
+ <polyline
+ points={points.join(" ")}
+ fill="none"
+ stroke={color}
+ strokeWidth={1.5}
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ />
+ </svg>
+ );
+}
diff --git a/client/src/app/[site]/events/components/EventNames/UsedIn.test.tsx b/client/src/app/[site]/events/components/EventNames/UsedIn.test.tsx
new file mode 100644
index 000000000..151d90dd7
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventNames/UsedIn.test.tsx
@@ -0,0 +1,144 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Goal, SavedFunnel } from "@/api/analytics/endpoints";
+import { useStore } from "@/lib/store";
+import { UsedIn } from "./UsedIn";
+
+const mocks = vi.hoisted(() => ({ search: "" }));
+
+vi.mock("next-intl", () => ({
+ // Enough ICU for the strings under test: {count} and "{count, plural, one {# x} other {# xs}}".
+ useExtracted: () => (message: string, values?: Record<string, string | number>) =>
+ message
+ .replace(/\{(\w+), plural, one \{([^}]*)\} other \{([^}]*)\}\}/g, (_match, key, one, other) =>
+ (Number(values?.[key]) === 1 ? one : other).replace("#", String(values?.[key]))
+ )
+ .replace(/\{(\w+)\}/g, (_match, key) => String(values?.[key])),
+}));
+
+vi.mock("next/navigation", () => ({
+ useSearchParams: () => new URLSearchParams(mocks.search),
+}));
+
+vi.mock("next/link", () => ({
+ default: ({ href, children, prefetch, ...props }: { href: string; children: ReactNode; prefetch?: boolean }) => (
+ <a href={href} data-prefetch={String(prefetch)} {...props}>
+ {children}
+ </a>
+ ),
+}));
+
+vi.mock("./CreateGoalPopover", () => ({
+ CreateGoalPopover: ({ eventName }: { eventName: string }) => (
+ <button type="button">Create goal for {eventName}</button>
+ ),
+}));
+
+const goal = (goalId: number, name: string | null): Goal => ({
+ goalId,
+ name,
+ goalType: "event",
+ config: { eventName: "signup" },
+ createdAt: "2026-01-01",
+ total_conversions: 0,
+ total_sessions: 0,
+ conversion_rate: 0,
+});
+
+const funnel = (id: number, name: string): SavedFunnel => ({
+ id,
+ name,
+ steps: [{ type: "event", value: "signup" }],
+ createdAt: "2026-01-01",
+ updatedAt: "2026-01-01",
+ conversionRate: null,
+ totalVisitors: null,
+});
+
+const renderUsedIn = (props: Partial<Parameters<typeof UsedIn>[0]> = {}) =>
+ render(<UsedIn eventName="signup" goals={[]} funnels={[]} isLoading={false} canCreateGoal={true} {...props} />);
+
+describe("UsedIn", () => {
+ beforeEach(() => {
+ mocks.search = "";
+ useStore.setState({ site: "81", privateKey: null });
+ });
+ afterEach(cleanup);
+
+ it("offers to create a goal for an event nothing measures", () => {
+ renderUsedIn();
+
+ expect(screen.getByRole("button", { name: "Create goal for signup" })).toBeTruthy();
+ expect(screen.queryByRole("link")).toBeNull();
+ });
+
+ it("offers nothing to a viewer who cannot create goals", () => {
+ renderUsedIn({ canCreateGoal: false });
+
+ expect(screen.queryByRole("button")).toBeNull();
+ expect(screen.getByText("—")).toBeTruthy();
+ });
+
+ it("shows neither chips nor the offer while goals and funnels load", () => {
+ renderUsedIn({ isLoading: true });
+
+ expect(screen.queryByRole("button")).toBeNull();
+ expect(screen.queryByRole("link")).toBeNull();
+ });
+
+ it("names a single goal and links it to the Goals page", () => {
+ renderUsedIn({ goals: [goal(1, "Signup")] });
+
+ const link = screen.getByRole("link", { name: "Signup" });
+ expect(link.getAttribute("href")).toBe("/81/goals");
+ expect(screen.queryByRole("button")).toBeNull();
+ });
+
+ it("falls back to the event name for a goal without one", () => {
+ renderUsedIn({ goals: [goal(1, null)] });
+
+ expect(screen.getByRole("link", { name: "signup" })).toBeTruthy();
+ });
+
+ it("counts several goals and lists them in the hover text", () => {
+ renderUsedIn({ goals: [goal(1, "Signup"), goal(2, "Signup with Google")] });
+
+ const link = screen.getByRole("link", { name: "2 goals" });
+ expect(link.getAttribute("title")).toBe("Signup, Signup with Google");
+ });
+
+ it("names a lone funnel when there is no goal beside it", () => {
+ renderUsedIn({ funnels: [funnel(1, "Visit to paid")] });
+
+ expect(screen.getByRole("link", { name: "Visit to paid" }).getAttribute("href")).toBe("/81/funnels");
+ });
+
+ it("counts funnels beside a goal, and when there are several", () => {
+ renderUsedIn({ goals: [goal(1, "Signup")], funnels: [funnel(1, "Visit to paid")] });
+ expect(screen.getByRole("link", { name: "1 funnel" })).toBeTruthy();
+ cleanup();
+
+ renderUsedIn({ funnels: [funnel(1, "Visit to paid"), funnel(2, "Demo to signup")] });
+ expect(screen.getByRole("link", { name: "2 funnels" }).getAttribute("title")).toBe("Visit to paid, Demo to signup");
+ });
+
+ it("keeps the period, the filters and a private link's key on the way out", () => {
+ mocks.search = "timeMode=range&startDate=2026-09-01&endDate=2026-09-30";
+ useStore.setState({ site: "81", privateKey: "a1b2c3d4e5f6" });
+ renderUsedIn({ goals: [goal(1, "Signup")], funnels: [funnel(1, "Visit to paid")] });
+
+ expect(screen.getByRole("link", { name: "Signup" }).getAttribute("href")).toBe(
+ "/81/a1b2c3d4e5f6/goals?timeMode=range&startDate=2026-09-01&endDate=2026-09-30"
+ );
+ expect(screen.getByRole("link", { name: "1 funnel" }).getAttribute("href")).toBe(
+ "/81/a1b2c3d4e5f6/funnels?timeMode=range&startDate=2026-09-01&endDate=2026-09-30"
+ );
+ });
+
+ it("does not prefetch a link per row", () => {
+ renderUsedIn({ goals: [goal(1, "Signup")] });
+
+ expect(screen.getByRole("link", { name: "Signup" }).getAttribute("data-prefetch")).toBe("false");
+ });
+});
diff --git a/client/src/app/[site]/events/components/EventNames/UsedIn.tsx b/client/src/app/[site]/events/components/EventNames/UsedIn.tsx
new file mode 100644
index 000000000..885224cba
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventNames/UsedIn.tsx
@@ -0,0 +1,110 @@
+"use client";
+
+import { Funnel, Target } from "lucide-react";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { useSearchParams } from "next/navigation";
+import { ReactNode } from "react";
+
+import { Goal, SavedFunnel } from "@/api/analytics/endpoints";
+import { Skeleton } from "@/components/ui/skeleton";
+import { useStore } from "@/lib/store";
+import { cn } from "@/lib/utils";
+import { CreateGoalPopover } from "./CreateGoalPopover";
+
+const CHIP =
+ "inline-flex min-w-0 items-center gap-1 whitespace-nowrap rounded-md border border-neutral-150 px-1.5 py-0.5 text-xs text-neutral-700 hover:bg-neutral-50 dark:border-neutral-800 dark:text-neutral-200 dark:hover:bg-neutral-800";
+
+function Chip({
+ href,
+ icon,
+ title,
+ fixed = false,
+ children,
+}: {
+ href: string;
+ icon: ReactNode;
+ title: string;
+ /** Keeps its width: a short count, where a name would be cut to make room. */
+ fixed?: boolean;
+ children: ReactNode;
+}) {
+ return (
+ // One link per row: prefetching them all would flood the router.
+ <Link href={href} prefetch={false} className={cn(CHIP, fixed && "shrink-0")} title={title}>
+ <span className="flex shrink-0 text-neutral-500 dark:text-neutral-400 [&>svg]:size-3">{icon}</span>
+ <span className="truncate">{children}</span>
+ </Link>
+ );
+}
+
+/** Where another page of this site lives, keeping the period, the filters and a private link's key. */
+function useSitePageHref() {
+ const site = useStore(state => state.site);
+ const privateKey = useStore(state => state.privateKey);
+ const search = useSearchParams().toString();
+
+ return (page: string) => {
+ const path = privateKey ? `/${site}/${privateKey}/${page}` : `/${site}/${page}`;
+ return search ? `${path}?${search}` : path;
+ };
+}
+
+interface UsedInProps {
+ eventName: string;
+ /** The goals that complete on this event. */
+ goals: Goal[];
+ /** The saved funnels with a step on this event. */
+ funnels: SavedFunnel[];
+ /** Goals and funnels are still loading. */
+ isLoading: boolean;
+ /** The viewer may create goals here. */
+ canCreateGoal: boolean;
+ className?: string;
+}
+
+/**
+ * The goals and funnels built on an event, as links to them; or, for an event
+ * nothing measures yet, the way to make it a goal.
+ */
+export function UsedIn({ eventName, goals, funnels, isLoading, canCreateGoal, className }: UsedInProps) {
+ const t = useExtracted();
+ const pageHref = useSitePageHref();
+
+ if (isLoading) {
+ return <Skeleton className="h-4 w-24 rounded" />;
+ }
+
+ if (goals.length === 0 && funnels.length === 0) {
+ return canCreateGoal ? (
+ <CreateGoalPopover eventName={eventName} />
+ ) : (
+ <span className="text-xs text-neutral-400 dark:text-neutral-500">—</span>
+ );
+ }
+
+ const goalNames = goals.map(goal => goal.name || eventName);
+ const funnelNames = funnels.map(funnel => funnel.name);
+
+ return (
+ <div className={cn("flex min-w-0 items-center gap-1.5", className)}>
+ {goals.length > 0 && (
+ <Chip href={pageHref("goals")} icon={<Target />} title={goalNames.join(", ")}>
+ {goals.length === 1 ? goalNames[0] : t("{count} goals", { count: goals.length.toLocaleString() })}
+ </Chip>
+ )}
+ {funnels.length > 0 && (
+ <Chip
+ href={pageHref("funnels")}
+ icon={<Funnel />}
+ title={funnelNames.join(", ")}
+ fixed={!(funnels.length === 1 && goals.length === 0)}
+ >
+ {funnels.length === 1 && goals.length === 0
+ ? funnelNames[0]
+ : t("{count, plural, one {# funnel} other {# funnels}}", { count: funnels.length })}
+ </Chip>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/events/components/EventNames/columns.test.ts b/client/src/app/[site]/events/components/EventNames/columns.test.ts
new file mode 100644
index 000000000..1fca44b94
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventNames/columns.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import { COLUMN, visibleColumnCount } from "./columns";
+
+describe("visibleColumnCount", () => {
+ it("counts every column before the card has been measured", () => {
+ expect(visibleColumnCount(null)).toBe(9);
+ expect(visibleColumnCount(null, false)).toBe(8);
+ });
+
+ it.each([
+ [358, 2],
+ [479, 2],
+ [480, 3],
+ [640, 5],
+ [723, 5],
+ [760, 6],
+ [840, 7],
+ [930, 8],
+ [1119, 8],
+ [1120, 9],
+ [1368, 9],
+ ])("shows %i px of card as %i columns", (width, columns) => {
+ expect(visibleColumnCount(width)).toBe(columns);
+ });
+
+ it("leaves the change column out when there is no comparison", () => {
+ expect(visibleColumnCount(639, false)).toBe(3);
+ expect(visibleColumnCount(640, false)).toBe(4);
+ expect(visibleColumnCount(1120, false)).toBe(8);
+ });
+
+ it("uses the same threshold in the class and in the count", () => {
+ for (const [column, className] of Object.entries(COLUMN)) {
+ const minWidth = Number(/@min-\[(\d+)px\]/.exec(className)?.[1]);
+ const hasChange = true;
+ // One pixel short of the class's threshold the column is not counted; at it, it is.
+ expect(
+ visibleColumnCount(minWidth, hasChange) - visibleColumnCount(minWidth - 1, hasChange),
+ column
+ ).toBeGreaterThan(0);
+ }
+ });
+});
diff --git a/client/src/app/[site]/events/components/EventNames/columns.ts b/client/src/app/[site]/events/components/EventNames/columns.ts
new file mode 100644
index 000000000..57253f26e
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventNames/columns.ts
@@ -0,0 +1,41 @@
+// The names table's optional columns give way as the card narrows; the expanded
+// row carries what they held. Container widths, not viewport ones: the sidebar
+// takes a varying share of the window.
+export const COLUMN = {
+ users: "hidden @min-[480px]:table-cell",
+ trend: "hidden @min-[640px]:table-cell",
+ change: "hidden @min-[640px]:table-cell",
+ lastSeen: "hidden @min-[760px]:table-cell",
+ perUser: "hidden @min-[840px]:table-cell",
+ people: "hidden @min-[930px]:table-cell",
+ usedIn: "hidden @min-[1120px]:table-cell",
+};
+
+// The same thresholds as numbers. Keep the two in step.
+const COLUMN_MIN_WIDTH: Record<keyof typeof COLUMN, number> = {
+ users: 480,
+ trend: 640,
+ change: 640,
+ lastSeen: 760,
+ perUser: 840,
+ people: 930,
+ usedIn: 1120,
+};
+
+// Event and Events are always there.
+const ALWAYS_VISIBLE_COLUMNS = 2;
+
+/**
+ * How many columns are on show at a card width. The expanded row spans exactly
+ * that many: a fixed-layout table makes a column for every one a cell spans,
+ * so spanning the hidden ones too would squeeze the name column to make room.
+ *
+ * The change column is only rendered while a comparison is on. An unmeasured
+ * card (null) counts every column.
+ */
+export const visibleColumnCount = (containerWidth: number | null, hasChangeColumn = true) =>
+ ALWAYS_VISIBLE_COLUMNS +
+ Object.entries(COLUMN_MIN_WIDTH).filter(
+ ([column, minWidth]) =>
+ (column !== "change" || hasChangeColumn) && (containerWidth === null || containerWidth >= minWidth)
+ ).length;
diff --git a/client/src/app/[site]/events/components/EventSeriesChart.tsx b/client/src/app/[site]/events/components/EventSeriesChart.tsx
new file mode 100644
index 000000000..bf255ad69
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventSeriesChart.tsx
@@ -0,0 +1,166 @@
+"use client";
+
+import { ResponsiveLine, SliceTooltipProps } from "@nivo/line";
+import { useMeasure } from "@uidotdev/usehooks";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+
+import { ChartTooltip } from "@/components/charts/ChartTooltip";
+import { Delta } from "@/components/site/Delta";
+import { formatChartDateTime, hour12, userLocale } from "@/lib/dateTimeUtils";
+import { percentDelta } from "@/lib/delta";
+import { useNivoTheme } from "@/lib/nivo";
+import { getTimezone, useStore } from "@/lib/store";
+import { formatter } from "@/lib/utils";
+
+export type SeriesPoint = {
+ x: string;
+ y: number;
+ currentTime: DateTime;
+ /** Position of the bucket in the period, to find its counterpart in the comparison period. */
+ index: number;
+};
+
+export type ChartSeries = {
+ id: string;
+ color: string;
+ data: SeriesPoint[];
+};
+
+/** The comparison period's bucket at the same position, summed over the visible series. */
+export type ComparisonBucket = {
+ time: DateTime;
+ total: number;
+};
+
+interface EventSeriesChartProps {
+ /** The visible series only. */
+ series: ChartSeries[];
+ /** By bucket position. Leave out when the comparison is off. */
+ comparison?: (ComparisonBucket | undefined)[];
+ /** Adds a total row to the tooltip. */
+ showTotal?: boolean;
+}
+
+const SUB_DAY_BUCKETS = ["minute", "five_minutes", "ten_minutes", "fifteen_minutes", "hour"];
+
+/** The line chart both breakdowns draw: one line per series, a shared tooltip per bucket. */
+export function EventSeriesChart({ series, comparison, showTotal = false }: EventSeriesChartProps) {
+ const t = useExtracted();
+ const bucket = useStore(state => state.bucket);
+ // The chart shares its card with the legend, so the ticks follow its own width, not the window's.
+ const [containerRef, { width }] = useMeasure<HTMLDivElement>();
+ const nivoTheme = useNivoTheme();
+ const timezone = getTimezone();
+
+ const values = series.flatMap(serie => serie.data.map(point => point.y));
+ const maxValue = values.length > 0 ? Math.max(...values) : 1;
+ const totalPoints = series[0]?.data.length ?? 0;
+ const maxTicks = Math.max(2, Math.floor(((width ?? 800) - 60) / 76));
+
+ const formatXAxisValue = (value: Date) => {
+ const dt = DateTime.fromJSDate(value, { zone: "utc" }).setZone(timezone).setLocale(userLocale);
+ if (SUB_DAY_BUCKETS.includes(bucket)) {
+ return dt.toFormat(hour12 ? "h:mm" : "HH:mm");
+ }
+ return dt.toFormat(hour12 ? "MMM d" : "dd MMM");
+ };
+
+ return (
+ <div ref={containerRef} className="h-full w-full">
+ <ResponsiveLine
+ data={series}
+ theme={nivoTheme}
+ margin={{ top: 10, right: 20, bottom: 30, left: 40 }}
+ xScale={{
+ type: "time",
+ format: "%Y-%m-%d %H:%M:%S",
+ precision: "second",
+ useUTC: true,
+ }}
+ yScale={{
+ type: "linear",
+ min: 0,
+ stacked: false,
+ reverse: false,
+ max: Math.max(maxValue, 1),
+ }}
+ enableGridX={true}
+ enableGridY={true}
+ gridYValues={5}
+ axisTop={null}
+ axisRight={null}
+ axisBottom={{
+ tickSize: 5,
+ tickPadding: 10,
+ tickRotation: 0,
+ truncateTickAt: 0,
+ tickValues: totalPoints > 0 ? Math.min(maxTicks, totalPoints) : undefined,
+ format: formatXAxisValue,
+ }}
+ axisLeft={{
+ tickSize: 5,
+ tickPadding: 10,
+ tickRotation: 0,
+ truncateTickAt: 0,
+ tickValues: 5,
+ format: formatter,
+ }}
+ colors={datum => datum.color}
+ enableTouchCrosshair={true}
+ enablePoints={false}
+ useMesh={true}
+ animate={false}
+ enableSlices="x"
+ lineWidth={2}
+ sliceTooltip={({ slice }: SliceTooltipProps<ChartSeries>) => {
+ const first = slice.points[0]?.data;
+ const currentTime = first?.currentTime as DateTime | undefined;
+ const sortedPoints = slice.points.toSorted((a, b) => Number(b.data.yFormatted) - Number(a.data.yFormatted));
+ const total = sortedPoints.reduce((acc, point) => acc + Number(point.data.yFormatted), 0);
+ const previous = first ? comparison?.[first.index as number] : undefined;
+
+ return (
+ <ChartTooltip>
+ <div className="min-w-[180px] p-3">
+ {currentTime && <div className="mb-2 font-medium">{formatChartDateTime(currentTime, bucket)}</div>}
+ <div className="space-y-1">
+ {sortedPoints.map(point => (
+ <div key={point.id} className="flex items-center justify-between gap-4">
+ <div className="flex items-center gap-2">
+ <div className="h-3 w-1 rounded-[3px]" style={{ backgroundColor: point.seriesColor }} />
+ <span className="max-w-[160px] truncate text-neutral-600 dark:text-neutral-300">
+ {point.seriesId}
+ </span>
+ </div>
+ <span className="font-medium tabular-nums text-neutral-700 dark:text-neutral-200">
+ {Number(point.data.yFormatted).toLocaleString()}
+ </span>
+ </div>
+ ))}
+ </div>
+ {showTotal && (
+ <div className="mt-2 flex justify-between border-t border-neutral-100 pt-2 dark:border-neutral-750">
+ <span className="text-neutral-600 dark:text-neutral-300">{t("Total")}</span>
+ <span className="font-semibold tabular-nums text-neutral-700 dark:text-neutral-200">
+ {total.toLocaleString()}
+ </span>
+ </div>
+ )}
+ {showTotal && previous && (
+ <div className="mt-1 flex justify-between gap-4 text-neutral-500 dark:text-neutral-400">
+ <span>{formatChartDateTime(previous.time, bucket)}</span>
+ <span className="flex items-center gap-1.5 tabular-nums">
+ {previous.total.toLocaleString()}
+ <Delta value={percentDelta(total, previous.total)} />
+ </span>
+ </div>
+ )}
+ </div>
+ </ChartTooltip>
+ );
+ }}
+ />
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/events/components/EventTypeMark.tsx b/client/src/app/[site]/events/components/EventTypeMark.tsx
new file mode 100644
index 000000000..d0169f1da
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventTypeMark.tsx
@@ -0,0 +1,81 @@
+"use client";
+
+import {
+ Copy,
+ ExternalLink,
+ Eye,
+ FileInput,
+ Gauge,
+ LucideIcon,
+ MousePointerClick,
+ SquareMousePointer,
+ TextCursorInput,
+ TriangleAlert,
+} from "lucide-react";
+import { useExtracted } from "next-intl";
+import { cn } from "@/lib/utils";
+
+// The same glyphs as components/EventIcons, which paints each type its own
+// colour across the app. This page keeps colour for meaning instead: custom
+// events in the data hue, errors red, everything else neutral.
+const ICONS: Record<string, LucideIcon> = {
+ pageview: Eye,
+ custom_event: MousePointerClick,
+ error: TriangleAlert,
+ outbound: ExternalLink,
+ button_click: SquareMousePointer,
+ copy: Copy,
+ form_submit: FileInput,
+ input_change: TextCursorInput,
+ performance: Gauge,
+};
+
+export function EventTypeMark({ type, className }: { type: string; className?: string }) {
+ const Icon = ICONS[type] ?? MousePointerClick;
+
+ return (
+ <Icon
+ aria-hidden="true"
+ className={cn(
+ "h-4 w-4 shrink-0",
+ type === "custom_event"
+ ? "text-dataviz"
+ : type === "error"
+ ? "text-red-500 dark:text-red-400"
+ : "text-neutral-500 dark:text-neutral-400",
+ className
+ )}
+ />
+ );
+}
+
+/** Translated names for the event types: one occurrence, and the type as a group. */
+export function useEventTypeLabels() {
+ const t = useExtracted();
+
+ const singular: Record<string, string> = {
+ pageview: t("Pageview"),
+ custom_event: t("Event"),
+ outbound: t("Outbound click"),
+ button_click: t("Button click"),
+ copy: t("Copy"),
+ form_submit: t("Form submit"),
+ input_change: t("Input change"),
+ error: t("Error"),
+ performance: t("Performance"),
+ };
+
+ const plural: Record<string, string> = {
+ pageview: t("Pageviews"),
+ custom_event: t("Custom events"),
+ outbound: t("Outbound"),
+ button_click: t("Button clicks"),
+ copy: t("Copies"),
+ form_submit: t("Form submits"),
+ input_change: t("Input changes"),
+ error: t("Errors"),
+ performance: t("Performance"),
+ };
+
+ return { singular, plural };
+}
diff --git a/client/src/app/[site]/events/components/EventTypesChart.tsx b/client/src/app/[site]/events/components/EventTypesChart.tsx
index 7160fcb1f..8b899670e 100644
--- a/client/src/app/[site]/events/components/EventTypesChart.tsx
+++ b/client/src/app/[site]/events/components/EventTypesChart.tsx
@@ -1,245 +1,129 @@
"use client";
-import { ResponsiveLine, SliceTooltipProps } from "@nivo/line";
-import { useWindowSize } from "@uidotdev/usehooks";
import { DateTime } from "luxon";
-import { useMemo, useState } from "react";
-
import { useExtracted } from "next-intl";
-import { useGetSiteEventCount } from "@/api/analytics/hooks/events/useGetSiteEventCount";
-import { ChartTooltip } from "@/components/charts/ChartTooltip";
-import { ChartLegend } from "./ChartLegend";
-import { formatChartDateTime, hour12, userLocale } from "@/lib/dateTimeUtils";
-import { useNivoTheme } from "@/lib/nivo";
-import { getTimezone, useStore } from "@/lib/store";
-import { formatter } from "@/lib/utils";
-import { CardLoader } from "../../../../components/ui/card";
-
-const EVENT_TYPE_CONFIG = [
- { key: "pageview_count", label: "Pageviews", color: "#60a5fa" },
- { key: "custom_event_count", label: "Custom Events", color: "#fbbf24" },
- { key: "performance_count", label: "Performance", color: "#a78bfa" },
- { key: "outbound_count", label: "Outbound", color: "#a3e635" },
- { key: "error_count", label: "Errors", color: "#f87171" },
- { key: "button_click_count", label: "Button Clicks", color: "#4ade80" },
- { key: "copy_count", label: "Copy", color: "#38bdf8" },
- { key: "form_submit_count", label: "Form Submits", color: "#c084fc" },
- { key: "input_change_count", label: "Input Changes", color: "#f472b6" },
-] as const;
-
-type EventTypeKey = (typeof EVENT_TYPE_CONFIG)[number]["key"];
+import { useState } from "react";
-type DataPoint = {
- x: string;
- y: number;
- currentTime: DateTime;
-};
-
-type Series = {
- id: string;
- color: string;
- data: DataPoint[];
+import { SiteEventCountPoint } from "@/api/analytics/endpoints";
+import { useGetSiteEventCount } from "@/api/analytics/hooks/events/useGetSiteEventCount";
+import { percentDelta } from "@/lib/delta";
+import { getTimezone, useComparisonEnabled } from "@/lib/store";
+import { DEFAULT_HIDDEN_TYPES, EVENT_TYPE_SERIES, totalsByType } from "../utils/eventTypes";
+import { ChartLegend, LegendRow } from "./ChartLegend";
+import { ChartPanel } from "./ChartPanel";
+import { ChartSeries, ComparisonBucket, EventSeriesChart } from "./EventSeriesChart";
+import { EventTypeMark, useEventTypeLabels } from "./EventTypeMark";
+
+type TimedPoint = { point: SiteEventCountPoint; time: DateTime };
+
+// Oldest first, without the buckets that have not started yet.
+const toTimedPoints = (points: SiteEventCountPoint[] | undefined, timezone: string): TimedPoint[] => {
+ const now = DateTime.now().toUTC();
+ return (points ?? [])
+ .map(point => ({ point, time: DateTime.fromSQL(point.time, { zone: timezone }).toUTC() }))
+ .filter(({ time }) => time.isValid && time <= now)
+ .sort((a, b) => a.time.toMillis() - b.time.toMillis());
};
export function EventTypesChart() {
const t = useExtracted();
- const { bucket } = useStore();
- const { data, isLoading } = useGetSiteEventCount();
- const { width } = useWindowSize();
- const nivoTheme = useNivoTheme();
+ const { plural } = useEventTypeLabels();
const timezone = getTimezone();
- const [hiddenTypes, setHiddenTypes] = useState<Set<string>>(new Set());
-
- const translatedLabels: Record<string, string> = {
- Pageviews: t("Pageviews"),
- "Custom Events": t("Custom Events"),
- Performance: t("Performance"),
- Outbound: t("Outbound"),
- Errors: t("Errors"),
- "Button Clicks": t("Button Clicks"),
- Copy: t("Copy"),
- "Form Submits": t("Form Submits"),
- "Input Changes": t("Input Changes"),
- };
-
- const toggleTypeVisibility = (typeLabel: string) => {
- setHiddenTypes((prev) => {
+ const comparisonEnabled = useComparisonEnabled();
+ // Pending, not loading: the query waits for the site, and "no events" is not true yet.
+ const { data, isPending: isLoading, isError } = useGetSiteEventCount();
+ const { data: previousData } = useGetSiteEventCount({ periodTime: "previous" });
+ // A disabled query keeps its last result, so the switch is read here.
+ const previous = comparisonEnabled ? previousData : undefined;
+ const [hidden, setHidden] = useState<ReadonlySet<string>>(DEFAULT_HIDDEN_TYPES);
+
+ const toggle = (type: string) => {
+ setHidden(prev => {
const next = new Set(prev);
- if (next.has(typeLabel)) {
- next.delete(typeLabel);
+ if (next.has(type)) {
+ next.delete(type);
} else {
- next.add(typeLabel);
+ next.add(type);
}
return next;
});
};
- const { series, legendItems, maxValue, totalPoints } = useMemo(() => {
- if (!data || data.length === 0) {
- return { series: [] as Series[], legendItems: [], maxValue: 1, totalPoints: 0 };
- }
-
- const sortedData = data.toSorted((a, b) => {
- const ta = DateTime.fromSQL(a.time, { zone: timezone }).toMillis();
- const tb = DateTime.fromSQL(b.time, { zone: timezone }).toMillis();
- return ta - tb;
- });
-
- const allSeries: Series[] = EVENT_TYPE_CONFIG.map((config) => ({
- id: translatedLabels[config.label] || config.label,
- color: config.color,
- data: sortedData
- .map((row) => {
- const timestamp = DateTime.fromSQL(row.time, { zone: timezone }).toUTC();
- if (!timestamp.isValid || timestamp > DateTime.now().toUTC()) {
- return null;
- }
- return {
- x: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"),
- y: row[config.key as EventTypeKey] as number,
- currentTime: timestamp,
- };
- })
- .filter((p): p is DataPoint => p !== null),
- }));
-
- // Only include series that have at least one non-zero value
- const activeSeries = allSeries.filter((s) => s.data.some((d) => d.y > 0));
-
- const values = activeSeries.flatMap((s) => s.data.map((d) => d.y));
- const maxValue = values.length > 0 ? Math.max(...values) : 1;
- const totalPoints = activeSeries.length > 0 ? activeSeries[0].data.length : 0;
-
- return {
- series: activeSeries,
- legendItems: activeSeries.map((s) => ({ id: s.id, color: s.color })),
- maxValue,
- totalPoints,
- };
- }, [data, timezone, translatedLabels]);
-
- const maxTicks = Math.round((width ?? 900) / 85);
- const visibleSeries = series.filter((s) => !hiddenTypes.has(s.id));
- const visibleValues = visibleSeries.flatMap((s) => s.data.map((d) => d.y));
- const visibleMaxValue = visibleValues.length > 0 ? Math.max(...visibleValues) : maxValue;
- const isAllHidden = series.length > 0 && visibleSeries.length === 0;
-
- const formatXAxisValue = (value: Date) => {
- const dt = DateTime.fromJSDate(value, { zone: "utc" }).setZone(timezone).setLocale(userLocale);
- if (["minute", "five_minutes", "ten_minutes", "fifteen_minutes", "hour"].includes(bucket)) {
- return dt.toFormat(hour12 ? "h:mm" : "HH:mm");
- }
- return dt.toFormat(hour12 ? "MMM d" : "dd MMM");
- };
-
-
- if (isAllHidden) {
- return (
- <>
- <div className="h-[260px] w-full flex items-center justify-center">
- <div className="text-center text-neutral-500">
- <p className="text-sm font-medium">{t("All event types hidden")}</p>
- <p className="text-xs">{t("Click a legend item to show it")}</p>
- </div>
- </div>
- <ChartLegend items={legendItems} hiddenItems={hiddenTypes} onToggle={toggleTypeVisibility} />
- </>
- );
- }
+ const points = toTimedPoints(data, timezone);
+ const previousPoints = toTimedPoints(previous, timezone);
+ const totals = totalsByType(data);
+ const previousTotals = totalsByType(previous);
+
+ // A type appears once it has fired in either period, so one that stopped still shows its drop.
+ const present = EVENT_TYPE_SERIES.filter(series => totals[series.type] > 0 || previousTotals[series.type] > 0);
+ const visible = present.filter(series => !hidden.has(series.type));
+
+ const series: ChartSeries[] = visible.map(config => ({
+ id: plural[config.type],
+ color: config.color,
+ data: points.map(({ point, time }, index) => ({
+ x: time.toFormat("yyyy-MM-dd HH:mm:ss"),
+ y: Number(point[config.countKey]) || 0,
+ currentTime: time,
+ index,
+ })),
+ }));
+
+ // The server fills empty buckets in both periods, so position n is the same
+ // distance into each of them.
+ const comparison: ComparisonBucket[] | undefined = previous
+ ? previousPoints.map(({ point, time }) => ({
+ time,
+ total: visible.reduce((sum, config) => sum + (Number(point[config.countKey]) || 0), 0),
+ }))
+ : undefined;
+
+ const legendRows: LegendRow[] = present.map(config => ({
+ id: config.type,
+ label: plural[config.type],
+ color: config.color,
+ icon: <EventTypeMark type={config.type} className="h-3.5 w-3.5" />,
+ total: totals[config.type],
+ delta: previous ? percentDelta(totals[config.type], previousTotals[config.type]) : null,
+ upIsGood: config.upIsGood,
+ }));
+
+ const hasHiddenPerformance = present.some(config => config.type === "performance");
+ const placeholder = isError
+ ? {
+ title: t("Failed to load events"),
+ description: t("There was a problem fetching the events. Please try again later."),
+ }
+ : present.length === 0
+ ? { title: t("No events in this period"), description: t("Try a different date range or filter") }
+ : visible.length === 0
+ ? { title: t("All event types hidden"), description: t("Click a type to show it") }
+ : null;
return (
- <>
- {isLoading && (
- <div className="absolute top-[-54px] left-0 w-full h-full">
- <CardLoader />
- </div>
- )}
- <div className="h-[260px] w-full">
- <ResponsiveLine
- data={visibleSeries}
- theme={nivoTheme}
- margin={{ top: 10, right: 20, bottom: 30, left: 40 }}
- xScale={{
- type: "time",
- format: "%Y-%m-%d %H:%M:%S",
- precision: "second",
- useUTC: true,
- }}
- yScale={{
- type: "linear",
- min: 0,
- stacked: false,
- reverse: false,
- max: Math.max(visibleMaxValue, 1),
- }}
- enableGridX={true}
- enableGridY={true}
- gridYValues={5}
- axisTop={null}
- axisRight={null}
- axisBottom={{
- tickSize: 5,
- tickPadding: 10,
- tickRotation: 0,
- truncateTickAt: 0,
- tickValues: totalPoints > 0 ? Math.min(maxTicks, totalPoints) : undefined,
- format: formatXAxisValue,
- }}
- axisLeft={{
- tickSize: 5,
- tickPadding: 10,
- tickRotation: 0,
- truncateTickAt: 0,
- tickValues: 5,
- format: formatter,
- }}
- colors={(datum) => datum.color}
- enableTouchCrosshair={true}
- enablePoints={false}
- useMesh={true}
- animate={false}
- enableSlices="x"
- lineWidth={2}
- sliceTooltip={({ slice }: SliceTooltipProps<Series>) => {
- const currentTime = slice.points[0]?.data.currentTime as DateTime | undefined;
- const sortedPoints = slice.points.toSorted(
- (a, b) => Number(b.data.yFormatted) - Number(a.data.yFormatted)
- );
- const total = sortedPoints.reduce((acc, p) => acc + Number(p.data.yFormatted), 0);
-
- return (
- <ChartTooltip>
- <div className="p-3 min-w-[160px]">
- {currentTime && <div className="mb-2">{formatChartDateTime(currentTime, bucket)}</div>}
- <div className="space-y-1">
- {sortedPoints.map((point) => (
- <div key={point.id} className="flex justify-between items-center gap-4">
- <div className="flex items-center gap-2">
- <div className="w-1 h-3 rounded-[3px]" style={{ backgroundColor: point.seriesColor }} />
- <span className="text-neutral-600 dark:text-neutral-300 max-w-[140px] truncate">
- {point.seriesId}
- </span>
- </div>
- <span className="font-medium text-neutral-700 dark:text-neutral-200">
- {formatter(Number(point.data.yFormatted))}
- </span>
- </div>
- ))}
- </div>
- <div className="mt-2 flex justify-between border-t border-neutral-100 dark:border-neutral-750 pt-2">
- <span className="text-neutral-600 dark:text-neutral-300">{t("Total")}</span>
- <span className="font-semibold text-neutral-700 dark:text-neutral-200">
- {formatter(total)}
- </span>
- </div>
- </div>
- </ChartTooltip>
- );
- }}
+ <ChartPanel
+ title={t("Events by type")}
+ isLoading={isLoading}
+ placeholder={placeholder}
+ chart={<EventSeriesChart series={series} comparison={comparison} showTotal />}
+ legend={
+ <ChartLegend
+ rows={legendRows}
+ hidden={hidden}
+ onToggle={toggle}
+ nameLabel={t("Type")}
+ showDelta={comparisonEnabled}
+ hasIcons
+ isLoading={isLoading}
+ note={
+ present.length === 0
+ ? undefined
+ : hasHiddenPerformance
+ ? t("Click a type to show or hide it. Pageviews and performance events are hidden by default.")
+ : t("Click a type to show or hide it. Pageviews are hidden by default.")
+ }
/>
- </div>
-
- <ChartLegend items={legendItems} hiddenItems={hiddenTypes} onToggle={toggleTypeVisibility} />
- </>
+ }
+ />
);
}
diff --git a/client/src/app/[site]/events/components/EventsChart.tsx b/client/src/app/[site]/events/components/EventsChart.tsx
index 613b238c4..3848c6865 100644
--- a/client/src/app/[site]/events/components/EventsChart.tsx
+++ b/client/src/app/[site]/events/components/EventsChart.tsx
@@ -1,80 +1,28 @@
"use client";
-import { useExtracted } from "next-intl";
-import { useState } from "react";
-
-import { BucketSelection } from "@/components/BucketSelection";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/basic-tabs";
-import { Card, CardHeader } from "@/components/ui/card";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Card } from "@/components/ui/card";
import { CustomEventsChart } from "./CustomEventsChart";
import { EventTypesChart } from "./EventTypesChart";
-const EVENT_LIMIT_OPTIONS = [1, 3, 5, 8, 10];
+export type EventsBreakdown = "type" | "name";
-type ChartTab = "custom_events" | "event_types";
+export const EVENT_LIMIT_OPTIONS = [1, 3, 5, 8, 10];
-export function EventsChart() {
- const t = useExtracted();
- const [tab, setTab] = useState<ChartTab>("custom_events");
- const [eventLimit, setEventLimit] = useState(5);
+interface EventsChartProps {
+ breakdown: EventsBreakdown;
+ /** How many custom events the by-name breakdown draws. */
+ eventLimit: number;
+}
+export function EventsChart({ breakdown, eventLimit }: EventsChartProps) {
return (
<Card className="overflow-visible">
- <Tabs value={tab} onValueChange={v => setTab(v as ChartTab)}>
- <CardHeader className="flex flex-col gap-0 pb-0">
- <div className="flex items-start gap-2">
- <TabsList className="flex-1 mt-[-8px]">
- <TabsTrigger value="custom_events">{t("Custom Events")}</TabsTrigger>
- <TabsTrigger value="event_types">{t("Event Types")}</TabsTrigger>
- </TabsList>
- <div className="hidden items-center gap-2 sm:flex">
- {tab === "custom_events" && (
- <Select value={String(eventLimit)} onValueChange={value => setEventLimit(Number(value))}>
- <SelectTrigger className="w-[90px]" size="sm">
- <SelectValue />
- </SelectTrigger>
- <SelectContent size="sm">
- {EVENT_LIMIT_OPTIONS.map(option => (
- <SelectItem key={option} value={String(option)} size="sm">
- {t("Top {option}", { option: String(option) })}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- <BucketSelection />
- </div>
- </div>
- <div className="mt-2 flex w-full flex-wrap items-center gap-2 sm:-mt-1">
- <div className="ml-auto flex items-center gap-2 sm:hidden">
- {tab === "custom_events" && (
- <Select value={String(eventLimit)} onValueChange={value => setEventLimit(Number(value))}>
- <SelectTrigger className="w-[90px]" size="sm">
- <SelectValue />
- </SelectTrigger>
- <SelectContent size="sm">
- {EVENT_LIMIT_OPTIONS.map(option => (
- <SelectItem key={option} value={String(option)} size="sm">
- {t("Top {option}", { option: String(option) })}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- <BucketSelection />
- </div>
- </div>
- </CardHeader>
- <div className="px-2 md:px-4 pb-2 md:pb-4 relative">
- <TabsContent value="custom_events">
- <CustomEventsChart eventLimit={eventLimit} />
- </TabsContent>
- <TabsContent value="event_types">
- <EventTypesChart />
- </TabsContent>
- </div>
- </Tabs>
+ {breakdown === "type" ? (
+ <EventTypesChart />
+ ) : (
+ // Keyed so the hidden lines reset when the set of events changes.
+ <CustomEventsChart key={eventLimit} eventLimit={eventLimit} />
+ )}
</Card>
);
}
diff --git a/client/src/app/[site]/events/components/EventsStatBand.tsx b/client/src/app/[site]/events/components/EventsStatBand.tsx
new file mode 100644
index 000000000..651f24276
--- /dev/null
+++ b/client/src/app/[site]/events/components/EventsStatBand.tsx
@@ -0,0 +1,94 @@
+"use client";
+
+import { MousePointerClick, Rewind, SquareMousePointer, Tag, User } from "lucide-react";
+import { useExtracted } from "next-intl";
+
+import { useGetEventsOverview } from "@/api/analytics/hooks/events/useGetEventsOverview";
+import { StatBand } from "@/components/site/StatBand";
+import { NO_DELTA_TEXT, percentDelta } from "@/lib/delta";
+import { useComparisonEnabled } from "@/lib/store";
+import { formatter } from "@/lib/utils";
+
+const ratio = (numerator: number | undefined, denominator: number | undefined) =>
+ numerator !== undefined && denominator ? numerator / denominator : undefined;
+
+interface EventsStatBandProps {
+ /** Event names seen in this period but not in the comparison period. Undefined while unknown or with no comparison. */
+ newEventNames?: number;
+}
+
+export function EventsStatBand({ newEventNames }: EventsStatBandProps) {
+ const t = useExtracted();
+ const comparisonEnabled = useComparisonEnabled();
+ // Pending, not loading: the query waits for the site, and a band of blanks is not an answer.
+ const { data: current, isPending } = useGetEventsOverview();
+ const { data: previousData } = useGetEventsOverview({ periodTime: "previous" });
+ // A disabled query keeps its last result, so the switch is read here.
+ const previous = comparisonEnabled ? previousData : undefined;
+
+ const perSession = ratio(current?.events, current?.sessions);
+ const previousPerSession = ratio(previous?.events, previous?.sessions);
+ const perActiveSession = ratio(current?.events, current?.sessions_with_events);
+ const userShare = ratio(current?.users_with_events, current?.users);
+
+ // A dash when the request failed: there is no number to show.
+ const count = (value: number | undefined) => (value === undefined ? NO_DELTA_TEXT : formatter(value));
+ const exact = (value: number | undefined) => value?.toLocaleString();
+
+ return (
+ <StatBand
+ isLoading={isPending}
+ cells={[
+ {
+ id: "events",
+ icon: <MousePointerClick className="h-3 w-3" />,
+ label: t("Events"),
+ value: count(current?.events),
+ title: exact(current?.events),
+ delta: percentDelta(current?.events, previous?.events),
+ sub: t("Custom events"),
+ },
+ {
+ id: "users",
+ icon: <User className="h-3 w-3" />,
+ label: t("Users with an event"),
+ value: count(current?.users_with_events),
+ title: exact(current?.users_with_events),
+ delta: percentDelta(current?.users_with_events, previous?.users_with_events),
+ sub: userShare === undefined ? "" : t("{share}% of users", { share: (userShare * 100).toFixed(1) }),
+ },
+ {
+ id: "per-session",
+ icon: <Rewind className="h-3 w-3" />,
+ label: t("Events per session"),
+ value: current ? (perSession ?? 0).toFixed(2) : NO_DELTA_TEXT,
+ delta: percentDelta(perSession, previousPerSession),
+ sub:
+ perActiveSession === undefined
+ ? ""
+ : t("{count} in sessions with events", { count: perActiveSession.toFixed(2) }),
+ },
+ {
+ id: "names",
+ icon: <Tag className="h-3 w-3" />,
+ label: t("Event names"),
+ value: count(current?.event_names),
+ title: exact(current?.event_names),
+ sub:
+ newEventNames === undefined
+ ? ""
+ : t("{count} new vs comparison", { count: newEventNames.toLocaleString() }),
+ },
+ {
+ id: "autocaptured",
+ icon: <SquareMousePointer className="h-3 w-3" />,
+ label: t("Autocaptured"),
+ value: count(current?.autocaptured),
+ title: exact(current?.autocaptured),
+ delta: percentDelta(current?.autocaptured, previous?.autocaptured),
+ sub: t("Clicks, links, forms, copies, inputs"),
+ },
+ ]}
+ />
+ );
+}
diff --git a/client/src/app/[site]/events/components/SilentEventNotice.tsx b/client/src/app/[site]/events/components/SilentEventNotice.tsx
new file mode 100644
index 000000000..e4c284d5a
--- /dev/null
+++ b/client/src/app/[site]/events/components/SilentEventNotice.tsx
@@ -0,0 +1,57 @@
+"use client";
+
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+
+import { SilentEvent } from "@/api/analytics/endpoints";
+import { InsightRow } from "@/components/site/InsightRow";
+import { Button } from "@/components/ui/button";
+import { addFilter, getTimezone } from "@/lib/store";
+import { silentEventDailyAverage } from "../utils/usedIn";
+
+interface SilentEventNoticeProps {
+ /** Ranked by how often they used to fire; the first one is named. */
+ events: SilentEvent[] | undefined;
+}
+
+/**
+ * Says when a custom event that fired on most days has stopped. Nothing else
+ * on the page can: an event with no occurrences drops out of every list.
+ */
+export function SilentEventNotice({ events }: SilentEventNoticeProps) {
+ const t = useExtracted();
+ const event = events?.[0];
+ if (!event) return null;
+
+ const lastSeen = DateTime.fromSQL(event.lastSeen, { zone: "utc" }).setZone(getTimezone());
+ const average = silentEventDailyAverage(event);
+ const others = (events?.length ?? 1) - 1;
+
+ return (
+ <InsightRow
+ action={
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => addFilter({ parameter: "event_name", type: "equals", value: [event.eventName] })}
+ >
+ {t("View event")}
+ </Button>
+ }
+ >
+ {t.rich("<name></name> has not fired since {date}. It averaged {average} a day before that.", {
+ name: () => <span className="font-medium text-neutral-900 dark:text-neutral-50">{event.eventName}</span>,
+ date: lastSeen.toFormat("MMM d"),
+ average: average >= 10 ? Math.round(average).toLocaleString() : average.toFixed(1),
+ })}
+ {others > 0 && (
+ <span className="text-neutral-500 dark:text-neutral-400">
+ {" "}
+ {t("{count, plural, one {# other event has gone quiet too.} other {# other events have gone quiet too.}}", {
+ count: others,
+ })}
+ </span>
+ )}
+ </InsightRow>
+ );
+}
diff --git a/client/src/app/[site]/events/page.tsx b/client/src/app/[site]/events/page.tsx
index 069c42e04..06df39545 100644
--- a/client/src/app/[site]/events/page.tsx
+++ b/client/src/app/[site]/events/page.tsx
@@ -1,36 +1,89 @@
"use client";
import { useExtracted } from "next-intl";
+import { useState } from "react";
import { EVENT_FILTERS } from "@/lib/filterGroups";
import { useGetEventNames } from "../../../api/analytics/hooks/events/useGetEventNames";
+import { useGetEventNameStats } from "../../../api/analytics/hooks/events/useGetEventNameStats";
+import { useGetSilentEvents } from "../../../api/analytics/hooks/events/useGetSilentEvents";
+import { BucketSelection } from "../../../components/BucketSelection";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
+import { AnalysisBar } from "../../../components/site/AnalysisBar";
+import { BreakdownControl } from "../../../components/site/BreakdownControl";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../components/ui/select";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
+import { useComparisonEnabled, useStore, useTimezone } from "../../../lib/store";
import { SubHeader } from "../components/SubHeader/SubHeader";
import { EventLog } from "./components/EventLog";
-import { EventsChart } from "./components/EventsChart";
-
+import { EventNamesCard } from "./components/EventNames/EventNamesCard";
+import { EVENT_LIMIT_OPTIONS, EventsBreakdown, EventsChart } from "./components/EventsChart";
+import { EventsStatBand } from "./components/EventsStatBand";
+import { SilentEventNotice } from "./components/SilentEventNotice";
+import { buildEventNameRows, countNewEventNames } from "./utils/eventNameRows";
+import { trendBucketFor } from "./utils/trendBucket";
export default function EventsPage() {
const t = useExtracted();
useSetPageTitle("Events");
- const { data: eventNamesData, isLoading: isLoadingEventNames } = useGetEventNames();
+ const time = useStore(state => state.time);
+ const timezone = useTimezone();
+ const comparisonEnabled = useComparisonEnabled();
+ const [breakdown, setBreakdown] = useState<EventsBreakdown>("type");
+ const [eventLimit, setEventLimit] = useState(5);
+
+ const trendBucket = trendBucketFor(time, timezone);
+ const stats = useGetEventNameStats({ trendBucket });
+ const previousNamesQuery = useGetEventNames({ periodTime: "previous" });
+ // A disabled query keeps its last result, so the switch is read here.
+ const previousNames = comparisonEnabled ? previousNamesQuery.data : undefined;
+ const { data: silentEvents } = useGetSilentEvents();
+
+ const rows = buildEventNameRows(stats.data, previousNames, timezone);
+ const silentNames = new Set((silentEvents ?? []).map(event => event.eventName));
return (
<DisabledOverlay message={t("Events")} featurePath="events">
- <div className="p-2 md:p-4 mx-auto space-y-3">
+ <div className="mx-auto max-w-[1400px] space-y-3 p-2 md:p-4">
<SubHeader availableFilters={EVENT_FILTERS} />
- <EventsChart />
- {/* <Card className="h-auto lg:h-full">
- <CardHeader>
-
- <CardTitle>Custom Events</CardTitle>
- </CardHeader>
- <CardContent>
- <EventList events={eventNamesData || []} isLoading={isLoadingEventNames} size="large" />
- </CardContent>
- </Card> */}
-
+ <EventsStatBand newEventNames={countNewEventNames(stats.data, previousNames)} />
+ <AnalysisBar
+ breakdown={
+ <BreakdownControl<EventsBreakdown>
+ value={breakdown}
+ onChange={setBreakdown}
+ options={[
+ { value: "type", label: t("Event type") },
+ { value: "name", label: t("Event name") },
+ ]}
+ />
+ }
+ end={<BucketSelection />}
+ >
+ {breakdown === "name" && (
+ <Select value={String(eventLimit)} onValueChange={value => setEventLimit(Number(value))}>
+ <SelectTrigger className="w-[90px]" size="sm" aria-label={t("Events on the chart")}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent size="sm">
+ {EVENT_LIMIT_OPTIONS.map(option => (
+ <SelectItem key={option} value={String(option)} size="sm">
+ {t("Top {option}", { option: String(option) })}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ </AnalysisBar>
+ <EventsChart breakdown={breakdown} eventLimit={eventLimit} />
+ <SilentEventNotice events={silentEvents} />
+ <EventNamesCard
+ rows={rows}
+ isLoading={stats.isPending}
+ isError={stats.isError}
+ trendBucket={trendBucket}
+ silentEvents={silentNames}
+ />
<EventLog />
</div>
</DisabledOverlay>
diff --git a/client/src/app/[site]/events/utils/eventNameRows.test.ts b/client/src/app/[site]/events/utils/eventNameRows.test.ts
new file mode 100644
index 000000000..ee559c6c1
--- /dev/null
+++ b/client/src/app/[site]/events/utils/eventNameRows.test.ts
@@ -0,0 +1,174 @@
+import { DateTime } from "luxon";
+import { describe, expect, it } from "vitest";
+import { EventNameStats } from "../../../../api/analytics/endpoints";
+import {
+ buildEventNameRows,
+ countNewEventNames,
+ EventNameRow,
+ filterEventNameRows,
+ sortEventNameRows,
+} from "./eventNameRows";
+
+const ZONE = "America/New_York";
+const NOW = DateTime.fromISO("2026-09-03T12:00:00", { zone: ZONE });
+
+const stats: EventNameStats = {
+ // The period runs to Sep 4; Sep 4 has not started yet.
+ buckets: ["2026-09-01 00:00:00", "2026-09-02 00:00:00", "2026-09-03 00:00:00", "2026-09-04 00:00:00"],
+ events: [
+ { eventName: "signup", count: 60, users: 40, lastSeen: "2026-09-03 15:59:00", trend: [10, 20, 30, 0] },
+ { eventName: "cta_click", count: 30, users: 10, lastSeen: "2026-09-02 08:00:00", trend: [30, 0, 0, 0] },
+ { eventName: "docs_search", count: 10, users: 0, lastSeen: "not a date", trend: [0, 10, 0, 0] },
+ ],
+};
+
+describe("buildEventNameRows", () => {
+ it("is empty until the stats arrive", () => {
+ expect(buildEventNameRows(undefined, undefined, ZONE, NOW)).toEqual([]);
+ });
+
+ it("works out events per user and each name's share of all custom events", () => {
+ const [signup, cta] = buildEventNameRows(stats, undefined, ZONE, NOW);
+
+ expect(signup.perUser).toBe(1.5);
+ expect(signup.share).toBe(0.6);
+ expect(cta.perUser).toBe(3);
+ expect(cta.share).toBe(0.3);
+ });
+
+ it("does not divide by zero users", () => {
+ expect(buildEventNameRows(stats, undefined, ZONE, NOW)[2].perUser).toBe(0);
+ });
+
+ it("cuts the trend at the buckets that have started, so an unfinished period does not end in zeros", () => {
+ const rows = buildEventNameRows(stats, undefined, ZONE, NOW);
+
+ expect(rows[0].trend).toEqual([10, 20, 30]);
+ expect(rows[1].trend).toEqual([30, 0, 0]);
+ });
+
+ it("reads the last occurrence as UTC and tolerates one it cannot read", () => {
+ const rows = buildEventNameRows(stats, undefined, ZONE, NOW);
+
+ expect(rows[0].lastSeen?.toUTC().toISO()).toBe("2026-09-03T15:59:00.000Z");
+ expect(rows[2].lastSeen).toBeNull();
+ });
+
+ it("leaves the comparison count undefined when there is no comparison", () => {
+ expect(buildEventNameRows(stats, undefined, ZONE, NOW).map(row => row.previousCount)).toEqual([
+ undefined,
+ undefined,
+ undefined,
+ ]);
+ });
+
+ it("counts a name missing from the comparison period as zero there", () => {
+ const rows = buildEventNameRows(stats, [{ eventName: "signup", count: 50 }], ZONE, NOW);
+
+ expect(rows.map(row => row.previousCount)).toEqual([50, 0, 0]);
+ });
+
+ it("matches a numeric-looking name the names endpoint returned as a number", () => {
+ const numeric: EventNameStats = {
+ buckets: [],
+ events: [{ eventName: "404", count: 5, users: 5, lastSeen: "2026-09-03 10:00:00", trend: [] }],
+ };
+ // processResults coerces "404" to 404 on the wire.
+ const previous = [{ eventName: 404 as unknown as string, count: 2 }];
+
+ expect(buildEventNameRows(numeric, previous, ZONE, NOW)[0].previousCount).toBe(2);
+ });
+});
+
+describe("countNewEventNames", () => {
+ it("is unknown without both periods", () => {
+ expect(countNewEventNames(undefined, [])).toBeUndefined();
+ expect(countNewEventNames(stats, undefined)).toBeUndefined();
+ });
+
+ it("counts the names the comparison period does not have", () => {
+ expect(countNewEventNames(stats, [{ eventName: "signup", count: 50 }])).toBe(2);
+ expect(countNewEventNames(stats, [])).toBe(3);
+ expect(
+ countNewEventNames(
+ stats,
+ stats.events.map(event => ({ eventName: event.eventName, count: 1 }))
+ )
+ ).toBe(0);
+ });
+});
+
+const row = (overrides: Partial<EventNameRow> & { eventName: string }): EventNameRow => ({
+ count: 0,
+ users: 0,
+ perUser: 0,
+ share: 0,
+ lastSeen: null,
+ trend: [],
+ previousCount: undefined,
+ ...overrides,
+});
+
+describe("sortEventNameRows", () => {
+ const rows = [
+ row({ eventName: "b", count: 10, users: 5, previousCount: 20 }),
+ row({ eventName: "a", count: 30, users: 2, previousCount: 10 }),
+ row({ eventName: "c", count: 20, users: 9, previousCount: 0 }),
+ ];
+ const names = (sorted: EventNameRow[]) => sorted.map(item => item.eventName);
+
+ it("sorts by a number in either direction", () => {
+ expect(names(sortEventNameRows(rows, "count", "desc"))).toEqual(["a", "c", "b"]);
+ expect(names(sortEventNameRows(rows, "users", "asc"))).toEqual(["a", "b", "c"]);
+ });
+
+ it("sorts names alphabetically", () => {
+ expect(names(sortEventNameRows(rows, "name", "asc"))).toEqual(["a", "b", "c"]);
+ expect(names(sortEventNameRows(rows, "name", "desc"))).toEqual(["c", "b", "a"]);
+ });
+
+ it("ranks a name that is new in the period above any finite rise", () => {
+ // a: +200%, b: -50%, c: new.
+ expect(names(sortEventNameRows(rows, "change", "desc"))).toEqual(["c", "a", "b"]);
+ expect(names(sortEventNameRows(rows, "change", "asc"))).toEqual(["b", "a", "c"]);
+ });
+
+ it("orders two new names by count instead of producing NaN", () => {
+ const fresh = [
+ row({ eventName: "x", count: 1, previousCount: 0 }),
+ row({ eventName: "y", count: 9, previousCount: 0 }),
+ ];
+
+ expect(names(sortEventNameRows(fresh, "change", "desc"))).toEqual(["y", "x"]);
+ });
+
+ it("breaks ties by count and then name, so the order is stable", () => {
+ const tied = [
+ row({ eventName: "z", count: 5, users: 1 }),
+ row({ eventName: "m", count: 5, users: 1 }),
+ row({ eventName: "k", count: 8, users: 1 }),
+ ];
+
+ expect(names(sortEventNameRows(tied, "users", "desc"))).toEqual(["k", "m", "z"]);
+ });
+
+ it("does not reorder the array it was given", () => {
+ sortEventNameRows(rows, "count", "desc");
+
+ expect(names(rows)).toEqual(["b", "a", "c"]);
+ });
+});
+
+describe("filterEventNameRows", () => {
+ const rows = [row({ eventName: "Signup" }), row({ eventName: "cta_click" })];
+
+ it("returns everything for an empty or blank search", () => {
+ expect(filterEventNameRows(rows, "")).toBe(rows);
+ expect(filterEventNameRows(rows, " ")).toBe(rows);
+ });
+
+ it("matches part of a name, ignoring case", () => {
+ expect(filterEventNameRows(rows, " SIGN ").map(item => item.eventName)).toEqual(["Signup"]);
+ expect(filterEventNameRows(rows, "missing")).toEqual([]);
+ });
+});
diff --git a/client/src/app/[site]/events/utils/eventNameRows.ts b/client/src/app/[site]/events/utils/eventNameRows.ts
new file mode 100644
index 000000000..b6e085fd7
--- /dev/null
+++ b/client/src/app/[site]/events/utils/eventNameRows.ts
@@ -0,0 +1,106 @@
+import { DateTime } from "luxon";
+import { EventName, EventNameStats } from "../../../../api/analytics/endpoints";
+
+export interface EventNameRow {
+ eventName: string;
+ count: number;
+ users: number;
+ /** Events per user who fired it. */
+ perUser: number;
+ /** Share of every custom event in the period, 0–1. */
+ share: number;
+ /** Null when the timestamp cannot be read. */
+ lastSeen: DateTime | null;
+ /** One value per trend bucket up to now, oldest first. */
+ trend: number[];
+ /** The comparison period's count. Undefined when there is no comparison. */
+ previousCount: number | undefined;
+}
+
+export type EventNameSortKey = "name" | "count" | "users" | "perUser" | "change" | "lastSeen";
+export type SortDirection = "asc" | "desc";
+
+/**
+ * Joins the period's per-name stats to the comparison period's counts.
+ *
+ * `now` trims the trend: the server fills buckets to the end of the period, so
+ * a month in progress would otherwise end in a run of zeros for days that have
+ * not happened.
+ */
+export function buildEventNameRows(
+ stats: EventNameStats | undefined,
+ previous: EventName[] | undefined,
+ zone: string,
+ now: DateTime = DateTime.now()
+): EventNameRow[] {
+ if (!stats) return [];
+
+ const started = stats.buckets.filter(bucket => {
+ const time = DateTime.fromSQL(bucket, { zone });
+ return !time.isValid || time <= now;
+ }).length;
+ const total = stats.events.reduce((sum, event) => sum + event.count, 0);
+ const previousCounts = previous ? new Map(previous.map(event => [String(event.eventName), event.count])) : null;
+
+ return stats.events.map(event => {
+ const lastSeen = DateTime.fromSQL(event.lastSeen, { zone: "utc" });
+ return {
+ eventName: event.eventName,
+ count: event.count,
+ users: event.users,
+ perUser: event.users > 0 ? event.count / event.users : 0,
+ share: total > 0 ? event.count / total : 0,
+ lastSeen: lastSeen.isValid ? lastSeen : null,
+ trend: event.trend.slice(0, started),
+ // A name missing from the comparison period fired zero times in it.
+ previousCount: previousCounts ? (previousCounts.get(event.eventName) ?? 0) : undefined,
+ };
+ });
+}
+
+/** Names in the period that the comparison period does not have. Undefined when there is no comparison. */
+export function countNewEventNames(
+ stats: EventNameStats | undefined,
+ previous: EventName[] | undefined
+): number | undefined {
+ if (!stats || !previous) return undefined;
+ const before = new Set(previous.map(event => String(event.eventName)));
+ return stats.events.filter(event => !before.has(event.eventName)).length;
+}
+
+// Relative change, with a name that is new in this period ranked above any finite rise.
+const changeOf = (row: EventNameRow): number => {
+ if (row.previousCount === undefined) return 0;
+ if (row.previousCount === 0) return row.count > 0 ? Number.POSITIVE_INFINITY : 0;
+ return (row.count - row.previousCount) / row.previousCount;
+};
+
+const SORT_VALUE: Record<Exclude<EventNameSortKey, "name">, (row: EventNameRow) => number> = {
+ count: row => row.count,
+ users: row => row.users,
+ perUser: row => row.perUser,
+ change: changeOf,
+ lastSeen: row => row.lastSeen?.toMillis() ?? 0,
+};
+
+/** Ties fall back to the count, then the name, so the order never shuffles between renders. */
+export function sortEventNameRows(
+ rows: EventNameRow[],
+ key: EventNameSortKey,
+ direction: SortDirection
+): EventNameRow[] {
+ const sign = direction === "asc" ? 1 : -1;
+ return rows.toSorted((a, b) => {
+ if (key === "name") return sign * a.eventName.localeCompare(b.eventName);
+ const value = SORT_VALUE[key];
+ const difference = value(a) - value(b);
+ // Infinity - Infinity is NaN: two new names tie.
+ const primary = Number.isNaN(difference) ? 0 : difference;
+ return sign * primary || b.count - a.count || a.eventName.localeCompare(b.eventName);
+ });
+}
+
+export function filterEventNameRows(rows: EventNameRow[], search: string): EventNameRow[] {
+ const query = search.trim().toLowerCase();
+ return query ? rows.filter(row => row.eventName.toLowerCase().includes(query)) : rows;
+}
diff --git a/client/src/app/[site]/events/utils/eventTypes.ts b/client/src/app/[site]/events/utils/eventTypes.ts
new file mode 100644
index 000000000..08f0b4852
--- /dev/null
+++ b/client/src/app/[site]/events/utils/eventTypes.ts
@@ -0,0 +1,76 @@
+import { SiteEventCountPoint } from "../../../../api/analytics/endpoints";
+
+/**
+ * Series colours for this page's charts: the data hue leads, then a ramp whose
+ * steps differ in lightness as well as hue. No emerald (it means action) and
+ * no red (it means a problem).
+ */
+export const SERIES_COLORS = [
+ "hsl(var(--dataviz))",
+ "hsl(var(--orange-400))",
+ "hsl(var(--teal-500))",
+ "hsl(var(--pink-400))",
+ "hsl(var(--amber-300))",
+ "hsl(var(--violet-500))",
+ "hsl(var(--neutral-400))",
+ "hsl(var(--sky-400))",
+ "hsl(var(--lime-400))",
+ "hsl(var(--rose-300))",
+] as const;
+
+export const seriesColor = (index: number) => SERIES_COLORS[index % SERIES_COLORS.length];
+
+/** Every type the events/count endpoint breaks out, including web vitals. */
+export type ChartEventType =
+ | "custom_event"
+ | "button_click"
+ | "outbound"
+ | "input_change"
+ | "copy"
+ | "form_submit"
+ | "error"
+ | "pageview"
+ | "performance";
+
+type CountKey = Exclude<keyof SiteEventCountPoint, "time" | "event_count">;
+
+export interface EventTypeSeries {
+ type: ChartEventType;
+ countKey: CountKey;
+ color: string;
+ /** One row per pageview: on the same axis it flattens every other type. */
+ hiddenByDefault?: boolean;
+ /** False where a rise is bad news. */
+ upIsGood?: boolean;
+}
+
+// The order is the legend's, and it fixes each type's colour.
+export const EVENT_TYPE_SERIES: EventTypeSeries[] = [
+ { type: "custom_event", countKey: "custom_event_count", color: SERIES_COLORS[0] },
+ { type: "button_click", countKey: "button_click_count", color: SERIES_COLORS[1] },
+ { type: "outbound", countKey: "outbound_count", color: SERIES_COLORS[2] },
+ { type: "input_change", countKey: "input_change_count", color: SERIES_COLORS[3] },
+ { type: "copy", countKey: "copy_count", color: SERIES_COLORS[4] },
+ { type: "form_submit", countKey: "form_submit_count", color: SERIES_COLORS[5] },
+ { type: "error", countKey: "error_count", color: SERIES_COLORS[6], upIsGood: false },
+ { type: "pageview", countKey: "pageview_count", color: SERIES_COLORS[7], hiddenByDefault: true },
+ { type: "performance", countKey: "performance_count", color: SERIES_COLORS[8], hiddenByDefault: true },
+];
+
+export const DEFAULT_HIDDEN_TYPES: ReadonlySet<string> = new Set(
+ EVENT_TYPE_SERIES.filter(series => series.hiddenByDefault).map(series => series.type)
+);
+
+/** The period's total for each type. */
+export function totalsByType(points: SiteEventCountPoint[] | undefined): Record<ChartEventType, number> {
+ const totals = Object.fromEntries(EVENT_TYPE_SERIES.map(series => [series.type, 0])) as Record<
+ ChartEventType,
+ number
+ >;
+ for (const point of points ?? []) {
+ for (const series of EVENT_TYPE_SERIES) {
+ totals[series.type] += Number(point[series.countKey]) || 0;
+ }
+ }
+ return totals;
+}
diff --git a/client/src/app/[site]/events/utils/eventsPageUtils.test.ts b/client/src/app/[site]/events/utils/eventsPageUtils.test.ts
new file mode 100644
index 000000000..9ca515a5d
--- /dev/null
+++ b/client/src/app/[site]/events/utils/eventsPageUtils.test.ts
@@ -0,0 +1,169 @@
+import { describe, expect, it } from "vitest";
+import { Goal, SavedFunnel, SiteEventCountPoint } from "../../../../api/analytics/endpoints";
+import { DEFAULT_HIDDEN_TYPES, EVENT_TYPE_SERIES, SERIES_COLORS, seriesColor, totalsByType } from "./eventTypes";
+import { formatShare, groupProperties } from "./properties";
+import { funnelsForEvent, goalsForEvent, silentEventDailyAverage } from "./usedIn";
+
+const goal = (goalId: number, goalType: Goal["goalType"], config: Goal["config"]): Goal => ({
+ goalId,
+ name: `Goal ${goalId}`,
+ goalType,
+ config,
+ createdAt: "2026-01-01",
+ total_conversions: 0,
+ total_sessions: 0,
+ conversion_rate: 0,
+});
+
+const funnel = (id: number, steps: SavedFunnel["steps"]): SavedFunnel => ({
+ id,
+ name: `Funnel ${id}`,
+ steps,
+ createdAt: "2026-01-01",
+ updatedAt: "2026-01-01",
+ conversionRate: null,
+ totalVisitors: null,
+});
+
+describe("goalsForEvent", () => {
+ const goals = [
+ goal(1, "event", { eventName: "signup" }),
+ goal(2, "event", { eventName: "signup_started" }),
+ goal(3, "path", { pathPattern: "/signup" }),
+ goal(4, "button_click", { valuePattern: "signup" }),
+ goal(5, "event", { eventName: "signup", propertyFilters: [{ key: "method", value: "google" }] }),
+ ];
+
+ it("returns the event goals on exactly this name", () => {
+ expect(goalsForEvent(goals, "signup").map(item => item.goalId)).toEqual([1, 5]);
+ });
+
+ it("is empty for an event nothing measures and while goals are unknown", () => {
+ expect(goalsForEvent(goals, "cta_click")).toEqual([]);
+ expect(goalsForEvent(undefined, "signup")).toEqual([]);
+ });
+});
+
+describe("funnelsForEvent", () => {
+ const funnels = [
+ funnel(1, [
+ { type: "page", value: "/pricing" },
+ { type: "event", value: "signup" },
+ ]),
+ funnel(2, [
+ { type: "page", value: "signup" },
+ { type: "button_click", value: "signup" },
+ ]),
+ funnel(3, [{ type: "event", value: "signup" }]),
+ ];
+
+ it("returns the funnels with an event step on this name", () => {
+ expect(funnelsForEvent(funnels, "signup").map(item => item.id)).toEqual([1, 3]);
+ });
+
+ it("ignores page and autocapture steps that happen to share the text", () => {
+ expect(funnelsForEvent([funnels[1]], "signup")).toEqual([]);
+ expect(funnelsForEvent(undefined, "signup")).toEqual([]);
+ });
+});
+
+describe("silentEventDailyAverage", () => {
+ it("averages over the days between the first and last occurrence", () => {
+ expect(silentEventDailyAverage({ total: 66, spanDays: 22 })).toBe(3);
+ });
+
+ it("does not divide by zero", () => {
+ expect(silentEventDailyAverage({ total: 5, spanDays: 0 })).toBe(0);
+ });
+});
+
+describe("event type series", () => {
+ const point = (overrides: Partial<SiteEventCountPoint>): SiteEventCountPoint => ({
+ time: "2026-09-01 00:00:00",
+ pageview_count: 0,
+ custom_event_count: 0,
+ performance_count: 0,
+ outbound_count: 0,
+ error_count: 0,
+ button_click_count: 0,
+ copy_count: 0,
+ form_submit_count: 0,
+ input_change_count: 0,
+ event_count: 0,
+ ...overrides,
+ });
+
+ it("leads with the data hue and never repeats a colour across the types", () => {
+ expect(EVENT_TYPE_SERIES[0]).toMatchObject({ type: "custom_event", color: "hsl(var(--dataviz))" });
+ expect(new Set(EVENT_TYPE_SERIES.map(series => series.color)).size).toBe(EVENT_TYPE_SERIES.length);
+ });
+
+ it("hides the per-pageview types by default and nothing else", () => {
+ expect([...DEFAULT_HIDDEN_TYPES].sort()).toEqual(["pageview", "performance"]);
+ });
+
+ it("treats only a rise in errors as bad news", () => {
+ expect(EVENT_TYPE_SERIES.filter(series => series.upIsGood === false).map(series => series.type)).toEqual(["error"]);
+ });
+
+ it("wraps around when there are more series than colours", () => {
+ expect(seriesColor(0)).toBe(SERIES_COLORS[0]);
+ expect(seriesColor(SERIES_COLORS.length)).toBe(SERIES_COLORS[0]);
+ });
+
+ it("sums each type over the period", () => {
+ const totals = totalsByType([
+ point({ custom_event_count: 4, pageview_count: 10, error_count: 1 }),
+ point({ custom_event_count: 6, pageview_count: 5 }),
+ ]);
+
+ expect(totals.custom_event).toBe(10);
+ expect(totals.pageview).toBe(15);
+ expect(totals.error).toBe(1);
+ expect(totals.copy).toBe(0);
+ });
+
+ it("is all zeros before the data arrives", () => {
+ expect(Object.values(totalsByType(undefined)).every(total => total === 0)).toBe(true);
+ });
+});
+
+describe("groupProperties", () => {
+ it("orders keys by the events that carry them and values by count", () => {
+ const groups = groupProperties([
+ { propertyKey: "referral_code", propertyValue: "HN", count: 4 },
+ { propertyKey: "method", propertyValue: "email", count: 30 },
+ { propertyKey: "method", propertyValue: "google", count: 50 },
+ { propertyKey: "referral_code", propertyValue: "NORTH", count: 6 },
+ ]);
+
+ expect(groups.map(group => [group.key, group.total])).toEqual([
+ ["method", 80],
+ ["referral_code", 10],
+ ]);
+ expect(groups[0].values.map(value => value.propertyValue)).toEqual(["google", "email"]);
+ expect(groups[1].values.map(value => value.propertyValue)).toEqual(["NORTH", "HN"]);
+ });
+
+ it("is empty for an event sent without properties", () => {
+ expect(groupProperties([])).toEqual([]);
+ });
+});
+
+describe("formatShare", () => {
+ it.each([
+ [1, "100%"],
+ [0.51, "51%"],
+ [0.104, "10%"],
+ [0.062, "6.2%"],
+ [0.0004, "0.0%"],
+ [0, "0.0%"],
+ ])("prints %s as %s", (fraction, expected) => {
+ expect(formatShare(fraction)).toBe(expected);
+ });
+
+ it("never rounds a part up to the whole", () => {
+ expect(formatShare(0.996)).toBe("99.6%");
+ expect(formatShare(0.99999)).toBe("99.9%");
+ });
+});
diff --git a/client/src/app/[site]/events/utils/properties.ts b/client/src/app/[site]/events/utils/properties.ts
new file mode 100644
index 000000000..7ab388c6d
--- /dev/null
+++ b/client/src/app/[site]/events/utils/properties.ts
@@ -0,0 +1,32 @@
+import { EventProperty } from "../../../../api/analytics/endpoints";
+
+export type PropertyGroup = {
+ key: string;
+ /** The key's values, most frequent first. */
+ values: EventProperty[];
+ /** Events that carried the key: an event has one value per key, so the values add up to it. */
+ total: number;
+};
+
+/** Property keys by how many events carry them, each key's values by count. */
+export function groupProperties(properties: EventProperty[]): PropertyGroup[] {
+ const groups = new Map<string, PropertyGroup>();
+ for (const property of properties) {
+ const key = String(property.propertyKey);
+ const group = groups.get(key) ?? { key, values: [], total: 0 };
+ group.values.push(property);
+ group.total += property.count;
+ groups.set(key, group);
+ }
+ return Array.from(groups.values())
+ .map(group => ({ ...group, values: group.values.toSorted((a, b) => b.count - a.count) }))
+ .sort((a, b) => b.total - a.total || a.key.localeCompare(b.key));
+}
+
+/** A share as the tables print it: whole percents, one decimal under 10%, and no "100%" short of all of it. */
+export function formatShare(fraction: number): string {
+ if (fraction >= 1) return "100%";
+ const percent = fraction * 100;
+ if (percent >= 99.5) return `${Math.min(percent, 99.9).toFixed(1)}%`;
+ return `${percent.toFixed(percent < 10 ? 1 : 0)}%`;
+}
diff --git a/client/src/app/[site]/events/utils/trendBucket.test.ts b/client/src/app/[site]/events/utils/trendBucket.test.ts
new file mode 100644
index 000000000..38f9ab793
--- /dev/null
+++ b/client/src/app/[site]/events/utils/trendBucket.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vitest";
+import { Time } from "../../../../components/DateSelector/types";
+import { trendBucketFor } from "./trendBucket";
+
+const ZONE = "America/New_York";
+
+describe("trendBucketFor", () => {
+ it.each<[string, Time, string]>([
+ ["a single day", { mode: "day", day: "2026-09-30" }, "hour"],
+ ["the last 24 hours", { mode: "past-minutes", pastMinutesStart: 1440, pastMinutesEnd: 0 }, "hour"],
+ ["two days", { mode: "range", startDate: "2026-09-29", endDate: "2026-09-30" }, "hour"],
+ ["three days", { mode: "range", startDate: "2026-09-28", endDate: "2026-09-30" }, "day"],
+ ["a week", { mode: "week", week: "2026-09-21" }, "day"],
+ ["the last 30 days", { mode: "range", startDate: "2026-09-01", endDate: "2026-09-30" }, "day"],
+ ["a month", { mode: "month", month: "2026-09-01" }, "day"],
+ ["the last 60 days", { mode: "range", startDate: "2026-08-02", endDate: "2026-09-30" }, "day"],
+ ["a quarter", { mode: "range", startDate: "2026-07-01", endDate: "2026-09-30" }, "week"],
+ ["a year", { mode: "year", year: "2026-01-01" }, "week"],
+ ["two years", { mode: "range", startDate: "2024-10-01", endDate: "2026-09-30" }, "month"],
+ ["all time", { mode: "all-time" }, "month"],
+ ])("draws %s by the %3$s", (_name, time, expected) => {
+ expect(trendBucketFor(time, ZONE)).toBe(expected);
+ });
+
+ it("reads a range with times by its real length", () => {
+ const time: Time = {
+ mode: "range",
+ startDate: "2026-09-30",
+ startTime: "09:00",
+ endDate: "2026-09-30",
+ endTime: "17:00",
+ };
+
+ expect(trendBucketFor(time, ZONE)).toBe("hour");
+ });
+});
diff --git a/client/src/app/[site]/events/utils/trendBucket.ts b/client/src/app/[site]/events/utils/trendBucket.ts
new file mode 100644
index 000000000..06839baf7
--- /dev/null
+++ b/client/src/app/[site]/events/utils/trendBucket.ts
@@ -0,0 +1,21 @@
+import { EventTrendBucket } from "../../../../api/analytics/endpoints";
+import { Time } from "../../../../components/DateSelector/types";
+import { getAbsoluteBounds } from "../../../../lib/time";
+
+const HOURS_PER_DAY = 24;
+
+/**
+ * The bucket a row's trend is drawn in. A sparkline is 84px wide, so it wants
+ * a few dozen points whatever the period: hours up to two days, days up to two
+ * months, weeks up to about a year, months beyond that and for all time.
+ */
+export function trendBucketFor(time: Time, zone: string): EventTrendBucket {
+ const bounds = getAbsoluteBounds(time, zone);
+ if (!bounds) return "month";
+
+ const hours = bounds.end.diff(bounds.start, "hours").hours;
+ if (hours <= 2 * HOURS_PER_DAY) return "hour";
+ if (hours <= 62 * HOURS_PER_DAY) return "day";
+ if (hours <= 400 * HOURS_PER_DAY) return "week";
+ return "month";
+}
diff --git a/client/src/app/[site]/events/utils/usedIn.ts b/client/src/app/[site]/events/utils/usedIn.ts
new file mode 100644
index 000000000..51f30198c
--- /dev/null
+++ b/client/src/app/[site]/events/utils/usedIn.ts
@@ -0,0 +1,16 @@
+import { Goal, SavedFunnel, SilentEvent } from "../../../../api/analytics/endpoints";
+
+/** The goals that complete on this custom event. Event goals match the name exactly. */
+export function goalsForEvent(goals: Goal[] | undefined, eventName: string): Goal[] {
+ return (goals ?? []).filter(goal => goal.goalType === "event" && goal.config.eventName === eventName);
+}
+
+/** The saved funnels with a step on this custom event. */
+export function funnelsForEvent(funnels: SavedFunnel[] | undefined, eventName: string): SavedFunnel[] {
+ return (funnels ?? []).filter(funnel => funnel.steps.some(step => step.type === "event" && step.value === eventName));
+}
+
+/** How often a silent event fired per day, over the days between its first and last occurrence in the lookback. */
+export function silentEventDailyAverage(event: Pick<SilentEvent, "total" | "spanDays">): number {
+ return event.spanDays > 0 ? event.total / event.spanDays : 0;
+}
diff --git a/client/src/app/[site]/funnels/components/CreateFunnel.tsx b/client/src/app/[site]/funnels/components/CreateFunnel.tsx
index 571fa4e52..3298ce00a 100644
--- a/client/src/app/[site]/funnels/components/CreateFunnel.tsx
+++ b/client/src/app/[site]/funnels/components/CreateFunnel.tsx
@@ -67,8 +67,8 @@ export function CreateFunnelDialog() {
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
- <Button className="flex gap-2">
- <Plus className="w-4 h-4" /> {t("Create Funnel")}
+ <Button variant="accent" size="sm">
+ <Plus /> {t("Create funnel")}
</Button>
</DialogTrigger>
<DialogContentFullScreen
diff --git a/client/src/app/[site]/funnels/components/Funnel.test.tsx b/client/src/app/[site]/funnels/components/Funnel.test.tsx
new file mode 100644
index 000000000..4f90a59a6
--- /dev/null
+++ b/client/src/app/[site]/funnels/components/Funnel.test.tsx
@@ -0,0 +1,204 @@
+import React, { ReactNode } from "react";
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { FunnelStep } from "@/api/analytics/endpoints";
+import { useStore } from "@/lib/store";
+import { computeFunnelMetrics } from "./funnelMetrics";
+
+const mocks = vi.hoisted(() => ({
+ replayAvailable: true,
+ stepSessions: vi.fn(),
+}));
+
+vi.mock("next-intl", () => {
+ const format = (message: string, values: Record<string, unknown> = {}) =>
+ message.replace(/\{(\w+)\}/g, (_, key: string) => String(values[key] ?? key));
+ const t = Object.assign(format, {
+ rich: (message: string, values?: Record<string, unknown>) => format(message.replace(/<\/?\w+>/g, ""), values),
+ });
+ return { useExtracted: () => t };
+});
+vi.mock("next/navigation", () => ({ useSearchParams: () => new URLSearchParams() }));
+vi.mock("next/link", () => ({
+ default: ({ href, children, prefetch, ...props }: { href: string; children: ReactNode; prefetch?: boolean }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+vi.mock("@/hooks/useReplayAvailable", () => ({ useReplayAvailable: () => mocks.replayAvailable }));
+vi.mock("@/hooks/usePermissions", () => ({ useCanOnSite: () => true }));
+vi.mock("@/app/[site]/components/SubHeader/Filters/SegmentDialog", () => ({ SegmentDialog: () => null }));
+vi.mock("@/api/analytics/hooks/funnels/useGetFunnelStepSessions", () => ({
+ useGetFunnelStepSessions: (options: unknown) => {
+ mocks.stepSessions(options);
+ return { data: [], isLoading: false };
+ },
+}));
+vi.mock("@/components/Sessions/SessionsList", () => ({
+ SessionsList: ({ headerElement, emptyMessage }: { headerElement: ReactNode; emptyMessage: string }) => (
+ <div data-testid="sessions-list">
+ {headerElement}
+ <p>{emptyMessage}</p>
+ </div>
+ ),
+}));
+
+import { Funnel } from "./Funnel";
+
+const steps: FunnelStep[] = [
+ { type: "page", value: "/**", name: "Any page" },
+ { type: "page", value: "/pricing", name: "Pricing" },
+ { type: "event", value: "signup", name: "Signed up", propertyFilters: [{ key: "plan", value: "pro" }] },
+];
+
+// 84,210 enter, 17,920 see pricing, 3,984 sign up.
+const metrics = computeFunnelMetrics(
+ [{ sessions: 84210, medianSecondsToNext: 58 }, { sessions: 17920, medianSecondsToNext: 81 }, { sessions: 3984 }],
+ 708
+);
+const previous = computeFunnelMetrics([{ sessions: 74930 }, { sessions: 15692 }, { sessions: 3388 }]);
+
+const lastRequest = () => mocks.stepSessions.mock.calls.at(-1)?.[0];
+
+beforeEach(() => {
+ mocks.replayAvailable = true;
+ useStore.setState({ site: "42", timezone: "UTC" });
+});
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("Funnel", () => {
+ it("states each step's sessions and share of the first step", () => {
+ const { container } = render(<Funnel steps={steps} metrics={metrics} />);
+
+ expect(container.textContent).toContain("84,210");
+ expect(container.textContent).toContain("17,920");
+ expect(container.textContent).toContain("21.3%");
+ expect(container.textContent).toContain("3,984");
+ expect(container.textContent).toContain("4.7%");
+ // What a step matches, under its name.
+ expect(screen.getByText("Page · /pricing")).toBeTruthy();
+ expect(screen.getByText("Event · signup · plan = pro")).toBeTruthy();
+ });
+
+ it("puts the drop-off on the step people left", () => {
+ render(<Funnel steps={steps} metrics={metrics} />);
+
+ // 84,210 - 17,920 left after the first step; 17,920 - 3,984 after pricing.
+ const firstStep = screen.getByRole("button", { name: /Any page/ });
+ const afterFirst = firstStep.nextElementSibling as HTMLElement;
+ expect(afterFirst.textContent).toContain("21.3%continue");
+ expect(afterFirst.textContent).toContain("66,290 dropped here · 78.7%");
+ expect(afterFirst.textContent).toContain("58s median to next step");
+
+ const afterPricing = screen.getByRole("button", { name: /Pricing/ }).nextElementSibling as HTMLElement;
+ expect(afterPricing.textContent).toContain("13,936 dropped here · 77.8%");
+ expect(afterPricing.textContent).toContain("1m 21s median to next step");
+ });
+
+ it("closes with the overall conversion and the time from the first step", () => {
+ const { container } = render(<Funnel steps={steps} metrics={metrics} />);
+
+ expect(container.textContent).toContain("4.7%overall");
+ expect(container.textContent).toContain("3,984 converted");
+ expect(container.textContent).toContain("11m 48s median from first step");
+ });
+
+ it("draws step and overall changes only against a comparison period", () => {
+ const alone = render(<Funnel steps={steps} metrics={metrics} />);
+ expect(alone.container.textContent).not.toContain(" pp");
+ expect(alone.container.textContent).not.toContain("Compared with");
+ cleanup();
+
+ const compared = render(
+ <Funnel steps={steps} metrics={metrics} previous={previous} comparisonLabel="Aug 2 – Aug 31" />
+ );
+ // 21.3% continue against 20.9%; 4.73% overall against 4.52%.
+ expect(compared.container.textContent).toContain("0.3 pp");
+ expect(compared.container.textContent).toContain("0.2 pp");
+ expect(compared.container.textContent).toContain("Compared with Aug 2 – Aug 31");
+ });
+
+ it("opens the sessions that left at a step from that step's drop-off", () => {
+ render(<Funnel steps={steps} metrics={metrics} />);
+ const afterPricing = screen.getByRole("button", { name: /Pricing/ }).nextElementSibling as HTMLElement;
+
+ fireEvent.click(within(afterPricing).getByRole("button", { name: "Sessions" }));
+
+ // Reached step 2 and not step 3.
+ expect(lastRequest()).toMatchObject({ steps, stepNumber: 2, mode: "dropped", replaysOnly: false, enabled: true });
+ expect(screen.getByText("Sessions that dropped off after Pricing")).toBeTruthy();
+
+ fireEvent.click(within(afterPricing).getByRole("button", { name: "Replays" }));
+ expect(lastRequest()).toMatchObject({ stepNumber: 2, mode: "dropped", replaysOnly: true });
+ expect(screen.getByText("Replays of sessions that dropped off after Pricing")).toBeTruthy();
+ expect(screen.getAllByTestId("sessions-list").length).toBe(1);
+ });
+
+ it("closes the list when its pivot is clicked again or it is dismissed", () => {
+ render(<Funnel steps={steps} metrics={metrics} />);
+ const afterFirst = screen.getByRole("button", { name: /Any page/ }).nextElementSibling as HTMLElement;
+ const sessions = within(afterFirst).getByRole("button", { name: "Sessions" });
+
+ fireEvent.click(sessions);
+ expect(screen.getByTestId("sessions-list")).toBeTruthy();
+ fireEvent.click(sessions);
+ expect(screen.queryByTestId("sessions-list")).toBeNull();
+
+ fireEvent.click(sessions);
+ fireEvent.click(screen.getByRole("button", { name: "Close sessions" }));
+ expect(screen.queryByTestId("sessions-list")).toBeNull();
+ });
+
+ it("opens the sessions that reached a step from the step itself", () => {
+ render(<Funnel steps={steps} metrics={metrics} />);
+
+ fireEvent.click(screen.getByRole("button", { name: /Pricing/ }));
+
+ expect(lastRequest()).toMatchObject({ stepNumber: 2, mode: "reached", replaysOnly: false });
+ expect(screen.getByText("Sessions that reached Pricing")).toBeTruthy();
+ expect(screen.getByRole("button", { name: /Pricing/ }).getAttribute("aria-expanded")).toBe("true");
+ });
+
+ it("opens the converted sessions from the outcome line", () => {
+ render(<Funnel steps={steps} metrics={metrics} />);
+ const outcome = screen.getByText("overall").closest("div")!.parentElement as HTMLElement;
+
+ fireEvent.click(within(outcome).getByRole("button", { name: "Sessions" }));
+
+ expect(lastRequest()).toMatchObject({ stepNumber: 3, mode: "reached", replaysOnly: false });
+ expect(screen.getByText("Sessions that converted")).toBeTruthy();
+ });
+
+ it("offers no replays on a site without replay", () => {
+ mocks.replayAvailable = false;
+ render(<Funnel steps={steps} metrics={metrics} />);
+
+ expect(screen.queryByRole("button", { name: "Replays" })).toBeNull();
+ expect(screen.getAllByRole("button", { name: "Sessions" }).length).toBe(3);
+ });
+
+ it("offers no sessions where nobody dropped or converted", () => {
+ const allTheWay = computeFunnelMetrics([{ sessions: 10 }, { sessions: 10 }, { sessions: 0 }]);
+ render(<Funnel steps={steps} metrics={allTheWay} />);
+
+ // Nobody left after step 1; all 10 left after step 2; nobody converted.
+ expect(screen.getAllByRole("button", { name: "Sessions" }).length).toBe(1);
+ });
+
+ it("links the last step to its goal", () => {
+ render(<Funnel steps={steps} metrics={metrics} goal={{ name: "Signup", href: "/42/goals" }} />);
+
+ expect(screen.getByRole("link", { name: /Goal: Signup/ }).getAttribute("href")).toBe("/42/goals");
+ });
+
+ it("survives a preview whose steps are ahead of its figures", () => {
+ // The builder removed a step; the last analysis still has three.
+ const { container } = render(<Funnel steps={steps.slice(0, 2)} metrics={metrics} />);
+
+ expect(container.textContent).toContain("Step 3");
+ });
+});
diff --git a/client/src/app/[site]/funnels/components/Funnel.tsx b/client/src/app/[site]/funnels/components/Funnel.tsx
index dc17e543b..a19d17ab9 100644
--- a/client/src/app/[site]/funnels/components/Funnel.tsx
+++ b/client/src/app/[site]/funnels/components/Funnel.tsx
@@ -1,288 +1,385 @@
"use client";
+import { Clock, Rewind, Target, Video, X } from "lucide-react";
import { useExtracted } from "next-intl";
-import round from "lodash/round";
-import { ChevronDown, ChevronUp } from "lucide-react";
-import { useState } from "react";
-import { FunnelResponse, FunnelStep, FunnelStepType } from "../../../../api/analytics/endpoints";
-import { useGetFunnelStepSessions } from "../../../../api/analytics/hooks/funnels/useGetFunnelStepSessions";
-import { EventTypeIcon } from "../../../../components/EventIcons";
-import { targetTypeToEventType } from "../../../../lib/events";
-import { SessionsList } from "../../../../components/Sessions/SessionsList";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../components/ui/basic-tabs";
-import { useStore } from "../../../../lib/store";
-
-export type FunnelChartData = {
- stepName: string;
- sessions: number;
- conversionRate: number;
- dropoffRate: number;
- stepNumber: number;
-};
-
-interface FunnelProps {
- data?: FunnelResponse[] | undefined;
- isError: boolean;
- error: unknown;
- isPending: boolean;
- steps: FunnelStep[];
-}
+import Link from "next/link";
+import { Fragment, ReactNode, useState } from "react";
+import { FunnelStep } from "@/api/analytics/endpoints";
+import { useGetFunnelStepSessions } from "@/api/analytics/hooks/funnels/useGetFunnelStepSessions";
+import { EventTypeIcon } from "@/components/EventIcons";
+import { SessionsList } from "@/components/Sessions/SessionsList";
+import { Delta } from "@/components/site/Delta";
+import { PivotActions, PivotButton } from "@/components/site/PivotActions";
+import { Button } from "@/components/ui/button";
+import { useReplayAvailable } from "@/hooks/useReplayAvailable";
+import { resolvePropertyFilters, targetTypeToEventType } from "@/lib/events";
+import { useStore } from "@/lib/store";
+import { cn } from "@/lib/utils";
+import { formatRate, formatStepDuration, FunnelMetrics, rateDelta, stepLabel, StepMetrics } from "./funnelMetrics";
+import { useStepTypeLabels } from "./useStepTypeLabels";
const LIMIT = 25;
-interface FunnelStepComponentProps {
- step: FunnelChartData;
- index: number;
- steps: FunnelStep[];
- chartData: FunnelChartData[];
- firstStep: FunnelChartData | undefined;
- siteId: number;
-}
+const MUTED = "text-neutral-500 dark:text-neutral-400";
+const STRONG = "font-medium tabular-nums text-neutral-900 dark:text-neutral-100";
-function FunnelStepComponent({ step, index, steps, chartData, firstStep, siteId }: FunnelStepComponentProps) {
- const t = useExtracted();
+// Number, step, bar, sessions, share of start. The columns follow the width of
+// the funnel itself (a container query), not the window: beside the sidebar or
+// in the builder's preview pane it has far less room than the viewport
+// suggests. When narrow, the bar drops to its own line.
+const STEP_GRID =
+ "grid grid-cols-[24px_minmax(0,1fr)_auto] items-center gap-x-3 @2xl:grid-cols-[24px_208px_minmax(0,1fr)_76px_64px]";
+// The line between two steps: what happened to the sessions that reached the step above.
+const LINK_GRID = "grid grid-cols-[24px_minmax(0,1fr)] items-center gap-x-3 @2xl:grid-cols-[24px_208px_minmax(0,1fr)]";
- const stepTypeLabels: Record<FunnelStepType, string> = {
- page: t("Page"),
- event: t("Event"),
- outbound: t("Outbound"),
- button_click: t("Button"),
- form_submit: t("Form"),
- copy: t("Copy"),
- };
+// The data hue in both encodings: solid for the share of the first step,
+// hatched for the share of the step before. The hatch is stronger on the light
+// theme's pale track.
+const SOLID = "bg-dataviz";
+const HATCH =
+ "bg-[repeating-linear-gradient(45deg,hsl(var(--dataviz)/0.6)_0_5px,hsl(var(--dataviz)/0.3)_5px_10px)] dark:bg-[repeating-linear-gradient(45deg,hsl(var(--dataviz)/0.3)_0_5px,hsl(var(--dataviz)/0.14)_5px_10px)]";
- const [isExpanded, setIsExpanded] = useState(false);
- const [currentTab, setCurrentTab] = useState<"reached" | "dropped">("reached");
- const [reachedPage, setReachedPage] = useState(1);
- const [droppedPage, setDroppedPage] = useState(1);
- const { time } = useStore();
+/** Which sessions are listed under the chart: the ones that reached a step, or the ones that left after it. */
+interface SessionsPanel {
+ stepIndex: number;
+ mode: "reached" | "dropped";
+ replaysOnly: boolean;
+}
- const maxBarWidth = 100;
- const ratio = firstStep?.sessions ? step.sessions / firstStep.sessions : 0;
- const barWidth = Math.max(ratio * maxBarWidth, 0);
+const samePanel = (a: SessionsPanel | null, b: SessionsPanel) =>
+ !!a && a.stepIndex === b.stepIndex && a.mode === b.mode && a.replaysOnly === b.replaysOnly;
- const prevStep = index > 0 ? chartData[index - 1] : null;
- const droppedFromPrevious = prevStep ? prevStep.sessions - step.sessions : 0;
- const dropoffPercent = prevStep ? (droppedFromPrevious / prevStep.sessions) * 100 : 0;
- const isFirstStep = index === 0;
+function StepSessions({
+ steps,
+ panel,
+ title,
+ onClose,
+}: {
+ steps: FunnelStep[];
+ panel: SessionsPanel;
+ title: string;
+ onClose: () => void;
+}) {
+ const t = useExtracted();
+ const site = useStore(state => state.site);
+ const time = useStore(state => state.time);
+ const [page, setPage] = useState(1);
- // Fetch sessions for "reached" mode
- const { data: reachedData, isLoading: isLoadingReached } = useGetFunnelStepSessions({
+ const { data, isLoading } = useGetFunnelStepSessions({
steps,
- stepNumber: step.stepNumber,
- siteId,
+ stepNumber: panel.stepIndex + 1,
+ siteId: Number(site),
time,
- mode: "reached",
- page: reachedPage,
+ mode: panel.mode,
+ page,
limit: LIMIT + 1,
- enabled: isExpanded && currentTab === "reached",
+ replaysOnly: panel.replaysOnly,
+ enabled: true,
});
- // Fetch sessions for "dropped" mode (only if not first step)
- // For step N, we want sessions that reached step N-1 but NOT step N
- const { data: droppedData, isLoading: isLoadingDropped } = useGetFunnelStepSessions({
- steps,
- stepNumber: step.stepNumber - 1, // Previous step
- siteId,
- time,
- mode: "dropped",
- page: droppedPage,
- limit: LIMIT + 1,
- enabled: isExpanded && currentTab === "dropped" && !isFirstStep,
- });
+ const sessions = data ?? [];
+ const emptyMessage = panel.replaysOnly
+ ? t("None of these sessions has a replay in the selected time period.")
+ : panel.mode === "reached"
+ ? t("No sessions reached this step in the selected time period.")
+ : t("No sessions dropped off after this step in the selected time period.");
+
+ return (
+ <div className="my-2 rounded-lg border border-neutral-100 p-3 dark:border-neutral-800 @2xl:ml-9">
+ <SessionsList
+ sessions={sessions.slice(0, LIMIT)}
+ isLoading={isLoading}
+ page={page}
+ onPageChange={setPage}
+ hasNextPage={sessions.length > LIMIT}
+ hasPrevPage={page > 1}
+ emptyMessage={emptyMessage}
+ pageSize={5}
+ headerElement={
+ <div className="flex min-w-0 items-center gap-1">
+ <Button variant="ghost" size="smIcon" onClick={onClose} aria-label={t("Close sessions")}>
+ <X />
+ </Button>
+ <span className="truncate text-sm font-medium text-neutral-900 dark:text-neutral-100">{title}</span>
+ </div>
+ }
+ />
+ </div>
+ );
+}
+
+function StepBar({ step, isFirst }: { step: StepMetrics; isFirst: boolean }) {
+ return (
+ <div className="relative col-span-2 col-start-2 row-start-2 mt-1 h-8 overflow-hidden rounded-md bg-neutral-100 dark:bg-neutral-800 @2xl:col-span-1 @2xl:col-start-auto @2xl:row-start-auto @2xl:mt-0">
+ {!isFirst && step.sessions > 0 && (
+ <div
+ className={cn("absolute inset-y-0 left-0 rounded-md", HATCH)}
+ style={{ width: `${(step.fromPrevious * 100).toFixed(2)}%` }}
+ />
+ )}
+ {step.sessions > 0 && (
+ <div
+ className={cn("absolute inset-y-0 left-0 rounded-md", SOLID)}
+ style={{ width: `${Math.max(0.5, step.ofStart * 100).toFixed(2)}%` }}
+ />
+ )}
+ </div>
+ );
+}
+
+function MedianTime({ seconds, children }: { seconds: number | null; children: (duration: string) => ReactNode }) {
+ if (seconds === null) return null;
+ return (
+ <div className={cn("flex items-center gap-1 whitespace-nowrap tabular-nums", MUTED)}>
+ <Clock className="h-3 w-3" aria-hidden="true" />
+ {children(formatStepDuration(seconds))}
+ </div>
+ );
+}
+
+export interface FunnelProps {
+ steps: FunnelStep[];
+ /** The selected period. */
+ metrics: FunnelMetrics;
+ /** The comparison period. Step and conversion deltas are drawn against it. */
+ previous?: FunnelMetrics | null;
+ /** The comparison window in words, e.g. "Aug 2 – Aug 31". */
+ comparisonLabel?: string | null;
+ /** The goal that measures the same thing as the last step. */
+ goal?: { name: string; href: string } | null;
+ /** Buttons at the end of the legend row. */
+ actions?: ReactNode;
+}
+
+/**
+ * A funnel, step by step: how many sessions reached each step, what share went
+ * on, and how many left at that step and how long the rest took, stated on the
+ * line under the step they belong to. Every count opens the sessions behind it.
+ */
+export function Funnel({ steps, metrics, previous, comparisonLabel, goal, actions }: FunnelProps) {
+ const t = useExtracted();
+ const typeLabels = useStepTypeLabels();
+ const replayAvailable = useReplayAvailable();
+ const [panel, setPanel] = useState<SessionsPanel | null>(null);
- const allReachedSessions = reachedData || [];
- const hasNextReached = allReachedSessions.length > LIMIT;
- const reachedSessions = allReachedSessions.slice(0, LIMIT);
- const hasPrevReached = reachedPage > 1;
+ const toggle = (next: SessionsPanel) => setPanel(current => (samePanel(current, next) ? null : next));
+ const lastIndex = metrics.steps.length - 1;
- const allDroppedSessions = droppedData || [];
- const hasNextDropped = allDroppedSessions.length > LIMIT;
- const droppedSessions = allDroppedSessions.slice(0, LIMIT);
- const hasPrevDropped = droppedPage > 1;
+ const nameOf = (index: number) => {
+ const step = steps[index];
+ return step
+ ? stepLabel(step, typeLabels[step.type] ?? typeLabels.event)
+ : t("Step {number}", { number: String(index + 1) });
+ };
+
+ // What a step matches, for the line under its name: "Page · /pricing · plan = pro".
+ const describe = (step: FunnelStep) =>
+ [
+ typeLabels[step.type] ?? typeLabels.event,
+ step.hostname,
+ step.value || t("any"),
+ ...resolvePropertyFilters(step).map(filter => `${filter.key} = ${filter.value}`),
+ ]
+ .filter(Boolean)
+ .join(" · ");
- const toggleExpansion = () => {
- setIsExpanded(!isExpanded);
- if (!isExpanded) {
- setCurrentTab("reached");
- setReachedPage(1);
- setDroppedPage(1);
+ const panelTitle = ({ stepIndex, mode, replaysOnly }: SessionsPanel) => {
+ const step = nameOf(stepIndex);
+ if (mode === "dropped") {
+ return replaysOnly
+ ? t("Replays of sessions that dropped off after {step}", { step })
+ : t("Sessions that dropped off after {step}", { step });
+ }
+ if (stepIndex === lastIndex) {
+ return replaysOnly ? t("Replays of sessions that converted") : t("Sessions that converted");
}
+ return replaysOnly
+ ? t("Replays of sessions that reached {step}", { step })
+ : t("Sessions that reached {step}", { step });
};
- return (
- <div key={step.stepNumber} className="relative pb-4">
- {/* Step Header - Clickable */}
- <div
- className="flex items-center cursor-pointer hover:bg-neutral-100 dark:hover:bg-neutral-800/30 rounded-md p-2 -ml-2 transition-colors"
- onClick={toggleExpansion}
- >
- <div className="shrink-0 w-6 h-6 rounded-full bg-neutral-100 dark:bg-neutral-800 flex items-center justify-center text-xs mr-2">
- {step.stepNumber}
- </div>
- <div className="font-medium text-sm flex items-center gap-2 flex-1">
- <EventTypeIcon type={targetTypeToEventType(steps[index]?.type || "event")} />
- {step.stepName || stepTypeLabels[steps[index]?.type || "event"]}
- </div>
- <div className="shrink-0">
- {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
- </div>
- </div>
+ // Sessions and Replays behind a count. "Left at this step" cannot be written
+ // as filters, so these open the step's own session list instead of linking
+ // to the Sessions page.
+ const pivots = (stepIndex: number, mode: SessionsPanel["mode"]) => {
+ const active = "bg-neutral-100 dark:bg-neutral-800";
+ const sessions = { stepIndex, mode, replaysOnly: false };
+ const replays = { stepIndex, mode, replaysOnly: true };
+ return (
+ <PivotActions actions={[]}>
+ <PivotButton
+ icon={<Rewind />}
+ label={t("Sessions")}
+ onClick={() => toggle(sessions)}
+ className={cn(samePanel(panel, sessions) && active)}
+ />
+ {replayAvailable && (
+ <PivotButton
+ icon={<Video />}
+ label={t("Replays")}
+ onClick={() => toggle(replays)}
+ className={cn("hidden md:inline-flex", samePanel(panel, replays) && active)}
+ />
+ )}
+ </PivotActions>
+ );
+ };
- {/* Bar and metrics */}
- <div className="flex items-center pl-8">
- {/* Metrics */}
- <div className="shrink-0 min-w-[130px] mr-4 space-y-1">
- <div className="flex items-baseline">
- <span className="text-base font-semibold">{step.sessions.toLocaleString()}</span>
- <span className="text-sm text-neutral-500 dark:text-neutral-400 ml-1">{t("sessions")}</span>
- </div>
- {index !== 0 && (
- <div className="flex items-baseline text-orange-500 text-xs font-medium">
- {t("{count} dropped", { count: droppedFromPrevious.toLocaleString() })}
- </div>
- )}
- </div>
+ const sessionsFor = (stepIndex: number, mode: SessionsPanel["mode"]) =>
+ panel && panel.stepIndex === stepIndex && panel.mode === mode ? (
+ <StepSessions
+ key={`${stepIndex}-${mode}-${panel.replaysOnly}`}
+ steps={steps}
+ panel={panel}
+ title={panelTitle(panel)}
+ onClose={() => setPanel(null)}
+ />
+ ) : null;
- {/* Bar */}
- <div className="grow h-10 bg-neutral-100 dark:bg-neutral-800 rounded-md overflow-hidden relative mt-2">
- {/* Relative conversion bar (from previous step) */}
- {index > 0 && prevStep && (
- <div
- className="absolute h-full rounded-md"
- style={{
- width: `${(step.sessions / prevStep.sessions) * 100}%`,
- background: `repeating-linear-gradient(
- 45deg,
- rgba(16, 185, 129, 0.25),
- rgba(16, 185, 129, 0.25) 6px,
- rgba(16, 185, 129, 0.15) 6px,
- rgba(16, 185, 129, 0.15) 12px
- )`,
- }}
- ></div>
- )}
- {/* Absolute conversion bar (from first step) */}
- <div className="h-full bg-emerald-500/70 rounded-md relative z-10" style={{ width: `${barWidth}%` }}></div>
- <div className="absolute top-2 right-2 z-20">
- <div className="text-base font-semibold">{round(step.conversionRate, 2)}%</div>
- </div>
- </div>
+ return (
+ <div className="@container">
+ <div className={cn(STEP_GRID, "hidden pb-1 text-xs @2xl:grid", MUTED)}>
+ <div />
+ <div>{t("Step")}</div>
+ <div>{t("Sessions that reached it")}</div>
+ <div className="text-right">{t("Sessions")}</div>
+ <div className="text-right">{t("Of start")}</div>
</div>
- {/* Expanded Sessions Section */}
- {isExpanded && (
- <div className=" ml-4 p-4">
- <Tabs value={currentTab} onValueChange={val => setCurrentTab(val as "reached" | "dropped")}>
- <TabsList className="mb-1">
- <TabsTrigger value="reached">{t("Reached ({count})", { count: step.sessions.toLocaleString() })}</TabsTrigger>
- {!isFirstStep && (
- <TabsTrigger value="dropped">{t("Dropped Off ({count})", { count: droppedFromPrevious.toLocaleString() })}</TabsTrigger>
- )}
- </TabsList>
+ {metrics.steps.map((step, index) => {
+ const definition = steps[index];
+ const isLast = index === lastIndex;
+ // The last step's sessions are the converted ones, listed from the line under it.
+ const reached = { stepIndex: index, mode: "reached" as const, replaysOnly: false };
- <TabsContent value="reached">
- <SessionsList
- sessions={reachedSessions}
- isLoading={isLoadingReached}
- page={reachedPage}
- onPageChange={setReachedPage}
- hasNextPage={hasNextReached}
- hasPrevPage={hasPrevReached}
- emptyMessage={t("No sessions reached this step in the selected time period.")}
- />
- </TabsContent>
-
- {!isFirstStep && (
- <TabsContent value="dropped">
- <SessionsList
- sessions={droppedSessions}
- isLoading={isLoadingDropped}
- page={droppedPage}
- onPageChange={setDroppedPage}
- hasNextPage={hasNextDropped}
- hasPrevPage={hasPrevDropped}
- emptyMessage={t("No sessions dropped off before reaching this step in the selected time period.")}
+ const rowContent = (
+ <>
+ <div className="flex h-6 w-6 items-center justify-center rounded-full bg-neutral-100 text-xs tabular-nums dark:bg-neutral-800">
+ {index + 1}
+ </div>
+ <div className="min-w-0">
+ <div className="flex items-center gap-1.5">
+ <EventTypeIcon
+ type={targetTypeToEventType(definition?.type || "event")}
+ className="h-3.5 w-3.5 shrink-0"
+ tooltip={false}
/>
- </TabsContent>
- )}
- </Tabs>
- </div>
- )}
- </div>
- );
-}
-
-export function Funnel({ data, steps, isError, error, isPending }: FunnelProps) {
- const t = useExtracted();
- const { site } = useStore();
+ <span className="truncate text-sm font-medium text-neutral-900 dark:text-neutral-100">
+ {nameOf(index)}
+ </span>
+ </div>
+ {definition && <div className={cn("truncate text-xs", MUTED)}>{describe(definition)}</div>}
+ </div>
+ <StepBar step={step} isFirst={index === 0} />
+ <div className="flex flex-col items-end @2xl:contents">
+ <div className="text-right text-sm font-semibold tabular-nums text-neutral-900 dark:text-neutral-50">
+ {step.sessions.toLocaleString()}
+ </div>
+ <div className={cn("text-right text-xs tabular-nums @2xl:text-sm", MUTED)}>
+ {metrics.entered > 0 ? formatRate(step.ofStart) : "—"}
+ </div>
+ </div>
+ </>
+ );
- // Prepare chart data
- const chartData =
- data?.map(step => ({
- stepName: step.step_name,
- sessions: step.sessions,
- conversionRate: step.conversion_rate,
- dropoffRate: step.dropoff_rate,
- stepNumber: step.step_number,
- })) || [];
+ return (
+ <Fragment key={index}>
+ {isLast ? (
+ <div className={cn(STEP_GRID, "min-h-10 py-1")}>{rowContent}</div>
+ ) : (
+ <button
+ type="button"
+ className={cn(
+ STEP_GRID,
+ "min-h-10 w-full cursor-pointer rounded-md py-1 text-left transition-colors hover:bg-neutral-50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 dark:hover:bg-neutral-800/40 dark:focus-visible:ring-neutral-300"
+ )}
+ aria-expanded={samePanel(panel, reached)}
+ title={t("Show the sessions that reached this step")}
+ onClick={() => toggle(reached)}
+ >
+ {rowContent}
+ </button>
+ )}
+ {!isLast && sessionsFor(index, "reached")}
- // Get first and last data points for total conversion metrics
- const firstStep = chartData[0];
- const lastStep = chartData[chartData.length - 1];
- const totalConversionRate = lastStep?.conversionRate || 0;
+ {isLast ? (
+ <div className={cn(LINK_GRID, "min-h-9")}>
+ <div className="row-span-2 @2xl:row-span-1" />
+ <div className="flex items-center gap-1.5 text-xs">
+ <span className={STRONG}>{metrics.conversion === null ? "—" : formatRate(metrics.conversion)}</span>
+ <span className={MUTED}>{t("overall")}</span>
+ <Delta value={rateDelta(metrics.conversion, previous?.conversion)} />
+ </div>
+ <div className="col-start-2 flex flex-wrap items-center justify-between gap-x-3 gap-y-1 text-xs @2xl:col-start-auto">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className={cn("tabular-nums", MUTED)}>
+ {t.rich("<count>{converted}</count> converted", {
+ converted: metrics.converted.toLocaleString(),
+ count: chunks => <span className={STRONG}>{chunks}</span>,
+ })}
+ </span>
+ {metrics.converted > 0 && pivots(index, "reached")}
+ {goal && (
+ <Link
+ href={goal.href}
+ prefetch={false}
+ className="inline-flex max-w-56 items-center gap-1 rounded-md border border-neutral-200 px-1.5 py-0.5 text-neutral-700 transition-colors hover:border-neutral-300 hover:text-neutral-900 dark:border-neutral-700 dark:text-neutral-300 dark:hover:border-neutral-600 dark:hover:text-neutral-50"
+ >
+ <Target className="h-3 w-3 shrink-0" aria-hidden="true" />
+ <span className="truncate">{t("Goal: {name}", { name: goal.name })}</span>
+ </Link>
+ )}
+ </div>
+ <MedianTime seconds={metrics.medianSecondsToConvert}>
+ {duration => t("{duration} median from first step", { duration })}
+ </MedianTime>
+ </div>
+ </div>
+ ) : (
+ <div className={cn(LINK_GRID, "min-h-9")}>
+ <div className="row-span-2 flex h-full justify-center self-stretch @2xl:row-span-1">
+ <div className="w-px bg-neutral-200 dark:bg-neutral-800" />
+ </div>
+ <div className="flex items-center gap-1.5 text-xs">
+ <span className={STRONG}>{step.continueRate === null ? "—" : formatRate(step.continueRate)}</span>
+ <span className={MUTED}>{t("continue")}</span>
+ <Delta value={rateDelta(step.continueRate, previous?.steps[index]?.continueRate)} />
+ </div>
+ <div className="col-start-2 flex flex-wrap items-center justify-between gap-x-3 gap-y-1 pb-1 text-xs @2xl:col-start-auto @2xl:pb-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className={cn("tabular-nums", MUTED)}>
+ {t.rich("<count>{dropped}</count> dropped here", {
+ dropped: step.dropped.toLocaleString(),
+ count: chunks => <span className={STRONG}>{chunks}</span>,
+ })}
+ {step.continueRate !== null && ` · ${formatRate(1 - step.continueRate)}`}
+ </span>
+ {step.dropped > 0 && pivots(index, "dropped")}
+ </div>
+ <MedianTime seconds={step.medianSecondsToNext}>
+ {duration => t("{duration} median to next step", { duration })}
+ </MedianTime>
+ </div>
+ </div>
+ )}
+ {sessionsFor(index, isLast ? "reached" : "dropped")}
+ </Fragment>
+ );
+ })}
- return (
- <div className="mt-2">
- {isError ? (
- <div className="h-[400px] flex items-center justify-center">
- <div className="text-red-500">
- {t("Error:")} {error instanceof Error ? error.message : t("Failed to analyze funnel")}
- </div>
- </div>
- ) : data && chartData.length > 0 ? (
- <div className="space-y-0">
- {chartData.map((step, index) => (
- <FunnelStepComponent
- key={step.stepNumber}
- step={step}
- index={index}
- steps={steps}
- chartData={chartData}
- firstStep={firstStep}
- siteId={Number(site)}
- />
- ))}
- </div>
- ) : (
- <div className="h-[400px] flex items-center justify-center">
- <div className="text-neutral-500 dark:text-neutral-400 text-sm">
- {isPending ? t("Analyzing funnel...") : t("Configure your funnel steps")}
- </div>
- </div>
- )}
- <div className="flex justify-between items-center gap-2 ml-4">
- <div className="flex items-center gap-4 mt-3 text-xs text-neutral-500 dark:text-neutral-400">
- <div className="flex items-center">
- <div className="w-3 h-3 bg-emerald-500/70 rounded-sm mr-1"></div>
- <span>{t("Overall conversion")}</span>
- </div>
- <div className="flex items-center">
- <div
- className="w-3 h-3 rounded-sm mr-1"
- style={{
- background: `repeating-linear-gradient(
- 45deg,
- rgba(16, 185, 129, 0.25),
- rgba(16, 185, 129, 0.25) 3px,
- rgba(16, 185, 129, 0.15) 3px,
- rgba(16, 185, 129, 0.15) 6px
- )`,
- }}
- ></div>
- <span>{t("Conversion from previous step")}</span>
- </div>
+ <div className="mt-2 flex flex-wrap items-center justify-between gap-x-3 gap-y-2 border-t border-neutral-100 pt-3 dark:border-neutral-800">
+ <div className={cn("flex flex-wrap items-center gap-x-4 gap-y-1 text-xs", MUTED)}>
+ <span className="inline-flex items-center gap-1.5">
+ <span className={cn("inline-block h-2.5 w-2.5 rounded-sm", SOLID)} />
+ {t("Share of first step")}
+ </span>
+ <span className="inline-flex items-center gap-1.5">
+ <span className={cn("inline-block h-2.5 w-2.5 rounded-sm", HATCH)} />
+ {t("Conversion from previous step")}
+ </span>
+ {previous && comparisonLabel && <span>{t("Compared with {period}", { period: comparisonLabel })}</span>}
</div>
+ {actions && <div className="flex flex-wrap items-center gap-1.5">{actions}</div>}
</div>
</div>
);
diff --git a/client/src/app/[site]/funnels/components/FunnelForm.tsx b/client/src/app/[site]/funnels/components/FunnelForm.tsx
index fb7655733..ff912ff0c 100644
--- a/client/src/app/[site]/funnels/components/FunnelForm.tsx
+++ b/client/src/app/[site]/funnels/components/FunnelForm.tsx
@@ -24,6 +24,7 @@ import { EventTypeIcon } from "../../../../components/EventIcons";
import { EventTrackingNotice } from "../../../../components/EventTrackingNotice";
import { isAutocaptureTargetType, targetTypeToEventType } from "../../../../lib/events";
import { Funnel } from "./Funnel";
+import { metricsFromAnalysis } from "./funnelMetrics";
const URL_PATTERN = /^(https?:\/\/|www\.|[a-zA-Z0-9-]+\.[a-zA-Z]{2,}\/)/i;
@@ -495,7 +496,11 @@ export function FunnelForm({
let funnelArea = null;
if (funnelData && funnelData.length) {
- funnelArea = <Funnel data={funnelData} isError={isError} error={error} isPending={isPending} steps={steps} />;
+ funnelArea = (
+ <div className="pt-3">
+ <Funnel steps={steps} metrics={metricsFromAnalysis(funnelData)} />
+ </div>
+ );
} else {
funnelArea = (
<div className="flex flex-1 items-center justify-center py-16">
diff --git a/client/src/app/[site]/funnels/components/FunnelRow.test.tsx b/client/src/app/[site]/funnels/components/FunnelRow.test.tsx
index eb29e99d8..8d0850093 100644
--- a/client/src/app/[site]/funnels/components/FunnelRow.test.tsx
+++ b/client/src/app/[site]/funnels/components/FunnelRow.test.tsx
@@ -1,12 +1,18 @@
-import React from "react";
+import React, { ReactNode } from "react";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import type { SavedFunnel } from "@/api/analytics/endpoints";
+import type { Goal, SavedFunnel } from "@/api/analytics/endpoints";
import { TooltipProvider } from "@/components/ui/tooltip";
import { useStore } from "@/lib/store";
+import { computeFunnelMetrics, FunnelRowData } from "./funnelMetrics";
-const mocks = vi.hoisted(() => ({ deleteFunnel: vi.fn(), toastSuccess: vi.fn() }));
+const mocks = vi.hoisted(() => ({
+ deleteFunnel: vi.fn(),
+ toastSuccess: vi.fn(),
+ useGetFunnel: vi.fn(),
+ funnel: vi.fn(),
+}));
vi.mock("next-intl", () => ({
useExtracted:
@@ -14,55 +20,104 @@ vi.mock("next-intl", () => ({
(message: string, values: Record<string, string> = {}) =>
message.replace(/\{(\w+)\}/g, (_, key: string) => values[key] ?? key),
}));
+vi.mock("next/link", () => ({
+ default: ({ href, children, prefetch, ...props }: { href: string; children: ReactNode; prefetch?: boolean }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
vi.mock("@/api/analytics/endpoints/funnels", async importOriginal => ({
...(await importOriginal<typeof import("@/api/analytics/endpoints/funnels")>()),
deleteFunnel: mocks.deleteFunnel,
}));
vi.mock("@/api/analytics/hooks/funnels/useGetFunnel", () => ({
- useGetFunnel: () => ({ data: undefined, isError: false, error: null, isLoading: false, isSuccess: false }),
+ useGetFunnel: (config: unknown) => mocks.useGetFunnel(config),
}));
vi.mock("@/components/ui/sonner", () => ({ toast: { success: mocks.toastSuccess, error: vi.fn() } }));
-vi.mock("./EditFunnel", () => ({ EditFunnelDialog: () => null }));
-vi.mock("./Funnel", () => ({ Funnel: () => null }));
+vi.mock("./EditFunnel", () => ({
+ EditFunnelDialog: ({ isCloneMode }: { isCloneMode?: boolean }) => (
+ <div role="dialog">{isCloneMode ? "clone editor" : "edit editor"}</div>
+ ),
+}));
+vi.mock("./Funnel", () => ({
+ Funnel: (props: { actions?: ReactNode }) => {
+ mocks.funnel(props);
+ return <div data-testid="funnel-chart">{props.actions}</div>;
+ },
+}));
-import { FunnelRow } from "./FunnelRow";
+import { FunnelRow, FunnelRowProps } from "./FunnelRow";
const funnel: SavedFunnel = {
id: 7,
name: "Signup",
steps: [
- { type: "page", value: "/" },
+ { type: "page", value: "/", name: "Home" },
+ { type: "page", value: "/pricing", name: "Pricing" },
{ type: "page", value: "/signup" },
],
createdAt: "2026-09-01T00:00:00Z",
updatedAt: "2026-09-01T00:00:00Z",
- conversionRate: null,
- totalVisitors: null,
};
-function renderRow() {
+const metrics = (sessions: number[]) => computeFunnelMetrics(sessions.map(count => ({ sessions: count })));
+
+const emptyRow: FunnelRowData = { funnel, current: null, previous: null };
+const fullRow: FunnelRowData = {
+ funnel,
+ current: metrics([84210, 17920, 412]),
+ previous: metrics([74930, 15692, 335]),
+};
+
+const links = { goals: "/42/goals?compare=previous", journeys: "/42/journeys?compare=previous" };
+
+function renderRow(props: Partial<FunnelRowProps> = {}) {
const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
- return render(
+ const onToggle = vi.fn();
+ const view = render(
<QueryClientProvider client={client}>
<TooltipProvider>
- <FunnelRow funnel={funnel} index={1} canWrite />
+ <FunnelRow
+ row={emptyRow}
+ expanded={false}
+ onToggle={onToggle}
+ canWrite
+ isLoading={false}
+ links={links}
+ {...props}
+ />
</TooltipProvider>
</QueryClientProvider>
);
+ return { ...view, onToggle };
}
-// The row's icon buttons are labelled by tooltips only, so find the delete one by its icon.
-function openDeleteDialog(container: HTMLElement) {
- const trash = container.querySelector(".lucide-trash-2, .lucide-trash2")?.closest("button");
- fireEvent.click(trash!);
+const openMenu = () =>
+ fireEvent.keyDown(screen.getByRole("button", { name: /Edit, clone or delete Signup/ }), { key: "Enter" });
+
+// Edit, clone and delete live in the row's menu.
+async function openDeleteDialog() {
+ openMenu();
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" }));
}
beforeEach(() => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
useStore.setState({ site: "42" });
+ mocks.useGetFunnel.mockReturnValue({ data: undefined, isError: false, error: null, isLoading: false });
vi.spyOn(console, "error").mockImplementation(() => {});
});
afterEach(() => {
cleanup();
+ vi.unstubAllGlobals();
vi.restoreAllMocks();
vi.clearAllMocks();
});
@@ -70,9 +125,9 @@ afterEach(() => {
describe("FunnelRow delete", () => {
it("keeps the dialog open and shows the server error when the delete fails", async () => {
mocks.deleteFunnel.mockRejectedValue(new Error("Funnel is used by a dashboard"));
- const { container } = renderRow();
+ renderRow();
- openDeleteDialog(container);
+ await openDeleteDialog();
fireEvent.click(await screen.findByRole("button", { name: "Delete" }));
expect(await screen.findByText(/Funnel is used by a dashboard/)).toBeTruthy();
@@ -83,9 +138,9 @@ describe("FunnelRow delete", () => {
it("toasts only after the server confirms, and can't be submitted twice meanwhile", async () => {
let resolve!: (value: { success: boolean }) => void;
mocks.deleteFunnel.mockReturnValue(new Promise(r => (resolve = r)));
- const { container } = renderRow();
+ renderRow();
- openDeleteDialog(container);
+ await openDeleteDialog();
fireEvent.click(await screen.findByRole("button", { name: "Delete" }));
const pending = (await screen.findByRole("button", { name: "Deleting..." })) as HTMLButtonElement;
@@ -100,3 +155,154 @@ describe("FunnelRow delete", () => {
expect(mocks.deleteFunnel).toHaveBeenCalledWith("42", 7);
});
});
+
+describe("FunnelRow menu", () => {
+ it("opens the editor to edit and to clone", async () => {
+ renderRow();
+
+ openMenu();
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Edit funnel" }));
+ expect(await screen.findByText("edit editor")).toBeTruthy();
+
+ openMenu();
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Clone" }));
+ expect(await screen.findByText("clone editor")).toBeTruthy();
+ });
+
+ it("does not toggle the row when the menu is used", async () => {
+ const { onToggle } = renderRow();
+
+ fireEvent.click(screen.getByRole("button", { name: /Edit, clone or delete Signup/ }));
+ await openDeleteDialog();
+
+ expect(onToggle).not.toHaveBeenCalled();
+ });
+
+ it("offers no edit, clone or delete without funnels:write", () => {
+ renderRow({ canWrite: false, expanded: true, row: fullRow });
+
+ expect(screen.queryByRole("button", { name: /Edit, clone or delete/ })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Edit funnel" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Clone" })).toBeNull();
+ // Reading where the paths go is not a write.
+ expect(screen.getByRole("link", { name: "Explore paths" }).getAttribute("href")).toBe(links.journeys);
+ });
+});
+
+describe("FunnelRow summary", () => {
+ it("states entered, converted, conversion and the change against the comparison period", () => {
+ renderRow({ row: fullRow });
+ const header = screen.getByTestId("funnel-row-header");
+
+ expect(header.textContent).toContain("84,210");
+ expect(header.textContent).toContain("412");
+ // 412 of 84,210 is 0.49%: two decimals, or it would read as 0.5%.
+ expect(header.textContent).toContain("0.49%");
+ // Against 335 of 74,930 (0.45%).
+ expect(header.textContent).toContain("0.04 pp");
+ expect(screen.getAllByRole("img", { name: "Sessions remaining at each of 3 steps" }).length).toBe(1);
+ });
+
+ it("lists the steps while closed and names the biggest drop-off once open", () => {
+ const closed = renderRow({ row: fullRow });
+ expect(closed.getByTestId("funnel-row-header").textContent).toContain("Home");
+ expect(closed.getByTestId("funnel-row-header").textContent).toContain("/signup");
+ cleanup();
+
+ renderRow({ row: fullRow, expanded: true });
+ // 17,920 of the 84,210 reach Pricing (78.7% lost); 412 of those 17,920 sign up (97.7% lost).
+ expect(screen.getByTestId("funnel-row-header").textContent).toContain(
+ "biggest drop-off Pricing to /signup (97.7%)"
+ );
+ });
+
+ it("draws dashes, not zeros, for a funnel with no figures", () => {
+ renderRow();
+ const header = screen.getByTestId("funnel-row-header");
+
+ expect(header.textContent).toContain("—");
+ expect(header.textContent).not.toContain("0%");
+ expect(screen.queryByRole("img")).toBeNull();
+ });
+
+ it("toggles from the row and from its name", () => {
+ const { onToggle } = renderRow({ row: fullRow });
+
+ fireEvent.click(screen.getByTestId("funnel-row-header"));
+ fireEvent.click(screen.getByRole("button", { name: "Signup" }));
+
+ expect(onToggle).toHaveBeenCalledTimes(2);
+ expect(screen.getByRole("button", { name: "Signup" }).getAttribute("aria-expanded")).toBe("false");
+ });
+});
+
+describe("FunnelRow expanded", () => {
+ it("draws the funnel from the summary without analyzing it again", () => {
+ renderRow({ row: fullRow, expanded: true, comparisonLabel: "Aug 2 – Aug 31" });
+
+ expect(screen.getByTestId("funnel-chart")).toBeTruthy();
+ expect(mocks.funnel).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ steps: funnel.steps,
+ metrics: fullRow.current,
+ previous: fullRow.previous,
+ comparisonLabel: "Aug 2 – Aug 31",
+ goal: null,
+ })
+ );
+ expect(mocks.useGetFunnel).toHaveBeenLastCalledWith(undefined);
+ });
+
+ it("links the last step to the goal that measures the same thing", () => {
+ const goals: Goal[] = [
+ {
+ goalId: 3,
+ name: "Signup page",
+ goalType: "path",
+ config: { pathPattern: "/signup" },
+ createdAt: "2026-09-01T00:00:00Z",
+ total_conversions: 0,
+ total_sessions: 0,
+ conversion_rate: 0,
+ },
+ ];
+ renderRow({ row: fullRow, expanded: true, goals });
+
+ expect(mocks.funnel).toHaveBeenLastCalledWith(
+ expect.objectContaining({ goal: { name: "Signup page", href: links.goals } })
+ );
+ });
+
+ it("analyzes a funnel the summary does not cover when it is opened", () => {
+ mocks.useGetFunnel.mockReturnValue({
+ data: [
+ { step_number: 1, step_name: "Home", sessions: 50, conversion_rate: 100, dropoff_rate: 0 },
+ { step_number: 2, step_name: "Pricing", sessions: 20, conversion_rate: 40, dropoff_rate: 60 },
+ { step_number: 3, step_name: "/signup", sessions: 5, conversion_rate: 10, dropoff_rate: 75 },
+ ],
+ isError: false,
+ error: null,
+ isLoading: false,
+ });
+ renderRow({ expanded: true });
+
+ expect(mocks.useGetFunnel).toHaveBeenLastCalledWith({ steps: funnel.steps });
+ expect(mocks.funnel).toHaveBeenLastCalledWith(
+ expect.objectContaining({ metrics: expect.objectContaining({ entered: 50, converted: 5, conversion: 0.1 }) })
+ );
+ });
+
+ it("waits for the summary before deciding to analyze", () => {
+ renderRow({ expanded: true, isLoading: true });
+
+ expect(mocks.useGetFunnel).toHaveBeenLastCalledWith(undefined);
+ expect(screen.queryByTestId("funnel-chart")).toBeNull();
+ });
+
+ it("says so when the analysis fails", () => {
+ mocks.useGetFunnel.mockReturnValue({ data: undefined, isError: true, error: new Error("boom"), isLoading: false });
+ renderRow({ expanded: true });
+
+ expect(screen.getByText(/Error loading funnel:/).textContent).toContain("boom");
+ });
+});
diff --git a/client/src/app/[site]/funnels/components/FunnelRow.tsx b/client/src/app/[site]/funnels/components/FunnelRow.tsx
index d03e180e5..cbf8a0478 100644
--- a/client/src/app/[site]/funnels/components/FunnelRow.tsx
+++ b/client/src/app/[site]/funnels/components/FunnelRow.tsx
@@ -1,69 +1,142 @@
"use client";
+import { ArrowRight, ChevronDown, ChevronRight, Copy, Ellipsis, Split, SquarePen, Trash2 } from "lucide-react";
import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { useState } from "react";
+import { Goal } from "@/api/analytics/endpoints";
+import { useDeleteFunnel } from "@/api/analytics/hooks/funnels/useDeleteFunnel";
+import { useGetFunnel } from "@/api/analytics/hooks/funnels/useGetFunnel";
import { ConfirmationModal } from "@/components/ConfirmationModal";
+import { EventTypeIcon } from "@/components/EventIcons";
+import { Delta } from "@/components/site/Delta";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { ArrowRight, ChevronDown, ChevronUp, Copy, Edit, Eye, MousePointerClick, Trash2 } from "lucide-react";
-import { useState } from "react";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Skeleton } from "@/components/ui/skeleton";
import { toast } from "@/components/ui/sonner";
-import { useDeleteFunnel } from "../../../../api/analytics/hooks/funnels/useDeleteFunnel";
-import { useGetFunnel } from "../../../../api/analytics/hooks/funnels/useGetFunnel";
-import { FunnelStepType, SavedFunnel } from "../../../../api/analytics/endpoints";
-import { ThreeDotLoader } from "../../../../components/Loaders";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { resolvePropertyFilters, targetTypeToEventType } from "@/lib/events";
+import { cn } from "@/lib/utils";
import { EditFunnelDialog } from "./EditFunnel";
import { Funnel } from "./Funnel";
-import { EventTypeIcon } from "../../../../components/EventIcons";
-import { resolvePropertyFilters, targetTypeToEventType } from "../../../../lib/events";
+import {
+ conversionDelta,
+ findMatchingGoal,
+ formatRate,
+ FunnelMetrics,
+ FunnelRowData,
+ metricsFromAnalysis,
+ stepLabel,
+} from "./funnelMetrics";
+import { useStepTypeLabels } from "./useStepTypeLabels";
+
+/**
+ * Chevron, funnel, step strip, entered, converted, conversion, change, actions.
+ * The figure columns appear when the list itself is wide enough (a container
+ * query: the sidebar takes a share of the window); otherwise the row keeps the
+ * first two and the last, and states its figures on one line.
+ */
+export const FUNNEL_ROW_GRID =
+ "grid grid-cols-[16px_minmax(0,1fr)_28px] items-center gap-x-3 @3xl:grid-cols-[16px_minmax(0,1fr)_84px_72px_72px_64px_92px_28px]";
+
+const MUTED = "text-neutral-500 dark:text-neutral-400";
+
+/** One bar per step: the share of entering sessions still in the funnel at that step. */
+function StepStrip({ metrics }: { metrics: FunnelMetrics }) {
+ const t = useExtracted();
+ return (
+ <div
+ className="flex h-6 items-end gap-[3px]"
+ role="img"
+ aria-label={t("Sessions remaining at each of {count} steps", { count: String(metrics.steps.length) })}
+ >
+ {metrics.steps.map((step, index) => (
+ <div
+ key={index}
+ className="relative h-full min-w-[2px] max-w-2 flex-1 overflow-hidden rounded-[2px] bg-neutral-100 dark:bg-neutral-800"
+ >
+ {step.sessions > 0 && (
+ <div
+ className="absolute inset-x-0 bottom-0 rounded-[2px] bg-dataviz"
+ style={{ height: `${Math.max(6, step.ofStart * 100).toFixed(1)}%` }}
+ />
+ )}
+ </div>
+ ))}
+ </div>
+ );
+}
-interface FunnelRowProps {
- funnel: SavedFunnel;
- index: number;
+function ExpandedSkeleton({ steps }: { steps: number }) {
+ return (
+ <div className="space-y-3">
+ {Array.from({ length: Math.min(steps, 6) }, (_, index) => (
+ <div key={index} className="flex items-center gap-3">
+ <Skeleton className="h-6 w-6 rounded-full" />
+ <Skeleton className="hidden h-4 w-40 rounded @2xl:block" />
+ <Skeleton className="h-8 flex-1 rounded-md" />
+ <Skeleton className="h-4 w-12 rounded" />
+ </div>
+ ))}
+ </div>
+ );
+}
+
+export interface FunnelRowProps {
+ row: FunnelRowData;
+ expanded: boolean;
+ onToggle: () => void;
/** funnels:write: edit, clone and delete. */
canWrite: boolean;
+ /** The selected period's numbers are on their way. */
+ isLoading: boolean;
+ /** The comparison period's numbers are on their way. */
+ isLoadingComparison?: boolean;
+ /** The comparison window in words, for the legend. */
+ comparisonLabel?: string | null;
+ /** The site's goals, to link the last step to the one that matches it. */
+ goals?: Goal[];
+ /** The Goals and Journeys pages of this site, carrying the current period and filters. */
+ links: { goals: string; journeys: string };
}
-export function FunnelRow({ funnel, index, canWrite }: FunnelRowProps) {
+export function FunnelRow({
+ row,
+ expanded,
+ onToggle,
+ canWrite,
+ isLoading,
+ isLoadingComparison = false,
+ comparisonLabel,
+ goals,
+ links,
+}: FunnelRowProps) {
const t = useExtracted();
+ const typeLabels = useStepTypeLabels();
+ const { funnel, current, previous } = row;
- const stepTypeLabels: Record<FunnelStepType, string> = {
- page: t("Page"),
- event: t("Event"),
- outbound: t("Outbound"),
- button_click: t("Button"),
- form_submit: t("Form"),
- copy: t("Copy"),
- };
- const [expanded, setExpanded] = useState(index === 0);
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
const [isCloneModalOpen, setIsCloneModalOpen] = useState(false);
- // Funnel data fetching
- const {
- data,
- isError,
- error,
- isLoading: isPending,
- isSuccess,
- } = useGetFunnel(
- expanded
- ? {
- steps: funnel.steps,
- }
- : undefined
- );
+ // The summary covers a capped number of funnels. One it leaves out (or every
+ // one, if the summary failed) is analyzed on its own when opened: the same
+ // step counts, without step times or a comparison. The row then shows those
+ // figures too.
+ const needsAnalysis = expanded && !current && !isLoading;
+ const analysis = useGetFunnel(needsAnalysis ? { steps: funnel.steps } : undefined);
+ const metrics = current ?? (needsAnalysis && analysis.data?.length ? metricsFromAnalysis(analysis.data) : null);
// Delete funnel mutation. mutateAsync so the modal waits for the server and shows its errors.
const { mutateAsync: deleteFunnel, isPending: isDeleting } = useDeleteFunnel();
- // Handle expansion
- const handleExpand = () => {
- setExpanded(!expanded);
- };
-
- // Handle funnel deletion
const handleDeleteFunnel = async () => {
try {
await deleteFunnel(funnel.id);
@@ -74,44 +147,117 @@ export function FunnelRow({ funnel, index, canWrite }: FunnelRowProps) {
}
};
+ const nameOf = (index: number) => {
+ const step = funnel.steps[index];
+ return stepLabel(step, typeLabels[step.type] ?? typeLabels.event);
+ };
+
+ const delta = conversionDelta(row);
+ const worst = metrics?.worstStep ?? null;
+ const lastStep = funnel.steps[funnel.steps.length - 1];
+ const goal = expanded && goals && lastStep ? findMatchingGoal(lastStep, goals) : undefined;
+
+ // A figure cell: the number, a skeleton while it loads, a dash when there is none.
+ const figure = (value: string | null | undefined, className?: string) =>
+ isLoading ? (
+ <Skeleton className="ml-auto h-4 w-10 rounded" />
+ ) : (
+ <span className={cn("tabular-nums", className)}>{value ?? "—"}</span>
+ );
+
return (
- <Card className="mb-4 overflow-hidden">
+ <Card id={`funnel-${funnel.id}`} className="@container">
{/* Header row (always visible) */}
- <div className="flex items-center justify-between py-2 px-5">
- <div className="flex items-center grow cursor-pointer transition-colors" onClick={handleExpand}>
- <div className="mt-1 text-xs text-neutral-500 dark:text-neutral-400 flex flex-col gap-3">
- {/* Steps visualization */}
- <div className="flex flex-wrap gap-1">
- <h3 className="font-medium text-neutral-900 dark:text-neutral-100 text-base mr-2">{funnel.name}</h3>
+ <div
+ className={cn(FUNNEL_ROW_GRID, "cursor-pointer px-4", expanded ? "py-3" : "py-2.5")}
+ onClick={onToggle}
+ data-testid="funnel-row-header"
+ >
+ {expanded ? (
+ <ChevronDown className={cn("h-4 w-4", MUTED)} aria-hidden="true" />
+ ) : (
+ <ChevronRight className={cn("h-4 w-4", MUTED)} aria-hidden="true" />
+ )}
+
+ <div className="min-w-0">
+ <div className="flex items-baseline gap-2">
+ <button
+ type="button"
+ className="min-w-0 cursor-pointer truncate rounded-sm text-left text-sm font-medium text-neutral-900 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 dark:text-neutral-100 dark:focus-visible:ring-neutral-300"
+ aria-expanded={expanded}
+ onClick={event => {
+ event.stopPropagation();
+ onToggle();
+ }}
+ >
+ {funnel.name}
+ </button>
+ <span className={cn("shrink-0 text-xs", MUTED)}>
+ {t("{count} steps", { count: String(funnel.steps.length) })}
+ </span>
+ </div>
+
+ {expanded ? (
+ <div className={cn("mt-1 text-xs", MUTED)}>
+ {t("Steps in order within one session")}
+ {metrics && worst !== null && (
+ <>
+ {" · "}
+ {t("biggest drop-off {from} to {to} ({rate})", {
+ from: nameOf(worst),
+ to: nameOf(worst + 1),
+ rate: formatRate(1 - metrics.steps[worst].continueRate!),
+ })}
+ </>
+ )}
+ </div>
+ ) : (
+ <div className="mt-1 flex flex-wrap items-center gap-y-1 text-xs">
{funnel.steps.map((step, index) => {
const propertyFilters = resolvePropertyFilters(step);
+ const typeLabel = typeLabels[step.type] ?? typeLabels.event;
return (
- <div key={index} className="flex items-center">
- {index > 0 && <ArrowRight className="h-3 w-3 mx-1 text-neutral-400" />}
+ <div key={index} className="flex min-w-0 items-center">
+ {index > 0 && (
+ <ArrowRight
+ className="mx-1 h-3 w-3 shrink-0 text-neutral-400 dark:text-neutral-500"
+ aria-hidden="true"
+ />
+ )}
<Tooltip>
<TooltipTrigger asChild>
- <span className="rounded bg-neutral-100 dark:bg-neutral-800 px-1.5 py-0.5 whitespace-nowrap overflow-hidden text-ellipsis flex items-center cursor-default">
- <EventTypeIcon type={targetTypeToEventType(step.type)} className="h-3 w-3 mr-1" />
- <span className="max-w-[120px] overflow-hidden text-ellipsis inline-block">
- {step.name || step.value || stepTypeLabels[step.type] || t("Event")}
- {propertyFilters.length > 0 && <span className="text-xs text-yellow-400 ml-1">*</span>}
- </span>
+ <span className="inline-flex min-w-0 cursor-default items-center gap-1 whitespace-nowrap rounded bg-neutral-100 px-1.5 py-0.5 text-neutral-700 dark:bg-neutral-800 dark:text-neutral-300">
+ <EventTypeIcon
+ type={targetTypeToEventType(step.type)}
+ className="h-3 w-3 shrink-0"
+ tooltip={false}
+ />
+ <span className="max-w-[160px] truncate">{stepLabel(step, typeLabel)}</span>
+ {propertyFilters.length > 0 && (
+ <span className={cn("max-w-[120px] truncate", MUTED)}>
+ {propertyFilters.map(filter => `${filter.key} = ${filter.value}`).join(", ")}
+ </span>
+ )}
</span>
</TooltipTrigger>
<TooltipContent side="bottom" className="text-xs">
<div>
- <span className="font-semibold">{stepTypeLabels[step.type] || t("Event")}:</span>{" "}
- {step.value || t("Any")}
+ <span className="font-semibold">{typeLabel}:</span> {step.value || t("Any")}
</div>
{step.name && (
<div>
<span className="font-semibold">{t("Label")}:</span> {step.name}
</div>
)}
+ {step.hostname && (
+ <div>
+ <span className="font-semibold">{t("Hostname")}:</span> {step.hostname}
+ </div>
+ )}
{propertyFilters.length > 0 && (
<div>
<span className="font-semibold">{t("Property")}:</span>{" "}
- {propertyFilters.map(f => `${f.key} = ${f.value}`).join(", ")}
+ {propertyFilters.map(filter => `${filter.key} = ${filter.value}`).join(", ")}
</div>
)}
</TooltipContent>
@@ -120,96 +266,133 @@ export function FunnelRow({ funnel, index, canWrite }: FunnelRowProps) {
);
})}
</div>
- </div>
- </div>
+ )}
- <div className="flex items-center gap-4">
- <div className="flex">
- {canWrite && (
+ {/* The figure columns, as one line, where there is no room for columns. */}
+ <div className={cn("mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs @3xl:hidden", MUTED)}>
+ {isLoading ? (
+ <Skeleton className="h-4 w-40 rounded" />
+ ) : metrics ? (
<>
- {/* Edit button */}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- onClick={e => {
- e.stopPropagation();
- setIsEditModalOpen(true);
- }}
- >
- <Edit className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{t("Edit Funnel")}</TooltipContent>
- </Tooltip>
-
- {/* Clone button */}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- onClick={e => {
- e.stopPropagation();
- setIsCloneModalOpen(true);
- }}
- >
- <Copy className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{t("Clone Funnel")}</TooltipContent>
- </Tooltip>
-
- {/* Delete button */}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- onClick={e => {
- e.stopPropagation();
- setIsDeleteModalOpen(true);
- }}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{t("Delete Funnel")}</TooltipContent>
- </Tooltip>
+ <span>{t("{count} entered", { count: metrics.entered.toLocaleString() })}</span>
+ <span>{t("{count} converted", { count: metrics.converted.toLocaleString() })}</span>
+ {metrics.conversion !== null && (
+ <span className="font-semibold tabular-nums text-neutral-900 dark:text-neutral-50">
+ {formatRate(metrics.conversion)}
+ </span>
+ )}
+ <Delta value={delta} />
</>
- )}
-
- <Button variant="ghost" size="icon" onClick={handleExpand}>
- {expanded ? <ChevronUp strokeWidth={3} /> : <ChevronDown strokeWidth={3} />}
- </Button>
+ ) : null}
</div>
</div>
+
+ <div className="hidden @3xl:block">
+ {isLoading ? <Skeleton className="h-6 w-12 rounded" /> : metrics ? <StepStrip metrics={metrics} /> : null}
+ </div>
+ <div className="hidden text-right text-sm text-neutral-900 dark:text-neutral-100 @3xl:block">
+ {figure(metrics?.entered.toLocaleString())}
+ </div>
+ <div className="hidden text-right text-sm text-neutral-900 dark:text-neutral-100 @3xl:block">
+ {figure(metrics?.converted.toLocaleString())}
+ </div>
+ <div className="hidden text-right text-sm text-neutral-900 dark:text-neutral-50 @3xl:block">
+ {figure(metrics?.conversion == null ? null : formatRate(metrics.conversion), "font-semibold")}
+ </div>
+ <div className="hidden justify-end @3xl:flex">
+ {isLoadingComparison ? <Skeleton className="h-4 w-12 rounded" /> : <Delta value={delta} />}
+ </div>
+
+ {canWrite ? (
+ // Not interactive itself: it only keeps the menu's clicks from toggling the row.
+ <div onClick={event => event.stopPropagation()}>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="smIcon"
+ aria-label={t("Edit, clone or delete {name}", { name: funnel.name })}
+ >
+ <Ellipsis />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onSelect={() => setIsEditModalOpen(true)}>
+ <SquarePen className="h-4 w-4" />
+ {t("Edit funnel")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => setIsCloneModalOpen(true)}>
+ <Copy className="h-4 w-4" />
+ {t("Clone")}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => setIsDeleteModalOpen(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")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ ) : (
+ <div />
+ )}
</div>
{/* Expandable content */}
{expanded && (
- <div className="border-t border-neutral-100 dark:border-neutral-800">
- <div className="p-4">
- {isPending ? (
- <ThreeDotLoader className="h-[400px]" />
- ) : isError ? (
- <div className="text-red-500 p-4 text-center">
- {t("Error loading funnel:")} {error instanceof Error ? error.message : t("Unknown error")}
- </div>
- ) : data && data.length > 0 ? (
- <Funnel data={data} steps={funnel.steps} isError={isError} error={error} isPending={isPending} />
- ) : (
- <div className="text-center p-6 text-neutral-500">{t("No funnel data available")}</div>
- )}
- </div>
+ <div className="border-t border-neutral-100 px-4 pb-3 pt-3 dark:border-neutral-800">
+ {isLoading || (needsAnalysis && analysis.isLoading) ? (
+ <ExpandedSkeleton steps={funnel.steps.length} />
+ ) : needsAnalysis && analysis.isError ? (
+ <div className="p-4 text-center text-sm text-red-500">
+ {t("Error loading funnel:")}{" "}
+ {analysis.error instanceof Error ? analysis.error.message : t("Failed to analyze funnel")}
+ </div>
+ ) : metrics ? (
+ <Funnel
+ steps={funnel.steps}
+ metrics={metrics}
+ previous={previous}
+ comparisonLabel={comparisonLabel}
+ goal={goal ? { name: goal.name || nameOf(funnel.steps.length - 1), href: links.goals } : null}
+ actions={
+ <>
+ <Button asChild variant="ghost" size="sm">
+ <Link href={links.journeys} prefetch={false}>
+ <Split />
+ {t("Explore paths")}
+ </Link>
+ </Button>
+ {canWrite && (
+ <>
+ <Button variant="ghost" size="sm" onClick={() => setIsCloneModalOpen(true)}>
+ <Copy />
+ {t("Clone")}
+ </Button>
+ <Button size="sm" onClick={() => setIsEditModalOpen(true)}>
+ <SquarePen />
+ {t("Edit funnel")}
+ </Button>
+ </>
+ )}
+ </>
+ }
+ />
+ ) : (
+ <div className={cn("p-6 text-center text-sm", MUTED)}>{t("No funnel data available")}</div>
+ )}
</div>
)}
{/* Delete Confirmation Modal */}
<ConfirmationModal
title={t("Delete Funnel")}
- description={t('Are you sure you want to delete "{name}"? This action cannot be undone.', { name: funnel.name })}
+ description={t('Are you sure you want to delete "{name}"? This action cannot be undone.', {
+ name: funnel.name,
+ })}
isOpen={isDeleteModalOpen}
setIsOpen={setIsDeleteModalOpen}
onConfirm={handleDeleteFunnel}
diff --git a/client/src/app/[site]/funnels/components/FunnelSortControl.tsx b/client/src/app/[site]/funnels/components/FunnelSortControl.tsx
new file mode 100644
index 000000000..1f19a3a84
--- /dev/null
+++ b/client/src/app/[site]/funnels/components/FunnelSortControl.tsx
@@ -0,0 +1,58 @@
+"use client";
+
+import { ArrowUpDown } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { ControlButton } from "@/components/site/ControlButton";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { FunnelSort } from "./funnelMetrics";
+
+const SORTS: FunnelSort[] = ["entered", "conversion", "change", "name", "created"];
+
+export interface FunnelSortControlProps {
+ value: FunnelSort;
+ onChange: (value: FunnelSort) => void;
+ /** Sorting by change needs a comparison period. */
+ comparisonEnabled: boolean;
+}
+
+export function FunnelSortControl({ value, onChange, comparisonEnabled }: FunnelSortControlProps) {
+ const t = useExtracted();
+
+ const labels: Record<FunnelSort, string> = {
+ entered: t("Sessions entered"),
+ conversion: t("Conversion"),
+ change: t("Change in conversion"),
+ name: t("Name"),
+ created: t("Date created"),
+ };
+ const options = SORTS.filter(sort => sort !== "change" || comparisonEnabled);
+
+ // Radix hands back a plain string; looking the option up returns it as a FunnelSort.
+ const select = (next: string) => {
+ const option = options.find(candidate => candidate === next);
+ if (option) onChange(option);
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <ControlButton icon={<ArrowUpDown />} label={t("Sort")} value={labels[value]} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup value={value} onValueChange={select}>
+ {options.map(option => (
+ <DropdownMenuRadioItem key={option} value={option}>
+ {labels[option]}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/client/src/app/[site]/funnels/components/FunnelStatBand.tsx b/client/src/app/[site]/funnels/components/FunnelStatBand.tsx
new file mode 100644
index 000000000..af960d9c6
--- /dev/null
+++ b/client/src/app/[site]/funnels/components/FunnelStatBand.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+import { ArrowDownRight, Funnel, LogIn, TrendingUp } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { StatBand, StatBandCell } from "@/components/site/StatBand";
+import { percentDelta } from "@/lib/delta";
+import {
+ biggestDropOff,
+ biggestGain,
+ countMoves,
+ formatRate,
+ FunnelRowData,
+ highestConversion,
+ stepLabel,
+} from "./funnelMetrics";
+import { useStepTypeLabels } from "./useStepTypeLabels";
+
+export interface FunnelStatBandProps {
+ rows: FunnelRowData[];
+ /** Sessions that entered at least one funnel in the selected period. */
+ sessionsEntered: number | undefined;
+ /** The same for the comparison period. Undefined when the comparison is off or not loaded. */
+ previousSessionsEntered: number | undefined;
+ /** Whether a comparison period is selected: it decides what the third cell reports. */
+ comparisonEnabled: boolean;
+ isLoading: boolean;
+}
+
+/** How the saved funnels did as a set: how many, how much traffic they see, and the two extremes. */
+export function FunnelStatBand({
+ rows,
+ sessionsEntered,
+ previousSessionsEntered,
+ comparisonEnabled,
+ isLoading,
+}: FunnelStatBandProps) {
+ const t = useExtracted();
+ const typeLabels = useStepTypeLabels();
+
+ const nameOf = (row: FunnelRowData, index: number) => {
+ const step = row.funnel.steps[index];
+ return stepLabel(step, typeLabels[step.type] ?? typeLabels.event);
+ };
+
+ // Without figures (the summary failed) or without the comparison's, a cell
+ // says nothing rather than "none" or zero.
+ const hasFigures = sessionsEntered !== undefined;
+ const hasComparison = hasFigures && previousSessionsEntered !== undefined;
+
+ const moves = countMoves(rows);
+ const withSessions = rows.filter(row => (row.current?.entered ?? 0) > 0).length;
+
+ const gain = biggestGain(rows);
+ const best = highestConversion(rows);
+ const thirdCell: StatBandCell = comparisonEnabled
+ ? {
+ id: "gain",
+ icon: <TrendingUp className="h-3 w-3" />,
+ label: t("Biggest gain"),
+ value: gain ? gain.row.funnel.name : hasComparison ? t("None") : "—",
+ title: gain?.row.funnel.name,
+ delta: gain?.delta,
+ sub: gain
+ ? t("{from} to {to} conversion", {
+ from: formatRate(gain.row.previous!.conversion!),
+ to: formatRate(gain.row.current!.conversion!),
+ })
+ : hasComparison
+ ? t("No funnel converts better than before")
+ : "",
+ }
+ : {
+ id: "gain",
+ icon: <TrendingUp className="h-3 w-3" />,
+ label: t("Highest conversion"),
+ value: best ? best.funnel.name : "—",
+ title: best?.funnel.name,
+ sub: best
+ ? t("{rate} of {count} sessions convert", {
+ rate: formatRate(best.current!.conversion!),
+ count: best.current!.entered.toLocaleString(),
+ })
+ : "",
+ };
+
+ const leak = biggestDropOff(rows);
+ const leakText = leak
+ ? t("{from} to {to}, in {funnel}", {
+ from: nameOf(leak.row, leak.stepIndex),
+ to: nameOf(leak.row, leak.stepIndex + 1),
+ funnel: leak.row.funnel.name,
+ })
+ : null;
+
+ const cells: StatBandCell[] = [
+ {
+ icon: <Funnel className="h-3 w-3" />,
+ label: t("Funnels tracked"),
+ value: rows.length.toLocaleString(),
+ // The count is known before any numbers are.
+ isLoading: false,
+ sub:
+ isLoading || !hasFigures || (comparisonEnabled && !hasComparison)
+ ? ""
+ : comparisonEnabled
+ ? t("{improved} improved, {declined} declined", {
+ improved: String(moves.improved),
+ declined: String(moves.declined),
+ })
+ : t("{count} with sessions in this period", { count: String(withSessions) }),
+ },
+ {
+ icon: <LogIn className="h-3 w-3" />,
+ label: t("Sessions entering any funnel"),
+ // No figure is not zero: the summary may have failed to load.
+ value: sessionsEntered === undefined ? "—" : sessionsEntered.toLocaleString(),
+ delta: percentDelta(sessionsEntered, previousSessionsEntered),
+ sub:
+ previousSessionsEntered === undefined
+ ? ""
+ : t("{count} in the comparison period", { count: previousSessionsEntered.toLocaleString() }),
+ },
+ thirdCell,
+ {
+ icon: <ArrowDownRight className="h-3 w-3" />,
+ label: t("Biggest drop-off"),
+ value: leak ? formatRate(leak.rate) : "—",
+ // The sentence is long for a narrow cell; the hover text keeps it whole.
+ sub: leakText ? <span title={leakText}>{leakText}</span> : hasFigures ? t("No sessions lost between steps") : "",
+ },
+ ];
+
+ return <StatBand cells={cells} isLoading={isLoading} columns={4} />;
+}
diff --git a/client/src/app/[site]/funnels/components/funnelMetrics.test.ts b/client/src/app/[site]/funnels/components/funnelMetrics.test.ts
new file mode 100644
index 000000000..616408977
--- /dev/null
+++ b/client/src/app/[site]/funnels/components/funnelMetrics.test.ts
@@ -0,0 +1,322 @@
+import { describe, expect, it } from "vitest";
+import type { FunnelSummariesResponse, Goal, SavedFunnel } from "@/api/analytics/endpoints";
+import {
+ biggestDecline,
+ biggestDropOff,
+ biggestGain,
+ computeFunnelMetrics,
+ countMoves,
+ findMatchingGoal,
+ formatRate,
+ formatStepDuration,
+ FunnelRowData,
+ highestConversion,
+ metricsFromSummary,
+ rateDelta,
+ searchFunnels,
+ sortFunnels,
+} from "./funnelMetrics";
+
+const funnel = (id: number, name: string, stepCount = 3): SavedFunnel => ({
+ id,
+ name,
+ steps: Array.from({ length: stepCount }, (_, index) => ({ type: "page" as const, value: `/step-${index + 1}` })),
+ createdAt: "2026-09-01T00:00:00Z",
+ updatedAt: "2026-09-01T00:00:00Z",
+});
+
+const row = (id: number, name: string, current: number[] | null, previous: number[] | null = null): FunnelRowData => ({
+ funnel: funnel(id, name, (current ?? previous ?? [0, 0, 0]).length),
+ current: current && computeFunnelMetrics(current.map(sessions => ({ sessions }))),
+ previous: previous && computeFunnelMetrics(previous.map(sessions => ({ sessions }))),
+});
+
+describe("computeFunnelMetrics", () => {
+ it("puts the drop-off on the step people left, not on the step they never reached", () => {
+ const metrics = computeFunnelMetrics([{ sessions: 1000 }, { sessions: 250 }, { sessions: 50 }]);
+
+ expect(metrics.steps.map(step => step.dropped)).toEqual([750, 200, 0]);
+ expect(metrics.steps.map(step => step.continueRate)).toEqual([0.25, 0.2, null]);
+ expect(metrics.steps.map(step => step.ofStart)).toEqual([1, 0.25, 0.05]);
+ expect(metrics.steps.map(step => step.fromPrevious)).toEqual([1, 0.25, 0.2]);
+ expect(metrics).toMatchObject({ entered: 1000, converted: 50, conversion: 0.05, worstStep: 1 });
+ });
+
+ it("has no rate to state when nobody entered", () => {
+ const metrics = computeFunnelMetrics([{ sessions: 0 }, { sessions: 0 }]);
+
+ expect(metrics.conversion).toBeNull();
+ expect(metrics.steps[0]).toMatchObject({ ofStart: 0, continueRate: null, dropped: 0 });
+ expect(metrics.worstStep).toBeNull();
+ });
+
+ it("names no worst step when every session goes all the way", () => {
+ expect(computeFunnelMetrics([{ sessions: 10 }, { sessions: 10 }]).worstStep).toBeNull();
+ });
+
+ it("keeps step times on the step they start from, and none on the last", () => {
+ const metrics = computeFunnelMetrics(
+ [
+ { sessions: 100, medianSecondsToNext: 58 },
+ { sessions: 40, medianSecondsToNext: 81 },
+ { sessions: 10, medianSecondsToNext: 999 },
+ ],
+ 708
+ );
+
+ expect(metrics.steps.map(step => step.medianSecondsToNext)).toEqual([58, 81, null]);
+ expect(metrics.medianSecondsToConvert).toBe(708);
+ });
+});
+
+describe("metricsFromSummary", () => {
+ const response: FunnelSummariesResponse = {
+ sessions_entered_any: 100,
+ truncated: false,
+ funnels: [
+ {
+ funnel_id: 7,
+ steps: [
+ { sessions: 100, median_seconds_to_next: 30 },
+ { sessions: 20, median_seconds_to_next: null },
+ ],
+ median_seconds_to_convert: 30,
+ },
+ ],
+ };
+
+ it("reads the funnel's own summary", () => {
+ expect(metricsFromSummary(funnel(7, "Signup", 2), response)).toMatchObject({
+ entered: 100,
+ converted: 20,
+ conversion: 0.2,
+ medianSecondsToConvert: 30,
+ });
+ });
+
+ it("has nothing for a funnel the summary leaves out, or while it loads", () => {
+ expect(metricsFromSummary(funnel(8, "Other", 2), response)).toBeNull();
+ expect(metricsFromSummary(funnel(7, "Signup", 2), undefined)).toBeNull();
+ });
+
+ it("ignores a summary computed for a different set of steps", () => {
+ // The funnel was just edited from two steps to three; the summary has not refetched.
+ expect(metricsFromSummary(funnel(7, "Signup", 3), response)).toBeNull();
+ });
+});
+
+describe("formatting", () => {
+ it("prints small rates with two decimals so 0.49% is not rounded to 0.5%", () => {
+ expect(formatRate(0.0049)).toBe("0.49%");
+ expect(formatRate(0.167)).toBe("16.7%");
+ expect(formatRate(0)).toBe("0%");
+ expect(formatRate(1)).toBe("100%");
+ });
+
+ it("states rate changes in percentage points at the precision of the rates", () => {
+ expect(rateDelta(0.167, 0.155)).toMatchObject({ direction: "up", text: "1.2 pp" });
+ expect(rateDelta(0.0049, 0.0045)).toMatchObject({ direction: "up", text: "0.04 pp" });
+ expect(rateDelta(0.147, 0.16)).toMatchObject({ direction: "down", text: "1.3 pp" });
+ expect(rateDelta(0.5, 0.5)).toMatchObject({ direction: "flat" });
+ });
+
+ it("draws no change without both periods", () => {
+ expect(rateDelta(0.5, null)).toBeNull();
+ expect(rateDelta(null, 0.5)).toBeNull();
+ expect(rateDelta(0.5, undefined)).toBeNull();
+ });
+
+ it("formats step times", () => {
+ expect(formatStepDuration(0.4)).toBe("<1s");
+ expect(formatStepDuration(58)).toBe("58s");
+ expect(formatStepDuration(81)).toBe("1m 21s");
+ expect(formatStepDuration(120)).toBe("2m");
+ expect(formatStepDuration(708)).toBe("11m 48s");
+ expect(formatStepDuration(7500)).toBe("2h 5m");
+ });
+});
+
+describe("sortFunnels", () => {
+ const rows = [
+ row(1, "Visit to paid", [1000, 100, 10], [1000, 100, 5]),
+ row(2, "Docs activation", [500, 200, 100], [500, 200, 150]),
+ row(3, "Blog to pricing", null),
+ row(4, "Hero to signup", [2000, 20, 2], [2000, 20, 2]),
+ ];
+ const names = (sorted: FunnelRowData[]) => sorted.map(item => item.funnel.name);
+
+ it("orders by sessions entered, funnels without figures last", () => {
+ expect(names(sortFunnels(rows, "entered"))).toEqual([
+ "Hero to signup",
+ "Visit to paid",
+ "Docs activation",
+ "Blog to pricing",
+ ]);
+ });
+
+ it("orders by conversion and by change in conversion", () => {
+ expect(names(sortFunnels(rows, "conversion"))).toEqual([
+ "Docs activation",
+ "Visit to paid",
+ "Hero to signup",
+ "Blog to pricing",
+ ]);
+ expect(names(sortFunnels(rows, "change"))).toEqual([
+ "Visit to paid",
+ "Hero to signup",
+ "Docs activation",
+ "Blog to pricing",
+ ]);
+ });
+
+ it("orders by name, and leaves creation order alone", () => {
+ expect(names(sortFunnels(rows, "name"))).toEqual([
+ "Blog to pricing",
+ "Docs activation",
+ "Hero to signup",
+ "Visit to paid",
+ ]);
+ expect(sortFunnels(rows, "created")).toEqual(rows);
+ });
+
+ it("does not reorder the rows it was given", () => {
+ const before = [...rows];
+ sortFunnels(rows, "entered");
+ expect(rows).toEqual(before);
+ });
+});
+
+describe("the stat band's picks", () => {
+ const rows = [
+ row(1, "Visit to paid", [1000, 100, 10], [1000, 100, 5]), // 0.5% -> 1%
+ row(2, "Docs activation", [500, 200, 100], [400, 200, 120]), // 30% -> 20%
+ row(3, "Demo to signup", [100, 90, 2], [100, 90, 10]), // 10% -> 2%, loses 88 of 90 at step 2
+ row(4, "Blog to pricing", null),
+ ];
+
+ it("counts funnels that convert better and worse", () => {
+ expect(countMoves(rows)).toEqual({ improved: 1, declined: 2 });
+ });
+
+ it("does not count a move that prints as zero", () => {
+ expect(countMoves([row(1, "Flat", [100000, 50000], [100000, 50001])])).toEqual({ improved: 0, declined: 0 });
+ });
+
+ it("picks the funnel whose conversion rose the most", () => {
+ const gain = biggestGain(rows);
+
+ expect(gain?.row.funnel.name).toBe("Visit to paid");
+ expect(gain?.delta).toMatchObject({ direction: "up", text: "0.50 pp" });
+ });
+
+ it("has no biggest gain when nothing improved or there is no comparison", () => {
+ expect(biggestGain([rows[1], rows[2]])).toBeNull();
+ expect(biggestGain([row(1, "No comparison", [10, 5])])).toBeNull();
+ });
+
+ it("picks the funnel whose conversion fell the most and the step transition that lost the most ground", () => {
+ const decline = biggestDecline(rows);
+
+ expect(decline?.row.funnel.name).toBe("Docs activation");
+ expect(decline?.delta).toMatchObject({ direction: "down", text: "10.0 pp" });
+ // Step 1 to 2 fell from 50% to 40%, step 2 to 3 from 60% to 50%: the first transition wins the tie.
+ expect(decline?.stepIndex).toBe(0);
+ // Entries rose from 400 to 500 while conversion fell.
+ expect(decline?.enteredDelta).toMatchObject({ direction: "up", text: "25.0%" });
+ });
+
+ it("only mentions entries when they rose", () => {
+ expect(biggestDecline([rows[2]])?.enteredDelta).toBeNull();
+ expect(biggestDecline([rows[0]])).toBeNull();
+ });
+
+ it("picks the single leakiest step across all funnels", () => {
+ const leak = biggestDropOff(rows);
+
+ expect(leak?.row.funnel.name).toBe("Demo to signup");
+ expect(leak?.stepIndex).toBe(1);
+ expect(leak?.rate).toBeCloseTo(88 / 90);
+ });
+
+ it("has no leakiest step without figures", () => {
+ expect(biggestDropOff([rows[3]])).toBeNull();
+ });
+
+ it("picks the best converting funnel when there is no comparison", () => {
+ expect(highestConversion(rows)?.funnel.name).toBe("Docs activation");
+ expect(highestConversion([rows[3]])).toBeNull();
+ });
+});
+
+describe("findMatchingGoal", () => {
+ const goal = (goalId: number, goalType: Goal["goalType"], config: Goal["config"]): Goal => ({
+ goalId,
+ name: `Goal ${goalId}`,
+ goalType,
+ config,
+ createdAt: "2026-09-01T00:00:00Z",
+ total_conversions: 0,
+ total_sessions: 0,
+ conversion_rate: 0,
+ });
+ const goals = [
+ goal(1, "path", { pathPattern: "/signup" }),
+ goal(2, "event", { eventName: "subscription_created" }),
+ goal(3, "event", { eventName: "cta_click", propertyFilters: [{ key: "location", value: "hero" }] }),
+ goal(4, "button_click", { valuePattern: "Buy*" }),
+ goal(5, "outbound", {}),
+ ];
+
+ it("matches a page step to a path goal with the same pattern", () => {
+ expect(findMatchingGoal({ type: "page", value: "/signup" }, goals)?.goalId).toBe(1);
+ expect(findMatchingGoal({ type: "page", value: "/pricing" }, goals)).toBeUndefined();
+ });
+
+ it("matches an event step to an event goal with the same name and property filters", () => {
+ expect(findMatchingGoal({ type: "event", value: "subscription_created" }, goals)?.goalId).toBe(2);
+ expect(findMatchingGoal({ type: "event", value: "cta_click" }, goals)).toBeUndefined();
+ expect(
+ findMatchingGoal(
+ { type: "event", value: "cta_click", propertyFilters: [{ key: "location", value: "hero" }] },
+ goals
+ )?.goalId
+ ).toBe(3);
+ // The legacy single-property fields mean the same thing.
+ expect(
+ findMatchingGoal(
+ { type: "event", value: "cta_click", eventPropertyKey: "location", eventPropertyValue: "hero" },
+ goals
+ )?.goalId
+ ).toBe(3);
+ });
+
+ it("matches autocapture steps by type and pattern, an empty pattern meaning any", () => {
+ expect(findMatchingGoal({ type: "button_click", value: "Buy*" }, goals)?.goalId).toBe(4);
+ expect(findMatchingGoal({ type: "button_click", value: "" }, goals)).toBeUndefined();
+ expect(findMatchingGoal({ type: "outbound", value: "" }, goals)?.goalId).toBe(5);
+ });
+
+ it("never matches a step limited to one hostname: no goal is that narrow", () => {
+ expect(findMatchingGoal({ type: "page", value: "/signup", hostname: "app.example.com" }, goals)).toBeUndefined();
+ });
+
+ it("does not confuse a page with an event of the same text", () => {
+ expect(findMatchingGoal({ type: "event", value: "/signup" }, goals)).toBeUndefined();
+ });
+});
+
+describe("searchFunnels", () => {
+ const rows = [row(1, "Visit to paid", null), row(2, "Docs activation", null)];
+ rows[1].funnel.steps[0] = { type: "event", value: "copy_snippet", name: "Copied snippet" };
+
+ it("matches the name, a step's value or a step's label, ignoring case", () => {
+ expect(searchFunnels(rows, "PAID").map(item => item.funnel.id)).toEqual([1]);
+ expect(searchFunnels(rows, "copy_").map(item => item.funnel.id)).toEqual([2]);
+ expect(searchFunnels(rows, "copied").map(item => item.funnel.id)).toEqual([2]);
+ expect(searchFunnels(rows, "/step-2").map(item => item.funnel.id)).toEqual([1, 2]);
+ });
+
+ it("returns everything for an empty search", () => {
+ expect(searchFunnels(rows, " ")).toEqual(rows);
+ });
+});
diff --git a/client/src/app/[site]/funnels/components/funnelMetrics.ts b/client/src/app/[site]/funnels/components/funnelMetrics.ts
new file mode 100644
index 000000000..84ac52a8a
--- /dev/null
+++ b/client/src/app/[site]/funnels/components/funnelMetrics.ts
@@ -0,0 +1,289 @@
+import { FunnelResponse, FunnelStep, FunnelSummariesResponse, Goal, SavedFunnel } from "@/api/analytics/endpoints";
+import { DeltaValue, percentDelta, pointDelta } from "@/lib/delta";
+import { resolvePropertyFilters } from "@/lib/events";
+
+/** One step of a funnel over one period. Rates are fractions (0 to 1). */
+export interface StepMetrics {
+ /** Sessions that reached the step. */
+ sessions: number;
+ /** Share of the sessions that entered the funnel. */
+ ofStart: number;
+ /** Share of the sessions that reached the step before. 1 on the first step. */
+ fromPrevious: number;
+ /** Share that went on to the next step. Null on the last step and when nobody reached this one. */
+ continueRate: number | null;
+ /** Sessions that reached this step and not the next: the people who left here. 0 on the last step. */
+ dropped: number;
+ medianSecondsToNext: number | null;
+}
+
+export interface FunnelMetrics {
+ steps: StepMetrics[];
+ entered: number;
+ converted: number;
+ /** Null when nobody entered: there is no rate to state. */
+ conversion: number | null;
+ medianSecondsToConvert: number | null;
+ /** Index of the step that loses the largest share of the sessions reaching it. Null when nothing is lost. */
+ worstStep: number | null;
+}
+
+export function computeFunnelMetrics(
+ steps: { sessions: number; medianSecondsToNext?: number | null }[],
+ medianSecondsToConvert: number | null = null
+): FunnelMetrics {
+ const entered = steps[0]?.sessions ?? 0;
+ const converted = steps[steps.length - 1]?.sessions ?? 0;
+
+ const metrics = steps.map((step, index): StepMetrics => {
+ const before = steps[index - 1];
+ const next = steps[index + 1];
+ return {
+ sessions: step.sessions,
+ ofStart: entered > 0 ? step.sessions / entered : 0,
+ fromPrevious: !before ? 1 : before.sessions > 0 ? step.sessions / before.sessions : 0,
+ continueRate: next && step.sessions > 0 ? next.sessions / step.sessions : null,
+ dropped: next ? Math.max(0, step.sessions - next.sessions) : 0,
+ medianSecondsToNext: next ? (step.medianSecondsToNext ?? null) : null,
+ };
+ });
+
+ let worstStep: number | null = null;
+ metrics.forEach((step, index) => {
+ if (step.continueRate === null || step.dropped === 0) return;
+ const worst = worstStep === null ? null : metrics[worstStep];
+ if (
+ !worst ||
+ step.continueRate < worst.continueRate! ||
+ (step.continueRate === worst.continueRate && step.dropped > worst.dropped)
+ ) {
+ worstStep = index;
+ }
+ });
+
+ return {
+ steps: metrics,
+ entered,
+ converted,
+ conversion: entered > 0 ? converted / entered : null,
+ medianSecondsToConvert: steps.length > 1 && converted > 0 ? medianSecondsToConvert : null,
+ worstStep,
+ };
+}
+
+/**
+ * A saved funnel's numbers out of a summary response. Null when the summary
+ * does not cover the funnel, or was computed for a different set of steps (the
+ * funnel was edited and the summary has not refetched yet).
+ */
+export function metricsFromSummary(
+ funnel: SavedFunnel,
+ response: FunnelSummariesResponse | undefined
+): FunnelMetrics | null {
+ const summary = response?.funnels.find(candidate => candidate.funnel_id === funnel.id);
+ if (!summary || summary.steps.length !== funnel.steps.length) return null;
+
+ return computeFunnelMetrics(
+ summary.steps.map(step => ({ sessions: step.sessions, medianSecondsToNext: step.median_seconds_to_next })),
+ summary.median_seconds_to_convert
+ );
+}
+
+/** The analyze endpoint's rows as metrics. It reports no step times. */
+export function metricsFromAnalysis(rows: FunnelResponse[]): FunnelMetrics {
+ return computeFunnelMetrics(rows.map(row => ({ sessions: row.sessions })));
+}
+
+/** One row of the funnels list: the definition and its numbers for both periods. */
+export interface FunnelRowData {
+ funnel: SavedFunnel;
+ /** Null while loading and when the summary does not cover the funnel. */
+ current: FunnelMetrics | null;
+ /** Null when the comparison is off, loading, or does not cover the funnel. */
+ previous: FunnelMetrics | null;
+}
+
+/**
+ * A rate for display: one decimal, two below 2% so that 0.49% is not printed
+ * as 0.5%.
+ */
+export function formatRate(fraction: number): string {
+ if (fraction === 0) return "0%";
+ if (fraction === 1) return "100%";
+ return `${(fraction * 100).toFixed(fraction < 0.02 ? 2 : 1)}%`;
+}
+
+/** Change of a rate in percentage points, with the precision `formatRate` prints the rates at. */
+export function rateDelta(current: number | null | undefined, previous: number | null | undefined): DeltaValue | null {
+ if (current == null || previous == null) return null;
+ return pointDelta(current * 100, previous * 100, { decimals: Math.max(current, previous) < 0.02 ? 2 : 1 });
+}
+
+export const conversionDelta = (row: FunnelRowData) => rateDelta(row.current?.conversion, row.previous?.conversion);
+
+const conversionChange = (row: FunnelRowData) =>
+ row.current?.conversion != null && row.previous?.conversion != null
+ ? row.current.conversion - row.previous.conversion
+ : null;
+
+/** "<1s", "58s", "1m 21s", "2h 5m". */
+export function formatStepDuration(seconds: number): string {
+ if (seconds < 1) return "<1s";
+ const total = Math.round(seconds);
+ const hours = Math.floor(total / 3600);
+ const minutes = Math.floor((total % 3600) / 60);
+ const secs = total % 60;
+ if (hours > 0) return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
+ if (minutes > 0) return secs > 0 ? `${minutes}m ${secs}s` : `${minutes}m`;
+ return `${secs}s`;
+}
+
+export type FunnelSort = "entered" | "conversion" | "change" | "name" | "created";
+
+// Missing numbers sort after every real one.
+const descending = (a: number | null | undefined, b: number | null | undefined) =>
+ (b ?? Number.NEGATIVE_INFINITY) - (a ?? Number.NEGATIVE_INFINITY);
+
+/** `rows` arrive in creation order; every sort is stable on top of that. */
+export function sortFunnels(rows: FunnelRowData[], sort: FunnelSort): FunnelRowData[] {
+ const sorted = [...rows];
+ switch (sort) {
+ case "entered":
+ return sorted.sort((a, b) => descending(a.current?.entered, b.current?.entered));
+ case "conversion":
+ return sorted.sort((a, b) => descending(a.current?.conversion, b.current?.conversion));
+ case "change":
+ return sorted.sort((a, b) => descending(conversionChange(a), conversionChange(b)));
+ case "name":
+ return sorted.sort((a, b) => a.funnel.name.localeCompare(b.funnel.name));
+ case "created":
+ return sorted;
+ }
+}
+
+/** How many funnels convert better and worse than in the comparison period, at the printed precision. */
+export function countMoves(rows: FunnelRowData[]): { improved: number; declined: number } {
+ let improved = 0;
+ let declined = 0;
+ for (const row of rows) {
+ const direction = conversionDelta(row)?.direction;
+ if (direction === "up") improved++;
+ if (direction === "down") declined++;
+ }
+ return { improved, declined };
+}
+
+// The funnel whose conversion moved furthest in one direction. A move that
+// prints as 0.0 pp is not a move.
+function biggestMove(rows: FunnelRowData[], direction: "up" | "down") {
+ let best: { row: FunnelRowData; delta: DeltaValue; change: number } | null = null;
+ for (const row of rows) {
+ const delta = conversionDelta(row);
+ const change = conversionChange(row);
+ if (!delta || change === null || delta.direction !== direction) continue;
+ if (!best || Math.abs(change) > Math.abs(best.change)) best = { row, delta, change };
+ }
+ return best;
+}
+
+export const biggestGain = (rows: FunnelRowData[]) => biggestMove(rows, "up");
+
+export interface FunnelDecline {
+ row: FunnelRowData;
+ delta: DeltaValue;
+ /** Change in sessions entering the funnel, when they rose while conversion fell. */
+ enteredDelta: DeltaValue | null;
+ /** Index of the step whose continue rate fell the most. */
+ stepIndex: number;
+}
+
+/** The funnel whose conversion fell the most, and the step transition that lost the most ground. */
+export function biggestDecline(rows: FunnelRowData[]): FunnelDecline | null {
+ const worst = biggestMove(rows, "down");
+ if (!worst) return null;
+
+ const { current, previous } = worst.row;
+ let stepIndex: number | null = null;
+ let largestFall = 0;
+ current!.steps.forEach((step, index) => {
+ const before = previous!.steps[index]?.continueRate;
+ if (step.continueRate === null || before == null) return;
+ const fall = before - step.continueRate;
+ if (fall > largestFall) {
+ largestFall = fall;
+ stepIndex = index;
+ }
+ });
+ if (stepIndex === null) return null;
+
+ const enteredDelta = percentDelta(current!.entered, previous!.entered);
+ return {
+ row: worst.row,
+ delta: worst.delta,
+ enteredDelta: enteredDelta?.direction === "up" ? enteredDelta : null,
+ stepIndex,
+ };
+}
+
+/** The funnel with the highest conversion this period: the stat band's third cell when there is no comparison. */
+export function highestConversion(rows: FunnelRowData[]): FunnelRowData | null {
+ let best: FunnelRowData | null = null;
+ for (const row of rows) {
+ if (row.current?.conversion == null) continue;
+ if (!best || row.current.conversion > best.current!.conversion!) best = row;
+ }
+ return best;
+}
+
+/** The single step, across all funnels, that loses the largest share of the sessions reaching it. */
+export function biggestDropOff(rows: FunnelRowData[]): { row: FunnelRowData; stepIndex: number; rate: number } | null {
+ let worst: { row: FunnelRowData; stepIndex: number; rate: number; dropped: number } | null = null;
+ for (const row of rows) {
+ const stepIndex = row.current?.worstStep;
+ if (stepIndex == null) continue;
+ const step = row.current!.steps[stepIndex];
+ const rate = 1 - step.continueRate!;
+ if (!worst || rate > worst.rate || (rate === worst.rate && step.dropped > worst.dropped)) {
+ worst = { row, stepIndex, rate, dropped: step.dropped };
+ }
+ }
+ return worst && { row: worst.row, stepIndex: worst.stepIndex, rate: worst.rate };
+}
+
+/** A step's name as shown everywhere: its label, else what it matches, else its type. */
+export const stepLabel = (step: FunnelStep, typeLabel: string) => step.name || step.value || typeLabel;
+
+const filterKey = (filters: { key: string; value: string | number | boolean }[]) =>
+ filters
+ .map(filter => `${filter.key}=${String(filter.value)}`)
+ .sort()
+ .join("&");
+
+/**
+ * The goal that counts exactly what a funnel step matches: same kind of
+ * target, same pattern, same property filters. A step limited to one hostname
+ * is narrower than any goal, so it never matches.
+ */
+export function findMatchingGoal(step: FunnelStep, goals: Goal[]): Goal | undefined {
+ if (step.hostname) return undefined;
+ const stepFilters = filterKey(resolvePropertyFilters(step));
+
+ return goals.find(goal => {
+ if (filterKey(resolvePropertyFilters(goal.config)) !== stepFilters) return false;
+ if (step.type === "page") return goal.goalType === "path" && goal.config.pathPattern === step.value;
+ if (step.type === "event") return goal.goalType === "event" && goal.config.eventName === step.value;
+ return goal.goalType === step.type && (goal.config.valuePattern ?? "").trim() === (step.value ?? "").trim();
+ });
+}
+
+/** The funnels whose name or steps contain the search text. */
+export function searchFunnels(rows: FunnelRowData[], search: string): FunnelRowData[] {
+ const query = search.trim().toLowerCase();
+ if (!query) return rows;
+
+ return rows.filter(
+ ({ funnel }) =>
+ funnel.name.toLowerCase().includes(query) ||
+ funnel.steps.some(step => step.value.toLowerCase().includes(query) || step.name?.toLowerCase().includes(query))
+ );
+}
diff --git a/client/src/app/[site]/funnels/components/useStepTypeLabels.ts b/client/src/app/[site]/funnels/components/useStepTypeLabels.ts
new file mode 100644
index 000000000..035e6348d
--- /dev/null
+++ b/client/src/app/[site]/funnels/components/useStepTypeLabels.ts
@@ -0,0 +1,15 @@
+import { useExtracted } from "next-intl";
+import { FunnelStepType } from "@/api/analytics/endpoints";
+
+/** What each kind of funnel step is called, for a step with no label and for the line under its name. */
+export function useStepTypeLabels(): Record<FunnelStepType, string> {
+ const t = useExtracted();
+ return {
+ page: t("Page"),
+ event: t("Event"),
+ outbound: t("Outbound"),
+ button_click: t("Button"),
+ form_submit: t("Form"),
+ copy: t("Copy"),
+ };
+}
diff --git a/client/src/app/[site]/funnels/page.tsx b/client/src/app/[site]/funnels/page.tsx
index 85241e783..3eb7951f6 100644
--- a/client/src/app/[site]/funnels/page.tsx
+++ b/client/src/app/[site]/funnels/page.tsx
@@ -1,61 +1,58 @@
"use client";
+import { Funnel } from "lucide-react";
import { useExtracted } from "next-intl";
-import { Input } from "@/components/ui/input";
-import { GOALS_PAGE_FILTERS } from "@/lib/filterGroups";
-import { useStore } from "@/lib/store";
-import { ArrowRight, Funnel } from "lucide-react";
-import { Card } from "@/components/ui/card";
+import { useSearchParams } from "next/navigation";
import { useMemo, useState } from "react";
-import { useGetFunnels } from "../../../api/analytics/hooks/funnels/useGetFunnels";
-import { SavedFunnel } from "../../../api/analytics/endpoints";
-import { DisabledOverlay } from "../../../components/DisabledOverlay";
-import { ErrorState } from "../../../components/ErrorState";
-import { NothingFound } from "../../../components/NothingFound";
-import { useCanOnSite } from "../../../hooks/usePermissions";
-import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
+import { useGetFunnelGoals } from "@/api/analytics/hooks/funnels/useGetFunnelGoals";
+import { useGetFunnels } from "@/api/analytics/hooks/funnels/useGetFunnels";
+import { useGetFunnelSummaries } from "@/api/analytics/hooks/funnels/useGetFunnelSummaries";
+import { describeComparisonWindow } from "@/components/DateSelector/rangeFields";
+import { DisabledOverlay } from "@/components/DisabledOverlay";
+import { ErrorState } from "@/components/ErrorState";
+import { ExternalLink } from "@/components/ExternalLink";
+import { NothingFound } from "@/components/NothingFound";
+import { AnalysisBar } from "@/components/site/AnalysisBar";
+import { InsightRow } from "@/components/site/InsightRow";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Skeleton } from "@/components/ui/skeleton";
+import { useCanOnSite } from "@/hooks/usePermissions";
+import { useSetPageTitle } from "@/hooks/useSetPageTitle";
+import { FUNNEL_PAGE_FILTERS } from "@/lib/filterGroups";
+import { useComparisonEnabled, useStore, useTimezone } from "@/lib/store";
+import { cn } from "@/lib/utils";
import { SubHeader } from "../components/SubHeader/SubHeader";
import { CreateFunnelDialog } from "./components/CreateFunnel";
-import { FunnelRow } from "./components/FunnelRow";
-import { ExternalLink } from "../../../components/ExternalLink";
+import {
+ biggestDecline,
+ FunnelRowData,
+ FunnelSort,
+ metricsFromSummary,
+ searchFunnels,
+ sortFunnels,
+ stepLabel,
+} from "./components/funnelMetrics";
+import { FUNNEL_ROW_GRID, FunnelRow } from "./components/FunnelRow";
+import { FunnelSortControl } from "./components/FunnelSortControl";
+import { FunnelStatBand } from "./components/FunnelStatBand";
+import { useStepTypeLabels } from "./components/useStepTypeLabels";
-// Skeleton for the funnel row component
const FunnelRowSkeleton = () => (
- <Card className="mb-4 overflow-hidden">
- <div className="flex items-center justify-between py-2 px-5 animate-pulse">
- <div className="flex items-center grow">
- <div className="mt-1 text-xs text-neutral-500 dark:text-neutral-400 flex flex-col gap-3">
- {/* Funnel name and steps skeleton */}
- <div className="flex flex-wrap gap-1">
- <div className="h-6 bg-neutral-200 dark:bg-neutral-700 rounded w-32 mr-2"></div>
- <div className="flex items-center">
- <span className="rounded bg-neutral-100 dark:bg-neutral-800 px-1.5 py-0.5 flex items-center">
- <div className="w-3 h-3 bg-neutral-200 dark:bg-neutral-700 rounded mr-1"></div>
- <div className="h-3 bg-neutral-200 dark:bg-neutral-700 rounded w-16"></div>
- </span>
- <ArrowRight className="h-3 w-3 mx-1 text-neutral-400" />
- <span className="rounded bg-neutral-100 dark:bg-neutral-800 px-1.5 py-0.5 flex items-center">
- <div className="w-3 h-3 bg-neutral-200 dark:bg-neutral-700 rounded mr-1"></div>
- <div className="h-3 bg-neutral-200 dark:bg-neutral-700 rounded w-20"></div>
- </span>
- <ArrowRight className="h-3 w-3 mx-1 text-neutral-400" />
- <span className="rounded bg-neutral-100 dark:bg-neutral-800 px-1.5 py-0.5 flex items-center">
- <div className="w-3 h-3 bg-neutral-200 dark:bg-neutral-700 rounded mr-1"></div>
- <div className="h-3 bg-neutral-200 dark:bg-neutral-700 rounded w-14"></div>
- </span>
- </div>
- </div>
- </div>
- </div>
-
- <div className="flex items-center gap-4">
- <div className="flex">
- <div className="h-9 w-9 bg-neutral-100 dark:bg-neutral-800 rounded-md"></div>
- <div className="h-9 w-9 bg-neutral-100 dark:bg-neutral-800 rounded-md"></div>
- <div className="h-9 w-9 bg-neutral-100 dark:bg-neutral-800 rounded-md"></div>
- <div className="h-9 w-9 bg-neutral-100 dark:bg-neutral-800 rounded-md"></div>
- </div>
+ <Card className="@container">
+ <div className={cn(FUNNEL_ROW_GRID, "px-4 py-2.5")}>
+ <Skeleton className="h-4 w-4 rounded" />
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-40 rounded" />
+ <Skeleton className="h-5 w-64 max-w-full rounded" />
</div>
+ <Skeleton className="hidden h-6 w-12 rounded @3xl:block" />
+ <Skeleton className="ml-auto hidden h-4 w-12 rounded @3xl:block" />
+ <Skeleton className="ml-auto hidden h-4 w-10 rounded @3xl:block" />
+ <Skeleton className="ml-auto hidden h-4 w-10 rounded @3xl:block" />
+ <Skeleton className="ml-auto hidden h-4 w-12 rounded @3xl:block" />
+ <div />
</div>
</Card>
);
@@ -64,61 +61,220 @@ export default function FunnelsPage() {
const t = useExtracted();
useSetPageTitle("Funnels");
- const { site } = useStore();
- const { data: funnels, isLoading, error } = useGetFunnels(site);
+ const site = useStore(state => state.site);
+ const privateKey = useStore(state => state.privateKey);
+ const time = useStore(state => state.time);
+ const previousTime = useStore(state => state.previousTime);
+ const zone = useTimezone();
+ const comparisonEnabled = useComparisonEnabled();
const canWrite = useCanOnSite("funnels:write");
+ const search = useSearchParams().toString();
+ const typeLabels = useStepTypeLabels();
+
+ const { data: funnels, isLoading, error } = useGetFunnels(site);
+ const current = useGetFunnelSummaries();
+ const previous = useGetFunnelSummaries({ periodTime: "previous" });
+
const [searchQuery, setSearchQuery] = useState("");
+ const [sort, setSort] = useState<FunnelSort>("entered");
+ // Null until someone opens or closes a row: until then the first funnel is open.
+ const [openIds, setOpenIds] = useState<number[] | null>(null);
- // Filter funnels based on search query
- const filteredFunnels = useMemo(() => {
- if (!funnels) return [];
- if (!searchQuery.trim()) return funnels;
+ const isLoadingSummary = current.isLoading;
+ const isLoadingComparison = comparisonEnabled && previous.isLoading;
+ // A comparison that is switched off may still be in the cache.
+ const previousData = comparisonEnabled ? previous.data : undefined;
+
+ const rows = useMemo<FunnelRowData[]>(
+ () =>
+ (funnels ?? []).map(funnel => ({
+ funnel,
+ current: metricsFromSummary(funnel, current.data),
+ previous: metricsFromSummary(funnel, previousData),
+ })),
+ [funnels, current.data, previousData]
+ );
+
+ const activeSort = sort === "change" && !comparisonEnabled ? "entered" : sort;
+ const visibleRows = useMemo(
+ () => searchFunnels(sortFunnels(rows, activeSort), searchQuery),
+ [rows, activeSort, searchQuery]
+ );
- const query = searchQuery.toLowerCase();
- return funnels.filter((funnel: SavedFunnel) => {
- // Search in funnel name
- if (funnel.name.toLowerCase().includes(query)) return true;
+ // The default row is picked once the order is final: sorting by a figure
+ // before the figures arrive would open one funnel and then move it.
+ const orderSettled = !isLoadingSummary && !(activeSort === "change" && isLoadingComparison);
+ const defaultOpenIds = orderSettled && visibleRows.length > 0 ? [visibleRows[0].funnel.id] : [];
+ const effectiveOpenIds = openIds ?? defaultOpenIds;
- // Search in step values
- return funnel.steps.some(
- step => step.value.toLowerCase().includes(query) || step.name?.toLowerCase().includes(query)
- );
- });
- }, [funnels, searchQuery]);
+ const toggleRow = (id: number) =>
+ setOpenIds(
+ effectiveOpenIds.includes(id) ? effectiveOpenIds.filter(open => open !== id) : [...effectiveOpenIds, id]
+ );
+
+ // Reordering or filtering keeps the rows that are open, rather than moving "the first one".
+ const changeSort = (next: FunnelSort) => {
+ setOpenIds(effectiveOpenIds);
+ setSort(next);
+ };
+ const changeSearch = (next: string) => {
+ setOpenIds(effectiveOpenIds);
+ setSearchQuery(next);
+ };
+
+ const openFunnel = (id: number) => {
+ setSearchQuery("");
+ setOpenIds(effectiveOpenIds.includes(id) ? effectiveOpenIds : [...effectiveOpenIds, id]);
+ // After the row has rendered open.
+ requestAnimationFrame(() =>
+ document.getElementById(`funnel-${id}`)?.scrollIntoView({ block: "nearest", behavior: "smooth" })
+ );
+ };
+
+ // Goals are only read to link an open funnel's last step.
+ const { data: goals } = useGetFunnelGoals({ enabled: effectiveOpenIds.length > 0 });
+
+ const base = privateKey ? `/${site}/${privateKey}` : `/${site}`;
+ const query = search ? `?${search}` : "";
+ const links = { goals: `${base}/goals${query}`, journeys: `${base}/journeys${query}` };
+
+ const comparisonLabel = comparisonEnabled ? describeComparisonWindow(previousTime, time, zone) : null;
+
+ const decline = previousData ? biggestDecline(rows) : null;
+ const declineStep = (offset: number) => {
+ const step = decline!.row.funnel.steps[decline!.stepIndex + offset];
+ return stepLabel(step, typeLabels[step.type] ?? typeLabels.event);
+ };
+
+ const hasFunnels = !!funnels?.length;
return (
<DisabledOverlay message="Funnels" featurePath="funnels">
<div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
- <SubHeader availableFilters={GOALS_PAGE_FILTERS} />
- <div className="flex justify-between items-center">
- <Input
- placeholder={t("Filter funnels")}
- className="w-48"
- isSearch
- value={searchQuery}
- onChange={e => setSearchQuery(e.target.value)}
- />
- {canWrite && <CreateFunnelDialog />}
- </div>
+ <SubHeader availableFilters={FUNNEL_PAGE_FILTERS} />
+
+ {(isLoading || hasFunnels) && (
+ <>
+ <FunnelStatBand
+ rows={rows}
+ sessionsEntered={current.data?.sessions_entered_any}
+ previousSessionsEntered={previousData?.sessions_entered_any}
+ comparisonEnabled={comparisonEnabled}
+ isLoading={isLoading || isLoadingSummary || isLoadingComparison}
+ />
+ <AnalysisBar
+ end={
+ <>
+ <Input
+ placeholder={t("Filter funnels")}
+ className="h-8 w-48"
+ isSearch
+ value={searchQuery}
+ onChange={e => changeSearch(e.target.value)}
+ />
+ {canWrite && <CreateFunnelDialog />}
+ </>
+ }
+ >
+ <FunnelSortControl value={activeSort} onChange={changeSort} comparisonEnabled={comparisonEnabled} />
+ </AnalysisBar>
+ {current.isError && (
+ <p className="text-sm text-neutral-500 dark:text-neutral-400">
+ {t("The funnels' figures could not be loaded. Open a funnel to analyze it on its own.")}
+ </p>
+ )}
+ </>
+ )}
+
+ {decline && (
+ <InsightRow
+ action={
+ <Button variant="ghost" size="xs" onClick={() => openFunnel(decline.row.funnel.id)}>
+ {t("Open funnel")}
+ </Button>
+ }
+ >
+ {decline.enteredDelta
+ ? t.rich(
+ "<name>{funnel}</name> converts {change} lower than the comparison period while sessions entering it are up {entered}. The largest fall is between {from} and {to}.",
+ {
+ funnel: decline.row.funnel.name,
+ change: decline.delta.text,
+ entered: decline.enteredDelta.text,
+ from: declineStep(0),
+ to: declineStep(1),
+ name: chunks => <span className="font-medium text-neutral-900 dark:text-neutral-50">{chunks}</span>,
+ }
+ )
+ : t.rich(
+ "<name>{funnel}</name> converts {change} lower than the comparison period. The largest fall is between {from} and {to}.",
+ {
+ funnel: decline.row.funnel.name,
+ change: decline.delta.text,
+ from: declineStep(0),
+ to: declineStep(1),
+ name: chunks => <span className="font-medium text-neutral-900 dark:text-neutral-50">{chunks}</span>,
+ }
+ )}
+ </InsightRow>
+ )}
{isLoading || !funnels ? (
- <div className="space-y-4">
- {[1, 2, 3].map(i => (
- <FunnelRowSkeleton key={i} />
- ))}
- </div>
- ) : error ? (
- <ErrorState
- title={t("Failed to load funnels")}
- message={t("There was a problem fetching the funnels. Please try again later.")}
- />
- ) : filteredFunnels?.length ? (
- <div className="space-y-4">
- {filteredFunnels.map((funnel: SavedFunnel, index: number) => (
- <FunnelRow key={funnel.id} funnel={funnel} index={index} canWrite={canWrite} />
- ))}
+ error ? (
+ <ErrorState
+ title={t("Failed to load funnels")}
+ message={t("There was a problem fetching the funnels. Please try again later.")}
+ />
+ ) : (
+ <div className="space-y-2">
+ {[1, 2, 3].map(i => (
+ <FunnelRowSkeleton key={i} />
+ ))}
+ </div>
+ )
+ ) : visibleRows.length ? (
+ <div className="@container">
+ {/* 17px: the cards' 16px padding plus their border. */}
+ <div
+ className={cn(
+ FUNNEL_ROW_GRID,
+ "hidden px-[17px] pb-1.5 text-xs text-neutral-500 dark:text-neutral-400 @3xl:grid"
+ )}
+ >
+ <div />
+ <div>{t("Funnel")}</div>
+ <div>{t("By step")}</div>
+ <div className="text-right">{t("Entered")}</div>
+ <div className="text-right">{t("Converted")}</div>
+ <div className="text-right">{t("Conversion")}</div>
+ <div className="whitespace-nowrap text-right">{comparisonEnabled && t("Change")}</div>
+ <div />
+ </div>
+ <div className="space-y-2">
+ {visibleRows.map(row => (
+ <FunnelRow
+ key={row.funnel.id}
+ row={row}
+ expanded={effectiveOpenIds.includes(row.funnel.id)}
+ onToggle={() => toggleRow(row.funnel.id)}
+ canWrite={canWrite}
+ isLoading={isLoadingSummary}
+ isLoadingComparison={isLoadingComparison}
+ comparisonLabel={comparisonLabel}
+ goals={goals?.data}
+ links={links}
+ />
+ ))}
+ </div>
+ {current.data?.truncated && (
+ <p className="pt-2 text-xs text-neutral-500 dark:text-neutral-400">
+ {t("Figures are shown for the {count} oldest funnels. Open any other funnel to analyze it.", {
+ count: String(current.data.funnels.length),
+ })}
+ </p>
+ )}
</div>
- ) : funnels?.length ? (
+ ) : hasFunnels ? (
<NothingFound
icon={<Funnel className="w-10 h-10" />}
title={t("No funnels found")}
@@ -128,7 +284,12 @@ export default function FunnelsPage() {
<NothingFound
icon={<Funnel className="w-10 h-10" />}
title={t("No funnels yet")}
- description={<span>{t("Create your first funnel to track conversions through your site's user journey.")} <ExternalLink href="https://rybbit.com/docs/funnels">{t("Learn more")}</ExternalLink></span>}
+ description={
+ <span>
+ {t("Create your first funnel to track conversions through your site's user journey.")}{" "}
+ <ExternalLink href="https://rybbit.com/docs/funnels">{t("Learn more")}</ExternalLink>
+ </span>
+ }
action={canWrite ? <CreateFunnelDialog /> : undefined}
/>
)}
diff --git a/client/src/app/[site]/goals/components/CreateGoalButton.tsx b/client/src/app/[site]/goals/components/CreateGoalButton.tsx
deleted file mode 100644
index d2b7b1fc4..000000000
--- a/client/src/app/[site]/goals/components/CreateGoalButton.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-"use client";
-
-import { useExtracted } from "next-intl";
-import { Plus } from "lucide-react";
-import { Button } from "../../../../components/ui/button";
-import GoalFormModal from "./GoalFormModal";
-
-interface CreateGoalButtonProps {
- siteId: number;
-}
-
-export default function CreateGoalButton({ siteId }: CreateGoalButtonProps) {
- const t = useExtracted();
- return (
- <>
- <GoalFormModal
- siteId={siteId}
- trigger={
- <Button className="flex items-center gap-1">
- <Plus className="h-4 w-4" />
- <span>{t("Add Goal")}</span>
- </Button>
- }
- />
- </>
- );
-}
diff --git a/client/src/app/[site]/goals/components/GoalCard.tsx b/client/src/app/[site]/goals/components/GoalCard.tsx
deleted file mode 100644
index 7a4aca7f3..000000000
--- a/client/src/app/[site]/goals/components/GoalCard.tsx
+++ /dev/null
@@ -1,351 +0,0 @@
-"use client";
-
-import { useExtracted } from "next-intl";
-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, GoalTimeSeriesPoint } from "../../../../api/analytics/endpoints";
-import { useGetGoalSessions } from "../../../../api/analytics/hooks/goals/useGetGoalSessions";
-import { EventTypeIcon } from "../../../../components/EventIcons";
-import { resolvePropertyFilters, targetTypeToEventType } from "../../../../lib/events";
-import { SessionsList } from "../../../../components/Sessions/SessionsList";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- 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 { formatChartDateTime } from "../../../../lib/dateTimeUtils";
-import { getTimezone, useStore } from "../../../../lib/store";
-import GoalFormModal from "./GoalFormModal";
-import { GoalBarChartSkeleton } from "./skeleton";
-
-interface GoalCardProps {
- goal: Goal;
- siteId: number;
- /** goals:write: edit, clone and delete. */
- canWrite: boolean;
- 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 lg:flex h-8 w-32 xl:w-44 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, canWrite, 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();
- const { time } = useStore();
-
- // Fetch sessions when expanded
- const { data: sessionsData, isLoading: isLoadingSessions } = useGetGoalSessions({
- goalId: goal.goalId,
- siteId,
- time,
- page,
- limit: LIMIT + 1,
- enabled: isExpanded,
- });
-
- const handleDelete = async () => {
- try {
- await deleteGoalMutation.mutateAsync(goal.goalId);
- setIsDeleteDialogOpen(false);
- } catch (error) {
- console.error("Error deleting goal:", error);
- }
- };
-
- const propertyFilters = resolvePropertyFilters(goal.config);
-
- const allSessions = sessionsData || [];
- const hasNextPage = allSessions.length > LIMIT;
- const sessions = allSessions.slice(0, LIMIT);
- const hasPrevPage = page > 1;
-
- const toggleExpansion = () => {
- setIsExpanded(!isExpanded);
- if (!isExpanded) {
- setPage(1); // Reset to first page when expanding
- }
- };
-
- return (
- <>
- <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 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=" min-w-0 md:flex-1 md:pr-4">
- <h3 className="font-medium text-base flex items-center gap-2 min-w-0">
- <EventTypeIcon type={targetTypeToEventType(goal.goalType)} />
- <span className="truncate">{goal.name || t("Goal #{goalId}", { goalId: String(goal.goalId) })}</span>
- </h3>
-
- <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="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.goalType === "event"
- ? goal.config.eventName
- : goal.config.valuePattern || t("Any")}
- </code>
-
- {propertyFilters.length > 0 && (
- <div className="mt-1 text-xs text-neutral-500 dark:text-neutral-400">
- {t("Property")}:{" "}
- <code className="text-xs bg-neutral-100 dark:bg-neutral-800 px-1 py-0.5 rounded text-neutral-900 dark:text-neutral-100">
- {propertyFilters.map(f => `${f.key}: ${f.value}`).join(", ")}
- </code>
- </div>
- )}
- </div>
- </div>
- {/* Center section - Stats */}
- <div className="w-full min-w-0 md:flex-1 flex justify-start md:justify-center">
- <div className="flex w-full flex-col gap-3 sm:w-auto sm:flex-row sm:items-center sm:gap-4 md:gap-6">
- <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="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 justify-end gap-1 md:pl-4">
- {canWrite && (
- <div onClick={e => e.stopPropagation()}>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <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>
- )}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button variant="ghost" size="smIcon">
- {isExpanded ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
- </Button>
- </TooltipTrigger>
- <TooltipContent>{isExpanded ? t("Collapse") : t("Expand to view conversions")}</TooltipContent>
- </Tooltip>
- </div>
- </div>
- <div className="relative">
- <div className="bg-neutral-100 dark:bg-neutral-700 h-1.5 w-full absolute bottom-0 left-0"></div>
- <div
- style={{
- width: goal.conversion_rate * 100 + "%",
- }}
- className="bg-accent-400/75 h-1.5 absolute bottom-0 left-0"
- ></div>
- </div>
-
- {/* 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>
- <SessionsList
- sessions={sessions}
- isLoading={isLoadingSessions}
- page={page}
- onPageChange={setPage}
- hasNextPage={hasNextPage}
- hasPrevPage={hasPrevPage}
- emptyMessage={t("No sessions converted to this goal in the selected time period.")}
- />
- </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>
- <AlertDialogHeader>
- <AlertDialogTitle>{t("Are you sure you want to delete this goal?")}</AlertDialogTitle>
- <AlertDialogDescription>
- {t("This action cannot be undone. This will permanently delete the goal and remove it from all reports.")}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>
- <AlertDialogAction onClick={handleDelete} variant="destructive">
- {deleteGoalMutation.isPending ? t("Deleting...") : t("Delete")}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </>
- );
-}
diff --git a/client/src/app/[site]/goals/components/GoalConversionsChart.tsx b/client/src/app/[site]/goals/components/GoalConversionsChart.tsx
new file mode 100644
index 000000000..7b748c75b
--- /dev/null
+++ b/client/src/app/[site]/goals/components/GoalConversionsChart.tsx
@@ -0,0 +1,122 @@
+"use client";
+
+import { DateTime } from "luxon";
+import { useMemo } from "react";
+import { ChartTooltip } from "@/components/charts/ChartTooltip";
+import { TimeSeriesChart, TimeSeriesChartPoint } from "@/components/charts/TimeSeriesChart";
+import { bucketsBetween, getChartTimeBounds, shiftBuckets } from "@/components/charts/timeSeriesChartUtils";
+import { formatChartDateTime } from "@/lib/dateTimeUtils";
+import { useStore, useTimezone } from "@/lib/store";
+import { TrendPoint } from "./GoalTrendBars";
+
+/** The comparison line's colour, shared with the chart's legend. */
+export const COMPARISON_COLOR = "hsl(var(--neutral-500))";
+
+type CurrentPoint = TimeSeriesChartPoint & { currentTime: DateTime };
+type PreviousPoint = TimeSeriesChartPoint & { originalTime: DateTime };
+
+/**
+ * One goal's conversions over the period, with the comparison period drawn
+ * behind it. Built the way the main chart is (MainSection/Chart): the
+ * comparison points are shifted onto this period's axis by a whole number of
+ * buckets and keep their own date for the tooltip.
+ */
+export function GoalConversionsChart({ data, previousData }: { data: TrendPoint[]; previousData?: TrendPoint[] }) {
+ const time = useStore(state => state.time);
+ const previousTime = useStore(state => state.previousTime);
+ const bucket = useStore(state => state.bucket);
+ const timezone = useTimezone();
+
+ const { current, previous, chartMin, chartMax, max, displayDashed } = useMemo(() => {
+ const { min: boundsMin, max: boundsMax } = getChartTimeBounds(time, bucket, timezone);
+ const now = DateTime.now();
+ const lowerBoundMs = boundsMin?.getTime();
+ const upperBoundMs = (boundsMax ?? now.toJSDate()).getTime();
+
+ // Points outside the selected period are a previous range still on screen
+ // while the new one loads; drawing them would stretch the axis.
+ const currentPoints: CurrentPoint[] = [];
+ for (const point of data) {
+ const timestamp = DateTime.fromSQL(point.time, { zone: timezone }).toUTC();
+ const ms = timestamp.toMillis();
+ if (timestamp > now || ms > upperBoundMs) continue;
+ if (lowerBoundMs !== undefined && ms < lowerBoundMs) continue;
+ currentPoints.push({ x: timestamp.toJSDate(), y: point.conversions, currentTime: timestamp });
+ }
+
+ const previousMin = previousTime ? getChartTimeBounds(previousTime, bucket, timezone).min : undefined;
+ const bucketShift =
+ boundsMin && previousMin
+ ? bucketsBetween(
+ DateTime.fromJSDate(previousMin, { zone: timezone }),
+ DateTime.fromJSDate(boundsMin, { zone: timezone }),
+ bucket
+ )
+ : 0;
+ const previousPoints: PreviousPoint[] = [];
+ for (const point of previousTime ? (previousData ?? []) : []) {
+ const originalTime = DateTime.fromSQL(point.time, { zone: timezone }).toUTC();
+ const ms = shiftBuckets(originalTime.setZone(timezone), bucket, bucketShift).toMillis();
+ if (ms > upperBoundMs) continue;
+ if (lowerBoundMs !== undefined && ms < lowerBoundMs) continue;
+ previousPoints.push({ x: new Date(ms), y: point.conversions, originalTime });
+ }
+
+ // The last bucket is dashed while it is still filling. The same rule as
+ // the main chart, so the two charts agree on what "still filling" means.
+ const today = now.toISODate();
+ const isExactRange = time.mode === "range" && Boolean(time.startTime && time.endTime);
+ const isMinuteBucket = bucket === "minute" || bucket === "five_minutes";
+ const isSettled =
+ time.mode === "all-time" ||
+ time.mode === "year" ||
+ isExactRange ||
+ (time.mode === "month" && time.month !== now.toFormat("yyyy-MM-01")) ||
+ (time.mode === "day" && time.day !== today) ||
+ (time.mode === "range" && time.endDate !== today) ||
+ ((time.mode === "day" || time.mode === "past-minutes") && isMinuteBucket);
+
+ return {
+ current: currentPoints,
+ previous: previousPoints,
+ chartMin: boundsMin ?? currentPoints[0]?.x,
+ chartMax: boundsMax ?? currentPoints[currentPoints.length - 1]?.x ?? now.toJSDate(),
+ max: Math.max(1, ...currentPoints.map(point => point.y), ...previousPoints.map(point => point.y)),
+ displayDashed: !isSettled && currentPoints.length >= 2,
+ };
+ }, [data, previousData, time, previousTime, bucket, timezone]);
+
+ return (
+ <TimeSeriesChart
+ current={current}
+ previous={previous}
+ max={max}
+ chartMin={chartMin}
+ chartMax={chartMax}
+ displayDashed={displayDashed}
+ previousColor={COMPARISON_COLOR}
+ renderTooltip={({ point, previousPoint, bucket: tooltipBucket }) => (
+ <ChartTooltip>
+ <div className="m-2 flex flex-col gap-1">
+ <div className="flex justify-between gap-3 text-sm">
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="h-3 w-1 shrink-0 rounded-[3px] bg-dataviz" />
+ <span className="truncate">{formatChartDateTime(point.currentTime, tooltipBucket)}</span>
+ </div>
+ <div className="shrink-0 tabular-nums">{point.y.toLocaleString()}</div>
+ </div>
+ {previousPoint && (
+ <div className="flex justify-between gap-3 text-sm text-muted-foreground">
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="h-3 w-1 shrink-0 rounded-[3px]" style={{ backgroundColor: COMPARISON_COLOR }} />
+ <span className="truncate">{formatChartDateTime(previousPoint.originalTime, tooltipBucket)}</span>
+ </div>
+ <div className="shrink-0 tabular-nums">{previousPoint.y.toLocaleString()}</div>
+ </div>
+ )}
+ </div>
+ </ChartTooltip>
+ )}
+ />
+ );
+}
diff --git a/client/src/app/[site]/goals/components/GoalEditor.tsx b/client/src/app/[site]/goals/components/GoalEditor.tsx
new file mode 100644
index 000000000..d394b3b3e
--- /dev/null
+++ b/client/src/app/[site]/goals/components/GoalEditor.tsx
@@ -0,0 +1,334 @@
+"use client";
+
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Copy, Pencil, Plus, X } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { useEffect, useId, useRef, useState } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { Goal, GoalType } from "@/api/analytics/endpoints";
+import { useAutocaptureValues } from "@/api/analytics/hooks/events/useAutocaptureValues";
+import { useCreateGoal } from "@/api/analytics/hooks/goals/useCreateGoal";
+import { useUpdateGoal } from "@/api/analytics/hooks/goals/useUpdateGoal";
+import { useMetric } from "@/api/analytics/hooks/useGetMetric";
+import { EventTrackingNotice } from "@/components/EventTrackingNotice";
+import { SegmentedControl } from "@/components/interior/segmented-control";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { InputWithSuggestions, SuggestionOption } from "@/components/ui/input-with-suggestions";
+import { toast } from "@/components/ui/sonner";
+import { isAutocaptureTargetType } from "@/lib/events";
+import { cn } from "@/lib/utils";
+import {
+ GOAL_TYPES,
+ goalDefinitionOf,
+ goalFormDefaults,
+ GoalFormMode,
+ goalFormSchema,
+ GoalFormValues,
+ PropertyFilterDraft,
+ propertyDraftsOf,
+} from "../utils/goalForm";
+import { GoalMatchPreview } from "./GoalMatchPreview";
+import { GoalTypeIcon, useGoalTypeLabels } from "./goalType";
+
+const FIELD_LABEL = "mb-1 block text-xs text-neutral-500 dark:text-neutral-400";
+const HELP_TEXT = "text-xs text-neutral-500 dark:text-neutral-400";
+
+interface GoalEditorProps {
+ siteId: number;
+ /** "create" starts empty; "edit" and "clone" start from `goal`. */
+ mode: GoalFormMode;
+ goal?: Goal;
+ /** Called after a save and on cancel: the caller closes the editor. */
+ onDone: () => void;
+ className?: string;
+}
+
+/**
+ * The goal form, inline in the ledger: a new goal at the foot of the table, an
+ * edit in place of the goal's row. Every goal type the product has is
+ * creatable here, and the line under the fields says how many sessions the
+ * definition would have counted before it is saved.
+ */
+export function GoalEditor({ siteId, mode, goal, onDone, className }: GoalEditorProps) {
+ const t = useExtracted();
+ const typeLabels = useGoalTypeLabels();
+ const fieldId = useId();
+ const containerRef = useRef<HTMLFormElement>(null);
+
+ const createGoal = useCreateGoal();
+ const updateGoal = useUpdateGoal();
+ const isSaving = createGoal.isPending || updateGoal.isPending;
+
+ const goalName = goal ? goal.name || t("Goal #{goalId}", { goalId: String(goal.goalId) }) : "";
+ const form = useForm<GoalFormValues>({
+ resolver: zodResolver(goalFormSchema),
+ defaultValues: goalFormDefaults(goal, mode, t("{name} (Copy)", { name: goalName })),
+ });
+ const [properties, setProperties] = useState<PropertyFilterDraft[]>(() => propertyDraftsOf(goal));
+
+ const values = form.watch();
+ const goalType = values.goalType;
+ const isAutocapture = isAutocaptureTargetType(goalType);
+
+ // Opened from a button that may be a screen away, or in place of the row
+ // whose menu was just used: bring the form into view and move focus to it,
+ // so the next Tab lands on its first control.
+ useEffect(() => {
+ containerRef.current?.scrollIntoView?.({ block: "nearest" });
+ containerRef.current?.focus({ preventScroll: true });
+ }, []);
+
+ // Suggestions for the pattern field, fetched only for the selected type.
+ const { data: paths } = useMetric({
+ parameter: "pathname",
+ limit: 1000,
+ useFilters: false,
+ enabled: goalType === "path",
+ });
+ const { data: events } = useMetric({
+ parameter: "event_name",
+ limit: 1000,
+ useFilters: false,
+ enabled: goalType === "event",
+ });
+ const { data: autocaptureValues } = useAutocaptureValues(goalType, isAutocapture);
+ const suggestions: SuggestionOption[] =
+ (goalType === "path" ? paths?.data : goalType === "event" ? events?.data : autocaptureValues)?.map(item => ({
+ value: item.value,
+ label: item.value,
+ count: item.count,
+ })) ?? [];
+
+ const patternField: Record<GoalType, { label: string; placeholder: string; help: string }> = {
+ path: {
+ label: t("Path pattern"),
+ placeholder: "/checkout/complete or /product/*/view",
+ help: t("Use * to match a single path segment. Use ** to match across segments."),
+ },
+ event: {
+ label: t("Event name"),
+ placeholder: t("e.g., sign_up_completed"),
+ help: "",
+ },
+ outbound: {
+ label: t("URL pattern (optional)"),
+ placeholder: "https://example.com/pricing or https://*.example.com/**",
+ help: t("Matches the destination URL of the outbound link. Leave empty to count any outbound click."),
+ },
+ button_click: {
+ label: t("Button text (optional)"),
+ placeholder: t("e.g., Sign Up"),
+ help: t("Matches the button's visible text. Leave empty to count any button click."),
+ },
+ form_submit: {
+ label: t("Form name or ID (optional)"),
+ placeholder: t("e.g., signup-form"),
+ help: t("Matches the form's name or id attribute. Leave empty to count any form submission."),
+ },
+ copy: {
+ label: t("Copied text (optional)"),
+ placeholder: t("e.g., PROMO*"),
+ help: t("Matches the text that was copied. Leave empty to count any copied text."),
+ },
+ };
+ const field = patternField[goalType];
+ const help = isAutocapture
+ ? `${field.help} ${t("Use * to match within a segment. Use ** to match anything.")}`
+ : field.help;
+
+ // Page goals match URL parameters; every other type matches event properties.
+ const propertyCopy =
+ goalType === "path"
+ ? {
+ add: t("Match a URL parameter"),
+ key: "e.g., utm_source",
+ value: "e.g., adwords",
+ keyLabel: t("URL parameter"),
+ valueLabel: t("Parameter value"),
+ }
+ : {
+ add: t("Match an event property"),
+ key: goalType === "event" ? "e.g., plan_type" : "e.g., text",
+ value: goalType === "event" ? "e.g., premium" : "e.g., Sign Up",
+ keyLabel: t("Event property"),
+ valueLabel: t("Property value"),
+ };
+
+ const patternErrors: Record<string, string> = {
+ required: goalType === "path" ? t("Enter a path pattern.") : t("Enter an event name."),
+ url: t("Enter a path (e.g., /checkout), not a full URL. The domain is already determined by your site."),
+ too_long: t("The pattern is too long."),
+ };
+ const patternError = form.formState.errors.pattern?.message;
+
+ const heading =
+ mode === "edit"
+ ? { icon: <Pencil />, label: t("Edit goal") }
+ : mode === "clone"
+ ? { icon: <Copy />, label: t("Clone goal") }
+ : { icon: <Plus />, label: t("New goal") };
+
+ const onSubmit = async (submitted: GoalFormValues) => {
+ const definition = goalDefinitionOf(submitted, properties);
+ if (!definition) return;
+
+ try {
+ if (mode === "edit" && goal) {
+ await updateGoal.mutateAsync({ goalId: goal.goalId, siteId, name: submitted.name?.trim(), ...definition });
+ } else {
+ await createGoal.mutateAsync({ siteId, name: submitted.name?.trim(), ...definition });
+ }
+ onDone();
+ } catch (error) {
+ console.error("Error saving goal:", error);
+ toast.error(error instanceof Error ? error.message : t("Failed to save goal"));
+ }
+ };
+
+ return (
+ <form
+ ref={containerRef}
+ onSubmit={form.handleSubmit(onSubmit)}
+ className={cn("space-y-3 px-3 py-3 focus:outline-none", className)}
+ aria-label={heading.label}
+ tabIndex={-1}
+ >
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ <div className="flex items-center gap-2 text-sm font-medium [&_svg]:h-4 [&_svg]:w-4 [&_svg]:text-neutral-500 dark:[&_svg]:text-neutral-400">
+ {heading.icon}
+ {heading.label}
+ </div>
+ <Controller
+ control={form.control}
+ name="goalType"
+ render={({ field: typeField }) => (
+ <SegmentedControl<GoalType>
+ size="sm"
+ aria-label={t("Goal type")}
+ value={typeField.value}
+ onValueChange={next => {
+ // A URL parameter and an event property are different things:
+ // clear the rows instead of silently reinterpreting them.
+ setProperties([]);
+ // What was typed for one type (a path) is not a value for another (an event name).
+ form.setValue("pattern", "");
+ form.clearErrors("pattern");
+ typeField.onChange(next);
+ }}
+ options={GOAL_TYPES.map(type => ({
+ value: type,
+ ariaLabel: typeLabels[type],
+ label: (
+ <>
+ <GoalTypeIcon type={type} className="h-3.5 w-3.5 text-current dark:text-current" />
+ <span className="hidden md:inline">{typeLabels[type]}</span>
+ </>
+ ),
+ }))}
+ />
+ )}
+ />
+ {help && <p className={cn(HELP_TEXT, "hidden min-w-0 flex-1 text-right xl:block")}>{help}</p>}
+ </div>
+
+ <div className="flex flex-wrap items-end gap-2">
+ <div className="w-full sm:w-72">
+ <label htmlFor={`${fieldId}-pattern`} className={FIELD_LABEL}>
+ {field.label}
+ </label>
+ <Controller
+ control={form.control}
+ name="pattern"
+ render={({ field: patternInput }) => (
+ <InputWithSuggestions
+ id={`${fieldId}-pattern`}
+ suggestions={suggestions}
+ placeholder={field.placeholder}
+ aria-invalid={!!patternError}
+ {...patternInput}
+ />
+ )}
+ />
+ </div>
+ <div className="w-full sm:w-60">
+ <label htmlFor={`${fieldId}-name`} className={FIELD_LABEL}>
+ {t("Name (optional)")}
+ </label>
+ <Input
+ id={`${fieldId}-name`}
+ placeholder={t("e.g., Sign up completion")}
+ autoComplete="off"
+ {...form.register("name")}
+ />
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ className="font-normal text-neutral-600 dark:text-neutral-300"
+ onClick={() => setProperties([...properties, { key: "", value: "" }])}
+ >
+ <Plus />
+ {propertyCopy.add}
+ </Button>
+ <div className="flex w-full items-center justify-end gap-2 sm:ml-auto sm:w-auto">
+ <Button type="button" variant="outline" onClick={onDone}>
+ {t("Cancel")}
+ </Button>
+ <Button type="submit" variant="accent" loading={isSaving} loadingLabel={t("Saving...")}>
+ {mode === "edit" ? t("Save changes") : t("Create goal")}
+ </Button>
+ </div>
+ </div>
+
+ {patternError && (
+ <p className="text-xs text-red-600 dark:text-red-400" role="alert">
+ {patternErrors[patternError] ?? patternError}
+ </p>
+ )}
+
+ {properties.length > 0 && (
+ <div className="space-y-2">
+ {properties.map((property, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <Input
+ className="w-full sm:w-72"
+ aria-label={propertyCopy.keyLabel}
+ placeholder={propertyCopy.key}
+ autoComplete="off"
+ value={property.key}
+ onChange={event =>
+ setProperties(properties.map((p, i) => (i === index ? { ...p, key: event.target.value } : p)))
+ }
+ />
+ <Input
+ className="w-full sm:w-60"
+ aria-label={propertyCopy.valueLabel}
+ placeholder={propertyCopy.value}
+ autoComplete="off"
+ value={property.value}
+ onChange={event =>
+ setProperties(properties.map((p, i) => (i === index ? { ...p, value: event.target.value } : p)))
+ }
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="smIcon"
+ className="shrink-0 text-neutral-500 dark:text-neutral-400"
+ aria-label={t("Remove")}
+ onClick={() => setProperties(properties.filter((_, i) => i !== index))}
+ >
+ <X />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {help && <p className={cn(HELP_TEXT, "xl:hidden")}>{help}</p>}
+ <EventTrackingNotice type={goalType} />
+ <GoalMatchPreview definition={goalDefinitionOf(values, properties)} />
+ </form>
+ );
+}
diff --git a/client/src/app/[site]/goals/components/GoalExpanded.tsx b/client/src/app/[site]/goals/components/GoalExpanded.tsx
new file mode 100644
index 000000000..0b2d756cd
--- /dev/null
+++ b/client/src/app/[site]/goals/components/GoalExpanded.tsx
@@ -0,0 +1,303 @@
+"use client";
+
+import { ArrowRight, ChevronRight, Funnel, MousePointerClick, Video } from "lucide-react";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { ReactNode, useState } from "react";
+import { GetSessionsResponse } from "@/api/analytics/endpoints";
+import { useGetEventNames } from "@/api/analytics/hooks/events/useGetEventNames";
+import { useGetFunnels } from "@/api/analytics/hooks/funnels/useGetFunnels";
+import { useGetGoalSessions } from "@/api/analytics/hooks/goals/useGetGoalSessions";
+import { useGetGoalTimeSeries } from "@/api/analytics/hooks/goals/useGetGoalTimeSeries";
+import { Avatar } from "@/components/Avatar";
+import { ChannelIcon, extractDomain } from "@/components/Channel";
+import { describeComparisonWindow } from "@/components/DateSelector/rangeFields";
+import { Pagination } from "@/components/pagination";
+import { ReplayDrawer } from "@/components/Sessions/ReplayDrawer";
+import { ChartLegend } from "@/components/site/ChartLegend";
+import { PivotActions } from "@/components/site/PivotActions";
+import { CountryFlagTooltipIcon } from "@/components/TooltipIcons/TooltipIcons";
+import { Button } from "@/components/ui/button";
+import { Skeleton } from "@/components/ui/skeleton";
+import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
+import { usePivotHref } from "@/hooks/usePivotHref";
+import { formatShortDuration } from "@/lib/dateTimeUtils";
+import { useStore, useTimezone } from "@/lib/store";
+import { getUserDisplayName } from "@/lib/utils";
+import { funnelRefs, goalPivotFilters, LedgerRow } from "../utils/goalLedger";
+import { COMPARISON_COLOR, GoalConversionsChart } from "./GoalConversionsChart";
+import { TrendPoint } from "./GoalTrendBars";
+
+const SESSIONS_PER_PAGE = 5;
+const MUTED = "text-neutral-500 dark:text-neutral-400";
+
+/** A chip that leads to another page's object: a funnel that has this goal as a step, the goal's event. */
+function CrossLink({ href, icon, label, sub }: { href: string; icon: ReactNode; label: string; sub?: string }) {
+ return (
+ <Link
+ href={href}
+ prefetch={false}
+ className="inline-flex h-6 max-w-full items-center gap-1.5 whitespace-nowrap rounded-md border border-neutral-150 px-2 text-xs text-neutral-700 transition-colors hover:bg-neutral-100 dark:border-neutral-800 dark:text-neutral-200 dark:hover:bg-neutral-800/80 [&_svg]:h-3.5 [&_svg]:w-3.5 [&_svg]:shrink-0 [&_svg]:text-neutral-500 dark:[&_svg]:text-neutral-400"
+ >
+ {icon}
+ <span className="truncate font-medium">{label}</span>
+ {sub && <span className={MUTED}>{sub}</span>}
+ </Link>
+ );
+}
+
+function ConvertedSession({ session, basePath }: { session: GetSessionsResponse[number]; basePath: string }) {
+ const t = useExtracted();
+ const timezone = useTimezone();
+ const { hour12, formatDateTime } = useDateTimeFormat();
+ const [replayOpen, setReplayOpen] = useState(false);
+
+ const start = DateTime.fromSQL(session.session_start, { zone: "utc" });
+ const end = DateTime.fromSQL(session.session_end, { zone: "utc" });
+ const userId = session.identified_user_id || session.user_id;
+ const pageviews = Number(session.pageviews) || 0;
+
+ return (
+ <li className="flex items-center gap-2.5 border-b border-neutral-100 px-3 py-2 last:border-b-0 dark:border-neutral-800">
+ <Avatar size={24} id={session.user_id} lastActiveTime={end} />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <Link
+ href={`${basePath}/user/${encodeURIComponent(userId)}`}
+ className="truncate text-sm font-medium text-neutral-900 hover:underline dark:text-neutral-100"
+ >
+ {getUserDisplayName(session)}
+ </Link>
+ {session.country && (
+ <CountryFlagTooltipIcon country={session.country} city={session.city} region={session.region} />
+ )}
+ </div>
+ <div className={`flex min-w-0 items-center gap-1 text-xs ${MUTED}`}>
+ <ChannelIcon channel={session.channel} className="h-3 w-3 shrink-0" />
+ <span className="max-w-[40%] shrink-0 truncate">{extractDomain(session.referrer) ?? session.channel}</span>
+ <span aria-hidden="true">·</span>
+ <span className="truncate">{session.entry_page || "-"}</span>
+ <ChevronRight className="h-3 w-3 shrink-0" aria-hidden="true" />
+ <span className="truncate">{session.exit_page || "-"}</span>
+ </div>
+ </div>
+ <div className="shrink-0 text-right text-xs tabular-nums">
+ <div className="text-neutral-700 dark:text-neutral-200">
+ {formatDateTime(start, {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ hour12,
+ timeZone: timezone,
+ })}
+ </div>
+ <div className={MUTED}>
+ {formatShortDuration(Math.max(0, Math.floor(end.diff(start).as("seconds"))))} ·{" "}
+ {t("{count, plural, one {# page} other {# pages}}", { count: pageviews })}
+ </div>
+ </div>
+ {session.has_replay === 1 && (
+ <>
+ <Button
+ type="button"
+ variant="ghost"
+ size="smIcon"
+ className="shrink-0 text-neutral-600 dark:text-neutral-300"
+ aria-label={t("Watch Session Replay")}
+ onClick={() => setReplayOpen(true)}
+ >
+ <Video />
+ </Button>
+ <ReplayDrawer sessionId={session.session_id} open={replayOpen} onOpenChange={setReplayOpen} />
+ </>
+ )}
+ </li>
+ );
+}
+
+function ConvertedSessions({ row, siteId, sessionsHref }: { row: LedgerRow; siteId: number; sessionsHref?: string }) {
+ const t = useExtracted();
+ const time = useStore(state => state.time);
+ const site = useStore(state => state.site);
+ const privateKey = useStore(state => state.privateKey);
+ const [page, setPage] = useState(1);
+
+ // One row past the page says whether there is a next page without a count query.
+ const { data, isLoading, isError } = useGetGoalSessions({
+ goalId: row.goal.goalId,
+ siteId,
+ time,
+ page,
+ limit: SESSIONS_PER_PAGE + 1,
+ enabled: true,
+ });
+ const sessions = (data ?? []).slice(0, SESSIONS_PER_PAGE);
+ const hasNextPage = (data ?? []).length > SESSIONS_PER_PAGE;
+ const basePath = privateKey ? `/${site}/${privateKey}` : `/${site}`;
+
+ return (
+ <div className="flex min-w-0 flex-col lg:border-l lg:border-neutral-100 lg:pl-2 lg:dark:border-neutral-800">
+ <div className="flex items-center justify-between gap-3 px-3 pb-2">
+ <div className="text-sm font-medium">
+ {t("Converted sessions")}
+ <span className={`ml-2 font-normal tabular-nums ${MUTED}`}>{row.conversions.toLocaleString()}</span>
+ </div>
+ {sessionsHref && (
+ <Link
+ href={sessionsHref}
+ prefetch={false}
+ className="inline-flex shrink-0 items-center gap-1 text-xs text-neutral-700 hover:underline dark:text-neutral-200"
+ >
+ {t("Open in Sessions")}
+ <ArrowRight className="h-3 w-3" aria-hidden="true" />
+ </Link>
+ )}
+ </div>
+
+ {isLoading ? (
+ <div className="space-y-2 px-3 py-1">
+ {Array.from({ length: 4 }, (_, index) => (
+ <Skeleton key={index} className="h-9 w-full rounded" />
+ ))}
+ </div>
+ ) : isError ? (
+ <p className={`px-3 py-6 text-center text-sm ${MUTED}`}>{t("The converted sessions could not be loaded.")}</p>
+ ) : sessions.length === 0 ? (
+ <p className={`px-3 py-6 text-center text-sm ${MUTED}`}>
+ {t("No sessions converted to this goal in the selected time period.")}
+ </p>
+ ) : (
+ <ul>
+ {sessions.map(session => (
+ <ConvertedSession key={session.session_id} session={session} basePath={basePath} />
+ ))}
+ </ul>
+ )}
+
+ {(page > 1 || hasNextPage) && (
+ <Pagination
+ className="mt-2 px-3"
+ page={page}
+ onPageChange={setPage}
+ hasPreviousPage={page > 1}
+ hasNextPage={hasNextPage}
+ />
+ )}
+ </div>
+ );
+}
+
+interface GoalExpandedProps {
+ row: LedgerRow;
+ siteId: number;
+ /** This period's series for the goal: the one the row's small bars already drew. */
+ timeSeries?: TrendPoint[];
+ isLoadingTimeSeries: boolean;
+ /** "Conversions per day", from the page's interval. */
+ chartTitle: string;
+}
+
+/**
+ * What opens under a ledger row: where else the goal's target is used, the
+ * people behind the number, the goal over time against the comparison period,
+ * and the sessions that converted.
+ */
+export function GoalExpanded({ row, siteId, timeSeries, isLoadingTimeSeries, chartTitle }: GoalExpandedProps) {
+ const t = useExtracted();
+ const { goal } = row;
+ const time = useStore(state => state.time);
+ const previousTime = useStore(state => state.previousTime);
+ const timezone = useTimezone();
+ const pivotHref = usePivotHref();
+
+ const { data: funnels } = useGetFunnels(siteId);
+ const refs = funnelRefs(goal, funnels ?? []);
+
+ const eventName = goal.goalType === "event" ? goal.config.eventName : undefined;
+ const { data: eventNames } = useGetEventNames();
+ const eventCount = eventName ? eventNames?.find(event => event.eventName === eventName)?.count : undefined;
+
+ const { data: previousSeries } = useGetGoalTimeSeries({ goalIds: [goal.goalId], periodTime: "previous" });
+
+ const pivotFilters = goalPivotFilters(goal);
+ // usePivotHref only builds Sessions, Users and Replay links. The funnels and
+ // events pages read the same query string, so their links are the Sessions
+ // link with the last path segment swapped.
+ const linkTo = (route: string, href: string) => href.replace(/\/sessions(?=\?|$)/, `/${route}`);
+ const funnelsHref = linkTo("funnels", pivotHref("sessions"));
+ const eventHref = eventName
+ ? linkTo("events", pivotHref("sessions", [{ parameter: "event_name", type: "equals", value: [eventName] }]))
+ : undefined;
+
+ const hasCrossLinks = refs.length > 0 || !!eventHref;
+ const currentWindow = describeComparisonWindow(time, time, timezone);
+ const comparisonWindow = describeComparisonWindow(previousTime, time, timezone);
+
+ return (
+ <div className="bg-neutral-50 px-3 pb-4 pt-1 dark:bg-neutral-800/30 md:px-4">
+ {(hasCrossLinks || pivotFilters) && (
+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2 pb-3">
+ <div className="flex min-w-0 flex-wrap items-center gap-1.5">
+ {hasCrossLinks && <span className={`mr-1 text-xs ${MUTED}`}>{t("Also in")}</span>}
+ {refs.map(ref => (
+ <CrossLink
+ key={ref.funnel.id}
+ href={funnelsHref}
+ icon={<Funnel />}
+ label={ref.funnel.name}
+ sub={t("step {step} of {total}", { step: String(ref.step), total: String(ref.of) })}
+ />
+ ))}
+ {eventHref && eventName && (
+ <CrossLink
+ href={eventHref}
+ icon={<MousePointerClick />}
+ label={eventName}
+ sub={
+ eventCount === undefined
+ ? undefined
+ : t("{count, plural, one {# event} other {# events}}", { count: eventCount })
+ }
+ />
+ )}
+ </div>
+ {pivotFilters && (
+ <PivotActions filters={pivotFilters} actions={["sessions", "users", "replays", "segment"]} />
+ )}
+ </div>
+ )}
+
+ <div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,470px)]">
+ <div className="flex min-w-0 flex-col">
+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1 pb-2">
+ <div className="text-sm font-medium">{chartTitle}</div>
+ <ChartLegend
+ items={[
+ { id: "current", label: currentWindow ?? t("This period"), color: "hsl(var(--dataviz))" },
+ ...(previousTime
+ ? [{ id: "previous", label: comparisonWindow ?? t("Comparison period"), color: COMPARISON_COLOR }]
+ : []),
+ ]}
+ />
+ </div>
+ {isLoadingTimeSeries ? (
+ <Skeleton className="min-h-[214px] w-full flex-1 rounded-md" />
+ ) : (
+ // As tall as the session list beside it, and never shorter than a readable chart.
+ <div className="min-h-[214px] w-full flex-1">
+ <GoalConversionsChart data={timeSeries ?? []} previousData={previousSeries} />
+ </div>
+ )}
+ </div>
+
+ <ConvertedSessions
+ row={row}
+ siteId={siteId}
+ sessionsHref={pivotFilters ? pivotHref("sessions", pivotFilters) : undefined}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/goals/components/GoalFormModal.tsx b/client/src/app/[site]/goals/components/GoalFormModal.tsx
deleted file mode 100644
index eab1cc128..000000000
--- a/client/src/app/[site]/goals/components/GoalFormModal.tsx
+++ /dev/null
@@ -1,616 +0,0 @@
-"use client";
-
-import { useExtracted } from "next-intl";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { useEffect, useState } from "react";
-import { useForm } from "react-hook-form";
-import * as z from "zod";
-import { useCreateGoal } from "../../../../api/analytics/hooks/goals/useCreateGoal";
-import { Goal, GoalType } from "../../../../api/analytics/endpoints";
-import { useUpdateGoal } from "../../../../api/analytics/hooks/goals/useUpdateGoal";
-import { useAutocaptureValues } from "../../../../api/analytics/hooks/events/useAutocaptureValues";
-import { useMetric } from "../../../../api/analytics/hooks/useGetMetric";
-import { EventTypeIcon } from "../../../../components/EventIcons";
-import { EventTrackingNotice } from "../../../../components/EventTrackingNotice";
-import {
- AUTOCAPTURE_TARGET_TYPES,
- AutocaptureTargetType,
- isAutocaptureTargetType,
- targetTypeToEventType,
-} from "../../../../lib/events";
-import { Button } from "../../../../components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "../../../../components/ui/dialog";
-import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../../../../components/ui/form";
-import { Input } from "../../../../components/ui/input";
-import { InputWithSuggestions, SuggestionOption } from "../../../../components/ui/input-with-suggestions";
-import { Label } from "../../../../components/ui/label";
-import { toast } from "../../../../components/ui/sonner";
-import { Switch } from "../../../../components/ui/switch";
-import { cn } from "../../../../lib/utils";
-import { Plus, X } from "lucide-react";
-
-// Define form schema
-const formSchema = z
- .object({
- name: z.string().optional(),
- goalType: z.enum(["path", "event", ...AUTOCAPTURE_TARGET_TYPES]),
- config: z.object({
- pathPattern: z.string().optional(),
- eventName: z.string().optional(),
- valuePattern: z.string().max(512).optional(),
- eventPropertyKey: z.string().optional(),
- eventPropertyValue: z.string().optional(),
- propertyFilters: z
- .array(
- z.object({
- key: z.string(),
- value: z.union([z.string(), z.number(), z.boolean()]),
- })
- )
- .optional(),
- }),
- })
- .refine(
- data => {
- if (data.goalType === "path") {
- return !!data.config.pathPattern;
- } else if (data.goalType === "event") {
- return !!data.config.eventName;
- }
- // Autocapture goals match any event of their type when the pattern is empty
- return true;
- },
- {
- message: "Configuration is required based on goal type",
- path: ["config"],
- }
- )
- .refine(
- data => {
- if (data.goalType === "path" && data.config.pathPattern) {
- return !/^(https?:\/\/|www\.|[a-zA-Z0-9-]+\.[a-zA-Z]{2,}\/)/i.test(data.config.pathPattern);
- }
- return true;
- },
- {
- message: "Enter a path (e.g., /checkout), not a full URL. The domain is already determined by your site.",
- path: ["config", "pathPattern"],
- }
- );
-
-type FormValues = z.infer<typeof formSchema>;
-
-type PropertyFilterDraft = { key: string; value: string };
-
-interface PropertyFilterSectionProps {
- id: string;
- toggleLabel: string;
- keyPlaceholder: string;
- valuePlaceholder: string;
- addButtonLabel: string;
- useProperties: boolean;
- setUseProperties: (enabled: boolean) => void;
- propertyFilters: PropertyFilterDraft[];
- setPropertyFilters: (filters: PropertyFilterDraft[]) => void;
-}
-
-function PropertyFilterSection({
- id,
- toggleLabel,
- keyPlaceholder,
- valuePlaceholder,
- addButtonLabel,
- useProperties,
- setUseProperties,
- propertyFilters,
- setPropertyFilters,
-}: PropertyFilterSectionProps) {
- return (
- <div className="mt-4">
- <div className="flex items-center space-x-2 mb-4">
- <Switch id={id} checked={useProperties} onCheckedChange={setUseProperties} />
- <Label htmlFor={id}>{toggleLabel}</Label>
- </div>
-
- {useProperties && (
- <div className="space-y-3">
- {propertyFilters.map((filter, index) => (
- <div key={index} className="flex gap-2 items-start">
- <div className="flex-1 grid grid-cols-2 gap-2">
- <Input
- placeholder={keyPlaceholder}
- value={filter.key}
- onChange={e => {
- const newFilters = [...propertyFilters];
- newFilters[index] = { ...newFilters[index], key: e.target.value };
- setPropertyFilters(newFilters);
- }}
- />
- <Input
- placeholder={valuePlaceholder}
- value={filter.value}
- onChange={e => {
- const newFilters = [...propertyFilters];
- newFilters[index] = { ...newFilters[index], value: e.target.value };
- setPropertyFilters(newFilters);
- }}
- />
- </div>
- {propertyFilters.length > 1 && (
- <Button
- type="button"
- variant="ghost"
- size="icon"
- onClick={() => setPropertyFilters(propertyFilters.filter((_, i) => i !== index))}
- >
- <X className="h-4 w-4" />
- </Button>
- )}
- </div>
- ))}
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => setPropertyFilters([...propertyFilters, { key: "", value: "" }])}
- className="w-full"
- >
- <Plus className="h-4 w-4" />
- {addButtonLabel}
- </Button>
- </div>
- )}
- </div>
- );
-}
-
-interface GoalFormModalProps {
- siteId: number;
- goal?: Goal; // Optional goal for editing mode
- trigger?: React.ReactNode;
- isCloneMode?: boolean; // Optional clone mode flag
- open?: boolean;
- onOpenChange?: (open: boolean) => void;
-}
-
-export default function GoalFormModal({
- siteId,
- goal,
- trigger,
- isCloneMode = false,
- open,
- onOpenChange,
-}: GoalFormModalProps) {
- const t = useExtracted();
- const [internalOpen, setInternalOpen] = useState(false);
- const isOpen = open ?? internalOpen;
- const setIsOpen = (nextOpen: boolean) => {
- if (open === undefined) {
- setInternalOpen(nextOpen);
- }
- onOpenChange?.(nextOpen);
- };
-
- const goalTypeOptions: { value: GoalType; label: string }[] = [
- { value: "path", label: t("Page") },
- { value: "event", label: t("Event") },
- { value: "outbound", label: t("Outbound Link") },
- { value: "button_click", label: t("Button Click") },
- { value: "form_submit", label: t("Form Submit") },
- { value: "copy", label: t("Copy") },
- ];
-
- // Field copy for autocapture goal types; the pattern is optional and
- // matches the type's primary property with * and ** wildcards
- const autocaptureFieldMeta: Record<AutocaptureTargetType, { label: string; placeholder: string; help: string }> = {
- outbound: {
- label: t("URL Pattern (optional)"),
- placeholder: "https://example.com/pricing or https://*.example.com/**",
- help: t("Matches the destination URL of the outbound link. Leave empty to count any outbound click."),
- },
- button_click: {
- label: t("Button Text (optional)"),
- placeholder: t("e.g., Sign Up"),
- help: t("Matches the button's visible text. Leave empty to count any button click."),
- },
- form_submit: {
- label: t("Form Name or ID (optional)"),
- placeholder: t("e.g., signup-form"),
- help: t("Matches the form's name or id attribute. Leave empty to count any form submission."),
- },
- copy: {
- label: t("Copied Text (optional)"),
- placeholder: t("e.g., PROMO*"),
- help: t("Matches the text that was copied. Leave empty to count any copied text."),
- },
- };
-
- // Copy for the property-filter toggle/inputs, per goal type. The 4 autocapture
- // types all filter on event props, so they share one entry.
- const autocapturePropertyFilterMeta = {
- id: "use-properties-autocapture",
- toggleLabel: t("Match specific event properties"),
- keyPlaceholder: "e.g., text",
- valuePlaceholder: "e.g., Sign Up",
- addButtonLabel: t("Add Another Property"),
- };
- const propertyFilterMeta: Record<GoalType, typeof autocapturePropertyFilterMeta> = {
- path: {
- id: "use-properties",
- toggleLabel: t("Match specific URL parameters"),
- keyPlaceholder: "e.g., utm_source",
- valuePlaceholder: "e.g., adwords",
- addButtonLabel: t("Add Another Parameter"),
- },
- event: {
- id: "use-properties-event",
- toggleLabel: t("Match specific event properties"),
- keyPlaceholder: "e.g., plan_type",
- valuePlaceholder: "e.g., premium",
- addButtonLabel: t("Add Another Property"),
- },
- outbound: autocapturePropertyFilterMeta,
- button_click: autocapturePropertyFilterMeta,
- form_submit: autocapturePropertyFilterMeta,
- copy: autocapturePropertyFilterMeta,
- };
-
- // Initialize useProperties based on either new propertyFilters or legacy properties
- const hasProperties = !!(
- goal?.config.propertyFilters?.length ||
- (goal?.config.eventPropertyKey && goal?.config.eventPropertyValue !== undefined)
- );
- const [useProperties, setUseProperties] = useState(hasProperties);
-
- // State for managing multiple property filters (store as strings in UI)
- const [propertyFilters, setPropertyFilters] = useState<PropertyFilterDraft[]>(
- goal?.config.propertyFilters?.map(f => ({ key: f.key, value: String(f.value) })) ||
- (goal?.config.eventPropertyKey && goal?.config.eventPropertyValue !== undefined
- ? [{ key: goal.config.eventPropertyKey, value: String(goal.config.eventPropertyValue) }]
- : [{ key: "", value: "" }])
- );
-
- // Fetch suggestions for paths and events
- const { data: pathsData } = useMetric({
- parameter: "pathname",
- limit: 1000,
- useFilters: false,
- });
-
- const { data: eventsData } = useMetric({
- parameter: "event_name",
- limit: 1000,
- useFilters: false,
- });
-
- // Transform data into SuggestionOption format
- const pathSuggestions: SuggestionOption[] =
- pathsData?.data?.map(item => ({
- value: item.value,
- label: item.value,
- count: item.count,
- })) || [];
-
- const eventSuggestions: SuggestionOption[] =
- eventsData?.data?.map(item => ({
- value: item.value,
- label: item.value,
- count: item.count,
- })) || [];
-
- // Reinitialize useProperties when goal changes or modal opens
- useEffect(() => {
- if (isOpen && goal) {
- // Update useProperties based on either new propertyFilters or legacy properties
- const hasFilters = !!(
- goal.config.propertyFilters?.length ||
- (goal.config.eventPropertyKey && goal.config.eventPropertyValue !== undefined)
- );
- setUseProperties(hasFilters);
-
- // Update propertyFilters state
- const filters =
- goal.config.propertyFilters?.map(f => ({ key: f.key, value: String(f.value) })) ||
- (goal.config.eventPropertyKey && goal.config.eventPropertyValue !== undefined
- ? [{ key: goal.config.eventPropertyKey, value: String(goal.config.eventPropertyValue) }]
- : [{ key: "", value: "" }]);
- setPropertyFilters(filters);
- }
- }, [isOpen, goal]);
-
- const onClose = () => {
- setIsOpen(false);
- };
-
- const isEditMode = !!goal && !isCloneMode;
- const createGoal = useCreateGoal();
- const updateGoal = useUpdateGoal();
-
- // Initialize form with default values or existing goal
- const form = useForm<FormValues>({
- resolver: zodResolver(formSchema),
- defaultValues:
- (isEditMode || isCloneMode) && goal
- ? {
- name: isCloneMode ? `${goal.name || `Goal #${goal.goalId}`} (Copy)` : goal.name || "",
- goalType: goal.goalType,
- config: {
- pathPattern: goal.config.pathPattern || "",
- eventName: goal.config.eventName || "",
- valuePattern: goal.config.valuePattern || "",
- eventPropertyKey: goal.config.eventPropertyKey || "",
- eventPropertyValue:
- goal.config.eventPropertyValue !== undefined ? String(goal.config.eventPropertyValue) : "",
- },
- }
- : {
- name: "",
- goalType: "path",
- config: {
- pathPattern: "",
- eventName: "",
- valuePattern: "",
- eventPropertyKey: "",
- eventPropertyValue: "",
- },
- },
- });
-
- const goalType = form.watch("goalType");
-
- // Suggestions for autocapture pattern values (urls, button texts, form names, copied texts)
- const { data: autocaptureValuesData } = useAutocaptureValues(goalType, isOpen && isAutocaptureTargetType(goalType));
-
- const autocaptureSuggestions: SuggestionOption[] =
- autocaptureValuesData?.map(item => ({
- value: item.value,
- label: item.value,
- count: item.count,
- })) || [];
-
- // Handle form submission
- const onSubmit = async (values: FormValues) => {
- try {
- // Clean up the config based on goal type
- if (values.goalType === "path") {
- values.config.eventName = undefined;
- values.config.valuePattern = undefined;
- } else if (values.goalType === "event") {
- values.config.pathPattern = undefined;
- values.config.valuePattern = undefined;
- } else {
- values.config.pathPattern = undefined;
- values.config.eventName = undefined;
- values.config.valuePattern = values.config.valuePattern?.trim() || undefined;
- }
-
- // Set propertyFilters if using properties
- if (useProperties) {
- const validFilters = propertyFilters.filter(f => f.key && f.value);
- values.config.propertyFilters = validFilters.length > 0 ? validFilters : undefined;
- } else {
- values.config.propertyFilters = undefined;
- }
- // Clear legacy fields
- values.config.eventPropertyKey = undefined;
- values.config.eventPropertyValue = undefined;
-
- if (isEditMode) {
- await updateGoal.mutateAsync({
- goalId: goal.goalId,
- siteId,
- name: values.name,
- goalType: values.goalType,
- config: values.config,
- });
- } else {
- await createGoal.mutateAsync({
- siteId,
- name: values.name,
- goalType: values.goalType,
- config: values.config,
- });
- }
-
- // Reset form and state after successful submission
- form.reset();
- setUseProperties(false);
-
- setIsOpen(false);
- } catch (error) {
- console.error("Error saving goal:", error);
- toast.error(error instanceof Error ? error.message : t("Failed to save goal"));
- }
- };
-
- return (
- <Dialog
- open={isOpen}
- onOpenChange={open => {
- setIsOpen(open);
- if (!open) {
- form.reset();
- setUseProperties(false);
- setPropertyFilters([{ key: "", value: "" }]);
- }
- }}
- >
- {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>
- <DialogDescription>
- {isEditMode
- ? t("Update the goal details below.")
- : isCloneMode
- ? t("Clone this goal with the same configuration.")
- : t("Set up a new conversion goal to track specific user actions.")}
- </DialogDescription>
- </DialogHeader>
-
- <Form {...form}>
- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>{t("Goal Name (optional)")}</FormLabel>
- <FormControl>
- <Input placeholder={t("e.g., Sign Up Completion")} autoComplete="off" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="goalType"
- render={({ field }) => (
- <FormItem>
- <FormLabel>{t("Goal Type")}</FormLabel>
- <FormControl>
- <div className="grid grid-cols-2 gap-2 mt-1">
- {goalTypeOptions.map(option => (
- <Button
- key={option.value}
- type="button"
- variant={field.value === option.value ? "default" : "outline"}
- className={cn(
- "flex items-center justify-start gap-2",
- field.value === option.value && "border-blue-500"
- )}
- onClick={() => {
- // Property filters are interpreted differently per goal type
- // (URL params vs. event props), so clear them on type change
- // instead of silently reinterpreting them.
- if (field.value !== option.value) {
- setUseProperties(false);
- setPropertyFilters([{ key: "", value: "" }]);
- }
- field.onChange(option.value);
- }}
- >
- <EventTypeIcon type={targetTypeToEventType(option.value)} />
- <span>{option.label}</span>
- </Button>
- ))}
- </div>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
- {goalType === "path" && (
- <FormField
- control={form.control}
- name="config.pathPattern"
- render={({ field }) => (
- <FormItem>
- <FormLabel>{t("Path Pattern")}</FormLabel>
- <FormControl>
- <InputWithSuggestions
- suggestions={pathSuggestions}
- placeholder="/checkout/complete or /product/*/view"
- {...field}
- />
- </FormControl>
- <FormMessage />
- <div className="text-xs text-neutral-500 mt-1">
- {t("Use * to match a single path segment. Use ** to match across segments.")}
- </div>
- </FormItem>
- )}
- />
- )}
-
- {goalType === "event" && (
- <FormField
- control={form.control}
- name="config.eventName"
- render={({ field }) => (
- <FormItem>
- <FormLabel>{t("Event Name")}</FormLabel>
- <FormControl>
- <InputWithSuggestions
- suggestions={eventSuggestions}
- placeholder={t("e.g., sign_up_completed")}
- {...field}
- />
- </FormControl>
- <FormMessage />
- <EventTrackingNotice type="event" className="mt-1" />
- </FormItem>
- )}
- />
- )}
-
- {isAutocaptureTargetType(goalType) && (
- <FormField
- control={form.control}
- name="config.valuePattern"
- render={({ field }) => (
- <FormItem>
- <FormLabel>{autocaptureFieldMeta[goalType].label}</FormLabel>
- <FormControl>
- <InputWithSuggestions
- suggestions={autocaptureSuggestions}
- placeholder={autocaptureFieldMeta[goalType].placeholder}
- {...field}
- />
- </FormControl>
- <FormMessage />
- <div className="text-xs text-neutral-500 mt-1">
- {autocaptureFieldMeta[goalType].help}{" "}
- {t("Use * to match within a segment. Use ** to match anything.")}
- </div>
- <EventTrackingNotice type={goalType} className="mt-1" />
- </FormItem>
- )}
- />
- )}
-
- <PropertyFilterSection
- id={propertyFilterMeta[goalType].id}
- toggleLabel={propertyFilterMeta[goalType].toggleLabel}
- keyPlaceholder={propertyFilterMeta[goalType].keyPlaceholder}
- valuePlaceholder={propertyFilterMeta[goalType].valuePlaceholder}
- addButtonLabel={propertyFilterMeta[goalType].addButtonLabel}
- useProperties={useProperties}
- setUseProperties={setUseProperties}
- propertyFilters={propertyFilters}
- setPropertyFilters={setPropertyFilters}
- />
-
- <div className="flex justify-end space-x-2">
- <Button variant="outline" type="button" onClick={onClose}>
- {t("Cancel")}
- </Button>
- <Button
- type="submit"
- variant="success"
- loading={createGoal.isPending || updateGoal.isPending}
- loadingLabel={t("Saving...")}
- >
- {isEditMode ? t("Update") : t("Create")}
- </Button>
- </div>
- </form>
- </Form>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/client/src/app/[site]/goals/components/GoalMatchPreview.tsx b/client/src/app/[site]/goals/components/GoalMatchPreview.tsx
new file mode 100644
index 000000000..010b5b57c
--- /dev/null
+++ b/client/src/app/[site]/goals/components/GoalMatchPreview.tsx
@@ -0,0 +1,80 @@
+"use client";
+
+import { useDebounce } from "@uidotdev/usehooks";
+import { useExtracted } from "next-intl";
+import { useMemo } from "react";
+import { GoalDefinition } from "@/api/analytics/endpoints";
+import { useGetGoalPreview } from "@/api/analytics/hooks/goals/useGetGoalPreview";
+import { Skeleton } from "@/components/ui/skeleton";
+import { formatRate } from "../utils/goalLedger";
+import { GoalTrendBars } from "./GoalTrendBars";
+
+const DEBOUNCE_MS = 500;
+
+/**
+ * How many sessions the goal being typed would have counted in the selected
+ * period. Goals are evaluated at query time over events that already exist,
+ * so this is the number the goal shows once it is saved.
+ *
+ * `definition` is null while the form is incomplete.
+ */
+export function GoalMatchPreview({ definition }: { definition: GoalDefinition | null }) {
+ const t = useExtracted();
+
+ // Debounced as text: a definition object is new on every render, and a
+ // debounce keyed on identity would never settle.
+ const serialized = definition ? JSON.stringify(definition) : "";
+ const settled = useDebounce(serialized, DEBOUNCE_MS);
+ const settledDefinition = useMemo<GoalDefinition | null>(() => (settled ? JSON.parse(settled) : null), [settled]);
+
+ const { data, isError } = useGetGoalPreview(settledDefinition);
+ // Still typing, or the request for what was typed is in flight.
+ const isPending = serialized !== settled || (settledDefinition !== null && !data && !isError);
+
+ if (!definition) {
+ return (
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">
+ {t("Say what the goal matches to see how many sessions would have converted in the selected period.")}
+ </p>
+ );
+ }
+
+ if (isPending) {
+ return (
+ <div className="flex items-center gap-3" aria-busy="true">
+ <Skeleton className="h-[22px] w-[120px] shrink-0 rounded" />
+ <Skeleton className="h-3 w-64 max-w-full rounded" />
+ </div>
+ );
+ }
+
+ if (isError || !data) {
+ return (
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">
+ {t("The preview could not be loaded. The goal can still be saved.")}
+ </p>
+ );
+ }
+
+ return (
+ <div className="flex items-center gap-3 text-xs">
+ <GoalTrendBars
+ data={data.series}
+ isLoading={false}
+ label={t("Sessions that would have converted, over the selected period")}
+ className="h-[22px] w-[120px] shrink-0"
+ />
+ <p className="min-w-0 text-neutral-700 dark:text-neutral-200">
+ {data.conversions === 0
+ ? t("No sessions would have converted in the selected period.")
+ : t(
+ "{count, plural, one {# session} other {# sessions}} would have converted in the selected period ({rate}).",
+ { count: data.conversions, rate: formatRate(data.conversion_rate) }
+ )}{" "}
+ <span className="text-neutral-500 dark:text-neutral-400">
+ {t("History is counted from events you already have.")}
+ </span>
+ </p>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/goals/components/GoalRow.tsx b/client/src/app/[site]/goals/components/GoalRow.tsx
new file mode 100644
index 000000000..d046ef80b
--- /dev/null
+++ b/client/src/app/[site]/goals/components/GoalRow.tsx
@@ -0,0 +1,301 @@
+"use client";
+
+import { ChevronDown, ChevronRight, Copy, MoreHorizontal, Pencil, Trash2 } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { useState } from "react";
+import { Goal } from "@/api/analytics/endpoints";
+import { useDeleteGoal } from "@/api/analytics/hooks/goals/useDeleteGoal";
+import { Delta } from "@/components/site/Delta";
+import { PivotActions } from "@/components/site/PivotActions";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Skeleton } from "@/components/ui/skeleton";
+import { toast } from "@/components/ui/sonner";
+import { resolvePropertyFilters } from "@/lib/events";
+import { cn } from "@/lib/utils";
+import { formatRate, goalPattern, goalPivotFilters, LedgerRow } from "../utils/goalLedger";
+import { GoalEditor } from "./GoalEditor";
+import { GoalExpanded } from "./GoalExpanded";
+import { GoalTrendBars, TrendPoint } from "./GoalTrendBars";
+import { GoalTypeIcon, useGoalTypeLabels } from "./goalType";
+
+/**
+ * The ledger's columns, for the header and every row. Each row is its own
+ * grid, so the tracks are fixed widths: goal, conversions, [change], rate,
+ * [change], [trend], actions. The two change columns exist only while a
+ * comparison is on; below `lg` changes sit under their figures instead, and
+ * the trend column appears from `xl`.
+ */
+export const LEDGER_GRID = {
+ compare:
+ "grid grid-cols-[minmax(0,1fr)_80px_72px_36px] lg:grid-cols-[minmax(0,1fr)_156px_80px_72px_80px_104px] xl:grid-cols-[minmax(0,1fr)_156px_80px_72px_80px_148px_104px] min-[87.5rem]:grid-cols-[minmax(0,1fr)_172px_88px_76px_88px_164px_196px]",
+ plain:
+ "grid grid-cols-[minmax(0,1fr)_80px_72px_36px] lg:grid-cols-[minmax(0,1fr)_156px_72px_104px] xl:grid-cols-[minmax(0,1fr)_156px_72px_148px_104px] min-[87.5rem]:grid-cols-[minmax(0,1fr)_172px_76px_164px_196px]",
+} as const;
+
+const ROW_BORDER = "border-b border-neutral-100 dark:border-neutral-800";
+
+/** What the goal is: its type and the pattern it matches, plus any property filters. */
+function DefinitionChip({ goal }: { goal: Goal }) {
+ const t = useExtracted();
+ const typeLabels = useGoalTypeLabels();
+ const pattern = goalPattern(goal) || t("Any");
+ const properties = resolvePropertyFilters(goal.config)
+ .map(filter => `${filter.key}: ${filter.value}`)
+ .join(", ");
+
+ return (
+ <span
+ className="inline-flex min-w-0 max-w-full items-center gap-1 self-start rounded bg-neutral-100 px-1.5 py-0.5 text-xs dark:bg-neutral-800 sm:self-auto"
+ title={properties ? `${pattern} (${properties})` : pattern}
+ >
+ <span className="shrink-0 text-neutral-500 dark:text-neutral-400">{typeLabels[goal.goalType]}</span>
+ <span className="truncate text-neutral-800 dark:text-neutral-200">{pattern}</span>
+ {properties && <span className="truncate text-neutral-500 dark:text-neutral-400">{properties}</span>}
+ </span>
+ );
+}
+
+interface GoalRowProps {
+ row: LedgerRow;
+ siteId: number;
+ /** goals:write: edit, clone and delete. */
+ canWrite: boolean;
+ /** Whether a comparison period is selected: the change columns exist. */
+ comparisonEnabled: boolean;
+ /** The comparison period's figures are still on their way. */
+ isLoadingComparison: boolean;
+ /** The largest conversion count among all goals: the bar's full width. */
+ maxConversions: number;
+ timeSeries?: TrendPoint[];
+ isLoadingTimeSeries: boolean;
+ /** "conversions per day", for the trend's accessible name. */
+ trendLabel: string;
+ chartTitle: string;
+ onClone: (goal: Goal) => void;
+}
+
+export function GoalRow({
+ row,
+ siteId,
+ canWrite,
+ comparisonEnabled,
+ isLoadingComparison,
+ maxConversions,
+ timeSeries,
+ isLoadingTimeSeries,
+ trendLabel,
+ chartTitle,
+ onClone,
+}: GoalRowProps) {
+ const t = useExtracted();
+ const { goal, label } = row;
+ const [isExpanded, setIsExpanded] = useState(false);
+ const [isEditing, setIsEditing] = useState(false);
+ const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
+ const deleteGoal = useDeleteGoal();
+
+ const pivotFilters = goalPivotFilters(goal);
+ const grid = comparisonEnabled ? LEDGER_GRID.compare : LEDGER_GRID.plain;
+ // A goal with conversions always shows a sliver; a goal with none shows an empty track.
+ const barWidth =
+ row.conversions > 0 && maxConversions > 0 ? Math.max(1.5, (row.conversions / maxConversions) * 100) : 0;
+
+ const handleDelete = async () => {
+ try {
+ await deleteGoal.mutateAsync(goal.goalId);
+ setIsDeleteDialogOpen(false);
+ } catch (error) {
+ console.error("Error deleting goal:", error);
+ toast.error(error instanceof Error ? error.message : t("Failed to delete goal"));
+ }
+ };
+
+ if (isEditing) {
+ return (
+ <div role="row" className={cn(ROW_BORDER, "bg-neutral-50 dark:bg-neutral-800/30")}>
+ <div role="cell">
+ <GoalEditor siteId={siteId} mode="edit" goal={goal} onDone={() => setIsEditing(false)} />
+ </div>
+ </div>
+ );
+ }
+
+ const comparisonCell = (value: LedgerRow["conversionsDelta"]) =>
+ isLoadingComparison ? <Skeleton className="h-3 w-10 rounded" /> : <Delta value={value} />;
+
+ return (
+ <>
+ <div
+ role="row"
+ className={cn(
+ grid,
+ "cursor-pointer items-center text-sm transition-colors hover:bg-neutral-50 dark:hover:bg-neutral-800/20",
+ isExpanded ? "bg-neutral-50 dark:bg-neutral-800/30" : ROW_BORDER
+ )}
+ onClick={() => setIsExpanded(!isExpanded)}
+ >
+ <div role="cell" className="flex min-w-0 items-center gap-1.5 py-2 pl-1.5 pr-2 sm:gap-2 sm:pl-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="smIcon"
+ className="shrink-0 text-neutral-500 dark:text-neutral-400"
+ aria-expanded={isExpanded}
+ aria-label={isExpanded ? t("Collapse {name}", { name: label }) : t("Expand {name}", { name: label })}
+ onClick={event => {
+ event.stopPropagation();
+ setIsExpanded(!isExpanded);
+ }}
+ >
+ {isExpanded ? <ChevronDown /> : <ChevronRight />}
+ </Button>
+ <GoalTypeIcon type={goal.goalType} className="hidden sm:block" />
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden sm:flex-row sm:items-center sm:gap-2">
+ <span className="max-w-full truncate font-medium text-neutral-900 dark:text-neutral-50 sm:max-w-[70%] sm:shrink-0">
+ {label}
+ </span>
+ <DefinitionChip goal={goal} />
+ </div>
+ </div>
+
+ <div role="cell" className="flex items-center justify-end gap-3 px-2">
+ <div
+ className="hidden h-1.5 w-20 shrink-0 overflow-hidden rounded-full bg-neutral-100 dark:bg-neutral-800 lg:block"
+ aria-hidden="true"
+ >
+ <div className="h-full rounded-full bg-dataviz" style={{ width: `${barWidth}%` }} />
+ </div>
+ <div className="flex flex-col items-end">
+ <span className="font-medium tabular-nums text-neutral-900 dark:text-neutral-100">
+ {row.conversions.toLocaleString()}
+ </span>
+ <Delta value={row.conversionsDelta} className="lg:hidden" />
+ </div>
+ </div>
+
+ {comparisonEnabled && (
+ <div role="cell" className="hidden items-center justify-end px-2 lg:flex">
+ {comparisonCell(row.conversionsDelta)}
+ </div>
+ )}
+
+ <div role="cell" className="flex flex-col items-end px-2">
+ <span className="tabular-nums">{formatRate(row.rate)}</span>
+ <Delta value={row.rateDelta} className="lg:hidden" />
+ </div>
+
+ {comparisonEnabled && (
+ <div role="cell" className="hidden items-center justify-end px-2 lg:flex">
+ {comparisonCell(row.rateDelta)}
+ </div>
+ )}
+
+ <div role="cell" className="hidden pl-6 pr-2 xl:block">
+ <GoalTrendBars data={timeSeries} isLoading={isLoadingTimeSeries} label={`${label}, ${trendLabel}`} />
+ </div>
+
+ <div
+ role="cell"
+ className="flex items-center justify-end gap-0.5 pr-2"
+ onClick={event => event.stopPropagation()}
+ >
+ {pivotFilters && (
+ <>
+ <PivotActions
+ filters={pivotFilters}
+ actions={["sessions", "users"]}
+ className="hidden flex-nowrap min-[87.5rem]:flex"
+ />
+ <PivotActions
+ filters={pivotFilters}
+ actions={["sessions", "users"]}
+ showLabels={false}
+ className="hidden flex-nowrap lg:flex min-[87.5rem]:hidden"
+ />
+ </>
+ )}
+ {canWrite && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="smIcon"
+ className="shrink-0 text-neutral-500 dark:text-neutral-400"
+ aria-label={t("Edit, clone or delete {name}", { name: label })}
+ >
+ <MoreHorizontal />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setIsEditing(true)}>
+ <Pencil className="h-4 w-4" />
+ {t("Edit goal")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => onClone(goal)}>
+ <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>
+
+ {isExpanded && (
+ <div role="row" className={ROW_BORDER}>
+ <div role="cell">
+ <GoalExpanded
+ row={row}
+ siteId={siteId}
+ timeSeries={timeSeries}
+ isLoadingTimeSeries={isLoadingTimeSeries}
+ chartTitle={chartTitle}
+ />
+ </div>
+ </div>
+ )}
+
+ <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t("Are you sure you want to delete this goal?")}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t("This action cannot be undone. This will permanently delete the goal and remove it from all reports.")}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>
+ <AlertDialogAction onClick={handleDelete} variant="destructive">
+ {deleteGoal.isPending ? t("Deleting...") : t("Delete")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
diff --git a/client/src/app/[site]/goals/components/GoalTrendBars.tsx b/client/src/app/[site]/goals/components/GoalTrendBars.tsx
new file mode 100644
index 000000000..73bb635e4
--- /dev/null
+++ b/client/src/app/[site]/goals/components/GoalTrendBars.tsx
@@ -0,0 +1,110 @@
+"use client";
+
+import { TimeBucket } from "@rybbit/shared";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import { useMemo } from "react";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { formatChartDateTime } from "@/lib/dateTimeUtils";
+import { useStore, useTimezone } from "@/lib/store";
+import { cn } from "@/lib/utils";
+
+const MAX_BARS = 44;
+
+export interface TrendPoint {
+ time: string;
+ conversions: number;
+}
+
+interface TrendBar {
+ conversions: number;
+ startTime: string;
+ endTime: string;
+}
+
+/** Folds the series into at most `maxBars` bars, summing neighbours, so a long range still fits. */
+export function groupTrendBars(points: TrendPoint[], maxBars = MAX_BARS): TrendBar[] {
+ if (points.length === 0) return [];
+
+ const groupSize = Math.ceil(points.length / maxBars);
+ const bars: TrendBar[] = [];
+ for (let i = 0; i < points.length; i += groupSize) {
+ const group = points.slice(i, i + groupSize);
+ bars.push({
+ conversions: group.reduce((sum, point) => sum + point.conversions, 0),
+ startTime: group[0].time,
+ endTime: group[group.length - 1].time,
+ });
+ }
+ return bars;
+}
+
+const formatBarTime = (bar: TrendBar, bucket: TimeBucket, timezone: string) => {
+ const start = formatChartDateTime(DateTime.fromSQL(bar.startTime, { zone: timezone }), bucket);
+ const end = formatChartDateTime(DateTime.fromSQL(bar.endTime, { zone: timezone }), bucket);
+ return start === end ? start : `${start} - ${end}`;
+};
+
+/**
+ * Conversions per interval as a row of small bars. The tallest bar fills the
+ * height, so the shape is comparable within a goal, not across goals: the
+ * Conversions column is where goals are compared.
+ */
+export function GoalTrendBars({
+ data,
+ isLoading,
+ label,
+ className,
+}: {
+ data?: TrendPoint[];
+ isLoading: boolean;
+ /** Accessible name, e.g. "Signup, conversions per day". */
+ label: string;
+ className?: string;
+}) {
+ const t = useExtracted();
+ const bucket = useStore(state => state.bucket);
+ const timezone = useTimezone();
+ const bars = useMemo(() => groupTrendBars(data ?? []), [data]);
+
+ if (isLoading) {
+ return <Skeleton className={cn("h-[26px] w-full rounded", className)} />;
+ }
+
+ // Nothing to draw: keep the cell's height so rows do not jump.
+ if (bars.length === 0) {
+ return <div className={cn("h-[26px] w-full", className)} />;
+ }
+
+ const max = Math.max(...bars.map(bar => bar.conversions));
+
+ return (
+ <div className={cn("flex h-[26px] w-full items-end gap-px", className)} role="img" aria-label={label}>
+ {bars.map((bar, index) => (
+ <Tooltip key={`${bar.startTime}-${index}`} delayDuration={100}>
+ <TooltipTrigger asChild>
+ <div
+ className="min-w-px flex-1 rounded-t-[1px] bg-dataviz/70"
+ style={{
+ height: max > 0 ? `${Math.max(8, (bar.conversions / max) * 100)}%` : "8%",
+ opacity: max > 0 ? 1 : 0.35,
+ }}
+ />
+ </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, timezone)}
+ </div>
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-neutral-500 dark:text-neutral-400">{t("Conversions")}</span>
+ <span className="font-semibold tabular-nums">{bar.conversions.toLocaleString()}</span>
+ </div>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ ))}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/goals/components/GoalsLedger.test.tsx b/client/src/app/[site]/goals/components/GoalsLedger.test.tsx
new file mode 100644
index 000000000..b635fa6c2
--- /dev/null
+++ b/client/src/app/[site]/goals/components/GoalsLedger.test.tsx
@@ -0,0 +1,166 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Goal, GoalsSummary } from "@/api/analytics/endpoints";
+import { buildLedgerRows, DEFAULT_LEDGER_SORT, LedgerSort } from "../utils/goalLedger";
+import { GoalsSummaryBand } from "./GoalsSummaryBand";
+
+vi.mock("next-intl", () => ({
+ // Fills {placeholders} the way the page's simple messages need; plural
+ // messages are left as written.
+ useExtracted: () => (message: string, values?: Record<string, string | number>) =>
+ message.replace(/\{(\w+)\}/g, (match, key) => (values && key in values ? String(values[key]) : match)),
+}));
+
+// The rows are not under test here, and they pull in the whole site shell
+// (pivots, segment dialog, replay drawer).
+vi.mock("./GoalRow", () => ({
+ LEDGER_GRID: { compare: "grid", plain: "grid" },
+ GoalRow: ({ row }: { row: { label: string } }) => <div role="row">{row.label}</div>,
+}));
+
+import { GoalsLedger } from "./GoalsLedger";
+
+afterEach(cleanup);
+
+const goal = (goalId: number, name: string, conversions: number, sessions: number): Goal => ({
+ goalId,
+ name,
+ goalType: "path",
+ config: { pathPattern: `/${name.toLowerCase()}` },
+ createdAt: "2026-09-01 00:00:00",
+ total_conversions: conversions,
+ total_sessions: sessions,
+ conversion_rate: conversions / sessions,
+});
+
+const summaryOf = (goals: Goal[], sessions: number, converting: number): GoalsSummary => ({
+ goals,
+ total_sessions: sessions,
+ converting_sessions: converting,
+ total_goals: goals.length,
+});
+
+const current = summaryOf([goal(1, "Pricing", 2000, 10_000), goal(2, "Signup", 500, 10_000)], 10_000, 2200);
+const previous = summaryOf([goal(1, "Pricing", 2500, 10_000), goal(2, "Signup", 250, 10_000)], 10_000, 2600);
+
+describe("GoalsLedger", () => {
+ const renderLedger = (sort: LedgerSort, comparisonEnabled = true) => {
+ const onSortChange = vi.fn();
+ render(
+ <GoalsLedger
+ rows={buildLedgerRows(current.goals, previous.goals)}
+ sort={sort}
+ onSortChange={onSortChange}
+ comparisonEnabled={comparisonEnabled}
+ isLoadingComparison={false}
+ maxConversions={2000}
+ siteId={1}
+ canWrite
+ timeSeriesByGoal={new Map()}
+ isLoadingTimeSeries={false}
+ trendHeading="Daily"
+ trendLabel="conversions per day"
+ chartTitle="Conversions per day"
+ onClone={() => {}}
+ />
+ );
+ return onSortChange;
+ };
+
+ it("marks the sorted column and leaves the others unsorted", () => {
+ renderLedger(DEFAULT_LEDGER_SORT);
+
+ expect(screen.getByRole("columnheader", { name: "Conversions" }).getAttribute("aria-sort")).toBe("descending");
+ expect(screen.getByRole("columnheader", { name: "Rate" }).getAttribute("aria-sort")).toBe("none");
+ });
+
+ it("flips the direction of the column that is already sorted", () => {
+ const onSortChange = renderLedger(DEFAULT_LEDGER_SORT);
+ fireEvent.click(screen.getByRole("button", { name: "Conversions" }));
+
+ expect(onSortChange).toHaveBeenCalledWith({ key: "conversions", order: "asc" });
+ });
+
+ it("starts a figure column at the largest and the name column at A", () => {
+ const onSortChange = renderLedger(DEFAULT_LEDGER_SORT);
+ fireEvent.click(screen.getByRole("button", { name: "Rate" }));
+ fireEvent.click(screen.getByRole("button", { name: "Goal" }));
+
+ expect(onSortChange).toHaveBeenNthCalledWith(1, { key: "rate", order: "desc" });
+ expect(onSortChange).toHaveBeenNthCalledWith(2, { key: "name", order: "asc" });
+ });
+
+ it("sorts each change column by its own figure", () => {
+ const onSortChange = renderLedger(DEFAULT_LEDGER_SORT);
+ const [conversionsChange, rateChange] = screen.getAllByRole("button", { name: "Change" });
+ fireEvent.click(conversionsChange);
+ fireEvent.click(rateChange);
+
+ expect(onSortChange).toHaveBeenNthCalledWith(1, { key: "conversionsChange", order: "desc" });
+ expect(onSortChange).toHaveBeenNthCalledWith(2, { key: "rateChange", order: "desc" });
+ });
+
+ it("has no change columns while the comparison is off", () => {
+ renderLedger(DEFAULT_LEDGER_SORT, false);
+
+ expect(screen.queryByRole("button", { name: "Change" })).toBeNull();
+ expect(screen.getByRole("button", { name: "Conversions" })).toBeTruthy();
+ });
+
+ it("draws a row for each goal it is given", () => {
+ renderLedger(DEFAULT_LEDGER_SORT);
+
+ expect(screen.getByText("Pricing")).toBeTruthy();
+ expect(screen.getByText("Signup")).toBeTruthy();
+ });
+});
+
+describe("GoalsSummaryBand", () => {
+ const renderBand = (comparisonEnabled: boolean, before: GoalsSummary | undefined = previous) =>
+ render(
+ <GoalsSummaryBand
+ summary={current}
+ previous={comparisonEnabled ? before : undefined}
+ rows={buildLedgerRows(current.goals, comparisonEnabled ? before.goals : undefined)}
+ isLoading={false}
+ comparisonEnabled={comparisonEnabled}
+ isLoadingComparison={false}
+ />
+ );
+
+ it("opens with sessions, converting sessions and goal completions", () => {
+ renderBand(false);
+
+ expect(screen.getByText("Sessions").parentElement?.parentElement?.textContent).toContain("10,000");
+ expect(screen.getByText("Converting sessions").parentElement?.parentElement?.textContent).toContain("2,200");
+ expect(screen.getByText("22.0% completed at least one goal")).toBeTruthy();
+ // 2,000 + 500: completions count a session once per goal it completed.
+ expect(screen.getByText("Goal completions").parentElement?.parentElement?.textContent).toContain("2,500");
+ });
+
+ it("names no mover and no slipping goal while the comparison is off", () => {
+ renderBand(false);
+
+ expect(screen.queryByText("Best mover")).toBeNull();
+ expect(screen.queryByText("Slipping")).toBeNull();
+ });
+
+ it("names the goal that gained the most and the one that lost the most rate", () => {
+ renderBand(true);
+
+ const mover = screen.getByText("Best mover").parentElement?.parentElement;
+ const slipping = screen.getByText("Slipping").parentElement?.parentElement;
+ expect(mover?.textContent).toContain("Signup");
+ expect(mover?.textContent).toContain("100.0%");
+ expect(slipping?.textContent).toContain("Pricing");
+ expect(slipping?.textContent).toContain("5.00 pp");
+ expect(screen.getByText("Rate went from 25.00% to 20.00%")).toBeTruthy();
+ });
+
+ it("says so when nothing gained and nothing slipped", () => {
+ renderBand(true, current);
+
+ expect(screen.getByText("No goal gained conversions")).toBeTruthy();
+ expect(screen.getByText("No goal lost conversion rate")).toBeTruthy();
+ });
+});
diff --git a/client/src/app/[site]/goals/components/GoalsLedger.tsx b/client/src/app/[site]/goals/components/GoalsLedger.tsx
new file mode 100644
index 000000000..d8494cefa
--- /dev/null
+++ b/client/src/app/[site]/goals/components/GoalsLedger.tsx
@@ -0,0 +1,203 @@
+"use client";
+
+import { ArrowDown, ArrowUp, ChevronsUpDown } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { ReactNode } from "react";
+import { Goal } from "@/api/analytics/endpoints";
+import { Skeleton } from "@/components/ui/skeleton";
+import { cn } from "@/lib/utils";
+import { LedgerRow, LedgerSort, LedgerSortKey } from "../utils/goalLedger";
+import { GoalRow, LEDGER_GRID } from "./GoalRow";
+import { TrendPoint } from "./GoalTrendBars";
+
+const HEADER_CELL = "flex h-8 items-center px-2 text-xs font-medium text-neutral-500 dark:text-neutral-400";
+
+function SortHeader({
+ label,
+ sortKey,
+ sort,
+ onSortChange,
+ className,
+}: {
+ label: string;
+ sortKey: LedgerSortKey;
+ sort: LedgerSort;
+ onSortChange: (sort: LedgerSort) => void;
+ className?: string;
+}) {
+ const active = sort.key === sortKey;
+ // A first click on a figure shows the largest first; on the name, A to Z.
+ const firstOrder = sortKey === "name" ? "asc" : "desc";
+ const nextOrder = active ? (sort.order === "desc" ? "asc" : "desc") : firstOrder;
+ const Icon = !active ? ChevronsUpDown : sort.order === "desc" ? ArrowDown : ArrowUp;
+
+ return (
+ <div
+ role="columnheader"
+ aria-sort={active ? (sort.order === "asc" ? "ascending" : "descending") : "none"}
+ className={cn(HEADER_CELL, className)}
+ >
+ <button
+ type="button"
+ onClick={() => onSortChange({ key: sortKey, order: nextOrder })}
+ className={cn(
+ "inline-flex items-center gap-1 rounded-sm hover:text-neutral-900 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400 dark:hover:text-neutral-100",
+ active && "text-neutral-900 dark:text-neutral-100"
+ )}
+ >
+ {label}
+ <Icon className={cn("h-3 w-3", !active && "opacity-40")} aria-hidden="true" />
+ </button>
+ </div>
+ );
+}
+
+interface GoalsLedgerProps {
+ /** The rows to draw: already searched, sorted and cut to the page. */
+ rows: LedgerRow[];
+ sort: LedgerSort;
+ onSortChange: (sort: LedgerSort) => void;
+ comparisonEnabled: boolean;
+ isLoadingComparison: boolean;
+ /** The largest conversion count among all goals, not only the ones on this page. */
+ maxConversions: number;
+ siteId: number;
+ canWrite: boolean;
+ timeSeriesByGoal: Map<number, TrendPoint[]>;
+ isLoadingTimeSeries: boolean;
+ /** The trend column's heading, from the page's interval: "Daily". */
+ trendHeading: string;
+ /** "conversions per day": the trend's accessible name and the expanded chart's title. */
+ trendLabel: string;
+ chartTitle: string;
+ onClone: (goal: Goal) => void;
+ /** Drawn in place of the rows: the "nothing matches" message. */
+ emptyState?: ReactNode;
+ /** Under the rows, inside the card: the inline new-goal form. */
+ footer?: ReactNode;
+}
+
+/**
+ * Every goal on one aligned, sortable table: conversions, rate, their change
+ * against the comparison period, and the goal over time. A row opens in place
+ * to the chart and the sessions behind it.
+ */
+export function GoalsLedger({
+ rows,
+ sort,
+ onSortChange,
+ comparisonEnabled,
+ isLoadingComparison,
+ maxConversions,
+ siteId,
+ canWrite,
+ timeSeriesByGoal,
+ isLoadingTimeSeries,
+ trendHeading,
+ trendLabel,
+ chartTitle,
+ onClone,
+ emptyState,
+ footer,
+}: GoalsLedgerProps) {
+ const t = useExtracted();
+ const grid = comparisonEnabled ? LEDGER_GRID.compare : LEDGER_GRID.plain;
+
+ return (
+ <div className="overflow-hidden rounded-lg border border-neutral-100 bg-white dark:border-neutral-850 dark:bg-neutral-900">
+ <div role="table" aria-label={t("Goals")}>
+ <div role="rowgroup">
+ <div role="row" className={cn(grid, "bg-neutral-50 dark:bg-neutral-850")}>
+ <SortHeader label={t("Goal")} sortKey="name" sort={sort} onSortChange={onSortChange} className="pl-3" />
+ <SortHeader
+ label={t("Conversions")}
+ sortKey="conversions"
+ sort={sort}
+ onSortChange={onSortChange}
+ className="justify-end"
+ />
+ {comparisonEnabled && (
+ <SortHeader
+ label={t("Change")}
+ sortKey="conversionsChange"
+ sort={sort}
+ onSortChange={onSortChange}
+ className="hidden justify-end lg:flex"
+ />
+ )}
+ <SortHeader
+ label={t("Rate")}
+ sortKey="rate"
+ sort={sort}
+ onSortChange={onSortChange}
+ className="justify-end"
+ />
+ {comparisonEnabled && (
+ <SortHeader
+ label={t("Change")}
+ sortKey="rateChange"
+ sort={sort}
+ onSortChange={onSortChange}
+ className="hidden justify-end lg:flex"
+ />
+ )}
+ <div role="columnheader" className={cn(HEADER_CELL, "hidden pl-6 xl:flex")}>
+ {trendHeading}
+ </div>
+ <div role="columnheader" className={HEADER_CELL}>
+ <span className="sr-only">{t("Actions")}</span>
+ </div>
+ </div>
+ </div>
+
+ <div role="rowgroup">
+ {rows.map(row => (
+ <GoalRow
+ key={row.goal.goalId}
+ row={row}
+ siteId={siteId}
+ canWrite={canWrite}
+ comparisonEnabled={comparisonEnabled}
+ isLoadingComparison={isLoadingComparison}
+ maxConversions={maxConversions}
+ timeSeries={timeSeriesByGoal.get(row.goal.goalId)}
+ isLoadingTimeSeries={isLoadingTimeSeries}
+ trendLabel={trendLabel}
+ chartTitle={chartTitle}
+ onClone={onClone}
+ />
+ ))}
+ </div>
+ </div>
+
+ {emptyState}
+ {footer}
+ </div>
+ );
+}
+
+/** The ledger while the goals load: the same card and row rhythm, no figures. */
+export function GoalsLedgerSkeleton({ rows = 4 }: { rows?: number }) {
+ return (
+ <div
+ className="overflow-hidden rounded-lg border border-neutral-100 bg-white dark:border-neutral-850 dark:bg-neutral-900"
+ aria-busy="true"
+ >
+ <div className="h-8 bg-neutral-50 dark:bg-neutral-850" />
+ {Array.from({ length: rows }, (_, index) => (
+ <div
+ key={index}
+ className="flex items-center gap-3 border-b border-neutral-100 px-3 py-2.5 last:border-b-0 dark:border-neutral-800"
+ >
+ <Skeleton className="h-4 w-4 rounded" />
+ <Skeleton className="h-4 w-32 rounded" />
+ <Skeleton className="hidden h-4 w-28 rounded sm:block" />
+ <div className="flex-1" />
+ <Skeleton className="h-4 w-14 rounded" />
+ <Skeleton className="h-4 w-12 rounded" />
+ <Skeleton className="hidden h-6 w-36 rounded xl:block" />
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/goals/components/GoalsList.tsx b/client/src/app/[site]/goals/components/GoalsList.tsx
deleted file mode 100644
index 48be72bb2..000000000
--- a/client/src/app/[site]/goals/components/GoalsList.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-"use client";
-
-import GoalCard from "./GoalCard";
-import { Goal, GoalTimeSeriesPoint } from "../../../../api/analytics/endpoints";
-
-interface GoalsListProps {
- goals: Goal[];
- siteId: number;
- /** goals:write: edit, clone and delete. */
- canWrite: boolean;
- timeSeriesByGoal: Map<number, GoalTimeSeriesPoint[]>;
- isLoadingTimeSeries: boolean;
-}
-
-export default function GoalsList({ goals, siteId, canWrite, timeSeriesByGoal, isLoadingTimeSeries }: GoalsListProps) {
- return (
- <div className="flex flex-col gap-3">
- {goals.map(goal => (
- <GoalCard
- key={goal.goalId}
- goal={goal}
- siteId={siteId}
- canWrite={canWrite}
- timeSeries={timeSeriesByGoal.get(goal.goalId)}
- isLoadingTimeSeries={isLoadingTimeSeries}
- />
- ))}
- </div>
- );
-}
diff --git a/client/src/app/[site]/goals/components/GoalsSummaryBand.tsx b/client/src/app/[site]/goals/components/GoalsSummaryBand.tsx
new file mode 100644
index 000000000..1268c3c8c
--- /dev/null
+++ b/client/src/app/[site]/goals/components/GoalsSummaryBand.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { CheckCheck, Rewind, Target, TrendingDown, TrendingUp } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { GoalsSummary } from "@/api/analytics/endpoints";
+import { StatBand, StatBandCell } from "@/components/site/StatBand";
+import { NO_DELTA_TEXT, percentDelta } from "@/lib/delta";
+import { bestMover, formatRate, LedgerRow, slippingGoal } from "../utils/goalLedger";
+
+const ICON = "h-3 w-3";
+
+interface GoalsSummaryBandProps {
+ summary?: GoalsSummary;
+ /** The same summary for the comparison period; undefined while it is off or loading. */
+ previous?: GoalsSummary;
+ /** Every goal, joined with the comparison period. */
+ rows: LedgerRow[];
+ isLoading: boolean;
+ comparisonEnabled: boolean;
+ isLoadingComparison: boolean;
+}
+
+const sumConversions = (summary: GoalsSummary | undefined) =>
+ summary ? summary.goals.reduce((sum, goal) => sum + goal.total_conversions, 0) : undefined;
+
+/**
+ * The page's opening numbers: how many sessions there were, how many of them
+ * completed any goal, how many goal completions that makes, and (with a
+ * comparison on) which goal gained the most and which lost the most rate.
+ */
+export function GoalsSummaryBand({
+ summary,
+ previous,
+ rows,
+ isLoading,
+ comparisonEnabled,
+ isLoadingComparison,
+}: GoalsSummaryBandProps) {
+ const t = useExtracted();
+
+ const sessions = summary?.total_sessions ?? 0;
+ const converting = summary?.converting_sessions ?? 0;
+ const completions = sumConversions(summary) ?? 0;
+ const goalCount = summary?.goals.length ?? 0;
+
+ const mover = bestMover(rows);
+ const slipping = slippingGoal(rows);
+
+ const cells: (StatBandCell | false)[] = [
+ {
+ id: "sessions",
+ icon: <Rewind className={ICON} />,
+ label: t("Sessions"),
+ value: sessions.toLocaleString(),
+ delta: percentDelta(sessions, previous?.total_sessions),
+ sub: t("The denominator of every rate"),
+ },
+ {
+ id: "converting",
+ icon: <Target className={ICON} />,
+ label: t("Converting sessions"),
+ value: converting.toLocaleString(),
+ delta: percentDelta(converting, previous?.converting_sessions),
+ sub: t("{rate} completed at least one goal", {
+ rate: `${(sessions > 0 ? (converting / sessions) * 100 : 0).toFixed(1)}%`,
+ }),
+ },
+ {
+ id: "completions",
+ icon: <CheckCheck className={ICON} />,
+ label: t("Goal completions"),
+ value: completions.toLocaleString(),
+ delta: percentDelta(completions, sumConversions(previous)),
+ sub: t("Across {count, plural, one {# goal} other {# goals}}", { count: goalCount }),
+ },
+ comparisonEnabled && {
+ id: "best-mover",
+ icon: <TrendingUp className={ICON} />,
+ label: t("Best mover"),
+ value: mover ? mover.label : NO_DELTA_TEXT,
+ title: mover?.label,
+ delta: mover?.conversionsDelta,
+ sub: mover
+ ? t("{count, plural, one {# conversion} other {# conversions}}", { count: mover.conversions })
+ : t("No goal gained conversions"),
+ isLoading: isLoading || isLoadingComparison,
+ },
+ comparisonEnabled && {
+ id: "slipping",
+ icon: <TrendingDown className={ICON} />,
+ label: t("Slipping"),
+ value: slipping ? slipping.label : NO_DELTA_TEXT,
+ title: slipping?.label,
+ delta: slipping?.rateDelta,
+ sub:
+ slipping && slipping.previousRate !== null
+ ? t("Rate went from {from} to {to}", {
+ from: formatRate(slipping.previousRate),
+ to: formatRate(slipping.rate),
+ })
+ : t("No goal lost conversion rate"),
+ isLoading: isLoading || isLoadingComparison,
+ },
+ ];
+
+ return <StatBand cells={cells} isLoading={isLoading} />;
+}
diff --git a/client/src/app/[site]/goals/components/goalType.tsx b/client/src/app/[site]/goals/components/goalType.tsx
new file mode 100644
index 000000000..dce87e586
--- /dev/null
+++ b/client/src/app/[site]/goals/components/goalType.tsx
@@ -0,0 +1,37 @@
+"use client";
+
+import { Copy, ExternalLink, Eye, FileInput, LucideIcon, MousePointerClick, SquareMousePointer } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { GoalType } from "@/api/analytics/endpoints";
+import { cn } from "@/lib/utils";
+
+// The same icons the event log uses for these types (components/EventIcons),
+// drawn neutral: in the ledger the type is a label, not a data series.
+const GOAL_TYPE_ICONS: Record<GoalType, LucideIcon> = {
+ path: Eye,
+ event: MousePointerClick,
+ outbound: ExternalLink,
+ button_click: SquareMousePointer,
+ form_submit: FileInput,
+ copy: Copy,
+};
+
+export function GoalTypeIcon({ type, className }: { type: GoalType; className?: string }) {
+ const Icon = GOAL_TYPE_ICONS[type] ?? MousePointerClick;
+ return (
+ <Icon className={cn("h-4 w-4 shrink-0 text-neutral-500 dark:text-neutral-400", className)} aria-hidden="true" />
+ );
+}
+
+/** What each goal type is called on the page. */
+export function useGoalTypeLabels(): Record<GoalType, string> {
+ const t = useExtracted();
+ return {
+ path: t("Page"),
+ event: t("Event"),
+ outbound: t("Outbound link"),
+ button_click: t("Button click"),
+ form_submit: t("Form submit"),
+ copy: t("Copy"),
+ };
+}
diff --git a/client/src/app/[site]/goals/components/skeleton.tsx b/client/src/app/[site]/goals/components/skeleton.tsx
deleted file mode 100644
index 74a0eba03..000000000
--- a/client/src/app/[site]/goals/components/skeleton.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-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 90cc12d58..e72986f21 100644
--- a/client/src/app/[site]/goals/page.tsx
+++ b/client/src/app/[site]/goals/page.tsx
@@ -1,238 +1,296 @@
"use client";
+import { TimeBucket } from "@rybbit/shared";
+import { Plus, Target } from "lucide-react";
import { useExtracted } from "next-intl";
import { useMemo, useState } from "react";
+import { Goal } from "../../../api/analytics/endpoints";
+import { useGetGoalsSummary } from "../../../api/analytics/hooks/goals/useGetGoalsSummary";
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 { ErrorState } from "../../../components/ErrorState";
+import { ExternalLink } from "../../../components/ExternalLink";
import { NothingFound } from "../../../components/NothingFound";
import { Pagination } from "../../../components/pagination";
+import { AnalysisBar } from "../../../components/site/AnalysisBar";
+import { Button } from "../../../components/ui/button";
+import { Input } from "../../../components/ui/input";
import { useCanOnSite } from "../../../hooks/usePermissions";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
-import { useStore } from "../../../lib/store";
import { GOALS_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { useComparisonEnabled, useStore } from "../../../lib/store";
import { SubHeader } from "../components/SubHeader/SubHeader";
-import CreateGoalButton from "./components/CreateGoalButton";
-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 gap-3 flex-row items-center mb-1">
- {/* Left section skeleton */}
- <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>
- </div>
- <div className="flex items-center gap-1 mt-2">
- <div className="h-3 bg-neutral-200 dark:bg-neutral-800 rounded w-12"></div>
- <div className="h-5 bg-neutral-200 dark:bg-neutral-800 rounded w-32 px-1 py-0.5"></div>
- </div>
- </div>
+import { GoalEditor } from "./components/GoalEditor";
+import { GoalsLedger, GoalsLedgerSkeleton } from "./components/GoalsLedger";
+import { GoalsSummaryBand } from "./components/GoalsSummaryBand";
+import { TrendPoint } from "./components/GoalTrendBars";
+import {
+ buildLedgerRows,
+ DEFAULT_LEDGER_SORT,
+ LedgerSort,
+ LedgerSortKey,
+ matchesGoalSearch,
+ sortLedgerRows,
+} from "./utils/goalLedger";
- {/* Center section skeleton */}
- <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="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>
+// Rows per page. Each visible row asks for its own series, so this also
+// bounds the time-series query.
+const PAGE_SIZE = 10;
- {/* Right section skeleton */}
- <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>
- </div>
- <div className="bg-neutral-100 dark:bg-neutral-700 h-1.5 w-full"></div>
- </div>
-);
+const CARD =
+ "overflow-hidden rounded-lg border border-neutral-100 bg-white dark:border-neutral-850 dark:bg-neutral-900";
+const MUTED = "text-neutral-500 dark:text-neutral-400";
+
+/** The inline form at the foot of the ledger: closed, a new goal, or a copy of an existing one. */
+type Creator = null | { mode: "create" } | { mode: "clone"; goal: Goal };
export default function GoalsPage() {
const t = useExtracted();
useSetPageTitle("Goals");
- const { site } = useStore();
+ const site = useStore(state => state.site);
+ const bucket = useStore(state => state.bucket);
const canWrite = useCanOnSite("goals:write");
- const [searchQuery, setSearchQuery] = useState("");
- const [pagination, setPagination] = useState({
- pageIndex: 0, // TablePagination uses 0-based indexing
- pageSize: 10, // Show 10 goals per page
- });
-
- const { data: goalsData, isLoading } = useGetGoals({
- page: pagination.pageIndex + 1, // API uses 1-based indexing
- pageSize: pagination.pageSize,
- });
-
- // Filter goals based on search query
- const filteredGoals = useMemo(() => {
- if (!goalsData?.data) return [];
- if (!searchQuery.trim()) return goalsData.data;
-
- const query = searchQuery.toLowerCase();
- return goalsData.data.filter(goal => {
- // Search in goal name
- if (goal.name?.toLowerCase().includes(query)) return true;
-
- // Search in path pattern, event name, or autocapture value pattern
- if (goal.goalType === "path" && goal.config.pathPattern?.toLowerCase().includes(query)) return true;
- if (goal.goalType === "event" && goal.config.eventName?.toLowerCase().includes(query)) return true;
- if (goal.config.valuePattern?.toLowerCase().includes(query)) return true;
-
- // Search in event property key/value
- if (
- goal.config.eventPropertyKey?.toLowerCase().includes(query) ||
- String(goal.config.eventPropertyValue)?.toLowerCase().includes(query)
- ) {
- return true;
- }
-
- return false;
- });
- }, [goalsData?.data, searchQuery]);
-
- const goalIds = useMemo(() => filteredGoals.map(goal => goal.goalId), [filteredGoals]);
-
- const { data: goalTimeSeries, isLoading: isLoadingGoalTimeSeries } = useGetGoalTimeSeries({
- goalIds,
- });
+ const comparisonEnabled = useComparisonEnabled();
- const timeSeriesByGoal = useMemo(() => {
- const map = new Map<number, GoalTimeSeriesPoint[]>();
+ const [search, setSearch] = useState("");
+ const [sort, setSort] = useState<LedgerSort>(DEFAULT_LEDGER_SORT);
+ const [page, setPage] = useState(1);
+ const [creator, setCreator] = useState<Creator>(null);
+
+ const { data: summary, isLoading, isError, refetch } = useGetGoalsSummary();
+ const previous = useGetGoalsSummary({ periodTime: "previous" });
+ // A disabled query can still hold the last comparison it fetched.
+ const previousSummary = comparisonEnabled ? previous.data : undefined;
+ const isLoadingComparison = comparisonEnabled && previous.isLoading;
- for (const point of goalTimeSeries ?? []) {
- const points = map.get(point.goal_id) ?? [];
+ const goalLabel = (goal: Goal) => goal.name || t("Goal #{goalId}", { goalId: String(goal.goalId) });
+ const allRows = buildLedgerRows(summary?.goals ?? [], previousSummary?.goals, goalLabel);
+
+ // Search and sort run over every goal; only then is the list cut into pages.
+ const changeSorts: LedgerSortKey[] = ["conversionsChange", "rateChange"];
+ const activeSort = !comparisonEnabled && changeSorts.includes(sort.key) ? DEFAULT_LEDGER_SORT : sort;
+ const matchingRows = sortLedgerRows(
+ allRows.filter(row => matchesGoalSearch(row, search)),
+ activeSort
+ );
+ const pageCount = Math.max(1, Math.ceil(matchingRows.length / PAGE_SIZE));
+ const currentPage = Math.min(page, pageCount);
+ const visibleRows = matchingRows.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE);
+ const maxConversions = allRows.reduce((max, row) => Math.max(max, row.conversions), 0);
+
+ // Sorted so that re-sorting the same page of goals does not ask again.
+ const visibleGoalIds = visibleRows.map(row => row.goal.goalId).sort((a, b) => a - b);
+ const { data: timeSeries, isLoading: isLoadingTimeSeries } = useGetGoalTimeSeries({ goalIds: visibleGoalIds });
+ const timeSeriesByGoal = useMemo(() => {
+ const byGoal = new Map<number, TrendPoint[]>();
+ for (const point of timeSeries ?? []) {
+ const points = byGoal.get(point.goal_id) ?? [];
points.push(point);
- map.set(point.goal_id, points);
+ byGoal.set(point.goal_id, points);
}
+ return byGoal;
+ }, [timeSeries]);
+
+ const interval: Partial<Record<TimeBucket, { heading: string; label: string; title: string }>> = {
+ hour: { heading: t("Hourly"), label: t("conversions per hour"), title: t("Conversions per hour") },
+ day: { heading: t("Daily"), label: t("conversions per day"), title: t("Conversions per day") },
+ week: { heading: t("Weekly"), label: t("conversions per week"), title: t("Conversions per week") },
+ month: { heading: t("Monthly"), label: t("conversions per month"), title: t("Conversions per month") },
+ year: { heading: t("Yearly"), label: t("conversions per year"), title: t("Conversions per year") },
+ };
+ const { heading, label, title } = interval[bucket] ?? {
+ heading: t("Trend"),
+ label: t("conversions over time"),
+ title: t("Conversions over time"),
+ };
- return map;
- }, [goalTimeSeries]);
-
- // Create pagination controller for TablePagination
- const paginationController = {
- getState: () => ({ pagination }),
- getCanPreviousPage: () => pagination.pageIndex > 0,
- getCanNextPage: () => {
- if (!goalsData?.meta) return false;
- return pagination.pageIndex + 1 < goalsData.meta.totalPages;
- },
- getPageCount: () => goalsData?.meta?.totalPages || 1,
- setPageIndex: (index: number) => {
- setPagination(prev => ({ ...prev, pageIndex: index }));
- // Scroll to top of page when changing pages
- window.scrollTo({
- top: 0,
- behavior: "smooth",
- });
- },
- previousPage: () => {
- if (pagination.pageIndex > 0) {
- setPagination(prev => ({ ...prev, pageIndex: prev.pageIndex - 1 }));
- window.scrollTo({ top: 0, behavior: "smooth" });
- }
- },
- nextPage: () => {
- if (goalsData?.meta && pagination.pageIndex + 1 < goalsData.meta.totalPages) {
- setPagination(prev => ({ ...prev, pageIndex: prev.pageIndex + 1 }));
- window.scrollTo({ top: 0, behavior: "smooth" });
- }
- },
+ const sortNames: Record<LedgerSortKey, string> = {
+ name: t("name"),
+ conversions: t("conversions"),
+ conversionsChange: t("change in conversions"),
+ rate: t("rate"),
+ rateChange: t("change in rate"),
};
- // Transform data for TablePagination
- const paginationData = goalsData
- ? {
- items: goalsData.data,
- total: goalsData.meta.total,
- }
- : undefined;
+ const openCreator = () => setCreator({ mode: "create" });
+ const closeCreator = () => setCreator(null);
+ const creatorForm = creator && (
+ <GoalEditor
+ // A clone of another goal is another form: start it from that goal.
+ key={creator.mode === "clone" ? `clone-${creator.goal.goalId}` : "create"}
+ siteId={Number(site)}
+ mode={creator.mode}
+ goal={creator.mode === "clone" ? creator.goal : undefined}
+ onDone={closeCreator}
+ />
+ );
+
+ const hasGoals = !!summary && summary.goals.length > 0;
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 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>
- {canWrite && <CreateGoalButton siteId={Number(site)} />}
- </div>
+
{/* if site is not loaded, show skeleton */}
{isLoading || !site ? (
- <div className="space-y-3">
- {Array(3)
- .fill(0)
- .map((_, index) => (
- <GoalCardSkeleton key={`skeleton-${index}`} />
- ))}
+ <>
+ <GoalsSummaryBand rows={[]} isLoading comparisonEnabled={comparisonEnabled} isLoadingComparison={false} />
+ <GoalsLedgerSkeleton />
+ </>
+ ) : isError || !summary ? (
+ <div className={CARD}>
+ <ErrorState
+ title={t("Failed to load goals")}
+ message={t("There was a problem fetching the goals. Please try again later.")}
+ refetch={refetch}
+ />
</div>
- ) : !goalsData || goalsData.data.length === 0 ? (
- <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>
- }
- action={canWrite ? <CreateGoalButton siteId={Number(site)} /> : undefined}
- />
- ) : filteredGoals.length === 0 ? (
- <NothingFound
- icon={<Target className="w-10 h-10" />}
- title={t("No goals found")}
- description={t('No goals match "{searchQuery}"', { searchQuery })}
- />
+ ) : !hasGoals ? (
+ <>
+ <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>
+ }
+ action={
+ canWrite && !creator ? (
+ <Button onClick={openCreator}>
+ <Plus />
+ {t("New goal")}
+ </Button>
+ ) : undefined
+ }
+ />
+ {canWrite && creator && <div className={CARD}>{creatorForm}</div>}
+ </>
) : (
- <div className="space-y-6">
- <GoalsList
- goals={filteredGoals}
+ <>
+ <GoalsSummaryBand
+ summary={summary}
+ previous={previousSummary}
+ rows={allRows}
+ isLoading={false}
+ comparisonEnabled={comparisonEnabled}
+ isLoadingComparison={isLoadingComparison}
+ />
+
+ <AnalysisBar
+ end={
+ <>
+ <span className={`hidden text-xs md:inline ${MUTED}`}>
+ {search.trim()
+ ? t("{shown} of {count, plural, one {# goal} other {# goals}}, sorted by {column}", {
+ shown: String(matchingRows.length),
+ count: allRows.length,
+ column: sortNames[activeSort.key],
+ })
+ : t("{count, plural, one {# goal} other {# goals}}, sorted by {column}", {
+ count: allRows.length,
+ column: sortNames[activeSort.key],
+ })}
+ </span>
+ {canWrite && (
+ <Button size="sm" onClick={openCreator}>
+ <Plus />
+ {t("New goal")}
+ </Button>
+ )}
+ </>
+ }
+ >
+ <div className="hidden h-5 w-px bg-neutral-200 dark:bg-neutral-800 sm:block" aria-hidden="true" />
+ <Input
+ placeholder={t("Filter goals")}
+ aria-label={t("Filter goals")}
+ className="h-8 w-44 text-xs sm:w-52"
+ isSearch
+ value={search}
+ onChange={event => {
+ setSearch(event.target.value);
+ setPage(1);
+ }}
+ />
+ <BucketSelection />
+ </AnalysisBar>
+
+ <GoalsLedger
+ rows={visibleRows}
+ sort={activeSort}
+ onSortChange={next => {
+ setSort(next);
+ setPage(1);
+ }}
+ comparisonEnabled={comparisonEnabled}
+ isLoadingComparison={isLoadingComparison}
+ maxConversions={maxConversions}
siteId={Number(site)}
canWrite={canWrite}
timeSeriesByGoal={timeSeriesByGoal}
- isLoadingTimeSeries={isLoadingGoalTimeSeries}
+ isLoadingTimeSeries={isLoadingTimeSeries}
+ trendHeading={heading}
+ trendLabel={label}
+ chartTitle={title}
+ onClone={goal => setCreator({ mode: "clone", goal })}
+ emptyState={
+ matchingRows.length === 0 ? (
+ <NothingFound
+ icon={<Target className="w-10 h-10" />}
+ title={t("No goals found")}
+ description={t('No goals match "{searchQuery}"', { searchQuery: search })}
+ />
+ ) : undefined
+ }
+ footer={
+ canWrite &&
+ (creator ? (
+ <div className="border-t border-neutral-100 dark:border-neutral-800">{creatorForm}</div>
+ ) : (
+ <button
+ type="button"
+ onClick={openCreator}
+ className="flex w-full items-center gap-2 border-t border-neutral-100 px-3 py-2.5 text-sm text-neutral-600 transition-colors hover:bg-neutral-50 hover:text-neutral-900 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-neutral-400 dark:border-neutral-800 dark:text-neutral-300 dark:hover:bg-neutral-800/20 dark:hover:text-neutral-100"
+ >
+ <Plus className="h-4 w-4" />
+ {t("New goal")}
+ </button>
+ ))
+ }
/>
- {goalsData.meta.totalPages > 1 && !searchQuery && (
+ {pageCount > 1 && (
<Pagination
- table={paginationController}
- data={paginationData}
- pagination={pagination}
- setPagination={setPagination}
- isLoading={isLoading}
+ page={currentPage}
+ pageCount={pageCount}
+ totalItems={matchingRows.length}
+ pageSize={PAGE_SIZE}
+ onPageChange={setPage}
itemName="goals"
/>
)}
- </div>
+
+ <p className={`px-1 text-xs ${MUTED}`}>
+ {t(
+ "A conversion is a session that completed the goal at least once. Rate is conversions divided by the {sessions} sessions in range.",
+ { sessions: summary.total_sessions.toLocaleString() }
+ )}
+ {summary.total_goals > summary.goals.length && (
+ <>
+ {" "}
+ {t("Showing the {shown} most recently created of {total} goals.", {
+ shown: String(summary.goals.length),
+ total: String(summary.total_goals),
+ })}
+ </>
+ )}
+ </p>
+ </>
)}
</div>
</DisabledOverlay>
diff --git a/client/src/app/[site]/goals/utils/goalForm.test.ts b/client/src/app/[site]/goals/utils/goalForm.test.ts
new file mode 100644
index 000000000..b514f2531
--- /dev/null
+++ b/client/src/app/[site]/goals/utils/goalForm.test.ts
@@ -0,0 +1,145 @@
+import { describe, expect, it } from "vitest";
+import { Goal } from "@/api/analytics/endpoints";
+import { goalDefinitionOf, goalFormDefaults, goalFormSchema, propertyDraftsOf } from "./goalForm";
+
+const goal = (overrides: Partial<Goal>): Goal => ({
+ goalId: 1,
+ name: "Signup",
+ goalType: "event",
+ config: { eventName: "signup" },
+ createdAt: "2026-09-01 00:00:00",
+ total_conversions: 0,
+ total_sessions: 0,
+ conversion_rate: 0,
+ ...overrides,
+});
+
+describe("goalFormSchema", () => {
+ const messageFor = (values: unknown) => {
+ const result = goalFormSchema.safeParse(values);
+ return result.success ? null : result.error.issues[0].message;
+ };
+
+ it("needs a pattern for page and event goals", () => {
+ expect(messageFor({ goalType: "path", pattern: " " })).toBe("required");
+ expect(messageFor({ goalType: "event", pattern: "" })).toBe("required");
+ });
+
+ it("lets autocapture goals match any event of their type", () => {
+ for (const goalType of ["outbound", "button_click", "form_submit", "copy"]) {
+ expect(messageFor({ goalType, pattern: "" })).toBeNull();
+ }
+ });
+
+ it("refuses a full URL as a page pattern, but not as an outbound pattern", () => {
+ expect(messageFor({ goalType: "path", pattern: "https://rybbit.com/pricing" })).toBe("url");
+ expect(messageFor({ goalType: "path", pattern: "rybbit.com/pricing" })).toBe("url");
+ expect(messageFor({ goalType: "path", pattern: "/pricing" })).toBeNull();
+ expect(messageFor({ goalType: "outbound", pattern: "https://github.com/**" })).toBeNull();
+ });
+
+ it("holds an autocapture pattern to the length the server accepts", () => {
+ expect(messageFor({ goalType: "copy", pattern: "a".repeat(513) })).toBe("too_long");
+ expect(messageFor({ goalType: "copy", pattern: "a".repeat(512) })).toBeNull();
+ });
+});
+
+describe("goalDefinitionOf", () => {
+ it("is null while the form is incomplete", () => {
+ expect(goalDefinitionOf({ goalType: "path", pattern: "", name: "" }, [])).toBeNull();
+ expect(goalDefinitionOf({ goalType: "path", pattern: "https://rybbit.com/x", name: "" }, [])).toBeNull();
+ });
+
+ it("saves the pattern under the config key of its type", () => {
+ expect(goalDefinitionOf({ goalType: "path", pattern: " /welcome ", name: "" }, [])).toEqual({
+ goalType: "path",
+ config: { pathPattern: "/welcome" },
+ });
+ expect(goalDefinitionOf({ goalType: "event", pattern: "signup", name: "" }, [])).toEqual({
+ goalType: "event",
+ config: { eventName: "signup" },
+ });
+ expect(goalDefinitionOf({ goalType: "button_click", pattern: "Sign Up*", name: "" }, [])).toEqual({
+ goalType: "button_click",
+ config: { valuePattern: "Sign Up*" },
+ });
+ });
+
+ it("saves an autocapture goal with no pattern as matching any event of the type", () => {
+ for (const goalType of ["outbound", "button_click", "form_submit", "copy"] as const) {
+ expect(goalDefinitionOf({ goalType, pattern: " ", name: "" }, [])).toEqual({ goalType, config: {} });
+ }
+ });
+
+ it("keeps only complete property rows", () => {
+ const definition = goalDefinitionOf({ goalType: "event", pattern: "subscribed", name: "" }, [
+ { key: " plan ", value: "pro" },
+ { key: "", value: "orphan" },
+ { key: "seats", value: "" },
+ ]);
+
+ expect(definition?.config).toEqual({ eventName: "subscribed", propertyFilters: [{ key: "plan", value: "pro" }] });
+ });
+
+ it("never writes the legacy single-property fields", () => {
+ const definition = goalDefinitionOf({ goalType: "path", pattern: "/pricing", name: "" }, [
+ { key: "utm_source", value: "ads" },
+ ]);
+
+ expect(definition?.config).not.toHaveProperty("eventPropertyKey");
+ expect(definition?.config).not.toHaveProperty("eventPropertyValue");
+ });
+});
+
+describe("goalFormDefaults", () => {
+ it("starts a new goal empty, as a page goal", () => {
+ expect(goalFormDefaults(undefined, "create")).toEqual({ name: "", goalType: "path", pattern: "" });
+ });
+
+ it("starts an edit from the goal", () => {
+ expect(goalFormDefaults(goal({}), "edit")).toEqual({ name: "Signup", goalType: "event", pattern: "signup" });
+ expect(
+ goalFormDefaults(goal({ name: null, goalType: "form_submit", config: { valuePattern: "signup-form" } }), "edit")
+ ).toEqual({ name: "", goalType: "form_submit", pattern: "signup-form" });
+ });
+
+ it("starts a clone under the copy's name", () => {
+ expect(goalFormDefaults(goal({}), "clone", "Signup (Copy)")).toEqual({
+ name: "Signup (Copy)",
+ goalType: "event",
+ pattern: "signup",
+ });
+ });
+});
+
+describe("propertyDraftsOf", () => {
+ it("has no rows for a goal without property filters", () => {
+ expect(propertyDraftsOf(undefined)).toEqual([]);
+ expect(propertyDraftsOf(goal({}))).toEqual([]);
+ });
+
+ it("reads property filters as text", () => {
+ const withFilters = goal({
+ config: {
+ eventName: "subscribed",
+ propertyFilters: [
+ { key: "plan", value: "pro" },
+ { key: "seats", value: 5 },
+ { key: "annual", value: true },
+ ],
+ },
+ });
+
+ expect(propertyDraftsOf(withFilters)).toEqual([
+ { key: "plan", value: "pro" },
+ { key: "seats", value: "5" },
+ { key: "annual", value: "true" },
+ ]);
+ });
+
+ it("reads the legacy single-property fields", () => {
+ const legacy = goal({ config: { eventName: "subscribed", eventPropertyKey: "plan", eventPropertyValue: "pro" } });
+
+ expect(propertyDraftsOf(legacy)).toEqual([{ key: "plan", value: "pro" }]);
+ });
+});
diff --git a/client/src/app/[site]/goals/utils/goalForm.ts b/client/src/app/[site]/goals/utils/goalForm.ts
new file mode 100644
index 000000000..8b3579441
--- /dev/null
+++ b/client/src/app/[site]/goals/utils/goalForm.ts
@@ -0,0 +1,90 @@
+import * as z from "zod";
+import { Goal, GoalConfig, GoalDefinition, GoalType } from "@/api/analytics/endpoints";
+import { AUTOCAPTURE_TARGET_TYPES, resolvePropertyFilters } from "@/lib/events";
+import { goalPattern } from "./goalLedger";
+
+export const GOAL_TYPES: readonly GoalType[] = ["path", "event", ...AUTOCAPTURE_TARGET_TYPES];
+
+// A path goal is matched against the pathname only; a pasted URL never matches.
+const LOOKS_LIKE_URL = /^(https?:\/\/|www\.|[a-zA-Z0-9-]+\.[a-zA-Z]{2,}\/)/i;
+
+export const goalFormSchema = z
+ .object({
+ name: z.string().optional(),
+ goalType: z.enum(["path", "event", ...AUTOCAPTURE_TARGET_TYPES]),
+ // One field for what the goal matches; which config key it is saved under
+ // depends on the type. Autocapture goals match any event of their type
+ // when it is empty.
+ pattern: z.string(),
+ })
+ .superRefine((data, context) => {
+ const pattern = data.pattern.trim();
+
+ if ((data.goalType === "path" || data.goalType === "event") && !pattern) {
+ context.addIssue({ code: z.ZodIssueCode.custom, path: ["pattern"], message: "required" });
+ }
+ if (data.goalType === "path" && LOOKS_LIKE_URL.test(pattern)) {
+ context.addIssue({ code: z.ZodIssueCode.custom, path: ["pattern"], message: "url" });
+ }
+ if (data.goalType !== "path" && data.goalType !== "event" && pattern.length > 512) {
+ context.addIssue({ code: z.ZodIssueCode.custom, path: ["pattern"], message: "too_long" });
+ }
+ });
+
+export type GoalFormValues = z.infer<typeof goalFormSchema>;
+
+/** A property filter as typed: both sides are text until the goal is saved. */
+export interface PropertyFilterDraft {
+ key: string;
+ value: string;
+}
+
+export type GoalFormMode = "create" | "edit" | "clone";
+
+/**
+ * The form's starting values: empty for a new goal, the goal's own for edit and
+ * clone. A clone starts under `cloneName` ("Signup (Copy)").
+ */
+export function goalFormDefaults(goal: Goal | undefined, mode: GoalFormMode, cloneName = ""): GoalFormValues {
+ if (!goal || mode === "create") return { name: "", goalType: "path", pattern: "" };
+
+ return {
+ name: mode === "clone" ? cloneName : (goal.name ?? ""),
+ goalType: goal.goalType,
+ pattern: goalPattern(goal),
+ };
+}
+
+/** The goal's property filters as form rows, reading the legacy single-property fields too. */
+export function propertyDraftsOf(goal: Goal | undefined): PropertyFilterDraft[] {
+ if (!goal) return [];
+ return resolvePropertyFilters(goal.config).map(filter => ({ key: filter.key, value: String(filter.value) }));
+}
+
+/**
+ * The definition the form describes, or null while it is incomplete or
+ * invalid. This is exactly what is saved, and what the live preview counts.
+ * Only complete property rows are kept; the legacy single-property fields are
+ * never written.
+ */
+export function goalDefinitionOf(values: GoalFormValues, properties: PropertyFilterDraft[]): GoalDefinition | null {
+ if (!goalFormSchema.safeParse(values).success) return null;
+
+ const pattern = values.pattern.trim();
+ const propertyFilters = properties
+ .map(filter => ({ key: filter.key.trim(), value: filter.value }))
+ .filter(filter => filter.key && filter.value);
+
+ const config: GoalConfig =
+ values.goalType === "path"
+ ? { pathPattern: pattern }
+ : values.goalType === "event"
+ ? { eventName: pattern }
+ : pattern
+ ? { valuePattern: pattern }
+ : {};
+
+ if (propertyFilters.length > 0) config.propertyFilters = propertyFilters;
+
+ return { goalType: values.goalType, config };
+}
diff --git a/client/src/app/[site]/goals/utils/goalLedger.test.ts b/client/src/app/[site]/goals/utils/goalLedger.test.ts
new file mode 100644
index 000000000..ad202dfab
--- /dev/null
+++ b/client/src/app/[site]/goals/utils/goalLedger.test.ts
@@ -0,0 +1,365 @@
+import { describe, expect, it } from "vitest";
+import { Goal, SavedFunnel } from "@/api/analytics/endpoints";
+import {
+ bestMover,
+ buildLedgerRows,
+ formatRate,
+ funnelRefs,
+ goalPattern,
+ goalPivotFilters,
+ matchesGoalSearch,
+ pathPatternToRegex,
+ slippingGoal,
+ sortLedgerRows,
+} from "./goalLedger";
+
+const SESSIONS = 10_000;
+
+const goal = (overrides: Partial<Goal> & { goalId: number }): Goal => {
+ const conversions = overrides.total_conversions ?? 0;
+ const sessions = overrides.total_sessions ?? SESSIONS;
+ return {
+ name: `Goal ${overrides.goalId}`,
+ goalType: "path",
+ config: { pathPattern: `/page-${overrides.goalId}` },
+ createdAt: "2026-09-01 00:00:00",
+ total_conversions: conversions,
+ total_sessions: sessions,
+ conversion_rate: sessions > 0 ? conversions / sessions : 0,
+ ...overrides,
+ };
+};
+
+const pricing = goal({
+ goalId: 1,
+ name: "Viewed pricing",
+ config: { pathPattern: "/pricing" },
+ total_conversions: 2000,
+});
+const signup = goal({
+ goalId: 2,
+ name: "Signup",
+ goalType: "event",
+ config: { eventName: "signup" },
+ total_conversions: 500,
+});
+const github = goal({
+ goalId: 3,
+ name: "GitHub click",
+ goalType: "outbound",
+ config: { valuePattern: "https://github.com/**" },
+ total_conversions: 300,
+});
+
+describe("buildLedgerRows", () => {
+ it("leaves every change empty without a comparison period", () => {
+ const [row] = buildLedgerRows([pricing], undefined);
+
+ expect(row.conversions).toBe(2000);
+ expect(row.rate).toBeCloseTo(0.2);
+ expect(row.previousConversions).toBeNull();
+ expect(row.conversionsDelta).toBeNull();
+ expect(row.rateDelta).toBeNull();
+ expect(row.conversionsChange).toBeNull();
+ expect(row.rateChange).toBeNull();
+ });
+
+ it("joins the comparison period by goal id, whatever order it arrives in", () => {
+ const previous = [
+ goal({ goalId: 2, total_conversions: 400, total_sessions: 8000 }),
+ goal({ goalId: 1, total_conversions: 1600, total_sessions: 8000 }),
+ ];
+ const [pricingRow, signupRow] = buildLedgerRows([pricing, signup], previous);
+
+ expect(pricingRow.previousConversions).toBe(1600);
+ expect(pricingRow.conversionsDelta).toEqual({ direction: "up", text: "25.0%", signed: "+25.0%" });
+ expect(signupRow.previousConversions).toBe(400);
+ });
+
+ it("reports the rate's change in percentage points at two decimals", () => {
+ // 20.00% now against 21.25% before.
+ const previous = [goal({ goalId: 1, total_conversions: 1700, total_sessions: 8000 })];
+ const [row] = buildLedgerRows([pricing], previous);
+
+ expect(row.rateChange).toBeCloseTo(-1.25);
+ expect(row.rateDelta).toEqual({ direction: "down", text: "1.25 pp", signed: "-1.25 pp" });
+ });
+
+ it("has no percentage for a goal that converted nothing before", () => {
+ const [row] = buildLedgerRows([pricing], [goal({ goalId: 1, total_conversions: 0 })]);
+
+ expect(row.conversionsChange).toBeNull();
+ expect(row.conversionsDelta?.direction).toBe("none");
+ });
+
+ it("leaves a goal the comparison period does not list without a change", () => {
+ const [row] = buildLedgerRows([pricing], [goal({ goalId: 99, total_conversions: 5 })]);
+
+ expect(row.previousConversions).toBeNull();
+ expect(row.conversionsDelta).toBeNull();
+ });
+
+ it("labels a goal saved without a name through the caller's stand-in", () => {
+ const unnamed = goal({ goalId: 7, name: null });
+
+ expect(buildLedgerRows([unnamed], undefined)[0].label).toBe("/page-7");
+ expect(buildLedgerRows([unnamed], undefined, g => `Goal #${g.goalId}`)[0].label).toBe("Goal #7");
+ });
+});
+
+describe("matchesGoalSearch", () => {
+ const rows = buildLedgerRows(
+ [
+ pricing,
+ signup,
+ goal({
+ goalId: 4,
+ name: "Paid plan",
+ goalType: "event",
+ config: { eventName: "subscribed", propertyFilters: [{ key: "plan", value: "Pro" }] },
+ }),
+ ],
+ undefined
+ );
+ const matching = (search: string) => rows.filter(row => matchesGoalSearch(row, search)).map(row => row.goal.goalId);
+
+ it("matches everything for an empty search", () => {
+ expect(matching(" ")).toEqual([1, 2, 4]);
+ });
+
+ it("matches the name, ignoring case", () => {
+ expect(matching("SIGN")).toEqual([2]);
+ });
+
+ it("matches what the goal targets", () => {
+ expect(matching("/pric")).toEqual([1]);
+ expect(matching("subscribed")).toEqual([4]);
+ });
+
+ it("matches property filter keys and values", () => {
+ expect(matching("plan")).toEqual([4]);
+ expect(matching("pro")).toEqual([4]);
+ });
+});
+
+describe("sortLedgerRows", () => {
+ const previous = [
+ goal({ goalId: 1, total_conversions: 1900 }), // +5.3%, +1.00 pp
+ goal({ goalId: 2, total_conversions: 250 }), // +100%, +2.50 pp
+ goal({ goalId: 3, total_conversions: 450 }), // -33.3%, -1.50 pp
+ ];
+ const rows = buildLedgerRows([github, pricing, signup], previous);
+ const ids = (sorted: ReturnType<typeof sortLedgerRows>) => sorted.map(row => row.goal.goalId);
+
+ it("sorts by conversions in both directions", () => {
+ expect(ids(sortLedgerRows(rows, { key: "conversions", order: "desc" }))).toEqual([1, 2, 3]);
+ expect(ids(sortLedgerRows(rows, { key: "conversions", order: "asc" }))).toEqual([3, 2, 1]);
+ });
+
+ it("sorts by rate", () => {
+ expect(ids(sortLedgerRows(rows, { key: "rate", order: "desc" }))).toEqual([1, 2, 3]);
+ });
+
+ it("sorts by the change in conversions and in rate", () => {
+ expect(ids(sortLedgerRows(rows, { key: "conversionsChange", order: "desc" }))).toEqual([2, 1, 3]);
+ expect(ids(sortLedgerRows(rows, { key: "rateChange", order: "asc" }))).toEqual([3, 1, 2]);
+ });
+
+ it("sorts by name without regard to case", () => {
+ const named = buildLedgerRows(
+ [goal({ goalId: 1, name: "signup" }), goal({ goalId: 2, name: "Checkout" }), goal({ goalId: 3, name: "Trial" })],
+ undefined
+ );
+
+ expect(ids(sortLedgerRows(named, { key: "name", order: "asc" }))).toEqual([2, 1, 3]);
+ expect(ids(sortLedgerRows(named, { key: "name", order: "desc" }))).toEqual([3, 1, 2]);
+ });
+
+ it("keeps goals without a change last in either direction", () => {
+ const withNewGoal = buildLedgerRows(
+ [pricing, signup, goal({ goalId: 9, total_conversions: 9000 })],
+ [...previous, goal({ goalId: 9, total_conversions: 0 })]
+ );
+
+ expect(ids(sortLedgerRows(withNewGoal, { key: "conversionsChange", order: "desc" }))).toEqual([2, 1, 9]);
+ expect(ids(sortLedgerRows(withNewGoal, { key: "conversionsChange", order: "asc" }))).toEqual([1, 2, 9]);
+ });
+
+ it("breaks ties by conversions, then by goal id", () => {
+ const tied = buildLedgerRows(
+ [goal({ goalId: 5, total_conversions: 10 }), goal({ goalId: 4, total_conversions: 10 })],
+ undefined
+ );
+
+ expect(ids(sortLedgerRows(tied, { key: "conversions", order: "desc" }))).toEqual([4, 5]);
+ expect(ids(sortLedgerRows(tied, { key: "conversions", order: "asc" }))).toEqual([4, 5]);
+ });
+
+ it("does not reorder its input", () => {
+ sortLedgerRows(rows, { key: "conversions", order: "desc" });
+
+ expect(ids(rows)).toEqual([3, 1, 2]);
+ });
+});
+
+describe("bestMover and slippingGoal", () => {
+ it("picks the largest percent gain and the largest rate drop", () => {
+ const rows = buildLedgerRows(
+ [pricing, signup, github],
+ [
+ goal({ goalId: 1, total_conversions: 1900 }),
+ goal({ goalId: 2, total_conversions: 250 }),
+ goal({ goalId: 3, total_conversions: 450 }),
+ ]
+ );
+
+ expect(bestMover(rows)?.goal.goalId).toBe(2);
+ expect(slippingGoal(rows)?.goal.goalId).toBe(3);
+ });
+
+ it("ignores a goal with no baseline when naming the best mover", () => {
+ const rows = buildLedgerRows(
+ [pricing, goal({ goalId: 9, total_conversions: 9000 })],
+ [goal({ goalId: 1, total_conversions: 1900 }), goal({ goalId: 9, total_conversions: 0 })]
+ );
+
+ expect(bestMover(rows)?.goal.goalId).toBe(1);
+ });
+
+ it("names nothing when no goal gained or lost", () => {
+ const flat = buildLedgerRows([pricing], [goal({ goalId: 1, total_conversions: 2000 })]);
+ const falling = buildLedgerRows([pricing], [goal({ goalId: 1, total_conversions: 2500 })]);
+ const rising = buildLedgerRows([pricing], [goal({ goalId: 1, total_conversions: 1500 })]);
+
+ expect(bestMover(flat)).toBeNull();
+ expect(slippingGoal(flat)).toBeNull();
+ expect(bestMover(falling)).toBeNull();
+ expect(slippingGoal(rising)).toBeNull();
+ });
+
+ it("does not call a change that prints as zero a move", () => {
+ // 20.000% against 20.004%: -0.004 pp prints as 0.00 pp.
+ const rows = buildLedgerRows(
+ [goal({ goalId: 1, total_conversions: 20_000, total_sessions: 100_000 })],
+ [goal({ goalId: 1, total_conversions: 20_004, total_sessions: 100_000 })]
+ );
+
+ expect(slippingGoal(rows)).toBeNull();
+ });
+
+ it("names nothing without a comparison period", () => {
+ const rows = buildLedgerRows([pricing, signup], undefined);
+
+ expect(bestMover(rows)).toBeNull();
+ expect(slippingGoal(rows)).toBeNull();
+ });
+});
+
+describe("pathPatternToRegex", () => {
+ it("anchors a literal path and escapes regex characters", () => {
+ expect(pathPatternToRegex("/pricing")).toBe("^/pricing$");
+ expect(pathPatternToRegex("/docs/v1.2")).toBe("^/docs/v1\\.2$");
+ });
+
+ it("makes * one segment and ** any number of segments, as the server does", () => {
+ expect(pathPatternToRegex("/product/*/view")).toBe("^/product/[^/]+/view$");
+ expect(pathPatternToRegex("/docs/**")).toBe("^/docs/.*$");
+ expect(new RegExp(pathPatternToRegex("/product/*/view")).test("/product/42/view")).toBe(true);
+ expect(new RegExp(pathPatternToRegex("/product/*/view")).test("/product/a/b/view")).toBe(false);
+ });
+});
+
+describe("goalPivotFilters", () => {
+ it("selects a literal page by its path", () => {
+ expect(goalPivotFilters(pricing)).toEqual([{ parameter: "pathname", type: "equals", value: ["/pricing"] }]);
+ });
+
+ it("selects a wildcard page pattern by the regex the goal is counted with", () => {
+ expect(goalPivotFilters({ goalType: "path", config: { pathPattern: "/docs/**" } })).toEqual([
+ { parameter: "pathname", type: "regex", value: ["^/docs/.*$"] },
+ ]);
+ });
+
+ it("selects an event by its name", () => {
+ expect(goalPivotFilters(signup)).toEqual([{ parameter: "event_name", type: "equals", value: ["signup"] }]);
+ });
+
+ it("offers nothing for goals the filters cannot express", () => {
+ expect(goalPivotFilters(github)).toBeNull();
+ expect(
+ goalPivotFilters({
+ goalType: "event",
+ config: { eventName: "signup", propertyFilters: [{ key: "plan", value: "pro" }] },
+ })
+ ).toBeNull();
+ expect(
+ goalPivotFilters({
+ goalType: "path",
+ config: { pathPattern: "/pricing", eventPropertyKey: "utm_source", eventPropertyValue: "ads" },
+ })
+ ).toBeNull();
+ expect(goalPivotFilters({ goalType: "path", config: { pathPattern: `/${"a".repeat(600)}/*` } })).toBeNull();
+ expect(goalPivotFilters({ goalType: "path", config: {} })).toBeNull();
+ });
+});
+
+describe("funnelRefs", () => {
+ const funnel = (id: number, steps: SavedFunnel["steps"]): SavedFunnel => ({
+ id,
+ name: `Funnel ${id}`,
+ steps,
+ createdAt: "",
+ updatedAt: "",
+ conversionRate: null,
+ totalVisitors: null,
+ });
+ const funnels = [
+ funnel(1, [
+ { type: "page", value: "/" },
+ { type: "page", value: "/pricing" },
+ { type: "event", value: "signup" },
+ ]),
+ funnel(2, [
+ { type: "event", value: "demo_opened" },
+ { type: "event", value: "signup" },
+ ]),
+ funnel(3, [
+ { type: "outbound", value: "https://github.com/**" },
+ { type: "page", value: "/docs" },
+ ]),
+ ];
+
+ it("finds the step that targets the goal's page", () => {
+ expect(funnelRefs(pricing, funnels)).toEqual([{ funnel: funnels[0], step: 2, of: 3 }]);
+ });
+
+ it("finds every funnel that uses the goal's event", () => {
+ expect(funnelRefs(signup, funnels).map(ref => [ref.funnel.id, ref.step, ref.of])).toEqual([
+ [1, 3, 3],
+ [2, 2, 2],
+ ]);
+ });
+
+ it("matches autocapture goals on type and pattern", () => {
+ expect(funnelRefs(github, funnels).map(ref => ref.funnel.id)).toEqual([3]);
+ expect(funnelRefs({ goalType: "outbound", config: {} }, funnels)).toEqual([]);
+ });
+
+ it("does not confuse a page with an event of the same name", () => {
+ expect(funnelRefs({ goalType: "path", config: { pathPattern: "signup" } }, funnels)).toEqual([]);
+ });
+});
+
+describe("formatting", () => {
+ it("prints a rate with two decimals", () => {
+ expect(formatRate(0.0473)).toBe("4.73%");
+ expect(formatRate(0)).toBe("0.00%");
+ });
+
+ it("names what a goal matches", () => {
+ expect(goalPattern(pricing)).toBe("/pricing");
+ expect(goalPattern(signup)).toBe("signup");
+ expect(goalPattern(github)).toBe("https://github.com/**");
+ expect(goalPattern({ goalType: "copy", config: {} })).toBe("");
+ });
+});
diff --git a/client/src/app/[site]/goals/utils/goalLedger.ts b/client/src/app/[site]/goals/utils/goalLedger.ts
new file mode 100644
index 000000000..d9cb0df2c
--- /dev/null
+++ b/client/src/app/[site]/goals/utils/goalLedger.ts
@@ -0,0 +1,203 @@
+import { Filter } from "@rybbit/shared";
+import { Goal, GoalConfig, GoalType, SavedFunnel } from "@/api/analytics/endpoints";
+import { DeltaValue, percentChange, percentDelta, pointDelta } from "@/lib/delta";
+import { isAutocaptureTargetType, resolvePropertyFilters } from "@/lib/events";
+
+/** Decimal places for a conversion rate and for its change in percentage points. */
+export const RATE_DECIMALS = 2;
+
+/** A goal with this period's numbers and, when a comparison is on, how they moved. */
+export interface LedgerRow {
+ goal: Goal;
+ /** The goal's name, or the page's stand-in for a goal saved without one. */
+ label: string;
+ conversions: number;
+ /** Conversions divided by sessions, 0–1. */
+ rate: number;
+ /** Null when there is no comparison period (turned off, still loading, or the goal is missing from it). */
+ previousConversions: number | null;
+ previousRate: number | null;
+ conversionsDelta: DeltaValue | null;
+ rateDelta: DeltaValue | null;
+ /** Percent change in conversions; null without a baseline to divide by. */
+ conversionsChange: number | null;
+ /** Change of the rate in percentage points. */
+ rateChange: number | null;
+}
+
+export type LedgerSortKey = "name" | "conversions" | "conversionsChange" | "rate" | "rateChange";
+export type SortOrder = "asc" | "desc";
+export interface LedgerSort {
+ key: LedgerSortKey;
+ order: SortOrder;
+}
+
+export const DEFAULT_LEDGER_SORT: LedgerSort = { key: "conversions", order: "desc" };
+
+/** What the goal matches: its path pattern, event name, or autocapture value pattern. */
+export function goalPattern(goal: { goalType: GoalType; config: GoalConfig }): string {
+ if (goal.goalType === "path") return goal.config.pathPattern ?? "";
+ if (goal.goalType === "event") return goal.config.eventName ?? "";
+ return goal.config.valuePattern ?? "";
+}
+
+const roundTo = (value: number, decimals: number) => Number(value.toFixed(decimals));
+
+/**
+ * Joins this period's goals with the comparison period's by id. `previous` is
+ * undefined while the comparison is off or loading: every delta is then null
+ * and draws nothing.
+ */
+export function buildLedgerRows(
+ current: Goal[],
+ previous: Goal[] | undefined,
+ labelOf: (goal: Goal) => string = goal => goal.name || goalPattern(goal)
+): LedgerRow[] {
+ const previousById = new Map(previous?.map(goal => [goal.goalId, goal]));
+
+ return current.map(goal => {
+ const before = previousById.get(goal.goalId);
+ const previousConversions = before ? before.total_conversions : null;
+ const previousRate = before ? before.conversion_rate : null;
+
+ return {
+ goal,
+ label: labelOf(goal),
+ conversions: goal.total_conversions,
+ rate: goal.conversion_rate,
+ previousConversions,
+ previousRate,
+ conversionsDelta: percentDelta(goal.total_conversions, previousConversions),
+ rateDelta: pointDelta(goal.conversion_rate * 100, previousRate === null ? null : previousRate * 100, {
+ decimals: RATE_DECIMALS,
+ }),
+ conversionsChange:
+ previousConversions === null ? null : percentChange(goal.total_conversions, previousConversions),
+ rateChange: previousRate === null ? null : (goal.conversion_rate - previousRate) * 100,
+ };
+ });
+}
+
+/** Case-insensitive match on the goal's label, what it matches, and its property filters. */
+export function matchesGoalSearch({ goal, label }: Pick<LedgerRow, "goal" | "label">, search: string): boolean {
+ const query = search.trim().toLowerCase();
+ if (!query) return true;
+
+ const haystack = [
+ label,
+ goalPattern(goal),
+ ...resolvePropertyFilters(goal.config).flatMap(filter => [filter.key, String(filter.value)]),
+ ];
+ return haystack.some(text => !!text && text.toLowerCase().includes(query));
+}
+
+/**
+ * Sorts every row, not a page of them. Rows with no value for the sorted
+ * column (a change without a baseline) go last in either direction; ties fall
+ * back to conversions, then to the goal id so the order never flickers.
+ */
+export function sortLedgerRows(rows: LedgerRow[], sort: LedgerSort): LedgerRow[] {
+ const direction = sort.order === "asc" ? 1 : -1;
+ const tieBreak = (a: LedgerRow, b: LedgerRow) => b.conversions - a.conversions || a.goal.goalId - b.goal.goalId;
+
+ return [...rows].sort((a, b) => {
+ if (sort.key === "name") {
+ return direction * a.label.localeCompare(b.label, undefined, { sensitivity: "base" }) || tieBreak(a, b);
+ }
+
+ const left = a[sort.key];
+ const right = b[sort.key];
+ if (left === null || right === null) {
+ if (left === right) return tieBreak(a, b);
+ return left === null ? 1 : -1;
+ }
+ return direction * (left - right) || tieBreak(a, b);
+ });
+}
+
+/**
+ * The goal whose conversions grew the most against the comparison period, in
+ * percent. Null when nothing grew: a goal needs a baseline to have moved, and
+ * growth that rounds to 0.0% is not a move.
+ */
+export function bestMover(rows: LedgerRow[]): LedgerRow | null {
+ const movers = rows.filter(row => row.conversionsChange !== null && roundTo(row.conversionsChange, 1) > 0);
+ if (movers.length === 0) return null;
+ return sortLedgerRows(movers, { key: "conversionsChange", order: "desc" })[0];
+}
+
+/**
+ * The goal whose conversion rate fell the most, in percentage points. Null
+ * when no rate fell by at least the precision the page prints.
+ */
+export function slippingGoal(rows: LedgerRow[]): LedgerRow | null {
+ const slipping = rows.filter(row => row.rateChange !== null && roundTo(row.rateChange, RATE_DECIMALS) < 0);
+ if (slipping.length === 0) return null;
+ return sortLedgerRows(slipping, { key: "rateChange", order: "asc" })[0];
+}
+
+/**
+ * The path-goal wildcard syntax as an anchored regex: `*` is one path segment,
+ * `**` crosses segments. Mirrors the server's `patternToRegex`
+ * (server/src/api/analytics/utils/utils.ts), which is what a path goal is
+ * counted with; keep the two in step.
+ */
+export function pathPatternToRegex(pattern: string): string {
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
+ const withDoubleStar = escaped.replace(/\*\*/g, "{{DOUBLE_STAR}}");
+ const withSingleStar = withDoubleStar.replace(/\*/g, "[^/]+");
+ return `^${withSingleStar.replace(/{{DOUBLE_STAR}}/g, ".*")}$`;
+}
+
+// The server refuses a regex filter longer than this (getFilterStatement).
+const MAX_REGEX_FILTER_LENGTH = 500;
+
+/**
+ * The filters that select the sessions behind a goal on another page, or null
+ * when the filter set cannot say what the goal says. A pivot built from a
+ * looser filter would list sessions that did not convert, so those goals get
+ * no pivot:
+ * - autocapture goals: there is no filter on the event type
+ * - goals narrowed by URL parameters or event properties
+ */
+export function goalPivotFilters(goal: { goalType: GoalType; config: GoalConfig }): Filter[] | null {
+ if (isAutocaptureTargetType(goal.goalType)) return null;
+ if (resolvePropertyFilters(goal.config).length > 0) return null;
+
+ if (goal.goalType === "event") {
+ const eventName = goal.config.eventName;
+ return eventName ? [{ parameter: "event_name", type: "equals", value: [eventName] }] : null;
+ }
+
+ const pattern = goal.config.pathPattern;
+ if (!pattern) return null;
+ if (!pattern.includes("*")) return [{ parameter: "pathname", type: "equals", value: [pattern] }];
+
+ const regex = pathPatternToRegex(pattern);
+ return regex.length > MAX_REGEX_FILTER_LENGTH ? null : [{ parameter: "pathname", type: "regex", value: [regex] }];
+}
+
+export interface FunnelRef {
+ funnel: SavedFunnel;
+ /** 1-based position of the matching step. */
+ step: number;
+ of: number;
+}
+
+/**
+ * Saved funnels with a step that targets the same thing as the goal: the same
+ * page pattern, the same event, or the same autocapture type and pattern.
+ */
+export function funnelRefs(goal: { goalType: GoalType; config: GoalConfig }, funnels: SavedFunnel[]): FunnelRef[] {
+ const stepType = goal.goalType === "path" ? "page" : goal.goalType;
+ const pattern = goalPattern(goal);
+ if (!pattern && !isAutocaptureTargetType(goal.goalType)) return [];
+
+ return funnels.flatMap(funnel => {
+ const index = funnel.steps.findIndex(step => step.type === stepType && (step.value ?? "") === pattern);
+ return index < 0 ? [] : [{ funnel, step: index + 1, of: funnel.steps.length }];
+ });
+}
+
+/** "4.73%": a 0–1 rate at the page's precision. */
+export const formatRate = (rate: number) => `${(rate * 100).toFixed(RATE_DECIMALS)}%`;
diff --git a/client/src/app/[site]/journeys/components/JourneyControls.tsx b/client/src/app/[site]/journeys/components/JourneyControls.tsx
new file mode 100644
index 000000000..ece7afe34
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/JourneyControls.tsx
@@ -0,0 +1,282 @@
+"use client";
+
+import { ListFilter, Minus, Plus } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { ReactNode, useState } from "react";
+import { ControlButton } from "@/components/site/ControlButton";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { cn, formatter } from "@/lib/utils";
+
+export interface ControlOption<T extends string> {
+ value: T;
+ label: string;
+}
+
+/** A "Label value ▾" control that picks one of a few options. */
+export function OptionControl<T extends string>({
+ icon,
+ label,
+ value,
+ options,
+ onChange,
+}: {
+ icon?: ReactNode;
+ label: string;
+ value: T;
+ options: ControlOption<T>[];
+ onChange: (value: T) => void;
+}) {
+ const selected = options.find(option => option.value === value);
+
+ // Radix hands back a plain string; looking the option up returns it as T.
+ const select = (next: string) => {
+ const option = options.find(candidate => candidate.value === next);
+ if (option) onChange(option.value);
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <ControlButton icon={icon} label={label} value={selected?.label ?? value} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup value={value} onValueChange={select}>
+ {options.map(option => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+/** How many steps deep the paths go: one click, one step, one request. */
+export function StepsStepper({
+ value,
+ onChange,
+ min,
+ max,
+}: {
+ value: number;
+ onChange: (value: number) => void;
+ min: number;
+ max: number;
+}) {
+ const t = useExtracted();
+ const button =
+ "flex h-full w-7 items-center justify-center text-neutral-600 transition-colors hover:bg-neutral-50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-neutral-950 disabled:pointer-events-none disabled:opacity-40 dark:text-neutral-300 dark:hover:bg-neutral-850 dark:focus-visible:ring-neutral-300";
+
+ return (
+ <div
+ role="group"
+ aria-label={t("Steps")}
+ className="inline-flex h-8 items-center overflow-hidden rounded-lg border border-neutral-100 text-xs dark:border-neutral-700"
+ >
+ <span className="pl-2.5 pr-2 text-neutral-500 dark:text-neutral-400">{t("Steps")}</span>
+ <button
+ type="button"
+ aria-label={t("Fewer steps")}
+ disabled={value <= min}
+ onClick={() => onChange(Math.max(min, value - 1))}
+ className={cn(button, "border-l border-neutral-100 dark:border-neutral-700")}
+ >
+ <Minus className="h-3.5 w-3.5" />
+ </button>
+ <span
+ aria-live="polite"
+ className="w-6 text-center font-medium tabular-nums text-neutral-900 dark:text-neutral-100"
+ >
+ {value}
+ </span>
+ <button
+ type="button"
+ aria-label={t("More steps")}
+ disabled={value >= max}
+ onClick={() => onChange(Math.min(max, value + 1))}
+ className={button}
+ >
+ <Plus className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ );
+}
+
+export interface PageSuggestion {
+ value: string;
+ count?: number;
+}
+
+const MAX_SUGGESTIONS = 50;
+const PICKER_ITEM =
+ "flex w-full items-center justify-between gap-3 rounded-md px-2 py-1.5 text-left text-xs hover:bg-neutral-100 focus-visible:bg-neutral-100 focus-visible:outline-none dark:hover:bg-neutral-700 dark:focus-visible:bg-neutral-700";
+
+/**
+ * The body of a page picker: type a page or a pattern, or pick one of the
+ * site's pages. Nothing is applied until a choice is made, so typing does not
+ * refetch on every keystroke.
+ */
+function PagePickerPanel({
+ value,
+ suggestions,
+ onPick,
+}: {
+ value: string;
+ suggestions: PageSuggestion[];
+ onPick: (value: string) => void;
+}) {
+ const t = useExtracted();
+ const [draft, setDraft] = useState(value);
+ const query = draft.trim();
+ const lower = query.toLowerCase();
+ const matches = suggestions
+ .filter(suggestion => suggestion.value.toLowerCase().includes(lower))
+ .slice(0, MAX_SUGGESTIONS);
+ const isListed = suggestions.some(suggestion => suggestion.value === query);
+
+ return (
+ <form
+ className="flex flex-col gap-2"
+ onSubmit={event => {
+ event.preventDefault();
+ onPick(query);
+ }}
+ >
+ <Input
+ autoFocus
+ inputSize="sm"
+ value={draft}
+ onChange={event => setDraft(event.target.value)}
+ placeholder={t("Page or pattern, e.g. /docs/**")}
+ aria-label={t("Page or pattern")}
+ />
+ <div className="-mx-1 max-h-56 overflow-y-auto">
+ {query && !isListed && (
+ <button type="submit" className={PICKER_ITEM}>
+ <span className="truncate">{t('Use "{pattern}"', { pattern: query })}</span>
+ </button>
+ )}
+ {matches.map(suggestion => (
+ <button
+ key={suggestion.value}
+ type="button"
+ onClick={() => onPick(suggestion.value)}
+ className={cn(PICKER_ITEM, suggestion.value === value && "bg-neutral-100 dark:bg-neutral-700")}
+ >
+ <span className="truncate">{suggestion.value}</span>
+ {suggestion.count !== undefined && (
+ <span className="shrink-0 tabular-nums text-neutral-500 dark:text-neutral-400">
+ {formatter(suggestion.count)}
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+ <div className="flex items-center justify-between gap-3 border-t border-neutral-100 pt-2 dark:border-neutral-700">
+ <span className="text-[11px] leading-snug text-neutral-500 dark:text-neutral-400">
+ {t("* matches one path segment, ** matches several")}
+ </span>
+ {value && (
+ <Button type="button" variant="ghost" size="xs" onClick={() => onPick("")}>
+ {t("Clear")}
+ </Button>
+ )}
+ </div>
+ </form>
+ );
+}
+
+interface PagePickerProps {
+ /** The applied page or pattern; empty for any page. */
+ value: string;
+ onChange: (value: string) => void;
+ suggestions: PageSuggestion[];
+}
+
+/** A "Label page ▾" control: where the paths start, or where they end. */
+export function PagePicker({
+ icon,
+ label,
+ value,
+ onChange,
+ suggestions,
+}: PagePickerProps & { icon?: ReactNode; label: string }) {
+ const t = useExtracted();
+ const [open, setOpen] = useState(false);
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <ControlButton icon={icon} label={label} value={value || t("Any page")} className="max-w-[260px]" />
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-72 p-2">
+ <PagePickerPanel
+ value={value}
+ suggestions={suggestions}
+ onPick={next => {
+ onChange(next);
+ setOpen(false);
+ }}
+ />
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+/** The filter button in a step's column header: the same picker, for that one step. */
+export function StepFilterButton({ step, value, onChange, suggestions }: PagePickerProps & { step: number }) {
+ const t = useExtracted();
+ const [open, setOpen] = useState(false);
+ const label = t("Filter step {number} by page", { number: String(step) });
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ {value ? (
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ aria-label={label}
+ title={label}
+ className="max-w-[140px] gap-1 font-normal"
+ >
+ <ListFilter className="h-3.5 w-3.5" />
+ <span className="truncate">{value}</span>
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ aria-label={label}
+ title={label}
+ className="h-5 w-5 px-0 text-neutral-500 dark:text-neutral-400"
+ >
+ <ListFilter className="h-3.5 w-3.5" />
+ </Button>
+ )}
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-72 p-2">
+ <PagePickerPanel
+ value={value}
+ suggestions={suggestions}
+ onPick={next => {
+ onChange(next);
+ setOpen(false);
+ }}
+ />
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/client/src/app/[site]/journeys/components/JourneyStats.tsx b/client/src/app/[site]/journeys/components/JourneyStats.tsx
new file mode 100644
index 000000000..c43837606
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/JourneyStats.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import { Footprints, LogIn, LogOut, Split, Target } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { JourneySummary } from "@/api/analytics/endpoints";
+import { useJourneyContext } from "@/api/analytics/hooks/useGetJourneys";
+import { StatBand } from "@/components/site/StatBand";
+import { percentDelta, pointDelta } from "@/lib/delta";
+
+const share = (part: number, whole: number) => `${((part / whole) * 100).toFixed(1)}%`;
+
+export interface JourneyStatsProps {
+ summary: JourneySummary | undefined;
+ /** The comparison period's figures; undefined while it is off or loading. */
+ previous: JourneySummary | undefined;
+ isLoading: boolean;
+ /** The selected goal's name; null leaves the reach cell out. */
+ goalName: string | null;
+}
+
+/** The figures that open the journeys page: how many sessions have a path at all, and where paths start, end and convert. */
+export function JourneyStats({ summary, previous, isLoading, goalName }: JourneyStatsProps) {
+ const t = useExtracted();
+ const context = useJourneyContext();
+
+ const sessions = summary?.sessions ?? 0;
+ const reach = summary && summary.conversions !== null && sessions > 0 ? (summary.conversions / sessions) * 100 : null;
+ const previousReach =
+ previous && previous.conversions !== null && previous.sessions > 0
+ ? (previous.conversions / previous.sessions) * 100
+ : null;
+
+ return (
+ <StatBand
+ isLoading={isLoading}
+ cells={[
+ {
+ id: "multi-page",
+ icon: <Split className="h-3 w-3" />,
+ label: t("Multi-page sessions"),
+ value: sessions.toLocaleString(),
+ delta: percentDelta(summary?.sessions, previous?.sessions),
+ sub:
+ context.sessions && sessions <= context.sessions
+ ? t("{percent} of {total} sessions", {
+ percent: share(sessions, context.sessions),
+ total: context.sessions.toLocaleString(),
+ })
+ : "",
+ },
+ {
+ id: "path-length",
+ icon: <Footprints className="h-3 w-3" />,
+ label: t("Avg path length"),
+ value: sessions > 0 ? t("{count} pages", { count: (summary?.avgPathLength ?? 0).toFixed(1) }) : "–",
+ sub:
+ previous && previous.sessions > 0
+ ? t("{count} in the comparison period", { count: previous.avgPathLength.toFixed(2) })
+ : "",
+ },
+ {
+ id: "top-entry",
+ icon: <LogIn className="h-3 w-3" />,
+ label: t("Top entry page"),
+ value: context.topEntry?.value ?? "–",
+ title: context.topEntry?.value,
+ isLoading: context.isLoading,
+ sub: context.topEntry
+ ? t("{count} entries · {percent} of sessions", {
+ count: context.topEntry.count.toLocaleString(),
+ percent: `${context.topEntry.percentage.toFixed(1)}%`,
+ })
+ : "",
+ },
+ {
+ id: "top-exit",
+ icon: <LogOut className="h-3 w-3" />,
+ label: t("Top exit after 2+ pages"),
+ value: summary?.topExit?.page ?? "–",
+ title: summary?.topExit?.page,
+ sub: summary?.topExit
+ ? t("{percent} of these sessions end here", { percent: share(summary.topExit.sessions, sessions) })
+ : "",
+ },
+ goalName !== null && {
+ id: "goal-reach",
+ icon: <Target className="h-3 w-3" />,
+ label: t("Reach {goal}", { goal: goalName }),
+ value: reach === null ? "–" : `${reach.toFixed(1)}%`,
+ delta: pointDelta(reach, previousReach),
+ sub:
+ summary && summary.conversions !== null
+ ? t("{count} of {total} sessions", {
+ count: summary.conversions.toLocaleString(),
+ total: sessions.toLocaleString(),
+ })
+ : "",
+ },
+ ]}
+ />
+ );
+}
diff --git a/client/src/app/[site]/journeys/components/PathActions.tsx b/client/src/app/[site]/journeys/components/PathActions.tsx
new file mode 100644
index 000000000..1997b137a
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/PathActions.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+import { Funnel, Rewind, Video } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { PivotActions, PivotButton } from "@/components/site/PivotActions";
+import { Button } from "@/components/ui/button";
+import { useReplayAvailable } from "@/hooks/useReplayAvailable";
+
+/** What a path can lead to. The page owns the sheet and the dialog these open. */
+export interface PathActionHandlers {
+ /** Lists the sessions that took exactly this path; `replaysOnly` keeps those with a replay. */
+ openSessions: (path: string[], replaysOnly: boolean) => void;
+ /** Absent when the viewer cannot create funnels. */
+ saveAsFunnel?: (path: string[]) => void;
+}
+
+export interface PathActionsProps {
+ path: string[];
+ handlers: PathActionHandlers;
+ /** False draws icons only, for table rows. */
+ showLabels?: boolean;
+ /** Draws "Save as funnel" as the solid primary action instead of a quiet pivot. */
+ primaryFunnel?: boolean;
+ /** Leaves "Save as funnel" out, where the surrounding text is not about one whole path. */
+ hideFunnel?: boolean;
+ className?: string;
+}
+
+/**
+ * The pivots of one path. A path is not expressible as filters, so these do
+ * not link to the Sessions or Replay pages: they open the path's own sessions
+ * in place.
+ */
+export function PathActions({
+ path,
+ handlers,
+ showLabels = true,
+ primaryFunnel = false,
+ hideFunnel = false,
+ className,
+}: PathActionsProps) {
+ const t = useExtracted();
+ const replayAvailable = useReplayAvailable();
+ const { saveAsFunnel } = handlers;
+
+ return (
+ // No standard pivots: the wrapper is used for its layout and for keeping clicks from a clickable row.
+ <PivotActions actions={[]} className={className}>
+ <PivotButton
+ icon={<Rewind />}
+ label={t("Sessions")}
+ showLabel={showLabels}
+ onClick={() => handlers.openSessions(path, false)}
+ />
+ {replayAvailable && (
+ // Desktop only, like the sidebar's Replay item.
+ <PivotButton
+ icon={<Video />}
+ label={t("Replays")}
+ showLabel={showLabels}
+ className="hidden md:inline-flex"
+ onClick={() => handlers.openSessions(path, true)}
+ />
+ )}
+ {/* A funnel needs two steps; grouped by section, a path can be a single one. */}
+ {saveAsFunnel &&
+ !hideFunnel &&
+ path.length >= 2 &&
+ (primaryFunnel ? (
+ <Button type="button" variant="accent" size="xs" className="ml-auto gap-1" onClick={() => saveAsFunnel(path)}>
+ <Funnel />
+ {t("Save as funnel")}
+ </Button>
+ ) : (
+ <PivotButton
+ icon={<Funnel />}
+ label={t("Save as funnel")}
+ showLabel={showLabels}
+ onClick={() => saveAsFunnel(path)}
+ />
+ ))}
+ </PivotActions>
+ );
+}
diff --git a/client/src/app/[site]/journeys/components/PathChips.tsx b/client/src/app/[site]/journeys/components/PathChips.tsx
new file mode 100644
index 000000000..d2acf2570
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/PathChips.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+import { ChevronRight } from "lucide-react";
+import Link from "next/link";
+import { Fragment, MouseEvent } from "react";
+import { cn } from "@/lib/utils";
+
+const CHIP =
+ "inline-flex max-w-[240px] items-center rounded-md border border-neutral-150 bg-neutral-50 px-1.5 py-0.5 text-xs font-medium text-neutral-800 dark:border-neutral-800 dark:bg-neutral-850 dark:text-neutral-200";
+
+// A chip inside a clickable row must not also trigger the row.
+const stopClick = (event: MouseEvent) => event.stopPropagation();
+
+export interface PathChipsProps {
+ path: string[];
+ /** Makes each page a link; return undefined for a step that is not one page. */
+ pageHref?: (page: string) => string | undefined;
+ className?: string;
+ chipClassName?: string;
+}
+
+/** A path as a row of page chips: / › /pricing › /signup. */
+export function PathChips({ path, pageHref, className, chipClassName }: PathChipsProps) {
+ return (
+ <span className={cn("inline-flex min-w-0 flex-wrap items-center gap-1", className)}>
+ {path.map((page, index) => {
+ const href = pageHref?.(page);
+ return (
+ <Fragment key={index}>
+ {index > 0 && (
+ <ChevronRight className="h-3 w-3 shrink-0 text-neutral-400 dark:text-neutral-500" aria-hidden="true" />
+ )}
+ {href ? (
+ <Link
+ href={href}
+ prefetch={false}
+ title={page}
+ onClick={stopClick}
+ className={cn(CHIP, "hover:border-neutral-300 dark:hover:border-neutral-700", chipClassName)}
+ >
+ <span className="truncate">{page}</span>
+ </Link>
+ ) : (
+ <span title={page} className={cn(CHIP, chipClassName)}>
+ <span className="truncate">{page}</span>
+ </span>
+ )}
+ </Fragment>
+ );
+ })}
+ </span>
+ );
+}
diff --git a/client/src/app/[site]/journeys/components/PathSessionsSheet.tsx b/client/src/app/[site]/journeys/components/PathSessionsSheet.tsx
new file mode 100644
index 000000000..a2db9e2d6
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/PathSessionsSheet.tsx
@@ -0,0 +1,123 @@
+"use client";
+
+import { useExtracted } from "next-intl";
+import { useState } from "react";
+import { JourneyShape, useJourneySessions } from "@/api/analytics/hooks/useGetJourneys";
+import { ErrorState } from "@/components/ErrorState";
+import { SegmentedControl } from "@/components/interior/segmented-control";
+import { SessionsList } from "@/components/Sessions/SessionsList";
+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
+import { useReplayAvailable } from "@/hooks/useReplayAvailable";
+import { PathChips } from "./PathChips";
+
+const PAGE_SIZE = 25;
+
+export interface PathSessionsTarget {
+ path: string[];
+ /** How many sessions the path's row counts, shown next to the title. */
+ count?: number;
+ replaysOnly: boolean;
+}
+
+type ReplayFilter = "all" | "replays";
+
+function PathSessions({ target, shape }: { target: PathSessionsTarget; shape: JourneyShape }) {
+ const t = useExtracted();
+ const replayAvailable = useReplayAvailable();
+ const [replayFilter, setReplayFilter] = useState<ReplayFilter>(target.replaysOnly ? "replays" : "all");
+ const [page, setPage] = useState(1);
+ // Only reachable where replay is available: the Replays pivot and the toggle below are hidden otherwise.
+ const replaysOnly = replayFilter === "replays";
+
+ // One row more than a page: its presence is how the list knows there is a next page.
+ const { data, isLoading, error, refetch } = useJourneySessions({
+ ...shape,
+ path: target.path,
+ replaysOnly,
+ page,
+ limit: PAGE_SIZE + 1,
+ });
+ const sessions = data ?? [];
+
+ return (
+ <>
+ <SheetHeader className="gap-2 space-y-0 border-b border-neutral-100 px-4 py-3 pr-12 text-left dark:border-neutral-800">
+ <SheetTitle className="text-base">
+ {target.count === undefined
+ ? t("Sessions on this path")
+ : t("{count} sessions on this path", { count: target.count.toLocaleString() })}
+ </SheetTitle>
+ <SheetDescription asChild>
+ <div>
+ <PathChips path={target.path} />
+ </div>
+ </SheetDescription>
+ </SheetHeader>
+ <div className="min-h-0 flex-1 overflow-y-auto p-3 md:p-4">
+ {error ? (
+ <ErrorState title={t("Failed to load sessions")} message={error.message} refetch={refetch} />
+ ) : (
+ <SessionsList
+ sessions={sessions.slice(0, PAGE_SIZE)}
+ isLoading={isLoading}
+ page={page}
+ onPageChange={setPage}
+ hasNextPage={sessions.length > PAGE_SIZE}
+ hasPrevPage={page > 1}
+ pageSize={PAGE_SIZE}
+ emptyMessage={
+ replaysOnly
+ ? t("None of the sessions on this path has a replay.")
+ : t("No sessions took this path in the selected period.")
+ }
+ headerElement={
+ replayAvailable || replaysOnly ? (
+ <SegmentedControl
+ size="sm"
+ aria-label={t("Which sessions to list")}
+ value={replayFilter}
+ onValueChange={value => {
+ setReplayFilter(value);
+ setPage(1);
+ }}
+ options={[
+ { value: "all", label: t("All sessions") },
+ { value: "replays", label: t("With a replay") },
+ ]}
+ />
+ ) : undefined
+ }
+ />
+ )}
+ </div>
+ </>
+ );
+}
+
+/**
+ * The sessions behind one path, listed in place. A path cannot be written as
+ * filters, so this is where its Sessions and Replays pivots lead instead of the
+ * Sessions and Replay pages.
+ */
+export function PathSessionsSheet({
+ target,
+ shape,
+ onClose,
+}: {
+ target: PathSessionsTarget | null;
+ /** The options the path was fetched with; the server derives the sessions from the same ones. */
+ shape: JourneyShape;
+ onClose: () => void;
+}) {
+ return (
+ <Sheet open={target !== null} onOpenChange={open => !open && onClose()}>
+ <SheetContent
+ side="right"
+ className="flex w-full flex-col gap-0 border-neutral-150 p-0 sm:max-w-3xl dark:border-neutral-800 dark:bg-neutral-900"
+ >
+ {/* Keyed by path so the page and the replay filter start over for another path. */}
+ {target && <PathSessions key={JSON.stringify(target)} target={target} shape={shape} />}
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/client/src/app/[site]/journeys/components/PinnedPath.tsx b/client/src/app/[site]/journeys/components/PinnedPath.tsx
new file mode 100644
index 000000000..9ea38bebd
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/PinnedPath.tsx
@@ -0,0 +1,140 @@
+"use client";
+
+import { Pin, X } from "lucide-react";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { ReactNode } from "react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { formatShare as percent, JourneyRow, pathContinuation } from "./journeyUtils";
+import { PathActionHandlers, PathActions } from "./PathActions";
+import { PathChips } from "./PathChips";
+
+export interface PinnedPathProps {
+ journey: JourneyRow;
+ /** The shown paths: the step-by-step figures are sums over them. */
+ journeys: JourneyRow[];
+ /** The selected goal and how many of all multi-page sessions reach it (0–1); null without a goal. */
+ goal: { name: string; overallRate: number | null; href: string } | null;
+ pageHref: (page: string) => string | undefined;
+ handlers: PathActionHandlers;
+ onUnpin: () => void;
+}
+
+/** The pinned path in detail: its size, its goal reach, and how sessions thin out page by page. */
+export function PinnedPath({ journey, journeys, goal, pageHref, handlers, onUnpin }: PinnedPathProps) {
+ const t = useExtracted();
+ const continuation = pathContinuation(journeys, journey.path);
+ const first = continuation[0]?.sessions ?? 0;
+ const reach =
+ goal && journey.conversions !== undefined && journey.count > 0 ? journey.conversions / journey.count : null;
+ const goalLink = (chunks: ReactNode) => (
+ <Link
+ href={goal?.href ?? ""}
+ prefetch={false}
+ className="text-neutral-700 underline decoration-neutral-400 underline-offset-2 dark:text-neutral-200 dark:decoration-neutral-500"
+ >
+ {chunks}
+ </Link>
+ );
+
+ return (
+ <div className="rounded-md border border-neutral-100 bg-white p-3 text-neutral-950 shadow-[0_12px_32px_-8px_rgba(0,0,0,0.18),0_1px_2px_rgba(0,0,0,0.06)] dark:border-transparent dark:bg-neutral-800 dark:text-neutral-50 dark:shadow-[0_12px_32px_-8px_rgba(0,0,0,0.65),0_1px_2px_rgba(0,0,0,0.4)]">
+ <div className="flex items-start justify-between gap-2">
+ <PathChips
+ path={journey.path}
+ pageHref={pageHref}
+ chipClassName="dark:border-neutral-700 dark:bg-neutral-750 dark:hover:border-neutral-600"
+ />
+ <div className="flex shrink-0 items-center gap-1">
+ <Badge variant="outline" className="dark:border-neutral-600">
+ <Pin className="mr-1 h-3 w-3" />
+ {t("Pinned")}
+ </Badge>
+ <Button
+ type="button"
+ variant="ghost"
+ size="smIcon"
+ className="h-6 w-6 dark:hover:bg-neutral-700"
+ aria-label={t("Unpin path")}
+ onClick={onUnpin}
+ >
+ <X />
+ </Button>
+ </div>
+ </div>
+
+ <div className="mt-2.5 flex flex-wrap gap-x-6 gap-y-2 text-xs text-neutral-500 dark:text-neutral-400">
+ <div>
+ <div className="text-sm font-semibold tabular-nums text-neutral-900 dark:text-neutral-50">
+ {journey.count.toLocaleString()}
+ </div>
+ <div>{t("sessions")}</div>
+ </div>
+ <div>
+ <div className="text-sm font-semibold tabular-nums text-neutral-900 dark:text-neutral-50">
+ {`${journey.percentage.toFixed(1)}%`}
+ </div>
+ <div>{t("of multi-page sessions")}</div>
+ </div>
+ {goal && reach !== null && (
+ <div className="min-w-0">
+ <div className="text-sm font-semibold tabular-nums text-neutral-900 dark:text-neutral-50">
+ {percent(reach)}
+ </div>
+ <div>
+ {goal.overallRate === null
+ ? t.rich("reach <goal>{name}</goal>", { name: goal.name, goal: goalLink })
+ : t.rich("reach <goal>{name}</goal>, {overall} across all paths", {
+ name: goal.name,
+ overall: percent(goal.overallRate),
+ goal: goalLink,
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+
+ <div className="mt-2 border-t border-neutral-100 pt-1.5 dark:border-neutral-700">
+ <div className="grid grid-cols-[minmax(0,1.5fr)_minmax(32px,1fr)_56px_64px] gap-2 pb-0.5 text-[11px] text-neutral-500 dark:text-neutral-400">
+ <span>{t("Step")}</span>
+ <span />
+ <span className="text-right">{t("Sessions")}</span>
+ <span className="text-right">{t("Continued")}</span>
+ </div>
+ {continuation.map((step, index) => (
+ <div
+ key={index}
+ className="grid grid-cols-[minmax(0,1.5fr)_minmax(32px,1fr)_56px_64px] items-center gap-2 py-1 text-xs"
+ >
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className="w-3 shrink-0 tabular-nums text-neutral-500 dark:text-neutral-400">{index + 1}</span>
+ <span className="truncate font-medium text-neutral-900 dark:text-neutral-100" title={step.page}>
+ {step.page}
+ </span>
+ </div>
+ <div className="h-1.5 rounded-full bg-neutral-100 dark:bg-neutral-700">
+ <div
+ className="h-full rounded-full bg-dataviz"
+ style={{ width: `${first > 0 ? Math.max(2, (step.sessions / first) * 100) : 0}%` }}
+ />
+ </div>
+ <div className="text-right tabular-nums text-neutral-900 dark:text-neutral-100">
+ {step.sessions.toLocaleString()}
+ </div>
+ <div className="text-right tabular-nums text-neutral-500 dark:text-neutral-400">
+ {step.continued === null ? "" : percent(step.continued)}
+ </div>
+ </div>
+ ))}
+ <p className="pt-1 text-[11px] text-neutral-500 dark:text-neutral-400">
+ {t("Sessions on the paths shown that got this far along the path.")}
+ </p>
+ </div>
+
+ <div className="mt-1.5 border-t border-neutral-100 pt-2 dark:border-neutral-700">
+ <PathActions path={journey.path} handlers={handlers} primaryFunnel />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/journeys/components/SankeyDiagram.test.tsx b/client/src/app/[site]/journeys/components/SankeyDiagram.test.tsx
new file mode 100644
index 000000000..534923ac9
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/SankeyDiagram.test.tsx
@@ -0,0 +1,192 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { SankeyDiagram } from "./SankeyDiagram";
+
+const mocks = vi.hoisted(() => ({ push: vi.fn(), width: 1104 as number | null }));
+
+vi.mock("next-intl", () => ({
+ useExtracted:
+ () =>
+ (message: string, values: Record<string, string> = {}) =>
+ message.replace(/\{(\w+)\}/g, (_, key: string) => values[key] ?? ""),
+}));
+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: mocks.push }) }));
+// jsdom lays nothing out: hand the diagram its width, and the overlay a height.
+vi.mock("@uidotdev/usehooks", () => ({ useMeasure: () => [() => {}, { width: mocks.width, height: 200 }] }));
+
+// 1,000 multi-page sessions; these paths cover 600.
+const journey = (path: string[], count: number) => ({ path, count, percentage: count / 10 });
+const JOURNEYS = [
+ journey(["/", "/pricing"], 300),
+ journey(["/", "/pricing", "/signup"], 150),
+ journey(["/", "/demo", "/pricing", "/signup"], 100),
+ journey(["/docs", "/pricing"], 50),
+];
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ mocks.width = 1104;
+});
+
+const tooltip = () => screen.getByRole("tooltip").textContent;
+const label = (text: string) => screen.getAllByText(text)[0];
+
+describe("SankeyDiagram", () => {
+ it("renders with the props the user profile passes, and nothing clickable", () => {
+ const { container } = render(<SankeyDiagram journeys={JOURNEYS} steps={4} maxJourneys={50} domain="example.com" />);
+
+ expect(screen.getByRole("img").getAttribute("aria-label")).toBe(
+ "Sankey diagram of the top 4 paths from session start, 4 steps deep"
+ );
+ expect(screen.getAllByText("/pricing")).toHaveLength(2);
+ expect(container.querySelector(".cursor-pointer")).toBeNull();
+ // A page name opens the page itself, as before.
+ const link = label("/demo").closest("a");
+ expect(link?.getAttribute("href")).toBe("https://example.com/demo");
+ expect(link?.getAttribute("target")).toBe("_blank");
+ });
+
+ it("labels each page with its sessions and the share that ended there", () => {
+ render(<SankeyDiagram journeys={JOURNEYS} steps={4} maxJourneys={50} domain="example.com" />);
+
+ expect(screen.getByText("550 sessions")).toBeTruthy();
+ expect(screen.getByText("500 · 70% end here")).toBeTruthy();
+ // /demo at step 2 and /pricing at step 3: everyone on the shown paths went on.
+ expect(screen.getAllByText("100 · all continue")).toHaveLength(2);
+ // The last step may have been cut short: a count, no exit share.
+ expect(screen.getByText("100")).toBeTruthy();
+ });
+
+ it("leaves exit shares out when paths are cut at an end page", () => {
+ render(<SankeyDiagram journeys={JOURNEYS} steps={4} maxJourneys={50} domain="example.com" exitsKnown={false} />);
+
+ expect(screen.queryByText(/end here/)).toBeNull();
+ expect(screen.queryByText(/all continue/)).toBeNull();
+ });
+
+ it("draws only the first maxJourneys paths", () => {
+ render(<SankeyDiagram journeys={JOURNEYS} steps={4} maxJourneys={1} domain="example.com" />);
+
+ expect(screen.getByText("300 sessions")).toBeTruthy();
+ expect(screen.queryByText("/demo")).toBeNull();
+ });
+
+ it("shows a page's own share in its tooltip, not that of the first path through it", () => {
+ render(<SankeyDiagram journeys={JOURNEYS} steps={4} maxJourneys={50} domain="example.com" />);
+
+ fireEvent.mouseEnter(label("/pricing").closest("g")!);
+ expect(tooltip()).toContain("500 sessions · 50.0% of sessions with 2+ pages");
+ expect(tooltip()).toContain("350 ended the session here (70%)");
+ });
+
+ it("shows a band's share of the page it leaves, not of all bands", () => {
+ const { container } = render(<SankeyDiagram journeys={JOURNEYS} steps={4} maxJourneys={50} domain="example.com" />);
+
+ // "/" → "/pricing" is the first band: 450 of the 550 sessions on "/".
+ fireEvent.mouseEnter(container.querySelector('path[stroke="transparent"]')!);
+ expect(tooltip()).toContain("450 sessions · 81.8% of those on / at step 1");
+ });
+
+ it("fades everything off the hovered path", () => {
+ const { container } = render(<SankeyDiagram journeys={JOURNEYS} steps={4} maxJourneys={50} domain="example.com" />);
+ const bands = () =>
+ [...container.querySelectorAll('path:not([stroke="transparent"])')].map(band => band.getAttribute("opacity"));
+
+ expect(new Set(bands())).toEqual(new Set(["0.2"]));
+ fireEvent.mouseEnter(label("/demo").closest("g")!);
+ // / → /demo → /pricing → /signup stays; the three other bands fade.
+ expect(bands().filter(opacity => opacity === "0.45")).toHaveLength(3);
+ expect(bands().filter(opacity => opacity === "0.07")).toHaveLength(3);
+ });
+
+ it("pins the largest path through a clicked bar or band", () => {
+ const onPinPath = vi.fn();
+ const { container } = render(
+ <SankeyDiagram journeys={JOURNEYS} steps={4} maxJourneys={50} domain="example.com" onPinPath={onPinPath} />
+ );
+
+ fireEvent.click(container.querySelector('path[stroke="transparent"]')!);
+ expect(onPinPath).toHaveBeenLastCalledWith(["/", "/pricing"]);
+
+ fireEvent.click(label("/demo").closest("g")!.querySelector("rect")!);
+ expect(onPinPath).toHaveBeenLastCalledWith(["/", "/demo", "/pricing", "/signup"]);
+ });
+
+ it("draws the pinned path at full strength over faded bands", () => {
+ const { container } = render(
+ <SankeyDiagram
+ journeys={JOURNEYS}
+ steps={4}
+ maxJourneys={50}
+ domain="example.com"
+ pinnedPath={["/", "/demo", "/pricing", "/signup"]}
+ />
+ );
+ const opacities = [...container.querySelectorAll('path:not([stroke="transparent"])')].map(band =>
+ band.getAttribute("opacity")
+ );
+
+ expect(opacities.filter(opacity => opacity === "0.9")).toHaveLength(3);
+ expect(opacities.filter(opacity => opacity === "0.14")).toHaveLength(6);
+ });
+
+ it("sends page names to the app page it is given, and leaves non-pages unlinked", () => {
+ render(
+ <SankeyDiagram
+ journeys={[journey(["/", "/docs/**"], 10)]}
+ steps={2}
+ maxJourneys={50}
+ domain="example.com"
+ pageHref={page => (page.includes("*") ? undefined : `/1/pages?page=${page}`)}
+ />
+ );
+
+ expect(label("/docs/**").closest("a")).toBeNull();
+ const link = label("/").closest("a")!;
+ expect(link.getAttribute("href")).toBe("/1/pages?page=/");
+ fireEvent.click(link);
+ expect(mocks.push).toHaveBeenCalledWith("/1/pages?page=/");
+ });
+
+ it("draws a header over each step and docks the overlay when there is room", () => {
+ render(
+ <SankeyDiagram
+ journeys={JOURNEYS}
+ steps={4}
+ maxJourneys={50}
+ domain="example.com"
+ renderStepHeader={({ index, sessions, previousSessions }) => (
+ <span>{`step ${index + 1}: ${sessions} after ${previousSessions}`}</span>
+ )}
+ overlay={<div>pinned details</div>}
+ />
+ );
+
+ expect(screen.getByText("step 1: 600 after null")).toBeTruthy();
+ expect(screen.getByText("step 3: 250 after 600")).toBeTruthy();
+ expect(screen.getByText("pinned details").parentElement?.className).toContain("absolute");
+ });
+
+ it("puts the overlay below a diagram too narrow to dock it", () => {
+ mocks.width = 360;
+ render(
+ <SankeyDiagram
+ journeys={JOURNEYS}
+ steps={4}
+ maxJourneys={50}
+ domain="example.com"
+ overlay={<div>pinned details</div>}
+ />
+ );
+
+ expect(screen.getByText("pinned details").parentElement?.className).not.toContain("absolute");
+ });
+
+ it("draws nothing until it knows its width", () => {
+ mocks.width = null;
+ render(<SankeyDiagram journeys={JOURNEYS} steps={4} maxJourneys={50} domain="example.com" />);
+
+ expect(screen.queryByRole("img")).toBeNull();
+ });
+});
diff --git a/client/src/app/[site]/journeys/components/SankeyDiagram.tsx b/client/src/app/[site]/journeys/components/SankeyDiagram.tsx
index 4b9f93f9e..a84a72500 100644
--- a/client/src/app/[site]/journeys/components/SankeyDiagram.tsx
+++ b/client/src/app/[site]/journeys/components/SankeyDiagram.tsx
@@ -1,12 +1,24 @@
"use client";
-import * as d3 from "d3";
-import { useTheme } from "next-themes";
-import { useEffect, useRef } from "react";
-
-const MIN_LINK_HEIGHT = 0;
-const MAX_LINK_HEIGHT = 56;
-const MIN_NODE_HEIGHT = 2;
+import { useMeasure } from "@uidotdev/usehooks";
+import { ArrowRight } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { useRouter } from "next/navigation";
+import { MouseEvent, ReactNode, useMemo, useRef, useState } from "react";
+import { cn } from "@/lib/utils";
+import {
+ buildSankeyGraph,
+ connectedLinkIds,
+ formatShare,
+ LaidOutLink,
+ LaidOutNode,
+ layoutSankey,
+ linkId,
+ NODE_WIDTH,
+ nodeId,
+ pathKey,
+ truncateMiddle,
+} from "./journeyUtils";
interface Journey {
path: string[];
@@ -14,514 +26,444 @@ interface Journey {
percentage: number;
}
+export interface SankeyStepHeader {
+ /** Zero-based step. */
+ index: number;
+ /** Sessions on the shown paths at this step. */
+ sessions: number;
+ /** The same for the step before; null on the first step. */
+ previousSessions: number | null;
+ /** Horizontal room the header has before the next column starts. */
+ width: number;
+}
+
interface SankeyDiagramProps {
journeys: Journey[];
steps: number;
maxJourneys: number;
domain: string;
+ /** Drawn at full strength through the diagram, the rest faded. Must be one of `journeys`. */
+ pinnedPath?: string[] | null;
+ /** Makes bars and bands clickable: called with the largest shown path through the one clicked. */
+ onPinPath?: (path: string[]) => void;
+ /** False when paths are cut at an end page rather than where the session ended: no exit shares. */
+ exitsKnown?: boolean;
+ /** Drawn above each column, aligned with it. */
+ renderStepHeader?: (step: SankeyStepHeader) => ReactNode;
+ /**
+ * Where a page name leads, inside the app; `undefined` for a name that is
+ * not a page. Without this prop a name opens the page itself in a new tab.
+ */
+ pageHref?: (page: string) => string | undefined;
+ /** Docked under the right-hand columns, or below the diagram when it is narrow. */
+ overlay?: ReactNode;
}
-export function SankeyDiagram({ journeys, steps, maxJourneys, domain }: SankeyDiagramProps) {
- const svgRef = useRef<SVGSVGElement>(null);
- const { resolvedTheme } = useTheme();
-
- useEffect(() => {
- if (!journeys || !svgRef.current || !domain) return;
-
- // Define theme-based colors
- const isDark = resolvedTheme === "dark";
- const linkColor = isDark ? "hsl(var(--neutral-500))" : "hsl(var(--neutral-400))";
- const pathTextColor = isDark ? "white" : "hsl(var(--neutral-900))";
-
- const svg = d3.select(svgRef.current);
- svg.selectAll("*").remove();
-
- const containerWidth = svgRef.current.parentElement?.clientWidth || 1000;
-
- // Build nodes and links
- const nodes: any[] = [];
- const links: any[] = [];
-
- journeys.slice(0, maxJourneys).forEach(journey => {
- for (let i = 0; i < journey.path.length; i++) {
- const stepName = journey.path[i];
- const stepKey = `${i}_${stepName}`;
-
- if (!nodes.find(n => n.id === stepKey)) {
- nodes.push({
- id: stepKey,
- name: stepName,
- step: i,
- incomingLinks: [],
- outgoingLinks: [],
- });
- }
-
- if (i < journey.path.length - 1) {
- const sourceKey = stepKey;
- const targetKey = `${i + 1}_${journey.path[i + 1]}`;
-
- const existingLink = links.find(l => l.source === sourceKey && l.target === targetKey);
-
- if (existingLink) {
- existingLink.value += journey.count;
- } else {
- links.push({
- source: sourceKey,
- target: targetKey,
- value: journey.count,
- });
- }
- }
- }
- });
-
- // Group nodes by step
- const nodesByStep = d3.group(nodes, d => d.step);
-
- // Track incoming and outgoing links for each node
- links.forEach(link => {
- const sourceNode = nodes.find(n => n.id === link.source);
- const targetNode = nodes.find(n => n.id === link.target);
-
- if (sourceNode) sourceNode.outgoingLinks.push(link);
- if (targetNode) targetNode.incomingLinks.push(link);
- });
-
- // Calculate node heights and metadata first (before positioning)
- const maxLinkValue = d3.max(links, link => link.value) || 1;
- const linkWidthScale = d3.scaleLinear().domain([0, maxLinkValue]).range([MIN_LINK_HEIGHT, MAX_LINK_HEIGHT]);
-
- nodes.forEach(node => {
- const incomingValue = node.incomingLinks.reduce((sum: number, link: any) => sum + link.value, 0);
- const outgoingValue = node.outgoingLinks.reduce((sum: number, link: any) => sum + link.value, 0);
- const maxValue = Math.max(incomingValue, outgoingValue);
-
- // Apply minimum height to nodes (but not to links/connections)
- node.height = Math.max(linkWidthScale(maxValue), MIN_NODE_HEIGHT);
- node.count = node.step === 0 ? outgoingValue : incomingValue;
-
- const matchingJourney = journeys.find(journey => journey.path[node.step] === node.name);
- node.percentage = matchingJourney ? matchingJourney.percentage : 0;
- });
-
- // Calculate dimensions based on actual node heights
- const nodeWidth = 30;
- const width = containerWidth;
- const stepWidth = width / steps;
- const stepSpacing = stepWidth - nodeWidth;
- const nodeGap = 10;
- const minHeight = 160;
- const verticalPadding = 6;
-
- // Calculate the total height needed for each step column
- const stepHeights = Array.from(nodesByStep.values()).map(stepNodes => {
- return stepNodes.reduce((sum, node) => sum + node.height, 0) + (stepNodes.length - 1) * nodeGap;
- });
- const maxStepHeight = Math.max(...stepHeights);
- const height = Math.max(minHeight, maxStepHeight + verticalPadding * 2);
-
- const margin = { top: 0, right: 0, bottom: verticalPadding, left: 0 };
-
- const g = svg
- .attr("width", width)
- .attr("height", height)
- .append("g")
- .attr("transform", `translate(${margin.left},${margin.top})`);
-
- // Position nodes - align from top so first node of each step is at same height
- nodesByStep.forEach((stepNodes, step) => {
- const stepX = step * stepWidth;
- let currentY = 0;
-
- stepNodes.forEach(node => {
- node.x = stepX;
- // Position node center based on accumulated height
- node.y = currentY + node.height / 2;
- currentY += node.height + nodeGap;
- });
- });
-
- // Calculate link positions - stack links within each node, aligned to top
- nodes.forEach(node => {
- node.incomingLinks.sort((a: any, b: any) => b.value - a.value);
- node.outgoingLinks.sort((a: any, b: any) => b.value - a.value);
-
- // Start outgoing links from top of node
- const outStartY = node.y - node.height / 2;
- let currentOutY = outStartY;
- node.outgoingLinks.forEach((link: any) => {
- const linkHeight = linkWidthScale(link.value);
- link.sourceY = currentOutY + linkHeight / 2;
- currentOutY += linkHeight;
- });
-
- // Start incoming links from top of node
- const inStartY = node.y - node.height / 2;
- let currentInY = inStartY;
- node.incomingLinks.forEach((link: any) => {
- const linkHeight = linkWidthScale(link.value);
- link.targetY = currentInY + linkHeight / 2;
- currentInY += linkHeight;
- });
- });
-
- // Helper function to find all connected paths (all reachable nodes/edges)
- const findAllConnectedPaths = (startLink: any, direction: "forward" | "backward"): any[] => {
- const connectedLinks: any[] = [];
- const queue: any[] = [startLink];
- const visited = new Set<string>();
-
- while (queue.length > 0) {
- const currentLink = queue.shift();
- const linkId = `${currentLink.source}|||${currentLink.target}`;
-
- if (visited.has(linkId)) continue;
- visited.add(linkId);
- connectedLinks.push(currentLink);
-
- if (direction === "forward") {
- const targetNode = nodes.find(n => n.id === currentLink.target);
- // Follow all outgoing links
- if (targetNode && targetNode.outgoingLinks.length > 0) {
- targetNode.outgoingLinks.forEach((link: any) => queue.push(link));
- }
- } else {
- const sourceNode = nodes.find(n => n.id === currentLink.source);
- // Follow all incoming links
- if (sourceNode && sourceNode.incomingLinks.length > 0) {
- sourceNode.incomingLinks.forEach((link: any) => queue.push(link));
- }
- }
- }
-
- return connectedLinks;
- };
-
- // Helper to generate link path
- const getLinkPath = (d: any) => {
- const source = nodes.find(n => n.id === d.source);
- const target = nodes.find(n => n.id === d.target);
-
- if (!source || !target) return "";
-
- const sourceY = d.sourceY || source.y;
- const targetY = d.targetY || target.y;
- const sourceX = source.x + nodeWidth;
- const targetX = target.x;
-
- const controlPoint1X = sourceX + stepSpacing / 3;
- const controlPoint2X = targetX - stepSpacing / 3;
-
- return `M ${sourceX},${sourceY}
- C ${controlPoint1X},${sourceY}
- ${controlPoint2X},${targetY}
- ${targetX},${targetY}`;
- };
+type Hover = { kind: "node"; id: string } | { kind: "link"; id: string };
+
+const DATA_COLOR = "hsl(var(--dataviz))";
+const LABEL_OFFSET = NODE_WIDTH + 8;
+// Average advance of a 12px Inter glyph in a path: labels are cut by character count.
+const LABEL_CHAR_WIDTH = 6.4;
+const OVERLAY_WIDTH = 488;
+// Below this the diagram has no free corner wide enough for the overlay.
+const OVERLAY_DOCK_MIN_WIDTH = 880;
+const HALO = "stroke-white dark:stroke-neutral-900";
+
+const bandPath = (link: LaidOutLink, source: LaidOutNode, target: LaidOutNode, thickness: number) => {
+ const x0 = source.x + NODE_WIDTH;
+ const x1 = target.x;
+ const y0 = link.sourceY + thickness / 2;
+ const y1 = link.targetY + thickness / 2;
+ const curve = (x1 - x0) * 0.42;
+ return `M${x0},${y0.toFixed(1)}C${(x0 + curve).toFixed(1)},${y0.toFixed(1)} ${(x1 - curve).toFixed(1)},${y1.toFixed(1)} ${x1},${y1.toFixed(1)}`;
+};
+
+export function SankeyDiagram({
+ journeys,
+ steps,
+ maxJourneys,
+ domain,
+ pinnedPath,
+ onPinPath,
+ exitsKnown = true,
+ renderStepHeader,
+ pageHref,
+ overlay,
+}: SankeyDiagramProps) {
+ const t = useExtracted();
+ const router = useRouter();
+ const [measureRef, { width: containerWidth }] = useMeasure<HTMLDivElement>();
+ const [overlayRef, { height: overlayHeight }] = useMeasure<HTMLDivElement>();
+ const tooltipRef = useRef<HTMLDivElement>(null);
+ const [hover, setHover] = useState<Hover | null>(null);
+
+ const shown = useMemo(() => journeys.slice(0, maxJourneys), [journeys, maxJourneys]);
+ const graph = useMemo(() => buildSankeyGraph(shown, steps, exitsKnown), [shown, steps, exitsKnown]);
+ const layout = useMemo(
+ () => (containerWidth ? layoutSankey(graph, steps, containerWidth) : null),
+ [graph, steps, containerWidth]
+ );
- // Calculate node colors based on first path segment
- const getFirstSegment = (path: string) => {
- // Split path and get first non-empty segment
- const segments = path.split("/").filter(Boolean);
- return segments.length > 0 ? `/${segments[0]}` : path;
+ const nodesById = useMemo(() => new Map(layout?.nodes.map(node => [node.id, node])), [layout]);
+ const linksById = useMemo(() => new Map(layout?.links.map(link => [link.id, link])), [layout]);
+
+ // The pinned path's own sessions through each of its links.
+ const pinned = useMemo(() => {
+ if (!pinnedPath) return null;
+ const key = pathKey(pinnedPath);
+ const journey = shown.find(candidate => pathKey(candidate.path) === key);
+ if (!journey) return null;
+ const path = journey.path.slice(0, steps);
+ return {
+ count: journey.count,
+ nodes: new Set(path.map((name, step) => nodeId(step, name))),
+ links: new Set(path.slice(1).map((name, index) => linkId(nodeId(index, path[index]), nodeId(index + 1, name)))),
};
-
- // Count occurrences of each first segment
- const segmentCounts = new Map<string, number>();
- nodes.forEach(node => {
- const segment = getFirstSegment(node.name);
- segmentCounts.set(segment, (segmentCounts.get(segment) || 0) + 1);
+ }, [pinnedPath, shown, steps]);
+
+ const highlighted = useMemo(() => {
+ if (!hover) return null;
+ const start =
+ hover.kind === "link"
+ ? graph.links.filter(link => link.id === hover.id)
+ : graph.links.filter(link => link.source === hover.id || link.target === hover.id);
+ const links = connectedLinkIds(graph, start);
+ const nodes = new Set<string>(hover.kind === "node" ? [hover.id] : []);
+ for (const link of graph.links) {
+ if (!links.has(link.id)) continue;
+ nodes.add(link.source);
+ nodes.add(link.target);
+ }
+ return { links, nodes };
+ }, [hover, graph]);
+
+ if (!journeys || !domain) return null;
+
+ const moveTooltip = (event: MouseEvent) => {
+ const tooltip = tooltipRef.current;
+ const frame = tooltip?.offsetParent;
+ if (!tooltip || !frame) return;
+ const bounds = frame.getBoundingClientRect();
+ const x = event.clientX - bounds.left + 12;
+ const y = event.clientY - bounds.top - 12;
+ // Keep it inside the diagram instead of under the cursor at the right edge.
+ const overflow = Math.max(0, x + tooltip.offsetWidth - bounds.width);
+ tooltip.style.transform = `translate(${x - overflow}px, ${y}px) translateY(-100%)`;
+ };
+
+ const pin = (path: string[] | undefined) => {
+ if (path && onPinPath) onPinPath(path);
+ };
+ const largestThroughNode = (node: LaidOutNode) => shown.find(journey => journey.path[node.step] === node.name)?.path;
+ const largestThroughLink = (source: LaidOutNode, target: LaidOutNode) =>
+ shown.find(journey => journey.path[source.step] === source.name && journey.path[target.step] === target.name)?.path;
+
+ // The overlay docks in the free corner below the right-hand columns: every
+ // column whose labels or incoming bands would run under it sets how far down.
+ const dockOverlay = !!overlay && !!layout && layout.width >= OVERLAY_DOCK_MIN_WIDTH;
+ let overlayTop = 0;
+ if (dockOverlay && layout) {
+ const overlayLeft = layout.width - OVERLAY_WIDTH;
+ layout.columns.forEach((x, step) => {
+ const labelsReach = x + LABEL_OFFSET + layout.labelWidths[step] > overlayLeft;
+ const bandsReach = step + 1 < layout.columns.length && layout.columns[step + 1] > overlayLeft;
+ if (labelsReach || bandsReach) overlayTop = Math.max(overlayTop, layout.columnBottoms[step] + 16);
});
+ }
+ const svgHeight = layout ? Math.max(layout.height, dockOverlay ? overlayTop + (overlayHeight ?? 0) : 0) + 4 : 160;
- // Color palette for repeated segments
- const colorPalette = [
- "hsl(160, 45%, 40%)", // teal
- "hsl(220, 45%, 50%)", // blue
- "hsl(270, 40%, 50%)", // purple
- "hsl(25, 50%, 50%)", // orange
- "hsl(340, 40%, 50%)", // pink
- "hsl(190, 45%, 45%)", // cyan
- "hsl(45, 45%, 50%)", // yellow
- "hsl(0, 45%, 50%)", // red
- ];
- const defaultColor = "hsl(0, 0%, 50%)";
-
- // Assign colors to repeated segments
- const segmentColors = new Map<string, string>();
- let colorIndex = 0;
- segmentCounts.forEach((count, segment) => {
- if (count > 1) {
- segmentColors.set(segment, colorPalette[colorIndex % colorPalette.length]);
- colorIndex++;
- }
- });
-
- // Get color for a node
- const getNodeColor = (node: any) => {
- const segment = getFirstSegment(node.name);
- return segmentColors.get(segment) || defaultColor;
- };
-
- // Get color for a link (based on source node)
- const getLinkColor = (d: any) => {
- const sourceNode = nodes.find(n => n.id === d.source);
- return sourceNode ? getNodeColor(sourceNode) : linkColor;
- };
-
- // Draw links (visual only, events handled by hit areas)
- g.selectAll(".link")
- .data(links)
- .join("path")
- .attr("class", "link")
- .attr("d", getLinkPath)
- .attr("fill", "none")
- .attr("stroke", d => getLinkColor(d))
- .attr("stroke-width", d => linkWidthScale(d.value))
- .attr("opacity", 0.3)
- .attr("data-source", d => d.source)
- .attr("data-target", d => d.target)
- .style("pointer-events", "none");
-
- // Add tooltip for links
- const tooltip = d3
- .select("body")
- .append("div")
- .attr("class", "sankey-tooltip")
- .style("position", "absolute")
- .style("visibility", "hidden")
- .style("background", isDark ? "hsl(var(--neutral-800))" : "hsl(var(--neutral-100))")
- .style("border", `1px solid ${isDark ? "hsl(var(--neutral-700))" : "hsl(var(--neutral-200))"}`)
- .style("border-radius", "6px")
- .style("padding", "8px 12px")
- .style("font-size", "12px")
- .style("color", isDark ? "white" : "hsl(var(--neutral-900))")
- .style("pointer-events", "none")
- .style("z-index", "1000")
- .style("box-shadow", "0 2px 8px rgba(0,0,0,0.15)");
-
- // Draw nodes
- const nodeGroups = g
- .selectAll(".node")
- .data(nodes)
- .join("g")
- .attr("class", "node")
- .attr("transform", d => `translate(${d.x},${d.y - d.height / 2})`);
-
- // Thin bar
- nodeGroups
- .append("rect")
- .attr("class", "node-rect")
- .attr("width", nodeWidth)
- .attr("height", d => d.height)
- .attr("fill", d => getNodeColor(d))
- .attr("rx", 2)
- .attr("ry", 2);
-
- // Path text (clickable)
- const pathLinks = nodeGroups
- .append("a")
- .attr("xlink:href", d => `https://${domain}${d.name}`)
- .attr("target", "_blank")
- .attr("rel", "noopener noreferrer");
-
- pathLinks
- .append("text")
- .attr("class", "node-text node-link-text")
- .attr("x", 36)
- .attr("y", d => d.height / 2 + 4)
- .text(d => d.name)
- .attr("font-size", "12px")
- .attr("fill", pathTextColor)
- .attr("text-anchor", "start")
- .style("text-decoration", "none");
-
- // Add hover effect to show underline on link text
- pathLinks
- .on("mouseenter", function (event, d) {
- d3.select(this).select(".node-link-text").style("text-decoration", "underline");
- // Show tooltip
- tooltip
- .style("visibility", "visible")
- .html(
- `<div style="font-weight: 500; margin-bottom: 4px;">${d.name}</div>` +
- `<div style="color: ${isDark ? "hsl(var(--neutral-300))" : "hsl(var(--neutral-600))"};">` +
- `${d.count.toLocaleString()} visits (${d.percentage.toFixed(1)}%)</div>`
- )
- .style("top", event.pageY - 10 + "px")
- .style("left", event.pageX + 10 + "px");
- // Stop event propagation to prevent nodeGroups handler from firing
- event.stopPropagation();
- })
- .on("mousemove", function (event) {
- tooltip.style("top", event.pageY - 10 + "px").style("left", event.pageX + 10 + "px");
- })
- .on("mouseleave", function () {
- d3.select(this).select(".node-link-text").style("text-decoration", "none");
- tooltip.style("visibility", "hidden");
- });
-
- // Node hover effects
- nodeGroups
- .on("mouseenter", function (event, d) {
- const nodeId = d.id;
- const connectedNodeIds = new Set<string>([nodeId]);
-
- // Show tooltip with node info
- tooltip
- .style("visibility", "visible")
- .html(
- `<div style="font-weight: 500; margin-bottom: 4px;">${d.name}</div>` +
- `<div style="color: ${isDark ? "hsl(var(--neutral-300))" : "hsl(var(--neutral-600))"};">` +
- `${d.count.toLocaleString()} visits (${d.percentage.toFixed(1)}%)</div>`
- )
- .style("top", event.pageY - 10 + "px")
- .style("left", event.pageX + 10 + "px");
+ const pinnedThickness = pinned && layout ? Math.max(1.5, pinned.count * layout.scale) : 0;
- // Find all directly connected links
- const directLinks = links.filter(link => link.source === nodeId || link.target === nodeId);
+ const hoveredNode = hover?.kind === "node" ? nodesById.get(hover.id) : undefined;
+ const hoveredLink = hover?.kind === "link" ? linksById.get(hover.id) : undefined;
+ const hoveredLinkSource = hoveredLink && nodesById.get(hoveredLink.source);
+ const hoveredLinkTarget = hoveredLink && nodesById.get(hoveredLink.target);
- const allConnectedLinks: any[] = [];
-
- // For each direct link, find all connected paths
- directLinks.forEach(link => {
- allConnectedLinks.push(link);
-
- const forwardPaths = findAllConnectedPaths(link, "forward");
- const backwardPaths = findAllConnectedPaths(link, "backward");
-
- allConnectedLinks.push(...forwardPaths);
- allConnectedLinks.push(...backwardPaths);
- });
-
- const connectedLinkIds = new Set<string>();
-
- // Collect all connected link and node IDs
- allConnectedLinks.forEach(link => {
- const linkId = `${link.source}|||${link.target}`;
- connectedLinkIds.add(linkId);
- connectedNodeIds.add(link.source);
- connectedNodeIds.add(link.target);
- });
-
- d3.selectAll(".link").attr("opacity", function () {
- const linkSource = d3.select(this).attr("data-source");
- const linkTarget = d3.select(this).attr("data-target");
- const thisLinkId = `${linkSource}|||${linkTarget}`;
- return connectedLinkIds.has(thisLinkId) ? 0.6 : 0.1;
- });
-
- d3.selectAll(".node-rect").attr("opacity", function (nodeData: any) {
- return connectedNodeIds.has(nodeData.id) ? 1 : 0.2;
- });
-
- d3.selectAll(".node-text").attr("opacity", function (nodeData: any) {
- return connectedNodeIds.has(nodeData.id) ? 1 : 0.3;
- });
- })
- .on("mousemove", function (event) {
- tooltip.style("top", event.pageY - 10 + "px").style("left", event.pageX + 10 + "px");
- })
- .on("mouseleave", function () {
- d3.selectAll(".link")
- .attr("opacity", 0.3)
- .attr("stroke", function () {
- const linkSource = d3.select(this).attr("data-source");
- const link = links.find(l => l.source === linkSource);
- return link ? getLinkColor(link) : linkColor;
- });
- d3.selectAll(".node-rect").attr("opacity", 1);
- d3.selectAll(".node-text").attr("opacity", 1);
- tooltip.style("visibility", "hidden");
- });
-
- // Invisible wider hit area for easier hovering on thin links (drawn last to be on top)
- g.selectAll(".link-hit-area")
- .data(links)
- .join("path")
- .attr("class", "link-hit-area")
- .attr("d", getLinkPath)
- .attr("fill", "none")
- .attr("stroke", "transparent")
- .attr("stroke-width", d => Math.max(linkWidthScale(d.value), 16))
- .attr("data-source", d => d.source)
- .attr("data-target", d => d.target)
- .style("cursor", "pointer")
- .on("mouseenter", function (event, d) {
- const sourceNode = nodes.find(n => n.id === d.source);
- const targetNode = nodes.find(n => n.id === d.target);
- const totalValue = d3.sum(links, (l: any) => l.value);
- const percentage = ((d.value / totalValue) * 100).toFixed(1);
-
- tooltip
- .style("visibility", "visible")
- .html(
- `<div style="font-weight: 500; margin-bottom: 4px;">${sourceNode?.name} → ${targetNode?.name}</div>` +
- `<div style="color: ${isDark ? "hsl(var(--neutral-300))" : "hsl(var(--neutral-600))"};">` +
- `${d.value.toLocaleString()} visits (${percentage}%)</div>`
- );
-
- const forwardPaths = findAllConnectedPaths(d, "forward");
- const backwardPaths = findAllConnectedPaths(d, "backward");
- const allConnectedLinks = [d, ...forwardPaths, ...backwardPaths];
-
- const connectedLinkIds = new Set<string>();
- const connectedNodeIds = new Set<string>();
-
- allConnectedLinks.forEach(link => {
- const linkId = `${link.source}|||${link.target}`;
- connectedLinkIds.add(linkId);
- connectedNodeIds.add(link.source);
- connectedNodeIds.add(link.target);
- });
-
- d3.selectAll(".link").attr("opacity", function () {
- const linkSource = d3.select(this).attr("data-source");
- const linkTarget = d3.select(this).attr("data-target");
- const thisLinkId = `${linkSource}|||${linkTarget}`;
- return connectedLinkIds.has(thisLinkId) ? 0.6 : 0.1;
- });
-
- d3.selectAll(".node-rect").attr("opacity", function (nodeData: any) {
- return connectedNodeIds.has(nodeData.id) ? 1 : 0.2;
- });
-
- d3.selectAll(".node-text").attr("opacity", function (nodeData: any) {
- return connectedNodeIds.has(nodeData.id) ? 1 : 0.3;
- });
-
- tooltip.style("top", event.pageY - 10 + "px").style("left", event.pageX + 10 + "px");
- })
- .on("mousemove", function (event) {
- tooltip.style("top", event.pageY - 10 + "px").style("left", event.pageX + 10 + "px");
- })
- .on("mouseleave", function () {
- d3.selectAll(".link")
- .attr("opacity", 0.3)
- .attr("stroke", function () {
- const linkSource = d3.select(this).attr("data-source");
- const link = links.find(l => l.source === linkSource);
- return link ? getLinkColor(link) : linkColor;
- });
- d3.selectAll(".node-rect").attr("opacity", 1);
- d3.selectAll(".node-text").attr("opacity", 1);
- tooltip.style("visibility", "hidden");
- });
-
- const dispose = () => {
- svg.selectAll("*").on("mouseenter", null).on("mousemove", null).on("mouseleave", null);
- svg.selectAll("*").remove();
- tooltip.remove();
- };
-
- // Cleanup tooltip and D3 handlers on unmount
- return () => {
- dispose();
- };
- }, [journeys, steps, maxJourneys, domain, resolvedTheme]);
+ const nodeMeta = (node: LaidOutNode) => {
+ const count = node.count.toLocaleString();
+ // The entry column says what the figures count; the others repeat only the number.
+ if (node.step === 0 && !node.exits) return t("{count} sessions", { count });
+ if (node.exits === null) return count;
+ if (node.exits === 0) return t("{count} · all continue", { count });
+ return t("{count} · {percent} end here", { count, percent: formatShare(node.exits / node.count, 0) });
+ };
return (
- <div className="overflow-x-auto w-full">
- <svg ref={svgRef} className="min-w-full" />
- </div>
+ <>
+ <div ref={measureRef} className="w-full overflow-x-auto">
+ {layout ? (
+ <div className="relative" style={{ width: layout.width }} onMouseLeave={() => setHover(null)}>
+ {renderStepHeader && (
+ <div className="relative mb-2 h-7">
+ {layout.columns.map((x, index) => (
+ <div key={index} className="absolute top-0 flex h-7 items-center gap-2" style={{ left: x }}>
+ {renderStepHeader({
+ index,
+ sessions: graph.stepTotals[index] ?? 0,
+ previousSessions: index === 0 ? null : (graph.stepTotals[index - 1] ?? 0),
+ width: (layout.columns[index + 1] ?? layout.width) - x,
+ })}
+ </div>
+ ))}
+ </div>
+ )}
+ <div className="relative">
+ <svg
+ width={layout.width}
+ height={svgHeight}
+ className="block"
+ role="img"
+ aria-label={t("Sankey diagram of the top {count} paths from session start, {steps} steps deep", {
+ count: String(shown.length),
+ steps: String(steps),
+ })}
+ >
+ {layout.links.map(link => {
+ const source = nodesById.get(link.source);
+ const target = nodesById.get(link.target);
+ if (!source || !target) return null;
+ const opacity = highlighted ? (highlighted.links.has(link.id) ? 0.45 : 0.07) : pinned ? 0.14 : 0.2;
+ return (
+ <path
+ key={link.id}
+ d={bandPath(link, source, target, link.thickness)}
+ fill="none"
+ stroke={DATA_COLOR}
+ strokeWidth={Math.max(1, link.thickness)}
+ opacity={opacity}
+ className="transition-opacity duration-150"
+ />
+ );
+ })}
+ {pinned &&
+ layout.links.map(link => {
+ const source = nodesById.get(link.source);
+ const target = nodesById.get(link.target);
+ if (!pinned.links.has(link.id) || !source || !target) return null;
+ return (
+ <path
+ key={link.id}
+ d={bandPath(link, source, target, pinnedThickness)}
+ fill="none"
+ stroke={DATA_COLOR}
+ strokeWidth={pinnedThickness}
+ opacity={highlighted && !highlighted.links.has(link.id) ? 0.35 : 0.9}
+ className="transition-opacity duration-150"
+ />
+ );
+ })}
+
+ {/* Invisible, wider hit areas so thin bands can be hovered. Bars and labels are drawn over them. */}
+ {layout.links.map(link => {
+ const source = nodesById.get(link.source);
+ const target = nodesById.get(link.target);
+ if (!source || !target) return null;
+ return (
+ <path
+ key={link.id}
+ d={bandPath(link, source, target, link.thickness)}
+ fill="none"
+ stroke="transparent"
+ strokeWidth={Math.max(link.thickness, 12)}
+ className={onPinPath ? "cursor-pointer" : undefined}
+ onMouseEnter={event => {
+ setHover({ kind: "link", id: link.id });
+ moveTooltip(event);
+ }}
+ onMouseMove={moveTooltip}
+ onClick={() => pin(largestThroughLink(source, target))}
+ />
+ );
+ })}
+
+ {layout.nodes.map(node => {
+ const dimmed = highlighted ? !highlighted.nodes.has(node.id) : false;
+ const isPinned = !!pinned?.nodes.has(node.id);
+ const exitShare = node.exits ? node.exits / node.count : 0;
+ const continuedHeight = node.height * (1 - exitShare);
+ // A pinned band leaving from the top of the bar would run under the label.
+ const pinnedBandOnTop =
+ !!pinned &&
+ node.outgoing.some(link => pinned.links.has(link.id) && linksById.get(link.id)?.sourceY === node.y);
+ const labelY = node.y + (pinnedBandOnTop ? pinnedThickness + 3 : 0);
+ const maxChars = Math.max(6, Math.floor(layout.labelWidths[node.step] / LABEL_CHAR_WIDTH));
+ const count = node.count.toLocaleString();
+ const name = layout.compact
+ ? truncateMiddle(node.name, Math.max(6, maxChars - count.length - 1))
+ : truncateMiddle(node.name, maxChars);
+ const href = pageHref ? pageHref(node.name) : `https://${domain}${node.name}`;
+ const nameText = (
+ <text
+ x={node.x + LABEL_OFFSET}
+ y={labelY + 11}
+ fontSize={12}
+ fontWeight={isPinned ? 600 : 500}
+ paintOrder="stroke"
+ strokeWidth={4}
+ strokeLinejoin="round"
+ className={cn(
+ HALO,
+ "sankey-node-name",
+ isPinned ? "fill-neutral-950 dark:fill-neutral-50" : "fill-neutral-800 dark:fill-neutral-200"
+ )}
+ >
+ {name}
+ {layout.compact && (
+ <tspan dx={6} fontSize={11} fontWeight={400} className="fill-neutral-500 dark:fill-neutral-400">
+ {count}
+ </tspan>
+ )}
+ </text>
+ );
+
+ return (
+ <g
+ key={node.id}
+ opacity={dimmed ? 0.25 : 1}
+ className="transition-opacity duration-150"
+ onMouseEnter={event => {
+ setHover({ kind: "node", id: node.id });
+ moveTooltip(event);
+ }}
+ onMouseMove={moveTooltip}
+ >
+ <g
+ onClick={() => pin(largestThroughNode(node))}
+ className={onPinPath ? "cursor-pointer" : undefined}
+ >
+ {/* Wider than the bar, so a thin one is still easy to hit. */}
+ <rect
+ x={node.x - 4}
+ y={node.y}
+ width={NODE_WIDTH + 8}
+ height={node.height}
+ fill="transparent"
+ />
+ {continuedHeight > 0.2 && (
+ <rect
+ x={node.x}
+ y={node.y}
+ width={NODE_WIDTH}
+ height={continuedHeight}
+ rx={2}
+ fill={DATA_COLOR}
+ />
+ )}
+ {exitShare > 0 && (
+ <rect
+ x={node.x}
+ y={node.y + continuedHeight}
+ width={NODE_WIDTH}
+ height={node.height - continuedHeight}
+ rx={2}
+ className="fill-neutral-300 dark:fill-neutral-600"
+ />
+ )}
+ </g>
+ {href ? (
+ <a
+ href={href}
+ className="[&:hover_.sankey-node-name]:underline"
+ {...(pageHref
+ ? {
+ onClick: (event: MouseEvent) => {
+ // Keep the browser's own handling for new-tab clicks.
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) return;
+ event.preventDefault();
+ router.push(href);
+ },
+ }
+ : { target: "_blank", rel: "noopener noreferrer" })}
+ >
+ {nameText}
+ </a>
+ ) : (
+ nameText
+ )}
+ {!layout.compact && (
+ <text
+ x={node.x + LABEL_OFFSET}
+ y={labelY + 26}
+ fontSize={11}
+ paintOrder="stroke"
+ strokeWidth={4}
+ strokeLinejoin="round"
+ className={cn(HALO, "fill-neutral-500 dark:fill-neutral-400")}
+ >
+ {nodeMeta(node)}
+ </text>
+ )}
+ </g>
+ );
+ })}
+ </svg>
+ {dockOverlay && (
+ <div
+ ref={overlayRef}
+ className="absolute right-0"
+ style={{ top: overlayTop, width: OVERLAY_WIDTH }}
+ onMouseEnter={() => setHover(null)}
+ >
+ {overlay}
+ </div>
+ )}
+ </div>
+
+ <div
+ ref={tooltipRef}
+ role="tooltip"
+ className={cn(
+ "pointer-events-none absolute left-0 top-0 z-10 max-w-xs rounded-md border border-neutral-100 bg-white px-2.5 py-2 text-xs text-neutral-900 shadow-lg dark:border-neutral-750 dark:bg-neutral-800 dark:text-neutral-50",
+ !hoveredNode && !hoveredLink && "invisible"
+ )}
+ >
+ {hoveredNode && (
+ <>
+ <div className="break-all font-medium">{hoveredNode.name}</div>
+ <div className="mt-1 tabular-nums text-neutral-600 dark:text-neutral-300">
+ {t("{count} sessions · {percent} of sessions with 2+ pages", {
+ count: hoveredNode.count.toLocaleString(),
+ percent: `${hoveredNode.percentage.toFixed(1)}%`,
+ })}
+ </div>
+ {!!hoveredNode.exits && (
+ <div className="tabular-nums text-neutral-600 dark:text-neutral-300">
+ {t("{count} ended the session here ({percent})", {
+ count: hoveredNode.exits.toLocaleString(),
+ percent: formatShare(hoveredNode.exits / hoveredNode.count),
+ })}
+ </div>
+ )}
+ </>
+ )}
+ {hoveredLink && hoveredLinkSource && hoveredLinkTarget && (
+ <>
+ <div className="flex flex-wrap items-center gap-1 break-all font-medium">
+ {hoveredLinkSource.name}
+ <ArrowRight
+ className="h-3 w-3 shrink-0 text-neutral-500 dark:text-neutral-400"
+ aria-hidden="true"
+ />
+ {hoveredLinkTarget.name}
+ </div>
+ <div className="mt-1 tabular-nums text-neutral-600 dark:text-neutral-300">
+ {t("{count} sessions · {percent} of those on {page} at step {step}", {
+ count: hoveredLink.value.toLocaleString(),
+ percent: formatShare(hoveredLink.value / hoveredLinkSource.count),
+ page: hoveredLinkSource.name,
+ step: String(hoveredLinkSource.step + 1),
+ })}
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ ) : (
+ <div className="h-40" />
+ )}
+ </div>
+ {overlay && !dockOverlay && <div className="mt-3">{overlay}</div>}
+ </>
);
}
diff --git a/client/src/app/[site]/journeys/components/SaveAsFunnelDialog.tsx b/client/src/app/[site]/journeys/components/SaveAsFunnelDialog.tsx
new file mode 100644
index 000000000..aeaa1d27b
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/SaveAsFunnelDialog.tsx
@@ -0,0 +1,77 @@
+"use client";
+
+import { useExtracted } from "next-intl";
+import { useState } from "react";
+import { FunnelStep, hasIncompleteSteps } from "@/api/analytics/endpoints";
+import { useGetFunnel, useSaveFunnel } from "@/api/analytics/hooks/funnels/useGetFunnel";
+import { Dialog, DialogContentFullScreen } from "@/components/ui/dialog";
+import { toast } from "@/components/ui/sonner";
+import { FunnelForm } from "../../funnels/components/FunnelForm";
+
+const stepsFromPath = (path: string[]): FunnelStep[] => path.map(page => ({ type: "page", value: page, name: "" }));
+
+function FunnelEditor({ path, onClose }: { path: string[]; onClose: () => void }) {
+ const t = useExtracted();
+ const [steps, setSteps] = useState<FunnelStep[]>(() => stepsFromPath(path));
+ const [name, setName] = useState(() => path.join(" > "));
+
+ // Drives the live preview, as in the funnels page's own editor.
+ const { data, isError, error, isLoading } = useGetFunnel(hasIncompleteSteps(steps) ? undefined : { steps }, true);
+ const { mutate: saveFunnel, isPending: isSaving } = useSaveFunnel();
+
+ const save = () => {
+ if (!name.trim() || hasIncompleteSteps(steps)) return;
+ saveFunnel(
+ { steps, name },
+ {
+ onSuccess: () => {
+ onClose();
+ toast?.success(t("Funnel saved successfully"));
+ },
+ onError: saveError => {
+ // Show the error but keep the editor open.
+ toast?.error(t("Failed to save funnel: {message}", { message: saveError.message }));
+ },
+ }
+ );
+ };
+
+ return (
+ <FunnelForm
+ title={t("Create Funnel")}
+ name={name}
+ setName={setName}
+ steps={steps}
+ setSteps={setSteps}
+ onSave={save}
+ onCancel={onClose}
+ saveButtonText={t("Save Funnel")}
+ isSaving={isSaving}
+ isError={isError}
+ isPending={isLoading}
+ error={error}
+ funnelData={data}
+ />
+ );
+}
+
+/**
+ * The funnels page's create-funnel editor, opened with a path's pages as its
+ * steps. It reuses that editor's form and hooks rather than its dialog, which
+ * owns its own trigger button and default steps.
+ */
+export function SaveAsFunnelDialog({ path, onClose }: { path: string[] | null; onClose: () => void }) {
+ return (
+ <Dialog open={path !== null} onOpenChange={open => !open && onClose()}>
+ <DialogContentFullScreen
+ aria-describedby={undefined}
+ onOpenAutoFocus={event => {
+ event.preventDefault();
+ document.getElementById("funnel-name-input")?.focus();
+ }}
+ >
+ {path && <FunnelEditor key={JSON.stringify(path)} path={path} onClose={onClose} />}
+ </DialogContentFullScreen>
+ </Dialog>
+ );
+}
diff --git a/client/src/app/[site]/journeys/components/TopPaths.test.tsx b/client/src/app/[site]/journeys/components/TopPaths.test.tsx
new file mode 100644
index 000000000..7723b3ab8
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/TopPaths.test.tsx
@@ -0,0 +1,218 @@
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+import { MouseEvent, ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { JourneyRow, pathKey } from "./journeyUtils";
+import { TopPaths, TopPathsProps } from "./TopPaths";
+
+const mocks = vi.hoisted(() => ({ replayAvailable: true }));
+
+vi.mock("next-intl", () => ({
+ useExtracted:
+ () =>
+ (message: string, values: Record<string, string> = {}) =>
+ message.replace(/\{(\w+)\}/g, (_, key: string) => values[key] ?? ""),
+}));
+vi.mock("next/navigation", () => ({ useSearchParams: () => new URLSearchParams() }));
+vi.mock("next/link", () => ({
+ default: ({
+ href,
+ children,
+ prefetch,
+ onClick,
+ ...props
+ }: {
+ href: string;
+ children: ReactNode;
+ prefetch?: boolean;
+ onClick?: (event: MouseEvent) => void;
+ }) => (
+ // jsdom cannot navigate; following the link is the router's job, not what is under test.
+ <a
+ href={href}
+ {...props}
+ onClick={event => {
+ onClick?.(event);
+ event.preventDefault();
+ }}
+ >
+ {children}
+ </a>
+ ),
+}));
+vi.mock("@/hooks/useReplayAvailable", () => ({ useReplayAvailable: () => mocks.replayAvailable }));
+vi.mock("@/hooks/usePermissions", () => ({ useCanOnSite: () => true }));
+vi.mock("@/app/[site]/components/SubHeader/Filters/SegmentDialog", () => ({ SegmentDialog: () => null }));
+
+const journey = (path: string[], count: number, conversions?: number): JourneyRow => ({
+ path,
+ count,
+ percentage: count / 100,
+ conversions,
+});
+const JOURNEYS = [
+ journey(["/", "/pricing"], 3290, 0),
+ journey(["/", "/demo"], 3180, 0),
+ journey(["/", "/pricing", "/signup"], 1290, 1290),
+ journey(["/docs", "/docs/script", "/signup"], 640, 80),
+];
+
+const handlers = { openSessions: vi.fn(), saveAsFunnel: vi.fn() };
+const onPin = vi.fn();
+
+const renderTable = (props: Partial<TopPathsProps> = {}) =>
+ render(
+ <TopPaths
+ journeys={JOURNEYS}
+ isLoading={false}
+ steps={4}
+ previousCounts={null}
+ goalName="Signup"
+ pinnedKey={null}
+ onPin={onPin}
+ pageHref={page => `/1/pages?page=${page}`}
+ handlers={handlers}
+ {...props}
+ />
+ );
+
+const rows = () => screen.getAllByRole("row").slice(1);
+const cells = (row: HTMLElement) =>
+ within(row)
+ .getAllByRole("cell")
+ .map(cell => cell.textContent);
+
+beforeEach(() => {
+ mocks.replayAvailable = true;
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("TopPaths", () => {
+ it("lists each path with its sessions, share and goal reach", () => {
+ renderTable();
+
+ expect(rows()).toHaveLength(4);
+ expect(cells(rows()[0]).slice(0, 5)).toEqual(["1", "//pricing", "3,290", "32.9%", "0%"]);
+ expect(cells(rows()[2])[4]).toBe("100%1,290");
+ expect(cells(rows()[3])[4]).toBe("12.5%80");
+ expect(screen.getByText("Showing 4 of 4 paths")).toBeTruthy();
+ });
+
+ it("leaves the change column out until the comparison period is known", () => {
+ renderTable();
+ expect(screen.queryByText("vs prev.")).toBeNull();
+ });
+
+ it("shows each path's change, and a dash for one the comparison period did not rank", () => {
+ renderTable({
+ previousCounts: new Map([
+ [pathKey(["/", "/pricing"]), 2632],
+ [pathKey(["/", "/demo"]), 3975],
+ ]),
+ });
+
+ expect(screen.getByText("vs prev.")).toBeTruthy();
+ expect(cells(rows()[0])[4]).toContain("25.0%");
+ expect(within(rows()[0]).getByText("+25.0%")).toBeTruthy();
+ expect(within(rows()[1]).getByText("-20.0%")).toBeTruthy();
+ expect(cells(rows()[2])[4]).toBe("—");
+ });
+
+ it("leaves the goal column and filter out without a goal", () => {
+ renderTable({ goalName: null });
+
+ expect(screen.queryByText("Reach Signup")).toBeNull();
+ expect(screen.queryByRole("radiogroup")).toBeNull();
+ expect(cells(rows()[0])).toHaveLength(5);
+ });
+
+ it("filters to the paths that reach the goal, or never do", () => {
+ renderTable();
+
+ fireEvent.click(screen.getByRole("radio", { name: "Reach Signup" }));
+ expect(rows().map(row => cells(row)[0])).toEqual(["3", "4"]);
+ expect(screen.getByText("Showing 2 of 4 paths")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("radio", { name: "Never reach it" }));
+ expect(rows().map(row => cells(row)[0])).toEqual(["1", "2"]);
+ });
+
+ it("filters by a page, keeping each row's rank", () => {
+ renderTable();
+ const search = screen.getByLabelText("Filter paths by page");
+
+ fireEvent.change(search, { target: { value: "/docs/**" } });
+ expect(rows().map(row => cells(row)[0])).toEqual(["4"]);
+
+ fireEvent.change(search, { target: { value: "nothing-like-this" } });
+ expect(screen.getByText("No paths match this filter.")).toBeTruthy();
+ });
+
+ it("shows twelve rows until asked for all", () => {
+ const many = Array.from({ length: 15 }, (_, index) => journey(["/", `/page-${index}`], 100 - index, 0));
+ renderTable({ journeys: many });
+
+ expect(rows()).toHaveLength(12);
+ expect(screen.getByText("Showing 12 of 15 paths")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Show all" }));
+ expect(rows()).toHaveLength(15);
+ fireEvent.click(screen.getByRole("button", { name: "Show fewer" }));
+ expect(rows()).toHaveLength(12);
+ });
+
+ it("pins a row on click and from the keyboard, and marks the pinned row", () => {
+ renderTable({ pinnedKey: pathKey(["/", "/demo"]) });
+
+ fireEvent.click(rows()[0]);
+ expect(onPin).toHaveBeenLastCalledWith(["/", "/pricing"]);
+ fireEvent.keyDown(rows()[2], { key: "Enter" });
+ expect(onPin).toHaveBeenLastCalledWith(["/", "/pricing", "/signup"]);
+
+ expect(rows()[1].getAttribute("aria-selected")).toBe("true");
+ expect(rows()[0].getAttribute("aria-selected")).toBe("false");
+ // The pinned row spells its actions out.
+ expect(within(rows()[1]).getByRole("button", { name: "Sessions" }).textContent).toBe("Sessions");
+ expect(within(rows()[0]).getByRole("button", { name: "Sessions" }).textContent).toBe("");
+ });
+
+ it("opens a path's sessions, replays and funnel without pinning the row", () => {
+ renderTable();
+ const row = within(rows()[2]);
+
+ fireEvent.click(row.getByRole("button", { name: "Sessions" }));
+ expect(handlers.openSessions).toHaveBeenLastCalledWith(["/", "/pricing", "/signup"], false);
+ fireEvent.click(row.getByRole("button", { name: "Replays" }));
+ expect(handlers.openSessions).toHaveBeenLastCalledWith(["/", "/pricing", "/signup"], true);
+ fireEvent.click(row.getByRole("button", { name: "Save as funnel" }));
+ expect(handlers.saveAsFunnel).toHaveBeenCalledWith(["/", "/pricing", "/signup"]);
+ fireEvent.click(row.getAllByRole("link")[0]);
+
+ expect(onPin).not.toHaveBeenCalled();
+ });
+
+ it("offers no replays without replay, and no funnel to a viewer who cannot create one", () => {
+ mocks.replayAvailable = false;
+ renderTable({ handlers: { openSessions: handlers.openSessions } });
+
+ expect(screen.queryByRole("button", { name: "Replays" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Save as funnel" })).toBeNull();
+ expect(screen.getAllByRole("button", { name: "Sessions" })).toHaveLength(4);
+ });
+
+ it("links each page of a path", () => {
+ renderTable();
+
+ const links = within(rows()[0]).getAllByRole("link");
+ expect(links.map(link => link.getAttribute("href"))).toEqual(["/1/pages?page=/", "/1/pages?page=/pricing"]);
+ });
+
+ it("shows placeholders while loading", () => {
+ renderTable({ isLoading: true, journeys: [] });
+
+ expect(screen.queryByText("No paths in this range.")).toBeNull();
+ expect(rows()).toHaveLength(6);
+ });
+});
diff --git a/client/src/app/[site]/journeys/components/TopPaths.tsx b/client/src/app/[site]/journeys/components/TopPaths.tsx
new file mode 100644
index 000000000..639f76cb1
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/TopPaths.tsx
@@ -0,0 +1,287 @@
+"use client";
+
+import { ChevronDown, ChevronUp, Target } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { KeyboardEvent, useState } from "react";
+import { SegmentedControl } from "@/components/interior/segmented-control";
+import { Delta } from "@/components/site/Delta";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Skeleton } from "@/components/ui/skeleton";
+import { NO_DELTA_TEXT, percentDelta } from "@/lib/delta";
+import { cn } from "@/lib/utils";
+import { JourneyRow, pathContainsPage, pathKey } from "./journeyUtils";
+import { PathActionHandlers, PathActions } from "./PathActions";
+import { PathChips } from "./PathChips";
+
+const COLLAPSED_ROWS = 12;
+
+type ReachFilter = "all" | "reached" | "not-reached";
+
+const TH = "h-8 px-2 text-left align-middle text-xs font-medium text-neutral-500 dark:text-neutral-400";
+const TD = "p-2 align-middle";
+
+export interface TopPathsProps {
+ journeys: JourneyRow[];
+ isLoading: boolean;
+ steps: number;
+ /**
+ * Each path's sessions in the comparison period, by path key. Null while the
+ * comparison is off or still loading: the column is then left out.
+ */
+ previousCounts: Map<string, number> | null;
+ /** The selected goal's name; null hides the reach column and filter. */
+ goalName: string | null;
+ pinnedKey: string | null;
+ onPin: (path: string[]) => void;
+ pageHref: (page: string) => string | undefined;
+ handlers: PathActionHandlers;
+}
+
+/** The shown paths as a table: size, share, change, goal reach, and the way to the sessions behind each. */
+export function TopPaths({
+ journeys,
+ isLoading,
+ steps,
+ previousCounts,
+ goalName,
+ pinnedKey,
+ onPin,
+ pageHref,
+ handlers,
+}: TopPathsProps) {
+ const t = useExtracted();
+ const [reachFilter, setReachFilter] = useState<ReachFilter>("all");
+ const [search, setSearch] = useState("");
+ const [expanded, setExpanded] = useState(false);
+
+ const hasGoal = goalName !== null && journeys.some(journey => journey.conversions !== undefined);
+ const activeReachFilter = hasGoal ? reachFilter : "all";
+ const matching = journeys.filter(journey => {
+ if (activeReachFilter === "reached" && !journey.conversions) return false;
+ if (activeReachFilter === "not-reached" && journey.conversions) return false;
+ return pathContainsPage(journey.path, search);
+ });
+ const visible = expanded ? matching : matching.slice(0, COLLAPSED_ROWS);
+ const largest = Math.max(1, ...journeys.map(journey => journey.count));
+ // A row keeps its rank among all paths when the table is filtered.
+ const ranks = new Map(journeys.map((journey, index) => [pathKey(journey.path), index + 1]));
+ const columnCount = 5 + (previousCounts ? 1 : 0) + (hasGoal ? 1 : 0);
+
+ const activateRow = (event: KeyboardEvent, path: string[]) => {
+ if (event.target !== event.currentTarget) return;
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onPin(path);
+ }
+ };
+
+ return (
+ <Card>
+ <div className="flex flex-col gap-3 px-4 py-3 md:flex-row md:items-center md:justify-between">
+ <div className="min-w-0">
+ <h2 className="font-semibold leading-none tracking-tight">{t("Top paths")}</h2>
+ <p className="mt-1.5 text-xs text-neutral-500 dark:text-neutral-400">
+ {t("Exact page sequences from session start, up to {steps} steps", { steps: String(steps) })}
+ </p>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ {hasGoal && (
+ <SegmentedControl
+ size="sm"
+ aria-label={t("Filter paths by goal")}
+ value={reachFilter}
+ onValueChange={setReachFilter}
+ options={[
+ { value: "all", label: t("All paths") },
+ { value: "reached", label: t("Reach {goal}", { goal: goalName }) },
+ { value: "not-reached", label: t("Never reach it") },
+ ]}
+ />
+ )}
+ <div className="w-full sm:w-56">
+ <Input
+ isSearch
+ value={search}
+ onChange={event => setSearch(event.target.value)}
+ placeholder={t("Contains page, e.g. /docs/**")}
+ aria-label={t("Filter paths by page")}
+ className="h-8 pl-8 text-xs"
+ />
+ </div>
+ </div>
+ </div>
+
+ <div className="relative w-full overflow-x-auto">
+ <table className="w-full min-w-[900px] caption-bottom text-sm">
+ <thead className="bg-neutral-50 dark:bg-neutral-850">
+ <tr>
+ <th className={cn(TH, "w-9 pl-4")}>#</th>
+ <th className={TH}>{t("Path")}</th>
+ <th className={cn(TH, "w-40 text-right")}>{t("Sessions")}</th>
+ <th className={cn(TH, "w-[72px] text-right")} title={t("Share of sessions with two or more pages")}>
+ {t("Share")}
+ </th>
+ {previousCounts && (
+ <th
+ className={cn(TH, "w-[84px] text-right")}
+ title={t("Change in sessions against the comparison period")}
+ >
+ {t("vs prev.")}
+ </th>
+ )}
+ {hasGoal && (
+ <th className={cn(TH, "w-[132px] text-right")}>
+ <span className="inline-flex max-w-full items-center gap-1">
+ <Target className="h-3 w-3 shrink-0" />
+ <span className="truncate">{t("Reach {goal}", { goal: goalName })}</span>
+ </span>
+ </th>
+ )}
+ {/* Wide enough for the pinned row's labelled actions, so pinning does not shift the columns. */}
+ <th className={cn(TH, "w-[276px] pr-4 text-right")}>{t("Open")}</th>
+ </tr>
+ </thead>
+ <tbody className="bg-white dark:bg-neutral-900 [&_tr:last-child]:border-0">
+ {isLoading
+ ? Array.from({ length: 6 }, (_, index) => (
+ <tr key={index} className="border-b border-b-neutral-100 dark:border-b-neutral-800">
+ <td className={cn(TD, "pl-4")} colSpan={columnCount}>
+ <Skeleton className="h-5 rounded" style={{ width: `${70 - index * 7}%` }} />
+ </td>
+ </tr>
+ ))
+ : visible.map(journey => {
+ const key = pathKey(journey.path);
+ const rank = ranks.get(key);
+ const isPinned = key === pinnedKey;
+ const previous = previousCounts?.get(key);
+ return (
+ <tr
+ key={key}
+ tabIndex={0}
+ aria-selected={isPinned}
+ onClick={() => onPin(journey.path)}
+ onKeyDown={event => activateRow(event, journey.path)}
+ className={cn(
+ "cursor-pointer border-b border-b-neutral-100 transition-colors hover:bg-neutral-50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-neutral-400 dark:border-b-neutral-800 dark:hover:bg-neutral-800/20 dark:focus-visible:ring-neutral-500",
+ isPinned && "bg-neutral-50 dark:bg-neutral-800/50 dark:hover:bg-neutral-800/50"
+ )}
+ >
+ <td className={cn(TD, "pl-4 text-xs tabular-nums text-neutral-500 dark:text-neutral-400")}>
+ {rank}
+ </td>
+ <td className={TD}>
+ <PathChips
+ path={journey.path}
+ pageHref={pageHref}
+ className="flex-nowrap"
+ chipClassName={isPinned ? "dark:border-neutral-700" : undefined}
+ />
+ </td>
+ <td className={TD}>
+ <div className="flex items-center justify-end gap-2.5">
+ <div className="h-1.5 w-16 shrink-0 rounded-full bg-neutral-100 dark:bg-neutral-800">
+ <div
+ className="h-full rounded-full bg-dataviz"
+ style={{ width: `${(journey.count / largest) * 100}%` }}
+ />
+ </div>
+ <span className="w-14 text-right font-medium tabular-nums">
+ {journey.count.toLocaleString()}
+ </span>
+ </div>
+ </td>
+ <td className={cn(TD, "text-right tabular-nums text-neutral-600 dark:text-neutral-300")}>
+ {`${journey.percentage.toFixed(1)}%`}
+ </td>
+ {previousCounts && (
+ <td className={cn(TD, "text-right")}>
+ {previous === undefined ? (
+ <span
+ className="text-xs text-neutral-500 dark:text-neutral-400"
+ title={t("Not among the top paths of the comparison period")}
+ >
+ {NO_DELTA_TEXT}
+ </span>
+ ) : (
+ <Delta value={percentDelta(journey.count, previous)} />
+ )}
+ </td>
+ )}
+ {hasGoal && (
+ <td className={cn(TD, "text-right tabular-nums")}>
+ {journey.conversions ? (
+ <>
+ <span className="font-medium">
+ {journey.conversions === journey.count
+ ? "100%"
+ : `${((journey.conversions / journey.count) * 100).toFixed(1)}%`}
+ </span>
+ <span className="ml-1.5 inline-block w-10 text-left text-xs text-neutral-500 dark:text-neutral-400">
+ {journey.conversions.toLocaleString()}
+ </span>
+ </>
+ ) : (
+ <>
+ <span className="text-neutral-500 dark:text-neutral-400">0%</span>
+ <span className="ml-1.5 inline-block w-10" />
+ </>
+ )}
+ </td>
+ )}
+ <td className={cn(TD, "pr-3")}>
+ <PathActions
+ path={journey.path}
+ handlers={handlers}
+ showLabels={isPinned}
+ className={cn(
+ "flex-nowrap justify-end",
+ !isPinned && "[&_a]:text-neutral-500 [&_button]:text-neutral-500"
+ )}
+ />
+ </td>
+ </tr>
+ );
+ })}
+ {!isLoading && visible.length === 0 && (
+ <tr>
+ <td
+ colSpan={columnCount}
+ className="px-4 py-8 text-center text-sm text-neutral-500 dark:text-neutral-400"
+ >
+ {journeys.length === 0 ? t("No paths in this range.") : t("No paths match this filter.")}
+ </td>
+ </tr>
+ )}
+ </tbody>
+ </table>
+ </div>
+
+ {!isLoading && matching.length > 0 && (
+ <div className="flex items-center justify-between border-t border-neutral-100 px-4 py-2 text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400">
+ <span className="tabular-nums">
+ {t("Showing {shown} of {total} paths", {
+ shown: String(visible.length),
+ total: String(journeys.length),
+ })}
+ </span>
+ {matching.length > COLLAPSED_ROWS && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ className="font-normal text-neutral-600 dark:text-neutral-300"
+ aria-expanded={expanded}
+ onClick={() => setExpanded(!expanded)}
+ >
+ {expanded ? t("Show fewer") : t("Show all")}
+ {expanded ? <ChevronUp /> : <ChevronDown />}
+ </Button>
+ )}
+ </div>
+ )}
+ </Card>
+ );
+}
diff --git a/client/src/app/[site]/journeys/components/journeyUtils.test.ts b/client/src/app/[site]/journeys/components/journeyUtils.test.ts
new file mode 100644
index 000000000..d5d385b7b
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/journeyUtils.test.ts
@@ -0,0 +1,279 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildSankeyGraph,
+ connectedLinkIds,
+ JourneyRow,
+ largestExit,
+ layoutSankey,
+ linkId,
+ nodeId,
+ NODE_WIDTH,
+ pagePatternToRegExp,
+ pathContainsPage,
+ pathContinuation,
+ pathKey,
+ sectionOfPage,
+ startsWithPath,
+ truncateMiddle,
+} from "./journeyUtils";
+
+// 1,000 multi-page sessions in total; these four paths cover 600 of them.
+const journey = (path: string[], count: number): JourneyRow => ({ path, count, percentage: count / 10 });
+const JOURNEYS = [
+ journey(["/", "/pricing"], 300),
+ journey(["/", "/pricing", "/signup"], 150),
+ journey(["/", "/demo", "/pricing", "/signup"], 100),
+ journey(["/docs", "/pricing"], 50),
+];
+
+const node = (graph: ReturnType<typeof buildSankeyGraph>, step: number, name: string) => {
+ const found = graph.nodes.find(candidate => candidate.id === nodeId(step, name));
+ if (!found) throw new Error(`no node ${step} ${name}`);
+ return found;
+};
+
+describe("pathKey and startsWithPath", () => {
+ it("tells apart paths a separator would merge", () => {
+ expect(pathKey(["/a > /b"])).not.toBe(pathKey(["/a", "/b"]));
+ expect(pathKey(["/a", "/b"])).toBe(pathKey(["/a", "/b"]));
+ });
+
+ it("matches a path against a prefix", () => {
+ expect(startsWithPath(["/", "/pricing", "/signup"], ["/", "/pricing"])).toBe(true);
+ expect(startsWithPath(["/", "/pricing"], ["/", "/pricing"])).toBe(true);
+ expect(startsWithPath(["/", "/pricing"], ["/", "/pricing", "/signup"])).toBe(false);
+ expect(startsWithPath(["/", "/pricing"], ["/pricing"])).toBe(false);
+ });
+});
+
+describe("page patterns", () => {
+ it("matches one segment with * and any number with **", () => {
+ expect(pagePatternToRegExp("/blog/*").test("/blog/post")).toBe(true);
+ expect(pagePatternToRegExp("/blog/*").test("/blog/2026/post")).toBe(false);
+ expect(pagePatternToRegExp("/docs/**").test("/docs/api/events")).toBe(true);
+ expect(pagePatternToRegExp("/docs/**").test("/docs")).toBe(false);
+ });
+
+ it("treats every other character literally", () => {
+ expect(pagePatternToRegExp("/v1.2/*").test("/v1x2/a")).toBe(false);
+ expect(pagePatternToRegExp("/v1.2/*").test("/v1.2/a")).toBe(true);
+ expect(pagePatternToRegExp("/a(b)+/**").test("/a(b)+/c")).toBe(true);
+ });
+
+ it("finds a page by any part of its name, or by a whole-page pattern", () => {
+ const path = ["/", "/docs/script", "/Pricing"];
+ expect(pathContainsPage(path, "")).toBe(true);
+ expect(pathContainsPage(path, " ")).toBe(true);
+ expect(pathContainsPage(path, "pricing")).toBe(true);
+ expect(pathContainsPage(path, "script")).toBe(true);
+ expect(pathContainsPage(path, "/docs/**")).toBe(true);
+ expect(pathContainsPage(path, "/docs/*/more")).toBe(false);
+ expect(pathContainsPage(path, "signup")).toBe(false);
+ });
+
+ it("names the section of a page the way the server groups it", () => {
+ expect(sectionOfPage("/docs/script")).toBe("/docs/**");
+ expect(sectionOfPage("/docs/api/events")).toBe("/docs/**");
+ expect(sectionOfPage("/docs")).toBe("/docs");
+ expect(sectionOfPage("/docs/")).toBe("/docs/");
+ expect(sectionOfPage("/")).toBe("/");
+ });
+});
+
+describe("buildSankeyGraph", () => {
+ const graph = buildSankeyGraph(JOURNEYS, 4);
+
+ it("counts a page once per step, from every path through it", () => {
+ expect(node(graph, 0, "/").count).toBe(550);
+ expect(node(graph, 1, "/pricing").count).toBe(500);
+ expect(node(graph, 2, "/pricing").count).toBe(100);
+ expect(graph.stepTotals).toEqual([600, 600, 250, 100]);
+ });
+
+ it("gives a page its own share, not the share of the first path through it", () => {
+ // The old tooltip showed 30% here: the share of "/ > /pricing" alone.
+ expect(node(graph, 0, "/").percentage).toBeCloseTo(55);
+ expect(node(graph, 1, "/pricing").percentage).toBeCloseTo(50);
+ });
+
+ it("counts the sessions that ended on a page: those whose path stops there", () => {
+ const pricing = node(graph, 1, "/pricing");
+ expect(pricing.continued).toBe(150);
+ expect(pricing.exits).toBe(350);
+ expect(node(graph, 0, "/").exits).toBe(0);
+ expect(node(graph, 2, "/signup").exits).toBe(150);
+ });
+
+ it("reports no exits on the last step, where a path may have been cut short", () => {
+ expect(node(graph, 3, "/signup").exits).toBeNull();
+ });
+
+ it("reports no exits at all when paths are cut at an end page", () => {
+ const cut = buildSankeyGraph(JOURNEYS, 4, false);
+ expect(cut.nodes.every(candidate => candidate.exits === null)).toBe(true);
+ });
+
+ it("merges the sessions of every path that shares a link", () => {
+ const home = nodeId(0, "/");
+ const pricing = nodeId(1, "/pricing");
+ const link = graph.links.find(candidate => candidate.id === linkId(home, pricing));
+ expect(link?.value).toBe(450);
+ expect(
+ node(graph, 0, "/")
+ .outgoing.map(candidate => candidate.value)
+ .sort()
+ ).toEqual([100, 450]);
+ expect(
+ node(graph, 1, "/pricing")
+ .incoming.map(candidate => candidate.value)
+ .sort()
+ ).toEqual([450, 50]);
+ });
+
+ it("ignores pages beyond the requested steps", () => {
+ const short = buildSankeyGraph(JOURNEYS, 2);
+ expect(short.stepTotals).toEqual([600, 600]);
+ expect(short.nodes.every(candidate => candidate.step < 2)).toBe(true);
+ });
+
+ it("is empty for no journeys", () => {
+ expect(buildSankeyGraph([], 4)).toEqual({ nodes: [], links: [], stepTotals: [] });
+ });
+});
+
+describe("connectedLinkIds", () => {
+ const graph = buildSankeyGraph(JOURNEYS, 4);
+ const link = (source: string, target: string) => {
+ const found = graph.links.find(candidate => candidate.id === linkId(source, target));
+ if (!found) throw new Error("no link");
+ return found;
+ };
+
+ it("follows a link forwards and backwards, and nothing beside it", () => {
+ const connected = connectedLinkIds(graph, [link(nodeId(1, "/demo"), nodeId(2, "/pricing"))]);
+ expect([...connected].sort()).toEqual(
+ [
+ linkId(nodeId(0, "/"), nodeId(1, "/demo")),
+ linkId(nodeId(1, "/demo"), nodeId(2, "/pricing")),
+ linkId(nodeId(2, "/pricing"), nodeId(3, "/signup")),
+ ].sort()
+ );
+ });
+});
+
+describe("pathContinuation", () => {
+ it("counts the sessions that got as far as each page of the path", () => {
+ expect(pathContinuation(JOURNEYS, ["/", "/pricing", "/signup"])).toEqual([
+ { page: "/", sessions: 550, continued: null },
+ { page: "/pricing", sessions: 450, continued: 450 / 550 },
+ { page: "/signup", sessions: 150, continued: 150 / 450 },
+ ]);
+ });
+
+ it("is zero, without dividing by it, for a path none of the journeys take", () => {
+ expect(pathContinuation(JOURNEYS, ["/nowhere", "/else"])).toEqual([
+ { page: "/nowhere", sessions: 0, continued: null },
+ { page: "/else", sessions: 0, continued: null },
+ ]);
+ });
+});
+
+describe("largestExit", () => {
+ it("picks the path where the most sessions ended while others carried on", () => {
+ expect(largestExit(JOURNEYS, 4)).toEqual({ path: ["/", "/pricing"], exits: 300, sessions: 450 });
+ });
+
+ it("skips a path nobody on the shown paths continues: nothing to compare the exits with", () => {
+ expect(largestExit([journey(["/blog", "/pricing"], 900), ...JOURNEYS], 4)).toEqual({
+ path: ["/", "/pricing"],
+ exits: 300,
+ sessions: 450,
+ });
+ });
+
+ it("skips paths that fill every step, which may not have ended", () => {
+ expect(largestExit([journey(["/", "/a"], 10), journey(["/", "/b"], 5)], 2)).toBeNull();
+ });
+
+ it("is null without journeys", () => {
+ expect(largestExit([], 4)).toBeNull();
+ });
+});
+
+describe("layoutSankey", () => {
+ const graph = buildSankeyGraph(JOURNEYS, 4);
+ const layout = layoutSankey(graph, 4, 1104);
+ const placed = (step: number, name: string) => {
+ const found = layout.nodes.find(candidate => candidate.id === nodeId(step, name));
+ if (!found) throw new Error("no node");
+ return found;
+ };
+
+ it("spreads the columns across the width, leaving the last one room for labels", () => {
+ expect(layout.columns).toEqual([0, 296, 592, 888]);
+ expect(layout.width).toBe(1104);
+ expect(layout.labelWidths).toEqual([268, 268, 268, 188]);
+ });
+
+ it("uses one scale for bars and bands, set by the busiest step", () => {
+ expect(layout.scale).toBeCloseTo(320 / 600);
+ expect(placed(0, "/").height).toBeCloseTo(550 * layout.scale);
+ const band = layout.links.find(link => link.id === linkId(nodeId(0, "/"), nodeId(1, "/pricing")));
+ expect(band?.thickness).toBeCloseTo(450 * layout.scale);
+ });
+
+ it("stacks rows without overlap and keeps a label's height for thin bars", () => {
+ for (let step = 0; step < 4; step++) {
+ const column = layout.nodes.filter(candidate => candidate.step === step).sort((a, b) => a.y - b.y);
+ for (let i = 1; i < column.length; i++) {
+ const above = column[i - 1];
+ expect(column[i].y).toBeGreaterThanOrEqual(above.y + Math.max(above.height, 34));
+ }
+ }
+ expect(layout.height).toBe(Math.max(...layout.columnBottoms));
+ });
+
+ it("orders the first column by size and later ones by where their sessions come from", () => {
+ expect(placed(0, "/").y).toBeLessThan(placed(0, "/docs").y);
+ // Both come from "/": the larger goes first.
+ expect(placed(1, "/pricing").y).toBeLessThan(placed(1, "/demo").y);
+ // /signup at step 3 is fed from /pricing (top of step 2); /pricing at step 3 from /demo below it.
+ expect(placed(2, "/signup").y).toBeLessThan(placed(2, "/pricing").y);
+ });
+
+ it("stacks a bar's bands from its top, in the order of the rows they lead to", () => {
+ const home = placed(0, "/");
+ const toPricing = layout.links.find(link => link.id === linkId(home.id, nodeId(1, "/pricing")));
+ const toDemo = layout.links.find(link => link.id === linkId(home.id, nodeId(1, "/demo")));
+ expect(toPricing?.sourceY).toBe(home.y);
+ expect(toDemo?.sourceY).toBeCloseTo(home.y + 450 * layout.scale);
+ });
+
+ it("keeps a minimum column pitch, growing wider than a narrow box", () => {
+ const narrow = layoutSankey(graph, 4, 340);
+ expect(narrow.columns).toEqual([0, 176, 352, 528]);
+ expect(narrow.width).toBe(528 + 140);
+ expect(narrow.labelWidths.every(width => width >= 140 - NODE_WIDTH - 20)).toBe(true);
+ });
+
+ it("switches to single-line rows when a column has many pages", () => {
+ const many = Array.from({ length: 30 }, (_, index) => journey(["/", `/page-${index}`], 30 - index));
+ expect(layoutSankey(buildSankeyGraph(many, 2), 2, 1000).compact).toBe(true);
+ expect(layout.compact).toBe(false);
+ });
+
+ it("lays out nothing for no journeys", () => {
+ const empty = layoutSankey(buildSankeyGraph([], 4), 4, 1000);
+ expect(empty.nodes).toEqual([]);
+ expect(empty.height).toBe(0);
+ });
+});
+
+describe("truncateMiddle", () => {
+ it("keeps short text and both ends of long text", () => {
+ expect(truncateMiddle("/pricing", 20)).toBe("/pricing");
+ expect(truncateMiddle("/blog/google-analytics-alternatives", 16)).toBe("/blog/go…natives");
+ expect(truncateMiddle("/blog/google-analytics-alternatives", 16)).toHaveLength(16);
+ expect(truncateMiddle("/abc", 1)).toBe("…");
+ });
+});
diff --git a/client/src/app/[site]/journeys/components/journeyUtils.ts b/client/src/app/[site]/journeys/components/journeyUtils.ts
new file mode 100644
index 000000000..0a891b3f3
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/journeyUtils.ts
@@ -0,0 +1,368 @@
+/** A journeys row: one exact page sequence from session start and the sessions that took it. */
+export interface JourneyRow {
+ path: string[];
+ count: number;
+ /** Share of the sessions with two or more pages, 0–100. */
+ percentage: number;
+ conversions?: number;
+}
+
+/** Identifies a path. Pages can contain any character, so they are not joined with a separator. */
+export const pathKey = (path: string[]) => JSON.stringify(path);
+
+export const startsWithPath = (path: string[], prefix: string[]) =>
+ prefix.length <= path.length && prefix.every((page, index) => path[index] === page);
+
+/** A fraction as a percentage with up to `digits` decimals and no trailing zeros: 27.4%, 100%, 0%. */
+export const formatShare = (fraction: number, digits = 1) => `${Number((fraction * 100).toFixed(digits))}%`;
+
+// ───────── page patterns ─────────
+
+/**
+ * The same wildcard grammar the server applies to step filters, goals and
+ * funnel steps: * is one path segment, ** is any number of them.
+ */
+export function pagePatternToRegExp(pattern: string): RegExp {
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
+ const source = escaped
+ .split("**")
+ .map(part => part.replace(/\*/g, "[^/]+"))
+ .join(".*");
+ return new RegExp(`^${source}$`);
+}
+
+/**
+ * Whether a path visits a page matching `query`. With a wildcard the query is
+ * a pattern for a whole page; without one it matches any part of a page, so
+ * typing "pricing" finds /pricing.
+ */
+export function pathContainsPage(path: string[], query: string): boolean {
+ const needle = query.trim();
+ if (!needle) return true;
+ if (needle.includes("*")) {
+ const pattern = pagePatternToRegExp(needle);
+ return path.some(page => pattern.test(page));
+ }
+ const lower = needle.toLowerCase();
+ return path.some(page => page.toLowerCase().includes(lower));
+}
+
+/**
+ * The section a page belongs to when pages are grouped: anything below a
+ * first-level folder becomes that folder's pattern (/docs/script → /docs/**),
+ * and top-level pages keep their own name. Mirrors the server's grouping.
+ */
+export function sectionOfPage(page: string): string {
+ const match = /^(\/[^/]+)\/.+/.exec(page);
+ return match ? `${match[1]}/**` : page;
+}
+
+// ───────── the graph ─────────
+
+export interface SankeyLink {
+ id: string;
+ source: string;
+ target: string;
+ /** Sessions that went from the source page to the target page at this step. */
+ value: number;
+}
+
+export interface SankeyNode {
+ id: string;
+ name: string;
+ /** Zero-based step. */
+ step: number;
+ /** Sessions on the shown paths that were on this page at this step. */
+ count: number;
+ /** How many of them went on to another shown step. */
+ continued: number;
+ /**
+ * How many ended the session here. Null on the last step, where a path may
+ * have been cut short, and when paths are cut at an end page.
+ */
+ exits: number | null;
+ /** Share of the sessions with two or more pages, 0–100. */
+ percentage: number;
+ incoming: SankeyLink[];
+ outgoing: SankeyLink[];
+}
+
+export interface SankeyGraph {
+ nodes: SankeyNode[];
+ links: SankeyLink[];
+ /** Sessions on the shown paths at each step. */
+ stepTotals: number[];
+}
+
+export const nodeId = (step: number, name: string) => `${step}_${name}`;
+export const linkId = (source: string, target: string) => `${source}|||${target}`;
+
+/**
+ * Folds the journeys into the nodes and links of the diagram. Every figure is
+ * a sum over the journeys given, so it describes the shown paths, not the
+ * whole site.
+ *
+ * A journey shorter than `steps` is a session that ended on its last page; one
+ * that fills every step may have gone on, so the last step reports no exits.
+ * `exitsKnown` is false when the journeys were cut at an end page instead of
+ * where the session ended.
+ */
+export function buildSankeyGraph(journeys: JourneyRow[], steps: number, exitsKnown = true): SankeyGraph {
+ const nodes = new Map<string, SankeyNode>();
+ const links = new Map<string, SankeyLink>();
+ const stepTotals: number[] = [];
+
+ for (const journey of journeys) {
+ const path = journey.path.slice(0, steps);
+ path.forEach((name, step) => {
+ const id = nodeId(step, name);
+ let node = nodes.get(id);
+ if (!node) {
+ node = { id, name, step, count: 0, continued: 0, exits: null, percentage: 0, incoming: [], outgoing: [] };
+ nodes.set(id, node);
+ }
+ node.count += journey.count;
+ node.percentage += journey.percentage;
+ stepTotals[step] = (stepTotals[step] ?? 0) + journey.count;
+
+ if (step < path.length - 1) {
+ node.continued += journey.count;
+ const target = nodeId(step + 1, path[step + 1]);
+ const id = linkId(node.id, target);
+ const link = links.get(id);
+ if (link) link.value += journey.count;
+ else links.set(id, { id, source: node.id, target, value: journey.count });
+ }
+ });
+ }
+
+ for (const link of links.values()) {
+ nodes.get(link.source)?.outgoing.push(link);
+ nodes.get(link.target)?.incoming.push(link);
+ }
+ for (const node of nodes.values()) {
+ node.exits = exitsKnown && node.step < steps - 1 ? node.count - node.continued : null;
+ }
+
+ return { nodes: [...nodes.values()], links: [...links.values()], stepTotals };
+}
+
+/** Every link reachable from `start` going forwards and every link leading to it. */
+export function connectedLinkIds(graph: SankeyGraph, start: SankeyLink[]): Set<string> {
+ const nodesById = new Map(graph.nodes.map(node => [node.id, node]));
+ const connected = new Set<string>();
+
+ const walk = (direction: "forward" | "backward") => {
+ const queue = [...start];
+ const seen = new Set<string>();
+ for (let link = queue.shift(); link; link = queue.shift()) {
+ if (seen.has(link.id)) continue;
+ seen.add(link.id);
+ connected.add(link.id);
+ const next =
+ direction === "forward" ? nodesById.get(link.target)?.outgoing : nodesById.get(link.source)?.incoming;
+ if (next) queue.push(...next);
+ }
+ };
+ walk("forward");
+ walk("backward");
+
+ return connected;
+}
+
+// ───────── one path ─────────
+
+export interface ContinuationStep {
+ page: string;
+ /** Sessions on the shown paths that followed the path up to and including this page. */
+ sessions: number;
+ /** Share of the previous step's sessions that got here; null on the first step. */
+ continued: number | null;
+}
+
+/** How the sessions on the shown paths thin out along one path, page by page. */
+export function pathContinuation(journeys: JourneyRow[], path: string[]): ContinuationStep[] {
+ let previous: number | null = null;
+ return path.map((page, index) => {
+ const prefix = path.slice(0, index + 1);
+ const sessions = journeys.reduce(
+ (total, journey) => (startsWithPath(journey.path, prefix) ? total + journey.count : total),
+ 0
+ );
+ const continued = previous === null || previous === 0 ? null : sessions / previous;
+ previous = sessions;
+ return { page, sessions, continued };
+ });
+}
+
+export interface PathExit {
+ path: string[];
+ /** Sessions that took exactly this path and ended there. */
+ exits: number;
+ /** Sessions on the shown paths that started with this path. */
+ sessions: number;
+}
+
+/**
+ * The shown path where the most sessions ended while others carried on: a
+ * journey shorter than `steps` (so the session ended on its last page) that at
+ * least one other shown journey continues.
+ */
+export function largestExit(journeys: JourneyRow[], steps: number): PathExit | null {
+ let best: PathExit | null = null;
+ for (const journey of journeys) {
+ if (journey.path.length >= steps || journey.path.length < 2) continue;
+ if (best && journey.count <= best.exits) continue;
+ const sessions = journeys.reduce(
+ (total, other) => (startsWithPath(other.path, journey.path) ? total + other.count : total),
+ 0
+ );
+ if (sessions > journey.count) best = { path: journey.path, exits: journey.count, sessions };
+ }
+ return best;
+}
+
+// ───────── layout ─────────
+
+export interface LaidOutNode extends SankeyNode {
+ x: number;
+ /** Top of the bar. */
+ y: number;
+ height: number;
+}
+
+export interface LaidOutLink extends SankeyLink {
+ /** Top edge of the band where it leaves the source and where it enters the target. */
+ sourceY: number;
+ targetY: number;
+ thickness: number;
+}
+
+export interface SankeyLayout {
+ nodes: LaidOutNode[];
+ links: LaidOutLink[];
+ /** Left edge of each step's column. */
+ columns: number[];
+ /** Horizontal room for a label next to a bar, per column. */
+ labelWidths: number[];
+ /** Rows are too many for two-line labels. */
+ compact: boolean;
+ /** Pixels per session, the same for bars and bands. */
+ scale: number;
+ width: number;
+ height: number;
+ /** Bottom of the lowest row in each column. */
+ columnBottoms: number[];
+}
+
+export const NODE_WIDTH = 8;
+const NODE_GAP = 8;
+const MIN_NODE_HEIGHT = 2;
+// A row is at least as tall as its two-line label (one line when compact).
+const ROW_HEIGHT = 34;
+const COMPACT_ROW_HEIGHT = 18;
+const COMPACT_ABOVE_ROWS = 18;
+// The tallest column's bars add up to this many pixels.
+const BAR_BUDGET = 320;
+const MIN_COLUMN_STEP = 176;
+// Space kept clear between a label and the next column's bar.
+const LABEL_GUTTER = 20;
+const LAST_COLUMN_WIDTH = 216;
+const MIN_LAST_COLUMN_WIDTH = 140;
+
+/**
+ * Positions the graph in a `width`-wide box. Columns keep a minimum pitch, so
+ * the result can be wider than the box (the caller scrolls). Rows are ordered
+ * to keep the big bands from crossing: the first column by size, the rest by
+ * the page most of their sessions come from.
+ */
+export function layoutSankey(graph: SankeyGraph, steps: number, width: number): SankeyLayout {
+ const columnCount = Math.max(steps, 1);
+ const lastColumnWidth = Math.max(MIN_LAST_COLUMN_WIDTH, Math.min(LAST_COLUMN_WIDTH, width / columnCount));
+ const columnStep = columnCount > 1 ? Math.max(MIN_COLUMN_STEP, (width - lastColumnWidth) / (columnCount - 1)) : width;
+ const columns = Array.from({ length: columnCount }, (_, step) => step * columnStep);
+ const laidOutWidth = columnCount > 1 ? columns[columnCount - 1] + lastColumnWidth : width;
+
+ const scale = BAR_BUDGET / Math.max(1, ...graph.stepTotals.filter(Boolean));
+ const byStep: SankeyNode[][] = Array.from({ length: columnCount }, () => []);
+ for (const node of graph.nodes) byStep[node.step]?.push(node);
+
+ const compact = byStep.some(column => column.length > COMPACT_ABOVE_ROWS);
+ const rowHeight = compact ? COMPACT_ROW_HEIGHT : ROW_HEIGHT;
+
+ const placed = new Map<string, LaidOutNode>();
+ const columnBottoms: number[] = [];
+
+ byStep.forEach((column, step) => {
+ // A row sits by the page most of its sessions came from; rows that share
+ // one are ordered by size. Children of the top row come first, so the big
+ // bands run level and the small ones do the crossing.
+ const origin = (node: SankeyNode) => {
+ let main: SankeyLink | undefined;
+ for (const link of node.incoming) {
+ if (placed.has(link.source) && (!main || link.value > main.value)) main = link;
+ }
+ return main ? (placed.get(main.source)?.y ?? 0) : Number.POSITIVE_INFINITY;
+ };
+ const origins = new Map(column.map(node => [node.id, step === 0 ? 0 : origin(node)]));
+ const ordered = [...column].sort(
+ (a, b) => (origins.get(a.id) ?? 0) - (origins.get(b.id) ?? 0) || b.count - a.count || a.name.localeCompare(b.name)
+ );
+
+ let y = 0;
+ for (const node of ordered) {
+ const height = Math.max(MIN_NODE_HEIGHT, node.count * scale);
+ placed.set(node.id, { ...node, x: columns[step], y, height });
+ y += Math.max(height, rowHeight) + NODE_GAP;
+ }
+ columnBottoms.push(Math.max(0, y - NODE_GAP));
+ });
+
+ // Bands stack from the top of each bar, in the order of the rows they connect to.
+ const positions = new Map<string, { sourceY: number; targetY: number }>();
+ const position = (id: string) => {
+ let entry = positions.get(id);
+ if (!entry) {
+ entry = { sourceY: 0, targetY: 0 };
+ positions.set(id, entry);
+ }
+ return entry;
+ };
+ for (const node of placed.values()) {
+ const rowOf = (id: string) => placed.get(id)?.y ?? 0;
+ let y = node.y;
+ for (const link of [...node.outgoing].sort((a, b) => rowOf(a.target) - rowOf(b.target))) {
+ position(link.id).sourceY = y;
+ y += link.value * scale;
+ }
+ y = node.y;
+ for (const link of [...node.incoming].sort((a, b) => rowOf(a.source) - rowOf(b.source))) {
+ position(link.id).targetY = y;
+ y += link.value * scale;
+ }
+ }
+
+ return {
+ nodes: [...placed.values()],
+ links: graph.links.map(link => ({ ...link, ...position(link.id), thickness: link.value * scale })),
+ columns,
+ labelWidths: columns.map(
+ (_, step) => (step === columnCount - 1 ? lastColumnWidth : columnStep) - NODE_WIDTH - LABEL_GUTTER
+ ),
+ compact,
+ scale,
+ width: laidOutWidth,
+ height: Math.max(0, ...columnBottoms),
+ columnBottoms,
+ };
+}
+
+/** Shortens a page to about `maxChars`, keeping both ends: the tail of a path says the most. */
+export function truncateMiddle(text: string, maxChars: number): string {
+ if (text.length <= maxChars) return text;
+ if (maxChars <= 1) return "…";
+ const keep = maxChars - 1;
+ const head = Math.ceil(keep / 2);
+ const tail = Math.floor(keep / 2);
+ return `${text.slice(0, head)}…${tail > 0 ? text.slice(-tail) : ""}`;
+}
diff --git a/client/src/app/[site]/journeys/components/useJourneyLinks.ts b/client/src/app/[site]/journeys/components/useJourneyLinks.ts
new file mode 100644
index 000000000..f76df4350
--- /dev/null
+++ b/client/src/app/[site]/journeys/components/useJourneyLinks.ts
@@ -0,0 +1,30 @@
+import { usePivotHref } from "@/hooks/usePivotHref";
+import { useStore } from "@/lib/store";
+
+/**
+ * Where a page name leads: the Pages page with the current period and filters,
+ * narrowed to that page. The shared pivots only know the Sessions, Users and
+ * Replay pages, so this borrows the Sessions link (same query string, built by
+ * the same serializer) and points it at Pages.
+ *
+ * Returns undefined for a section such as /docs/**, which is not one page.
+ */
+export function usePagesHref(): (page: string) => string | undefined {
+ const pivotHref = usePivotHref();
+
+ return page => {
+ if (page.includes("*")) return undefined;
+ const href = pivotHref("sessions", [{ parameter: "pathname", type: "equals", value: [page] }]);
+ const queryStart = href.indexOf("?");
+ const path = queryStart === -1 ? href : href.slice(0, queryStart);
+ const query = queryStart === -1 ? "" : href.slice(queryStart);
+ return `${path.replace(/\/sessions$/, "/pages")}${query}`;
+ };
+}
+
+/** A page of the current site, staying inside a private-link view. */
+export function useSiteHref(): (route: string) => string {
+ const site = useStore(state => state.site);
+ const privateKey = useStore(state => state.privateKey);
+ return route => (privateKey ? `/${site}/${privateKey}/${route}` : `/${site}/${route}`);
+}
diff --git a/client/src/app/[site]/journeys/page.tsx b/client/src/app/[site]/journeys/page.tsx
index 3086f9749..66f53f66f 100644
--- a/client/src/app/[site]/journeys/page.tsx
+++ b/client/src/app/[site]/journeys/page.tsx
@@ -1,160 +1,448 @@
"use client";
+import { FolderTree, LogIn, LogOut, Route, Target } from "lucide-react";
import { useExtracted } from "next-intl";
-import { useJourneys } from "@/api/analytics/hooks/useGetJourneys";
-import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
-import { InputWithSuggestions, SuggestionOption } from "@/components/ui/input-with-suggestions";
-import { Slider } from "@/components/ui/slider";
-import { AlertCircle } from "lucide-react";
-import { useState } from "react";
-import { useGetSite } from "../../../api/admin/hooks/useSites";
-import { useMetric } from "../../../api/analytics/hooks/useGetMetric";
-import { DisabledOverlay } from "../../../components/DisabledOverlay";
-import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
-import { timeZone } from "../../../lib/dateTimeUtils";
-import { useStore } from "../../../lib/store";
-import { JOURNEY_PAGE_FILTERS } from "../../../lib/filterGroups";
+import Link from "next/link";
+import { ReactNode, useMemo, useState } from "react";
+import { useGetSite } from "@/api/admin/hooks/useSites";
+import { JourneyGrouping } from "@/api/analytics/endpoints";
+import { useGetGoals } from "@/api/analytics/hooks/goals/useGetGoals";
+import { JourneyShape, useJourneys, useJourneySummary } from "@/api/analytics/hooks/useGetJourneys";
+import { useMetric } from "@/api/analytics/hooks/useGetMetric";
+import { DisabledOverlay } from "@/components/DisabledOverlay";
+import { ErrorState } from "@/components/ErrorState";
+import { AnalysisBar } from "@/components/site/AnalysisBar";
+import { ChartLegend } from "@/components/site/ChartLegend";
+import { InsightRow } from "@/components/site/InsightRow";
+import { Button } from "@/components/ui/button";
+import { Card, CardLoader } from "@/components/ui/card";
+import { Skeleton } from "@/components/ui/skeleton";
+import { useCanOnSite } from "@/hooks/usePermissions";
+import { useSetPageTitle } from "@/hooks/useSetPageTitle";
+import { JOURNEY_PAGE_FILTERS } from "@/lib/filterGroups";
+import { useComparisonEnabled, useStore } from "@/lib/store";
import { SubHeader } from "../components/SubHeader/SubHeader";
+import {
+ OptionControl,
+ PagePicker,
+ PageSuggestion,
+ StepFilterButton,
+ StepsStepper,
+} from "./components/JourneyControls";
+import { JourneyStats } from "./components/JourneyStats";
+import { formatShare, largestExit, pathKey, sectionOfPage } from "./components/journeyUtils";
+import { PathActionHandlers, PathActions } from "./components/PathActions";
+import { PathChips } from "./components/PathChips";
+import { PathSessionsSheet, PathSessionsTarget } from "./components/PathSessionsSheet";
+import { PinnedPath } from "./components/PinnedPath";
import { SankeyDiagram } from "./components/SankeyDiagram";
+import { SaveAsFunnelDialog } from "./components/SaveAsFunnelDialog";
+import { TopPaths } from "./components/TopPaths";
+import { usePagesHref, useSiteHref } from "./components/useJourneyLinks";
+
+// The server takes 2 to 10 steps and up to 500 paths.
+const MIN_STEPS = 2;
+const MAX_STEPS = 10;
+const PATH_LIMITS = [10, 15, 25, 50, 100, 200, 500];
+// The comparison period is asked for as many paths as the server gives, so a
+// path that ranked lower then is still found.
+const COMPARISON_LIMIT = 500;
+// Below this column pitch a step header has room for its session count only.
+const WIDE_STEP_HEADER = 216;
+const NO_GOAL = "none";
+
+// Sankey-shaped placeholder: columns of blocks thinning to the right.
+const SKELETON_COLUMNS: string[][] = [
+ ["h-24", "h-10", "h-8", "h-6"],
+ ["h-16", "h-12", "h-8", "h-6", "h-4"],
+ ["h-12", "h-8", "h-6"],
+ ["h-8", "h-6", "h-4"],
+];
+
+function SankeySkeleton() {
+ return (
+ <div className="flex min-h-[320px] items-start gap-10 py-2" aria-hidden>
+ {SKELETON_COLUMNS.map((column, i) => (
+ <div key={i} className="flex flex-1 flex-col gap-2.5">
+ {column.map((height, j) => (
+ <Skeleton key={j} className={`${height} w-2/3 rounded`} />
+ ))}
+ </div>
+ ))}
+ </div>
+ );
+}
export default function JourneysPage() {
const t = useExtracted();
useSetPageTitle("Journeys");
- const [steps, setSteps] = useState<number>(4);
- const [maxJourneys, setMaxJourneys] = useState<number>(50);
+ const [steps, setSteps] = useState(4);
+ const [limit, setLimit] = useState(15);
const [stepFilters, setStepFilters] = useState<Record<number, string>>({});
+ const [endsAt, setEndsAt] = useState("");
+ const [groupBy, setGroupBy] = useState<JourneyGrouping>("path");
+ // A goal id, NO_GOAL, or null until the viewer chooses: the default goal then stands in.
+ const [goalChoice, setGoalChoice] = useState<string | null>(null);
+ const [defaultGoalId, setDefaultGoalId] = useState<number | null>(null);
+ const [pinnedKey, setPinnedKey] = useState<string | null>(null);
+ const [sessionsTarget, setSessionsTarget] = useState<PathSessionsTarget | null>(null);
+ const [funnelPath, setFunnelPath] = useState<string[] | null>(null);
const { data: siteMetadata } = useGetSite();
- const { time } = useStore();
+ const privateKey = useStore(state => state.privateKey);
+ const canWriteFunnels = useCanOnSite("funnels:write");
+ const comparisonEnabled = useComparisonEnabled();
+ const pageHref = usePagesHref();
+ const siteHref = useSiteHref();
- // Fetch path suggestions
- const { data: pathsData } = useMetric({
- parameter: "pathname",
- limit: 1000,
- useFilters: false,
- });
+ const { data: goalsData, isLoading: isLoadingGoals } = useGetGoals({ pageSize: 100 });
+ const goals = goalsData?.data ?? [];
+ // The default is the goal with the most conversions when the list first
+ // arrives. It is kept from then on, so a new date range (which reloads the
+ // list with new counts) does not swap the goal under the viewer.
+ const busiestGoal = goals.reduce<(typeof goals)[number] | undefined>(
+ (best, goal) => (!best || goal.total_conversions > best.total_conversions ? goal : best),
+ undefined
+ );
+ if (defaultGoalId === null && busiestGoal) setDefaultGoalId(busiestGoal.goalId);
+ const defaultGoal = goals.find(candidate => candidate.goalId === defaultGoalId) ?? busiestGoal;
+ const goal =
+ goalChoice === NO_GOAL
+ ? undefined
+ : (goals.find(candidate => String(candidate.goalId) === goalChoice) ?? defaultGoal);
+ const goalName = goal ? goal.name || t("Goal #{id}", { id: String(goal.goalId) }) : null;
- const pathSuggestions: SuggestionOption[] =
- pathsData?.data?.map(item => ({
- value: item.value,
- label: item.value,
- count: item.count,
- })) ?? [];
+ // A filter on a step that is no longer shown would match nothing.
+ const activeStepFilters = Object.fromEntries(
+ Object.entries(stepFilters).filter(([step, pattern]) => pattern && Number(step) < steps)
+ );
+ const shape: JourneyShape = { steps, stepFilters: activeStepFilters, endsAt, groupBy };
+ const hasPathFilters = Object.keys(activeStepFilters).length > 0 || !!endsAt;
+ // Paths cut at an end page stop where the page is reached, not where the session ended.
+ const exitsKnown = !endsAt;
- const { data, isLoading, error } = useJourneys({
+ // The goal is part of the request: wait for the goal list rather than ask twice.
+ const journeysQuery = useJourneys({
+ siteId: siteMetadata?.siteId,
+ ...shape,
+ limit,
+ goalId: goal?.goalId,
+ enabled: !isLoadingGoals,
+ });
+ const previousJourneysQuery = useJourneys({
siteId: siteMetadata?.siteId,
- steps,
- timeZone,
- time,
- limit: maxJourneys,
- stepFilters,
+ ...shape,
+ limit: COMPARISON_LIMIT,
+ periodTime: "previous",
+ enabled: !isLoadingGoals,
+ });
+ const summaryQuery = useJourneySummary({ goalId: goal?.goalId, enabled: !isLoadingGoals });
+ const previousSummaryQuery = useJourneySummary({
+ goalId: goal?.goalId,
+ periodTime: "previous",
+ enabled: !isLoadingGoals,
});
+ const { data: pathsData } = useMetric({ parameter: "pathname", limit: 1000, useFilters: false });
+ const pageSuggestions = useMemo(() => {
+ const pages: PageSuggestion[] = pathsData?.data?.map(item => ({ value: item.value, count: item.count })) ?? [];
+ if (groupBy === "path") return pages;
+ // Grouped steps are sections, so that is what a step can be filtered to.
+ const sections = new Map<string, number>();
+ for (const page of pages) {
+ const section = sectionOfPage(page.value);
+ sections.set(section, (sections.get(section) ?? 0) + (page.count ?? 0));
+ }
+ return [...sections].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count);
+ }, [pathsData, groupBy]);
+
+ const journeys = journeysQuery.data?.journeys ?? [];
+ const totalSessions = journeysQuery.data?.totalSessions ?? 0;
+ const isLoading = isLoadingGoals || journeysQuery.isLoading || !siteMetadata;
+ const covered = journeys.reduce((total, journey) => total + journey.count, 0);
+ const pinnedJourney = journeys.find(journey => pathKey(journey.path) === pinnedKey);
+ const exit = exitsKnown && !isLoading ? largestExit(journeys, steps) : null;
+
+ const previousJourneys = previousJourneysQuery.data?.journeys;
+ const previousCounts = useMemo(
+ () =>
+ comparisonEnabled && previousJourneys
+ ? new Map(previousJourneys.map(journey => [pathKey(journey.path), journey.count]))
+ : null,
+ [comparisonEnabled, previousJourneys]
+ );
+
+ const summary = summaryQuery.data;
+ const overallReach =
+ summary && summary.conversions !== null && summary.sessions > 0 ? summary.conversions / summary.sessions : null;
+
+ const togglePin = (path: string[]) => {
+ const key = pathKey(path);
+ setPinnedKey(current => (current === key ? null : key));
+ };
+ const setStepFilter = (step: number, pattern: string) => {
+ setStepFilters(current => {
+ const next = { ...current };
+ if (pattern) next[step] = pattern;
+ else delete next[step];
+ return next;
+ });
+ };
+ const handlers: PathActionHandlers = {
+ openSessions: (path, replaysOnly) => {
+ const key = pathKey(path);
+ const count = journeys.find(journey => pathKey(journey.path) === key)?.count;
+ setSessionsTarget({ path, count, replaysOnly });
+ },
+ // Public and private-link viewers hold no permissions.
+ saveAsFunnel: canWriteFunnels && !privateKey ? setFunnelPath : undefined,
+ };
+
+ const strong = (chunks: ReactNode) => (
+ <span className="font-medium tabular-nums text-neutral-900 dark:text-neutral-50">{chunks}</span>
+ );
+
return (
<DisabledOverlay message="User Journeys" featurePath="journeys">
- <div className="container mx-auto p-2 md:p-4">
+ <div className="mx-auto max-w-[1300px] space-y-3 p-2 md:p-4">
<SubHeader availableFilters={JOURNEY_PAGE_FILTERS} />
- <div className="flex items-center gap-6 my-1">
- <div className="flex items-center gap-3 w-[180px]">
- <span className="text-sm text-neutral-600 dark:text-neutral-300 whitespace-nowrap">
- {t("{steps} steps", { steps: String(steps) })}
- </span>
- <Slider
- value={[steps]}
- onValueChange={([value]) => setSteps(value)}
- min={2}
- max={6}
- step={1}
- className="flex-1"
- />
- </div>
- <div className="flex items-center gap-3 w-[200px]">
- <span className="text-sm text-neutral-600 dark:text-neutral-300 whitespace-nowrap">
- {t("{maxJourneys} journeys", { maxJourneys: String(maxJourneys) })}
- </span>
- <Slider
- value={[maxJourneys]}
- onValueChange={([value]) => setMaxJourneys(value)}
- min={10}
- max={200}
- step={10}
- className="flex-1"
+
+ <JourneyStats
+ summary={summary}
+ previous={comparisonEnabled ? previousSummaryQuery.data : undefined}
+ isLoading={isLoadingGoals || summaryQuery.isLoading}
+ goalName={goalName}
+ />
+
+ <AnalysisBar>
+ <span className="mx-1 hidden h-5 w-px bg-neutral-200 sm:block dark:bg-neutral-800" aria-hidden="true" />
+ {goals.length > 0 && (
+ <OptionControl
+ icon={<Target />}
+ label={t("Goal")}
+ value={goal ? String(goal.goalId) : NO_GOAL}
+ onChange={setGoalChoice}
+ options={[
+ { value: NO_GOAL, label: t("None") },
+ ...goals.map(candidate => ({
+ value: String(candidate.goalId),
+ label: candidate.name || t("Goal #{id}", { id: String(candidate.goalId) }),
+ })),
+ ]}
/>
+ )}
+ <OptionControl<JourneyGrouping>
+ icon={<FolderTree />}
+ label={t("Group pages")}
+ value={groupBy}
+ onChange={setGroupBy}
+ options={[
+ { value: "path", label: t("Exact path") },
+ { value: "section", label: t("By section") },
+ ]}
+ />
+ </AnalysisBar>
+
+ {exit && (
+ <InsightRow action={<PathActions path={exit.path} handlers={handlers} hideFunnel className="shrink-0" />}>
+ {t.rich(
+ "<b>{percent}</b> of sessions that start <path></path> end there ({exits} of {sessions}), the largest exit on the paths shown.",
+ {
+ percent: `${((exit.exits / exit.sessions) * 100).toFixed(1)}%`,
+ exits: exit.exits.toLocaleString(),
+ sessions: exit.sessions.toLocaleString(),
+ b: strong,
+ path: () => <PathChips path={exit.path} pageHref={pageHref} className="mx-0.5 align-middle" />,
+ }
+ )}
+ </InsightRow>
+ )}
+
+ <Card>
+ {journeysQuery.isFetching && !isLoading && <CardLoader />}
+ <div className="flex flex-col gap-3 border-b border-neutral-100 px-4 py-3 xl:flex-row xl:items-center xl:justify-between dark:border-neutral-850">
+ <div className="min-w-0">
+ <h2 className="font-semibold leading-none tracking-tight">{t("Paths from session start")}</h2>
+ <p className="mt-1.5 text-xs text-neutral-500 dark:text-neutral-400">
+ {journeys.length > 0 && totalSessions > 0
+ ? t.rich("Top {count} paths cover <b>{covered}</b> of {total} multi-page sessions ({percent})", {
+ count: String(journeys.length),
+ covered: covered.toLocaleString(),
+ total: totalSessions.toLocaleString(),
+ percent: `${((covered / totalSessions) * 100).toFixed(1)}%`,
+ b: chunks => (
+ <span className="tabular-nums text-neutral-700 dark:text-neutral-200">{chunks}</span>
+ ),
+ })
+ : t("The most common page sequences, from the first page of a session")}
+ </p>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <PagePicker
+ icon={<LogIn />}
+ label={t("Starts at")}
+ value={stepFilters[0] ?? ""}
+ onChange={pattern => setStepFilter(0, pattern)}
+ suggestions={pageSuggestions}
+ />
+ <PagePicker
+ icon={<LogOut />}
+ label={t("Ends at")}
+ value={endsAt}
+ onChange={setEndsAt}
+ suggestions={pageSuggestions}
+ />
+ <StepsStepper value={steps} onChange={setSteps} min={MIN_STEPS} max={MAX_STEPS} />
+ <OptionControl
+ label={t("Show")}
+ value={String(limit)}
+ onChange={value => setLimit(Number(value))}
+ options={PATH_LIMITS.map(count => ({
+ value: String(count),
+ label: t("Top {count} paths", { count: String(count) }),
+ }))}
+ />
+ </div>
</div>
- </div>
- {siteMetadata?.domain ? (
- <div className="relative">
- {isLoading && (
- <div className="absolute inset-0 bg-white/30 dark:bg-neutral-900/30 backdrop-blur-sm z-10 flex items-center justify-center">
- <div className="flex flex-col items-center gap-2">
- <div className="h-8 w-8 rounded-full border-2 border-accent-400 border-t-transparent animate-spin"></div>
- <span className="text-sm text-neutral-600 dark:text-neutral-300">{t("Loading journey data...")}</span>
+ <div className="px-4 pb-3 pt-3">
+ {isLoading ? (
+ <SankeySkeleton />
+ ) : journeysQuery.error ? (
+ <ErrorState
+ title={t("Failed to load journeys")}
+ message={journeysQuery.error.message}
+ refetch={journeysQuery.refetch}
+ />
+ ) : journeys.length > 0 && siteMetadata?.domain ? (
+ <>
+ <SankeyDiagram
+ journeys={journeys}
+ steps={steps}
+ maxJourneys={limit}
+ domain={siteMetadata.domain}
+ pinnedPath={pinnedJourney?.path}
+ onPinPath={togglePin}
+ exitsKnown={exitsKnown}
+ pageHref={pageHref}
+ renderStepHeader={({ index, sessions, previousSessions, width }) => (
+ <>
+ <span className="whitespace-nowrap text-xs font-medium text-neutral-900 dark:text-neutral-100">
+ {index === 0
+ ? t("Step {number} · entry", { number: "1" })
+ : t("Step {number}", { number: String(index + 1) })}
+ </span>
+ <span className="whitespace-nowrap text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
+ {width < WIDE_STEP_HEADER || sessions === 0
+ ? sessions.toLocaleString()
+ : previousSessions
+ ? t("{count} · {percent} of step {step}", {
+ count: sessions.toLocaleString(),
+ percent: formatShare(sessions / previousSessions),
+ step: String(index),
+ })
+ : t("{count} sessions", { count: sessions.toLocaleString() })}
+ </span>
+ <StepFilterButton
+ step={index + 1}
+ value={stepFilters[index] ?? ""}
+ onChange={pattern => setStepFilter(index, pattern)}
+ suggestions={pageSuggestions}
+ />
+ </>
+ )}
+ overlay={
+ pinnedJourney && (
+ <PinnedPath
+ journey={pinnedJourney}
+ journeys={journeys}
+ goal={goalName ? { name: goalName, overallRate: overallReach, href: siteHref("goals") } : null}
+ pageHref={pageHref}
+ handlers={handlers}
+ onUnpin={() => setPinnedKey(null)}
+ />
+ )
+ }
+ />
+ <div className="mt-2 flex flex-col gap-2 border-t border-neutral-100 pt-3 md:flex-row md:items-center md:justify-between dark:border-neutral-850">
+ <ChartLegend
+ className="[--journey-exit:hsl(var(--neutral-400))] dark:[--journey-exit:hsl(var(--neutral-600))]"
+ items={
+ exitsKnown
+ ? [
+ { id: "continued", label: t("Continued to the next step"), color: "hsl(var(--dataviz))" },
+ { id: "ended", label: t("Ended the session there"), color: "var(--journey-exit)" },
+ ]
+ : [{ id: "sessions", label: t("Sessions on the path"), color: "hsl(var(--dataviz))" }]
+ }
+ />
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">
+ {t.rich(
+ "Bar height is sessions on the paths shown. Click a path to pin it; a page name opens it in <link>Pages</link>.",
+ {
+ link: chunks => (
+ <Link
+ href={siteHref("pages")}
+ prefetch={false}
+ className="text-neutral-700 underline decoration-neutral-400 underline-offset-2 dark:text-neutral-200 dark:decoration-neutral-600"
+ >
+ {chunks}
+ </Link>
+ ),
+ }
+ )}
+ </p>
</div>
- </div>
- )}
- <div className="flex flex-col gap-1 my-2">
- <div className="flex gap-1">
- {Array.from({ length: steps }, (_, i) => (
- <div
- key={i}
- className="flex-1 h-8 bg-neutral-50 dark:bg-neutral-850 flex items-center text-neutral-900 dark:text-white text-sm relative px-2"
- style={{
- clipPath: "polygon(0 0, 10px 50%, 0 100%, calc(100% - 10px) 100%, 100% 50%, calc(100% - 10px) 0)",
+ </>
+ ) : (
+ <div className="flex min-h-[240px] flex-col items-center justify-center gap-1 py-6 text-center">
+ <Route className="mb-1 h-5 w-5 text-neutral-400 dark:text-neutral-500" />
+ <p className="text-sm text-neutral-700 dark:text-neutral-200">
+ {hasPathFilters ? t("No paths match these steps") : t("No journeys in this range")}
+ </p>
+ <p className="max-w-[380px] text-xs text-neutral-500 dark:text-neutral-400">
+ {hasPathFilters
+ ? t("No session took a path with these start, end and step filters in the selected period.")
+ : t("Journeys map the paths of sessions that visit two or more pages. Try a wider date range.")}
+ </p>
+ {hasPathFilters && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="mt-2"
+ onClick={() => {
+ setStepFilters({});
+ setEndsAt("");
}}
>
- <span className="ml-2 whitespace-nowrap text-neutral-700 dark:text-neutral-200">
- {t("Step {number}", { number: String(i + 1) })}
- </span>
- <InputWithSuggestions
- suggestions={pathSuggestions}
- placeholder={t("Path filter")}
- value={stepFilters[i] || ""}
- onChange={e => {
- const newFilters = { ...stepFilters };
- if (e.target.value) {
- newFilters[i] = e.target.value;
- } else {
- delete newFilters[i];
- }
- setStepFilters(newFilters);
- }}
- className="h-6 bg-white dark:bg-neutral-900 border-neutral-100 dark:border-neutral-800 text-neutral-900 dark:text-white placeholder:text-neutral-400 dark:placeholder:text-neutral-500 ml-2 mr-2"
- />
- </div>
- ))}
- </div>
- <div className="text-xs text-neutral-500">
- {t("Use * to match a single path segment, ** to match multiple segments")}
+ {t("Clear path filters")}
+ </Button>
+ )}
</div>
- </div>
- {data?.journeys?.length && data?.journeys?.length > 0 ? (
- <SankeyDiagram
- journeys={data.journeys}
- steps={steps}
- maxJourneys={maxJourneys}
- domain={siteMetadata.domain}
- />
- ) : null}
- {error && (
- <Alert variant="destructive">
- <AlertCircle className="h-4 w-4" />
- <AlertTitle>{t("Error")}</AlertTitle>
- <AlertDescription>{t("Failed to load journey data. Please try again.")}</AlertDescription>
- </Alert>
- )}
-
- {data?.journeys?.length === 0 && !isLoading && !error && (
- <Alert>
- <AlertCircle className="h-4 w-4" />
- <AlertTitle>{t("No Data")}</AlertTitle>
- <AlertDescription>{t("No journey data found for the selected criteria.")}</AlertDescription>
- </Alert>
)}
</div>
- ) : null}
+ </Card>
+
+ {/* With nothing to list, the card above already says so. */}
+ {(isLoading || journeys.length > 0) && (
+ <TopPaths
+ journeys={journeys}
+ isLoading={isLoading}
+ steps={steps}
+ previousCounts={previousCounts}
+ goalName={goalName}
+ pinnedKey={pinnedJourney ? pinnedKey : null}
+ onPin={togglePin}
+ pageHref={pageHref}
+ handlers={handlers}
+ />
+ )}
</div>
+
+ <PathSessionsSheet target={sessionsTarget} shape={shape} onClose={() => setSessionsTarget(null)} />
+ <SaveAsFunnelDialog path={funnelPath} onClose={() => setFunnelPath(null)} />
</DisabledOverlay>
);
}
diff --git a/client/src/app/[site]/pages/components/PageSparklineChart.tsx b/client/src/app/[site]/pages/components/PageSparklineChart.tsx
index 74fa274c3..59fa65bda 100644
--- a/client/src/app/[site]/pages/components/PageSparklineChart.tsx
+++ b/client/src/app/[site]/pages/components/PageSparklineChart.tsx
@@ -1,129 +1,115 @@
"use client";
-import { GetOverviewBucketedResponse } from "@/api/analytics/endpoints";
+import { ResponsiveLine } from "@nivo/line";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import { useState } from "react";
+import type { PageTrend } from "@/api/analytics/hooks/useGetPages";
import { ChartTooltip } from "@/components/charts/ChartTooltip";
+import { Skeleton } from "@/components/ui/skeleton";
import { hour12, userLocale } from "@/lib/dateTimeUtils";
import { useNivoTheme } from "@/lib/nivo";
-import { getTimezone } from "@/lib/store";
-import { ResponsiveLine } from "@nivo/line";
-import { DateTime } from "luxon";
+import { useTimezone } from "@/lib/store";
interface PageSparklineChartProps {
- data: GetOverviewBucketedResponse | undefined;
- isHovering: boolean;
- pageTitle: string;
+ /** Views per bucket. Undefined once loaded means the row had no views to plot. */
+ series: PageTrend["series"] | undefined;
+ /** Names the line for the tooltip: the page title or the section. */
+ label: string;
isLoading: boolean;
}
-export function PageSparklineChart({ data, isHovering, pageTitle, isLoading }: PageSparklineChartProps) {
+const formatDateTime = (dt: DateTime, tz: string) =>
+ new Intl.DateTimeFormat(userLocale, {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "numeric",
+ hour12: hour12,
+ timeZone: tz,
+ }).format(dt.toJSDate());
+
+export function PageSparklineChart({ series, label, isLoading }: PageSparklineChartProps) {
+ const t = useExtracted();
const nivoTheme = useNivoTheme();
- const timezone = getTimezone();
+ const timezone = useTimezone();
+ const [isHovering, setIsHovering] = useState(false);
if (isLoading) {
- return (
- <div className="h-full w-full flex items-center justify-center animate-pulse">
- <div className="h-px w-full bg-border opacity-50"></div>
- </div>
- );
+ return <Skeleton className="h-6 w-full rounded" />;
}
- // Format the chart data
- const sparklineData = data
- ?.filter(e => {
- // Filter out dates from the future
- return DateTime.fromSQL(e.time, { zone: timezone }).toUTC() <= DateTime.now();
+ const now = DateTime.now();
+ const points = (series ?? [])
+ .map(point => {
+ const time = DateTime.fromSQL(point.time, { zone: timezone }).toUTC();
+ return { x: time.toFormat("yyyy-MM-dd HH:mm:ss"), y: point.pageviews, time };
})
- .map(e => ({
- x: DateTime.fromSQL(e.time, { zone: timezone }).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
- y: e.sessions || 0,
- time: DateTime.fromSQL(e.time, { zone: timezone }).toUTC(),
- }));
+ // The window is filled to its end; buckets that have not happened yet are not zeros.
+ .filter(point => point.time <= now);
- if (!sparklineData || sparklineData.length === 0) {
+ if (points.length === 0) {
return (
- <div className="h-full w-full flex items-center justify-center">
- <div className="h-px w-full bg-border opacity-50"></div>
+ <div className="flex h-6 w-full items-center">
+ <div className="h-px w-full bg-neutral-200 dark:bg-neutral-800" />
</div>
);
}
return (
- <ResponsiveLine
- data={[{ id: pageTitle, data: sparklineData }]}
- theme={nivoTheme}
- margin={{ top: 5, right: 0, bottom: 0, left: 0 }}
- xScale={{
- type: "time",
- format: "%Y-%m-%d %H:%M:%S",
- precision: "second",
- useUTC: true,
- }}
- yScale={{
- type: "linear",
- min: 0,
- stacked: false,
- reverse: false,
- }}
- enableGridX={false}
- enableGridY={false}
- axisTop={null}
- axisRight={null}
- axisBottom={null}
- axisLeft={null}
- enableTouchCrosshair={true}
- enablePoints={false}
- useMesh={true}
- animate={false}
- enableSlices={"x"}
- colors={[isHovering ? "hsl(var(--dataviz-2))" : "hsl(var(--dataviz))"]}
- enableArea={true}
- areaBaselineValue={0}
- areaOpacity={0.3}
- curve="linear"
- defs={[
- {
- id: "gradient",
- type: "linearGradient",
- colors: [
- { offset: 0, color: "hsl(var(--dataviz))", opacity: 1 },
- {
- offset: 100,
- color: "hsl(var(--dataviz))",
- opacity: 0,
- },
- ],
- },
- ]}
- fill={[{ match: () => true, id: "gradient" }]}
- sliceTooltip={({ slice }: any) => {
- const point = slice.points[0];
- const value = point.data.y;
- const timestamp = point.data.time as DateTime;
+ <div className="h-6 w-full" onMouseEnter={() => setIsHovering(true)} onMouseLeave={() => setIsHovering(false)}>
+ <ResponsiveLine
+ data={[{ id: label, data: points }]}
+ theme={nivoTheme}
+ margin={{ top: 3, right: 1, bottom: 1, left: 1 }}
+ xScale={{ type: "time", format: "%Y-%m-%d %H:%M:%S", precision: "second", useUTC: true }}
+ yScale={{ type: "linear", min: 0, stacked: false, reverse: false }}
+ enableGridX={false}
+ enableGridY={false}
+ axisTop={null}
+ axisRight={null}
+ axisBottom={null}
+ axisLeft={null}
+ enableTouchCrosshair={true}
+ enablePoints={false}
+ useMesh={true}
+ animate={false}
+ enableSlices="x"
+ colors={[isHovering ? "hsl(var(--dataviz-2))" : "hsl(var(--dataviz))"]}
+ lineWidth={1.5}
+ enableArea={true}
+ areaBaselineValue={0}
+ areaOpacity={0.3}
+ curve="linear"
+ defs={[
+ {
+ id: "gradient",
+ type: "linearGradient",
+ colors: [
+ { offset: 0, color: "hsl(var(--dataviz))", opacity: 1 },
+ { offset: 100, color: "hsl(var(--dataviz))", opacity: 0 },
+ ],
+ },
+ ]}
+ fill={[{ match: () => true, id: "gradient" }]}
+ sliceTooltip={({ slice }) => {
+ const point = slice.points[0];
+ const { time, y } = point.data as unknown as { time: DateTime; y: number };
- return (
- <ChartTooltip>
- <div className="p-2">
- <div className="flex items-center justify-between gap-3">
- <div>{formatDateTime(timestamp, timezone)}</div>
- <div className="font-medium">{value.toLocaleString()}</div>
+ return (
+ <ChartTooltip>
+ <div className="p-2">
+ <div className="flex items-center justify-between gap-3">
+ <div>{formatDateTime(time, timezone)}</div>
+ <div className="font-medium tabular-nums">
+ {t("{count, plural, one {# view} other {# views}}", { count: y })}
+ </div>
+ </div>
</div>
- </div>
- </ChartTooltip>
- );
- }}
- />
+ </ChartTooltip>
+ );
+ }}
+ />
+ </div>
);
}
-
-const formatDateTime = (dt: DateTime, tz: string) => {
- const options: Intl.DateTimeFormatOptions = {
- month: "short",
- day: "numeric",
- hour: "numeric",
- minute: "numeric",
- hour12: hour12,
- timeZone: tz,
- };
-
- return new Intl.DateTimeFormat(userLocale, options).format(dt.toJSDate());
-};
diff --git a/client/src/app/[site]/pages/components/PagesInsight.tsx b/client/src/app/[site]/pages/components/PagesInsight.tsx
new file mode 100644
index 000000000..35d8bcda7
--- /dev/null
+++ b/client/src/app/[site]/pages/components/PagesInsight.tsx
@@ -0,0 +1,54 @@
+"use client";
+
+import { useExtracted } from "next-intl";
+import { useGetPagesSummary } from "@/api/analytics/hooks/useGetPages";
+import { InsightRow } from "@/components/site/InsightRow";
+import { Button } from "@/components/ui/button";
+import { percentDelta } from "@/lib/delta";
+import { useComparisonEnabled } from "@/lib/store";
+import { formatSection } from "./pageIdentity";
+import { findOnlyLosingSection, LosingSection } from "./losingSection";
+
+/**
+ * One sentence, shown only when it is exactly true: a single section has fewer
+ * views than in the comparison period while every other section held or grew.
+ */
+export function PagesInsight({ onShowSection }: { onShowSection: (section: LosingSection) => void }) {
+ const t = useExtracted();
+ const comparing = useComparisonEnabled();
+ const current = useGetPagesSummary();
+ const previous = useGetPagesSummary({ periodTime: "previous" });
+
+ // Both answers must be for the periods on screen, not the ones before a change.
+ if (!comparing || current.isPlaceholderData || previous.isPlaceholderData) return null;
+
+ const losing = findOnlyLosingSection(current.data, previous.data);
+ const change = losing && percentDelta(losing.pageviews, losing.previousPageviews);
+ // A drop that rounds to 0.0% is not worth a sentence.
+ if (!losing || change?.direction !== "down") return null;
+
+ const section = formatSection(losing.section);
+
+ return (
+ <InsightRow
+ action={
+ losing.rank !== null && (
+ <Button type="button" variant="ghost" size="xs" onClick={() => onShowSection(losing)}>
+ {t("Show {section} pages", { section })}
+ </Button>
+ )
+ }
+ >
+ {t.rich(
+ "<name>{section}</name> is the only section losing traffic: {views} views, down {change} from {previous}.",
+ {
+ name: chunks => <span className="font-medium text-neutral-900 dark:text-neutral-50">{chunks}</span>,
+ section,
+ views: losing.pageviews.toLocaleString(),
+ change: change.text,
+ previous: losing.previousPageviews.toLocaleString(),
+ }
+ )}
+ </InsightRow>
+ );
+}
diff --git a/client/src/app/[site]/pages/components/PagesStatBand.tsx b/client/src/app/[site]/pages/components/PagesStatBand.tsx
new file mode 100644
index 000000000..306c9bd52
--- /dev/null
+++ b/client/src/app/[site]/pages/components/PagesStatBand.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+import { Clock, Eye, Files, Layers, LogOut } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { useGetPagesSummary } from "@/api/analytics/hooks/useGetPages";
+import { StatBand } from "@/components/site/StatBand";
+import { formatShortDuration } from "@/lib/dateTimeUtils";
+import { percentDelta, pointDelta } from "@/lib/delta";
+import { useComparisonEnabled } from "@/lib/store";
+import { formatter } from "@/lib/utils";
+
+const EMPTY = "—";
+
+export function PagesStatBand() {
+ const t = useExtracted();
+ const comparing = useComparisonEnabled();
+ const { data: current, isLoading } = useGetPagesSummary();
+ const { data: previousSummary } = useGetPagesSummary({ periodTime: "previous" });
+ // With the comparison off the query is idle but can still hold its last answer.
+ const previous = comparing ? previousSummary : undefined;
+
+ // The comparison line under a value: reserved (empty) while it loads, absent when comparison is off.
+ const previousLine = (value: string | undefined) =>
+ comparing ? (value === undefined ? "" : t("{value} previous period", { value })) : undefined;
+ const fixed = (value: number | null | undefined) => (value == null ? undefined : value.toFixed(2));
+
+ return (
+ <StatBand
+ isLoading={isLoading || !current}
+ cells={[
+ {
+ id: "pageviews",
+ icon: <Eye className="h-3 w-3" />,
+ label: t("Pageviews"),
+ value: current ? formatter(current.pageviews) : EMPTY,
+ title: current?.pageviews.toLocaleString(),
+ delta: percentDelta(current?.pageviews, previous?.pageviews),
+ sub: previousLine(previous ? formatter(previous.pageviews) : undefined),
+ },
+ {
+ id: "pages",
+ icon: <Files className="h-3 w-3" />,
+ label: t("Pages with traffic"),
+ value: current ? current.pages.toLocaleString() : EMPTY,
+ delta: percentDelta(current?.pages, previous?.pages),
+ sub: previousLine(previous?.pages.toLocaleString()),
+ },
+ {
+ id: "views-per-session",
+ icon: <Layers className="h-3 w-3" />,
+ label: t("Views per session"),
+ value: fixed(current?.views_per_session) ?? EMPTY,
+ delta: percentDelta(current?.views_per_session, previous?.views_per_session),
+ // A comparison period with no sessions has no ratio to print.
+ sub: previousLine(fixed(previous?.views_per_session)),
+ },
+ {
+ id: "time-on-page",
+ icon: <Clock className="h-3 w-3" />,
+ label: t("Avg time on page"),
+ value: current?.time_on_page_seconds != null ? formatShortDuration(current.time_on_page_seconds) : EMPTY,
+ delta: percentDelta(current?.time_on_page_seconds, previous?.time_on_page_seconds),
+ sub: t("Exit views excluded"),
+ },
+ {
+ id: "bounce-rate",
+ icon: <LogOut className="h-3 w-3" />,
+ label: t("Entry bounce rate"),
+ value: current?.bounce_rate != null ? `${current.bounce_rate.toFixed(1)}%` : EMPTY,
+ delta: pointDelta(current?.bounce_rate, previous?.bounce_rate),
+ upIsGood: false,
+ sub: current
+ ? t("{bounced} of {sessions} sessions", {
+ bounced: formatter(current.bounced_sessions),
+ sessions: formatter(current.sessions),
+ })
+ : "",
+ },
+ ]}
+ />
+ );
+}
diff --git a/client/src/app/[site]/pages/components/PagesTable.tsx b/client/src/app/[site]/pages/components/PagesTable.tsx
index 4bf970e9e..148c67992 100644
--- a/client/src/app/[site]/pages/components/PagesTable.tsx
+++ b/client/src/app/[site]/pages/components/PagesTable.tsx
@@ -1,320 +1,744 @@
"use client";
-import {
- createColumnHelper,
- flexRender,
- getCoreRowModel,
- getPaginationRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-import { ExternalLink } from "lucide-react";
+import { ArrowDown, ArrowUp, ChevronDown, ChevronRight, ChevronsUpDown, ExternalLink, Folder } from "lucide-react";
import { useExtracted } from "next-intl";
-import Link from "next/link";
-import { useMemo, useState } from "react";
+import { createContext, Fragment, ReactNode, useContext } from "react";
import { useGetSite } from "@/api/admin/hooks/useSites";
-import { useGetOverviewBucketed } from "@/api/analytics/hooks/useGetOverviewBucketed";
-import { useGetPageTitlesPaginated } from "@/api/analytics/hooks/useGetPageTitles";
-import { PageTitleItem } from "@/api/analytics/endpoints";
+import {
+ PageRow,
+ PagesGroup,
+ PagesMode,
+ PagesSort,
+ PagesSortOrder,
+ useGetPages,
+ useGetPagesSummary,
+ useGetPageTrends,
+ useGetSectionPages,
+} from "@/api/analytics/hooks/useGetPages";
import { ErrorState } from "@/components/ErrorState";
import { Pagination } from "@/components/pagination";
-import { useComparisonEnabled, useStore } from "@/lib/store";
+import { Delta } from "@/components/site/Delta";
+import { PivotActions } from "@/components/site/PivotActions";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Skeleton } from "@/components/ui/skeleton";
+import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatShortDuration } from "@/lib/dateTimeUtils";
-import { cn, truncateString } from "@/lib/utils";
+import { percentDelta } from "@/lib/delta";
+import { addFilter, removeFilter, useComparisonEnabled, useStore } from "@/lib/store";
+import { cn, formatter } from "@/lib/utils";
+import { formatSection, getPageFilters, getRowId, getTrendKeys } from "./pageIdentity";
import { PageSparklineChart } from "./PageSparklineChart";
-import { getPageItemFilters, getPageItemKey } from "./pageIdentity";
-const PAGE_SIZE = 25;
-const MAX_TITLE_LENGTH = 80;
+export const PAGE_SIZE = 25;
+const SECTION_PAGE_SIZE = 10;
-const columnHelper = createColumnHelper<PageTitleItem>();
+type ColumnId = "views" | "sessions" | "entries" | "exits" | "time" | "bounce" | "change" | "trend";
-function ChangePercentage({ current, previous }: { current: number; previous: number }) {
- const comparisonEnabled = useComparisonEnabled();
- if (!comparisonEnabled) return null;
+// Columns drop out as the table narrows, least important first. The widths sit
+// on the header cells (the table is fixed-layout), so a hidden column leaves no
+// gap and the page column takes what is left.
+const COLUMN_VISIBILITY: Record<ColumnId, string> = {
+ views: "",
+ sessions: "hidden @[640px]:table-cell",
+ entries: "hidden @[840px]:table-cell",
+ exits: "hidden @[840px]:table-cell",
+ time: "hidden @[920px]:table-cell",
+ bounce: "hidden @[920px]:table-cell",
+ change: "",
+ trend: "hidden @[550px]:table-cell",
+};
+// The share-of-views bar is the one decoration in the row, so between 920px and
+// 1000px it gives its room to the last two figures. The two ranges it shows in
+// do not overlap, which keeps the result independent of CSS order.
+const VIEWS_BAR = "hidden @min-[550px]:@max-[919px]:block @[1000px]:block";
+const VIEWS_NUMBER =
+ "min-w-12 flex-1 @min-[550px]:@max-[919px]:min-w-14 @min-[550px]:@max-[919px]:flex-none @[1000px]:min-w-14 @[1000px]:flex-none";
+const COLUMN_WIDTH: Record<ColumnId, string> = {
+ views: "w-[112px] @min-[550px]:@max-[919px]:w-[186px] @[1000px]:w-[186px]",
+ sessions: "w-[88px]",
+ entries: "w-[84px]",
+ exits: "w-[116px]",
+ time: "w-[86px]",
+ bounce: "w-[78px]",
+ change: "w-[76px] @[550px]:w-[84px]",
+ trend: "w-[100px]",
+};
+const COLUMN_SORT: Partial<Record<ColumnId, PagesSort>> = {
+ views: "pageviews",
+ sessions: "sessions",
+ entries: "entries",
+ exits: "exits",
+ time: "time_on_page",
+ bounce: "bounce_rate",
+};
- if (previous === 0) {
- if (current === 0) return null;
- return <span className="text-xs text-green-400">+999%</span>;
- }
- const change = ((current - previous) / previous) * 100;
- if (change === 0) return <span className="text-xs text-foreground/50">0%</span>;
- const isPositive = change > 0;
- return (
- <span className={cn("text-xs inline-flex items-center", isPositive ? "text-green-400" : "text-red-400")}>
- {isPositive ? "+" : ""}
- {change.toFixed(1)}%
- </span>
- );
+const MUTED = "text-neutral-500 dark:text-neutral-400";
+const NUMBER_CELL = "px-3 text-right tabular-nums whitespace-nowrap";
+
+// Exact up to six digits, which is what the columns are sized for; a million and up is
+// abbreviated, with the exact figure on hover.
+const formatCount = (value: number) => (value >= 1_000_000 ? formatter(value) : value.toLocaleString());
+
+function Count({ value }: { value: number }) {
+ return <span title={value >= 1_000_000 ? value.toLocaleString() : undefined}>{formatCount(value)}</span>;
}
-function TrendCell({ pageItem }: { pageItem: PageTitleItem }) {
- const { site, bucket, time } = useStore();
- const [isHovering, setIsHovering] = useState(false);
- const isPastMinutesMode = time.mode === "past-minutes";
- const pageFilters = getPageItemFilters(pageItem);
-
- const { data: regularData, isLoading: isLoadingRegular } = useGetOverviewBucketed({
- site,
- bucket,
- dynamicFilters: pageFilters,
- props: { enabled: !isPastMinutesMode },
- });
+const formatShare = (share: number) => {
+ const percent = share * 100;
+ if (percent > 0 && percent < 0.1) return "<0.1%";
+ return percent >= 99.95 ? "100%" : `${percent.toFixed(1)}%`;
+};
- const { data: pastMinutesData, isLoading: isLoadingPastMinutes } = useGetOverviewBucketed({
- site,
- bucket,
- dynamicFilters: [{ parameter: "pathname", value: [pageItem.pathname], type: "equals" }],
- props: { enabled: isPastMinutesMode },
- });
+interface TableContextValue {
+ mode: PagesMode;
+ sort: PagesSort;
+ order: PagesSortOrder;
+ /** Every pageview in the period, for each row's share. */
+ totalViews: number | undefined;
+ /** The largest row in view, which the bars are drawn against. */
+ maxViews: number;
+ showChange: boolean;
+ /** Section rows indent the pages under their chevrons. */
+ grouped: boolean;
+ domain: string | undefined;
+ expanded: ReadonlySet<string>;
+ onToggleSection: (section: string) => void;
+ focusSection: string | null;
+ onFocusHandled: () => void;
+}
+
+const TableContext = createContext<TableContextValue | null>(null);
+
+function useTableContext() {
+ const context = useContext(TableContext);
+ if (!context) throw new Error("Pages table rows must render inside PagesTable");
+ return context;
+}
- const data = isPastMinutesMode ? pastMinutesData : regularData;
- const isLoading = isPastMinutesMode ? isLoadingPastMinutes : isLoadingRegular;
+interface RowFigures {
+ /** Views over time; undefined when the row has none to plot. */
+ series: { time: string; pageviews: number }[] | undefined;
+ trendLoading: boolean;
+ /** Views in the comparison period; undefined while unknown. */
+ previousViews: number | undefined;
+ changeLoading: boolean;
+}
+
+function MetricCells({ row, figures, strong }: { row: PageRow; figures: RowFigures; strong?: boolean }) {
+ const { totalViews, maxViews, showChange } = useTableContext();
+ const exitRate = row.sessions > 0 ? Math.round((row.exits / row.sessions) * 100) : null;
return (
- <div
- className="h-8 w-32"
- onMouseEnter={() => setIsHovering(true)}
- onMouseLeave={() => setIsHovering(false)}
- >
- <PageSparklineChart
- data={data}
- isHovering={isHovering}
- pageTitle={pageItem.value || pageItem.pathname}
- isLoading={isLoading}
- />
- </div>
+ <>
+ <TableCell className={cn("px-3", strong && "font-medium")}>
+ <div className="flex items-center gap-2">
+ <div
+ className={cn(
+ "h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-neutral-100 dark:bg-neutral-800",
+ VIEWS_BAR
+ )}
+ >
+ <div
+ className="h-full rounded-full bg-dataviz"
+ style={{ width: `${maxViews > 0 ? Math.min((row.pageviews / maxViews) * 100, 100) : 0}%` }}
+ />
+ </div>
+ <span className={cn("text-right tabular-nums", VIEWS_NUMBER)}>
+ <Count value={row.pageviews} />
+ </span>
+ <span className={cn("min-w-10 text-right text-xs tabular-nums", MUTED)}>
+ {totalViews ? formatShare(row.pageviews / totalViews) : ""}
+ </span>
+ </div>
+ </TableCell>
+ <TableCell className={cn(NUMBER_CELL, COLUMN_VISIBILITY.sessions)}>
+ <Count value={row.sessions} />
+ </TableCell>
+ <TableCell className={cn(NUMBER_CELL, COLUMN_VISIBILITY.entries)}>
+ <Count value={row.entries} />
+ </TableCell>
+ <TableCell className={cn(NUMBER_CELL, COLUMN_VISIBILITY.exits)}>
+ <Count value={row.exits} />
+ <span className={cn("ml-1.5 inline-block w-8 text-right text-xs", MUTED)}>
+ {exitRate === null ? "" : `${exitRate}%`}
+ </span>
+ </TableCell>
+ <TableCell className={cn(NUMBER_CELL, COLUMN_VISIBILITY.time)}>
+ {row.time_on_page_seconds === null ? (
+ <span className={MUTED}>—</span>
+ ) : (
+ formatShortDuration(row.time_on_page_seconds)
+ )}
+ </TableCell>
+ <TableCell className={cn(NUMBER_CELL, COLUMN_VISIBILITY.bounce)}>
+ {row.bounce_rate === null ? <span className={MUTED}>—</span> : `${Math.round(row.bounce_rate)}%`}
+ </TableCell>
+ {showChange && (
+ <TableCell className={cn("px-3 text-right", COLUMN_VISIBILITY.change)}>
+ {figures.changeLoading ? (
+ <Skeleton className="ml-auto h-3 w-10 rounded" />
+ ) : (
+ <Delta value={percentDelta(row.pageviews, figures.previousViews)} />
+ )}
+ </TableCell>
+ )}
+ <TableCell className={cn("px-3", COLUMN_VISIBILITY.trend)}>
+ <div className="ml-auto w-[76px]">
+ <PageSparklineChart
+ series={figures.series}
+ label={row.kind === "section" ? formatSection(row.key) : row.title || row.key}
+ isLoading={figures.trendLoading}
+ />
+ </div>
+ </TableCell>
+ </>
);
}
-export function PagesTable() {
+function PageTableRow({ row, figures, child }: { row: PageRow; figures: RowFigures; child?: boolean }) {
const t = useExtracted();
- const { site } = useStore();
- const { data: siteMetadata } = useGetSite();
+ const { mode, grouped, domain } = useTableContext();
+ const filters = useStore(state => state.filters);
- const [pagination, setPagination] = useState({
- pageIndex: 0,
- pageSize: PAGE_SIZE,
- });
-
- const page = pagination.pageIndex + 1;
-
- const {
- data: currentResp,
- isLoading: isLoadingCurrent,
- isFetching: isFetchingCurrent,
- isError,
- } = useGetPageTitlesPaginated({
- limit: pagination.pageSize,
- page,
- });
+ const path = row.key;
+ const pageFilters = getPageFilters(path, mode);
+ const pageUrl = domain ? `https://${domain}${path}` : "";
- const { data: previousResp } = useGetPageTitlesPaginated({
- limit: 1000,
- page: 1,
- periodTime: "previous",
- });
-
- const currentItems = currentResp?.data ?? [];
- const totalCount = currentResp?.totalCount ?? 0;
+ // The same toggle as a row on the main dashboard: click to filter, click again to clear.
+ const toggleFilter = () => {
+ const [filter] = pageFilters;
+ const applied = filters.find(
+ candidate => candidate.parameter === filter.parameter && candidate.value.some(value => value === path)
+ );
+ if (applied) removeFilter(applied);
+ else addFilter(filter);
+ };
- const previousByKey = useMemo(() => {
- const map = new Map<string, PageTitleItem>();
- for (const item of previousResp?.data ?? []) {
- map.set(getPageItemKey(item), item);
- }
- return map;
- }, [previousResp]);
-
- const isLoading = isLoadingCurrent || isFetchingCurrent;
-
- const columns = [
- columnHelper.accessor("value", {
- header: t("Page"),
- cell: info => {
- const item = info.row.original;
- const title = item.value;
- const pathname = item.pathname;
- const pageUrl = siteMetadata?.domain ? `https://${siteMetadata.domain}${pathname}` : "";
-
- return (
- <div className="min-w-0 max-w-[420px]">
- <div className="flex items-center gap-1.5">
- <span
- className="text-sm font-medium truncate text-foreground"
- title={title || pathname}
+ return (
+ <TableRow className="group">
+ <TableCell className={cn("py-1.5 pr-3", child ? "pl-11" : grouped ? "pl-9" : "pl-3")}>
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="min-w-[64px] flex-1">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <button
+ type="button"
+ onClick={toggleFilter}
+ title={t("Filter by {page}", { page: row.title || path })}
+ className="truncate text-left text-sm font-medium text-neutral-900 hover:underline focus-visible:underline focus-visible:outline-none dark:text-neutral-100"
>
- {truncateString(title || pathname, MAX_TITLE_LENGTH)}
- </span>
+ {row.title || path}
+ </button>
{pageUrl && (
- <Link
+ <a
href={pageUrl}
target="_blank"
rel="noopener noreferrer"
- onClick={e => e.stopPropagation()}
- className="text-muted-foreground hover:text-primary shrink-0"
+ aria-label={t("Open page in a new tab")}
+ className="shrink-0 text-neutral-400 hover:text-neutral-900 dark:text-neutral-500 dark:hover:text-neutral-200"
>
<ExternalLink className="h-3.5 w-3.5" />
- </Link>
+ </a>
)}
</div>
- <p className="text-xs text-muted-foreground truncate" title={pathname}>
- {pathname}
- </p>
+ {/* An untitled page already shows its path above; repeating it would read as two facts. */}
+ <div className={cn("truncate text-xs", MUTED)} title={row.title ? path : undefined}>
+ {row.title ? path : t("No page title")}
+ </div>
</div>
- );
- },
- }),
- columnHelper.display({
- id: "trend",
- header: t("Trend"),
- cell: ({ row }) => <TrendCell pageItem={row.original} />,
- }),
- columnHelper.accessor("pageviews", {
- header: t("Views"),
- cell: info => {
- const v = info.getValue();
- return <div className="whitespace-nowrap">{(v ?? 0).toLocaleString()}</div>;
- },
- }),
- columnHelper.accessor("count", {
- header: t("Sessions"),
- cell: info => {
- const current = info.getValue() ?? 0;
- const prev = previousByKey.get(getPageItemKey(info.row.original))?.count ?? 0;
- return (
- <div className="whitespace-nowrap flex items-center gap-1.5">
- <span>{current.toLocaleString()}</span>
- <ChangePercentage current={current} previous={prev} />
+ <PivotActions
+ filters={pageFilters}
+ actions={["sessions"]}
+ className="hidden shrink-0 flex-nowrap @[640px]:group-focus-within:flex @[640px]:group-hover:flex"
+ />
+ </div>
+ </TableCell>
+ <MetricCells row={row} figures={figures} />
+ </TableRow>
+ );
+}
+
+function SectionTableRow({ row, figures }: { row: PageRow; figures: RowFigures }) {
+ const t = useExtracted();
+ const { expanded, onToggleSection, focusSection, onFocusHandled } = useTableContext();
+ const isOpen = expanded.has(row.key);
+ const label = formatSection(row.key);
+
+ return (
+ <TableRow
+ // Scrolls to the section the insight row points at, once it is on screen.
+ ref={
+ focusSection === row.key
+ ? node => {
+ if (!node) return;
+ node.scrollIntoView({ block: "center", behavior: "smooth" });
+ onFocusHandled();
+ }
+ : undefined
+ }
+ onClick={() => onToggleSection(row.key)}
+ className="cursor-pointer bg-neutral-50 dark:bg-neutral-850/60"
+ >
+ <TableCell className="py-1.5 pl-2 pr-3">
+ <div className="flex min-w-0 items-center gap-1">
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ aria-expanded={isOpen}
+ aria-label={
+ isOpen ? t("Collapse {section}", { section: label }) : t("Expand {section}", { section: label })
+ }
+ onClick={event => {
+ event.stopPropagation();
+ onToggleSection(row.key);
+ }}
+ className={cn("h-6 w-6 shrink-0 px-0", MUTED)}
+ >
+ {isOpen ? <ChevronDown /> : <ChevronRight />}
+ </Button>
+ <div className="min-w-0">
+ <div className="flex items-center gap-1.5">
+ <span className="truncate text-sm font-semibold text-neutral-900 dark:text-neutral-100">{label}</span>
+ <Folder className="h-3.5 w-3.5 shrink-0 text-neutral-400 dark:text-neutral-500" aria-hidden="true" />
+ </div>
+ <div className={cn("truncate text-xs tabular-nums", MUTED)}>
+ {t("{count, plural, one {# page} other {# pages}}", { count: row.pages })}
+ </div>
</div>
- );
- },
- }),
- columnHelper.accessor("bounce_rate", {
- header: t("Bounce"),
- cell: info => {
- const v = info.getValue();
- if (v === undefined || v === null) return <div className="text-muted-foreground">—</div>;
- return <div className="whitespace-nowrap">{Math.round(v)}%</div>;
- },
- }),
- columnHelper.accessor("time_on_page_seconds", {
- header: t("Duration"),
- cell: info => {
- const v = info.getValue();
- if (v === undefined || v === null) return <div className="text-muted-foreground">—</div>;
- return <div className="whitespace-nowrap">{formatShortDuration(v)}</div>;
- },
- }),
- ];
-
- const table = useReactTable({
- data: currentItems,
- columns,
- pageCount: totalCount ? Math.ceil(totalCount / pagination.pageSize) : -1,
- state: { pagination },
- onPaginationChange: setPagination,
- getCoreRowModel: getCoreRowModel(),
- getPaginationRowModel: getPaginationRowModel(),
- manualPagination: true,
+ </div>
+ </TableCell>
+ <MetricCells row={row} figures={figures} strong />
+ </TableRow>
+ );
+}
+
+function SkeletonRows({ count, child }: { count: number; child?: boolean }) {
+ const { showChange, grouped } = useTableContext();
+ const bar = <Skeleton className="ml-auto h-3.5 w-10 rounded" />;
+
+ return (
+ <>
+ {Array.from({ length: count }, (_, index) => (
+ <TableRow key={index}>
+ <TableCell className={cn("py-1.5 pr-3", child ? "pl-11" : grouped ? "pl-9" : "pl-3")}>
+ <div className="space-y-1.5">
+ <Skeleton className="h-3.5 w-3/5 rounded" />
+ <Skeleton className="h-3 w-2/5 rounded" />
+ </div>
+ </TableCell>
+ <TableCell className="px-3">
+ <Skeleton className="h-3.5 w-full rounded" />
+ </TableCell>
+ <TableCell className={cn("px-3", COLUMN_VISIBILITY.sessions)}>{bar}</TableCell>
+ <TableCell className={cn("px-3", COLUMN_VISIBILITY.entries)}>{bar}</TableCell>
+ <TableCell className={cn("px-3", COLUMN_VISIBILITY.exits)}>{bar}</TableCell>
+ <TableCell className={cn("px-3", COLUMN_VISIBILITY.time)}>{bar}</TableCell>
+ <TableCell className={cn("px-3", COLUMN_VISIBILITY.bounce)}>{bar}</TableCell>
+ {showChange && <TableCell className={cn("px-3", COLUMN_VISIBILITY.change)}>{bar}</TableCell>}
+ <TableCell className={cn("px-3", COLUMN_VISIBILITY.trend)}>
+ <Skeleton className="ml-auto h-6 w-[76px] rounded" />
+ </TableCell>
+ </TableRow>
+ ))}
+ </>
+ );
+}
+
+/**
+ * A batch of rows with one trend request for all of them, and one more for the
+ * comparison period, whose totals are each row's baseline for its change.
+ */
+function RowsBlock({ rows, child }: { rows: PageRow[]; child?: boolean }) {
+ const { expanded, showChange } = useTableContext();
+ const bucket = useStore(state => state.bucket);
+ const keys = getTrendKeys(rows);
+
+ const trends = useGetPageTrends({ ...keys, bucket });
+ const previous = useGetPageTrends({ ...keys, bucket, periodTime: "previous" });
+
+ const trendById = new Map((trends.data ?? []).map(trend => [getRowId(trend), trend]));
+ const previousById = new Map((previous.data ?? []).map(trend => [getRowId(trend), trend]));
+
+ // A key the server leaves out had no views. That only holds for an answer to
+ // this batch: while the last batch's answer stands in, a missing key is unknown.
+ const figuresFor = (id: string): RowFigures => {
+ const trend = trendById.get(id);
+ const baseline = previousById.get(id);
+ const previousKnown = showChange && previous.data !== undefined && (!previous.isPlaceholderData || !!baseline);
+
+ return {
+ series: trend?.series,
+ trendLoading: !trend && trends.isFetching,
+ previousViews: previousKnown ? (baseline?.pageviews ?? 0) : undefined,
+ changeLoading: !previousKnown && previous.isFetching,
+ };
+ };
+
+ return (
+ <>
+ {rows.map(row => {
+ const id = getRowId(row);
+ const figures = figuresFor(id);
+
+ if (row.kind === "section") {
+ return (
+ <Fragment key={id}>
+ <SectionTableRow row={row} figures={figures} />
+ {expanded.has(row.key) && <SectionPages section={row} />}
+ </Fragment>
+ );
+ }
+ return <PageTableRow key={id} row={row} figures={figures} child={child} />;
+ })}
+ </>
+ );
+}
+
+function SectionPages({ section }: { section: PageRow }) {
+ const t = useExtracted();
+ const { mode, sort, order } = useTableContext();
+ const { data, isLoading, isError, hasNextPage, isFetchingNextPage, fetchNextPage } = useGetSectionPages({
+ section: section.key,
+ mode,
+ sort,
+ order,
+ limit: SECTION_PAGE_SIZE,
+ });
+
+ if (isLoading) return <SkeletonRows count={Math.min(section.pages, 3)} child />;
+
+ const batches = data?.pages ?? [];
+ if (isError || batches.length === 0) {
+ return (
+ <TableRow>
+ <TableCell colSpan={2} className={cn("py-2 pl-11 pr-3 text-xs", MUTED)}>
+ {t("Could not load the pages in {section}.", { section: formatSection(section.key) })}
+ </TableCell>
+ </TableRow>
+ );
+ }
+
+ const loaded = batches.flatMap(batch => batch.data);
+ const remaining = Math.max(batches[batches.length - 1].totalCount - loaded.length, 0);
+ // Every page of the section is listed on the all-pages view, so what is not
+ // shown is the section's views minus the rows above.
+ const hiddenViews =
+ mode === "all" ? section.pageviews - loaded.reduce((total, page) => total + page.pageviews, 0) : null;
+
+ return (
+ <>
+ {batches.map((batch, index) => (
+ <RowsBlock key={index} rows={batch.data} child />
+ ))}
+ {isFetchingNextPage && <SkeletonRows count={Math.min(remaining, 3)} child />}
+ {hasNextPage && remaining > 0 && (
+ <TableRow>
+ {/* Spans the two columns every width keeps: a wider span would outgrow a narrow table. */}
+ <TableCell colSpan={2} className="py-1.5 pl-11 pr-3">
+ <div className="flex flex-wrap items-center gap-x-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ disabled={isFetchingNextPage}
+ onClick={() => fetchNextPage()}
+ className="-ml-1.5 gap-1 font-normal text-neutral-600 dark:text-neutral-300"
+ >
+ <ChevronsUpDown />
+ {t("Show {count, plural, one {# more page} other {# more pages}} in {section}", {
+ count: Math.min(remaining, SECTION_PAGE_SIZE),
+ section: formatSection(section.key),
+ })}
+ </Button>
+ <span className={cn("text-xs tabular-nums", MUTED)}>
+ {hiddenViews !== null && hiddenViews > 0
+ ? t("{pages} not shown, {views} views", {
+ pages: remaining.toLocaleString(),
+ views: hiddenViews.toLocaleString(),
+ })
+ : t("{pages} not shown", { pages: remaining.toLocaleString() })}
+ </span>
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </>
+ );
+}
+
+function HeaderCell({
+ column,
+ label,
+ title,
+ align = "right",
+ onSort,
+}: {
+ column: ColumnId;
+ label: string;
+ title?: string;
+ align?: "left" | "right";
+ onSort: (sort: PagesSort) => void;
+}) {
+ const { sort, order } = useTableContext();
+ const sortKey = COLUMN_SORT[column];
+ const sorted = sortKey !== undefined && sort === sortKey;
+ const Arrow = order === "asc" ? ArrowUp : ArrowDown;
+
+ return (
+ <TableHead
+ scope="col"
+ title={title}
+ aria-sort={sorted ? (order === "asc" ? "ascending" : "descending") : undefined}
+ className={cn(
+ // The header is a flat band inside the card, not the rounded pill of a free-standing table.
+ "whitespace-nowrap px-3 last:rounded-r-none",
+ align === "right" && "text-right",
+ COLUMN_WIDTH[column],
+ COLUMN_VISIBILITY[column]
+ )}
+ >
+ {sortKey ? (
+ <button
+ type="button"
+ onClick={() => onSort(sortKey)}
+ className={cn(
+ "inline-flex items-center gap-1 font-medium focus-visible:underline focus-visible:outline-none",
+ sorted ? "text-neutral-900 dark:text-neutral-100" : "hover:text-neutral-900 dark:hover:text-neutral-200"
+ )}
+ >
+ {label}
+ {sorted && <Arrow className="h-3 w-3" aria-hidden="true" />}
+ </button>
+ ) : (
+ label
+ )}
+ </TableHead>
+ );
+}
+
+export interface PagesTableProps {
+ /** Section rollups, or one flat list of pages. A search always lists pages. */
+ group: PagesGroup;
+ mode: PagesMode;
+ search: string;
+ sort: PagesSort;
+ order: PagesSortOrder;
+ onSort: (sort: PagesSort) => void;
+ /** 1-indexed. */
+ page: number;
+ onPageChange: (page: number) => void;
+ expanded: ReadonlySet<string>;
+ onExpandedChange: (expanded: Set<string>) => void;
+ /** A section to scroll to when its row appears. */
+ focusSection: string | null;
+ onFocusHandled: () => void;
+}
+
+export function PagesTable({
+ group,
+ mode,
+ search,
+ sort,
+ order,
+ onSort,
+ page,
+ onPageChange,
+ expanded,
+ onExpandedChange,
+ focusSection,
+ onFocusHandled,
+}: PagesTableProps) {
+ const t = useExtracted();
+ const { data: siteMetadata } = useGetSite();
+ const showChange = useComparisonEnabled();
+
+ const { data, isLoading, isPlaceholderData, isError, refetch } = useGetPages({
+ group,
+ mode,
+ sort,
+ order,
+ search,
+ limit: PAGE_SIZE,
+ page,
});
+ const { data: summary } = useGetPagesSummary();
+
+ const rows = data?.data ?? [];
+ const totalCount = data?.totalCount ?? 0;
+ const pageCount = Math.max(Math.ceil(totalCount / PAGE_SIZE), 1);
+ const sectionKeys = rows.filter(row => row.kind === "section").map(row => row.key);
+ const openSections = sectionKeys.filter(key => expanded.has(key));
+
+ const context: TableContextValue = {
+ mode,
+ sort,
+ order,
+ totalViews: summary?.pageviews,
+ maxViews: rows.reduce((max, row) => Math.max(max, row.pageviews), 0),
+ showChange,
+ grouped: group === "section",
+ domain: siteMetadata?.domain,
+ expanded,
+ onToggleSection: section => {
+ const next = new Set(expanded);
+ if (!next.delete(section)) next.add(section);
+ onExpandedChange(next);
+ },
+ focusSection,
+ onFocusHandled,
+ };
if (isError) {
return (
<ErrorState
title={t("Failed to load pages")}
message={t("There was a problem fetching the pages. Please try again later.")}
+ refetch={refetch}
/>
);
}
+ let footnote: ReactNode = null;
+ if (data && totalCount > 0) {
+ if (search) {
+ footnote = t("{count, plural, one {# page matches} other {# pages match}}", { count: totalCount });
+ } else if (group === "section") {
+ footnote = summary
+ ? t("{rows, plural, one {# row} other {# rows}} · {pages, plural, one {# page} other {# pages}} with traffic", {
+ rows: totalCount,
+ pages: summary.pages,
+ })
+ : t("{rows, plural, one {# row} other {# rows}}", { rows: totalCount });
+ } else if (mode === "entry") {
+ footnote = t("{count, plural, one {# entry page} other {# entry pages}}", { count: totalCount });
+ } else if (mode === "exit") {
+ footnote = t("{count, plural, one {# exit page} other {# exit pages}}", { count: totalCount });
+ } else {
+ footnote = t("{count, plural, one {# page} other {# pages}} with traffic", { count: totalCount });
+ }
+ }
+
return (
- <div className="space-y-3">
- <div className="relative overflow-x-auto">
- <table className="w-full text-sm text-left">
- <thead className="[&_tr]:border-b-0 bg-neutral-50 dark:bg-neutral-850">
- {table.getHeaderGroups().map(headerGroup => (
- <tr key={headerGroup.id}>
- {headerGroup.headers.map(header => (
- <th
- key={header.id}
- scope="col"
- className="h-8 px-3 text-left align-middle font-medium text-xs text-neutral-500 dark:text-neutral-400 whitespace-nowrap first:rounded-l-xl last:rounded-r-xl"
- >
- {header.isPlaceholder
- ? null
- : flexRender(header.column.columnDef.header, header.getContext())}
- </th>
- ))}
- </tr>
- ))}
- </thead>
- <tbody>
- {isLoading && currentItems.length === 0 ? (
- Array.from({ length: 10 }).map((_, index) => (
- <tr key={index} className="border-b border-neutral-100 dark:border-neutral-800 animate-pulse">
- <td className="px-3 py-2">
- <div className="space-y-1.5 max-w-[420px]">
- <div className="h-3.5 bg-neutral-200 dark:bg-neutral-800 rounded w-3/5"></div>
- <div className="h-3 bg-neutral-200 dark:bg-neutral-800 rounded w-2/5 opacity-70"></div>
- </div>
- </td>
- <td className="px-3 py-2">
- <div className="h-8 w-32 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
- </td>
- <td className="px-3 py-2">
- <div className="h-3.5 w-10 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
- </td>
- <td className="px-3 py-2">
- <div className="flex items-center gap-1.5">
- <div className="h-3.5 w-10 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
- <div className="h-3 w-8 bg-neutral-200 dark:bg-neutral-800 rounded opacity-70"></div>
- </div>
- </td>
- <td className="px-3 py-2">
- <div className="h-3.5 w-8 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
- </td>
- <td className="px-3 py-2">
- <div className="h-3.5 w-8 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
- </td>
- </tr>
- ))
- ) : table.getRowModel().rows.length === 0 ? (
+ <TableContext.Provider value={context}>
+ <Card>
+ <div className="@container overflow-x-auto">
+ <table className="w-full min-w-[340px] table-fixed caption-bottom text-sm">
+ <TableHeader>
<tr>
- <td
- colSpan={columns.length}
- className="px-3 py-7 text-center text-neutral-500 dark:text-neutral-400"
+ <TableHead
+ scope="col"
+ className={cn("whitespace-nowrap pr-3 first:rounded-l-none", group === "section" ? "pl-9" : "pl-3")}
>
- {t("No pages data found for the selected period.")}
- </td>
+ {group === "section" ? t("Page / section") : t("Page")}
+ </TableHead>
+ <HeaderCell column="views" label={t("Views")} align="left" onSort={onSort} />
+ <HeaderCell column="sessions" label={t("Sessions")} onSort={onSort} />
+ <HeaderCell
+ column="entries"
+ label={t("Entries")}
+ title={t("Sessions that started on this page")}
+ onSort={onSort}
+ />
+ <HeaderCell
+ column="exits"
+ label={t("Exits")}
+ title={t("Sessions that ended on this page, and their share of the sessions that saw it")}
+ onSort={onSort}
+ />
+ <HeaderCell
+ column="time"
+ label={t("Avg time")}
+ title={t("Average time until the next page in the session. Exit views are left out.")}
+ onSort={onSort}
+ />
+ <HeaderCell
+ column="bounce"
+ label={t("Bounce")}
+ title={t("Entry bounce rate: sessions that started here and viewed nothing else")}
+ onSort={onSort}
+ />
+ {showChange && (
+ <HeaderCell
+ column="change"
+ label={t("Change")}
+ title={t("Change in views against the comparison period")}
+ onSort={onSort}
+ />
+ )}
+ <HeaderCell column="trend" label={t("Trend")} title={t("Views over the period")} onSort={onSort} />
</tr>
- ) : (
- table.getRowModel().rows.map(row => (
- <tr
- key={row.id}
- className="border-b border-neutral-100 dark:border-neutral-800 group hover:bg-neutral-50 dark:hover:bg-neutral-850"
+ </TableHeader>
+ {/* Dimmed while the last answer stands in for a new sort, page or period. */}
+ <TableBody className={cn("transition-opacity", isPlaceholderData && "opacity-60")}>
+ {isLoading || !data ? <SkeletonRows count={10} /> : <RowsBlock rows={rows} />}
+ </TableBody>
+ </table>
+ {data && rows.length === 0 && (
+ <div className={cn("px-3 py-7 text-center text-sm", MUTED)}>
+ {totalCount > 0 ? (
+ // The list got shorter (a live period, a filter) and this page is past its end.
+ <Button type="button" variant="outline" size="sm" onClick={() => onPageChange(1)}>
+ {t("Back to the first page")}
+ </Button>
+ ) : search ? (
+ t("No pages match “{search}”.", { search })
+ ) : mode === "entry" ? (
+ t("No sessions started in the selected period.")
+ ) : mode === "exit" ? (
+ t("No sessions ended in the selected period.")
+ ) : (
+ t("No pages data found for the selected period.")
+ )}
+ </div>
+ )}
+ </div>
+ <div
+ className={cn(
+ "flex flex-wrap items-center justify-between gap-x-3 gap-y-2 border-t border-neutral-100 px-3 py-2 text-xs dark:border-neutral-800",
+ // Nothing to count and nothing to page through: the empty message stands alone.
+ data && totalCount === 0 && "hidden"
+ )}
+ >
+ <div className={cn("min-h-6 tabular-nums leading-6", MUTED)}>{footnote}</div>
+ <div className="flex items-center gap-1">
+ {sectionKeys.length > 0 && (
+ <>
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ disabled={openSections.length === sectionKeys.length}
+ onClick={() => onExpandedChange(new Set([...expanded, ...sectionKeys]))}
+ className="font-normal text-neutral-600 dark:text-neutral-300"
>
- {row.getVisibleCells().map(cell => (
- <td key={cell.id} className="px-3 py-2 align-middle">
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </td>
- ))}
- </tr>
- ))
+ {t("Expand all")}
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ disabled={openSections.length === 0}
+ onClick={() => onExpandedChange(new Set())}
+ className="font-normal text-neutral-600 dark:text-neutral-300"
+ >
+ {t("Collapse all")}
+ </Button>
+ </>
+ )}
+ {pageCount > 1 && (
+ <Pagination
+ page={page}
+ pageCount={pageCount}
+ onPageChange={onPageChange}
+ isLoading={isLoading}
+ showRange={false}
+ className="ml-2 w-auto"
+ />
)}
- </tbody>
- </table>
- </div>
-
- <div className="px-4">
- <Pagination
- table={table}
- data={{ items: currentItems, total: totalCount }}
- pagination={pagination}
- setPagination={setPagination}
- isLoading={isLoading}
- itemName={t("pages")}
- />
- </div>
- </div>
+ </div>
+ </div>
+ </Card>
+ </TableContext.Provider>
);
}
diff --git a/client/src/app/[site]/pages/components/losingSection.test.ts b/client/src/app/[site]/pages/components/losingSection.test.ts
new file mode 100644
index 000000000..91807c05d
--- /dev/null
+++ b/client/src/app/[site]/pages/components/losingSection.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from "vitest";
+
+import type { PagesSummary, SectionViews } from "@/api/analytics/hooks/useGetPages";
+import { findOnlyLosingSection } from "./losingSection";
+
+const summary = (sections: [string, number, number][], sectionCount = sections.length): PagesSummary => ({
+ pageviews: 0,
+ sessions: 0,
+ pages: 0,
+ bounced_sessions: 0,
+ bounce_rate: null,
+ time_on_page_seconds: null,
+ views_per_session: null,
+ sections: sections.map(([section, pageviews, pages]): SectionViews => ({ section, pageviews, pages })),
+ sectionCount,
+});
+
+describe("findOnlyLosingSection", () => {
+ it("names the section when it alone lost views", () => {
+ const current = summary([
+ ["/docs", 500, 12],
+ ["/", 300, 1],
+ ["/blog", 180, 8],
+ ]);
+ const previous = summary([
+ ["/docs", 450, 11],
+ ["/", 400, 1],
+ ["/blog", 200, 8],
+ ]);
+
+ // "/" lost views too, but a single page is not a section.
+ expect(findOnlyLosingSection(current, previous)).toEqual({
+ section: "/blog",
+ pageviews: 180,
+ previousPageviews: 200,
+ rank: 2,
+ });
+ });
+
+ it("says nothing when no section or several sections lost views", () => {
+ const previous = summary([
+ ["/docs", 450, 11],
+ ["/blog", 200, 8],
+ ]);
+
+ expect(
+ findOnlyLosingSection(
+ summary([
+ ["/docs", 500, 12],
+ ["/blog", 200, 8],
+ ]),
+ previous
+ )
+ ).toBeNull();
+ expect(
+ findOnlyLosingSection(
+ summary([
+ ["/docs", 400, 12],
+ ["/blog", 180, 8],
+ ]),
+ previous
+ )
+ ).toBeNull();
+ });
+
+ it("needs another section to compare with", () => {
+ expect(findOnlyLosingSection(summary([["/docs", 400, 12]]), summary([["/docs", 450, 11]]))).toBeNull();
+ });
+
+ it("counts a section that lost all its traffic", () => {
+ const current = summary([["/docs", 500, 12]]);
+ const previous = summary([
+ ["/docs", 450, 11],
+ ["/blog", 200, 8],
+ ]);
+
+ expect(findOnlyLosingSection(current, previous)).toEqual({
+ section: "/blog",
+ pageviews: 0,
+ previousPageviews: 200,
+ rank: null,
+ });
+ });
+
+ it("does not point at a section that is down to one page", () => {
+ const current = summary([
+ ["/docs", 500, 12],
+ ["/blog", 50, 1],
+ ]);
+ const previous = summary([
+ ["/docs", 450, 11],
+ ["/blog", 200, 8],
+ ]);
+
+ expect(findOnlyLosingSection(current, previous)?.rank).toBeNull();
+ });
+
+ it("says nothing without a comparison or when either section list was capped", () => {
+ const current = summary([
+ ["/docs", 500, 12],
+ ["/blog", 180, 8],
+ ]);
+ const previous = summary([
+ ["/docs", 450, 11],
+ ["/blog", 200, 8],
+ ]);
+
+ expect(findOnlyLosingSection(current, undefined)).toBeNull();
+ expect(findOnlyLosingSection(undefined, previous)).toBeNull();
+ expect(findOnlyLosingSection({ ...current, sectionCount: 900 }, previous)).toBeNull();
+ expect(findOnlyLosingSection(current, { ...previous, sectionCount: 900 })).toBeNull();
+ });
+});
diff --git a/client/src/app/[site]/pages/components/losingSection.ts b/client/src/app/[site]/pages/components/losingSection.ts
new file mode 100644
index 000000000..5a3f0121b
--- /dev/null
+++ b/client/src/app/[site]/pages/components/losingSection.ts
@@ -0,0 +1,51 @@
+import type { PagesSummary } from "@/api/analytics/hooks/useGetPages";
+
+export interface LosingSection {
+ section: string;
+ pageviews: number;
+ previousPageviews: number;
+ /**
+ * Where the section sits among the top-level rows sorted by views, or null
+ * when it is not a row of its own in this period (fewer than two pages left).
+ */
+ rank: number | null;
+}
+
+// A list the server capped cannot prove that no other section lost traffic.
+const isComplete = (summary: PagesSummary) => summary.sections.length >= summary.sectionCount;
+
+/**
+ * The one section with fewer views than in the comparison period, when every
+ * other section held or grew. Null in every other case: no comparison, a
+ * capped section list, fewer than two sections, or none or several losing.
+ *
+ * A section is a first path segment with two or more pages in either period,
+ * so one that lost all its traffic still counts as losing.
+ */
+export function findOnlyLosingSection(
+ current: PagesSummary | undefined,
+ previous: PagesSummary | undefined
+): LosingSection | null {
+ if (!current || !previous || !isComplete(current) || !isComplete(previous)) return null;
+
+ const now = new Map(current.sections.map(section => [section.section, section]));
+ const before = new Map(previous.sections.map(section => [section.section, section]));
+
+ const sections = [...new Set([...now.keys(), ...before.keys()])].filter(
+ key => (now.get(key)?.pages ?? 0) >= 2 || (before.get(key)?.pages ?? 0) >= 2
+ );
+ if (sections.length < 2) return null;
+
+ const losing = sections.filter(key => (now.get(key)?.pageviews ?? 0) < (before.get(key)?.pageviews ?? 0));
+ if (losing.length !== 1) return null;
+
+ const [section] = losing;
+ const rank = current.sections.findIndex(candidate => candidate.section === section);
+
+ return {
+ section,
+ pageviews: now.get(section)?.pageviews ?? 0,
+ previousPageviews: before.get(section)?.pageviews ?? 0,
+ rank: rank !== -1 && (now.get(section)?.pages ?? 0) >= 2 ? rank : null,
+ };
+}
diff --git a/client/src/app/[site]/pages/components/pageIdentity.test.ts b/client/src/app/[site]/pages/components/pageIdentity.test.ts
index ec561f446..a00361b34 100644
--- a/client/src/app/[site]/pages/components/pageIdentity.test.ts
+++ b/client/src/app/[site]/pages/components/pageIdentity.test.ts
@@ -1,31 +1,35 @@
import { describe, expect, it } from "vitest";
-import type { PageTitleItem } from "@/api/analytics/endpoints";
-import { getPageItemFilters, getPageItemKey } from "./pageIdentity";
-
-const pageItem = (overrides: Partial<PageTitleItem> = {}): PageTitleItem => ({
- value: "Pricing",
- pathname: "/pricing",
- count: 1,
- percentage: 100,
- ...overrides,
-});
+import { formatSection, getPageFilters, getRowId, getTrendKeys } from "./pageIdentity";
describe("page identity", () => {
- it("identifies and filters titled rows by page title", () => {
- const item = pageItem();
-
- expect(getPageItemKey(item)).toBe("title:Pricing");
- expect(getPageItemFilters(item)).toEqual([{ parameter: "page_title", value: ["Pricing"], type: "equals" }]);
+ it("tells a page from the section of the same name", () => {
+ expect(getRowId({ kind: "page", key: "/docs" })).toBe("page:/docs");
+ expect(getRowId({ kind: "section", key: "/docs" })).toBe("section:/docs");
});
- it("identifies and filters untitled rows by pathname", () => {
- const item = pageItem({ value: "", pathname: "/docs/getting-started" });
+ it("writes sections with a trailing slash", () => {
+ expect(formatSection("/docs")).toBe("/docs/");
+ expect(formatSection("/")).toBe("/");
+ });
- expect(getPageItemKey(item)).toBe("pathname:/docs/getting-started");
- expect(getPageItemFilters(item)).toEqual([
- { parameter: "page_title", value: [], type: "is_null" },
- { parameter: "pathname", value: ["/docs/getting-started"], type: "equals" },
+ it("filters by path, or by entry or exit page on those lists", () => {
+ expect(getPageFilters("/pricing", "all")).toEqual([{ parameter: "pathname", value: ["/pricing"], type: "equals" }]);
+ expect(getPageFilters("/pricing", "entry")).toEqual([
+ { parameter: "entry_page", value: ["/pricing"], type: "equals" },
]);
+ expect(getPageFilters("/pricing", "exit")).toEqual([
+ { parameter: "exit_page", value: ["/pricing"], type: "equals" },
+ ]);
+ });
+
+ it("splits a batch of rows into paths and sections", () => {
+ expect(
+ getTrendKeys([
+ { kind: "page", key: "/" },
+ { kind: "section", key: "/docs" },
+ { kind: "page", key: "/pricing" },
+ ])
+ ).toEqual({ paths: ["/", "/pricing"], sections: ["/docs"] });
});
});
diff --git a/client/src/app/[site]/pages/components/pageIdentity.ts b/client/src/app/[site]/pages/components/pageIdentity.ts
index 65b529d4c..e03955431 100644
--- a/client/src/app/[site]/pages/components/pageIdentity.ts
+++ b/client/src/app/[site]/pages/components/pageIdentity.ts
@@ -1,18 +1,32 @@
-import type { Filter } from "@rybbit/shared";
+import type { Filter, FilterParameter } from "@rybbit/shared";
-import type { PageTitleItem } from "@/api/analytics/endpoints";
+import type { PageRow, PagesMode, PageTrend } from "@/api/analytics/hooks/useGetPages";
-export function getPageItemKey(item: PageTitleItem) {
- return item.value ? `title:${item.value}` : `pathname:${item.pathname}`;
-}
+/** Unique among the rows of one table: a page and a section can share a key ("/docs"). */
+export const getRowId = (row: Pick<PageRow | PageTrend, "kind" | "key">) => `${row.kind}:${row.key}`;
+
+/** How a section is written: "/docs/". The root section is just "/". */
+export const formatSection = (section: string) => (section.endsWith("/") ? section : `${section}/`);
-export function getPageItemFilters(item: PageTitleItem): Filter[] {
- if (item.value) {
- return [{ parameter: "page_title", value: [item.value], type: "equals" }];
- }
+const MODE_PARAMETER: Record<PagesMode, FilterParameter> = {
+ all: "pathname",
+ entry: "entry_page",
+ exit: "exit_page",
+};
+
+/**
+ * The filter that identifies a page row. On the entry and exit lists a row
+ * stands for the sessions that started or ended on the page, not every session
+ * that saw it.
+ */
+export function getPageFilters(path: string, mode: PagesMode): Filter[] {
+ return [{ parameter: MODE_PARAMETER[mode], value: [path], type: "equals" }];
+}
- return [
- { parameter: "page_title", value: [], type: "is_null" },
- { parameter: "pathname", value: [item.pathname], type: "equals" },
- ];
+/** Paths and sections of a batch of rows, as the trends endpoint takes them. */
+export function getTrendKeys(rows: Pick<PageRow, "kind" | "key">[]) {
+ return {
+ paths: rows.filter(row => row.kind === "page").map(row => row.key),
+ sections: rows.filter(row => row.kind === "section").map(row => row.key),
+ };
}
diff --git a/client/src/app/[site]/pages/page.tsx b/client/src/app/[site]/pages/page.tsx
index 341b502cc..c65cf4fda 100644
--- a/client/src/app/[site]/pages/page.tsx
+++ b/client/src/app/[site]/pages/page.tsx
@@ -1,15 +1,52 @@
"use client";
+import { useDebounce } from "@uidotdev/usehooks";
import { useExtracted } from "next-intl";
+import { useState } from "react";
+import { PagesMode, PagesSort, PagesSortOrder } from "@/api/analytics/hooks/useGetPages";
+import { SegmentedControl } from "@/components/interior/segmented-control";
+import { AnalysisBar } from "@/components/site/AnalysisBar";
+import { BreakdownControl } from "@/components/site/BreakdownControl";
+import { Input } from "@/components/ui/input";
import { useSetPageTitle } from "@/hooks/useSetPageTitle";
import { useStore } from "@/lib/store";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { SubHeader } from "../components/SubHeader/SubHeader";
-import { PagesTable } from "./components/PagesTable";
+import { PagesInsight } from "./components/PagesInsight";
+import { PagesStatBand } from "./components/PagesStatBand";
+import { PAGE_SIZE, PagesTable } from "./components/PagesTable";
+
+type Breakdown = "section" | "none";
+
+// Each list opens on the column it is about.
+const MODE_SORT: Record<PagesMode, PagesSort> = {
+ all: "pageviews",
+ entry: "entries",
+ exit: "exits",
+};
export default function Pages() {
const t = useExtracted();
- const { site } = useStore();
+ const { site, time, filters } = useStore();
+
+ const [breakdown, setBreakdown] = useState<Breakdown>("section");
+ const [mode, setMode] = useState<PagesMode>("all");
+ const [sorting, setSorting] = useState<{ sort: PagesSort; order: PagesSortOrder }>({
+ sort: "pageviews",
+ order: "desc",
+ });
+ const [search, setSearch] = useState("");
+ // The page number belongs to one period and filter set: a new one starts at the first page.
+ const scope = JSON.stringify([time, filters]);
+ const [paging, setPaging] = useState({ page: 1, scope });
+ const page = paging.scope === scope ? paging.page : 1;
+ const setPage = (next: number) => setPaging({ page: next, scope });
+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
+ const [focusSection, setFocusSection] = useState<string | null>(null);
+
+ const debouncedSearch = useDebounce(search.trim(), 300);
+ // Typing waits for a pause; clearing the box applies at once.
+ const activeSearch = search.trim() ? debouncedSearch : "";
useSetPageTitle("Pages");
@@ -17,11 +54,100 @@ export default function Pages() {
return null;
}
+ // Any change to what is listed starts again from the first page, and drops a pending scroll.
+ const restart = () => {
+ setPage(1);
+ setFocusSection(null);
+ };
+
return (
<DisabledOverlay message={t("pages")} featurePath="pages">
- <div className="p-2 md:p-4 max-w-[1400px] mx-auto space-y-3">
+ <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
<SubHeader />
- <PagesTable />
+ <PagesStatBand />
+ <AnalysisBar
+ // On a phone the search takes a row of its own, full width.
+ className="[&>div:last-child]:w-full sm:[&>div:last-child]:w-auto"
+ breakdown={
+ <BreakdownControl<Breakdown>
+ value={breakdown}
+ onChange={value => {
+ setBreakdown(value);
+ restart();
+ }}
+ options={[
+ { value: "section", label: t("Section") },
+ { value: "none", label: t("None") },
+ ]}
+ />
+ }
+ end={
+ <div className="w-full sm:w-64 [&>div]:w-full">
+ <Input
+ isSearch
+ type="search"
+ value={search}
+ onChange={event => {
+ setSearch(event.target.value);
+ restart();
+ }}
+ placeholder={t("Search title or path")}
+ aria-label={t("Search title or path")}
+ className="h-8 text-xs"
+ />
+ </div>
+ }
+ >
+ <SegmentedControl<PagesMode>
+ size="sm"
+ aria-label={t("Pages to list")}
+ value={mode}
+ onValueChange={value => {
+ setMode(value);
+ setSorting({ sort: MODE_SORT[value], order: "desc" });
+ restart();
+ }}
+ options={[
+ { value: "all", label: t("All pages") },
+ { value: "entry", label: t("Entry pages") },
+ { value: "exit", label: t("Exit pages") },
+ ]}
+ />
+ </AnalysisBar>
+ <PagesInsight
+ onShowSection={({ section, rank }) => {
+ if (rank === null) return;
+ // The section's place among the rows sorted by views is its place in the default table.
+ setBreakdown("section");
+ setMode("all");
+ setSorting({ sort: "pageviews", order: "desc" });
+ setSearch("");
+ setPage(Math.floor(rank / PAGE_SIZE) + 1);
+ setExpanded(current => new Set(current).add(section));
+ setFocusSection(section);
+ }}
+ />
+ <PagesTable
+ // A search lists the matching pages themselves: a rollup of a few matches would read as the section's total.
+ group={breakdown === "section" && !activeSearch ? "section" : "page"}
+ mode={mode}
+ search={activeSearch}
+ sort={sorting.sort}
+ order={sorting.order}
+ onSort={sort => {
+ setSorting(current => ({
+ sort,
+ order: current.sort === sort && current.order === "desc" ? "asc" : "desc",
+ }));
+ restart();
+ }}
+ page={page}
+ onPageChange={setPage}
+ expanded={expanded}
+ onExpandedChange={setExpanded}
+ focusSection={focusSection}
+ onFocusHandled={() => setFocusSection(null)}
+ />
</div>
</DisabledOverlay>
);
diff --git a/client/src/app/[site]/performance/components/PercentileSelector.tsx b/client/src/app/[site]/performance/components/PercentileSelector.tsx
index 32f6b99ec..38197961d 100644
--- a/client/src/app/[site]/performance/components/PercentileSelector.tsx
+++ b/client/src/app/[site]/performance/components/PercentileSelector.tsx
@@ -4,16 +4,7 @@ import { useExtracted } from "next-intl";
import { SegmentedControl } from "@/components/interior/segmented-control";
import { PercentileLevel, usePerformanceStore } from "../performanceStore";
-const PERCENTILE_OPTIONS: {
- value: PercentileLevel;
- label: string;
- color: string;
-}[] = [
- { value: "p50", label: "P50", color: "hsl(var(--indigo-100))" },
- { value: "p75", label: "P75", color: "hsl(var(--indigo-300))" },
- { value: "p90", label: "P90", color: "hsl(var(--indigo-400))" },
- { value: "p99", label: "P99", color: "hsl(var(--indigo-500))" },
-];
+const PERCENTILES: PercentileLevel[] = ["p50", "p75", "p90", "p99"];
export function PercentileSelector() {
const t = useExtracted();
@@ -23,16 +14,7 @@ export function PercentileSelector() {
<SegmentedControl<PercentileLevel>
aria-label={t("Percentile")}
size="sm"
- options={PERCENTILE_OPTIONS.map(option => ({
- value: option.value,
- // The swatch matches this percentile's line in the chart below.
- label: (
- <>
- <span aria-hidden className="h-2.5 w-2.5 rounded-sm" style={{ backgroundColor: option.color }} />
- {option.label}
- </>
- ),
- }))}
+ options={PERCENTILES.map(percentile => ({ value: percentile, label: percentile }))}
value={selectedPercentile}
onValueChange={setSelectedPercentile}
/>
diff --git a/client/src/app/[site]/performance/components/PerformanceByDimensions.tsx b/client/src/app/[site]/performance/components/PerformanceByDimensions.tsx
index 59c68af55..052d1b1bc 100644
--- a/client/src/app/[site]/performance/components/PerformanceByDimensions.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceByDimensions.tsx
@@ -1,13 +1,14 @@
"use client";
-import { useState } from "react";
import { useExtracted } from "next-intl";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../components/ui/basic-tabs";
-import { Card, CardContent } from "../../../../components/ui/card";
-import { PerformanceTable } from "./PerformanceTable";
+import { useState } from "react";
+import { Card } from "../../../../components/ui/card";
+import { Tabs, TabsList, TabsTrigger } from "../../../../components/ui/tabs";
+import { PerformanceDimension } from "../utils/usePerformanceRows";
import { PerformanceMap } from "./PerformanceMap";
+import { PerformanceTable } from "./PerformanceTable";
-type Tab = "pathname" | "country" | "map" | "device_type" | "browser" | "operating_system";
+type Tab = PerformanceDimension | "map";
export function PerformanceByDimensions() {
const t = useExtracted();
@@ -15,42 +16,27 @@ export function PerformanceByDimensions() {
return (
<Card>
- <CardContent className="mt-2">
- <Tabs defaultValue="pathname" value={tab} onValueChange={value => setTab(value as Tab)}>
+ <div className="overflow-x-auto p-4 pb-3">
+ <Tabs value={tab} onValueChange={value => setTab(value as Tab)}>
<TabsList>
<TabsTrigger value="pathname">{t("Pages")}</TabsTrigger>
<TabsTrigger value="country">{t("Countries")}</TabsTrigger>
+ <TabsTrigger value="region">{t("Regions")}</TabsTrigger>
<TabsTrigger value="map">{t("Map")}</TabsTrigger>
<TabsTrigger value="device_type">{t("Devices")}</TabsTrigger>
<TabsTrigger value="browser">{t("Browsers")}</TabsTrigger>
- <TabsTrigger value="operating_system">{t("Operating Systems")}</TabsTrigger>
+ <TabsTrigger value="operating_system">{t("Operating systems")}</TabsTrigger>
</TabsList>
-
- <TabsContent value="pathname">
- <PerformanceTable dimension="pathname" title={t("Performance by Page")} />
- </TabsContent>
-
- <TabsContent value="country">
- <PerformanceTable dimension="country" title={t("Performance by Country")} />
- </TabsContent>
-
- <TabsContent value="map">
- <PerformanceMap height="600px" />
- </TabsContent>
-
- <TabsContent value="device_type">
- <PerformanceTable dimension="device_type" title={t("Performance by Device Type")} />
- </TabsContent>
-
- <TabsContent value="browser">
- <PerformanceTable dimension="browser" title={t("Performance by Browser")} />
- </TabsContent>
-
- <TabsContent value="operating_system">
- <PerformanceTable dimension="operating_system" title={t("Performance by Operating System")} />
- </TabsContent>
</Tabs>
- </CardContent>
+ </div>
+ {tab === "map" ? (
+ <div className="px-4 pb-4">
+ <PerformanceMap height="600px" />
+ </div>
+ ) : (
+ // Keyed so each dimension starts on its first page with its own sort.
+ <PerformanceTable key={tab} dimension={tab} />
+ )}
</Card>
);
}
diff --git a/client/src/app/[site]/performance/components/PerformanceChart.tsx b/client/src/app/[site]/performance/components/PerformanceChart.tsx
index 6c1d187af..8e2cd8480 100644
--- a/client/src/app/[site]/performance/components/PerformanceChart.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceChart.tsx
@@ -1,235 +1,564 @@
"use client";
-import { Card, CardContent, CardLoader } from "@/components/ui/card";
-import { Skeleton } from "@/components/ui/skeleton";
+import type { Annotation, TimeBucket } from "@rybbit/shared";
+import * as d3 from "d3";
import { DateTime } from "luxon";
-import Link from "next/link";
import { useExtracted } from "next-intl";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
+import { createPortal } from "react-dom";
+import { ChartLegend, ChartLegendItem } from "@/components/site/ChartLegend";
+import { Card, CardLoader } from "@/components/ui/card";
+import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
+import { Skeleton } from "@/components/ui/skeleton";
+import { cn, formatter } from "@/lib/utils";
+import { GetPerformanceTimeSeriesResponse } from "../../../../api/analytics/endpoints";
import { useGetPerformanceTimeSeries } from "../../../../api/analytics/hooks/performance/useGetPerformanceTimeSeries";
-import { BucketSelection } from "../../../../components/BucketSelection";
import { ChartTooltip } from "../../../../components/charts/ChartTooltip";
import { TimeSeriesChart } from "../../../../components/charts/TimeSeriesChart";
-import type { TimeSeriesChartPoint, TimeSeriesChartSeries } from "../../../../components/charts/TimeSeriesChart";
-import { getChartTimeBounds } from "../../../../components/charts/timeSeriesChartUtils";
-import { RybbitTextLogo } from "../../../../components/RybbitLogo";
-import { ToggleChip } from "../../../../components/ToggleChip";
-import { useWhiteLabel } from "../../../../hooks/useIsWhiteLabel";
-import { authClient } from "../../../../lib/auth";
+import type { TimeSeriesChartPoint, TimeSeriesOverlayContext } from "../../../../components/charts/TimeSeriesChart";
+import { bucketsBetween, getChartTimeBounds, shiftBuckets } from "../../../../components/charts/timeSeriesChartUtils";
+import { describeComparisonWindow } from "../../../../components/DateSelector/rangeFields";
import { formatChartDateTime } from "../../../../lib/dateTimeUtils";
-import { getTimezone, useStore } from "../../../../lib/store";
-import { usePerformanceStore } from "../performanceStore";
-import { formatMetricValue, getMetricUnit, getPerformanceThresholds, METRIC_LABELS } from "../utils/performanceUtils";
-
-const PERCENTILES = ["P50", "P75", "P90", "P99"] as const;
-type PercentileLabel = (typeof PERCENTILES)[number];
-
-const percentileColors: Record<PercentileLabel, string> = {
- P50: "hsl(var(--indigo-100))",
- P75: "hsl(var(--indigo-300))",
- P90: "hsl(var(--indigo-400))",
- P99: "hsl(var(--indigo-500))",
-};
+import { useComparisonEnabled, useStore, useTimezone } from "../../../../lib/store";
+import {
+ AnnotationHoverCard,
+ AnnotationPopoverContent,
+} from "../../main/components/MainSection/annotations/AnnotationDetails";
+import { AnnotationPins } from "../../main/components/MainSection/annotations/AnnotationPins";
+import type { AnnotationCluster } from "../../main/components/MainSection/annotations/annotationUtils";
+import { PercentileLevel, PerformanceMetric, usePerformanceStore } from "../performanceStore";
+import {
+ formatMetric,
+ getMetricRating,
+ getPerformanceThresholds,
+ MetricRating,
+ RATING_COLOR,
+ RATING_TEXT_CLASS,
+} from "../utils/performanceUtils";
+import { useVisibleAnnotations } from "../utils/useVisibleAnnotations";
+import { RatingMark, useMetricNames, useRatingLabels } from "./shared/RatingMark";
-const percentileFields: Record<PercentileLabel, "p50" | "p75" | "p90" | "p99"> = {
- P50: "p50",
- P75: "p75",
- P90: "p90",
- P99: "p99",
-};
+const DATA_COLOR = "hsl(var(--dataviz))";
+const RANGE_COLOR = "hsl(var(--dataviz) / 0.35)";
+const PREVIOUS_COLOR = "hsl(var(--neutral-500))";
+const TOOLTIP_PERCENTILES: PercentileLevel[] = ["p99", "p90", "p75", "p50"];
+
+// TimeSeriesChart never lets its y axis end below 1, which flattens a metric
+// measured in hundredths. CLS is plotted in thousandths and printed back in
+// its own unit.
+const plotScaleOf = (metric: PerformanceMetric) => (metric === "cls" ? 1000 : 1);
+
+type TimeSeriesRow = GetPerformanceTimeSeriesResponse[number];
+
+const isMeasured = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value);
-type PerformancePoint = TimeSeriesChartPoint & {
- currentTime: DateTime;
- percentile: PercentileLabel;
+type VitalPoint = TimeSeriesChartPoint & {
+ time: DateTime;
+ loads: number;
+ /** The metric at every percentile, in its own unit. */
+ percentiles: Record<PercentileLevel, number | null>;
};
+type RangePoint = { x: Date; low: number; high: number };
+type PreviousPoint = TimeSeriesChartPoint & { value: number; originalTime: DateTime };
+type LoadsBar = { x: Date; loads: number };
+
+const percentilesOf = (row: TimeSeriesRow, metric: PerformanceMetric): Record<PercentileLevel, number | null> => ({
+ p50: row[`${metric}_p50`],
+ p75: row[`${metric}_p75`],
+ p90: row[`${metric}_p90`],
+ p99: row[`${metric}_p99`],
+});
+
+type PinTarget = { cluster: AnnotationCluster; rect: DOMRect };
+
+/**
+ * Everything the chart adds to a plain line: the rating bands, the p50 to p90
+ * range, the previous period, and the loads each bucket rests on. It is drawn
+ * through TimeSeriesChart's overlay, so it shares the chart's scales exactly;
+ * the zone labels and the loads strip sit just outside the plot, in padding
+ * the wrapper reserves for them.
+ */
+function VitalsOverlay({
+ context,
+ metric,
+ line,
+ range,
+ previous,
+ bars,
+ bucket,
+ ratingLabels,
+ loadsLabel,
+}: {
+ context: TimeSeriesOverlayContext;
+ metric: PerformanceMetric;
+ line: VitalPoint[];
+ range: RangePoint[];
+ previous: PreviousPoint[];
+ bars: LoadsBar[];
+ bucket: TimeBucket;
+ ratingLabels: Record<MetricRating, string>;
+ loadsLabel: string;
+}) {
+ const { xScale, yScale, plotLeft, plotRight, plotTop, plotBottom, isDark } = context;
+ const thresholds = getPerformanceThresholds(metric);
+ const scale = plotScaleOf(metric);
+ const clampY = (value: number) => Math.max(plotTop, Math.min(plotBottom, yScale(value * scale)));
+ const goodY = clampY(thresholds.good);
+ const poorY = clampY(thresholds.needs_improvement);
+
+ const linePath = d3
+ .line<TimeSeriesChartPoint>()
+ .x(d => xScale(d.x))
+ .y(d => yScale(d.y));
+ const rangePath = d3
+ .area<RangePoint>()
+ .x(d => xScale(d.x))
+ .y0(d => yScale(d.low))
+ .y1(d => yScale(d.high));
+
+ const zones: { rating: MetricRating; y: number }[] = [
+ { rating: "good", y: (plotBottom + goodY) / 2 },
+ { rating: "needs_improvement", y: (goodY + poorY) / 2 },
+ { rating: "poor", y: (poorY + plotTop) / 2 },
+ ];
+
+ const axisColor = isDark ? "hsl(var(--neutral-400))" : "hsl(var(--neutral-500))";
+ const gridColor = isDark ? "hsl(var(--neutral-800))" : "hsl(var(--neutral-100))";
+ // Below the x axis labels.
+ const stripTop = plotBottom + 34;
+ const stripBottom = stripTop + 32;
+ const maxLoads = bars.reduce((largest, bar) => Math.max(largest, bar.loads), 0);
+ const bucketWidth = bars.length
+ ? xScale(shiftBuckets(DateTime.fromJSDate(bars[0].x), bucket, 1).toJSDate()) - xScale(bars[0].x)
+ : 0;
+ const barWidth = Math.max(1, Math.min(24, bucketWidth * 0.62));
+ // The first bar is centred on the plot's left edge, so its labels start left of it.
+ const labelX = plotLeft - barWidth / 2 - 6;
+
+ return (
+ <g pointerEvents="none">
+ <rect
+ x={plotLeft}
+ y={poorY}
+ width={plotRight - plotLeft}
+ height={goodY - poorY}
+ fill={RATING_COLOR.needs_improvement}
+ opacity={0.05}
+ />
+ <rect
+ x={plotLeft}
+ y={plotTop}
+ width={plotRight - plotLeft}
+ height={poorY - plotTop}
+ fill={RATING_COLOR.poor}
+ opacity={0.07}
+ />
+ {zones.map(zone => (
+ <text
+ key={zone.rating}
+ x={plotRight + 10}
+ y={zone.y}
+ dy="0.35em"
+ fontSize={11}
+ className={cn("hidden fill-current md:block", RATING_TEXT_CLASS[zone.rating])}
+ >
+ {ratingLabels[zone.rating]}
+ </text>
+ ))}
+
+ {range.length > 1 && <path d={rangePath(range) ?? ""} fill={DATA_COLOR} opacity={0.13} />}
+ {/* The two limits, above the range so it does not wash them out. */}
+ <line
+ x1={plotLeft}
+ x2={plotRight}
+ y1={goodY}
+ y2={goodY}
+ stroke={RATING_COLOR.good}
+ strokeDasharray="6 5"
+ opacity={0.75}
+ />
+ <line
+ x1={plotLeft}
+ x2={plotRight}
+ y1={poorY}
+ y2={poorY}
+ stroke={RATING_COLOR.poor}
+ strokeDasharray="6 5"
+ opacity={0.75}
+ />
+ {previous.length > 0 && (
+ <path
+ d={linePath(previous) ?? ""}
+ fill="none"
+ stroke={PREVIOUS_COLOR}
+ strokeWidth={1.5}
+ strokeDasharray="4 4"
+ strokeLinejoin="round"
+ />
+ )}
+ {/* Again, so the measured line stays above the range and the previous period. */}
+ <path d={linePath(line) ?? ""} fill="none" stroke={DATA_COLOR} strokeWidth={2} strokeLinejoin="round" />
+
+ {maxLoads > 0 && (
+ <g>
+ <line x1={plotLeft} x2={plotRight} y1={stripBottom} y2={stripBottom} stroke={gridColor} strokeWidth={1} />
+ <text x={labelX} y={stripTop} dy="0.7em" textAnchor="end" fontSize={11} fill={axisColor}>
+ {formatter(maxLoads)}
+ </text>
+ <text x={labelX} y={stripBottom} textAnchor="end" fontSize={11} fill={axisColor}>
+ 0
+ </text>
+ {bars.map(bar => {
+ const height = Math.max(1, (bar.loads / maxLoads) * (stripBottom - stripTop));
+ return (
+ <rect
+ key={bar.x.getTime()}
+ x={xScale(bar.x) - barWidth / 2}
+ y={stripBottom - height}
+ width={barWidth}
+ height={height}
+ rx={Math.min(1.5, barWidth / 2)}
+ fill={DATA_COLOR}
+ opacity={0.4}
+ />
+ );
+ })}
+ <text
+ x={plotRight + 10}
+ y={(stripTop + stripBottom) / 2}
+ dy="0.35em"
+ fontSize={11}
+ fill={axisColor}
+ className="hidden md:block"
+ >
+ {loadsLabel}
+ </text>
+ </g>
+ )}
+ </g>
+ );
+}
+
export function PerformanceChart() {
const t = useExtracted();
- const session = authClient.useSession();
- const { site, bucket, time } = useStore();
- const { selectedPerformanceMetric } = usePerformanceStore();
- const { isWhiteLabel } = useWhiteLabel();
- const timezone = getTimezone();
-
- const [visiblePercentiles, setVisiblePercentiles] = useState<Set<string>>(new Set(PERCENTILES));
-
- const togglePercentile = (percentile: string) => {
- setVisiblePercentiles(prev => {
- const newSet = new Set(prev);
- if (newSet.has(percentile)) {
- newSet.delete(percentile);
- } else {
- newSet.add(percentile);
- }
- return newSet;
- });
- };
-
- const {
- data: timeSeriesData,
- isLoading,
- isFetching,
- } = useGetPerformanceTimeSeries({
- site,
- });
-
- const thresholds = getPerformanceThresholds(selectedPerformanceMetric);
-
- const thresholdMarkers = thresholds
- ? [
- {
- value: thresholds.good,
- color: "hsl(var(--green-400))",
- strokeDasharray: "8 8",
- label: `Good (≤${formatMetricValue(selectedPerformanceMetric, thresholds.good)}${getMetricUnit(
- selectedPerformanceMetric,
- thresholds.good
- )})`,
- },
- {
- value: thresholds.needs_improvement,
- color: "hsl(var(--amber-400))",
- strokeDasharray: "8 8",
- label: `Needs Improvement (≤${formatMetricValue(
- selectedPerformanceMetric,
- thresholds.needs_improvement
- )}${getMetricUnit(selectedPerformanceMetric, thresholds.needs_improvement)})`,
- },
- ]
- : [];
-
- const { current, chartSeries, chartMin, chartMax, max } = useMemo(() => {
- const { min: boundsMin, max: boundsMax } = getChartTimeBounds(time, bucket, timezone);
+ const { site, bucket, time, previousTime } = useStore();
+ const timezone = useTimezone();
+ const comparisonEnabled = useComparisonEnabled();
+ const { selectedPerformanceMetric: metric, selectedPercentile: percentile, showAnnotations } = usePerformanceStore();
+ const metricNames = useMetricNames();
+ const ratingLabels = useRatingLabels();
+ const visibleAnnotations = useVisibleAnnotations();
+ const annotations: Annotation[] = showAnnotations ? visibleAnnotations : [];
+
+ const { data, isLoading, isFetching } = useGetPerformanceTimeSeries({ site });
+ const { data: previousSeries } = useGetPerformanceTimeSeries({ site, periodTime: "previous" });
+ // A query that is switched off keeps its last result as a placeholder.
+ const previousData = comparisonEnabled ? previousSeries : undefined;
+
+ const [hoveredPin, setHoveredPin] = useState<PinTarget | null>(null);
+ const [selectedPin, setSelectedPin] = useState<PinTarget | null>(null);
+ // A pin's card anchors to a snapshot of where the pin was on screen.
+ useEffect(() => {
+ setSelectedPin(null);
+ setHoveredPin(null);
+ }, [time, bucket, site, metric, percentile, showAnnotations]);
+
+ const thresholds = getPerformanceThresholds(metric);
+ const scale = plotScaleOf(metric);
+
+ const { line, range, bars, previous, previousByTime, chartMin, chartMax, max } = useMemo(() => {
+ const { min: boundsMin, max: boundsMax } = getChartTimeBounds(time, bucket, timezone);
const now = DateTime.now();
const lowerBoundMs = boundsMin?.getTime();
const upperBoundMs = (boundsMax ?? now.toJSDate()).getTime();
- const seriesByPercentile = new Map<PercentileLabel, PerformancePoint[]>(
- PERCENTILES.map(percentile => [percentile, []])
- );
+ // Stale rows from the period just left must not land on the new x axis.
+ const inWindow = (ms: number) => (lowerBoundMs === undefined || ms >= lowerBoundMs) && ms <= upperBoundMs;
+
+ const line: VitalPoint[] = [];
+ const range: RangePoint[] = [];
+ const bars: LoadsBar[] = [];
+ data?.forEach(row => {
+ const timestamp = DateTime.fromSQL(row.time, { zone: timezone }).toUTC();
+ const loads = Number(row.event_count) || 0;
+ // A bucket nobody loaded a page in is a gap, not a zero.
+ if (timestamp > now || !inWindow(timestamp.toMillis()) || loads <= 0) return;
- timeSeriesData?.forEach(item => {
- const timestamp = DateTime.fromSQL(item.time, { zone: timezone }).toUTC();
- if (timestamp > now) return;
- const timestampMs = timestamp.toMillis();
- if (lowerBoundMs !== undefined && timestampMs < lowerBoundMs) return;
- if (timestampMs > upperBoundMs) return;
-
- PERCENTILES.forEach(percentile => {
- if (!visiblePercentiles.has(percentile)) return;
- const field = `${selectedPerformanceMetric}_${percentileFields[percentile]}` as keyof typeof item;
- const value = item[field];
- if (typeof value !== "number") return;
- seriesByPercentile.get(percentile)?.push({
- x: timestamp.toJSDate(),
- y: value,
- currentTime: timestamp,
- percentile,
- });
- });
+ const x = timestamp.toJSDate();
+ const percentiles = percentilesOf(row, metric);
+ bars.push({ x, loads });
+ const value = percentiles[percentile];
+ if (isMeasured(value)) line.push({ x, y: value * scale, time: timestamp, loads, percentiles });
+ if (isMeasured(percentiles.p50) && isMeasured(percentiles.p90)) {
+ range.push({ x, low: percentiles.p50 * scale, high: percentiles.p90 * scale });
+ }
});
- const chartSeries: TimeSeriesChartSeries<PerformancePoint>[] = PERCENTILES.map(percentile => ({
- id: percentile,
- color: percentileColors[percentile],
- data: seriesByPercentile.get(percentile) ?? [],
- strokeWidth: 1,
- })).filter(series => series.data.length > 0 && visiblePercentiles.has(series.id));
+ // The previous period is moved onto this period's x axis by a whole number
+ // of buckets, first bucket onto first bucket, as the Main chart does.
+ const previousMin = previousTime ? getChartTimeBounds(previousTime, bucket, timezone).min : undefined;
+ const bucketShift =
+ boundsMin && previousMin
+ ? bucketsBetween(
+ DateTime.fromJSDate(previousMin, { zone: timezone }),
+ DateTime.fromJSDate(boundsMin, { zone: timezone }),
+ bucket
+ )
+ : 0;
+ const previous: PreviousPoint[] = [];
+ previousData?.forEach(row => {
+ const originalTime = DateTime.fromSQL(row.time, { zone: timezone }).toUTC();
+ const value = row[`${metric}_${percentile}`];
+ if (!isMeasured(value) || !(Number(row.event_count) > 0)) return;
+ const mappedMs = shiftBuckets(originalTime.setZone(timezone), bucket, bucketShift).toMillis();
+ if (!inWindow(mappedMs)) return;
+ previous.push({ x: new Date(mappedMs), y: value * scale, value, originalTime });
+ });
- const allPoints = chartSeries.flatMap(series => series.data);
- const dataMin = allPoints.length ? new Date(Math.min(...allPoints.map(point => point.x.getTime()))) : undefined;
- const dataMax = allPoints.length ? new Date(Math.max(...allPoints.map(point => point.x.getTime()))) : undefined;
- const max = allPoints.reduce((largest, point) => Math.max(largest, point.y), 0);
+ const highest = [...line.map(p => p.y), ...range.map(p => p.high), ...previous.map(p => p.y)].reduce(
+ (largest, y) => Math.max(largest, y),
+ 0
+ );
return {
- current: chartSeries[0]?.data ?? [],
- chartSeries,
- chartMin: dataMin ?? boundsMin,
- chartMax: dataMax ?? boundsMax ?? now.toJSDate(),
- max,
+ line,
+ range,
+ bars,
+ previous,
+ previousByTime: new Map(previous.map(point => [point.x.getTime(), point])),
+ chartMin: boundsMin ?? bars[0]?.x,
+ chartMax: boundsMax ?? bars[bars.length - 1]?.x ?? now.toJSDate(),
+ // Tall enough to show all three rating bands, with room above the data.
+ max: Math.max(highest * 1.05, thresholds.needs_improvement * scale * 1.25),
};
- }, [bucket, selectedPerformanceMetric, time, timeSeriesData, timezone, visiblePercentiles]);
+ }, [data, previousData, metric, percentile, scale, thresholds, time, previousTime, bucket, timezone]);
+
+ const interval = (() => {
+ switch (bucket) {
+ case "minute":
+ return t("per minute");
+ case "five_minutes":
+ return t("per 5 minutes");
+ case "ten_minutes":
+ return t("per 10 minutes");
+ case "fifteen_minutes":
+ return t("per 15 minutes");
+ case "hour":
+ return t("per hour");
+ case "day":
+ return t("per day");
+ case "week":
+ return t("per week");
+ case "month":
+ return t("per month");
+ case "year":
+ return t("per year");
+ }
+ })();
+
+ const currentWindow = describeComparisonWindow(time, time, timezone);
+ const previousWindow = describeComparisonWindow(previousTime, time, timezone);
+ const legend: ChartLegendItem[] = [
+ { id: "current", label: currentWindow ? `${percentile}, ${currentWindow}` : percentile, color: DATA_COLOR },
+ { id: "range", label: t("p50 to p90"), color: RANGE_COLOR },
+ ];
+ if (previous.length > 0) {
+ legend.push({
+ id: "previous",
+ label: previousWindow ? `${percentile}, ${previousWindow}` : t("{percentile}, previous period", { percentile }),
+ color: PREVIOUS_COLOR,
+ dashed: true,
+ });
+ }
+
+ const hoverLeft =
+ hoveredPin && typeof window !== "undefined" ? Math.min(hoveredPin.rect.right + 8, window.innerWidth - 272) : 0;
return (
<Card className="overflow-visible">
{isFetching && <CardLoader />}
- <CardContent className="p-2 md:p-4 py-3 w-full">
- <div className="flex items-center justify-between px-2 md:px-0">
- <div className="flex items-center space-x-4">
- {!isWhiteLabel && (
- <Link href={session.data ? "/" : "https://rybbit.com"} className="opacity-75">
- <RybbitTextLogo width={80} />
- </Link>
- )}
- </div>
- <div className="flex items-center space-x-4">
- <span className="text-sm text-neutral-600 dark:text-neutral-200">
- {METRIC_LABELS[selectedPerformanceMetric]}
- </span>
- <div className="flex items-center space-x-2">
- {PERCENTILES.map(percentile => (
- <ToggleChip
- key={percentile}
- isSelected={visiblePercentiles.has(percentile)}
- onClick={() => togglePercentile(percentile)}
- swatchColor={percentileColors[percentile]}
- label={percentile}
- />
- ))}
- </div>
- </div>
- <BucketSelection />
+ <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2 p-4 pb-2">
+ <div className="min-w-0">
+ <div className="font-semibold leading-none tracking-tight">{metricNames[metric]}</div>
+ <p className="mt-1.5 text-sm text-neutral-500 dark:text-neutral-400">
+ {t("{percentile} {interval}. Good up to {good}, poor over {poor}.", {
+ percentile,
+ interval,
+ good: formatMetric(metric, thresholds.good),
+ poor: formatMetric(metric, thresholds.needs_improvement),
+ })}{" "}
+ {t("Select a metric in the band above.")}
+ </p>
</div>
+ {line.length > 0 && <ChartLegend items={legend} className="pt-0.5" />}
+ </div>
+
+ <div className="px-2 pb-3 md:px-4">
{isLoading ? (
- <div className="space-y-3">
- <Skeleton className="w-full h-[300px] rounded-md" />
- </div>
- ) : chartSeries.length === 0 ? (
- <div className="h-[300px] w-full flex items-center justify-center">
- <div className="text-center text-neutral-500">
- <p className="text-lg font-medium">{t("No performance data available")}</p>
+ <Skeleton className="h-[300px] w-full rounded-md" />
+ ) : line.length === 0 ? (
+ <div className="flex h-[300px] w-full items-center justify-center">
+ <div className="text-center text-neutral-500 dark:text-neutral-400">
+ <p className="text-base font-medium">{t("No performance data available")}</p>
<p className="text-sm">{t("Try adjusting your date range or filters")}</p>
</div>
</div>
) : (
- <div className="h-[300px] w-full">
- <TimeSeriesChart
- current={current}
- series={chartSeries}
- markers={thresholdMarkers}
- max={max}
- chartMin={chartMin}
- chartMax={chartMax}
- currentColor={chartSeries[0]?.color}
- yTickFormat={value => formatMetricValue(selectedPerformanceMetric, value)}
- renderTooltip={({ point, points, bucket }) => (
- <ChartTooltip>
- <div className="p-3 min-w-[150px]">
- <div className="mb-2">{formatChartDateTime(point.currentTime, bucket)}</div>
- <div className="space-y-2">
- {points.map(({ id, color, point }) => (
- <div key={id} className="flex justify-between items-center">
- <div className="flex items-center gap-2">
- <div className="w-1 h-3 rounded-[3px]" style={{ backgroundColor: color }} />
- <span>{id}</span>
- </div>
- <span>
- <span className="font-medium">{formatMetricValue(selectedPerformanceMetric, point.y)}</span>
- <span className="text-muted-foreground">
- {getMetricUnit(selectedPerformanceMetric, point.y)}
- </span>
+ // The padding holds what the overlay draws outside the plot: the loads
+ // strip below it and, from `md`, the zone labels beside it.
+ <div className="pb-11 md:pr-28 [&_svg]:overflow-visible">
+ <div className="h-[260px] w-full">
+ <TimeSeriesChart
+ current={[]}
+ series={[{ id: percentile, data: line, color: DATA_COLOR, strokeWidth: 2 }]}
+ max={max}
+ chartMin={chartMin}
+ chartMax={chartMax}
+ yTickFormat={value => (value === 0 ? "0" : formatMetric(metric, value / scale))}
+ renderOverlay={context => (
+ <>
+ <VitalsOverlay
+ context={context}
+ metric={metric}
+ line={line}
+ range={range}
+ previous={previous}
+ bars={bars}
+ bucket={bucket}
+ ratingLabels={ratingLabels}
+ loadsLabel={t("Loads measured")}
+ />
+ {annotations.length > 0 && (
+ <AnnotationPins
+ context={context}
+ annotations={annotations}
+ bucket={bucket}
+ selectedKey={selectedPin?.cluster.key ?? null}
+ onSelect={(cluster, rect) => {
+ setHoveredPin(null);
+ setSelectedPin({ cluster, rect });
+ }}
+ onHover={(cluster, rect) => setHoveredPin(cluster && rect ? { cluster, rect } : null)}
+ />
+ )}
+ </>
+ )}
+ renderTooltip={({ point, bucket }) => {
+ const previousPoint = previousByTime.get(point.x.getTime());
+ return (
+ <ChartTooltip>
+ <div className="p-3 text-xs">
+ <div className="flex items-center justify-between gap-3">
+ <span className="font-medium">{formatChartDateTime(point.time, bucket)}</span>
+ <span className="tabular-nums text-neutral-500 dark:text-neutral-400">
+ {t("{count} loads", { count: point.loads.toLocaleString() })}
</span>
</div>
- ))}
- </div>
- </div>
- </ChartTooltip>
- )}
- />
+ <div className="mt-2 space-y-1.5">
+ {TOOLTIP_PERCENTILES.map(level => {
+ const value = point.percentiles[level];
+ const selected = level === percentile;
+ const inRange = level === "p50" || level === "p90";
+ return (
+ <div key={level} className="flex items-center justify-between gap-4">
+ <span className="flex items-center gap-2 text-neutral-600 dark:text-neutral-300">
+ <span
+ className="h-2 w-2 shrink-0 rounded-full"
+ style={{
+ background: selected ? DATA_COLOR : inRange ? RANGE_COLOR : "transparent",
+ }}
+ />
+ {level}
+ </span>
+ <span
+ className={cn(
+ "inline-flex items-center gap-1.5 tabular-nums",
+ selected
+ ? "font-medium text-neutral-900 dark:text-neutral-50"
+ : "text-neutral-700 dark:text-neutral-200"
+ )}
+ >
+ {selected && isMeasured(value) && (
+ <RatingMark
+ rating={getMetricRating(metric, value)}
+ label={ratingLabels[getMetricRating(metric, value)]}
+ />
+ )}
+ {isMeasured(value) ? formatMetric(metric, value) : "—"}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ {previousPoint && (
+ <div className="mt-2 flex items-center justify-between gap-4 border-t border-neutral-100 pt-2 dark:border-neutral-750">
+ <span className="flex min-w-0 items-center gap-2 text-neutral-600 dark:text-neutral-300">
+ <span
+ className="w-2.5 shrink-0 border-t border-dashed"
+ style={{ borderColor: PREVIOUS_COLOR }}
+ />
+ <span className="truncate">
+ {percentile}, {formatChartDateTime(previousPoint.originalTime, bucket)}
+ </span>
+ </span>
+ <span className="inline-flex shrink-0 items-center gap-1.5 tabular-nums text-neutral-700 dark:text-neutral-200">
+ <RatingMark
+ rating={getMetricRating(metric, previousPoint.value)}
+ label={ratingLabels[getMetricRating(metric, previousPoint.value)]}
+ />
+ {formatMetric(metric, previousPoint.value)}
+ </span>
+ </div>
+ )}
+ </div>
+ </ChartTooltip>
+ );
+ }}
+ />
+ </div>
</div>
)}
- </CardContent>
+ {!isLoading && line.length > 0 && (
+ <p className="px-2 text-xs text-neutral-500 dark:text-neutral-400 md:hidden">
+ {t("The bars under the chart are the loads measured {interval}.", { interval })}
+ </p>
+ )}
+ </div>
+
+ {hoveredPin &&
+ !selectedPin &&
+ typeof document !== "undefined" &&
+ createPortal(
+ <div
+ style={{
+ position: "fixed",
+ left: hoverLeft,
+ top: Math.max(8, hoveredPin.rect.top - 6),
+ pointerEvents: "none",
+ zIndex: 9999,
+ }}
+ >
+ <AnnotationHoverCard cluster={hoveredPin.cluster} />
+ </div>,
+ document.body
+ )}
+
+ {selectedPin && (
+ <Popover open onOpenChange={open => !open && setSelectedPin(null)}>
+ <PopoverAnchor virtualRef={{ current: { getBoundingClientRect: () => selectedPin.rect } }} />
+ <PopoverContent side="top" align="start" className="w-80 p-0">
+ {/* Read-only here: annotations are written and edited on the Main chart. */}
+ <AnnotationPopoverContent
+ cluster={selectedPin.cluster}
+ canManage={() => false}
+ onEdit={() => {}}
+ onDelete={() => {}}
+ />
+ </PopoverContent>
+ </Popover>
+ )}
</Card>
);
}
diff --git a/client/src/app/[site]/performance/components/PerformanceInsight.tsx b/client/src/app/[site]/performance/components/PerformanceInsight.tsx
new file mode 100644
index 000000000..89b8b24ad
--- /dev/null
+++ b/client/src/app/[site]/performance/components/PerformanceInsight.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import { ArrowRight } from "lucide-react";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { InsightRow } from "@/components/site/InsightRow";
+import { Button } from "@/components/ui/button";
+import { usePivotHref } from "@/hooks/usePivotHref";
+import { usePerformanceStore } from "../performanceStore";
+import { findOnlyPoorRow, formatMetric, getRatingSplit, METRIC_LABELS_SHORT } from "../utils/performanceUtils";
+import { usePerformanceRows } from "../utils/usePerformanceRows";
+
+// A p75 over a handful of loads says little about a page.
+const MIN_LOADS = 20;
+
+/**
+ * One sentence, only when it is plainly true of the numbers on the page:
+ * among the pages with the most loads, exactly one is rated poor on the
+ * selected metric at p75, the percentile Core Web Vitals are assessed at.
+ * Nothing is inferred; with no such page, or several, the row is not drawn.
+ *
+ * It reads the same request as the Pages tab in its default state, so it adds
+ * no query of its own.
+ */
+export function PerformanceInsight() {
+ const t = useExtracted();
+ const pivotHref = usePivotHref();
+ const metric = usePerformanceStore(state => state.selectedPerformanceMetric);
+ const { rows, previousByValue } = usePerformanceRows({ dimension: "pathname" });
+
+ const busiest = rows.filter(row => (getRatingSplit(row, metric)?.count ?? 0) >= MIN_LOADS);
+ const poor = findOnlyPoorRow(busiest, metric, row => row[`${metric}_p75`]);
+ const current = poor?.[`${metric}_p75`];
+ if (!poor || typeof current !== "number") return null;
+
+ const page = String(poor.pathname);
+ const previous = previousByValue.get(page)?.[`${metric}_p75`];
+ const values = { metric: METRIC_LABELS_SHORT[metric], page, current: formatMetric(metric, current) };
+
+ return (
+ <InsightRow
+ action={
+ <Button asChild variant="ghost" size="xs" className="shrink-0 gap-1">
+ <Link href={pivotHref("sessions", [{ parameter: "pathname", type: "equals", value: [page] }])}>
+ {t("View sessions")}
+ <ArrowRight />
+ </Link>
+ </Button>
+ }
+ >
+ {typeof previous === "number" && formatMetric(metric, previous) !== values.current
+ ? t("{metric} on {page} went from {previous} to {current} at p75.", {
+ ...values,
+ previous: formatMetric(metric, previous),
+ })
+ : t("{metric} on {page} is {current} at p75.", values)}{" "}
+ {t("It is the only one of the {count} pages with the most loads rated poor.", {
+ count: String(busiest.length),
+ })}
+ </InsightRow>
+ );
+}
diff --git a/client/src/app/[site]/performance/components/PerformanceOverview.tsx b/client/src/app/[site]/performance/components/PerformanceOverview.tsx
index 09f3e534d..78e0843c0 100644
--- a/client/src/app/[site]/performance/components/PerformanceOverview.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceOverview.tsx
@@ -1,165 +1,188 @@
"use client";
+import { Gauge, Image as ImageIcon, LucideIcon, Move, Paintbrush, Pointer, Server } from "lucide-react";
import { useExtracted } from "next-intl";
+import { ReactNode } from "react";
+import { Delta } from "@/components/site/Delta";
import { Skeleton } from "@/components/ui/skeleton";
+import { DeltaValue, percentDelta } from "@/lib/delta";
import { cn } from "@/lib/utils";
-import NumberFlow from "@number-flow/react";
-import { TrendingDown, TrendingUp } from "lucide-react";
import { useGetPerformanceOverview } from "../../../../api/analytics/hooks/performance/useGetPerformanceOverview";
-import { Card, CardContent, CardLoader } from "../../../../components/ui/card";
+import { useGetOverview } from "../../../../api/analytics/hooks/useGetOverview";
import { useComparisonEnabled, useStore } from "../../../../lib/store";
import { PerformanceMetric, usePerformanceStore } from "../performanceStore";
-import { formatMetricValue, getMetricColor, getMetricUnit } from "../utils/performanceUtils";
-import { PercentileSelector } from "./PercentileSelector";
+import {
+ formatMetric,
+ formatShare,
+ getMetricRating,
+ getRatingSplit,
+ METRIC_LABELS_SHORT,
+ PERFORMANCE_METRICS,
+ RATING_TEXT_CLASS,
+} from "../utils/performanceUtils";
import { MetricTooltip } from "./shared/MetricTooltip";
-
-const ChangePercentage = ({ current, previous }: { current: number; previous: number }) => {
- const comparisonEnabled = useComparisonEnabled();
- if (!comparisonEnabled) return null;
-
- const change = ((current - previous) / previous) * 100;
-
- if (previous === 0) {
- if (current === 0) {
- return <div className="text-sm">0%</div>;
- }
- return <div className="text-sm">+999%</div>;
- }
-
- if (change === 0) {
- return <div className="text-sm">0%</div>;
- }
-
- // For performance metrics, lower is better, so we reverse the color logic
- return (
- <div className={cn("text-xs flex items-center gap-1", change < 0 ? "text-green-400" : "text-red-400")}>
- {change > 0 ? <TrendingUp className="w-4 h-4" /> : <TrendingDown className="w-4 h-4" />}
- {Math.abs(change).toFixed(1)}%
- </div>
- );
+import { RatingMark, useRatingLabels } from "./shared/RatingMark";
+
+const METRIC_ICONS: Record<PerformanceMetric, LucideIcon> = {
+ lcp: ImageIcon,
+ inp: Pointer,
+ cls: Move,
+ fcp: Paintbrush,
+ ttfb: Server,
};
-const Stat = ({
- title,
- id,
- value,
- previous,
+// The band clips its corners, which would cut the selection ring of a cell
+// sitting in one. Each metric cell rounds the corners it occupies at each
+// width: two columns, three from `sm`, one row of six from `lg`.
+const CORNERS = [
+ "rounded-tl-lg lg:rounded-l-lg",
+ "rounded-tr-lg sm:rounded-none",
+ "sm:rounded-tr-lg lg:rounded-none",
+ "sm:rounded-bl-lg lg:rounded-none",
+ "rounded-bl-lg sm:rounded-none",
+];
+
+const CELL = "min-w-0 bg-white px-3.5 py-2.5 text-left dark:bg-neutral-900";
+const LABEL =
+ "flex min-w-0 items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-neutral-500 dark:text-neutral-400";
+
+// The same three lines as the shared StatBand cell, so the band keeps its height while loading.
+function CellBody({
isLoading,
+ value,
+ delta,
+ upIsGood,
+ sub,
}: {
- title: string;
- id: PerformanceMetric;
- value: number;
- previous: number;
isLoading: boolean;
-}) => {
- const { selectedPerformanceMetric, setSelectedPerformanceMetric, selectedPercentile } = usePerformanceStore();
-
- return (
- <div
- className={cn(
- "flex flex-col cursor-pointer border-r border-neutral-100 dark:border-neutral-800 last:border-r-0 text-nowrap",
- selectedPerformanceMetric === id && "bg-neutral-0 dark:bg-neutral-850"
- )}
- onClick={() => setSelectedPerformanceMetric(id)}
- >
- <div className="flex flex-col px-3 py-2">
- <div className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
- {title}
- <MetricTooltip metric={id} />
+ value: ReactNode;
+ delta: DeltaValue | null;
+ upIsGood: boolean;
+ sub: ReactNode;
+}) {
+ if (isLoading) {
+ return (
+ <>
+ <div className="mt-0.5 flex h-6 items-center">
+ <Skeleton className="h-4 w-16 rounded" />
</div>
- <div className="text-2xl font-medium flex gap-2 items-center justify-between">
- {isLoading ? (
- <>
- <Skeleton className="w-[60px] h-9 rounded-md" />
- <Skeleton className="w-[50px] h-5 rounded-md" />
- </>
- ) : (
- <>
- <span className={getMetricColor(id, value)}>
- <NumberFlow value={Number(formatMetricValue(id, value))} format={{ notation: "compact" }} />
- <span className="text-sm ml-1">{getMetricUnit(id, value)}</span>
- </span>
- <ChangePercentage current={value} previous={previous} />
- </>
- )}
+ <div className="mt-0.5 flex h-4 items-center">
+ <Skeleton className="h-3 w-24 rounded" />
</div>
+ </>
+ );
+ }
+
+ return (
+ <>
+ <div className="mt-0.5 flex items-baseline gap-2">
+ <span className="truncate text-base font-semibold tabular-nums text-neutral-900 dark:text-neutral-50">
+ {value}
+ </span>
+ <Delta value={delta} upIsGood={upIsGood} />
</div>
- </div>
+ <div className="mt-0.5 h-4 truncate text-xs tabular-nums text-neutral-500 dark:text-neutral-400">{sub}</div>
+ </>
);
-};
+}
+/**
+ * The page's stat band: the five Web Vitals at the chosen percentile, each
+ * rated and compared with the previous period, then how many page loads they
+ * rest on. A metric cell selects what the chart and the table's share and
+ * change columns show.
+ *
+ * Drawn here rather than with the shared StatBand, whose cells cannot be
+ * selected and have no place for a rating; the markup follows it.
+ */
export function PerformanceOverview() {
const t = useExtracted();
- const { site } = useStore();
- const { selectedPercentile } = usePerformanceStore();
-
- const { data: overviewData, isLoading: isOverviewLoading, isFetching } = useGetPerformanceOverview({ site });
-
- const { data: overviewDataPrevious, isLoading: isOverviewLoadingPrevious } = useGetPerformanceOverview({
- site,
- periodTime: "previous",
- });
-
- const isLoading = isOverviewLoading || isOverviewLoadingPrevious;
+ const site = useStore(state => state.site);
+ const comparisonEnabled = useComparisonEnabled();
+ const ratingLabels = useRatingLabels();
+ const { selectedPercentile, selectedPerformanceMetric, setSelectedPerformanceMetric } = usePerformanceStore();
- const currentData = overviewData ?? {};
- const previousData = overviewDataPrevious ?? {};
+ const { data: current, isLoading } = useGetPerformanceOverview({ site });
+ const { data: previousData } = useGetPerformanceOverview({ site, periodTime: "previous" });
+ const { data: siteOverview } = useGetOverview({ site });
+ // A query that is switched off keeps its last result as a placeholder.
+ const previous = comparisonEnabled ? previousData : undefined;
- // Helper function to get metric value for selected percentile
- const getMetricValue = (data: any, metric: PerformanceMetric): number => {
- const key = `${metric}_${selectedPercentile}`;
- return data[key] ?? 0;
- };
+ const loads = current?.total_performance_events ?? 0;
+ const pageviews = siteOverview?.pageviews ?? 0;
return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <h2 className="text-lg font-semibold">{t("Web Vitals")}</h2>
- <PercentileSelector />
- </div>
-
- <Card>
- <CardContent className="p-0 w-full">
- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-0 items-center 0 rounded-lg overflow-hidden">
- <Stat
- title={t("Largest Contentful Paint")}
- id="lcp"
- value={getMetricValue(currentData, "lcp")}
- previous={getMetricValue(previousData, "lcp")}
- isLoading={isLoading}
- />
- <Stat
- title={t("Cumulative Layout Shift")}
- id="cls"
- value={getMetricValue(currentData, "cls")}
- previous={getMetricValue(previousData, "cls")}
- isLoading={isLoading}
- />
- <Stat
- title={t("Interaction to Next Paint")}
- id="inp"
- value={getMetricValue(currentData, "inp")}
- previous={getMetricValue(previousData, "inp")}
- isLoading={isLoading}
- />
- <Stat
- title={t("First Contentful Paint")}
- id="fcp"
- value={getMetricValue(currentData, "fcp")}
- previous={getMetricValue(previousData, "fcp")}
- isLoading={isLoading}
- />
- <Stat
- title={t("Time to First Byte")}
- id="ttfb"
- value={getMetricValue(currentData, "ttfb")}
- previous={getMetricValue(previousData, "ttfb")}
- isLoading={isLoading}
- />
+ <div className="overflow-hidden rounded-lg border border-neutral-100 dark:border-neutral-850">
+ <div className="grid grid-cols-2 gap-px bg-neutral-100 dark:bg-neutral-850 sm:grid-cols-3 lg:grid-cols-6">
+ {PERFORMANCE_METRICS.map((metric, index) => {
+ const Icon = METRIC_ICONS[metric];
+ const value = current?.[`${metric}_${selectedPercentile}`] ?? null;
+ const rating = value === null ? null : getMetricRating(metric, value);
+ const split = getRatingSplit(current, metric);
+ const selected = selectedPerformanceMetric === metric;
+
+ return (
+ <button
+ key={metric}
+ type="button"
+ aria-pressed={selected}
+ onClick={() => setSelectedPerformanceMetric(metric)}
+ className={cn(
+ CELL,
+ CORNERS[index],
+ "relative transition-colors hover:bg-neutral-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-neutral-400 dark:hover:bg-neutral-850 dark:focus-visible:ring-neutral-500",
+ selected &&
+ "z-10 ring-2 ring-inset ring-neutral-900 hover:bg-white dark:ring-neutral-50 dark:hover:bg-neutral-900"
+ )}
+ >
+ <div className="flex items-center justify-between gap-1.5">
+ <div className={cn(LABEL, "shrink-0")}>
+ <Icon className="h-3 w-3 shrink-0" />
+ <MetricTooltip metric={metric}>
+ <span className="truncate">{METRIC_LABELS_SHORT[metric]}</span>
+ </MetricTooltip>
+ </div>
+ {rating && !isLoading && (
+ <span
+ className={cn(
+ "inline-flex min-w-0 items-center gap-1 text-[11px] font-medium",
+ RATING_TEXT_CLASS[rating]
+ )}
+ title={ratingLabels[rating]}
+ >
+ <RatingMark rating={rating} className="h-1.5 w-1.5" />
+ <span className="truncate">{ratingLabels[rating]}</span>
+ </span>
+ )}
+ </div>
+ <CellBody
+ isLoading={isLoading}
+ value={value === null ? "—" : formatMetric(metric, value)}
+ delta={percentDelta(value, previous?.[`${metric}_${selectedPercentile}`])}
+ upIsGood={false}
+ sub={split ? t("{share} of loads good", { share: formatShare(split.goodShare) }) : ""}
+ />
+ </button>
+ );
+ })}
+ <div className={CELL}>
+ <div className={LABEL}>
+ <Gauge className="h-3 w-3 shrink-0" />
+ <span className="truncate">{t("Loads measured")}</span>
</div>
- </CardContent>
- {isFetching && <CardLoader />}
- </Card>
+ <CellBody
+ isLoading={isLoading}
+ value={loads.toLocaleString()}
+ delta={loads > 0 ? percentDelta(loads, previous?.total_performance_events) : null}
+ upIsGood
+ sub={
+ loads > 0 && pageviews > 0
+ ? t("{share} of pageviews", { share: formatShare((loads / pageviews) * 100) })
+ : ""
+ }
+ />
+ </div>
+ </div>
</div>
);
}
diff --git a/client/src/app/[site]/performance/components/PerformanceTable.tsx b/client/src/app/[site]/performance/components/PerformanceTable.tsx
index 87ccad2b2..e99c03eb7 100644
--- a/client/src/app/[site]/performance/components/PerformanceTable.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceTable.tsx
@@ -1,429 +1,500 @@
"use client";
+import { ArrowDown, ArrowUp, ChevronLeft, ChevronRight, SquareArrowOutUpRight } from "lucide-react";
import { useExtracted } from "next-intl";
+import { ReactNode, useState } from "react";
+import { Delta } from "@/components/site/Delta";
+import { PivotActions } from "@/components/site/PivotActions";
+import { Button } from "@/components/ui/button";
+import { CardLoader } from "@/components/ui/card";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Skeleton } from "@/components/ui/skeleton";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
- TableSortIndicator,
-} from "@/components/ui/table";
-import { FilterParameter } from "@rybbit/shared";
-import {
- createColumnHelper,
- flexRender,
- getCoreRowModel,
- getSortedRowModel,
- SortingState,
- useReactTable,
-} from "@tanstack/react-table";
-import { SquareArrowOutUpRight } from "lucide-react";
-import { useCallback, useMemo, useState } from "react";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { percentDelta } from "@/lib/delta";
+import { cn } from "@/lib/utils";
import { useGetSite } from "../../../../api/admin/hooks/useSites";
import { PerformanceByDimensionItem } from "../../../../api/analytics/endpoints";
-import { useGetPerformanceByDimension } from "../../../../api/analytics/hooks/performance/useGetPerformanceByDimension";
-import { Pagination } from "../../../../components/pagination";
-import { CardLoader } from "../../../../components/ui/card";
+import { useSubdivisions } from "../../../../lib/geo";
import { addFilter, removeFilter, useStore } from "../../../../lib/store";
import { getCountryName } from "../../../../lib/utils";
import { Browser } from "../../components/shared/icons/Browser";
import { CountryFlag } from "../../components/shared/icons/CountryFlag";
import { DeviceIcon } from "../../components/shared/icons/Device";
import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";
-import { PerformanceMetric, usePerformanceStore } from "../performanceStore";
-import { formatMetricValue, getMetricColor, getMetricUnit } from "../utils/performanceUtils";
+import { PercentileLevel, PerformanceMetric, usePerformanceStore } from "../performanceStore";
+import {
+ formatMetric,
+ formatShare,
+ getMetricRating,
+ getPerformanceThresholds,
+ getRatingSplit,
+ METRIC_LABELS_SHORT,
+ METRIC_RATINGS,
+ MetricRating,
+ PASSING_GOOD_SHARE,
+ PERFORMANCE_METRICS,
+ RATING_TEXT_CLASS,
+} from "../utils/performanceUtils";
+import {
+ DEFAULT_PERFORMANCE_SORT,
+ PERFORMANCE_PAGE_SIZE,
+ PerformanceDimension,
+ PerformanceSort,
+ usePerformanceRows,
+} from "../utils/usePerformanceRows";
import { MetricTooltip } from "./shared/MetricTooltip";
+import { RatingMark, useRatingLabels } from "./shared/RatingMark";
+
+const isMeasured = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value);
+
+const HEAD_BUTTON =
+ "inline-flex items-center gap-1 rounded-sm hover:text-neutral-900 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400 dark:hover:text-neutral-100";
+
+type SortColumn = PerformanceMetric | "loads";
+
+function SortHeader({
+ active,
+ desc,
+ onSort,
+ children,
+ className,
+}: {
+ active: boolean;
+ desc: boolean;
+ onSort: () => void;
+ children: ReactNode;
+ className?: string;
+}) {
+ const Arrow = desc ? ArrowDown : ArrowUp;
+ return (
+ <TableHead
+ aria-sort={active ? (desc ? "descending" : "ascending") : undefined}
+ className={cn("text-right", active && "text-neutral-900 dark:text-neutral-100", className)}
+ >
+ <button type="button" className={HEAD_BUTTON} onClick={onSort}>
+ {children}
+ {active && <Arrow className="h-3 w-3" aria-hidden="true" />}
+ </button>
+ </TableHead>
+ );
+}
-const MetricCell = ({
+/** How one row's loads split across the three ratings, and the way from that row to the people behind it. */
+function MetricPopover({
metric,
- value,
percentile,
+ dimension,
+ value,
+ name,
+ row,
+ current,
+ previous,
}: {
metric: PerformanceMetric;
- value: number | null | undefined;
- percentile: string;
-}) => {
- if (value === null || value === undefined) {
- return <span className="text-neutral-500">-</span>;
- }
+ percentile: PercentileLevel;
+ dimension: PerformanceDimension;
+ /** The row's raw dimension value, as the filter takes it. */
+ value: string;
+ /** The row as the table prints it: a path, a country name. */
+ name: string;
+ row: PerformanceByDimensionItem;
+ current: number;
+ previous: number | null | undefined;
+}) {
+ const t = useExtracted();
+ const ratingLabels = useRatingLabels();
+ const thresholds = getPerformanceThresholds(metric);
+ const rating = getMetricRating(metric, current);
+ const split = getRatingSplit(row, metric);
+ const good = formatMetric(metric, thresholds.good);
+ const poor = formatMetric(metric, thresholds.needs_improvement);
+ const ranges: Record<MetricRating, string> = {
+ good: t("up to {limit}", { limit: good }),
+ needs_improvement: t("{from} to {to}", { from: good, to: poor }),
+ poor: t("over {limit}", { limit: poor }),
+ };
+ const loads = (split?.count ?? row.event_count).toLocaleString();
+ const now = formatMetric(metric, current);
return (
- <span className={getMetricColor(metric, value)}>
- {formatMetricValue(metric, value)}
- <span className="text-xs ml-1 text-neutral-400">{getMetricUnit(metric, value)}</span>
- </span>
+ <>
+ <div className="flex items-start justify-between gap-3 px-3 pb-2 pt-2.5">
+ <div className="min-w-0">
+ <div className="truncate text-sm font-medium" title={name}>
+ {t("{metric} on {name}", { metric: METRIC_LABELS_SHORT[metric], name })}
+ </div>
+ <div className="mt-0.5 text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
+ {isMeasured(previous)
+ ? t("{loads} loads · {percentile} {value} · was {previous}", {
+ loads,
+ percentile,
+ value: now,
+ previous: formatMetric(metric, previous),
+ })
+ : t("{loads} loads · {percentile} {value}", { loads, percentile, value: now })}
+ </div>
+ </div>
+ <span
+ className={cn(
+ "inline-flex shrink-0 items-center gap-1 pt-0.5 text-xs font-medium",
+ RATING_TEXT_CLASS[rating]
+ )}
+ >
+ <RatingMark rating={rating} />
+ {ratingLabels[rating]}
+ </span>
+ </div>
+ {split && (
+ <div className="border-t border-neutral-100 px-1 py-1.5 dark:border-neutral-700">
+ {METRIC_RATINGS.map(key => (
+ <div
+ key={key}
+ className={cn(
+ "flex h-7 items-center gap-2 rounded-md px-2 text-xs",
+ key === rating && "bg-neutral-100 dark:bg-neutral-700"
+ )}
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-1.5">
+ <RatingMark rating={key} />
+ <span className="truncate text-neutral-800 dark:text-neutral-100">{ratingLabels[key]}</span>
+ </span>
+ <span className="w-24 shrink-0 whitespace-nowrap text-neutral-500 dark:text-neutral-400">
+ {ranges[key]}
+ </span>
+ <span className="w-12 shrink-0 text-right tabular-nums text-neutral-700 dark:text-neutral-200">
+ {split[key].toLocaleString()}
+ </span>
+ <span className="w-12 shrink-0 text-right font-medium tabular-nums text-neutral-900 dark:text-neutral-50">
+ {formatShare((split[key] / split.count) * 100)}
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+ <div className="border-t border-neutral-100 px-1.5 py-1.5 dark:border-neutral-700">
+ <PivotActions
+ filters={[{ parameter: dimension, type: "equals", value: [value] }]}
+ actions={["sessions", "replays", "segment"]}
+ />
+ </div>
+ </>
);
-};
-
-const columnHelper = createColumnHelper<PerformanceByDimensionItem>();
-
-interface PerformanceTableProps {
- dimension: string;
- title: string;
}
-// Custom hook for filter handling logic
-const useFilterToggle = () => {
- const filters = useStore(state => state.filters);
+function MetricCell(props: {
+ metric: PerformanceMetric;
+ percentile: PercentileLevel;
+ dimension: PerformanceDimension;
+ value: string;
+ name: string;
+ row: PerformanceByDimensionItem;
+ previousRow: PerformanceByDimensionItem | undefined;
+}) {
+ const { metric, percentile, row, previousRow } = props;
+ const ratingLabels = useRatingLabels();
+ const current = row[`${metric}_${percentile}`];
+ if (!isMeasured(current)) return <span className="text-neutral-400 dark:text-neutral-500">—</span>;
- const toggleFilter = useCallback(
- (parameter: FilterParameter, value: string) => {
- const foundFilter = filters.find(f => f.parameter === parameter && f.value.some(v => v === value));
- if (foundFilter) {
- removeFilter(foundFilter);
- } else {
- addFilter({
- parameter,
- value: [value],
- type: "equals",
- });
- }
- },
- [filters]
+ const rating = getMetricRating(metric, current);
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className={cn(
+ "-mr-1.5 inline-flex items-center gap-1.5 whitespace-nowrap rounded px-1.5 py-1 tabular-nums hover:bg-neutral-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400 data-[state=open]:ring-2 data-[state=open]:ring-neutral-900 dark:hover:bg-neutral-800 dark:data-[state=open]:ring-neutral-50",
+ rating === "good" ? "text-neutral-800 dark:text-neutral-200" : cn("font-medium", RATING_TEXT_CLASS[rating])
+ )}
+ >
+ <RatingMark rating={rating} label={ratingLabels[rating]} />
+ {formatMetric(metric, current)}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-[372px] max-w-[calc(100vw-2rem)] p-0">
+ <MetricPopover {...props} current={current} previous={previousRow?.[`${metric}_${percentile}`]} />
+ </PopoverContent>
+ </Popover>
);
+}
- return toggleFilter;
-};
+/** Share of good loads as a bar, with a tick at the 75% a metric needs to pass. */
+function GoodShare({ share }: { share: number | null }) {
+ if (share === null) return <span className="text-neutral-400 dark:text-neutral-500">—</span>;
+ return (
+ <div className="flex items-center gap-2">
+ <div className="relative h-1.5 min-w-0 flex-1 rounded-full bg-neutral-100 dark:bg-neutral-800">
+ <div className="h-full rounded-full bg-dataviz" style={{ width: `${share}%` }} />
+ <div
+ className="absolute -top-1 h-3.5 w-px bg-neutral-400 dark:bg-neutral-300"
+ style={{ left: `${PASSING_GOOD_SHARE}%` }}
+ />
+ </div>
+ <span
+ className={cn(
+ "w-11 shrink-0 text-right tabular-nums",
+ share < PASSING_GOOD_SHARE
+ ? "font-medium text-neutral-900 dark:text-neutral-50"
+ : "text-neutral-700 dark:text-neutral-200"
+ )}
+ >
+ {formatShare(share)}
+ </span>
+ </div>
+ );
+}
-export function PerformanceTable({ dimension, title }: PerformanceTableProps) {
+export function PerformanceTable({ dimension }: { dimension: PerformanceDimension }) {
const t = useExtracted();
- const { site } = useStore();
+ const filters = useStore(state => state.filters);
const { data: siteMetadata } = useGetSite();
- const { selectedPercentile } = usePerformanceStore();
- const toggleFilter = useFilterToggle();
- const [pagination, setPagination] = useState({
- pageIndex: 0,
- pageSize: 25,
- });
+ const { data: subdivisions } = useSubdivisions();
+ const { selectedPercentile: percentile, selectedPerformanceMetric: selectedMetric } = usePerformanceStore();
+ const ratingLabels = useRatingLabels();
+ const [pageIndex, setPageIndex] = useState(0);
+ const [sortColumn, setSortColumn] = useState<SortColumn>("loads");
+ const [sortDesc, setSortDesc] = useState(true);
- const [sorting, setSorting] = useState<SortingState>([{ id: "event_count", desc: true }]);
+ // Sorted on the server. A metric column sorts by the percentile on screen.
+ const sortId = (column: SortColumn) => (column === "loads" ? DEFAULT_PERFORMANCE_SORT.by : `${column}_${percentile}`);
+ const sort: PerformanceSort = { by: sortId(sortColumn), desc: sortDesc };
+ const onSort = (column: SortColumn) => {
+ setSortDesc(column === sortColumn ? !sortDesc : true);
+ setSortColumn(column);
+ setPageIndex(0);
+ };
- const {
- data: performanceData,
- isLoading,
- isFetching,
- } = useGetPerformanceByDimension({
- site,
+ const { rows, totalCount, previousByValue, hasPrevious, isLoading, isFetching } = usePerformanceRows({
dimension,
- page: pagination.pageIndex + 1, // API expects 1-based page numbers
- limit: pagination.pageSize,
- sortBy: sorting[0]?.id || "event_count",
- sortOrder: sorting[0]?.desc ? "desc" : "asc",
+ page: pageIndex + 1,
+ sort,
});
+ const totalPages = Math.ceil(totalCount / PERFORMANCE_PAGE_SIZE);
+ // A filter or a shorter period can leave fewer pages than the one on screen.
+ if (!isFetching && totalPages > 0 && pageIndex > totalPages - 1) setPageIndex(totalPages - 1);
- const paths = performanceData?.data ?? [];
- const totalCount = performanceData?.totalCount ?? 0;
- const totalPages = Math.ceil(totalCount / pagination.pageSize);
-
- // Create columns based on selected percentile and dimension
- const columns = useMemo(
- () => [
- columnHelper.accessor(dimension, {
- header:
- dimension === "pathname"
- ? t("Path")
- : dimension === "country"
- ? t("Country")
- : dimension === "device_type"
- ? t("Device Type")
- : dimension === "browser"
- ? t("Browser")
- : dimension === "operating_system"
- ? t("Operating System")
- : dimension.charAt(0).toUpperCase() + dimension.slice(1),
- cell: info => {
- const value = info.getValue();
- const displayValue = value || (dimension === "pathname" ? "/" : t("Unknown"));
-
- const handleClick = () => {
- if (value) {
- toggleFilter(dimension as FilterParameter, value);
- }
- };
+ const toggleFilter = (value: string) => {
+ const existing = filters.find(filter => filter.parameter === dimension && filter.value.some(v => v === value));
+ if (existing) removeFilter(existing);
+ else addFilter({ parameter: dimension, value: [value], type: "equals" });
+ };
- return (
- <div
- className="text-neutral-900 dark:text-white max-w-[300px] truncate flex items-center gap-2 cursor-pointer hover:underline"
- onClick={handleClick}
- >
- {dimension === "country" && value ? (
- <>
- <CountryFlag country={value} />
- {getCountryName(value) || value}
- </>
- ) : dimension === "device_type" ? (
- <>
- <DeviceIcon deviceType={value || ""} />
- {value || t("Other")}
- </>
- ) : dimension === "browser" && value ? (
- <>
- <Browser browser={value} />
- {value || t("Other")}
- </>
- ) : dimension === "operating_system" ? (
- <>
- <OperatingSystem os={value || "Other"} />
- {value || t("Other")}
- </>
- ) : (
- <>
- {displayValue}
- {dimension === "pathname" && value && (
- <a
- href={`https://${siteMetadata?.domain}${value}`}
- target="_blank"
- onClick={e => e.stopPropagation()}
- >
- <SquareArrowOutUpRight
- className="w-3.5 h-3.5 text-neutral-600 dark:text-neutral-300 hover:text-neutral-900 dark:hover:text-neutral-100"
- strokeWidth={3}
- />
- </a>
- )}
- </>
- )}
- </div>
- );
- },
- }),
- columnHelper.accessor(`lcp_${selectedPercentile}`, {
- header: () => (
- <div className="flex items-center gap-1">
- LCP
- <MetricTooltip metric="lcp" />
- </div>
- ),
- cell: info => <MetricCell metric="lcp" value={info.getValue() as number} percentile={selectedPercentile} />,
- }),
- columnHelper.accessor(`cls_${selectedPercentile}`, {
- header: () => (
- <div className="flex items-center gap-1">
- CLS
- <MetricTooltip metric="cls" />
- </div>
- ),
- cell: info => <MetricCell metric="cls" value={info.getValue() as number} percentile={selectedPercentile} />,
- }),
- columnHelper.accessor(`inp_${selectedPercentile}`, {
- header: () => (
- <div className="flex items-center gap-1">
- INP
- <MetricTooltip metric="inp" />
- </div>
- ),
- cell: info => <MetricCell metric="inp" value={info.getValue() as number} percentile={selectedPercentile} />,
- }),
- columnHelper.accessor(`fcp_${selectedPercentile}`, {
- header: () => (
- <div className="flex items-center gap-1">
- FCP
- <MetricTooltip metric="fcp" />
- </div>
- ),
- cell: info => <MetricCell metric="fcp" value={info.getValue() as number} percentile={selectedPercentile} />,
- }),
- columnHelper.accessor(`ttfb_${selectedPercentile}`, {
- header: () => (
- <div className="flex items-center gap-1">
- TTFB
- <MetricTooltip metric="ttfb" />
- </div>
- ),
- cell: info => <MetricCell metric="ttfb" value={info.getValue() as number} percentile={selectedPercentile} />,
- }),
- columnHelper.accessor("event_count", {
- header: t("Events"),
- cell: info => (
- <div className="text-neutral-600 dark:text-neutral-300">{info.getValue()?.toLocaleString() ?? 0}</div>
- ),
- }),
- ],
- [selectedPercentile]
- );
+ const regionName = (code: string) =>
+ subdivisions?.features.find(feature => feature.properties.iso_3166_2 === code)?.properties.name ?? code.slice(3);
- const table = useReactTable({
- data: paths,
- columns,
- getCoreRowModel: getCoreRowModel(),
- getSortedRowModel: getSortedRowModel(),
- onSortingChange: updater => {
- setSorting(updater);
- // Reset to first page when sorting changes
- setPagination(prev => ({ ...prev, pageIndex: 0 }));
- },
- state: {
- sorting,
- },
- // Disable client-side sorting since we're doing server-side sorting
- enableSortingRemoval: false,
- manualSorting: true,
- });
+ const nameOf = (value: string): string => {
+ if (dimension === "country") return getCountryName(value) || value;
+ if (dimension === "region") return `${value.split("-")[0]} › ${regionName(value)}`;
+ return value;
+ };
- // Create pagination controller that matches the interface
- const paginationController = {
- getState: () => ({ pagination }),
- getCanPreviousPage: () => pagination.pageIndex > 0,
- getCanNextPage: () => pagination.pageIndex < totalPages - 1,
- getPageCount: () => totalPages,
- setPageIndex: (index: number) => setPagination(prev => ({ ...prev, pageIndex: index })),
- previousPage: () =>
- setPagination(prev => ({
- ...prev,
- pageIndex: Math.max(0, prev.pageIndex - 1),
- })),
- nextPage: () =>
- setPagination(prev => ({
- ...prev,
- pageIndex: Math.min(totalPages - 1, prev.pageIndex + 1),
- })),
+ const iconOf = (value: string): ReactNode => {
+ switch (dimension) {
+ case "country":
+ return <CountryFlag country={value} />;
+ case "region":
+ return <CountryFlag country={value.split("-")[0]} />;
+ case "device_type":
+ return <DeviceIcon deviceType={value} />;
+ case "browser":
+ return <Browser browser={value} />;
+ case "operating_system":
+ return <OperatingSystem os={value} />;
+ default:
+ return null;
+ }
};
- // Transform data to match expected format
- const paginationData = {
- items: paths,
- total: totalCount,
+ const dimensionLabel: Record<PerformanceDimension, string> = {
+ pathname: t("Page"),
+ country: t("Country"),
+ region: t("Region"),
+ device_type: t("Device type"),
+ browser: t("Browser"),
+ operating_system: t("Operating system"),
};
+ const selectedShort = METRIC_LABELS_SHORT[selectedMetric];
+ const columnCount = PERFORMANCE_METRICS.length + (hasPrevious ? 5 : 4);
+ const firstRow = pageIndex * PERFORMANCE_PAGE_SIZE + 1;
return (
<>
- {isFetching && (
- <div className="absolute top-[-8px] left-0 w-full h-full">
- <CardLoader />
- </div>
- )}
- {isLoading ? (
- <Table>
- <TableHeader>
- <TableRow className="border-neutral-300 dark:border-neutral-800">
- <TableHead className="text-neutral-600 dark:text-neutral-300">
- <Skeleton className="h-4 w-20" />
- </TableHead>
- <TableHead className="text-neutral-600 dark:text-neutral-300 text-center">
- <Skeleton className="h-4 w-8 mx-auto" />
- </TableHead>
- <TableHead className="text-neutral-600 dark:text-neutral-300 text-center">
- <Skeleton className="h-4 w-8 mx-auto" />
- </TableHead>
- <TableHead className="text-neutral-600 dark:text-neutral-300 text-center">
- <Skeleton className="h-4 w-8 mx-auto" />
- </TableHead>
- <TableHead className="text-neutral-600 dark:text-neutral-300 text-center">
- <Skeleton className="h-4 w-8 mx-auto" />
- </TableHead>
- <TableHead className="text-neutral-600 dark:text-neutral-300 text-center">
- <Skeleton className="h-4 w-10 mx-auto" />
- </TableHead>
- <TableHead className="text-neutral-600 dark:text-neutral-300 text-center">
- <Skeleton className="h-4 w-12 mx-auto" />
+ {isFetching && <CardLoader />}
+ <Table className="min-w-[1020px]">
+ <TableHeader>
+ <TableRow className="hover:bg-transparent dark:hover:bg-transparent">
+ <TableHead className="min-w-[200px] rounded-none pl-4 first:rounded-none">
+ {dimensionLabel[dimension]}
+ </TableHead>
+ {PERFORMANCE_METRICS.map(metric => (
+ <SortHeader
+ key={metric}
+ active={sortColumn === metric}
+ desc={sortDesc}
+ onSort={() => onSort(metric)}
+ className={cn("w-[84px]", metric === selectedMetric && "text-neutral-900 dark:text-neutral-100")}
+ >
+ <MetricTooltip metric={metric}>
+ <span>{METRIC_LABELS_SHORT[metric]}</span>
+ </MetricTooltip>
+ </SortHeader>
+ ))}
+ <TableHead className="w-[168px] pl-4">{t("Good {metric} loads", { metric: selectedShort })}</TableHead>
+ {hasPrevious && (
+ <TableHead className="w-[88px] whitespace-nowrap text-right">
+ {t("{metric} change", { metric: selectedShort })}
</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {Array.from({ length: 10 }).map((_, i) => (
- <TableRow key={i}>
- <TableCell>
- <div className="flex items-center gap-2">
- <Skeleton className="h-4 w-4 rounded" />
- <Skeleton className="h-4 w-32" />
- </div>
- </TableCell>
- <TableCell>
- <div>
- <Skeleton className="h-4 w-12 mx-auto" />
- </div>
- </TableCell>
- <TableCell>
- <div>
- <Skeleton className="h-4 w-10 mx-auto" />
- </div>
- </TableCell>
- <TableCell>
- <div>
- <Skeleton className="h-4 w-12 mx-auto" />
- </div>
- </TableCell>
- <TableCell>
- <div>
- <Skeleton className="h-4 w-12 mx-auto" />
- </div>
- </TableCell>
- <TableCell>
- <div>
- <Skeleton className="h-4 w-12 mx-auto" />
- </div>
- </TableCell>
- <TableCell>
- <div>
- <Skeleton className="h-4 w-16 mx-auto" />
- </div>
+ )}
+ <SortHeader
+ active={sortColumn === "loads"}
+ desc={sortDesc}
+ onSort={() => onSort("loads")}
+ className="w-[76px]"
+ >
+ {t("Loads")}
+ </SortHeader>
+ <TableHead className="w-[72px] rounded-none pr-4 last:rounded-none">
+ <span className="sr-only">{t("Open in")}</span>
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isLoading ? (
+ Array.from({ length: 10 }).map((_, index) => (
+ <TableRow key={index} className="h-9">
+ <TableCell className="py-0 pl-4">
+ <Skeleton className="h-4 w-40" />
</TableCell>
+ {Array.from({ length: columnCount - 1 }).map((_, cell) => (
+ <TableCell key={cell} className="py-0">
+ <Skeleton className="ml-auto h-4 w-12" />
+ </TableCell>
+ ))}
</TableRow>
- ))}
- </TableBody>
- </Table>
- ) : (
- <>
- <Table>
- <TableHeader>
- {table.getHeaderGroups().map(headerGroup => (
- <TableRow key={headerGroup.id}>
- {headerGroup.headers.map(header => (
- <TableHead
- key={header.id}
- className={`text-neutral-600 dark:text-neutral-300 ${header.column.getCanSort()
- ? "cursor-pointer hover:text-white transition-colors select-none"
- : ""
- }`}
- onClick={header.column.getToggleSortingHandler()}
- >
- <div className="flex items-center gap-1">
- {flexRender(header.column.columnDef.header, header.getContext())}
- <TableSortIndicator
- sortDirection={header.column.getIsSorted()}
- canSort={header.column.getCanSort()}
- />
- </div>
- </TableHead>
+ ))
+ ) : rows.length === 0 ? (
+ <TableRow className="hover:bg-transparent dark:hover:bg-transparent">
+ <TableCell colSpan={columnCount} className="py-10 text-center text-neutral-500 dark:text-neutral-400">
+ {t("No performance data available")}
+ </TableCell>
+ </TableRow>
+ ) : (
+ rows.map(row => {
+ const value = String(row[dimension]);
+ const name = nameOf(value);
+ const previousRow = previousByValue.get(value);
+ const split = getRatingSplit(row, selectedMetric);
+ const key = `${selectedMetric}_${percentile}` as const;
+
+ return (
+ <TableRow key={value} className="group h-9">
+ <TableCell className="max-w-0 py-0 pl-4">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <button
+ type="button"
+ className="flex min-w-0 items-center gap-2 text-neutral-900 hover:underline dark:text-neutral-100"
+ title={t("Filter by {name}", { name })}
+ onClick={() => toggleFilter(value)}
+ >
+ {iconOf(value)}
+ <span className="truncate">{name}</span>
+ </button>
+ {dimension === "pathname" && siteMetadata?.domain && (
+ <a
+ href={`https://${siteMetadata.domain}${value}`}
+ target="_blank"
+ rel="noreferrer"
+ aria-label={t("Open page in a new tab")}
+ className="shrink-0 text-neutral-500 hover:text-neutral-900 focus-visible:opacity-100 dark:text-neutral-400 dark:hover:text-neutral-100 md:opacity-0 md:group-hover:opacity-100"
+ >
+ <SquareArrowOutUpRight className="h-3.5 w-3.5" />
+ </a>
+ )}
+ </div>
+ </TableCell>
+ {PERFORMANCE_METRICS.map(metric => (
+ <TableCell key={metric} className="py-0 text-right">
+ <MetricCell
+ metric={metric}
+ percentile={percentile}
+ dimension={dimension}
+ value={value}
+ name={name}
+ row={row}
+ previousRow={previousRow}
+ />
+ </TableCell>
))}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows.length === 0 ? (
- <TableRow>
- <TableCell colSpan={columns.length} className="text-neutral-500 py-8">
- {t("No performance data available")}
+ <TableCell className="py-0 pl-4">
+ <GoodShare share={split ? split.goodShare : null} />
+ </TableCell>
+ {hasPrevious && (
+ <TableCell className="py-0 text-right">
+ <Delta value={percentDelta(row[key], previousRow?.[key])} upIsGood={false} />
+ </TableCell>
+ )}
+ <TableCell className="py-0 text-right tabular-nums text-neutral-700 dark:text-neutral-200">
+ {row.event_count.toLocaleString()}
+ </TableCell>
+ <TableCell className="py-0 pr-4">
+ <PivotActions
+ filters={[{ parameter: dimension, type: "equals", value: [value] }]}
+ actions={["sessions", "replays"]}
+ showLabels={false}
+ className="flex-nowrap justify-end"
+ />
</TableCell>
</TableRow>
- ) : (
- table.getRowModel().rows.map(row => (
- <TableRow key={row.id}>
- {row.getVisibleCells().map(cell => (
- <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
- ))}
- </TableRow>
- ))
- )}
- </TableBody>
- </Table>
+ );
+ })
+ )}
+ </TableBody>
+ </Table>
- {totalPages > 1 && (
- <div className="mt-4">
- <Pagination
- table={paginationController}
- data={paginationData}
- pagination={pagination}
- setPagination={setPagination}
- isLoading={isLoading}
- itemName={dimension === "pathname" ? "paths" : dimension}
- />
+ {rows.length > 0 && (
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t border-neutral-100 px-4 py-2.5 text-xs text-neutral-500 dark:border-neutral-850 dark:text-neutral-400">
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1">
+ {METRIC_RATINGS.map(rating => (
+ <span key={rating} className="inline-flex items-center gap-1.5">
+ <RatingMark rating={rating} />
+ {ratingLabels[rating]}
+ </span>
+ ))}
+ <span>
+ {t("Rated at {percentile}. The tick on each bar is the 75% of good loads needed to pass.", {
+ percentile,
+ })}
+ </span>
+ </div>
+ <div className="ml-auto flex items-center gap-2">
+ <span className="tabular-nums">
+ {t("{from}–{to} of {total}", {
+ from: firstRow.toLocaleString(),
+ to: (firstRow + rows.length - 1).toLocaleString(),
+ total: totalCount.toLocaleString(),
+ })}
+ </span>
+ <div className="flex items-center">
+ <Button
+ variant="ghost"
+ size="smIcon"
+ aria-label={t("Previous page")}
+ disabled={pageIndex === 0}
+ onClick={() => setPageIndex(index => Math.max(0, index - 1))}
+ >
+ <ChevronLeft />
+ </Button>
+ <Button
+ variant="ghost"
+ size="smIcon"
+ aria-label={t("Next page")}
+ disabled={pageIndex >= totalPages - 1}
+ onClick={() => setPageIndex(index => index + 1)}
+ >
+ <ChevronRight />
+ </Button>
</div>
- )}
- </>
+ </div>
+ </div>
)}
</>
);
diff --git a/client/src/app/[site]/performance/components/shared/RatingMark.tsx b/client/src/app/[site]/performance/components/shared/RatingMark.tsx
new file mode 100644
index 000000000..170b62b82
--- /dev/null
+++ b/client/src/app/[site]/performance/components/shared/RatingMark.tsx
@@ -0,0 +1,58 @@
+import { useExtracted } from "next-intl";
+import { cn } from "@/lib/utils";
+import { PerformanceMetric } from "../../performanceStore";
+import { MetricRating, RATING_TEXT_CLASS } from "../../utils/performanceUtils";
+
+export function useRatingLabels(): Record<MetricRating, string> {
+ const t = useExtracted();
+ return {
+ good: t("Good"),
+ needs_improvement: t("Needs improvement"),
+ poor: t("Poor"),
+ };
+}
+
+export function useMetricNames(): Record<PerformanceMetric, string> {
+ const t = useExtracted();
+ return {
+ lcp: t("Largest Contentful Paint"),
+ inp: t("Interaction to Next Paint"),
+ cls: t("Cumulative Layout Shift"),
+ fcp: t("First Contentful Paint"),
+ ttfb: t("Time to First Byte"),
+ };
+}
+
+/**
+ * A rating as a mark that differs in shape as well as colour (circle, square,
+ * triangle), so it reads without colour vision. Decorative by default: put the
+ * rating in words next to it, or pass `label` when it stands alone.
+ */
+export function RatingMark({
+ rating,
+ label,
+ className,
+}: {
+ rating: MetricRating;
+ /** Accessible name, for a mark with no rating text beside it. */
+ label?: string;
+ className?: string;
+}) {
+ return (
+ <svg
+ viewBox="0 0 10 10"
+ className={cn("h-2 w-2 shrink-0 fill-current", RATING_TEXT_CLASS[rating], className)}
+ role={label ? "img" : undefined}
+ aria-label={label}
+ aria-hidden={label ? undefined : true}
+ >
+ {rating === "good" ? (
+ <circle cx="5" cy="5" r="4.4" />
+ ) : rating === "needs_improvement" ? (
+ <rect x="1" y="1" width="8" height="8" rx="1.5" />
+ ) : (
+ <path d="M5 0.8 9.7 9.2H0.3Z" />
+ )}
+ </svg>
+ );
+}
diff --git a/client/src/app/[site]/performance/page.tsx b/client/src/app/[site]/performance/page.tsx
index 0ead815e5..2ee364788 100644
--- a/client/src/app/[site]/performance/page.tsx
+++ b/client/src/app/[site]/performance/page.tsx
@@ -1,27 +1,63 @@
"use client";
+import { Flag } from "lucide-react";
import { useExtracted } from "next-intl";
+import { BucketSelection } from "../../../components/BucketSelection";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
+import { AnalysisBar } from "../../../components/site/AnalysisBar";
+import { Button } from "../../../components/ui/button";
+import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
+import { cn } from "../../../lib/utils";
import { SubHeader } from "../components/SubHeader/SubHeader";
+import { EnableWebVitals } from "./components/EnableWebVitals";
+import { PercentileSelector } from "./components/PercentileSelector";
+import { PerformanceByDimensions } from "./components/PerformanceByDimensions";
import { PerformanceChart } from "./components/PerformanceChart";
+import { PerformanceInsight } from "./components/PerformanceInsight";
import { PerformanceOverview } from "./components/PerformanceOverview";
-import { PerformanceByDimensions } from "./components/PerformanceByDimensions";
-import { EnableWebVitals } from "./components/EnableWebVitals";
-import { DisabledOverlay } from "../../../components/DisabledOverlay";
-import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
+import { usePerformanceStore } from "./performanceStore";
+import { useVisibleAnnotations } from "./utils/useVisibleAnnotations";
+
+// Shows and hides the timeline annotations on the chart. Without any in the
+// selected period there is nothing to toggle, so it is not drawn.
+function AnnotationsToggle() {
+ const t = useExtracted();
+ const { showAnnotations, setShowAnnotations } = usePerformanceStore();
+ const annotations = useVisibleAnnotations();
+ if (annotations.length === 0) return null;
+
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-pressed={showAnnotations}
+ onClick={() => setShowAnnotations(!showAnnotations)}
+ className={cn("gap-1.5 font-normal", showAnnotations && "bg-neutral-100 dark:bg-neutral-800")}
+ >
+ <Flag />
+ {t("Annotations")}
+ <span className="tabular-nums text-neutral-500 dark:text-neutral-400">{annotations.length}</span>
+ </Button>
+ );
+}
export default function PerformancePage() {
useSetPageTitle("Performance");
const t = useExtracted();
return (
<DisabledOverlay message={t("Performance")} featurePath="performance">
- <div className="p-2 md:p-4 max-w-[1100px] mx-auto space-y-3 ">
+ <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
<SubHeader />
<EnableWebVitals />
- <div className="space-y-4">
- <PerformanceOverview />
- <PerformanceChart />
- <PerformanceByDimensions />
- </div>
+ <PerformanceOverview />
+ <AnalysisBar end={<AnnotationsToggle />}>
+ <PercentileSelector />
+ <BucketSelection />
+ </AnalysisBar>
+ <PerformanceInsight />
+ <PerformanceChart />
+ <PerformanceByDimensions />
</div>
</DisabledOverlay>
);
diff --git a/client/src/app/[site]/performance/performanceStore.ts b/client/src/app/[site]/performance/performanceStore.ts
index c88175656..fb04776bf 100644
--- a/client/src/app/[site]/performance/performanceStore.ts
+++ b/client/src/app/[site]/performance/performanceStore.ts
@@ -9,11 +9,16 @@ type PerformanceStore = {
setSelectedPercentile: (percentile: PercentileLevel) => void;
selectedPerformanceMetric: PerformanceMetric;
setSelectedPerformanceMetric: (metric: PerformanceMetric) => void;
+ showAnnotations: boolean;
+ setShowAnnotations: (show: boolean) => void;
};
export const usePerformanceStore = create<PerformanceStore>(set => ({
- selectedPercentile: "p90",
+ // Core Web Vitals are assessed at the 75th percentile.
+ selectedPercentile: "p75",
setSelectedPercentile: percentile => set({ selectedPercentile: percentile }),
selectedPerformanceMetric: "lcp",
setSelectedPerformanceMetric: metric => set({ selectedPerformanceMetric: metric }),
+ showAnnotations: true,
+ setShowAnnotations: show => set({ showAnnotations: show }),
}));
diff --git a/client/src/app/[site]/performance/utils/annotationWindow.ts b/client/src/app/[site]/performance/utils/annotationWindow.ts
new file mode 100644
index 000000000..9bf4e4c02
--- /dev/null
+++ b/client/src/app/[site]/performance/utils/annotationWindow.ts
@@ -0,0 +1,23 @@
+import type { Annotation, TimeBucket } from "@rybbit/shared";
+import { DateTime } from "luxon";
+import { shiftBuckets } from "@/components/charts/timeSeriesChartUtils";
+import { parseAnnotationInstant } from "../../main/components/MainSection/annotations/annotationUtils";
+
+/**
+ * The annotations that touch the chart's window. The window ends with its last
+ * bucket, not at that bucket's start, so a note from 2pm on the last day of a
+ * daily chart still counts: the same rule the pins on the chart follow.
+ */
+export function annotationsInWindow(
+ annotations: Annotation[],
+ window: { min?: Date; max?: Date },
+ bucket: TimeBucket,
+ now: Date = new Date()
+): Annotation[] {
+ const windowEnd = shiftBuckets(DateTime.fromJSDate(window.max ?? now), bucket, 1).toJSDate();
+ return annotations.filter(annotation => {
+ const start = parseAnnotationInstant(annotation.date).toJSDate();
+ const end = annotation.endDate ? parseAnnotationInstant(annotation.endDate).toJSDate() : start;
+ return start < windowEnd && (window.min === undefined || end >= window.min);
+ });
+}
diff --git a/client/src/app/[site]/performance/utils/performanceUtils.test.ts b/client/src/app/[site]/performance/utils/performanceUtils.test.ts
new file mode 100644
index 000000000..cd4c5b91f
--- /dev/null
+++ b/client/src/app/[site]/performance/utils/performanceUtils.test.ts
@@ -0,0 +1,149 @@
+import type { Annotation } from "@rybbit/shared";
+import { describe, expect, it } from "vitest";
+import { annotationsInWindow } from "./annotationWindow";
+import {
+ findOnlyPoorRow,
+ formatMetric,
+ formatShare,
+ getMetricRating,
+ getRatingSplit,
+ PERFORMANCE_METRICS,
+} from "./performanceUtils";
+
+describe("getMetricRating", () => {
+ it("rates a value on the limit as the better of the two", () => {
+ expect(getMetricRating("lcp", 2500)).toBe("good");
+ expect(getMetricRating("lcp", 2501)).toBe("needs_improvement");
+ expect(getMetricRating("lcp", 4000)).toBe("needs_improvement");
+ expect(getMetricRating("lcp", 4001)).toBe("poor");
+ });
+
+ it("uses each metric's own limits", () => {
+ expect(getMetricRating("cls", 0.1)).toBe("good");
+ expect(getMetricRating("cls", 0.14)).toBe("needs_improvement");
+ expect(getMetricRating("cls", 0.26)).toBe("poor");
+ expect(getMetricRating("inp", 96)).toBe("good");
+ expect(getMetricRating("inp", 501)).toBe("poor");
+ expect(getMetricRating("fcp", 1801)).toBe("needs_improvement");
+ expect(getMetricRating("ttfb", 800)).toBe("good");
+ expect(getMetricRating("ttfb", 1801)).toBe("poor");
+ });
+});
+
+describe("formatMetric", () => {
+ it("prints the unit the value calls for", () => {
+ expect(formatMetric("lcp", 2400)).toBe("2.4s");
+ expect(formatMetric("lcp", 1240)).toBe("1.24s");
+ expect(formatMetric("inp", 96)).toBe("96ms");
+ expect(formatMetric("ttfb", 560)).toBe("560ms");
+ expect(formatMetric("cls", 0.14)).toBe("0.14");
+ });
+});
+
+describe("getRatingSplit", () => {
+ it("derives the loads that need improvement and the share of good ones", () => {
+ expect(getRatingSplit({ lcp_count: 3327, lcp_good: 1367, lcp_poor: 880 }, "lcp")).toEqual({
+ count: 3327,
+ good: 1367,
+ needs_improvement: 1080,
+ poor: 880,
+ goodShare: (1367 / 3327) * 100,
+ });
+ });
+
+ it("reads each metric's own columns", () => {
+ const row = { lcp_count: 10, lcp_good: 10, lcp_poor: 0, inp_count: 4, inp_good: 1, inp_poor: 3 };
+ expect(getRatingSplit(row, "lcp")?.goodShare).toBe(100);
+ expect(getRatingSplit(row, "inp")).toMatchObject({ count: 4, needs_improvement: 0, goodShare: 25 });
+ });
+
+ it("has no split when no load reported the metric", () => {
+ expect(getRatingSplit({ inp_count: 0, inp_good: 0, inp_poor: 0 }, "inp")).toBeNull();
+ expect(getRatingSplit({}, "lcp")).toBeNull();
+ expect(getRatingSplit(undefined, "lcp")).toBeNull();
+ expect(getRatingSplit(null, "lcp")).toBeNull();
+ });
+
+ it("never reports a negative count from inconsistent input", () => {
+ expect(getRatingSplit({ cls_count: 5, cls_good: 4, cls_poor: 3 }, "cls")?.needs_improvement).toBe(0);
+ });
+});
+
+describe("formatShare", () => {
+ it("keeps one decimal", () => {
+ expect(formatShare(77.34)).toBe("77.3%");
+ expect(formatShare(100)).toBe("100.0%");
+ expect(formatShare(0)).toBe("0.0%");
+ });
+});
+
+describe("findOnlyPoorRow", () => {
+ const rows = (values: (number | null)[]) => values.map((lcp_p75, index) => ({ pathname: `/page-${index}`, lcp_p75 }));
+ const value = (row: { lcp_p75: number | null }) => row.lcp_p75;
+
+ it("finds the single poor row", () => {
+ expect(findOnlyPoorRow(rows([2100, 4100, 1800, 3900]), "lcp", value)).toEqual({
+ pathname: "/page-1",
+ lcp_p75: 4100,
+ });
+ });
+
+ it("says nothing when no row or several rows are poor", () => {
+ expect(findOnlyPoorRow(rows([2100, 3900, 1800]), "lcp", value)).toBeNull();
+ expect(findOnlyPoorRow(rows([4100, 4700, 1800]), "lcp", value)).toBeNull();
+ });
+
+ it("needs three rated rows to single one out", () => {
+ expect(findOnlyPoorRow(rows([4100, 1800]), "lcp", value)).toBeNull();
+ expect(findOnlyPoorRow(rows([4100, 1800, null]), "lcp", value)).toBeNull();
+ expect(findOnlyPoorRow(rows([4100, 1800, null, 2000]), "lcp", value)?.pathname).toBe("/page-0");
+ });
+
+ it("rates against the metric it is asked about", () => {
+ // 600 is a poor INP but a good LCP.
+ expect(findOnlyPoorRow(rows([600, 100, 150]), "inp", value)?.pathname).toBe("/page-0");
+ expect(findOnlyPoorRow(rows([600, 100, 150]), "lcp", value)).toBeNull();
+ });
+});
+
+describe("PERFORMANCE_METRICS", () => {
+ it("lists the Core Web Vitals first", () => {
+ expect(PERFORMANCE_METRICS).toEqual(["lcp", "inp", "cls", "fcp", "ttfb"]);
+ });
+});
+
+describe("annotationsInWindow", () => {
+ const annotation = (annotationId: number, date: string, endDate: string | null = null) =>
+ ({ annotationId, date, endDate }) as Annotation;
+ const window = { min: new Date("2026-09-01T00:00:00Z"), max: new Date("2026-09-30T00:00:00Z") };
+ const ids = (annotations: Annotation[]) => annotations.map(a => a.annotationId);
+
+ it("keeps annotations inside the window, including the whole last bucket", () => {
+ const annotations = [
+ annotation(1, "2026-08-31T23:59:00Z"),
+ annotation(2, "2026-09-01T00:00:00Z"),
+ annotation(3, "2026-09-15T12:00:00Z"),
+ annotation(4, "2026-09-30T14:00:00Z"),
+ annotation(5, "2026-10-01T00:00:00Z"),
+ ];
+ expect(ids(annotationsInWindow(annotations, window, "day"))).toEqual([2, 3, 4]);
+ });
+
+ it("keeps a range that began before the window and reaches into it", () => {
+ const annotations = [
+ annotation(1, "2026-08-20T00:00:00Z", "2026-09-02T00:00:00Z"),
+ annotation(2, "2026-08-20T00:00:00Z", "2026-08-25T00:00:00Z"),
+ ];
+ expect(ids(annotationsInWindow(annotations, window, "day"))).toEqual([1]);
+ });
+
+ it("has no lower bound for all time and ends at now when the window is open", () => {
+ const now = new Date("2026-09-30T10:00:00Z");
+ const annotations = [
+ annotation(1, "2021-01-01T00:00:00Z"),
+ annotation(2, "2026-09-30T10:30:00Z"),
+ annotation(3, "2026-09-30T12:00:00Z"),
+ ];
+ expect(ids(annotationsInWindow(annotations, {}, "hour", now))).toEqual([1, 2]);
+ });
+});
diff --git a/client/src/app/[site]/performance/utils/performanceUtils.ts b/client/src/app/[site]/performance/utils/performanceUtils.ts
index d7d9687d5..eec06a701 100644
--- a/client/src/app/[site]/performance/utils/performanceUtils.ts
+++ b/client/src/app/[site]/performance/utils/performanceUtils.ts
@@ -83,3 +83,92 @@ export const METRIC_LABELS_SHORT: Record<PerformanceMetric, string> = {
export const getPerformanceThresholds = (metric: PerformanceMetric) => {
return PERFORMANCE_THRESHOLDS[metric] || null;
};
+
+/** The order every surface lists the metrics in: the three Core Web Vitals, then the supporting two. */
+export const PERFORMANCE_METRICS: PerformanceMetric[] = ["lcp", "inp", "cls", "fcp", "ttfb"];
+
+export type MetricRating = "good" | "needs_improvement" | "poor";
+
+export const METRIC_RATINGS: MetricRating[] = ["good", "needs_improvement", "poor"];
+
+/** Where a value stands against the Web Vitals limits: up to `good` is good, over `needs_improvement` is poor. */
+export const getMetricRating = (metric: PerformanceMetric, value: number): MetricRating => {
+ const thresholds = PERFORMANCE_THRESHOLDS[metric];
+ if (value <= thresholds.good) return "good";
+ return value <= thresholds.needs_improvement ? "needs_improvement" : "poor";
+};
+
+/** Value and unit as one string: "2.4s", "96ms", "0.14". */
+export const formatMetric = (metric: PerformanceMetric, value: number): string =>
+ `${formatMetricValue(metric, value)}${getMetricUnit(metric, value)}`;
+
+// State colours, for rating marks and the chart's rating bands only. Measured
+// lines and bars stay in the data hue.
+export const RATING_TEXT_CLASS: Record<MetricRating, string> = {
+ good: "text-green-600 dark:text-green-400",
+ needs_improvement: "text-yellow-600 dark:text-yellow-400",
+ poor: "text-red-600 dark:text-red-400",
+};
+
+export const RATING_COLOR: Record<MetricRating, string> = {
+ good: "hsl(var(--green-400))",
+ needs_improvement: "hsl(var(--yellow-400))",
+ poor: "hsl(var(--red-400))",
+};
+
+/** The share of good loads a metric needs to pass, which is what "good at p75" means. */
+export const PASSING_GOOD_SHARE = 75;
+
+export type RatingSplit = {
+ /** Loads that reported the metric. */
+ count: number;
+ good: number;
+ needs_improvement: number;
+ poor: number;
+ /** Good loads as a percentage of `count`, 0–100. */
+ goodShare: number;
+};
+
+/**
+ * Splits the loads that reported a metric into the three ratings. The server
+ * counts the measured, the good and the poor loads; the rest need improvement.
+ * Null when nothing was measured: there is no share to speak of.
+ */
+export const getRatingSplit = (
+ counts: Record<string, unknown> | null | undefined,
+ metric: PerformanceMetric
+): RatingSplit | null => {
+ const count = Number(counts?.[`${metric}_count`]);
+ const good = Number(counts?.[`${metric}_good`]);
+ const poor = Number(counts?.[`${metric}_poor`]);
+ if (!Number.isFinite(count) || !Number.isFinite(good) || !Number.isFinite(poor) || count <= 0) return null;
+
+ return {
+ count,
+ good,
+ needs_improvement: Math.max(0, count - good - poor),
+ poor,
+ goodShare: (good / count) * 100,
+ };
+};
+
+/** A percentage of loads to one decimal: 77.34 → "77.3%". */
+export const formatShare = (share: number): string => `${share.toFixed(1)}%`;
+
+/**
+ * The one row rated poor in a list, or null when none or several are. Fewer
+ * than three rated rows is not a list worth singling one out of.
+ */
+export const findOnlyPoorRow = <T>(
+ rows: T[],
+ metric: PerformanceMetric,
+ getValue: (row: T) => number | null | undefined
+): T | null => {
+ const rated = rows.filter(row => {
+ const value = getValue(row);
+ return typeof value === "number" && Number.isFinite(value);
+ });
+ if (rated.length < 3) return null;
+ const poor = rated.filter(row => getMetricRating(metric, getValue(row) as number) === "poor");
+ return poor.length === 1 ? poor[0] : null;
+};
diff --git a/client/src/app/[site]/performance/utils/usePerformanceRows.ts b/client/src/app/[site]/performance/utils/usePerformanceRows.ts
new file mode 100644
index 000000000..03a3954a6
--- /dev/null
+++ b/client/src/app/[site]/performance/utils/usePerformanceRows.ts
@@ -0,0 +1,80 @@
+import { useMemo } from "react";
+import { PerformanceByDimensionItem } from "@/api/analytics/endpoints";
+import { useGetPerformanceByDimension } from "@/api/analytics/hooks/performance/useGetPerformanceByDimension";
+import { useComparisonEnabled, useStore } from "@/lib/store";
+
+/** The dimensions the by-dimension endpoint groups by. Each is also a filter parameter. */
+export type PerformanceDimension = "pathname" | "country" | "region" | "device_type" | "browser" | "operating_system";
+
+export const PERFORMANCE_PAGE_SIZE = 25;
+
+export type PerformanceSort = { by: string; desc: boolean };
+
+export const DEFAULT_PERFORMANCE_SORT: PerformanceSort = { by: "event_count", desc: true };
+
+const EMPTY: PerformanceByDimensionItem[] = [];
+
+/**
+ * One page of rows for a dimension, and the same rows in the comparison
+ * period.
+ *
+ * The previous period is asked for by name, with a filter on exactly the
+ * values on screen: its own first page would be a different set of rows
+ * whenever the ranking moved. It runs once the current rows are known and
+ * stops when the comparison is turned off.
+ */
+export function usePerformanceRows({
+ dimension,
+ page = 1,
+ sort = DEFAULT_PERFORMANCE_SORT,
+}: {
+ dimension: PerformanceDimension;
+ /** 1-based. */
+ page?: number;
+ sort?: PerformanceSort;
+}) {
+ const site = useStore(state => state.site);
+ const comparisonEnabled = useComparisonEnabled();
+
+ const { data, isLoading, isFetching, isPlaceholderData } = useGetPerformanceByDimension({
+ site,
+ dimension,
+ page,
+ limit: PERFORMANCE_PAGE_SIZE,
+ sortBy: sort.by,
+ sortOrder: sort.desc ? "desc" : "asc",
+ });
+
+ const rows = data?.data ?? EMPTY;
+ const values = useMemo(() => rows.map(row => String(row[dimension])), [rows, dimension]);
+
+ const previousQuery = useGetPerformanceByDimension({
+ site,
+ dimension,
+ periodTime: "previous",
+ limit: PERFORMANCE_PAGE_SIZE,
+ additionalFilters: [{ parameter: dimension, type: "equals", value: values }],
+ // Rows still on screen from the last request would ask for the wrong names.
+ enabled: comparisonEnabled && values.length > 0 && !isPlaceholderData,
+ });
+
+ // A previous period carried over from another request, or left behind when
+ // the comparison was turned off, would be compared against the wrong rows.
+ const previousRows =
+ comparisonEnabled && !isPlaceholderData && !previousQuery.isPlaceholderData ? previousQuery.data?.data : undefined;
+
+ const previousByValue = useMemo(
+ () => new Map((previousRows ?? EMPTY).map(row => [String(row[dimension]), row])),
+ [previousRows, dimension]
+ );
+
+ return {
+ rows,
+ totalCount: data?.totalCount ?? 0,
+ previousByValue,
+ /** False while the comparison is off or still loading: there is no change to show yet. */
+ hasPrevious: previousRows !== undefined,
+ isLoading,
+ isFetching,
+ };
+}
diff --git a/client/src/app/[site]/performance/utils/useVisibleAnnotations.ts b/client/src/app/[site]/performance/utils/useVisibleAnnotations.ts
new file mode 100644
index 000000000..d6caec350
--- /dev/null
+++ b/client/src/app/[site]/performance/utils/useVisibleAnnotations.ts
@@ -0,0 +1,20 @@
+import type { Annotation } from "@rybbit/shared";
+import { useMemo } from "react";
+import { useGetAnnotations } from "@/api/analytics/hooks/useAnnotations";
+import { getChartTimeBounds } from "@/components/charts/timeSeriesChartUtils";
+import { useStore, useTimezone } from "@/lib/store";
+import { annotationsInWindow } from "./annotationWindow";
+
+/** Timeline annotations (the ones written on the Main chart) inside the selected period. */
+export function useVisibleAnnotations(): Annotation[] {
+ const site = useStore(state => state.site);
+ const time = useStore(state => state.time);
+ const bucket = useStore(state => state.bucket);
+ const timezone = useTimezone();
+ const { data } = useGetAnnotations(site);
+
+ return useMemo(
+ () => (data?.length ? annotationsInWindow(data, getChartTimeBounds(time, bucket, timezone), bucket) : []),
+ [data, time, bucket, timezone]
+ );
+}
diff --git a/client/src/app/[site]/retention/RetentionCard.tsx b/client/src/app/[site]/retention/RetentionCard.tsx
new file mode 100644
index 000000000..7ffc99387
--- /dev/null
+++ b/client/src/app/[site]/retention/RetentionCard.tsx
@@ -0,0 +1,206 @@
+"use client";
+
+import { useExtracted } from "next-intl";
+import { CSSProperties, useCallback, useState } from "react";
+import { ProcessedRetentionData } from "../../../api/analytics/endpoints";
+import { SegmentedControl } from "../../../components/interior/segmented-control";
+import { Card } from "../../../components/ui/card";
+import { cn } from "../../../lib/utils";
+import { RetentionChart, RetentionReadout } from "./RetentionChart";
+import {
+ CellTarget,
+ HATCH_VARIABLE,
+ HatchSwatch,
+ HeatLegend,
+ HoverTarget,
+ RetentionGrid,
+ RetentionUnit,
+} from "./RetentionGrid";
+import { lastPeriodProgress, RetentionAverage, RetentionModel } from "./retentionModel";
+
+// Shared by the curve and the grid so a period's point sits over its column:
+// cohort label, cohort size, then one track per period since the first visit.
+const COLUMNS =
+ "grid-cols-[128px_72px_repeat(var(--rt-periods),minmax(52px,1fr))] md:grid-cols-[168px_120px_repeat(var(--rt-periods),minmax(52px,1fr))]";
+
+interface RetentionCardProps {
+ data: ProcessedRetentionData;
+ model: RetentionModel;
+ /** The comparison period's average per offset; null while the comparison is off or loading. */
+ previousAverage: (RetentionAverage | null)[] | null;
+ /** A cohort picked outside the card (the insight row's action). */
+ pinnedCohort: string | null;
+ onPinCohort: (cohort: string) => void;
+ hasFilters: boolean;
+ cohortLabel: (key: string) => string;
+ periodLabel: (offset: number) => string;
+ formatDay: (key: string) => string;
+}
+
+/**
+ * The page's one instrument: the retention curve fused above the cohort heat
+ * grid. Hovering either moves one crosshair through both; a cell click pins
+ * its figures in a popover.
+ */
+export function RetentionCard({
+ data,
+ model,
+ previousAverage,
+ pinnedCohort,
+ onPinCohort,
+ hasFilters,
+ cohortLabel,
+ periodLabel,
+ formatDay,
+}: RetentionCardProps) {
+ const t = useExtracted();
+ const [unit, setUnit] = useState<RetentionUnit>("percent");
+ const [hover, setHover] = useState<HoverTarget | null>(null);
+ const [selected, setSelected] = useState<CellTarget | null>(null);
+
+ const isWeekly = model.mode === "week";
+ const cohortByKey = (key: string | null | undefined) =>
+ key ? model.cohorts.find(cohort => cohort.key === key && cohort.size > 0) : undefined;
+ const inRange = (offset: number | null | undefined): offset is number =>
+ typeof offset === "number" && offset >= 1 && offset <= model.maxOffset;
+
+ // A selection made on an earlier range may no longer be in the grid.
+ const selectedCohort = cohortByKey(selected?.cohort);
+ const selectedOffset = selectedCohort && inRange(selected?.offset) ? selected.offset : null;
+ const hoverOffset = inRange(hover?.offset) ? hover.offset : null;
+
+ const activeCohort =
+ cohortByKey(hover?.cohort) ??
+ selectedCohort ??
+ cohortByKey(pinnedCohort) ??
+ model.best ??
+ model.cohorts.find(cohort => cohort.size > 0) ??
+ null;
+ const activeOffset = hoverOffset ?? selectedOffset ?? 1;
+
+ const hoverOffsetOnly = useCallback(
+ (offset: number | null) => setHover(offset === null ? null : { cohort: null, offset }),
+ []
+ );
+ const pinCohort = useCallback(
+ (cohort: string) => {
+ setSelected(null);
+ onPinCohort(cohort);
+ },
+ [onPinCohort]
+ );
+
+ const progress = lastPeriodProgress(data);
+ const lastPeriod = data.periods[data.periods.length - 1];
+
+ const progressNote = !progress
+ ? null
+ : data.lastPeriodInProgress
+ ? isWeekly
+ ? t("In progress: the week of {date} has {elapsed} of {total} days", {
+ date: formatDay(lastPeriod),
+ elapsed: String(progress.elapsedDays),
+ total: String(progress.totalDays),
+ })
+ : t("In progress: {date} is not over yet", { date: formatDay(lastPeriod) })
+ : isWeekly
+ ? t("Partial: the range ends partway through the week of {date}", { date: formatDay(lastPeriod) })
+ : t("Partial: the range ends partway through {date}", { date: formatDay(lastPeriod) });
+
+ const readout = (
+ <RetentionReadout
+ model={model}
+ previousAverage={previousAverage}
+ activeCohort={activeCohort}
+ activeCohortLabel={activeCohort ? cohortLabel(activeCohort.key) : null}
+ activeOffset={activeOffset}
+ periodLabel={periodLabel}
+ />
+ );
+
+ return (
+ <Card className={cn("overflow-visible", HATCH_VARIABLE)}>
+ <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-3 p-4 pb-3">
+ <div className="min-w-0">
+ <h2 className="font-semibold leading-none tracking-tight">
+ {isWeekly ? t("Retention by weekly cohort") : t("Retention by daily cohort")}
+ </h2>
+ <p className="mt-1.5 text-sm text-neutral-500 dark:text-neutral-400">
+ {isWeekly
+ ? t("Share of each week's new users who were active again, by weeks since their first visit")
+ : t("Share of each day's new users who were active again, by days since their first visit")}
+ </p>
+ </div>
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <HeatLegend scaleMax={model.scaleMax} />
+ <SegmentedControl<RetentionUnit>
+ aria-label={t("Show cells as")}
+ size="sm"
+ options={[
+ { value: "percent", label: "%", ariaLabel: t("Percent") },
+ { value: "users", label: t("Users") },
+ ]}
+ value={unit}
+ onValueChange={setUnit}
+ />
+ </div>
+ </div>
+
+ {/* Outside the scroller, so it stays put while the grid scrolls sideways on a narrow screen. */}
+ <div className="px-4 pb-3 md:hidden">{readout}</div>
+
+ <div className="overflow-x-auto px-4 pb-3" style={{ "--rt-periods": model.maxOffset } as CSSProperties}>
+ <RetentionChart
+ model={model}
+ previousAverage={previousAverage}
+ activeCohort={activeCohort}
+ activeCohortLabel={activeCohort ? cohortLabel(activeCohort.key) : null}
+ activeOffset={activeOffset}
+ onHoverOffset={hoverOffsetOnly}
+ readout={readout}
+ columnsClassName={COLUMNS}
+ />
+ <RetentionGrid
+ model={model}
+ unit={unit}
+ activeCohortKey={activeCohort?.key ?? null}
+ bandOffset={hoverOffset ?? selectedOffset}
+ selected={selectedCohort && selectedOffset !== null ? selected : null}
+ onHover={setHover}
+ onSelect={setSelected}
+ onPinCohort={pinCohort}
+ cohortLabel={cohortLabel}
+ periodLabel={periodLabel}
+ formatDay={formatDay}
+ progress={progress}
+ inProgress={data.lastPeriodInProgress}
+ columnsClassName={COLUMNS}
+ />
+ </div>
+
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1.5 border-t border-neutral-100 px-4 py-2.5 text-xs text-neutral-500 dark:border-neutral-850 dark:text-neutral-400">
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5">
+ {progressNote && (
+ <span className="inline-flex items-center gap-1.5">
+ <HatchSwatch />
+ {progressNote}
+ </span>
+ )}
+ {isWeekly && <span>{t("Cohort weeks start on Monday")}</span>}
+ <span>
+ {t("New users had no visit in the {days} days before the range", { days: String(data.lookbackDays) })}
+ </span>
+ {hasFilters && <span>{t("Filters apply to each user's first visit")}</span>}
+ {data.truncated && (
+ <span>
+ {isWeekly
+ ? t("Showing the latest {count} weeks of the range", { count: String(data.periods.length) })
+ : t("Showing the latest {count} days of the range", { count: String(data.periods.length) })}
+ </span>
+ )}
+ </div>
+ <span>{t("Click a cell for details")}</span>
+ </div>
+ </Card>
+ );
+}
diff --git a/client/src/app/[site]/retention/RetentionChart.tsx b/client/src/app/[site]/retention/RetentionChart.tsx
index 867d8f7b4..fb3c2bb69 100644
--- a/client/src/app/[site]/retention/RetentionChart.tsx
+++ b/client/src/app/[site]/retention/RetentionChart.tsx
@@ -1,234 +1,333 @@
"use client";
import { useExtracted } from "next-intl";
-import { useNivoTheme } from "@/lib/nivo";
-import { ResponsiveLine } from "@nivo/line";
-import { DateTime } from "luxon";
-import { useTheme } from "next-themes";
-import { useMemo } from "react";
-import { ProcessedRetentionData, RetentionMode } from "../../../api/analytics/endpoints";
-import { ChartTooltip } from "../../../components/charts/ChartTooltip";
-import { Skeleton } from "../../../components/ui/skeleton";
+import { ReactNode, useId } from "react";
+import { ChartLegend, ChartLegendItem } from "../../../components/site/ChartLegend";
+import { cn } from "../../../lib/utils";
+import { formatPercent, RetentionAverage, RetentionCohortRow, RetentionModel } from "./retentionModel";
-interface RetentionChartProps {
- data: ProcessedRetentionData | undefined;
- isLoading: boolean;
- mode: RetentionMode;
+export const AVERAGE_COLOR = "hsl(var(--dataviz))";
+/** The one cohort drawn on its own line. Orange differs from the data hue in lightness as well as hue. */
+export const COHORT_COLOR = "hsl(var(--orange-400))";
+const PREVIOUS_COLOR = "hsl(var(--neutral-500))";
+const OTHERS_COLOR = "hsl(var(--dataviz) / 0.5)";
+
+// The plot is drawn in a 1000-unit-wide box stretched over the grid's period
+// columns, so a period's x is the centre of its column at any width. Strokes
+// keep their pixel width (non-scaling-stroke); dots are HTML, which a
+// stretched SVG would squash.
+const BOX_WIDTH = 1000;
+const HEIGHT = 204;
+const PLOT_TOP = 12;
+const PLOT_BOTTOM = HEIGHT - 6;
+
+type Point = [number, number];
+
+const linePath = (points: Point[]) =>
+ points.map(([x, y], index) => `${index === 0 ? "M" : "L"}${x.toFixed(2)},${y.toFixed(2)}`).join("");
+
+/** Finished cells only: a period still in progress would read as a drop. */
+const finishedCells = (cohort: RetentionCohortRow) => cohort.cells.filter(cell => cell.offset >= 1 && !cell.partial);
+
+interface RetentionReadoutProps {
+ model: RetentionModel;
+ /** The comparison period's average per offset. Null while the comparison is off or loading. */
+ previousAverage: (RetentionAverage | null)[] | null;
+ /** The cohort drawn on its own line. */
+ activeCohort: RetentionCohortRow | null;
+ activeCohortLabel: string | null;
+ /** The period under the crosshair. */
+ activeOffset: number;
+ periodLabel: (offset: number) => string;
}
-// Vibrant color palette for different cohorts using Tailwind CSS HSL variables
-const cohortColors = [
- "hsl(var(--accent-500))", // Primary accent color
- "hsl(var(--green-500))", // Green
- "hsl(var(--red-500))", // Red
- "hsl(var(--blue-500))", // Blue
- "hsl(var(--orange-500))", // Orange
- "hsl(var(--purple-500))", // Purple
- "hsl(var(--teal-500))", // Teal
- "hsl(var(--amber-500))", // Amber
- "hsl(var(--slate-600))", // Slate
- "hsl(var(--red-600))", // Darker red
- "hsl(var(--green-600))", // Darker green
- "hsl(var(--blue-600))", // Darker blue
- "hsl(var(--purple-600))", // Darker purple
- "hsl(var(--teal-600))", // Darker teal
-];
-
-// Loading skeleton
-const RetentionChartSkeleton = () => (
- <div className="h-[400px] flex items-center justify-center">
- <div className="w-full space-y-3">
- <Skeleton className="h-[300px] w-full bg-neutral-100 dark:bg-neutral-900 rounded-md animate-pulse" />
- <div className="flex items-center justify-between px-6">
- {Array.from({ length: 6 }).map((_, i) => (
- <Skeleton
- key={i}
- className="h-4 w-12 bg-neutral-150/50 dark:bg-neutral-700/50 animate-pulse"
- style={{
- animationDelay: `${i * 100}ms`,
- opacity: 0.3 + i * 0.1,
- }}
- />
- ))}
+/**
+ * The curve's legend and its reading at the period under the crosshair, in
+ * one: each series is named beside its value.
+ */
+export function RetentionReadout({
+ model,
+ previousAverage,
+ activeCohort,
+ activeCohortLabel,
+ activeOffset,
+ periodLabel,
+}: RetentionReadoutProps) {
+ const t = useExtracted();
+
+ const average = model.average[activeOffset] ?? null;
+ const previous = previousAverage?.[activeOffset] ?? null;
+ const activeCell = activeCohort?.cells[activeOffset];
+ const cohort = activeCell && !activeCell.partial ? activeCell : null;
+ const others = model.cohorts.flatMap(other => {
+ const cell = other.cells[activeOffset];
+ return other.size > 0 && other.key !== activeCohort?.key && cell && !cell.partial ? [cell.pct] : [];
+ });
+
+ const row = (label: string, text: string) => (
+ <span className="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span className="truncate">{label}</span>
+ <span className="font-medium tabular-nums text-neutral-900 dark:text-neutral-50">{text}</span>
+ </span>
+ );
+ const none = t("n/a");
+
+ const legend: ChartLegendItem[] = [
+ {
+ id: "average",
+ color: AVERAGE_COLOR,
+ label: row(t("Average, all cohorts"), average ? formatPercent(average.pct) : none),
+ },
+ ];
+ if (activeCohort && activeCohortLabel) {
+ legend.push({
+ id: "cohort",
+ color: COHORT_COLOR,
+ label: row(t("{cohort} cohort", { cohort: activeCohortLabel }), cohort ? formatPercent(cohort.pct) : none),
+ });
+ }
+ if (previousAverage) {
+ legend.push({
+ id: "previous",
+ color: PREVIOUS_COLOR,
+ dashed: true,
+ label: row(t("Comparison period"), previous ? formatPercent(previous.pct) : none),
+ });
+ }
+ if (others.length > 0) {
+ legend.push({
+ id: "others",
+ color: OTHERS_COLOR,
+ label: row(
+ t("Other cohorts"),
+ others.length === 1
+ ? formatPercent(others[0])
+ : `${Math.min(...others).toFixed(1)} – ${formatPercent(Math.max(...others))}`
+ ),
+ });
+ }
+
+ return (
+ <div className="text-xs">
+ <div className="flex items-center justify-between gap-3 text-neutral-500 dark:text-neutral-400">
+ <span className="font-medium text-neutral-900 dark:text-neutral-50">{periodLabel(activeOffset)}</span>
+ <span>{t("after first visit")}</span>
+ </div>
+ <ChartLegend items={legend} className="mt-2.5 flex-col flex-nowrap items-stretch gap-y-2" />
+ <div className="mt-3 border-t border-neutral-100 pt-2.5 leading-relaxed text-neutral-500 dark:border-neutral-850 dark:text-neutral-400">
+ {model.mode === "week"
+ ? t("Week 0 is always 100%, so the curve starts at week 1.")
+ : t("Day 0 is always 100%, so the curve starts at day 1.")}
</div>
</div>
- </div>
-);
+ );
+}
+
+interface RetentionChartProps {
+ model: RetentionModel;
+ /** The comparison period's average per offset. Null while the comparison is off or loading. */
+ previousAverage: (RetentionAverage | null)[] | null;
+ /** The cohort drawn on its own line. */
+ activeCohort: RetentionCohortRow | null;
+ activeCohortLabel: string | null;
+ /** The period under the crosshair. */
+ activeOffset: number;
+ onHoverOffset: (offset: number | null) => void;
+ /** Drawn in the grid's two leading columns, from md up. */
+ readout: ReactNode;
+ /** Classes that lay out the grid's columns, shared with the heat grid below. */
+ columnsClassName: string;
+}
-export function RetentionChart({ data, isLoading, mode }: RetentionChartProps) {
+/**
+ * The retention curve, drawn over the heat grid's own columns: the average of
+ * all cohorts, one highlighted cohort, the comparison period, and the other
+ * cohorts as a faint spread. It starts at period 1, since period 0 is always
+ * 100% and would flatten everything after it.
+ */
+export function RetentionChart({
+ model,
+ previousAverage,
+ activeCohort,
+ activeCohortLabel,
+ activeOffset,
+ onHoverOffset,
+ readout,
+ columnsClassName,
+}: RetentionChartProps) {
const t = useExtracted();
- const { resolvedTheme } = useTheme();
- const nivoTheme = useNivoTheme();
-
- // Get cohort keys once for both chart data and tooltip
- const cohortKeys = useMemo(() => {
- if (!data || !data.cohorts) return [];
- return Object.keys(data.cohorts)
- .sort((a, b) => b.localeCompare(a))
- .slice(0, 12); // Limit to 12 most recent cohorts for better readability
- }, [data]);
-
- // Process data for the chart - organize by cohort
- const chartData = useMemo(() => {
- if (!data || !data.cohorts || cohortKeys.length === 0) {
- return [];
- }
-
- // Format each cohort as a series (line)
- return cohortKeys.map((cohortKey, index) => {
- const cohortData = data.cohorts[cohortKey];
-
- // Format the date label based on mode
- let formattedDate: string;
- const startDate = DateTime.fromISO(cohortKey);
- if (mode === "day") {
- formattedDate = startDate.toFormat("MMM dd");
- } else {
- // For weekly mode
- const endDate = startDate.plus({ days: 6 });
-
- // If same month, don't repeat month
- if (startDate.month === endDate.month) {
- formattedDate = `${startDate.toFormat("MMM dd")}-${endDate.toFormat("dd")}`;
- } else {
- formattedDate = `${startDate.toFormat("MMM dd")}-${endDate.toFormat("MMM dd")}`;
- }
- }
-
- // Create data points for each period
- const points = cohortData.percentages.map((percentage, periodIndex) => ({
- x: periodIndex,
- y: percentage ?? null,
- }));
-
- return {
- id: formattedDate,
- data: points.filter(point => point.y !== null), // Remove null points
- color: cohortColors[index % cohortColors.length],
- };
- });
- }, [data, mode, cohortKeys]);
+ const gradientId = useId();
- if (isLoading) {
- return <RetentionChartSkeleton />;
- }
+ const columns = model.maxOffset;
+ const x = (offset: number) => ((offset - 0.5) / columns) * BOX_WIDTH;
+ const y = (pct: number) => PLOT_BOTTOM - (Math.min(pct, model.scaleMax) / model.scaleMax) * (PLOT_BOTTOM - PLOT_TOP);
+ const left = (offset: number) => `${((offset - 0.5) / columns) * 100}%`;
- if (!data || chartData.length === 0) {
- return (
- <div className="h-[400px] flex items-center justify-center">
- <div className="text-neutral-500 dark:text-neutral-400 text-sm">{t("No retention data available")}</div>
- </div>
- );
- }
+ const ticks = Array.from({ length: Math.round(model.scaleMax / model.scaleStep) + 1 }, (_, i) => i * model.scaleStep);
+
+ const averagePoints = model.average.flatMap((average, offset): Point[] =>
+ average && offset >= 1 ? [[x(offset), y(average.pct)]] : []
+ );
+ const previousPoints = (previousAverage ?? []).flatMap((average, offset): Point[] =>
+ average && offset >= 1 && offset <= columns ? [[x(offset), y(average.pct)]] : []
+ );
+ const activePoints = activeCohort
+ ? finishedCells(activeCohort).map((cell): Point => [x(cell.offset), y(cell.pct)])
+ : [];
+ const others = model.cohorts.filter(cohort => cohort.size > 0 && cohort.key !== activeCohort?.key);
- // Calculate max Y value with a little headroom
- const maxY = Math.min(
- 100,
- Math.max(...chartData.flatMap(series => series.data.map(d => (typeof d.y === "number" ? d.y : 0)))) * 1.1
+ const averageAtActive = model.average[activeOffset] ?? null;
+ const previousAtActive = previousAverage?.[activeOffset] ?? null;
+ const activeCell = activeCohort?.cells[activeOffset];
+ const cohortAtActive = activeCell && !activeCell.partial ? activeCell : null;
+
+ const dot = (key: string, offset: number, pct: number, color: string, hollow: boolean) => (
+ <span
+ key={key}
+ className={cn(
+ "pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 rounded-full",
+ hollow ? "h-2 w-2 border-2 bg-white dark:bg-neutral-900" : "h-[5px] w-[5px]"
+ )}
+ style={{
+ left: left(offset),
+ top: y(pct),
+ ...(hollow ? { borderColor: color, boxSizing: "content-box" } : { backgroundColor: color }),
+ }}
+ />
);
return (
- <div className="h-[400px] overflow-visible">
- <ResponsiveLine
- data={chartData}
- theme={nivoTheme}
- margin={{ top: 20, right: 120, bottom: 30, left: 40 }}
- xScale={{
- type: "linear",
- min: 0,
- max: "auto",
- }}
- yScale={{
- type: "linear",
- min: 0,
- max: maxY,
- stacked: false,
- }}
- curve="linear"
- axisBottom={{
- tickSize: 5,
- tickPadding: 5,
- tickRotation: 0,
- tickValues: chartData.length,
- format: value => `${value}`,
- }}
- axisLeft={{
- tickSize: 5,
- tickPadding: 5,
- tickRotation: 0,
- tickValues: 5,
- format: value => `${value}%`,
- }}
- enableGridX={true}
- gridYValues={5}
- gridXValues={Array.from({ length: data.maxPeriods + 1 }, (_, i) => i)}
- colors={{ datum: "color" }}
- enableSlices="x"
- pointSize={0}
- legends={[
- {
- anchor: "right",
- direction: "column",
- justify: false,
- translateX: 120,
- translateY: 0,
- itemsSpacing: 5,
- itemDirection: "left-to-right",
- itemWidth: 100,
- itemHeight: 20,
- itemOpacity: 0.85,
- symbolSize: 12,
- symbolShape: "circle",
- symbolBorderColor: "rgba(0, 0, 0, .5)",
- effects: [
- {
- on: "hover",
- style: {
- itemBackground: "rgba(0, 0, 0, .1)",
- itemOpacity: 1,
- },
- },
- ],
- itemTextColor: resolvedTheme === "dark" ? "hsl(var(--neutral-200))" : "hsl(var(--neutral-700))",
- },
- ]}
- sliceTooltip={({ slice }) => {
- const xValue = slice.points[0]?.data.x as number;
-
- return (
- <ChartTooltip>
- <div className="p-2 text-sm">
- <div className="font-medium mb-2 text-neutral-700 dark:text-neutral-200">
- {mode === "day" ? t("Day {value}", { value: String(xValue) }) : t("Week {value}", { value: String(xValue) })}
- </div>
- <div className="flex flex-col gap-1">
- {slice.points.map((point: any) => {
- const value = point.data.y as number | null;
- // Point ID format is "serieId.index", extract the serie ID
- const cohortLabel = String(point.id).split(".")[0];
- // Get color from chartData since point.serieColor may be undefined
- const seriesData = chartData.find(s => s.id === cohortLabel);
- const color = point.serieColor || seriesData?.color || point.color;
- return (
- <div key={point.id} className="flex justify-between items-center gap-4">
- <div className="flex items-center gap-2">
- <div className="w-1 h-3 rounded-[3px]" style={{ backgroundColor: color }} />
- <span className="text-neutral-600 dark:text-neutral-300 whitespace-nowrap">
- {cohortLabel}
- </span>
- </div>
- <span className="font-medium text-neutral-700 dark:text-neutral-200">
- {value !== null ? `${value.toFixed(1)}%` : "-"}
- </span>
- </div>
- );
- })}
- </div>
- </div>
- </ChartTooltip>
- );
- }}
- />
+ <div className={cn("grid gap-x-0.5", columnsClassName)}>
+ {/* Below md the leading columns are too narrow for the readout; the card puts it above the plot. */}
+ <div className="col-span-2 hidden pr-14 pt-2 md:block">{readout}</div>
+ <div
+ className="relative col-start-3 col-end-[-1]"
+ style={{ height: HEIGHT }}
+ role="img"
+ aria-label={
+ activeCohortLabel
+ ? t("Average retention by period since first visit, with the {cohort} cohort highlighted", {
+ cohort: activeCohortLabel,
+ })
+ : t("Average retention by period since first visit")
+ }
+ >
+ {ticks.map(tick => (
+ <span
+ key={tick}
+ className="absolute right-full mr-2 -translate-y-1/2 whitespace-nowrap text-[11px] tabular-nums text-neutral-500 dark:text-neutral-400"
+ style={{ top: y(tick) }}
+ >
+ {Number.isInteger(tick) ? tick : tick.toFixed(2).replace(/0$/, "")}%
+ </span>
+ ))}
+ <svg
+ viewBox={`0 0 ${BOX_WIDTH} ${HEIGHT}`}
+ preserveAspectRatio="none"
+ className="absolute inset-0 h-full w-full"
+ aria-hidden="true"
+ >
+ <defs>
+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0" stopColor={AVERAGE_COLOR} stopOpacity="0.2" />
+ <stop offset="1" stopColor={AVERAGE_COLOR} stopOpacity="0" />
+ </linearGradient>
+ </defs>
+ {ticks.map(tick => (
+ <line
+ key={tick}
+ x1={0}
+ x2={BOX_WIDTH}
+ y1={y(tick)}
+ y2={y(tick)}
+ className="stroke-neutral-200 dark:stroke-neutral-800"
+ strokeWidth={1}
+ strokeDasharray={tick === 0 ? undefined : "2 4"}
+ vectorEffect="non-scaling-stroke"
+ />
+ ))}
+ {others.map(cohort => {
+ const points = finishedCells(cohort).map((cell): Point => [x(cell.offset), y(cell.pct)]);
+ return points.length > 1 ? (
+ <path
+ key={cohort.key}
+ d={linePath(points)}
+ fill="none"
+ stroke="hsl(var(--dataviz) / 0.3)"
+ strokeWidth={1}
+ vectorEffect="non-scaling-stroke"
+ />
+ ) : null;
+ })}
+ {averagePoints.length > 1 && (
+ <path
+ d={`${linePath(averagePoints)}L${averagePoints[averagePoints.length - 1][0].toFixed(2)},${PLOT_BOTTOM}L${averagePoints[0][0].toFixed(2)},${PLOT_BOTTOM}Z`}
+ fill={`url(#${gradientId})`}
+ />
+ )}
+ {previousPoints.length > 1 && (
+ <path
+ d={linePath(previousPoints)}
+ fill="none"
+ stroke={PREVIOUS_COLOR}
+ strokeWidth={1.5}
+ strokeDasharray="4 4"
+ vectorEffect="non-scaling-stroke"
+ />
+ )}
+ <line
+ x1={x(activeOffset)}
+ x2={x(activeOffset)}
+ y1={0}
+ y2={HEIGHT}
+ className="stroke-neutral-300 dark:stroke-neutral-600"
+ strokeWidth={1}
+ vectorEffect="non-scaling-stroke"
+ />
+ {activePoints.length > 1 && (
+ <path
+ d={linePath(activePoints)}
+ fill="none"
+ stroke={COHORT_COLOR}
+ strokeWidth={2}
+ strokeLinejoin="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ )}
+ {averagePoints.length > 1 && (
+ <path
+ d={linePath(averagePoints)}
+ fill="none"
+ stroke={AVERAGE_COLOR}
+ strokeWidth={2.5}
+ strokeLinejoin="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ )}
+ </svg>
+ {model.average.map((average, offset) =>
+ average && offset >= 1 ? dot(`average-${offset}`, offset, average.pct, AVERAGE_COLOR, false) : null
+ )}
+ {/* A cohort with a single finished period has no line to draw. */}
+ {activeCohort && activePoints.length === 1
+ ? finishedCells(activeCohort).map(cell =>
+ dot(`cohort-${cell.offset}`, cell.offset, cell.pct, COHORT_COLOR, false)
+ )
+ : null}
+ {previousAtActive && dot("previous", activeOffset, previousAtActive.pct, PREVIOUS_COLOR, true)}
+ {cohortAtActive && dot("cohort", activeOffset, cohortAtActive.pct, COHORT_COLOR, true)}
+ {averageAtActive && dot("average", activeOffset, averageAtActive.pct, AVERAGE_COLOR, true)}
+ {/* One hover target per period column, so the crosshair follows the pointer onto the grid below. */}
+ <div
+ className="absolute inset-0 grid gap-x-0.5"
+ style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
+ onMouseLeave={() => onHoverOffset(null)}
+ >
+ {Array.from({ length: columns }, (_, index) => (
+ <div key={index} onMouseEnter={() => onHoverOffset(index + 1)} />
+ ))}
+ </div>
+ </div>
</div>
);
}
diff --git a/client/src/app/[site]/retention/RetentionGrid.tsx b/client/src/app/[site]/retention/RetentionGrid.tsx
new file mode 100644
index 000000000..e34b0ab48
--- /dev/null
+++ b/client/src/app/[site]/retention/RetentionGrid.tsx
@@ -0,0 +1,508 @@
+"use client";
+
+import { Hourglass } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { memo, RefObject, useCallback, useRef } from "react";
+import { Badge } from "../../../components/ui/badge";
+import { Popover, PopoverAnchor, PopoverContent } from "../../../components/ui/popover";
+import { cn, formatter } from "../../../lib/utils";
+import { COHORT_COLOR } from "./RetentionChart";
+import {
+ formatPercent,
+ HEAT_DARK_TEXT_FROM,
+ heatColor,
+ heatStep,
+ PeriodProgress,
+ RetentionCell,
+ RetentionCohortRow,
+ RetentionModel,
+} from "./retentionModel";
+
+export type RetentionUnit = "percent" | "users";
+
+export interface CellTarget {
+ cohort: string;
+ offset: number;
+}
+
+/** What the pointer is over: a cell, a whole cohort (its label) or a whole period (its header). */
+export interface HoverTarget {
+ cohort: string | null;
+ offset: number | null;
+}
+
+// Diagonal hatch for figures that are not final. The stripe colour is the
+// panel's, set per theme on the card (--rt-hatch).
+const HATCH = "repeating-linear-gradient(135deg, transparent 0 4px, var(--rt-hatch) 4px 6px)";
+export const HATCH_VARIABLE = "[--rt-hatch:hsl(var(--neutral-50)/0.8)] dark:[--rt-hatch:hsl(var(--neutral-900)/0.6)]";
+
+const ROW_HIGHLIGHT = "bg-neutral-100 dark:bg-neutral-850";
+// The label column stays put while the grid scrolls sideways. Its ::before
+// covers the scroller's left padding, where scrolled cells would otherwise show.
+const STICKY =
+ "sticky left-0 z-20 before:absolute before:inset-y-0 before:-left-4 before:w-4 before:bg-white dark:before:bg-neutral-900";
+const HEADER_ROWS = 3;
+
+/** A count that has to fit a grid cell: exact up to six digits, compact beyond. */
+export const formatCount = (value: number) => (value >= 100_000 ? formatter(value) : value.toLocaleString());
+
+const solid = (color: string) => `linear-gradient(${color}, ${color})`;
+
+function heatStyle(pct: number, scaleMax: number, partial: boolean) {
+ const step = heatStep(pct, scaleMax);
+ return {
+ step,
+ // Painted as an image so it sits over the cell's own base colour, which
+ // keeps the palest steps visible on the light panel.
+ style: { backgroundImage: partial ? `${HATCH}, ${solid(heatColor(step))}` : solid(heatColor(step)) },
+ textClassName: cn(
+ partial ? "text-neutral-700" : "text-neutral-900",
+ step >= HEAT_DARK_TEXT_FROM ? "dark:text-neutral-950" : partial ? "dark:text-neutral-200" : "dark:text-neutral-50"
+ ),
+ };
+}
+
+const CELL =
+ "flex h-8 items-center justify-center rounded text-xs font-medium tabular-nums bg-neutral-50 dark:bg-transparent";
+
+/** The scale's key: lowest label, the eight steps, highest label. */
+export function HeatLegend({ scaleMax }: { scaleMax: number }) {
+ return (
+ <div className="flex items-center gap-1.5 text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
+ <span>0%</span>
+ <span className="flex gap-px" aria-hidden="true">
+ {Array.from({ length: 8 }, (_, step) => (
+ <span
+ key={step}
+ className="h-2.5 w-4 bg-neutral-50 first:rounded-l-sm last:rounded-r-sm dark:bg-transparent"
+ style={{ backgroundImage: solid(heatColor(step)) }}
+ />
+ ))}
+ </span>
+ <span>{scaleMax}%</span>
+ </div>
+ );
+}
+
+/** The swatch that explains hatched cells. */
+export function HatchSwatch() {
+ return (
+ <span
+ className="inline-block h-3 w-5 shrink-0 rounded-sm bg-neutral-50 dark:bg-transparent"
+ style={{ backgroundImage: `${HATCH}, ${solid(heatColor(2))}` }}
+ aria-hidden="true"
+ />
+ );
+}
+
+interface CohortRowProps {
+ cohort: RetentionCohortRow;
+ row: number;
+ label: string;
+ title: string | undefined;
+ maxOffset: number;
+ maxSize: number;
+ scaleMax: number;
+ unit: RetentionUnit;
+ isActive: boolean;
+ /** The selected cell's offset when it is in this row. */
+ selectedOffset: number | null;
+ emptyMessage: string | null;
+ inProgressIcon: boolean;
+ cellLabel: (cohort: RetentionCohortRow, cell: RetentionCell) => string;
+ onHover: (target: HoverTarget | null) => void;
+ onSelect: (target: CellTarget | null) => void;
+ onPinCohort: (cohort: string) => void;
+ anchorRef: RefObject<HTMLButtonElement | null>;
+}
+
+const CohortRow = memo(function CohortRow({
+ cohort,
+ row,
+ label,
+ title,
+ maxOffset,
+ maxSize,
+ scaleMax,
+ unit,
+ isActive,
+ selectedOffset,
+ emptyMessage,
+ inProgressIcon,
+ cellLabel,
+ onHover,
+ onSelect,
+ onPinCohort,
+ anchorRef,
+}: CohortRowProps) {
+ const unfinished = cohort.open || cohort.clipped;
+ const stickyBackground = isActive ? ROW_HIGHLIGHT : "bg-white dark:bg-neutral-900";
+
+ return (
+ <>
+ {isActive && (
+ <div className={cn("-z-10 -mr-1 rounded-md", ROW_HIGHLIGHT)} style={{ gridRow: row, gridColumn: "1 / -1" }} />
+ )}
+ <div
+ className={cn(STICKY, "flex h-8 items-center rounded-l-md", stickyBackground)}
+ style={{ gridRow: row, gridColumn: 1 }}
+ >
+ <button
+ type="button"
+ title={title}
+ aria-pressed={isActive}
+ onClick={() => onPinCohort(cohort.key)}
+ onMouseEnter={() => onHover({ cohort: cohort.key, offset: null })}
+ onFocus={() => onHover({ cohort: cohort.key, offset: null })}
+ className={cn(
+ "flex h-full w-full min-w-0 items-center gap-1.5 rounded px-2 text-left text-xs tabular-nums outline-none focus-visible:ring-2 focus-visible:ring-neutral-400 md:text-sm dark:focus-visible:ring-neutral-500",
+ isActive ? "font-medium text-neutral-900 dark:text-neutral-50" : "text-neutral-700 dark:text-neutral-200"
+ )}
+ >
+ {isActive && (
+ <span
+ className="h-1.5 w-1.5 shrink-0 rounded-full"
+ style={{ backgroundColor: COHORT_COLOR }}
+ aria-hidden="true"
+ />
+ )}
+ <span className="truncate">{label}</span>
+ </button>
+ </div>
+ <div className="flex h-8 items-center gap-2 px-2" style={{ gridRow: row, gridColumn: 2 }}>
+ <span
+ className={cn(
+ "w-full shrink-0 text-right text-xs tabular-nums md:w-12",
+ isActive ? "font-medium text-neutral-900 dark:text-neutral-50" : "text-neutral-700 dark:text-neutral-200"
+ )}
+ >
+ {cohort.size.toLocaleString()}
+ </span>
+ <span className="hidden h-1.5 flex-1 overflow-hidden rounded-full bg-neutral-100 md:block dark:bg-neutral-800">
+ <span
+ className="block h-full rounded-full"
+ style={{
+ width: `${maxSize > 0 ? (cohort.size / maxSize) * 100 : 0}%`,
+ backgroundImage: unfinished
+ ? `${HATCH}, ${solid("hsl(var(--dataviz) / 0.3)")}`
+ : solid("hsl(var(--dataviz) / 0.62)"),
+ }}
+ />
+ </span>
+ </div>
+ {emptyMessage !== null
+ ? maxOffset >= 1 && (
+ <div
+ className="flex h-8 items-center gap-2 rounded border border-dashed border-neutral-200 px-3 text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400"
+ style={{ gridRow: row, gridColumn: "3 / -1" }}
+ >
+ {inProgressIcon && <Hourglass className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />}
+ <span className="truncate">{emptyMessage}</span>
+ </div>
+ )
+ : cohort.cells.slice(1).map(cell => {
+ const heat = heatStyle(cell.pct, scaleMax, cell.partial);
+ const isSelected = selectedOffset === cell.offset;
+ return (
+ <button
+ key={cell.offset}
+ ref={isSelected ? anchorRef : undefined}
+ type="button"
+ aria-label={cellLabel(cohort, cell)}
+ aria-pressed={isSelected}
+ onClick={() => onSelect(isSelected ? null : { cohort: cohort.key, offset: cell.offset })}
+ onMouseEnter={() => onHover({ cohort: cohort.key, offset: cell.offset })}
+ onFocus={() => onHover({ cohort: cohort.key, offset: cell.offset })}
+ className={cn(
+ CELL,
+ heat.textClassName,
+ "w-full cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-neutral-400 dark:focus-visible:ring-neutral-500",
+ isSelected &&
+ "relative z-10 ring-2 ring-neutral-900 ring-offset-2 ring-offset-white dark:ring-neutral-50 dark:ring-offset-neutral-900"
+ )}
+ style={{ ...heat.style, gridRow: row, gridColumn: cell.offset + 2 }}
+ >
+ {unit === "percent" ? formatPercent(cell.pct) : formatCount(cell.users)}
+ </button>
+ );
+ })}
+ </>
+ );
+});
+
+interface RetentionGridProps {
+ model: RetentionModel;
+ unit: RetentionUnit;
+ /** The cohort drawn on its own line in the curve; its row is marked. */
+ activeCohortKey: string | null;
+ /** The period column to band: set while one is hovered or selected. */
+ bandOffset: number | null;
+ selected: CellTarget | null;
+ onHover: (target: HoverTarget | null) => void;
+ onSelect: (target: CellTarget | null) => void;
+ onPinCohort: (cohort: string) => void;
+ cohortLabel: (key: string) => string;
+ periodLabel: (offset: number) => string;
+ formatDay: (key: string) => string;
+ /** How far the window reaches into its last period; null when that period is whole. */
+ progress: PeriodProgress | null;
+ /** The last period is partial because it is still going on, not because the range stops there. */
+ inProgress: boolean;
+ columnsClassName: string;
+}
+
+/**
+ * The cohort heat grid: one row per cohort period, one column per period since
+ * the first visit, starting at period 1. A cell opens a popover with the
+ * figures behind it.
+ */
+export function RetentionGrid({
+ model,
+ unit,
+ activeCohortKey,
+ bandOffset,
+ selected,
+ onHover,
+ onSelect,
+ onPinCohort,
+ cohortLabel,
+ periodLabel,
+ formatDay,
+ progress,
+ inProgress,
+ columnsClassName,
+}: RetentionGridProps) {
+ const t = useExtracted();
+ const anchorRef = useRef<HTMLButtonElement | null>(null);
+
+ const offsets = Array.from({ length: model.maxOffset }, (_, index) => index + 1);
+ const maxSize = Math.max(...model.cohorts.map(cohort => cohort.size), 0);
+ const isWeekly = model.mode === "week";
+
+ const selectedCohort = selected ? model.cohorts.find(cohort => cohort.key === selected.cohort) : undefined;
+ const selectedCell =
+ selectedCohort && selected && selected.offset >= 1 ? selectedCohort.cells[selected.offset] : undefined;
+ const selectedAverage = selected ? model.average[selected.offset] : null;
+ const returnPeriod =
+ selectedCohort && selectedCell ? model.cohorts[selectedCohort.index + selectedCell.offset] : undefined;
+
+ // Stable, like the other props of the memoized rows: a hover should re-render two rows, not all of them.
+ const cellLabel = useCallback(
+ (cohort: RetentionCohortRow, cell: RetentionCell) =>
+ t("{cohort} cohort, {period}: {percent}, {users} of {size} users", {
+ cohort: cohortLabel(cohort.key),
+ period: periodLabel(cell.offset),
+ percent: formatPercent(cell.pct),
+ users: formatCount(cell.users),
+ size: formatCount(cohort.size),
+ }),
+ [t, cohortLabel, periodLabel]
+ );
+
+ const emptyMessage = (cohort: RetentionCohortRow): string | null => {
+ if (cohort.size === 0) return t("No new users");
+ if (cohort.cells.length > 1) return null;
+ if (cohort.open && inProgress && progress) {
+ return isWeekly
+ ? t("Week in progress, {elapsed} of {total} days. Returns start filling in on {date}.", {
+ elapsed: String(progress.elapsedDays),
+ total: String(progress.totalDays),
+ date: formatDay(progress.nextPeriod),
+ })
+ : t("Day in progress. Returns start filling in on {date}.", { date: formatDay(progress.nextPeriod) });
+ }
+ return t("The range ends here, so there are no returns to show.");
+ };
+
+ const rowTitle = (cohort: RetentionCohortRow) =>
+ cohort.clipped
+ ? isWeekly
+ ? t("The range starts partway through this week, so this cohort misses its first days.")
+ : t("The range starts partway through this day, so this cohort misses its first hours.")
+ : undefined;
+
+ const figure = "tabular-nums text-neutral-900 dark:text-neutral-50";
+ const factLabel = "text-neutral-600 dark:text-neutral-300";
+
+ return (
+ <Popover open={!!selectedCell} onOpenChange={open => !open && onSelect(null)}>
+ {/* Anchored to whichever cell is selected, without wrapping (and remounting) it. */}
+ <PopoverAnchor virtualRef={anchorRef as RefObject<HTMLButtonElement>} />
+ <div className={cn("relative isolate grid gap-0.5", columnsClassName)} onMouseLeave={() => onHover(null)}>
+ {bandOffset !== null && bandOffset >= 1 && bandOffset <= model.maxOffset && (
+ <div
+ className="-z-10 -mx-[3px] rounded-md bg-neutral-100 dark:bg-neutral-800/70"
+ style={{ gridColumn: bandOffset + 2, gridRow: `1 / span ${HEADER_ROWS + model.cohorts.length}` }}
+ />
+ )}
+
+ <div
+ className={cn(
+ STICKY,
+ "flex h-7 items-center bg-white px-2 text-xs text-neutral-500 dark:bg-neutral-900 dark:text-neutral-400"
+ )}
+ style={{ gridRow: 1, gridColumn: 1 }}
+ >
+ <span className="truncate">{t("Cohort, by first visit")}</span>
+ </div>
+ <div
+ className="flex h-7 items-center justify-end px-1 text-xs text-neutral-500 md:justify-start md:px-2 dark:text-neutral-400"
+ style={{ gridRow: 1, gridColumn: 2 }}
+ >
+ <span className="truncate">{t("New users")}</span>
+ </div>
+ {offsets.map(offset => (
+ <div
+ key={offset}
+ onMouseEnter={() => onHover({ cohort: null, offset })}
+ className={cn(
+ "flex h-7 items-center justify-center whitespace-nowrap text-xs",
+ offset === bandOffset
+ ? "font-medium text-neutral-900 dark:text-neutral-50"
+ : "text-neutral-500 dark:text-neutral-400"
+ )}
+ style={{ gridRow: 1, gridColumn: offset + 2 }}
+ >
+ {periodLabel(offset)}
+ </div>
+ ))}
+
+ <div
+ className={cn(STICKY, "flex h-8 items-baseline gap-1.5 bg-white px-2 pt-2 dark:bg-neutral-900")}
+ style={{ gridRow: 2, gridColumn: 1 }}
+ >
+ <span className="truncate text-xs font-medium text-neutral-900 md:text-sm dark:text-neutral-50">
+ {t("All cohorts")}
+ </span>
+ <span className="hidden text-xs text-neutral-500 md:inline dark:text-neutral-400">
+ {unit === "percent" ? t("weighted") : t("total")}
+ </span>
+ </div>
+ <div className="flex h-8 items-center gap-2 px-2" style={{ gridRow: 2, gridColumn: 2 }}>
+ <span className="w-full shrink-0 text-right text-xs font-medium tabular-nums text-neutral-900 md:w-12 dark:text-neutral-50">
+ {model.totalNew.toLocaleString()}
+ </span>
+ <span className="hidden text-xs text-neutral-500 md:inline dark:text-neutral-400">{t("total")}</span>
+ </div>
+ {offsets.map(offset => {
+ const average = model.average[offset];
+ if (!average) {
+ return (
+ <div
+ key={offset}
+ onMouseEnter={() => onHover({ cohort: null, offset })}
+ className="flex h-8 items-center justify-center text-xs text-neutral-500 dark:text-neutral-400"
+ style={{ gridRow: 2, gridColumn: offset + 2 }}
+ >
+ {t("n/a")}
+ </div>
+ );
+ }
+ const heat = heatStyle(average.pct, model.scaleMax, false);
+ return (
+ <div
+ key={offset}
+ onMouseEnter={() => onHover({ cohort: null, offset })}
+ title={t("{users} of {size} new users, across the cohorts that have finished {period}", {
+ users: average.users.toLocaleString(),
+ size: average.size.toLocaleString(),
+ period: isWeekly
+ ? t("week {index}", { index: String(offset) })
+ : t("day {index}", { index: String(offset) }),
+ })}
+ className={cn(CELL, heat.textClassName)}
+ style={{ ...heat.style, gridRow: 2, gridColumn: offset + 2 }}
+ >
+ {unit === "percent" ? formatPercent(average.pct) : formatCount(average.users)}
+ </div>
+ );
+ })}
+
+ <div className="my-1 h-px bg-neutral-100 dark:bg-neutral-800" style={{ gridRow: 3, gridColumn: "1 / -1" }} />
+
+ {model.cohorts.map(cohort => (
+ <CohortRow
+ key={cohort.key}
+ cohort={cohort}
+ row={HEADER_ROWS + 1 + cohort.index}
+ label={cohortLabel(cohort.key)}
+ title={rowTitle(cohort)}
+ maxOffset={model.maxOffset}
+ maxSize={maxSize}
+ scaleMax={model.scaleMax}
+ unit={unit}
+ isActive={cohort.key === activeCohortKey}
+ selectedOffset={selectedCell && selected?.cohort === cohort.key ? selected.offset : null}
+ emptyMessage={emptyMessage(cohort)}
+ inProgressIcon={cohort.open && inProgress}
+ cellLabel={cellLabel}
+ onHover={onHover}
+ onSelect={onSelect}
+ onPinCohort={onPinCohort}
+ anchorRef={anchorRef}
+ />
+ ))}
+ </div>
+
+ {selectedCohort && selectedCell && (
+ <PopoverContent
+ side="bottom"
+ align="start"
+ sideOffset={8}
+ className="w-[296px] p-0"
+ aria-label={t("Cohort cell details")}
+ // The cell keeps focus and toggles itself; without this a click on it would close and reopen.
+ onOpenAutoFocus={event => event.preventDefault()}
+ onInteractOutside={event => {
+ if (anchorRef.current?.contains(event.target as Node)) event.preventDefault();
+ }}
+ >
+ <div className="px-3 pb-2 pt-2.5">
+ <div className="flex items-center justify-between gap-2">
+ <span className="truncate text-sm font-medium">
+ {t("{cohort} cohort", { cohort: cohortLabel(selectedCohort.key) })}
+ </span>
+ <Badge variant="outline" className="shrink-0">
+ {periodLabel(selectedCell.offset)}
+ </Badge>
+ </div>
+ {returnPeriod && (
+ <div className="mt-0.5 text-xs text-neutral-500 dark:text-neutral-400">
+ {t("Active again {period}", { period: cohortLabel(returnPeriod.key) })}
+ </div>
+ )}
+ </div>
+ <div className="space-y-1.5 border-t border-neutral-100 px-3 py-2.5 text-xs dark:border-neutral-700">
+ <div className="flex items-center justify-between gap-3">
+ <span className={factLabel}>{selectedCell.partial ? t("Came back so far") : t("Came back")}</span>
+ <span className={cn("tabular-nums", factLabel)}>
+ <span className={cn("font-medium", figure)}>{selectedCell.users.toLocaleString()}</span>{" "}
+ {t("of {size}", { size: selectedCohort.size.toLocaleString() })}
+ {" · "}
+ <span className={cn("font-medium", figure)}>{formatPercent(selectedCell.pct)}</span>
+ </span>
+ </div>
+ <div className="flex items-center justify-between gap-3">
+ <span className={factLabel}>
+ {t("Average for {period}", { period: periodLabel(selectedCell.offset) })}
+ </span>
+ <span className={figure}>{selectedAverage ? formatPercent(selectedAverage.pct) : t("n/a")}</span>
+ </div>
+ <div className="flex items-center justify-between gap-3">
+ <span className={factLabel}>{selectedCell.partial ? t("Not back yet") : t("Did not come back")}</span>
+ <span className={figure}>{(selectedCohort.size - selectedCell.users).toLocaleString()}</span>
+ </div>
+ </div>
+ {selectedCell.partial && (
+ <div className="flex items-center gap-2 border-t border-neutral-100 px-3 py-2 text-xs text-neutral-500 dark:border-neutral-700 dark:text-neutral-400">
+ <HatchSwatch />
+ {inProgress
+ ? t("Still in progress, so this figure will rise.")
+ : t("The range ends partway through this period.")}
+ </div>
+ )}
+ </PopoverContent>
+ )}
+ </Popover>
+ );
+}
diff --git a/client/src/app/[site]/retention/page.test.tsx b/client/src/app/[site]/retention/page.test.tsx
new file mode 100644
index 000000000..48d383190
--- /dev/null
+++ b/client/src/app/[site]/retention/page.test.tsx
@@ -0,0 +1,237 @@
+import React from "react";
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { ProcessedRetentionData } from "@/api/analytics/endpoints";
+import { useStore } from "@/lib/store";
+
+type QueryState = { data?: ProcessedRetentionData; isLoading: boolean; isError: boolean; refetch: () => void };
+type HookOptions = { periodTime?: "current" | "previous"; enabled?: boolean };
+
+const mocks = vi.hoisted(() => ({
+ current: {} as QueryState,
+ previous: undefined as ProcessedRetentionData | undefined,
+ calls: [] as { mode: string; options?: HookOptions }[],
+}));
+
+// Fills {placeholders} and drops rich-text tags, so assertions read like the screen.
+const translate = (message: string, values?: Record<string, unknown>) =>
+ message.replace(/<\/?\w+>/g, "").replace(/\{(\w+)\}/g, (_, key: string) => String(values?.[key] ?? `{${key}}`));
+vi.mock("next-intl", () => ({
+ useExtracted: () => Object.assign(translate, { rich: translate }),
+ useLocale: () => "en",
+}));
+vi.mock("@/api/analytics/hooks/useGetRetention", () => ({
+ useGetRetention: (mode: string, options?: HookOptions) => {
+ mocks.calls.push({ mode, options });
+ if (options?.periodTime === "previous") return { data: options.enabled === false ? undefined : mocks.previous };
+ return mocks.current;
+ },
+}));
+vi.mock("@/hooks/useSetPageTitle", () => ({ useSetPageTitle: () => {} }));
+vi.mock("@/components/DisabledOverlay", () => ({
+ DisabledOverlay: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}));
+vi.mock("@/components/site/CompareControl", () => ({ CompareControl: () => <div data-testid="compare" /> }));
+vi.mock("../components/SubHeader/SubHeader", () => ({ SubHeader: () => <div data-testid="sub-header" /> }));
+
+import RetentionPage from "./page";
+
+const WEEKS = ["2026-08-31", "2026-09-07", "2026-09-14", "2026-09-21", "2026-09-28"];
+
+function response(
+ counts: Record<string, number[]>,
+ overrides: Partial<ProcessedRetentionData> = {}
+): ProcessedRetentionData {
+ const periods = overrides.periods ?? WEEKS;
+ const cohorts: ProcessedRetentionData["cohorts"] = {};
+ for (const [key, values] of Object.entries(counts)) {
+ const padded = periods.map((_, offset) => values[offset] ?? null);
+ cohorts[key] = {
+ size: values[0],
+ counts: padded,
+ percentages: padded.map(value => (value === null ? null : (value / values[0]) * 100)),
+ };
+ }
+ return {
+ cohorts,
+ maxPeriods: periods.length - 1,
+ mode: "week",
+ range: 31,
+ periods,
+ windowStart: "2026-08-31T00:00:00.000Z",
+ windowEnd: "2026-09-30T15:00:00.000Z",
+ timeZone: "UTC",
+ firstPeriodPartial: false,
+ lastPeriodPartial: true,
+ lastPeriodInProgress: true,
+ truncated: false,
+ lookbackDays: 90,
+ ...overrides,
+ };
+}
+
+const populated = () =>
+ response({
+ "2026-08-31": [1000, 200, 100, 80, 20],
+ "2026-09-07": [1000, 100, 60, 10],
+ "2026-09-14": [2000, 200, 30],
+ "2026-09-21": [1000, 40],
+ "2026-09-28": [400],
+ });
+
+const settled = (data: ProcessedRetentionData): QueryState => ({
+ data,
+ isLoading: false,
+ isError: false,
+ refetch: vi.fn(),
+});
+
+beforeEach(() => {
+ mocks.current = settled(populated());
+ mocks.previous = undefined;
+ mocks.calls = [];
+ useStore.setState({
+ site: "1",
+ time: { mode: "range", startDate: "2026-08-31", endDate: "2026-09-30" },
+ previousTime: { mode: "range", startDate: "2026-07-31", endDate: "2026-08-30" },
+ filters: [],
+ });
+});
+
+afterEach(cleanup);
+
+describe("RetentionPage", () => {
+ it("takes its period from the sub-header and defaults to weekly cohorts on a month", () => {
+ render(<RetentionPage />);
+
+ expect(screen.getByTestId("sub-header")).toBeTruthy();
+ expect(mocks.calls[0]).toMatchObject({ mode: "week" });
+ expect(mocks.calls.some(call => call.options?.periodTime === "previous")).toBe(true);
+ });
+
+ it("defaults to daily cohorts on a short range", () => {
+ useStore.setState({ time: { mode: "range", startDate: "2026-09-24", endDate: "2026-09-30" } });
+ render(<RetentionPage />);
+
+ expect(mocks.calls[0]).toMatchObject({ mode: "day" });
+ });
+
+ it("states the average retention, cohort size and best cohort", () => {
+ render(<RetentionPage />);
+
+ const stat = (label: string) => screen.getByText(label).parentElement!.parentElement!;
+ expect(within(stat("Week 1 retention")).getByText("12.5%")).toBeTruthy();
+ expect(within(stat("Week 2 retention")).getByText("8.0%")).toBeTruthy();
+ expect(within(stat("Avg. cohort size")).getByText("1,250")).toBeTruthy();
+ expect(within(stat("Best cohort")).getByText("Aug 31 – Sep 6")).toBeTruthy();
+ expect(within(stat("Best cohort")).getByText("20.0% came back in week 1")).toBeTruthy();
+ });
+
+ it("shows deltas against the comparison period", () => {
+ mocks.previous = response({
+ "2026-08-31": [800, 80, 40, 30, 10],
+ "2026-09-07": [800, 80, 40, 10],
+ "2026-09-14": [800, 80, 10],
+ "2026-09-21": [800, 10],
+ "2026-09-28": [300],
+ });
+ render(<RetentionPage />);
+
+ const weekOne = screen.getByText("Week 1 retention").parentElement!.parentElement!;
+ // 12.5% against 10.0% in the comparison period.
+ expect(within(weekOne).getByText("+2.5 pp")).toBeTruthy();
+ expect(within(weekOne).getByText(/^10\.0% in /)).toBeTruthy();
+ });
+
+ it("does not ask for a comparison on all time", () => {
+ useStore.setState({ time: { mode: "all-time" }, previousTime: { mode: "all-time" } });
+ render(<RetentionPage />);
+
+ expect(mocks.calls.find(call => call.options?.periodTime === "previous")?.options?.enabled).toBe(false);
+ });
+
+ it("draws the grid from period 1 and hatches the period in progress instead of calling it final", () => {
+ render(<RetentionPage />);
+
+ expect(screen.queryByText("Week 0")).toBeNull();
+ const finished = screen.getByRole("button", { name: "Aug 31 – Sep 6 cohort, Week 1: 20.0%, 200 of 1,000 users" });
+ const inProgress = screen.getByRole("button", { name: "Sep 21 – Sep 27 cohort, Week 1: 4.0%, 40 of 1,000 users" });
+ expect(finished.style.backgroundImage).not.toContain("repeating-linear-gradient");
+ expect(inProgress.style.backgroundImage).toContain("repeating-linear-gradient");
+ expect(screen.getByText("Week in progress, 3 of 7 days. Returns start filling in on Oct 5.")).toBeTruthy();
+ expect(screen.getByText("In progress: the week of Sep 28 has 3 of 7 days")).toBeTruthy();
+ });
+
+ it("switches the cells between percent and retained users", () => {
+ render(<RetentionPage />);
+
+ const cell = screen.getByRole("button", { name: "Aug 31 – Sep 6 cohort, Week 1: 20.0%, 200 of 1,000 users" });
+ expect(cell.textContent).toBe("20.0%");
+ fireEvent.click(screen.getByRole("radio", { name: "Users" }));
+ expect(cell.textContent).toBe("200");
+ });
+
+ it("opens a popover with the figures behind a cell", () => {
+ render(<RetentionPage />);
+
+ fireEvent.click(screen.getByRole("button", { name: "Aug 31 – Sep 6 cohort, Week 2: 10.0%, 100 of 1,000 users" }));
+
+ const popover = screen.getByRole("dialog", { name: "Cohort cell details" });
+ expect(within(popover).getByText("Aug 31 – Sep 6 cohort")).toBeTruthy();
+ expect(within(popover).getByText("Active again Sep 14 – Sep 20")).toBeTruthy();
+ expect(within(popover).getByText("Came back")).toBeTruthy();
+ expect(within(popover).getByText("Did not come back").nextElementSibling?.textContent).toBe("900");
+ expect(within(popover).getByText("Average for Week 2").nextElementSibling?.textContent).toBe("8.0%");
+ });
+
+ it("calls out the largest cohort when it retains differently, and highlights it on request", () => {
+ render(<RetentionPage />);
+
+ expect(
+ screen.getByText(
+ "The Sep 14 – Sep 20 cohort is your largest at 2,000 new users, but only 10.0% came back in week 1, 2.5 pp under average."
+ )
+ ).toBeTruthy();
+ const row = screen.getByRole("button", { name: "Sep 14 – Sep 20" });
+ expect(row.getAttribute("aria-pressed")).toBe("false");
+ fireEvent.click(screen.getByRole("button", { name: "View cohort" }));
+ expect(row.getAttribute("aria-pressed")).toBe("true");
+ });
+
+ it("keeps the controls live and shows skeletons while loading", () => {
+ mocks.current = { isLoading: true, isError: false, refetch: vi.fn() };
+ const { container } = render(<RetentionPage />);
+
+ expect(screen.getByRole("radio", { name: "Daily" })).toBeTruthy();
+ expect(container.querySelector('[aria-busy="true"]')).toBeTruthy();
+ expect(screen.getByText("Week 1 retention")).toBeTruthy();
+ });
+
+ it("asks for a longer range when the range holds a single period", () => {
+ mocks.current = settled(response({ "2026-09-28": [400] }, { periods: ["2026-09-28"] }));
+ render(<RetentionPage />);
+
+ expect(screen.getByText("This range is too short for retention")).toBeTruthy();
+ expect(screen.queryByText("Week 1 retention")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Last 60 Days" }));
+ expect(useStore.getState().time).toMatchObject({ mode: "range", wellKnown: "last-60-days" });
+ });
+
+ it("says so when the range has no new users", () => {
+ mocks.current = settled(response({}));
+ render(<RetentionPage />);
+
+ expect(screen.getByText("No new users in this range")).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Export CSV" }).hasAttribute("disabled")).toBe(true);
+ });
+
+ it("shows the error state with a retry", () => {
+ const refetch = vi.fn();
+ mocks.current = { isLoading: false, isError: true, refetch };
+ render(<RetentionPage />);
+
+ expect(screen.getByText("Failed to load retention data")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: /Try Again/ }));
+ expect(refetch).toHaveBeenCalled();
+ });
+});
diff --git a/client/src/app/[site]/retention/page.tsx b/client/src/app/[site]/retention/page.tsx
index 33997b475..4bbb806b1 100644
--- a/client/src/app/[site]/retention/page.tsx
+++ b/client/src/app/[site]/retention/page.tsx
@@ -1,266 +1,346 @@
"use client";
+import {
+ ArrowRight,
+ CalendarClock,
+ CalendarRange,
+ ChartColumnDecreasing,
+ Download,
+ Repeat,
+ Trophy,
+ Users,
+} from "lucide-react";
+import { DateTime } from "luxon";
import { useExtracted } from "next-intl";
-import { ChartColumnDecreasing } from "lucide-react";
-import { DateTime } from "luxon"; // Import Luxon for date formatting
-import { Fragment, useMemo, useState } from "react";
-import { useGetRetention } from "../../../api/analytics/hooks/useGetRetention";
+import { ReactNode, useCallback, useMemo, useState } from "react";
import { RetentionMode } from "../../../api/analytics/endpoints";
+import { useGetRetention } from "../../../api/analytics/hooks/useGetRetention";
+import { usePresetLabels } from "../../../components/DateSelector/presets";
+import { describeComparisonWindow } from "../../../components/DateSelector/rangeFields";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
-import { ThreeDotLoader } from "../../../components/Loaders";
-import { NothingFound } from "../../../components/NothingFound";
+import { ErrorState } from "../../../components/ErrorState";
import { SegmentedControl } from "../../../components/interior/segmented-control";
-import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../components/ui/select";
+import { NothingFound } from "../../../components/NothingFound";
+import { AnalysisBar } from "../../../components/site/AnalysisBar";
+import { InsightRow } from "../../../components/site/InsightRow";
+import { StatBand, StatBandCell } from "../../../components/site/StatBand";
+import { Button } from "../../../components/ui/button";
+import { Card } from "../../../components/ui/card";
+import { Skeleton } from "../../../components/ui/skeleton";
+import { useDateTimeFormat } from "../../../hooks/useDateTimeFormat";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
-import { MobileSidebar } from "../components/Sidebar/MobileSidebar";
-import { RetentionChart } from "./RetentionChart";
-import { ErrorState } from "../../../components/ErrorState";
-
-// Dynamic color function that creates a smooth gradient based on retention percentage
-const getRetentionColor = (
- percentage: number | null,
- isDark: boolean
-): { backgroundColor: string; textColor: string } => {
- if (percentage === null || isNaN(percentage)) {
- return {
- backgroundColor: isDark ? "rgb(38, 38, 38)" : "rgb(250, 250, 250)", // bg-neutral-800 : bg-neutral-50
- textColor: "transparent",
- };
- }
-
- if (percentage === 0) {
- return {
- backgroundColor: isDark ? "rgb(38, 38, 38)" : "rgb(250, 250, 250)", // bg-neutral-800 : bg-neutral-50
- textColor: isDark ? "white" : "rgb(64, 64, 64)",
- };
- }
+import { getDashboardTimeForRange } from "../../../lib/defaultTimeRange";
+import { percentDelta, pointDelta } from "../../../lib/delta";
+import { downloadCSV } from "../../../lib/export";
+import { SESSION_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { useStore, useTimezone } from "../../../lib/store";
+import { SubHeader } from "../components/SubHeader/SubHeader";
+import { RetentionCard } from "./RetentionCard";
+import {
+ buildRetentionModel,
+ defaultRetentionMode,
+ findCohortOutlier,
+ formatPercent,
+ periodDays,
+ retentionCsv,
+ statOffsets,
+} from "./retentionModel";
- // The base emerald-500 color in RGB
- const emerald = "rgb(16, 185, 129)"; // emerald-500
+const NO_VALUE = "—";
+const LONGER_RANGES = ["last-30-days", "last-60-days"] as const;
- // Calculate both linear and logarithmic scales
- const linearScale = percentage / 100;
- const logScale = Math.log(percentage + 1) / Math.log(101);
-
- // Blend between logarithmic and linear (60% log, 40% linear)
- // This creates a less extreme logarithmic effect
- const blendedScale = logScale * 0.6 + linearScale * 0.4;
-
- // Scale the blended value to get appropriate opacity (min 0.1, max 1.0)
- const scaledOpacity = 0.1 + blendedScale * 0.9;
-
- // Use the scaled opacity for the background color
- return {
- backgroundColor: `rgba(16, 185, 129, ${scaledOpacity.toFixed(2)})`,
- textColor: isDark ? "white" : "black",
- };
-};
+function RetentionCardSkeleton() {
+ return (
+ <Card aria-busy="true">
+ <div className="space-y-2 p-4 pb-3">
+ <Skeleton className="h-4 w-48 rounded" />
+ <Skeleton className="h-4 w-80 max-w-full rounded" />
+ </div>
+ <div className="space-y-1.5 px-4 pb-4">
+ <Skeleton className="h-[204px] w-full rounded" />
+ {Array.from({ length: 8 }, (_, index) => (
+ <Skeleton key={index} className="h-8 w-full rounded" />
+ ))}
+ </div>
+ </Card>
+ );
+}
export default function RetentionPage() {
const t = useExtracted();
useSetPageTitle("Retention");
- // State for the retention mode (day or week)
- const [mode, setMode] = useState<RetentionMode>("week");
- // State for the data time range (days)
- const [timeRange, setTimeRange] = useState<number>(30);
+ const time = useStore(state => state.time);
+ const previousTime = useStore(state => state.previousTime);
+ const setTime = useStore(state => state.setTime);
+ const hasFilters = useStore(state => state.filters.length > 0);
+ const timezone = useTimezone();
+ const presetLabels = usePresetLabels();
+ const { formatDateTime } = useDateTimeFormat();
- // Check if dark mode is active
- const [isDark, setIsDark] = useState(true);
+ // Daily for a short range and weekly for a long one, until the viewer picks.
+ const [chosenMode, setChosenMode] = useState<RetentionMode | null>(null);
+ const mode = chosenMode ?? defaultRetentionMode(time, timezone);
+ const [pinnedCohort, setPinnedCohort] = useState<string | null>(null);
- // Detect theme on client side
- if (typeof window !== "undefined") {
- const checkTheme = () => {
- const isDarkMode = document.documentElement.classList.contains("dark");
- if (isDarkMode !== isDark) {
- setIsDark(isDarkMode);
- }
- };
- checkTheme();
- }
+ const { data, isLoading, isError, refetch } = useGetRetention(mode);
+ // All time has no earlier period: its "previous" is all time again.
+ const { data: previousData } = useGetRetention(mode, { periodTime: "previous", enabled: time.mode !== "all-time" });
- // Use the updated hook without the limit parameter
- const { data, isLoading, isError } = useGetRetention(mode, timeRange);
+ // The response says which mode it holds, so labels never run ahead of the grid.
+ const model = useMemo(() => (data ? buildRetentionModel(data) : null), [data]);
+ const previousModel = useMemo(
+ () => (previousData && previousTime && time.mode !== "all-time" ? buildRetentionModel(previousData) : null),
+ [previousData, previousTime, time.mode]
+ );
+ const dataMode = model?.mode ?? mode;
+ const isWeekly = dataMode === "week";
+ const lastPeriodYear = data?.periods.length ? DateTime.fromISO(data.periods[data.periods.length - 1]).year : null;
- // Get sorted cohort keys (oldest first)
- const cohortKeys = useMemo(
- () => (data?.cohorts ? Object.keys(data.cohorts).sort((a, b) => a.localeCompare(b)) : []),
- [data?.cohorts]
+ const cohortLabel = useCallback(
+ (key: string) => {
+ const { first, last } = periodDays(key, dataMode);
+ if (dataMode === "day") return formatDateTime(first, { weekday: "short", month: "short", day: "numeric" });
+ // The year is only worth its width on a range that crosses into another one.
+ const year = first.year !== lastPeriodYear ? ({ year: "numeric" } as const) : {};
+ return `${formatDateTime(first, { month: "short", day: "numeric", ...year })} – ${formatDateTime(last, { month: "short", day: "numeric" })}`;
+ },
+ [dataMode, formatDateTime, lastPeriodYear]
+ );
+ const formatDay = useCallback(
+ (key: string) => formatDateTime(DateTime.fromISO(key), { month: "short", day: "numeric" }),
+ [formatDateTime]
);
+ const periodLabel = useCallback(
+ (offset: number) =>
+ dataMode === "week" ? t("Week {index}", { index: String(offset) }) : t("Day {index}", { index: String(offset) }),
+ [dataMode, t]
+ );
+ // The same, as it reads inside a sentence.
+ const periodName = (offset: number) =>
+ dataMode === "week" ? t("week {index}", { index: String(offset) }) : t("day {index}", { index: String(offset) });
- // Function to format date based on mode
- const formatDate = (dateStr: string) => {
- const startDate = DateTime.fromISO(dateStr);
- if (mode === "day") {
- return startDate.toFormat("MMM dd, yyyy");
- } else {
- // For weekly mode, show start and end dates of the week
- const endDate = startDate.plus({ days: 6 }); // End of week (7 days total)
+ const hasGrid = !!model && model.cohorts.length >= 2 && model.totalNew > 0;
+ const outlier = hasGrid ? findCohortOutlier(model) : null;
+ const comparisonWindow = previousModel ? describeComparisonWindow(previousTime, time, timezone) : null;
- // If same month, don't repeat month name
- if (startDate.month === endDate.month) {
- return `${startDate.toFormat("MMM dd")} - ${endDate.toFormat("dd, yyyy")}`;
- } else if (startDate.year === endDate.year) {
- // Different months, same year
- return `${startDate.toFormat("MMM dd")} - ${endDate.toFormat("MMM dd, yyyy")}`;
- } else {
- // Different years
- return `${startDate.toFormat("MMM dd, yyyy")} - ${endDate.toFormat("MMM dd, yyyy")}`;
- }
- }
+ const periodStat = (offset: number, icon: ReactNode): StatBandCell => {
+ const current = model?.average[offset] ?? null;
+ const previous = previousModel?.average[offset] ?? null;
+ const period = periodLabel(offset);
+ return {
+ id: `period-${offset}`,
+ icon,
+ label: t("{period} retention", { period }),
+ value: current ? formatPercent(current.pct) : NO_VALUE,
+ delta: current && previous ? pointDelta(current.pct, previous.pct) : null,
+ sub: !current
+ ? t("No cohort has finished {period} yet", { period: periodName(offset) })
+ : previous
+ ? comparisonWindow
+ ? t("{value} in {window}", { value: formatPercent(previous.pct), window: comparisonWindow })
+ : t("{value} in the comparison period", { value: formatPercent(previous.pct) })
+ : t("{users} of {size} new users", {
+ users: current.users.toLocaleString(),
+ size: current.size.toLocaleString(),
+ }),
+ title: current
+ ? t("{users} of {size} new users, across the cohorts that have finished {period}", {
+ users: current.users.toLocaleString(),
+ size: current.size.toLocaleString(),
+ period: periodName(offset),
+ })
+ : undefined,
+ };
};
- // Labels for column headers based on mode
- const getPeriodLabel = (index: number) => {
- return mode === "day" ? t("Day {index}", { index: String(index) }) : t("Week {index}", { index: String(index) });
- };
+ const [firstOffset, secondOffset, thirdOffset] = statOffsets(dataMode, model);
+ const bestCell = model?.best?.cells[1];
+ const stats: StatBandCell[] = [
+ periodStat(firstOffset, <Repeat className="h-3 w-3" />),
+ periodStat(secondOffset, <CalendarRange className="h-3 w-3" />),
+ periodStat(thirdOffset, <CalendarClock className="h-3 w-3" />),
+ {
+ id: "cohort-size",
+ icon: <Users className="h-3 w-3" />,
+ label: t("Avg. cohort size"),
+ value: model?.averageSize != null ? Math.round(model.averageSize).toLocaleString() : NO_VALUE,
+ delta: percentDelta(model?.averageSize, previousModel?.averageSize),
+ sub: isWeekly ? t("new users per week") : t("new users per day"),
+ title: isWeekly
+ ? t("Mean size of the cohorts whose week lies wholly inside the range")
+ : t("Mean size of the cohorts whose day lies wholly inside the range"),
+ },
+ {
+ id: "best-cohort",
+ icon: <Trophy className="h-3 w-3" />,
+ label: t("Best cohort"),
+ value: model?.best ? cohortLabel(model.best.key) : NO_VALUE,
+ sub:
+ model?.best && bestCell
+ ? isWeekly
+ ? t("{value} came back in week 1", { value: formatPercent(bestCell.pct) })
+ : t("{value} came back on day 1", { value: formatPercent(bestCell.pct) })
+ : t("No cohort has finished {period} yet", { period: periodName(1) }),
+ title: isWeekly
+ ? t("Highest week 1 retention among cohorts at least half the average size")
+ : t("Highest day 1 retention among cohorts at least half the average size"),
+ },
+ ];
- const handleRangeChange = (value: string) => {
- setTimeRange(parseInt(value));
+ const exportCsv = () => {
+ if (!model || !data) return;
+ const { columns, rows } = retentionCsv(model);
+ const first = data.periods[0];
+ const last = data.periods[data.periods.length - 1];
+ downloadCSV(`retention-${model.mode === "week" ? "weekly" : "daily"}-${first}-to-${last}.csv`, rows, columns);
};
- // Rendered above every state (data, empty, error) so the controls the empty
- // state points to are always there. An element, not an inline component:
- // an inline component remounts each render, dropping focus and the thumb's
- // slide. The controls stay live while a query loads (a new choice just
- // changes the query key); the loading region is marked aria-busy instead.
- const filterControls = (
- <div className="flex justify-between items-center">
- <div>
- <MobileSidebar />
- </div>
- <div className="flex items-center gap-3 flex-wrap justify-end">
- <div className="flex items-center gap-2">
- <Select value={timeRange.toString()} onValueChange={handleRangeChange}>
- <SelectTrigger id="time-range">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="7">{t("Last 7 days")}</SelectItem>
- <SelectItem value="14">{t("Last 14 days")}</SelectItem>
- <SelectItem value="30">{t("Last 30 days")}</SelectItem>
- <SelectItem value="60">{t("Last 60 days")}</SelectItem>
- <SelectItem value="90">{t("Last 90 days")}</SelectItem>
- <SelectItem value="180">{t("Last 6 months")}</SelectItem>
- <SelectItem value="365">{t("Last 1 year")}</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <SegmentedControl<RetentionMode>
- aria-label={t("Cohort period")}
- options={[
- { value: "day", label: t("Daily") },
- { value: "week", label: t("Weekly") },
- ]}
- value={mode}
- onValueChange={setMode}
- />
- </div>
- </div>
+ const outlierName = (chunks: ReactNode) => (
+ <span className="font-medium text-neutral-900 dark:text-neutral-50">{chunks}</span>
);
-
- const isEmpty = !!data && (!data.cohorts || cohortKeys.length === 0);
-
- const periodHeaders =
- !isLoading && data ? Array.from({ length: data.maxPeriods + 1 }, (_, i) => getPeriodLabel(i)) : [];
+ const outlierValues = outlier && {
+ cohort: cohortLabel(outlier.cohort.key),
+ size: outlier.cohort.size.toLocaleString(),
+ value: formatPercent(outlier.pct),
+ difference: `${Math.abs(outlier.difference).toFixed(1)} pp`,
+ name: outlierName,
+ };
return (
<DisabledOverlay message="Retention" featurePath="retention">
- <div className="p-2 md:p-4 max-w-[1300px] mx-auto flex flex-col gap-3">
- {filterControls}
+ <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
+ <SubHeader availableFilters={SESSION_PAGE_FILTERS} />
+
+ {(isLoading || hasGrid) && !isError && <StatBand cells={stats} isLoading={isLoading} />}
+
+ {/* Always rendered, and live while a query loads: a new choice only changes the query key. */}
+ <AnalysisBar
+ end={
+ <Button
+ variant="ghost"
+ size="sm"
+ className="gap-1.5 font-normal text-neutral-600 dark:text-neutral-300"
+ onClick={exportCsv}
+ disabled={!hasGrid}
+ >
+ <Download />
+ {t("Export CSV")}
+ </Button>
+ }
+ >
+ <span className="mx-1 hidden h-5 w-px bg-neutral-200 sm:block dark:bg-neutral-800" aria-hidden="true" />
+ <SegmentedControl<RetentionMode>
+ aria-label={t("Cohort period")}
+ size="sm"
+ options={[
+ { value: "day", label: t("Daily") },
+ { value: "week", label: t("Weekly") },
+ ]}
+ value={mode}
+ onValueChange={setChosenMode}
+ />
+ </AnalysisBar>
+
+ {outlier && outlierValues && (
+ <InsightRow
+ action={
+ <Button variant="ghost" size="xs" className="gap-1" onClick={() => setPinnedCohort(outlier.cohort.key)}>
+ {t("View cohort")}
+ <ArrowRight />
+ </Button>
+ }
+ >
+ {isWeekly
+ ? outlier.difference < 0
+ ? t.rich(
+ "The <name>{cohort}</name> cohort is your largest at {size} new users, but only {value} came back in week 1, {difference} under average.",
+ outlierValues
+ )
+ : t.rich(
+ "The <name>{cohort}</name> cohort is your largest at {size} new users, and {value} came back in week 1, {difference} above average.",
+ outlierValues
+ )
+ : outlier.difference < 0
+ ? t.rich(
+ "The <name>{cohort}</name> cohort is your largest at {size} new users, but only {value} came back on day 1, {difference} under average.",
+ outlierValues
+ )
+ : t.rich(
+ "The <name>{cohort}</name> cohort is your largest at {size} new users, and {value} came back on day 1, {difference} above average.",
+ outlierValues
+ )}
+ </InsightRow>
+ )}
+
{isError ? (
<Card>
- <CardContent>
- <ErrorState
- title={t("Failed to load retention data")}
- message={t("There was a problem fetching the retention data. Please try again later.")}
- />
- </CardContent>
+ <ErrorState
+ title={t("Failed to load retention data")}
+ message={t("There was a problem fetching the retention data. Please try again later.")}
+ refetch={refetch}
+ />
</Card>
- ) : isEmpty ? (
- <NothingFound
- icon={<ChartColumnDecreasing className="w-10 h-10" />}
- title={t("No retention data available")}
- description={t("Try selecting a different time range or make sure you have tracking data in the system.")}
- />
- ) : (
- <>
- <Card className="overflow-visible" aria-busy={isLoading}>
- <CardHeader className="flex flex-row items-center justify-between pb-2">
- <CardTitle>{t("Retention")}</CardTitle>
- </CardHeader>
- <CardContent className="space-y-6 overflow-visible">
- {isLoading ? (
- <ThreeDotLoader />
- ) : data ? (
- <RetentionChart data={data} isLoading={false} mode={mode} />
- ) : null}
- </CardContent>
- </Card>
- <Card className="pt-3" aria-busy={isLoading}>
- <CardContent className="space-y-6 px-2">
- <div>
- {isLoading ? (
- <ThreeDotLoader />
- ) : data ? (
- <div className="overflow-x-auto">
- <div
- className="inline-grid gap-px bg-neutral-50 dark:bg-neutral-900 rounded-lg"
- style={{
- gridTemplateColumns: `minmax(120px, auto) repeat(${data.maxPeriods + 1}, minmax(80px, auto))`,
- }}
- >
- {/* Header Row */}
- <div className="p-2 text-sm font-semibold bg-white dark:bg-neutral-900 text-neutral-600 dark:text-neutral-100 text-center sticky left-0 z-10 border-b border-r border-neutral-50 dark:border-neutral-700">
- {t("Cohort")}
- </div>
- {periodHeaders.map(header => (
- <div
- key={header}
- className="p-2 text-sm bg-white dark:bg-neutral-900 text-neutral-600 dark:text-neutral-100 text-center border-b border-neutral-50 dark:border-neutral-700"
- >
- {header}
- </div>
- ))}
-
- {/* Data Rows */}
- {cohortKeys.map(cohortPeriod => (
- <Fragment key={cohortPeriod}>
- {/* Cohort Info Cell */}
- <div className="p-2 bg-white dark:bg-neutral-900 text-sm sticky left-0 z-10 border-r border-neutral-50 dark:border-neutral-800">
- <div className="whitespace-nowrap text-neutral-700 dark:text-neutral-100">
- {formatDate(cohortPeriod)}
- </div>
- <div className="text-xs text-neutral-500 dark:text-neutral-300 mt-1 whitespace-nowrap">
- {t("{count} users", { count: data.cohorts[cohortPeriod].size.toLocaleString() })}
- </div>
- </div>
- {/* Retention Cells */}
- {data.cohorts[cohortPeriod].percentages.map((percentage: number | null, index: number) => {
- const { backgroundColor, textColor } = getRetentionColor(percentage, isDark);
- return (
- <div
- key={`${cohortPeriod}-period-${index}`}
- className="m-[2px] text-center flex items-center justify-center font-medium transition-colors duration-150 bg-white dark:bg-neutral-900 rounded-md"
- style={{
- backgroundColor,
- color: textColor,
- }}
- >
- {percentage !== null ? `${percentage.toFixed(1)}%` : "-"}
- </div>
- );
- })}
- </Fragment>
- ))}
- </div>
- </div>
- ) : null}
+ ) : isLoading || !model || !data ? (
+ <RetentionCardSkeleton />
+ ) : model.cohorts.length < 2 ? (
+ <Card>
+ <NothingFound
+ icon={<ChartColumnDecreasing className="w-10 h-10" />}
+ title={t("This range is too short for retention")}
+ description={
+ isWeekly
+ ? t(
+ "Retention follows new users into the weeks after their first visit, so it needs a range of at least two weeks."
+ )
+ : t(
+ "Retention follows new users into the days after their first visit, so it needs a range of at least two days."
+ )
+ }
+ action={
+ <div className="flex flex-wrap items-center justify-center gap-2">
+ {LONGER_RANGES.map(range => (
+ <Button
+ key={range}
+ variant="outline"
+ size="sm"
+ onClick={() => setTime(getDashboardTimeForRange(range, timezone))}
+ >
+ {presetLabels[range]}
+ </Button>
+ ))}
</div>
- </CardContent>
- </Card>
- </>
+ }
+ />
+ </Card>
+ ) : model.totalNew === 0 ? (
+ <Card>
+ <NothingFound
+ icon={<ChartColumnDecreasing className="w-10 h-10" />}
+ title={t("No new users in this range")}
+ description={
+ hasFilters
+ ? t(
+ "Retention follows people from their first visit, and nobody's first visit in this range matches the filters. Try a longer range or fewer filters."
+ )
+ : t(
+ "Retention follows people from their first visit. Try a longer range, or check that tracking is installed."
+ )
+ }
+ />
+ </Card>
+ ) : (
+ <RetentionCard
+ data={data}
+ model={model}
+ previousAverage={previousModel?.average ?? null}
+ pinnedCohort={pinnedCohort}
+ onPinCohort={setPinnedCohort}
+ hasFilters={hasFilters}
+ cohortLabel={cohortLabel}
+ periodLabel={periodLabel}
+ formatDay={formatDay}
+ />
)}
</div>
</DisabledOverlay>
diff --git a/client/src/app/[site]/retention/retentionModel.test.ts b/client/src/app/[site]/retention/retentionModel.test.ts
new file mode 100644
index 000000000..df85434ec
--- /dev/null
+++ b/client/src/app/[site]/retention/retentionModel.test.ts
@@ -0,0 +1,246 @@
+import { describe, expect, it } from "vitest";
+import { ProcessedRetentionData } from "../../../api/analytics/endpoints";
+import {
+ buildRetentionModel,
+ defaultRetentionMode,
+ findCohortOutlier,
+ HEAT_STEPS,
+ heatStep,
+ lastPeriodProgress,
+ niceScale,
+ retentionCsv,
+ statOffsets,
+} from "./retentionModel";
+
+const WEEKS = ["2026-08-31", "2026-09-07", "2026-09-14", "2026-09-21", "2026-09-28"];
+
+/** Cohorts given as counts per offset; the response pads past the window with null. */
+function response(
+ counts: Record<string, number[]>,
+ overrides: Partial<ProcessedRetentionData> = {}
+): ProcessedRetentionData {
+ const periods = overrides.periods ?? WEEKS;
+ const cohorts: ProcessedRetentionData["cohorts"] = {};
+ for (const [key, values] of Object.entries(counts)) {
+ const padded = periods.map((_, offset) => values[offset] ?? null);
+ cohorts[key] = {
+ size: values[0],
+ counts: padded,
+ percentages: padded.map(value => (value === null ? null : (value / values[0]) * 100)),
+ };
+ }
+ return {
+ cohorts,
+ maxPeriods: periods.length - 1,
+ mode: "week",
+ range: 31,
+ periods,
+ windowStart: "2026-08-31T00:00:00.000Z",
+ windowEnd: "2026-09-30T15:00:00.000Z",
+ timeZone: "UTC",
+ firstPeriodPartial: false,
+ lastPeriodPartial: true,
+ lastPeriodInProgress: true,
+ truncated: false,
+ lookbackDays: 90,
+ ...overrides,
+ };
+}
+
+const sample = () =>
+ response({
+ "2026-08-31": [1000, 200, 100, 80, 20],
+ "2026-09-07": [1000, 100, 60, 10],
+ "2026-09-14": [2000, 200, 30],
+ "2026-09-21": [1000, 40],
+ "2026-09-28": [400],
+ });
+
+describe("buildRetentionModel", () => {
+ it("marks the last diagonal as in progress and keeps the user counts", () => {
+ const model = buildRetentionModel(sample());
+
+ expect(model.maxOffset).toBe(4);
+ expect(model.cohorts.map(cohort => cohort.cells.length)).toEqual([5, 4, 3, 2, 1]);
+ expect(model.cohorts[0].cells[1]).toEqual({ offset: 1, users: 200, pct: 20, partial: false });
+ // Aug 31 + 4 weeks, Sep 7 + 3 weeks…: the week of Sep 28, which is not over.
+ expect(model.cohorts.map(cohort => cohort.cells[cohort.cells.length - 1].partial)).toEqual([
+ true,
+ true,
+ true,
+ true,
+ true,
+ ]);
+ expect(model.cohorts[1].cells[2].partial).toBe(false);
+ expect(model.cohorts[4].open).toBe(true);
+ expect(model.cohorts[3].open).toBe(false);
+ });
+
+ it("averages finished cells only, weighted by cohort size", () => {
+ const model = buildRetentionModel(sample());
+
+ // Week 1: 200 + 100 + 200 of 1000 + 1000 + 2000; the Sep 21 cohort's week 1 is in progress.
+ expect(model.average[1]).toEqual({ users: 500, size: 4000, pct: 12.5 });
+ expect(model.average[2]).toEqual({ users: 160, size: 2000, pct: 8 });
+ expect(model.average[3]).toEqual({ users: 80, size: 1000, pct: 8 });
+ expect(model.average[4]).toBeNull();
+ });
+
+ it("leaves the open cohort out of the average cohort size", () => {
+ const model = buildRetentionModel(sample());
+
+ expect(model.totalNew).toBe(5400);
+ expect(model.averageSize).toBe(1250);
+ });
+
+ it("leaves a cohort clipped by the range start out of the average size too", () => {
+ const model = buildRetentionModel({ ...sample(), firstPeriodPartial: true });
+
+ expect(model.cohorts[0].clipped).toBe(true);
+ expect(model.averageSize).toBeCloseTo(4000 / 3);
+ });
+
+ it("picks the best cohort by finished period-1 retention, ignoring tiny cohorts", () => {
+ const data = sample();
+ data.cohorts["2026-09-07"] = { size: 10, counts: [10, 9, 9, 1, null], percentages: [100, 90, 90, 10, null] };
+ const model = buildRetentionModel(data);
+
+ // 90% of 10 users does not beat 20% of 1000.
+ expect(model.best?.key).toBe("2026-08-31");
+ });
+
+ it("keeps periods with no new users as empty rows", () => {
+ const data = sample();
+ delete data.cohorts["2026-09-07"];
+ const model = buildRetentionModel(data);
+
+ expect(model.cohorts[1]).toMatchObject({ key: "2026-09-07", size: 0 });
+ expect(model.average[1]).toEqual({ users: 400, size: 3000, pct: (400 / 3000) * 100 });
+ });
+
+ it("scales the heat and the axis to the highest finished figure after period 0", () => {
+ const model = buildRetentionModel(sample());
+ expect(model.scaleMax).toBe(20);
+ expect(model.scaleStep).toBe(5);
+ });
+
+ it("treats every cell as final when the last period is whole", () => {
+ const model = buildRetentionModel({ ...sample(), lastPeriodPartial: false, lastPeriodInProgress: false });
+
+ expect(model.cohorts.some(cohort => cohort.cells.some(cell => cell.partial))).toBe(false);
+ expect(model.cohorts[4].open).toBe(false);
+ expect(model.average[4]).toEqual({ users: 20, size: 1000, pct: 2 });
+ });
+});
+
+describe("niceScale", () => {
+ it("rounds up to a ceiling with at most five steps", () => {
+ expect(niceScale(16.8)).toEqual({ max: 20, step: 5 });
+ expect(niceScale(43)).toEqual({ max: 50, step: 10 });
+ expect(niceScale(3.2)).toEqual({ max: 4, step: 1 });
+ expect(niceScale(100)).toEqual({ max: 100, step: 20 });
+ expect(niceScale(0)).toEqual({ max: 1, step: 0.25 });
+ });
+});
+
+describe("heatStep", () => {
+ it("spreads the scale over the eight steps and clamps at both ends", () => {
+ expect(heatStep(0, 20)).toBe(0);
+ expect(heatStep(9.9, 20)).toBe(3);
+ expect(heatStep(10, 20)).toBe(4);
+ expect(heatStep(20, 20)).toBe(HEAT_STEPS.length - 1);
+ expect(heatStep(55, 20)).toBe(HEAT_STEPS.length - 1);
+ });
+});
+
+describe("statOffsets", () => {
+ it("uses the longest set of periods the range has finished", () => {
+ expect(statOffsets("week", buildRetentionModel(sample()))).toEqual([1, 2, 3]);
+ expect(statOffsets("week", null)).toEqual([1, 4, 8]);
+ expect(statOffsets("day", null)).toEqual([1, 7, 30]);
+ });
+});
+
+describe("findCohortOutlier", () => {
+ it("reports the largest cohort when it is clearly larger and retains differently", () => {
+ const outlier = findCohortOutlier(buildRetentionModel(sample()));
+
+ expect(outlier?.cohort.key).toBe("2026-09-14");
+ expect(outlier?.pct).toBe(10);
+ expect(outlier?.difference).toBe(-2.5);
+ });
+
+ it("stays quiet when no cohort stands out in size", () => {
+ const model = buildRetentionModel(
+ response({
+ "2026-08-31": [1000, 200, 100, 80, 20],
+ "2026-09-07": [1050, 100, 60, 10],
+ "2026-09-14": [1000, 150, 30],
+ "2026-09-21": [1000, 40],
+ "2026-09-28": [400],
+ })
+ );
+ expect(findCohortOutlier(model)).toBeNull();
+ });
+
+ it("stays quiet when the largest cohort retains like the rest", () => {
+ const model = buildRetentionModel(
+ response({
+ "2026-08-31": [1000, 125, 100, 80, 20],
+ "2026-09-07": [1000, 125, 60, 10],
+ "2026-09-14": [2000, 250, 30],
+ "2026-09-21": [1000, 40],
+ "2026-09-28": [400],
+ })
+ );
+ expect(findCohortOutlier(model)).toBeNull();
+ });
+
+ it("needs at least three cohorts with a finished period 1", () => {
+ const model = buildRetentionModel(
+ response(
+ { "2026-09-14": [2000, 200, 30], "2026-09-21": [1000, 40], "2026-09-28": [400] },
+ { periods: ["2026-09-14", "2026-09-21", "2026-09-28"] }
+ )
+ );
+ expect(findCohortOutlier(model)).toBeNull();
+ });
+});
+
+describe("lastPeriodProgress", () => {
+ it("counts the days of the last period the window has reached", () => {
+ // Monday Sep 28 to Wednesday Sep 30, 15:00: three days in.
+ expect(lastPeriodProgress(sample())).toEqual({ elapsedDays: 3, totalDays: 7, nextPeriod: "2026-10-05" });
+ });
+
+ it("is null when the last period is whole", () => {
+ expect(lastPeriodProgress({ ...sample(), lastPeriodPartial: false })).toBeNull();
+ });
+});
+
+describe("defaultRetentionMode", () => {
+ it("is daily for a short range and weekly for a long one", () => {
+ expect(defaultRetentionMode({ mode: "day", day: "2026-09-30" }, "UTC")).toBe("day");
+ expect(defaultRetentionMode({ mode: "range", startDate: "2026-09-24", endDate: "2026-09-30" }, "UTC")).toBe("day");
+ expect(defaultRetentionMode({ mode: "range", startDate: "2026-09-01", endDate: "2026-09-30" }, "UTC")).toBe("week");
+ expect(defaultRetentionMode({ mode: "month", month: "2026-09-01" }, "UTC")).toBe("week");
+ expect(defaultRetentionMode({ mode: "all-time" }, "UTC")).toBe("week");
+ });
+});
+
+describe("retentionCsv", () => {
+ it("exports users and percent per period, leaving in-progress cells blank", () => {
+ const { columns, rows } = retentionCsv(buildRetentionModel(sample()));
+
+ expect(columns.slice(0, 4)).toEqual(["cohort_start", "new_users", "week_1_users", "week_1_percent"]);
+ expect(rows[0]).toMatchObject({
+ cohort_start: "2026-08-31",
+ new_users: 1000,
+ week_1_users: 200,
+ week_1_percent: 20,
+ });
+ // The Sep 21 cohort's week 1 is the week in progress.
+ expect(rows[3]).toMatchObject({ cohort_start: "2026-09-21", week_1_users: "", week_1_percent: "" });
+ expect(rows[0].week_4_users).toBe("");
+ });
+});
diff --git a/client/src/app/[site]/retention/retentionModel.ts b/client/src/app/[site]/retention/retentionModel.ts
new file mode 100644
index 000000000..8dd7eb952
--- /dev/null
+++ b/client/src/app/[site]/retention/retentionModel.ts
@@ -0,0 +1,279 @@
+import { DateTime } from "luxon";
+import { ProcessedRetentionData, RetentionMode } from "../../../api/analytics/endpoints";
+import { Time } from "../../../components/DateSelector/types";
+import { getAbsoluteBounds } from "../../../lib/time";
+
+/**
+ * The retention response laid out for the page: one row per cohort period,
+ * the size-weighted average per period, and the handful of facts the stat
+ * band and the insight row state. Pure, so it is tested without a browser.
+ */
+
+export interface RetentionCell {
+ /** Periods since the cohort's first visit. 0 is the cohort's own period. */
+ offset: number;
+ users: number;
+ /** Share of the cohort, 0 to 100. */
+ pct: number;
+ /** The period this cell covers is not over inside the window, so the figure is not final. */
+ partial: boolean;
+}
+
+export interface RetentionCohortRow {
+ /** The cohort period's first day, YYYY-MM-DD. */
+ key: string;
+ index: number;
+ size: number;
+ /** Indexed by offset. Later cohorts have fewer: nothing past the window's end is observable. */
+ cells: RetentionCell[];
+ /** The cohort's own period is not over, so its new users are still arriving. */
+ open: boolean;
+ /** The window starts after this period began, so the cohort misses the period's first days. */
+ clipped: boolean;
+}
+
+export interface RetentionAverage {
+ users: number;
+ size: number;
+ pct: number;
+}
+
+export interface RetentionModel {
+ mode: RetentionMode;
+ cohorts: RetentionCohortRow[];
+ /** The highest offset a cohort can show: one less than the number of periods. */
+ maxOffset: number;
+ /** Indexed by offset, weighted by cohort size over finished cells. Null when no cohort has finished that period. */
+ average: (RetentionAverage | null)[];
+ totalNew: number;
+ /** Mean size of the cohorts whose period lies wholly inside the window. */
+ averageSize: number | null;
+ /** Highest period-1 retention among cohorts of a meaningful size. */
+ best: RetentionCohortRow | null;
+ /** Ceiling shared by the heat scale and the curve's y axis, in percent. */
+ scaleMax: number;
+ /** Step between y-axis ticks, in percent. */
+ scaleStep: number;
+}
+
+// The stat band's three periods, longest first: the classic 1/4/8 weeks and
+// 1/7/30 days when the range is long enough to have finished them, shorter
+// sets otherwise, so a 30-day range does not open with an empty figure.
+const STAT_OFFSETS: Record<RetentionMode, readonly (readonly [number, number, number])[]> = {
+ day: [
+ [1, 7, 30],
+ [1, 7, 14],
+ [1, 3, 7],
+ [1, 2, 3],
+ ],
+ week: [
+ [1, 4, 8],
+ [1, 2, 4],
+ [1, 2, 3],
+ ],
+};
+
+/** The periods the stat band reports on: the longest set whose last period some cohort has finished. */
+export function statOffsets(mode: RetentionMode, model: RetentionModel | null): readonly [number, number, number] {
+ const sets = STAT_OFFSETS[mode];
+ return (model && sets.find(set => model.average[set[2]])) || sets[model ? sets.length - 1 : 0];
+}
+
+const SCALE_STEPS = [0.25, 0.5, 1, 2, 2.5, 5, 10, 20, 25];
+
+/** The smallest "nice" ceiling with at most five ticks above zero. */
+export function niceScale(dataMax: number): { max: number; step: number } {
+ if (!(dataMax > 0)) return { max: 1, step: 0.25 };
+ for (const step of SCALE_STEPS) {
+ const ticks = Math.ceil(dataMax / step - 1e-9);
+ if (ticks <= 5) return { max: Math.min(100, ticks * step), step };
+ }
+ return { max: 100, step: 25 };
+}
+
+export function buildRetentionModel(data: ProcessedRetentionData): RetentionModel {
+ const periodCount = data.periods.length;
+
+ const cohorts: RetentionCohortRow[] = data.periods.map((key, index) => {
+ const raw = data.cohorts[key];
+ const size = raw?.size ?? 0;
+ const cells: RetentionCell[] = Array.from({ length: periodCount - index }, (_, offset) => {
+ const users = raw?.counts[offset] ?? 0;
+ return {
+ offset,
+ users,
+ pct: size > 0 ? (users / size) * 100 : 0,
+ partial: data.lastPeriodPartial && index + offset === periodCount - 1,
+ };
+ });
+ return {
+ key,
+ index,
+ size,
+ cells,
+ open: data.lastPeriodPartial && index === periodCount - 1,
+ clipped: data.firstPeriodPartial && index === 0,
+ };
+ });
+
+ const maxOffset = Math.max(periodCount - 1, 0);
+ const average: (RetentionAverage | null)[] = Array.from({ length: maxOffset + 1 }, (_, offset) => {
+ let users = 0;
+ let size = 0;
+ for (const cohort of cohorts) {
+ const cell = cohort.cells[offset];
+ if (!cell || cell.partial || cohort.size === 0) continue;
+ users += cell.users;
+ size += cohort.size;
+ }
+ return size > 0 ? { users, size, pct: (users / size) * 100 } : null;
+ });
+
+ const whole = cohorts.filter(cohort => !cohort.open && !cohort.clipped);
+ const averageSize = whole.length > 0 ? whole.reduce((sum, cohort) => sum + cohort.size, 0) / whole.length : null;
+
+ // A cohort of a few users can post any percentage; it has to be at least
+ // half the usual size to be called the best.
+ const minimumSize = averageSize === null ? 1 : Math.max(1, averageSize / 2);
+ const best = cohorts
+ .filter(cohort => cohort.size >= minimumSize && cohort.cells[1] && !cohort.cells[1].partial)
+ .reduce<RetentionCohortRow | null>(
+ (winner, cohort) => (winner === null || cohort.cells[1].pct > winner.cells[1].pct ? cohort : winner),
+ null
+ );
+
+ let dataMax = 0;
+ for (const cohort of cohorts) {
+ if (cohort.size === 0) continue;
+ for (const cell of cohort.cells) {
+ if (cell.offset >= 1 && !cell.partial && cell.pct > dataMax) dataMax = cell.pct;
+ }
+ }
+ const scale = niceScale(dataMax);
+
+ return {
+ mode: data.mode,
+ cohorts,
+ maxOffset,
+ average,
+ totalNew: cohorts.reduce((sum, cohort) => sum + cohort.size, 0),
+ averageSize,
+ best,
+ scaleMax: scale.max,
+ scaleStep: scale.step,
+ };
+}
+
+export interface CohortOutlier {
+ cohort: RetentionCohortRow;
+ /** The cohort's period-1 retention, in percent. */
+ pct: number;
+ /** Percentage points above (positive) or below the all-cohort average. */
+ difference: number;
+}
+
+const OUTLIER_SIZE_RATIO = 1.15;
+const OUTLIER_MIN_DIFFERENCE = 1;
+const OUTLIER_MIN_COHORTS = 3;
+
+/**
+ * The largest cohort, when it is clearly larger than usual and its period-1
+ * retention sits at least a point away from the average: the case where a
+ * spike in new users (a launch, a campaign) retained differently. Fixed
+ * thresholds, no judgement: null whenever the data does not meet them.
+ */
+export function findCohortOutlier(model: RetentionModel): CohortOutlier | null {
+ const average = model.average[1];
+ if (!average || model.averageSize === null) return null;
+
+ const measured = model.cohorts.filter(cohort => cohort.size > 0 && cohort.cells[1] && !cohort.cells[1].partial);
+ if (measured.length < OUTLIER_MIN_COHORTS) return null;
+
+ const largest = measured.reduce((winner, cohort) => (cohort.size > winner.size ? cohort : winner));
+ if (largest.size < model.averageSize * OUTLIER_SIZE_RATIO) return null;
+
+ const pct = largest.cells[1].pct;
+ const difference = pct - average.pct;
+ if (Math.abs(difference) < OUTLIER_MIN_DIFFERENCE) return null;
+
+ return { cohort: largest, pct, difference };
+}
+
+/**
+ * Stepped opacity ramp of the data hue. The jump from 0.44 to 0.64 skips the
+ * band where neither light nor dark text reaches 4.5:1 on the dark panel, so
+ * every label stays readable: light text up to step 4, dark text from step 5.
+ * On the light panel dark text clears 4.5:1 on every step.
+ */
+export const HEAT_STEPS = [0.06, 0.12, 0.2, 0.3, 0.44, 0.64, 0.8, 0.96] as const;
+export const HEAT_DARK_TEXT_FROM = 5;
+
+export function heatStep(pct: number, scaleMax: number): number {
+ const position = Math.max(0, Math.min(0.9999, scaleMax > 0 ? pct / scaleMax : 0));
+ return Math.floor(position * HEAT_STEPS.length);
+}
+
+export const heatColor = (step: number) => `hsl(var(--dataviz) / ${HEAT_STEPS[step]})`;
+
+export const formatPercent = (pct: number) => `${pct.toFixed(1)}%`;
+
+/** The first and last day a cohort period covers, as calendar dates. */
+export function periodDays(key: string, mode: RetentionMode): { first: DateTime; last: DateTime } {
+ const first = DateTime.fromISO(key);
+ return { first, last: mode === "week" ? first.plus({ days: 6 }) : first };
+}
+
+export interface PeriodProgress {
+ /** Days of the last period the window has reached, counting the current one. */
+ elapsedDays: number;
+ totalDays: number;
+ /** The first day after the last period, YYYY-MM-DD: when the next return period begins. */
+ nextPeriod: string;
+}
+
+/** How far into its last period the window reaches. Null when that period is whole. */
+export function lastPeriodProgress(data: ProcessedRetentionData): PeriodProgress | null {
+ const lastKey = data.periods[data.periods.length - 1];
+ if (!data.lastPeriodPartial || !lastKey) return null;
+
+ const totalDays = data.mode === "week" ? 7 : 1;
+ const start = DateTime.fromISO(lastKey, { zone: data.timeZone });
+ const end = DateTime.fromISO(data.windowEnd, { zone: data.timeZone });
+ const elapsedDays = Math.max(1, Math.min(totalDays, Math.ceil(end.diff(start, "days").days)));
+
+ return { elapsedDays, totalDays, nextPeriod: start.plus({ days: totalDays }).toISODate() ?? "" };
+}
+
+const WEEKLY_FROM_DAYS = 21;
+
+/**
+ * Daily cohorts for a short range, weekly for a longer one, until the viewer
+ * picks: a week of data is a single weekly cohort with nothing to come back to.
+ */
+export function defaultRetentionMode(time: Time, zone: string): RetentionMode {
+ const bounds = getAbsoluteBounds(time, zone);
+ if (!bounds) return "week";
+ return bounds.end.diff(bounds.start, "days").days < WEEKLY_FROM_DAYS ? "day" : "week";
+}
+
+/** One CSV row per cohort; in-progress cells are left blank rather than exported as final. */
+export function retentionCsv(model: RetentionModel): { columns: string[]; rows: Record<string, unknown>[] } {
+ const unit = model.mode === "week" ? "week" : "day";
+ const offsets = Array.from({ length: model.maxOffset }, (_, i) => i + 1);
+ const columns = [
+ "cohort_start",
+ "new_users",
+ ...offsets.flatMap(offset => [`${unit}_${offset}_users`, `${unit}_${offset}_percent`]),
+ ];
+ const rows = model.cohorts.map(cohort => {
+ const row: Record<string, unknown> = { cohort_start: cohort.key, new_users: cohort.size };
+ for (const offset of offsets) {
+ const cell = cohort.cells[offset];
+ const final = cell && !cell.partial && cohort.size > 0;
+ row[`${unit}_${offset}_users`] = final ? cell.users : "";
+ row[`${unit}_${offset}_percent`] = final ? Number(cell.pct.toFixed(2)) : "";
+ }
+ return row;
+ });
+ return { columns, rows };
+}
diff --git a/client/src/app/[site]/sessions/components/GoalChip.tsx b/client/src/app/[site]/sessions/components/GoalChip.tsx
new file mode 100644
index 000000000..9e90e8111
--- /dev/null
+++ b/client/src/app/[site]/sessions/components/GoalChip.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import { Target } from "lucide-react";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { SessionGoal } from "@/api/analytics/endpoints";
+import { cn } from "@/lib/utils";
+import { useSitePath } from "./useSitePath";
+
+/** The goals page names an unnamed goal by its number; so does this. */
+export function useGoalName(): (goal: SessionGoal) => string {
+ const t = useExtracted();
+ return goal => goal.name || t("Goal #{goalId}", { goalId: String(goal.id) });
+}
+
+/** A completed goal, as a link to the Goals page for the same period. */
+export function GoalChip({ goal, className }: { goal: SessionGoal; className?: string }) {
+ const goalName = useGoalName();
+ const sitePath = useSitePath();
+ const name = goalName(goal);
+
+ return (
+ <Link
+ href={sitePath("goals", { keepQuery: true })}
+ prefetch={false}
+ title={name}
+ // Rows toggle on click; following the link must not.
+ onClick={event => event.stopPropagation()}
+ className={cn(
+ "inline-flex max-w-full items-center gap-1 whitespace-nowrap rounded-md border border-neutral-150 px-1.5 py-0.5 text-xs font-medium text-neutral-700 hover:border-neutral-300 dark:border-neutral-800 dark:text-neutral-200 dark:hover:border-neutral-650",
+ className
+ )}
+ >
+ <Target className="h-3 w-3 shrink-0 text-emerald-600 dark:text-emerald-400" />
+ <span className="truncate">{name}</span>
+ </Link>
+ );
+}
diff --git a/client/src/app/[site]/sessions/components/RangeChip.test.tsx b/client/src/app/[site]/sessions/components/RangeChip.test.tsx
new file mode 100644
index 000000000..95414eded
--- /dev/null
+++ b/client/src/app/[site]/sessions/components/RangeChip.test.tsx
@@ -0,0 +1,119 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { RangeValue } from "../sessionRanges";
+import { RangeChip } from "./RangeChip";
+
+vi.mock("next-intl", () => ({
+ useExtracted:
+ () =>
+ (message: string, values: Record<string, string> = {}) =>
+ message.replace(/\{(\w+)\}/g, (_, key) => values[key] ?? ""),
+}));
+
+beforeEach(() => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+const renderChip = (value: RangeValue, duration = false) => {
+ const onChange = vi.fn();
+ render(
+ <RangeChip
+ label={duration ? "Duration" : "Pageviews"}
+ clearLabel="Clear range"
+ value={value}
+ onChange={onChange}
+ duration={duration}
+ />
+ );
+ return onChange;
+};
+
+const trigger = () => screen.getByRole("button", { name: /^(Pageviews|Duration)/ });
+
+describe("RangeChip label", () => {
+ it("reads Any at rest, with nothing to clear", () => {
+ renderChip({});
+
+ expect(trigger().textContent).toBe("Pageviews Any");
+ expect(screen.queryByRole("button", { name: "Clear range" })).toBeNull();
+ });
+
+ it("reads as the filter it applies", () => {
+ renderChip({ min: 3 });
+ expect(trigger().textContent).toBe("Pageviews 3 or more");
+ cleanup();
+
+ renderChip({ max: 5 });
+ expect(trigger().textContent).toBe("Pageviews up to 5");
+ cleanup();
+
+ renderChip({ min: 2, max: 5 });
+ expect(trigger().textContent).toBe("Pageviews 2 to 5");
+ cleanup();
+
+ renderChip({ min: 1, max: 1 });
+ expect(trigger().textContent).toBe("Pageviews exactly 1");
+ });
+
+ it("reads seconds as a duration", () => {
+ renderChip({ min: 10 }, true);
+ expect(trigger().textContent).toBe("Duration 10s or longer");
+ cleanup();
+
+ renderChip({ min: 30, max: 300 }, true);
+ expect(trigger().textContent).toBe("Duration 30s to 5m");
+ });
+});
+
+describe("RangeChip editing", () => {
+ it("applies what was typed and nothing before Apply is pressed", () => {
+ const onChange = renderChip({});
+
+ fireEvent.click(trigger());
+ fireEvent.change(screen.getByLabelText("At least"), { target: { value: "2" } });
+ fireEvent.change(screen.getByLabelText("At most"), { target: { value: "9" } });
+ expect(onChange).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole("button", { name: "Apply" }));
+ expect(onChange).toHaveBeenCalledWith({ min: 2, max: 9 });
+ });
+
+ it("opens on the applied range", () => {
+ renderChip({ min: 10 }, true);
+
+ fireEvent.click(trigger());
+
+ expect((screen.getByLabelText("At least (seconds)") as HTMLInputElement).value).toBe("10");
+ expect((screen.getByLabelText("At most (seconds)") as HTMLInputElement).value).toBe("");
+ });
+
+ it("clears from the chip without opening it", () => {
+ const onChange = renderChip({ min: 10 }, true);
+
+ fireEvent.click(screen.getByRole("button", { name: "Clear range" }));
+
+ expect(onChange).toHaveBeenCalledWith({});
+ expect(screen.queryByLabelText("At least (seconds)")).toBeNull();
+ });
+
+ it("clears from inside the popover", () => {
+ const onChange = renderChip({ max: 4 });
+
+ fireEvent.click(trigger());
+ fireEvent.click(screen.getByRole("button", { name: "Clear" }));
+
+ expect(onChange).toHaveBeenCalledWith({});
+ });
+});
diff --git a/client/src/app/[site]/sessions/components/RangeChip.tsx b/client/src/app/[site]/sessions/components/RangeChip.tsx
new file mode 100644
index 000000000..038d96af9
--- /dev/null
+++ b/client/src/app/[site]/sessions/components/RangeChip.tsx
@@ -0,0 +1,153 @@
+"use client";
+
+import { X } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { FormEvent, useId, useState } from "react";
+import { ControlButton } from "@/components/site/ControlButton";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { formatShortDuration } from "@/lib/dateTimeUtils";
+import { cn } from "@/lib/utils";
+import { describeRange, hasRange, RangeValue, toRange } from "../sessionRanges";
+
+interface RangeChipProps {
+ /** What is being ranged: "Pageviews", "Events", "Duration". */
+ label: string;
+ value: RangeValue;
+ onChange: (value: RangeValue) => void;
+ /** Accessible name of the clear button, e.g. "Clear duration range". */
+ clearLabel: string;
+ /** Bounds are seconds and read as durations ("10s or longer"). */
+ duration?: boolean;
+}
+
+function RangeForm({
+ value,
+ duration,
+ onApply,
+}: Pick<RangeChipProps, "value" | "duration"> & { onApply: (value: RangeValue) => void }) {
+ const t = useExtracted();
+ const id = useId();
+ const [min, setMin] = useState(value.min?.toString() ?? "");
+ const [max, setMax] = useState(value.max?.toString() ?? "");
+
+ const submit = (event: FormEvent) => {
+ event.preventDefault();
+ onApply(toRange(min, max));
+ };
+
+ return (
+ <form onSubmit={submit} className="space-y-3">
+ <div className="grid grid-cols-2 gap-2">
+ <div className="space-y-1.5">
+ <Label htmlFor={`${id}-min`} className="text-xs text-neutral-600 dark:text-neutral-300">
+ {duration ? t("At least (seconds)") : t("At least")}
+ </Label>
+ <Input
+ id={`${id}-min`}
+ type="number"
+ inputMode="numeric"
+ min={0}
+ step={1}
+ placeholder="0"
+ value={min}
+ onChange={event => setMin(event.target.value)}
+ className="h-8 tabular-nums"
+ autoFocus
+ />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor={`${id}-max`} className="text-xs text-neutral-600 dark:text-neutral-300">
+ {duration ? t("At most (seconds)") : t("At most")}
+ </Label>
+ <Input
+ id={`${id}-max`}
+ type="number"
+ inputMode="numeric"
+ min={0}
+ step={1}
+ placeholder={t("Any")}
+ value={max}
+ onChange={event => setMax(event.target.value)}
+ className="h-8 tabular-nums"
+ />
+ </div>
+ </div>
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="ghost" size="sm" onClick={() => onApply({})} disabled={!hasRange(value)}>
+ {t("Clear")}
+ </Button>
+ <Button type="submit" variant="accent" size="sm">
+ {t("Apply")}
+ </Button>
+ </div>
+ </form>
+ );
+}
+
+/**
+ * A min/max range as one analysis-bar control. At rest it reads "Pageviews
+ * Any"; with a bound set it reads as the filter it is ("Duration 10s or
+ * longer") and carries its own clear button.
+ */
+export function RangeChip({ label, value, onChange, clearLabel, duration = false }: RangeChipProps) {
+ const t = useExtracted();
+ const [open, setOpen] = useState(false);
+ const applied = hasRange(value);
+
+ const show = (bound: number) => (duration ? formatShortDuration(bound) : bound.toLocaleString());
+ const description = describeRange(value);
+ const text =
+ description.kind === "any"
+ ? t("Any")
+ : description.kind === "exact"
+ ? t("exactly {value}", { value: show(description.value) })
+ : description.kind === "between"
+ ? t("{min} to {max}", { min: show(description.min), max: show(description.max) })
+ : description.kind === "min"
+ ? duration
+ ? t("{value} or longer", { value: show(description.min) })
+ : t("{value} or more", { value: show(description.min) })
+ : t("up to {value}", { value: show(description.max) });
+
+ return (
+ <div className="flex max-w-full items-stretch">
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <ControlButton
+ label={label}
+ value={<span className="tabular-nums">{text}</span>}
+ className={cn(
+ applied && "rounded-r-none border-neutral-150 bg-neutral-50 dark:border-neutral-700 dark:bg-neutral-850"
+ )}
+ />
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-64 p-3">
+ {/* Mounted with the popover, so the inputs start from the applied range each time it opens. */}
+ <RangeForm
+ value={value}
+ duration={duration}
+ onApply={next => {
+ onChange(next);
+ setOpen(false);
+ }}
+ />
+ </PopoverContent>
+ </Popover>
+ {applied && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-label={clearLabel}
+ onClick={() => onChange({})}
+ className="-ml-px rounded-l-none border-neutral-150 bg-neutral-50 px-1.5 text-neutral-500 dark:border-neutral-700 dark:bg-neutral-850 dark:text-neutral-400 [&_svg]:size-3.5"
+ >
+ <X strokeWidth={2.5} />
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/sessions/components/SessionLedgerDetails.tsx b/client/src/app/[site]/sessions/components/SessionLedgerDetails.tsx
new file mode 100644
index 000000000..6d175b22d
--- /dev/null
+++ b/client/src/app/[site]/sessions/components/SessionLedgerDetails.tsx
@@ -0,0 +1,195 @@
+"use client";
+
+import { ArrowRight, Video } from "lucide-react";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { ReactNode } from "react";
+import { GetSessionsResponse } from "@/api/analytics/endpoints";
+import { Avatar } from "@/components/Avatar";
+import { ChannelIcon, extractDomain } from "@/components/Channel";
+import { IdentifiedBadge } from "@/components/IdentifiedBadge";
+import { CopyButton } from "@/components/interior/copy-button";
+import { sessionEventCount } from "@/components/Sessions/sessionEventCount";
+import { Button } from "@/components/ui/button";
+import { useGetRegionName } from "@/lib/geo";
+import { getCountryName, getLanguageName, getUserDisplayName } from "@/lib/utils";
+import { Browser } from "../../components/shared/icons/Browser";
+import { CountryFlag } from "../../components/shared/icons/CountryFlag";
+import { DeviceIcon } from "../../components/shared/icons/Device";
+import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";
+import { SessionTimeline } from "./SessionTimeline";
+
+type Session = GetSessionsResponse[number];
+
+function Fact({ label, children }: { label: string; children: ReactNode }) {
+ return (
+ <div className="flex items-start gap-3 py-1.5">
+ <dt className="w-[4.5rem] shrink-0 pt-px text-xs text-neutral-500 dark:text-neutral-400">{label}</dt>
+ <dd className="flex min-w-0 flex-1 flex-wrap items-center gap-x-1.5 gap-y-1 text-[13px] text-neutral-800 dark:text-neutral-200">
+ {children}
+ </dd>
+ </div>
+ );
+}
+
+const UTM_FIELDS = [
+ ["source", "utm_source"],
+ ["medium", "utm_medium"],
+ ["campaign", "utm_campaign"],
+ ["term", "utm_term"],
+ ["content", "utm_content"],
+] as const;
+
+function SessionFacts({
+ session,
+ userHref,
+ onWatchReplay,
+}: {
+ session: Session;
+ userHref: string;
+ onWatchReplay?: () => void;
+}) {
+ const t = useExtracted();
+ const { getRegionName } = useGetRegionName();
+
+ const location = [session.city, getRegionName(session.region), session.country && getCountryName(session.country)]
+ .filter(Boolean)
+ .join(", ");
+ const referrerDomain = extractDomain(session.referrer);
+ const utm = UTM_FIELDS.filter(([, field]) => session[field]);
+ const muted = "text-neutral-500 dark:text-neutral-400";
+
+ return (
+ <div>
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="text-sm font-semibold">{t("Session facts")}</h3>
+ <div className={`flex min-w-0 items-center gap-0.5 text-xs tabular-nums ${muted}`}>
+ <span className="truncate" title={session.session_id}>
+ {session.session_id.slice(0, 8)}
+ </span>
+ <CopyButton
+ iconOnly
+ tooltip
+ size="xs"
+ variant="ghost"
+ value={session.session_id}
+ label={t("Copy session ID")}
+ />
+ </div>
+ </div>
+
+ <dl className="mt-1.5">
+ <Fact label={t("User")}>
+ <Avatar size={16} id={session.user_id} />
+ <Link href={userHref} className="truncate hover:underline">
+ {getUserDisplayName(session)}
+ </Link>
+ {!!session.identified_user_id && (
+ <IdentifiedBadge traits={session.traits} userId={session.identified_user_id} className="px-1 py-px" />
+ )}
+ </Fact>
+ {location && (
+ <Fact label={t("Location")}>
+ {session.country && <CountryFlag country={session.country} className="w-4 shrink-0" />}
+ <span className="min-w-0 break-words">{location}</span>
+ </Fact>
+ )}
+ <Fact label={t("Device")}>
+ <span className={`shrink-0 ${muted}`}>
+ <DeviceIcon deviceType={session.device_type} size={14} />
+ </span>
+ <span>{session.device_type || t("Unknown")}</span>
+ {!!session.screen_width && !!session.screen_height && (
+ <span className={`tabular-nums ${muted}`}>
+ {session.screen_width} × {session.screen_height}
+ </span>
+ )}
+ </Fact>
+ <Fact label={t("Browser")}>
+ <Browser browser={session.browser || "Unknown"} size={14} />
+ <span>{[session.browser || t("Unknown"), session.browser_version].filter(Boolean).join(" ")}</span>
+ {session.operating_system && (
+ <>
+ <span className="ml-1 flex shrink-0">
+ <OperatingSystem os={session.operating_system} size={14} />
+ </span>
+ <span>{[session.operating_system, session.operating_system_version].filter(Boolean).join(" ")}</span>
+ </>
+ )}
+ </Fact>
+ <Fact label={t("Source")}>
+ <ChannelIcon channel={session.channel} className={`h-3.5 w-3.5 shrink-0 ${muted}`} />
+ <span>{session.channel || t("Unknown")}</span>
+ {referrerDomain && (
+ <span className={`min-w-0 truncate ${muted}`} title={session.referrer}>
+ {referrerDomain}
+ </span>
+ )}
+ </Fact>
+ {utm.length > 0 && (
+ <Fact label={t("Campaign")}>
+ {utm.map(([name, field]) => (
+ <span
+ key={field}
+ title={`utm_${name}: ${session[field]}`}
+ className="inline-flex max-w-full items-center rounded-md border border-neutral-150 px-1.5 py-0.5 text-xs dark:border-neutral-800"
+ >
+ <span className={`mr-1 shrink-0 ${muted}`}>{name}</span>
+ <span className="truncate font-medium">{session[field]}</span>
+ </span>
+ ))}
+ </Fact>
+ )}
+ {session.language && <Fact label={t("Language")}>{getLanguageName(session.language)}</Fact>}
+ {session.ip && (
+ <Fact label={t("IP")}>
+ <span className="tabular-nums">{session.ip}</span>
+ </Fact>
+ )}
+ </dl>
+
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ {onWatchReplay && (
+ <Button type="button" variant="success" size="sm" className="gap-1.5" onClick={onWatchReplay}>
+ <Video />
+ {t("Watch replay")}
+ </Button>
+ )}
+ <Button asChild variant="outline" size="sm" className="gap-1.5">
+ <Link href={userHref}>
+ {t("View user")}
+ <ArrowRight />
+ </Link>
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+interface SessionLedgerDetailsProps {
+ session: Session;
+ userHref: string;
+ /** Opens the replay; left out when the session has none. */
+ onWatchReplay?: () => void;
+}
+
+/**
+ * An open ledger row: the session's timeline beside its facts. They used to
+ * be two tabs, so reading where someone came from meant leaving what they did.
+ */
+export function SessionLedgerDetails({ session, userHref, onWatchReplay }: SessionLedgerDetailsProps) {
+ return (
+ // Side by side once the ledger (the container) has the width; stacked before that.
+ <div className="grid border-b border-neutral-100 bg-neutral-50 @min-[900px]:grid-cols-[minmax(0,1fr)_316px] dark:border-neutral-800 dark:bg-background">
+ <div className="min-w-0 px-3 py-3 @min-[800px]:pl-[38px] @min-[800px]:pr-4">
+ <SessionTimeline
+ sessionId={session.session_id}
+ expectedEvents={session.pageviews + sessionEventCount(session) + (session.errors || 0)}
+ />
+ </div>
+ <div className="border-t border-neutral-100 px-3 py-3 @min-[800px]:px-4 @min-[900px]:border-l @min-[900px]:border-t-0 dark:border-neutral-800">
+ <SessionFacts session={session} userHref={userHref} onWatchReplay={onWatchReplay} />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/sessions/components/SessionLedgerRow.tsx b/client/src/app/[site]/sessions/components/SessionLedgerRow.tsx
new file mode 100644
index 000000000..7dc7d9772
--- /dev/null
+++ b/client/src/app/[site]/sessions/components/SessionLedgerRow.tsx
@@ -0,0 +1,383 @@
+"use client";
+
+import { FilterParameter } from "@rybbit/shared";
+import { ArrowRight, ChevronDown, ChevronRight, TriangleAlert, Video } from "lucide-react";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { MouseEvent, useState } from "react";
+import { GetSessionsResponse } from "@/api/analytics/endpoints";
+import { Avatar } from "@/components/Avatar";
+import { ChannelIcon, extractDomain, getDisplayName } from "@/components/Channel";
+import { IdentifiedBadge } from "@/components/IdentifiedBadge";
+import { ReplayDrawer } from "@/components/Sessions/ReplayDrawer";
+import { sessionEventCount } from "@/components/Sessions/sessionEventCount";
+import {
+ BrowserTooltipIcon,
+ CountryFlagTooltipIcon,
+ DeviceTypeTooltipIcon,
+ OperatingSystemTooltipIcon,
+} from "@/components/TooltipIcons/TooltipIcons";
+import { Button } from "@/components/ui/button";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
+import { formatShortDuration } from "@/lib/dateTimeUtils";
+import { addFilter, useTimezone } from "@/lib/store";
+import { cn, getUserDisplayName } from "@/lib/utils";
+import { GoalChip, useGoalName } from "./GoalChip";
+import { SessionLedgerDetails } from "./SessionLedgerDetails";
+import { useSitePath } from "./useSitePath";
+
+type Session = GetSessionsResponse[number];
+
+/*
+ * The ledger lays itself out by its own width, not the viewport's: the sidebar
+ * takes a fixed share of the window and can be hidden, so a viewport
+ * breakpoint would be wrong one way or the other. The ledger card is the
+ * container (see SessionsLedger).
+ *
+ * under 800px each session is a short stack of lines
+ * 800px chevron, user, device, entry and exit, pages, events, duration, replay, started
+ * 1080px plus errors, source and, on a site with goals, goal
+ *
+ * The last column holds a time under a day heading and a date and time
+ * otherwise, so it comes in two widths. Every class is written out in full
+ * for Tailwind to find.
+ */
+const COMPACT_COLUMNS = {
+ time: "@min-[800px]:grid-cols-[16px_140px_84px_minmax(0,1fr)_48px_52px_72px_24px_72px]",
+ dateTime: "@min-[800px]:grid-cols-[16px_140px_84px_minmax(0,1fr)_48px_52px_72px_24px_116px]",
+};
+const WIDE_COLUMNS = {
+ time: "@min-[1080px]:grid-cols-[16px_150px_84px_minmax(0,1fr)_44px_52px_48px_68px_108px_24px_72px]",
+ dateTime: "@min-[1080px]:grid-cols-[16px_150px_84px_minmax(0,1fr)_44px_52px_48px_68px_108px_24px_116px]",
+};
+const WIDE_COLUMNS_WITH_GOAL = {
+ time: "@min-[1080px]:grid-cols-[16px_150px_84px_minmax(0,1fr)_44px_52px_48px_68px_108px_118px_24px_72px]",
+ dateTime: "@min-[1080px]:grid-cols-[16px_150px_84px_minmax(0,1fr)_44px_52px_48px_68px_108px_118px_24px_116px]",
+};
+
+/** Shown only once the ledger is wide enough for every column. */
+export const WIDE_ONLY_BLOCK = "hidden @min-[1080px]:block";
+export const WIDE_ONLY_FLEX = "hidden @min-[1080px]:flex";
+
+/** The grid every ledger row and the column header share. Hidden below 800px. */
+export const ledgerGrid = (showGoals: boolean, groupedByDay: boolean) => {
+ const started = groupedByDay ? "time" : "dateTime";
+ return cn(
+ "hidden items-center gap-x-3 px-3 @min-[800px]:grid",
+ COMPACT_COLUMNS[started],
+ (showGoals ? WIDE_COLUMNS_WITH_GOAL : WIDE_COLUMNS)[started]
+ );
+};
+
+/** What takes the grid's place below 800px. */
+export const STACKED_ONLY = "@min-[800px]:hidden";
+
+interface SessionLedgerRowProps {
+ session: Session;
+ /** The site has goals, so the ledger has a Goal column. */
+ showGoals: boolean;
+ /** The site has a Replay page, so sessions with a replay offer it. */
+ showReplay: boolean;
+ /** Rows sit under a day heading, so the start time needs no date. */
+ groupedByDay: boolean;
+}
+
+/**
+ * One session as one aligned line: who, on what, from where to where, how
+ * much, how long, from which source, which goal, and when. The marks keep
+ * their click-to-filter; the row itself opens the timeline and facts.
+ */
+export function SessionLedgerRow({ session, showGoals, showReplay, groupedByDay }: SessionLedgerRowProps) {
+ const t = useExtracted();
+ const goalName = useGoalName();
+ const sitePath = useSitePath();
+ const zone = useTimezone();
+ const { hour12, formatDateTime, formatRelative } = useDateTimeFormat();
+ const [expanded, setExpanded] = useState(false);
+ const [replayOpen, setReplayOpen] = useState(false);
+
+ const isIdentified = !!session.identified_user_id;
+ const userHref = sitePath(`user/${encodeURIComponent(isIdentified ? session.identified_user_id : session.user_id)}`);
+ const hasReplay = showReplay && session.has_replay === 1;
+ const goals = session.converted_goals ?? [];
+ const eventCount = sessionEventCount(session);
+ const singlePage = session.pageviews === 1 && session.entry_page === session.exit_page;
+ const referrerDomain = extractDomain(session.referrer);
+ const source = referrerDomain ? getDisplayName(referrerDomain) : session.channel;
+
+ const start = DateTime.fromSQL(session.session_start, { zone: "utc" });
+ const startedTime = formatDateTime(start, { hour: "numeric", minute: "2-digit", hour12, timeZone: zone });
+ const startedDate = formatDateTime(start, { month: "short", day: "numeric", timeZone: zone });
+ const startedFull = `${formatDateTime(start, { dateStyle: "medium", timeStyle: "medium", hour12, timeZone: zone })} (${formatRelative(start)})`;
+
+ const stop = (event: MouseEvent) => event.stopPropagation();
+ const filterBy = (parameter: FilterParameter, value: string | undefined) => (event: MouseEvent) => {
+ event.stopPropagation();
+ if (!value) return;
+ addFilter({ parameter, value: [value], type: "equals" });
+ };
+
+ // An event breakdown is only worth a tooltip when the total hides something.
+ const eventParts = [
+ [t("Custom events"), session.events],
+ [t("Button clicks"), session.button_clicks],
+ [t("Copies"), session.copies],
+ [t("Form submits"), session.form_submits],
+ [t("Input changes"), session.input_changes],
+ ].filter((part): part is [string, number] => Number(part[1]) > 0);
+ const showEventBreakdown = eventParts.length > 1 || eventCount !== session.events || session.outbound > 0;
+
+ const toggle = (
+ <button
+ type="button"
+ aria-expanded={expanded}
+ aria-label={expanded ? t("Collapse session") : t("Expand session")}
+ // The row toggles on click too; without this the two would cancel out.
+ onClick={event => {
+ event.stopPropagation();
+ setExpanded(!expanded);
+ }}
+ className="flex shrink-0 items-center rounded text-neutral-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400 dark:text-neutral-400"
+ >
+ {expanded ? (
+ <ChevronDown className="h-4 w-4" strokeWidth={2.5} />
+ ) : (
+ <ChevronRight className="h-4 w-4" strokeWidth={2.5} />
+ )}
+ </button>
+ );
+
+ const user = (
+ <Link href={userHref} onClick={stop} className="flex min-w-0 items-center gap-2">
+ <Avatar size={20} id={session.user_id} lastActiveTime={DateTime.fromSQL(session.session_end, { zone: "utc" })} />
+ <span
+ className={cn(
+ "truncate hover:underline",
+ isIdentified ? "font-medium text-neutral-900 dark:text-neutral-100" : "text-neutral-700 dark:text-neutral-300"
+ )}
+ >
+ {getUserDisplayName(session)}
+ </span>
+ {isIdentified && (
+ <IdentifiedBadge traits={session.traits} userId={session.identified_user_id} className="shrink-0 px-1 py-px" />
+ )}
+ </Link>
+ );
+
+ const marks = (
+ <div className="flex shrink-0 items-center gap-1.5">
+ {session.country && (
+ <CountryFlagTooltipIcon
+ country={session.country}
+ city={session.city}
+ region={session.region}
+ onClick={filterBy("country", session.country)}
+ />
+ )}
+ <BrowserTooltipIcon
+ browser={session.browser || "Unknown"}
+ browser_version={session.browser_version}
+ onClick={filterBy("browser", session.browser)}
+ />
+ <OperatingSystemTooltipIcon
+ operating_system={session.operating_system || ""}
+ operating_system_version={session.operating_system_version}
+ onClick={filterBy("operating_system", session.operating_system)}
+ />
+ <span className="text-neutral-500 dark:text-neutral-400">
+ <DeviceTypeTooltipIcon
+ device_type={session.device_type || ""}
+ screen_width={session.screen_width}
+ screen_height={session.screen_height}
+ size={16}
+ onClick={filterBy("device_type", session.device_type)}
+ />
+ </span>
+ </div>
+ );
+
+ const pathButton = (parameter: "entry_page" | "exit_page", path: string, className: string) => (
+ <button
+ type="button"
+ title={t("{path} (click to filter)", { path: path || "-" })}
+ onClick={filterBy(parameter, path)}
+ className={cn("truncate text-left underline-offset-2 hover:underline", className)}
+ >
+ {path || "-"}
+ </button>
+ );
+ const paths = (
+ <div className="flex min-w-0 items-center gap-1.5 text-xs text-neutral-700 dark:text-neutral-300">
+ {pathButton("entry_page", session.entry_page, "min-w-0 shrink")}
+ {singlePage ? (
+ <span className="shrink-0 text-neutral-500 dark:text-neutral-400">{t("single page")}</span>
+ ) : (
+ <>
+ <ArrowRight className="h-3 w-3 shrink-0 text-neutral-500" />
+ {pathButton("exit_page", session.exit_page, "max-w-[55%] shrink-0")}
+ </>
+ )}
+ </div>
+ );
+
+ const events = showEventBreakdown ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="cursor-default">{eventCount.toLocaleString()}</span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <div className="space-y-0.5 text-xs tabular-nums">
+ {eventParts.map(([label, count]) => (
+ <div key={label} className="flex justify-between gap-4">
+ <span>{label}</span>
+ <span>{count.toLocaleString()}</span>
+ </div>
+ ))}
+ {session.outbound > 0 && (
+ <div className="flex justify-between gap-4 opacity-70">
+ <span>{t("Outbound clicks (not counted)")}</span>
+ <span>{session.outbound.toLocaleString()}</span>
+ </div>
+ )}
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ eventCount.toLocaleString()
+ );
+
+ const errors = session.errors > 0 && (
+ <span
+ className="inline-flex items-center gap-1 font-medium text-red-600 dark:text-red-400"
+ title={t("JavaScript errors: {count}", { count: session.errors.toLocaleString() })}
+ >
+ <TriangleAlert className="h-3 w-3" aria-hidden="true" />
+ {session.errors.toLocaleString()}
+ </span>
+ );
+
+ const sourceButton = (
+ <button
+ type="button"
+ title={t("{channel} (click to filter)", { channel: session.channel || t("Unknown") })}
+ onClick={filterBy("channel", session.channel)}
+ className="flex min-w-0 items-center gap-1.5 text-xs text-neutral-700 hover:underline dark:text-neutral-300"
+ >
+ <ChannelIcon channel={session.channel} className="h-3.5 w-3.5 shrink-0 text-neutral-500 dark:text-neutral-400" />
+ <span className="truncate">{source || t("Unknown")}</span>
+ </button>
+ );
+
+ const goal = goals.length > 0 && (
+ <div className="flex min-w-0 items-center gap-1">
+ <GoalChip goal={goals[0]} className="min-w-0" />
+ {goals.length > 1 && (
+ <span
+ className="shrink-0 text-xs tabular-nums text-neutral-500 dark:text-neutral-400"
+ title={goals.slice(1).map(goalName).join(", ")}
+ >
+ +{goals.length - 1}
+ </span>
+ )}
+ </div>
+ );
+
+ const replay = hasReplay && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="smIcon"
+ aria-label={t("Watch replay")}
+ title={t("Watch replay")}
+ onClick={event => {
+ event.stopPropagation();
+ setReplayOpen(true);
+ }}
+ className="h-6 w-6 text-neutral-700 dark:text-neutral-200"
+ >
+ <Video />
+ </Button>
+ );
+
+ return (
+ <>
+ <div
+ onClick={() => setExpanded(!expanded)}
+ className={cn(
+ "cursor-pointer border-b border-neutral-100 text-[13px] dark:border-neutral-800",
+ expanded ? "bg-neutral-50 dark:bg-neutral-850" : "hover:bg-neutral-50 dark:hover:bg-neutral-800/20"
+ )}
+ >
+ {/* A narrow ledger: the same facts stacked on three short lines. */}
+ <div className={cn("flex flex-col gap-1.5 px-3 py-2", STACKED_ONLY)}>
+ <div className="flex items-center gap-2">
+ {toggle}
+ {user}
+ <span
+ className="ml-auto shrink-0 text-xs tabular-nums text-neutral-500 dark:text-neutral-400"
+ title={startedFull}
+ >
+ {groupedByDay ? startedTime : `${startedDate}, ${startedTime}`}
+ </span>
+ </div>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 pl-6 text-xs tabular-nums">
+ {marks}
+ <span className="text-neutral-500 dark:text-neutral-400">
+ {t("Pages")}{" "}
+ <span className="text-neutral-800 dark:text-neutral-200">{session.pageviews.toLocaleString()}</span>
+ </span>
+ <span className="text-neutral-500 dark:text-neutral-400">
+ {t("Events")}{" "}
+ <span className={eventCount ? "text-neutral-800 dark:text-neutral-200" : undefined}>
+ {eventCount.toLocaleString()}
+ </span>
+ </span>
+ <span className="text-neutral-800 dark:text-neutral-200">
+ {formatShortDuration(session.session_duration)}
+ </span>
+ {errors}
+ {replay && <span className="-my-1">{replay}</span>}
+ </div>
+ <div className="flex min-w-0 items-center gap-3 pl-6">
+ <div className="min-w-0 flex-1">{paths}</div>
+ <div className="max-w-[40%] shrink-0">{sourceButton}</div>
+ </div>
+ {goal && <div className="pl-6">{goal}</div>}
+ </div>
+
+ {/* With room: one aligned line. */}
+ <div className={cn("h-9", ledgerGrid(showGoals, groupedByDay))}>
+ {toggle}
+ {user}
+ {marks}
+ {paths}
+ <div className="text-right tabular-nums">{session.pageviews.toLocaleString()}</div>
+ <div className={cn("text-right tabular-nums", !eventCount && "text-neutral-500")}>{events}</div>
+ <div className={cn("text-right tabular-nums", WIDE_ONLY_BLOCK)}>{errors}</div>
+ <div className="text-right tabular-nums">{formatShortDuration(session.session_duration)}</div>
+ <div className={cn("min-w-0 pl-2", WIDE_ONLY_FLEX)}>{sourceButton}</div>
+ {showGoals && <div className={cn("min-w-0", WIDE_ONLY_BLOCK)}>{goal}</div>}
+ <div className="flex justify-center">{replay}</div>
+ <div
+ className="truncate text-right text-xs tabular-nums text-neutral-500 dark:text-neutral-400"
+ title={startedFull}
+ >
+ {groupedByDay ? startedTime : `${startedDate}, ${startedTime}`}
+ </div>
+ </div>
+ </div>
+
+ {expanded && (
+ <SessionLedgerDetails
+ session={session}
+ userHref={userHref}
+ onWatchReplay={hasReplay ? () => setReplayOpen(true) : undefined}
+ />
+ )}
+
+ {hasReplay && <ReplayDrawer sessionId={session.session_id} open={replayOpen} onOpenChange={setReplayOpen} />}
+ </>
+ );
+}
diff --git a/client/src/app/[site]/sessions/components/SessionTimeline.tsx b/client/src/app/[site]/sessions/components/SessionTimeline.tsx
new file mode 100644
index 000000000..a4e2a0861
--- /dev/null
+++ b/client/src/app/[site]/sessions/components/SessionTimeline.tsx
@@ -0,0 +1,388 @@
+"use client";
+
+import {
+ Copy,
+ ExternalLink,
+ Eye,
+ FileInput,
+ LucideIcon,
+ MousePointerClick,
+ SquareMousePointer,
+ TextCursorInput,
+ TriangleAlert,
+} from "lucide-react";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import { useMemo, useState } from "react";
+import { SessionEvent } from "@/api/analytics/endpoints";
+import { useGetSessionDetailsInfinite } from "@/api/analytics/hooks/useGetUserSessions";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import { Skeleton } from "@/components/ui/skeleton";
+import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
+import { formatShortDuration } from "@/lib/dateTimeUtils";
+import { EVENT_TYPE_CONFIG, EventType, PROPS_TO_HIDE, useEventDisplayName } from "@/lib/events";
+import { useTimezone } from "@/lib/store";
+import { cn } from "@/lib/utils";
+import { GoalChip } from "./GoalChip";
+
+// Colour is kept for state: pageviews and autocaptured interactions are
+// neutral, tracked events take the data colour, errors are red.
+const NEUTRAL = "text-neutral-500 dark:text-neutral-400";
+const TYPE_MARKS: Record<EventType, { icon: LucideIcon; className: string }> = {
+ pageview: { icon: Eye, className: NEUTRAL },
+ custom_event: { icon: MousePointerClick, className: "text-dataviz" },
+ outbound: { icon: ExternalLink, className: NEUTRAL },
+ button_click: { icon: SquareMousePointer, className: NEUTRAL },
+ copy: { icon: Copy, className: NEUTRAL },
+ form_submit: { icon: FileInput, className: NEUTRAL },
+ input_change: { icon: TextCursorInput, className: NEUTRAL },
+ error: { icon: TriangleAlert, className: "text-red-500 dark:text-red-400" },
+};
+
+function TypeIcon({ type, className }: { type: string; className?: string }) {
+ const mark = TYPE_MARKS[type as EventType] ?? TYPE_MARKS.custom_event;
+ const Icon = mark.icon;
+ return <Icon aria-hidden="true" className={cn("h-4 w-4 shrink-0", mark.className, className)} />;
+}
+
+const toMillis = (timestamp: string) => DateTime.fromSQL(timestamp, { zone: "utc" }).toMillis();
+
+/**
+ * Seconds spent on each pageview, by its index in `events`: the time until the
+ * next pageview, or until the session's last event for the final one. The
+ * final page is only timed once every event is loaded.
+ */
+function timeOnPages(events: SessionEvent[], sessionEnd: string | undefined, complete: boolean) {
+ const seconds = new Map<number, number>();
+ let previous: number | null = null;
+
+ events.forEach((event, index) => {
+ if (event.type !== "pageview") return;
+ if (previous !== null) {
+ seconds.set(previous, Math.max(0, (toMillis(event.timestamp) - toMillis(events[previous].timestamp)) / 1000));
+ }
+ previous = index;
+ });
+
+ if (previous !== null && complete && sessionEnd) {
+ // A pageview that is also the session's last event has no measurable time.
+ const last = (toMillis(sessionEnd) - toMillis(events[previous].timestamp)) / 1000;
+ if (last >= 1) seconds.set(previous, last);
+ }
+ return seconds;
+}
+
+function PropBadge({ label, value }: { label: string; value: unknown }) {
+ const text = typeof value === "object" && value !== null ? JSON.stringify(value) : String(value);
+ return (
+ <span
+ title={`${label}: ${text}`}
+ className="inline-flex max-w-56 items-center rounded-md border border-neutral-150 px-1.5 py-0.5 text-xs dark:border-neutral-800"
+ >
+ <span className="mr-1 shrink-0 text-neutral-500 dark:text-neutral-400">{label}</span>
+ <span className="truncate font-medium text-neutral-800 dark:text-neutral-200">{text}</span>
+ </span>
+ );
+}
+
+/** The props worth a badge: not the ones the event's own label already spells out. */
+function badgeProps(event: SessionEvent): [string, unknown][] {
+ if (!event.props || event.type === "pageview") return [];
+ if (event.type === "error") return [];
+ if (event.type === "outbound") {
+ return (["text", "target"] as const).flatMap(key => (event.props?.[key] ? [[key, event.props[key]]] : []));
+ }
+ const hidden = PROPS_TO_HIDE[event.type] ?? [];
+ return Object.entries(event.props).filter(([key]) => !hidden.includes(key));
+}
+
+interface TimelineRowProps {
+ event: SessionEvent;
+ /** Seconds on this page; undefined for anything but a timed pageview. */
+ timeOnPage: number | undefined;
+ longestPage: number;
+ showHostname: boolean;
+}
+
+function TimelineRow({ event, timeOnPage, longestPage, showHostname }: TimelineRowProps) {
+ const t = useExtracted();
+ const eventDisplayName = useEventDisplayName();
+ const { hour12 } = useDateTimeFormat();
+ const zone = useTimezone();
+ const [stackOpen, setStackOpen] = useState(false);
+
+ const isPageview = event.type === "pageview";
+ const isError = event.type === "error";
+ const time = DateTime.fromSQL(event.timestamp, { zone: "utc" }).setZone(zone);
+ const outboundUrl = event.type === "outbound" && event.props?.url ? String(event.props.url) : null;
+ const message = isError && event.props?.message ? String(event.props.message) : null;
+ const stack = isError && event.props?.stack ? String(event.props.stack) : null;
+ const props = badgeProps(event);
+
+ return (
+ <li className="border-b border-neutral-100 py-1 last:border-0 dark:border-neutral-800/70">
+ <div className="flex min-h-6 items-center gap-3">
+ <span className="w-[4.5rem] shrink-0 text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
+ {time.toFormat(hour12 ? "h:mm:ss a" : "HH:mm:ss")}
+ </span>
+ {/* Everything that happened on a page sits indented under it. */}
+ <div
+ className={cn(
+ "flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1",
+ !isPageview && "@min-[520px]:pl-6"
+ )}
+ >
+ <TypeIcon type={event.type} />
+ {isPageview ? (
+ <a
+ href={`https://${event.hostname}${event.pathname}${event.querystring ?? ""}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={`${event.pathname}${event.querystring ?? ""}`}
+ className="min-w-0 truncate text-sm text-neutral-900 underline-offset-2 hover:underline dark:text-neutral-100"
+ >
+ {showHostname && event.hostname}
+ {event.pathname}
+ {event.querystring && <span className="text-neutral-500 dark:text-neutral-400">{event.querystring}</span>}
+ </a>
+ ) : outboundUrl ? (
+ <a
+ href={outboundUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={outboundUrl}
+ className="min-w-0 truncate text-sm font-medium text-neutral-900 underline-offset-2 hover:underline dark:text-neutral-100"
+ >
+ {outboundUrl}
+ </a>
+ ) : (
+ <span className="min-w-0 truncate text-sm font-medium text-neutral-900 dark:text-neutral-100">
+ {isError ? event.event_name || t("Error") : eventDisplayName(event)}
+ </span>
+ )}
+ {isPageview && event.page_title && (
+ <span className="hidden min-w-0 truncate text-xs text-neutral-500 @min-[520px]:inline dark:text-neutral-400">
+ {event.page_title}
+ </span>
+ )}
+ {message && (
+ <span title={message} className="min-w-0 truncate text-xs text-neutral-600 dark:text-neutral-300">
+ {message}
+ </span>
+ )}
+ {stack && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ aria-expanded={stackOpen}
+ onClick={() => setStackOpen(!stackOpen)}
+ className="font-normal text-neutral-600 dark:text-neutral-300"
+ >
+ {stackOpen ? t("Hide stack trace") : t("Stack trace")}
+ </Button>
+ )}
+ {props.map(([key, value]) => (
+ <PropBadge key={key} label={key} value={value} />
+ ))}
+ </div>
+ {event.goals?.map(goal => (
+ <GoalChip key={goal.id} goal={goal} className="hidden shrink-0 @min-[520px]:inline-flex" />
+ ))}
+ {timeOnPage !== undefined ? (
+ <div
+ className="flex w-16 shrink-0 items-center justify-end gap-2 @min-[520px]:w-28"
+ title={t("Time on page: {duration}", { duration: formatShortDuration(timeOnPage) })}
+ >
+ <div className="hidden h-1 flex-1 overflow-hidden rounded-full bg-neutral-100 @min-[520px]:block dark:bg-neutral-800">
+ <div
+ className="h-full rounded-full bg-dataviz/70"
+ style={{ width: `${longestPage > 0 ? Math.max(4, Math.round((timeOnPage / longestPage) * 100)) : 0}%` }}
+ />
+ </div>
+ <span className="w-14 text-right text-xs tabular-nums text-neutral-700 dark:text-neutral-300">
+ {formatShortDuration(timeOnPage)}
+ </span>
+ </div>
+ ) : (
+ <div className="hidden w-28 shrink-0 @min-[520px]:block" />
+ )}
+ </div>
+ {/* A narrow timeline has no room for the chip beside the label. */}
+ {!!event.goals?.length && (
+ <div className="mt-1 flex flex-wrap gap-1 pl-[5.25rem] @min-[520px]:hidden">
+ {event.goals.map(goal => (
+ <GoalChip key={goal.id} goal={goal} />
+ ))}
+ </div>
+ )}
+ {stack && stackOpen && (
+ <pre className="mb-1 mt-1.5 overflow-x-auto whitespace-pre-wrap break-words rounded-md bg-neutral-100 p-2 text-xs text-neutral-900 @min-[520px]:ml-[5.25rem] dark:bg-neutral-800 dark:text-neutral-100">
+ {stack}
+ </pre>
+ )}
+ </li>
+ );
+}
+
+function TimelineSkeleton({ rows }: { rows: number }) {
+ return (
+ <div aria-hidden="true">
+ <div className="mb-2 flex gap-1.5">
+ <Skeleton className="h-6 w-24 rounded" />
+ <Skeleton className="h-6 w-20 rounded" />
+ </div>
+ {Array.from({ length: rows }, (_, index) => (
+ <div
+ key={index}
+ className="flex h-8 items-center gap-3 border-b border-neutral-100 last:border-0 dark:border-neutral-800/70"
+ >
+ <Skeleton className="h-3 w-14 rounded" />
+ <Skeleton className="h-4 w-4 rounded" />
+ <Skeleton className={cn("h-3 rounded", index % 3 === 0 ? "w-40" : index % 3 === 1 ? "w-56" : "w-28")} />
+ </div>
+ ))}
+ </div>
+ );
+}
+
+interface SessionTimelineProps {
+ sessionId: string;
+ /** How many rows to sketch while loading; the session's own event count. */
+ expectedEvents: number;
+}
+
+/**
+ * Everything a session did, in order, one compact row per event: when, what,
+ * the goals it completed, and for pageviews how long the page was open. The
+ * type chips hide and show kinds of event; errors start visible.
+ */
+export function SessionTimeline({ sessionId, expectedEvents }: SessionTimelineProps) {
+ const t = useExtracted();
+ const { data, isLoading, error, fetchNextPage, hasNextPage, isFetchingNextPage } =
+ useGetSessionDetailsInfinite(sessionId);
+ const [hiddenTypes, setHiddenTypes] = useState<ReadonlySet<string>>(new Set());
+
+ const events = useMemo(() => data?.pages.flatMap(page => page?.events ?? []) ?? [], [data?.pages]);
+ const sessionEnd = data?.pages[0]?.session?.session_end;
+ const total = data?.pages[0]?.pagination?.total ?? 0;
+
+ const pageSeconds = useMemo(() => timeOnPages(events, sessionEnd, !hasNextPage), [events, sessionEnd, hasNextPage]);
+ const longestPage = Math.max(0, ...pageSeconds.values());
+
+ const typeCounts = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const event of events) counts.set(event.type, (counts.get(event.type) ?? 0) + 1);
+ return counts;
+ }, [events]);
+
+ const showHostname = useMemo(
+ () => new Set(events.filter(event => event.type === "pageview").map(event => event.hostname)).size > 1,
+ [events]
+ );
+
+ const typeLabels: Record<EventType, string> = {
+ pageview: t("Pageviews"),
+ custom_event: t("Events"),
+ outbound: t("Outbound"),
+ button_click: t("Button clicks"),
+ copy: t("Copies"),
+ form_submit: t("Form submits"),
+ input_change: t("Input changes"),
+ error: t("Errors"),
+ };
+
+ const toggleType = (type: string) =>
+ setHiddenTypes(current => {
+ const next = new Set(current);
+ if (!next.delete(type)) next.add(type);
+ return next;
+ });
+
+ if (isLoading) return <TimelineSkeleton rows={Math.min(Math.max(expectedEvents, 3), 12)} />;
+
+ if (error) {
+ return (
+ <Alert variant="destructive">
+ <AlertDescription>{t("Error loading session details. Please try again.")}</AlertDescription>
+ </Alert>
+ );
+ }
+
+ if (events.length === 0) {
+ return (
+ <div className="py-4 text-center text-sm text-neutral-500 dark:text-neutral-400">{t("No data available")}</div>
+ );
+ }
+
+ const presentTypes = EVENT_TYPE_CONFIG.filter(config => typeCounts.has(config.value));
+ const visible = events.map((event, index) => ({ event, index })).filter(({ event }) => !hiddenTypes.has(event.type));
+
+ return (
+ // Its rows size themselves against the timeline's own width: it is the
+ // whole ledger wide on a phone and a column beside the facts on a desktop.
+ <div className="@container">
+ <div className="mb-1.5 flex flex-wrap items-center gap-1.5">
+ {presentTypes.map(config => {
+ const on = !hiddenTypes.has(config.value);
+ return (
+ <button
+ key={config.value}
+ type="button"
+ aria-pressed={on}
+ onClick={() => toggleType(config.value)}
+ className={cn(
+ "flex items-center gap-1.5 whitespace-nowrap rounded px-2 py-1 text-xs font-medium transition-colors",
+ on
+ ? "bg-neutral-150 text-neutral-900 dark:bg-neutral-800 dark:text-white"
+ : "text-neutral-500 hover:text-neutral-700 dark:text-neutral-400 dark:hover:text-neutral-200"
+ )}
+ >
+ <TypeIcon type={config.value} className={cn("h-3 w-3", !on && "opacity-40")} />
+ {typeLabels[config.value]}
+ <span className="tabular-nums text-neutral-500 dark:text-neutral-400">
+ {typeCounts.get(config.value)}
+ </span>
+ </button>
+ );
+ })}
+ <span className="ml-auto text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
+ {t("{shown} of {total} events", {
+ shown: String(visible.length),
+ total: String(Math.max(total, events.length)),
+ })}
+ {/* Says what the bars on the pageview rows measure. */}
+ {pageSeconds.size > 0 && ` · ${t("time on page")}`}
+ </span>
+ </div>
+
+ <ol>
+ {visible.map(({ event, index }) => (
+ <TimelineRow
+ key={`${event.timestamp}-${index}`}
+ event={event}
+ timeOnPage={pageSeconds.get(index)}
+ longestPage={longestPage}
+ showHostname={showHostname}
+ />
+ ))}
+ </ol>
+
+ {hasNextPage && (
+ <div className="mt-2 flex justify-center">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => fetchNextPage()}
+ loading={isFetchingNextPage}
+ loadingLabel={t("Loading...")}
+ >
+ {t("Load More")}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/sessions/components/SessionsLedger.test.tsx b/client/src/app/[site]/sessions/components/SessionsLedger.test.tsx
new file mode 100644
index 000000000..53a5f3453
--- /dev/null
+++ b/client/src/app/[site]/sessions/components/SessionsLedger.test.tsx
@@ -0,0 +1,313 @@
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+import { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { GetSessionsResponse, SessionViewCounts } from "@/api/analytics/endpoints";
+import { useStore } from "@/lib/store";
+import { SessionsLedger, SessionsLedgerProps } from "./SessionsLedger";
+
+const mocks = vi.hoisted(() => ({
+ canWriteSegments: true,
+ segmentDialog: vi.fn(),
+}));
+
+// Enough of ICU for the messages under test: {name} and one/other plurals.
+const format = (message: string, values: Record<string, string | number> = {}) =>
+ message
+ .replace(/\{(\w+), plural, one \{([^}]*)\} other \{([^}]*)\}\}/g, (_, key, one, other) =>
+ (Number(values[key]) === 1 ? one : other).replace("#", String(values[key]))
+ )
+ .replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? ""));
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => format,
+ useLocale: () => "en-US",
+}));
+
+vi.mock("next/link", () => ({
+ default: ({ href, children, ...props }: { href: string; children: ReactNode }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+
+vi.mock("@/hooks/usePermissions", () => ({
+ useCanOnSite: () => mocks.canWriteSegments,
+}));
+
+vi.mock("../../components/SubHeader/Filters/SegmentDialog", () => ({
+ SegmentDialog: (props: { open: boolean }) => {
+ mocks.segmentDialog(props);
+ return props.open ? <div role="dialog" /> : null;
+ },
+}));
+
+// The row is covered by its own pieces; here it only has to say which session it is.
+vi.mock("./SessionLedgerRow", async importOriginal => ({
+ ...(await importOriginal<typeof import("./SessionLedgerRow")>()),
+ SessionLedgerRow: ({ session, groupedByDay }: { session: { session_id: string }; groupedByDay: boolean }) => (
+ <div data-testid="row" data-grouped={String(groupedByDay)}>
+ {session.session_id}
+ </div>
+ ),
+}));
+
+const session = (session_id: string, session_start: string) =>
+ ({ session_id, session_start }) as GetSessionsResponse[number];
+
+const sessions = [
+ session("a", "2026-09-30 14:00:00"),
+ session("b", "2026-09-30 09:00:00"),
+ session("c", "2026-09-29 22:00:00"),
+ session("d", "2026-09-27 08:00:00"),
+];
+
+const counts: SessionViewCounts = { all: 137, identified: 43, replay: 50, converted: 36, bounced: 42, errors: 1 };
+
+const handlers = () => ({
+ onViewChange: vi.fn(),
+ onSortChange: vi.fn(),
+ onPageChange: vi.fn(),
+ onPageSizeChange: vi.fn(),
+});
+
+const renderLedger = (props: Partial<SessionsLedgerProps> = {}) => {
+ const callbacks = handlers();
+ render(
+ <SessionsLedger
+ sessions={sessions}
+ isLoading={false}
+ isRefreshing={false}
+ isError={false}
+ view="all"
+ counts={counts}
+ dayCounts={
+ new Map([
+ ["2026-09-30", 30],
+ ["2026-09-29", 1],
+ ])
+ }
+ showReplay
+ narrowed={false}
+ sort={{ by: "started", order: "desc" }}
+ page={1}
+ pageSize={20}
+ {...callbacks}
+ {...props}
+ />
+ );
+ return callbacks;
+};
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date("2026-09-30T18:00:00Z"));
+ mocks.canWriteSegments = true;
+ mocks.segmentDialog.mockClear();
+ useStore.setState({ site: "5", privateKey: null, timezone: "UTC", filters: [] });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+describe("SessionsLedger views", () => {
+ it("offers every view with its count", () => {
+ renderLedger();
+
+ expect(screen.getAllByRole("tab").map(tab => tab.textContent)).toEqual([
+ "All137",
+ "Identified43",
+ "Has replay50",
+ "Converted36",
+ "Bounced42",
+ "With errors1",
+ ]);
+ expect(screen.getByRole("tab", { name: /^All/ }).getAttribute("aria-selected")).toBe("true");
+ });
+
+ it("has no Converted view or Goal column on a site without goals", () => {
+ renderLedger({ counts: { ...counts, converted: null } });
+
+ expect(screen.queryByRole("tab", { name: /Converted/ })).toBeNull();
+ expect(screen.queryByText("Goal")).toBeNull();
+ });
+
+ it("has no Has replay view on a site without a Replay page", () => {
+ renderLedger({ showReplay: false });
+
+ expect(screen.queryByRole("tab", { name: /Has replay/ })).toBeNull();
+ });
+
+ it("shows the views without counts until the summary arrives", () => {
+ renderLedger({ counts: undefined });
+
+ expect(screen.getByRole("tab", { name: "Bounced" })).toBeTruthy();
+ // Unknown yet whether the site has goals, so the column is not taken away.
+ expect(screen.getByText("Goal")).toBeTruthy();
+ });
+
+ it("reports the view that was picked", () => {
+ const { onViewChange } = renderLedger();
+
+ fireEvent.mouseDown(screen.getByRole("tab", { name: /With errors/ }), { button: 0 });
+
+ expect(onViewChange).toHaveBeenCalledWith("errors");
+ });
+});
+
+describe("SessionsLedger rows", () => {
+ it("groups rows under day headings with each day's total while in start order", () => {
+ renderLedger();
+
+ expect(screen.getByText("Today")).toBeTruthy();
+ expect(screen.getByText("30 sessions so far")).toBeTruthy();
+ expect(screen.getByText("Yesterday")).toBeTruthy();
+ // One session, and a past day is not "so far".
+ expect(screen.getByText("1 session")).toBeTruthy();
+ // A day the summary has no count for still gets its heading.
+ expect(screen.getByText("Sun, Sep 27")).toBeTruthy();
+
+ expect(screen.getAllByTestId("row").map(row => row.textContent)).toEqual(["a", "b", "c", "d"]);
+ expect(screen.getAllByTestId("row").every(row => row.dataset.grouped === "true")).toBe(true);
+ });
+
+ it("drops the day headings when sorted by anything but the start", () => {
+ renderLedger({ sort: { by: "duration", order: "desc" } });
+
+ expect(screen.queryByText("Today")).toBeNull();
+ expect(screen.getAllByTestId("row").every(row => row.dataset.grouped === "false")).toBe(true);
+ });
+
+ it("sketches rows while loading", () => {
+ renderLedger({ isLoading: true, sessions: [] });
+
+ expect(screen.queryAllByTestId("row")).toHaveLength(0);
+ expect(document.querySelectorAll(".animate-pulse").length).toBeGreaterThan(20);
+ expect(screen.queryByText("No sessions found")).toBeNull();
+ });
+
+ it("says so when the request failed, instead of claiming there are no sessions", () => {
+ renderLedger({ isError: true, sessions: [] });
+
+ expect(screen.getByText("Sessions could not be loaded. Please try again.")).toBeTruthy();
+ expect(screen.queryByText("No sessions found")).toBeNull();
+ });
+
+ it("suggests the next step that fits an empty list", () => {
+ renderLedger({ sessions: [] });
+ expect(screen.getByText("Try a different date range or filter")).toBeTruthy();
+ cleanup();
+
+ renderLedger({ sessions: [], narrowed: true });
+ expect(screen.getByText("Nothing matches this view. Try another view or a wider range.")).toBeTruthy();
+ cleanup();
+
+ renderLedger({ sessions: [], view: "identified" });
+ expect(screen.getByRole("link", { name: "Learn how to identify users" })).toBeTruthy();
+ });
+});
+
+describe("SessionsLedger sorting", () => {
+ const header = (name: string) => screen.getByRole("button", { name });
+
+ it("marks the sorted column", () => {
+ renderLedger();
+
+ expect(header("Started").getAttribute("aria-pressed")).toBe("true");
+ expect(header("Duration").getAttribute("aria-pressed")).toBe("false");
+ });
+
+ it("starts a new column at its highest and flips the active one", () => {
+ const { onSortChange } = renderLedger({ sort: { by: "duration", order: "desc" } });
+
+ fireEvent.click(header("Pages"));
+ expect(onSortChange).toHaveBeenLastCalledWith({ by: "pageviews", order: "desc" });
+
+ fireEvent.click(header("Duration"));
+ expect(onSortChange).toHaveBeenLastCalledWith({ by: "duration", order: "asc" });
+ });
+
+ it("flips back from ascending", () => {
+ const { onSortChange } = renderLedger({ sort: { by: "events", order: "asc" } });
+
+ fireEvent.click(header("Events"));
+ expect(onSortChange).toHaveBeenLastCalledWith({ by: "events", order: "desc" });
+ });
+});
+
+describe("SessionsLedger paging", () => {
+ it("pages over the current view's total", () => {
+ const { onPageChange } = renderLedger({ view: "identified", page: 2 });
+
+ expect(screen.getByText("Showing 21 to 40 of 43 sessions")).toBeTruthy();
+ expect(screen.getByLabelText("Page 2 of 3")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Next page" }));
+ expect(onPageChange).toHaveBeenCalledWith(3);
+ });
+
+ it("stops at the last page", () => {
+ renderLedger({ view: "identified", page: 3 });
+
+ expect(screen.getByRole("button", { name: "Next page" }).hasAttribute("disabled")).toBe(true);
+ });
+
+ it("pages open-ended until the total is known", () => {
+ renderLedger({ counts: undefined, pageSize: 4 });
+ // A full page may have more behind it.
+ expect(screen.getByRole("button", { name: "Next page" }).hasAttribute("disabled")).toBe(false);
+ cleanup();
+
+ renderLedger({ counts: undefined, pageSize: 20 });
+ expect(screen.getByRole("button", { name: "Next page" }).hasAttribute("disabled")).toBe(true);
+ });
+
+ it("has no pager on an empty first page but keeps the way back from an empty later one", () => {
+ renderLedger({ sessions: [] });
+ expect(screen.queryByRole("button", { name: "Previous page" })).toBeNull();
+ cleanup();
+
+ renderLedger({ sessions: [], page: 3 });
+ expect(screen.getByRole("button", { name: "Previous page" }).hasAttribute("disabled")).toBe(false);
+ });
+});
+
+describe("Save as segment", () => {
+ it("opens the segment dialog with the page's filters, without applying the new segment", () => {
+ useStore.setState({
+ filters: [
+ { parameter: "country", type: "equals", value: ["US"] },
+ // Not a Sessions filter, so the list ignores it and the segment leaves it out.
+ { parameter: "feature_flag:beta", type: "equals", value: ["on"] },
+ ],
+ });
+ renderLedger();
+
+ fireEvent.click(screen.getByRole("button", { name: "Save as segment" }));
+
+ expect(screen.getByRole("dialog")).toBeTruthy();
+ expect(mocks.segmentDialog).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ open: true,
+ siteId: "5",
+ applyOnCreate: false,
+ initialFilters: [{ parameter: "country", type: "equals", value: ["US"] }],
+ })
+ );
+ });
+
+ it("is not offered to someone who cannot write segments, or on a private link", () => {
+ mocks.canWriteSegments = false;
+ renderLedger();
+ expect(screen.queryByRole("button", { name: "Save as segment" })).toBeNull();
+ cleanup();
+
+ mocks.canWriteSegments = true;
+ useStore.setState({ privateKey: "abcdef123456" });
+ renderLedger();
+ expect(screen.queryByRole("button", { name: "Save as segment" })).toBeNull();
+ expect(within(document.body).queryByRole("dialog")).toBeNull();
+ });
+});
diff --git a/client/src/app/[site]/sessions/components/SessionsLedger.tsx b/client/src/app/[site]/sessions/components/SessionsLedger.tsx
new file mode 100644
index 000000000..881525a1c
--- /dev/null
+++ b/client/src/app/[site]/sessions/components/SessionsLedger.tsx
@@ -0,0 +1,434 @@
+"use client";
+
+import { ArrowDown, ArrowUp, ArrowUpDown, BookmarkPlus, Rewind, Video } from "lucide-react";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { ReactNode, useState } from "react";
+import { GetSessionsResponse, SessionSort, SessionView, SessionViewCounts } from "@/api/analytics/endpoints";
+import { NothingFound } from "@/components/NothingFound";
+import { Pagination } from "@/components/pagination";
+import { ControlButton } from "@/components/site/ControlButton";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
+import { useCanOnSite } from "@/hooks/usePermissions";
+import { SESSION_PAGE_FILTERS } from "@/lib/filterGroups";
+import { getFilteredFilters, useStore, useTimezone } from "@/lib/store";
+import { cn } from "@/lib/utils";
+import { SegmentDialog } from "../../components/SubHeader/Filters/SegmentDialog";
+import { groupSessionsByDay, relativeDay } from "../sessionDays";
+import { ledgerGrid, SessionLedgerRow, STACKED_ONLY, WIDE_ONLY_BLOCK, WIDE_ONLY_FLEX } from "./SessionLedgerRow";
+
+export interface SessionSortState {
+ by: SessionSort;
+ order: "asc" | "desc";
+}
+
+export const PAGE_SIZE_OPTIONS = [20, 50, 100];
+
+const VIEW_ORDER: SessionView[] = ["all", "identified", "replay", "converted", "bounced", "errors"];
+
+/**
+ * Saves the page's current filters as a segment. The saved views and the
+ * ranges are not filters, so they are not part of what is saved. Hidden for
+ * anyone who cannot write segments, and on a private link.
+ */
+function SaveSegmentButton() {
+ const t = useExtracted();
+ const site = useStore(state => state.site);
+ const privateKey = useStore(state => state.privateKey);
+ const canWriteSegments = useCanOnSite("segments:write", site);
+ const [open, setOpen] = useState(false);
+
+ if (privateKey || !canWriteSegments) return null;
+
+ return (
+ <>
+ <Button
+ type="button"
+ variant="accent"
+ size="sm"
+ className="shrink-0 gap-1.5"
+ aria-label={t("Save as segment")}
+ onClick={() => setOpen(true)}
+ >
+ <BookmarkPlus />
+ {/* The label gives way to the view tabs when the ledger is narrow. */}
+ <span className="hidden @min-[640px]:inline">{t("Save as segment")}</span>
+ </Button>
+ <SegmentDialog
+ open={open}
+ onOpenChange={setOpen}
+ siteId={site}
+ initialFilters={getFilteredFilters(SESSION_PAGE_FILTERS)}
+ availableFilters={SESSION_PAGE_FILTERS}
+ applyOnCreate={false}
+ />
+ </>
+ );
+}
+
+function SortHeader({
+ label,
+ column,
+ sort,
+ onSortChange,
+ className,
+}: {
+ label: string;
+ column: SessionSort;
+ sort: SessionSortState;
+ onSortChange: (sort: SessionSortState) => void;
+ className?: string;
+}) {
+ const t = useExtracted();
+ const active = sort.by === column;
+ const Icon = sort.order === "asc" ? ArrowUp : ArrowDown;
+
+ return (
+ <div className={cn("flex min-w-0 justify-end", className)}>
+ <button
+ type="button"
+ aria-pressed={active}
+ title={
+ !active
+ ? t("Sort by {column}", { column: label })
+ : sort.order === "asc"
+ ? t("Sorted by {column}, lowest first", { column: label })
+ : t("Sorted by {column}, highest first", { column: label })
+ }
+ // A new column starts at its largest; the active one flips.
+ onClick={() => onSortChange({ by: column, order: active && sort.order === "desc" ? "asc" : "desc" })}
+ className={cn(
+ "flex min-w-0 items-center gap-0.5 rounded font-medium hover:text-neutral-900 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400 dark:hover:text-neutral-100",
+ active && "text-neutral-900 dark:text-neutral-100"
+ )}
+ >
+ <span className="truncate">{label}</span>
+ {active && <Icon className="h-3 w-3 shrink-0" aria-hidden="true" />}
+ </button>
+ </div>
+ );
+}
+
+function LedgerSkeleton({
+ rows,
+ showGoals,
+ groupedByDay,
+}: {
+ rows: number;
+ showGoals: boolean;
+ groupedByDay: boolean;
+}) {
+ return (
+ <div aria-hidden="true">
+ {Array.from({ length: rows }, (_, index) => (
+ <div key={index} className="border-b border-neutral-100 dark:border-neutral-800">
+ <div className={cn("flex flex-col gap-2 px-3 py-2.5", STACKED_ONLY)}>
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-5 w-5 rounded-full" />
+ <Skeleton className="h-3 w-28 rounded" />
+ <Skeleton className="ml-auto h-3 w-12 rounded" />
+ </div>
+ <Skeleton className="ml-6 h-3 w-48 rounded" />
+ <Skeleton className="ml-6 h-3 w-36 rounded" />
+ </div>
+ <div className={cn("h-9", ledgerGrid(showGoals, groupedByDay))}>
+ <Skeleton className="h-4 w-4 rounded" />
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-5 w-5 shrink-0 rounded-full" />
+ <Skeleton className={cn("h-3 rounded", index % 2 ? "w-20" : "w-24")} />
+ </div>
+ <Skeleton className="h-4 w-[76px] rounded" />
+ <Skeleton className={cn("h-3 rounded", index % 3 === 0 ? "w-40" : index % 3 === 1 ? "w-56" : "w-32")} />
+ <Skeleton className="ml-auto h-3 w-4 rounded" />
+ <Skeleton className="ml-auto h-3 w-4 rounded" />
+ <div className={WIDE_ONLY_BLOCK} />
+ <Skeleton className="ml-auto h-3 w-10 rounded" />
+ <Skeleton className={cn("ml-2 h-3 w-20 rounded", WIDE_ONLY_BLOCK)} />
+ {showGoals && <div className={WIDE_ONLY_BLOCK} />}
+ <div />
+ <Skeleton className="ml-auto h-3 w-10 rounded" />
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+export interface SessionsLedgerProps {
+ sessions: GetSessionsResponse;
+ isLoading: boolean;
+ /** A refetch is replacing the rows on screen. */
+ isRefreshing: boolean;
+ isError: boolean;
+ view: SessionView;
+ onViewChange: (view: SessionView) => void;
+ /** Sessions per view with the ranges applied; undefined until the summary loads. */
+ counts: SessionViewCounts | undefined;
+ /** Sessions per day (YYYY-MM-DD) for the current view. */
+ dayCounts: Map<string, number>;
+ /** The site has a Replay page. */
+ showReplay: boolean;
+ /** A range is narrowing the list, which changes what the empty state suggests. */
+ narrowed: boolean;
+ sort: SessionSortState;
+ onSortChange: (sort: SessionSortState) => void;
+ page: number;
+ pageSize: number;
+ onPageChange: (page: number) => void;
+ onPageSizeChange: (size: number) => void;
+}
+
+/**
+ * The sessions ledger: saved views across the top, one aligned row per
+ * session with sortable columns, day headings while it is in start order, and
+ * a real total underneath.
+ */
+export function SessionsLedger({
+ sessions,
+ isLoading,
+ isRefreshing,
+ isError,
+ view,
+ onViewChange,
+ counts,
+ dayCounts,
+ showReplay,
+ narrowed,
+ sort,
+ onSortChange,
+ page,
+ pageSize,
+ onPageChange,
+ onPageSizeChange,
+}: SessionsLedgerProps) {
+ const t = useExtracted();
+ const zone = useTimezone();
+ const { formatDateTime } = useDateTimeFormat();
+
+ // Until the summary says otherwise, assume the site has goals: the column is
+ // only removed once it is known to be empty for good.
+ const showGoals = counts ? counts.converted !== null : true;
+ const total = counts?.[view] ?? undefined;
+ const groupedByDay = sort.by === "started";
+
+ const viewLabels: Record<SessionView, string> = {
+ all: t("All"),
+ identified: t("Identified"),
+ replay: t("Has replay"),
+ converted: t("Converted"),
+ bounced: t("Bounced"),
+ errors: t("With errors"),
+ };
+ const views = VIEW_ORDER.filter(
+ candidate => (candidate !== "replay" || showReplay) && (candidate !== "converted" || showGoals)
+ );
+
+ const sortLabels: Record<Exclude<SessionSort, "ended">, string> = {
+ started: t("Started"),
+ duration: t("Duration"),
+ pageviews: t("Pages"),
+ events: t("Events"),
+ errors: t("Errors"),
+ };
+ const sortLabel = sort.by === "ended" ? t("Started") : sortLabels[sort.by];
+
+ const dayHeading = (day: string, count: number | undefined): ReactNode => {
+ const relative = relativeDay(day, zone);
+ const date = formatDateTime(DateTime.fromISO(day, { zone }), {
+ weekday: "short",
+ month: "short",
+ day: "numeric",
+ timeZone: zone,
+ });
+
+ return (
+ <div className="flex h-7 items-center justify-between gap-3 border-b border-neutral-100 px-3 text-xs dark:border-neutral-800">
+ <span className="truncate font-medium text-neutral-700 dark:text-neutral-200">
+ {relative ? (
+ <>
+ {relative === "today" ? t("Today") : t("Yesterday")}{" "}
+ <span className="font-normal text-neutral-500 dark:text-neutral-400">{date}</span>
+ </>
+ ) : (
+ date
+ )}
+ </span>
+ {count !== undefined && (
+ <span className="shrink-0 tabular-nums text-neutral-500 dark:text-neutral-400">
+ {relative === "today"
+ ? t("{count, plural, one {# session so far} other {# sessions so far}}", { count })
+ : t("{count, plural, one {# session} other {# sessions}}", { count })}
+ </span>
+ )}
+ </div>
+ );
+ };
+
+ const row = (session: GetSessionsResponse[number]) => (
+ <SessionLedgerRow
+ key={session.session_id}
+ session={session}
+ showGoals={showGoals}
+ showReplay={showReplay}
+ groupedByDay={groupedByDay}
+ />
+ );
+
+ const emptyDescription: ReactNode =
+ view === "identified" ? (
+ <>
+ {t("No identified visitors match.")}{" "}
+ <Link
+ href="https://www.rybbit.io/docs/identify-users"
+ target="_blank"
+ className="underline underline-offset-2 hover:text-neutral-900 dark:hover:text-neutral-200"
+ >
+ {t("Learn how to identify users")}
+ </Link>
+ </>
+ ) : view !== "all" || narrowed ? (
+ t("Nothing matches this view. Try another view or a wider range.")
+ ) : (
+ t("Try a different date range or filter")
+ );
+
+ return (
+ // The container its rows and header size themselves against (see SessionLedgerRow).
+ <div className="@container overflow-hidden rounded-lg border border-neutral-100 bg-white dark:border-neutral-850 dark:bg-neutral-900">
+ <div className="flex items-center justify-between gap-2 border-b border-neutral-100 px-3 py-2 dark:border-neutral-800">
+ <div className="min-w-0 overflow-x-auto [scrollbar-width:none]">
+ <Tabs value={view} onValueChange={next => onViewChange(next as SessionView)}>
+ <TabsList className="h-8">
+ {views.map(candidate => (
+ <TabsTrigger key={candidate} value={candidate} className="gap-1.5 px-2.5 text-[13px]">
+ {viewLabels[candidate]}
+ {counts && (
+ <span className="font-normal tabular-nums text-neutral-500 dark:text-neutral-400">
+ {(counts[candidate] ?? 0).toLocaleString()}
+ </span>
+ )}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
+ </div>
+ <SaveSegmentButton />
+ </div>
+
+ {/* The stacked layout has no column headers to sort by. */}
+ <div className={cn("flex border-b border-neutral-100 px-3 py-2 dark:border-neutral-800", STACKED_ONLY)}>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <ControlButton icon={<ArrowUpDown />} label={t("Sort")} value={sortLabel} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={sort.by}
+ onValueChange={next => onSortChange({ by: next as SessionSort, order: "desc" })}
+ >
+ {(Object.keys(sortLabels) as (keyof typeof sortLabels)[]).map(column => (
+ <DropdownMenuRadioItem key={column} value={column}>
+ {sortLabels[column]}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuRadioGroup
+ value={sort.order}
+ onValueChange={next => onSortChange({ by: sort.by, order: next === "asc" ? "asc" : "desc" })}
+ >
+ <DropdownMenuRadioItem value="desc">{t("Highest or newest first")}</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="asc">{t("Lowest or oldest first")}</DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+
+ <div
+ className={cn(
+ "h-8 border-b border-neutral-100 bg-neutral-50 text-xs font-medium text-neutral-500 dark:border-neutral-800 dark:bg-neutral-850 dark:text-neutral-400",
+ ledgerGrid(showGoals, groupedByDay)
+ )}
+ >
+ <div />
+ <div className="truncate">{t("User")}</div>
+ <div className="truncate">{t("Device")}</div>
+ <div className="truncate">{t("Entry and exit page")}</div>
+ <SortHeader label={t("Pages")} column="pageviews" sort={sort} onSortChange={onSortChange} />
+ <SortHeader label={t("Events")} column="events" sort={sort} onSortChange={onSortChange} />
+ <SortHeader
+ label={t("Errors")}
+ column="errors"
+ sort={sort}
+ onSortChange={onSortChange}
+ className={WIDE_ONLY_FLEX}
+ />
+ <SortHeader label={t("Duration")} column="duration" sort={sort} onSortChange={onSortChange} />
+ <div className={cn("truncate pl-2", WIDE_ONLY_BLOCK)}>{t("Source")}</div>
+ {showGoals && <div className={cn("truncate", WIDE_ONLY_BLOCK)}>{t("Goal")}</div>}
+ <div className="flex justify-center">
+ {showReplay && <Video className="h-3.5 w-3.5" aria-hidden="true" />}
+ <span className="sr-only">{t("Replay")}</span>
+ </div>
+ <SortHeader label={t("Started")} column="started" sort={sort} onSortChange={onSortChange} />
+ </div>
+
+ {isLoading ? (
+ <LedgerSkeleton rows={Math.min(pageSize, 20)} showGoals={showGoals} groupedByDay={groupedByDay} />
+ ) : isError ? (
+ <div className="p-3">
+ <Alert variant="destructive">
+ <AlertDescription>{t("Sessions could not be loaded. Please try again.")}</AlertDescription>
+ </Alert>
+ </div>
+ ) : sessions.length === 0 ? (
+ <NothingFound
+ icon={<Rewind className="h-10 w-10" />}
+ title={t("No sessions found")}
+ description={emptyDescription}
+ />
+ ) : (
+ <div className={cn("transition-opacity", isRefreshing && "opacity-60")}>
+ {groupedByDay
+ ? groupSessionsByDay(sessions, zone).map(group => (
+ <div key={group.day}>
+ {dayHeading(group.day, dayCounts.get(group.day))}
+ {group.sessions.map(row)}
+ </div>
+ ))
+ : sessions.map(row)}
+ </div>
+ )}
+
+ {!isLoading && !isError && (sessions.length > 0 || page > 1) && (
+ <div className="px-3 py-2">
+ <Pagination
+ page={page}
+ pageSize={pageSize}
+ totalItems={total}
+ pageCount={total !== undefined ? Math.max(1, Math.ceil(total / pageSize)) : undefined}
+ // Without a total yet, a full page is the only sign there may be more.
+ hasNextPage={total !== undefined ? undefined : sessions.length === pageSize}
+ onPageChange={onPageChange}
+ onPageSizeChange={onPageSizeChange}
+ pageSizeOptions={PAGE_SIZE_OPTIONS}
+ itemName={t("sessions")}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/sessions/components/SessionsStatBand.test.tsx b/client/src/app/[site]/sessions/components/SessionsStatBand.test.tsx
new file mode 100644
index 000000000..186ebdb6b
--- /dev/null
+++ b/client/src/app/[site]/sessions/components/SessionsStatBand.test.tsx
@@ -0,0 +1,140 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SessionsSummary } from "@/api/analytics/endpoints";
+import { SessionsStatBand } from "./SessionsStatBand";
+
+const mocks = vi.hoisted(() => ({ comparisonEnabled: true }));
+
+// Enough of ICU for the messages under test: {name} and one/other plurals.
+const format = (message: string, values: Record<string, string | number> = {}) =>
+ message
+ .replace(/\{(\w+), plural, one \{([^}]*)\} other \{([^}]*)\}\}/g, (_, key, one, other) =>
+ (Number(values[key]) === 1 ? one : other).replace("#", String(values[key]))
+ )
+ .replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? ""));
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => format,
+}));
+
+vi.mock("@/lib/store", () => ({
+ useComparisonEnabled: () => mocks.comparisonEnabled,
+}));
+
+const matching = { all: 0, identified: 0, replay: 0, converted: 0, bounced: 0, errors: 0 };
+
+const summary = (overrides: Partial<SessionsSummary> = {}): SessionsSummary => ({
+ sessions: 2000,
+ session_duration: 164,
+ pages_per_session: 2.534,
+ bounce_rate: 41.2,
+ converted: 650,
+ with_errors: 44,
+ matching,
+ days: [],
+ ...overrides,
+});
+
+const previous = summary({
+ sessions: 1600,
+ session_duration: 151,
+ pages_per_session: 2.5,
+ bounce_rate: 43.1,
+ converted: 480,
+ with_errors: 30,
+});
+
+const labels = () => [...document.querySelectorAll(".uppercase")].map(label => label.textContent);
+
+beforeEach(() => {
+ mocks.comparisonEnabled = true;
+});
+
+afterEach(cleanup);
+
+describe("SessionsStatBand", () => {
+ it("shows the period's six figures", () => {
+ render(<SessionsStatBand summary={summary()} previous={previous} isLoading={false} />);
+
+ expect(labels()).toEqual([
+ "Sessions",
+ "Avg duration",
+ "Pages per session",
+ "Bounce rate",
+ "Converted",
+ "With errors",
+ ]);
+ expect(screen.getByText("2m 44s")).toBeTruthy();
+ expect(screen.getByText("2.53")).toBeTruthy();
+ expect(screen.getByText("41.2%")).toBeTruthy();
+ // 650 and 44 of 2,000 sessions.
+ expect(screen.getByText("32.5%")).toBeTruthy();
+ expect(screen.getByText("2.2%")).toBeTruthy();
+ expect(screen.getByText("650 sessions, any goal")).toBeTruthy();
+ expect(screen.getByText("44 sessions")).toBeTruthy();
+ });
+
+ it("compares each figure with the previous period: percent for amounts, points for rates", () => {
+ render(<SessionsStatBand summary={summary()} previous={previous} isLoading={false} />);
+
+ expect(screen.getByText("25.0%")).toBeTruthy(); // sessions 2,000 against 1,600
+ expect(screen.getByText("8.6%")).toBeTruthy(); // duration 164s against 151s
+ expect(screen.getByText("1.9 pp")).toBeTruthy(); // bounce 41.2% against 43.1%
+ expect(screen.getByText("2.5 pp")).toBeTruthy(); // converted 32.5% against 30.0%
+ expect(screen.getByText("0.3 pp")).toBeTruthy(); // errors 2.2% against 1.9%
+ expect(screen.getByText("2m 31s prev.")).toBeTruthy();
+ expect(screen.getByText("43.1% prev.")).toBeTruthy();
+ });
+
+ it("colours a falling bounce rate as good and rising errors as bad", () => {
+ render(<SessionsStatBand summary={summary()} previous={previous} isLoading={false} />);
+
+ expect(screen.getByText("1.9 pp").parentElement?.className).toContain("emerald");
+ expect(screen.getByText("0.3 pp").parentElement?.className).toContain("red");
+ });
+
+ it("draws no deltas or previous values with the comparison off", () => {
+ mocks.comparisonEnabled = false;
+ render(<SessionsStatBand summary={summary()} previous={undefined} isLoading={false} />);
+
+ expect(screen.queryByText(/prev\./)).toBeNull();
+ expect(screen.queryByText(/pp$/)).toBeNull();
+ // The counts under the two rates are not comparisons and stay.
+ expect(screen.getByText("44 sessions")).toBeTruthy();
+ });
+
+ it("leaves conversions out on a site with no goals", () => {
+ render(<SessionsStatBand summary={summary({ converted: null })} previous={previous} isLoading={false} />);
+
+ expect(labels()).toEqual(["Sessions", "Avg duration", "Pages per session", "Bounce rate", "With errors"]);
+ });
+
+ it("reports an empty period as zeros, not as NaN", () => {
+ render(
+ <SessionsStatBand
+ summary={summary({
+ sessions: 0,
+ session_duration: 0,
+ pages_per_session: 0,
+ bounce_rate: 0,
+ converted: 0,
+ with_errors: 0,
+ })}
+ previous={undefined}
+ isLoading={false}
+ />
+ );
+
+ expect(document.body.textContent).not.toContain("NaN");
+ expect(screen.getByText("0 sessions")).toBeTruthy();
+ expect(screen.getByText("0 sessions, any goal")).toBeTruthy();
+ });
+
+ it("keeps its labels and hides its values while loading", () => {
+ render(<SessionsStatBand summary={undefined} previous={undefined} isLoading />);
+
+ expect(labels()).toContain("Sessions");
+ expect(screen.queryByText("0s")).toBeNull();
+ expect(document.querySelectorAll(".animate-pulse").length).toBeGreaterThan(0);
+ });
+});
diff --git a/client/src/app/[site]/sessions/components/SessionsStatBand.tsx b/client/src/app/[site]/sessions/components/SessionsStatBand.tsx
new file mode 100644
index 000000000..89493677f
--- /dev/null
+++ b/client/src/app/[site]/sessions/components/SessionsStatBand.tsx
@@ -0,0 +1,101 @@
+"use client";
+
+import { Clock, Files, LogOut, Rewind, Target, TriangleAlert } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { SessionsSummary } from "@/api/analytics/endpoints";
+import { StatBand } from "@/components/site/StatBand";
+import { formatShortDuration } from "@/lib/dateTimeUtils";
+import { percentDelta, pointDelta } from "@/lib/delta";
+import { useComparisonEnabled } from "@/lib/store";
+import { formatter } from "@/lib/utils";
+
+// A count as a percentage of the period's sessions; undefined when there is no count to show.
+const share = (count: number | null | undefined, sessions: number | undefined) => {
+ if (count == null || sessions === undefined) return undefined;
+ return sessions > 0 ? (count / sessions) * 100 : 0;
+};
+
+const percent = (value: number | undefined) => (value === undefined ? "" : `${value.toFixed(1)}%`);
+
+interface SessionsStatBandProps {
+ summary: SessionsSummary | undefined;
+ /** The comparison period's summary; undefined while it loads or when the comparison is off. */
+ previous: SessionsSummary | undefined;
+ isLoading: boolean;
+}
+
+/**
+ * The period at a glance. These figures describe every session the filters
+ * allow; the ranges and the saved views narrow the ledger below, not the band.
+ */
+export function SessionsStatBand({ summary, previous, isLoading }: SessionsStatBandProps) {
+ const t = useExtracted();
+ const comparisonEnabled = useComparisonEnabled();
+
+ // With the comparison on, the line is reserved while the previous period loads.
+ const previousLine = (format: (period: SessionsSummary) => string) =>
+ comparisonEnabled ? (previous ? t("{value} prev.", { value: format(previous) }) : "") : undefined;
+
+ const convertedShare = share(summary?.converted, summary?.sessions);
+ const errorShare = share(summary?.with_errors, summary?.sessions);
+
+ return (
+ <StatBand
+ isLoading={isLoading || !summary}
+ cells={[
+ {
+ id: "sessions",
+ icon: <Rewind className="h-3 w-3" />,
+ label: t("Sessions"),
+ value: formatter(summary?.sessions ?? 0),
+ title: summary?.sessions.toLocaleString(),
+ delta: percentDelta(summary?.sessions, previous?.sessions),
+ sub: previousLine(period => formatter(period.sessions)),
+ },
+ {
+ id: "duration",
+ icon: <Clock className="h-3 w-3" />,
+ label: t("Avg duration"),
+ value: formatShortDuration(summary?.session_duration ?? 0),
+ delta: percentDelta(summary?.session_duration, previous?.session_duration),
+ sub: previousLine(period => formatShortDuration(period.session_duration)),
+ },
+ {
+ id: "pages",
+ icon: <Files className="h-3 w-3" />,
+ label: t("Pages per session"),
+ value: (summary?.pages_per_session ?? 0).toFixed(2),
+ delta: percentDelta(summary?.pages_per_session, previous?.pages_per_session),
+ sub: previousLine(period => period.pages_per_session.toFixed(2)),
+ },
+ {
+ id: "bounce",
+ icon: <LogOut className="h-3 w-3" />,
+ label: t("Bounce rate"),
+ value: percent(summary?.bounce_rate),
+ delta: pointDelta(summary?.bounce_rate, previous?.bounce_rate),
+ upIsGood: false,
+ sub: previousLine(period => percent(period.bounce_rate)),
+ },
+ // A site with no goals has no conversions to report.
+ summary?.converted != null && {
+ id: "converted",
+ icon: <Target className="h-3 w-3" />,
+ label: t("Converted"),
+ value: percent(convertedShare),
+ delta: pointDelta(convertedShare, share(previous?.converted, previous?.sessions)),
+ sub: t("{count, plural, one {# session} other {# sessions}}, any goal", { count: summary.converted }),
+ },
+ {
+ id: "errors",
+ icon: <TriangleAlert className="h-3 w-3" />,
+ label: t("With errors"),
+ value: percent(errorShare),
+ delta: pointDelta(errorShare, share(previous?.with_errors, previous?.sessions)),
+ upIsGood: false,
+ sub: t("{count, plural, one {# session} other {# sessions}}", { count: summary?.with_errors ?? 0 }),
+ },
+ ]}
+ />
+ );
+}
diff --git a/client/src/app/[site]/sessions/components/useSitePath.ts b/client/src/app/[site]/sessions/components/useSitePath.ts
new file mode 100644
index 000000000..9fb6bf127
--- /dev/null
+++ b/client/src/app/[site]/sessions/components/useSitePath.ts
@@ -0,0 +1,19 @@
+import { useSearchParams } from "next/navigation";
+import { useStore } from "@/lib/store";
+
+/**
+ * Builds links to other pages of the site being viewed. They stay inside a
+ * private link, and `keepQuery` carries the address bar's period and filters
+ * across the way the sidebar's links do.
+ */
+export function useSitePath(): (route: string, options?: { keepQuery?: boolean }) => string {
+ const site = useStore(state => state.site);
+ const privateKey = useStore(state => state.privateKey);
+ const searchParams = useSearchParams();
+
+ return (route, { keepQuery = false } = {}) => {
+ const path = privateKey ? `/${site}/${privateKey}/${route}` : `/${site}/${route}`;
+ const query = keepQuery ? searchParams.toString() : "";
+ return query ? `${path}?${query}` : path;
+ };
+}
diff --git a/client/src/app/[site]/sessions/page.tsx b/client/src/app/[site]/sessions/page.tsx
index b67448c07..210d9978a 100644
--- a/client/src/app/[site]/sessions/page.tsx
+++ b/client/src/app/[site]/sessions/page.tsx
@@ -1,158 +1,136 @@
"use client";
import { useExtracted } from "next-intl";
-import { SessionsList } from "@/components/Sessions/SessionsList";
-import { Info } from "lucide-react";
-import Link from "next/link";
-import { useState } from "react";
-import { useGetSessions } from "../../../api/analytics/hooks/useGetUserSessions";
-import { DisabledOverlay } from "../../../components/DisabledOverlay";
-import { Input } from "../../../components/ui/input";
-import { Label } from "../../../components/ui/label";
-import { Switch } from "../../../components/ui/switch";
-import { Tooltip, TooltipContent, TooltipTrigger } from "../../../components/ui/tooltip";
-import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
-import { SESSION_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { useMemo, useState } from "react";
+import { SessionView } from "@/api/analytics/endpoints";
+import { useGetSessionsSummary } from "@/api/analytics/hooks/useGetSessionsSummary";
+import { useGetSessions } from "@/api/analytics/hooks/useGetUserSessions";
+import { DisabledOverlay } from "@/components/DisabledOverlay";
+import { AnalysisBar } from "@/components/site/AnalysisBar";
+import { useReplayAvailable } from "@/hooks/useReplayAvailable";
+import { useSetPageTitle } from "@/hooks/useSetPageTitle";
+import { SESSION_PAGE_FILTERS } from "@/lib/filterGroups";
+import { useComparisonEnabled, useStore } from "@/lib/store";
import { SubHeader } from "../components/SubHeader/SubHeader";
+import { RangeChip } from "./components/RangeChip";
+import { PAGE_SIZE_OPTIONS, SessionSortState, SessionsLedger } from "./components/SessionsLedger";
+import { SessionsStatBand } from "./components/SessionsStatBand";
+import { EMPTY_RANGES, hasAnyRange, RangeMetric, RangeValue, SessionRanges, toRangeParams } from "./sessionRanges";
-const LIMIT = 100;
+const DEFAULT_SORT: SessionSortState = { by: "started", order: "desc" };
export default function SessionsPage() {
const t = useExtracted();
useSetPageTitle("Sessions");
- const [page, setPage] = useState(1);
- const [identifiedOnly, setIdentifiedOnly] = useState(false);
- const [minPageviews, setMinPageviews] = useState<number | undefined>(undefined);
- const [minEvents, setMinEvents] = useState<number | undefined>(undefined);
- const [minDuration, setMinDuration] = useState<number | undefined>(undefined);
- const { data, isLoading } = useGetSessions({
- page: page,
- limit: LIMIT + 1,
- identifiedOnly: identifiedOnly,
- minPageviews,
- minEvents,
- minDuration,
- });
- const allSessions = data || [];
- const hasNextPage = allSessions.length > LIMIT;
- const sessions = allSessions.slice(0, LIMIT);
- const hasPrevPage = page > 1;
+ const [view, setView] = useState<SessionView>("all");
+ const [sort, setSort] = useState<SessionSortState>(DEFAULT_SORT);
+ const [ranges, setRanges] = useState<SessionRanges>(EMPTY_RANGES);
+ const [pageSize, setPageSize] = useState(PAGE_SIZE_OPTIONS[0]);
- const handleNumberInput = (
- value: string,
- setter: (val: number | undefined) => void
- ) => {
- if (value === "") {
- setter(undefined);
- } else {
- const num = parseInt(value, 10);
- if (!isNaN(num) && num >= 0) {
- setter(num);
- }
- }
- setPage(1);
- };
+ // The page number only means something for one list. Anything that changes
+ // which sessions are listed, or their order, starts again from page 1; the
+ // number is stored with the list it belongs to, so no effect has to reset it.
+ const time = useStore(state => state.time);
+ const filters = useStore(state => state.filters);
+ const segmentId = useStore(state => state.segmentId);
+ const listKey = JSON.stringify([time, filters, segmentId, view, sort, ranges, pageSize]);
+ const [pageState, setPageState] = useState({ listKey, page: 1 });
+ const page = pageState.listKey === listKey ? pageState.page : 1;
+ const setPage = (next: number) => setPageState({ listKey, page: next });
- const headerElement = (
- <div className="flex items-center gap-4 flex-wrap">
- {/* Identified only toggle */}
- <div className="flex items-center gap-2">
- <Switch
- id="identified-only"
- checked={identifiedOnly}
- onCheckedChange={val => {
- setIdentifiedOnly(val);
- setPage(1);
- }}
- />
- <Label
- htmlFor="identified-only"
- className="text-sm text-neutral-600 dark:text-neutral-400 cursor-pointer"
- >
- {t("Identified only")}
- </Label>
- <Tooltip>
- <TooltipTrigger asChild>
- <Link href="https://www.rybbit.io/docs/identify-users" target="_blank">
- <Info className="h-4 w-4 text-neutral-400 hover:text-neutral-600 dark:hover:text-neutral-300 cursor-pointer" />
- </Link>
- </TooltipTrigger>
- <TooltipContent>
- <p>{t("Learn how to identify users")}</p>
- </TooltipContent>
- </Tooltip>
- </div>
+ const setRange = (metric: RangeMetric) => (value: RangeValue) =>
+ setRanges(current => ({ ...current, [metric]: value }));
+ const rangeParams = toRangeParams(ranges);
- {/* Min filters - hidden on mobile */}
- <div className="hidden md:flex items-center gap-4">
- <div className="flex items-center gap-2">
- <Label
- htmlFor="min-pageviews"
- className="text-sm text-neutral-600 dark:text-neutral-400 whitespace-nowrap"
- >
- {t("Min pageviews")}
- </Label>
- <Input
- id="min-pageviews"
- type="number"
- min={0}
- placeholder="0"
- value={minPageviews ?? ""}
- onChange={e => handleNumberInput(e.target.value, setMinPageviews)}
- className="w-20 h-8"
- />
- </div>
- <div className="flex items-center gap-2">
- <Label
- htmlFor="min-events"
- className="text-sm text-neutral-600 dark:text-neutral-400 whitespace-nowrap"
- >
- {t("Min events")}
- </Label>
- <Input
- id="min-events"
- type="number"
- min={0}
- placeholder="0"
- value={minEvents ?? ""}
- onChange={e => handleNumberInput(e.target.value, setMinEvents)}
- className="w-20 h-8"
- />
- </div>
- <div className="flex items-center gap-2">
- <Label
- htmlFor="min-duration"
- className="text-sm text-neutral-600 dark:text-neutral-400 whitespace-nowrap"
- >
- {t("Min duration (s)")}
- </Label>
- <Input
- id="min-duration"
- type="number"
- min={0}
- placeholder="0"
- value={minDuration ?? ""}
- onChange={e => handleNumberInput(e.target.value, setMinDuration)}
- className="w-20 h-8"
- />
- </div>
- </div>
- </div>
+ const replayAvailable = useReplayAvailable();
+ const comparisonEnabled = useComparisonEnabled();
+
+ const {
+ data: sessions,
+ isLoading,
+ isError,
+ isPlaceholderData,
+ } = useGetSessions({
+ page,
+ limit: pageSize,
+ view: view === "all" ? undefined : view,
+ sortBy: sort.by,
+ sortOrder: sort.order,
+ includeGoals: true,
+ ...rangeParams,
+ });
+ const { data: summary, isLoading: isSummaryLoading } = useGetSessionsSummary(rangeParams);
+ // The band describes the whole period, so its comparison takes no ranges.
+ const { data: previousSummary } = useGetSessionsSummary({ periodTime: "previous" });
+
+ const dayCounts = useMemo(
+ () => new Map((summary?.days ?? []).map(day => [day.day, day[view] ?? 0])),
+ [summary?.days, view]
);
+ const narrowed = hasAnyRange(ranges);
+
return (
<DisabledOverlay message={t("Sessions")} featurePath="sessions">
<div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
<SubHeader availableFilters={SESSION_PAGE_FILTERS} />
- <SessionsList
- sessions={sessions}
+ <SessionsStatBand
+ summary={summary}
+ previous={comparisonEnabled ? previousSummary : undefined}
+ isLoading={isSummaryLoading}
+ />
+ <AnalysisBar
+ end={
+ narrowed && summary ? (
+ <span className="whitespace-nowrap text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
+ {t.rich("<b>{matching}</b> of {total} sessions match", {
+ matching: summary.matching.all.toLocaleString(),
+ total: summary.sessions.toLocaleString(),
+ b: chunks => <span className="font-medium text-neutral-900 dark:text-neutral-100">{chunks}</span>,
+ })}
+ </span>
+ ) : null
+ }
+ >
+ <div className="mx-1 hidden h-5 w-px bg-neutral-200 sm:block dark:bg-neutral-800" />
+ <RangeChip
+ label={t("Pageviews")}
+ clearLabel={t("Clear pageviews range")}
+ value={ranges.pageviews}
+ onChange={setRange("pageviews")}
+ />
+ <RangeChip
+ label={t("Events")}
+ clearLabel={t("Clear events range")}
+ value={ranges.events}
+ onChange={setRange("events")}
+ />
+ <RangeChip
+ label={t("Duration")}
+ clearLabel={t("Clear duration range")}
+ value={ranges.duration}
+ onChange={setRange("duration")}
+ duration
+ />
+ </AnalysisBar>
+ <SessionsLedger
+ sessions={sessions ?? []}
isLoading={isLoading}
+ isRefreshing={isPlaceholderData}
+ isError={isError}
+ view={view}
+ onViewChange={setView}
+ counts={summary?.matching}
+ dayCounts={dayCounts}
+ showReplay={replayAvailable}
+ narrowed={narrowed}
+ sort={sort}
+ onSortChange={setSort}
page={page}
+ pageSize={pageSize}
onPageChange={setPage}
- hasNextPage={hasNextPage}
- hasPrevPage={hasPrevPage}
- headerElement={headerElement}
+ onPageSizeChange={setPageSize}
/>
</div>
</DisabledOverlay>
diff --git a/client/src/app/[site]/sessions/sessionDays.test.ts b/client/src/app/[site]/sessions/sessionDays.test.ts
new file mode 100644
index 000000000..0a0903a92
--- /dev/null
+++ b/client/src/app/[site]/sessions/sessionDays.test.ts
@@ -0,0 +1,73 @@
+import { DateTime } from "luxon";
+import { describe, expect, it } from "vitest";
+import { groupSessionsByDay, relativeDay, sessionDayKey } from "./sessionDays";
+
+const session = (id: string, session_start: string) => ({ id, session_start });
+
+describe("sessionDayKey", () => {
+ it("is the day in the viewer's timezone, not the UTC day the row was stored under", () => {
+ // 01:30 UTC on the 30th is still the 29th in New York and already the 30th in Tokyo.
+ expect(sessionDayKey("2026-09-30 01:30:00", "UTC")).toBe("2026-09-30");
+ expect(sessionDayKey("2026-09-30 01:30:00", "America/New_York")).toBe("2026-09-29");
+ expect(sessionDayKey("2026-09-30 01:30:00", "Asia/Tokyo")).toBe("2026-09-30");
+ expect(sessionDayKey("2026-09-30 20:30:00", "Asia/Tokyo")).toBe("2026-10-01");
+ });
+});
+
+describe("groupSessionsByDay", () => {
+ const newestFirst = [
+ session("a", "2026-09-30 14:00:00"),
+ session("b", "2026-09-30 02:00:00"),
+ session("c", "2026-09-29 23:00:00"),
+ session("d", "2026-09-28 10:00:00"),
+ ];
+
+ it("splits a start-ordered list into runs of one day, keeping the order", () => {
+ expect(
+ groupSessionsByDay(newestFirst, "UTC").map(group => [group.day, group.sessions.map(row => row.id).join("")])
+ ).toEqual([
+ ["2026-09-30", "ab"],
+ ["2026-09-29", "c"],
+ ["2026-09-28", "d"],
+ ]);
+ });
+
+ it("moves the day boundary with the timezone", () => {
+ expect(
+ groupSessionsByDay(newestFirst, "America/New_York").map(group => [
+ group.day,
+ group.sessions.map(row => row.id).join(""),
+ ])
+ ).toEqual([
+ ["2026-09-30", "a"],
+ ["2026-09-29", "bc"],
+ ["2026-09-28", "d"],
+ ]);
+ });
+
+ it("works oldest first and on an empty page", () => {
+ expect(groupSessionsByDay([...newestFirst].reverse(), "UTC").map(group => group.day)).toEqual([
+ "2026-09-28",
+ "2026-09-29",
+ "2026-09-30",
+ ]);
+ expect(groupSessionsByDay([], "UTC")).toEqual([]);
+ });
+});
+
+describe("relativeDay", () => {
+ // 03:00 UTC on Oct 1 is still Sep 30 in Los Angeles.
+ const now = DateTime.fromISO("2026-10-01T03:00:00Z");
+
+ it("names today and yesterday where the viewer is", () => {
+ expect(relativeDay("2026-10-01", "UTC", now)).toBe("today");
+ expect(relativeDay("2026-09-30", "UTC", now)).toBe("yesterday");
+ expect(relativeDay("2026-09-30", "America/Los_Angeles", now)).toBe("today");
+ expect(relativeDay("2026-09-29", "America/Los_Angeles", now)).toBe("yesterday");
+ });
+
+ it("leaves every other day to be shown as a date", () => {
+ expect(relativeDay("2026-09-28", "UTC", now)).toBeNull();
+ expect(relativeDay("2026-10-02", "UTC", now)).toBeNull();
+ });
+});
diff --git a/client/src/app/[site]/sessions/sessionDays.ts b/client/src/app/[site]/sessions/sessionDays.ts
new file mode 100644
index 000000000..22ffef05a
--- /dev/null
+++ b/client/src/app/[site]/sessions/sessionDays.ts
@@ -0,0 +1,40 @@
+import { DateTime } from "luxon";
+
+/**
+ * The calendar day a session started on, in the viewer's timezone, as
+ * YYYY-MM-DD. The sessions summary keys its per-day counts the same way.
+ */
+export function sessionDayKey(sessionStart: string, zone: string): string {
+ return DateTime.fromSQL(sessionStart, { zone: "utc" }).setZone(zone).toISODate() ?? "";
+}
+
+export interface SessionDayGroup<T> {
+ day: string;
+ sessions: T[];
+}
+
+/**
+ * Splits a list that is already in start-time order into runs of the same
+ * day. Order is kept as given, so it works for newest-first and oldest-first.
+ */
+export function groupSessionsByDay<T extends { session_start: string }>(
+ sessions: T[],
+ zone: string
+): SessionDayGroup<T>[] {
+ const groups: SessionDayGroup<T>[] = [];
+ for (const session of sessions) {
+ const day = sessionDayKey(session.session_start, zone);
+ const last = groups[groups.length - 1];
+ if (last && last.day === day) last.sessions.push(session);
+ else groups.push({ day, sessions: [session] });
+ }
+ return groups;
+}
+
+/** Whether a day key is today or yesterday in the viewer's timezone. */
+export function relativeDay(day: string, zone: string, now: DateTime = DateTime.now()): "today" | "yesterday" | null {
+ const today = now.setZone(zone);
+ if (day === today.toISODate()) return "today";
+ if (day === today.minus({ days: 1 }).toISODate()) return "yesterday";
+ return null;
+}
diff --git a/client/src/app/[site]/sessions/sessionRanges.test.ts b/client/src/app/[site]/sessions/sessionRanges.test.ts
new file mode 100644
index 000000000..331f438af
--- /dev/null
+++ b/client/src/app/[site]/sessions/sessionRanges.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vitest";
+import {
+ describeRange,
+ EMPTY_RANGES,
+ hasAnyRange,
+ hasRange,
+ parseBound,
+ toRange,
+ toRangeParams,
+} from "./sessionRanges";
+
+describe("parseBound", () => {
+ it("accepts whole numbers of zero or more", () => {
+ expect(parseBound("0")).toBe(0);
+ expect(parseBound(" 12 ")).toBe(12);
+ });
+
+ it("treats anything else as no bound", () => {
+ for (const text of ["", " ", "-3", "2.5", "1e3", "ten", "5s"]) {
+ expect(parseBound(text)).toBeUndefined();
+ }
+ });
+
+ it("stays inside what the server can bind", () => {
+ expect(parseBound("99999999999999")).toBe(2_147_483_647);
+ });
+});
+
+describe("toRange", () => {
+ it("keeps only the bounds that were typed", () => {
+ expect(toRange("3", "")).toEqual({ min: 3 });
+ expect(toRange("", "8")).toEqual({ max: 8 });
+ expect(toRange("3", "8")).toEqual({ min: 3, max: 8 });
+ expect(toRange("", "")).toEqual({});
+ });
+
+ it("swaps bounds typed the wrong way round instead of matching nothing", () => {
+ expect(toRange("8", "3")).toEqual({ min: 3, max: 8 });
+ });
+
+ it("drops an at-least-zero bound, which narrows nothing", () => {
+ expect(toRange("0", "")).toEqual({});
+ expect(toRange("0", "4")).toEqual({ max: 4 });
+ // At most zero is a real range: sessions with none.
+ expect(toRange("", "0")).toEqual({ max: 0 });
+ });
+});
+
+describe("describeRange", () => {
+ it("names the shape of the range for its chip", () => {
+ expect(describeRange({})).toEqual({ kind: "any" });
+ expect(describeRange({ min: 10 })).toEqual({ kind: "min", min: 10 });
+ expect(describeRange({ max: 5 })).toEqual({ kind: "max", max: 5 });
+ expect(describeRange({ min: 2, max: 5 })).toEqual({ kind: "between", min: 2, max: 5 });
+ expect(describeRange({ min: 3, max: 3 })).toEqual({ kind: "exact", value: 3 });
+ expect(describeRange({ max: 0 })).toEqual({ kind: "max", max: 0 });
+ });
+});
+
+describe("range state", () => {
+ it("knows when anything is narrowing the list", () => {
+ expect(hasRange({})).toBe(false);
+ expect(hasRange({ max: 0 })).toBe(true);
+ expect(hasAnyRange(EMPTY_RANGES)).toBe(false);
+ expect(hasAnyRange({ ...EMPTY_RANGES, duration: { min: 10 } })).toBe(true);
+ });
+
+ it("maps onto the hook params one for one", () => {
+ expect(toRangeParams({ pageviews: { min: 2 }, events: { max: 9 }, duration: { min: 10, max: 600 } })).toEqual({
+ minPageviews: 2,
+ maxPageviews: undefined,
+ minEvents: undefined,
+ maxEvents: 9,
+ minDuration: 10,
+ maxDuration: 600,
+ });
+ });
+});
diff --git a/client/src/app/[site]/sessions/sessionRanges.ts b/client/src/app/[site]/sessions/sessionRanges.ts
new file mode 100644
index 000000000..3d779d390
--- /dev/null
+++ b/client/src/app/[site]/sessions/sessionRanges.ts
@@ -0,0 +1,67 @@
+/**
+ * The Sessions page's min/max ranges: how many pageviews, how many events and
+ * how long. Pure, so the popover, the request and the labels cannot disagree
+ * about what a range means.
+ */
+export type RangeMetric = "pageviews" | "events" | "duration";
+
+export interface RangeValue {
+ min?: number;
+ max?: number;
+}
+
+export type SessionRanges = Record<RangeMetric, RangeValue>;
+
+export const EMPTY_RANGES: SessionRanges = { pageviews: {}, events: {}, duration: {} };
+
+// The server binds these as Int32.
+const MAX_BOUND = 2_147_483_647;
+
+/** A typed bound: a whole number of zero or more, or nothing. */
+export function parseBound(text: string): number | undefined {
+ const trimmed = text.trim();
+ if (!/^\d+$/.test(trimmed)) return undefined;
+ return Math.min(Number(trimmed), MAX_BOUND);
+}
+
+/**
+ * What the two inputs mean together. "At least 0" is no bound, and bounds
+ * typed the wrong way round are swapped rather than matching nothing.
+ */
+export function toRange(minText: string, maxText: string): RangeValue {
+ let min = parseBound(minText);
+ let max = parseBound(maxText);
+ if (min !== undefined && max !== undefined && min > max) [min, max] = [max, min];
+ if (min === 0) min = undefined;
+ return { ...(min !== undefined ? { min } : {}), ...(max !== undefined ? { max } : {}) };
+}
+
+export const hasRange = (range: RangeValue) => range.min !== undefined || range.max !== undefined;
+
+export const hasAnyRange = (ranges: SessionRanges) => Object.values(ranges).some(hasRange);
+
+/** How a range reads on its chip; the component supplies the words. */
+export type RangeDescription =
+ | { kind: "any" }
+ | { kind: "exact"; value: number }
+ | { kind: "min"; min: number }
+ | { kind: "max"; max: number }
+ | { kind: "between"; min: number; max: number };
+
+export function describeRange({ min, max }: RangeValue): RangeDescription {
+ if (min !== undefined && max !== undefined)
+ return min === max ? { kind: "exact", value: min } : { kind: "between", min, max };
+ if (min !== undefined) return { kind: "min", min };
+ if (max !== undefined) return { kind: "max", max };
+ return { kind: "any" };
+}
+
+/** The ranges as the sessions hooks take them. */
+export const toRangeParams = (ranges: SessionRanges) => ({
+ minPageviews: ranges.pageviews.min,
+ maxPageviews: ranges.pageviews.max,
+ minEvents: ranges.events.min,
+ maxEvents: ranges.events.max,
+ minDuration: ranges.duration.min,
+ maxDuration: ranges.duration.max,
+});
diff --git a/client/src/app/[site]/user/[userId]/components/ActivityCalendar.tsx b/client/src/app/[site]/user/[userId]/components/ActivityCalendar.tsx
new file mode 100644
index 000000000..8ab985919
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/ActivityCalendar.tsx
@@ -0,0 +1,253 @@
+"use client";
+
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import { UserSessionCountResponse } from "../../../../../api/analytics/endpoints";
+import { describeComparisonWindow } from "../../../../../components/DateSelector/rangeFields";
+import { ErrorState } from "../../../../../components/ErrorState";
+import { Card } from "../../../../../components/ui/card";
+import { Skeleton } from "../../../../../components/ui/skeleton";
+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";
+import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
+import { useStore, useTimezone } from "../../../../../lib/store";
+import { cn } from "../../../../../lib/utils";
+import {
+ ActivityLevel,
+ activityStats,
+ buildCalendarWeeks,
+ CALENDAR_WEEKS,
+ CalendarDay,
+ monthLabelColumns,
+ rangeColumns,
+} from "./calendarLayout";
+import { profileWindow, singleDayLabel } from "./profileWindow";
+
+// The data hue in three steps over a neutral empty day. Emerald stays out of
+// it: on this page it means online, identified and converted.
+const LEVEL_CLASS: Record<ActivityLevel, string> = {
+ 0: "bg-neutral-100 dark:bg-neutral-800",
+ 1: "bg-dataviz/30",
+ 2: "bg-dataviz/60",
+ 3: "bg-dataviz/95",
+};
+
+const CELL = "aspect-square w-full rounded-[3px]";
+// Monday, Wednesday, Friday, Sunday.
+const LABELLED_ROWS = [0, 2, 4, 6];
+
+interface ActivityCalendarProps {
+ /** One row per day with sessions, over the user's whole history. */
+ sessionCount: UserSessionCountResponse[];
+ isLoading: boolean;
+ /** Set when the history could not be loaded. */
+ error?: Error | null;
+ refetch?: () => void;
+ /** Active days in the selected period, from the stat band's query. */
+ activeDays: number | undefined;
+ /** ISO date of the day the session list is narrowed to, if any. */
+ selectedDay: string | null;
+ onSelectDay: (day: string | null) => void;
+}
+
+/**
+ * The user's last eighteen weeks, a cell a day. Independent of the selected
+ * period, which is marked underneath; picking a day narrows the session list
+ * to it.
+ */
+export function ActivityCalendar({
+ sessionCount,
+ isLoading,
+ error,
+ refetch,
+ activeDays,
+ selectedDay,
+ onSelectDay,
+}: ActivityCalendarProps) {
+ const t = useExtracted();
+ const zone = useTimezone();
+ const time = useStore(state => state.time);
+ const { formatDateTime } = useDateTimeFormat();
+
+ const counts = sessionCount.map(row => ({ date: String(row.date).slice(0, 10), sessions: Number(row.sessions) }));
+ const today = DateTime.now().setZone(zone);
+ const weeks = buildCalendarWeeks(counts, today, CALENDAR_WEEKS);
+ const months = monthLabelColumns(weeks);
+
+ const window = profileWindow(time, zone, today);
+ const marked = window ? rangeColumns(weeks, window.start, window.end) : null;
+ const windowLabel = singleDayLabel(describeComparisonWindow(time, time, zone));
+ const stats = activityStats(counts, window?.start ?? null, window?.end ?? null);
+
+ // Calendar days are dates, not instants: format them at noon in the zone so
+ // no offset can push the label onto a neighbouring day.
+ const dayAt = (isoDate: string) => DateTime.fromISO(`${isoDate}T12:00:00`, { zone });
+ const formatDay = (isoDate: string) =>
+ formatDateTime(dayAt(isoDate), { weekday: "short", month: "short", day: "numeric", timeZone: zone });
+ const weekdayName = (weekday: number, width: "short" | "long") =>
+ // 2024-01-01 was a Monday.
+ formatDateTime(DateTime.fromISO("2024-01-01T12:00:00", { zone }).plus({ days: weekday - 1 }), {
+ weekday: width,
+ timeZone: zone,
+ });
+
+ const describeDay = (day: CalendarDay) =>
+ day.sessions > 0
+ ? t("{count, plural, one {# session} other {# sessions}}", { count: day.sessions })
+ : day.beforeFirstVisit
+ ? t("Before first visit")
+ : t("No sessions");
+
+ // An empty grid would say "never visited"; a failed request must not.
+ if (error) {
+ return (
+ <Card>
+ <div className="p-4">
+ <h2 className="text-sm font-medium text-neutral-700 dark:text-neutral-200">{t("Activity")}</h2>
+ <ErrorState title={t("Failed to load data")} message={error.message} refetch={refetch} />
+ </div>
+ </Card>
+ );
+ }
+
+ return (
+ <Card>
+ <div className="p-4">
+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
+ <h2 className="text-sm font-medium text-neutral-700 dark:text-neutral-200">{t("Activity")}</h2>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-neutral-500 dark:text-neutral-400">
+ <span className="inline-flex items-center gap-1.5">
+ <span className="inline-block h-2.5 w-2.5 rounded-[2px] border border-neutral-200 dark:border-neutral-700" />
+ {t("Before first visit")}
+ </span>
+ <span className="inline-flex items-center gap-1">
+ {t("Less")}
+ {([0, 1, 2, 3] as ActivityLevel[]).map(level => (
+ <span key={level} className={cn("inline-block h-2.5 w-2.5 rounded-[2px]", LEVEL_CLASS[level])} />
+ ))}
+ {t("More")}
+ </span>
+ </div>
+ </div>
+
+ {isLoading ? (
+ <Skeleton className="mt-3 h-[178px] w-full max-w-[430px] rounded-md" />
+ ) : (
+ <div
+ className="mt-3 grid w-full max-w-[430px] gap-[3px]"
+ style={{ gridTemplateColumns: `auto repeat(${weeks.length}, minmax(0, 1fr))` }}
+ >
+ {months.map(({ month, column }) => (
+ <span
+ key={month}
+ className="h-[18px] whitespace-nowrap text-[11px] text-neutral-500 dark:text-neutral-400"
+ // Room for the name, without spanning past the last week into implicit columns.
+ style={{ gridRow: 1, gridColumn: `${column + 2} / span ${Math.min(3, weeks.length - column)}` }}
+ >
+ {formatDateTime(dayAt(`${month}-01`), { month: "short", timeZone: zone })}
+ </span>
+ ))}
+
+ {LABELLED_ROWS.map(row => (
+ <span
+ key={row}
+ className="flex items-center pr-1.5 text-[10px] leading-none text-neutral-500 dark:text-neutral-400"
+ style={{ gridRow: row + 2, gridColumn: 1 }}
+ >
+ {weekdayName(row + 1, "short")}
+ </span>
+ ))}
+
+ {weeks.flatMap((week, column) =>
+ week.days.map((day, row) => {
+ if (!day) return null;
+ const position = { gridRow: row + 2, gridColumn: column + 2 };
+ const selected = day.date === selectedDay;
+ const label = `${describeDay(day)} · ${formatDay(day.date)}`;
+
+ return (
+ <Tooltip key={day.date}>
+ <TooltipTrigger asChild>
+ {day.sessions > 0 ? (
+ <button
+ type="button"
+ style={position}
+ aria-label={label}
+ aria-pressed={selected}
+ onClick={() => onSelectDay(selected ? null : day.date)}
+ className={cn(
+ CELL,
+ LEVEL_CLASS[day.level],
+ "cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-400 dark:focus-visible:ring-neutral-500",
+ selected &&
+ "ring-2 ring-neutral-900 ring-offset-1 ring-offset-white dark:ring-neutral-100 dark:ring-offset-neutral-900"
+ )}
+ />
+ ) : (
+ <span
+ style={position}
+ className={cn(
+ CELL,
+ day.beforeFirstVisit ? "border border-neutral-200 dark:border-neutral-850" : LEVEL_CLASS[0]
+ )}
+ />
+ )}
+ </TooltipTrigger>
+ <TooltipContent>
+ <span className="font-medium tabular-nums">{describeDay(day)}</span>{" "}
+ <span className="opacity-70">· {formatDay(day.date)}</span>
+ </TooltipContent>
+ </Tooltip>
+ );
+ })
+ )}
+
+ {marked && windowLabel && (
+ <div
+ className="relative mt-1 h-5 border-t border-neutral-300 dark:border-neutral-600"
+ style={{ gridRow: 9, gridColumn: `${marked.from + 2} / ${marked.to + 3}` }}
+ >
+ <span
+ className={cn(
+ "absolute top-1 whitespace-nowrap text-[11px] leading-none text-neutral-500 dark:text-neutral-400",
+ // A narrow mark near the right edge would push its label out of the card.
+ marked.from > weeks.length / 2 ? "right-0" : "left-0"
+ )}
+ >
+ {windowLabel}
+ </span>
+ </div>
+ )}
+ </div>
+ )}
+
+ <div className="mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-1 border-t border-neutral-100 pt-3 text-xs dark:border-neutral-850">
+ <CalendarFact
+ value={activeDays != null ? activeDays.toLocaleString() : null}
+ label={window ? t("active days in range") : t("active days")}
+ />
+ <CalendarFact
+ value={isLoading ? null : t("{count, plural, one {# day} other {# days}}", { count: stats.longestStreak })}
+ label={t("longest streak")}
+ />
+ <CalendarFact
+ value={isLoading ? null : stats.busiestWeekday ? weekdayName(stats.busiestWeekday, "long") : "—"}
+ label={t("busiest day")}
+ />
+ </div>
+ </div>
+ </Card>
+ );
+}
+
+function CalendarFact({ value, label }: { value: string | null; label: string }) {
+ return (
+ <div className="flex items-center gap-1.5">
+ {value === null ? (
+ <Skeleton className="h-3 w-8 rounded" />
+ ) : (
+ <span className="font-medium tabular-nums text-neutral-900 dark:text-neutral-100">{value}</span>
+ )}
+ <span className="text-neutral-500 dark:text-neutral-400">{label}</span>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/user/[userId]/components/Calendar.tsx b/client/src/app/[site]/user/[userId]/components/Calendar.tsx
deleted file mode 100644
index 051e4fed1..000000000
--- a/client/src/app/[site]/user/[userId]/components/Calendar.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { ResponsiveTimeRange } from "@nivo/calendar";
-import { DateTime } from "luxon";
-import get from "lodash/get";
-import sortBy from "lodash/sortBy";
-import { useExtracted } from "next-intl";
-import { useTheme } from "next-themes";
-import { UserSessionCountResponse } from "../../../../../api/analytics/endpoints";
-import { useNivoTheme } from "../../../../../lib/nivo";
-import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
-
-export const VisitCalendar = ({ sessionCount }: { sessionCount: UserSessionCountResponse[] }) => {
- const t = useExtracted();
- const { resolvedTheme } = useTheme();
- const nivoTheme = useNivoTheme();
-
- const data = sessionCount
- .map(e => ({
- value: e.sessions,
- day: DateTime.fromSQL(e.date ?? 0).toFormat("y-LL-dd"),
- }))
- .reverse();
-
-
- const maxValue = get(sortBy(data, "value")[Math.floor(data.length * 0.95)], "value");
-
- if (data.length === 0) {
- return null;
- }
-
- const toDate = DateTime.now().plus({ days: 1 }).toFormat("y-LL-dd");
- const fromDate = DateTime.now().minus({ days: 120 }).toFormat("y-LL-dd");
-
- return (
- <ResponsiveTimeRange
- data={data}
- theme={nivoTheme}
- from={fromDate}
- to={toDate}
- emptyColor={resolvedTheme === "dark" ? "hsl(var(--neutral-750))" : "hsl(var(--neutral-100))"}
- colors={
- resolvedTheme === "dark"
- ? ["#10452A", "#006D32", "#3E9058", "#3CD456"]
- : ["#9be9a8", "#40c463", "#30a14e", "#216e39"]
- }
- margin={{ top: 20, right: 0, bottom: 0, left: 0 }}
- dayBorderWidth={2}
- daySpacing={3}
- dayBorderColor="rgba(0, 0, 0, 0)"
- dayRadius={3}
- weekdayTicks={[]}
- weekdayLegendOffset={0}
- maxValue={maxValue}
- tooltip={({ value, day }) => {
- return (
- <ChartTooltip className="p-2 flex gap-1">
- {t("{count} sessions on {day}", { count: String(value), day })}
- </ChartTooltip>
- );
- }}
- />
- );
-};
diff --git a/client/src/app/[site]/user/[userId]/components/LocationDevices.tsx b/client/src/app/[site]/user/[userId]/components/LocationDevices.tsx
index 0417d5770..2184c0b93 100644
--- a/client/src/app/[site]/user/[userId]/components/LocationDevices.tsx
+++ b/client/src/app/[site]/user/[userId]/components/LocationDevices.tsx
@@ -35,7 +35,8 @@ function ShareRow({
{icon}
<span className="truncate text-neutral-700 dark:text-neutral-200">{label}</span>
</div>
- <span className="shrink-0 text-neutral-500 dark:text-neutral-400">{Math.round(share)}%</span>
+ {/* Sits on the bar fill, so it takes foreground text. */}
+ <span className="shrink-0 tabular-nums text-neutral-900 dark:text-neutral-100">{Math.round(share)}%</span>
</div>
</div>
);
@@ -167,6 +168,16 @@ export function LocationDevices({
)}
<InfoRow label={t("Language")} value={data?.language ? getLanguageName(data.language) : "—"} />
+ {data?.timezone && (
+ <InfoRow
+ label={t("Timezone")}
+ value={
+ <span className="inline-block max-w-[170px] truncate align-bottom" title={data.timezone}>
+ {data.timezone}
+ </span>
+ }
+ />
+ )}
{multiDevice ? (
<BreakdownList
diff --git a/client/src/app/[site]/user/[userId]/components/ProfileCard.tsx b/client/src/app/[site]/user/[userId]/components/ProfileCard.tsx
new file mode 100644
index 000000000..776082106
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/ProfileCard.tsx
@@ -0,0 +1,30 @@
+import { ArrowUpRight } from "lucide-react";
+import Link from "next/link";
+import { ReactNode } from "react";
+
+/** A card's title row: the title, an optional quiet note beside it, and one thing on the right. */
+export function ProfileCardHeader({ title, note, right }: { title: string; note?: ReactNode; right?: ReactNode }) {
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1">
+ <div className="flex min-w-0 items-baseline gap-2">
+ <h2 className="shrink-0 text-sm font-medium text-neutral-700 dark:text-neutral-200">{title}</h2>
+ {note != null && <span className="truncate text-xs text-neutral-500 dark:text-neutral-400">{note}</span>}
+ </div>
+ {right}
+ </div>
+ );
+}
+
+/** "Open in Pages ↗": the same user and period on another page of the site. */
+export function OpenInLink({ href, children }: { href: string; children: ReactNode }) {
+ return (
+ <Link
+ href={href}
+ prefetch={false}
+ className="inline-flex shrink-0 items-center gap-1 rounded-sm text-xs text-neutral-500 underline-offset-2 hover:text-neutral-800 hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400 dark:text-neutral-400 dark:hover:text-neutral-200"
+ >
+ {children}
+ <ArrowUpRight className="h-3 w-3" aria-hidden="true" />
+ </Link>
+ );
+}
diff --git a/client/src/app/[site]/user/[userId]/components/SessionLedgerRow.tsx b/client/src/app/[site]/user/[userId]/components/SessionLedgerRow.tsx
new file mode 100644
index 000000000..3cf869ea2
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/SessionLedgerRow.tsx
@@ -0,0 +1,290 @@
+"use client";
+
+import { FilterParameter } from "@rybbit/shared";
+import { ArrowRight, ChevronDown, ChevronRight, Target, TriangleAlert, Video } from "lucide-react";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import { MouseEvent, useState } from "react";
+import { GetSessionsResponse } from "../../../../../api/analytics/endpoints";
+import { Channel } from "../../../../../components/Channel";
+import { EventTypeIcon } from "../../../../../components/EventIcons";
+import { ReplayDrawer } from "../../../../../components/Sessions/ReplayDrawer";
+import { SessionDetails } from "../../../../../components/Sessions/SessionDetails";
+import {
+ BrowserTooltipIcon,
+ CountryFlagTooltipIcon,
+ DeviceTypeTooltipIcon,
+ OperatingSystemTooltipIcon,
+} from "../../../../../components/TooltipIcons/TooltipIcons";
+import { Badge } from "../../../../../components/ui/badge";
+import { Button } from "../../../../../components/ui/button";
+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";
+import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
+import { formatShortDuration } from "../../../../../lib/dateTimeUtils";
+import { addFilter, useTimezone } from "../../../../../lib/store";
+import { cn, formatter, truncateString } from "../../../../../lib/utils";
+
+type Session = GetSessionsResponse[number];
+
+const QUIET_BADGE = "flex items-center gap-1 bg-neutral-100 text-neutral-600 dark:bg-neutral-800 dark:text-neutral-300";
+
+interface SessionLedgerRowProps {
+ session: Session;
+ userId: string;
+ /** Names of the goals this session completed. */
+ goals: string[];
+ /** Day groups print the time alone; week groups need the weekday too. */
+ showWeekday: boolean;
+}
+
+/**
+ * One session in the profile's day ledger. It carries what the shared session
+ * card carries, minus the user (the whole page is one user), plus what the
+ * card does not show without opening it: errors and completed goals. Opening
+ * the row shows the same session details the card does.
+ */
+export function SessionLedgerRow({ session, userId, goals, showWeekday }: SessionLedgerRowProps) {
+ const t = useExtracted();
+ const zone = useTimezone();
+ const { hour12, formatDateTime } = useDateTimeFormat();
+ const [expanded, setExpanded] = useState(false);
+ const [replayOpen, setReplayOpen] = useState(false);
+
+ const start = DateTime.fromSQL(session.session_start, { zone: "utc" }).setZone(zone);
+ const startLabel = formatDateTime(start, {
+ weekday: showWeekday ? "short" : undefined,
+ hour: "numeric",
+ minute: "2-digit",
+ hour12,
+ timeZone: zone,
+ });
+ const startTitle = formatDateTime(start, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ second: "2-digit",
+ hour12,
+ timeZone: zone,
+ });
+
+ const interactions =
+ session.events +
+ (session.button_clicks || 0) +
+ (session.copies || 0) +
+ (session.form_submits || 0) +
+ (session.input_changes || 0);
+ const hasReplay = session.has_replay === 1;
+
+ // Clicking an attribute filters the profile by it, as on the session card.
+ const filterBy = (event: MouseEvent, parameter: FilterParameter, value: string | undefined) => {
+ event.stopPropagation();
+ if (!value) return;
+ addFilter({ parameter, value: [value], type: "equals" });
+ };
+
+ const when = (
+ <span className="flex shrink-0 items-baseline gap-2.5 whitespace-nowrap" title={startTitle}>
+ <span className="text-xs font-medium tabular-nums text-neutral-900 dark:text-neutral-100">{startLabel}</span>
+ <span className="text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
+ {formatShortDuration(Math.max(0, session.session_duration ?? 0))}
+ </span>
+ </span>
+ );
+
+ const device = (
+ <span className="flex shrink-0 items-center gap-2">
+ {session.country && (
+ <CountryFlagTooltipIcon
+ country={session.country}
+ city={session.city}
+ region={session.region}
+ onClick={event => filterBy(event, "country", session.country)}
+ />
+ )}
+ <BrowserTooltipIcon
+ browser={session.browser || "Unknown"}
+ browser_version={session.browser_version}
+ onClick={event => filterBy(event, "browser", session.browser)}
+ />
+ <OperatingSystemTooltipIcon
+ operating_system={session.operating_system || ""}
+ operating_system_version={session.operating_system_version}
+ onClick={event => filterBy(event, "operating_system", session.operating_system)}
+ />
+ <DeviceTypeTooltipIcon
+ device_type={session.device_type || ""}
+ screen_width={session.screen_width}
+ screen_height={session.screen_height}
+ onClick={event => filterBy(event, "device_type", session.device_type)}
+ />
+ </span>
+ );
+
+ const channel = (
+ <Channel
+ channel={session.channel}
+ referrer={session.referrer}
+ onClick={event => filterBy(event, "channel", session.channel)}
+ />
+ );
+
+ const page = (parameter: "entry_page" | "exit_page", pathname: string) => (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span
+ className="inline-block max-w-[200px] cursor-pointer truncate hover:opacity-70"
+ onClick={event => filterBy(event, parameter, pathname)}
+ >
+ {truncateString(pathname, 32)}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{pathname || "-"}</p>
+ </TooltipContent>
+ </Tooltip>
+ );
+
+ const markers = (
+ <>
+ {session.errors > 0 && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="destructive" className="gap-1 tabular-nums">
+ <TriangleAlert className="h-3.5 w-3.5" />
+ <span>{formatter(session.errors)}</span>
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>
+ {t("{count, plural, one {# error} other {# errors}}", { count: session.errors })}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {goals.length > 0 && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="success" className="max-w-[180px] gap-1 font-normal">
+ <Target className="h-3.5 w-3.5 shrink-0" />
+ <span className="truncate">
+ {goals.length === 1
+ ? goals[0]
+ : t("{count, plural, one {# goal} other {# goals}}", { count: goals.length })}
+ </span>
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p className="mb-0.5 font-medium">{t("Goals completed")}</p>
+ {goals.map(goal => (
+ <p key={goal}>{goal}</p>
+ ))}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </>
+ );
+
+ const counts = (
+ <>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge className={QUIET_BADGE}>
+ <EventTypeIcon type="pageview" />
+ <span className="tabular-nums">{formatter(session.pageviews)}</span>
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>{t("Pageviews")}</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge className={QUIET_BADGE}>
+ <EventTypeIcon type="custom_event" />
+ <span className="tabular-nums">{formatter(interactions)}</span>
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>{t("Events")}</TooltipContent>
+ </Tooltip>
+ </>
+ );
+
+ const replay = hasReplay && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ size="smIcon"
+ className="h-6 w-7 shrink-0"
+ aria-label={t("Watch Session Replay")}
+ onClick={event => {
+ event.stopPropagation();
+ setReplayOpen(true);
+ }}
+ >
+ <Video className="h-3.5 w-3.5" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{t("Watch Session Replay")}</TooltipContent>
+ </Tooltip>
+ );
+
+ const Chevron = expanded ? ChevronDown : ChevronRight;
+ const chevron = <Chevron className="h-4 w-4 shrink-0 text-neutral-500 dark:text-neutral-400" strokeWidth={3} />;
+
+ return (
+ <div className="border-t border-neutral-100 first:border-t-0 dark:border-neutral-850">
+ <div
+ role="button"
+ tabIndex={0}
+ aria-expanded={expanded}
+ className="cursor-pointer px-3 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-neutral-400"
+ onClick={() => setExpanded(open => !open)}
+ onKeyDown={event => {
+ if (event.target !== event.currentTarget) return;
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ setExpanded(open => !open);
+ }
+ }}
+ >
+ {/* Narrow screens: two lines, entry and exit pages left to the details. */}
+ <div className="flex flex-col gap-2 py-2.5 md:hidden">
+ <div className="flex items-center justify-between gap-2">
+ {when}
+ <div className="flex items-center gap-1.5">
+ {markers}
+ {chevron}
+ </div>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ {device}
+ {channel}
+ {counts}
+ {replay}
+ </div>
+ </div>
+
+ {/* Wide screens: one line. */}
+ <div className="hidden h-11 items-center gap-2.5 md:flex">
+ {/* A fixed column so the rows line up; the weekday needs more of it. */}
+ <span className={cn("shrink-0", showWeekday ? "w-[158px]" : "w-[124px]")}>{when}</span>
+ {device}
+ <span className="shrink-0">{channel}</span>
+ <div className="flex min-w-0 flex-1 items-center text-xs text-neutral-500 dark:text-neutral-400">
+ {page("entry_page", session.entry_page)}
+ <ArrowRight className="mx-2 h-3 w-3 shrink-0" />
+ {page("exit_page", session.exit_page)}
+ </div>
+ <div className="flex shrink-0 items-center gap-1.5">
+ {markers}
+ {counts}
+ </div>
+ <span className="flex w-7 shrink-0 justify-center">{replay}</span>
+ {chevron}
+ </div>
+ </div>
+
+ {expanded && <SessionDetails session={session} userId={userId} />}
+
+ {hasReplay && <ReplayDrawer sessionId={session.session_id} open={replayOpen} onOpenChange={setReplayOpen} />}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/user/[userId]/components/SidebarPrimitives.tsx b/client/src/app/[site]/user/[userId]/components/SidebarPrimitives.tsx
index 2cae630fd..940bea690 100644
--- a/client/src/app/[site]/user/[userId]/components/SidebarPrimitives.tsx
+++ b/client/src/app/[site]/user/[userId]/components/SidebarPrimitives.tsx
@@ -1,36 +1,34 @@
import { ReactNode } from "react";
import { Skeleton } from "../../../../../components/ui/skeleton";
-// Reusable card wrapper for sidebar sections
-export function SidebarCard({ children, className = "" }: { children: ReactNode; className?: string }) {
- return (
- <div
- className={`bg-white dark:bg-neutral-900 rounded-lg border border-neutral-100 dark:border-neutral-850 p-4 ${className}`}
- >
- {children}
- </div>
- );
+// One block of the rail's facts ledger. The rail is a single card; sections
+// are separated by its hairline dividers, not by cards of their own.
+export function SidebarSection({ children, className = "" }: { children: ReactNode; className?: string }) {
+ return <section className={`p-4 ${className}`}>{children}</section>;
}
-// Uniform section header: micro-label title on the left, optional control or
-// hint on the right (edit button, "p75", ...)
+// Uniform section header: a sentence-case title on the left, optional control
+// or hint on the right (edit button, "p75", ...)
export function SidebarHeader({ title, right }: { title: ReactNode; right?: ReactNode }) {
return (
<div className="mb-2 flex items-center justify-between gap-2">
- <h3 className="text-[11px] font-medium uppercase tracking-wide text-neutral-500 dark:text-neutral-400">
- {title}
- </h3>
+ <h3 className="text-sm font-medium text-neutral-700 dark:text-neutral-200">{title}</h3>
{right}
</div>
);
}
+// The quiet note on the right of a section header: what the section's numbers are scoped to.
+export function SidebarHint({ children }: { children: ReactNode }) {
+ return <span className="text-[10px] uppercase tracking-wide text-neutral-400 dark:text-neutral-500">{children}</span>;
+}
+
// Info row component for consistent styling
export function InfoRow({ icon, label, value }: { icon?: ReactNode; label: ReactNode; value: ReactNode }) {
return (
- <div className="flex items-center justify-between py-1.5 border-b border-neutral-50 dark:border-neutral-850 last:border-0 text-xs">
- <span className="text-neutral-500 dark:text-neutral-400">{label}</span>
- <span className="text-neutral-700 dark:text-neutral-200 flex items-center gap-1.5">
+ <div className="flex items-center justify-between gap-3 py-1.5 border-b border-neutral-50 dark:border-neutral-850 last:border-0 text-xs">
+ <span className="shrink-0 text-neutral-500 dark:text-neutral-400">{label}</span>
+ <span className="text-neutral-700 dark:text-neutral-200 flex min-w-0 items-center gap-1.5">
{icon}
{value}
</span>
@@ -39,7 +37,11 @@ export function InfoRow({ icon, label, value }: { icon?: ReactNode; label: React
}
// Skeleton matching InfoRow's shape, for card loading states
-export function InfoRowSkeleton({ labelWidth = "w-14", valueWidth = "w-24", withIcon = false }: {
+export function InfoRowSkeleton({
+ labelWidth = "w-14",
+ valueWidth = "w-24",
+ withIcon = false,
+}: {
labelWidth?: string;
valueWidth?: string;
withIcon?: boolean;
diff --git a/client/src/app/[site]/user/[userId]/components/UserErrorInsight.tsx b/client/src/app/[site]/user/[userId]/components/UserErrorInsight.tsx
new file mode 100644
index 000000000..53583e1a6
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/UserErrorInsight.tsx
@@ -0,0 +1,77 @@
+"use client";
+
+import { Video } from "lucide-react";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import { ReactNode, useState } from "react";
+import { useUserRepeatedError } from "../../../../../api/analytics/hooks/useUserProfile";
+import { ReplayDrawer } from "../../../../../components/Sessions/ReplayDrawer";
+import { InsightRow } from "../../../../../components/site/InsightRow";
+import { Button } from "../../../../../components/ui/button";
+import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
+import { useReplayAvailable } from "../../../../../hooks/useReplayAvailable";
+import { useTimezone } from "../../../../../lib/store";
+
+/**
+ * One sentence, shown only when it is true: in the selected period this user
+ * hit the same error more than once in a single session. The rule is fixed
+ * (one message, one session, two or more times; the latest such session wins)
+ * and the server evaluates it, so the row never guesses.
+ */
+export function UserErrorInsight({ userId }: { userId: string }) {
+ const t = useExtracted();
+ const zone = useTimezone();
+ const replayAvailable = useReplayAvailable();
+ const { formatDateTime, formatRelative } = useDateTimeFormat();
+ const [replayOpen, setReplayOpen] = useState(false);
+ const { data: repeated } = useUserRepeatedError(userId);
+
+ if (!repeated) return null;
+
+ const firstSeen = DateTime.fromSQL(repeated.first_seen, { zone: "utc" }).setZone(zone);
+ const when = firstSeen.isValid ? formatRelative(firstSeen) : "";
+ const exact = firstSeen.isValid
+ ? formatDateTime(firstSeen, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ timeZone: zone,
+ })
+ : undefined;
+
+ const strong = (chunks: ReactNode) => (
+ <span className="font-medium text-neutral-900 dark:text-neutral-50">{chunks}</span>
+ );
+ const values = { count: repeated.occurrences.toLocaleString(), path: repeated.pathname, when, strong };
+ const canWatch = repeated.has_replay && replayAvailable;
+
+ return (
+ <>
+ <InsightRow
+ action={
+ canWatch ? (
+ <Button
+ variant="ghost"
+ size="xs"
+ className="hidden shrink-0 gap-1 md:inline-flex"
+ onClick={() => setReplayOpen(true)}
+ >
+ <Video />
+ {t("Watch replay")}
+ </Button>
+ ) : undefined
+ }
+ >
+ <span title={exact}>
+ {repeated.pathname
+ ? t.rich("Hit the same error {count} times in one session {when}, on <strong>{path}</strong>:", values)
+ : t.rich("Hit the same error {count} times in one session {when}:", values)}
+ </span>{" "}
+ <span className="break-words font-mono text-xs text-neutral-600 dark:text-neutral-300">{repeated.message}</span>
+ </InsightRow>
+ {canWatch && <ReplayDrawer sessionId={repeated.session_id} open={replayOpen} onOpenChange={setReplayOpen} />}
+ </>
+ );
+}
diff --git a/client/src/app/[site]/user/[userId]/components/UserGoals.tsx b/client/src/app/[site]/user/[userId]/components/UserGoals.tsx
new file mode 100644
index 000000000..61c580d7a
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/UserGoals.tsx
@@ -0,0 +1,151 @@
+"use client";
+
+import { CircleCheck, Target } from "lucide-react";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import { UserGoal } from "../../../../../api/analytics/endpoints/userProfile";
+import { useUserGoals } from "../../../../../api/analytics/hooks/useUserProfile";
+import { ErrorState } from "../../../../../components/ErrorState";
+import { Card } from "../../../../../components/ui/card";
+import { Skeleton } from "../../../../../components/ui/skeleton";
+import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
+import { useTimezone } from "../../../../../lib/store";
+import { cn } from "../../../../../lib/utils";
+import { OpenInLink, ProfileCardHeader } from "./ProfileCard";
+import { useProfileHref, userFilter } from "./profileLinks";
+import { relativeDay } from "./sessionGroups";
+
+/** Completed in the period first, most sessions on top; the rest keep the server's order. */
+export const sortUserGoals = (goals: UserGoal[]) =>
+ [...goals].sort(
+ (a, b) =>
+ b.sessions - a.sessions || (b.last_completed ?? "").localeCompare(a.last_completed ?? "") || a.goalId - b.goalId
+ );
+
+/**
+ * The site's goals as this user met them in the selected period: how many
+ * sessions completed each one and when the last completion was.
+ */
+export function UserGoals({ userId }: { userId: string }) {
+ const t = useExtracted();
+ const zone = useTimezone();
+ const profileHref = useProfileHref();
+ const { formatDateTime } = useDateTimeFormat();
+ const { data, isLoading, error, refetch } = useUserGoals(userId);
+
+ const goals = sortUserGoals(data ?? []);
+ const now = DateTime.now().setZone(zone);
+
+ const lastCompleted = (goal: UserGoal) => {
+ if (!goal.last_completed) return null;
+ const at = DateTime.fromSQL(goal.last_completed, { zone: "utc" }).setZone(zone);
+ if (!at.isValid) return null;
+ const named = relativeDay(at.toISODate() ?? "", now);
+ return {
+ label:
+ named === "today"
+ ? t("Today")
+ : named === "yesterday"
+ ? t("Yesterday")
+ : formatDateTime(at, {
+ month: "short",
+ day: "numeric",
+ year: at.year === now.year ? undefined : "numeric",
+ timeZone: zone,
+ }),
+ title: formatDateTime(at, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ timeZone: zone,
+ }),
+ };
+ };
+
+ return (
+ <Card>
+ <div className="p-4">
+ <ProfileCardHeader
+ title={t("Goals")}
+ right={<OpenInLink href={profileHref("goals", [userFilter(userId)])}>{t("Open in Goals")}</OpenInLink>}
+ />
+
+ {isLoading ? (
+ <div className="mt-3 space-y-3" aria-hidden>
+ {[0, 1, 2, 3, 4].map(row => (
+ <div key={row} className="flex items-center gap-2">
+ <Skeleton className="h-3.5 w-3.5 rounded-full" />
+ <Skeleton className="h-3 flex-1 rounded" />
+ <Skeleton className="h-3 w-12 rounded" />
+ </div>
+ ))}
+ </div>
+ ) : error ? (
+ <ErrorState title={t("Failed to load data")} message={error.message} refetch={refetch} />
+ ) : goals.length === 0 ? (
+ <div className="flex min-h-[140px] flex-col items-center justify-center gap-1 py-4 text-center">
+ <Target className="mb-1 h-5 w-5 text-neutral-400 dark:text-neutral-500" />
+ <p className="text-sm text-neutral-700 dark:text-neutral-200">{t("No goals on this site yet")}</p>
+ <p className="max-w-[260px] text-xs text-neutral-500 dark:text-neutral-400">
+ {t("Create a goal to see which ones this user completes.")}
+ </p>
+ </div>
+ ) : (
+ <>
+ <div className="mt-2 flex items-center gap-2 text-[11px] text-neutral-500 dark:text-neutral-400">
+ <span className="flex-1">{t("Goal")}</span>
+ <span className="w-14 text-right">{t("Sessions")}</span>
+ <span className="w-[72px] text-right">{t("Last")}</span>
+ </div>
+ <ul className="mt-0.5 max-h-[224px] overflow-y-auto">
+ {goals.map(goal => {
+ const completed = goal.sessions > 0;
+ const last = lastCompleted(goal);
+ return (
+ <li
+ key={goal.goalId}
+ className="flex h-8 items-center gap-2 border-b border-neutral-50 text-xs last:border-0 dark:border-neutral-850"
+ >
+ <CircleCheck
+ aria-hidden="true"
+ className={cn(
+ "h-3.5 w-3.5 shrink-0",
+ completed ? "text-emerald-600 dark:text-emerald-400" : "text-neutral-300 dark:text-neutral-600"
+ )}
+ />
+ <span
+ className={cn(
+ "min-w-0 flex-1 truncate text-[13px]",
+ completed ? "text-neutral-900 dark:text-neutral-100" : "text-neutral-500 dark:text-neutral-400"
+ )}
+ title={goal.name ?? undefined}
+ >
+ {goal.name || t("Goal #{goalId}", { goalId: String(goal.goalId) })}
+ {!completed && <span className="sr-only"> ({t("not completed in this period")})</span>}
+ </span>
+ <span
+ className={cn(
+ "w-14 text-right tabular-nums",
+ completed ? "text-neutral-700 dark:text-neutral-200" : "text-neutral-400 dark:text-neutral-500"
+ )}
+ >
+ {completed ? `${goal.sessions.toLocaleString()}×` : "–"}
+ </span>
+ <span
+ className="w-[72px] truncate text-right tabular-nums text-neutral-500 dark:text-neutral-400"
+ title={last?.title}
+ >
+ {last?.label ?? "–"}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ </>
+ )}
+ </div>
+ </Card>
+ );
+}
diff --git a/client/src/app/[site]/user/[userId]/components/UserHeader.tsx b/client/src/app/[site]/user/[userId]/components/UserHeader.tsx
index f21b77360..3588a19f9 100644
--- a/client/src/app/[site]/user/[userId]/components/UserHeader.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserHeader.tsx
@@ -1,19 +1,26 @@
"use client";
-import { Clock } from "lucide-react";
+import { Clock, Rewind, Video } from "lucide-react";
import { DateTime } from "luxon";
import { useExtracted, useLocale } from "next-intl";
+import Link from "next/link";
+import { useState } from "react";
import { UserInfo } from "../../../../../api/analytics/endpoints";
import { Avatar } from "../../../../../components/Avatar";
import { IdentifiedBadge } from "../../../../../components/IdentifiedBadge";
import { CopyAnnouncement, CopyStatusIcon } from "../../../../../components/interior/copy-button";
import { useCopyToClipboard } from "../../../../../components/interior/use-copy-to-clipboard";
+import { ReplayDrawer } from "../../../../../components/Sessions/ReplayDrawer";
+import { Button } from "../../../../../components/ui/button";
import { Skeleton } from "../../../../../components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";
import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
+import { useReplayAvailable } from "../../../../../hooks/useReplayAvailable";
import { getTimezone } from "../../../../../lib/store";
import { userStore } from "../../../../../lib/userStore";
+import { useProfileHref, userFilter } from "./profileLinks";
import { UserActions } from "./UserActions";
+import { headlineTraits, traitLabel } from "./userTraits";
// Considered "online" when the latest event is under five minutes old — the
// same window the session avatars use for their presence dot.
@@ -54,21 +61,56 @@ function CopyUserId({ value }: { value: string }) {
);
}
+// Opens the newest recording in the selected period. Desktop only, and only
+// where the site has a Replay page, like the sidebar's Replay item.
+function LatestReplayButton({ sessionId }: { sessionId: string }) {
+ const t = useExtracted();
+ const replayAvailable = useReplayAvailable();
+ const [open, setOpen] = useState(false);
+
+ if (!replayAvailable) return null;
+
+ return (
+ <>
+ <Button size="sm" className="hidden md:inline-flex" onClick={() => setOpen(true)}>
+ <Video />
+ {t("Latest replay")}
+ </Button>
+ <ReplayDrawer sessionId={sessionId} open={open} onOpenChange={setOpen} />
+ </>
+ );
+}
+
interface UserHeaderProps {
+ /** The id in the URL: what the avatar, the copy button and the delete action refer to. */
userId: string;
+ /** The identity the profile's panels query: the identified id when there is one. */
+ queryUserId: string;
displayName: string;
data: UserInfo | undefined;
isLoading: boolean;
+ /** The newest session in the selected period that has a recording, if any. */
+ latestReplaySessionId?: string;
}
-export function UserHeader({ userId, displayName, data, isLoading }: UserHeaderProps) {
+export function UserHeader({
+ userId,
+ queryUserId,
+ displayName,
+ data,
+ isLoading,
+ latestReplaySessionId,
+}: UserHeaderProps) {
const t = useExtracted();
const locale = useLocale();
const { user } = userStore();
const { formatRelative, formatDateTime, hour12 } = useDateTimeFormat();
+ const profileHref = useProfileHref();
const isIdentified = !!data?.identified_user_id;
const traitsEmail = data?.traits?.email as string | undefined;
+ // The Users list has no trait filter to link to, so these are plain chips.
+ const chips = isIdentified ? headlineTraits(data?.traits) : [];
// The user's clock, from the timezone captured on their latest event
const localTime = data?.timezone ? DateTime.now().setZone(data.timezone) : null;
@@ -81,7 +123,7 @@ export function UserHeader({ userId, displayName, data, isLoading }: UserHeaderP
const isOnline = !!lastSeenValid && -lastSeenValid.diffNow().as("seconds") < ONLINE_WINDOW_SECONDS;
return (
- <header className="mb-4 mt-4 flex flex-wrap items-start justify-between gap-x-6 gap-y-3">
+ <header className="flex flex-wrap items-start justify-between gap-x-6 gap-y-3">
<div className="flex min-w-0 items-center gap-3.5">
<Avatar size={52} id={userId} />
<div className="min-w-0">
@@ -146,15 +188,39 @@ export function UserHeader({ userId, displayName, data, isLoading }: UserHeaderP
</span>
)}
</div>
+ {chips.length > 0 && (
+ <ul className="mt-2 flex flex-wrap items-center gap-1.5" aria-label={t("Traits")}>
+ {chips.map(([key, value]) => (
+ <li
+ key={key}
+ className="inline-flex h-6 max-w-full items-center gap-1 rounded-md border border-neutral-100 px-1.5 text-xs dark:border-neutral-800"
+ >
+ <span className="shrink-0 capitalize text-neutral-500 dark:text-neutral-400">
+ {traitLabel(key)}
+ </span>
+ <span className="truncate font-medium text-neutral-900 dark:text-neutral-100">
+ {String(value)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
</>
)}
</div>
</div>
- {user && data && (
- <div className="shrink-0">
- <UserActions userId={userId} data={data} />
- </div>
- )}
+ <div className="flex shrink-0 flex-wrap items-center gap-1.5">
+ {latestReplaySessionId && <LatestReplayButton sessionId={latestReplaySessionId} />}
+ {data && (
+ <Button asChild variant="outline" size="sm">
+ <Link href={profileHref("sessions", [userFilter(queryUserId)])} prefetch={false}>
+ <Rewind />
+ {t("Open in Sessions")}
+ </Link>
+ </Button>
+ )}
+ {user && data && <UserActions userId={userId} data={data} />}
+ </div>
</header>
);
}
diff --git a/client/src/app/[site]/user/[userId]/components/UserJourneys.tsx b/client/src/app/[site]/user/[userId]/components/UserJourneys.tsx
index 0aceb6603..cfd3e6625 100644
--- a/client/src/app/[site]/user/[userId]/components/UserJourneys.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserJourneys.tsx
@@ -1,19 +1,27 @@
"use client";
import { Route } from "lucide-react";
-import { useState } from "react";
+import { useId, useState } from "react";
import { useExtracted } from "next-intl";
import { useGetSite } from "../../../../../api/admin/hooks/useSites";
import { useJourneys } from "../../../../../api/analytics/hooks/useGetJourneys";
import { ErrorState } from "../../../../../components/ErrorState";
+import { SegmentedControl } from "../../../../../components/interior/segmented-control";
import { Card, CardContent, CardLoader } from "../../../../../components/ui/card";
import { Skeleton } from "../../../../../components/ui/skeleton";
-import { Slider } from "../../../../../components/ui/slider";
import { useStore } from "../../../../../lib/store";
import { SankeyDiagram } from "../../../journeys/components/SankeyDiagram";
+import { OpenInLink, ProfileCardHeader } from "./ProfileCard";
+import { useProfileHref, userFilter } from "./profileLinks";
const MAX_JOURNEYS = 50;
+// Five choices, so each is one click away: a slider hid the values and took
+// a drag to move one step.
+const STEP_CHOICES = ["2", "3", "4", "5", "6"] as const;
+type StepChoice = (typeof STEP_CHOICES)[number];
+const STEP_OPTIONS = STEP_CHOICES.map(value => ({ value, label: value }));
+
// Sankey-shaped placeholder: three columns of node blocks thinning to the right
const SKELETON_COLUMNS: string[][] = [
["h-12", "h-7", "h-4"],
@@ -37,42 +45,52 @@ function JourneysSkeleton() {
export function UserJourneys({ userId }: { userId: string }) {
const t = useExtracted();
- const [steps, setSteps] = useState<number>(3);
+ const stepsLabelId = useId();
+ const [stepChoice, setStepChoice] = useState<StepChoice>("3");
+ const steps = Number(stepChoice);
const { data: siteMetadata } = useGetSite();
const { time } = useStore();
+ const profileHref = useProfileHref();
const { data, isLoading, isFetching, error, refetch } = useJourneys({
siteId: siteMetadata?.siteId,
steps,
time,
limit: MAX_JOURNEYS,
- additionalFilters: [{ parameter: "user_id", value: [userId], type: "equals" }],
+ additionalFilters: [userFilter(userId)],
});
const journeys = data?.journeys ?? [];
return (
<Card>
- <CardContent className="pt-3">
+ <CardContent className="pt-4">
{/* Step changes keep the previous diagram on screen; signal the refresh
the same way StandardSection does */}
{isFetching && !isLoading && <CardLoader />}
- <div className="mb-3 flex items-center justify-between gap-4">
- <h2 className="text-sm font-medium text-neutral-700 dark:text-neutral-200">{t("Journeys")}</h2>
- <div className="flex w-[150px] items-center gap-2.5">
- <span className="whitespace-nowrap text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
- {t("{steps} steps", { steps: String(steps) })}
- </span>
- <Slider
- value={[steps]}
- onValueChange={([value]) => setSteps(value)}
- min={2}
- max={6}
- step={1}
- className="flex-1"
- />
- </div>
+ <div className="mb-3">
+ <ProfileCardHeader
+ title={t("Journeys")}
+ note={t("First {steps} pages of each session", { steps: String(steps) })}
+ right={
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <div className="flex items-center gap-2">
+ <span id={stepsLabelId} className="text-xs text-neutral-500 dark:text-neutral-400">
+ {t("Steps")}
+ </span>
+ <SegmentedControl<StepChoice>
+ aria-labelledby={stepsLabelId}
+ size="sm"
+ options={STEP_OPTIONS}
+ value={stepChoice}
+ onValueChange={setStepChoice}
+ />
+ </div>
+ <OpenInLink href={profileHref("journeys", [userFilter(userId)])}>{t("Open in Journeys")}</OpenInLink>
+ </div>
+ }
+ />
</div>
{isLoading ? (
<JourneysSkeleton />
diff --git a/client/src/app/[site]/user/[userId]/components/UserLocationMap.test.tsx b/client/src/app/[site]/user/[userId]/components/UserLocationMap.test.tsx
index 1fef9a154..a918d1da0 100644
--- a/client/src/app/[site]/user/[userId]/components/UserLocationMap.test.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserLocationMap.test.tsx
@@ -21,12 +21,18 @@ vi.mock("mapbox-gl", () => ({
}),
},
}));
-vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message }));
+vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message, useLocale: () => "en" }));
vi.mock("next-themes", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
vi.mock("@/lib/configs", () => ({ useConfigs: () => ({ configs: { mapboxToken: "test-token" } }) }));
vi.mock("@/lib/userStore", () => ({ userStore: () => ({ user: null }) }));
vi.mock("@/components/EditTraitsDialog", () => ({ EditTraitsDialog: () => null }));
-vi.mock("./Calendar", () => ({ VisitCalendar: () => null }));
+// The rail's segments section and its links reach the analytics layer and the
+// router; neither has anything to do with where the map points.
+vi.mock("@/api/analytics/hooks/useUserProfile", () => ({ useUserSegments: () => ({ data: undefined }) }));
+vi.mock("./profileLinks", async importOriginal => ({
+ ...(await importOriginal<typeof import("./profileLinks")>()),
+ useProfileHref: () => () => "#",
+}));
const regionNames: Record<string, string> = {
"ES-MD": "Madrid, Comunidad de",
@@ -53,10 +59,11 @@ function showSidebar(location: Pick<UserInfo, "country" | "region" | "city">, re
return render(
<QueryClientProvider client={client}>
<UserSidebar
+ userId="visitor"
data={location as UserInfo}
isLoading={false}
- sessionCount={[]}
- isLoadingCalendar={false}
+ firstTouch={undefined}
+ isLoadingFirstTouch={false}
getRegionName={resolveRegion}
/>
</QueryClientProvider>
diff --git a/client/src/app/[site]/user/[userId]/components/UserSessions.tsx b/client/src/app/[site]/user/[userId]/components/UserSessions.tsx
new file mode 100644
index 000000000..57ea479c5
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/UserSessions.tsx
@@ -0,0 +1,266 @@
+"use client";
+
+import { Rewind, X } from "lucide-react";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import { useRef, useState } from "react";
+import { useGetSessions } from "../../../../../api/analytics/hooks/useGetUserSessions";
+import { useUserGoals, useUserSessionGoals } from "../../../../../api/analytics/hooks/useUserProfile";
+import { Time } from "../../../../../components/DateSelector/types";
+import { NothingFound } from "../../../../../components/NothingFound";
+import { Pagination } from "../../../../../components/pagination";
+import { SessionsList } from "../../../../../components/Sessions/SessionsList";
+import { Badge } from "../../../../../components/ui/badge";
+import { Card } from "../../../../../components/ui/card";
+import { Skeleton } from "../../../../../components/ui/skeleton";
+import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
+import { useTimezone } from "../../../../../lib/store";
+import { formatter } from "../../../../../lib/utils";
+import { SessionBreakdown, SessionGroup, formatGroupDuration, groupSessions, relativeDay } from "./sessionGroups";
+import { SessionLedgerRow } from "./SessionLedgerRow";
+
+export const SESSIONS_PAGE_SIZE = 25;
+
+interface UserSessionsProps {
+ userId: string;
+ breakdown: SessionBreakdown;
+ /** The day picked on the activity calendar, or null for the selected period. */
+ selectedDay: string | null;
+ onClearDay: () => void;
+ /** How many sessions the list holds in all, when known. */
+ totalSessions: number | undefined;
+}
+
+/**
+ * This user's sessions, newest first, a page at a time. With a breakdown they
+ * are a ledger grouped by day or week, each row marked with its errors and the
+ * goals it completed; with none they are the same list the Sessions page
+ * shows. Picking a day on the calendar narrows either view to that day.
+ *
+ * The parent keys this component by user, period and picked day, so the page
+ * number starts over whenever what is being listed changes.
+ */
+export function UserSessions({ userId, breakdown, selectedDay, onClearDay, totalSessions }: UserSessionsProps) {
+ const t = useExtracted();
+ const zone = useTimezone();
+ const { formatDateTime } = useDateTimeFormat();
+ const [page, setPage] = useState(1);
+ const topRef = useRef<HTMLDivElement>(null);
+
+ const dayTime: Time | undefined = selectedDay ? { mode: "day", day: selectedDay } : undefined;
+
+ // One row past the page size tells whether there is a next page.
+ const { data, isLoading } = useGetSessions({
+ userId,
+ page,
+ limit: SESSIONS_PAGE_SIZE + 1,
+ timeOverride: dayTime,
+ });
+ const all = data ?? [];
+ const sessions = all.slice(0, SESSIONS_PAGE_SIZE);
+ const hasNextPage = all.length > SESSIONS_PAGE_SIZE;
+ const hasPrevPage = page > 1;
+
+ const grouped = breakdown !== "none";
+ const { data: goals } = useUserGoals(userId);
+ // Markers are only drawn in the ledger; the plain list asks for nothing extra.
+ const { data: sessionGoals } = useUserSessionGoals(
+ userId,
+ grouped ? sessions.map(session => session.session_id) : [],
+ dayTime
+ );
+
+ const goalNames = new Map(
+ (goals ?? []).map(goal => [goal.goalId, goal.name || t("Goal #{goalId}", { goalId: String(goal.goalId) })])
+ );
+ const goalsBySession = new Map(
+ (sessionGoals ?? []).map(row => [
+ row.session_id,
+ row.goal_ids.map(id => goalNames.get(id)).filter((name): name is string => !!name),
+ ])
+ );
+
+ // Dates are days, not instants: format at noon in the zone.
+ const dayAt = (isoDate: string) => DateTime.fromISO(`${isoDate}T12:00:00`, { zone });
+ const now = DateTime.now().setZone(zone);
+ const formatDay = (isoDate: string) => {
+ const day = dayAt(isoDate);
+ return formatDateTime(day, {
+ weekday: "short",
+ month: "short",
+ day: "numeric",
+ year: day.year === now.year ? undefined : "numeric",
+ timeZone: zone,
+ });
+ };
+
+ const groupTitle = (group: SessionGroup) => {
+ if (breakdown === "week") {
+ return { name: t("Week of {date}", { date: formatDay(group.key) }), date: null };
+ }
+ const named = relativeDay(group.key, now);
+ return named
+ ? { name: named === "today" ? t("Today") : t("Yesterday"), date: formatDay(group.key) }
+ : { name: formatDay(group.key), date: null };
+ };
+
+ const from = (page - 1) * SESSIONS_PAGE_SIZE + 1;
+ const to = (page - 1) * SESSIONS_PAGE_SIZE + sessions.length;
+
+ const header = (
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <h2 className="text-sm font-medium text-neutral-700 dark:text-neutral-200">{t("Sessions")}</h2>
+ {totalSessions != null && (
+ <Badge variant="secondary" className="tabular-nums" title={totalSessions.toLocaleString()}>
+ {formatter(totalSessions)}
+ </Badge>
+ )}
+ {selectedDay && (
+ <button
+ type="button"
+ onClick={onClearDay}
+ aria-label={t("Showing {day} only. Show the whole period.", { day: formatDay(selectedDay) })}
+ className="inline-flex h-6 items-center gap-1 rounded-md border border-neutral-200 px-1.5 text-xs text-neutral-700 hover:bg-neutral-50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400 dark:border-neutral-800 dark:text-neutral-200 dark:hover:bg-neutral-850"
+ >
+ {formatDay(selectedDay)}
+ <X className="h-3 w-3 text-neutral-500 dark:text-neutral-400" />
+ </button>
+ )}
+ </div>
+ );
+
+ const changePage = (next: number) => {
+ setPage(next);
+ };
+ // Bottom pagination: restore context by jumping back to the top of the list
+ const changePageFromBottom = (next: number) => {
+ setPage(next);
+ topRef.current?.scrollIntoView({ block: "start" });
+ };
+
+ const emptyMessage = selectedDay ? t("No sessions on this day match the filters") : undefined;
+
+ return (
+ <div ref={topRef} className="scroll-mt-4 space-y-3">
+ {grouped ? (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between gap-2">
+ {header}
+ <div className="flex shrink-0 items-center gap-3">
+ {totalSessions != null && sessions.length > 0 && (
+ <span className="hidden text-xs tabular-nums text-neutral-500 dark:text-neutral-400 sm:inline">
+ {t("{from}–{to} of {total}", {
+ from: from.toLocaleString(),
+ to: to.toLocaleString(),
+ total: Math.max(totalSessions, to).toLocaleString(),
+ })}
+ </span>
+ )}
+ <Pagination
+ className="w-auto"
+ page={page}
+ onPageChange={changePage}
+ hasPreviousPage={hasPrevPage}
+ hasNextPage={hasNextPage}
+ />
+ </div>
+ </div>
+
+ {isLoading ? (
+ <LedgerSkeleton />
+ ) : sessions.length === 0 ? (
+ <NothingFound
+ icon={<Rewind className="w-10 h-10" />}
+ title={t("No sessions found")}
+ description={emptyMessage || t("Try a different date range or filter")}
+ />
+ ) : (
+ <Card>
+ {groupSessions(sessions, zone, breakdown).map(group => {
+ const title = groupTitle(group);
+ return (
+ <section
+ key={group.key}
+ className="border-t border-neutral-100 first:border-t-0 dark:border-neutral-850"
+ >
+ <header className="flex min-h-8 items-center justify-between gap-3 bg-neutral-50 px-3 py-1.5 text-xs dark:bg-neutral-850/60">
+ <h3>
+ <span className="font-medium text-neutral-900 dark:text-neutral-100">{title.name}</span>
+ {title.date && <span className="text-neutral-500 dark:text-neutral-400"> · {title.date}</span>}
+ </h3>
+ <span className="text-right tabular-nums text-neutral-500 dark:text-neutral-400">
+ {t("{count, plural, one {# session} other {# sessions}}", { count: group.sessions.length })}
+ <span className="hidden sm:inline">
+ {" · "}
+ {formatGroupDuration(group.duration)}
+ {" · "}
+ {t("{count, plural, one {# pageview} other {# pageviews}}", { count: group.pageviews })}
+ </span>
+ </span>
+ </header>
+ {group.sessions.map(session => (
+ <SessionLedgerRow
+ key={session.session_id}
+ session={session}
+ userId={userId}
+ goals={goalsBySession.get(session.session_id) ?? []}
+ showWeekday={breakdown === "week"}
+ />
+ ))}
+ </section>
+ );
+ })}
+ </Card>
+ )}
+ </div>
+ ) : (
+ <SessionsList
+ sessions={sessions}
+ isLoading={isLoading}
+ page={page}
+ onPageChange={changePage}
+ hasNextPage={hasNextPage}
+ hasPrevPage={hasPrevPage}
+ userId={userId}
+ emptyMessage={emptyMessage}
+ headerElement={header}
+ />
+ )}
+
+ {!isLoading && sessions.length >= 10 && (hasNextPage || hasPrevPage) && (
+ <Pagination
+ page={page}
+ onPageChange={changePageFromBottom}
+ hasPreviousPage={hasPrevPage}
+ hasNextPage={hasNextPage}
+ />
+ )}
+ </div>
+ );
+}
+
+function LedgerSkeleton() {
+ return (
+ <Card aria-hidden>
+ <div className="flex h-8 items-center bg-neutral-50 px-3 dark:bg-neutral-850/60">
+ <Skeleton className="h-3 w-28 rounded" />
+ </div>
+ {[0, 1, 2, 3, 4, 5].map(row => (
+ <div
+ key={row}
+ className="flex h-11 items-center gap-2.5 border-t border-neutral-100 px-3 dark:border-neutral-850"
+ >
+ <Skeleton className="h-3 w-10 rounded" />
+ <Skeleton className="h-3 w-12 rounded" />
+ <Skeleton className="h-4 w-4 rounded-sm" />
+ <Skeleton className="h-4 w-4 rounded-sm" />
+ <Skeleton className="h-4 w-4 rounded-sm" />
+ <Skeleton className="hidden h-[21px] w-16 rounded-sm md:block" />
+ <Skeleton className="hidden h-3 flex-1 rounded md:block" />
+ <Skeleton className="ml-auto h-[21px] w-12 rounded-sm" />
+ <Skeleton className="h-[21px] w-12 rounded-sm" />
+ </div>
+ ))}
+ </Card>
+ );
+}
diff --git a/client/src/app/[site]/user/[userId]/components/UserSidebar.test.tsx b/client/src/app/[site]/user/[userId]/components/UserSidebar.test.tsx
new file mode 100644
index 000000000..134d1d6a0
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/UserSidebar.test.tsx
@@ -0,0 +1,204 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, render, screen, within } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { UserInfo } from "@/api/analytics/endpoints";
+import type { UserSegments } from "@/api/analytics/endpoints/userProfile";
+
+const mocks = vi.hoisted(() => ({
+ segments: undefined as UserSegments | undefined,
+ canEdit: false,
+ href: vi.fn((route: string) => `/1/${route}`),
+}));
+
+vi.mock("next-intl", () => ({
+ // Fill {placeholders} so assertions read like the rendered sentence.
+ useExtracted: () => (message: string, values?: Record<string, string>) =>
+ message.replace(/\{(\w+)\}/g, (_, key) => values?.[key] ?? `{${key}}`),
+ useLocale: () => "en-US",
+}));
+vi.mock("@/lib/configs", () => ({ useConfigs: () => ({ configs: {} }) }));
+vi.mock("@/hooks/usePermissions", () => ({ useCanOnSite: () => mocks.canEdit }));
+vi.mock("@/components/EditTraitsDialog", () => ({ EditTraitsDialog: () => null }));
+vi.mock("@/components/Favicon", () => ({ Favicon: () => null }));
+vi.mock("@/api/analytics/hooks/useUserProfile", () => ({ useUserSegments: () => ({ data: mocks.segments }) }));
+vi.mock("./UserLocationMap", () => ({ UserLocationMap: () => null }));
+vi.mock("./profileLinks", async importOriginal => ({
+ ...(await importOriginal<typeof import("./profileLinks")>()),
+ useProfileHref: () => mocks.href,
+}));
+
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { UserSidebar } from "./UserSidebar";
+
+const base = {
+ identified_user_id: "usr_8f2kq1",
+ user_id: "5be2c07f41d9",
+ country: "SE",
+ region: "SE-AB",
+ city: "Stockholm",
+ language: "sv",
+ timezone: "Europe/Stockholm",
+ device_type: "Desktop",
+ browser: "Chrome",
+ operating_system: "macOS",
+ // The selected period's own first session: a later, different touch.
+ first_seen: "2026-09-01 08:00:00",
+ first_channel: "Direct",
+ first_referrer: "",
+ first_entry_page: "/login",
+ last_channel: "Direct",
+ traits: { name: "Mara Lindqvist", email: "[email protected]", plan: "Pro", company: "Northpine" },
+ linked_devices: [
+ { anonymous_id: "5be2c07f41d9", created_at: "2026-08-14 09:12:00.123" },
+ { anonymous_id: "c84a19e6d370", created_at: "2026-08-19T18:40:00.000Z" },
+ ],
+ vitals: { lcp_p75: 1420, cls_p75: 0.03, inp_p75: 96, fcp_p75: 880, ttfb_p75: 212, performance_events: 12 },
+ locations: [],
+ devices: [],
+} as unknown as UserInfo;
+
+const firstDay = {
+ ...base,
+ first_seen: "2026-08-12 10:15:00",
+ first_channel: "Organic Search",
+ first_referrer: "https://google.com/",
+ first_entry_page: "/blog/google-analytics-alternatives",
+} as UserInfo;
+
+function showSidebar(props: Partial<Parameters<typeof UserSidebar>[0]> = {}) {
+ return render(
+ <QueryClientProvider client={new QueryClient()}>
+ <TooltipProvider>
+ <UserSidebar
+ userId="usr_8f2kq1"
+ data={base}
+ isLoading={false}
+ firstTouch={firstDay}
+ isLoadingFirstTouch={false}
+ getRegionName={() => "Stockholm County"}
+ {...props}
+ />
+ </TooltipProvider>
+ </QueryClientProvider>
+ );
+}
+
+const sectionTitles = () => screen.getAllByRole("heading", { level: 3 }).map(heading => heading.textContent);
+const section = (title: string) => screen.getByRole("heading", { level: 3, name: title }).closest("section")!;
+
+afterEach(() => {
+ cleanup();
+ mocks.segments = undefined;
+ mocks.canEdit = false;
+ mocks.href.mockClear();
+});
+
+describe("UserSidebar", () => {
+ it("is one ledger with traits first and web vitals last", () => {
+ showSidebar();
+
+ expect(sectionTitles()).toEqual(["Traits", "Acquisition", "Location & device", "Linked devices", "Web vitals"]);
+ });
+
+ it("lists custom traits and leaves out the ones the header shows as identity", () => {
+ showSidebar();
+
+ const traits = within(section("Traits"));
+ expect(traits.getByText("Pro")).toBeTruthy();
+ expect(traits.getByText("Northpine")).toBeTruthy();
+ expect(traits.queryByText("[email protected]")).toBeNull();
+ });
+
+ it("draws the linked devices the API returns, with the day each was linked", () => {
+ showSidebar();
+
+ const linked = within(section("Linked devices"));
+ expect(linked.getByText("5be2c07f41d9")).toBeTruthy();
+ expect(linked.getByText("linked Aug 14")).toBeTruthy();
+ expect(linked.getByText("c84a19e6d370")).toBeTruthy();
+ expect(linked.getByText("linked Aug 19")).toBeTruthy();
+ });
+
+ it("takes first-touch facts from the user's first day, not from the selected period", () => {
+ showSidebar();
+
+ const acquisition = within(section("Acquisition"));
+ expect(acquisition.getByText("Organic Search")).toBeTruthy();
+ expect(acquisition.getByText("/blog/google-analytics-alternatives")).toBeTruthy();
+ expect(acquisition.getByText(/Aug 12, 2026/)).toBeTruthy();
+ expect(acquisition.queryByText("/login")).toBeNull();
+ // The period's channel differs from the first one, so it is shown as the latest.
+ expect(acquisition.getByText("Latest channel")).toBeTruthy();
+ });
+
+ it("does not present the period's first session as the day the user was first seen", () => {
+ showSidebar({ firstTouch: undefined });
+
+ const acquisition = within(section("Acquisition"));
+ expect(acquisition.queryByText("First seen")).toBeNull();
+ expect(acquisition.getByText("/login")).toBeTruthy();
+ });
+
+ it("lists the segments the user's sessions match, each linking to those sessions", () => {
+ mocks.segments = {
+ segments: [
+ {
+ segmentId: 4,
+ name: "Docs readers",
+ filters: [{ parameter: "pathname", type: "contains", value: ["/docs"] }],
+ sessions: 34,
+ },
+ ],
+ total_sessions: 42,
+ truncated: false,
+ };
+ showSidebar();
+
+ expect(sectionTitles().slice(0, 2)).toEqual(["Traits", "Segments"]);
+ const segments = within(section("Segments"));
+ expect(segments.getByText("34")).toBeTruthy();
+ expect(segments.getByText("of 42")).toBeTruthy();
+ expect(segments.getByRole("link", { name: /Docs readers/ }).getAttribute("href")).toBe("/1/sessions");
+ expect(mocks.href).toHaveBeenCalledWith("sessions", [
+ { parameter: "pathname", type: "contains", value: ["/docs"] },
+ { parameter: "user_id", type: "equals", value: ["usr_8f2kq1"] },
+ ]);
+ });
+
+ it("keeps a segment the Sessions list cannot filter by as plain text", () => {
+ mocks.segments = {
+ segments: [
+ {
+ segmentId: 9,
+ name: "Stockholm time",
+ filters: [{ parameter: "timezone", type: "equals", value: ["Europe/Stockholm"] }],
+ sessions: 3,
+ },
+ ],
+ total_sessions: 42,
+ truncated: false,
+ };
+ showSidebar();
+
+ const segments = within(section("Segments"));
+ expect(segments.getByText("Stockholm time")).toBeTruthy();
+ expect(segments.queryByRole("link")).toBeNull();
+ });
+
+ it("shows no traits or linked devices for an anonymous visitor", () => {
+ showSidebar({ data: { ...base, identified_user_id: "", traits: null } as UserInfo });
+
+ expect(sectionTitles()).toEqual(["Acquisition", "Location & device", "Web vitals"]);
+ });
+
+ it("offers trait editing only to someone who may write users", () => {
+ showSidebar();
+ expect(screen.queryByRole("button", { name: "Edit traits" })).toBeNull();
+ cleanup();
+
+ mocks.canEdit = true;
+ showSidebar();
+ expect(screen.getByRole("button", { name: "Edit traits" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Add trait" })).toBeTruthy();
+ });
+});
diff --git a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
index 0f4b22d74..64f1d659a 100644
--- a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
@@ -1,17 +1,23 @@
"use client";
+import { Bookmark, Fingerprint, Pencil, Plus } from "lucide-react";
+import { DateTime } from "luxon";
import { useExtracted } from "next-intl";
-import { Pencil } from "lucide-react";
+import Link from "next/link";
import { useState } from "react";
-import { Button } from "../../../../../components/ui/button";
-import { Skeleton } from "../../../../../components/ui/skeleton";
-import { VisitCalendar } from "./Calendar";
-import { UserInfo, UserSessionCountResponse } from "../../../../../api/analytics/endpoints";
+import { UserInfo } from "../../../../../api/analytics/endpoints";
+import { useUserSegments } from "../../../../../api/analytics/hooks/useUserProfile";
import { ChannelIcon, extractDomain, getDisplayName } from "../../../../../components/Channel";
+import { EditTraitsDialog } from "../../../../../components/EditTraitsDialog";
import { Favicon } from "../../../../../components/Favicon";
+import { Button } from "../../../../../components/ui/button";
+import { Card } from "../../../../../components/ui/card";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";
+import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
import { useCanOnSite } from "../../../../../hooks/usePermissions";
import { useConfigs } from "../../../../../lib/configs";
+import { canPivot } from "../../../../../lib/pivots";
+import { useTimezone } from "../../../../../lib/store";
import { PerformanceMetric } from "../../../performance/performanceStore";
import {
formatMetricValue,
@@ -20,221 +26,370 @@ import {
METRIC_LABELS,
METRIC_LABELS_SHORT,
} from "../../../performance/utils/performanceUtils";
-import { EditTraitsDialog } from "../../../../../components/EditTraitsDialog";
import { LocationDevices } from "./LocationDevices";
-import { InfoRow, InfoRowSkeleton, SidebarCard, SidebarHeader } from "./SidebarPrimitives";
+import { useProfileHref, userFilter } from "./profileLinks";
+import { InfoRow, InfoRowSkeleton, SidebarHeader, SidebarHint, SidebarSection } from "./SidebarPrimitives";
import { UserLocationMap } from "./UserLocationMap";
+import { customTraits, traitLabel, traitText } from "./userTraits";
interface UserSidebarProps {
+ /** The identity the profile's panels query: the identified id when there is one. */
+ userId: string;
data: UserInfo | undefined;
isLoading: boolean;
- sessionCount: UserSessionCountResponse[];
- isLoadingCalendar: boolean;
+ /**
+ * The user's first day on the site, read on its own so first-touch facts do
+ * not move with the date range. Undefined while it loads, and for a user the
+ * page's filters leave with no sessions at all.
+ */
+ firstTouch: UserInfo | undefined;
+ isLoadingFirstTouch: boolean;
getRegionName: (region: string) => string;
}
const VITALS_ORDER: PerformanceMetric[] = ["lcp", "cls", "inp", "fcp", "ttfb"];
-export function UserSidebar({ data, isLoading, sessionCount, isLoadingCalendar, getRegionName }: UserSidebarProps) {
+// Postgres hands timestamps back as "2026-08-14 10:02:11.123"; an API in
+// front of it may hand back ISO. Both are UTC.
+const parseUtc = (value: string | undefined) => {
+ if (!value) return null;
+ const sql = DateTime.fromSQL(value, { zone: "utc" });
+ const parsed = sql.isValid ? sql : DateTime.fromISO(value, { zone: "utc" });
+ // Empty ranges come back as epoch-zero timestamps; treat them as absent
+ return parsed.isValid && parsed.year > 1970 ? parsed : null;
+};
+
+/**
+ * The rail: everything the page knows about who this is, as one ledger.
+ * Traits lead because they are what the site itself said about the person;
+ * what Rybbit observed follows.
+ */
+export function UserSidebar({
+ userId,
+ data,
+ isLoading,
+ firstTouch,
+ isLoadingFirstTouch,
+ getRegionName,
+}: UserSidebarProps) {
const t = useExtracted();
+ const zone = useTimezone();
const { configs } = useConfigs();
+ const { formatDateTime, formatRelative } = useDateTimeFormat();
+ const profileHref = useProfileHref();
const canEditTraits = useCanOnSite("users:write");
const [traitsOpen, setTraitsOpen] = useState(false);
+ const { data: segmentData } = useUserSegments(userId);
+
const isIdentified = !!data?.identified_user_id;
+ const traits = customTraits(data?.traits);
+ const showTraits = isIdentified && !!data && (traits.length > 0 || canEditTraits);
- // Filter custom traits (exclude username, name, email)
- const customTraits = data?.traits
- ? Object.entries(data.traits).filter(([key]) => !["username", "name", "email"].includes(key))
- : [];
+ const segments = segmentData?.segments ?? [];
+
+ // First-touch facts come from the user's first day; the selected period's
+ // own first session stands in only when there is no first day to read.
+ const acquisition = firstTouch ?? data;
+ const isLoadingAcquisition = isLoading || isLoadingFirstTouch;
+ const firstReferrerDomain = acquisition?.first_referrer ? extractDomain(acquisition.first_referrer) : null;
+ const latestChannel = data?.last_channel;
+ const channelChanged = !!latestChannel && !!acquisition && latestChannel !== acquisition.first_channel;
+ const firstSeen = parseUtc(firstTouch?.first_seen)?.setZone(zone) ?? null;
- const firstReferrerDomain = data?.first_referrer ? extractDomain(data.first_referrer) : null;
- const channelChanged = !!data?.last_channel && data.last_channel !== data.first_channel;
const vitals = data?.vitals ?? null;
- const vitalsToShow = vitals
- ? VITALS_ORDER.filter(metric => vitals[`${metric}_p75`] != null)
- : [];
+ const vitalsToShow = vitals ? VITALS_ORDER.filter(metric => vitals[`${metric}_p75`] != null) : [];
const showMap = !!configs?.mapboxToken && !!data?.country;
+ const linkedDevices = isIdentified ? (data?.linked_devices ?? []) : [];
+
+ const truncated = (value: string) => (
+ <span className="inline-block max-w-[170px] truncate align-bottom" title={value}>
+ {value}
+ </span>
+ );
return (
- <div className="w-full lg:w-[300px] lg:shrink-0 space-y-3">
- {/* Acquisition (first-touch attribution) */}
- <SidebarCard>
- <SidebarHeader title={t("Acquisition")} />
- {isLoading ? (
- <div>
- <InfoRowSkeleton labelWidth="w-14" valueWidth="w-24" withIcon />
- <InfoRowSkeleton labelWidth="w-12" valueWidth="w-20" withIcon />
- <InfoRowSkeleton labelWidth="w-16" valueWidth="w-28" />
- </div>
- ) : (
- <div>
- <InfoRow
- icon={data?.first_channel ? <ChannelIcon channel={data.first_channel} className="w-3.5 h-3.5" /> : undefined}
- label={t("Channel")}
- value={data?.first_channel || "—"}
- />
- <InfoRow
- icon={firstReferrerDomain ? <Favicon domain={firstReferrerDomain} className="w-3.5 h-3.5" /> : undefined}
- label={t("Referrer")}
- value={firstReferrerDomain ? getDisplayName(firstReferrerDomain) : "—"}
- />
- <InfoRow
- label={t("Landing page")}
- value={
- data?.first_entry_page ? (
- <span className="truncate max-w-[160px] inline-block" title={data.first_entry_page}>
- {data.first_entry_page}
- </span>
- ) : (
- "—"
- )
+ <Card className="w-full self-start lg:w-[300px] lg:shrink-0">
+ <div className="divide-y divide-neutral-100 dark:divide-neutral-850">
+ {/* Traits (identified users only) */}
+ {showTraits && (
+ <SidebarSection>
+ <SidebarHeader
+ title={t("Traits")}
+ right={
+ canEditTraits ? (
+ <Button
+ variant="ghost"
+ size="smIcon"
+ className="-my-1.5 -mr-1.5 h-6 w-6 text-neutral-500 dark:text-neutral-400"
+ aria-label={t("Edit traits")}
+ onClick={() => setTraitsOpen(true)}
+ >
+ <Pencil className="w-3 h-3" />
+ </Button>
+ ) : undefined
}
/>
- {data?.first_utm_source && (
- <InfoRow
- label={t("Source")}
- value={<span className="truncate max-w-[160px] inline-block">{data.first_utm_source}</span>}
- />
+ {traits.length > 0 ? (
+ <div>
+ {traits.map(([key, value]) => (
+ <InfoRow
+ key={key}
+ label={<span className="capitalize">{traitLabel(key)}</span>}
+ value={truncated(traitText(value))}
+ />
+ ))}
+ </div>
+ ) : (
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">{t("No traits yet")}</p>
+ )}
+ {canEditTraits && (
+ <button
+ type="button"
+ onClick={() => setTraitsOpen(true)}
+ className="mt-1.5 inline-flex items-center gap-1 rounded-sm text-xs text-neutral-500 hover:text-neutral-800 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400 dark:text-neutral-400 dark:hover:text-neutral-200"
+ >
+ <Plus className="h-3 w-3" />
+ {t("Add trait")}
+ </button>
)}
- {data?.first_utm_medium && (
+ <EditTraitsDialog
+ userId={data.identified_user_id}
+ traits={data.traits}
+ open={traitsOpen}
+ onOpenChange={setTraitsOpen}
+ />
+ </SidebarSection>
+ )}
+
+ {/* Saved segments this user's sessions fall into */}
+ {segments.length > 0 && segmentData && (
+ <SidebarSection>
+ <SidebarHeader title={t("Segments")} right={<SidebarHint>{t("Sessions in range")}</SidebarHint>} />
+ <div>
+ {segments.map(segment => {
+ const filters = [...segment.filters, userFilter(userId)];
+ const name = (
+ <>
+ <Bookmark className="h-3.5 w-3.5 shrink-0 text-neutral-400 dark:text-neutral-500" />
+ <span className="truncate">{segment.name}</span>
+ </>
+ );
+ return (
+ <InfoRow
+ key={segment.segmentId}
+ label={
+ // Offered only when the Sessions list honours every one of the segment's filters.
+ canPivot("sessions", filters) ? (
+ <Link
+ href={profileHref("sessions", filters)}
+ prefetch={false}
+ title={t("Open these sessions")}
+ className="inline-flex max-w-[170px] items-center gap-1.5 rounded-sm text-neutral-700 underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400 dark:text-neutral-200"
+ >
+ {name}
+ </Link>
+ ) : (
+ <span className="inline-flex max-w-[170px] items-center gap-1.5 text-neutral-700 dark:text-neutral-200">
+ {name}
+ </span>
+ )
+ }
+ value={
+ <>
+ <span className="tabular-nums">{segment.sessions.toLocaleString()}</span>
+ <span className="tabular-nums text-neutral-500 dark:text-neutral-400">
+ {t("of {total}", { total: segmentData.total_sessions.toLocaleString() })}
+ </span>
+ </>
+ }
+ />
+ );
+ })}
+ </div>
+ {segmentData.truncated && (
+ <p className="mt-1.5 text-[11px] text-neutral-500 dark:text-neutral-400">
+ {t("Only the first segments by name are checked.")}
+ </p>
+ )}
+ </SidebarSection>
+ )}
+
+ {/* Acquisition (first-touch attribution) */}
+ <SidebarSection>
+ <SidebarHeader title={t("Acquisition")} right={<SidebarHint>{t("First touch")}</SidebarHint>} />
+ {isLoadingAcquisition ? (
+ <div>
+ <InfoRowSkeleton labelWidth="w-14" valueWidth="w-24" withIcon />
+ <InfoRowSkeleton labelWidth="w-12" valueWidth="w-20" withIcon />
+ <InfoRowSkeleton labelWidth="w-16" valueWidth="w-28" />
+ <InfoRowSkeleton labelWidth="w-14" valueWidth="w-32" />
+ </div>
+ ) : (
+ <div>
<InfoRow
- label={t("Medium")}
- value={<span className="truncate max-w-[160px] inline-block">{data.first_utm_medium}</span>}
+ icon={
+ acquisition?.first_channel ? (
+ <ChannelIcon channel={acquisition.first_channel} className="w-3.5 h-3.5" />
+ ) : undefined
+ }
+ label={t("Channel")}
+ value={acquisition?.first_channel || "—"}
/>
- )}
- {data?.first_utm_campaign && (
<InfoRow
- label={t("Campaign")}
- value={<span className="truncate max-w-[160px] inline-block">{data.first_utm_campaign}</span>}
+ icon={
+ firstReferrerDomain ? <Favicon domain={firstReferrerDomain} className="w-3.5 h-3.5" /> : undefined
+ }
+ label={t("Referrer")}
+ value={firstReferrerDomain ? getDisplayName(firstReferrerDomain) : "—"}
/>
- )}
- {channelChanged && (
<InfoRow
- icon={<ChannelIcon channel={data.last_channel} className="w-3.5 h-3.5" />}
- label={t("Latest channel")}
- value={data.last_channel}
+ label={t("Landing page")}
+ value={acquisition?.first_entry_page ? truncated(acquisition.first_entry_page) : "—"}
/>
- )}
- </div>
- )}
- </SidebarCard>
-
- {/* Location & Device Info */}
- <SidebarCard>
- <SidebarHeader title={t("Location & Device")} />
- {showMap && data && !isLoading && (
- <UserLocationMap
- country={data.country}
- region={getRegionName(data.region)}
- city={data.city}
- className="mb-3 h-[132px]"
- />
- )}
- <LocationDevices data={data} isLoading={isLoading} getRegionName={getRegionName} />
- </SidebarCard>
-
- {/* Activity Calendar — always the user's full recent history, independent
- of the selected date range */}
- <SidebarCard>
- <SidebarHeader
- title={t("Activity Calendar")}
- right={
- <span className="text-[10px] uppercase tracking-wide text-neutral-400 dark:text-neutral-500">
- {t("Last 4 months")}
- </span>
- }
- />
- <div className="h-[140px]">
- {isLoadingCalendar ? (
- <Skeleton className="h-full w-full rounded-md" />
- ) : sessionCount.length > 0 ? (
- <VisitCalendar sessionCount={sessionCount} />
- ) : (
- <div className="flex h-full items-center justify-center text-xs text-neutral-500 dark:text-neutral-400">
- {t("No visits in the last 4 months")}
- </div>
- )}
- </div>
- </SidebarCard>
-
- {/* Web Vitals (p75 across this user's performance events) */}
- {vitals && vitalsToShow.length > 0 && (
- <SidebarCard>
- <SidebarHeader
- title={t("Web Vitals")}
- right={
- <span className="text-[10px] uppercase tracking-wide text-neutral-400 dark:text-neutral-500">p75</span>
- }
- />
- <div>
- {vitalsToShow.map(metric => {
- const value = vitals[`${metric}_p75`] as number;
- return (
+ {acquisition?.first_utm_source && (
+ <InfoRow label={t("Source")} value={truncated(acquisition.first_utm_source)} />
+ )}
+ {acquisition?.first_utm_medium && (
+ <InfoRow label={t("Medium")} value={truncated(acquisition.first_utm_medium)} />
+ )}
+ {acquisition?.first_utm_campaign && (
+ <InfoRow label={t("Campaign")} value={truncated(acquisition.first_utm_campaign)} />
+ )}
+ {channelChanged && (
<InfoRow
- key={metric}
- label={
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="cursor-default">{METRIC_LABELS_SHORT[metric]}</span>
- </TooltipTrigger>
- <TooltipContent>{METRIC_LABELS[metric]}</TooltipContent>
- </Tooltip>
- }
+ icon={<ChannelIcon channel={latestChannel} className="w-3.5 h-3.5" />}
+ label={t("Latest channel")}
+ value={latestChannel}
+ />
+ )}
+ {firstSeen && (
+ <InfoRow
+ label={t("First seen")}
value={
- <span className={getMetricColor(metric, value)}>
- {formatMetricValue(metric, value)}
- {getMetricUnit(metric, value)}
+ <span
+ className="whitespace-nowrap"
+ title={formatDateTime(firstSeen, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ timeZone: zone,
+ })}
+ >
+ {formatDateTime(firstSeen, { year: "numeric", month: "short", day: "numeric", timeZone: zone })}
+ <span className="text-neutral-500 dark:text-neutral-400"> · {formatRelative(firstSeen)}</span>
</span>
}
/>
- );
- })}
- </div>
- </SidebarCard>
- )}
-
- {/* User Traits (identified users only) */}
- {isIdentified && data && (customTraits.length > 0 || canEditTraits) && (
- <SidebarCard>
- <SidebarHeader
- title={t("User Traits")}
- right={
- canEditTraits ? (
- <Button
- variant="ghost"
- size="smIcon"
- className="-my-1.5 -mr-1.5 h-6 w-6 text-neutral-500"
- aria-label={t("Edit Traits")}
- onClick={() => setTraitsOpen(true)}
- >
- <Pencil className="w-3 h-3" />
- </Button>
- ) : undefined
- }
- />
- {customTraits.length > 0 ? (
- <div className="space-y-1">
- {customTraits.map(([key, value]) => (
- <div
- key={key}
- className="flex items-center justify-between py-1 border-b border-neutral-50 dark:border-neutral-850 last:border-0 text-xs"
- >
- <span className="text-neutral-500 dark:text-neutral-400 capitalize">{key.replace(/_/g, " ")}</span>
- <span className="text-neutral-700 dark:text-neutral-200 truncate max-w-[160px]">{String(value)}</span>
- </div>
- ))}
+ )}
</div>
- ) : (
- <p className="text-xs text-neutral-400 dark:text-neutral-500">{t("No traits yet")}</p>
)}
- <EditTraitsDialog
- userId={data.identified_user_id}
- traits={data.traits}
- open={traitsOpen}
- onOpenChange={setTraitsOpen}
- />
- </SidebarCard>
- )}
- </div>
+ </SidebarSection>
+
+ {/* Location & device */}
+ <SidebarSection>
+ <SidebarHeader title={t("Location & device")} />
+ {showMap && data && !isLoading && (
+ <UserLocationMap
+ country={data.country}
+ region={getRegionName(data.region)}
+ city={data.city}
+ className="mb-3 h-[132px]"
+ />
+ )}
+ <LocationDevices data={data} isLoading={isLoading} getRegionName={getRegionName} />
+ </SidebarSection>
+
+ {/* Devices that were merged into this identity. The API has always
+ returned them; the page never drew them. */}
+ {linkedDevices.length > 0 && (
+ <SidebarSection>
+ <SidebarHeader
+ title={t("Linked devices")}
+ right={<SidebarHint>{linkedDevices.length.toLocaleString()}</SidebarHint>}
+ />
+ <div>
+ {linkedDevices.map(device => {
+ const linkedAt = parseUtc(device.created_at)?.setZone(zone) ?? null;
+ return (
+ <InfoRow
+ key={device.anonymous_id}
+ label={
+ <span className="inline-flex items-center gap-1.5">
+ <Fingerprint className="h-3.5 w-3.5 shrink-0 text-neutral-400 dark:text-neutral-500" />
+ <span
+ className="inline-block max-w-[110px] truncate font-mono text-neutral-700 dark:text-neutral-200"
+ title={device.anonymous_id}
+ >
+ {device.anonymous_id}
+ </span>
+ </span>
+ }
+ value={
+ linkedAt ? (
+ <span
+ className="whitespace-nowrap text-neutral-500 dark:text-neutral-400"
+ title={formatDateTime(linkedAt, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ timeZone: zone,
+ })}
+ >
+ {t("linked {date}", {
+ date: formatDateTime(linkedAt, {
+ month: "short",
+ day: "numeric",
+ year: linkedAt.year === DateTime.now().year ? undefined : "numeric",
+ timeZone: zone,
+ }),
+ })}
+ </span>
+ ) : (
+ "—"
+ )
+ }
+ />
+ );
+ })}
+ </div>
+ </SidebarSection>
+ )}
+
+ {/* Web vitals (p75 across this user's performance events) */}
+ {vitals && vitalsToShow.length > 0 && (
+ <SidebarSection>
+ <SidebarHeader title={t("Web vitals")} right={<SidebarHint>p75</SidebarHint>} />
+ <div>
+ {vitalsToShow.map(metric => {
+ const value = vitals[`${metric}_p75`] as number;
+ return (
+ <InfoRow
+ key={metric}
+ label={
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="cursor-default">{METRIC_LABELS_SHORT[metric]}</span>
+ </TooltipTrigger>
+ <TooltipContent>{METRIC_LABELS[metric]}</TooltipContent>
+ </Tooltip>
+ }
+ value={
+ <span className={`tabular-nums ${getMetricColor(metric, value)}`}>
+ {formatMetricValue(metric, value)}
+ {getMetricUnit(metric, value)}
+ </span>
+ }
+ />
+ );
+ })}
+ </div>
+ </SidebarSection>
+ )}
+ </div>
+ </Card>
);
}
diff --git a/client/src/app/[site]/user/[userId]/components/UserStatBand.tsx b/client/src/app/[site]/user/[userId]/components/UserStatBand.tsx
index e8fe7916e..8925f38e6 100644
--- a/client/src/app/[site]/user/[userId]/components/UserStatBand.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserStatBand.tsx
@@ -1,124 +1,142 @@
"use client";
-import { Calendar, CalendarCheck, Clock, Files } from "lucide-react";
-import { DateTime } from "luxon";
+import { CalendarCheck, Clock, Files, Target } from "lucide-react";
import { useExtracted } from "next-intl";
import { ReactNode } from "react";
-import { UserInfo } from "../../../../../api/analytics/endpoints";
+import { useUserGoals, useUserSummary } from "../../../../../api/analytics/hooks/useUserProfile";
+import { describeComparisonWindow } from "../../../../../components/DateSelector/rangeFields";
import { EventTypeIcon } from "../../../../../components/EventIcons";
-import { Skeleton } from "../../../../../components/ui/skeleton";
-import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
-import { formatDuration } from "../../../../../lib/dateTimeUtils";
-import { getTimezone } from "../../../../../lib/store";
+import { StatBand, StatBandProps } from "../../../../../components/site/StatBand";
+import { formatShortDuration } from "../../../../../lib/dateTimeUtils";
+import { percentDelta } from "../../../../../lib/delta";
+import { useComparisonEnabled, useStore, useTimezone } from "../../../../../lib/store";
import { formatter } from "../../../../../lib/utils";
+import { profileWindow, singleDayLabel } from "./profileWindow";
-function StatCell({
- icon,
- label,
- value,
- title,
- isLoading,
-}: {
- icon: ReactNode;
- label: string;
- value: ReactNode;
- title?: string;
- isLoading: boolean;
-}) {
- return (
- <div className="min-w-0 bg-white px-3.5 py-2.5 dark:bg-neutral-900">
- <div className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-neutral-500 dark:text-neutral-400">
- {icon}
- <span className="truncate">{label}</span>
- </div>
- {isLoading ? (
- <Skeleton className="mt-1.5 h-4 w-16 rounded" />
- ) : (
- <div
- className="mt-0.5 truncate text-base font-semibold tabular-nums text-neutral-900 dark:text-neutral-50"
- title={title}
- >
- {value}
- </div>
- )}
- </div>
- );
-}
+const OutOf = ({ children }: { children: ReactNode }) => (
+ <span className="text-sm font-normal text-neutral-500 dark:text-neutral-400"> {children}</span>
+);
-// Full-width engagement summary: one flat strip of six cells separated by
-// hairline seams (gap-px over the border color), wrapping 6 → 3 → 2 per row.
-export function UserStatBand({ data, isLoading }: { data: UserInfo | undefined; isLoading: boolean }) {
+/**
+ * The profile's summary strip: what this user did in the selected period,
+ * each figure against the comparison period. Lifetime facts (first seen, last
+ * seen) live in the rail, not here, so nothing in the band changes meaning
+ * with the date range.
+ */
+export function UserStatBand({ userId }: { userId: string }) {
const t = useExtracted();
- const { formatRelative, formatDateTime, hour12 } = useDateTimeFormat();
+ const zone = useTimezone();
+ const time = useStore(state => state.time);
+ const previousTime = useStore(state => state.previousTime);
+ const comparisonEnabled = useComparisonEnabled();
- const timezone = getTimezone();
- const toLocal = (sql: string | undefined) => {
- if (!sql) return null;
- const dt = DateTime.fromSQL(sql, { zone: "utc" }).setZone(timezone);
- // Empty ranges come back as epoch-zero timestamps; treat them as absent
- return dt.isValid && dt.year > 1970 ? dt : null;
- };
- const firstSeen = toLocal(data?.first_seen);
- const lastSeen = toLocal(data?.last_seen);
- const absolute = (dt: DateTime) =>
- formatDateTime(dt, {
- year: "numeric",
- month: "short",
- day: "numeric",
- hour: "numeric",
- minute: "2-digit",
- hour12,
- timeZone: timezone,
- });
+ const { data: current, isLoading } = useUserSummary(userId);
+ const { data: previousSummary, isLoading: isLoadingPrevious } = useUserSummary(userId, "previous");
+ // Turning the comparison off disables the query, but a disabled query still
+ // hands back its last result as a placeholder: drop it here so the deltas go.
+ const previous = comparisonEnabled ? previousSummary : undefined;
+ const { data: goals, isLoading: isLoadingGoals } = useUserGoals(userId);
+
+ const comparisonWindow = singleDayLabel(describeComparisonWindow(previousTime, time, zone));
+ const window = profileWindow(time, zone);
const count = (value: number | undefined) => (value != null ? formatter(value) : "—");
- const countTitle = (value: number | undefined) => (value != null ? value.toLocaleString() : undefined);
+ const exact = (value: number | undefined) => (value != null ? value.toLocaleString() : undefined);
+ const duration = (seconds: number | undefined) => (seconds ? formatShortDuration(seconds) : "—");
+
+ // One line under each figure: what it was in the comparison period. Passed
+ // as "" while that is loading so the line's height is reserved, and left out
+ // altogether when the comparison is off.
+ const before = (value: string | undefined) => {
+ if (!comparisonEnabled) return undefined;
+ if (isLoadingPrevious || !previous || value === undefined) return "";
+ return comparisonWindow
+ ? t("{value} in {window}", { value, window: comparisonWindow })
+ : t("{value} before", { value });
+ };
+
+ const completedGoals = goals?.filter(goal => goal.sessions > 0).length ?? 0;
+ // A conversion is one session completing one goal, as on the Goals page.
+ const conversions = goals?.reduce((total, goal) => total + goal.sessions, 0) ?? 0;
+ // A site with no goals has nothing to put in the last cell.
+ const showGoals = isLoadingGoals || (goals?.length ?? 0) > 0;
+
+ const cells: StatBandProps["cells"] = [
+ {
+ id: "sessions",
+ icon: <Files className="h-3 w-3" />,
+ label: t("Sessions"),
+ value: count(current?.sessions),
+ title: exact(current?.sessions),
+ delta: percentDelta(current?.sessions, previous?.sessions),
+ sub: before(previous ? formatter(previous.sessions) : undefined),
+ },
+ {
+ id: "pageviews",
+ icon: <EventTypeIcon type="pageview" className="h-3 w-3" />,
+ label: t("Pageviews"),
+ value: count(current?.pageviews),
+ title: exact(current?.pageviews),
+ delta: percentDelta(current?.pageviews, previous?.pageviews),
+ sub: before(previous ? formatter(previous.pageviews) : undefined),
+ },
+ {
+ id: "events",
+ icon: <EventTypeIcon type="custom_event" className="h-3 w-3" />,
+ label: t("Events"),
+ value: count(current?.events),
+ title: exact(current?.events),
+ delta: percentDelta(current?.events, previous?.events),
+ sub: before(previous ? formatter(previous.events) : undefined),
+ },
+ {
+ id: "duration",
+ icon: <Clock className="h-3 w-3" />,
+ label: t("Avg duration"),
+ value: duration(current?.duration),
+ // No sessions means no average: nothing to compare and nothing to
+ // quote, rather than an average of zero.
+ delta: current?.sessions ? percentDelta(current.duration, previous?.duration) : null,
+ sub: before(previous && previous.sessions > 0 ? duration(previous.duration) : undefined),
+ },
+ {
+ id: "active-days",
+ icon: <CalendarCheck className="h-3 w-3" />,
+ label: t("Active days"),
+ value: (
+ <>
+ {count(current?.active_days)}
+ {window && current && <OutOf>{t("of {total}", { total: window.days.toLocaleString() })}</OutOf>}
+ </>
+ ),
+ title: t("Days on which this user started a session"),
+ delta: percentDelta(current?.active_days, previous?.active_days),
+ sub: before(previous ? formatter(previous.active_days) : undefined),
+ },
+ showGoals && {
+ id: "goals",
+ icon: <Target className="h-3 w-3" />,
+ label: t("Goals completed"),
+ value: (
+ <>
+ {completedGoals.toLocaleString()}
+ <OutOf>{t("of {total}", { total: (goals?.length ?? 0).toLocaleString() })}</OutOf>
+ </>
+ ),
+ title: t("Goals this user completed at least once in this period"),
+ sub: t("{count, plural, one {# conversion} other {# conversions}}", { count: conversions }),
+ isLoading: isLoadingGoals,
+ },
+ ];
+ // One row of six needs about 160px a cell. The band's own breakpoints go by
+ // the viewport, and between `lg` and `xl` the app sidebar leaves less than
+ // that, which cut off the figures themselves. Below `xl` the band is rows
+ // of three instead.
return (
- <div className="mb-4 overflow-hidden rounded-lg border border-neutral-100 dark:border-neutral-850">
- <div className="grid grid-cols-2 gap-px bg-neutral-100 dark:bg-neutral-850 sm:grid-cols-3 lg:grid-cols-6">
- <StatCell
- icon={<Files className="h-3 w-3" />}
- label={t("Sessions")}
- value={count(data?.sessions)}
- title={countTitle(data?.sessions)}
- isLoading={isLoading}
- />
- <StatCell
- icon={<EventTypeIcon type="pageview" className="h-3 w-3" />}
- label={t("Pageviews")}
- value={count(data?.pageviews)}
- title={countTitle(data?.pageviews)}
- isLoading={isLoading}
- />
- <StatCell
- icon={<EventTypeIcon type="custom_event" className="h-3 w-3" />}
- label={t("Events")}
- value={count(data?.events)}
- title={countTitle(data?.events)}
- isLoading={isLoading}
- />
- <StatCell
- icon={<Clock className="h-3 w-3" />}
- label={t("Avg Duration")}
- value={data?.duration ? formatDuration(data.duration) : "—"}
- isLoading={isLoading}
- />
- <StatCell
- icon={<Calendar className="h-3 w-3" />}
- label={t("First Seen")}
- value={firstSeen ? formatRelative(firstSeen) : "—"}
- title={firstSeen ? absolute(firstSeen) : undefined}
- isLoading={isLoading}
- />
- <StatCell
- icon={<CalendarCheck className="h-3 w-3" />}
- label={t("Last Seen")}
- value={lastSeen ? formatRelative(lastSeen) : "—"}
- title={lastSeen ? absolute(lastSeen) : undefined}
- isLoading={isLoading}
- />
- </div>
- </div>
+ <>
+ <StatBand className="xl:hidden" isLoading={isLoading} columns={3} cells={cells} />
+ <StatBand className="hidden xl:block" isLoading={isLoading} columns={showGoals ? 6 : 5} cells={cells} />
+ </>
);
}
diff --git a/client/src/app/[site]/user/[userId]/components/UserStepper.tsx b/client/src/app/[site]/user/[userId]/components/UserStepper.tsx
new file mode 100644
index 000000000..bed85f54a
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/UserStepper.tsx
@@ -0,0 +1,99 @@
+"use client";
+
+import { QueryKey, QueryObserver, useQueryClient } from "@tanstack/react-query";
+import { ChevronDown, ChevronUp } from "lucide-react";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { ReactNode, useEffect } from "react";
+import { UsersListResponse } from "../../../../../api/analytics/endpoints";
+import { Button } from "../../../../../components/ui/button";
+import { useStore } from "../../../../../lib/store";
+import { CachedUsersList, findUsersListPosition } from "./usersListPosition";
+
+// The key useGetUsers declares; the rest of the key is built by the analytics
+// query layer as [name, site, path, params, body].
+const USERS_LIST_KEY = "users";
+
+/**
+ * "3 of 4,870 users", with the previous and next user of the Users list the
+ * visitor came from. It reads the pages of that list already in the query
+ * cache (whatever sort, search and page they were on) and asks for nothing: a
+ * profile opened from a session card or a pasted link has no list behind it
+ * and shows no stepper.
+ */
+export function UserStepper({ userIds }: { userIds: string[] }) {
+ const t = useExtracted();
+ const queryClient = useQueryClient();
+ const site = useStore(state => state.site);
+ const privateKey = useStore(state => state.privateKey);
+
+ const lists: (CachedUsersList & { queryKey: QueryKey })[] = queryClient
+ .getQueryCache()
+ .findAll({ queryKey: [USERS_LIST_KEY] })
+ .filter(query => String(query.queryKey[1]) === String(site) && query.queryKey[2] === "users")
+ .map(query => ({
+ queryKey: query.queryKey,
+ data: query.state.data as UsersListResponse | undefined,
+ params: query.queryKey[3] as Record<string, unknown> | undefined,
+ updatedAt: query.state.dataUpdatedAt,
+ }));
+
+ const found = findUsersListPosition(lists, userIds);
+ const listKey = found?.list.queryKey;
+ const listKeyHash = listKey ? JSON.stringify(listKey) : null;
+
+ // The Users page is unmounted, so nothing observes its query and the cache
+ // would drop it after a few minutes of stepping. A disabled observer keeps
+ // the page of results alive without ever refetching it.
+ useEffect(() => {
+ if (!listKey) return;
+ const observer = new QueryObserver(queryClient, { queryKey: listKey, enabled: false });
+ return observer.subscribe(() => {});
+ // listKeyHash stands in for listKey, which is a new array on every render.
+ }, [queryClient, listKeyHash]);
+
+ if (!found) return null;
+
+ const hrefFor = (id: string) => {
+ const base = privateKey ? `/${site}/${privateKey}` : `/${site}`;
+ return `${base}/user/${encodeURIComponent(id)}`;
+ };
+
+ const values = { position: found.position.toLocaleString(), total: found.total.toLocaleString() };
+
+ return (
+ <div className="flex shrink-0 items-center gap-1.5 text-xs text-neutral-500 dark:text-neutral-400">
+ <span className="hidden whitespace-nowrap tabular-nums sm:inline">
+ {found.identifiedOnly
+ ? t("{position} of {total} identified users", values)
+ : t("{position} of {total} users", values)}
+ </span>
+ <div className="flex items-center">
+ <StepButton label={t("Previous user")} href={found.previousId ? hrefFor(found.previousId) : null}>
+ <ChevronUp />
+ </StepButton>
+ <StepButton label={t("Next user")} href={found.nextId ? hrefFor(found.nextId) : null}>
+ <ChevronDown />
+ </StepButton>
+ </div>
+ </div>
+ );
+}
+
+function StepButton({ label, href, children }: { label: string; href: string | null; children: ReactNode }) {
+ if (!href) {
+ return (
+ <Button variant="ghost" size="xs" className="w-6 px-0" aria-label={label} title={label} disabled>
+ {children}
+ </Button>
+ );
+ }
+
+ return (
+ <Button asChild variant="ghost" size="xs" className="w-6 px-0">
+ <Link href={href} aria-label={label} title={label}>
+ {children}
+ </Link>
+ </Button>
+ );
+}
diff --git a/client/src/app/[site]/user/[userId]/components/UserTopPages.tsx b/client/src/app/[site]/user/[userId]/components/UserTopPages.tsx
index dc256d1b0..cca55953d 100644
--- a/client/src/app/[site]/user/[userId]/components/UserTopPages.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserTopPages.tsx
@@ -1,31 +1,31 @@
-import { useState } from "react";
import { useExtracted } from "next-intl";
import { useGetSite } from "../../../../../api/admin/hooks/useSites";
-import { TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
-import { Card, CardContent } from "../../../../../components/ui/card";
-import { Tabs } from "../../../../../components/ui/tabs";
+import { Card } from "../../../../../components/ui/card";
import { truncateString } from "../../../../../lib/utils";
import { StandardSection } from "../../../components/shared/StandardSection/StandardSection";
+import { OpenInLink, ProfileCardHeader } from "./ProfileCard";
+import { useProfileHref, userFilter } from "./profileLinks";
-type Tab = "pages" | "events";
-
+/**
+ * What this user looked at and did, side by side: both lists are on screen at
+ * once instead of behind a tab, and each opens the same user on its own page.
+ */
export function UserTopPages({ userId }: { userId: string }) {
const t = useExtracted();
- const [tab, setTab] = useState<Tab>("pages");
-
const { data: siteMetadata } = useGetSite();
+ const profileHref = useProfileHref();
+ const filters = [userFilter(userId)];
return (
- <Card>
- <CardContent className="pt-3">
- <Tabs defaultValue="pages" value={tab} onValueChange={value => setTab(value as Tab)}>
- <div className="flex flex-row gap-2 items-center">
- <TabsList>
- <TabsTrigger value="pages">{t("Top Pages")}</TabsTrigger>
- <TabsTrigger value="events">{t("Events")}</TabsTrigger>
- </TabsList>
- </div>
- <TabsContent value="pages">
+ // Pairs up by the width of the profile's main column (a container), not the viewport.
+ <div className="grid grid-cols-1 gap-3 @xl:grid-cols-2">
+ <Card>
+ <div className="p-4">
+ <ProfileCardHeader
+ title={t("Top pages")}
+ right={<OpenInLink href={profileHref("pages", filters)}>{t("Open in Pages")}</OpenInLink>}
+ />
+ <div className="mt-2.5">
<StandardSection
filterParameter="pathname"
title={t("Pages")}
@@ -36,10 +36,18 @@ export function UserTopPages({ userId }: { userId: string }) {
const host = e.hostname || siteMetadata?.domain;
return host ? `https://${host}${e.value}` : "#";
}}
- additionalFilters={[{ parameter: "user_id", value: [userId], type: "equals" }]}
+ additionalFilters={filters}
/>
- </TabsContent>
- <TabsContent value="events">
+ </div>
+ </div>
+ </Card>
+ <Card>
+ <div className="p-4">
+ <ProfileCardHeader
+ title={t("Events")}
+ right={<OpenInLink href={profileHref("events", filters)}>{t("Open in Events")}</OpenInLink>}
+ />
+ <div className="mt-2.5">
<StandardSection
filterParameter="event_name"
title={t("Events")}
@@ -47,11 +55,11 @@ export function UserTopPages({ userId }: { userId: string }) {
getValue={e => e.value}
getKey={e => e.value}
getLabel={e => truncateString(e.value, 50) || "Other"}
- additionalFilters={[{ parameter: "user_id", value: [userId], type: "equals" }]}
+ additionalFilters={filters}
/>
- </TabsContent>
- </Tabs>
- </CardContent>
- </Card>
+ </div>
+ </div>
+ </Card>
+ </div>
);
}
diff --git a/client/src/app/[site]/user/[userId]/components/calendarLayout.test.ts b/client/src/app/[site]/user/[userId]/components/calendarLayout.test.ts
new file mode 100644
index 000000000..3b42b8517
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/calendarLayout.test.ts
@@ -0,0 +1,155 @@
+import { DateTime } from "luxon";
+import { describe, expect, it } from "vitest";
+import {
+ activityCeiling,
+ activityLevel,
+ activityStats,
+ buildCalendarWeeks,
+ firstActiveDay,
+ monthLabelColumns,
+ rangeColumns,
+} from "./calendarLayout";
+
+// Wednesday.
+const today = DateTime.fromISO("2026-09-30", { zone: "utc" });
+const day = (date: string, sessions: number) => ({ date, sessions });
+
+describe("buildCalendarWeeks", () => {
+ const counts = [day("2026-08-12", 1), day("2026-09-28", 2), day("2026-09-30", 3)];
+ const weeks = buildCalendarWeeks(counts, today, 18);
+
+ it("ends with the week today falls in and starts every week on Monday", () => {
+ expect(weeks).toHaveLength(18);
+ expect(weeks[17].start).toBe("2026-09-28");
+ expect(weeks[0].start).toBe("2026-06-01");
+ expect(weeks.every(week => DateTime.fromISO(week.start).weekday === 1)).toBe(true);
+ });
+
+ it("leaves out days that have not happened yet", () => {
+ expect(weeks[17].days.map(d => d?.date ?? null)).toEqual([
+ "2026-09-28",
+ "2026-09-29",
+ "2026-09-30",
+ null,
+ null,
+ null,
+ null,
+ ]);
+ });
+
+ it("marks the days before the first session, and only those", () => {
+ const all = weeks.flatMap(week => week.days).filter(d => d !== null);
+ expect(all.find(d => d.date === "2026-08-11")?.beforeFirstVisit).toBe(true);
+ expect(all.find(d => d.date === "2026-08-12")?.beforeFirstVisit).toBe(false);
+ expect(all.find(d => d.date === "2026-08-13")?.beforeFirstVisit).toBe(false);
+ });
+
+ it("carries each day's sessions and level", () => {
+ expect(weeks[17].days[0]).toEqual({ date: "2026-09-28", sessions: 2, level: 2, beforeFirstVisit: false });
+ expect(weeks[17].days[1]).toEqual({ date: "2026-09-29", sessions: 0, level: 0, beforeFirstVisit: false });
+ expect(weeks[17].days[2]?.level).toBe(3);
+ });
+
+ it("treats every day as before the first visit for a user with no sessions", () => {
+ const empty = buildCalendarWeeks([], today, 2);
+ expect(empty.flatMap(week => week.days).every(d => d === null || d.beforeFirstVisit)).toBe(true);
+ });
+});
+
+describe("activity levels", () => {
+ it("never saturates a visitor who comes once a day", () => {
+ const counts = [day("2026-09-01", 1), day("2026-09-02", 1)];
+ expect(activityCeiling(counts)).toBe(3);
+ expect(activityLevel(1, 3)).toBe(1);
+ expect(activityLevel(2, 3)).toBe(2);
+ expect(activityLevel(3, 3)).toBe(3);
+ expect(activityLevel(9, 3)).toBe(3);
+ expect(activityLevel(0, 3)).toBe(0);
+ });
+
+ it("scales to a heavy user without letting one outlier flatten the rest", () => {
+ const counts = [
+ ...Array.from({ length: 30 }, (_, i) => day(`2026-08-${String(i + 1).padStart(2, "0")}`, 6)),
+ day("2026-09-01", 200),
+ ];
+ expect(activityCeiling(counts)).toBe(6);
+ expect(activityLevel(2, 6)).toBe(1);
+ expect(activityLevel(4, 6)).toBe(2);
+ });
+});
+
+describe("firstActiveDay", () => {
+ it("is the earliest day with a session, whatever the row order", () => {
+ expect(firstActiveDay([day("2026-09-02", 1), day("2026-08-12", 2), day("2026-08-01", 0)])).toBe("2026-08-12");
+ expect(firstActiveDay([])).toBeNull();
+ });
+});
+
+describe("monthLabelColumns", () => {
+ it("puts each month on the week that holds its first day", () => {
+ const labels = monthLabelColumns(buildCalendarWeeks([], today, 18));
+ expect(labels).toEqual([
+ { month: "2026-06", column: 0 },
+ { month: "2026-07", column: 4 },
+ { month: "2026-08", column: 8 },
+ { month: "2026-09", column: 13 },
+ ]);
+ });
+
+ it("does not label a month none of whose days are drawn", () => {
+ // The last week runs into October, but today is still in September.
+ const labels = monthLabelColumns(buildCalendarWeeks([], today, 2));
+ expect(labels.map(label => label.month)).toEqual(["2026-09"]);
+ });
+});
+
+describe("rangeColumns", () => {
+ const weeks = buildCalendarWeeks([], today, 18);
+
+ it("covers the weeks a range touches", () => {
+ expect(rangeColumns(weeks, "2026-09-01", "2026-09-30")).toEqual({ from: 13, to: 17 });
+ expect(rangeColumns(weeks, "2026-09-14", "2026-09-14")).toEqual({ from: 15, to: 15 });
+ });
+
+ it("clamps a range that starts before the calendar", () => {
+ expect(rangeColumns(weeks, "2026-01-01", "2026-06-10")).toEqual({ from: 0, to: 1 });
+ });
+
+ it("is null for a range the calendar does not show", () => {
+ expect(rangeColumns(weeks, "2026-01-01", "2026-03-01")).toBeNull();
+ expect(rangeColumns(weeks, "2026-10-10", "2026-10-20")).toBeNull();
+ });
+});
+
+describe("activityStats", () => {
+ const counts = [
+ day("2026-08-31", 4),
+ day("2026-09-01", 2),
+ day("2026-09-02", 1),
+ day("2026-09-03", 3),
+ day("2026-09-05", 0),
+ day("2026-09-07", 2),
+ day("2026-09-08", 2),
+ // Monday again: Mondays total 2 + 3 inside September.
+ day("2026-09-14", 3),
+ ];
+
+ it("finds the longest run of consecutive active days inside the range", () => {
+ expect(activityStats(counts, "2026-09-01", "2026-09-30").longestStreak).toBe(3);
+ // The day before the range would extend the run to four.
+ expect(activityStats(counts, null, null).longestStreak).toBe(4);
+ });
+
+ it("names the weekday with the most sessions", () => {
+ // Mon 5, Tue 4, Wed 1, Thu 3 inside September.
+ expect(activityStats(counts, "2026-09-01", "2026-09-30").busiestWeekday).toBe(1);
+ });
+
+ it("breaks a tie towards the earlier weekday", () => {
+ expect(activityStats([day("2026-09-03", 2), day("2026-09-01", 2)], null, null).busiestWeekday).toBe(2);
+ });
+
+ it("has nothing to say about a range with no sessions", () => {
+ expect(activityStats(counts, "2026-07-01", "2026-07-31")).toEqual({ longestStreak: 0, busiestWeekday: null });
+ });
+});
diff --git a/client/src/app/[site]/user/[userId]/components/calendarLayout.ts b/client/src/app/[site]/user/[userId]/components/calendarLayout.ts
new file mode 100644
index 000000000..ed6e1ebd4
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/calendarLayout.ts
@@ -0,0 +1,161 @@
+import { DateTime } from "luxon";
+
+// Pure layout and statistics for the profile's activity calendar. Days are ISO
+// dates ("2026-09-14") in the dashboard's timezone, the same days the
+// session-count endpoint buckets by.
+
+export const CALENDAR_WEEKS = 18;
+
+/** 0 is an empty day; 1 to 3 are the three steps of the data hue. */
+export type ActivityLevel = 0 | 1 | 2 | 3;
+
+export interface CalendarDay {
+ date: string;
+ sessions: number;
+ level: ActivityLevel;
+ /** Earlier than the user's first recorded session: drawn as an outline. */
+ beforeFirstVisit: boolean;
+}
+
+export interface CalendarWeek {
+ /** Monday of the week. */
+ start: string;
+ /** Monday first. Null for days that have not happened yet. */
+ days: (CalendarDay | null)[];
+}
+
+export interface DayCount {
+ date: string;
+ sessions: number;
+}
+
+/** The first day with a session, or null for a user with none. */
+export function firstActiveDay(counts: DayCount[]): string | null {
+ return counts.reduce<string | null>(
+ (first, day) => (day.sessions > 0 && (first === null || day.date < first) ? day.date : first),
+ null
+ );
+}
+
+/**
+ * The session count that earns the darkest step. Taken near the top of the
+ * user's own days so one outlier does not wash out every other day, and never
+ * below three so a visitor who comes once a day reads as light, not saturated.
+ */
+export function activityCeiling(counts: DayCount[]): number {
+ const active = counts
+ .map(day => day.sessions)
+ .filter(sessions => sessions > 0)
+ .sort((a, b) => a - b);
+ if (active.length === 0) return 3;
+ return Math.max(3, active[Math.floor((active.length - 1) * 0.95)]);
+}
+
+export function activityLevel(sessions: number, ceiling: number): ActivityLevel {
+ if (sessions <= 0) return 0;
+ return Math.min(3, Math.max(1, Math.ceil((sessions / ceiling) * 3))) as ActivityLevel;
+}
+
+/**
+ * The last `weeks` weeks ending with the week `today` falls in, oldest first.
+ */
+export function buildCalendarWeeks(counts: DayCount[], today: DateTime, weeks = CALENDAR_WEEKS): CalendarWeek[] {
+ const byDate = new Map(counts.map(day => [day.date, day.sessions]));
+ const firstVisit = firstActiveDay(counts);
+ const ceiling = activityCeiling(counts);
+ const todayIso = today.toISODate() ?? "";
+ const firstMonday = today.startOf("week").minus({ weeks: weeks - 1 });
+
+ return Array.from({ length: weeks }, (_, weekIndex) => {
+ const monday = firstMonday.plus({ weeks: weekIndex });
+ return {
+ start: monday.toISODate() ?? "",
+ days: Array.from({ length: 7 }, (_, dayIndex) => {
+ const date = monday.plus({ days: dayIndex }).toISODate() ?? "";
+ if (date > todayIso) return null;
+ const sessions = byDate.get(date) ?? 0;
+ return {
+ date,
+ sessions,
+ level: activityLevel(sessions, ceiling),
+ beforeFirstVisit: firstVisit === null || date < firstVisit,
+ };
+ }),
+ };
+ });
+}
+
+/**
+ * Where each month's label goes: the week that holds its first drawn day. A
+ * week is filed under the month of its last drawn day, so the week with the
+ * 1st in it opens the new month. `month` is "2026-09".
+ */
+export function monthLabelColumns(weeks: CalendarWeek[]): { month: string; column: number }[] {
+ const labels: { month: string; column: number }[] = [];
+ weeks.forEach((week, column) => {
+ const lastDay = [...week.days].reverse().find(day => day !== null);
+ if (!lastDay) return;
+ const month = lastDay.date.slice(0, 7);
+ if (labels[labels.length - 1]?.month !== month) labels.push({ month, column });
+ });
+ return labels;
+}
+
+/**
+ * The columns a date range covers, clamped to the calendar. Null when the
+ * range lies wholly outside it. `end` is inclusive.
+ */
+export function rangeColumns(weeks: CalendarWeek[], start: string, end: string): { from: number; to: number } | null {
+ if (weeks.length === 0 || start > end) return null;
+ const sundayOf = (week: CalendarWeek) => DateTime.fromISO(week.start).plus({ days: 6 }).toISODate() ?? "";
+
+ const from = weeks.findIndex(week => sundayOf(week) >= start);
+ if (from === -1) return null;
+
+ let to = -1;
+ weeks.forEach((week, column) => {
+ if (week.start <= end) to = column;
+ });
+ return to < from ? null : { from, to };
+}
+
+export interface ActivityStats {
+ /** Longest run of consecutive days with a session. */
+ longestStreak: number;
+ /** ISO weekday (1 = Monday) with the most sessions, or null with no sessions. */
+ busiestWeekday: number | null;
+}
+
+/**
+ * Streak and busiest weekday over the days from `start` to `end` inclusive.
+ * Pass nulls to read the user's whole history.
+ */
+export function activityStats(counts: DayCount[], start: string | null, end: string | null): ActivityStats {
+ const active = counts
+ .filter(day => day.sessions > 0 && (start === null || day.date >= start) && (end === null || day.date <= end))
+ .sort((a, b) => a.date.localeCompare(b.date));
+
+ let longestStreak = 0;
+ let streak = 0;
+ let previous: DateTime | null = null;
+ const perWeekday = new Map<number, number>();
+
+ for (const day of active) {
+ const date = DateTime.fromISO(day.date);
+ streak = previous !== null && Math.round(date.diff(previous, "days").days) === 1 ? streak + 1 : 1;
+ longestStreak = Math.max(longestStreak, streak);
+ previous = date;
+ perWeekday.set(date.weekday, (perWeekday.get(date.weekday) ?? 0) + day.sessions);
+ }
+
+ // Ties go to the earlier weekday, so the answer does not depend on row order.
+ let busiestWeekday: number | null = null;
+ for (let weekday = 1; weekday <= 7; weekday++) {
+ const sessions = perWeekday.get(weekday) ?? 0;
+ if (sessions > 0 && (busiestWeekday === null || sessions > (perWeekday.get(busiestWeekday) ?? 0))) {
+ busiestWeekday = weekday;
+ }
+ }
+
+ return { longestStreak, busiestWeekday };
+}
diff --git a/client/src/app/[site]/user/[userId]/components/profileLinks.test.ts b/client/src/app/[site]/user/[userId]/components/profileLinks.test.ts
new file mode 100644
index 000000000..9824e5a96
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/profileLinks.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it, vi } from "vitest";
+
+// usePivotHref pulls in the store and the router; withRoute needs neither.
+vi.mock("../../../../../hooks/usePivotHref", () => ({ usePivotHref: vi.fn() }));
+
+import { userFilter, withRoute } from "./profileLinks";
+
+describe("withRoute", () => {
+ it("swaps the page and keeps the query string", () => {
+ expect(withRoute("/42/sessions?wellKnown=last-30-days&filters=x", "goals")).toBe(
+ "/42/goals?wellKnown=last-30-days&filters=x"
+ );
+ });
+
+ it("stays inside a private link", () => {
+ expect(withRoute("/42/abc123def456/sessions?stat=users", "journeys")).toBe("/42/abc123def456/journeys?stat=users");
+ });
+
+ it("handles a link with no query string", () => {
+ expect(withRoute("/42/sessions", "events")).toBe("/42/events");
+ });
+
+ it("only touches the route segment, not a value that happens to contain it", () => {
+ expect(withRoute("/42/sessions?filters=%2Fsessions%2Fnew", "pages")).toBe("/42/pages?filters=%2Fsessions%2Fnew");
+ });
+});
+
+describe("userFilter", () => {
+ it("is an equals filter on user_id", () => {
+ expect(userFilter("usr_8f2kq1")).toEqual({ parameter: "user_id", type: "equals", value: ["usr_8f2kq1"] });
+ });
+});
diff --git a/client/src/app/[site]/user/[userId]/components/profileLinks.ts b/client/src/app/[site]/user/[userId]/components/profileLinks.ts
new file mode 100644
index 000000000..26ed0c885
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/profileLinks.ts
@@ -0,0 +1,28 @@
+import { Filter } from "@rybbit/shared";
+import { usePivotHref } from "../../../../../hooks/usePivotHref";
+
+/** Pages of the site the profile links out to, as their route segment. */
+export type ProfileRoute = "sessions" | "users" | "pages" | "events" | "goals" | "journeys";
+
+/**
+ * Points a Sessions pivot link at another page of the same site, keeping its
+ * query string. The shared pivot builder only knows Sessions, Users and
+ * Replay; the profile also links to Pages, Events, Goals and Journeys, which
+ * read the same period and filters from the URL.
+ */
+export function withRoute(sessionsHref: string, route: ProfileRoute): string {
+ return sessionsHref.replace(/\/sessions(?=\?|$)/, `/${route}`);
+}
+
+/** The filter that narrows any site page to one user. */
+export const userFilter = (userId: string): Filter => ({ parameter: "user_id", type: "equals", value: [userId] });
+
+/**
+ * Returns a builder for links from the profile to another page of the site,
+ * with the current period, comparison and private-link key, narrowed by
+ * `extraFilters`. Every target used here accepts the `user_id` filter.
+ */
+export function useProfileHref(): (route: ProfileRoute, extraFilters?: Filter[]) => string {
+ const pivotHref = usePivotHref();
+ return (route, extraFilters) => withRoute(pivotHref("sessions", extraFilters), route);
+}
diff --git a/client/src/app/[site]/user/[userId]/components/profileWindow.test.ts b/client/src/app/[site]/user/[userId]/components/profileWindow.test.ts
new file mode 100644
index 000000000..b4410d927
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/profileWindow.test.ts
@@ -0,0 +1,65 @@
+import { DateTime } from "luxon";
+import { describe, expect, it } from "vitest";
+import { profileWindow, singleDayLabel } from "./profileWindow";
+
+describe("singleDayLabel", () => {
+ it("names a one-day window once", () => {
+ expect(singleDayLabel("Sep 30 – Sep 30")).toBe("Sep 30");
+ expect(singleDayLabel("Sep 30 – Sep 30, 2025")).toBe("Sep 30, 2025");
+ });
+
+ it("leaves a real range alone", () => {
+ expect(singleDayLabel("Aug 3 – Sep 1")).toBe("Aug 3 – Sep 1");
+ expect(singleDayLabel("Dec 30 – Jan 5, 2025")).toBe("Dec 30 – Jan 5, 2025");
+ expect(singleDayLabel(null)).toBeNull();
+ });
+});
+
+const zone = "Europe/Stockholm";
+const now = DateTime.fromISO("2026-09-30T14:46:00", { zone });
+
+describe("profileWindow", () => {
+ it("counts both ends of a date range", () => {
+ expect(profileWindow({ mode: "range", startDate: "2026-09-01", endDate: "2026-09-30" }, zone, now)).toEqual({
+ start: "2026-09-01",
+ end: "2026-09-30",
+ days: 30,
+ });
+ });
+
+ it("is one day for a single day", () => {
+ expect(profileWindow({ mode: "day", day: "2026-09-14" }, zone, now)).toEqual({
+ start: "2026-09-14",
+ end: "2026-09-14",
+ days: 1,
+ });
+ });
+
+ it("stops a period that runs into the future at today", () => {
+ expect(profileWindow({ mode: "year", year: "2026-01-01" }, zone, now)).toEqual({
+ start: "2026-01-01",
+ end: "2026-09-30",
+ days: 273,
+ });
+ expect(profileWindow({ mode: "week", week: "2026-09-28" }, zone, now)?.days).toBe(3);
+ });
+
+ it("covers a whole past month", () => {
+ expect(profileWindow({ mode: "month", month: "2026-08-01" }, zone, now)?.days).toBe(31);
+ });
+
+ it("counts the days a range with times touches", () => {
+ const window = profileWindow(
+ { mode: "range", startDate: "2026-09-10", endDate: "2026-09-12", startTime: "18:00", endTime: "06:00" },
+ zone,
+ now
+ );
+ expect(window).toEqual({ start: "2026-09-10", end: "2026-09-12", days: 3 });
+ });
+
+ it("has no day count for all time, a trailing-minutes window, or a period that has not started", () => {
+ expect(profileWindow({ mode: "all-time" }, zone, now)).toBeNull();
+ expect(profileWindow({ mode: "past-minutes", pastMinutesStart: 60, pastMinutesEnd: 0 }, zone, now)).toBeNull();
+ expect(profileWindow({ mode: "day", day: "2026-10-05" }, zone, now)).toBeNull();
+ });
+});
diff --git a/client/src/app/[site]/user/[userId]/components/profileWindow.ts b/client/src/app/[site]/user/[userId]/components/profileWindow.ts
new file mode 100644
index 000000000..d662217f6
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/profileWindow.ts
@@ -0,0 +1,46 @@
+import { DateTime } from "luxon";
+import { Time } from "../../../../../components/DateSelector/types";
+import { getAbsoluteBounds } from "../../../../../lib/time";
+
+export interface ProfileWindow {
+ /** First day of the selected period, ISO date in the dashboard's timezone. */
+ start: string;
+ /** Last day of it that has begun: a period running into the future stops at today. */
+ end: string;
+ /** Days from `start` to `end`, both included. */
+ days: number;
+}
+
+/**
+ * The selected period as whole days, for "active days of N" and for marking
+ * the period on the activity calendar. Null where days are not the unit: all
+ * time has no bounds and a past-minutes window is shorter than a day's worth
+ * of meaning.
+ */
+export function profileWindow(time: Time, zone: string, now: DateTime = DateTime.now()): ProfileWindow | null {
+ if (time.mode === "past-minutes") return null;
+ const bounds = getAbsoluteBounds(time, zone);
+ if (!bounds) return null;
+
+ const today = now.setZone(zone).startOf("day");
+ const first = bounds.start.startOf("day");
+ // The end bound is exclusive: the last day covered is the one its final instant falls in.
+ const lastCovered = bounds.end.minus({ milliseconds: 1 }).startOf("day");
+ const last = lastCovered > today ? today : lastCovered;
+ if (last < first) return null;
+
+ const start = first.toISODate();
+ const end = last.toISODate();
+ if (!start || !end) return null;
+
+ return { start, end, days: Math.round(last.diff(first, "days").days) + 1 };
+}
+
+/**
+ * The shared window label prints both ends even when they are the same day
+ * ("Sep 30 – Sep 30", or "Sep 30 – Sep 30, 2025"). On the profile that reads
+ * as a range, so a one-day window names its day once.
+ */
+export function singleDayLabel(label: string | null): string | null {
+ return label ? label.replace(/^(.+) – \1(, \d{4})?$/, "$1$2") : label;
+}
diff --git a/client/src/app/[site]/user/[userId]/components/sessionGroups.test.ts b/client/src/app/[site]/user/[userId]/components/sessionGroups.test.ts
new file mode 100644
index 000000000..6ea1d3b1d
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/sessionGroups.test.ts
@@ -0,0 +1,86 @@
+import { DateTime } from "luxon";
+import { describe, expect, it } from "vitest";
+import { GetSessionsResponse } from "../../../../../api/analytics/endpoints";
+import { formatGroupDuration, groupSessions, relativeDay } from "./sessionGroups";
+
+const session = (id: string, start: string, duration: number, pageviews: number) =>
+ ({ session_id: id, session_start: start, session_duration: duration, pageviews }) as GetSessionsResponse[number];
+
+// Newest first, as the endpoint returns them. Times are UTC.
+const sessions = [
+ session("a", "2026-09-30 12:32:08", 742, 11),
+ session("b", "2026-09-30 07:14:00", 223, 4),
+ // 22:30 UTC on the 29th is 00:30 on the 30th in Stockholm (UTC+2).
+ session("c", "2026-09-29 22:30:00", 60, 2),
+ session("d", "2026-09-29 14:05:00", 490, 7),
+ session("e", "2026-09-25 11:58:00", 567, 9),
+];
+
+describe("groupSessions", () => {
+ it("groups by the day a session started, in the dashboard's timezone", () => {
+ const groups = groupSessions(sessions, "Europe/Stockholm", "day");
+
+ expect(groups.map(group => [group.key, group.sessions.map(s => s.session_id)])).toEqual([
+ ["2026-09-30", ["a", "b", "c"]],
+ ["2026-09-29", ["d"]],
+ ["2026-09-25", ["e"]],
+ ]);
+ });
+
+ it("puts the same sessions on different days in a different timezone", () => {
+ const groups = groupSessions(sessions, "UTC", "day");
+
+ expect(groups.map(group => [group.key, group.sessions.length])).toEqual([
+ ["2026-09-30", 2],
+ ["2026-09-29", 2],
+ ["2026-09-25", 1],
+ ]);
+ });
+
+ it("totals the sessions it lists", () => {
+ const [today] = groupSessions(sessions, "UTC", "day");
+
+ expect(today.duration).toBe(965);
+ expect(today.pageviews).toBe(15);
+ });
+
+ it("groups by ISO week, keyed by its Monday", () => {
+ const groups = groupSessions(sessions, "UTC", "week");
+
+ expect(groups.map(group => [group.key, group.sessions.length])).toEqual([
+ ["2026-09-28", 4],
+ ["2026-09-21", 1],
+ ]);
+ });
+
+ it("has no groups for an empty page", () => {
+ expect(groupSessions([], "UTC", "day")).toEqual([]);
+ });
+});
+
+describe("formatGroupDuration", () => {
+ it("stays in minutes and seconds under an hour", () => {
+ expect(formatGroupDuration(45)).toBe("45s");
+ expect(formatGroupDuration(965)).toBe("16m 5s");
+ expect(formatGroupDuration(600)).toBe("10m");
+ });
+
+ it("switches to hours and minutes past the hour", () => {
+ expect(formatGroupDuration(4757)).toBe("1h 19m");
+ expect(formatGroupDuration(7200)).toBe("2h");
+ });
+
+ it("is zero seconds for nothing", () => {
+ expect(formatGroupDuration(0)).toBe("0s");
+ });
+});
+
+describe("relativeDay", () => {
+ const now = DateTime.fromISO("2026-09-30T09:00:00", { zone: "utc" });
+
+ it("names today and yesterday and nothing else", () => {
+ expect(relativeDay("2026-09-30", now)).toBe("today");
+ expect(relativeDay("2026-09-29", now)).toBe("yesterday");
+ expect(relativeDay("2026-09-28", now)).toBeNull();
+ });
+});
diff --git a/client/src/app/[site]/user/[userId]/components/sessionGroups.ts b/client/src/app/[site]/user/[userId]/components/sessionGroups.ts
new file mode 100644
index 000000000..b34db3573
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/sessionGroups.ts
@@ -0,0 +1,68 @@
+import { DateTime } from "luxon";
+import { GetSessionsResponse } from "../../../../../api/analytics/endpoints";
+
+export type SessionBreakdown = "day" | "week" | "none";
+
+type Session = GetSessionsResponse[number];
+
+export interface SessionGroup {
+ /** ISO date of the day, or of the Monday that opens the week. */
+ key: string;
+ sessions: Session[];
+ /** Seconds, summed over the listed sessions. */
+ duration: number;
+ pageviews: number;
+}
+
+const sessionStart = (session: Session, zone: string) =>
+ DateTime.fromSQL(session.session_start, { zone: "utc" }).setZone(zone);
+
+/**
+ * Splits one page of the session list into runs that started on the same day
+ * (or in the same week) in `zone`. The list arrives newest first and the order
+ * is kept, so a group is always a contiguous run. Totals cover the sessions
+ * listed, not the whole day: a day that continues on the next page shows what
+ * this page holds of it.
+ */
+export function groupSessions(
+ sessions: Session[],
+ zone: string,
+ breakdown: Exclude<SessionBreakdown, "none">
+): SessionGroup[] {
+ const groups: SessionGroup[] = [];
+
+ for (const session of sessions) {
+ const start = sessionStart(session, zone);
+ const key = (breakdown === "week" ? start.startOf("week") : start).toISODate() ?? "";
+ const current = groups[groups.length - 1];
+ const group =
+ current?.key === key ? current : groups[groups.push({ key, sessions: [], duration: 0, pageviews: 0 }) - 1];
+
+ group.sessions.push(session);
+ group.duration += Math.max(0, session.session_duration ?? 0);
+ group.pageviews += session.pageviews ?? 0;
+ }
+
+ return groups;
+}
+
+/**
+ * A group's total time. A day or a week of sessions adds up past the hour, and
+ * "79m 17s" is harder to read than "1h 19m".
+ */
+export function formatGroupDuration(seconds: number): string {
+ const whole = Math.max(0, Math.round(seconds));
+ const hours = Math.floor(whole / 3600);
+ const minutes = Math.floor((whole % 3600) / 60);
+ if (hours > 0) return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
+ const rest = whole % 60;
+ if (minutes > 0) return rest > 0 ? `${minutes}m ${rest}s` : `${minutes}m`;
+ return `${rest}s`;
+}
+
+/** "today", "yesterday", or null: which fixed name a day has relative to `now`. */
+export function relativeDay(isoDate: string, now: DateTime): "today" | "yesterday" | null {
+ if (isoDate === now.toISODate()) return "today";
+ if (isoDate === now.minus({ days: 1 }).toISODate()) return "yesterday";
+ return null;
+}
diff --git a/client/src/app/[site]/user/[userId]/components/userTraits.test.ts b/client/src/app/[site]/user/[userId]/components/userTraits.test.ts
new file mode 100644
index 000000000..19bb9ded5
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/userTraits.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "vitest";
+import { customTraits, headlineTraits, traitLabel, traitText } from "./userTraits";
+
+const traits = {
+ name: "Mara Lindqvist",
+ email: "[email protected]",
+ plan: "Pro",
+ company: "Northpine",
+ seats: 12,
+ beta: true,
+ notes: "x".repeat(60),
+ address: { city: "Stockholm" },
+ empty: "",
+ role: "Founder",
+};
+
+describe("customTraits", () => {
+ it("leaves out the traits the header already shows as identity", () => {
+ expect(customTraits(traits).map(([key]) => key)).toEqual([
+ "plan",
+ "company",
+ "seats",
+ "beta",
+ "notes",
+ "address",
+ "empty",
+ "role",
+ ]);
+ });
+
+ it("is empty without traits", () => {
+ expect(customTraits(null)).toEqual([]);
+ expect(customTraits(undefined)).toEqual([]);
+ });
+});
+
+describe("headlineTraits", () => {
+ it("takes the first few short scalar traits", () => {
+ expect(headlineTraits(traits)).toEqual([
+ ["plan", "Pro"],
+ ["company", "Northpine"],
+ ["seats", 12],
+ ]);
+ });
+
+ it("skips long, empty and structured values", () => {
+ expect(headlineTraits(traits, 10).map(([key]) => key)).toEqual(["plan", "company", "seats", "beta", "role"]);
+ });
+});
+
+describe("trait text", () => {
+ it("labels a key in words", () => {
+ expect(traitLabel("signup_plan")).toBe("signup plan");
+ });
+
+ it("prints structured values as JSON and nothing for null", () => {
+ expect(traitText({ city: "Stockholm" })).toBe('{"city":"Stockholm"}');
+ expect(traitText(false)).toBe("false");
+ expect(traitText(null)).toBe("");
+ });
+});
diff --git a/client/src/app/[site]/user/[userId]/components/userTraits.ts b/client/src/app/[site]/user/[userId]/components/userTraits.ts
new file mode 100644
index 000000000..a05a9dc46
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/userTraits.ts
@@ -0,0 +1,35 @@
+// Traits the profile already shows as the user's name and email.
+const IDENTITY_TRAITS = ["username", "name", "email"];
+
+// A header chip is one glance: longer values stay in the rail.
+const MAX_CHIP_VALUE_LENGTH = 32;
+
+export type TraitEntry = [key: string, value: unknown];
+
+/** Every trait except the identity ones, in stored order. */
+export function customTraits(traits: Record<string, unknown> | null | undefined): TraitEntry[] {
+ return traits ? Object.entries(traits).filter(([key]) => !IDENTITY_TRAITS.includes(key)) : [];
+}
+
+/** "signup_plan" reads as "signup plan"; the row capitalises it. */
+export const traitLabel = (key: string) => key.replace(/_/g, " ");
+
+/** A trait value as text. Objects and arrays are shown as JSON rather than "[object Object]". */
+export function traitText(value: unknown): string {
+ if (value === null || value === undefined) return "";
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
+}
+
+/**
+ * The few traits worth repeating beside the name: the first `max` that are a
+ * short, non-empty string, number or boolean.
+ */
+export function headlineTraits(traits: Record<string, unknown> | null | undefined, max = 3): TraitEntry[] {
+ return customTraits(traits)
+ .filter(([, value]) => {
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") return false;
+ const text = String(value).trim();
+ return text.length > 0 && text.length <= MAX_CHIP_VALUE_LENGTH;
+ })
+ .slice(0, max);
+}
diff --git a/client/src/app/[site]/user/[userId]/components/usersListPosition.test.ts b/client/src/app/[site]/user/[userId]/components/usersListPosition.test.ts
new file mode 100644
index 000000000..ced5d5bf9
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/usersListPosition.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from "vitest";
+import { UsersListResponse, UsersResponse } from "../../../../../api/analytics/endpoints";
+import { CachedUsersList, findUsersListPosition } from "./usersListPosition";
+
+const row = (userId: string, identifiedUserId = "") =>
+ ({ user_id: userId, identified_user_id: identifiedUserId }) as UsersResponse;
+
+const list = (
+ rows: UsersResponse[],
+ params: Record<string, unknown>,
+ updatedAt: number,
+ totalCount = 4870
+): CachedUsersList => ({
+ data: {
+ data: rows,
+ totalCount,
+ page: Number(params.page ?? 1),
+ pageSize: Number(params.page_size ?? 50),
+ } as UsersListResponse,
+ params,
+ updatedAt,
+});
+
+describe("findUsersListPosition", () => {
+ const firstPage = list([row("fp1", "mara"), row("fp2"), row("fp3", "elias")], { page: 1, page_size: 50 }, 100);
+
+ it("finds an identified user by the id the list links them with", () => {
+ expect(findUsersListPosition([firstPage], ["mara"])).toEqual({
+ list: firstPage,
+ position: 1,
+ total: 4870,
+ identifiedOnly: false,
+ previousId: null,
+ nextId: "fp2",
+ });
+ });
+
+ it("finds an anonymous visitor by fingerprint and names both neighbours", () => {
+ expect(findUsersListPosition([firstPage], ["fp2"])).toMatchObject({
+ position: 2,
+ previousId: "mara",
+ nextId: "elias",
+ });
+ });
+
+ it("matches a profile opened by fingerprint after the device was identified", () => {
+ // The route still carries the fingerprint; the resolved identity is tried too.
+ expect(findUsersListPosition([firstPage], ["fp3", "elias"])?.position).toBe(3);
+ });
+
+ it("counts from the start of the list on a later page and stops at the page's edges", () => {
+ const thirdPage = list([row("a"), row("b")], { page: 3, page_size: 50, identified_only: true }, 100);
+
+ expect(findUsersListPosition([thirdPage], ["b"])).toEqual({
+ list: thirdPage,
+ position: 102,
+ total: 4870,
+ identifiedOnly: true,
+ previousId: "a",
+ nextId: null,
+ });
+ });
+
+ it("prefers the list fetched most recently", () => {
+ const older = list([row("x"), row("fp2")], { page: 1, page_size: 50 }, 50);
+
+ expect(findUsersListPosition([older, firstPage], ["fp2"])?.previousId).toBe("mara");
+ expect(findUsersListPosition([firstPage, older], ["fp2"])?.previousId).toBe("mara");
+ });
+
+ it("does not mistake an identified user for the anonymous visitor behind the same fingerprint", () => {
+ const shared = list([row("fp9", "bob"), row("fp9")], { page: 1, page_size: 50 }, 100);
+
+ expect(findUsersListPosition([shared], ["fp9"])?.position).toBe(2);
+ });
+
+ it("has no position for a profile that is in no fetched list", () => {
+ expect(findUsersListPosition([firstPage], ["stranger"])).toBeNull();
+ expect(findUsersListPosition([], ["mara"])).toBeNull();
+ expect(findUsersListPosition([{ data: undefined, params: undefined, updatedAt: 1 }], ["mara"])).toBeNull();
+ expect(findUsersListPosition([firstPage], [""])).toBeNull();
+ });
+});
diff --git a/client/src/app/[site]/user/[userId]/components/usersListPosition.ts b/client/src/app/[site]/user/[userId]/components/usersListPosition.ts
new file mode 100644
index 000000000..5a0af5d34
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/usersListPosition.ts
@@ -0,0 +1,70 @@
+import { UsersListResponse, UsersResponse } from "../../../../../api/analytics/endpoints";
+
+/** One cached page of the Users list: what the list query returned and what it was asked. */
+export interface CachedUsersList {
+ data: UsersListResponse | undefined;
+ /** The wire params of the request: `page`, `page_size`, `identified_only`, … */
+ params: Record<string, unknown> | undefined;
+ /** When the page was fetched. The most recent list is the one the visitor came from. */
+ updatedAt: number;
+}
+
+export interface UsersListPosition {
+ /** 1-based position in the whole list, across pages. */
+ position: number;
+ total: number;
+ identifiedOnly: boolean;
+ /** Route ids of the neighbours on the same page of the list; null at its edges. */
+ previousId: string | null;
+ nextId: string | null;
+}
+
+// The id the Users list links a row by: the identified id when there is one.
+export const userRouteId = (user: Pick<UsersResponse, "user_id" | "identified_user_id">) =>
+ user.identified_user_id || user.user_id;
+
+const toNumber = (value: unknown, fallback: number) => {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
+};
+
+/**
+ * Where a profile sits in the Users list the visitor last looked at, and who
+ * is next to it. Reads only pages already fetched: the newest cached page that
+ * contains the user wins, and a profile opened from anywhere else has no
+ * position. Neighbours stop at the edges of that page rather than fetching the
+ * next one.
+ */
+export function findUsersListPosition<T extends CachedUsersList>(
+ lists: T[],
+ userIds: string[]
+): (UsersListPosition & { list: T }) | null {
+ const ids = new Set(userIds.filter(Boolean));
+ if (ids.size === 0) return null;
+
+ const newestFirst = [...lists].sort((a, b) => b.updatedAt - a.updatedAt);
+ for (const list of newestFirst) {
+ const { data, params } = list;
+ if (!data?.data?.length) continue;
+ const rows = data.data;
+
+ // Matched on the id the list links by, never on the bare fingerprint: one
+ // fingerprint can sit under several identified rows.
+ const index = rows.findIndex(row => ids.has(userRouteId(row)));
+ if (index === -1) continue;
+
+ const page = toNumber(params?.page ?? data.page, 1);
+ const pageSize = toNumber(params?.page_size ?? data.pageSize, rows.length);
+
+ return {
+ list,
+ position: (page - 1) * pageSize + index + 1,
+ total: Math.max(data.totalCount ?? 0, (page - 1) * pageSize + rows.length),
+ identifiedOnly: params?.identified_only === true || params?.identified_only === "true",
+ previousId: index > 0 ? userRouteId(rows[index - 1]) : null,
+ nextId: index < rows.length - 1 ? userRouteId(rows[index + 1]) : null,
+ };
+ }
+
+ return null;
+}
diff --git a/client/src/app/[site]/user/[userId]/page.tsx b/client/src/app/[site]/user/[userId]/page.tsx
index b59e52092..d1660591a 100644
--- a/client/src/app/[site]/user/[userId]/page.tsx
+++ b/client/src/app/[site]/user/[userId]/page.tsx
@@ -1,14 +1,16 @@
"use client";
import { useExtracted } from "next-intl";
-import { SessionsList } from "@/components/Sessions/SessionsList";
import { ChevronLeft, ChevronRight } from "lucide-react";
import Link from "next/link";
import { useParams } from "next/navigation";
-import { useRef, useState } from "react";
+import { useState } from "react";
import { useUserInfo } from "../../../../api/analytics/hooks/userGetInfo";
import { useGetSessions, useGetUserSessionCount } from "../../../../api/analytics/hooks/useGetUserSessions";
+import { useUserSummary } from "../../../../api/analytics/hooks/useUserProfile";
import { DateSelector } from "../../../../components/DateSelector/DateSelector";
+import { AnalysisBar } from "../../../../components/site/AnalysisBar";
+import { BreakdownControl } from "../../../../components/site/BreakdownControl";
import { Button } from "../../../../components/ui/button";
import { canGoBack, canGoForward, goBack, goForward, useStore } from "../../../../lib/store";
import { USER_DETAIL_PAGE_FILTERS } from "../../../../lib/filterGroups";
@@ -25,24 +27,27 @@ import {
import { useSetPageTitle } from "../../../../hooks/useSetPageTitle";
import { useGetRegionName } from "../../../../lib/geo";
import { MobileSidebar } from "../../components/Sidebar/MobileSidebar";
+import { ActivityCalendar } from "./components/ActivityCalendar";
+import { firstActiveDay } from "./components/calendarLayout";
+import { SessionBreakdown } from "./components/sessionGroups";
+import { UserErrorInsight } from "./components/UserErrorInsight";
+import { UserGoals } from "./components/UserGoals";
import { UserHeader } from "./components/UserHeader";
+import { SESSIONS_PAGE_SIZE, UserSessions } from "./components/UserSessions";
import { UserSidebar } from "./components/UserSidebar";
import { UserStatBand } from "./components/UserStatBand";
-import { Badge } from "../../../../components/ui/badge";
-import { Pagination } from "../../../../components/pagination";
+import { UserStepper } from "./components/UserStepper";
import { Skeleton } from "../../../../components/ui/skeleton";
import { generateName } from "../../../../components/Avatar";
-import { formatter, getUserDisplayName } from "../../../../lib/utils";
+import { getUserDisplayName } from "../../../../lib/utils";
import { UserJourneys } from "./components/UserJourneys";
import { UserTopPages } from "./components/UserTopPages";
-const LIMIT = 25;
-
export default function UserPage() {
const t = useExtracted();
const { userId: rawUserId, site } = useParams();
- const { time, setTime } = useStore();
+ const { time, setTime, privateKey } = useStore();
const userId = (() => {
const value = Array.isArray(rawUserId) ? rawUserId[0] : rawUserId;
if (!value) return "";
@@ -52,8 +57,11 @@ export default function UserPage() {
return value;
}
})();
- const [page, setPage] = useState(1);
- const sessionsRef = useRef<HTMLDivElement>(null);
+ const [breakdown, setBreakdown] = useState<SessionBreakdown>("day");
+ // The day picked on the activity calendar, remembered with the user it was
+ // picked for: stepping to another profile starts without one.
+ const [pickedDay, setPickedDay] = useState<{ userId: string; day: string } | null>(null);
+ const selectedDay = pickedDay?.userId === userId ? pickedDay.day : null;
const { data, isLoading } = useUserInfo(Number(site), userId);
// The route can still be a device fingerprint after that device has been
@@ -61,17 +69,31 @@ export default function UserPage() {
// has to query the identity it resolved to or they all come back empty. Anonymous
// visitors have no identified_user_id, so they keep querying the route id.
const queryUserId = data?.identified_user_id || userId;
- const { data: sessionCount, isLoading: isLoadingCalendar } = useGetUserSessionCount(queryUserId);
- const { data: sessionsData, isLoading: isLoadingSessions } = useGetSessions({
- userId: queryUserId,
- page: page,
- limit: LIMIT + 1,
+ const {
+ data: sessionCount,
+ isLoading: isLoadingCalendar,
+ error: calendarError,
+ refetch: refetchCalendar,
+ } = useGetUserSessionCount(queryUserId);
+ const { data: summary } = useUserSummary(queryUserId);
+
+ // The user's first day on the site, from the calendar's full history. Their
+ // profile for that one day is their first touch, whatever period is selected.
+ const dayCounts = (sessionCount ?? []).map(row => ({
+ date: String(row.date).slice(0, 10),
+ sessions: Number(row.sessions),
+ }));
+ const firstDay = firstActiveDay(dayCounts);
+ const firstTouchQuery = useUserInfo(Number(site), queryUserId, {
+ time: firstDay ? { mode: "day", day: firstDay } : undefined,
+ enabled: !!firstDay,
});
+ const firstTouch = firstDay ? firstTouchQuery.data : undefined;
- const allSessions = sessionsData || [];
- const hasNextPage = allSessions.length > LIMIT;
- const sessions = allSessions.slice(0, LIMIT);
- const hasPrevPage = page > 1;
+ // The first page of the period's sessions, newest first: the same request
+ // the session list makes for its first page, so it is answered from cache.
+ const { data: latestSessions } = useGetSessions({ userId: queryUserId, page: 1, limit: SESSIONS_PAGE_SIZE + 1 });
+ const latestReplaySessionId = latestSessions?.find(session => session.has_replay === 1)?.session_id;
const { getRegionName } = useGetRegionName();
@@ -81,111 +103,139 @@ export default function UserPage() {
useSetPageTitle(isLoading ? "User" : displayName);
- // Bottom pagination: restore context by jumping back to the top of the list
- const handleBottomPageChange = (nextPage: number) => {
- setPage(nextPage);
- sessionsRef.current?.scrollIntoView({ block: "start" });
- };
+ // What the session list holds in all: the day's sessions when one is picked
+ // on the calendar, otherwise the period's.
+ const totalSessions = selectedDay
+ ? dayCounts.find(day => day.date === selectedDay)?.sessions
+ : (summary?.sessions ?? data?.sessions);
+
+ const usersHref = privateKey ? `/${site}/${privateKey}/users` : `/${site}/users`;
return (
- <div className="p-2 md:p-4 max-w-[1200px] mx-auto">
- <Breadcrumb className="min-w-0">
- <BreadcrumbList className="flex-nowrap">
- <BreadcrumbItem>
- <BreadcrumbLink asChild>
- <Link href={`/${site}/users`}>{t("Users")}</Link>
- </BreadcrumbLink>
- </BreadcrumbItem>
- <BreadcrumbSeparator />
- <BreadcrumbItem className="min-w-0">
- <BreadcrumbPage className="truncate">
- {isLoading ? <Skeleton className="h-4 w-28 rounded" /> : displayName}
- </BreadcrumbPage>
- </BreadcrumbItem>
- </BreadcrumbList>
- </Breadcrumb>
+ <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
+ <div className="flex items-center justify-between gap-3">
+ <Breadcrumb className="min-w-0">
+ <BreadcrumbList className="flex-nowrap">
+ <BreadcrumbItem>
+ <BreadcrumbLink asChild>
+ <Link href={usersHref}>{t("Users")}</Link>
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ <BreadcrumbSeparator />
+ <BreadcrumbItem className="min-w-0">
+ <BreadcrumbPage className="truncate">
+ {isLoading ? <Skeleton className="h-4 w-28 rounded" /> : displayName}
+ </BreadcrumbPage>
+ </BreadcrumbItem>
+ </BreadcrumbList>
+ </Breadcrumb>
+ <UserStepper userIds={[userId, queryUserId]} />
+ </div>
{/* Toolbar */}
- <div className="flex items-center gap-2 mt-2">
- <MobileSidebar />
- <div className="hidden md:block">
+ <div>
+ <div className="flex items-center gap-2">
+ <MobileSidebar />
+ <div className="hidden md:block">
+ <NewFilterButton availableFilters={USER_DETAIL_PAGE_FILTERS} />
+ </div>
+ <div className="ml-auto flex items-center gap-2 shrink-0">
+ <DateSelector time={time} setTime={setTime} />
+ <div className="flex items-center">
+ <Button
+ variant="secondary"
+ size="icon"
+ onClick={goBack}
+ disabled={!canGoBack(time)}
+ className="rounded-r-none h-8 w-8"
+ >
+ <ChevronLeft />
+ </Button>
+ <Button
+ variant="secondary"
+ size="icon"
+ onClick={goForward}
+ disabled={!canGoForward(time)}
+ className="rounded-l-none -ml-px h-8 w-8"
+ >
+ <ChevronRight />
+ </Button>
+ </div>
+ </div>
+ </div>
+ <div className="md:hidden mt-2">
<NewFilterButton availableFilters={USER_DETAIL_PAGE_FILTERS} />
</div>
- <div className="ml-auto flex items-center gap-2 shrink-0">
- <DateSelector time={time} setTime={setTime} />
- <div className="flex items-center">
- <Button
- variant="secondary"
- size="icon"
- onClick={goBack}
- disabled={!canGoBack(time)}
- className="rounded-r-none h-8 w-8"
- >
- <ChevronLeft />
- </Button>
- <Button
- variant="secondary"
- size="icon"
- onClick={goForward}
- disabled={!canGoForward(time)}
- className="rounded-l-none -ml-px h-8 w-8"
- >
- <ChevronRight />
- </Button>
- </div>
+ {/* The chip row takes its gap only when it has chips. */}
+ <div className="[&>div:not(:empty)]:mt-2">
+ <Filters availableFilters={USER_DETAIL_PAGE_FILTERS} />
</div>
</div>
- <div className="md:hidden mt-2">
- <NewFilterButton availableFilters={USER_DETAIL_PAGE_FILTERS} />
- </div>
- <Filters availableFilters={USER_DETAIL_PAGE_FILTERS} />
-
- <UserHeader userId={userId} displayName={displayName} data={data} isLoading={isLoading} />
- <UserStatBand data={data} isLoading={isLoading} />
+ <UserHeader
+ userId={userId}
+ queryUserId={queryUserId}
+ displayName={displayName}
+ data={data}
+ isLoading={isLoading}
+ latestReplaySessionId={latestReplaySessionId}
+ />
+
+ <UserStatBand userId={queryUserId} />
+
+ <AnalysisBar
+ breakdown={
+ <BreakdownControl<SessionBreakdown>
+ value={breakdown}
+ onChange={setBreakdown}
+ options={[
+ { value: "day", label: t("Day") },
+ { value: "week", label: t("Week") },
+ { value: "none", label: t("None") },
+ ]}
+ />
+ }
+ />
+
+ <UserErrorInsight userId={queryUserId} />
{/* Main content leads in the DOM so activity comes first on mobile;
row-reverse puts the profile rail back on the left on desktop */}
- <div className="flex flex-col gap-4 lg:flex-row-reverse">
- <div className="flex-1 min-w-0 space-y-4">
- <UserTopPages userId={queryUserId} />
- <UserJourneys userId={queryUserId} />
- <div ref={sessionsRef} className="scroll-mt-4 space-y-3">
- <SessionsList
- sessions={sessions}
- isLoading={isLoadingSessions}
- page={page}
- onPageChange={setPage}
- hasNextPage={hasNextPage}
- hasPrevPage={hasPrevPage}
- userId={queryUserId}
- headerElement={
- <div className="flex items-center gap-2">
- <h2 className="text-sm font-medium text-neutral-700 dark:text-neutral-200">{t("Sessions")}</h2>
- {!isLoading && data?.sessions != null && (
- <Badge variant="secondary" className="tabular-nums" title={data.sessions.toLocaleString()}>
- {formatter(data.sessions)}
- </Badge>
- )}
- </div>
- }
+ <div className="flex flex-col gap-3 lg:flex-row-reverse">
+ {/* A container, so the cards inside pair up by the room this column
+ has rather than by the viewport: the rail and the app sidebar both
+ take from it. */}
+ <div className="@container flex-1 min-w-0 space-y-3">
+ <div className="grid grid-cols-1 gap-3 @3xl:grid-cols-[minmax(0,1fr)_322px]">
+ <ActivityCalendar
+ sessionCount={sessionCount ?? []}
+ isLoading={isLoadingCalendar}
+ error={calendarError}
+ refetch={() => void refetchCalendar()}
+ activeDays={summary?.active_days}
+ selectedDay={selectedDay}
+ onSelectDay={day => setPickedDay(day ? { userId, day } : null)}
/>
- {!isLoadingSessions && sessions.length >= 10 && (hasNextPage || hasPrevPage) && (
- <Pagination
- page={page}
- onPageChange={handleBottomPageChange}
- hasPreviousPage={hasPrevPage}
- hasNextPage={hasNextPage}
- />
- )}
+ <UserGoals userId={queryUserId} />
</div>
+ <UserTopPages userId={queryUserId} />
+ <UserJourneys userId={queryUserId} />
+ <UserSessions
+ key={JSON.stringify([queryUserId, selectedDay, time])}
+ userId={queryUserId}
+ breakdown={breakdown}
+ selectedDay={selectedDay}
+ onClearDay={() => setPickedDay(null)}
+ totalSessions={totalSessions}
+ />
</div>
<UserSidebar
+ userId={queryUserId}
data={data}
isLoading={isLoading}
- sessionCount={sessionCount ?? []}
- isLoadingCalendar={isLoadingCalendar}
+ firstTouch={firstTouch}
+ isLoadingFirstTouch={isLoadingCalendar || (!!firstDay && firstTouchQuery.isLoading)}
getRegionName={getRegionName}
/>
</div>
diff --git a/client/src/app/[site]/users/columns.test.ts b/client/src/app/[site]/users/columns.test.ts
new file mode 100644
index 000000000..13f605300
--- /dev/null
+++ b/client/src/app/[site]/users/columns.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from "vitest";
+import {
+ columnId,
+ DEFAULT_BUILT_IN,
+ defaultTraitColumns,
+ formatTraitValue,
+ parseColumnSelection,
+ tableMinWidth,
+ toggleBuiltIn,
+ toggleTrait,
+ USER_COLUMN_MIN_WIDTH,
+ visibleColumns,
+} from "./columns";
+
+describe("visibleColumns", () => {
+ it("puts traits first, then the built-in columns in table order whatever order they were chosen in", () => {
+ const columns = visibleColumns({ builtIn: ["device", "sessions", "last_seen"], traits: ["plan", "company"] });
+ expect(columns.map(columnId)).toEqual(["trait:plan", "trait:company", "last_seen", "sessions", "device"]);
+ });
+
+ it("is only as wide as the user column when nothing else is shown", () => {
+ expect(tableMinWidth(visibleColumns({ builtIn: [], traits: [] }))).toBe(USER_COLUMN_MIN_WIDTH);
+ });
+
+ it("fits the default columns and two traits in the page's desktop content width", () => {
+ // 1440px viewport, less the sidebar and the page padding.
+ expect(tableMinWidth(visibleColumns({ builtIn: DEFAULT_BUILT_IN, traits: ["a", "b"] }))).toBeLessThanOrEqual(1138);
+ });
+});
+
+describe("defaultTraitColumns", () => {
+ const key = (name: string, userCount: number) => ({ key: name, userCount });
+
+ it("takes the most common traits, skipping the ones the user cell already shows", () => {
+ const keys = [
+ key("email", 90),
+ key("Name", 90),
+ key("plan", 80),
+ key("username", 70),
+ key("company", 60),
+ key("role", 5),
+ ];
+ expect(defaultTraitColumns(keys)).toEqual(["plan", "company"]);
+ });
+
+ it("is empty for a site with no traits", () => {
+ expect(defaultTraitColumns([])).toEqual([]);
+ });
+});
+
+describe("toggling columns", () => {
+ const selection = { builtIn: DEFAULT_BUILT_IN, traits: ["plan"] };
+
+ it("adds and removes a built-in column without touching the traits", () => {
+ const added = toggleBuiltIn(selection, "first_seen");
+ expect(added.builtIn).toContain("first_seen");
+ expect(toggleBuiltIn(added, "first_seen")).toEqual(selection);
+ });
+
+ it("adds and removes a trait without touching the built-ins", () => {
+ expect(toggleTrait(selection, "role")).toEqual({ builtIn: DEFAULT_BUILT_IN, traits: ["plan", "role"] });
+ expect(toggleTrait(selection, "plan")).toEqual({ builtIn: DEFAULT_BUILT_IN, traits: [] });
+ });
+});
+
+describe("parseColumnSelection", () => {
+ it("reads back what was stored", () => {
+ const selection = { builtIn: ["sessions", "device"], traits: ["plan"] };
+ expect(parseColumnSelection(JSON.stringify(selection))).toEqual(selection);
+ });
+
+ it("drops columns this version does not have", () => {
+ expect(
+ parseColumnSelection(JSON.stringify({ builtIn: ["sessions", "bounce_rate", 7], traits: ["plan", null] }))
+ ).toEqual({ builtIn: ["sessions"], traits: ["plan"] });
+ });
+
+ it.each([null, "", "not json", "[]", "null", JSON.stringify({ builtIn: "sessions", traits: [] })])(
+ "falls back to the defaults for %j",
+ raw => {
+ expect(parseColumnSelection(raw)).toBeNull();
+ }
+ );
+});
+
+describe("formatTraitValue", () => {
+ it.each([
+ ["Pro", "Pro"],
+ [42, "42"],
+ [false, "false"],
+ [0, "0"],
+ [{ tier: 2 }, '{"tier":2}'],
+ [["a", "b"], '["a","b"]'],
+ ])("shows %j as %s", (value, expected) => {
+ expect(formatTraitValue(value)).toBe(expected);
+ });
+
+ it.each([null, undefined, ""])("has nothing to show for %j", value => {
+ expect(formatTraitValue(value)).toBeNull();
+ });
+});
diff --git a/client/src/app/[site]/users/columns.ts b/client/src/app/[site]/users/columns.ts
new file mode 100644
index 000000000..03fe7db73
--- /dev/null
+++ b/client/src/app/[site]/users/columns.ts
@@ -0,0 +1,132 @@
+import { TraitKey } from "@/api/analytics/endpoints";
+
+/** The table's own columns, in display order. The user column is always shown and comes first. */
+export const BUILT_IN_COLUMNS = [
+ "last_seen",
+ "first_seen",
+ "sessions",
+ "pageviews",
+ "events",
+ "source",
+ "location",
+ "device",
+] as const;
+
+export type BuiltInColumn = (typeof BUILT_IN_COLUMNS)[number];
+
+/** A built-in column, or a trait shown as a column. Trait columns sit between the user and the built-ins. */
+export type TableColumn = { kind: "trait"; key: string } | { kind: "builtIn"; id: BuiltInColumn };
+
+export interface ColumnSelection {
+ builtIn: BuiltInColumn[];
+ traits: string[];
+}
+
+export const DEFAULT_BUILT_IN: BuiltInColumn[] = [
+ "last_seen",
+ "sessions",
+ "pageviews",
+ "events",
+ "source",
+ "location",
+ "device",
+];
+
+/** Per-user counts: the columns a trait group averages. */
+export const METRIC_COLUMNS: readonly BuiltInColumn[] = ["sessions", "pageviews", "events"];
+
+/** The columns the server can sort by. */
+export const SORTABLE_COLUMNS: readonly BuiltInColumn[] = [
+ "last_seen",
+ "first_seen",
+ "sessions",
+ "pageviews",
+ "events",
+];
+
+// Sized so the default columns and two traits fit the page at its usual desktop width without scrolling.
+export const USER_COLUMN_MIN_WIDTH = 224;
+const TRAIT_COLUMN_WIDTH = 104;
+const COLUMN_WIDTHS: Record<BuiltInColumn, number> = {
+ // Wide enough for the absolute date the cell shows on hover.
+ last_seen: 128,
+ first_seen: 128,
+ sessions: 76,
+ pageviews: 84,
+ events: 68,
+ source: 140,
+ location: 124,
+ device: 84,
+};
+
+export const columnWidth = (column: TableColumn) =>
+ column.kind === "trait" ? TRAIT_COLUMN_WIDTH : COLUMN_WIDTHS[column.id];
+
+export const columnId = (column: TableColumn) => (column.kind === "trait" ? `trait:${column.key}` : column.id);
+
+/** The visible columns after the user column, in display order. */
+export function visibleColumns(selection: ColumnSelection): TableColumn[] {
+ return [
+ ...selection.traits.map(key => ({ kind: "trait" as const, key })),
+ ...BUILT_IN_COLUMNS.filter(id => selection.builtIn.includes(id)).map(id => ({ kind: "builtIn" as const, id })),
+ ];
+}
+
+/** The narrowest the table can be before it scrolls sideways. */
+export const tableMinWidth = (columns: TableColumn[]) =>
+ columns.reduce((total, column) => total + columnWidth(column), USER_COLUMN_MIN_WIDTH);
+
+// Already on every row: the name and the line under it.
+const IDENTITY_TRAITS = new Set(["username", "name", "email"]);
+const DEFAULT_TRAIT_COLUMNS = 2;
+
+/**
+ * Trait columns shown before the viewer has chosen any: the site's most common
+ * traits, which is the order the keys arrive in.
+ */
+export function defaultTraitColumns(keys: TraitKey[]): string[] {
+ return keys
+ .map(item => item.key)
+ .filter(key => !IDENTITY_TRAITS.has(key.toLowerCase()))
+ .slice(0, DEFAULT_TRAIT_COLUMNS);
+}
+
+export function toggleBuiltIn(selection: ColumnSelection, id: BuiltInColumn): ColumnSelection {
+ const builtIn = selection.builtIn.includes(id)
+ ? selection.builtIn.filter(candidate => candidate !== id)
+ : [...selection.builtIn, id];
+ return { ...selection, builtIn };
+}
+
+export function toggleTrait(selection: ColumnSelection, key: string): ColumnSelection {
+ const traits = selection.traits.includes(key)
+ ? selection.traits.filter(candidate => candidate !== key)
+ : [...selection.traits, key];
+ return { ...selection, traits };
+}
+
+const isBuiltIn = (value: unknown): value is BuiltInColumn =>
+ typeof value === "string" && (BUILT_IN_COLUMNS as readonly string[]).includes(value);
+
+/** A stored selection, or null when it is missing or not in the shape this version writes. */
+export function parseColumnSelection(raw: string | null): ColumnSelection | null {
+ if (!raw) return null;
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (typeof parsed !== "object" || parsed === null) return null;
+ const { builtIn, traits } = parsed as { builtIn?: unknown; traits?: unknown };
+ if (!Array.isArray(builtIn) || !Array.isArray(traits)) return null;
+ return {
+ builtIn: builtIn.filter(isBuiltIn),
+ traits: traits.filter((key): key is string => typeof key === "string"),
+ };
+ } catch {
+ return null;
+ }
+}
+
+/** How a trait value reads in a cell. Null when there is nothing to show. */
+export function formatTraitValue(value: unknown): string | null {
+ if (value === null || value === undefined || value === "") return null;
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
+}
diff --git a/client/src/app/[site]/users/components/ColumnPicker.tsx b/client/src/app/[site]/users/components/ColumnPicker.tsx
new file mode 100644
index 000000000..35d497ae5
--- /dev/null
+++ b/client/src/app/[site]/users/components/ColumnPicker.tsx
@@ -0,0 +1,80 @@
+"use client";
+
+import { Columns3, Tags } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { BUILT_IN_COLUMNS, BuiltInColumn, ColumnSelection, toggleBuiltIn, toggleTrait } from "../columns";
+
+// Toggling a column keeps the menu open, so several can be set in one visit.
+const keepOpen = (event: Event) => event.preventDefault();
+
+/** Chooses the table's columns: its own, and any of the site's traits. */
+export function ColumnPicker({
+ selection,
+ onChange,
+ traitKeys,
+ columnLabels,
+}: {
+ selection: ColumnSelection;
+ onChange: (selection: ColumnSelection) => void;
+ /** Every trait key the site has, most common first. */
+ traitKeys: string[];
+ columnLabels: Record<BuiltInColumn, string>;
+}) {
+ const t = useExtracted();
+ // A chosen trait stays listed even if no profile carries it any more, so it can be turned off.
+ const traits = [...traitKeys, ...selection.traits.filter(key => !traitKeys.includes(key))];
+ const count = selection.builtIn.length + selection.traits.length;
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button type="button" size="sm" className="gap-1.5">
+ <Columns3 />
+ {t("Columns")}
+ <span className="tabular-nums text-neutral-500 dark:text-neutral-400">{count}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="max-h-[min(28rem,70vh)] w-56 overflow-y-auto">
+ <DropdownMenuLabel>{t("Columns")}</DropdownMenuLabel>
+ {BUILT_IN_COLUMNS.map(id => (
+ <DropdownMenuCheckboxItem
+ key={id}
+ checked={selection.builtIn.includes(id)}
+ onCheckedChange={() => onChange(toggleBuiltIn(selection, id))}
+ onSelect={keepOpen}
+ >
+ {columnLabels[id]}
+ </DropdownMenuCheckboxItem>
+ ))}
+ {traits.length > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel className="flex items-center gap-1.5">
+ <Tags className="h-3.5 w-3.5" />
+ {t("Traits")}
+ </DropdownMenuLabel>
+ {traits.map(key => (
+ <DropdownMenuCheckboxItem
+ key={key}
+ checked={selection.traits.includes(key)}
+ onCheckedChange={() => onChange(toggleTrait(selection, key))}
+ onSelect={keepOpen}
+ >
+ <span className="truncate">{key}</span>
+ </DropdownMenuCheckboxItem>
+ ))}
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/client/src/app/[site]/users/components/QuickFilters.tsx b/client/src/app/[site]/users/components/QuickFilters.tsx
new file mode 100644
index 000000000..2123434b6
--- /dev/null
+++ b/client/src/app/[site]/users/components/QuickFilters.tsx
@@ -0,0 +1,103 @@
+"use client";
+
+import { useExtracted } from "next-intl";
+import { UsersSummary } from "@/api/analytics/endpoints";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+export interface QuickFilterState {
+ identified: boolean;
+ isNew: boolean;
+ power: boolean;
+}
+
+export const NO_QUICK_FILTERS: QuickFilterState = { identified: false, isNew: false, power: false };
+
+function Chip({
+ label,
+ count,
+ pressed,
+ title,
+ disabled,
+ onToggle,
+}: {
+ label: string;
+ count: number | undefined;
+ pressed: boolean;
+ title?: string;
+ disabled?: boolean;
+ onToggle: () => void;
+}) {
+ return (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-pressed={pressed}
+ title={title}
+ disabled={disabled}
+ className={cn(
+ "gap-1.5 font-normal",
+ pressed &&
+ "border-neutral-300 bg-neutral-100 text-neutral-900 hover:bg-neutral-100 dark:border-neutral-500 dark:bg-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-800"
+ )}
+ onClick={onToggle}
+ >
+ {label}
+ {count !== undefined && (
+ <span className="tabular-nums text-neutral-500 dark:text-neutral-400">{count.toLocaleString()}</span>
+ )}
+ </Button>
+ );
+}
+
+/**
+ * One-click cohorts for the table. Each count is the stat band's figure for
+ * the same period and filters, so a chip never promises more than it lists.
+ */
+export function QuickFilters({
+ value,
+ onChange,
+ summary,
+}: {
+ value: QuickFilterState;
+ onChange: (value: QuickFilterState) => void;
+ summary: UsersSummary | undefined;
+}) {
+ const t = useExtracted();
+ const days = String(summary?.lookback_days ?? 0);
+
+ return (
+ <>
+ <Chip
+ label={t("Identified")}
+ count={summary?.identified_users}
+ pressed={value.identified}
+ onToggle={() => onChange({ ...value, identified: !value.identified })}
+ />
+ {/* An all-time period has no "before" for anyone to be new against. */}
+ {summary?.new_users !== null && (
+ <Chip
+ label={t("New")}
+ count={summary?.new_users ?? undefined}
+ pressed={value.isNew}
+ title={t("Users with no visit in the {days} days before this period", { days })}
+ disabled={!summary}
+ onToggle={() => onChange({ ...value, isNew: !value.isNew })}
+ />
+ )}
+ <Chip
+ label={t("Power users")}
+ count={summary?.power_users}
+ pressed={value.power}
+ title={
+ summary
+ ? t("Users with {count} or more sessions in this period", { count: String(summary.power_min_sessions) })
+ : undefined
+ }
+ disabled={!summary}
+ onToggle={() => onChange({ ...value, power: !value.power })}
+ />
+ </>
+ );
+}
diff --git a/client/src/app/[site]/users/components/TraitGroupRows.test.tsx b/client/src/app/[site]/users/components/TraitGroupRows.test.tsx
new file mode 100644
index 000000000..09c9fc754
--- /dev/null
+++ b/client/src/app/[site]/users/components/TraitGroupRows.test.tsx
@@ -0,0 +1,197 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { UsersResponse } from "@/api/analytics/endpoints";
+import { ColumnSelection, visibleColumns } from "../columns";
+import { TraitGroupRows, TraitGroupView } from "./TraitGroupRows";
+
+const mocks = vi.hoisted(() => ({
+ useGetUsersInfinite: vi.fn(),
+ fetchNextPage: vi.fn(),
+}));
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => (message: string, values?: Record<string, string>) =>
+ Object.entries(values ?? {}).reduce((text, [key, value]) => text.replace(`{${key}}`, value), message),
+}));
+
+vi.mock("@/api/analytics/hooks/useGetUsers", () => ({
+ useGetUsersInfinite: mocks.useGetUsersInfinite,
+}));
+
+vi.mock("./UserRow", () => ({
+ UserRow: ({ user, indented }: { user: UsersResponse; indented?: boolean }) => (
+ <tr data-testid="user-row" data-indented={String(!!indented)}>
+ <td>{user.identified_user_id}</td>
+ </tr>
+ ),
+}));
+
+const user = (id: string) => ({ identified_user_id: id, user_id: `device-${id}` }) as UsersResponse;
+
+const group: TraitGroupView = {
+ id: "value:Pro",
+ label: "Pro",
+ name: "Pro",
+ stats: { users: 640, sessions: 9472, pageviews: 39168, events: 11008 },
+ previousUsers: 570,
+ shareLabel: "13.1% of identified",
+ bar: 0.4,
+ selector: { key: "plan", value: "Pro" },
+};
+
+const everything: ColumnSelection = {
+ builtIn: ["last_seen", "sessions", "pageviews", "events", "source", "location", "device"],
+ traits: ["company", "role"],
+};
+
+function renderGroup({
+ view = group,
+ open = false,
+ selection = everything,
+ onToggle = () => {},
+}: {
+ view?: TraitGroupView;
+ open?: boolean;
+ selection?: ColumnSelection;
+ onToggle?: () => void;
+} = {}) {
+ return render(
+ <table>
+ <tbody>
+ <TraitGroupRows
+ group={view}
+ open={open}
+ onToggle={onToggle}
+ columns={visibleColumns(selection)}
+ narrowing={{ identifiedOnly: true, search: "ma", searchField: "name" }}
+ sortBy="sessions"
+ sortOrder="desc"
+ site="1"
+ privateKey={null}
+ />
+ </tbody>
+ </table>
+ );
+}
+
+const summaryCells = () => [...document.querySelectorAll("tr")[0].querySelectorAll("td")];
+
+beforeEach(() => {
+ mocks.fetchNextPage.mockClear();
+ mocks.useGetUsersInfinite.mockReset();
+ mocks.useGetUsersInfinite.mockReturnValue({
+ data: { pages: [{ data: [user("a"), user("b")], totalCount: 640 }] },
+ isError: false,
+ hasNextPage: true,
+ isFetchingNextPage: false,
+ fetchNextPage: mocks.fetchNextPage,
+ });
+});
+afterEach(cleanup);
+
+describe("TraitGroupRows", () => {
+ it("summarises the group: users, change, share and per-user averages", () => {
+ renderGroup();
+
+ expect(screen.getByText("640 users")).toBeTruthy();
+ expect(screen.getByText("+12.3%")).toBeTruthy();
+ expect(screen.getByText("13.1% of identified")).toBeTruthy();
+ // 9,472 / 640, 39,168 / 640, 11,008 / 640
+ expect(
+ summaryCells()
+ .slice(1, 4)
+ .map(cell => cell.textContent)
+ ).toEqual(["14.8", "61.2", "17.2"]);
+ });
+
+ it("lines the averages up under the count columns", () => {
+ renderGroup();
+
+ // User, two traits and Last seen before the counts; source, location and device after.
+ expect(summaryCells().map(cell => cell.colSpan)).toEqual([4, 1, 1, 1, 3]);
+ });
+
+ it("follows the chosen columns", () => {
+ renderGroup({ selection: { builtIn: ["pageviews", "device"], traits: [] } });
+ expect(summaryCells().map(cell => cell.colSpan)).toEqual([1, 1, 1]);
+ expect(summaryCells()[1].textContent).toBe("61.2");
+ cleanup();
+
+ renderGroup({ selection: { builtIn: ["last_seen", "device"], traits: ["company"] } });
+ expect(summaryCells().map(cell => cell.colSpan)).toEqual([4]);
+ expect(screen.queryByText("Avg / user")).toBeNull();
+ });
+
+ it("asks for nobody while closed", () => {
+ const onToggle = vi.fn();
+ renderGroup({ onToggle });
+
+ expect(mocks.useGetUsersInfinite).not.toHaveBeenCalled();
+ expect(screen.queryAllByTestId("user-row")).toHaveLength(0);
+
+ fireEvent.click(screen.getByRole("button", { name: "Expand Pro" }));
+ expect(onToggle).toHaveBeenCalledOnce();
+ });
+
+ it("lists the group's users with the table's narrowing and sort when open", () => {
+ renderGroup({ open: true });
+
+ expect(mocks.useGetUsersInfinite).toHaveBeenCalledWith({
+ identifiedOnly: true,
+ search: "ma",
+ searchField: "name",
+ traitGroup: { key: "plan", value: "Pro" },
+ pageSize: 10,
+ sortBy: "sessions",
+ sortOrder: "desc",
+ });
+ const rows = screen.getAllByTestId("user-row");
+ expect(rows).toHaveLength(2);
+ expect(rows.every(row => row.dataset.indented === "true")).toBe(true);
+ expect(screen.getByRole("button", { name: "Collapse Pro" }).getAttribute("aria-expanded")).toBe("true");
+ });
+
+ it("loads the next page on demand and says how many are left", () => {
+ renderGroup({ open: true });
+
+ expect(screen.getByText("638 left")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Show 10 more" }));
+ expect(mocks.fetchNextPage).toHaveBeenCalledOnce();
+ });
+
+ it("offers only what is left on the last page", () => {
+ mocks.useGetUsersInfinite.mockReturnValue({
+ data: { pages: [{ data: [user("a"), user("b")], totalCount: 5 }] },
+ isError: false,
+ hasNextPage: true,
+ isFetchingNextPage: false,
+ fetchNextPage: mocks.fetchNextPage,
+ });
+ renderGroup({ open: true });
+
+ expect(screen.getByRole("button", { name: "Show 3 more" })).toBeTruthy();
+ expect(screen.queryByText("3 left")).toBeNull();
+ });
+
+ it("says so when the group's users fail to load", () => {
+ mocks.useGetUsersInfinite.mockReturnValue({ data: undefined, isError: true, hasNextPage: false });
+ renderGroup({ open: true });
+
+ expect(screen.getByText("Could not load these users. Try again in a moment.")).toBeTruthy();
+ });
+
+ it("cannot be opened when it has no list to show", () => {
+ renderGroup({
+ view: { ...group, id: "other", label: "12 other values", name: "12 other values", selector: null },
+ open: true,
+ });
+
+ expect(screen.queryByRole("button")).toBeNull();
+ expect(mocks.useGetUsersInfinite).not.toHaveBeenCalled();
+ });
+
+ it("draws no change without a comparison", () => {
+ renderGroup({ view: { ...group, previousUsers: undefined } });
+ expect(screen.queryByText(/%$/)).toBeNull();
+ });
+});
diff --git a/client/src/app/[site]/users/components/TraitGroupRows.tsx b/client/src/app/[site]/users/components/TraitGroupRows.tsx
new file mode 100644
index 000000000..d1d6cc881
--- /dev/null
+++ b/client/src/app/[site]/users/components/TraitGroupRows.tsx
@@ -0,0 +1,244 @@
+"use client";
+
+import { ChevronDown, ChevronRight } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { ReactNode } from "react";
+import { TraitGroupStats } from "@/api/analytics/endpoints";
+import { TraitGroupSelector, useGetUsersInfinite, UsersNarrowing } from "@/api/analytics/hooks/useGetUsers";
+import { Delta } from "@/components/site/Delta";
+import { Skeleton } from "@/components/ui/skeleton";
+import { percentDelta } from "@/lib/delta";
+import { BuiltInColumn, columnId, METRIC_COLUMNS, TableColumn } from "../columns";
+import { UserRow } from "./UserRow";
+
+const GROUP_PAGE_SIZE = 10;
+
+export interface TraitGroupView {
+ /** Stable across refetches: the value, or a fixed id for the two catch-all groups. */
+ id: string;
+ label: ReactNode;
+ /** The label as plain text, for the expand button's accessible name. */
+ name: string;
+ stats: TraitGroupStats;
+ /** Users in the comparison period. Undefined when there is nothing to compare with. */
+ previousUsers?: number;
+ /** The group's share of its population, as a sentence: "13.1% of identified". */
+ shareLabel: string;
+ /** Bar length against the largest group, 0 to 1. Omitted for the catch-all groups. */
+ bar?: number;
+ /** What to ask the users list for. Null when the group cannot be listed. */
+ selector: TraitGroupSelector | null;
+}
+
+const isMetric = (column: TableColumn): column is { kind: "builtIn"; id: BuiltInColumn } =>
+ column.kind === "builtIn" && METRIC_COLUMNS.includes(column.id);
+
+function GroupUsers({
+ selector,
+ total,
+ columns,
+ narrowing,
+ sortBy,
+ sortOrder,
+ site,
+ privateKey,
+}: {
+ selector: TraitGroupSelector;
+ total: number;
+ columns: TableColumn[];
+ narrowing: Omit<UsersNarrowing, "traitGroup">;
+ sortBy: string;
+ sortOrder: string;
+ site: string;
+ privateKey: string | null;
+}) {
+ const t = useExtracted();
+ const { data, isError, hasNextPage, fetchNextPage, isFetchingNextPage } = useGetUsersInfinite({
+ ...narrowing,
+ traitGroup: selector,
+ pageSize: GROUP_PAGE_SIZE,
+ sortBy,
+ sortOrder,
+ });
+ const span = columns.length + 1;
+
+ if (data === undefined && !isError) {
+ return Array.from({ length: Math.min(total, 3) }).map((_, index) => (
+ <tr key={index} className="border-b border-b-neutral-100 dark:border-b-neutral-800">
+ <td colSpan={span} className="py-2.5 pl-9 pr-3">
+ <Skeleton className="h-5 w-full rounded" />
+ </td>
+ </tr>
+ ));
+ }
+
+ const users = data?.pages.flatMap(page => page.data) ?? [];
+ const listed = data?.pages[0]?.totalCount ?? 0;
+ const remaining = Math.max(listed - users.length, 0);
+
+ if (isError || users.length === 0) {
+ return (
+ <tr className="border-b border-b-neutral-100 dark:border-b-neutral-800">
+ <td colSpan={span} className="py-2 pl-9 pr-3 text-xs text-neutral-500 dark:text-neutral-400">
+ {isError ? t("Could not load these users. Try again in a moment.") : t("No users found")}
+ </td>
+ </tr>
+ );
+ }
+
+ return (
+ <>
+ {users.map(user => (
+ <UserRow
+ key={user.identified_user_id || user.user_id}
+ user={user}
+ columns={columns}
+ site={site}
+ privateKey={privateKey}
+ indented
+ />
+ ))}
+ {hasNextPage && (
+ <tr className="border-b border-b-neutral-100 dark:border-b-neutral-800">
+ <td colSpan={span} className="py-1.5 pl-9 pr-3">
+ <button
+ type="button"
+ className="inline-flex items-center gap-1 text-xs font-medium text-neutral-700 hover:underline disabled:opacity-50 dark:text-neutral-300"
+ disabled={isFetchingNextPage}
+ onClick={() => fetchNextPage()}
+ >
+ {t("Show {count} more", { count: Math.min(remaining, GROUP_PAGE_SIZE).toLocaleString() })}
+ <ChevronDown className="h-3 w-3" />
+ </button>
+ {remaining > GROUP_PAGE_SIZE && (
+ <span className="ml-2 text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
+ {t("{count} left", { count: remaining.toLocaleString() })}
+ </span>
+ )}
+ </td>
+ </tr>
+ )}
+ </>
+ );
+}
+
+/**
+ * One group of the trait breakdown: a summary row (users, change, share, and
+ * per-user averages under the count columns) and, when open, the group's users.
+ */
+export function TraitGroupRows({
+ group,
+ open,
+ onToggle,
+ columns,
+ narrowing,
+ sortBy,
+ sortOrder,
+ site,
+ privateKey,
+}: {
+ group: TraitGroupView;
+ open: boolean;
+ onToggle: () => void;
+ columns: TableColumn[];
+ narrowing: Omit<UsersNarrowing, "traitGroup">;
+ sortBy: string;
+ sortOrder: string;
+ site: string;
+ privateKey: string | null;
+}) {
+ const t = useExtracted();
+ const { stats, selector } = group;
+
+ // The summary spans the columns before the counts, then lines its averages
+ // up under them. Whatever follows the counts is left empty.
+ const firstMetric = columns.findIndex(isMetric);
+ const metrics = columns.filter(isMetric);
+ const leadSpan = 1 + (firstMetric === -1 ? columns.length : firstMetric);
+ const trailingSpan = firstMetric === -1 ? 0 : columns.length - firstMetric - metrics.length;
+
+ const average = (id: BuiltInColumn) => {
+ const total = id === "sessions" ? stats.sessions : id === "pageviews" ? stats.pageviews : stats.events;
+ return stats.users > 0 ? (total / stats.users).toFixed(1) : "–";
+ };
+ const expandable = selector !== null && stats.users > 0;
+
+ return (
+ <>
+ <tr className="border-b border-b-neutral-100 bg-neutral-50 dark:border-b-neutral-800 dark:bg-neutral-850/60">
+ <td colSpan={leadSpan} className="py-1.5 pl-3 pr-2">
+ <div className="@container">
+ <div className="flex min-w-0 items-center gap-2">
+ {expandable ? (
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-label={
+ open ? t("Collapse {group}", { group: group.name }) : t("Expand {group}", { group: group.name })
+ }
+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-neutral-500 hover:bg-neutral-200 hover:text-neutral-900 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-neutral-100"
+ onClick={onToggle}
+ >
+ {open ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
+ </button>
+ ) : (
+ <span className="h-5 w-5 shrink-0" />
+ )}
+ <span
+ className="min-w-0 truncate text-sm font-semibold text-neutral-900 dark:text-neutral-50"
+ title={group.name}
+ >
+ {group.label}
+ </span>
+ <span className="whitespace-nowrap text-sm tabular-nums text-neutral-700 dark:text-neutral-200">
+ {stats.users === 1
+ ? t("{count} user", { count: stats.users.toLocaleString() })
+ : t("{count} users", { count: stats.users.toLocaleString() })}
+ </span>
+ <Delta value={percentDelta(stats.users, group.previousUsers)} />
+ <span className="ml-auto flex shrink-0 items-center gap-2">
+ {group.bar !== undefined && (
+ <span className="hidden h-1.5 w-16 overflow-hidden rounded-full bg-neutral-200 @lg:block dark:bg-neutral-800">
+ <span
+ className="block h-full rounded-full bg-dataviz"
+ style={{ width: `${Math.min(group.bar, 1) * 100}%` }}
+ />
+ </span>
+ )}
+ <span className="hidden whitespace-nowrap text-xs tabular-nums text-neutral-500 @md:inline dark:text-neutral-400">
+ {group.shareLabel}
+ </span>
+ {metrics.length > 0 && (
+ <span className="hidden whitespace-nowrap pl-2 text-[11px] uppercase tracking-wide text-neutral-500 @sm:inline dark:text-neutral-400">
+ {t("Avg / user")}
+ </span>
+ )}
+ </span>
+ </div>
+ </div>
+ </td>
+ {metrics.map(column => (
+ <td
+ key={columnId(column)}
+ className="px-2 text-right text-sm tabular-nums text-neutral-700 dark:text-neutral-200"
+ >
+ {average(column.id)}
+ </td>
+ ))}
+ {trailingSpan > 0 && <td colSpan={trailingSpan} />}
+ </tr>
+ {expandable && open && (
+ <GroupUsers
+ selector={selector}
+ total={stats.users}
+ columns={columns}
+ narrowing={narrowing}
+ sortBy={sortBy}
+ sortOrder={sortOrder}
+ site={site}
+ privateKey={privateKey}
+ />
+ )}
+ </>
+ );
+}
diff --git a/client/src/app/[site]/users/components/TraitKeyRow.tsx b/client/src/app/[site]/users/components/TraitKeyRow.tsx
deleted file mode 100644
index a016e0470..000000000
--- a/client/src/app/[site]/users/components/TraitKeyRow.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { ChevronRight } from "lucide-react";
-import { TraitValuesList } from "./TraitValuesList";
-
-export function TraitKeyRow({
- traitKey,
- userCount,
-}: {
- traitKey: string;
- userCount: number;
-}) {
- const [expanded, setExpanded] = useState(false);
-
- return (
- <div className="border-b border-neutral-100 dark:border-neutral-800 last:border-b-0">
- <button
- onClick={() => setExpanded(!expanded)}
- className="w-full flex items-center justify-between px-4 py-3 hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition-colors"
- >
- <div className="flex items-center gap-2">
- <ChevronRight
- className={`h-4 w-4 text-neutral-400 transition-transform ${expanded ? "rotate-90" : ""}`}
- />
- <span className="font-medium text-sm">{traitKey}</span>
- </div>
- <span className="text-neutral-500 dark:text-neutral-400 text-xs">
- {userCount.toLocaleString()} {userCount === 1 ? "user" : "users"}
- </span>
- </button>
- {expanded && <TraitValuesList traitKey={traitKey} />}
- </div>
- );
-}
diff --git a/client/src/app/[site]/users/components/TraitValueUsersList.tsx b/client/src/app/[site]/users/components/TraitValueUsersList.tsx
deleted file mode 100644
index 78b8efd90..000000000
--- a/client/src/app/[site]/users/components/TraitValueUsersList.tsx
+++ /dev/null
@@ -1,179 +0,0 @@
-"use client";
-
-import { useEffect, useMemo, useState } from "react";
-import { useExtracted } from "next-intl";
-import { useIntersectionObserver } from "@uidotdev/usehooks";
-import { Loader2, Search } from "lucide-react";
-import { Input } from "../../../../components/ui/input";
-import Link from "next/link";
-import { useParams } from "next/navigation";
-import { useGetUserTraitValueUsers } from "../../../../api/analytics/hooks/useGetUserTraits";
-import { Avatar } from "../../../../components/Avatar";
-import { IdentifiedBadge } from "../../../../components/IdentifiedBadge";
-import {
- CountryFlagTooltipIcon,
- BrowserTooltipIcon,
- OperatingSystemTooltipIcon,
- DeviceTypeTooltipIcon,
-} from "../../../../components/TooltipIcons/TooltipIcons";
-import { getUserDisplayName } from "../../../../lib/utils";
-
-export function TraitValueUsersList({
- traitKey,
- value,
- userCount,
-}: {
- traitKey: string;
- value: string;
- userCount: number;
-}) {
- const t = useExtracted();
- const [searchTerm, setSearchTerm] = useState("");
- const { site } = useParams();
- const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } =
- useGetUserTraitValueUsers(traitKey, value);
-
- const [ref, entry] = useIntersectionObserver({
- threshold: 0,
- root: null,
- rootMargin: "0px 0px 200px 0px",
- });
-
- const flattenedUsers = useMemo(() => {
- if (!data) return [];
- return data.pages.flatMap((page) => page.users);
- }, [data]);
-
- const filteredUsers = useMemo(() => {
- if (!searchTerm) return flattenedUsers;
- const lower = searchTerm.toLowerCase();
- return flattenedUsers.filter((user) =>
- getUserDisplayName(user).toLowerCase().includes(lower)
- );
- }, [flattenedUsers, searchTerm]);
-
- useEffect(() => {
- if (
- entry?.isIntersecting &&
- hasNextPage &&
- !isFetchingNextPage &&
- !isLoading
- ) {
- fetchNextPage();
- }
- }, [
- entry?.isIntersecting,
- fetchNextPage,
- hasNextPage,
- isFetchingNextPage,
- isLoading,
- ]);
-
- if (isLoading) {
- return (
- <div className="border-l border-neutral-150 dark:border-neutral-750 ml-[19px]">
- {Array.from({ length: Math.min(userCount, 10) }).map((_, i) => (
- <div
- key={i}
- className="flex items-center gap-3 py-1.5 px-3 animate-pulse"
- >
- <div className="h-5 w-5 bg-neutral-200 dark:bg-neutral-800 rounded-full shrink-0" />
- <div className="w-56 shrink">
- <div
- className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded"
- style={{ width: `${20 + Math.random() * 100}px` }}
- />
- </div>
- <div className="flex items-center gap-1.5 shrink-0">
- <div className="h-5 w-7 bg-neutral-200 dark:bg-neutral-800 rounded" />
- <div className="h-4 w-5 bg-neutral-200 dark:bg-neutral-800 rounded" />
- <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded" />
- <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded" />
- <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded" />
- <div className="h-4 w-16 bg-neutral-200 dark:bg-neutral-800 rounded ml-1" />
- </div>
- </div>
- ))}
- </div>
- );
- }
-
- if (flattenedUsers.length === 0) {
- return (
- <div className="pl-12 py-3 text-xs text-neutral-500 dark:text-neutral-400">
- {t("No users found")}
- </div>
- );
- }
-
- return (
- <div className="border-l border-neutral-150 dark:border-neutral-750 ml-[19px]">
- {flattenedUsers.length > 5 && (
- <div className="px-3 py-1.5">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-neutral-400" />
- <Input
- placeholder={t("Search users...")}
- value={searchTerm}
- onChange={(e) => setSearchTerm(e.target.value)}
- className="h-7 pl-7 text-xs"
- />
- </div>
- </div>
- )}
- {filteredUsers.map((user, index) => {
- const isIdentified = !!user.identified_user_id;
- const linkId = isIdentified ? user.identified_user_id : user.user_id;
- const encodedLinkId = encodeURIComponent(linkId);
- const displayName = getUserDisplayName(user);
-
- return (
- <div
- key={`${linkId}-${index}`}
- className="flex items-center gap-3 py-1.5 px-3 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition-colors"
- >
- <Link
- href={`/${site}/user/${encodedLinkId}`}
- className="flex items-center gap-2 w-64 shrink"
- target="_blank"
- >
- <Avatar size={20} id={linkId} />
- <span
- className="truncate hover:underline"
- title={displayName}
- >
- {displayName}
- </span>
- </Link>
- <div className="flex items-center gap-1.5 shrink-0">
- {isIdentified && <IdentifiedBadge traits={user.traits} userId={user.identified_user_id} />}
- <CountryFlagTooltipIcon
- country={user.country || ""}
- city={user.city || ""}
- region={user.region || ""}
- />
- <BrowserTooltipIcon browser={user.browser || ""} />
- <OperatingSystemTooltipIcon
- operating_system={user.operating_system || ""}
- />
- <DeviceTypeTooltipIcon device_type={user.device_type || ""} />
- <span className="text-neutral-500 dark:text-neutral-400 text-xs whitespace-nowrap ml-1">
- {user.sessions === 1 ? t("{count} session", { count: user.sessions.toLocaleString() }) : t("{count} sessions", { count: user.sessions.toLocaleString() })}
- </span>
- </div>
- </div>
- );
- })}
- {hasNextPage && (
- <div ref={ref} className="py-2 flex justify-center">
- {isFetchingNextPage && (
- <div className="flex items-center gap-2 text-neutral-600 dark:text-neutral-400 text-xs">
- <Loader2 className="h-3 w-3 animate-spin" />
- {t("Loading more...")}
- </div>
- )}
- </div>
- )}
- </div>
- );
-}
diff --git a/client/src/app/[site]/users/components/TraitValuesList.tsx b/client/src/app/[site]/users/components/TraitValuesList.tsx
deleted file mode 100644
index e58c258c0..000000000
--- a/client/src/app/[site]/users/components/TraitValuesList.tsx
+++ /dev/null
@@ -1,145 +0,0 @@
-"use client";
-
-import { useEffect, useMemo, useState } from "react";
-import { useExtracted } from "next-intl";
-import { useIntersectionObserver } from "@uidotdev/usehooks";
-import { ChevronRight, Loader2, Search } from "lucide-react";
-import { Input } from "../../../../components/ui/input";
-import { useGetUserTraitValues } from "../../../../api/analytics/hooks/useGetUserTraits";
-import { TraitValueUsersList } from "./TraitValueUsersList";
-
-function TraitValueRow({
- traitKey,
- value,
- userCount,
-}: {
- traitKey: string;
- value: string;
- userCount: number;
-}) {
- const t = useExtracted();
- const [expanded, setExpanded] = useState(false);
-
- return (
- <div>
- <button
- onClick={() => setExpanded(!expanded)}
- className="w-full flex items-center justify-between py-1.5 px-3 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition-colors"
- >
- <div className="flex items-center gap-2">
- <ChevronRight
- className={`h-4 w-4 text-neutral-400 transition-transform ${expanded ? "rotate-90" : ""}`}
- />
- <span className="text-neutral-700 dark:text-neutral-300 truncate">
- {value || <span className="italic text-neutral-400">{t("empty")}</span>}
- </span>
- </div>
- <span className="text-neutral-500 dark:text-neutral-400 text-xs whitespace-nowrap">
- {userCount === 1 ? t("{count} user", { count: userCount.toLocaleString() }) : t("{count} users", { count: userCount.toLocaleString() })}
- </span>
- </button>
- {expanded && <TraitValueUsersList traitKey={traitKey} value={value} userCount={userCount} />}
- </div>
- );
-}
-
-export function TraitValuesList({ traitKey }: { traitKey: string }) {
- const t = useExtracted();
- const [searchTerm, setSearchTerm] = useState("");
- const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } =
- useGetUserTraitValues(traitKey);
-
- const [ref, entry] = useIntersectionObserver({
- threshold: 0,
- root: null,
- rootMargin: "0px 0px 200px 0px",
- });
-
- const flattenedValues = useMemo(() => {
- if (!data) return [];
- return data.pages.flatMap((page) => page.values);
- }, [data]);
-
- const filteredValues = useMemo(() => {
- if (!searchTerm) return flattenedValues;
- const lower = searchTerm.toLowerCase();
- return flattenedValues.filter((item) =>
- item.value.toLowerCase().includes(lower)
- );
- }, [flattenedValues, searchTerm]);
-
- useEffect(() => {
- if (
- entry?.isIntersecting &&
- hasNextPage &&
- !isFetchingNextPage &&
- !isLoading
- ) {
- fetchNextPage();
- }
- }, [
- entry?.isIntersecting,
- fetchNextPage,
- hasNextPage,
- isFetchingNextPage,
- isLoading,
- ]);
-
- if (isLoading) {
- return (
- <div className="border-l border-neutral-150 dark:border-neutral-750 ml-[23px]">
- {Array.from({ length: 3 }).map((_, i) => (
- <div
- key={i}
- className="flex items-center justify-between py-2 px-3 animate-pulse"
- >
- <div className="flex items-center gap-2">
- <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded shrink-0" />
- <div
- className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded"
- style={{ width: `${100 + i * 20}px` }}
- />
- </div>
- <div className="h-4 w-16 bg-neutral-200 dark:bg-neutral-800 rounded" />
- </div>
- ))}
- </div>
- );
- }
-
- return (
- <div className="border-l border-neutral-150 dark:border-neutral-750 ml-[23px]">
- {flattenedValues.length > 5 && (
- <div className="px-3 py-1.5">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-neutral-400" />
- <Input
- placeholder={t("Search values...")}
- value={searchTerm}
- onChange={(e) => setSearchTerm(e.target.value)}
- className="h-7 pl-7 text-xs"
- />
- </div>
- </div>
- )}
- {filteredValues.map((item, index) => (
- <TraitValueRow
- key={`${item.value}-${index}`}
- traitKey={traitKey}
- value={item.value}
- userCount={item.userCount}
- />
- ))}
- {hasNextPage && (
- <div ref={ref} className="py-2 flex justify-center">
- {isFetchingNextPage && (
- <div className="flex items-center gap-2 text-neutral-600 dark:text-neutral-400 text-xs">
- <Loader2 className="h-3 w-3 animate-spin" />
- {t("Loading more...")}
- </div>
- )}
- </div>
- )}
- </div>
- );
-}
diff --git a/client/src/app/[site]/users/components/TraitsExplorer.tsx b/client/src/app/[site]/users/components/TraitsExplorer.tsx
deleted file mode 100644
index 949739afc..000000000
--- a/client/src/app/[site]/users/components/TraitsExplorer.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-"use client";
-
-import { useExtracted } from "next-intl";
-import { Tags } from "lucide-react";
-import { ExternalLink } from "../../../../components/ExternalLink";
-import { NothingFound } from "../../../../components/NothingFound";
-import { useGetUserTraitKeys } from "../../../../api/analytics/hooks/useGetUserTraits";
-import { TraitKeyRow } from "./TraitKeyRow";
-
-export function TraitsExplorer() {
- const t = useExtracted();
- const { data, isLoading } = useGetUserTraitKeys();
-
- if (isLoading) {
- return (
- <div className="rounded-lg border border-neutral-100 dark:border-neutral-850 bg-white dark:bg-neutral-900">
- {Array.from({ length: 5 }).map((_, i) => (
- <div
- key={i}
- className="flex items-center justify-between px-4 py-3 border-b border-neutral-100 dark:border-neutral-800 last:border-b-0 animate-pulse"
- >
- <div className="flex items-center gap-2">
- <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded" />
- <div
- className="h-5 bg-neutral-200 dark:bg-neutral-800 rounded"
- style={{ width: `${80 + i * 16}px` }}
- />
- </div>
- <div className="h-4 w-20 bg-neutral-200 dark:bg-neutral-800 rounded" />
- </div>
- ))}
- </div>
- );
- }
-
- if (!data?.keys?.length) {
- return (
- <NothingFound
- icon={<Tags className="w-10 h-10" />}
- title={t("No traits found")}
- description={<p>{t("Traits will appear here once you")} <ExternalLink href="https://rybbit.com/docs/identify-users">{t("identify users")}</ExternalLink> {t("with custom properties.")}</p>}
- />
- );
- }
-
- return (
- <div className="rounded-lg border border-neutral-100 dark:border-neutral-850 bg-white dark:bg-neutral-900">
- {data.keys.map((item) => (
- <TraitKeyRow key={item.key} traitKey={item.key} userCount={item.userCount} />
- ))}
- </div>
- );
-}
diff --git a/client/src/app/[site]/users/components/UserRow.test.tsx b/client/src/app/[site]/users/components/UserRow.test.tsx
new file mode 100644
index 000000000..cc69ac68d
--- /dev/null
+++ b/client/src/app/[site]/users/components/UserRow.test.tsx
@@ -0,0 +1,203 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { UsersResponse } from "@/api/analytics/endpoints";
+import { visibleColumns } from "../columns";
+import { UserRow } from "./UserRow";
+
+const mocks = vi.hoisted(() => ({
+ push: vi.fn(),
+ addFilter: vi.fn(),
+}));
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => (message: string, values?: Record<string, string>) =>
+ Object.entries(values ?? {}).reduce((text, [key, value]) => text.replace(`{${key}}`, value), message),
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push: mocks.push }),
+}));
+
+vi.mock("next/link", () => ({
+ default: ({
+ href,
+ children,
+ prefetch,
+ onClick,
+ ...props
+ }: {
+ href: string;
+ children: ReactNode;
+ prefetch?: boolean;
+ onClick?: (event: React.MouseEvent) => void;
+ }) => (
+ // jsdom cannot navigate; following the link is the router's job, not what is under test.
+ <a
+ href={href}
+ {...props}
+ onClick={event => {
+ event.preventDefault();
+ onClick?.(event);
+ }}
+ >
+ {children}
+ </a>
+ ),
+}));
+
+vi.mock("@/lib/store", () => ({
+ addFilter: mocks.addFilter,
+ getTimezone: () => "UTC",
+}));
+
+vi.mock("@/hooks/useDateTimeFormat", () => ({
+ useDateTimeFormat: () => ({ formatRelative: () => "2 hours ago", formatDateTime: () => "Sep 30, 10:00 AM" }),
+}));
+
+vi.mock("@/components/Avatar", () => ({
+ Avatar: () => <span data-testid="avatar" />,
+ generateName: (id: string) => `Visitor ${id}`,
+}));
+vi.mock("@/components/Favicon", () => ({ Favicon: () => <span /> }));
+vi.mock("../../components/shared/icons/CountryFlag", () => ({ CountryFlag: () => <span /> }));
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
+ TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
+ TooltipContent: () => null,
+}));
+vi.mock("@/components/TooltipIcons/TooltipIcons", () => ({
+ BrowserTooltipIcon: ({ browser, onClick }: { browser: string; onClick: (event: React.MouseEvent) => void }) => (
+ <button type="button" onClick={onClick}>
+ {browser}
+ </button>
+ ),
+ OperatingSystemTooltipIcon: () => <span />,
+ DeviceTypeTooltipIcon: () => <span />,
+}));
+// Stands in for the badge's trait editor: a dialog rendered in a portal, the way Radix does.
+vi.mock("@/components/IdentifiedBadge", () => ({
+ IdentifiedBadge: () => createPortal(<button type="button">Save traits</button>, document.body),
+}));
+
+const base: UsersResponse = {
+ user_id: "a1d7b800719f",
+ identified_user_id: "",
+ traits: null,
+ country: "DE",
+ region: "DE-BE",
+ city: "Berlin",
+ language: "en",
+ browser: "Firefox",
+ operating_system: "Linux",
+ device_type: "Desktop",
+ referrer: "",
+ channel: "Organic Search",
+ pageviews: 1234,
+ events: 5,
+ sessions: 3,
+ last_seen: "2026-09-30 10:00:00",
+ first_seen: "2026-09-01 10:00:00",
+};
+const identified: UsersResponse = {
+ ...base,
+ identified_user_id: "usr/42",
+ traits: { name: "Mara Lindqvist", email: "[email protected]", plan: "Pro", seats: 12 },
+};
+
+const columns = visibleColumns({
+ builtIn: ["last_seen", "sessions", "pageviews", "events", "source", "location", "device"],
+ traits: ["plan", "seats", "missing"],
+});
+
+const renderRow = (user: UsersResponse, privateKey: string | null = null) =>
+ render(
+ <table>
+ <tbody>
+ <UserRow user={user} columns={columns} site="7" privateKey={privateKey} />
+ </tbody>
+ </table>
+ );
+
+beforeEach(() => {
+ mocks.push.mockClear();
+ mocks.addFilter.mockClear();
+});
+afterEach(cleanup);
+
+describe("UserRow", () => {
+ it("shows an identified user by name with the email under it, and their traits", () => {
+ renderRow(identified);
+
+ expect(screen.getByRole("link", { name: "Mara Lindqvist" }).getAttribute("href")).toBe("/7/user/usr%2F42");
+ expect(screen.getByText("[email protected]")).toBeTruthy();
+ expect(screen.getByText("Pro")).toBeTruthy();
+ expect(screen.getByText("12")).toBeTruthy();
+ expect(screen.getByText("1,234")).toBeTruthy();
+ });
+
+ it("shows an anonymous user by a generated name and a short id", () => {
+ renderRow(base);
+
+ expect(screen.getByRole("link").getAttribute("href")).toBe("/7/user/a1d7b800719f");
+ expect(screen.getByText("Anonymous · a1d7b8")).toBeTruthy();
+ });
+
+ it("does not repeat the name on the second line when the email is the name", () => {
+ renderRow({ ...identified, traits: { email: "[email protected]" } });
+
+ expect(screen.getAllByText("[email protected]")).toHaveLength(1);
+ expect(screen.getByText("usr/42")).toBeTruthy();
+ });
+
+ it("opens the profile from anywhere on the row", () => {
+ renderRow(identified);
+
+ fireEvent.click(screen.getByText("1,234"));
+ expect(mocks.push).toHaveBeenCalledWith("/7/user/usr%2F42");
+ });
+
+ it("stays inside a private link", () => {
+ renderRow(identified, "k3y");
+
+ fireEvent.click(screen.getByText("1,234"));
+ expect(mocks.push).toHaveBeenCalledWith("/7/k3y/user/usr%2F42");
+ expect(screen.getByRole("link", { name: "Mara Lindqvist" }).getAttribute("href")).toBe("/7/k3y/user/usr%2F42");
+ });
+
+ it("leaves the name link to navigate on its own", () => {
+ renderRow(identified);
+
+ fireEvent.click(screen.getByRole("link", { name: "Mara Lindqvist" }));
+ expect(mocks.push).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["Berlin", { parameter: "country", value: ["DE"], type: "equals" }],
+ ["Organic Search", { parameter: "channel", value: ["Organic Search"], type: "equals" }],
+ ["Firefox", { parameter: "browser", value: ["Firefox"], type: "equals" }],
+ ])("filters by %s without opening the profile", (text, filter) => {
+ renderRow(identified);
+
+ fireEvent.click(screen.getByText(text));
+ expect(mocks.addFilter).toHaveBeenCalledWith(filter);
+ expect(mocks.push).not.toHaveBeenCalled();
+ });
+
+ it("ignores clicks that reach the row from a dialog it opened", () => {
+ renderRow(identified);
+
+ fireEvent.click(screen.getByRole("button", { name: "Save traits" }));
+ expect(mocks.push).not.toHaveBeenCalled();
+ });
+
+ it("does not navigate when the click ends a text selection", () => {
+ renderRow(identified);
+ const selection = vi.spyOn(window, "getSelection").mockReturnValue({ toString: () => "Mara" } as Selection);
+
+ fireEvent.click(screen.getByText("1,234"));
+ expect(mocks.push).not.toHaveBeenCalled();
+ selection.mockRestore();
+ });
+});
diff --git a/client/src/app/[site]/users/components/UserRow.tsx b/client/src/app/[site]/users/components/UserRow.tsx
new file mode 100644
index 000000000..9452ee123
--- /dev/null
+++ b/client/src/app/[site]/users/components/UserRow.tsx
@@ -0,0 +1,226 @@
+"use client";
+
+import { FilterParameter } from "@rybbit/shared";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { MouseEvent } from "react";
+import { UsersResponse } from "@/api/analytics/endpoints";
+import { Avatar } from "@/components/Avatar";
+import { ChannelIcon, extractDomain, getDisplayName } from "@/components/Channel";
+import { Favicon } from "@/components/Favicon";
+import { IdentifiedBadge } from "@/components/IdentifiedBadge";
+import {
+ BrowserTooltipIcon,
+ DeviceTypeTooltipIcon,
+ OperatingSystemTooltipIcon,
+} from "@/components/TooltipIcons/TooltipIcons";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
+import { addFilter, getTimezone } from "@/lib/store";
+import { cn, getCountryName, getUserDisplayName } from "@/lib/utils";
+import { CountryFlag } from "../../components/shared/icons/CountryFlag";
+import { columnId, formatTraitValue, TableColumn } from "../columns";
+
+const ANONYMOUS_ID_LENGTH = 6;
+
+const filterBy = (event: MouseEvent, parameter: FilterParameter, value: string | undefined) => {
+ // The row itself opens the profile.
+ event.stopPropagation();
+ if (!value) return;
+ addFilter({ parameter, value: [value], type: "equals" });
+};
+
+const Dash = () => <span className="text-neutral-400 dark:text-neutral-600">–</span>;
+
+/** Relative time that swaps to the absolute date while the row is hovered. */
+function TimeCell({ value }: { value: string }) {
+ const { formatRelative, formatDateTime } = useDateTimeFormat();
+ const date = DateTime.fromSQL(value, { zone: "utc" }).setZone(getTimezone());
+ const relative = Math.abs(date.diffNow(["minutes"]).minutes) < 1 ? "<1 min ago" : formatRelative(date);
+ const absolute = formatDateTime(date, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
+
+ return (
+ <div className="grid whitespace-nowrap text-neutral-700 dark:text-neutral-300">
+ <span className="col-start-1 row-start-1 truncate group-hover:invisible">{relative}</span>
+ <span className="invisible col-start-1 row-start-1 truncate group-hover:visible">{absolute}</span>
+ </div>
+ );
+}
+
+function SourceCell({ user }: { user: UsersResponse }) {
+ const domain = extractDomain(user.referrer);
+
+ return (
+ <button
+ type="button"
+ className="flex max-w-full items-center gap-2 text-neutral-700 hover:opacity-70 dark:text-neutral-300"
+ onClick={event => filterBy(event, "channel", user.channel)}
+ >
+ {domain ? (
+ <Favicon domain={domain} className="h-4 w-4 shrink-0" />
+ ) : (
+ <ChannelIcon channel={user.channel} className="shrink-0 text-neutral-500 dark:text-neutral-400" />
+ )}
+ <span className="truncate">{domain ? getDisplayName(domain) : user.channel}</span>
+ </button>
+ );
+}
+
+function LocationCell({ user }: { user: UsersResponse }) {
+ const t = useExtracted();
+ const countryName = user.country ? getCountryName(user.country) : t("Unknown");
+
+ return (
+ <button
+ type="button"
+ className="flex max-w-full items-center gap-2 text-neutral-700 hover:opacity-70 dark:text-neutral-300"
+ onClick={event => filterBy(event, "country", user.country)}
+ >
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="shrink-0">
+ <CountryFlag country={user.country || ""} />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{countryName}</p>
+ </TooltipContent>
+ </Tooltip>
+ <span className="truncate">{user.city || user.region || countryName}</span>
+ </button>
+ );
+}
+
+function DeviceCell({ user }: { user: UsersResponse }) {
+ return (
+ <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">
+ <DeviceTypeTooltipIcon
+ device_type={user.device_type || ""}
+ size={16}
+ onClick={event => filterBy(event, "device_type", user.device_type)}
+ />
+ <BrowserTooltipIcon browser={user.browser || ""} onClick={event => filterBy(event, "browser", user.browser)} />
+ <OperatingSystemTooltipIcon
+ operating_system={user.operating_system || ""}
+ onClick={event => filterBy(event, "operating_system", user.operating_system)}
+ />
+ </div>
+ );
+}
+
+function Cell({ column, user }: { column: TableColumn; user: UsersResponse }) {
+ if (column.kind === "trait") {
+ const value = formatTraitValue(user.traits?.[column.key]);
+ return value === null ? (
+ <Dash />
+ ) : (
+ <div className="truncate text-neutral-700 dark:text-neutral-300" title={value}>
+ {value}
+ </div>
+ );
+ }
+
+ switch (column.id) {
+ case "last_seen":
+ return <TimeCell value={user.last_seen} />;
+ case "first_seen":
+ return <TimeCell value={user.first_seen} />;
+ case "sessions":
+ case "pageviews":
+ case "events":
+ return <div className="text-right tabular-nums">{user[column.id].toLocaleString()}</div>;
+ case "source":
+ return <SourceCell user={user} />;
+ case "location":
+ return <LocationCell user={user} />;
+ case "device":
+ return <DeviceCell user={user} />;
+ }
+}
+
+/**
+ * One user. The whole row opens the profile; the name is the real link, so the
+ * row is still reachable by keyboard and opens in a new tab the usual ways.
+ * Cells that filter, and the identified badge, keep their own click.
+ */
+export function UserRow({
+ user,
+ columns,
+ site,
+ privateKey,
+ indented = false,
+}: {
+ user: UsersResponse;
+ columns: TableColumn[];
+ site: string;
+ privateKey: string | null;
+ /** Under a trait group, the row steps in to sit below the group's label. */
+ indented?: boolean;
+}) {
+ const t = useExtracted();
+ const router = useRouter();
+
+ const isIdentified = !!user.identified_user_id;
+ const linkId = isIdentified ? user.identified_user_id : user.user_id;
+ const base = privateKey ? `/${site}/${privateKey}` : `/${site}`;
+ const href = `${base}/user/${encodeURIComponent(linkId)}`;
+
+ const displayName = getUserDisplayName(user);
+ const email = typeof user.traits?.email === "string" ? user.traits.email : "";
+ // The line under the name says who this is in a second way: the email, or
+ // failing that the id, unless the name already is that.
+ const secondary = isIdentified
+ ? [email, user.identified_user_id].find(candidate => candidate && candidate !== displayName)
+ : t("Anonymous · {id}", { id: user.user_id.slice(0, ANONYMOUS_ID_LENGTH) });
+
+ const open = (event: MouseEvent<HTMLTableRowElement>) => {
+ // Clicks inside a dialog opened from the row (edit traits) bubble here through React, not the DOM.
+ if (!event.currentTarget.contains(event.target as Node)) return;
+ // Selecting text in a row is not a click on it.
+ if (window.getSelection()?.toString()) return;
+ if (event.metaKey || event.ctrlKey) {
+ window.open(href, "_blank", "noopener");
+ return;
+ }
+ router.push(href);
+ };
+
+ return (
+ <tr
+ className="group cursor-pointer border-b border-b-neutral-100 transition-colors hover:bg-neutral-50 dark:border-b-neutral-800 dark:hover:bg-neutral-800/20"
+ onClick={open}
+ >
+ <td className={cn("py-1.5 pl-3 pr-2 align-middle", indented && "pl-9")}>
+ <div className="flex min-w-0 items-center gap-2.5">
+ <div className="shrink-0">
+ <Avatar size={24} id={linkId} lastActiveTime={DateTime.fromSQL(user.last_seen, { zone: "utc" })} />
+ </div>
+ <div className="min-w-0">
+ <div className="flex items-center gap-1.5">
+ <Link
+ href={href}
+ prefetch={false}
+ className="truncate font-medium text-neutral-900 hover:underline dark:text-neutral-100"
+ title={displayName}
+ onClick={event => event.stopPropagation()}
+ >
+ {displayName}
+ </Link>
+ {isIdentified && (
+ <IdentifiedBadge className="px-1" traits={user.traits} userId={user.identified_user_id} />
+ )}
+ </div>
+ {secondary && <div className="truncate text-xs text-neutral-500 dark:text-neutral-400">{secondary}</div>}
+ </div>
+ </div>
+ </td>
+ {columns.map(column => (
+ <td key={columnId(column)} className="px-2 py-1.5 align-middle">
+ <Cell column={column} user={user} />
+ </td>
+ ))}
+ </tr>
+ );
+}
diff --git a/client/src/app/[site]/users/components/UsersStatBand.tsx b/client/src/app/[site]/users/components/UsersStatBand.tsx
new file mode 100644
index 000000000..a650347ee
--- /dev/null
+++ b/client/src/app/[site]/users/components/UsersStatBand.tsx
@@ -0,0 +1,126 @@
+"use client";
+
+import { Files, IdCard, Radio, Repeat, User, UserPlus } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { useGetLiveUserCount } from "@/api/analytics/hooks/useGetLiveUserCount";
+import { useGetUsersSummary } from "@/api/analytics/hooks/useGetUsers";
+import { StatBand } from "@/components/site/StatBand";
+import { percentDelta } from "@/lib/delta";
+
+const LIVE_MINUTES = 5;
+const NO_VALUE = "–";
+
+const share = (part: number, whole: number) => (whole > 0 ? part / whole : 0);
+
+const formatShare = (value: number) =>
+ value.toLocaleString(undefined, { style: "percent", maximumFractionDigits: value < 0.1 ? 1 : 0 });
+
+const perUser = (sessions: number | undefined, users: number | undefined) =>
+ sessions !== undefined && users ? sessions / users : undefined;
+
+/** The page's summary: who was here in the period, and how that compares with the period before. */
+export function UsersStatBand({ comparisonEnabled }: { comparisonEnabled: boolean }) {
+ const t = useExtracted();
+ const { data: current, isError } = useGetUsersSummary();
+ const { data: previousData } = useGetUsersSummary({ periodTime: "previous", enabled: comparisonEnabled });
+ // A result kept from before the comparison was switched off is not a comparison any more.
+ const previous = comparisonEnabled ? previousData : undefined;
+ const { data: live, isError: isLiveError } = useGetLiveUserCount(LIVE_MINUTES);
+ // Nothing in hand yet, including while the query waits for the site to resolve: a skeleton, not a zero.
+ const isLoading = current === undefined && !isError;
+
+ const count = (value: number | null | undefined) => (value == null ? NO_VALUE : value.toLocaleString());
+ // A line of context only describes figures that arrived; it still holds its space while they load or fail.
+ // `hint` spells the line out on hover, for the widths where the band has to cut it short.
+ const context = (text: string, hint?: string) => (current ? <span title={hint}>{text}</span> : "");
+ const newHint = t("Users with no visit in the {days} days before this period", {
+ days: String(current?.lookback_days ?? 0),
+ });
+ const returningHint = t("Users who also visited in the {days} days before this period", {
+ days: String(current?.lookback_days ?? 0),
+ });
+ const users = current?.users ?? 0;
+ const days = current?.lookback_days ?? 0;
+
+ const sessionsPerUser = perUser(current?.sessions, current?.users);
+ const identifiedSessionsPerUser = perUser(current?.identified_sessions, current?.identified_users);
+
+ return (
+ <StatBand
+ isLoading={isLoading}
+ cells={[
+ {
+ id: "users",
+ icon: <User className="h-3 w-3" />,
+ label: t("Users"),
+ value: count(current?.users),
+ delta: percentDelta(current?.users, previous?.users),
+ sub: context(
+ previous
+ ? t("{count} prev. period", { count: previous.users.toLocaleString() })
+ : t("active in this period")
+ ),
+ },
+ {
+ id: "identified",
+ icon: <IdCard className="h-3 w-3" />,
+ label: t("Identified"),
+ value: count(current?.identified_users),
+ delta: percentDelta(current?.identified_users, previous?.identified_users),
+ sub: context(t("{percent} of users", { percent: formatShare(share(current?.identified_users ?? 0, users)) })),
+ },
+ // An all-time period has no "before" to be new or returning against.
+ current?.new_users !== null && {
+ id: "new",
+ icon: <UserPlus className="h-3 w-3" />,
+ label: t("New"),
+ value: count(current?.new_users),
+ delta: percentDelta(current?.new_users, previous?.new_users),
+ sub: context(
+ t("{percent} · first visit in {days} days", {
+ percent: formatShare(share(current?.new_users ?? 0, users)),
+ days: String(days),
+ }),
+ newHint
+ ),
+ title: newHint,
+ },
+ current?.returning_users !== null && {
+ id: "returning",
+ icon: <Repeat className="h-3 w-3" />,
+ label: t("Returning"),
+ value: count(current?.returning_users),
+ delta: percentDelta(current?.returning_users, previous?.returning_users),
+ sub: context(
+ t("{percent} · back within {days} days", {
+ percent: formatShare(share(current?.returning_users ?? 0, users)),
+ days: String(days),
+ }),
+ returningHint
+ ),
+ title: returningHint,
+ },
+ {
+ id: "sessions-per-user",
+ icon: <Files className="h-3 w-3" />,
+ label: t("Sessions per user"),
+ value: sessionsPerUser === undefined ? NO_VALUE : sessionsPerUser.toFixed(2),
+ delta: percentDelta(sessionsPerUser, perUser(previous?.sessions, previous?.users)),
+ sub: context(
+ identifiedSessionsPerUser === undefined
+ ? t("no identified users")
+ : t("{value} when identified", { value: identifiedSessionsPerUser.toFixed(2) })
+ ),
+ },
+ {
+ id: "active-now",
+ icon: <Radio className="h-3 w-3" />,
+ label: t("Active now"),
+ value: count(live?.count),
+ sub: t("seen in the last {minutes} minutes", { minutes: String(LIVE_MINUTES) }),
+ isLoading: live === undefined && !isLiveError,
+ },
+ ]}
+ />
+ );
+}
diff --git a/client/src/app/[site]/users/components/UsersTable.tsx b/client/src/app/[site]/users/components/UsersTable.tsx
index 81111dbe3..a12c348c2 100644
--- a/client/src/app/[site]/users/components/UsersTable.tsx
+++ b/client/src/app/[site]/users/components/UsersTable.tsx
@@ -1,436 +1,480 @@
"use client";
-import {
- createColumnHelper,
- flexRender,
- getCoreRowModel,
- getPaginationRowModel,
- getSortedRowModel,
- SortingState,
- useReactTable,
-} from "@tanstack/react-table";
-import { addFilter, getTimezone } from "@/lib/store";
-import { Info } from "lucide-react";
-import { DateTime } from "luxon";
-import Link from "next/link";
-import { useParams } from "next/navigation";
-import { useEffect, useState } from "react";
-import { useExtracted } from "next-intl";
-import { useDateTimeFormat } from "../../../../hooks/useDateTimeFormat";
import { useDebounce } from "@uidotdev/usehooks";
-import { UsersResponse } from "../../../../api/analytics/endpoints";
-import { useGetUsers } from "../../../../api/analytics/hooks/useGetUsers";
-import { Avatar } from "../../../../components/Avatar";
-import { ChannelIcon, extractDomain, getDisplayName } from "../../../../components/Channel";
-import { ErrorState } from "../../../../components/ErrorState";
-import { Favicon } from "../../../../components/Favicon";
-import { IdentifiedBadge } from "../../../../components/IdentifiedBadge";
-import { Pagination } from "../../../../components/pagination";
-import { Input } from "../../../../components/ui/input";
-import { Label } from "../../../../components/ui/label";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../../components/ui/select";
-import { Switch } from "../../../../components/ui/switch";
-import { TableSortIndicator } from "../../../../components/ui/table";
-import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
-import { FilterParameter } from "@rybbit/shared";
-import { getCountryName, getUserDisplayName } from "../../../../lib/utils";
-import { Browser } from "../../components/shared/icons/Browser";
-import { CountryFlag } from "../../components/shared/icons/CountryFlag";
-import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";
-import { DeviceIcon } from "../../components/shared/icons/Device";
-
-const columnHelper = createColumnHelper<UsersResponse>();
-const TIME_COLUMN_WIDTH = "10rem";
-const TIME_COLUMN_WIDTH_CLASS = "w-40";
-const TIME_COLUMN_IDS = new Set(["last_seen", "first_seen"]);
-
-const isTimeColumn = (columnId: string) => TIME_COLUMN_IDS.has(columnId);
-
-const handleFilterClick = (e: React.MouseEvent, parameter: FilterParameter, value: string | undefined) => {
- e.stopPropagation();
- if (!value) return;
- addFilter({
- parameter,
- value: [value],
- type: "equals",
- });
-};
+import { ChevronDown, ChevronsDownUp, ChevronsUpDown, ChevronUp, Tags } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { ReactNode, useState } from "react";
+import { TraitBreakdown } from "@/api/analytics/endpoints";
+import { useGetUsers, UsersNarrowing } from "@/api/analytics/hooks/useGetUsers";
+import { useGetUserTraitBreakdown, useGetUserTraitKeys } from "@/api/analytics/hooks/useGetUserTraits";
+import { ErrorState } from "@/components/ErrorState";
+import { Pagination } from "@/components/pagination";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Skeleton } from "@/components/ui/skeleton";
+import { useStore } from "@/lib/store";
+import { cn } from "@/lib/utils";
+import {
+ BuiltInColumn,
+ columnId,
+ columnWidth,
+ SORTABLE_COLUMNS,
+ TableColumn,
+ tableMinWidth,
+ visibleColumns,
+} from "../columns";
+import { useColumnSelection } from "../useColumnSelection";
+import { ColumnPicker } from "./ColumnPicker";
+import { TraitGroupRows, TraitGroupView } from "./TraitGroupRows";
+import { UserRow } from "./UserRow";
-const SortHeader = ({ column, children }: any) => {
- const isSorted = column.getIsSorted();
+type SearchField = "name" | "username" | "email" | "user_id";
+type SortColumn = "last_seen" | "first_seen" | "sessions" | "pageviews" | "events";
+interface Sort {
+ column: SortColumn;
+ descending: boolean;
+}
- return (
- <div
- onClick={() => column.toggleSorting(isSorted ? isSorted === "asc" : true)}
- className="flex items-center gap-1 cursor-pointer select-none"
- >
- {children}
- <TableSortIndicator sortDirection={isSorted} />
- </div>
- );
-};
+const RIGHT_ALIGNED: readonly BuiltInColumn[] = ["sessions", "pageviews", "events"];
+const DEFAULT_PAGE_SIZE = 50;
-export function UsersTable() {
- const t = useExtracted();
- const { formatRelative, formatDateTime } = useDateTimeFormat();
+const isSortable = (id: BuiltInColumn): id is SortColumn => SORTABLE_COLUMNS.includes(id);
- const formatRelativeTime = (dateStr: string) => {
- const date = DateTime.fromSQL(dateStr, { zone: "utc" }).setZone(getTimezone());
- const diff = Math.abs(date.diffNow(["minutes"]).minutes);
+const formatShare = (part: number, whole: number) =>
+ (whole > 0 ? part / whole : 0).toLocaleString(undefined, { style: "percent", maximumFractionDigits: 1 });
- if (diff < 1) {
- return "<1 min ago";
- }
+function SortHeader({
+ label,
+ direction,
+ alignRight,
+ onSort,
+}: {
+ label: string;
+ direction: "asc" | "desc" | null;
+ alignRight: boolean;
+ onSort: () => void;
+}) {
+ const Icon = direction === "desc" ? ChevronDown : direction === "asc" ? ChevronUp : ChevronsUpDown;
- return formatRelative(date);
- };
+ return (
+ <button
+ type="button"
+ className={cn(
+ "inline-flex items-center gap-1 whitespace-nowrap hover:text-neutral-900 dark:hover:text-neutral-100",
+ alignRight && "flex-row-reverse",
+ direction && "text-neutral-900 dark:text-neutral-100"
+ )}
+ onClick={onSort}
+ >
+ {label}
+ <Icon
+ className={cn(
+ "h-3 w-3 shrink-0",
+ direction ? "text-neutral-900 dark:text-neutral-100" : "text-neutral-400 dark:text-neutral-500"
+ )}
+ aria-hidden="true"
+ />
+ </button>
+ );
+}
- const renderTimeCell = (dateStr: string) => {
- const date = DateTime.fromSQL(dateStr, {
- zone: "utc",
- }).setZone(getTimezone());
- const formattedDate = formatDateTime(date, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
- const relativeTime = formatRelativeTime(dateStr);
+function SkeletonRows({ rows, span }: { rows: number; span: number }) {
+ return Array.from({ length: rows }).map((_, index) => (
+ <tr key={index} className="border-b border-b-neutral-100 dark:border-b-neutral-800">
+ <td colSpan={span} className="px-3 py-2.5">
+ <Skeleton className="h-6 w-full rounded" />
+ </td>
+ </tr>
+ ));
+}
- return (
- <div className={`grid ${TIME_COLUMN_WIDTH_CLASS} whitespace-nowrap`}>
- <span className="col-start-1 row-start-1 group-hover:invisible">{relativeTime}</span>
- <span className="col-start-1 row-start-1 invisible group-hover:visible">{formattedDate}</span>
- </div>
- );
- };
- const { site } = useParams();
+function MessageRow({ span, children }: { span: number; children: ReactNode }) {
+ return (
+ <tr>
+ <td colSpan={span} className="px-3 py-10 text-center text-sm text-neutral-500 dark:text-neutral-400">
+ {children}
+ </td>
+ </tr>
+ );
+}
+
+/**
+ * The users in the period: one table, flat and paged, or grouped by a trait
+ * when `breakdown` names one. Search, the quick filters and the sort apply to
+ * both shapes.
+ */
+export function UsersTable({
+ breakdown,
+ narrowing,
+ ready,
+ comparisonEnabled,
+}: {
+ /** The trait key the table is grouped by, or null for the flat list. */
+ breakdown: string | null;
+ narrowing: Pick<UsersNarrowing, "identifiedOnly" | "newOnly" | "minSessions">;
+ /** False while a quick filter is still waiting for the figure it filters by. */
+ ready: boolean;
+ comparisonEnabled: boolean;
+}) {
+ const t = useExtracted();
+ const site = useStore(state => state.site);
+ const privateKey = useStore(state => state.privateKey);
- const [pagination, setPagination] = useState({
- pageIndex: 0,
- pageSize: 50,
- });
- const [sorting, setSorting] = useState<SortingState>([{ id: "last_seen", desc: true }]);
- const [identifiedOnly, setIdentifiedOnly] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
- const [searchField, setSearchField] = useState("username");
- const debouncedSearch = useDebounce(searchTerm, 300);
+ const [searchField, setSearchField] = useState<SearchField>("name");
+ const search = useDebounce(searchTerm, 300).trim();
+ const [sort, setSort] = useState<Sort>({ column: "last_seen", descending: true });
+ const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
+ const [pageState, setPageState] = useState({ scope: "", page: 1 });
+ const [expandedState, setExpandedState] = useState<{ key: string | null; open: Record<string, boolean> }>({
+ key: null,
+ open: {},
+ });
- useEffect(() => {
- setPagination((prev) => ({ ...prev, pageIndex: 0 }));
- }, [debouncedSearch]);
+ const { data: traitKeys, isError: isKeysError } = useGetUserTraitKeys();
+ const { selection, setSelection } = useColumnSelection(site, traitKeys?.keys);
+ const columns = visibleColumns(selection);
+ const span = columns.length + 1;
- const effectiveIdentifiedOnly = identifiedOnly || debouncedSearch.length > 0;
+ const fullNarrowing: Omit<UsersNarrowing, "traitGroup"> = { ...narrowing, search, searchField };
+ const sortBy = sort.column;
+ const sortOrder = sort.descending ? "desc" : "asc";
- const page = pagination.pageIndex + 1;
- const sortBy = sorting.length > 0 ? sorting[0].id : "last_seen";
- const sortOrder = sorting.length > 0 && !sorting[0].desc ? "asc" : "desc";
+ // Anything that changes which users are listed sends the pager back to page one.
+ const scope = JSON.stringify([fullNarrowing, sortBy, sortOrder, pageSize]);
+ const page = pageState.scope === scope ? pageState.page : 1;
- const { data, isLoading, isError } = useGetUsers({
+ const list = useGetUsers({
+ ...fullNarrowing,
page,
- pageSize: pagination.pageSize,
+ pageSize,
sortBy,
sortOrder,
- identifiedOnly: effectiveIdentifiedOnly,
- search: debouncedSearch,
- searchField,
+ enabled: ready && !breakdown,
});
-
- const columns = [
- columnHelper.accessor("user_id", {
- header: t("User"),
- cell: info => {
- const identifiedUserId = info.row.original.identified_user_id;
- const isIdentified = !!info.row.original.identified_user_id;
- const linkId = isIdentified ? identifiedUserId : info.getValue();
- const encodedLinkId = encodeURIComponent(linkId);
- const displayName = getUserDisplayName(info.row.original);
- const lastSeen = DateTime.fromSQL(info.row.original.last_seen, { zone: "utc" });
-
- return (
- <Link href={`/${site}/user/${encodedLinkId}`} className="flex items-center gap-2">
- <Avatar size={20} id={linkId as string} lastActiveTime={lastSeen} />
- <span className="max-w-32 truncate hover:underline" title={displayName}>
- {displayName}
- </span>
- {isIdentified && <IdentifiedBadge traits={info.row.original.traits} userId={identifiedUserId} />}
- </Link>
- );
- },
- }),
- columnHelper.accessor("country", {
- header: t("Country"),
- cell: info => {
- const country = info.getValue();
- return (
- <div
- className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "country", country)}
- >
- <Tooltip>
- <TooltipTrigger asChild>
- <CountryFlag country={country || ""} />
- </TooltipTrigger>
- <TooltipContent>
- <p>{country ? getCountryName(country) : t("Unknown")}</p>
- </TooltipContent>
- </Tooltip>
- {info.row.original.city || info.row.original.region || getCountryName(country)}
- </div>
- );
- },
- }),
- columnHelper.accessor("referrer", {
- header: t("Channel"),
- cell: info => {
- const channel = info.row.original.channel;
- const referrer = info.getValue();
- const domain = extractDomain(referrer);
-
- if (domain) {
- const displayName = getDisplayName(domain);
- return (
- <div
- className="flex items-center gap-2 cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "channel", channel)}
- >
- <Favicon domain={domain} className="w-4 h-4" />
- <span>{displayName}</span>
- </div>
- );
- }
-
- return (
- <div
- className="flex items-center gap-2 cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "channel", channel)}
- >
- <ChannelIcon channel={channel} />
- <span>{channel}</span>
- </div>
- );
- },
- }),
- columnHelper.accessor("browser", {
- header: t("Browser"),
- cell: info => {
- const browser = info.getValue();
- return (
- <div
- className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "browser", browser)}
- >
- <Browser browser={browser || "Unknown"} />
- {browser || t("Unknown")}
- </div>
- );
- },
- }),
- columnHelper.accessor("operating_system", {
- header: t("OS"),
- cell: info => {
- const os = info.getValue();
- return (
- <div
- className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "operating_system", os)}
- >
- <OperatingSystem os={os || ""} />
- {os || t("Unknown")}
- </div>
- );
- },
- }),
- columnHelper.accessor("device_type", {
- header: t("Device"),
- cell: info => {
- const deviceType = info.getValue();
- return (
- <div
- className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "device_type", deviceType)}
- >
- <DeviceIcon deviceType={deviceType || ""} />
- {deviceType}
- </div>
- );
- },
- }),
- columnHelper.accessor("pageviews", {
- header: ({ column }) => <SortHeader column={column}>{t("Pageviews")}</SortHeader>,
- cell: info => <div className="whitespace-nowrap">{info.getValue().toLocaleString()}</div>,
- }),
- columnHelper.accessor("events", {
- header: ({ column }) => <SortHeader column={column}>{t("Events")}</SortHeader>,
- cell: info => <div className="whitespace-nowrap">{info.getValue().toLocaleString()}</div>,
- }),
- columnHelper.accessor("sessions", {
- header: ({ column }) => <SortHeader column={column}>{t("Sessions")}</SortHeader>,
- cell: info => <div className="whitespace-nowrap">{info.getValue().toLocaleString()}</div>,
- }),
- columnHelper.accessor("last_seen", {
- header: ({ column }) => <SortHeader column={column}>{t("Last Seen")}</SortHeader>,
- cell: info => renderTimeCell(info.getValue()),
- }),
- columnHelper.accessor("first_seen", {
- header: ({ column }) => <SortHeader column={column}>{t("First Seen")}</SortHeader>,
- cell: info => renderTimeCell(info.getValue()),
- }),
- ];
-
- const table = useReactTable({
- data: data?.data || [],
- columns,
- pageCount: data?.totalCount ? Math.ceil(data.totalCount / pagination.pageSize) : -1,
- state: {
- pagination,
- sorting,
- },
- onPaginationChange: setPagination,
- onSortingChange: setSorting,
- getCoreRowModel: getCoreRowModel(),
- getSortedRowModel: getSortedRowModel(),
- getPaginationRowModel: getPaginationRowModel(),
- manualPagination: true,
- manualSorting: true,
- sortDescFirst: true,
+ const groups = useGetUserTraitBreakdown({ traitKey: breakdown, narrowing: fullNarrowing, enabled: ready });
+ // Disabled while the comparison is off, which leaves every group's delta undrawn.
+ const previousGroups = useGetUserTraitBreakdown({
+ traitKey: breakdown,
+ periodTime: "previous",
+ narrowing: fullNarrowing,
+ enabled: ready && comparisonEnabled,
});
+ // While a newly picked trait loads, the last trait's groups are still in hand; they are not this trait's.
+ const current = breakdown && groups.data?.key === breakdown ? groups.data : undefined;
+ const previous =
+ comparisonEnabled && previousGroups.data?.key === breakdown && !previousGroups.data?.limited
+ ? previousGroups.data
+ : undefined;
+
+ const columnLabels: Record<BuiltInColumn, string> = {
+ last_seen: t("Last seen"),
+ first_seen: t("First seen"),
+ sessions: t("Sessions"),
+ pageviews: t("Pageviews"),
+ events: t("Events"),
+ source: t("First source"),
+ location: t("Location"),
+ device: t("Device"),
+ };
+
+ const toggleSort = (column: SortColumn) =>
+ setSort(previousSort => ({
+ column,
+ descending: previousSort.column === column ? !previousSort.descending : true,
+ }));
+
+ const groupViews = current ? buildGroupViews(current, previous) : [];
+ const open = expandedState.key === breakdown ? expandedState.open : {};
+ // The first group starts open, so the table shows people without a click.
+ const isOpen = (id: string, index: number) => open[id] ?? index === 0;
+ const anyOpen = groupViews.some((group, index) => group.selector !== null && isOpen(group.id, index));
+ const setOpen = (next: Record<string, boolean>) => setExpandedState({ key: breakdown, open: next });
+
+ function buildGroupViews(data: TraitBreakdown, before: TraitBreakdown | undefined): TraitGroupView[] {
+ const identified = data.totals?.identified ?? 0;
+ const everyone = data.totals?.users ?? 0;
+ const largest = data.groups[0]?.users ?? 0;
+
+ const usersBefore = (value: string) => {
+ if (!before) return undefined;
+ const match = before.groups.find(group => group.value === value);
+ if (match) return match.users;
+ // Past the listed values the group may be folded into "other": unknown, not zero.
+ return before.other ? undefined : 0;
+ };
+
+ const views: TraitGroupView[] = data.groups.map(group => ({
+ id: `value:${group.value}`,
+ label:
+ group.value === "" ? (
+ <span className="font-normal italic text-neutral-500 dark:text-neutral-400">{t("empty")}</span>
+ ) : (
+ group.value
+ ),
+ name: group.value === "" ? t("empty") : group.value,
+ stats: group,
+ previousUsers: usersBefore(group.value),
+ shareLabel: t("{percent} of identified", { percent: formatShare(group.users, identified) }),
+ bar: largest > 0 ? group.users / largest : 0,
+ selector: { key: data.key, value: group.value },
+ }));
+
+ if (data.other) {
+ const name = t("{count} other values", { count: data.other.values.toLocaleString() });
+ views.push({
+ id: "other",
+ label: name,
+ name,
+ stats: data.other,
+ shareLabel: t("{percent} of identified", { percent: formatShare(data.other.users, identified) }),
+ selector: null,
+ });
+ }
+ if (data.none && data.none.users > 0) {
+ const name = t("No {trait}", { trait: data.key });
+ views.push({
+ id: "none",
+ label: name,
+ name,
+ stats: data.none,
+ previousUsers: before?.none?.users,
+ shareLabel: t("{percent} of all users", { percent: formatShare(data.none.users, everyone) }),
+ selector: { key: data.key, missing: true },
+ });
+ }
+ return views;
+ }
+
+ const isGrouped = !!breakdown;
+ // "Nothing in hand yet" rather than the queries' loading flags: those are false while a query waits to be
+ // enabled (the site not resolved yet), and the table would report an empty period it has not asked about.
+ const isLoadingKeys = traitKeys === undefined && !isKeysError;
+ const isLoadingRows = isGrouped ? !current && !groups.isError : list.data === undefined && !list.isError;
+ const isLoading = !ready || isLoadingKeys || isLoadingRows;
+ const isError = isGrouped ? groups.isError : list.isError;
+ const users = list.data?.data ?? [];
+ const total = isGrouped ? current?.totals?.users : list.data?.totalCount;
+ const searchLimited = isGrouped ? current?.searchLimited : list.data?.searchLimited;
+
+ const summary =
+ total === undefined || isLoading
+ ? null
+ : isGrouped
+ ? t("{users} users in {groups} groups", {
+ users: total.toLocaleString(),
+ groups: groupViews.length.toLocaleString(),
+ })
+ : total === 1
+ ? t("{count} user", { count: total.toLocaleString() })
+ : t("{count} users", { count: total.toLocaleString() });
+
+ const isNarrowed = !!(narrowing.identifiedOnly || narrowing.newOnly || narrowing.minSessions);
+ const emptyMessage = search
+ ? t("No users match this search")
+ : isNarrowed
+ ? t("No users match these filters")
+ : t("No users in this period");
+
+ let body: ReactNode;
if (isError) {
+ body = (
+ <MessageRow span={span}>
+ <ErrorState
+ title={t("Failed to load users")}
+ message={t("There was a problem fetching the users. Please try again later.")}
+ refetch={isGrouped ? groups.refetch : list.refetch}
+ />
+ </MessageRow>
+ );
+ } else if (isLoading) {
+ body = <SkeletonRows rows={isGrouped ? 6 : 12} span={span} />;
+ } else if (isGrouped && current?.limited) {
+ body = (
+ <MessageRow span={span}>
+ <span className="mx-auto block max-w-md">
+ {t(
+ "More than {limit} identified users were active in this period, which is too many to group by a trait here. Shorten the period or add a filter.",
+ { limit: current.limit.toLocaleString() }
+ )}
+ </span>
+ </MessageRow>
+ );
+ } else if (isGrouped) {
+ body =
+ groupViews.length === 0 ? (
+ <MessageRow span={span}>{emptyMessage}</MessageRow>
+ ) : (
+ groupViews.map((group, index) => (
+ <TraitGroupRows
+ key={group.id}
+ group={group}
+ open={isOpen(group.id, index)}
+ onToggle={() => setOpen({ ...open, [group.id]: !isOpen(group.id, index) })}
+ columns={columns}
+ narrowing={fullNarrowing}
+ sortBy={sortBy}
+ sortOrder={sortOrder}
+ site={site}
+ privateKey={privateKey}
+ />
+ ))
+ );
+ } else {
+ body =
+ users.length === 0 ? (
+ <MessageRow span={span}>{emptyMessage}</MessageRow>
+ ) : (
+ users.map(user => (
+ <UserRow
+ key={user.identified_user_id || user.user_id}
+ user={user}
+ columns={columns}
+ site={site}
+ privateKey={privateKey}
+ />
+ ))
+ );
+ }
+
+ const renderHeader = (column: TableColumn) => {
+ if (column.kind === "trait") {
+ return (
+ <span className="inline-flex max-w-full items-center gap-1" title={column.key}>
+ <Tags className="h-3 w-3 shrink-0" aria-hidden="true" />
+ <span className="truncate">{column.key}</span>
+ </span>
+ );
+ }
+ const { id } = column;
+ if (!isSortable(id)) return columnLabels[id];
return (
- <ErrorState
- title={t("Failed to load users")}
- message={t("There was a problem fetching the users. Please try again later.")}
+ <SortHeader
+ label={columnLabels[id]}
+ direction={sort.column === id ? (sort.descending ? "desc" : "asc") : null}
+ alignRight={RIGHT_ALIGNED.includes(id)}
+ onSort={() => toggleSort(id)}
/>
);
- }
+ };
return (
- <div className="space-y-3">
- <div className="flex justify-between">
- <div className="flex max-w-sm">
- <Select value={searchField} onValueChange={setSearchField}>
- <SelectTrigger className="w-[110px] shrink-0 rounded-r-none border-r-0">
+ <div className="overflow-hidden rounded-lg border border-neutral-100 bg-white text-neutral-950 dark:border-neutral-850 dark:bg-neutral-900 dark:text-neutral-50">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 border-b border-neutral-100 px-3 py-2 dark:border-neutral-800">
+ <div className="flex w-full sm:w-auto">
+ <Select value={searchField} onValueChange={value => setSearchField(value as SearchField)}>
+ <SelectTrigger className="h-8 w-[112px] shrink-0 rounded-r-none border-r-0 text-[13px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem value="username">{t("Username")}</SelectItem>
<SelectItem value="name">{t("Name")}</SelectItem>
+ <SelectItem value="username">{t("Username")}</SelectItem>
<SelectItem value="email">{t("Email")}</SelectItem>
<SelectItem value="user_id">{t("User ID")}</SelectItem>
</SelectContent>
</Select>
<Input
- placeholder={t("Search by {field}...", { field: searchField === "user_id" ? t("user ID") : searchField })}
- className="rounded-l-none"
+ // Names, usernames and emails are traits, which only identified users have. Ids cover everyone.
+ placeholder={searchField === "user_id" ? t("Search by user ID…") : t("Search identified users…")}
+ aria-label={t("Search users")}
+ className="h-8 min-w-0 flex-1 rounded-l-none text-[13px] sm:w-64 sm:flex-none"
type="search"
value={searchTerm}
- onChange={(e) => setSearchTerm(e.target.value)}
+ onChange={event => setSearchTerm(event.target.value)}
/>
</div>
- <div className="flex items-center gap-2">
- <Switch
- id="identified-only"
- checked={effectiveIdentifiedOnly}
- onCheckedChange={setIdentifiedOnly}
- disabled={debouncedSearch.length > 0}
+ <div className="ml-auto flex flex-wrap items-center gap-x-3 gap-y-2">
+ {summary && (
+ <span className="text-xs tabular-nums text-neutral-500 dark:text-neutral-400" aria-live="polite">
+ {summary}
+ </span>
+ )}
+ {isGrouped && anyOpen && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="gap-1.5 font-normal text-neutral-700 dark:text-neutral-300"
+ onClick={() => setOpen(Object.fromEntries(groupViews.map(group => [group.id, false])))}
+ >
+ <ChevronsDownUp />
+ {t("Collapse all")}
+ </Button>
+ )}
+ <ColumnPicker
+ selection={selection}
+ onChange={setSelection}
+ traitKeys={traitKeys?.keys.map(item => item.key) ?? []}
+ columnLabels={columnLabels}
/>
- <Label htmlFor="identified-only" className="text-sm text-neutral-600 dark:text-neutral-400 cursor-pointer">
- {t("Identified only")}
- </Label>
- <Tooltip>
- <TooltipTrigger asChild>
- <Link href="https://www.rybbit.io/docs/identify-users" target="_blank">
- <Info className="h-4 w-4 text-neutral-400 hover:text-neutral-600 dark:hover:text-neutral-300 cursor-pointer" />
- </Link>
- </TooltipTrigger>
- <TooltipContent>
- <p>{t("Learn how to identify users")}</p>
- </TooltipContent>
- </Tooltip>
</div>
</div>
- <div className="relative overflow-x-auto">
- <table className="w-full text-sm text-left">
- <thead className="[&_tr]:border-b-0 bg-neutral-50 dark:bg-neutral-850">
- {table.getHeaderGroups().map(headerGroup => (
- <tr key={headerGroup.id}>
- {headerGroup.headers.map(header => (
- <th
- key={header.id}
- scope="col"
- className="h-8 px-2 text-left align-middle font-medium text-xs text-neutral-500 dark:text-neutral-400 whitespace-nowrap first:rounded-l-xl last:rounded-r-xl"
- style={{
- minWidth:
- header.id === "user_id" ? "100px" : isTimeColumn(header.id) ? TIME_COLUMN_WIDTH : "auto",
- width: isTimeColumn(header.id) ? TIME_COLUMN_WIDTH : undefined,
- }}
- >
- {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
- </th>
- ))}
- </tr>
+
+ {searchLimited && (
+ <div className="border-b border-neutral-100 px-3 py-1.5 text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400">
+ {t(
+ "More than 10,000 profiles match this search. Showing the most recently updated; type more to narrow it down."
+ )}
+ </div>
+ )}
+
+ <div className="overflow-x-auto">
+ <table className="w-full table-fixed caption-bottom text-sm" style={{ minWidth: tableMinWidth(columns) }}>
+ <colgroup>
+ <col />
+ {columns.map(column => (
+ <col key={columnId(column)} style={{ width: columnWidth(column) }} />
))}
- </thead>
- <tbody>
- {isLoading ? (
- Array.from({ length: 15 }).map((_, index) => (
- <tr key={index} className="border-b border-neutral-100 dark:border-neutral-800 animate-pulse">
- {Array.from({ length: columns.length }).map((_, cellIndex) => (
- <td key={cellIndex} className="p-3">
- <div className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
- </td>
- ))}
- </tr>
- ))
- ) : table.getRowModel().rows.length === 0 ? (
- <tr>
- <td
- colSpan={columns.length}
- className="px-3 py-8 text-center text-neutral-500 dark:text-neutral-400"
+ </colgroup>
+ <thead className="bg-neutral-50 dark:bg-neutral-850">
+ <tr>
+ <th
+ scope="col"
+ className="h-8 pl-3 pr-2 text-left align-middle text-xs font-medium text-neutral-500 dark:text-neutral-400"
+ >
+ {t("User")}
+ </th>
+ {columns.map(column => (
+ <th
+ key={columnId(column)}
+ scope="col"
+ aria-sort={
+ column.kind === "builtIn" && sort.column === column.id
+ ? sort.descending
+ ? "descending"
+ : "ascending"
+ : undefined
+ }
+ className={cn(
+ "h-8 px-2 text-left align-middle text-xs font-medium text-neutral-500 dark:text-neutral-400",
+ column.kind === "builtIn" && RIGHT_ALIGNED.includes(column.id) && "text-right"
+ )}
>
- {t("No users found")}
- </td>
- </tr>
- ) : (
- table.getRowModel().rows.map(row => {
- const linkId = row.original.identified_user_id || row.original.user_id;
- const href = `/${site}/user/${encodeURIComponent(linkId)}`;
-
- return (
- <tr key={row.id} className="border-b border-neutral-100 dark:border-neutral-800 group hover:bg-neutral-50 dark:hover:bg-neutral-850">
- {row.getVisibleCells().map(cell => (
- <td
- key={cell.id}
- className={isTimeColumn(cell.column.id) ? `p-3 relative ${TIME_COLUMN_WIDTH_CLASS}` : "p-3 relative"}
- >
- {/* <Link
- href={href}
- className="absolute inset-0 z-10"
- aria-label={`View user ${userId}`}
- >
- <span className="sr-only">View user details</span>
- </Link> */}
- <span className="relative z-0">
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </span>
- </td>
- ))}
- </tr>
- );
- })
- )}
- </tbody>
+ {renderHeader(column)}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody className="bg-white dark:bg-neutral-900 [&_tr:last-child]:border-0">{body}</tbody>
</table>
</div>
- <div className="border-t border-neutral-100 dark:border-neutral-800">
- <div className="px-4 py-3">
+ {!isGrouped && !isError && (
+ <div className="border-t border-neutral-100 px-3 py-2 dark:border-neutral-800">
<Pagination
- table={table}
- data={{ items: data?.data || [], total: data?.totalCount || 0 }}
- pagination={pagination}
- setPagination={setPagination}
+ page={page}
+ pageSize={pageSize}
+ pageCount={Math.max(Math.ceil((list.data?.totalCount ?? 0) / pageSize), 1)}
+ totalItems={list.data?.totalCount ?? 0}
+ onPageChange={next => setPageState({ scope, page: next })}
+ onPageSizeChange={setPageSize}
isLoading={isLoading}
- itemName="users"
+ itemName={t("users")}
/>
</div>
- </div>
+ )}
</div>
);
}
diff --git a/client/src/app/[site]/users/page.tsx b/client/src/app/[site]/users/page.tsx
index 04fb6ef1f..c191fd8b8 100644
--- a/client/src/app/[site]/users/page.tsx
+++ b/client/src/app/[site]/users/page.tsx
@@ -1,34 +1,97 @@
"use client";
+import { Info, Tags } from "lucide-react";
import { useExtracted } from "next-intl";
+import { useState } from "react";
+import { useGetUsersSummary } from "../../../api/analytics/hooks/useGetUsers";
+import { useGetUserTraitKeys } from "../../../api/analytics/hooks/useGetUserTraits";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../components/ui/basic-tabs";
+import { AnalysisBar } from "../../../components/site/AnalysisBar";
+import { BreakdownControl, BreakdownOption } from "../../../components/site/BreakdownControl";
+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../components/ui/tooltip";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { USER_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { useStore } from "../../../lib/store";
import { SubHeader } from "../components/SubHeader/SubHeader";
-import { TraitsExplorer } from "./components/TraitsExplorer";
+import { NO_QUICK_FILTERS, QuickFilters, QuickFilterState } from "./components/QuickFilters";
+import { UsersStatBand } from "./components/UsersStatBand";
import { UsersTable } from "./components/UsersTable";
+// Not a trait key: keys come from identify() calls and may be any string, the empty one aside.
+const NO_BREAKDOWN = "";
+
export default function UsersPage() {
useSetPageTitle("Users");
const t = useExtracted();
+ const [breakdown, setBreakdown] = useState(NO_BREAKDOWN);
+ const [quickFilters, setQuickFilters] = useState<QuickFilterState>(NO_QUICK_FILTERS);
+
+ // All time compared with "the previous period" is all time again: the same numbers, and a row of 0% deltas.
+ const comparisonEnabled = useStore(state => state.previousTime !== null && state.previousTime.mode !== "all-time");
+ const { data: summary } = useGetUsersSummary();
+ const { data: traitKeys } = useGetUserTraitKeys();
+
+ const keys = traitKeys?.keys.map(item => item.key) ?? [];
+ const breakdownOptions: BreakdownOption<string>[] = [
+ { value: NO_BREAKDOWN, label: t("None") },
+ ...keys.map(key => ({ value: key, label: key, icon: <Tags /> })),
+ ];
+ // A trait that no profile carries any more cannot group anyone.
+ const activeBreakdown = keys.includes(breakdown) ? breakdown : null;
+
+ // "New" needs a period with a before; without one the chip is gone and so is its filter.
+ const newOnly = quickFilters.isNew && summary?.new_users !== null;
+
return (
<DisabledOverlay message={t("Users")} featurePath="users">
<div className="p-2 md:p-4 max-w-[1400px] mx-auto space-y-3">
<SubHeader availableFilters={USER_PAGE_FILTERS} />
- <Tabs defaultValue="users">
- <TabsList>
- <TabsTrigger value="users">{t("Users")}</TabsTrigger>
- <TabsTrigger value="traits">{t("Traits")}</TabsTrigger>
- </TabsList>
- <TabsContent value="users">
- <UsersTable />
- </TabsContent>
- <TabsContent value="traits">
- <TraitsExplorer />
- </TabsContent>
- </Tabs>
+ <UsersStatBand comparisonEnabled={comparisonEnabled} />
+ <AnalysisBar
+ // With no traits on the site there is nothing to break the users down by.
+ breakdown={
+ keys.length > 0 ? (
+ <BreakdownControl
+ value={activeBreakdown ?? NO_BREAKDOWN}
+ onChange={setBreakdown}
+ options={breakdownOptions}
+ />
+ ) : null
+ }
+ end={
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <a
+ href="https://rybbit.com/docs/identify-users"
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label={t("Learn how to identify users")}
+ className="flex h-8 w-8 items-center justify-center rounded-lg text-neutral-500 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-neutral-100"
+ >
+ <Info className="h-4 w-4" />
+ </a>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{t("Learn how to identify users")}</p>
+ </TooltipContent>
+ </Tooltip>
+ }
+ >
+ <span className="mx-1 hidden h-5 w-px bg-neutral-200 dark:bg-neutral-800 sm:block" aria-hidden="true" />
+ <QuickFilters value={quickFilters} onChange={setQuickFilters} summary={summary} />
+ </AnalysisBar>
+ <UsersTable
+ breakdown={activeBreakdown}
+ narrowing={{
+ identifiedOnly: quickFilters.identified,
+ newOnly,
+ minSessions: quickFilters.power ? summary?.power_min_sessions : undefined,
+ }}
+ // A power-user filter cannot be sent before the session count that defines it has loaded.
+ ready={!quickFilters.power || summary !== undefined}
+ comparisonEnabled={comparisonEnabled}
+ />
</div>
</DisabledOverlay>
);
diff --git a/client/src/app/[site]/users/useColumnSelection.ts b/client/src/app/[site]/users/useColumnSelection.ts
new file mode 100644
index 000000000..e7856fa12
--- /dev/null
+++ b/client/src/app/[site]/users/useColumnSelection.ts
@@ -0,0 +1,50 @@
+import { useEffect, useState } from "react";
+import { TraitKey } from "@/api/analytics/endpoints";
+import { ColumnSelection, DEFAULT_BUILT_IN, defaultTraitColumns, parseColumnSelection } from "./columns";
+
+const storageKey = (site: string) => `rybbit-users-columns-${site}`;
+
+// Storage can be unavailable (private mode, blocked site data); the picker then works for the visit only.
+function readStored(site: string): ColumnSelection | null {
+ try {
+ return parseColumnSelection(localStorage.getItem(storageKey(site)));
+ } catch {
+ return null;
+ }
+}
+
+function writeStored(site: string, selection: ColumnSelection) {
+ try {
+ localStorage.setItem(storageKey(site), JSON.stringify(selection));
+ } catch {
+ // Nothing to do: the choice still applies until the page is left.
+ }
+}
+
+/**
+ * The columns the viewer has chosen for this site, remembered in the browser.
+ * Until they choose, the site's most common traits are shown beside the
+ * default built-in columns.
+ */
+export function useColumnSelection(site: string, traitKeys: TraitKey[] | undefined) {
+ const [stored, setStored] = useState<{ site: string; selection: ColumnSelection | null } | null>(null);
+
+ // Read after mount: the server render has no storage, and the first client
+ // render has to match it.
+ useEffect(() => {
+ setStored({ site, selection: site ? readStored(site) : null });
+ }, [site]);
+
+ const chosen = stored?.site === site ? stored.selection : null;
+ const selection: ColumnSelection = chosen ?? {
+ builtIn: DEFAULT_BUILT_IN,
+ traits: defaultTraitColumns(traitKeys ?? []),
+ };
+
+ const setSelection = (next: ColumnSelection) => {
+ setStored({ site, selection: next });
+ if (site) writeStored(site, next);
+ };
+
+ return { selection, setSelection };
+}
diff --git a/client/src/components/DateSelector/ComparisonSelect.tsx b/client/src/components/DateSelector/ComparisonSelect.tsx
index b44044d29..557bd9601 100644
--- a/client/src/components/DateSelector/ComparisonSelect.tsx
+++ b/client/src/components/DateSelector/ComparisonSelect.tsx
@@ -3,12 +3,12 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
-import { availableComparisonModes, getAbsoluteBounds, resolveComparison } from "@/lib/time";
+import { availableComparisonModes, resolveComparison } from "@/lib/time";
import { cn } from "@/lib/utils";
import { Check, ChevronDown } from "lucide-react";
import { useExtracted } from "next-intl";
import { useState } from "react";
-import { describeBounds, rangeFieldsForTime, timeFromRangeFields } from "./rangeFields";
+import { describeComparisonWindow, rangeFieldsForTime, timeFromRangeFields } from "./rangeFields";
import { Comparison, ComparisonMode, Time } from "./types";
type CustomFields = { startDate: string; endDate: string };
@@ -60,17 +60,7 @@ export function ComparisonSelect({
none: t("No comparison"),
};
- // "Mar 8 – Mar 14" says nothing useful when the window is a year back, so the
- // year is named whenever it differs from the period being compared.
- const describe = (target: Time | null) => {
- const bounds = target && getAbsoluteBounds(target, zone);
- const label = describeBounds(bounds ?? null);
- const current = getAbsoluteBounds(time, zone);
- if (!bounds || !label || !current) return label;
-
- const year = bounds.end.minus({ minutes: 1 }).year;
- return year === current.end.minus({ minutes: 1 }).year ? label : `${label}, ${year}`;
- };
+ const describe = (target: Time | null) => describeComparisonWindow(target, time, zone);
const resolvedRange = describe(resolved);
diff --git a/client/src/components/DateSelector/rangeFields.test.ts b/client/src/components/DateSelector/rangeFields.test.ts
index 59b6c0c51..327fc7959 100644
--- a/client/src/components/DateSelector/rangeFields.test.ts
+++ b/client/src/components/DateSelector/rangeFields.test.ts
@@ -3,6 +3,7 @@ import { DateTime } from "luxon";
import { describe, expect, it } from "vitest";
import {
describeBounds,
+ describeComparisonWindow,
rangeFieldsForTime,
timeFromRangeFields,
timeFromSelectedDays,
@@ -267,3 +268,27 @@ describe("describeBounds", () => {
expect(describeBounds(bounds)).toBe("Mar 8 – Mar 8");
});
});
+
+describe("describeComparisonWindow", () => {
+ const march: Time = { mode: "range", startDate: "2024-03-08", endDate: "2024-03-14" };
+
+ it("leaves the year out when the window ends in the same year as the period", () => {
+ const previous: Time = { mode: "range", startDate: "2024-03-01", endDate: "2024-03-07" };
+ expect(describeComparisonWindow(previous, march, ZONE)).toBe("Mar 1 – Mar 7");
+ });
+
+ it("names the year when the window ends in another one", () => {
+ const lastYear: Time = { mode: "range", startDate: "2023-03-08", endDate: "2023-03-14" };
+ expect(describeComparisonWindow(lastYear, march, ZONE)).toBe("Mar 8 – Mar 14, 2023");
+ });
+
+ it("has nothing to say without a window", () => {
+ expect(describeComparisonWindow(null, march, ZONE)).toBeNull();
+ expect(describeComparisonWindow({ mode: "all-time" }, march, ZONE)).toBeNull();
+ });
+
+ it("still describes the window when the period itself has no bounds", () => {
+ const custom: Time = { mode: "range", startDate: "2023-03-08", endDate: "2023-03-14" };
+ expect(describeComparisonWindow(custom, { mode: "all-time" }, ZONE)).toBe("Mar 8 – Mar 14");
+ });
+});
diff --git a/client/src/components/DateSelector/rangeFields.ts b/client/src/components/DateSelector/rangeFields.ts
index b9954891a..3f1f44382 100644
--- a/client/src/components/DateSelector/rangeFields.ts
+++ b/client/src/components/DateSelector/rangeFields.ts
@@ -106,3 +106,19 @@ export function describeBounds(bounds: { start: DateTime; end: DateTime } | null
if (!bounds) return null;
return `${bounds.start.toFormat("MMM d")} – ${bounds.end.minus({ minutes: 1 }).toFormat("MMM d")}`;
}
+
+/**
+ * The window a comparison resolves to, as the date panel and the Compare
+ * control print it. "Mar 8 – Mar 14" says nothing useful when the window is a
+ * year back, so the year is named whenever it differs from the period being
+ * compared.
+ */
+export function describeComparisonWindow(target: Time | null, time: Time, zone: string): string | null {
+ const bounds = target && getAbsoluteBounds(target, zone);
+ const label = describeBounds(bounds ?? null);
+ const current = getAbsoluteBounds(time, zone);
+ if (!bounds || !label || !current) return label;
+
+ const year = bounds.end.minus({ minutes: 1 }).year;
+ return year === current.end.minus({ minutes: 1 }).year ? label : `${label}, ${year}`;
+}
diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsx
index ab7c6a333..65c65ce99 100644
--- a/client/src/components/Sessions/SessionCard.tsx
+++ b/client/src/components/Sessions/SessionCard.tsx
@@ -25,6 +25,7 @@ import {
import { Badge } from "../ui/badge";
import { ReplayDrawer } from "./ReplayDrawer";
import { SessionDetails } from "./SessionDetails";
+import { sessionEventCount } from "./sessionEventCount";
interface SessionCardProps {
session: GetSessionsResponse[number];
@@ -163,7 +164,7 @@ export function SessionCard({ session, onClick, userId, expandedByDefault, highl
<TooltipTrigger asChild>
<Badge className="flex items-center gap-1 bg-neutral-100 dark:bg-neutral-800 text-neutral-600 dark:text-neutral-300">
<EventTypeIcon type="custom_event" />
- <span>{formatter(session.events + (session.button_clicks || 0) + (session.copies || 0) + (session.form_submits || 0) + (session.input_changes || 0))}</span>
+ <span>{formatter(sessionEventCount(session))}</span>
</Badge>
</TooltipTrigger>
<TooltipContent>{t("Events")}</TooltipContent>
@@ -253,7 +254,7 @@ export function SessionCard({ session, onClick, userId, expandedByDefault, highl
<TooltipTrigger asChild>
<Badge className="flex items-center gap-1 bg-neutral-100 dark:bg-neutral-800 text-neutral-600 dark:text-neutral-300">
<EventTypeIcon type="custom_event" />
- <span>{formatter(session.events + (session.button_clicks || 0) + (session.copies || 0) + (session.form_submits || 0) + (session.input_changes || 0))}</span>
+ <span>{formatter(sessionEventCount(session))}</span>
</Badge>
</TooltipTrigger>
<TooltipContent>{t("Events")}</TooltipContent>
diff --git a/client/src/components/Sessions/SessionDetails/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails/SessionDetails.tsx
index dbf4a084c..e750aed88 100644
--- a/client/src/components/Sessions/SessionDetails/SessionDetails.tsx
+++ b/client/src/components/Sessions/SessionDetails/SessionDetails.tsx
@@ -50,6 +50,9 @@ export function SessionDetails({ session, userId, highlightedEventTimestamp }: S
"copy",
"form_submit",
"input_change",
+ // Errors used to start hidden, so a session's failures only appeared
+ // after finding and switching on their chip.
+ "error",
])
);
diff --git a/client/src/components/Sessions/SessionDetails/SessionInfoTab.tsx b/client/src/components/Sessions/SessionDetails/SessionInfoTab.tsx
index fd6618114..2746b9597 100644
--- a/client/src/components/Sessions/SessionDetails/SessionInfoTab.tsx
+++ b/client/src/components/Sessions/SessionDetails/SessionInfoTab.tsx
@@ -114,7 +114,8 @@ export function SessionInfoTab({
<div className="flex items-center gap-1 text-neutral-500 dark:text-neutral-400">
<CountryFlag country={sessionDetails.country} />
<span>{getCountryName(sessionDetails.country)}</span>
- {sessionDetails.region && (
+ {/* The Region row below names the region; the raw code only stands in when it has no name. */}
+ {sessionDetails.region && !getRegionName(sessionDetails.region) && (
<span>({sessionDetails.region})</span>
)}
</div>
diff --git a/client/src/components/Sessions/sessionEventCount.test.ts b/client/src/components/Sessions/sessionEventCount.test.ts
new file mode 100644
index 000000000..5007353e6
--- /dev/null
+++ b/client/src/components/Sessions/sessionEventCount.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vitest";
+import { sessionEventCount } from "./sessionEventCount";
+
+describe("sessionEventCount", () => {
+ it("adds custom events and autocaptured interactions, the sum the events range filters on", () => {
+ expect(sessionEventCount({ events: 3, button_clicks: 2, copies: 1, form_submits: 1, input_changes: 4 })).toBe(11);
+ });
+
+ it("copes with lists that only report custom events", () => {
+ // Goal and funnel session lists leave the autocapture counts out.
+ expect(sessionEventCount({ events: 5 } as Parameters<typeof sessionEventCount>[0])).toBe(5);
+ });
+});
diff --git a/client/src/components/Sessions/sessionEventCount.ts b/client/src/components/Sessions/sessionEventCount.ts
new file mode 100644
index 000000000..7c30864a6
--- /dev/null
+++ b/client/src/components/Sessions/sessionEventCount.ts
@@ -0,0 +1,22 @@
+import { GetSessionsResponse } from "../../api/analytics/endpoints";
+
+type SessionEventCounts = Pick<
+ GetSessionsResponse[number],
+ "events" | "button_clicks" | "copies" | "form_submits" | "input_changes"
+>;
+
+/**
+ * A session's "events" figure: custom events plus the autocaptured
+ * interactions. The sessions list filters and sorts on the same sum
+ * (SESSION_EVENT_TOTAL on the server), so the number on a row is the number
+ * the events range compares. Outbound clicks and errors are counted apart.
+ */
+export function sessionEventCount(session: SessionEventCounts): number {
+ return (
+ session.events +
+ (session.button_clicks || 0) +
+ (session.copies || 0) +
+ (session.form_submits || 0) +
+ (session.input_changes || 0)
+ );
+}
diff --git a/client/src/components/command-palette/CommandPalette.test.tsx b/client/src/components/command-palette/CommandPalette.test.tsx
index 9c06b22ab..6036142c1 100644
--- a/client/src/components/command-palette/CommandPalette.test.tsx
+++ b/client/src/components/command-palette/CommandPalette.test.tsx
@@ -301,7 +301,7 @@ describe("CommandPalette", () => {
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
cleanup();
- mocks.pathname = "/12/retention";
+ mocks.pathname = "/12/query";
render(<CommandPalette />);
dialog = await openPalette();
expect(within(dialog).queryByText("Date range")).toBeNull();
diff --git a/client/src/components/command-palette/routes.test.ts b/client/src/components/command-palette/routes.test.ts
index fbca97687..e8f5aa2d3 100644
--- a/client/src/components/command-palette/routes.test.ts
+++ b/client/src/components/command-palette/routes.test.ts
@@ -17,13 +17,21 @@ describe("getActiveSiteId", () => {
describe("hasDateSelector", () => {
it("is true on pages that mount a DateSelector", () => {
- for (const path of ["/", "/rollup", "/12/main", "/12/sessions", "/12/user/abc", "/12/dashboards/4"]) {
+ for (const path of [
+ "/",
+ "/rollup",
+ "/12/main",
+ "/12/sessions",
+ "/12/retention",
+ "/12/user/abc",
+ "/12/dashboards/4",
+ ]) {
expect(hasDateSelector(path), path).toBe(true);
}
});
it("is false where the preset hotkeys do nothing", () => {
- for (const path of ["/12/retention", "/12/query", "/12/api-playground", "/12/dashboards", "/settings/account"]) {
+ for (const path of ["/12/query", "/12/api-playground", "/12/dashboards", "/settings/account"]) {
expect(hasDateSelector(path), path).toBe(false);
}
});
diff --git a/client/src/components/command-palette/routes.ts b/client/src/components/command-palette/routes.ts
index be15df638..487a43fe3 100644
--- a/client/src/components/command-palette/routes.ts
+++ b/client/src/components/command-palette/routes.ts
@@ -39,6 +39,7 @@ const DATE_SELECTOR_ROUTES = new Set([
"goals",
"funnels",
"journeys",
+ "retention",
"errors",
"performance",
"experiments",
diff --git a/client/src/components/site/AnalysisBar.test.tsx b/client/src/components/site/AnalysisBar.test.tsx
new file mode 100644
index 000000000..f96b56c80
--- /dev/null
+++ b/client/src/components/site/AnalysisBar.test.tsx
@@ -0,0 +1,164 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { DEFAULT_COMPARISON } from "@/components/DateSelector/types";
+import { useStore } from "@/lib/store";
+import { AnalysisBar } from "./AnalysisBar";
+import { BreakdownControl } from "./BreakdownControl";
+import { CompareControl } from "./CompareControl";
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => (message: string) => message,
+}));
+
+const SEPTEMBER = { mode: "range", startDate: "2026-09-01", endDate: "2026-09-30" } as const;
+
+beforeEach(() => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ useStore.setState({ timezone: "UTC" });
+ useStore.getState().setComparison(DEFAULT_COMPARISON);
+ useStore.getState().setTime(SEPTEMBER);
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+const openMenu = (name: RegExp) => fireEvent.keyDown(screen.getByRole("button", { name }), { key: "Enter" });
+
+describe("AnalysisBar", () => {
+ it("puts compare first, then breakdown, then the page's controls, with the end slot last", () => {
+ render(
+ <AnalysisBar
+ breakdown={<button type="button">Breakdown stand-in</button>}
+ end={<button type="button">New goal</button>}
+ >
+ <button type="button">Sort</button>
+ </AnalysisBar>
+ );
+
+ expect(screen.getAllByRole("button").map(button => button.textContent)).toEqual([
+ "Compare Previous period",
+ "Breakdown stand-in",
+ "Sort",
+ "New goal",
+ ]);
+ });
+
+ it("drops the compare control when a page has nothing to compare", () => {
+ render(<AnalysisBar compare={null} breakdown={<button type="button">Breakdown stand-in</button>} />);
+
+ expect(screen.queryByRole("button", { name: /Compare/ })).toBeNull();
+ });
+});
+
+describe("CompareControl", () => {
+ it("names the comparison the dashboard is using", () => {
+ render(<CompareControl />);
+
+ expect(screen.getByRole("button", { name: "Compare Previous period" })).toBeTruthy();
+ });
+
+ it("offers the modes the period supports with the window each resolves to, and no custom range", () => {
+ render(<CompareControl />);
+ openMenu(/Compare/);
+
+ expect(screen.getAllByRole("menuitemradio").map(item => item.textContent)).toEqual([
+ "Previous periodAug 2 – Aug 31",
+ "Matching weekdaysAug 4 – Sep 2",
+ "Same period last yearSep 1 – Sep 30, 2025",
+ "Off",
+ ]);
+ expect(screen.getByRole("menuitemradio", { name: /Previous period/ }).getAttribute("aria-checked")).toBe("true");
+ });
+
+ it("turns the comparison off for the whole dashboard", () => {
+ render(<CompareControl />);
+ openMenu(/Compare/);
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Off" }));
+
+ expect(useStore.getState().comparison).toEqual({ mode: "none" });
+ expect(useStore.getState().previousTime).toBeNull();
+ expect(screen.getByRole("button", { name: "Compare Off" })).toBeTruthy();
+ });
+
+ it("turns it back on", () => {
+ useStore.getState().setComparison({ mode: "none" });
+ render(<CompareControl />);
+ openMenu(/Compare/);
+ fireEvent.click(screen.getByRole("menuitemradio", { name: /Previous period/ }));
+
+ expect(useStore.getState().comparison).toEqual({ mode: "previous" });
+ expect(useStore.getState().previousTime).toEqual({ mode: "range", startDate: "2026-08-02", endDate: "2026-08-31" });
+ });
+
+ it("shows a custom window set in the date panel and keeps its dates when it is picked again", () => {
+ const custom = {
+ mode: "custom",
+ customTime: { mode: "range", startDate: "2026-07-01", endDate: "2026-07-30" },
+ } as const;
+ useStore.getState().setComparison(custom);
+ render(<CompareControl />);
+
+ expect(screen.getByRole("button", { name: "Compare Custom range" })).toBeTruthy();
+
+ openMenu(/Compare/);
+ const item = screen.getByRole("menuitemradio", { name: /Custom range/ });
+ expect(item.textContent).toBe("Custom rangeJul 1 – Jul 30");
+ fireEvent.click(item);
+
+ expect(useStore.getState().comparison).toEqual(custom);
+ });
+
+ it("reports the previous period when the stored mode does not apply to the selected period", () => {
+ useStore.getState().setComparison({ mode: "weekday" });
+ useStore.getState().setTime({ mode: "month", month: "2026-09-01" });
+ render(<CompareControl />);
+
+ expect(screen.getByRole("button", { name: "Compare Previous period" })).toBeTruthy();
+
+ openMenu(/Compare/);
+ expect(screen.queryByRole("menuitemradio", { name: /Matching weekdays/ })).toBeNull();
+ });
+});
+
+describe("BreakdownControl", () => {
+ type Dimension = "none" | "section" | "channel";
+ const options = [
+ { value: "none", label: "None" },
+ { value: "section", label: "Section" },
+ { value: "channel", label: "Channel", icon: <svg data-testid="channel-icon" /> },
+ ] satisfies { value: Dimension; label: string; icon?: React.ReactNode }[];
+
+ it("shows the selected option on its trigger", () => {
+ render(<BreakdownControl<Dimension> value="section" onChange={() => {}} options={options} />);
+
+ expect(screen.getByRole("button", { name: "Breakdown Section" })).toBeTruthy();
+ });
+
+ it("reports the option that was picked", () => {
+ const onChange = vi.fn<(value: Dimension) => void>();
+ render(<BreakdownControl<Dimension> value="none" onChange={onChange} options={options} />);
+ openMenu(/Breakdown/);
+
+ expect(screen.getByRole("menuitemradio", { name: "None" }).getAttribute("aria-checked")).toBe("true");
+ expect(screen.getByTestId("channel-icon")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Channel" }));
+
+ expect(onChange).toHaveBeenCalledWith("channel");
+ });
+
+ it("takes another label for the same control", () => {
+ render(<BreakdownControl<Dimension> value="none" onChange={() => {}} options={options} label="Group by" />);
+
+ expect(screen.getByRole("button", { name: "Group by None" })).toBeTruthy();
+ });
+});
diff --git a/client/src/components/site/AnalysisBar.tsx b/client/src/components/site/AnalysisBar.tsx
new file mode 100644
index 000000000..fcd56adc7
--- /dev/null
+++ b/client/src/components/site/AnalysisBar.tsx
@@ -0,0 +1,36 @@
+"use client";
+
+import { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+import { CompareControl } from "./CompareControl";
+
+export interface AnalysisBarProps {
+ /**
+ * The compare control. Defaults to `<CompareControl />`; pass `null` on a
+ * page with nothing to compare.
+ */
+ compare?: ReactNode;
+ /** The breakdown control, usually a `<BreakdownControl />`. */
+ breakdown?: ReactNode;
+ /** Page-specific controls, after compare and breakdown: view toggles, sort, interval. */
+ children?: ReactNode;
+ /** Pushed to the far end of the row: search, column picker, the page's create button. */
+ end?: ReactNode;
+ className?: string;
+}
+
+/**
+ * The row of compact controls under the stat band. The order is the same on
+ * every page (compare, breakdown, then the page's own), so the two shared
+ * controls are slots rather than children.
+ */
+export function AnalysisBar({ compare = <CompareControl />, breakdown, children, end, className }: AnalysisBarProps) {
+ return (
+ <div className={cn("flex flex-wrap items-center gap-2", className)}>
+ {compare}
+ {breakdown}
+ {children}
+ {end != null && <div className="ml-auto flex flex-wrap items-center gap-2">{end}</div>}
+ </div>
+ );
+}
diff --git a/client/src/components/site/BreakdownControl.tsx b/client/src/components/site/BreakdownControl.tsx
new file mode 100644
index 000000000..9fa98a6e9
--- /dev/null
+++ b/client/src/components/site/BreakdownControl.tsx
@@ -0,0 +1,75 @@
+"use client";
+
+import { Layers } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { ReactNode } from "react";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { ControlButton } from "./ControlButton";
+
+export interface BreakdownOption<T extends string> {
+ value: T;
+ label: string;
+ /** A 16px icon shown beside the label in the menu. */
+ icon?: ReactNode;
+}
+
+export interface BreakdownControlProps<T extends string> {
+ value: T;
+ onChange: (value: T) => void;
+ /** Every choice, including the one that means no breakdown if the page has one. */
+ options: BreakdownOption<T>[];
+ /** Replaces "Breakdown" on the trigger. */
+ label?: string;
+ className?: string;
+}
+
+/**
+ * The analysis bar's second control: which dimension the page's numbers are
+ * split by. The page owns the choice and what it means.
+ */
+export function BreakdownControl<T extends string>({
+ value,
+ onChange,
+ options,
+ label,
+ className,
+}: BreakdownControlProps<T>) {
+ const t = useExtracted();
+ const selected = options.find(option => option.value === value);
+
+ // Radix hands back a plain string; looking the option up returns it as T.
+ const select = (next: string) => {
+ const option = options.find(candidate => candidate.value === next);
+ if (option) onChange(option.value);
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <ControlButton
+ icon={<Layers />}
+ label={label ?? t("Breakdown")}
+ value={selected?.label ?? value}
+ className={className}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup value={value} onValueChange={select}>
+ {options.map(option => (
+ <DropdownMenuRadioItem key={option.value} value={option.value} className="gap-2">
+ {/* Sized here, not on the item: a descendant selector there would also resize the radio dot. */}
+ {option.icon && <span className="flex shrink-0 items-center [&>svg]:size-4">{option.icon}</span>}
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/client/src/components/site/ChartLegend.tsx b/client/src/components/site/ChartLegend.tsx
new file mode 100644
index 000000000..a0c9f2093
--- /dev/null
+++ b/client/src/components/site/ChartLegend.tsx
@@ -0,0 +1,56 @@
+import { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+
+export interface ChartLegendItem {
+ /** React key. Defaults to the label when it is a string. */
+ id?: string;
+ label: ReactNode;
+ /** Any CSS colour, e.g. `hsl(var(--dataviz))`. */
+ color: string;
+ /** Draws a dashed line instead of a dot: the comparison series. */
+ dashed?: boolean;
+}
+
+export interface ChartLegendProps {
+ items: ChartLegendItem[];
+ className?: string;
+}
+
+/**
+ * Names a chart's series: a dot per series, a dashed line for the comparison
+ * period. Read-only; the events page keeps its own toggling legend.
+ */
+export function ChartLegend({ items, className }: ChartLegendProps) {
+ if (items.length === 0) return null;
+
+ return (
+ <ul
+ className={cn(
+ "flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-neutral-600 dark:text-neutral-300",
+ className
+ )}
+ >
+ {items.map((item, index) => (
+ <li
+ key={item.id ?? (typeof item.label === "string" ? item.label : index)}
+ className="inline-flex items-center gap-1.5"
+ >
+ {item.dashed ? (
+ <span
+ className="inline-block w-3 border-t border-dashed"
+ style={{ borderColor: item.color }}
+ aria-hidden="true"
+ />
+ ) : (
+ <span
+ className="inline-block h-2 w-2 rounded-full"
+ style={{ backgroundColor: item.color }}
+ aria-hidden="true"
+ />
+ )}
+ {item.label}
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/client/src/components/site/CompareControl.tsx b/client/src/components/site/CompareControl.tsx
new file mode 100644
index 000000000..dd47f6683
--- /dev/null
+++ b/client/src/components/site/CompareControl.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+import { GitCompareArrows } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { describeComparisonWindow } from "@/components/DateSelector/rangeFields";
+import { ComparisonMode } from "@/components/DateSelector/types";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { useStore, useTimezone } from "@/lib/store";
+import { availableComparisonModes, resolveComparison } from "@/lib/time";
+import { ControlButton } from "./ControlButton";
+
+/**
+ * The analysis bar's first control: what the page's numbers are compared
+ * against. It reads and writes the dashboard's one comparison (the store's
+ * `comparison`, the same choice the date panel edits and the URL carries), so
+ * turning it off here removes every delta and comparison line on every page:
+ * `previousTime` becomes null, `useComparisonEnabled()` false, and queries
+ * with `periodTime: "previous"` stop running.
+ *
+ * A custom window is shown and can be kept, but is only edited in the date
+ * panel, where its two date fields live.
+ */
+export function CompareControl({ className }: { className?: string }) {
+ const t = useExtracted();
+ const time = useStore(state => state.time);
+ const comparison = useStore(state => state.comparison);
+ const setComparison = useStore(state => state.setComparison);
+ const zone = useTimezone();
+
+ const labels: Record<ComparisonMode, string> = {
+ previous: t("Previous period"),
+ weekday: t("Matching weekdays"),
+ year: t("Same period last year"),
+ custom: t("Custom range"),
+ none: t("Off"),
+ };
+
+ const available = availableComparisonModes(time);
+ // A stored mode the selected period cannot express resolves to the previous
+ // period (see resolveComparison), so that is what the control reports.
+ const mode = available.includes(comparison.mode) ? comparison.mode : "previous";
+ const modes = available.filter(candidate => candidate !== "custom" || mode === "custom");
+
+ const select = (next: string) => {
+ const picked = modes.find(candidate => candidate === next);
+ // Re-picking the stored mode would only drop a custom window's dates.
+ if (!picked || picked === comparison.mode) return;
+ setComparison({ mode: picked });
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <ControlButton icon={<GitCompareArrows />} label={t("Compare")} value={labels[mode]} className={className} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-64">
+ <DropdownMenuRadioGroup value={mode} onValueChange={select}>
+ {modes.map(candidate => (
+ <DropdownMenuRadioItem key={candidate} value={candidate} className="gap-6">
+ <span className="whitespace-nowrap">{labels[candidate]}</span>
+ {candidate !== "none" && (
+ <span className="ml-auto whitespace-nowrap text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
+ {describeComparisonWindow(
+ resolveComparison(time, { ...comparison, mode: candidate }, zone),
+ time,
+ zone
+ )}
+ </span>
+ )}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/client/src/components/site/ControlButton.tsx b/client/src/components/site/ControlButton.tsx
new file mode 100644
index 000000000..b571bb30e
--- /dev/null
+++ b/client/src/components/site/ControlButton.tsx
@@ -0,0 +1,40 @@
+"use client";
+
+import { ChevronDown } from "lucide-react";
+import { forwardRef, ReactNode } from "react";
+import { Button, ButtonProps } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+export interface ControlButtonProps extends Omit<ButtonProps, "children" | "value" | "variant" | "size"> {
+ /** A 16px icon, e.g. `<Layers />`. The button sizes it. */
+ icon?: ReactNode;
+ /** What the control changes: "Compare", "Breakdown", "Sort". */
+ label: string;
+ /** The current choice. */
+ value: ReactNode;
+}
+
+/**
+ * The compact "Label value ▾" trigger every analysis-bar control shares. It
+ * forwards its ref and props, so it works as the child of a
+ * `DropdownMenuTrigger asChild` or `PopoverTrigger asChild`.
+ */
+export const ControlButton = forwardRef<HTMLButtonElement, ControlButtonProps>(
+ ({ icon, label, value, className, ...props }, ref) => (
+ <Button
+ ref={ref}
+ type="button"
+ variant="outline"
+ size="sm"
+ className={cn("max-w-full gap-1.5 font-normal", className)}
+ {...props}
+ >
+ {icon}
+ {/* The space is not laid out in a flex row; it separates the two words in the accessible name. */}
+ <span className="text-neutral-500 dark:text-neutral-400">{label}</span>{" "}
+ <span className="truncate font-medium text-neutral-900 dark:text-neutral-100">{value}</span>
+ <ChevronDown className="opacity-60" />
+ </Button>
+ )
+);
+ControlButton.displayName = "ControlButton";
diff --git a/client/src/components/site/Delta.tsx b/client/src/components/site/Delta.tsx
new file mode 100644
index 000000000..f9bf14715
--- /dev/null
+++ b/client/src/components/site/Delta.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import { ArrowDown, ArrowUp, Minus } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { DeltaTone, DeltaValue, deltaTone } from "@/lib/delta";
+import { cn } from "@/lib/utils";
+
+const TONE_CLASS: Record<DeltaTone, string> = {
+ good: "text-emerald-600 dark:text-emerald-400",
+ bad: "text-red-600 dark:text-red-400",
+ neutral: "text-neutral-500 dark:text-neutral-400",
+};
+
+export interface DeltaProps {
+ /** From `percentDelta` or `pointDelta` (lib/delta). Null draws nothing. */
+ value: DeltaValue | null | undefined;
+ /** False for metrics where a rise is bad news: bounce rate, load time, errors. */
+ upIsGood?: boolean;
+ className?: string;
+}
+
+/**
+ * Change against the comparison period: an arrow, the magnitude, and a colour
+ * that says whether the move is good. Renders nothing without a value, so a
+ * page can pass the previous period straight through and lose its deltas when
+ * the comparison is turned off.
+ */
+export function Delta({ value, upIsGood = true, className }: DeltaProps) {
+ const t = useExtracted();
+ if (!value) return null;
+
+ const { direction } = value;
+ const classes = cn(
+ "inline-flex shrink-0 items-center gap-0.5 whitespace-nowrap text-xs font-medium tabular-nums",
+ TONE_CLASS[deltaTone(direction, upIsGood)],
+ className
+ );
+
+ if (direction === "none") {
+ const label = t("No data in the comparison period");
+ return (
+ <span className={classes} title={label}>
+ <span aria-hidden="true">{value.text}</span>
+ <span className="sr-only">{label}</span>
+ </span>
+ );
+ }
+
+ const Icon = direction === "up" ? ArrowUp : direction === "down" ? ArrowDown : Minus;
+
+ // The arrow carries the sign for sighted readers; assistive tech gets the
+ // signed figure instead of an unlabelled icon.
+ return (
+ <span className={classes}>
+ <Icon className="h-3 w-3" aria-hidden="true" />
+ <span aria-hidden="true">{value.text}</span>
+ <span className="sr-only">{value.signed}</span>
+ </span>
+ );
+}
diff --git a/client/src/components/site/InsightRow.tsx b/client/src/components/site/InsightRow.tsx
new file mode 100644
index 000000000..c5f86320c
--- /dev/null
+++ b/client/src/components/site/InsightRow.tsx
@@ -0,0 +1,30 @@
+import { Sparkles } from "lucide-react";
+import { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+
+export interface InsightRowProps {
+ /** One plain sentence about what changed and why it matters. */
+ children: ReactNode;
+ /** One follow-up, usually a `<Button variant="ghost" size="sm">`. */
+ action?: ReactNode;
+ className?: string;
+}
+
+/**
+ * A single observation above a page's content. Neutral on purpose: no accent
+ * tint, no border stripe. A page shows one or two at most.
+ */
+export function InsightRow({ children, action, className }: InsightRowProps) {
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-2.5 rounded-lg border border-neutral-100 bg-white px-3 py-2 text-sm dark:border-neutral-850 dark:bg-neutral-900",
+ className
+ )}
+ >
+ <Sparkles className="h-4 w-4 shrink-0 text-neutral-500 dark:text-neutral-400" aria-hidden="true" />
+ <div className="min-w-0 flex-1 text-neutral-700 dark:text-neutral-200">{children}</div>
+ {action}
+ </div>
+ );
+}
diff --git a/client/src/components/site/PivotActions.test.tsx b/client/src/components/site/PivotActions.test.tsx
new file mode 100644
index 000000000..523294a3c
--- /dev/null
+++ b/client/src/components/site/PivotActions.test.tsx
@@ -0,0 +1,252 @@
+import { Filter } from "@rybbit/shared";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { DEFAULT_COMPARISON } from "@/components/DateSelector/types";
+import { analyticsParsers } from "@/lib/parsers";
+import { useStore } from "@/lib/store";
+import { PivotActions, PivotButton } from "./PivotActions";
+
+const mocks = vi.hoisted(() => ({
+ search: "",
+ replayAvailable: true,
+ canWriteSegments: true,
+ segmentDialog: vi.fn(),
+}));
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => (message: string) => message,
+}));
+
+vi.mock("next/navigation", () => ({
+ useSearchParams: () => new URLSearchParams(mocks.search),
+}));
+
+vi.mock("next/link", () => ({
+ default: ({ href, children, prefetch, ...props }: { href: string; children: ReactNode; prefetch?: boolean }) => (
+ // jsdom cannot navigate; following the link is the router's job, not what is under test.
+ <a href={href} data-prefetch={String(prefetch)} {...props} onClick={event => event.preventDefault()}>
+ {children}
+ </a>
+ ),
+}));
+
+vi.mock("@/hooks/useReplayAvailable", () => ({
+ useReplayAvailable: () => mocks.replayAvailable,
+}));
+
+vi.mock("@/hooks/usePermissions", () => ({
+ useCanOnSite: () => mocks.canWriteSegments,
+}));
+
+vi.mock("@/app/[site]/components/SubHeader/Filters/SegmentDialog", () => ({
+ SegmentDialog: (props: { open: boolean; onOpenChange: (open: boolean) => void }) => {
+ mocks.segmentDialog(props);
+ return props.open ? (
+ <div role="dialog">
+ <input aria-label="Name" />
+ <button type="button" onClick={() => props.onOpenChange(false)}>
+ Close
+ </button>
+ </div>
+ ) : null;
+ },
+}));
+
+const country: Filter = { parameter: "country", type: "equals", value: ["US"] };
+const pricing: Filter = { parameter: "pathname", type: "equals", value: ["/pricing"] };
+const signup: Filter = { parameter: "event_name", type: "equals", value: ["signup"] };
+
+beforeEach(() => {
+ mocks.search = "";
+ mocks.replayAvailable = true;
+ mocks.canWriteSegments = true;
+ useStore.setState({ site: "42", privateKey: null, timezone: "UTC", filters: [country], segmentId: null });
+ useStore.getState().setComparison(DEFAULT_COMPARISON);
+ useStore.getState().setTime({ mode: "range", startDate: "2026-09-01", endDate: "2026-09-30" });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+const link = (name: string) => screen.getByRole("link", { name }) as HTMLAnchorElement;
+const filtersOf = (anchor: HTMLAnchorElement) =>
+ analyticsParsers.filters.parse(new URL(anchor.href).searchParams.get("filters") ?? "[]");
+
+describe("PivotActions", () => {
+ it("links to Sessions, Users and Replays by default, without Save segment", () => {
+ render(<PivotActions filters={[pricing]} />);
+
+ expect(screen.getAllByRole("link").map(anchor => anchor.textContent)).toEqual(["Sessions", "Users", "Replays"]);
+ expect(screen.queryByRole("button", { name: "Save segment" })).toBeNull();
+ });
+
+ it("carries the current filters narrowed by the row's, and the current period", () => {
+ render(<PivotActions filters={[pricing]} />);
+ const sessions = link("Sessions");
+ const url = new URL(sessions.href);
+
+ expect(url.pathname).toBe("/42/sessions");
+ expect(filtersOf(sessions)).toEqual([country, pricing]);
+ expect(url.searchParams.get("startDate")).toBe("2026-09-01");
+ expect(url.searchParams.get("endDate")).toBe("2026-09-30");
+ expect(new URL(link("Users").href).pathname).toBe("/42/users");
+ expect(new URL(link("Replays").href).pathname).toBe("/42/replay");
+ });
+
+ it("links to the page's whole population when the row adds no filter", () => {
+ render(<PivotActions />);
+
+ expect(filtersOf(link("Sessions"))).toEqual([country]);
+ });
+
+ it("stays inside a private link and stays embedded", () => {
+ useStore.setState({ privateKey: "abcdef123456" });
+ mocks.search = "embed=true&tab=entry";
+ render(<PivotActions filters={[pricing]} />);
+ const url = new URL(link("Sessions").href);
+
+ expect(url.pathname).toBe("/42/abcdef123456/sessions");
+ expect(url.searchParams.get("embed")).toBe("true");
+ expect(url.searchParams.has("tab")).toBe(false);
+ });
+
+ it("does not prefetch: a table draws one link per row and per target", () => {
+ render(<PivotActions filters={[pricing]} />);
+
+ expect(link("Sessions").dataset.prefetch).toBe("false");
+ });
+
+ it("leaves out a target that would drop the row's filter", () => {
+ render(<PivotActions filters={[signup]} />);
+
+ expect(screen.getAllByRole("link").map(anchor => anchor.textContent)).toEqual(["Sessions", "Replays"]);
+ });
+
+ it("leaves Replays out on a site without replay", () => {
+ mocks.replayAvailable = false;
+ render(<PivotActions filters={[pricing]} />);
+
+ expect(screen.getAllByRole("link").map(anchor => anchor.textContent)).toEqual(["Sessions", "Users"]);
+ });
+
+ it("hides Replays below the desktop breakpoint, like the sidebar", () => {
+ render(<PivotActions filters={[pricing]} />);
+ const classes = link("Replays").className.split(/\s+/);
+
+ expect(classes).toContain("hidden");
+ expect(classes).toContain("md:inline-flex");
+ expect(classes).not.toContain("inline-flex");
+ });
+
+ it("offers only the actions asked for, in the order given", () => {
+ render(<PivotActions filters={[pricing]} actions={["users", "sessions"]} />);
+
+ expect(screen.getAllByRole("link").map(anchor => anchor.textContent)).toEqual(["Users", "Sessions"]);
+ });
+
+ it("keeps the label as the accessible name when only icons are drawn", () => {
+ render(<PivotActions filters={[pricing]} actions={["sessions"]} showLabels={false} />);
+ const sessions = link("Sessions");
+
+ expect(sessions.textContent).toBe("");
+ expect(sessions.getAttribute("title")).toBe("Sessions");
+ });
+
+ it("draws a page's own pivots after the standard ones", () => {
+ render(
+ <PivotActions filters={[pricing]} actions={["sessions"]}>
+ <PivotButton icon={<svg />} label="Journeys" href="/42/journeys" />
+ </PivotActions>
+ );
+
+ expect(screen.getAllByRole("link").map(anchor => anchor.textContent)).toEqual(["Sessions", "Journeys"]);
+ });
+
+ it("opens the segment dialog pre-filled with the current and the row's filters, without applying it", () => {
+ render(<PivotActions filters={[pricing]} actions={["segment"]} />);
+
+ expect(screen.queryByRole("dialog")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Save segment" }));
+
+ expect(screen.getByRole("dialog")).toBeTruthy();
+ expect(mocks.segmentDialog).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ open: true,
+ siteId: "42",
+ initialFilters: [country, pricing],
+ applyOnCreate: false,
+ })
+ );
+ });
+
+ it("offers Save segment for any filter, since a segment is not tied to a page", () => {
+ render(<PivotActions filters={[signup]} actions={["users", "segment"]} />);
+
+ expect(screen.queryByRole("link")).toBeNull();
+ expect(screen.getByRole("button", { name: "Save segment" })).toBeTruthy();
+ });
+
+ it("leaves Save segment out for a viewer who cannot write segments", () => {
+ mocks.canWriteSegments = false;
+ render(<PivotActions filters={[pricing]} actions={["sessions", "segment"]} />);
+
+ expect(screen.queryByRole("button", { name: "Save segment" })).toBeNull();
+ expect(link("Sessions")).toBeTruthy();
+ });
+
+ it("leaves Save segment out on a private link, which is read-only", () => {
+ useStore.setState({ privateKey: "abcdef123456" });
+ render(<PivotActions filters={[pricing]} actions={["segment"]} />);
+
+ expect(screen.queryByRole("button", { name: "Save segment" })).toBeNull();
+ });
+
+ describe("inside a clickable row", () => {
+ const onRowClick = vi.fn();
+ const onRowKeyDown = vi.fn();
+ const renderInRow = () =>
+ render(
+ <div role="button" tabIndex={0} onClick={onRowClick} onKeyDown={onRowKeyDown}>
+ <PivotActions filters={[pricing]} actions={["sessions", "segment"]} />
+ </div>
+ );
+
+ it("does not hand a click on a pivot to the row", () => {
+ renderInRow();
+ fireEvent.click(link("Sessions"));
+ fireEvent.click(screen.getByRole("button", { name: "Save segment" }));
+
+ expect(onRowClick).not.toHaveBeenCalled();
+ });
+
+ it("does not hand the row the keys that activate a pivot", () => {
+ renderInRow();
+ fireEvent.keyDown(link("Sessions"), { key: "Enter" });
+ fireEvent.keyDown(screen.getByRole("button", { name: "Save segment" }), { key: " " });
+
+ expect(onRowKeyDown).not.toHaveBeenCalled();
+ });
+
+ it("lets every other key through to the row and the page", () => {
+ renderInRow();
+ fireEvent.keyDown(link("Sessions"), { key: "ArrowDown" });
+
+ expect(onRowKeyDown).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps clicks and typing inside the segment dialog away from the row", () => {
+ renderInRow();
+ fireEvent.click(screen.getByRole("button", { name: "Save segment" }));
+
+ fireEvent.keyDown(screen.getByLabelText("Name"), { key: " " });
+ fireEvent.click(screen.getByRole("button", { name: "Close" }));
+
+ expect(onRowKeyDown).not.toHaveBeenCalled();
+ expect(onRowClick).not.toHaveBeenCalled();
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+ });
+});
diff --git a/client/src/components/site/PivotActions.tsx b/client/src/components/site/PivotActions.tsx
new file mode 100644
index 000000000..544994f06
--- /dev/null
+++ b/client/src/components/site/PivotActions.tsx
@@ -0,0 +1,182 @@
+"use client";
+
+import { Filter } from "@rybbit/shared";
+import { BookmarkPlus, Rewind, User, Video } from "lucide-react";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { KeyboardEvent, MouseEvent, ReactNode, useState } from "react";
+import { SegmentDialog } from "@/app/[site]/components/SubHeader/Filters/SegmentDialog";
+import { Button } from "@/components/ui/button";
+import { useCanOnSite } from "@/hooks/usePermissions";
+import { usePivotHref } from "@/hooks/usePivotHref";
+import { useReplayAvailable } from "@/hooks/useReplayAvailable";
+import { canPivot, mergeFilters } from "@/lib/pivots";
+import { useStore } from "@/lib/store";
+import { cn } from "@/lib/utils";
+
+export type PivotAction = "sessions" | "users" | "replays" | "segment";
+
+const DEFAULT_ACTIONS: PivotAction[] = ["sessions", "users", "replays"];
+
+export interface PivotButtonProps {
+ /** A 16px icon. The button sizes it. */
+ icon: ReactNode;
+ label: string;
+ /** Renders a link. Without it the button calls `onClick`. */
+ href?: string;
+ onClick?: () => void;
+ /** False draws the icon alone; the label stays as the accessible name and tooltip. */
+ showLabel?: boolean;
+ className?: string;
+}
+
+/**
+ * One quiet pivot. `PivotActions` draws the standard four with it; a page
+ * passes its own (Journeys, Funnel, Goal) as children of `PivotActions`.
+ */
+export function PivotButton({ icon, label, href, onClick, showLabel = true, className }: PivotButtonProps) {
+ const classes = cn("gap-1 font-normal text-neutral-600 dark:text-neutral-300", className);
+ const name = showLabel ? undefined : label;
+ const content = (
+ <>
+ {icon}
+ {showLabel && label}
+ </>
+ );
+
+ if (href) {
+ return (
+ <Button asChild variant="ghost" size="xs" className={classes}>
+ {/* One link per row and per target: prefetching them all would flood the router. */}
+ <Link href={href} prefetch={false} aria-label={name} title={name} onClick={onClick}>
+ {content}
+ </Link>
+ </Button>
+ );
+ }
+
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ className={classes}
+ aria-label={name}
+ title={name}
+ onClick={onClick}
+ >
+ {content}
+ </Button>
+ );
+}
+
+function ReplaysPivot({ href, label, showLabel }: { href: string; label: string; showLabel: boolean }) {
+ const replayAvailable = useReplayAvailable();
+ if (!replayAvailable) return null;
+
+ // Desktop only, like the sidebar's Replay item.
+ return (
+ <PivotButton icon={<Video />} label={label} href={href} showLabel={showLabel} className="hidden md:inline-flex" />
+ );
+}
+
+function SaveSegmentPivot({ filters, label, showLabel }: { filters: Filter[]; label: string; showLabel: boolean }) {
+ const site = useStore(state => state.site);
+ const privateKey = useStore(state => state.privateKey);
+ const currentFilters = useStore(state => state.filters);
+ const canWriteSegments = useCanOnSite("segments:write", site);
+ const [open, setOpen] = useState(false);
+
+ // The same rule as the Filter popover's Segments tab: public viewers hold no
+ // permissions, and a private link is read-only even for members.
+ if (privateKey || !canWriteSegments) return null;
+
+ return (
+ <>
+ <PivotButton icon={<BookmarkPlus />} label={label} showLabel={showLabel} onClick={() => setOpen(true)} />
+ <SegmentDialog
+ open={open}
+ onOpenChange={setOpen}
+ siteId={site}
+ initialFilters={mergeFilters(currentFilters, filters)}
+ applyOnCreate={false}
+ />
+ </>
+ );
+}
+
+export interface PivotActionsProps {
+ /**
+ * The filters that identify the aggregate these actions belong to, e.g.
+ * `[{ parameter: "pathname", type: "equals", value: ["/pricing"] }]`. They
+ * are applied on top of the page's current filters. Leave empty for the
+ * page's whole population.
+ */
+ filters?: Filter[];
+ /** Which actions to offer, in order. Defaults to Sessions, Users and Replays. */
+ actions?: PivotAction[];
+ /** False draws icons only, for tight rows. */
+ showLabels?: boolean;
+ /** Page-specific pivots, drawn after the standard ones. Use `PivotButton`. */
+ children?: ReactNode;
+ className?: string;
+}
+
+const stopClick = (event: MouseEvent) => event.stopPropagation();
+
+// Enter and Space activate the focused pivot or type into the segment dialog; a
+// row that toggles on them would call preventDefault and swallow both. Other
+// keys keep bubbling so page-level shortcuts still work.
+const stopActivationKeys = (event: KeyboardEvent) => {
+ if (event.key === "Enter" || event.key === " ") event.stopPropagation();
+};
+
+/**
+ * The doorway from an aggregate number to the people behind it: quiet links to
+ * the Sessions, Users and Replay pages with the current period and filters
+ * narrowed by `filters`, and a button that saves those filters as a segment.
+ *
+ * An action is left out when it cannot be honoured: a target that would drop
+ * one of `filters` (see `canPivot`), Replays on a site without replay, Save
+ * segment for a viewer who cannot write segments.
+ *
+ * Safe inside a clickable row: clicks and activation keys do not reach the
+ * row, including those from inside the segment dialog.
+ */
+export function PivotActions({
+ filters = [],
+ actions = DEFAULT_ACTIONS,
+ showLabels = true,
+ children,
+ className,
+}: PivotActionsProps) {
+ const t = useExtracted();
+ const pivotHref = usePivotHref();
+
+ return (
+ // Not interactive itself: the handlers only keep its buttons' events from a clickable ancestor.
+ <div
+ className={cn("flex flex-wrap items-center gap-0.5", className)}
+ onClick={stopClick}
+ onKeyDown={stopActivationKeys}
+ >
+ {actions.map(action => {
+ if (action === "segment") {
+ return <SaveSegmentPivot key={action} filters={filters} label={t("Save segment")} showLabel={showLabels} />;
+ }
+ if (!canPivot(action, filters)) return null;
+
+ const href = pivotHref(action, filters);
+ if (action === "replays") {
+ return <ReplaysPivot key={action} href={href} label={t("Replays")} showLabel={showLabels} />;
+ }
+ return action === "sessions" ? (
+ <PivotButton key={action} icon={<Rewind />} label={t("Sessions")} href={href} showLabel={showLabels} />
+ ) : (
+ <PivotButton key={action} icon={<User />} label={t("Users")} href={href} showLabel={showLabels} />
+ );
+ })}
+ {children}
+ </div>
+ );
+}
diff --git a/client/src/components/site/StatBand.test.tsx b/client/src/components/site/StatBand.test.tsx
new file mode 100644
index 000000000..cc2e444f1
--- /dev/null
+++ b/client/src/components/site/StatBand.test.tsx
@@ -0,0 +1,171 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { percentDelta, pointDelta } from "@/lib/delta";
+import { Delta } from "./Delta";
+import { StatBand, StatBandCell } from "./StatBand";
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => (message: string) => message,
+}));
+
+afterEach(cleanup);
+
+const cells = (count: number): StatBandCell[] =>
+ Array.from({ length: count }, (_, index) => ({ label: `Metric ${index + 1}`, value: String(index + 1) }));
+
+const grid = (container: HTMLElement) => container.querySelector(".grid")!;
+const classList = (value: string) => value.split(/\s+/).filter(Boolean).sort();
+
+describe("StatBand", () => {
+ it("draws a label, a value and its hover text for each cell", () => {
+ render(<StatBand cells={[{ label: "Sessions", value: "84.2k", title: "84,210" }]} />);
+
+ expect(screen.getByText("Sessions")).toBeTruthy();
+ expect(screen.getByText("84.2k").getAttribute("title")).toBe("84,210");
+ });
+
+ it("skips falsy cells so one can be conditional inline", () => {
+ const { container } = render(<StatBand cells={[{ label: "Sessions", value: "1" }, false, null, undefined]} />);
+
+ expect(grid(container).children).toHaveLength(1);
+ });
+
+ it("renders nothing without cells", () => {
+ const { container } = render(<StatBand cells={[false]} />);
+
+ expect(container.firstChild).toBeNull();
+ });
+
+ it("replaces every value with a skeleton while loading, keeping the labels", () => {
+ const { container } = render(
+ <StatBand isLoading cells={[{ label: "Sessions", value: "84.2k", delta: percentDelta(110, 100) }]} />
+ );
+
+ expect(screen.getByText("Sessions")).toBeTruthy();
+ expect(screen.queryByText("84.2k")).toBeNull();
+ expect(screen.queryByText("10.0%")).toBeNull();
+ expect(container.querySelectorAll(".animate-pulse")).toHaveLength(1);
+ });
+
+ it("lets one cell load on its own", () => {
+ render(
+ <StatBand
+ cells={[
+ { label: "Sessions", value: "84.2k" },
+ { label: "Users", value: "61.5k", isLoading: true },
+ ]}
+ />
+ );
+
+ expect(screen.getByText("84.2k")).toBeTruthy();
+ expect(screen.queryByText("61.5k")).toBeNull();
+ });
+
+ it("holds the sub line's place while loading", () => {
+ const { container } = render(<StatBand isLoading cells={[{ label: "Sessions", value: "1", sub: "vs 74.9k" }]} />);
+
+ expect(screen.queryByText("vs 74.9k")).toBeNull();
+ expect(container.querySelectorAll(".animate-pulse")).toHaveLength(2);
+ });
+
+ it("shows the delta and the sub line beside a loaded value", () => {
+ render(
+ <StatBand cells={[{ label: "Bounce rate", value: "41.2%", delta: pointDelta(41.2, 43.1), sub: "vs 43.1%" }]} />
+ );
+
+ expect(screen.getByText("1.9 pp")).toBeTruthy();
+ expect(screen.getByText("vs 43.1%")).toBeTruthy();
+ });
+
+ it("lays six cells out 2, 3 and 6 to a row, as the user profile band always has", () => {
+ const { container } = render(<StatBand cells={cells(6)} />);
+
+ expect(classList(grid(container).className)).toEqual(
+ classList("grid grid-cols-2 gap-px bg-neutral-100 dark:bg-neutral-850 sm:grid-cols-3 lg:grid-cols-6")
+ );
+ expect(grid(container).lastElementChild!.className).not.toContain("col-span");
+ });
+
+ it("lays four cells out 2 and 4 to a row", () => {
+ const { container } = render(<StatBand cells={cells(4)} />);
+
+ expect(grid(container).className).toContain("grid-cols-2");
+ expect(grid(container).className).toContain("lg:grid-cols-4");
+ expect(grid(container).className).not.toContain("sm:grid-cols");
+ });
+
+ it("stretches the last of five cells so no row is left short", () => {
+ const { container } = render(<StatBand cells={cells(5)} />);
+ const last = grid(container).lastElementChild!.className;
+
+ // 2 to a row leaves one over, 3 to a row leaves two: the last cell spans two columns in both.
+ expect(last).toContain("col-span-2");
+ expect(last).not.toContain("sm:col-span");
+ expect(last).toContain("lg:col-span-1");
+ expect(grid(container).firstElementChild!.className).not.toContain("col-span");
+ });
+
+ it("honours an explicit column count", () => {
+ const { container } = render(<StatBand cells={cells(8)} columns={4} />);
+
+ expect(grid(container).className).toContain("lg:grid-cols-4");
+ expect(grid(container).lastElementChild!.className).not.toContain("col-span");
+ });
+
+ it("caps the default at six to a row and fills the row a seventh cell starts", () => {
+ const { container } = render(<StatBand cells={cells(7)} />);
+ const last = grid(container).lastElementChild!.className;
+
+ expect(grid(container).className).toContain("lg:grid-cols-6");
+ expect(last).toContain("col-span-2");
+ expect(last).toContain("sm:col-span-3");
+ expect(last).toContain("lg:col-span-6");
+ });
+});
+
+describe("Delta", () => {
+ it("draws nothing without a value", () => {
+ const { container } = render(<Delta value={percentDelta(10, undefined)} />);
+
+ expect(container.firstChild).toBeNull();
+ });
+
+ it("paints a rise green and reads out the signed figure", () => {
+ const { container } = render(<Delta value={percentDelta(1124, 1000)} />);
+
+ expect(container.firstElementChild!.className).toContain("text-emerald-600");
+ expect(screen.getByText("12.4%").getAttribute("aria-hidden")).toBe("true");
+ expect(screen.getByText("+12.4%").className).toContain("sr-only");
+ });
+
+ it("paints a fall red", () => {
+ const { container } = render(<Delta value={percentDelta(951, 1000)} />);
+
+ expect(container.firstElementChild!.className).toContain("text-red-600");
+ expect(screen.getByText("-4.9%")).toBeTruthy();
+ });
+
+ it("flips the colours for a metric where up is bad", () => {
+ const rise = render(<Delta value={pointDelta(43.1, 41.2)} upIsGood={false} />);
+ expect(rise.container.firstElementChild!.className).toContain("text-red-600");
+ rise.unmount();
+
+ const fall = render(<Delta value={pointDelta(41.2, 43.1)} upIsGood={false} />);
+ expect(fall.container.firstElementChild!.className).toContain("text-emerald-600");
+ });
+
+ it("is neutral when nothing changed, whatever direction is good", () => {
+ const { container } = render(<Delta value={pointDelta(47.1, 47.1)} upIsGood={false} />);
+
+ expect(container.firstElementChild!.className).toContain("text-neutral-500");
+ expect(screen.getAllByText("0.0 pp")).toHaveLength(2);
+ });
+
+ it("is neutral and says why when the comparison period is empty", () => {
+ const { container } = render(<Delta value={percentDelta(42, 0)} />);
+
+ expect(container.firstElementChild!.className).toContain("text-neutral-500");
+ expect(container.querySelector("svg")).toBeNull();
+ expect(screen.getByText("No data in the comparison period")).toBeTruthy();
+ });
+});
diff --git a/client/src/components/site/StatBand.tsx b/client/src/components/site/StatBand.tsx
new file mode 100644
index 000000000..89a58e7f2
--- /dev/null
+++ b/client/src/components/site/StatBand.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { ReactNode } from "react";
+import { Skeleton } from "@/components/ui/skeleton";
+import { DeltaValue } from "@/lib/delta";
+import { cn } from "@/lib/utils";
+import { Delta } from "./Delta";
+
+export interface StatBandCell {
+ /** React key. Defaults to the label. */
+ id?: string;
+ /** A 12px icon, e.g. `<Files className="h-3 w-3" />`. */
+ icon?: ReactNode;
+ label: string;
+ value: ReactNode;
+ /** Change against the comparison period, from `percentDelta` or `pointDelta` (lib/delta). */
+ delta?: DeltaValue | null;
+ /** False for metrics where a rise is bad news. Only read with `delta`. */
+ upIsGood?: boolean;
+ /** One quiet line under the value. */
+ sub?: ReactNode;
+ /** Hover text for the value, e.g. the unrounded number. */
+ title?: string;
+ /** Overrides the band's `isLoading` for this cell. */
+ isLoading?: boolean;
+}
+
+export type StatBandColumns = 1 | 2 | 3 | 4 | 5 | 6;
+
+// Cells per row at each width, for each wide-screen column count: [base, sm, lg].
+const ROW_SIZES: Record<StatBandColumns, readonly [number, number, number]> = {
+ 1: [1, 1, 1],
+ 2: [2, 2, 2],
+ 3: [2, 3, 3],
+ 4: [2, 2, 4],
+ 5: [2, 3, 5],
+ 6: [2, 3, 6],
+};
+
+// Indexed by [breakpoint][count]. Written out in full so Tailwind sees every class.
+const GRID_COLUMNS = [
+ ["", "grid-cols-1", "grid-cols-2", "grid-cols-3", "grid-cols-4", "grid-cols-5", "grid-cols-6"],
+ ["", "sm:grid-cols-1", "sm:grid-cols-2", "sm:grid-cols-3", "sm:grid-cols-4", "sm:grid-cols-5", "sm:grid-cols-6"],
+ ["", "lg:grid-cols-1", "lg:grid-cols-2", "lg:grid-cols-3", "lg:grid-cols-4", "lg:grid-cols-5", "lg:grid-cols-6"],
+];
+const COLUMN_SPAN = [
+ ["", "col-span-1", "col-span-2", "col-span-3", "col-span-4", "col-span-5", "col-span-6"],
+ ["", "sm:col-span-1", "sm:col-span-2", "sm:col-span-3", "sm:col-span-4", "sm:col-span-5", "sm:col-span-6"],
+ ["", "lg:col-span-1", "lg:col-span-2", "lg:col-span-3", "lg:col-span-4", "lg:col-span-5", "lg:col-span-6"],
+];
+
+// A breakpoint repeats the one below it unless its count differs.
+const responsive = (lookup: string[][], counts: readonly number[]) =>
+ counts.map((count, breakpoint) => (count === counts[breakpoint - 1] ? "" : lookup[breakpoint][count])).join(" ");
+
+/**
+ * How many columns the last cell takes at each width so the last row is never
+ * short: an empty grid track would show the seam colour as a grey block.
+ */
+const lastCellSpans = (cellCount: number, rowSizes: readonly number[]) =>
+ rowSizes.map(size => (cellCount % size === 0 ? 1 : size - (cellCount % size) + 1));
+
+function Cell({ cell, isLoading, className }: { cell: StatBandCell; isLoading: boolean; className?: string }) {
+ return (
+ <div className={cn("min-w-0 bg-white px-3.5 py-2.5 dark:bg-neutral-900", className)}>
+ <div className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-neutral-500 dark:text-neutral-400">
+ {cell.icon}
+ <span className="truncate">{cell.label}</span>
+ </div>
+ {isLoading ? (
+ // As tall as the value line it stands in for, so the band does not grow when data arrives.
+ <div className="mt-0.5 flex h-6 items-center">
+ <Skeleton className="h-4 w-16 rounded" />
+ </div>
+ ) : (
+ <div className="mt-0.5 flex items-baseline gap-2">
+ <div
+ className={cn(
+ "min-w-0 truncate text-base font-semibold tabular-nums text-neutral-900 dark:text-neutral-50",
+ // Alone, the value takes the whole line; a delta sits right after it instead.
+ !cell.delta && "flex-1"
+ )}
+ title={cell.title}
+ >
+ {cell.value}
+ </div>
+ <Delta value={cell.delta} upIsGood={cell.upIsGood} />
+ </div>
+ )}
+ {cell.sub != null &&
+ (isLoading ? (
+ <div className="mt-0.5 flex h-4 items-center">
+ <Skeleton className="h-3 w-24 rounded" />
+ </div>
+ ) : (
+ <div className="mt-0.5 truncate text-xs text-neutral-500 dark:text-neutral-400">{cell.sub}</div>
+ ))}
+ </div>
+ );
+}
+
+export interface StatBandProps {
+ /** Falsy entries are skipped, so a cell can be conditional inline. */
+ cells: (StatBandCell | false | null | undefined)[];
+ /** Shows a skeleton in place of every value. */
+ isLoading?: boolean;
+ /**
+ * Cells per row on a wide screen; narrower screens wrap to 3 and then 2.
+ * Defaults to the number of cells, up to 6.
+ */
+ columns?: StatBandColumns;
+ className?: string;
+}
+
+/**
+ * The summary strip that opens a site page: flat cells separated by hairline
+ * seams (gap-px over the border colour), each a label, a figure, and
+ * optionally its change against the comparison period and one line of context.
+ */
+export function StatBand({ cells, isLoading = false, columns, className }: StatBandProps) {
+ const visible = cells.filter((cell): cell is StatBandCell => !!cell);
+ if (visible.length === 0) return null;
+
+ const rowSizes = ROW_SIZES[columns ?? (Math.min(visible.length, 6) as StatBandColumns)];
+ const spans = lastCellSpans(visible.length, rowSizes);
+ const lastCellSpan = spans.some(span => span > 1) ? responsive(COLUMN_SPAN, spans) : undefined;
+
+ return (
+ <div className={cn("overflow-hidden rounded-lg border border-neutral-100 dark:border-neutral-850", className)}>
+ <div className={cn("grid gap-px bg-neutral-100 dark:bg-neutral-850", responsive(GRID_COLUMNS, rowSizes))}>
+ {visible.map((cell, index) => (
+ <Cell
+ key={cell.id ?? cell.label}
+ cell={cell}
+ isLoading={cell.isLoading ?? isLoading}
+ className={index === visible.length - 1 ? lastCellSpan : undefined}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/hooks/usePivotHref.ts b/client/src/hooks/usePivotHref.ts
new file mode 100644
index 000000000..0db112b66
--- /dev/null
+++ b/client/src/hooks/usePivotHref.ts
@@ -0,0 +1,31 @@
+import { Filter } from "@rybbit/shared";
+import { useSearchParams } from "next/navigation";
+import { useShallow } from "zustand/react/shallow";
+import { buildPivotHref, PivotTarget } from "../lib/pivots";
+import { useStore } from "../lib/store";
+
+/**
+ * Returns a builder for pivot links from the page being viewed: the Sessions,
+ * Users or Replay page of the current site, with the current period and
+ * private-link key, and the current filters narrowed by `extraFilters`.
+ *
+ * Check `canPivot(target, extraFilters)` (lib/pivots) before offering a link:
+ * not every target can honour every filter.
+ */
+export function usePivotHref(): (target: PivotTarget, extraFilters?: Filter[]) => string {
+ const context = useStore(
+ useShallow(state => ({
+ site: state.site,
+ privateKey: state.privateKey,
+ time: state.time,
+ comparison: state.comparison,
+ bucket: state.bucket,
+ selectedStat: state.selectedStat,
+ filters: state.filters,
+ segmentId: state.segmentId,
+ }))
+ );
+ const search = useSearchParams();
+
+ return (target, extraFilters) => buildPivotHref(target, { ...context, search }, extraFilters);
+}
diff --git a/client/src/hooks/useReplayAvailable.ts b/client/src/hooks/useReplayAvailable.ts
new file mode 100644
index 000000000..710e5d7d1
--- /dev/null
+++ b/client/src/hooks/useReplayAvailable.ts
@@ -0,0 +1,25 @@
+import { useGetSite } from "../api/admin/hooks/useSites";
+import { useStripeSubscription } from "../lib/subscription/useStripeSubscription";
+import { useAppEnv } from "./useIsProduction";
+
+/**
+ * Whether the current site has a Replay page to link to. This is the site
+ * sidebar's rule for showing its Replay item (app/[site]/components/Sidebar):
+ * web sites only, not on AppSumo plans, not on the demo, and not until the
+ * subscription has loaded. Keep the two in step.
+ *
+ * The sidebar also hides the item below `md`; a link that relies on this hook
+ * should do the same.
+ */
+export function useReplayAvailable(): boolean {
+ const { data: site } = useGetSite();
+ const { data: subscription, isLoading: isSubscriptionLoading } = useStripeSubscription();
+ const appEnv = useAppEnv();
+
+ return (
+ site?.type !== "mobile" &&
+ !subscription?.planName?.startsWith("appsumo") &&
+ !isSubscriptionLoading &&
+ appEnv !== "demo"
+ );
+}
diff --git a/client/src/lib/delta.test.ts b/client/src/lib/delta.test.ts
new file mode 100644
index 000000000..0edd7962c
--- /dev/null
+++ b/client/src/lib/delta.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from "vitest";
+import {
+ deltaTone,
+ formatPercentChange,
+ formatPointChange,
+ NO_DELTA_TEXT,
+ percentChange,
+ percentDelta,
+ pointDelta,
+} from "./delta";
+
+describe("percentChange", () => {
+ it("is the relative change in percent", () => {
+ expect(percentChange(120, 100)).toBe(20);
+ expect(percentChange(75, 100)).toBe(-25);
+ expect(percentChange(100, 100)).toBe(0);
+ });
+
+ it("has no answer without a baseline", () => {
+ expect(percentChange(10, 0)).toBeNull();
+ expect(percentChange(0, 0)).toBeNull();
+ expect(percentChange(10, Number.NaN)).toBeNull();
+ expect(percentChange(Number.POSITIVE_INFINITY, 10)).toBeNull();
+ });
+});
+
+describe("formatPercentChange", () => {
+ it("signs the change and keeps one decimal by default", () => {
+ expect(formatPercentChange(12.44)).toBe("+12.4%");
+ expect(formatPercentChange(-3.06)).toBe("-3.1%");
+ expect(formatPercentChange(14)).toBe("+14.0%");
+ });
+
+ it("writes no sign on a change that rounds to zero", () => {
+ expect(formatPercentChange(0)).toBe("0.0%");
+ expect(formatPercentChange(0.04)).toBe("0.0%");
+ expect(formatPercentChange(-0.04)).toBe("0.0%");
+ });
+
+ it("honours the decimals option", () => {
+ expect(formatPercentChange(12.44, { decimals: 0 })).toBe("+12%");
+ expect(formatPercentChange(-0.126, { decimals: 2 })).toBe("-0.13%");
+ });
+
+ it("caps a runaway percentage", () => {
+ expect(formatPercentChange(999)).toBe("+999.0%");
+ expect(formatPercentChange(4200)).toBe(">999%");
+ expect(formatPercentChange(-4200)).toBe("<-999%");
+ });
+});
+
+describe("formatPointChange", () => {
+ it('writes percentage points as "pp"', () => {
+ expect(formatPointChange(2.1)).toBe("+2.1 pp");
+ expect(formatPointChange(-0.33, { decimals: 2 })).toBe("-0.33 pp");
+ expect(formatPointChange(0)).toBe("0.0 pp");
+ expect(formatPointChange(-0.04)).toBe("0.0 pp");
+ });
+});
+
+describe("percentDelta", () => {
+ it("describes a rise", () => {
+ expect(percentDelta(1124, 1000)).toEqual({ direction: "up", text: "12.4%", signed: "+12.4%" });
+ });
+
+ it("describes a fall", () => {
+ expect(percentDelta(951, 1000)).toEqual({ direction: "down", text: "4.9%", signed: "-4.9%" });
+ });
+
+ it("is flat when the change rounds to nothing", () => {
+ expect(percentDelta(1000, 1000)).toEqual({ direction: "flat", text: "0.0%", signed: "0.0%" });
+ expect(percentDelta(10004, 10000)).toEqual({ direction: "flat", text: "0.0%", signed: "0.0%" });
+ expect(percentDelta(9996, 10000)).toEqual({ direction: "flat", text: "0.0%", signed: "0.0%" });
+ });
+
+ it("is flat when both periods are empty", () => {
+ expect(percentDelta(0, 0)).toEqual({ direction: "flat", text: "0.0%", signed: "0.0%" });
+ });
+
+ it("is the neutral no-baseline state when only the previous period is empty", () => {
+ expect(percentDelta(42, 0)).toEqual({ direction: "none", text: NO_DELTA_TEXT, signed: NO_DELTA_TEXT });
+ });
+
+ it("draws nothing when a side is missing", () => {
+ expect(percentDelta(42, undefined)).toBeNull();
+ expect(percentDelta(42, null)).toBeNull();
+ expect(percentDelta(undefined, 42)).toBeNull();
+ expect(percentDelta(42, Number.NaN)).toBeNull();
+ });
+
+ it("keeps a runaway rise readable beside its arrow", () => {
+ expect(percentDelta(5000, 100)).toEqual({ direction: "up", text: ">999%", signed: ">999%" });
+ });
+
+ it("honours the decimals option", () => {
+ expect(percentDelta(1124, 1000, { decimals: 0 })).toEqual({ direction: "up", text: "12%", signed: "+12%" });
+ });
+
+ it("measures against the size of a negative baseline", () => {
+ expect(percentDelta(-50, -100)).toEqual({ direction: "up", text: "50.0%", signed: "+50.0%" });
+ });
+});
+
+describe("pointDelta", () => {
+ it("subtracts two rates on the same percent scale", () => {
+ expect(pointDelta(43.3, 41.2)).toEqual({ direction: "up", text: "2.1 pp", signed: "+2.1 pp" });
+ expect(pointDelta(39.3, 41.2)).toEqual({ direction: "down", text: "1.9 pp", signed: "-1.9 pp" });
+ });
+
+ it("is flat when the change rounds to nothing", () => {
+ expect(pointDelta(47.12, 47.1)).toEqual({ direction: "flat", text: "0.0 pp", signed: "0.0 pp" });
+ });
+
+ it("has a real answer against a rate of zero", () => {
+ expect(pointDelta(4.73, 0, { decimals: 2 })).toEqual({ direction: "up", text: "4.73 pp", signed: "+4.73 pp" });
+ });
+
+ it("draws nothing when a side is missing", () => {
+ expect(pointDelta(41.2, undefined)).toBeNull();
+ expect(pointDelta(null, 41.2)).toBeNull();
+ });
+});
+
+describe("deltaTone", () => {
+ it("reads up as good by default", () => {
+ expect(deltaTone("up")).toBe("good");
+ expect(deltaTone("down")).toBe("bad");
+ });
+
+ it("flips for metrics where up is bad", () => {
+ expect(deltaTone("up", false)).toBe("bad");
+ expect(deltaTone("down", false)).toBe("good");
+ });
+
+ it("is neutral with no change or no baseline", () => {
+ expect(deltaTone("flat")).toBe("neutral");
+ expect(deltaTone("flat", false)).toBe("neutral");
+ expect(deltaTone("none")).toBe("neutral");
+ });
+});
diff --git a/client/src/lib/delta.ts b/client/src/lib/delta.ts
new file mode 100644
index 000000000..c1012a776
--- /dev/null
+++ b/client/src/lib/delta.ts
@@ -0,0 +1,127 @@
+/**
+ * Change against the comparison period, in the one shape every site page draws
+ * it: a direction for the arrow and the colour, the magnitude to print beside
+ * the arrow, and the signed form for sentences and screen readers.
+ */
+
+/**
+ * `flat` is a change that rounds to nothing; `none` is a comparison period
+ * with nothing in it, where a percentage has no meaning.
+ */
+export type DeltaDirection = "up" | "down" | "flat" | "none";
+
+export type DeltaTone = "good" | "bad" | "neutral";
+
+export interface DeltaValue {
+ direction: DeltaDirection;
+ /** Magnitude without a sign, to sit beside an arrow: "12.4%", "2.1 pp". */
+ text: string;
+ /** The same change with its sign, for prose and screen readers: "+12.4%", "-2.1 pp". */
+ signed: string;
+}
+
+export interface DeltaOptions {
+ /** Decimal places. Defaults to 1. */
+ decimals?: number;
+}
+
+/** Printed where a number would be when the comparison period is empty. */
+export const NO_DELTA_TEXT = "—";
+
+// Past this a percentage stops being read as a number, and the stat band needs
+// a bounded width.
+const MAX_PERCENT = 999;
+
+const isNumber = (value: number | null | undefined): value is number =>
+ typeof value === "number" && Number.isFinite(value);
+
+// Rounds first so the sign is taken from what is printed: -0.04 at one decimal
+// is "0.0", not "-0.0".
+const roundTo = (value: number, decimals: number) => {
+ const rounded = Number(value.toFixed(decimals));
+ return rounded === 0 ? 0 : rounded;
+};
+
+const sign = (value: number) => (value > 0 ? "+" : value < 0 ? "-" : "");
+
+const directionOf = (value: number): DeltaDirection => (value > 0 ? "up" : value < 0 ? "down" : "flat");
+
+/**
+ * Relative change in percent: 120 against 100 is 20. Null when there is no
+ * baseline to divide by.
+ */
+export function percentChange(current: number, previous: number): number | null {
+ if (!isNumber(current) || !isNumber(previous) || previous === 0) return null;
+ return ((current - previous) / Math.abs(previous)) * 100;
+}
+
+/** "+12.4%", "-3.1%", "0.0%"; anything past 999% is ">999%". */
+export function formatPercentChange(change: number, { decimals = 1 }: DeltaOptions = {}): string {
+ const rounded = roundTo(change, decimals);
+ if (Math.abs(rounded) > MAX_PERCENT) return `${rounded > 0 ? ">" : "<-"}${MAX_PERCENT}%`;
+ return `${sign(rounded)}${Math.abs(rounded).toFixed(decimals)}%`;
+}
+
+/** "+2.1 pp", "-0.3 pp", "0.0 pp". Percentage points are always written "pp". */
+export function formatPointChange(change: number, { decimals = 1 }: DeltaOptions = {}): string {
+ const rounded = roundTo(change, decimals);
+ return `${sign(rounded)}${Math.abs(rounded).toFixed(decimals)} pp`;
+}
+
+/**
+ * Percent change of a count or a duration against the comparison period.
+ *
+ * Null when either side is missing (comparison turned off, or the previous
+ * period still loading or failed): there is nothing to draw. A comparison
+ * period of zero gives the neutral `none` state rather than an invented
+ * percentage.
+ */
+export function percentDelta(
+ current: number | null | undefined,
+ previous: number | null | undefined,
+ { decimals = 1 }: DeltaOptions = {}
+): DeltaValue | null {
+ if (!isNumber(current) || !isNumber(previous)) return null;
+
+ // Nothing before and nothing now is no change; nothing before and something
+ // now has no baseline to be a percentage of.
+ if (previous === 0 && current !== 0) return { direction: "none", text: NO_DELTA_TEXT, signed: NO_DELTA_TEXT };
+
+ const change = roundTo(percentChange(current, previous) ?? 0, decimals);
+ const signed = formatPercentChange(change, { decimals });
+
+ return {
+ direction: directionOf(change),
+ // ">999%" keeps its marker beside the arrow; everything else drops the sign.
+ text: Math.abs(change) > MAX_PERCENT ? `>${MAX_PERCENT}%` : signed.replace(/^[+-]/, ""),
+ signed,
+ };
+}
+
+/**
+ * Change of a rate in percentage points. Both sides are percentages on the
+ * same 0–100 scale: 43.3 against 41.2 is "+2.1 pp".
+ *
+ * Null when either side is missing, as with `percentDelta`.
+ */
+export function pointDelta(
+ current: number | null | undefined,
+ previous: number | null | undefined,
+ { decimals = 1 }: DeltaOptions = {}
+): DeltaValue | null {
+ if (!isNumber(current) || !isNumber(previous)) return null;
+
+ const change = roundTo(current - previous, decimals);
+ const signed = formatPointChange(change, { decimals });
+
+ return { direction: directionOf(change), text: signed.replace(/^[+-]/, ""), signed };
+}
+
+/**
+ * Whether a move is good news. Up is good unless the metric says otherwise
+ * (bounce rate, load time, errors); no move and no baseline are neutral.
+ */
+export function deltaTone(direction: DeltaDirection, upIsGood = true): DeltaTone {
+ if (direction === "flat" || direction === "none") return "neutral";
+ return (direction === "up") === upIsGood ? "good" : "bad";
+}
diff --git a/client/src/lib/filterGroups.ts b/client/src/lib/filterGroups.ts
index 6661f3bb0..19bf0d176 100644
--- a/client/src/lib/filterGroups.ts
+++ b/client/src/lib/filterGroups.ts
@@ -63,12 +63,12 @@ export const JOURNEY_PAGE_FILTERS: FilterParameter[] = [
"city",
"device_type",
"referrer",
- // "channel",
- // "utm_source",
- // "utm_medium",
- // "utm_campaign",
- // "utm_term",
- // "utm_content",
+ "channel",
+ "utm_source",
+ "utm_medium",
+ "utm_campaign",
+ "utm_term",
+ "utm_content",
"entry_page",
"exit_page",
"dimensions",
diff --git a/client/src/lib/pivots.test.ts b/client/src/lib/pivots.test.ts
new file mode 100644
index 000000000..cf2ebb329
--- /dev/null
+++ b/client/src/lib/pivots.test.ts
@@ -0,0 +1,213 @@
+import { Filter } from "@rybbit/shared";
+import { describe, expect, it } from "vitest";
+import { analyticsParsers } from "./parsers";
+import { buildPivotHref, canPivot, mergeFilters, PivotContext } from "./pivots";
+import { urlParamsToComparison, urlParamsToTime } from "./time";
+
+const country: Filter = { parameter: "country", type: "equals", value: ["US", "CA"] };
+const device: Filter = { parameter: "device_type", type: "equals", value: ["Mobile"] };
+const pricing: Filter = { parameter: "pathname", type: "equals", value: ["/pricing"] };
+const signup: Filter = { parameter: "event_name", type: "equals", value: ["signup"] };
+
+const context: PivotContext = {
+ site: "42",
+ privateKey: null,
+ time: { mode: "range", startDate: "2026-09-01", endDate: "2026-09-30", wellKnown: "last-30-days" },
+ comparison: { mode: "previous" },
+ bucket: "day",
+ selectedStat: "users",
+ filters: [country],
+ segmentId: null,
+};
+
+// Reads an href back the way the destination page does: nuqs parsers, then the
+// same time and comparison deserialisers useSyncStateWithUrl calls.
+function readBack(href: string) {
+ const url = new URL(href, "https://app.example");
+ const raw = (key: keyof typeof analyticsParsers) => url.searchParams.get(key);
+ const filters = raw("filters");
+ const segment = raw("segment");
+ const start = raw("past_minutes_start");
+ const end = raw("past_minutes_end");
+
+ return {
+ pathname: url.pathname,
+ params: url.searchParams,
+ filters: filters === null ? null : analyticsParsers.filters.parse(filters),
+ segment: segment === null ? null : analyticsParsers.segment.parse(segment),
+ time: urlParamsToTime(
+ {
+ timeMode: raw("timeMode"),
+ wellKnown: raw("wellKnown"),
+ day: raw("day"),
+ startDate: raw("startDate"),
+ endDate: raw("endDate"),
+ startTime: raw("startTime"),
+ endTime: raw("endTime"),
+ week: raw("week"),
+ month: raw("month"),
+ year: raw("year"),
+ past_minutes_start: start === null ? null : Number(start),
+ past_minutes_end: end === null ? null : Number(end),
+ },
+ "UTC"
+ ),
+ comparison: urlParamsToComparison({
+ compare: raw("compare"),
+ compareStart: raw("compareStart"),
+ compareEnd: raw("compareEnd"),
+ }),
+ };
+}
+
+describe("mergeFilters", () => {
+ it("appends an extra on a new parameter", () => {
+ expect(mergeFilters([country], [pricing])).toEqual([country, pricing]);
+ });
+
+ it("replaces a current filter on the same parameter and operator, in place", () => {
+ const us: Filter = { parameter: "country", type: "equals", value: ["US"] };
+
+ expect(mergeFilters([country, device], [us])).toEqual([us, device]);
+ });
+
+ it("keeps a current filter on the same parameter with a different operator", () => {
+ const notDocs: Filter = { parameter: "pathname", type: "not_contains", value: ["/docs"] };
+
+ expect(mergeFilters([notDocs], [pricing])).toEqual([notDocs, pricing]);
+ });
+
+ it("applies several extras in order", () => {
+ expect(mergeFilters([], [pricing, device])).toEqual([pricing, device]);
+ });
+
+ it("returns the current filters when there is nothing to add, without mutating them", () => {
+ const current = [country];
+
+ expect(mergeFilters(current, [])).toEqual([country]);
+ mergeFilters(current, [pricing]);
+ expect(current).toEqual([country]);
+ });
+});
+
+describe("canPivot", () => {
+ it("offers every target when the aggregate adds no filter", () => {
+ expect(canPivot("sessions", [])).toBe(true);
+ expect(canPivot("users", [])).toBe(true);
+ expect(canPivot("replays", [])).toBe(true);
+ });
+
+ it("offers Sessions for a page or an event", () => {
+ expect(canPivot("sessions", [pricing])).toBe(true);
+ expect(canPivot("sessions", [signup])).toBe(true);
+ });
+
+ it("does not offer Users for an event: the users list would drop the filter", () => {
+ expect(canPivot("users", [pricing])).toBe(true);
+ expect(canPivot("users", [signup])).toBe(false);
+ expect(canPivot("users", [pricing, signup])).toBe(false);
+ });
+
+ it("offers Replays for any filter: the replay list sends them all", () => {
+ expect(canPivot("replays", [pricing, signup])).toBe(true);
+ expect(canPivot("replays", [{ parameter: "timezone", type: "equals", value: ["Europe/Berlin"] }])).toBe(true);
+ });
+
+ it("does not offer Sessions for a parameter the sessions list drops", () => {
+ expect(canPivot("sessions", [{ parameter: "timezone", type: "equals", value: ["Europe/Berlin"] }])).toBe(false);
+ });
+});
+
+describe("buildPivotHref", () => {
+ it("leads to the target page of the same site", () => {
+ expect(readBack(buildPivotHref("sessions", context)).pathname).toBe("/42/sessions");
+ expect(readBack(buildPivotHref("users", context)).pathname).toBe("/42/users");
+ expect(readBack(buildPivotHref("replays", context)).pathname).toBe("/42/replay");
+ });
+
+ it("stays inside a private link", () => {
+ const href = buildPivotHref("sessions", { ...context, privateKey: "abcdef123456" });
+
+ expect(readBack(href).pathname).toBe("/42/abcdef123456/sessions");
+ });
+
+ it("carries the current filters narrowed by the extras", () => {
+ const href = buildPivotHref("sessions", context, [pricing]);
+
+ expect(readBack(href).filters).toEqual([country, pricing]);
+ });
+
+ it("survives values that need escaping", () => {
+ const awkward: Filter = { parameter: "pathname", type: "equals", value: ["/search?q=a&b=c d#x", '/"quoted"/100%'] };
+
+ expect(readBack(buildPivotHref("sessions", { ...context, filters: [] }, [awkward])).filters).toEqual([awkward]);
+ });
+
+ it("writes no filters param when there are none", () => {
+ const href = buildPivotHref("sessions", { ...context, filters: [] });
+
+ expect(readBack(href).params.has("filters")).toBe(false);
+ });
+
+ it("keeps a preset period as the preset", () => {
+ const { params } = readBack(buildPivotHref("sessions", context));
+
+ expect(params.get("wellKnown")).toBe("last-30-days");
+ expect(params.get("timeMode")).toBe("range");
+ expect(params.has("startDate")).toBe(false);
+ });
+
+ it("keeps an explicit range, a day and a rolling window", () => {
+ const range = { mode: "range", startDate: "2026-08-02", endDate: "2026-08-31" } as const;
+ const day = { mode: "day", day: "2026-09-14" } as const;
+ const rolling = { mode: "past-minutes", pastMinutesStart: 60, pastMinutesEnd: 0 } as const;
+
+ expect(readBack(buildPivotHref("sessions", { ...context, time: range })).time).toEqual(range);
+ expect(readBack(buildPivotHref("sessions", { ...context, time: day })).time).toEqual(day);
+ expect(readBack(buildPivotHref("sessions", { ...context, time: rolling })).time).toEqual(rolling);
+ });
+
+ it("leaves the default comparison out and keeps any other", () => {
+ expect(readBack(buildPivotHref("sessions", context)).params.has("compare")).toBe(false);
+
+ const off = readBack(buildPivotHref("sessions", { ...context, comparison: { mode: "none" } }));
+ expect(off.comparison).toEqual({ mode: "none" });
+
+ const custom = {
+ mode: "custom",
+ customTime: { mode: "range", startDate: "2026-07-01", endDate: "2026-07-30" },
+ } as const;
+ expect(readBack(buildPivotHref("sessions", { ...context, comparison: custom })).comparison).toEqual(custom);
+ });
+
+ it("keeps the bucket, the selected stat and the applied segment", () => {
+ const href = buildPivotHref("users", { ...context, bucket: "hour", selectedStat: "bounce_rate", segmentId: 7 });
+ const { params, segment } = readBack(href);
+
+ expect(params.get("bucket")).toBe("hour");
+ expect(params.get("stat")).toBe("bounce_rate");
+ expect(segment).toBe(7);
+ });
+
+ it("stays embedded but leaves a page's own params behind", () => {
+ const href = buildPivotHref("sessions", {
+ ...context,
+ search: "?embed=true&hideSidebar=true&theme=light&tab=entry&filters=%5B%5D&wellKnown=today",
+ });
+ const { params, filters } = readBack(href);
+
+ expect(params.get("embed")).toBe("true");
+ expect(params.get("hideSidebar")).toBe("true");
+ expect(params.get("theme")).toBe("light");
+ expect(params.has("tab")).toBe(false);
+ // The store wins over whatever the address bar still says.
+ expect(filters).toEqual([country]);
+ expect(params.get("wellKnown")).toBe("last-30-days");
+ });
+
+ it("accepts the query string as URLSearchParams", () => {
+ const href = buildPivotHref("sessions", { ...context, search: new URLSearchParams("embed=true") });
+
+ expect(readBack(href).params.get("embed")).toBe("true");
+ });
+});
diff --git a/client/src/lib/pivots.ts b/client/src/lib/pivots.ts
new file mode 100644
index 000000000..72c334ebf
--- /dev/null
+++ b/client/src/lib/pivots.ts
@@ -0,0 +1,114 @@
+import { Filter, FilterParameter, TimeBucket } from "@rybbit/shared";
+import { createSerializer } from "nuqs";
+import { Comparison, ComparisonMode, Time } from "../components/DateSelector/types";
+import { SESSION_PAGE_FILTERS, USER_PAGE_FILTERS } from "./filterGroups";
+import { analyticsParsers } from "./parsers";
+import type { StatType } from "./store";
+import { comparisonToUrlParams, timeToUrlParams } from "./time";
+
+/**
+ * A pivot is the doorway from an aggregate (a table row, a funnel step, a
+ * chart cell) to the people behind it: the same period and filters, narrowed
+ * by the filters that identify the aggregate, on the page that lists them.
+ */
+export type PivotTarget = "sessions" | "users" | "replays";
+
+const PIVOT_ROUTES: Record<PivotTarget, string> = {
+ sessions: "sessions",
+ users: "users",
+ replays: "replay",
+};
+
+/**
+ * The filters each target's list query actually sends. The Sessions and Users
+ * lists drop every parameter outside their page set before asking the server
+ * (useGetSessions, useGetUsers); the replay list sends the store's filters
+ * untouched, so it has no restriction.
+ */
+const PIVOT_FILTERS: Record<PivotTarget, readonly FilterParameter[] | null> = {
+ sessions: SESSION_PAGE_FILTERS,
+ users: USER_PAGE_FILTERS,
+ replays: null,
+};
+
+/**
+ * Whether the target can honour every filter that identifies the aggregate. A
+ * target that would drop one of them lists everyone instead of the people
+ * behind the number, so the pivot must not be offered at all.
+ */
+export function canPivot(target: PivotTarget, extraFilters: Filter[]): boolean {
+ const supported = PIVOT_FILTERS[target];
+ return supported === null || extraFilters.every(filter => supported.includes(filter.parameter));
+}
+
+/**
+ * The current filters narrowed by `extras`. An extra takes the place of a
+ * current filter on the same parameter and operator and is appended
+ * otherwise, which is what the store's `addFilter` does when a row is clicked.
+ */
+export function mergeFilters(current: Filter[], extras: Filter[]): Filter[] {
+ return extras.reduce<Filter[]>((merged, extra) => {
+ const index = merged.findIndex(filter => filter.parameter === extra.parameter && filter.type === extra.type);
+ return index === -1 ? [...merged, extra] : merged.map((filter, i) => (i === index ? extra : filter));
+ }, current);
+}
+
+/** The slice of the store a pivot carries over, plus the query string it leaves from. */
+export interface PivotContext {
+ site: string | number;
+ /** Set on a private-link view; the link stays inside it. */
+ privateKey?: string | null;
+ time: Time;
+ comparison: Comparison;
+ bucket: TimeBucket;
+ selectedStat: StatType;
+ filters: Filter[];
+ segmentId: number | null;
+ /** The current query string. Only the embed options are read from it. */
+ search?: string | URLSearchParams;
+}
+
+// Not analytics state, so the store does not hold them, but an embedded
+// dashboard has to stay embedded when a pivot is followed.
+const CARRIED_PARAMS = ["embed", "hideSidebar", "theme"];
+
+const serialize = createSerializer(analyticsParsers);
+
+/**
+ * Where a pivot leads: the target page of the same site with the current
+ * period, comparison, bucket, stat and segment, and the current filters
+ * narrowed by `extraFilters`.
+ *
+ * The query string is written from the store rather than copied from the
+ * address bar, so it is right on pages the URL sync does not cover (retention,
+ * bots, a user profile) and never carries a page's own params to another page.
+ * It is serialised with the same parsers `useSyncStateWithUrl` reads on
+ * arrival.
+ */
+export function buildPivotHref(target: PivotTarget, context: PivotContext, extraFilters: Filter[] = []): string {
+ const { site, privateKey, time, comparison, bucket, selectedStat, segmentId } = context;
+ const filters = mergeFilters(context.filters, extraFilters);
+
+ const current = new URLSearchParams(context.search);
+ const carried = new URLSearchParams();
+ for (const key of CARRIED_PARAMS) {
+ const value = current.get(key);
+ if (value !== null) carried.set(key, value);
+ }
+
+ const path = privateKey ? `/${site}/${privateKey}/${PIVOT_ROUTES[target]}` : `/${site}/${PIVOT_ROUTES[target]}`;
+ const comparisonParams = comparisonToUrlParams(comparison);
+
+ const query = serialize(carried, {
+ ...timeToUrlParams(time),
+ ...comparisonParams,
+ // comparisonToUrlParams types the mode as a plain string.
+ compare: comparisonParams.compare as ComparisonMode | null,
+ bucket,
+ stat: selectedStat,
+ filters: filters.length > 0 ? filters : null,
+ segment: segmentId,
+ });
+
+ return `${path}${query}`;
+}
diff --git a/client/src/lib/siteRoute.ts b/client/src/lib/siteRoute.ts
index ff041c3af..6a1723227 100644
--- a/client/src/lib/siteRoute.ts
+++ b/client/src/lib/siteRoute.ts
@@ -10,6 +10,7 @@ export const SYNCED_ANALYTICS_ROUTES = new Set([
"events",
"funnels",
"journeys",
+ "retention",
"errors",
"pages",
"replay",
diff --git a/docs/content/docs/api/insights/journeys.mdx b/docs/content/docs/api/insights/journeys.mdx
index 79f2e6d83..a4c940db1 100644
--- a/docs/content/docs/api/insights/journeys.mdx
+++ b/docs/content/docs/api/insights/journeys.mdx
@@ -51,6 +51,21 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
typeDescription: 'JSON string mapping step index to required path',
required: false,
},
+ endsAt: {
+ description: 'Page (or pattern with * and **) the journeys must reach. Each journey is cut at the first visit to it after the entry page, and only sessions that reach it within `steps` are counted',
+ type: 'string',
+ required: false,
+ },
+ groupBy: {
+ description: 'Set to "section" to collapse the pages under a first-level folder into one step (/docs/script and /docs/api become /docs/**)',
+ type: '"path" | "section"',
+ default: 'path',
+ },
+ goalId: {
+ description: 'ID of a goal. Adds `conversions` to each journey: the sessions on it that completed the goal',
+ type: 'number',
+ required: false,
+ },
}}
/>
@@ -62,6 +77,10 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
description: 'Array of journey objects',
type: 'Journey[]',
},
+ totalSessions: {
+ description: 'Sessions that visited two or more pages in the period, before stepFilters and endsAt are applied',
+ type: 'number',
+ },
}}
/>
@@ -78,9 +97,14 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
type: 'number',
},
percentage: {
- description: 'Percentage of total sessions',
+ description: 'Share of `totalSessions` (sessions with two or more pages), 0-100',
type: 'number',
},
+ conversions: {
+ description: 'Sessions on this journey that completed the goal. Only present with `goalId`',
+ type: 'number',
+ required: false,
+ },
}}
/>
@@ -232,7 +256,8 @@ var data = await response.Content.ReadAsStringAsync();
"count": 420,
"percentage": 2.73
}
- ]
+ ],
+ "totalSessions": 15394
}
```
@@ -369,7 +394,8 @@ var data = await response.Content.ReadAsStringAsync();
"count": 580,
"percentage": 5.8
}
- ]
+ ],
+ "totalSessions": 10000
}
```
diff --git a/docs/content/docs/api/insights/retention.mdx b/docs/content/docs/api/insights/retention.mdx
index 740a3e90f..929a035fc 100644
--- a/docs/content/docs/api/insights/retention.mdx
+++ b/docs/content/docs/api/insights/retention.mdx
@@ -17,6 +17,8 @@ GET /api/sites/:site/retention
Returns cohort-based retention analysis data. Users are grouped into cohorts based on their first visit, and retention is tracked over subsequent time periods.
+A user joins a cohort only when the requested time range holds their first visit: anyone seen in the 90 days before the range starts is a returning visitor and is left out. Returns are counted up to the end of the range. Filters select users by their first visit; any later activity counts as a return.
+
### Path Parameters
<TypeTable
@@ -31,22 +33,26 @@ Returns cohort-based retention analysis data. Users are grouped into cohorts bas
### Query Parameters
+Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plus the following:
+
<TypeTable
type={{
mode: {
- description: 'Retention period granularity',
+ description: 'Retention period granularity. Weeks start on Monday, in the requested time zone',
type: 'string',
typeDescription: '"day" | "week"',
default: 'week',
},
range: {
- description: 'Number of days to analyze (7-365)',
+ description: 'Number of trailing days to analyze (7-365). Only used when no time range is sent',
type: 'number',
default: 90,
},
}}
/>
+A range longer than 53 weeks (weekly) or 92 days (daily) is cut to its most recent periods, and `truncated` is `true` in the response.
+
### Response
<TypeTable
@@ -79,6 +85,42 @@ Returns cohort-based retention analysis data. Users are grouped into cohorts bas
description: 'Time range in days',
type: 'number',
},
+ periods: {
+ description: 'First day of every cohort period in the range, oldest first, including periods with no new users',
+ type: 'string[]',
+ },
+ windowStart: {
+ description: 'Start of the analyzed range (UTC, inclusive)',
+ type: 'string',
+ },
+ windowEnd: {
+ description: 'End of the analyzed range (UTC, exclusive). Never later than now',
+ type: 'string',
+ },
+ timeZone: {
+ description: 'Time zone the periods are counted in',
+ type: 'string',
+ },
+ firstPeriodPartial: {
+ description: 'The range starts partway through its first period, so that cohort is missing its first days',
+ type: 'boolean',
+ },
+ lastPeriodPartial: {
+ description: 'The range ends partway through its last period, so figures for that period are not final',
+ type: 'boolean',
+ },
+ lastPeriodInProgress: {
+ description: 'The last period is partial because it is still going on',
+ type: 'boolean',
+ },
+ truncated: {
+ description: 'The range held more periods than the limit and was cut to the most recent ones',
+ type: 'boolean',
+ },
+ lookbackDays: {
+ description: 'Days before the range in which a visit makes a user returning rather than new',
+ type: 'number',
+ },
}}
/>
@@ -93,7 +135,12 @@ Returns cohort-based retention analysis data. Users are grouped into cohorts bas
percentages: {
description: 'Retention percentages for each period (index 0 = period 0, etc.)',
type: '(number | null)[]',
- typeDescription: 'null indicates no data for that period yet',
+ typeDescription: 'null indicates a period after the end of the range; 0 means nobody came back',
+ },
+ counts: {
+ description: 'Retained users for each period (index 0 is the cohort size)',
+ type: '(number | null)[]',
+ typeDescription: 'null indicates a period after the end of the range',
},
}}
/>
@@ -222,32 +269,48 @@ var data = await response.Content.ReadAsStringAsync();
"cohorts": {
"2024-01-01": {
"size": 1250,
- "percentages": [100, 45.2, 32.1, 28.5, 25.3, 22.1]
+ "percentages": [100, 45.2, 32.08, 28.48, 12.4],
+ "counts": [1250, 565, 401, 356, 155]
},
"2024-01-08": {
"size": 1420,
- "percentages": [100, 48.5, 35.2, 30.1, 26.8, null]
+ "percentages": [100, 48.52, 35.21, 14.08, null],
+ "counts": [1420, 689, 500, 200, null]
},
"2024-01-15": {
"size": 1380,
- "percentages": [100, 46.8, 33.5, 29.2, null, null]
+ "percentages": [100, 46.81, 15.94, null, null],
+ "counts": [1380, 646, 220, null, null]
},
"2024-01-22": {
"size": 1510,
- "percentages": [100, 44.2, 31.8, null, null, null]
+ "percentages": [100, 17.02, null, null, null],
+ "counts": [1510, 257, null, null, null]
},
"2024-01-29": {
- "size": 1290,
- "percentages": [100, 47.1, null, null, null, null]
+ "size": 540,
+ "percentages": [100, null, null, null, null],
+ "counts": [540, null, null, null, null]
}
},
- "maxPeriods": 5,
+ "maxPeriods": 4,
"mode": "week",
- "range": 90
+ "range": 31,
+ "periods": ["2024-01-01", "2024-01-08", "2024-01-15", "2024-01-22", "2024-01-29"],
+ "windowStart": "2024-01-01T00:00:00.000Z",
+ "windowEnd": "2024-01-31T14:05:00.000Z",
+ "timeZone": "UTC",
+ "firstPeriodPartial": false,
+ "lastPeriodPartial": true,
+ "lastPeriodInProgress": true,
+ "truncated": false,
+ "lookbackDays": 90
}
}
```
+In this example the range ends on a Wednesday, so the week of Jan 29 is in progress: the last value of every cohort (the one that falls in that week) is not final.
+
### Understanding Retention Data
The retention data shows how many users from each cohort return in subsequent periods:
@@ -257,7 +320,7 @@ The retention data shows how many users from each cohort return in subsequent pe
- **Period 2**: Users who returned 2 weeks later
- etc.
-A `null` value indicates that period hasn't occurred yet for that cohort.
+A `null` value indicates that the period falls after the end of the range for that cohort. A value of `0` means the period has been observed and nobody came back.
### Visualization Example
diff --git a/server/src/api/__snapshots__/routes.test.ts.snap b/server/src/api/__snapshots__/routes.test.ts.snap
index 6c37303b5..81b36e679 100644
--- a/server/src/api/__snapshots__/routes.test.ts.snap
+++ b/server/src/api/__snapshots__/routes.test.ts.snap
@@ -56,8 +56,11 @@ exports[`API route table > pins the access each route requires 1`] = `
"GET /api/sites/:siteId/events/autocapture-values → site events:read [viewer+] (or public)",
"GET /api/sites/:siteId/events/count → site events:read [viewer+] (or public)",
"GET /api/sites/:siteId/events/names → site events:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/events/names/stats → site events:read [viewer+] (or public)",
"GET /api/sites/:siteId/events/outbound → site events:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/events/overview → site events:read [viewer+] (or public)",
"GET /api/sites/:siteId/events/properties → site events:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/events/silent → site events:read [viewer+] (or public)",
"GET /api/sites/:siteId/events/time-series → site events:read [viewer+] (or public)",
"GET /api/sites/:siteId/excluded-asns → site sites:read [viewer+]",
"GET /api/sites/:siteId/excluded-countries → site sites:read [viewer+]",
@@ -71,8 +74,10 @@ exports[`API route table > pins the access each route requires 1`] = `
"GET /api/sites/:siteId/export/pdf → site analytics:read [viewer+]",
"GET /api/sites/:siteId/feature-flags → site flags:read [viewer+]",
"GET /api/sites/:siteId/funnels → site funnels:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/funnels/summary → site funnels:read [viewer+] (or public)",
"GET /api/sites/:siteId/goals → site goals:read [viewer+] (or public)",
"GET /api/sites/:siteId/goals/:goalId/sessions → site goals:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/goals/summary → site goals:read [viewer+] (or public)",
"GET /api/sites/:siteId/goals/time-series → site goals:read [viewer+] (or public)",
"GET /api/sites/:siteId/gsc/connect → site gsc:write [editor+]",
"GET /api/sites/:siteId/gsc/data → site gsc:read [viewer+] (or public)",
@@ -81,6 +86,8 @@ exports[`API route table > pins the access each route requires 1`] = `
"GET /api/sites/:siteId/imports → site imports:read [editor+]",
"GET /api/sites/:siteId/is-public → site sites:read [viewer+] (or public)",
"GET /api/sites/:siteId/journeys → site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/journeys/sessions → site sessions:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/journeys/summary → site analytics:read [viewer+] (or public)",
"GET /api/sites/:siteId/live-user-count → site analytics:read [viewer+] (or public)",
"GET /api/sites/:siteId/metric → site analytics:read [viewer+] (or public)",
"GET /api/sites/:siteId/metric-lite → site analytics:read [viewer+] (or public)",
@@ -89,6 +96,9 @@ exports[`API route table > pins the access each route requires 1`] = `
"GET /api/sites/:siteId/overview-lite → site analytics:read [viewer+] (or public)",
"GET /api/sites/:siteId/overview/time-series → site analytics:read [viewer+] (or public)",
"GET /api/sites/:siteId/page-titles → site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/pages → site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/pages/summary → site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/pages/trends → site analytics:read [viewer+] (or public)",
"GET /api/sites/:siteId/performance/by-dimension → site analytics:read [viewer+] (or public)",
"GET /api/sites/:siteId/performance/overview → site analytics:read [viewer+] (or public)",
"GET /api/sites/:siteId/performance/time-series → site analytics:read [viewer+] (or public)",
@@ -101,14 +111,22 @@ exports[`API route table > pins the access each route requires 1`] = `
"GET /api/sites/:siteId/sessions → site sessions:read [viewer+] (or public)",
"GET /api/sites/:siteId/sessions/:sessionId → site sessions:read [viewer+] (or public)",
"GET /api/sites/:siteId/sessions/locations → site sessions:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/sessions/summary → site sessions:read [viewer+] (or public)",
"GET /api/sites/:siteId/transfer → site sites:transfer [admin+]",
"GET /api/sites/:siteId/usage → site sites:read [viewer+]",
+ "GET /api/sites/:siteId/user-traits/breakdown → site users:read [viewer+] (or public)",
"GET /api/sites/:siteId/user-traits/keys → site users:read [viewer+] (or public)",
"GET /api/sites/:siteId/user-traits/users → site users:read [viewer+] (or public)",
"GET /api/sites/:siteId/user-traits/values → site users:read [viewer+] (or public)",
"GET /api/sites/:siteId/users → site users:read [viewer+] (or public)",
"GET /api/sites/:siteId/users/:userId → site users:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/users/:userId/goals → site users:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/users/:userId/repeated-error → site users:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/users/:userId/segments → site users:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/users/:userId/session-goals → site users:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/users/:userId/summary → site users:read [viewer+] (or public)",
"GET /api/sites/:siteId/users/session-count → site users:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/users/summary → site users:read [viewer+] (or public)",
"GET /api/stripe/invoices → authenticated",
"GET /api/stripe/subscription → authenticated",
"GET /api/user/organizations → authenticated",
@@ -143,6 +161,7 @@ exports[`API route table > pins the access each route requires 1`] = `
"POST /api/sites/:siteId/funnels/:stepNumber/sessions → site funnels:read [viewer+] (or public)",
"POST /api/sites/:siteId/funnels/analyze → site funnels:read [viewer+] (or public)",
"POST /api/sites/:siteId/goals → site goals:write [member+]",
+ "POST /api/sites/:siteId/goals/preview → site goals:write [member+]",
"POST /api/sites/:siteId/gsc/select-property → site gsc:write [editor+]",
"POST /api/sites/:siteId/imports → site imports:write [editor+]",
"POST /api/sites/:siteId/imports/:importId/events → site imports:write [editor+]",
diff --git a/server/src/api/analytics/events/eventsPageQueries.test.ts b/server/src/api/analytics/events/eventsPageQueries.test.ts
new file mode 100644
index 000000000..fd3f4c10d
--- /dev/null
+++ b/server/src/api/analytics/events/eventsPageQueries.test.ts
@@ -0,0 +1,271 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../db/clickhouse/clickhouse.js", () => ({
+ clickhouse: { query: vi.fn() },
+}));
+vi.mock("../../../db/postgres/postgres.js", () => ({
+ db: {},
+}));
+
+import { buildEventsQuery } from "./getEvents.js";
+import {
+ alignTrends,
+ buildEventNameStatsQuery,
+ buildEventTrendBucketsQuery,
+ isTrendBucket,
+ TREND_BUCKETS,
+} from "./getEventNameStats.js";
+import { buildEventsOverviewQuery } from "./getEventsOverview.js";
+import {
+ buildSilentEventsQuery,
+ SILENT_AFTER_DAYS,
+ SILENT_LOOKBACK_DAYS,
+ SILENT_MIN_ACTIVE_SHARE,
+ SILENT_MIN_HISTORY_DAYS,
+} from "./getSilentEvents.js";
+import { buildSiteEventCountQuery } from "./getSiteEventCount.js";
+
+const SITE_ID = 1;
+
+const dateRange = (overrides: Record<string, unknown> = {}) => ({
+ start_date: "2026-09-01",
+ end_date: "2026-09-30",
+ time_zone: "America/New_York",
+ filters: "",
+ ...overrides,
+});
+
+const allTime = (overrides: Record<string, unknown> = {}) => ({
+ start_date: "",
+ end_date: "",
+ time_zone: "UTC",
+ filters: "",
+ ...overrides,
+});
+
+const eventNameFilter = JSON.stringify([{ parameter: "event_name", type: "equals", value: ["signup"] }]);
+const channelFilter = JSON.stringify([{ parameter: "channel", type: "equals", value: ["Direct"] }]);
+
+describe("buildEventsOverviewQuery", () => {
+ it("reads the period once and counts custom events, their users and their sessions", () => {
+ const query = buildEventsOverviewQuery(dateRange(), SITE_ID);
+
+ expect(query.match(/FROM events/g)).toHaveLength(1);
+ expect(query).toContain("countIf(type = 'custom_event') AS events");
+ expect(query).toContain("type = 'custom_event') AS users_with_events");
+ expect(query).toContain("uniqExactIf(session_id, type = 'custom_event') AS sessions_with_events");
+ expect(query).toContain("uniqExact(session_id) AS sessions");
+ expect(query).toContain("AS event_names");
+ });
+
+ it("counts a user by identity when there is one", () => {
+ const query = buildEventsOverviewQuery(dateRange(), SITE_ID);
+
+ expect(query).toContain("uniqExact(COALESCE(NULLIF(identified_user_id, ''), user_id)) AS users");
+ });
+
+ it("counts the autocaptured types and leaves pageviews, errors and web vitals out", () => {
+ const query = buildEventsOverviewQuery(dateRange(), SITE_ID);
+
+ expect(query).toContain(
+ "countIf(type IN ('outbound', 'button_click', 'copy', 'form_submit', 'input_change')) AS autocaptured"
+ );
+ });
+
+ it("is bounded by the requested period", () => {
+ const query = buildEventsOverviewQuery(dateRange(), SITE_ID);
+
+ expect(query).toContain("toDateTime('2026-09-01', 'America/New_York')");
+ expect(query).toContain("toDateTime('2026-09-30', 'America/New_York')");
+ });
+
+ it("keeps event_name row-scoped and channel session-scoped, like the other event queries", () => {
+ const byName = buildEventsOverviewQuery(dateRange({ filters: eventNameFilter }), SITE_ID);
+ expect(byName).toContain("AND event_name = 'signup'");
+ expect(byName).not.toContain("SELECT DISTINCT session_id");
+
+ const byChannel = buildEventsOverviewQuery(dateRange({ filters: channelFilter }), SITE_ID);
+ expect(byChannel).toContain("session_id IN");
+ expect(byChannel).toContain("session_channel = 'Direct'");
+ });
+
+ it("adds no filter clause when there are no filters", () => {
+ expect(buildEventsOverviewQuery(dateRange(), SITE_ID)).not.toContain("session_id IN");
+ });
+});
+
+describe("buildEventNameStatsQuery", () => {
+ it("returns every name's count, users, last occurrence and trend from one aggregation", () => {
+ const query = buildEventNameStatsQuery(dateRange(), SITE_ID, "day");
+
+ expect(query.match(/FROM events/g)).toHaveLength(1);
+ expect(query).toContain("count() AS count");
+ expect(query).toContain("uniqExact(COALESCE(NULLIF(identified_user_id, ''), user_id)) AS users");
+ expect(query).toContain("toString(max(timestamp)) AS lastSeen");
+ expect(query).toContain("AS trend");
+ expect(query).toContain("GROUP BY event_name");
+ });
+
+ it("only reads named custom events", () => {
+ const query = buildEventNameStatsQuery(dateRange(), SITE_ID, "day");
+
+ expect(query).toContain("AND type = 'custom_event'");
+ expect(query).toContain("AND event_name != ''");
+ });
+
+ it("is bounded by the period and by a row limit", () => {
+ const query = buildEventNameStatsQuery(dateRange(), SITE_ID, "day");
+
+ expect(query).toContain("toDateTime('2026-09-01', 'America/New_York')");
+ expect(query).toContain("LIMIT 1000");
+ });
+
+ it.each([
+ ["hour", "toStartOfHour"],
+ ["day", "toStartOfDay"],
+ ["week", "toStartOfWeek"],
+ ["month", "toStartOfMonth"],
+ ] as const)("buckets the trend by %s in the request's timezone", (bucket, fn) => {
+ const query = buildEventNameStatsQuery(dateRange(), SITE_ID, bucket);
+
+ expect(query).toContain(`sumMap([toDateTime(${fn}(toTimeZone(timestamp, 'America/New_York')))], [toUInt64(1)])`);
+ });
+
+ it("keeps event_name row-scoped and channel session-scoped", () => {
+ const byName = buildEventNameStatsQuery(dateRange({ filters: eventNameFilter }), SITE_ID, "day");
+ expect(byName).toContain("AND event_name = 'signup'");
+ expect(byName).not.toContain("SELECT DISTINCT session_id");
+
+ const byChannel = buildEventNameStatsQuery(dateRange({ filters: channelFilter }), SITE_ID, "day");
+ expect(byChannel).toContain("session_id IN");
+ });
+});
+
+describe("buildEventTrendBucketsQuery", () => {
+ it("uses the same bucket expression as the trend and fills the empty buckets", () => {
+ const query = buildEventTrendBucketsQuery(dateRange(), SITE_ID, "day");
+
+ expect(query).toContain("toDateTime(toStartOfDay(toTimeZone(timestamp, 'America/New_York'))) AS time");
+ expect(query).toContain("WITH FILL FROM");
+ expect(query).toContain("STEP INTERVAL 1 DAY");
+ });
+
+ it("has nothing to fill between on an all-time request", () => {
+ expect(buildEventTrendBucketsQuery(allTime(), SITE_ID, "month")).not.toContain("WITH FILL");
+ });
+
+ it("applies the same filters as the stats query", () => {
+ const query = buildEventTrendBucketsQuery(dateRange({ filters: eventNameFilter }), SITE_ID, "day");
+
+ expect(query).toContain("AND event_name = 'signup'");
+ });
+});
+
+describe("isTrendBucket", () => {
+ it("accepts the coarse buckets only", () => {
+ expect(TREND_BUCKETS.every(isTrendBucket)).toBe(true);
+ expect(isTrendBucket("minute")).toBe(false);
+ expect(isTrendBucket("year")).toBe(false);
+ expect(isTrendBucket("day; DROP TABLE events")).toBe(false);
+ expect(isTrendBucket(undefined)).toBe(false);
+ });
+});
+
+describe("alignTrends", () => {
+ const buckets = ["2026-09-01 00:00:00", "2026-09-02 00:00:00", "2026-09-03 00:00:00"];
+ const row = (trend: [string[], (number | string)[]], eventName: unknown = "signup") =>
+ ({ eventName, count: 0, users: 0, lastSeen: "2026-09-03 10:00:00", trend }) as Parameters<typeof alignTrends>[1][0];
+
+ it("puts each count on its bucket and a zero on the rest", () => {
+ const [stat] = alignTrends(buckets, [
+ row([
+ ["2026-09-01 00:00:00", "2026-09-03 00:00:00"],
+ [4, 7],
+ ]),
+ ]);
+
+ expect(stat.trend).toEqual([4, 0, 7]);
+ });
+
+ it("reads the 64-bit counts ClickHouse sends as strings", () => {
+ const [stat] = alignTrends(buckets, [row([["2026-09-02 00:00:00"], ["12"]])]);
+
+ expect(stat.trend).toEqual([0, 12, 0]);
+ });
+
+ it("drops a bucket that is not on the axis instead of misplacing it", () => {
+ const [stat] = alignTrends(buckets, [
+ row([
+ ["2026-08-31 00:00:00", "2026-09-01 00:00:00"],
+ [9, 1],
+ ]),
+ ]);
+
+ expect(stat.trend).toEqual([1, 0, 0]);
+ });
+
+ it("gives every name a trend as long as the axis, even with no buckets at all", () => {
+ expect(alignTrends(buckets, [row([[], []])])[0].trend).toEqual([0, 0, 0]);
+ expect(alignTrends([], [row([[], []])])[0].trend).toEqual([]);
+ });
+
+ it("keeps a numeric-looking event name as text", () => {
+ const [stat] = alignTrends(buckets, [row([[], []], 404)]);
+
+ expect(stat.eventName).toBe("404");
+ });
+});
+
+describe("buildSilentEventsQuery", () => {
+ const query = buildSilentEventsQuery();
+
+ it("reads a fixed window ending now, whatever the page's period", () => {
+ expect(query.match(/FROM events/g)).toHaveLength(1);
+ expect(query).toContain(`AND timestamp >= now() - INTERVAL ${SILENT_LOOKBACK_DAYS} DAY`);
+ expect(query).toContain("LIMIT 5");
+ });
+
+ it("only reads named custom events of the site", () => {
+ expect(query).toContain("site_id = {siteId:Int32}");
+ expect(query).toContain("AND type = 'custom_event'");
+ expect(query).toContain("AND event_name != ''");
+ });
+
+ it("flags an event that stopped after firing on most days", () => {
+ expect(query).toContain(`max(timestamp) < now() - INTERVAL ${SILENT_AFTER_DAYS} DAY`);
+ expect(query).toContain(`spanDays >= ${SILENT_MIN_HISTORY_DAYS}`);
+ expect(query).toContain(`activeDays >= spanDays * ${SILENT_MIN_ACTIVE_SHARE}`);
+ });
+
+ it("leaves room in the lookback to see the history it asks for", () => {
+ expect(SILENT_LOOKBACK_DAYS).toBeGreaterThanOrEqual(SILENT_AFTER_DAYS + SILENT_MIN_HISTORY_DAYS);
+ });
+
+ it("counts days in the viewer's timezone, passed as a bound parameter", () => {
+ expect(query).toContain("uniqExact(toDate(timestamp, {timeZone:String})) AS activeDays");
+ expect(query).not.toMatch(/toDate\([^)]*'[A-Za-z_]+\/[A-Za-z_]+'/);
+ });
+});
+
+describe("buildSiteEventCountQuery", () => {
+ it("fills empty buckets so the comparison period lines up bucket for bucket", () => {
+ const query = buildSiteEventCountQuery({ ...dateRange(), bucket: "day" }, SITE_ID);
+
+ expect(query).toContain("toDateTime(toStartOfDay(toTimeZone(timestamp, 'America/New_York'))) AS time");
+ expect(query).toContain("WITH FILL FROM");
+ expect(query).toContain("STEP INTERVAL 1 DAY");
+ });
+
+ it("does not fill an all-time request", () => {
+ expect(buildSiteEventCountQuery({ ...allTime(), bucket: "month" }, SITE_ID)).not.toContain("WITH FILL");
+ });
+});
+
+describe("buildEventsQuery types", () => {
+ it("returns errors with the rest of the log, and leaves web vitals out", () => {
+ const { query } = buildEventsQuery({ ...allTime(), page_size: "50" }, SITE_ID);
+
+ expect(query).toContain("'error'");
+ expect(query).not.toContain("'performance'");
+ });
+});
diff --git a/server/src/api/analytics/events/getEventNameStats.ts b/server/src/api/analytics/events/getEventNameStats.ts
new file mode 100644
index 000000000..5ed2da1da
--- /dev/null
+++ b/server/src/api/analytics/events/getEventNameStats.ts
@@ -0,0 +1,157 @@
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { effectiveUserId } from "../utils/effectiveUserId.js";
+import { getFilterStatement } from "../utils/getFilterStatement.js";
+import { resolveTimeWindow } from "../utils/timeWindow.js";
+
+// The buckets a row's trend may be drawn in. Coarse on purpose: the client
+// picks the one that keeps a trend to a few dozen points, so a year of data is
+// never returned minute by minute for a thousand names.
+export const TREND_BUCKETS = ["hour", "day", "week", "month"] as const;
+export type TrendBucket = (typeof TREND_BUCKETS)[number];
+
+export const isTrendBucket = (value: unknown): value is TrendBucket =>
+ typeof value === "string" && (TREND_BUCKETS as readonly string[]).includes(value);
+
+export type EventNameStat = {
+ eventName: string;
+ count: number;
+ users: number;
+ /** UTC, as ClickHouse prints it: `YYYY-MM-DD hh:mm:ss`. */
+ lastSeen: string;
+ /** Events per bucket, aligned to the response's `buckets`. */
+ trend: number[];
+};
+
+export type GetEventNameStatsResponse = {
+ /** Bucket start times in the request's timezone, oldest first. */
+ buckets: string[];
+ events: EventNameStat[];
+};
+
+export interface GetEventNameStatsRequest {
+ Params: {
+ siteId: string;
+ };
+ Querystring: FilterParams<{
+ trend_bucket?: string;
+ }>;
+}
+
+type EventNameStatsRow = Omit<EventNameStat, "trend"> & {
+ // sumMap's result: the buckets that hold events and the count in each.
+ trend: [string[], (number | string)[]];
+};
+
+const CUSTOM_EVENT_ROWS = `
+ site_id = {siteId:Int32}
+ AND type = 'custom_event'
+ AND event_name IS NOT NULL
+ AND event_name != ''`;
+
+const fragments = (query: GetEventNameStatsRequest["Querystring"], siteId: number) => {
+ const window = resolveTimeWindow(query);
+ const timeStatement = window.where();
+ const filterStatement = getFilterStatement(query.filters, siteId, timeStatement, {
+ sessionLevelParams: ["channel"],
+ });
+ return { window, timeStatement, filterStatement };
+};
+
+/**
+ * Every custom event name in the period with its count, its users, when it
+ * last fired and its count per bucket: one aggregation for the whole table
+ * rather than a query per row.
+ */
+export const buildEventNameStatsQuery = (
+ query: GetEventNameStatsRequest["Querystring"],
+ siteId: number,
+ bucket: TrendBucket
+) => {
+ const { window, timeStatement, filterStatement } = fragments(query, siteId);
+
+ return `
+ SELECT
+ event_name AS eventName,
+ count() AS count,
+ uniqExact(${effectiveUserId()}) AS users,
+ toString(max(timestamp)) AS lastSeen,
+ sumMap([${window.bucketed("timestamp", bucket)}], [toUInt64(1)]) AS trend
+ FROM events
+ WHERE${CUSTOM_EVENT_ROWS}
+ ${timeStatement}
+ ${filterStatement}
+ GROUP BY event_name
+ ORDER BY count DESC, eventName ASC
+ LIMIT 1000
+ `;
+};
+
+/**
+ * The buckets the trends are drawn over. A name's trend only lists the buckets
+ * it fired in, so the gaps are filled from here: a bucket with no events at
+ * all still gets its zero.
+ */
+export const buildEventTrendBucketsQuery = (
+ query: GetEventNameStatsRequest["Querystring"],
+ siteId: number,
+ bucket: TrendBucket
+) => {
+ const { window, timeStatement, filterStatement } = fragments(query, siteId);
+
+ return `
+ SELECT
+ ${window.bucketed("timestamp", bucket)} AS time
+ FROM events
+ WHERE${CUSTOM_EVENT_ROWS}
+ ${timeStatement}
+ ${filterStatement}
+ GROUP BY time
+ ORDER BY time
+ ${window.fill(bucket)}
+ `;
+};
+
+/** Spreads each name's sparse (bucket, count) pairs over the shared bucket axis. */
+export const alignTrends = (buckets: string[], rows: EventNameStatsRow[]): EventNameStat[] => {
+ const position = new Map(buckets.map((bucket, index) => [bucket, index]));
+
+ return rows.map(({ trend: [times, counts], ...row }) => {
+ const trend = new Array<number>(buckets.length).fill(0);
+ times.forEach((time, index) => {
+ const at = position.get(time);
+ if (at !== undefined) trend[at] = Number(counts[index]);
+ });
+ // processResults turns a numeric-looking name ("404") into a number.
+ return { ...row, eventName: String(row.eventName), trend };
+ });
+};
+
+export const getEventNameStats = analyticsRoute<GetEventNameStatsRequest>(
+ "event name stats",
+ async (req: FastifyRequest<GetEventNameStatsRequest>, res: FastifyReply) => {
+ const siteId = Number(req.params.siteId);
+ const bucket = req.query.trend_bucket ?? "day";
+
+ if (!isTrendBucket(bucket)) {
+ return res.status(400).send({ error: `Invalid trend_bucket value: ${bucket}` });
+ }
+
+ const [rows, bucketRows] = await Promise.all([
+ runAnalyticsQuery<EventNameStatsRow>({
+ query: buildEventNameStatsQuery(req.query, siteId, bucket),
+ params: { siteId },
+ }),
+ runAnalyticsQuery<{ time: string }>({
+ query: buildEventTrendBucketsQuery(req.query, siteId, bucket),
+ params: { siteId },
+ }),
+ ]);
+
+ const buckets = bucketRows.map(row => row.time);
+ const data: GetEventNameStatsResponse = { buckets, events: alignTrends(buckets, rows) };
+
+ return res.send({ data });
+ }
+);
diff --git a/server/src/api/analytics/events/getEvents.ts b/server/src/api/analytics/events/getEvents.ts
index 11e9e7acc..48653a414 100644
--- a/server/src/api/analytics/events/getEvents.ts
+++ b/server/src/api/analytics/events/getEvents.ts
@@ -72,7 +72,9 @@ const EVENT_COLUMNS = `
type
`;
-const EVENT_TYPE_FILTER = `AND type IN ('custom_event', 'pageview', 'outbound', 'button_click', 'copy', 'form_submit', 'input_change')`;
+// Everything a visitor does, which leaves out only the web-vitals rows. Errors
+// belong here: the log has always offered an Error type to filter by.
+const EVENT_TYPE_FILTER = `AND type IN ('custom_event', 'pageview', 'outbound', 'button_click', 'copy', 'form_submit', 'input_change', 'error')`;
export const buildEventsQuery = (query: GetEventsRequest["Querystring"], siteId: number): QuerySpec => {
const { since_timestamp, before_timestamp, page_size: pageSize = "50", filters } = query;
diff --git a/server/src/api/analytics/events/getEventsOverview.ts b/server/src/api/analytics/events/getEventsOverview.ts
new file mode 100644
index 000000000..9c45cef93
--- /dev/null
+++ b/server/src/api/analytics/events/getEventsOverview.ts
@@ -0,0 +1,74 @@
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { effectiveUserId } from "../utils/effectiveUserId.js";
+import { getFilterStatement } from "../utils/getFilterStatement.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
+
+export type GetEventsOverviewResponse = {
+ /** Custom events in the period. */
+ events: number;
+ /** Users who fired at least one custom event. */
+ users_with_events: number;
+ /** Every user active in the period, the base for `users_with_events`. */
+ users: number;
+ /** Every session in the period, the base for events per session. */
+ sessions: number;
+ /** Sessions that hold at least one custom event. */
+ sessions_with_events: number;
+ /** Distinct custom event names. */
+ event_names: number;
+ /** Events the script records on its own: outbound, button, copy, form and input events. */
+ autocaptured: number;
+};
+
+export interface GetEventsOverviewRequest {
+ Params: {
+ siteId: string;
+ };
+ Querystring: FilterParams;
+}
+
+// The types the tracking script captures without a `track()` call.
+export const AUTOCAPTURED_EVENT_TYPES = ["outbound", "button_click", "copy", "form_submit", "input_change"] as const;
+
+export const buildEventsOverviewQuery = (query: GetEventsOverviewRequest["Querystring"], siteId: number) => {
+ const timeStatement = getTimeStatement(query);
+ const filterStatement = getFilterStatement(query.filters, siteId, timeStatement, {
+ sessionLevelParams: ["channel"],
+ });
+ const user = effectiveUserId();
+ const autocaptured = AUTOCAPTURED_EVENT_TYPES.map(type => `'${type}'`).join(", ");
+
+ return `
+ SELECT
+ countIf(type = 'custom_event') AS events,
+ uniqExactIf(${user}, type = 'custom_event') AS users_with_events,
+ uniqExact(${user}) AS users,
+ uniqExact(session_id) AS sessions,
+ uniqExactIf(session_id, type = 'custom_event') AS sessions_with_events,
+ uniqExactIf(event_name, type = 'custom_event' AND event_name != '') AS event_names,
+ countIf(type IN (${autocaptured})) AS autocaptured
+ FROM events
+ WHERE
+ site_id = {siteId:Int32}
+ ${timeStatement}
+ ${filterStatement}
+ `;
+};
+
+// The events page's stat band: one pass over the period's events. The client
+// asks again for the comparison period.
+export const getEventsOverview = analyticsRoute<GetEventsOverviewRequest>(
+ "events overview",
+ async (req: FastifyRequest<GetEventsOverviewRequest>, res: FastifyReply) => {
+ const siteId = Number(req.params.siteId);
+
+ const data = await runAnalyticsQuery<GetEventsOverviewResponse>({
+ query: buildEventsOverviewQuery(req.query, siteId),
+ params: { siteId },
+ });
+
+ return res.send({ data: data[0] });
+ }
+);
diff --git a/server/src/api/analytics/events/getSilentEvents.ts b/server/src/api/analytics/events/getSilentEvents.ts
new file mode 100644
index 000000000..10360b556
--- /dev/null
+++ b/server/src/api/analytics/events/getSilentEvents.ts
@@ -0,0 +1,85 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { isValidTimeZone } from "../utils/timeWindow.js";
+
+/** How far back the check reads. Nothing older is ever scanned. */
+export const SILENT_LOOKBACK_DAYS = 35;
+/** An event is silent once it has gone this long without firing. */
+export const SILENT_AFTER_DAYS = 7;
+/** It has to have been around for at least this many days before it stopped. */
+export const SILENT_MIN_HISTORY_DAYS = 14;
+/** "Used to fire daily": it fired on at least this share of those days. */
+export const SILENT_MIN_ACTIVE_SHARE = 0.8;
+
+export type SilentEvent = {
+ eventName: string;
+ /** The last time it fired. UTC, as ClickHouse prints it: `YYYY-MM-DD hh:mm:ss`. */
+ lastSeen: string;
+ /** Events between its first appearance in the lookback and `lastSeen`. */
+ total: number;
+ /** Days it fired on in that span. */
+ activeDays: number;
+ /** Length of that span in days, counting both ends. */
+ spanDays: number;
+};
+
+export type GetSilentEventsResponse = SilentEvent[];
+
+export interface GetSilentEventsRequest {
+ Params: {
+ siteId: string;
+ };
+ Querystring: {
+ time_zone?: string;
+ };
+}
+
+/**
+ * Custom events that fired almost every day and then stopped: nothing in the
+ * last SILENT_AFTER_DAYS days, after at least SILENT_MIN_HISTORY_DAYS days on
+ * which it fired on SILENT_MIN_ACTIVE_SHARE of them. A broken tracking call
+ * looks exactly like this, and nothing else on the page shows it, because a
+ * name with no events drops out of every list.
+ *
+ * It is a statement about the site right now, so it reads a fixed window
+ * ending at now() and ignores the page's period and filters. Days are counted
+ * in the viewer's timezone. Binds `{siteId:Int32}` and `{timeZone:String}`.
+ */
+export const buildSilentEventsQuery = () => `
+ SELECT
+ event_name AS eventName,
+ toString(max(timestamp)) AS lastSeen,
+ count() AS total,
+ uniqExact(toDate(timestamp, {timeZone:String})) AS activeDays,
+ dateDiff('day', toDate(min(timestamp), {timeZone:String}), toDate(max(timestamp), {timeZone:String})) + 1 AS spanDays
+ FROM events
+ WHERE
+ site_id = {siteId:Int32}
+ AND type = 'custom_event'
+ AND event_name IS NOT NULL
+ AND event_name != ''
+ AND timestamp >= now() - INTERVAL ${SILENT_LOOKBACK_DAYS} DAY
+ GROUP BY event_name
+ HAVING
+ max(timestamp) < now() - INTERVAL ${SILENT_AFTER_DAYS} DAY
+ AND spanDays >= ${SILENT_MIN_HISTORY_DAYS}
+ AND activeDays >= spanDays * ${SILENT_MIN_ACTIVE_SHARE}
+ ORDER BY total / spanDays DESC, eventName ASC
+ LIMIT 5
+ `;
+
+export const getSilentEvents = analyticsRoute<GetSilentEventsRequest>(
+ "silent events",
+ async (req: FastifyRequest<GetSilentEventsRequest>, res: FastifyReply) => {
+ const siteId = Number(req.params.siteId);
+ const timeZone = req.query.time_zone && isValidTimeZone(req.query.time_zone) ? req.query.time_zone : "UTC";
+
+ const data = await runAnalyticsQuery<SilentEvent>({
+ query: buildSilentEventsQuery(),
+ params: { siteId, timeZone },
+ });
+
+ // processResults turns a numeric-looking name ("404") into a number.
+ return res.send({ data: data.map(row => ({ ...row, eventName: String(row.eventName) })) });
+ }
+);
diff --git a/server/src/api/analytics/events/getSiteEventCount.ts b/server/src/api/analytics/events/getSiteEventCount.ts
index 74b417e6d..44c5f7700 100644
--- a/server/src/api/analytics/events/getSiteEventCount.ts
+++ b/server/src/api/analytics/events/getSiteEventCount.ts
@@ -2,7 +2,7 @@ import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { TimeBucket } from "../types.js";
import { getFilterStatement } from "../utils/getFilterStatement.js";
-import { getTimeStatement, TimeBucketToFn } from "../utils/timeWindow.js";
+import { resolveTimeWindow, TimeBucketToFn } from "../utils/timeWindow.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
export type GetSiteEventCountResponse = {
@@ -31,14 +31,18 @@ interface GetSiteEventCountRequest {
export const buildSiteEventCountQuery = (query: GetSiteEventCountRequest["Querystring"], siteId: number) => {
const { bucket = "day" } = query;
- const timeStatement = getTimeStatement(query);
+ const window = resolveTimeWindow(query);
+ const timeStatement = window.where();
const filterStatement = getFilterStatement(query.filters, siteId, timeStatement, {
sessionLevelParams: ["channel"],
});
+ // Filled, so a bucket with no events is a zero row rather than a gap: the
+ // chart dips instead of interpolating, and the comparison period lines up
+ // with the current one bucket for bucket.
return `
SELECT
- toDateTime(${TimeBucketToFn[bucket]}(toTimeZone(timestamp, {timeZone:String}))) AS time,
+ ${window.bucketed("timestamp", bucket)} AS time,
countIf(type = 'pageview') as pageview_count,
countIf(type = 'custom_event') as custom_event_count,
countIf(type = 'performance') as performance_count,
@@ -57,6 +61,7 @@ export const buildSiteEventCountQuery = (query: GetSiteEventCountRequest["Querys
${filterStatement}
GROUP BY time
ORDER BY time
+ ${window.fill(bucket)}
`;
};
@@ -65,8 +70,6 @@ export const getSiteEventCount = analyticsRoute<GetSiteEventCountRequest>(
async (req: FastifyRequest<GetSiteEventCountRequest>, res: FastifyReply) => {
const site = req.params.siteId;
const { bucket = "day" } = req.query;
- const timeZone = req.query.time_zone || "UTC";
-
if (!TimeBucketToFn[bucket]) {
return res.status(400).send({ error: `Invalid bucket value: ${bucket}` });
}
@@ -75,7 +78,6 @@ export const getSiteEventCount = analyticsRoute<GetSiteEventCountRequest>(
query: buildSiteEventCountQuery(req.query, Number(site)),
params: {
siteId: Number(site),
- timeZone,
},
});
diff --git a/server/src/api/analytics/funnels/funnelQueries.test.ts b/server/src/api/analytics/funnels/funnelQueries.test.ts
index 3c5a89147..41df76b62 100644
--- a/server/src/api/analytics/funnels/funnelQueries.test.ts
+++ b/server/src/api/analytics/funnels/funnelQueries.test.ts
@@ -66,6 +66,41 @@ describe("funnel queries with global session filters", () => {
expect(sql).toContain("FROM Step2");
});
+ it("orders drilldown steps by the millisecond timestamp, like the analysis that counted them", () => {
+ const sql = buildFunnelStepSessionsQuery({ ...query, mode: "dropped", page: 1, limit: 25 }, 1, steps, 1);
+
+ expect(sql).toContain("min(timestamp_ms) as step_time");
+ expect(sql).toContain("sa.timestamp_ms > s1.step_time");
+ expect(sql).not.toContain("sa.timestamp > s1.step_time");
+ });
+
+ it("marks each drilldown session that has a replay and keeps the newest first", () => {
+ const sql = buildFunnelStepSessionsQuery({ ...query, mode: "reached", page: 1, limit: 25 }, 1, steps, 2);
+
+ expect(sql).toContain("FROM session_replay_metadata_v2");
+ expect(sql).toContain("if(r.session_id != '', 1, 0) AS has_replay");
+ expect(sql).toContain("ORDER BY a.session_end DESC");
+ expect(sql).not.toContain("session_id IN (SELECT session_id FROM ReplaySessions)");
+ });
+
+ it("narrows the drilldown to sessions with a replay when asked", () => {
+ const reached = buildFunnelStepSessionsQuery(
+ { ...query, mode: "reached", page: 1, limit: 25, replays_only: "true" },
+ 1,
+ steps,
+ 2
+ );
+ const dropped = buildFunnelStepSessionsQuery(
+ { ...query, mode: "dropped", page: 1, limit: 25, replays_only: "true" },
+ 1,
+ steps,
+ 1
+ );
+
+ expect(reached).toMatch(/FROM Step2\s+WHERE session_id IN \(SELECT session_id FROM ReplaySessions\)/);
+ expect(dropped).toMatch(/FROM Step2\s+\)\s+AND session_id IN \(SELECT session_id FROM ReplaySessions\)/);
+ });
+
it("returns the same canonical attribution fields used by session filtering", () => {
const sql = buildFunnelStepSessionsQuery({ ...query, mode: "reached", page: 1, limit: 25 }, 1, steps, 2);
diff --git a/server/src/api/analytics/funnels/getFunnelStepSessions.ts b/server/src/api/analytics/funnels/getFunnelStepSessions.ts
index 2adae8fdc..946ab4160 100644
--- a/server/src/api/analytics/funnels/getFunnelStepSessions.ts
+++ b/server/src/api/analytics/funnels/getFunnelStepSessions.ts
@@ -1,5 +1,6 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
import { enrichWithTraits } from "../utils/utils.js";
import { getTimeStatement } from "../utils/timeWindow.js";
import { GetSessionsResponse } from "../sessions/getSessions.js";
@@ -22,9 +23,13 @@ export interface GetFunnelStepSessionsRequest {
mode: "reached" | "dropped";
limit?: number;
page: number;
+ /** "true" lists only the sessions that have a replay. */
+ replays_only?: string;
}>;
}
+const replaysOnlySchema = z.enum(["true", "false"]).optional();
+
export const buildFunnelStepSessionsQuery = (
query: GetFunnelStepSessionsRequest["Querystring"],
siteId: number,
@@ -32,6 +37,7 @@ export const buildFunnelStepSessionsQuery = (
stepNumber: number
) => {
const { mode } = query;
+ const replaysOnly = query.replays_only === "true";
const timeStatement = getTimeStatement(query);
const filteredSessionsCTE = buildFilteredSessionsCTE(query.filters, siteId, timeStatement);
@@ -39,14 +45,17 @@ export const buildFunnelStepSessionsQuery = (
const stepsToCheck = mode === "reached" ? stepNumber : stepNumber + 1;
const stepConditions = steps.slice(0, stepsToCheck).map(step => buildFunnelStepCondition(step));
- // Build CTEs for each funnel step to identify qualifying sessions
+ // Build CTEs for each funnel step to identify qualifying sessions. Steps are
+ // ordered by the millisecond timestamp, as in the analyze and summary queries,
+ // so a session counted as continuing is never listed as dropped (a pageview
+ // and the event it fires often share a second).
const stepCTEs = [
`
${filteredSessionsCTE ? `${filteredSessionsCTE},` : ""}
SessionActions AS (
SELECT
session_id,
- timestamp,
+ timestamp_ms,
pathname,
event_name,
type,
@@ -63,7 +72,7 @@ export const buildFunnelStepSessionsQuery = (
Step1 AS (
SELECT DISTINCT
session_id,
- min(timestamp) as step_time
+ min(timestamp_ms) as step_time
FROM SessionActions
WHERE ${stepConditions[0]}
GROUP BY session_id
@@ -76,17 +85,18 @@ export const buildFunnelStepSessionsQuery = (
Step${i + 1} AS (
SELECT DISTINCT
s${i}.session_id,
- min(sa.timestamp) as step_time
+ min(sa.timestamp_ms) as step_time
FROM Step${i} s${i}
JOIN SessionActions sa ON s${i}.session_id = sa.session_id
WHERE
- sa.timestamp > s${i}.step_time
+ sa.timestamp_ms > s${i}.step_time
AND ${stepConditions[i]}
GROUP BY s${i}.session_id
)`);
}
// Determine which sessions to retrieve
+ const replayCondition = replaysOnly ? "session_id IN (SELECT session_id FROM ReplaySessions)" : "";
let targetSessionsCTE = "";
if (mode === "reached") {
// Sessions that completed step N
@@ -94,6 +104,7 @@ export const buildFunnelStepSessionsQuery = (
TargetSessions AS (
SELECT session_id
FROM Step${stepNumber}
+ ${replayCondition ? `WHERE ${replayCondition}` : ""}
)`;
} else {
// Sessions that completed step N but NOT step N+1
@@ -105,6 +116,7 @@ export const buildFunnelStepSessionsQuery = (
SELECT session_id
FROM Step${stepNumber + 1}
)
+ ${replayCondition ? `AND ${replayCondition}` : ""}
)`;
}
@@ -113,6 +125,15 @@ export const buildFunnelStepSessionsQuery = (
WITH
${stepCTEs.join(",\n")}
,
+ -- Same rule as the sessions list: a replay with at least two recorded events
+ ReplaySessions AS (
+ SELECT DISTINCT session_id
+ FROM session_replay_metadata_v2
+ FINAL
+ WHERE site_id = {siteId:Int32}
+ AND event_count >= 2
+ )
+ ,
${targetSessionsCTE}
,
AggregatedSessions AS (
@@ -162,10 +183,13 @@ export const buildFunnelStepSessionsQuery = (
GROUP BY
e.session_id,
e.user_id
- ORDER BY session_end DESC
)
- SELECT *
- FROM AggregatedSessions
+ SELECT
+ a.*,
+ if(r.session_id != '', 1, 0) AS has_replay
+ FROM AggregatedSessions a
+ LEFT JOIN ReplaySessions r ON a.session_id = r.session_id
+ ORDER BY a.session_end DESC
LIMIT {limit:Int32} OFFSET {offset:Int32}
`;
};
@@ -192,6 +216,10 @@ export const getFunnelStepSessions = analyticsRoute<GetFunnelStepSessionsRequest
return res.status(400).send({ error: "Mode must be 'reached' or 'dropped'" });
}
+ if (!replaysOnlySchema.safeParse(req.query.replays_only).success) {
+ return res.status(400).send({ error: "replays_only must be 'true' or 'false'" });
+ }
+
// For final step in "dropped" mode, return empty results (no drop-off possible)
if (mode === "dropped" && stepNumber === steps.length) {
return res.send({ data: [] });
diff --git a/server/src/api/analytics/funnels/getFunnelSummaries.test.ts b/server/src/api/analytics/funnels/getFunnelSummaries.test.ts
new file mode 100644
index 000000000..3246fd46b
--- /dev/null
+++ b/server/src/api/analytics/funnels/getFunnelSummaries.test.ts
@@ -0,0 +1,208 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../db/clickhouse/clickhouse.js", () => ({
+ clickhouse: { query: vi.fn() },
+}));
+vi.mock("../../../db/postgres/postgres.js", () => ({
+ db: {},
+}));
+
+import {
+ buildFunnelSummaryQuery,
+ parseSavedFunnels,
+ readFunnelSummaries,
+ SummaryFunnel,
+} from "./getFunnelSummaries.js";
+
+const query = { start_date: "2026-09-01", end_date: "2026-09-30", time_zone: "UTC", filters: "" };
+
+const visitToSignup: SummaryFunnel = {
+ id: 7,
+ steps: [
+ { type: "page", value: "/pricing" },
+ { type: "page", value: "/signup" },
+ { type: "event", value: "signup" },
+ ],
+};
+const pricingToSignup: SummaryFunnel = {
+ id: 9,
+ steps: [
+ { type: "page", value: "/pricing" },
+ { type: "event", value: "signup" },
+ ],
+};
+
+const occurrences = (sql: string, fragment: string) => sql.split(fragment).length - 1;
+
+describe("buildFunnelSummaryQuery", () => {
+ it("walks each funnel in order on the millisecond timestamp, strictly after the step before", () => {
+ const sql = buildFunnelSummaryQuery(query, 1, [visitToSignup]);
+
+ expect(sql).toContain(
+ "minIf(toUnixTimestamp64Milli(timestamp_ms), type = 'pageview' AND match(pathname, '^/pricing$')) AS first_0"
+ );
+ expect(sql).toContain("first_0 AS f0_t0");
+ expect(sql).toContain("if(f0_t0 = 0, 0, arrayMin(arrayFilter(x -> x > f0_t0, all_1))) AS f0_t1");
+ expect(sql).toContain("if(f0_t1 = 0, 0, arrayMin(arrayFilter(x -> x > f0_t1, all_2))) AS f0_t2");
+ });
+
+ it("counts every step and takes medians between steps and from first to last", () => {
+ const sql = buildFunnelSummaryQuery(query, 1, [visitToSignup]);
+
+ expect(sql).toContain("countIf(f0_t0 > 0) AS f0_sessions0");
+ expect(sql).toContain("countIf(f0_t2 > 0) AS f0_sessions2");
+ expect(sql).toContain("quantileIf(0.5)(f0_t1 - f0_t0, f0_t1 > 0) AS f0_median0");
+ expect(sql).toContain("quantileIf(0.5)(f0_t2 - f0_t1, f0_t2 > 0) AS f0_median1");
+ expect(sql).toContain("quantileIf(0.5)(f0_t2 - f0_t0, f0_t2 > 0) AS f0_median_total");
+ expect(sql).not.toContain("f0_median2");
+ });
+
+ it("collects a step condition shared by several funnels once", () => {
+ const sql = buildFunnelSummaryQuery(query, 1, [visitToSignup, pricingToSignup]);
+
+ // /pricing opens both funnels and signup closes both.
+ expect(occurrences(sql, "AS first_0")).toBe(1);
+ expect(
+ occurrences(
+ sql,
+ "groupArrayIf(toUnixTimestamp64Milli(timestamp_ms), type = 'custom_event' AND event_name = 'signup')"
+ )
+ ).toBe(1);
+ expect(sql).toContain("first_0 AS f1_t0");
+ expect(sql).toContain("if(f1_t0 = 0, 0, arrayMin(arrayFilter(x -> x > f1_t0, all_2))) AS f1_t1");
+ });
+
+ it("collects every match of a condition that is both a first and a later step", () => {
+ const repeat: SummaryFunnel = {
+ id: 3,
+ steps: [
+ { type: "page", value: "/pricing" },
+ { type: "page", value: "/pricing" },
+ ],
+ };
+ const sql = buildFunnelSummaryQuery(query, 1, [repeat]);
+
+ expect(sql).toContain("AS first_0");
+ expect(sql).toContain("AS all_0");
+ expect(sql).toContain("if(f0_t0 = 0, 0, arrayMin(arrayFilter(x -> x > f0_t0, all_0))) AS f0_t1");
+ });
+
+ it("counts a session once however many funnels it enters", () => {
+ const sql = buildFunnelSummaryQuery(query, 1, [visitToSignup, pricingToSignup]);
+
+ expect(sql).toContain("countIf(f0_t0 > 0 OR f1_t0 > 0) AS sessions_entered_any");
+ });
+
+ it("is bounded by the site and the time window and scans only events that match a step", () => {
+ const sql = buildFunnelSummaryQuery(query, 1, [visitToSignup]);
+
+ expect(sql).toContain("site_id = {siteId:Int32}");
+ expect(sql).toContain("toDateTime('2026-09-01', 'UTC')");
+ expect(sql).toContain(
+ "AND ((type = 'pageview' AND match(pathname, '^/pricing$'))\n OR (type = 'pageview' AND match(pathname, '^/signup$'))\n OR (type = 'custom_event' AND event_name = 'signup'))"
+ );
+ expect(sql).toContain("GROUP BY session_id");
+ });
+
+ it("qualifies sessions by the global filters without filtering the step events themselves", () => {
+ const filters = JSON.stringify([{ parameter: "utm_campaign", type: "equals", value: ["launch"] }]);
+ const sql = buildFunnelSummaryQuery({ ...query, filters }, 1, [visitToSignup]);
+ const sessionSteps = sql.slice(sql.indexOf("SessionSteps AS"), sql.indexOf("SessionFunnels AS"));
+
+ expect(sql).toContain("FilteredSessions AS");
+ expect(sql).toContain("WHERE 1 = 1 AND utm_campaign = 'launch'");
+ expect(sessionSteps).toContain("INNER JOIN FilteredSessions USING (session_id)");
+ expect(sessionSteps).not.toContain("utm_campaign");
+ });
+
+ it("escapes step values instead of interpolating them", () => {
+ const sql = buildFunnelSummaryQuery(query, 1, [
+ {
+ id: 1,
+ steps: [
+ { type: "event", value: "it's" },
+ { type: "page", value: "/a", hostname: "x' OR 1=1 --" },
+ ],
+ },
+ ]);
+
+ expect(sql).toContain("event_name = 'it\\'s'");
+ expect(sql).toContain("hostname = 'x\\' OR 1=1 --'");
+ });
+});
+
+describe("readFunnelSummaries", () => {
+ it("maps the wide row back to one summary per funnel, in seconds", () => {
+ const summaries = readFunnelSummaries(
+ {
+ f0_sessions0: 100,
+ f0_sessions1: 40,
+ f0_sessions2: 10,
+ f0_median0: 58_400,
+ f0_median1: 81_000.5,
+ f0_median_total: 150_000,
+ f1_sessions0: 100,
+ f1_sessions1: 0,
+ f1_median0: null,
+ f1_median_total: null,
+ },
+ [visitToSignup, pricingToSignup]
+ );
+
+ expect(summaries).toEqual([
+ {
+ funnel_id: 7,
+ steps: [
+ { sessions: 100, median_seconds_to_next: 58.4 },
+ { sessions: 40, median_seconds_to_next: 81.001 },
+ { sessions: 10, median_seconds_to_next: null },
+ ],
+ median_seconds_to_convert: 150,
+ },
+ {
+ funnel_id: 9,
+ steps: [
+ { sessions: 100, median_seconds_to_next: null },
+ { sessions: 0, median_seconds_to_next: null },
+ ],
+ median_seconds_to_convert: null,
+ },
+ ]);
+ });
+
+ it("reads a period with no matching events as zeros", () => {
+ expect(readFunnelSummaries(undefined, [pricingToSignup])).toEqual([
+ {
+ funnel_id: 9,
+ steps: [
+ { sessions: 0, median_seconds_to_next: null },
+ { sessions: 0, median_seconds_to_next: null },
+ ],
+ median_seconds_to_convert: null,
+ },
+ ]);
+ });
+});
+
+describe("parseSavedFunnels", () => {
+ it("keeps funnels with at least two well-formed steps and skips the rest", () => {
+ const funnels = parseSavedFunnels([
+ { reportId: 1, data: { name: "Good", steps: pricingToSignup.steps } },
+ { reportId: 2, data: { name: "One step", steps: [{ type: "page", value: "/" }] } },
+ { reportId: 3, data: { name: "No steps" } },
+ { reportId: 4, data: null },
+ {
+ reportId: 5,
+ data: {
+ steps: [
+ { type: "page", value: 5 },
+ { type: "page", value: "/" },
+ ],
+ },
+ },
+ { reportId: 6, data: { steps: "nope" } },
+ ]);
+
+ expect(funnels).toEqual([{ id: 1, steps: pricingToSignup.steps }]);
+ });
+});
diff --git a/server/src/api/analytics/funnels/getFunnelSummaries.ts b/server/src/api/analytics/funnels/getFunnelSummaries.ts
new file mode 100644
index 000000000..3ab40d41e
--- /dev/null
+++ b/server/src/api/analytics/funnels/getFunnelSummaries.ts
@@ -0,0 +1,232 @@
+import { FilterParams } from "@rybbit/shared";
+import { eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import { db } from "../../../db/postgres/postgres.js";
+import { funnels as funnelsTable } from "../../../db/postgres/schema.js";
+import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { buildFilteredSessionsCTE } from "../utils/sessionFilters.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
+import { buildFunnelStepCondition, FunnelStep } from "./funnelSteps.js";
+
+/**
+ * How many saved funnels one summary covers. The query is one scan whatever the
+ * count, but every extra funnel adds aggregates to it, so the list is capped
+ * (oldest first, the order the funnels page lists them in) and the response
+ * says when funnels were left out.
+ */
+export const MAX_SUMMARY_FUNNELS = 50;
+
+export interface SummaryFunnel {
+ id: number;
+ steps: FunnelStep[];
+}
+
+export interface FunnelSummary {
+ funnel_id: number;
+ steps: {
+ /** Sessions that reached this step. Funnels are session-scoped, not person-scoped. */
+ sessions: number;
+ /** Median time from reaching this step to reaching the next. Null on the last step and when nobody continued. */
+ median_seconds_to_next: number | null;
+ }[];
+ /** Median time from the first step to the last, over sessions that reached the last. */
+ median_seconds_to_convert: number | null;
+}
+
+export interface FunnelSummariesResponse {
+ /** Distinct sessions that reached the first step of at least one summarised funnel. */
+ sessions_entered_any: number;
+ funnels: FunnelSummary[];
+ /** True when the site has more saved funnels than one summary covers. */
+ truncated: boolean;
+}
+
+// Saved steps come out of a jsonb column, so they are checked before they are
+// turned into SQL. Unknown step types are kept: the condition builder matches
+// them as custom events, as it does for the analyze endpoint.
+const propertyValueSchema = z.union([z.string(), z.number(), z.boolean()]);
+const savedStepSchema = z.object({
+ value: z.string(),
+ type: z.string(),
+ name: z.string().optional(),
+ hostname: z.string().optional(),
+ eventPropertyKey: z.string().optional(),
+ eventPropertyValue: propertyValueSchema.optional(),
+ propertyFilters: z.array(z.object({ key: z.string(), value: propertyValueSchema })).optional(),
+});
+const savedStepsSchema = z.array(savedStepSchema).min(2);
+
+/** The saved funnels a summary can be computed for: at least two well-formed steps. */
+export function parseSavedFunnels(records: { reportId: number; data: unknown }[]): SummaryFunnel[] {
+ const funnels: SummaryFunnel[] = [];
+ for (const record of records) {
+ const steps = savedStepsSchema.safeParse((record.data as { steps?: unknown } | null)?.steps);
+ if (steps.success) funnels.push({ id: record.reportId, steps: steps.data as FunnelStep[] });
+ }
+ return funnels;
+}
+
+const EVENT_MS = "toUnixTimestamp64Milli(timestamp_ms)";
+
+/**
+ * One scan for every saved funnel of a site.
+ *
+ * The analyze endpoint walks a funnel with a chain of CTEs: step N is the first
+ * event matching its condition strictly after the session reached step N-1.
+ * This query answers the same question per session in a single GROUP BY: the
+ * first step is the earliest matching event, and each later step is the
+ * earliest of its matching events after the step before it (0 when the session
+ * never got there). Counting those per funnel gives the same step counts as
+ * analyze, and the step times give the medians between steps.
+ *
+ * Step conditions shared by several funnels (or repeated inside one) are
+ * collected once, and the scan is narrowed to events that match at least one
+ * of them.
+ */
+export const buildFunnelSummaryQuery = (query: FilterParams<{}>, siteId: number, funnels: SummaryFunnel[]): string => {
+ const timeStatement = getTimeStatement(query);
+ const filteredSessionsCTE = buildFilteredSessionsCTE(query.filters, siteId, timeStatement);
+
+ const conditions: string[] = [];
+ const conditionIndex = (step: FunnelStep) => {
+ const condition = buildFunnelStepCondition(step);
+ const existing = conditions.indexOf(condition);
+ return existing === -1 ? conditions.push(condition) - 1 : existing;
+ };
+
+ // The earliest match is all a first step needs; later steps need every match.
+ const firstStepConditions = new Set<number>();
+ const laterStepConditions = new Set<number>();
+ const funnelConditions = funnels.map(funnel =>
+ funnel.steps.map((step, stepIndex) => {
+ const index = conditionIndex(step);
+ (stepIndex === 0 ? firstStepConditions : laterStepConditions).add(index);
+ return index;
+ })
+ );
+
+ const sessionAggregates = conditions.flatMap((condition, index) => [
+ ...(firstStepConditions.has(index) ? [`minIf(${EVENT_MS}, ${condition}) AS first_${index}`] : []),
+ ...(laterStepConditions.has(index) ? [`groupArrayIf(${EVENT_MS}, ${condition}) AS all_${index}`] : []),
+ ]);
+
+ // f{funnel}_t{step}: when the session reached the step, in epoch ms; 0 if it did not.
+ const stepTimes = funnelConditions.flatMap((stepConditions, funnel) =>
+ stepConditions.map((condition, step) => {
+ const time = `f${funnel}_t${step}`;
+ if (step === 0) return `first_${condition} AS ${time}`;
+ const previous = `f${funnel}_t${step - 1}`;
+ return `if(${previous} = 0, 0, arrayMin(arrayFilter(x -> x > ${previous}, all_${condition}))) AS ${time}`;
+ })
+ );
+
+ const totals = funnelConditions.flatMap((stepConditions, funnel) => {
+ const lastStep = stepConditions.length - 1;
+ return [
+ ...stepConditions.map((_, step) => `countIf(f${funnel}_t${step} > 0) AS f${funnel}_sessions${step}`),
+ ...stepConditions
+ .slice(1)
+ .map(
+ (_, step) =>
+ `quantileIf(0.5)(f${funnel}_t${step + 1} - f${funnel}_t${step}, f${funnel}_t${step + 1} > 0) AS f${funnel}_median${step}`
+ ),
+ `quantileIf(0.5)(f${funnel}_t${lastStep} - f${funnel}_t0, f${funnel}_t${lastStep} > 0) AS f${funnel}_median_total`,
+ ];
+ });
+
+ return `
+ WITH
+ ${filteredSessionsCTE ? `${filteredSessionsCTE},` : ""}
+ -- One row per session: when each step condition matched
+ SessionSteps AS (
+ SELECT
+ session_id,
+ ${sessionAggregates.join(",\n ")}
+ FROM events
+ ${filteredSessionsCTE ? "INNER JOIN FilteredSessions USING (session_id)" : ""}
+ WHERE
+ site_id = {siteId:Int32}
+ ${timeStatement}
+ AND (${conditions.map(condition => `(${condition})`).join("\n OR ")})
+ GROUP BY session_id
+ ),
+ -- Walk each funnel in order within the session
+ SessionFunnels AS (
+ SELECT
+ ${stepTimes.join(",\n ")}
+ FROM SessionSteps
+ )
+ SELECT
+ ${totals.join(",\n ")},
+ countIf(${funnels.map((_, funnel) => `f${funnel}_t0 > 0`).join(" OR ")}) AS sessions_entered_any
+ FROM SessionFunnels
+ `;
+};
+
+const toCount = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
+
+// An empty median is NaN in ClickHouse, which JSON carries as null.
+const toSeconds = (value: unknown) =>
+ typeof value === "number" && Number.isFinite(value) ? Math.round(value) / 1000 : null;
+
+/** Reads the query's single wide row back into one summary per funnel. */
+export function readFunnelSummaries(
+ row: Record<string, unknown> | undefined,
+ funnels: SummaryFunnel[]
+): FunnelSummary[] {
+ return funnels.map((funnel, index) => ({
+ funnel_id: funnel.id,
+ steps: funnel.steps.map((_, step) => ({
+ sessions: toCount(row?.[`f${index}_sessions${step}`]),
+ median_seconds_to_next: step < funnel.steps.length - 1 ? toSeconds(row?.[`f${index}_median${step}`]) : null,
+ })),
+ median_seconds_to_convert: toSeconds(row?.[`f${index}_median_total`]),
+ }));
+}
+
+export interface GetFunnelSummariesRequest {
+ Params: {
+ siteId: string;
+ };
+ Querystring: FilterParams<{}>;
+}
+
+/**
+ * Step counts and step-to-step medians for the saved funnels of a site over the
+ * requested window. The funnels page calls it once for the selected period and
+ * once for the comparison period.
+ */
+export const getFunnelSummaries = analyticsRoute<GetFunnelSummariesRequest>(
+ "funnel summaries",
+ async (req: FastifyRequest<GetFunnelSummariesRequest>, res: FastifyReply) => {
+ const siteId = Number(req.params.siteId);
+
+ const records = await db
+ .select({ reportId: funnelsTable.reportId, data: funnelsTable.data })
+ .from(funnelsTable)
+ .where(eq(funnelsTable.siteId, siteId))
+ .orderBy(funnelsTable.createdAt)
+ .limit(MAX_SUMMARY_FUNNELS + 1);
+
+ const truncated = records.length > MAX_SUMMARY_FUNNELS;
+ const funnels = parseSavedFunnels(records.slice(0, MAX_SUMMARY_FUNNELS));
+
+ if (funnels.length === 0) {
+ const empty: FunnelSummariesResponse = { sessions_entered_any: 0, funnels: [], truncated };
+ return res.send({ data: empty });
+ }
+
+ const rows = await runAnalyticsQuery<Record<string, unknown>>({
+ query: buildFunnelSummaryQuery(req.query, siteId, funnels),
+ params: { siteId },
+ });
+
+ const data: FunnelSummariesResponse = {
+ sessions_entered_any: toCount(rows[0]?.sessions_entered_any),
+ funnels: readFunnelSummaries(rows[0], funnels),
+ truncated,
+ };
+ return res.send({ data });
+ }
+);
diff --git a/server/src/api/analytics/funnels/getFunnels.ts b/server/src/api/analytics/funnels/getFunnels.ts
index 229eb368f..972b16d13 100644
--- a/server/src/api/analytics/funnels/getFunnels.ts
+++ b/server/src/api/analytics/funnels/getFunnels.ts
@@ -31,9 +31,8 @@ export async function getFunnels(
configuration: data.configuration || {},
createdAt: record.createdAt,
updatedAt: record.updatedAt,
- // Include any additional analytics data that might be stored
- conversionRate: data.lastResult?.conversionRate || null,
- totalVisitors: data.lastResult?.totalVisitors || null,
+ // Sessions and conversion are computed per period by getFunnelSummaries;
+ // nothing is stored with the definition.
};
});
diff --git a/server/src/api/analytics/getJourneySessions.ts b/server/src/api/analytics/getJourneySessions.ts
new file mode 100644
index 000000000..b5627e89b
--- /dev/null
+++ b/server/src/api/analytics/getJourneySessions.ts
@@ -0,0 +1,181 @@
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import {
+ buildJourneyFragments,
+ JourneyOptions,
+ JourneyQuerySpec,
+ JourneyQuerystring,
+ MAX_JOURNEY_STEPS,
+ parseJourneyOptions,
+} from "./journeyPaths.js";
+import { GetSessionsResponse } from "./sessions/getSessions.js";
+import { analyticsRoute, runAnalyticsQuery } from "./utils/analyticsQuery.js";
+import {
+ SESSION_CHANNEL_AGG,
+ SESSION_REFERRER_AGG,
+ SESSION_UTM_CAMPAIGN_AGG,
+ SESSION_UTM_CONTENT_AGG,
+ SESSION_UTM_MEDIUM_AGG,
+ SESSION_UTM_SOURCE_AGG,
+ SESSION_UTM_TERM_AGG,
+} from "./utils/sessionAttribution.js";
+import { getTimeStatement } from "./utils/timeWindow.js";
+import { enrichWithTraits } from "./utils/utils.js";
+
+const MAX_PAGE_SIZE = 100;
+
+// The journey whose sessions are wanted: the pages exactly as a journeys row
+// lists them.
+const journeyPathSchema = z.array(z.string().max(2048)).min(1).max(MAX_JOURNEY_STEPS);
+
+interface GetJourneySessionsRequest {
+ Params: { siteId: string };
+ Querystring: FilterParams<
+ JourneyQuerystring & {
+ path: string;
+ replays_only?: string;
+ limit?: string;
+ page?: string;
+ }
+ >;
+}
+
+interface JourneySessionsOptions {
+ path: string[];
+ replaysOnly: boolean;
+ limit: number;
+ page: number;
+}
+
+/**
+ * The sessions counted in one journeys row. The journey is derived exactly as
+ * the journeys endpoint derives it (same filters, steps, end page and page
+ * grouping), so the list is the row's sessions and no others.
+ */
+export const buildJourneySessionsQuery = (
+ query: GetJourneySessionsRequest["Querystring"],
+ siteId: number,
+ options: JourneyOptions,
+ { path, replaysOnly, limit, page }: JourneySessionsOptions
+): JourneyQuerySpec => {
+ const { ctes, params } = buildJourneyFragments(query, siteId, options);
+ const timeStatement = getTimeStatement(query);
+
+ return {
+ query: `
+ WITH ${ctes},
+ TargetSessions AS (
+ SELECT session_id
+ FROM session_journeys
+ WHERE journey = {journeyPath:Array(String)}
+ ),
+ AggregatedSessions AS (
+ SELECT
+ session_id,
+ argMax(user_id, timestamp) AS user_id,
+ argMax(identified_user_id, timestamp) AS identified_user_id,
+ argMax(country, timestamp) AS country,
+ argMax(region, timestamp) AS region,
+ argMax(city, timestamp) AS city,
+ argMax(language, timestamp) AS language,
+ argMax(device_type, timestamp) AS device_type,
+ argMax(browser, timestamp) AS browser,
+ argMax(browser_version, timestamp) AS browser_version,
+ argMax(operating_system, timestamp) AS operating_system,
+ argMax(operating_system_version, timestamp) AS operating_system_version,
+ argMax(screen_width, timestamp) AS screen_width,
+ argMax(screen_height, timestamp) AS screen_height,
+ ${SESSION_REFERRER_AGG} AS referrer,
+ ${SESSION_CHANNEL_AGG} AS channel,
+ argMin(hostname, timestamp) AS hostname,
+ ${SESSION_UTM_SOURCE_AGG} AS utm_source,
+ ${SESSION_UTM_MEDIUM_AGG} AS utm_medium,
+ ${SESSION_UTM_CAMPAIGN_AGG} AS utm_campaign,
+ ${SESSION_UTM_TERM_AGG} AS utm_term,
+ ${SESSION_UTM_CONTENT_AGG} AS utm_content,
+ MAX(timestamp) AS session_end,
+ MIN(timestamp) AS session_start,
+ dateDiff('second', MIN(timestamp), MAX(timestamp)) AS session_duration,
+ argMinIf(pathname, timestamp_ms, type = 'pageview') AS entry_page,
+ argMaxIf(pathname, timestamp_ms, type = 'pageview') AS exit_page,
+ countIf(type = 'pageview') AS pageviews,
+ countIf(type = 'custom_event') AS events,
+ countIf(type = 'error') AS errors,
+ countIf(type = 'outbound') AS outbound,
+ countIf(type = 'button_click') AS button_clicks,
+ countIf(type = 'copy') AS copies,
+ countIf(type = 'form_submit') AS form_submits,
+ countIf(type = 'input_change') AS input_changes,
+ argMax(ip, timestamp) AS ip,
+ argMax(lat, timestamp) AS lat,
+ argMax(lon, timestamp) AS lon,
+ argMax(tag, timestamp) AS tag
+ FROM events
+ WHERE
+ site_id = {siteId:Int32}
+ ${timeStatement}
+ AND session_id IN (SELECT session_id FROM TargetSessions)
+ GROUP BY
+ session_id
+ ),
+ ReplaySessions AS (
+ SELECT DISTINCT session_id
+ FROM session_replay_metadata_v2
+ FINAL
+ WHERE site_id = {siteId:Int32}
+ AND event_count >= 2
+ )
+ SELECT
+ a.*,
+ if(r.session_id != '', 1, 0) AS has_replay
+ FROM AggregatedSessions a
+ LEFT JOIN ReplaySessions r ON a.session_id = r.session_id
+ ${replaysOnly ? "WHERE r.session_id != ''" : ""}
+ ORDER BY a.session_end DESC
+ LIMIT {limit:Int32} OFFSET {offset:Int32}
+ `,
+ params: { ...params, journeyPath: path, limit, offset: (page - 1) * limit },
+ };
+};
+
+export const getJourneySessions = analyticsRoute<GetJourneySessionsRequest>(
+ "journey sessions",
+ async (request: FastifyRequest<GetJourneySessionsRequest>, reply: FastifyReply) => {
+ const siteId = parseInt(request.params.siteId, 10);
+
+ // The sessions are picked by their path alone; a goal only adds a count.
+ const parsed = parseJourneyOptions({ ...request.query, goalId: undefined });
+ if (!parsed.ok) {
+ return reply.status(400).send({ error: parsed.error });
+ }
+
+ let path: string[];
+ try {
+ path = journeyPathSchema.parse(JSON.parse(request.query.path));
+ } catch {
+ return reply.status(400).send({ error: "Path must be a JSON array of 1 to 10 pages" });
+ }
+
+ const limit = parseInt(request.query.limit ?? "25", 10);
+ const page = parseInt(request.query.page ?? "1", 10);
+ if (isNaN(limit) || limit < 1 || limit > MAX_PAGE_SIZE) {
+ return reply.status(400).send({ error: `Limit parameter must be a number between 1 and ${MAX_PAGE_SIZE}` });
+ }
+ if (isNaN(page) || page < 1) {
+ return reply.status(400).send({ error: "Invalid page number" });
+ }
+
+ const data = await runAnalyticsQuery<Omit<GetSessionsResponse[number], "traits">>(
+ buildJourneySessionsQuery(request.query, siteId, parsed.options, {
+ path,
+ replaysOnly: request.query.replays_only === "true",
+ limit,
+ page,
+ })
+ );
+
+ const dataWithTraits = await enrichWithTraits(data, siteId);
+ return reply.send({ data: dataWithTraits });
+ }
+);
diff --git a/server/src/api/analytics/getJourneySummary.ts b/server/src/api/analytics/getJourneySummary.ts
new file mode 100644
index 000000000..5f1f30361
--- /dev/null
+++ b/server/src/api/analytics/getJourneySummary.ts
@@ -0,0 +1,102 @@
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import {
+ buildJourneyFragments,
+ JourneyOptions,
+ JourneyQuerySpec,
+ parseJourneyOptions,
+ resolveJourneyGoal,
+} from "./journeyPaths.js";
+import { analyticsRoute, runAnalyticsQuery } from "./utils/analyticsQuery.js";
+
+interface GetJourneySummaryRequest {
+ Params: { siteId: string };
+ Querystring: FilterParams<{ goalId?: string }>;
+}
+
+type JourneySummaryRow = {
+ sessions: number;
+ pages: number;
+ conversions: number;
+ top_exit_page: string;
+ top_exit_sessions: number;
+};
+
+export interface JourneySummary {
+ /** Sessions that visited two or more pages. */
+ sessions: number;
+ /** Mean number of pages on those sessions' paths (a reloaded page counts once). */
+ avgPathLength: number;
+ /** How many of those sessions completed the goal; null without a goal. */
+ conversions: number | null;
+ /** The page most of those sessions ended on. */
+ topExit: { page: string; sessions: number } | null;
+}
+
+/**
+ * The page-level figures for the journeys page. One pass over the period's
+ * pageviews: sessions are grouped by their last page first, so the totals and
+ * the most common exit page come out of the same aggregation.
+ */
+export const buildJourneySummaryQuery = (
+ query: GetJourneySummaryRequest["Querystring"],
+ siteId: number,
+ goalCondition?: string
+): JourneyQuerySpec => {
+ const options: JourneyOptions = { maxSteps: 2, stepFilters: {}, groupBy: "path", goalCondition };
+ const { ctes, convertedExpression, params } = buildJourneyFragments(query, siteId, options);
+
+ return {
+ query: `
+ WITH ${ctes}
+
+ SELECT
+ sum(exit_sessions) AS sessions,
+ sum(exit_pages) AS pages,
+ sum(exit_conversions) AS conversions,
+ argMax(exit_page, exit_sessions) AS top_exit_page,
+ max(exit_sessions) AS top_exit_sessions
+ FROM (
+ SELECT
+ path_sequence[length(path_sequence)] AS exit_page,
+ count() AS exit_sessions,
+ sum(length(path_sequence)) AS exit_pages,
+ ${convertedExpression ? `countIf(${convertedExpression})` : "0"} AS exit_conversions
+ FROM user_paths
+ GROUP BY exit_page
+ )
+ `,
+ params,
+ };
+};
+
+export const getJourneySummary = analyticsRoute<GetJourneySummaryRequest>(
+ "journey summary",
+ async (request: FastifyRequest<GetJourneySummaryRequest>, reply: FastifyReply) => {
+ const siteId = parseInt(request.params.siteId, 10);
+
+ const parsed = parseJourneyOptions({ goalId: request.query.goalId });
+ if (!parsed.ok) {
+ return reply.status(400).send({ error: parsed.error });
+ }
+
+ const goal = await resolveJourneyGoal(parsed.goalId, siteId);
+ if (!goal.ok) {
+ return reply.status(goal.status).send({ error: goal.error });
+ }
+
+ const [row] = await runAnalyticsQuery<JourneySummaryRow>(
+ buildJourneySummaryQuery(request.query, siteId, goal.goalCondition)
+ );
+
+ const sessions = Number(row?.sessions ?? 0);
+ const data: JourneySummary = {
+ sessions,
+ avgPathLength: sessions > 0 ? Number(row.pages) / sessions : 0,
+ conversions: goal.goalCondition ? Number(row?.conversions ?? 0) : null,
+ topExit: sessions > 0 ? { page: row.top_exit_page, sessions: Number(row.top_exit_sessions) } : null,
+ };
+
+ return reply.send({ data });
+ }
+);
diff --git a/server/src/api/analytics/getJourneys.test.ts b/server/src/api/analytics/getJourneys.test.ts
index f6f31fb88..4b20f824b 100644
--- a/server/src/api/analytics/getJourneys.test.ts
+++ b/server/src/api/analytics/getJourneys.test.ts
@@ -3,10 +3,16 @@ import { describe, expect, it, vi } from "vitest";
vi.mock("../../db/clickhouse/clickhouse.js", () => ({
clickhouse: { query: vi.fn() },
}));
+vi.mock("../../db/postgres/postgres.js", () => ({
+ db: {},
+}));
import { buildJourneysQuery } from "./getJourneys.js";
+import { buildJourneySessionsQuery } from "./getJourneySessions.js";
+import { buildJourneySummaryQuery } from "./getJourneySummary.js";
+import { JourneyOptions, parseJourneyOptions } from "./journeyPaths.js";
-const baseQuery = (filters: string) => ({
+const baseQuery = (filters = "") => ({
filters,
start_date: "",
end_date: "",
@@ -15,22 +21,31 @@ const baseQuery = (filters: string) => ({
const filter = (parameter: string, value: string) => ({ parameter, type: "equals", value: [value] });
+const options = (overrides: Partial<JourneyOptions> = {}): JourneyOptions => ({
+ maxSteps: 4,
+ stepFilters: {},
+ groupBy: "path",
+ ...overrides,
+});
+
+const journeysSql = (filters = "", overrides: Partial<JourneyOptions> = {}) =>
+ buildJourneysQuery(baseQuery(filters), 1, options(overrides), 15);
+
describe("buildJourneysQuery session-scoped filters", () => {
it("keeps later journey pageviews when the referrer exists only on the acquisition row", () => {
- const sql = buildJourneysQuery(baseQuery(JSON.stringify([filter("referrer", "google.com")])), 1, {});
+ const { query: sql } = journeysSql(JSON.stringify([filter("referrer", "google.com")]));
expect(sql).toContain("FilteredSessions AS");
expect(sql).toContain("argMinIf(referrer, timestamp, referrer != '') AS referrer");
expect(sql).toContain("WHERE 1 = 1 AND domainWithoutWWW(referrer) = 'google.com'");
expect(sql).toContain("FROM events\n INNER JOIN FilteredSessions USING (session_id)");
expect(sql).toContain("AND type = 'pageview'");
- expect(sql).toContain("SELECT count() FROM FilteredSessions");
expect(sql.match(/domainWithoutWWW\(referrer\) = 'google\.com'/g)).toHaveLength(1);
});
it("allows campaign and a later pathname to qualify on different rows", () => {
const filters = JSON.stringify([filter("utm_campaign", "recipe_book_2026"), filter("pathname", "/thank-you")]);
- const sql = buildJourneysQuery(baseQuery(filters), 1, {});
+ const { query: sql } = journeysSql(filters);
expect(sql).toContain("WHERE 1 = 1 AND utm_campaign = 'recipe_book_2026'");
expect(sql).toContain("SELECT DISTINCT session_id\n FROM events");
@@ -38,4 +53,210 @@ describe("buildJourneysQuery session-scoped filters", () => {
expect(sql.match(/utm_campaign = 'recipe_book_2026'/g)).toHaveLength(1);
expect(sql.match(/pathname = '\/thank-you'/g)).toHaveLength(1);
});
+
+ it("qualifies sessions by their acquisition channel", () => {
+ const { query: sql } = journeysSql(JSON.stringify([filter("channel", "Organic Search")]));
+
+ expect(sql).toContain("FilteredSessions AS");
+ expect(sql).toContain("INNER JOIN FilteredSessions USING (session_id)");
+ expect(sql).toContain("'Organic Search'");
+ });
+});
+
+describe("buildJourneysQuery", () => {
+ it("takes each journey's share from the sessions with two or more pages", () => {
+ const { query: sql, params } = journeysSql();
+
+ expect(sql).toContain("WHERE length(path_sequence) >= 2");
+ expect(sql).toContain("CROSS JOIN (SELECT count() AS total_sessions FROM user_paths) AS totals");
+ expect(sql).toContain("sessions_count * 100 / total_sessions AS percentage");
+ // The old denominator: every session, including the single-page ones no journey can come from.
+ expect(sql).not.toContain("count(DISTINCT session_id)");
+ expect(sql).not.toContain("SELECT count() FROM FilteredSessions");
+ expect(params).toEqual({ siteId: 1, maxSteps: 4, journeyLimit: 15 });
+ });
+
+ it("binds step filters as parameters instead of writing them into the SQL", () => {
+ const { query: sql, params } = journeysSql("", {
+ stepFilters: { 0: "/pricing", 2: "/docs/**", 3: "/blog/*" },
+ });
+
+ expect(sql).toContain("journey[1] = {stepFilter1:String}");
+ expect(sql).toContain("match(journey[3], {stepFilter3:String})");
+ expect(sql).toContain("match(journey[4], {stepFilter4:String})");
+ expect(sql).not.toContain("/pricing");
+ expect(sql).not.toContain("/docs");
+ expect(params).toMatchObject({
+ stepFilter1: "/pricing",
+ stepFilter3: "^/docs/.*$",
+ stepFilter4: "^/blog/[^/]+$",
+ });
+ });
+
+ it("keeps a hostile step filter out of the SQL text", () => {
+ const hostile = "'; DROP TABLE events; --";
+ const { query: sql, params } = journeysSql("", { stepFilters: { 0: hostile } });
+
+ expect(sql).not.toContain("DROP TABLE");
+ expect(params.stepFilter1).toBe(hostile);
+ });
+
+ it("ignores empty step filters and filters beyond the last step", () => {
+ const { query: sql, params } = journeysSql("", { stepFilters: { 1: "", 4: "/late", 99999999999: "/far" } });
+
+ expect(sql).not.toContain("journey[");
+ expect(Object.keys(params).filter(key => key.startsWith("stepFilter"))).toEqual([]);
+ });
+
+ it("cuts journeys at the first visit to the end page after the entry page", () => {
+ const { query: sql, params } = journeysSql("", { endsAt: "/signup" });
+
+ expect(sql).toContain("arrayFirstIndex((p, i) -> i >= 2 AND p = {endsAt:String}, pages, arrayEnumerate(pages))");
+ expect(sql).toContain("BETWEEN 2 AND {maxSteps:Int32}");
+ expect(sql).toContain("WHERE notEmpty(journey)");
+ expect(params.endsAt).toBe("/signup");
+ });
+
+ it("matches a wildcard end page as a pattern", () => {
+ const { query: sql, params } = journeysSql("", { endsAt: "/signup/**" });
+
+ expect(sql).toContain("match(p, {endsAt:String})");
+ expect(params.endsAt).toBe("^/signup/.*$");
+ });
+
+ it("uses whole paths unless pages are grouped by section", () => {
+ expect(journeysSql().query).toContain("SELECT session_id, path_sequence AS pages");
+
+ const { query: sql } = journeysSql("", { groupBy: "section" });
+ expect(sql).toContain("arrayCompact(arrayMap(p -> if(match(p, '^/[^/]+/.+')");
+ expect(sql).toContain("concat(extract(p, '^(/[^/]+)/'), '/**')");
+ });
+
+ it("counts goal conversions per journey only when a goal is given", () => {
+ expect(journeysSql().query).not.toContain("GoalSessions");
+ expect(journeysSql().query).not.toContain("conversions");
+
+ const { query: sql } = journeysSql("", { goalCondition: "type = 'custom_event' AND event_name = 'signup'" });
+ expect(sql).toContain("GoalSessions AS (");
+ expect(sql).toContain("AND (type = 'custom_event' AND event_name = 'signup')");
+ expect(sql).toContain("countIf(session_id IN (SELECT session_id FROM GoalSessions)) AS conversions");
+ });
+
+ it("bounds the result and breaks ties by path so pages of results are stable", () => {
+ const { query: sql, params } = journeysSql();
+
+ expect(sql).toContain("ORDER BY sessions_count DESC, journey ASC\n LIMIT {journeyLimit:Int32}");
+ expect(params.journeyLimit).toBe(15);
+ });
+});
+
+describe("buildJourneySummaryQuery", () => {
+ it("aggregates the multi-page sessions by exit page in one pass", () => {
+ const { query: sql, params } = buildJourneySummaryQuery(baseQuery(), 7);
+
+ expect(sql).toContain("path_sequence[length(path_sequence)] AS exit_page");
+ expect(sql).toContain("FROM user_paths\n GROUP BY exit_page");
+ expect(sql).toContain("argMax(exit_page, exit_sessions) AS top_exit_page");
+ expect(sql).toContain("0 AS exit_conversions");
+ expect(sql).not.toContain("GoalSessions");
+ expect(params).toEqual({ siteId: 7, maxSteps: 2 });
+ });
+
+ it("counts the sessions that completed the goal", () => {
+ const { query: sql } = buildJourneySummaryQuery(
+ baseQuery(),
+ 7,
+ "type = 'pageview' AND match(pathname, '^/welcome$')"
+ );
+
+ expect(sql).toContain("GoalSessions AS (");
+ expect(sql).toContain("countIf(session_id IN (SELECT session_id FROM GoalSessions)) AS exit_conversions");
+ });
+
+ it("applies the page's session filters", () => {
+ const { query: sql } = buildJourneySummaryQuery(baseQuery(JSON.stringify([filter("country", "US")])), 7);
+
+ expect(sql).toContain("FilteredSessions AS");
+ expect(sql).toContain("INNER JOIN FilteredSessions USING (session_id)");
+ });
+});
+
+describe("buildJourneySessionsQuery", () => {
+ const sessionsSql = (overrides: Partial<JourneyOptions> = {}, replaysOnly = false) =>
+ buildJourneySessionsQuery({ ...baseQuery(), path: "[]" }, 1, options(overrides), {
+ path: ["/", "/pricing"],
+ replaysOnly,
+ limit: 25,
+ page: 3,
+ });
+
+ it("selects the sessions whose journey is exactly the path", () => {
+ const { query: sql, params } = sessionsSql();
+
+ expect(sql).toContain("FROM session_journeys\n WHERE journey = {journeyPath:Array(String)}");
+ expect(sql).toContain("AND session_id IN (SELECT session_id FROM TargetSessions)");
+ expect(sql).not.toContain("/pricing");
+ expect(params).toMatchObject({ journeyPath: ["/", "/pricing"], limit: 25, offset: 50, maxSteps: 4 });
+ });
+
+ it("derives the journey the same way the journeys query does", () => {
+ const journeyOptions = { endsAt: "/signup", groupBy: "section" as const, stepFilters: { 0: "/" } };
+ const journeysCte = journeysSql("", journeyOptions).query.match(/session_journeys AS \(([\s\S]*?)\n\s*\),/)?.[1];
+ const sessionsCte = sessionsSql(journeyOptions).query.match(/session_journeys AS \(([\s\S]*?)\n\s*\),/)?.[1];
+
+ expect(journeysCte).toBeTruthy();
+ expect(sessionsCte).toBe(journeysCte);
+ });
+
+ it("can keep only the sessions that have a replay", () => {
+ expect(sessionsSql().query).not.toContain("WHERE r.session_id != ''");
+ expect(sessionsSql({}, true).query).toContain("WHERE r.session_id != ''");
+ });
+});
+
+describe("parseJourneyOptions", () => {
+ it("defaults to three steps of whole paths", () => {
+ expect(parseJourneyOptions({})).toEqual({
+ ok: true,
+ options: { maxSteps: 3, stepFilters: {}, endsAt: undefined, groupBy: "path" },
+ goalId: undefined,
+ });
+ });
+
+ it("reads every option", () => {
+ expect(
+ parseJourneyOptions({
+ steps: "10",
+ stepFilters: JSON.stringify({ 0: "/", 2: "/docs/**" }),
+ endsAt: " /signup ",
+ groupBy: "section",
+ goalId: "12",
+ })
+ ).toEqual({
+ ok: true,
+ options: { maxSteps: 10, stepFilters: { 0: "/", 2: "/docs/**" }, endsAt: "/signup", groupBy: "section" },
+ goalId: 12,
+ });
+ });
+
+ it.each([{ steps: "1" }, { steps: "11" }, { steps: "many" }])("rejects steps outside 2 to 10: %o", query => {
+ expect(parseJourneyOptions(query)).toEqual({
+ ok: false,
+ error: "Steps parameter must be a number between 2 and 10",
+ });
+ });
+
+ it.each(["not json", JSON.stringify({ first: "/" }), JSON.stringify({ 0: 5 }), JSON.stringify(["/"])])(
+ "rejects malformed step filters: %s",
+ stepFilters => {
+ expect(parseJourneyOptions({ stepFilters })).toEqual({ ok: false, error: "Invalid stepFilters format" });
+ }
+ );
+
+ it.each([{ groupBy: "folder" }, { goalId: "abc" }, { goalId: "-3" }, { endsAt: "/".repeat(2049) }])(
+ "rejects an unknown grouping, a bad goal id and an oversized end page: %o",
+ query => {
+ expect(parseJourneyOptions(query)).toEqual({ ok: false, error: "Invalid journey options" });
+ }
+ );
});
diff --git a/server/src/api/analytics/getJourneys.ts b/server/src/api/analytics/getJourneys.ts
index 994184dbe..307b62907 100644
--- a/server/src/api/analytics/getJourneys.ts
+++ b/server/src/api/analytics/getJourneys.ts
@@ -1,125 +1,75 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
-import SqlString from "sqlstring";
-import { z } from "zod";
-import { buildFilteredSessionsCTE } from "./utils/sessionFilters.js";
-import { patternToRegex } from "./utils/utils.js";
-import { getTimeStatement } from "./utils/timeWindow.js";
+import {
+ buildJourneyFragments,
+ JourneyOptions,
+ JourneyQuerySpec,
+ JourneyQuerystring,
+ parseJourneyOptions,
+ resolveJourneyGoal,
+} from "./journeyPaths.js";
import { AnalyticsQueryError, runAnalyticsQuery } from "./utils/analyticsQuery.js";
-// stepFilters arrives as a JSON object mapping a (numeric) step index to a path
-// pattern. Both the keys and values are attacker-controlled, so validate the
-// shape before interpolating any of it into the ClickHouse query.
-const stepFiltersSchema = z.record(
- z.string().regex(/^\d+$/, "Step index must be a non-negative integer"),
- z.string().max(2048)
-);
-
interface GetJourneysRequest {
Params: { siteId: string };
- Querystring: FilterParams<{
- steps?: string;
- limit?: string;
- stepFilters?: string;
- }>;
+ Querystring: FilterParams<JourneyQuerystring & { limit?: string }>;
}
type JourneyRow = {
journey: string[];
sessions_count: number;
+ conversions?: number;
+ total_sessions: number;
percentage: number;
};
export const buildJourneysQuery = (
query: GetJourneysRequest["Querystring"],
siteId: number,
- parsedStepFilters: Record<string, string>
-) => {
- // Time conditions using getTimeStatement
- const timeStatement = getTimeStatement(query);
- const filteredSessionsCTE = buildFilteredSessionsCTE(query.filters, siteId, timeStatement);
- const filteredSessionsJoin = filteredSessionsCTE ? "INNER JOIN FilteredSessions USING (session_id)" : "";
-
- // Build step filter conditions for the HAVING clause
- // Supports wildcard patterns: * matches single segment, ** matches multiple segments
- const stepFilterConditions = Object.entries(parsedStepFilters)
- .map(([step, path]) => {
- const stepIndex = parseInt(step, 10) + 1; // ClickHouse arrays are 1-indexed
- if (path.includes("*")) {
- // Use regex matching for wildcard patterns. SqlString.escape correctly
- // escapes the regex literal for ClickHouse (handles both ' and \).
- const regex = patternToRegex(path);
- return `match(journey[${stepIndex}], ${SqlString.escape(regex)})`;
- }
- // Use exact match for non-wildcard patterns (more efficient)
- return `journey[${stepIndex}] = ${SqlString.escape(path)}`;
- })
- .join(" AND ");
+ options: JourneyOptions,
+ journeyLimit: number
+): JourneyQuerySpec => {
+ const { ctes, convertedExpression, params } = buildJourneyFragments(query, siteId, options);
- // Query to find sequences of events (journeys) for each user
- return `
- WITH ${filteredSessionsCTE ? `${filteredSessionsCTE},` : ""}
- user_paths AS (
- SELECT
- session_id,
- arrayCompact(groupArray(pathname)) AS path_sequence
- FROM (
- SELECT
- session_id,
- pathname,
- timestamp
- FROM events
- ${filteredSessionsJoin}
- WHERE
- site_id = {siteId:Int32}
- ${timeStatement || ""}
- AND type = 'pageview'
- ORDER BY session_id, timestamp
- )
- GROUP BY session_id
- HAVING length(path_sequence) >= 2
- ),
+ // Each journey's share is of the sessions that visited two or more pages:
+ // the population journeys are drawn from, whatever the step filters keep.
+ return {
+ query: `
+ WITH ${ctes},
journey_segments AS (
SELECT
- arraySlice(path_sequence, 1, {maxSteps:Int32}) AS journey,
+ journey,
count() AS sessions_count
- FROM user_paths
+ ${convertedExpression ? `, countIf(${convertedExpression}) AS conversions` : ""}
+ FROM session_journeys
GROUP BY journey
- ${stepFilterConditions ? `HAVING ${stepFilterConditions}` : ""}
- ORDER BY sessions_count DESC
+ ORDER BY sessions_count DESC, journey ASC
LIMIT {journeyLimit:Int32}
)
SELECT
journey,
sessions_count,
- sessions_count * 100 / (
- ${
- filteredSessionsCTE
- ? "SELECT count() FROM FilteredSessions"
- : `SELECT count(DISTINCT session_id)
- FROM events
- WHERE site_id = {siteId:Int32}
- ${timeStatement || ""}`
- }
- ) AS percentage
+ ${convertedExpression ? "conversions," : ""}
+ total_sessions,
+ sessions_count * 100 / total_sessions AS percentage
FROM journey_segments
- `;
+ CROSS JOIN (SELECT count() AS total_sessions FROM user_paths) AS totals
+ ORDER BY sessions_count DESC, journey ASC
+ `,
+ params: { ...params, journeyLimit },
+ };
};
export const getJourneys = async (request: FastifyRequest<GetJourneysRequest>, reply: FastifyReply) => {
try {
- const { siteId } = request.params;
- const { steps = "3", limit = "100", stepFilters } = request.query;
-
- const maxSteps = parseInt(steps, 10);
- const journeyLimit = parseInt(limit, 10);
+ const siteId = parseInt(request.params.siteId, 10);
+ const journeyLimit = parseInt(request.query.limit ?? "100", 10);
- if (isNaN(maxSteps) || maxSteps < 2 || maxSteps > 10) {
- return reply.status(400).send({
- error: "Steps parameter must be a number between 2 and 10",
- });
+ const parsed = parseJourneyOptions(request.query);
+ if (!parsed.ok) {
+ return reply.status(400).send({ error: parsed.error });
}
if (isNaN(journeyLimit) || journeyLimit < 1 || journeyLimit > 500) {
@@ -128,33 +78,24 @@ export const getJourneys = async (request: FastifyRequest<GetJourneysRequest>, r
});
}
- // Parse and validate step filters
- let parsedStepFilters: Record<string, string> = {};
- if (stepFilters) {
- try {
- parsedStepFilters = stepFiltersSchema.parse(JSON.parse(stepFilters));
- } catch (error) {
- return reply.status(400).send({
- error: "Invalid stepFilters format",
- });
- }
+ const goal = await resolveJourneyGoal(parsed.goalId, siteId);
+ if (!goal.ok) {
+ return reply.status(goal.status).send({ error: goal.error });
}
- const data = await runAnalyticsQuery<JourneyRow>({
- query: buildJourneysQuery(request.query, Number(siteId), parsedStepFilters),
- params: {
- siteId: parseInt(siteId, 10),
- maxSteps: maxSteps,
- journeyLimit: journeyLimit,
- },
- });
+ const data = await runAnalyticsQuery<JourneyRow>(
+ buildJourneysQuery(request.query, siteId, { ...parsed.options, goalCondition: goal.goalCondition }, journeyLimit)
+ );
return reply.send({
journeys: data.map(item => ({
path: item.journey,
count: Number(item.sessions_count),
percentage: Number(item.percentage),
+ ...(item.conversions !== undefined ? { conversions: Number(item.conversions) } : {}),
})),
+ // Sessions with two or more pages in the period, before the step filters.
+ totalSessions: Number(data[0]?.total_sessions ?? 0),
});
} catch (error) {
request.log.error({ err: error instanceof AnalyticsQueryError ? error.original : error }, "Error getting journeys");
diff --git a/server/src/api/analytics/getPages.clickhouse.test.ts b/server/src/api/analytics/getPages.clickhouse.test.ts
new file mode 100644
index 000000000..bc9349256
--- /dev/null
+++ b/server/src/api/analytics/getPages.clickhouse.test.ts
@@ -0,0 +1,231 @@
+import { createClient } from "@clickhouse/client";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+// Run against any ClickHouse using CLICKHOUSE_TEST_URL and optional
+// CLICKHOUSE_TEST_USER / CLICKHOUSE_TEST_PASSWORD. Every query supplies its own
+// events CTE: no tables, migrations or production data are needed.
+vi.mock("../../db/clickhouse/clickhouse.js", () => ({ clickhouse: {} }));
+
+import {
+ buildPagesQuery,
+ buildPagesSummaryQuery,
+ buildPageTrendsQuery,
+ buildSectionViewsQuery,
+ groupTrendRows,
+ pagesQuerySchema,
+ trendsQuerySchema,
+} from "./getPages.js";
+
+// site, time, session, path, title, type
+const events: [number, string, string, string, string, string][] = [
+ // A four-page visit: enters on /, leaves from /pricing.
+ [1, "2026-09-10 09:00:00", "s1", "/", "Home", "pageview"],
+ [1, "2026-09-10 09:00:30", "s1", "/docs", "Docs", "pageview"],
+ [1, "2026-09-10 09:01:30", "s1", "/docs/script", "Script", "pageview"],
+ [1, "2026-09-10 09:02:30", "s1", "/pricing", "Pricing", "pageview"],
+ // A bounce on /pricing.
+ [1, "2026-09-10 10:00:00", "s2", "/pricing", "Pricing", "pageview"],
+ // Enters and leaves on /docs/script, with an untitled page between; the
+ // page's latest title wins.
+ [1, "2026-09-10 11:00:00", "s3", "/docs/script", "Tracking script", "pageview"],
+ [1, "2026-09-10 11:00:20", "s3", "/docs/api", "", "pageview"],
+ [1, "2026-09-10 11:00:50", "s3", "/docs/script", "Tracking script", "pageview"],
+ // 40 minutes on /blog/a is capped at 30.
+ [1, "2026-09-10 12:00:00", "s4", "/blog/a", "A", "pageview"],
+ [1, "2026-09-10 12:40:00", "s4", "/", "Home", "pageview"],
+ // Not pageviews, or not this site, or not this period.
+ [1, "2026-09-10 13:00:00", "s5", "/pricing", "Pricing", "custom_event"],
+ [2, "2026-09-10 13:00:00", "s6", "/pricing", "Pricing", "pageview"],
+ [1, "2026-09-09 13:00:00", "s7", "/pricing", "Pricing", "pageview"],
+];
+const fixture = `WITH events AS (SELECT * FROM values(
+ 'site_id Int32, timestamp DateTime(\\'UTC\\'), timestamp_ms DateTime64(3, \\'UTC\\'), session_id String, pathname String, page_title String, type String',
+ ${events.map(([site, time, session, path, title, type]) => `(${site}, '${time}', '${time}', '${session}', '${path}', '${title}', '${type}')`).join(",")}
+))`;
+
+const day = { start_date: "2026-09-10", end_date: "2026-09-10", time_zone: "UTC", filters: "" };
+const pathnameFilter = JSON.stringify([{ parameter: "pathname", type: "equals", value: ["/pricing"] }]);
+
+describe.skipIf(!process.env.CLICKHOUSE_TEST_URL)("Pages report: ClickHouse results", () => {
+ let client: ReturnType<typeof createClient>;
+
+ beforeAll(() => {
+ client = createClient({
+ url: process.env.CLICKHOUSE_TEST_URL,
+ username: process.env.CLICKHOUSE_TEST_USER || "default",
+ password: process.env.CLICKHOUSE_TEST_PASSWORD || "",
+ compression: { request: false, response: false },
+ clickhouse_settings: { readonly: "2", max_threads: 2, max_execution_time: 10 },
+ });
+ });
+ afterAll(async () => {
+ await client.close();
+ });
+
+ async function run<T>({ query, params }: { query: string; params?: Record<string, unknown> }) {
+ const sql = /^\s*WITH\b/.test(query) ? query.replace(/^\s*WITH\b/, `${fixture},`) : `${fixture} ${query}`;
+ const result = await client.query({ query: sql, query_params: params, format: "JSONEachRow" });
+ const rows = await result.json<Record<string, unknown>>();
+ // ClickHouse sends 64-bit counts as strings; compare numbers.
+ return rows.map(row =>
+ Object.fromEntries(
+ Object.entries(row).map(([key, value]) => [
+ key,
+ typeof value === "string" && value !== "" && !isNaN(Number(value)) && key !== "key" && key !== "section"
+ ? Number(value)
+ : value,
+ ])
+ )
+ ) as T[];
+ }
+
+ const pages = (query: Record<string, unknown> = {}, params = day) =>
+ run<Record<string, unknown>>(buildPagesQuery(params, pagesQuerySchema.parse(query), 1));
+
+ it("keys rows by path with entries, exits, entry bounce and time on page without exit views", async () => {
+ const rows = await pages();
+ expect(rows.map(row => row.key)).toEqual(["/docs/script", "/", "/pricing", "/blog/a", "/docs", "/docs/api"]);
+
+ const byKey = Object.fromEntries(rows.map(row => [row.key, row]));
+ expect(byKey["/docs/script"]).toMatchObject({
+ kind: "page",
+ title: "Tracking script",
+ section: "/docs",
+ pageviews: 3,
+ sessions: 2,
+ entries: 1,
+ exits: 1,
+ bounced_entries: 0,
+ // 60s in s1 and 20s in s3; s3's closing view is its exit and has no time on page.
+ time_on_page_seconds: 40,
+ bounce_rate: 0,
+ total_count: 6,
+ });
+ expect(byKey["/pricing"]).toMatchObject({
+ pageviews: 2,
+ sessions: 2,
+ entries: 1,
+ exits: 2,
+ bounced_entries: 1,
+ time_on_page_seconds: null,
+ bounce_rate: 100,
+ });
+ expect(byKey["/blog/a"]).toMatchObject({ time_on_page_seconds: 1800, entries: 1, exits: 0 });
+ expect(byKey["/docs"]).toMatchObject({ entries: 0, exits: 0, bounce_rate: null, time_on_page_seconds: 60 });
+ expect(byKey["/docs/api"]).toMatchObject({ title: "", time_on_page_seconds: 30 });
+ });
+
+ it("rolls pages up into sections and lists a one-page section as that page", async () => {
+ const rows = await pages({ group: "section" });
+ expect(rows.map(row => [row.kind, row.key, row.pages])).toEqual([
+ ["section", "/docs", 3],
+ ["page", "/", 1],
+ ["page", "/pricing", 1],
+ ["page", "/blog/a", 1],
+ ]);
+ expect(rows[0]).toMatchObject({
+ title: "",
+ pageviews: 5,
+ // Distinct sessions across the section, not the sum of its pages' sessions.
+ sessions: 2,
+ entries: 1,
+ exits: 1,
+ time_on_page_seconds: 42.5,
+ total_count: 4,
+ });
+ });
+
+ it("lists a section's pages with the same figures as the full list", async () => {
+ const all = await pages();
+ const children = await pages({ section: "/docs" });
+ expect(children.map(row => row.key)).toEqual(["/docs/script", "/docs", "/docs/api"]);
+ for (const child of children) {
+ const { total_count: _, ...figures } = child;
+ expect(all.find(row => row.key === child.key)).toMatchObject(figures);
+ }
+ });
+
+ it("sorts, filters to entry or exit pages, searches and paginates", async () => {
+ expect((await pages({ mode: "entry", sort: "entries" })).map(row => row.key)).toEqual([
+ "/",
+ "/blog/a",
+ "/docs/script",
+ "/pricing",
+ ]);
+ expect((await pages({ mode: "exit", sort: "exits" })).map(row => row.key)).toEqual([
+ "/pricing",
+ "/",
+ "/docs/script",
+ ]);
+ expect((await pages({ sort: "time_on_page", order: "asc" })).map(row => row.key)).toEqual([
+ "/",
+ "/docs/api",
+ "/docs/script",
+ "/docs",
+ "/blog/a",
+ // No time on page sorts last in either direction.
+ "/pricing",
+ ]);
+ expect((await pages({ search: "TRACKING" })).map(row => row.key)).toEqual(["/docs/script"]);
+ expect((await pages({ search: "pric" })).map(row => row.key)).toEqual(["/pricing"]);
+ const second = await pages({ limit: 2, page: 2 });
+ expect(second.map(row => row.key)).toEqual(["/pricing", "/blog/a"]);
+ expect(second[0].total_count).toBe(6);
+ });
+
+ it("applies filters to whole sessions", async () => {
+ const rows = await pages({}, { ...day, filters: pathnameFilter });
+ expect(rows.map(row => [row.key, row.pageviews])).toEqual([
+ ["/pricing", 2],
+ ["/", 1],
+ ["/docs", 1],
+ ["/docs/script", 1],
+ ]);
+ });
+
+ it("summarises the period", async () => {
+ const [summary] = await run<Record<string, unknown>>(buildPagesSummaryQuery(day, 1));
+ expect(summary).toMatchObject({
+ pageviews: 10,
+ sessions: 4,
+ pages: 6,
+ bounced_sessions: 1,
+ bounce_rate: 25,
+ views_per_session: 2.5,
+ });
+ expect(summary.time_on_page_seconds).toBeCloseTo(2000 / 6, 5);
+
+ const sections = await run<Record<string, unknown>>(buildSectionViewsQuery(day, 1));
+ expect(sections.map(row => [row.section, row.pageviews, row.pages])).toEqual([
+ ["/docs", 5, 3],
+ ["/", 2, 1],
+ ["/pricing", 2, 1],
+ ["/blog", 1, 1],
+ ]);
+ expect(sections[0].total_count).toBe(4);
+ });
+
+ it("returns one zero-filled series per requested path and section", async () => {
+ const query = trendsQuerySchema.parse({
+ bucket: "hour",
+ paths: JSON.stringify(["/pricing", "/nowhere"]),
+ sections: JSON.stringify(["/docs"]),
+ });
+ const rows = await run<{ key: string; time: string; pageviews: number }>(buildPageTrendsQuery(day, query, 1));
+ const trends = groupTrendRows(rows);
+
+ expect(trends.map(trend => [trend.kind, trend.key, trend.pageviews])).toEqual([
+ ["page", "/pricing", 2],
+ ["section", "/docs", 5],
+ ]);
+ for (const trend of trends) {
+ expect(trend.series).toHaveLength(24);
+ expect(trend.series[0].time).toBe("2026-09-10 00:00:00");
+ }
+ const pricing = trends[0].series.filter(point => point.pageviews > 0);
+ expect(pricing).toEqual([
+ { time: "2026-09-10 09:00:00", pageviews: 1 },
+ { time: "2026-09-10 10:00:00", pageviews: 1 },
+ ]);
+ });
+});
diff --git a/server/src/api/analytics/getPages.test.ts b/server/src/api/analytics/getPages.test.ts
new file mode 100644
index 000000000..771ababc3
--- /dev/null
+++ b/server/src/api/analytics/getPages.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../../db/clickhouse/clickhouse.js", () => ({
+ clickhouse: { query: vi.fn() },
+}));
+vi.mock("../../db/postgres/postgres.js", () => ({
+ db: {},
+}));
+
+import {
+ buildPagesQuery,
+ buildPageTrendsQuery,
+ groupTrendRows,
+ MAX_TREND_KEYS,
+ pagesQuerySchema,
+ trendsQuerySchema,
+} from "./getPages.js";
+
+const params = {
+ start_date: "2026-08-01",
+ end_date: "2026-08-31",
+ time_zone: "UTC",
+ filters: "",
+};
+const campaignFilter = JSON.stringify([{ parameter: "utm_campaign", type: "equals", value: ["spring"] }]);
+
+describe("pagesQuerySchema", () => {
+ it("defaults to all pages by views, 25 at a time", () => {
+ expect(pagesQuerySchema.parse({})).toEqual({
+ group: "page",
+ mode: "all",
+ sort: "pageviews",
+ order: "desc",
+ limit: 25,
+ page: 1,
+ });
+ });
+
+ it("rejects unknown sort columns, oversized pages and sections inside sections", () => {
+ expect(pagesQuerySchema.safeParse({ sort: "pathname; DROP TABLE events" }).success).toBe(false);
+ expect(pagesQuerySchema.safeParse({ limit: "500" }).success).toBe(false);
+ expect(pagesQuerySchema.safeParse({ page: "0" }).success).toBe(false);
+ expect(pagesQuerySchema.safeParse({ group: "section", section: "/docs" }).success).toBe(false);
+ expect(pagesQuerySchema.safeParse({ group: "section", search: "docs" }).success).toBe(false);
+ });
+
+ it("treats a blank search as none", () => {
+ expect(pagesQuerySchema.parse({ group: "section", search: " " }).search).toBeUndefined();
+ });
+});
+
+describe("trendsQuerySchema", () => {
+ it("parses JSON key lists and needs at least one key", () => {
+ expect(trendsQuerySchema.parse({ paths: '["/a"]', sections: '["/docs"]' })).toEqual({
+ bucket: "day",
+ paths: ["/a"],
+ sections: ["/docs"],
+ });
+ expect(trendsQuerySchema.safeParse({}).success).toBe(false);
+ expect(trendsQuerySchema.safeParse({ paths: "not json" }).success).toBe(false);
+ expect(trendsQuerySchema.safeParse({ paths: "[1]" }).success).toBe(false);
+ expect(trendsQuerySchema.safeParse({ bucket: "decade", paths: '["/a"]' }).success).toBe(false);
+ });
+
+ it(`caps a batch at ${MAX_TREND_KEYS} keys`, () => {
+ const keys = (count: number, prefix: string) =>
+ JSON.stringify(Array.from({ length: count }, (_, i) => `${prefix}${i}`));
+ expect(trendsQuerySchema.safeParse({ paths: keys(MAX_TREND_KEYS, "/p") }).success).toBe(true);
+ expect(trendsQuerySchema.safeParse({ paths: keys(MAX_TREND_KEYS + 1, "/p") }).success).toBe(false);
+ expect(trendsQuerySchema.safeParse({ paths: keys(30, "/p"), sections: keys(30, "/s") }).success).toBe(false);
+ });
+});
+
+describe("buildPagesQuery", () => {
+ it("binds search and section as parameters instead of interpolating them", () => {
+ const spec = buildPagesQuery(params, pagesQuerySchema.parse({ section: "/it's", search: "o'brien" }), 1);
+
+ expect(spec.query).not.toContain("o'brien");
+ expect(spec.query).not.toContain("/it's");
+ expect(spec.query).toContain("{search:String}");
+ expect(spec.query).toContain("{section:String}");
+ expect(spec.params).toEqual({ siteId: 1, section: "/it's", search: "o'brien" });
+ });
+
+ it("groups rows by path, not by title", () => {
+ const { query } = buildPagesQuery(params, pagesQuerySchema.parse({}), 1);
+
+ expect(query).toContain("GROUP BY pathname");
+ expect(query).not.toContain("GROUP BY page_title");
+ expect(query).not.toContain("GROUP BY section");
+ });
+
+ it("orders by the whitelisted column with nulls last and pages with LIMIT and OFFSET", () => {
+ const { query } = buildPagesQuery(
+ params,
+ pagesQuerySchema.parse({ sort: "bounce_rate", order: "asc", limit: "10", page: "3" }),
+ 1
+ );
+
+ expect(query).toContain("ORDER BY bounce_rate ASC NULLS LAST, key ASC");
+ expect(query).toContain("LIMIT 10 OFFSET 20");
+ });
+
+ it("breaks ties in section mode the way the section list does", () => {
+ const { query } = buildPagesQuery(params, pagesQuerySchema.parse({ group: "section" }), 1);
+
+ expect(query).toContain("ORDER BY pageviews DESC NULLS LAST, section ASC");
+ });
+
+ it("filters entry and exit pages per page, and per section in section mode", () => {
+ const entryPages = buildPagesQuery(params, pagesQuerySchema.parse({ mode: "entry" }), 1).query;
+ const exitSections = buildPagesQuery(params, pagesQuerySchema.parse({ mode: "exit", group: "section" }), 1).query;
+
+ expect(entryPages).toContain("HAVING entry_views > 0");
+ expect(exitSections).toContain("GROUP BY section");
+ expect(exitSections).toContain("HAVING exits > 0");
+ expect(exitSections).not.toContain("exit_views > 0");
+ });
+
+ it("qualifies whole sessions with the filters before measuring pages", () => {
+ const { query } = buildPagesQuery({ ...params, filters: campaignFilter }, pagesQuerySchema.parse({}), 1);
+
+ expect(query).toContain("FilteredSessions AS (");
+ expect(query).toContain("INNER JOIN FilteredSessions USING (session_id)");
+ expect(query.slice(query.indexOf("PageViews AS ("))).not.toContain("url_parameters['utm_campaign']");
+ });
+
+ it("keeps whole sessions when listing one section", () => {
+ const { query } = buildPagesQuery(params, pagesQuerySchema.parse({ section: "/docs" }), 1);
+
+ // The section narrows the sessions read, then the pages listed; never the views inside a session.
+ expect(query).toMatch(/AND session_id IN \(\s*SELECT session_id/);
+ expect(query).toContain("WHERE extract(pathname, '^/?[^/]*') = {section:String}");
+ });
+});
+
+describe("buildPageTrendsQuery", () => {
+ it("binds the key lists and zero-fills each key's series", () => {
+ const query = trendsQuerySchema.parse({ bucket: "day", paths: '["/a"]', sections: '["/docs"]' });
+ const spec = buildPageTrendsQuery(params, query, 1);
+
+ expect(spec.params).toEqual({ siteId: 1, paths: ["/a"], sections: ["/docs"] });
+ expect(spec.query).toContain("{paths:Array(String)}");
+ expect(spec.query).toContain("ORDER BY key, time WITH FILL");
+ expect(spec.query).not.toContain("'/a'");
+ });
+});
+
+describe("groupTrendRows", () => {
+ it("splits keys into pages and sections and totals each series", () => {
+ expect(
+ groupTrendRows([
+ { key: "page:/a:b", time: "2026-08-01 00:00:00", pageviews: 2 },
+ { key: "page:/a:b", time: "2026-08-02 00:00:00", pageviews: 0 },
+ { key: "section:/docs", time: "2026-08-01 00:00:00", pageviews: 5 },
+ ])
+ ).toEqual([
+ {
+ kind: "page",
+ key: "/a:b",
+ pageviews: 2,
+ series: [
+ { time: "2026-08-01 00:00:00", pageviews: 2 },
+ { time: "2026-08-02 00:00:00", pageviews: 0 },
+ ],
+ },
+ { kind: "section", key: "/docs", pageviews: 5, series: [{ time: "2026-08-01 00:00:00", pageviews: 5 }] },
+ ]);
+ });
+});
diff --git a/server/src/api/analytics/getPages.ts b/server/src/api/analytics/getPages.ts
new file mode 100644
index 000000000..3cf2fe6d0
--- /dev/null
+++ b/server/src/api/analytics/getPages.ts
@@ -0,0 +1,474 @@
+import { FilterParams, TimeBucket } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import { analyticsRoute, QuerySpec, runAnalyticsQuery } from "./utils/analyticsQuery.js";
+import { buildFilteredSessionsCTE } from "./utils/sessionFilters.js";
+import { resolveTimeWindow, TimeBucketToFn, TimeWindowParams } from "./utils/timeWindow.js";
+
+/**
+ * The Pages report: one row per path (or per section), with the entry and exit
+ * counts, time on page and entry bounce rate that the main dashboard only shows
+ * on separate tabs.
+ *
+ * Every figure comes from the same per-pageview pass: each pageview knows the
+ * session's previous and next pageview, so a view with no previous one is the
+ * session's entry, a view with no next one is its exit, and a view with neither
+ * is a bounce. Time on page is the gap to the next view, so exit views have no
+ * time on page and are left out of the average instead of counting as 0s.
+ */
+
+/** A path's section is its first segment: "/docs" and "/docs/script" are both in "/docs"; "/" is its own. */
+export const sectionOf = (column: string) => `extract(${column}, '^/?[^/]*')`;
+
+// Same 30-minute cap as the other time-on-page figures, so one tab left open
+// overnight does not swamp a page's average.
+const MAX_TIME_ON_PAGE_SECONDS = 1800;
+const timeOnPage = `least(greatest(dateDiff('second', timestamp_ms, next_view), 0), ${MAX_TIME_ON_PAGE_SECONDS})`;
+
+const SORT_COLUMNS = {
+ pageviews: "pageviews",
+ sessions: "sessions",
+ entries: "entries",
+ exits: "exits",
+ time_on_page: "time_on_page_seconds",
+ bounce_rate: "bounce_rate",
+} as const;
+
+export type PagesSort = keyof typeof SORT_COLUMNS;
+
+// The section list is only used whole (the "only section losing traffic" check
+// needs every section), so it is capped rather than paginated.
+export const MAX_SECTIONS = 500;
+export const MAX_TREND_KEYS = 50;
+
+const optionalText = (max: number) =>
+ z
+ .string()
+ .trim()
+ .max(max)
+ .optional()
+ .transform(value => value || undefined);
+
+export const pagesQuerySchema = z
+ .object({
+ group: z.enum(["page", "section"]).default("page"),
+ section: optionalText(2048),
+ mode: z.enum(["all", "entry", "exit"]).default("all"),
+ sort: z.enum(Object.keys(SORT_COLUMNS) as [PagesSort, ...PagesSort[]]).default("pageviews"),
+ order: z.enum(["asc", "desc"]).default("desc"),
+ search: optionalText(200),
+ limit: z.coerce.number().int().min(1).max(100).default(25),
+ page: z.coerce.number().int().min(1).max(10_000).default(1),
+ })
+ // A section row is a rollup of all its pages, so it cannot be narrowed by a
+ // search or nested in another section.
+ .refine(query => query.group === "page" || (!query.section && !query.search), {
+ message: "section and search only apply to page rows",
+ });
+
+export type PagesQuery = z.infer<typeof pagesQuerySchema>;
+
+const keyListSchema = z
+ .string()
+ .optional()
+ .transform((raw, ctx) => {
+ if (!raw) return [];
+ try {
+ return z.array(z.string().max(2048)).max(MAX_TREND_KEYS).parse(JSON.parse(raw));
+ } catch {
+ ctx.addIssue({ code: "custom", message: `Expected a JSON array of at most ${MAX_TREND_KEYS} strings` });
+ return z.NEVER;
+ }
+ });
+
+export const trendsQuerySchema = z
+ .object({
+ bucket: z.enum(Object.keys(TimeBucketToFn) as [TimeBucket, ...TimeBucket[]]).default("day"),
+ paths: keyListSchema,
+ sections: keyListSchema,
+ })
+ .refine(query => query.paths.length + query.sections.length > 0, { message: "Pass paths or sections" })
+ .refine(query => query.paths.length + query.sections.length <= MAX_TREND_KEYS, {
+ message: `At most ${MAX_TREND_KEYS} paths and sections in total`,
+ });
+
+export type TrendsQuery = z.infer<typeof trendsQuerySchema>;
+
+type WindowParams = TimeWindowParams & Pick<FilterParams, "filters">;
+
+/** The filtered-sessions CTE and the join that applies it, built the way every session-scoped report builds them. */
+function sessionScope(params: WindowParams, siteId: number) {
+ const timeStatement = resolveTimeWindow(params).where();
+ const filteredSessionsCTE = buildFilteredSessionsCTE(params.filters, siteId, timeStatement);
+ return {
+ timeStatement,
+ filteredSessionsCTE,
+ sessionJoin: filteredSessionsCTE ? "INNER JOIN FilteredSessions USING (session_id)" : "",
+ };
+}
+
+const withClause = (...ctes: (string | null | undefined)[]) => {
+ const present = ctes.filter(Boolean);
+ return present.length ? `WITH ${present.join(",\n")}` : "";
+};
+
+/**
+ * One row per pageview with the session's previous and next pageview beside
+ * it. `restrictTo` keeps only sessions that viewed a matching page, which keeps
+ * the window small for a single section without cutting any session short.
+ */
+function pageViewsCTE(siteId: number, scope: ReturnType<typeof sessionScope>, restrictTo?: string) {
+ const restriction = restrictTo
+ ? `AND session_id IN (
+ SELECT session_id
+ FROM events
+ WHERE site_id = {siteId:Int32}
+ AND type = 'pageview'
+ ${scope.timeStatement}
+ AND ${restrictTo}
+ )`
+ : "";
+
+ return `PageViews AS (
+ SELECT
+ session_id,
+ pathname,
+ page_title,
+ timestamp_ms,
+ lagInFrame(toNullable(timestamp_ms)) OVER (
+ PARTITION BY session_id ORDER BY timestamp_ms ROWS BETWEEN 1 PRECEDING AND CURRENT ROW
+ ) AS previous_view,
+ leadInFrame(toNullable(timestamp_ms)) OVER (
+ PARTITION BY session_id ORDER BY timestamp_ms ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING
+ ) AS next_view
+ FROM events
+ ${scope.sessionJoin}
+ WHERE site_id = {siteId:Int32}
+ AND type = 'pageview'
+ ${scope.timeStatement}
+ ${restriction}
+ )`;
+}
+
+export interface PageRow {
+ /** "section" rows roll up two or more pages; a section with one page is listed as that page. */
+ kind: "page" | "section";
+ /** The path for a page row, the section for a section row. */
+ key: string;
+ /** The page's most recent non-empty title; empty for sections and untitled pages. */
+ title: string;
+ section: string;
+ pages: number;
+ pageviews: number;
+ sessions: number;
+ entries: number;
+ exits: number;
+ bounced_entries: number;
+ /** Average seconds to the next pageview, over views that were not the session's last. */
+ time_on_page_seconds: number | null;
+ /** Share of the sessions that entered here and viewed nothing else, 0–100. */
+ bounce_rate: number | null;
+}
+
+export const buildPagesQuery = (params: WindowParams, query: PagesQuery, siteId: number): QuerySpec => {
+ const scope = sessionScope(params, siteId);
+ const sectionFilter = query.section ? `${sectionOf("pathname")} = {section:String}` : undefined;
+ const pageHaving = [
+ query.group === "page" && query.mode === "entry" ? "entry_views > 0" : "",
+ query.group === "page" && query.mode === "exit" ? "exit_views > 0" : "",
+ query.search
+ ? "(positionCaseInsensitiveUTF8(pathname, {search:String}) > 0 OR positionCaseInsensitiveUTF8(title, {search:String}) > 0)"
+ : "",
+ ].filter(Boolean);
+ const sectionHaving = query.mode === "entry" ? "HAVING entries > 0" : query.mode === "exit" ? "HAVING exits > 0" : "";
+
+ const pageStats = `PageStats AS (
+ SELECT
+ pathname,
+ ${sectionOf("pathname")} AS section,
+ argMaxIf(page_title, timestamp_ms, page_title != '') AS title,
+ count() AS page_views,
+ uniqExactState(session_id) AS session_state,
+ countIf(previous_view IS NULL) AS entry_views,
+ countIf(next_view IS NULL) AS exit_views,
+ countIf(previous_view IS NULL AND next_view IS NULL) AS bounced_views,
+ sumIf(${timeOnPage}, next_view IS NOT NULL) AS timed_seconds,
+ countIf(next_view IS NOT NULL) AS timed_views
+ FROM PageViews
+ ${sectionFilter ? `WHERE ${sectionFilter}` : ""}
+ GROUP BY pathname
+ ${pageHaving.length ? `HAVING ${pageHaving.join(" AND ")}` : ""}
+ )`;
+
+ const rows =
+ query.group === "section"
+ ? `SELECT
+ if(count() = 1, 'page', 'section') AS kind,
+ if(count() = 1, any(pathname), section) AS key,
+ if(count() = 1, any(title), '') AS title,
+ section,
+ count() AS pages,
+ sum(page_views) AS pageviews,
+ uniqExactMerge(session_state) AS sessions,
+ sum(entry_views) AS entries,
+ sum(exit_views) AS exits,
+ sum(bounced_views) AS bounced_entries,
+ sum(timed_seconds) / nullIf(sum(timed_views), 0) AS time_on_page_seconds,
+ sum(bounced_views) * 100 / nullIf(sum(entry_views), 0) AS bounce_rate,
+ count() OVER () AS total_count
+ FROM PageStats
+ GROUP BY section
+ ${sectionHaving}`
+ : `SELECT
+ 'page' AS kind,
+ pathname AS key,
+ title,
+ section,
+ 1 AS pages,
+ page_views AS pageviews,
+ finalizeAggregation(session_state) AS sessions,
+ entry_views AS entries,
+ exit_views AS exits,
+ bounced_views AS bounced_entries,
+ timed_seconds / nullIf(timed_views, 0) AS time_on_page_seconds,
+ bounced_views * 100 / nullIf(entry_views, 0) AS bounce_rate,
+ count() OVER () AS total_count
+ FROM PageStats`;
+
+ const offset = (query.page - 1) * query.limit;
+
+ return {
+ query: `
+ ${withClause(scope.filteredSessionsCTE, pageViewsCTE(siteId, scope, sectionFilter), pageStats)}
+ ${rows}
+ ORDER BY ${SORT_COLUMNS[query.sort]} ${query.order === "asc" ? "ASC" : "DESC"} NULLS LAST, ${
+ // Ties break the way the section list does, so a section's place there is its place here.
+ query.group === "section" ? "section" : "key"
+ } ASC
+ LIMIT ${query.limit}${offset > 0 ? ` OFFSET ${offset}` : ""}
+ `,
+ params: {
+ siteId,
+ ...(query.section ? { section: query.section } : {}),
+ ...(query.search ? { search: query.search } : {}),
+ },
+ };
+};
+
+export interface PagesSummary {
+ pageviews: number;
+ /** Sessions with at least one pageview; each of them has exactly one entry page. */
+ sessions: number;
+ /** Distinct paths viewed. */
+ pages: number;
+ bounced_sessions: number;
+ bounce_rate: number | null;
+ time_on_page_seconds: number | null;
+ views_per_session: number | null;
+}
+
+export const buildPagesSummaryQuery = (params: WindowParams, siteId: number): QuerySpec => {
+ const scope = sessionScope(params, siteId);
+ return {
+ query: `
+ ${withClause(scope.filteredSessionsCTE, pageViewsCTE(siteId, scope))}
+ SELECT
+ count() AS pageviews,
+ uniqExact(session_id) AS sessions,
+ uniqExact(pathname) AS pages,
+ countIf(previous_view IS NULL AND next_view IS NULL) AS bounced_sessions,
+ bounced_sessions * 100 / nullIf(sessions, 0) AS bounce_rate,
+ sumIf(${timeOnPage}, next_view IS NOT NULL) / nullIf(countIf(next_view IS NOT NULL), 0) AS time_on_page_seconds,
+ pageviews / nullIf(sessions, 0) AS views_per_session
+ FROM PageViews
+ `,
+ params: { siteId },
+ };
+};
+
+export interface SectionViews {
+ section: string;
+ pageviews: number;
+ pages: number;
+}
+
+/** Views and page count per section, largest first, for the whole period. */
+export const buildSectionViewsQuery = (params: WindowParams, siteId: number): QuerySpec => {
+ const scope = sessionScope(params, siteId);
+ return {
+ query: `
+ ${withClause(
+ scope.filteredSessionsCTE,
+ `Sections AS (
+ SELECT
+ ${sectionOf("pathname")} AS section,
+ count() AS pageviews,
+ uniqExact(pathname) AS pages
+ FROM events
+ ${scope.sessionJoin}
+ WHERE site_id = {siteId:Int32}
+ AND type = 'pageview'
+ ${scope.timeStatement}
+ GROUP BY section
+ )`
+ )}
+ SELECT section, pageviews, pages, count() OVER () AS total_count
+ FROM Sections
+ ORDER BY pageviews DESC, section ASC
+ LIMIT ${MAX_SECTIONS}
+ `,
+ params: { siteId },
+ };
+};
+
+export interface PageTrend {
+ kind: "page" | "section";
+ key: string;
+ /** Total views in the period, the sum of `series`. */
+ pageviews: number;
+ series: { time: string; pageviews: number }[];
+}
+
+/**
+ * Views per bucket for a batch of paths and sections in one pass. A view counts
+ * toward its path and toward its section when both were asked for. Each key's
+ * series is zero-filled across the window (ClickHouse fills per value of the
+ * sorting prefix, here the key); a key with no views in the window is absent.
+ */
+export const buildPageTrendsQuery = (
+ params: WindowParams,
+ { bucket, paths, sections }: TrendsQuery,
+ siteId: number
+): QuerySpec => {
+ const window = resolveTimeWindow(params);
+ const scope = sessionScope(params, siteId);
+ const section = sectionOf("pathname");
+
+ return {
+ query: `
+ ${withClause(scope.filteredSessionsCTE)}
+ SELECT key, time, pageviews
+ FROM (
+ SELECT
+ arrayJoin(
+ arrayConcat(
+ if(has({paths:Array(String)}, pathname), [concat('page:', pathname)], []),
+ if(has({sections:Array(String)}, ${section}), [concat('section:', ${section})], [])
+ )
+ ) AS key,
+ ${window.bucketed("timestamp", bucket)} AS time,
+ count() AS pageviews
+ FROM events
+ ${scope.sessionJoin}
+ WHERE site_id = {siteId:Int32}
+ AND type = 'pageview'
+ ${scope.timeStatement}
+ AND (pathname IN {paths:Array(String)} OR ${section} IN {sections:Array(String)})
+ GROUP BY key, time
+ )
+ ORDER BY key, time ${window.fill(bucket)}
+ `,
+ params: { siteId, paths, sections },
+ };
+};
+
+/** Groups trend rows by key. Rows must arrive ordered by key, then time. */
+export function groupTrendRows(rows: { key: string; time: string; pageviews: number }[]): PageTrend[] {
+ const trends = new Map<string, PageTrend>();
+ for (const row of rows) {
+ const rawKey = String(row.key);
+ const separator = rawKey.indexOf(":");
+ let trend = trends.get(rawKey);
+ if (!trend) {
+ trend = {
+ kind: rawKey.slice(0, separator) === "section" ? "section" : "page",
+ key: rawKey.slice(separator + 1),
+ pageviews: 0,
+ series: [],
+ };
+ trends.set(rawKey, trend);
+ }
+ const pageviews = Number(row.pageviews) || 0;
+ trend.pageviews += pageviews;
+ trend.series.push({ time: String(row.time), pageviews });
+ }
+ return [...trends.values()];
+}
+
+// processResults turns numeric-looking strings into numbers, so a page titled
+// "404" or a path section "2024" would come back as a number.
+const asText = (value: unknown) => (value === null || value === undefined ? "" : String(value));
+
+type PagesRequest<Q> = { Params: { siteId: string }; Querystring: FilterParams<Q> };
+
+export const getPages = analyticsRoute<PagesRequest<Record<string, string | undefined>>>(
+ "pages",
+ async (req: FastifyRequest<PagesRequest<Record<string, string | undefined>>>, res: FastifyReply) => {
+ const parsed = pagesQuerySchema.safeParse(req.query);
+ if (!parsed.success) {
+ return res.status(400).send({ error: parsed.error.issues.map(issue => issue.message).join("; ") });
+ }
+
+ const siteId = Number(req.params.siteId);
+ const rows = await runAnalyticsQuery<PageRow & { total_count: number }>(
+ buildPagesQuery(req.query, parsed.data, siteId)
+ );
+
+ // The total rides on the rows, so a page past the end has none to carry it.
+ let totalCount = rows[0]?.total_count ?? 0;
+ if (rows.length === 0 && parsed.data.page > 1) {
+ const [first] = await runAnalyticsQuery<{ total_count: number }>(
+ buildPagesQuery(req.query, { ...parsed.data, page: 1, limit: 1 }, siteId)
+ );
+ totalCount = first?.total_count ?? 0;
+ }
+
+ return res.send({
+ data: {
+ data: rows.map(({ total_count: _, ...row }) => ({
+ ...row,
+ key: asText(row.key),
+ title: asText(row.title),
+ section: asText(row.section),
+ })),
+ totalCount,
+ },
+ });
+ }
+);
+
+export const getPagesSummary = analyticsRoute<PagesRequest<object>>(
+ "pages summary",
+ async (req: FastifyRequest<PagesRequest<object>>, res: FastifyReply) => {
+ const siteId = Number(req.params.siteId);
+ const [totals, sections] = await Promise.all([
+ runAnalyticsQuery<PagesSummary>(buildPagesSummaryQuery(req.query, siteId)),
+ runAnalyticsQuery<SectionViews & { total_count: number }>(buildSectionViewsQuery(req.query, siteId)),
+ ]);
+
+ return res.send({
+ data: {
+ ...totals[0],
+ sections: sections.map(({ total_count: _, ...row }) => ({ ...row, section: asText(row.section) })),
+ sectionCount: sections[0]?.total_count ?? 0,
+ },
+ });
+ }
+);
+
+export const getPageTrends = analyticsRoute<PagesRequest<Record<string, string | undefined>>>(
+ "page trends",
+ async (req: FastifyRequest<PagesRequest<Record<string, string | undefined>>>, res: FastifyReply) => {
+ const parsed = trendsQuerySchema.safeParse(req.query);
+ if (!parsed.success) {
+ return res.status(400).send({ error: parsed.error.issues.map(issue => issue.message).join("; ") });
+ }
+
+ const siteId = Number(req.params.siteId);
+ const rows = await runAnalyticsQuery<{ key: string; time: string; pageviews: number }>(
+ buildPageTrendsQuery(req.query, parsed.data, siteId)
+ );
+
+ return res.send({ data: groupTrendRows(rows) });
+ }
+);
diff --git a/server/src/api/analytics/getRetention.test.ts b/server/src/api/analytics/getRetention.test.ts
new file mode 100644
index 000000000..229382fab
--- /dev/null
+++ b/server/src/api/analytics/getRetention.test.ts
@@ -0,0 +1,273 @@
+import { describe, expect, it, vi } from "vitest";
+
+const query = vi.fn();
+vi.mock("../../db/clickhouse/clickhouse.js", () => ({
+ clickhouse: { query: (...args: unknown[]) => query(...args) },
+}));
+
+import {
+ buildRetentionQuery,
+ buildRetentionQueryParams,
+ getRetention,
+ MAX_COHORTS,
+ processRetentionData,
+ resolveRetentionWindow,
+ RETENTION_LOOKBACK_DAYS,
+} from "./getRetention.js";
+
+// Wednesday Sep 30, 2026, 11:00 in New York.
+const NOW = Date.parse("2026-09-30T15:00:00Z");
+const NY = "America/New_York";
+
+describe("resolveRetentionWindow", () => {
+ it("lays Monday-start weeks over a date range and ends a range that includes today at now", () => {
+ const window = resolveRetentionWindow(
+ { start_date: "2026-08-03", end_date: "2026-09-30", time_zone: NY },
+ "week",
+ NOW
+ );
+
+ expect(window.periods).toEqual([
+ "2026-08-03",
+ "2026-08-10",
+ "2026-08-17",
+ "2026-08-24",
+ "2026-08-31",
+ "2026-09-07",
+ "2026-09-14",
+ "2026-09-21",
+ "2026-09-28",
+ ]);
+ expect(window.start.toUTC().toISO()).toBe("2026-08-03T04:00:00.000Z");
+ expect(window.end.toMillis()).toBe(NOW);
+ expect(window.firstPeriodPartial).toBe(false);
+ // The week of Sep 28 has only reached Wednesday: in progress, not a drop.
+ expect(window.lastPeriodPartial).toBe(true);
+ expect(window.endsAtNow).toBe(true);
+ expect(window.truncated).toBe(false);
+ });
+
+ it("marks cohorts cut by a range that starts and ends mid-week", () => {
+ const window = resolveRetentionWindow(
+ { start_date: "2026-08-05", end_date: "2026-08-20", time_zone: NY },
+ "week",
+ NOW
+ );
+
+ expect(window.periods).toEqual(["2026-08-03", "2026-08-10", "2026-08-17"]);
+ expect(window.firstPeriodPartial).toBe(true);
+ expect(window.lastPeriodPartial).toBe(true);
+ // Cut by the range, not still going on.
+ expect(window.endsAtNow).toBe(false);
+ expect(window.end.toUTC().toISO()).toBe("2026-08-21T04:00:00.000Z");
+ });
+
+ it("treats a past range that ends on a period boundary as complete", () => {
+ const window = resolveRetentionWindow(
+ { start_date: "2026-08-03", end_date: "2026-08-16", time_zone: "UTC" },
+ "week",
+ NOW
+ );
+
+ expect(window.periods).toEqual(["2026-08-03", "2026-08-10"]);
+ expect(window.lastPeriodPartial).toBe(false);
+ });
+
+ it("keeps the latest periods of a window longer than the cohort cap", () => {
+ const window = resolveRetentionWindow(
+ { start_date: "2026-01-01", end_date: "2026-09-30", time_zone: "UTC" },
+ "day",
+ NOW
+ );
+
+ expect(window.periods).toHaveLength(MAX_COHORTS.day);
+ expect(window.periods[window.periods.length - 1]).toBe("2026-09-30");
+ expect(window.truncated).toBe(true);
+ expect(window.firstPeriodPartial).toBe(false);
+ });
+
+ it("reads the dashboard's empty date range as all time, capped", () => {
+ const window = resolveRetentionWindow({ start_date: "", end_date: "", time_zone: "UTC" }, "week", NOW);
+
+ expect(window.periods).toHaveLength(MAX_COHORTS.week);
+ expect(window.periods[window.periods.length - 1]).toBe("2026-09-28");
+ expect(window.truncated).toBe(true);
+ });
+
+ it("answers the legacy range param, clamped to 7 to 365 days", () => {
+ expect(resolveRetentionWindow({ range: "60" }, "day", NOW).start.toISODate()).toBe("2026-08-01");
+ expect(resolveRetentionWindow({ range: "2" }, "day", NOW).start.toISODate()).toBe("2026-09-23");
+ });
+
+ it("defaults to the last 90 days when the request names no window", () => {
+ const window = resolveRetentionWindow({}, "week", NOW);
+ expect(window.start.toISODate()).toBe("2026-07-02");
+ expect(window.end.toMillis()).toBe(NOW);
+ });
+
+ it("uses datetime and past-minutes windows as given", () => {
+ const datetime = resolveRetentionWindow(
+ { start_datetime: "2026-09-01 00:00:00", end_datetime: "2026-09-08 00:00:00", time_zone: "UTC" },
+ "day",
+ NOW
+ );
+ expect(datetime.periods).toHaveLength(7);
+
+ const pastMinutes = resolveRetentionWindow({ past_minutes_start: "1440", past_minutes_end: "0" }, "day", NOW);
+ expect(pastMinutes.periods).toEqual(["2026-09-29", "2026-09-30"]);
+ });
+
+ it("returns no periods for a window entirely in the future", () => {
+ const window = resolveRetentionWindow(
+ { start_date: "2026-10-05", end_date: "2026-10-10", time_zone: "UTC" },
+ "day",
+ NOW
+ );
+ expect(window.periods).toEqual([]);
+ });
+});
+
+describe("buildRetentionQuery", () => {
+ const window = resolveRetentionWindow(
+ { start_date: "2026-08-03", end_date: "2026-09-30", time_zone: NY },
+ "week",
+ NOW
+ );
+
+ it("scans the window plus a bounded lookback, and drops users seen during it", () => {
+ const sql = buildRetentionQuery(window, undefined, 1);
+
+ expect(sql).toContain("AND timestamp >= toDateTime('2026-05-05 04:00:00', 'UTC')");
+ expect(sql).toContain("AND timestamp < toDateTime('2026-09-30 15:00:00', 'UTC')");
+ expect(sql).toContain("HAVING earlier_events = 0");
+ expect(sql).toContain("COALESCE(NULLIF(identified_user_id, ''), user_id) AS effective_user_id");
+ expect(sql).toContain("toStartOfWeek(timestamp, 1, {timeZone:String})");
+ expect(sql).toContain("intDiv(dateDiff('day', cohort_period, activity_period), 7) AS period_difference");
+ expect(sql).toContain("LIMIT {rowLimit:UInt32}");
+ expect(sql).not.toContain("FilteredSessions");
+ expect(RETENTION_LOOKBACK_DAYS).toBe(90);
+ });
+
+ it("selects cohorts by their first session when filters are set", () => {
+ const filters = JSON.stringify([{ parameter: "country", type: "equals", value: ["US"] }]);
+ const sql = buildRetentionQuery(window, filters, 1);
+
+ expect(sql).toContain("FilteredSessions AS");
+ expect(sql).toContain("WHERE first_session_id IN (SELECT session_id FROM FilteredSessions)");
+ // The filter CTE covers the window only, not the lookback.
+ expect(sql).toContain("AND timestamp >= toDateTime('2026-08-03 04:00:00', 'UTC')");
+ expect(sql.match(/country = 'US'/g)).toHaveLength(1);
+ });
+
+ it("counts days in the window's timezone", () => {
+ const daily = resolveRetentionWindow(
+ { start_date: "2026-09-01", end_date: "2026-09-30", time_zone: NY },
+ "day",
+ NOW
+ );
+ const sql = buildRetentionQuery(daily, undefined, 1);
+
+ expect(sql).toContain("toDate(timestamp, {timeZone:String})");
+ expect(sql).toContain("dateDiff('day', cohort_period, activity_period) AS period_difference");
+ });
+
+ it("binds the timezone, window start and a triangle-sized row limit as parameters", () => {
+ expect(buildRetentionQueryParams(window, 7)).toEqual({
+ siteId: 7,
+ timeZone: NY,
+ windowStart: "2026-08-03 04:00:00",
+ rowLimit: (MAX_COHORTS.week * (MAX_COHORTS.week + 1)) / 2,
+ });
+ });
+});
+
+describe("processRetentionData", () => {
+ const periods = ["2026-08-03", "2026-08-10", "2026-08-17"];
+
+ it("keeps retained user counts and fills unobserved returns with 0 inside the triangle", () => {
+ const cohorts = processRetentionData(
+ [
+ { cohort_period: "2026-08-03", period_difference: 0, retained_users: 4 },
+ { cohort_period: "2026-08-03", period_difference: 2, retained_users: 1 },
+ { cohort_period: "2026-08-10", period_difference: 0, retained_users: 3 },
+ { cohort_period: "2026-08-10", period_difference: 1, retained_users: 1 },
+ ],
+ periods
+ );
+
+ expect(cohorts["2026-08-03"]).toEqual({ size: 4, counts: [4, 0, 1], percentages: [100, 0, 25] });
+ expect(cohorts["2026-08-10"]).toEqual({ size: 3, counts: [3, 1, null], percentages: [100, 33.33, null] });
+ expect(cohorts["2026-08-17"]).toBeUndefined();
+ expect(Object.keys(cohorts)).toEqual(["2026-08-03", "2026-08-10"]);
+ });
+
+ it("ignores rows outside the window's periods", () => {
+ const cohorts = processRetentionData(
+ [
+ { cohort_period: "2026-07-27", period_difference: 0, retained_users: 9 },
+ { cohort_period: "2026-08-17", period_difference: 0, retained_users: 2 },
+ { cohort_period: "2026-08-17", period_difference: 1, retained_users: 2 },
+ ],
+ periods
+ );
+
+ expect(cohorts).toEqual({ "2026-08-17": { size: 2, counts: [2, null, null], percentages: [100, null, null] } });
+ });
+});
+
+describe("getRetention", () => {
+ const reply = () => {
+ const res = { statusCode: 200, body: undefined as unknown };
+ return Object.assign(res, {
+ status(code: number) {
+ res.statusCode = code;
+ return this;
+ },
+ send(body: unknown) {
+ res.body = body;
+ return this;
+ },
+ });
+ };
+ const request = (querystring: Record<string, unknown>) =>
+ ({ params: { siteId: "1" }, query: querystring, log: { error: vi.fn(), debug: vi.fn() } }) as any;
+
+ it("rejects an unknown mode", async () => {
+ const res = reply();
+ await getRetention(request({ mode: "month" }), res as any);
+ expect(res.statusCode).toBe(400);
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ it("returns the window's shape without querying when it holds no periods", async () => {
+ const res = reply();
+ await getRetention(
+ request({ mode: "day", start_date: "2999-01-01", end_date: "2999-01-02", time_zone: "UTC" }),
+ res as any
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(query).not.toHaveBeenCalled();
+ expect(res.body).toMatchObject({ data: { cohorts: {}, periods: [], maxPeriods: 0, mode: "day" } });
+ });
+
+ it("queries with bound parameters and returns counts alongside percentages", async () => {
+ query.mockResolvedValueOnce({
+ json: async () => [
+ { cohort_period: "2026-09-28", period_difference: "0", retained_users: "5" },
+ { cohort_period: "2026-09-28", period_difference: "1", retained_users: "2" },
+ ],
+ });
+ const res = reply();
+ await getRetention(
+ request({ mode: "week", start_date: "2026-09-28", end_date: "2026-10-11", time_zone: "UTC" }),
+ res as any
+ );
+
+ expect(query).toHaveBeenCalledTimes(1);
+ expect(query.mock.calls[0][0].query_params).toMatchObject({ siteId: 1, timeZone: "UTC" });
+ const body = res.body as { data: { cohorts: Record<string, unknown>; lookbackDays: number } };
+ expect(body.data.lookbackDays).toBe(RETENTION_LOOKBACK_DAYS);
+ expect(Object.values(body.data.cohorts)[0]).toMatchObject({ size: 5 });
+ });
+});
diff --git a/server/src/api/analytics/getRetention.ts b/server/src/api/analytics/getRetention.ts
index 31cccbc65..ffe5ab14c 100644
--- a/server/src/api/analytics/getRetention.ts
+++ b/server/src/api/analytics/getRetention.ts
@@ -1,155 +1,374 @@
import { FastifyReply, FastifyRequest } from "fastify";
+import { DateTime } from "luxon";
+import { z } from "zod";
import { analyticsRoute, runAnalyticsQuery } from "./utils/analyticsQuery.js";
import { effectiveUserId } from "./utils/effectiveUserId.js";
+import { buildFilteredSessionsCTE } from "./utils/sessionFilters.js";
+import { getTimeStatement, isValidTimeZone, parseDateTimeMs } from "./utils/timeWindow.js";
-// Define the expected shape of a single data row from the query
-interface RetentionDataRow {
+/**
+ * Cohort retention: users grouped by the period of their first visit, and the
+ * share of each group that was active again 1, 2, 3… periods later.
+ *
+ * The cohort window is the request's time window (the dashboard's date range),
+ * and returns are counted inside that same window, so a cohort's row ends where
+ * the range ends. A user belongs to a cohort only if the window holds their
+ * first visit: anyone seen in the {@link RETENTION_LOOKBACK_DAYS} days before
+ * the window started is a returning visitor and is left out. The lookback is
+ * bounded so the query is too; a visitor gone for longer than that counts as new.
+ *
+ * Filters pick users by their first visit (the session that put them in a
+ * cohort). Returns count any later activity on the site.
+ */
+
+export type RetentionMode = "day" | "week";
+
+/** How far before the window a visit makes someone a returning visitor rather than a new one. */
+export const RETENTION_LOOKBACK_DAYS = 90;
+
+/**
+ * At most this many cohorts. A longer window keeps its latest periods: the
+ * grid stays readable and the scan stays bounded (a year of weeks, a quarter
+ * of days).
+ */
+export const MAX_COHORTS: Record<RetentionMode, number> = { day: 92, week: 53 };
+
+// The `range` param predates the shared date range. It still answers API and
+// MCP callers that send no window.
+const LEGACY_RANGE_DEFAULT_DAYS = 90;
+const LEGACY_RANGE_MIN_DAYS = 7;
+const LEGACY_RANGE_MAX_DAYS = 365;
+
+const optionalText = z.string().optional();
+
+const retentionQuerySchema = z
+ .object({
+ mode: z.enum(["day", "week"]).default("week"),
+ range: z.string().regex(/^\d+$/, { message: "range must be a whole number of days" }).optional().or(z.literal("")),
+ start_date: optionalText,
+ end_date: optionalText,
+ start_datetime: optionalText,
+ end_datetime: optionalText,
+ past_minutes_start: z.union([z.string(), z.number()]).optional(),
+ past_minutes_end: z.union([z.string(), z.number()]).optional(),
+ time_zone: optionalText,
+ filters: optionalText,
+ })
+ .refine(query => !query.start_date || !query.end_date || query.start_date <= query.end_date, {
+ message: "start_date must not be after end_date",
+ });
+
+export type RetentionQuery = z.infer<typeof retentionQuerySchema>;
+
+interface RetentionRow {
cohort_period: string;
period_difference: number;
- cohort_size: number;
retained_users: number;
- retention_percentage: number;
}
-// Processed data structure for the frontend
-interface ProcessedRetentionData {
- cohorts: Record<string, { size: number; percentages: (number | null)[] }>;
+export interface RetentionCohort {
+ /** New users in the cohort. */
+ size: number;
+ /**
+ * Share of the cohort active in each period since their first, in percent
+ * (index 0 is always 100). Null where the period falls after the window.
+ */
+ percentages: (number | null)[];
+ /** The same, as user counts. */
+ counts: (number | null)[];
+}
+
+export interface RetentionResponse {
+ /** Keyed by the cohort period's first day (YYYY-MM-DD, in the window's timezone), oldest first. Empty cohorts are left out. */
+ cohorts: Record<string, RetentionCohort>;
+ /** Highest period offset in the grid: one less than the number of periods. */
maxPeriods: number;
- mode: "day" | "week";
+ mode: RetentionMode;
+ /** Days spanned by the window. */
range: number;
+ /** Every cohort period in the window, oldest first, including empty ones. */
+ periods: string[];
+ /** The window as UTC instants: start inclusive, end exclusive. */
+ windowStart: string;
+ windowEnd: string;
+ timeZone: string;
+ /** The window starts after the first period begins, so that cohort only holds part of its period's new users. */
+ firstPeriodPartial: boolean;
+ /** The window ends before the last period does (it is in progress, or the range stops mid-period). */
+ lastPeriodPartial: boolean;
+ /** The last period is partial because it is still going on: the window ends now. */
+ lastPeriodInProgress: boolean;
+ /** The window held more than MAX_COHORTS periods and was cut to the latest ones. */
+ truncated: boolean;
+ lookbackDays: number;
}
-interface GetRetentionRequest {
- Params: { siteId: string };
- Querystring: { mode?: string; range?: string };
+export interface RetentionWindow {
+ mode: RetentionMode;
+ timeZone: string;
+ start: DateTime;
+ end: DateTime;
+ periods: string[];
+ firstPeriodPartial: boolean;
+ lastPeriodPartial: boolean;
+ /** The window runs up to now. */
+ endsAtNow: boolean;
+ truncated: boolean;
}
-export const buildRetentionQuery = (retentionMode: "day" | "week") => {
- // Build the appropriate SQL based on the retention mode
- const periodFunction = retentionMode === "day" ? "toDate" : "toStartOfWeek";
- const periodDiffFunc = retentionMode === "day" ? "day" : "week";
+const unitFor = (mode: RetentionMode) => (mode === "week" ? "weeks" : "days");
+
+/**
+ * The cohort window a request asks for, as absolute instants, cut to whole
+ * periods where it is too long and never reaching past now.
+ *
+ * Precedence matches the shared time window: a date range, then a datetime
+ * range, then past minutes, then the legacy `range`, and all time when none is
+ * given. The request's time params are validated before this runs.
+ */
+export function resolveRetentionWindow(
+ query: Omit<RetentionQuery, "mode" | "filters">,
+ mode: RetentionMode,
+ nowMs: number = Date.now()
+): RetentionWindow {
+ const timeZone = query.time_zone && isValidTimeZone(query.time_zone) ? query.time_zone : "UTC";
+ const now = DateTime.fromMillis(nowMs, { zone: timeZone });
+
+ let start: DateTime;
+ let end: DateTime;
+ if (query.start_date && query.end_date) {
+ start = DateTime.fromISO(query.start_date, { zone: timeZone }).startOf("day");
+ end = DateTime.fromISO(query.end_date, { zone: timeZone }).plus({ days: 1 }).startOf("day");
+ } else if (query.start_datetime && query.end_datetime) {
+ start = DateTime.fromMillis(parseDateTimeMs(query.start_datetime), { zone: timeZone });
+ end = DateTime.fromMillis(parseDateTimeMs(query.end_datetime), { zone: timeZone });
+ } else if (
+ query.past_minutes_start !== undefined &&
+ query.past_minutes_start !== "" &&
+ query.past_minutes_end !== undefined &&
+ query.past_minutes_end !== ""
+ ) {
+ start = now.minus({ minutes: Number(query.past_minutes_start) });
+ end = now.minus({ minutes: Number(query.past_minutes_end) });
+ } else if (query.range) {
+ const days = Math.min(LEGACY_RANGE_MAX_DAYS, Math.max(LEGACY_RANGE_MIN_DAYS, parseInt(query.range, 10)));
+ start = now.startOf("day").minus({ days });
+ end = now;
+ } else if (query.start_date === "" && query.end_date === "") {
+ // The dashboard's All time sends an empty date range. The cohort cap below
+ // turns it into the latest periods.
+ start = DateTime.fromMillis(0, { zone: timeZone });
+ end = now;
+ } else {
+ // No window at all: the endpoint's documented default for API callers.
+ start = now.startOf("day").minus({ days: LEGACY_RANGE_DEFAULT_DAYS });
+ end = now;
+ }
+
+ // Nothing after now has happened yet; ending the window there is what lets
+ // the last period read as in progress rather than as a drop.
+ const endsAtNow = end >= now;
+ if (endsAtNow) end = now;
+
+ const unit = mode === "week" ? "week" : "day";
+ if (!start.isValid || !end.isValid || start >= end) {
+ return {
+ mode,
+ timeZone,
+ start: end.isValid ? end : now,
+ end: end.isValid ? end : now,
+ periods: [],
+ firstPeriodPartial: false,
+ lastPeriodPartial: false,
+ endsAtNow,
+ truncated: false,
+ };
+ }
+
+ // luxon's week starts on Monday, like toStartOfWeek(…, 1) in the query.
+ const lastPeriodStart = end.minus({ milliseconds: 1 }).startOf(unit);
+ const earliestStart = lastPeriodStart.minus({ [unitFor(mode)]: MAX_COHORTS[mode] - 1 });
+ const truncated = start < earliestStart;
+ if (truncated) start = earliestStart;
+
+ const firstPeriodStart = start.startOf(unit);
+ const periods: string[] = [];
+ for (let period = firstPeriodStart; period <= lastPeriodStart; period = period.plus({ [unitFor(mode)]: 1 })) {
+ periods.push(period.toISODate() ?? "");
+ }
+
+ return {
+ mode,
+ timeZone,
+ start,
+ end,
+ periods,
+ firstPeriodPartial: start > firstPeriodStart,
+ lastPeriodPartial: lastPeriodStart.plus({ [unitFor(mode)]: 1 }) > end,
+ endsAtNow,
+ truncated,
+ };
+}
+
+const toClickhouseInstant = (instant: DateTime) => instant.toUTC().toFormat("yyyy-MM-dd HH:mm:ss");
+
+/** The cohort period an instant falls in, in the window's timezone. Monday-start weeks. */
+const periodOf = (mode: RetentionMode, column: string) =>
+ mode === "day" ? `toDate(${column}, {timeZone:String})` : `toStartOfWeek(${column}, 1, {timeZone:String})`;
+
+/**
+ * One pass over the window plus the lookback before it, grouped by user:
+ * users with any earlier activity drop out, the rest are placed in the period
+ * of their first visit, and each of their active periods becomes one
+ * (cohort, offset) count. Bounded by the window cap, the fixed lookback and a
+ * row limit of one triangle of cells.
+ */
+export function buildRetentionQuery(window: RetentionWindow, filters: string | undefined, siteId: number) {
+ const lookbackStart = window.start.minus({ days: RETENTION_LOOKBACK_DAYS });
+ const scanTimeStatement = getTimeStatement({
+ start_datetime: toClickhouseInstant(lookbackStart),
+ end_datetime: toClickhouseInstant(window.end),
+ time_zone: window.timeZone,
+ });
+ const windowTimeStatement = getTimeStatement({
+ start_datetime: toClickhouseInstant(window.start),
+ end_datetime: toClickhouseInstant(window.end),
+ time_zone: window.timeZone,
+ });
+
+ // Filters qualify the user's first session, so they select who is in a
+ // cohort without narrowing what counts as coming back.
+ const filteredSessionsCTE = buildFilteredSessionsCTE(filters, siteId, windowTimeStatement);
+ const inWindow = "timestamp >= toDateTime({windowStart:String}, 'UTC')";
+ const offset =
+ window.mode === "day"
+ ? "dateDiff('day', cohort_period, activity_period)"
+ : "intDiv(dateDiff('day', cohort_period, activity_period), 7)";
return `
-WITH UserFirstPeriod AS (
+WITH ${filteredSessionsCTE ? `${filteredSessionsCTE},` : ""}
+Users AS (
SELECT
- -- Use effective user ID: identified_user_id for identified users, user_id for anonymous
${effectiveUserId()} AS effective_user_id,
- ${periodFunction}(min(timestamp)${retentionMode === "week" ? ", 1" : ""}) AS cohort_period
+ countIf(NOT (${inWindow})) AS earlier_events,
+ minIf(timestamp, ${inWindow}) AS first_seen,
+ argMinIf(session_id, timestamp, ${inWindow}) AS first_session_id,
+ groupUniqArrayIf(${periodOf(window.mode, "timestamp")}, ${inWindow}) AS active_periods
FROM events
WHERE site_id = {siteId:UInt16}
- -- Use the configurable time range
- AND timestamp >= addDays(today(), -{timeRange:UInt16})
+ ${scanTimeStatement}
GROUP BY effective_user_id
-),
-PeriodActivity AS (
- SELECT DISTINCT
- ${effectiveUserId()} AS effective_user_id,
- ${periodFunction}(timestamp${retentionMode === "week" ? ", 1" : ""}) AS activity_period
- FROM events
- WHERE site_id = {siteId:UInt16}
- -- Match the date range filter
- AND timestamp >= addDays(today(), -{timeRange:UInt16})
-),
-CohortRetention AS (
- SELECT
- ufp.cohort_period,
- dateDiff('${periodDiffFunc}', ufp.cohort_period, pa.activity_period) AS period_difference,
- count(DISTINCT pa.effective_user_id) AS retained_users
- FROM UserFirstPeriod ufp
- JOIN PeriodActivity pa ON ufp.effective_user_id = pa.effective_user_id
- WHERE pa.activity_period >= ufp.cohort_period
- GROUP BY
- ufp.cohort_period,
- period_difference
-),
-CohortSize AS (
- SELECT
- cohort_period,
- count(DISTINCT effective_user_id) AS total_users
- FROM UserFirstPeriod
- GROUP BY cohort_period
+ HAVING earlier_events = 0
)
SELECT
- cr.cohort_period,
- cr.period_difference,
- cs.total_users AS cohort_size,
- cr.retained_users,
- round(cr.retained_users * 100.0 / cs.total_users, 2) AS retention_percentage
-FROM CohortRetention cr
-JOIN CohortSize cs ON cr.cohort_period = cs.cohort_period
-ORDER BY
- cr.cohort_period DESC,
- cr.period_difference ASC;
- `;
-};
+ cohort_period,
+ ${offset} AS period_difference,
+ count() AS retained_users
+FROM (
+ SELECT
+ ${periodOf(window.mode, "first_seen")} AS cohort_period,
+ arrayJoin(active_periods) AS activity_period
+ FROM Users
+ ${filteredSessionsCTE ? "WHERE first_session_id IN (SELECT session_id FROM FilteredSessions)" : ""}
+)
+GROUP BY cohort_period, period_difference
+ORDER BY cohort_period, period_difference
+LIMIT {rowLimit:UInt32}
+`;
+}
-export const getRetention = analyticsRoute<GetRetentionRequest>(
- "retention",
- async (req: FastifyRequest<GetRetentionRequest>, res: FastifyReply) => {
- const { siteId } = req.params;
- const { mode = "week", range = "90" } = req.query; // Default to weekly mode and 90 days range
-
- // Validate mode parameter
- const retentionMode = mode === "day" ? "day" : "week";
-
- // Validate range parameter (between 7-365 days)
- const timeRange = Math.min(365, Math.max(7, parseInt(range) || 90));
-
- const results = await runAnalyticsQuery<RetentionDataRow>({
- query: buildRetentionQuery(retentionMode),
- params: {
- siteId: Number(siteId),
- timeRange: timeRange,
- },
- });
-
- // Process data into a grid-friendly format
- const processedData: ProcessedRetentionData = {
- ...processRetentionData(results),
- mode: retentionMode as "day" | "week",
- range: timeRange,
- };
+export function buildRetentionQueryParams(window: RetentionWindow, siteId: number) {
+ const cohorts = MAX_COHORTS[window.mode];
+ return {
+ siteId,
+ timeZone: window.timeZone,
+ windowStart: toClickhouseInstant(window.start),
+ rowLimit: (cohorts * (cohorts + 1)) / 2,
+ };
+}
+
+const roundPercent = (value: number) => Math.round(value * 100) / 100;
+
+/**
+ * Lays the (cohort, offset) counts out as a grid over the window's periods.
+ * Inside the observable triangle a missing count means nobody came back (0);
+ * past the window's end there is nothing to observe (null).
+ */
+export function processRetentionData(rows: RetentionRow[], periods: string[]): Record<string, RetentionCohort> {
+ const periodCount = periods.length;
+ const indexOf = new Map(periods.map((period, index) => [period, index]));
+ const counts = new Map<string, (number | null)[]>();
- return res.send({ data: processedData });
+ for (const row of rows) {
+ const cohortIndex = indexOf.get(row.cohort_period);
+ const offset = Number(row.period_difference);
+ if (cohortIndex === undefined || offset < 0 || cohortIndex + offset >= periodCount) continue;
+
+ let cohortCounts = counts.get(row.cohort_period);
+ if (!cohortCounts) {
+ cohortCounts = Array.from({ length: periodCount }, (_, p) => (cohortIndex + p < periodCount ? 0 : null));
+ counts.set(row.cohort_period, cohortCounts);
+ }
+ cohortCounts[offset] = Number(row.retained_users);
}
-);
-// Process raw retention data into a grid-friendly format
-function processRetentionData(rawData: RetentionDataRow[]): Omit<ProcessedRetentionData, "mode" | "range"> {
- if (!rawData || rawData.length === 0) {
- return { cohorts: {}, maxPeriods: 0 };
+ const cohorts: Record<string, RetentionCohort> = {};
+ for (const period of periods) {
+ const cohortCounts = counts.get(period);
+ const size = cohortCounts?.[0] ?? 0;
+ if (!cohortCounts || size <= 0) continue;
+ cohorts[period] = {
+ size,
+ counts: cohortCounts,
+ percentages: cohortCounts.map(count => (count === null ? null : roundPercent((count / size) * 100))),
+ };
}
+ return cohorts;
+}
- const processedCohorts: Record<string, { size: number; percentages: (number | null)[] }> = {};
- let maxPeriodDiff = 0;
+export function buildRetentionResponse(window: RetentionWindow, rows: RetentionRow[]): RetentionResponse {
+ return {
+ cohorts: processRetentionData(rows, window.periods),
+ maxPeriods: Math.max(window.periods.length - 1, 0),
+ mode: window.mode,
+ range: Math.max(0, Math.round(window.end.diff(window.start, "days").days)),
+ periods: window.periods,
+ windowStart: window.start.toUTC().toISO() ?? "",
+ windowEnd: window.end.toUTC().toISO() ?? "",
+ timeZone: window.timeZone,
+ firstPeriodPartial: window.firstPeriodPartial,
+ lastPeriodPartial: window.lastPeriodPartial,
+ lastPeriodInProgress: window.lastPeriodPartial && window.endsAtNow,
+ truncated: window.truncated,
+ lookbackDays: RETENTION_LOOKBACK_DAYS,
+ };
+}
- rawData.forEach(row => {
- if (!processedCohorts[row.cohort_period]) {
- processedCohorts[row.cohort_period] = {
- size: row.cohort_size,
- percentages: [],
- };
- }
- // Ensure array is long enough, filling gaps with null
- while (processedCohorts[row.cohort_period].percentages.length <= row.period_difference) {
- processedCohorts[row.cohort_period].percentages.push(null);
- }
- processedCohorts[row.cohort_period].percentages[row.period_difference] = row.retention_percentage;
+interface GetRetentionRequest {
+ Params: { siteId: string };
+ Querystring: Record<string, unknown>;
+}
- if (row.period_difference > maxPeriodDiff) {
- maxPeriodDiff = row.period_difference;
+export const getRetention = analyticsRoute<GetRetentionRequest>(
+ "retention",
+ async (req: FastifyRequest<GetRetentionRequest>, res: FastifyReply) => {
+ const parsed = retentionQuerySchema.safeParse(req.query);
+ if (!parsed.success) {
+ return res.status(400).send({ error: parsed.error.issues.map(issue => issue.message).join("; ") });
}
- });
- // Ensure all percentage arrays have the same length for grid alignment
- const finalMaxPeriods = Math.max(maxPeriodDiff, 0);
+ const siteId = Number(req.params.siteId);
+ const { mode, filters, ...windowParams } = parsed.data;
+ const window = resolveRetentionWindow(windowParams, mode);
- Object.values(processedCohorts).forEach(cohort => {
- // Ensure all cohorts have the same number of periods
- while (cohort.percentages.length <= finalMaxPeriods) {
- cohort.percentages.push(null);
- }
- });
+ const rows =
+ window.periods.length === 0
+ ? []
+ : await runAnalyticsQuery<RetentionRow>({
+ query: buildRetentionQuery(window, filters, siteId),
+ params: buildRetentionQueryParams(window, siteId),
+ });
- return { cohorts: processedCohorts, maxPeriods: finalMaxPeriods };
-}
+ return res.send({ data: buildRetentionResponse(window, rows) });
+ }
+);
diff --git a/server/src/api/analytics/goals/getGoalPreview.ts b/server/src/api/analytics/goals/getGoalPreview.ts
new file mode 100644
index 000000000..fc5010ae9
--- /dev/null
+++ b/server/src/api/analytics/goals/getGoalPreview.ts
@@ -0,0 +1,99 @@
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { goals } from "../../../db/postgres/schema.js";
+import { TimeBucket } from "../types.js";
+import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { TimeBucketToFn } from "../utils/timeWindow.js";
+import { buildGoalsConversionsQuery, buildGoalsTotalSessionsQuery } from "./getGoals.js";
+import { buildGoalTimeSeriesQuery } from "./getGoalTimeSeries.js";
+import { buildGoalCondition } from "./goalConditions.js";
+import { GoalBody, goalBodySchema } from "./goalSchema.js";
+
+type SiteGoal = typeof goals.$inferSelect;
+
+// No stored goal has id 0 (the column is a serial), so the draft cannot be
+// mistaken for one in the shared query builders.
+const DRAFT_GOAL_ID = 0;
+
+export interface GoalPreview {
+ /** Sessions in the window that would have completed the goal. */
+ conversions: number;
+ total_sessions: number;
+ conversion_rate: number;
+ series: { time: string; conversions: number }[];
+}
+
+interface GetGoalPreviewRequest {
+ Params: { siteId: string };
+ Body: GoalBody;
+ Querystring: FilterParams<{ bucket?: TimeBucket }>;
+}
+
+/**
+ * A goal that has not been saved, in the shape the stored-goal query builders
+ * take. The preview runs exactly the SQL a saved goal would, so what it
+ * reports is what the ledger shows once the goal exists.
+ */
+export const draftGoal = (siteId: number, body: Pick<GoalBody, "goalType" | "config">): SiteGoal => ({
+ goalId: DRAFT_GOAL_ID,
+ siteId,
+ name: null,
+ goalType: body.goalType,
+ config: body.config,
+ createdAt: null,
+});
+
+/**
+ * What a goal would have counted in the selected window, before it is saved:
+ * goals are evaluated at query time over events that already exist, so the
+ * answer is the same one the goal will show once created.
+ */
+export const getGoalPreview = analyticsRoute<GetGoalPreviewRequest>(
+ "goal preview",
+ async (request: FastifyRequest<GetGoalPreviewRequest>, reply: FastifyReply) => {
+ const siteId = Number(request.params.siteId);
+ const { bucket = "hour" } = request.query;
+
+ if (!TimeBucketToFn[bucket]) {
+ return reply.status(400).send({ error: `Invalid bucket value: ${bucket}` });
+ }
+
+ const parsed = goalBodySchema.safeParse(request.body);
+ if (!parsed.success) {
+ return reply.status(400).send({ error: "Validation error", details: parsed.error.errors });
+ }
+
+ const goal = draftGoal(siteId, parsed.data);
+ if (!buildGoalCondition(goal)) {
+ return reply.status(400).send({ error: "Invalid goal configuration" });
+ }
+
+ const query = { ...request.query, bucket };
+ const conversionsQuery = buildGoalsConversionsQuery(query, siteId, [goal]);
+ const seriesQuery = buildGoalTimeSeriesQuery(query, siteId, [goal]);
+ if (conversionsQuery === null || seriesQuery === null) {
+ return reply.status(400).send({ error: "Invalid goal configuration" });
+ }
+
+ const [totalSessionsData, conversionsData, seriesData] = await Promise.all([
+ runAnalyticsQuery<{ total_sessions: number }>({ query: buildGoalsTotalSessionsQuery(query, siteId) }),
+ runAnalyticsQuery<Record<string, number>>({ query: conversionsQuery }),
+ runAnalyticsQuery<{ time: string; conversions: number }>({
+ query: seriesQuery,
+ params: { siteId, timeZone: request.query.time_zone || "UTC" },
+ }),
+ ]);
+
+ const totalSessions = Number(totalSessionsData[0]?.total_sessions) || 0;
+ const conversions = Number(conversionsData[0]?.[`goal_${DRAFT_GOAL_ID}_conversions`]) || 0;
+
+ const preview: GoalPreview = {
+ conversions,
+ total_sessions: totalSessions,
+ conversion_rate: totalSessions > 0 ? conversions / totalSessions : 0,
+ series: seriesData.map(point => ({ time: point.time, conversions: Number(point.conversions) || 0 })),
+ };
+
+ return reply.send({ data: preview });
+ }
+);
diff --git a/server/src/api/analytics/goals/getGoalsSummary.ts b/server/src/api/analytics/goals/getGoalsSummary.ts
new file mode 100644
index 000000000..69cd96e35
--- /dev/null
+++ b/server/src/api/analytics/goals/getGoalsSummary.ts
@@ -0,0 +1,165 @@
+import { FilterParams } from "@rybbit/shared";
+import { count, desc, eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import SqlString from "sqlstring";
+import { db } from "../../../db/postgres/postgres.js";
+import { goals } from "../../../db/postgres/schema.js";
+import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { buildFilteredSessionsCTE } from "../utils/sessionFilters.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
+import { buildGoalsConversionsQuery, buildGoalsTotalSessionsQuery } from "./getGoals.js";
+import { buildGoalCondition } from "./goalConditions.js";
+
+type SiteGoal = typeof goals.$inferSelect;
+
+/**
+ * The most goals one summary computes. Each goal is one conditional
+ * aggregate, so the bound is on ClickHouse work per request; a site with more
+ * gets its most recently created ones and `total_goals` says how many exist.
+ */
+export const MAX_SUMMARY_GOALS = 200;
+
+/**
+ * Goals per conversions query. The paginated list (`GET /goals`) already
+ * allows this many in one query.
+ */
+export const GOALS_PER_QUERY = 100;
+
+export interface GoalSummaryRow {
+ goalId: number;
+ name: string | null;
+ goalType: string;
+ config: SiteGoal["config"];
+ createdAt: string | null;
+ total_conversions: number;
+ total_sessions: number;
+ conversion_rate: number;
+}
+
+export interface GoalsSummary {
+ /** Every computed goal, most conversions first. */
+ goals: GoalSummaryRow[];
+ /** Sessions in the window: the denominator of every rate. */
+ total_sessions: number;
+ /** Sessions that completed at least one of `goals`. */
+ converting_sessions: number;
+ /** Goals the site has. Larger than `goals.length` when the bound was hit. */
+ total_goals: number;
+}
+
+interface GetGoalsSummaryRequest {
+ Params: { siteId: string };
+ Querystring: FilterParams<{}>;
+}
+
+export const chunkGoals = <T>(items: T[], size: number): T[][] => {
+ const chunks: T[][] = [];
+ for (let i = 0; i < items.length; i += size) {
+ chunks.push(items.slice(i, i + size));
+ }
+ return chunks;
+};
+
+/**
+ * Sessions that completed any of the goals. Not the sum of the per-goal
+ * counts: a session that completes two goals is one converting session.
+ * Returns null when none of the goals produces a valid condition.
+ */
+export const buildConvertingSessionsQuery = (
+ query: GetGoalsSummaryRequest["Querystring"],
+ siteId: number,
+ siteGoals: Pick<SiteGoal, "goalType" | "config">[]
+): string | null => {
+ const conditions = siteGoals.map(goal => buildGoalCondition(goal)).filter((c): c is string => !!c);
+ if (conditions.length === 0) return null;
+
+ const timeStatement = getTimeStatement(query);
+ const filteredSessionsCTE = buildFilteredSessionsCTE(query.filters, siteId, timeStatement);
+
+ return `
+ ${filteredSessionsCTE ? `WITH ${filteredSessionsCTE}` : ""}
+ SELECT COUNT(DISTINCT session_id) AS converting_sessions
+ FROM events
+ ${filteredSessionsCTE ? "INNER JOIN FilteredSessions USING (session_id)" : ""}
+ WHERE site_id = ${SqlString.escape(siteId)}
+ AND (${conditions.map(condition => `(${condition})`).join(" OR ")})
+ ${timeStatement}
+ `;
+};
+
+/**
+ * Ranks after computing, across every goal: most conversions first. The rate
+ * shares one denominator, so this is also the rate order. Ties keep the newest
+ * goal first, then the higher id, so the order is stable between requests.
+ */
+export const rankGoals = (rows: GoalSummaryRow[]): GoalSummaryRow[] =>
+ [...rows].sort(
+ (a, b) =>
+ b.total_conversions - a.total_conversions ||
+ (b.createdAt ?? "").localeCompare(a.createdAt ?? "") ||
+ b.goalId - a.goalId
+ );
+
+export const getGoalsSummary = analyticsRoute<GetGoalsSummaryRequest>(
+ "goals summary",
+ async (request: FastifyRequest<GetGoalsSummaryRequest>, reply: FastifyReply) => {
+ const siteId = Number(request.params.siteId);
+
+ const [totalGoalsResult, siteGoals] = await Promise.all([
+ db.select({ count: count() }).from(goals).where(eq(goals.siteId, siteId)),
+ db
+ .select()
+ .from(goals)
+ .where(eq(goals.siteId, siteId))
+ .orderBy(desc(goals.createdAt), desc(goals.goalId))
+ .limit(MAX_SUMMARY_GOALS),
+ ]);
+ const totalGoals = totalGoalsResult[0]?.count || 0;
+
+ if (siteGoals.length === 0) {
+ const empty: GoalsSummary = { goals: [], total_sessions: 0, converting_sessions: 0, total_goals: totalGoals };
+ return reply.send({ data: empty });
+ }
+
+ const convertingQuery = buildConvertingSessionsQuery(request.query, siteId, siteGoals);
+ const conversionQueries = chunkGoals(siteGoals, GOALS_PER_QUERY)
+ .map(chunk => buildGoalsConversionsQuery(request.query, siteId, chunk))
+ .filter((query): query is string => query !== null);
+
+ const [totalSessionsData, convertingData, ...conversionData] = await Promise.all([
+ runAnalyticsQuery<{ total_sessions: number }>({
+ query: buildGoalsTotalSessionsQuery(request.query, siteId),
+ }),
+ convertingQuery
+ ? runAnalyticsQuery<{ converting_sessions: number }>({ query: convertingQuery })
+ : Promise.resolve([]),
+ ...conversionQueries.map(query => runAnalyticsQuery<Record<string, number>>({ query })),
+ ]);
+
+ const totalSessions = Number(totalSessionsData[0]?.total_sessions) || 0;
+ const conversions: Record<string, number> = Object.assign({}, ...conversionData.map(rows => rows[0] ?? {}));
+
+ const rows: GoalSummaryRow[] = siteGoals.map(goal => {
+ const totalConversions = Number(conversions[`goal_${goal.goalId}_conversions`]) || 0;
+ return {
+ goalId: goal.goalId,
+ name: goal.name,
+ goalType: goal.goalType,
+ config: goal.config,
+ createdAt: goal.createdAt,
+ total_conversions: totalConversions,
+ total_sessions: totalSessions,
+ conversion_rate: totalSessions > 0 ? totalConversions / totalSessions : 0,
+ };
+ });
+
+ const summary: GoalsSummary = {
+ goals: rankGoals(rows),
+ total_sessions: totalSessions,
+ converting_sessions: Number(convertingData[0]?.converting_sessions) || 0,
+ total_goals: totalGoals,
+ };
+
+ return reply.send({ data: summary });
+ }
+);
diff --git a/server/src/api/analytics/goals/goalsSummary.test.ts b/server/src/api/analytics/goals/goalsSummary.test.ts
new file mode 100644
index 000000000..3797992fb
--- /dev/null
+++ b/server/src/api/analytics/goals/goalsSummary.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../db/clickhouse/clickhouse.js", () => ({
+ clickhouse: { query: vi.fn() },
+}));
+vi.mock("../../../db/postgres/postgres.js", () => ({
+ db: {},
+}));
+
+import { draftGoal } from "./getGoalPreview.js";
+import { buildGoalTimeSeriesQuery } from "./getGoalTimeSeries.js";
+import { buildGoalsConversionsQuery } from "./getGoals.js";
+import {
+ buildConvertingSessionsQuery,
+ chunkGoals,
+ GoalSummaryRow,
+ GOALS_PER_QUERY,
+ MAX_SUMMARY_GOALS,
+ rankGoals,
+} from "./getGoalsSummary.js";
+
+const CAMPAIGN_FILTER = JSON.stringify([{ parameter: "utm_campaign", type: "equals", value: ["recipe_book_2026"] }]);
+
+const query = {
+ filters: "",
+ start_date: "2026-09-01",
+ end_date: "2026-09-30",
+ time_zone: "UTC",
+};
+
+const pricingGoal = { goalType: "path", config: { pathPattern: "/pricing" } };
+const signupGoal = { goalType: "event", config: { eventName: "signup" } };
+
+const row = (overrides: Partial<GoalSummaryRow>): GoalSummaryRow => ({
+ goalId: 1,
+ name: null,
+ goalType: "path",
+ config: { pathPattern: "/" },
+ createdAt: "2026-09-01 00:00:00",
+ total_conversions: 0,
+ total_sessions: 100,
+ conversion_rate: 0,
+ ...overrides,
+});
+
+describe("buildConvertingSessionsQuery", () => {
+ it("counts a session once however many goals it completed", () => {
+ const sql = buildConvertingSessionsQuery(query, 1, [pricingGoal, signupGoal]);
+
+ expect(sql).toContain("COUNT(DISTINCT session_id) AS converting_sessions");
+ expect(sql).toContain(
+ "((type = 'pageview' AND match(pathname, '^/pricing$')) OR (type = 'custom_event' AND event_name = 'signup'))"
+ );
+ expect(sql).toContain("site_id = 1");
+ });
+
+ it("is bounded by the selected window", () => {
+ const sql = buildConvertingSessionsQuery(query, 1, [pricingGoal]);
+
+ expect(sql).toContain("2026-09-01");
+ expect(sql).toContain("2026-09-30");
+ });
+
+ it("qualifies sessions with the same filters as the per-goal counts", () => {
+ const sql = buildConvertingSessionsQuery({ ...query, filters: CAMPAIGN_FILTER }, 1, [signupGoal]);
+
+ expect(sql).toContain("FilteredSessions AS");
+ expect(sql).toContain("WHERE 1 = 1 AND utm_campaign = 'recipe_book_2026'");
+ expect(sql).toContain("INNER JOIN FilteredSessions USING (session_id)");
+ });
+
+ it("escapes goal patterns instead of interpolating them", () => {
+ const sql = buildConvertingSessionsQuery(query, 1, [{ goalType: "event", config: { eventName: "x' OR 1=1 --" } }]);
+
+ expect(sql).toContain("event_name = 'x\\' OR 1=1 --'");
+ });
+
+ it("skips goals with no usable condition and returns null when none is left", () => {
+ const sql = buildConvertingSessionsQuery(query, 1, [{ goalType: "path", config: {} }, signupGoal]);
+
+ expect(sql).toContain("AND ((type = 'custom_event' AND event_name = 'signup'))");
+ expect(buildConvertingSessionsQuery(query, 1, [{ goalType: "path", config: {} }])).toBeNull();
+ expect(buildConvertingSessionsQuery(query, 1, [])).toBeNull();
+ });
+});
+
+describe("chunkGoals", () => {
+ it("keeps every goal, in order, in chunks no larger than the size", () => {
+ const ids = Array.from({ length: 5 }, (_, index) => index);
+
+ expect(chunkGoals(ids, 2)).toEqual([[0, 1], [2, 3], [4]]);
+ expect(chunkGoals([], 2)).toEqual([]);
+ });
+
+ it("needs at most two conversions queries for the largest summary", () => {
+ const ids = Array.from({ length: MAX_SUMMARY_GOALS }, (_, index) => index);
+
+ expect(chunkGoals(ids, GOALS_PER_QUERY)).toHaveLength(2);
+ });
+});
+
+describe("rankGoals", () => {
+ it("puts the most conversions first", () => {
+ const ranked = rankGoals([
+ row({ goalId: 1, total_conversions: 5 }),
+ row({ goalId: 2, total_conversions: 50 }),
+ row({ goalId: 3, total_conversions: 20 }),
+ ]);
+
+ expect(ranked.map(goal => goal.goalId)).toEqual([2, 3, 1]);
+ });
+
+ it("breaks ties by newest goal, then by id, so the order is stable", () => {
+ const ranked = rankGoals([
+ row({ goalId: 1, createdAt: "2026-01-01 00:00:00" }),
+ row({ goalId: 2, createdAt: "2026-05-01 00:00:00" }),
+ row({ goalId: 3, createdAt: null }),
+ row({ goalId: 4, createdAt: null }),
+ ]);
+
+ expect(ranked.map(goal => goal.goalId)).toEqual([2, 1, 4, 3]);
+ });
+
+ it("does not reorder its input", () => {
+ const rows = [row({ goalId: 1, total_conversions: 1 }), row({ goalId: 2, total_conversions: 2 })];
+ rankGoals(rows);
+
+ expect(rows.map(goal => goal.goalId)).toEqual([1, 2]);
+ });
+});
+
+describe("goal preview", () => {
+ const draft = draftGoal(7, { goalType: "path", config: { pathPattern: "/welcome/*" } });
+
+ it("runs an unsaved goal through the stored-goal conversions query", () => {
+ const sql = buildGoalsConversionsQuery(query, 7, [draft]);
+
+ expect(sql).toContain("match(pathname, '^/welcome/[^/]+$')");
+ expect(sql).toContain("AS goal_0_conversions");
+ expect(sql).toContain("site_id = 7");
+ });
+
+ it("runs an unsaved goal through the stored-goal time series query", () => {
+ const sql = buildGoalTimeSeriesQuery({ ...query, bucket: "day" }, 7, [draft]);
+
+ expect(sql).toContain("toStartOfDay");
+ expect(sql).toContain("match(pathname, '^/welcome/[^/]+$')");
+ expect(sql).toContain("SELECT arrayJoin([0]) AS goal_id");
+ });
+
+ it("applies the page's filters to the preview", () => {
+ const sql = buildGoalsConversionsQuery({ ...query, filters: CAMPAIGN_FILTER }, 7, [draft]);
+
+ expect(sql).toContain("INNER JOIN FilteredSessions USING (session_id)");
+ });
+});
diff --git a/server/src/api/analytics/index.ts b/server/src/api/analytics/index.ts
index fecbbb5c6..9944efcab 100644
--- a/server/src/api/analytics/index.ts
+++ b/server/src/api/analytics/index.ts
@@ -3,6 +3,9 @@ export { getAutocaptureEvents } from "./events/getAutocaptureEvents.js";
export { getAutocaptureValues } from "./events/getAutocaptureValues.js";
export { getEventBucketed } from "./events/getEventBucketed.js";
export { getEventNames } from "./events/getEventNames.js";
+export { getEventNameStats } from "./events/getEventNameStats.js";
+export { getEventsOverview } from "./events/getEventsOverview.js";
+export { getSilentEvents } from "./events/getSilentEvents.js";
export { getEventProperties } from "./events/getEventProperties.js";
export { getEvents } from "./events/getEvents.js";
export { getOutboundLinks } from "./events/getOutboundLinks.js";
@@ -13,6 +16,7 @@ export { createFunnel } from "./funnels/createFunnel.js";
export { deleteFunnel } from "./funnels/deleteFunnel.js";
export { getFunnel } from "./funnels/getFunnel.js";
export { getFunnelStepSessions } from "./funnels/getFunnelStepSessions.js";
+export { getFunnelSummaries } from "./funnels/getFunnelSummaries.js";
export { getFunnels } from "./funnels/getFunnels.js";
// Dashboards
@@ -34,8 +38,10 @@ export { expandSegmentParam } from "./segments/expandSegmentParam.js";
// Goals
export { createGoal } from "./goals/createGoal.js";
export { deleteGoal } from "./goals/deleteGoal.js";
+export { getGoalPreview } from "./goals/getGoalPreview.js";
export { getGoals } from "./goals/getGoals.js";
export { getGoalSessions } from "./goals/getGoalSessions.js";
+export { getGoalsSummary } from "./goals/getGoalsSummary.js";
export { getGoalTimeSeries } from "./goals/getGoalTimeSeries.js";
export { updateGoal } from "./goals/updateGoal.js";
@@ -59,6 +65,8 @@ export { getErrorEvents } from "./getErrorEvents.js";
export { getErrorNames } from "./getErrorNames.js";
export { generateCustomQuery } from "./generateCustomQuery.js";
export { getJourneys } from "./getJourneys.js";
+export { getJourneySessions } from "./getJourneySessions.js";
+export { getJourneySummary } from "./getJourneySummary.js";
export { getLiveUsercount } from "./getLiveUsercount.js";
export { getMetric } from "./getMetric.js";
export { getOrgEventCount } from "./getOrgEventCount.js";
@@ -69,15 +77,23 @@ export { getSiteCards, getSiteCardsLite } from "./getSiteCards.js";
export { getOverviewBucketedLite } from "./lite/getOverviewBucketedLite.js";
export { getMetricLite } from "./lite/getMetricLite.js";
export { getPageTitles } from "./getPageTitles.js";
+export { getPages, getPagesSummary, getPageTrends } from "./getPages.js";
export { getRetention } from "./getRetention.js";
export { runCustomQuery } from "./runCustomQuery.js";
export { getSession } from "./sessions/getSession.js";
export { getSessionLocations } from "./sessions/getSessionLocations.js";
export { getSessions } from "./sessions/getSessions.js";
+export { getSessionsSummary } from "./sessions/getSessionsSummary.js";
export { deleteUser } from "./users/deleteUser.js";
+export { getUserGoals, getUserSessionGoals } from "./users/getUserGoals.js";
export { getUserInfo } from "./users/getUserInfo.js";
+export { getUserRepeatedError } from "./users/getUserRepeatedError.js";
+export { getUserSegments } from "./users/getUserSegments.js";
export { getUserSessionCount } from "./users/getUserSessionCount.js";
+export { getUserSummary } from "./users/getUserSummary.js";
export { getUsers } from "./users/getUsers.js";
+export { getUsersSummary } from "./users/getUsersSummary.js";
+export { getUserTraitBreakdown } from "./users/getUserTraitBreakdown.js";
export { getUserTraitKeys, getUserTraitValues, getUserTraitValueUsers } from "./users/getUserTraits.js";
export { identifyUser } from "./users/identifyUser.js";
export { updateUserTraits } from "./users/updateUserTraits.js";
diff --git a/server/src/api/analytics/journeyPaths.ts b/server/src/api/analytics/journeyPaths.ts
new file mode 100644
index 000000000..b235f3b90
--- /dev/null
+++ b/server/src/api/analytics/journeyPaths.ts
@@ -0,0 +1,236 @@
+import { eq } from "drizzle-orm";
+import { z } from "zod";
+import { db } from "../../db/postgres/postgres.js";
+import { goals } from "../../db/postgres/schema.js";
+import { buildGoalCondition } from "./goals/goalConditions.js";
+import { QuerySpec } from "./utils/analyticsQuery.js";
+import { buildFilteredSessionsCTE } from "./utils/sessionFilters.js";
+import { getTimeStatement } from "./utils/timeWindow.js";
+import { patternToRegex } from "./utils/utils.js";
+
+/**
+ * How a session becomes a journey, shared by the three journeys endpoints (the
+ * paths, their summary, and the sessions behind one path) so that a row and the
+ * sessions it opens are the same sessions by construction.
+ */
+
+/** A journeys query always binds parameters (at least the site). */
+export type JourneyQuerySpec = Required<QuerySpec>;
+
+export const MIN_JOURNEY_STEPS = 2;
+export const MAX_JOURNEY_STEPS = 10;
+
+// stepFilters arrives as a JSON object mapping a (numeric) step index to a path
+// pattern. Both the keys and values are attacker-controlled, so validate the
+// shape before any of it reaches the ClickHouse query.
+export const stepFiltersSchema = z.record(
+ z.string().regex(/^\d+$/, "Step index must be a non-negative integer"),
+ z.string().max(2048)
+);
+
+export const journeyGroupingSchema = z.enum(["path", "section"]);
+export type JourneyGrouping = z.infer<typeof journeyGroupingSchema>;
+
+export const journeyOptionsSchema = z.object({
+ endsAt: z.string().max(2048).optional(),
+ groupBy: journeyGroupingSchema.default("path"),
+ goalId: z.coerce.number().int().positive().optional(),
+});
+
+export interface JourneyQuerystring {
+ steps?: string;
+ stepFilters?: string;
+ endsAt?: string;
+ groupBy?: string;
+ goalId?: string;
+}
+
+export interface JourneyOptions {
+ maxSteps: number;
+ stepFilters: Record<string, string>;
+ /** Path pattern. Journeys are cut at the first visit to it after the entry page. */
+ endsAt?: string;
+ groupBy: JourneyGrouping;
+ /** A goal's ClickHouse condition; adds a `conversions` count per journey. */
+ goalCondition?: string;
+}
+
+type ParsedJourneyOptions =
+ | { ok: true; options: Omit<JourneyOptions, "goalCondition">; goalId?: number }
+ | { ok: false; error: string };
+
+/** Validates the query params the journeys endpoints share. */
+export const parseJourneyOptions = (query: JourneyQuerystring): ParsedJourneyOptions => {
+ const maxSteps = parseInt(query.steps ?? "3", 10);
+ if (isNaN(maxSteps) || maxSteps < MIN_JOURNEY_STEPS || maxSteps > MAX_JOURNEY_STEPS) {
+ return { ok: false, error: "Steps parameter must be a number between 2 and 10" };
+ }
+
+ let stepFilters: Record<string, string> = {};
+ if (query.stepFilters) {
+ try {
+ stepFilters = stepFiltersSchema.parse(JSON.parse(query.stepFilters));
+ } catch {
+ return { ok: false, error: "Invalid stepFilters format" };
+ }
+ }
+
+ const parsed = journeyOptionsSchema.safeParse({
+ endsAt: query.endsAt,
+ groupBy: query.groupBy,
+ goalId: query.goalId,
+ });
+ if (!parsed.success) {
+ return { ok: false, error: "Invalid journey options" };
+ }
+
+ return {
+ ok: true,
+ options: {
+ maxSteps,
+ stepFilters,
+ endsAt: parsed.data.endsAt?.trim() || undefined,
+ groupBy: parsed.data.groupBy,
+ },
+ goalId: parsed.data.goalId,
+ };
+};
+
+type GoalLookup = { ok: true; goalCondition?: string } | { ok: false; status: number; error: string };
+
+/** Loads the goal a journey report measures conversion against, checking it belongs to the site. */
+export const resolveJourneyGoal = async (goalId: number | undefined, siteId: number): Promise<GoalLookup> => {
+ if (goalId === undefined) return { ok: true };
+
+ const [goal] = await db.select().from(goals).where(eq(goals.goalId, goalId)).limit(1);
+ if (!goal) return { ok: false, status: 404, error: "Goal not found" };
+ if (goal.siteId !== siteId) return { ok: false, status: 403, error: "Goal does not belong to this site" };
+
+ const goalCondition = buildGoalCondition(goal);
+ if (!goalCondition) return { ok: false, status: 400, error: "Invalid goal configuration" };
+
+ return { ok: true, goalCondition };
+};
+
+// Pages below a first-level section collapse into that section: /docs/script and
+// /docs/api/events both become /docs/**. Top-level pages (/, /pricing, /docs)
+// keep their own name. The result is itself a valid path pattern, so it works
+// unchanged as a step filter or a funnel step.
+const SECTION_OF_PAGE = "if(match(p, '^/[^/]+/.+'), concat(extract(p, '^(/[^/]+)/'), '/**'), p)";
+
+/**
+ * A predicate matching `subject` against a path pattern (* is one segment, ** is
+ * any number), bound as a query parameter rather than written into the SQL.
+ */
+const pagePredicate = (subject: string, pattern: string, paramName: string, params: Record<string, unknown>) => {
+ if (pattern.includes("*")) {
+ params[paramName] = patternToRegex(pattern);
+ return `match(${subject}, {${paramName}:String})`;
+ }
+ params[paramName] = pattern;
+ return `${subject} = {${paramName}:String}`;
+};
+
+export interface JourneyFragments {
+ /**
+ * The CTEs, comma-separated, without `WITH` and without a trailing comma:
+ * - `session_paths`: every session with a pageview and its page sequence
+ * - `user_paths`: the sessions that visited two or more pages
+ * - `session_journeys`: each of those sessions' journey, already narrowed
+ * by the step filters and, with `endsAt`, to the sessions that reach it
+ * - `GoalSessions` (with a goal): the sessions that completed the goal
+ */
+ ctes: string;
+ /** SQL for "this session completed the goal", or null without a goal. */
+ convertedExpression: string | null;
+ params: Record<string, unknown>;
+}
+
+export const buildJourneyFragments = (
+ query: { filters: string } & Parameters<typeof getTimeStatement>[0],
+ siteId: number,
+ options: JourneyOptions
+): JourneyFragments => {
+ const params: Record<string, unknown> = { siteId, maxSteps: options.maxSteps };
+ const timeStatement = getTimeStatement(query);
+ const filteredSessionsCTE = buildFilteredSessionsCTE(query.filters, siteId, timeStatement);
+ const filteredSessionsJoin = filteredSessionsCTE ? "INNER JOIN FilteredSessions USING (session_id)" : "";
+
+ const pages =
+ options.groupBy === "section" ? `arrayCompact(arrayMap(p -> ${SECTION_OF_PAGE}, path_sequence))` : "path_sequence";
+
+ // A journey is the first `maxSteps` pages of the session. With an end page it
+ // is instead the path up to the first visit to that page after the entry
+ // page, when that visit falls within `maxSteps`; other sessions are dropped.
+ let journey = "arraySlice(pages, 1, {maxSteps:Int32})";
+ const journeyConditions: string[] = [];
+ if (options.endsAt) {
+ const reachesEnd = pagePredicate("p", options.endsAt, "endsAt", params);
+ const endIndex = `arrayFirstIndex((p, i) -> i >= 2 AND ${reachesEnd}, pages, arrayEnumerate(pages))`;
+ journey = `if(${endIndex} BETWEEN 2 AND {maxSteps:Int32}, arraySlice(pages, 1, ${endIndex}), emptyArrayString())`;
+ journeyConditions.push("notEmpty(journey)");
+ }
+
+ // Wildcard patterns: * matches a single segment, ** matches several.
+ for (const [step, pattern] of Object.entries(options.stepFilters)) {
+ const stepIndex = parseInt(step, 10) + 1; // ClickHouse arrays are 1-indexed
+ // A filter on a step the journey does not have can only match nothing.
+ if (pattern === "" || stepIndex > options.maxSteps) continue;
+ journeyConditions.push(pagePredicate(`journey[${stepIndex}]`, pattern, `stepFilter${stepIndex}`, params));
+ }
+
+ const ctes = [
+ filteredSessionsCTE,
+ options.goalCondition
+ ? `GoalSessions AS (
+ SELECT DISTINCT session_id
+ FROM events
+ WHERE
+ site_id = {siteId:Int32}
+ ${timeStatement || ""}
+ AND (${options.goalCondition})
+ )`
+ : null,
+ `session_paths AS (
+ SELECT
+ session_id,
+ arrayCompact(groupArray(pathname)) AS path_sequence
+ FROM (
+ SELECT
+ session_id,
+ pathname,
+ timestamp
+ FROM events
+ ${filteredSessionsJoin}
+ WHERE
+ site_id = {siteId:Int32}
+ ${timeStatement || ""}
+ AND type = 'pageview'
+ ORDER BY session_id, timestamp
+ )
+ GROUP BY session_id
+ )`,
+ `user_paths AS (
+ SELECT session_id, path_sequence
+ FROM session_paths
+ WHERE length(path_sequence) >= 2
+ )`,
+ `session_journeys AS (
+ SELECT session_id, journey
+ FROM (
+ SELECT session_id, ${journey} AS journey
+ FROM (
+ SELECT session_id, ${pages} AS pages
+ FROM user_paths
+ )
+ )
+ ${journeyConditions.length ? `WHERE ${journeyConditions.join(" AND ")}` : ""}
+ )`,
+ ].filter((cte): cte is string => !!cte);
+
+ return {
+ ctes: ctes.join(",\n "),
+ convertedExpression: options.goalCondition ? "session_id IN (SELECT session_id FROM GoalSessions)" : null,
+ params,
+ };
+};
diff --git a/server/src/api/analytics/performance/getPerformanceByDimension.ts b/server/src/api/analytics/performance/getPerformanceByDimension.ts
index c2d3df8ff..9776626e1 100644
--- a/server/src/api/analytics/performance/getPerformanceByDimension.ts
+++ b/server/src/api/analytics/performance/getPerformanceByDimension.ts
@@ -3,6 +3,8 @@ import { getTimeStatement } from "../utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { analyticsRoute, getPaginationStatements, runPaginatedQuery } from "../utils/analyticsQuery.js";
import { buildSessionAndRowFilterFragments, TARGET_EVENT_ROW_LEVEL_PARAMS } from "../utils/sessionFilters.js";
+import { WebVitalRatingCounts } from "../types.js";
+import { WEB_VITAL_RATING_COLUMNS, webVitalRatingCounts } from "./webVitalRatings.js";
interface GetPerformanceByDimensionRequest {
Params: {
@@ -46,7 +48,7 @@ export type PerformanceByDimensionItem = {
ttfb_p75: number | null;
ttfb_p90: number | null;
ttfb_p99: number | null;
-};
+} & WebVitalRatingCounts;
type GetPerformanceByDimensionPaginatedResponse = {
data: PerformanceByDimensionItem[];
@@ -141,7 +143,8 @@ export const buildPerformanceByDimensionQuery = (
quantileIf(0.5)(ttfb, ttfb IS NOT NULL) as ttfb_p50,
quantileIf(0.75)(ttfb, ttfb IS NOT NULL) as ttfb_p75,
quantileIf(0.9)(ttfb, ttfb IS NOT NULL) as ttfb_p90,
- quantileIf(0.99)(ttfb, ttfb IS NOT NULL) as ttfb_p99
+ quantileIf(0.99)(ttfb, ttfb IS NOT NULL) as ttfb_p99,
+ ${webVitalRatingCounts()}
FROM events
${sessionJoin}
WHERE
@@ -191,7 +194,8 @@ export const buildPerformanceByDimensionQuery = (
ttfb_p50,
ttfb_p75,
ttfb_p90,
- ttfb_p99
+ ttfb_p99,
+ ${WEB_VITAL_RATING_COLUMNS.join(",\n ")}
FROM PerformanceStats
${orderByStatement}
${limitStatement}
diff --git a/server/src/api/analytics/performance/getPerformanceOverview.ts b/server/src/api/analytics/performance/getPerformanceOverview.ts
index e9fa1a07e..f0d8c6375 100644
--- a/server/src/api/analytics/performance/getPerformanceOverview.ts
+++ b/server/src/api/analytics/performance/getPerformanceOverview.ts
@@ -4,6 +4,7 @@ import { PerformanceOverviewMetrics } from "../types.js";
import { FilterParams } from "@rybbit/shared";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
import { buildSessionAndRowFilterFragments, TARGET_EVENT_ROW_LEVEL_PARAMS } from "../utils/sessionFilters.js";
+import { webVitalRatingCounts } from "./webVitalRatings.js";
export const buildPerformanceOverviewQuery = (query: FilterParams, siteId: number) => {
const timeStatement = getTimeStatement(query);
@@ -37,6 +38,7 @@ export const buildPerformanceOverviewQuery = (query: FilterParams, siteId: numbe
quantile(0.75)(ttfb) AS ttfb_p75,
quantile(0.9)(ttfb) AS ttfb_p90,
quantile(0.99)(ttfb) AS ttfb_p99,
+ ${webVitalRatingCounts()},
COUNT(*) AS total_performance_events
FROM events
${sessionJoin}
diff --git a/server/src/api/analytics/performance/webVitalRatings.test.ts b/server/src/api/analytics/performance/webVitalRatings.test.ts
new file mode 100644
index 000000000..1c582756f
--- /dev/null
+++ b/server/src/api/analytics/performance/webVitalRatings.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../db/clickhouse/clickhouse.js", () => ({
+ clickhouse: { query: vi.fn() },
+}));
+vi.mock("../../../db/postgres/postgres.js", () => ({
+ db: {},
+}));
+
+import { buildPerformanceByDimensionQuery } from "./getPerformanceByDimension.js";
+import { buildPerformanceOverviewQuery } from "./getPerformanceOverview.js";
+import {
+ WEB_VITAL_LIMITS,
+ WEB_VITAL_METRICS,
+ WEB_VITAL_RATING_COLUMNS,
+ webVitalRatingCounts,
+} from "./webVitalRatings.js";
+
+const SITE_ID = 1;
+const baseParams = { start_date: "2026-09-01", end_date: "2026-09-30", time_zone: "UTC", filters: "[]" };
+
+describe("web vital rating counts", () => {
+ it("counts measured, good and poor loads for every metric", () => {
+ const sql = webVitalRatingCounts();
+
+ expect(WEB_VITAL_METRICS).toEqual(["lcp", "cls", "inp", "fcp", "ttfb"]);
+ for (const metric of WEB_VITAL_METRICS) {
+ const { good, poor } = WEB_VITAL_LIMITS[metric];
+ expect(sql).toContain(`countIf(${metric} IS NOT NULL) AS ${metric}_count`);
+ expect(sql).toContain(`countIf(${metric} IS NOT NULL AND ${metric} <= ${good}) AS ${metric}_good`);
+ expect(sql).toContain(`countIf(${metric} IS NOT NULL AND ${metric} > ${poor}) AS ${metric}_poor`);
+ }
+ });
+
+ it("uses Google's limits, with good below poor", () => {
+ expect(WEB_VITAL_LIMITS).toEqual({
+ lcp: { good: 2500, poor: 4000 },
+ cls: { good: 0.1, poor: 0.25 },
+ inp: { good: 200, poor: 500 },
+ fcp: { good: 1800, poor: 3000 },
+ ttfb: { good: 800, poor: 1800 },
+ });
+ });
+
+ it("is part of the overview, next to the percentiles and the load count", () => {
+ const sql = buildPerformanceOverviewQuery(baseParams, SITE_ID);
+
+ expect(sql).toContain("quantile(0.75)(lcp) AS lcp_p75");
+ expect(sql).toContain("countIf(lcp IS NOT NULL AND lcp <= 2500) AS lcp_good");
+ expect(sql).toContain("countIf(cls IS NOT NULL AND cls > 0.25) AS cls_poor");
+ expect(sql).toContain("COUNT(*) AS total_performance_events");
+ });
+
+ it("is computed per dimension value and returned with each row", () => {
+ const sql = buildPerformanceByDimensionQuery({ ...baseParams, dimension: "pathname" }, SITE_ID, false);
+ const [stats, outerSelect] = sql.split("FROM PerformanceStats").map(part => part.trim());
+
+ expect(stats).toContain("countIf(inp IS NOT NULL AND inp <= 200) AS inp_good");
+ expect(stats).toContain("GROUP BY pathname");
+ // Every rating column the CTE computes is selected by the outer query.
+ const selected = sql.slice(sql.lastIndexOf("SELECT"), sql.lastIndexOf("FROM PerformanceStats"));
+ for (const column of WEB_VITAL_RATING_COLUMNS) {
+ expect(selected).toContain(column);
+ }
+ expect(outerSelect).toContain("ORDER BY event_count DESC");
+ expect(outerSelect).toContain("LIMIT 100");
+ });
+
+ it("leaves the count query a count", () => {
+ const sql = buildPerformanceByDimensionQuery({ ...baseParams, dimension: "region" }, SITE_ID, true);
+
+ expect(sql).toContain("SELECT COUNT(DISTINCT region) as totalCount FROM PerformanceStats");
+ expect(sql).not.toContain("LIMIT");
+ });
+
+ it("bounds the previous-period lookup for the rows on screen", () => {
+ const filters = JSON.stringify([{ parameter: "pathname", type: "equals", value: ["/pricing", "/demo"] }]);
+ const sql = buildPerformanceByDimensionQuery(
+ { ...baseParams, filters, dimension: "pathname", limit: 25 },
+ SITE_ID,
+ false
+ );
+
+ expect(sql).toContain("'/pricing'");
+ expect(sql).toContain("'/demo'");
+ expect(sql).toContain("LIMIT 25");
+ // The measured path is a row-level filter: no session qualification needed.
+ expect(sql).not.toContain("FilteredSessions AS (");
+ });
+});
diff --git a/server/src/api/analytics/performance/webVitalRatings.ts b/server/src/api/analytics/performance/webVitalRatings.ts
new file mode 100644
index 000000000..9f7660a80
--- /dev/null
+++ b/server/src/api/analytics/performance/webVitalRatings.ts
@@ -0,0 +1,37 @@
+import type { WebVitalMetric } from "@rybbit/shared";
+
+/**
+ * Google's Web Vitals limits: a value up to `good` is good, a value over
+ * `poor` is poor, anything between needs improvement. The client rates the
+ * percentiles it shows with the same numbers
+ * (client/src/app/[site]/performance/utils/performanceUtils.ts).
+ */
+export const WEB_VITAL_LIMITS: Record<WebVitalMetric, { good: number; poor: number }> = {
+ lcp: { good: 2500, poor: 4000 },
+ cls: { good: 0.1, poor: 0.25 },
+ inp: { good: 200, poor: 500 },
+ fcp: { good: 1800, poor: 3000 },
+ ttfb: { good: 800, poor: 1800 },
+};
+
+export const WEB_VITAL_METRICS = Object.keys(WEB_VITAL_LIMITS) as WebVitalMetric[];
+
+export const WEB_VITAL_RATING_COLUMNS = WEB_VITAL_METRICS.flatMap(metric => [
+ `${metric}_count`,
+ `${metric}_good`,
+ `${metric}_poor`,
+]);
+
+/**
+ * For each metric: how many loads reported it, and how many of those were good
+ * and poor (the rest need improvement). A load that never reported a metric,
+ * such as INP on a page nobody interacted with, counts towards none of the
+ * three, so shares are of the loads that were actually measured.
+ */
+export const webVitalRatingCounts = (): string =>
+ WEB_VITAL_METRICS.map(metric => {
+ const { good, poor } = WEB_VITAL_LIMITS[metric];
+ return `countIf(${metric} IS NOT NULL) AS ${metric}_count,
+ countIf(${metric} IS NOT NULL AND ${metric} <= ${good}) AS ${metric}_good,
+ countIf(${metric} IS NOT NULL AND ${metric} > ${poor}) AS ${metric}_poor`;
+ }).join(",\n ");
diff --git a/server/src/api/analytics/sessions/getSession.ts b/server/src/api/analytics/sessions/getSession.ts
index 0f22da42c..aa9957006 100644
--- a/server/src/api/analytics/sessions/getSession.ts
+++ b/server/src/api/analytics/sessions/getSession.ts
@@ -1,6 +1,7 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { SESSION_CHANNEL_AGG, SESSION_REFERRER_AGG } from "../utils/sessionAttribution.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { getSessionGoalMatcher, resolveSessionGoals, SessionGoal } from "./sessionGoals.js";
export interface SessionDetails {
session_id: string;
@@ -38,6 +39,8 @@ export interface Event {
type: string;
event_name?: string;
properties?: string;
+ // Goals this event completed. Empty for most events.
+ goals: SessionGoal[];
}
export interface SessionPageviewsAndEvents {
@@ -63,7 +66,10 @@ export interface GetSessionRequest {
};
}
-export const buildSessionQueries = (query: GetSessionRequest["Querystring"]) => {
+// Array(UInt32) of the goal ids an event completes; see buildSessionGoalMatcher.
+const NO_GOALS_EXPRESSION = "emptyArrayUInt32()";
+
+export const buildSessionQueries = (query: GetSessionRequest["Querystring"], goalExpression = NO_GOALS_EXPRESSION) => {
const minutes = query.minutes ? parseInt(query.minutes) : undefined;
// Add time filter if minutes is provided
@@ -130,7 +136,8 @@ SELECT
referrer,
type,
event_name,
- props
+ props,
+ ${goalExpression} AS goal_ids
FROM events
WHERE
site_id = {siteId:Int32}
@@ -152,7 +159,10 @@ export const getSession = analyticsRoute<GetSessionRequest>(
const limit = req.query.limit ? parseInt(req.query.limit) : 100;
const offset = req.query.offset ? parseInt(req.query.offset) : 0;
- const { sessionQuery, countQuery, eventsQuery } = buildSessionQueries(req.query);
+ // The same conditions the Goals page counts with, so an event marked here
+ // is one that page counted as a conversion.
+ const matcher = await getSessionGoalMatcher(Number(siteId));
+ const { sessionQuery, countQuery, eventsQuery } = buildSessionQueries(req.query, matcher.expression);
// Execute queries in parallel
const [sessionData, countData, eventsData] = await Promise.all([
@@ -170,7 +180,7 @@ export const getSession = analyticsRoute<GetSessionRequest>(
sessionId,
},
}),
- runAnalyticsQuery<Event>({
+ runAnalyticsQuery<Omit<Event, "goals"> & { goal_ids: number[] }>({
query: eventsQuery,
params: {
siteId: Number(siteId),
@@ -188,7 +198,10 @@ export const getSession = analyticsRoute<GetSessionRequest>(
// Combine results
const response: SessionPageviewsAndEvents = {
session: sessionData[0],
- events: eventsData,
+ events: eventsData.map(({ goal_ids, ...event }) => ({
+ ...event,
+ goals: resolveSessionGoals(matcher, [], goal_ids ?? []),
+ })),
pagination: {
total: countData[0].total,
limit,
diff --git a/server/src/api/analytics/sessions/getSessions.ts b/server/src/api/analytics/sessions/getSessions.ts
index 65eed11db..b92b7d349 100644
--- a/server/src/api/analytics/sessions/getSessions.ts
+++ b/server/src/api/analytics/sessions/getSessions.ts
@@ -1,19 +1,19 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
-import {
- SESSION_CHANNEL_AGG,
- SESSION_REFERRER_AGG,
- SESSION_UTM_CAMPAIGN_AGG,
- SESSION_UTM_CONTENT_AGG,
- SESSION_UTM_MEDIUM_AGG,
- SESSION_UTM_SOURCE_AGG,
- SESSION_UTM_TERM_AGG,
-} from "../utils/sessionAttribution.js";
import { getSessionFilterStatement } from "../utils/sessionFilters.js";
import { enrichWithTraits } from "../utils/utils.js";
import { getTimeStatement } from "../utils/timeWindow.js";
import { analyticsRoute, runAnalyticsQuery, QuerySpec } from "../utils/analyticsQuery.js";
-import { matchesUser } from "../utils/effectiveUserId.js";
+import { getSessionGoalMatcher, resolveSessionGoals, SessionGoal, SessionGoalMatcher } from "./sessionGoals.js";
+import {
+ buildAggregatedSessionsCTE,
+ buildRangeConditions,
+ buildSessionOrder,
+ buildViewCondition,
+ parseSessionListParams,
+ REPLAY_LOOKUP_QUERY,
+ sessionListParamsSchema,
+} from "./sessionQuery.js";
export type GetSessionsResponse = {
session_id: string;
@@ -58,6 +58,9 @@ export type GetSessionsResponse = {
lat: number;
lon: number;
has_replay: number;
+ // Goals the session completed, the most recent conversion first. Present
+ // when the request asked for goals (include_goals, or the converted view).
+ converted_goals?: SessionGoal[];
}[];
export interface GetSessionsRequest {
@@ -70,28 +73,44 @@ export interface GetSessionsRequest {
user_id?: string;
session_id?: string;
identified_only?: string;
+ view?: string;
+ sort_by?: string;
+ sort_order?: string;
+ include_goals?: string;
min_pageviews?: string;
+ max_pageviews?: string;
min_events?: string;
+ max_events?: string;
min_duration?: string;
+ max_duration?: string;
}>;
}
-export const buildSessionsQuery = (query: GetSessionsRequest["Querystring"], siteId: number): QuerySpec => {
- const {
- filters,
- page = 1,
- user_id: userId,
- session_id: sessionId,
- limit = 100,
- identified_only: identifiedOnly = "false",
- min_pageviews: minPageviewsStr,
- min_events: minEventsStr,
- min_duration: minDurationStr,
- } = query;
- const filterIdentified = identifiedOnly === "true";
- const minPageviews = minPageviewsStr ? parseInt(minPageviewsStr, 10) : undefined;
- const minEvents = minEventsStr ? parseInt(minEventsStr, 10) : undefined;
- const minDuration = minDurationStr ? parseInt(minDurationStr, 10) : undefined;
+const DEFAULT_LIMIT = 100;
+// The Globe timeline pages through sessions 10,000 at a time; nothing asks for more.
+const MAX_LIMIT = 10_000;
+// Session ids per replay lookup. Query parameters travel in the request URL,
+// so a 10,000-row page is looked up in slices rather than as one long list.
+const REPLAY_LOOKUP_CHUNK = 1000;
+
+const NO_GOALS: SessionGoalMatcher = { goals: [], expression: "emptyArrayUInt32()" };
+
+// Untrusted `limit`/`page`: anything unusable falls back to the defaults, and
+// one request can never ask for more than MAX_LIMIT rows.
+const toPositiveInt = (value: unknown, fallback: number) => {
+ const parsed = parseInt(String(value), 10);
+ return Number.isFinite(parsed) && parsed >= 1 ? parsed : fallback;
+};
+
+export const buildSessionsQuery = (
+ query: GetSessionsRequest["Querystring"],
+ siteId: number,
+ matcher: SessionGoalMatcher = NO_GOALS
+): QuerySpec => {
+ const { filters, user_id: userId, session_id: sessionId, identified_only: identifiedOnly = "false" } = query;
+ const params = sessionListParamsSchema.parse(query);
+ const limit = Math.min(toPositiveInt(query.limit, DEFAULT_LIMIT), MAX_LIMIT);
+ const page = toPositiveInt(query.page, 1);
const timeStatement = getTimeStatement(query);
@@ -102,76 +121,23 @@ export const buildSessionsQuery = (query: GetSessionsRequest["Querystring"], sit
// - fieldMappings: CTE extracts UTM params as separate columns, so we need to map the field names
const filterStatement = getSessionFilterStatement(filters, siteId, timeStatement);
+ const ranges = buildRangeConditions(params);
+ const conditions = [
+ identifiedOnly === "true" ? "identified_user_id != ''" : null,
+ buildViewCondition(params.view, query),
+ ...ranges.conditions,
+ ].filter((condition): condition is string => !!condition);
+
+ // The ORDER BY belongs to the statement that carries the LIMIT. It used to
+ // sit inside the CTE, where the outer query was free to ignore it, so
+ // consecutive pages could repeat or skip sessions.
const querySQL = `
- WITH AggregatedSessions AS (
- SELECT
- session_id,
- argMax(user_id, timestamp) AS user_id,
- argMax(identified_user_id, timestamp) AS identified_user_id,
- argMax(country, timestamp) AS country,
- argMax(region, timestamp) AS region,
- argMax(city, timestamp) AS city,
- argMax(language, timestamp) AS language,
- argMax(device_type, timestamp) AS device_type,
- argMax(browser, timestamp) AS browser,
- argMax(browser_version, timestamp) AS browser_version,
- argMax(operating_system, timestamp) AS operating_system,
- argMax(operating_system_version, timestamp) AS operating_system_version,
- argMax(screen_width, timestamp) AS screen_width,
- argMax(screen_height, timestamp) AS screen_height,
- ${SESSION_REFERRER_AGG} AS referrer,
- ${SESSION_CHANNEL_AGG} AS channel,
- argMin(hostname, timestamp) AS hostname,
- ${SESSION_UTM_SOURCE_AGG} AS utm_source,
- ${SESSION_UTM_MEDIUM_AGG} AS utm_medium,
- ${SESSION_UTM_CAMPAIGN_AGG} AS utm_campaign,
- ${SESSION_UTM_TERM_AGG} AS utm_term,
- ${SESSION_UTM_CONTENT_AGG} AS utm_content,
- MAX(timestamp) AS session_end,
- MIN(timestamp) AS session_start,
- dateDiff('second', MIN(timestamp), MAX(timestamp)) AS session_duration,
- argMinIf(pathname, timestamp_ms, type = 'pageview') AS entry_page,
- argMaxIf(pathname, timestamp_ms, type = 'pageview') AS exit_page,
- countIf(type = 'pageview') AS pageviews,
- countIf(type = 'custom_event') AS events,
- countIf(type = 'error') AS errors,
- countIf(type = 'outbound') AS outbound,
- countIf(type = 'button_click') AS button_clicks,
- countIf(type = 'copy') AS copies,
- countIf(type = 'form_submit') AS form_submits,
- countIf(type = 'input_change') AS input_changes,
- argMax(ip, timestamp) AS ip,
- argMax(lat, timestamp) AS lat,
- argMax(lon, timestamp) AS lon,
- argMax(tag, timestamp) AS tag,
- argMax(timezone, timestamp) AS timezone
- FROM events
- WHERE
- site_id = {siteId:Int32}
- ${userId ? ` AND ${matchesUser("{user_id:String}", "events")}` : ""}
- ${sessionId ? ` AND events.session_id = {session_id:String}` : ""}
- ${timeStatement}
- GROUP BY
- session_id
- ORDER BY session_end DESC
- ),
- ReplaySessions AS (
- SELECT DISTINCT session_id
- FROM session_replay_metadata_v2
- FINAL
- WHERE site_id = {siteId:Int32}
- AND event_count >= 2
- )
- SELECT
- a.*,
- if(r.session_id != '', 1, 0) AS has_replay
- FROM AggregatedSessions a
- LEFT JOIN ReplaySessions r ON a.session_id = r.session_id
+ WITH ${buildAggregatedSessionsCTE(query, matcher)}
+ SELECT *
+ FROM AggregatedSessions
WHERE 1 = 1 ${filterStatement}
- ${filterIdentified ? "AND a.identified_user_id != ''" : ""}
- ${minPageviews !== undefined ? "AND a.pageviews >= {minPageviews:Int32}" : ""}
- ${minEvents !== undefined ? "AND a.events >= {minEvents:Int32}" : ""}
- ${minDuration !== undefined ? "AND a.session_duration >= {minDuration:Int32}" : ""}
+ ${conditions.map(condition => `AND ${condition}`).join("\n ")}
+ ${buildSessionOrder(params.sort_by, params.sort_order)}
LIMIT {limit:Int32} OFFSET {offset:Int32}
`;
@@ -181,26 +147,66 @@ export const buildSessionsQuery = (query: GetSessionsRequest["Querystring"], sit
siteId,
user_id: userId,
session_id: sessionId,
- limit: limit || 100,
- offset: (page - 1) * (limit || 100),
- minPageviews: minPageviews ?? 0,
- minEvents: minEvents ?? 0,
- minDuration: minDuration ?? 0,
+ limit,
+ offset: (page - 1) * limit,
+ ...ranges.queryParams,
},
};
};
+type SessionRow = Omit<GetSessionsResponse[number], "traits" | "has_replay" | "converted_goals"> & {
+ converted_goal_ids: number[];
+ last_goal_ids: number[];
+};
+
+/** Slices of at most `size` ids, in order. */
+export const chunkIds = (ids: string[], size: number): string[][] =>
+ Array.from({ length: Math.ceil(ids.length / size) }, (_, index) => ids.slice(index * size, (index + 1) * size));
+
+/**
+ * Which of these sessions have a replay. A key lookup for the rows of one page,
+ * instead of the join that used to read all of the site's replay metadata on
+ * every list request.
+ */
+async function findSessionsWithReplay(siteId: number, sessionIds: string[]): Promise<Set<string>> {
+ const found = await Promise.all(
+ chunkIds(sessionIds, REPLAY_LOOKUP_CHUNK).map(ids =>
+ runAnalyticsQuery<{ session_id: string }>({ query: REPLAY_LOOKUP_QUERY, params: { siteId, sessionIds: ids } })
+ )
+ );
+ return new Set(found.flat().map(row => row.session_id));
+}
+
export const getSessions = analyticsRoute<GetSessionsRequest>(
"sessions",
async (req: FastifyRequest<GetSessionsRequest>, res: FastifyReply) => {
- const site = req.params.siteId;
+ const siteId = Number(req.params.siteId);
- const data = await runAnalyticsQuery<Omit<GetSessionsResponse[number], "traits">>(
- buildSessionsQuery(req.query, Number(site))
+ const parsed = parseSessionListParams(req.query);
+ if (!parsed.ok) {
+ return res.status(400).send({ error: parsed.error });
+ }
+
+ // Goals are matched only for a request that shows or filters on them.
+ const wantsGoals = parsed.params.include_goals === "true" || parsed.params.view === "converted";
+ const matcher = wantsGoals ? await getSessionGoalMatcher(siteId) : NO_GOALS;
+ const rows = await runAnalyticsQuery<SessionRow>(buildSessionsQuery(req.query, siteId, matcher));
+
+ const withReplay = await findSessionsWithReplay(
+ siteId,
+ rows.map(row => row.session_id)
);
+ const data = rows.map(({ converted_goal_ids, last_goal_ids, ...row }) => ({
+ ...row,
+ has_replay: withReplay.has(row.session_id) ? 1 : 0,
+ ...(wantsGoals
+ ? { converted_goals: resolveSessionGoals(matcher, last_goal_ids ?? [], converted_goal_ids ?? []) }
+ : {}),
+ }));
+
// Enrich with traits from Postgres
- const dataWithTraits = await enrichWithTraits(data, Number(site));
+ const dataWithTraits = await enrichWithTraits(data, siteId);
return res.send({ data: dataWithTraits });
}
diff --git a/server/src/api/analytics/sessions/getSessionsSummary.ts b/server/src/api/analytics/sessions/getSessionsSummary.ts
new file mode 100644
index 000000000..580d996bc
--- /dev/null
+++ b/server/src/api/analytics/sessions/getSessionsSummary.ts
@@ -0,0 +1,171 @@
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { analyticsRoute, QuerySpec, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { getSessionFilterStatement } from "../utils/sessionFilters.js";
+import { getTimeStatement, isValidTimeZone } from "../utils/timeWindow.js";
+import { getSessionGoalMatcher, SessionGoalMatcher } from "./sessionGoals.js";
+import {
+ buildAggregatedSessionsCTE,
+ buildRangeConditions,
+ buildViewCondition,
+ parseSessionListParams,
+ sessionListParamsSchema,
+ SessionView,
+} from "./sessionQuery.js";
+
+/** How many sessions each saved view holds. `converted` is null on a site with no goals. */
+export interface SessionViewCounts {
+ all: number;
+ identified: number;
+ replay: number;
+ converted: number | null;
+ bounced: number;
+ errors: number;
+}
+
+export interface SessionsSummary {
+ // The period at a glance: every session the filters allow, whatever the
+ // pageview/event/duration ranges are set to.
+ sessions: number;
+ session_duration: number;
+ pages_per_session: number;
+ bounce_rate: number;
+ converted: number | null;
+ with_errors: number;
+ // The same sessions narrowed by the ranges, per view: the tab counts and the
+ // list's total.
+ matching: SessionViewCounts;
+ // `matching` split by the day each session started, in the request's
+ // timezone, newest first.
+ days: ({ day: string } & SessionViewCounts)[];
+}
+
+export interface GetSessionsSummaryRequest {
+ Params: {
+ siteId: string;
+ };
+ Querystring: FilterParams<{
+ min_pageviews?: string;
+ max_pageviews?: string;
+ min_events?: string;
+ max_events?: string;
+ min_duration?: string;
+ max_duration?: string;
+ }>;
+}
+
+// A day row per day of the window; ten years of days is far past any real range.
+const MAX_DAYS = 3660;
+
+const COUNTED_VIEWS: Exclude<SessionView, "all">[] = ["identified", "replay", "converted", "bounced", "errors"];
+
+/**
+ * One pass over the period's sessions, grouped by the day they started. The
+ * rollup row (empty `day`) carries the period totals, so totals and day rows
+ * cannot disagree and no second scan is needed for the list's total.
+ */
+export const buildSessionsSummaryQuery = (
+ query: GetSessionsSummaryRequest["Querystring"],
+ siteId: number,
+ matcher: SessionGoalMatcher
+): QuerySpec => {
+ const params = sessionListParamsSchema.parse(query);
+ const timeStatement = getTimeStatement(query);
+ const filterStatement = getSessionFilterStatement(query.filters, siteId, timeStatement);
+ const ranges = buildRangeConditions(params);
+ const inRange = ranges.conditions.length ? ranges.conditions.join(" AND ") : "1";
+
+ const viewCounts = COUNTED_VIEWS.map(
+ view => `countIf(${inRange} AND ${buildViewCondition(view, query)}) AS matching_${view}`
+ ).join(",\n ");
+
+ const querySQL = `
+ WITH ${buildAggregatedSessionsCTE(query, matcher)}
+ SELECT
+ toString(toDate(session_start, {timeZone:String})) AS day,
+ count() AS sessions,
+ -- Not aliased to the column names: the ranges below read those columns,
+ -- and an alias that shadows one turns them into nested aggregates.
+ avg(session_duration) AS avg_duration,
+ avg(pageviews) AS avg_pageviews,
+ countIf(pageviews = 1) AS bounced,
+ countIf(notEmpty(converted_goal_ids)) AS converted,
+ countIf(errors > 0) AS with_errors,
+ countIf(${inRange}) AS matching_all,
+ ${viewCounts}
+ FROM AggregatedSessions
+ WHERE 1 = 1 ${filterStatement}
+ GROUP BY day WITH ROLLUP
+ ORDER BY day = '' DESC, day DESC
+ LIMIT {maxRows:Int32}
+ `;
+
+ return {
+ query: querySQL,
+ params: {
+ siteId,
+ timeZone: query.time_zone && isValidTimeZone(query.time_zone) ? query.time_zone : "UTC",
+ maxRows: MAX_DAYS + 1,
+ ...ranges.queryParams,
+ },
+ };
+};
+
+type SummaryRow = {
+ day: string;
+ sessions: number;
+ avg_duration: number | null;
+ avg_pageviews: number | null;
+ bounced: number;
+ converted: number;
+ with_errors: number;
+ matching_all: number;
+ matching_identified: number;
+ matching_replay: number;
+ matching_converted: number;
+ matching_bounced: number;
+ matching_errors: number;
+};
+
+const viewCounts = (row: SummaryRow | undefined, hasGoals: boolean): SessionViewCounts => ({
+ all: row?.matching_all ?? 0,
+ identified: row?.matching_identified ?? 0,
+ replay: row?.matching_replay ?? 0,
+ converted: hasGoals ? (row?.matching_converted ?? 0) : null,
+ bounced: row?.matching_bounced ?? 0,
+ errors: row?.matching_errors ?? 0,
+});
+
+/** Rollup row to period totals, day rows to `days`. An empty period has no rollup row. */
+export function toSessionsSummary(rows: SummaryRow[], hasGoals: boolean): SessionsSummary {
+ const total = rows.find(row => row.day === "");
+ const sessions = total?.sessions ?? 0;
+
+ return {
+ sessions,
+ session_duration: total?.avg_duration ?? 0,
+ pages_per_session: total?.avg_pageviews ?? 0,
+ bounce_rate: sessions > 0 ? ((total?.bounced ?? 0) / sessions) * 100 : 0,
+ converted: hasGoals ? (total?.converted ?? 0) : null,
+ with_errors: total?.with_errors ?? 0,
+ matching: viewCounts(total, hasGoals),
+ days: rows.filter(row => row.day !== "").map(row => ({ day: row.day, ...viewCounts(row, hasGoals) })),
+ };
+}
+
+export const getSessionsSummary = analyticsRoute<GetSessionsSummaryRequest>(
+ "sessions summary",
+ async (req: FastifyRequest<GetSessionsSummaryRequest>, res: FastifyReply) => {
+ const siteId = Number(req.params.siteId);
+
+ const parsed = parseSessionListParams(req.query);
+ if (!parsed.ok) {
+ return res.status(400).send({ error: parsed.error });
+ }
+
+ const matcher = await getSessionGoalMatcher(siteId);
+ const rows = await runAnalyticsQuery<SummaryRow>(buildSessionsSummaryQuery(req.query, siteId, matcher));
+
+ return res.send({ data: toSessionsSummary(rows, matcher.goals.length > 0) });
+ }
+);
diff --git a/server/src/api/analytics/sessions/sessionGoals.ts b/server/src/api/analytics/sessions/sessionGoals.ts
new file mode 100644
index 000000000..1e8c80635
--- /dev/null
+++ b/server/src/api/analytics/sessions/sessionGoals.ts
@@ -0,0 +1,80 @@
+import { asc, eq } from "drizzle-orm";
+import { db } from "../../../db/postgres/postgres.js";
+import { goals } from "../../../db/postgres/schema.js";
+import { buildGoalCondition } from "../goals/goalConditions.js";
+
+/** A goal as the session endpoints report it: enough to name it and link to it. */
+export interface SessionGoal {
+ id: number;
+ name: string | null;
+}
+
+type GoalRow = Pick<typeof goals.$inferSelect, "goalId" | "name" | "goalType" | "config">;
+
+/**
+ * Every goal condition is evaluated against every event of the period, so the
+ * number of goals a session query will look at is capped. A site past the cap
+ * reports conversions for its oldest goals only.
+ */
+export const MAX_SESSION_GOALS = 50;
+
+/** No goals: the typed empty array, so the column exists either way. */
+const NO_GOALS_EXPRESSION = "emptyArrayUInt32()";
+
+export interface SessionGoalMatcher {
+ /** The goals the expression can report, i.e. those with a usable condition. */
+ goals: SessionGoal[];
+ /**
+ * Per-event SQL expression of type Array(UInt32): the ids of the goals this
+ * event completes. Reads the unqualified `events` columns.
+ */
+ expression: string;
+}
+
+/**
+ * Turns a site's goals into one expression that tags an event with the goals
+ * it completes, using the same conditions the Goals page counts with
+ * (buildGoalCondition), so a session marked as converted here is one the Goals
+ * page counted.
+ */
+export function buildSessionGoalMatcher(siteGoals: GoalRow[]): SessionGoalMatcher {
+ const matched: SessionGoal[] = [];
+ const branches: string[] = [];
+
+ for (const goal of siteGoals.slice(0, MAX_SESSION_GOALS)) {
+ const condition = buildGoalCondition(goal);
+ if (!condition) continue;
+ // goalId is a Postgres serial; coerced so nothing but a number can reach the SQL.
+ const id = Number(goal.goalId);
+ if (!Number.isInteger(id) || id <= 0) continue;
+
+ matched.push({ id, name: goal.name });
+ branches.push(`if((${condition}), toUInt32(${id}), toUInt32(0))`);
+ }
+
+ return {
+ goals: matched,
+ expression: branches.length ? `arrayFilter(x -> x != 0, [${branches.join(", ")}])` : NO_GOALS_EXPRESSION,
+ };
+}
+
+export async function getSessionGoalMatcher(siteId: number): Promise<SessionGoalMatcher> {
+ const siteGoals = await db
+ .select({ goalId: goals.goalId, name: goals.name, goalType: goals.goalType, config: goals.config })
+ .from(goals)
+ .where(eq(goals.siteId, siteId))
+ .orderBy(asc(goals.goalId))
+ .limit(MAX_SESSION_GOALS);
+
+ return buildSessionGoalMatcher(siteGoals);
+}
+
+/**
+ * Goal ids back to goals, most recent conversion first: `latest` are the goals
+ * the session's last converting event completed, `all` every goal it completed.
+ */
+export function resolveSessionGoals(matcher: SessionGoalMatcher, latest: number[], all: number[]): SessionGoal[] {
+ const byId = new Map(matcher.goals.map(goal => [goal.id, goal]));
+ const ordered = [...new Set([...latest, ...[...all].sort((a, b) => a - b)])];
+ return ordered.flatMap(id => byId.get(Number(id)) ?? []);
+}
diff --git a/server/src/api/analytics/sessions/sessionQueries.test.ts b/server/src/api/analytics/sessions/sessionQueries.test.ts
new file mode 100644
index 000000000..26789d46c
--- /dev/null
+++ b/server/src/api/analytics/sessions/sessionQueries.test.ts
@@ -0,0 +1,336 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../db/clickhouse/clickhouse.js", () => ({
+ clickhouse: { query: vi.fn() },
+}));
+vi.mock("../../../db/postgres/postgres.js", () => ({
+ db: {},
+}));
+
+import { buildSessionQueries } from "./getSession.js";
+import { buildSessionsQuery, chunkIds } from "./getSessions.js";
+import { buildSessionsSummaryQuery, toSessionsSummary } from "./getSessionsSummary.js";
+import { buildSessionGoalMatcher, MAX_SESSION_GOALS, resolveSessionGoals } from "./sessionGoals.js";
+import { parseSessionListParams, REPLAY_LOOKUP_QUERY, SESSION_EVENT_TOTAL } from "./sessionQuery.js";
+
+const window = { start_date: "2026-09-01", end_date: "2026-09-30", time_zone: "UTC", filters: "" };
+const listQuery = { ...window, page: 1, limit: 20 };
+
+const signup = { goalId: 3, name: "Signup", goalType: "event", config: { eventName: "signup" } };
+const pricing = { goalId: 5, name: null, goalType: "path", config: { pathPattern: "/pricing" } };
+const broken = { goalId: 7, name: "No pattern", goalType: "path", config: {} };
+const matcher = buildSessionGoalMatcher([signup, pricing, broken]);
+
+// Everything from the statement that carries the LIMIT, i.e. past the CTE.
+const outerQuery = (sql: string) => sql.slice(sql.lastIndexOf("FROM AggregatedSessions"));
+
+describe("buildSessionsQuery paging", () => {
+ it("orders in the statement that carries the LIMIT, with a full tie-break", () => {
+ const { query } = buildSessionsQuery(listQuery, 1);
+ const outer = outerQuery(query);
+
+ expect(outer).toMatch(/ORDER BY session_end DESC, session_start DESC, session_id DESC\s+LIMIT/);
+ // The CTE no longer carries an ORDER BY the outer query was free to drop.
+ expect(query.slice(0, query.lastIndexOf("FROM AggregatedSessions"))).not.toContain("ORDER BY");
+ });
+
+ it("sorts by an allowed column in the requested direction", () => {
+ const sql = (sort_by: string, sort_order?: string) =>
+ outerQuery(buildSessionsQuery({ ...listQuery, sort_by, sort_order }, 1).query);
+
+ expect(sql("started")).toContain("ORDER BY session_start DESC, session_id DESC");
+ expect(sql("duration", "asc")).toContain("ORDER BY session_duration ASC, session_start ASC, session_id ASC");
+ expect(sql("events")).toContain(`ORDER BY ${SESSION_EVENT_TOTAL} DESC`);
+ expect(sql("errors")).toContain("ORDER BY errors DESC");
+ });
+
+ it("refuses a sort column or direction that is not on the list", () => {
+ expect(parseSessionListParams({ sort_by: "session_id; DROP TABLE events" })).toMatchObject({ ok: false });
+ expect(parseSessionListParams({ sort_order: "sideways" })).toMatchObject({ ok: false });
+ expect(parseSessionListParams({ view: "everything" })).toMatchObject({ ok: false });
+ expect(() => buildSessionsQuery({ ...listQuery, sort_by: "ip" }, 1)).toThrow();
+ });
+
+ it("caps the page size and falls back on unusable paging params", () => {
+ expect(buildSessionsQuery({ ...listQuery, limit: 50000, page: 3 }, 1).params).toMatchObject({
+ limit: 10000,
+ offset: 20000,
+ });
+ // The Globe timeline's page size still gets what it asks for.
+ expect(buildSessionsQuery({ ...listQuery, limit: 10000, page: 2 }, 1).params).toMatchObject({
+ limit: 10000,
+ offset: 10000,
+ });
+ expect(buildSessionsQuery({ ...window, limit: "abc", page: "-4" } as any, 1).params).toMatchObject({
+ limit: 100,
+ offset: 0,
+ });
+ // The value the page sends when it peeks one row past the page.
+ expect(buildSessionsQuery({ ...window, limit: "101", page: "2" } as any, 1).params).toMatchObject({
+ limit: 101,
+ offset: 101,
+ });
+ });
+});
+
+describe("buildSessionsQuery ranges and views", () => {
+ it("binds min and max bounds instead of interpolating them", () => {
+ const { query, params } = buildSessionsQuery(
+ { ...listQuery, min_pageviews: "2", max_pageviews: "9", min_duration: "10", max_duration: "600" },
+ 1
+ );
+ const outer = outerQuery(query);
+
+ expect(outer).toContain("AND pageviews >= {minPageviews:Int32}");
+ expect(outer).toContain("AND pageviews <= {maxPageviews:Int32}");
+ expect(outer).toContain("AND session_duration >= {minDuration:Int32}");
+ expect(outer).toContain("AND session_duration <= {maxDuration:Int32}");
+ expect(params).toMatchObject({ minPageviews: 2, maxPageviews: 9, minDuration: 10, maxDuration: 600 });
+ });
+
+ it("filters events on the total the row shows, not custom events alone", () => {
+ const { query, params } = buildSessionsQuery({ ...listQuery, min_events: "3", max_events: "8" }, 1);
+ const outer = outerQuery(query);
+
+ expect(SESSION_EVENT_TOTAL).toBe("(events + button_clicks + copies + form_submits + input_changes)");
+ expect(outer).toContain(`AND ${SESSION_EVENT_TOTAL} >= {minEvents:Int32}`);
+ expect(outer).toContain(`AND ${SESSION_EVENT_TOTAL} <= {maxEvents:Int32}`);
+ expect(params).toMatchObject({ minEvents: 3, maxEvents: 8 });
+ });
+
+ it("leaves unset and empty bounds out, and rejects ones that are not whole numbers", () => {
+ const { query, params } = buildSessionsQuery({ ...listQuery, min_pageviews: "", max_events: undefined }, 1);
+
+ expect(outerQuery(query)).not.toContain("{minPageviews:Int32}");
+ expect(params).not.toHaveProperty("minPageviews");
+ expect(parseSessionListParams({ min_duration: "soon" })).toMatchObject({ ok: false });
+ expect(parseSessionListParams({ max_pageviews: "-1" })).toMatchObject({ ok: false });
+ expect(parseSessionListParams({ max_pageviews: "2.5" })).toMatchObject({ ok: false });
+ });
+
+ it("applies each saved view as one condition over the aggregated sessions", () => {
+ const outer = (view: string) => outerQuery(buildSessionsQuery({ ...listQuery, view }, 1, matcher).query);
+
+ expect(outer("identified")).toContain("AND identified_user_id != ''");
+ expect(outer("converted")).toContain("AND notEmpty(converted_goal_ids)");
+ expect(outer("bounced")).toContain("AND pageviews = 1");
+ expect(outer("errors")).toContain("AND errors > 0");
+ expect(outer("all")).not.toMatch(/AND (identified_user_id|notEmpty|pageviews = 1|errors > 0)/);
+ });
+
+ it("still honours identified_only", () => {
+ const { query } = buildSessionsQuery({ ...listQuery, identified_only: "true" }, 1);
+ expect(outerQuery(query)).toContain("AND identified_user_id != ''");
+ });
+});
+
+describe("replay lookups", () => {
+ it("does not read replay metadata unless the replay view asks for it", () => {
+ expect(buildSessionsQuery(listQuery, 1).query).not.toContain("session_replay_metadata_v2");
+ });
+
+ it("bounds the replay view's scan by the request's window", () => {
+ const { query } = buildSessionsQuery({ ...listQuery, view: "replay" }, 1);
+ const replay = query.slice(query.indexOf("FROM session_replay_metadata_v2"));
+
+ expect(replay).toContain("site_id = {siteId:Int32}");
+ expect(replay).toContain("event_count >= 2");
+ expect(replay).toContain("AND start_time >= toTimeZone(");
+ expect(replay).toContain("toStartOfDay(toDateTime('2026-09-01', 'UTC'))");
+ });
+
+ it("flags a page's rows with a key lookup", () => {
+ expect(REPLAY_LOOKUP_QUERY).toContain("session_id IN ({sessionIds:Array(String)})");
+ expect(REPLAY_LOOKUP_QUERY).toContain("site_id = {siteId:Int32}");
+ });
+
+ it("looks a large page up in slices, and an empty page not at all", () => {
+ const ids = Array.from({ length: 2500 }, (_, index) => `s${index}`);
+ const chunks = chunkIds(ids, 1000);
+
+ expect(chunks.map(chunk => chunk.length)).toEqual([1000, 1000, 500]);
+ expect(chunks.flat()).toEqual(ids);
+ expect(chunkIds([], 1000)).toEqual([]);
+ });
+});
+
+describe("session goals", () => {
+ it("tags events with the goals they complete, using the Goals page's conditions", () => {
+ expect(matcher.goals).toEqual([
+ { id: 3, name: "Signup" },
+ { id: 5, name: null },
+ ]);
+ expect(matcher.expression).toContain("arrayFilter(x -> x != 0, [");
+ expect(matcher.expression).toContain(
+ "if((type = 'custom_event' AND event_name = 'signup'), toUInt32(3), toUInt32(0))"
+ );
+ expect(matcher.expression).toContain("type = 'pageview' AND match(pathname,");
+ // A goal with no usable condition is skipped rather than matching everything.
+ expect(matcher.expression).not.toContain("toUInt32(7)");
+ });
+
+ it("keeps the column typed when the site has no goals", () => {
+ const none = buildSessionGoalMatcher([]);
+ const { query } = buildSessionsQuery(listQuery, 1, none);
+
+ expect(none).toEqual({ goals: [], expression: "emptyArrayUInt32()" });
+ expect(query).toContain("emptyArrayUInt32() AS converted_goal_ids");
+ expect(query).not.toContain("groupUniqArrayArray");
+ });
+
+ it("matches no goals for a caller that did not ask for them", () => {
+ // The live-visitors drawer, the Globe and the user profile read this list
+ // without goals; they get the same query they always ran.
+ const { query } = buildSessionsQuery(listQuery, 1);
+
+ expect(query).not.toContain("groupUniqArrayArray");
+ expect(query).not.toContain("match(pathname");
+ expect(parseSessionListParams({ include_goals: "true" })).toMatchObject({ ok: true });
+ expect(parseSessionListParams({ include_goals: "yes" })).toMatchObject({ ok: false });
+ });
+
+ it("escapes goal text and never looks past the cap", () => {
+ const hostile = buildSessionGoalMatcher([
+ { goalId: 1, name: "x", goalType: "event", config: { eventName: "a') OR 1=1 --" } },
+ ]);
+ expect(hostile.expression).toContain("event_name = 'a\\') OR 1=1 --'");
+
+ const many = Array.from({ length: MAX_SESSION_GOALS + 5 }, (_, index) => ({
+ goalId: index + 1,
+ name: null,
+ goalType: "event",
+ config: { eventName: `event_${index}` },
+ }));
+ expect(buildSessionGoalMatcher(many).goals).toHaveLength(MAX_SESSION_GOALS);
+ });
+
+ it("aggregates a session's goals and its latest conversion", () => {
+ const { query } = buildSessionsQuery(listQuery, 1, matcher);
+
+ expect(query).toContain(`groupUniqArrayArray(${matcher.expression}) AS converted_goal_ids`);
+ expect(query).toContain(
+ `argMaxIf(${matcher.expression}, timestamp_ms, notEmpty(${matcher.expression})) AS last_goal_ids`
+ );
+ });
+
+ it("lists the latest conversion first and drops ids it cannot name", () => {
+ expect(resolveSessionGoals(matcher, [5], [3, 5, 99])).toEqual([
+ { id: 5, name: null },
+ { id: 3, name: "Signup" },
+ ]);
+ expect(resolveSessionGoals(matcher, [], [])).toEqual([]);
+ });
+
+ it("marks the converting events of a session's timeline", () => {
+ expect(buildSessionQueries({}, matcher.expression).eventsQuery).toContain(`${matcher.expression} AS goal_ids`);
+ expect(buildSessionQueries({}).eventsQuery).toContain("emptyArrayUInt32() AS goal_ids");
+ });
+});
+
+describe("buildSessionsSummaryQuery", () => {
+ it("counts every view over the same sessions the list pages through", () => {
+ const filters = JSON.stringify([{ parameter: "country", type: "equals", value: ["US"] }]);
+ const summary = buildSessionsSummaryQuery({ ...window, filters, min_duration: "10" }, 1, matcher);
+ const list = buildSessionsQuery({ ...listQuery, filters, min_duration: "10" }, 1, matcher);
+ const cte = (sql: string) => sql.slice(sql.indexOf("AggregatedSessions AS ("), sql.indexOf("GROUP BY\n"));
+
+ // Same aggregation, same session filter.
+ expect(cte(summary.query)).toContain("countIf(type = 'pageview') AS pageviews");
+ expect(cte(summary.query)).toBe(cte(list.query));
+ expect(outerQuery(summary.query)).toContain("WHERE 1 = 1 AND country = 'US'");
+ expect(outerQuery(list.query)).toContain("WHERE 1 = 1 AND country = 'US'");
+ expect(summary.params).toMatchObject({ siteId: 1, minDuration: 10, timeZone: "UTC" });
+ });
+
+ it("keeps the period totals free of the ranges and applies them to the view counts", () => {
+ const { query } = buildSessionsSummaryQuery({ ...window, min_duration: "10", max_pageviews: "5" }, 1, matcher);
+ const inRange = "session_duration >= {minDuration:Int32}";
+
+ expect(query).toContain("count() AS sessions");
+ expect(query).toContain("countIf(pageviews = 1) AS bounced");
+ expect(query).toContain(
+ "countIf(pageviews <= {maxPageviews:Int32} AND session_duration >= {minDuration:Int32}) AS matching_all"
+ );
+ expect(query).toContain(`${inRange} AND identified_user_id != '') AS matching_identified`);
+ expect(query).toContain(`${inRange} AND notEmpty(converted_goal_ids)) AS matching_converted`);
+ expect(query).toContain(`${inRange} AND pageviews = 1) AS matching_bounced`);
+ expect(query).toContain(`${inRange} AND errors > 0) AS matching_errors`);
+ expect(query).toMatch(/AND session_id IN \([\s\S]*session_replay_metadata_v2[\s\S]*\) AS matching_replay/);
+ // An alias named after a column the ranges read would nest the aggregates.
+ expect(query).not.toMatch(/AS (session_duration|pageviews|errors)\b,\n\s+avg/);
+ expect(query).toContain("avg(session_duration) AS avg_duration");
+ });
+
+ it("groups by the day a session started in the viewer's timezone, with period totals", () => {
+ const { query, params } = buildSessionsSummaryQuery({ ...window, time_zone: "America/New_York" }, 1, matcher);
+
+ expect(query).toContain("toString(toDate(session_start, {timeZone:String})) AS day");
+ expect(query).toContain("GROUP BY day WITH ROLLUP");
+ expect(query).toContain("LIMIT {maxRows:Int32}");
+ expect(params).toMatchObject({ timeZone: "America/New_York" });
+ expect(buildSessionsSummaryQuery({ ...window, time_zone: "Not/AZone" }, 1, matcher).params).toMatchObject({
+ timeZone: "UTC",
+ });
+ });
+});
+
+describe("toSessionsSummary", () => {
+ const row = (day: string, sessions: number, overrides: Record<string, number> = {}) => ({
+ day,
+ sessions,
+ avg_duration: 120,
+ avg_pageviews: 2.5,
+ bounced: 1,
+ converted: 2,
+ with_errors: 1,
+ matching_all: sessions,
+ matching_identified: 1,
+ matching_replay: 0,
+ matching_converted: 2,
+ matching_bounced: 1,
+ matching_errors: 1,
+ ...overrides,
+ });
+
+ it("reads period totals from the rollup row and days from the rest", () => {
+ const summary = toSessionsSummary(
+ [row("", 4, { matching_all: 3 }), row("2026-09-30", 3), row("2026-09-29", 1)],
+ true
+ );
+
+ expect(summary).toMatchObject({
+ sessions: 4,
+ session_duration: 120,
+ pages_per_session: 2.5,
+ bounce_rate: 25,
+ converted: 2,
+ with_errors: 1,
+ matching: { all: 3, identified: 1, replay: 0, converted: 2, bounced: 1, errors: 1 },
+ });
+ expect(summary.days.map(day => [day.day, day.all])).toEqual([
+ ["2026-09-30", 3],
+ ["2026-09-29", 1],
+ ]);
+ });
+
+ it("reports no conversion figures for a site without goals", () => {
+ const summary = toSessionsSummary([row("", 4), row("2026-09-30", 4)], false);
+
+ expect(summary.converted).toBeNull();
+ expect(summary.matching.converted).toBeNull();
+ expect(summary.days[0].converted).toBeNull();
+ });
+
+ it("is all zeros for an empty period", () => {
+ expect(toSessionsSummary([], true)).toEqual({
+ sessions: 0,
+ session_duration: 0,
+ pages_per_session: 0,
+ bounce_rate: 0,
+ converted: 0,
+ with_errors: 0,
+ matching: { all: 0, identified: 0, replay: 0, converted: 0, bounced: 0, errors: 0 },
+ days: [],
+ });
+ });
+});
diff --git a/server/src/api/analytics/sessions/sessionQuery.ts b/server/src/api/analytics/sessions/sessionQuery.ts
new file mode 100644
index 000000000..d438d85bc
--- /dev/null
+++ b/server/src/api/analytics/sessions/sessionQuery.ts
@@ -0,0 +1,228 @@
+import { z } from "zod";
+import { matchesUser } from "../utils/effectiveUserId.js";
+import {
+ SESSION_CHANNEL_AGG,
+ SESSION_REFERRER_AGG,
+ SESSION_UTM_CAMPAIGN_AGG,
+ SESSION_UTM_CONTENT_AGG,
+ SESSION_UTM_MEDIUM_AGG,
+ SESSION_UTM_SOURCE_AGG,
+ SESSION_UTM_TERM_AGG,
+} from "../utils/sessionAttribution.js";
+import { getTimeStatement, TimeWindowParams } from "../utils/timeWindow.js";
+import { SessionGoalMatcher } from "./sessionGoals.js";
+
+/**
+ * The pieces the session list and the session summary share, so the two can
+ * only ever describe the same set of sessions: the per-session aggregation,
+ * the saved views, and the pageview/event/duration ranges.
+ */
+
+/** The saved views of the Sessions page. `all` applies no condition. */
+export const SESSION_VIEWS = ["all", "identified", "replay", "converted", "bounced", "errors"] as const;
+export type SessionView = (typeof SESSION_VIEWS)[number];
+
+/**
+ * What a session's "events" figure counts: custom events plus the
+ * autocaptured interactions. The dashboard row has always shown this sum
+ * while `min_events` compared custom events alone, so a row showing 5 events
+ * could disappear under "at least 3". Filter and sort use the sum too.
+ * Outbound clicks and errors are reported on their own.
+ */
+export const SESSION_EVENT_TOTAL = "(events + button_clicks + copies + form_submits + input_changes)";
+
+// Sort keys the API accepts, mapped to the aggregated column they order by.
+// Only these strings ever reach the ORDER BY.
+const SESSION_SORT_COLUMNS = {
+ started: "session_start",
+ ended: "session_end",
+ duration: "session_duration",
+ pageviews: "pageviews",
+ events: SESSION_EVENT_TOTAL,
+ errors: "errors",
+} as const;
+export type SessionSort = keyof typeof SESSION_SORT_COLUMNS;
+
+const INT32_MAX = 2_147_483_647;
+
+// An empty value means "no bound", as the unset inputs have always sent it.
+const bound = z.preprocess(
+ value => (value === "" || value === null ? undefined : value),
+ z.coerce.number().int().min(0).max(INT32_MAX).optional()
+);
+
+export const sessionListParamsSchema = z.object({
+ view: z.enum(SESSION_VIEWS).optional(),
+ sort_by: z.enum(Object.keys(SESSION_SORT_COLUMNS) as [SessionSort, ...SessionSort[]]).optional(),
+ sort_order: z.enum(["asc", "desc"]).optional(),
+ // Report each session's completed goals. Opt-in: matching every goal against
+ // every event is work the callers that never show goals should not pay for.
+ include_goals: z.enum(["true", "false"]).optional(),
+ min_pageviews: bound,
+ max_pageviews: bound,
+ min_events: bound,
+ max_events: bound,
+ min_duration: bound,
+ max_duration: bound,
+});
+export type SessionListParams = z.infer<typeof sessionListParamsSchema>;
+
+/** The validated params, or the message for a 400. */
+export function parseSessionListParams(
+ query: unknown
+): { ok: true; params: SessionListParams } | { ok: false; error: string } {
+ const parsed = sessionListParamsSchema.safeParse(query);
+ if (parsed.success) return { ok: true, params: parsed.data };
+ const issue = parsed.error.issues[0];
+ return { ok: false, error: `Invalid ${issue?.path.join(".") || "query"}: ${issue?.message ?? "invalid value"}` };
+}
+
+/**
+ * One row per session over the request's window, with everything the list
+ * shows and every column a session filter can name. `converted_goal_ids` is
+ * every goal the session completed; `last_goal_ids` the goals completed by its
+ * most recent converting event.
+ */
+export function buildAggregatedSessionsCTE(
+ query: TimeWindowParams & { user_id?: string; session_id?: string },
+ matcher: SessionGoalMatcher
+): string {
+ const goalColumns = matcher.goals.length
+ ? `groupUniqArrayArray(${matcher.expression}) AS converted_goal_ids,
+ argMaxIf(${matcher.expression}, timestamp_ms, notEmpty(${matcher.expression})) AS last_goal_ids`
+ : `emptyArrayUInt32() AS converted_goal_ids,
+ emptyArrayUInt32() AS last_goal_ids`;
+
+ return `AggregatedSessions AS (
+ SELECT
+ session_id,
+ argMax(user_id, timestamp) AS user_id,
+ argMax(identified_user_id, timestamp) AS identified_user_id,
+ argMax(country, timestamp) AS country,
+ argMax(region, timestamp) AS region,
+ argMax(city, timestamp) AS city,
+ argMax(language, timestamp) AS language,
+ argMax(device_type, timestamp) AS device_type,
+ argMax(browser, timestamp) AS browser,
+ argMax(browser_version, timestamp) AS browser_version,
+ argMax(operating_system, timestamp) AS operating_system,
+ argMax(operating_system_version, timestamp) AS operating_system_version,
+ argMax(screen_width, timestamp) AS screen_width,
+ argMax(screen_height, timestamp) AS screen_height,
+ ${SESSION_REFERRER_AGG} AS referrer,
+ ${SESSION_CHANNEL_AGG} AS channel,
+ argMin(hostname, timestamp) AS hostname,
+ ${SESSION_UTM_SOURCE_AGG} AS utm_source,
+ ${SESSION_UTM_MEDIUM_AGG} AS utm_medium,
+ ${SESSION_UTM_CAMPAIGN_AGG} AS utm_campaign,
+ ${SESSION_UTM_TERM_AGG} AS utm_term,
+ ${SESSION_UTM_CONTENT_AGG} AS utm_content,
+ MAX(timestamp) AS session_end,
+ MIN(timestamp) AS session_start,
+ dateDiff('second', MIN(timestamp), MAX(timestamp)) AS session_duration,
+ argMinIf(pathname, timestamp_ms, type = 'pageview') AS entry_page,
+ argMaxIf(pathname, timestamp_ms, type = 'pageview') AS exit_page,
+ countIf(type = 'pageview') AS pageviews,
+ countIf(type = 'custom_event') AS events,
+ countIf(type = 'error') AS errors,
+ countIf(type = 'outbound') AS outbound,
+ countIf(type = 'button_click') AS button_clicks,
+ countIf(type = 'copy') AS copies,
+ countIf(type = 'form_submit') AS form_submits,
+ countIf(type = 'input_change') AS input_changes,
+ argMax(ip, timestamp) AS ip,
+ argMax(lat, timestamp) AS lat,
+ argMax(lon, timestamp) AS lon,
+ argMax(tag, timestamp) AS tag,
+ argMax(timezone, timestamp) AS timezone,
+ ${goalColumns}
+ FROM events
+ WHERE
+ site_id = {siteId:Int32}
+ ${query.user_id ? ` AND ${matchesUser("{user_id:String}", "events")}` : ""}
+ ${query.session_id ? ` AND events.session_id = {session_id:String}` : ""}
+ ${getTimeStatement(query)}
+ GROUP BY
+ session_id
+ )`;
+}
+
+/**
+ * Sessions that have a replay worth opening, as a subquery for `IN`.
+ *
+ * Bounded by the request's window on the replay's own start time, which is
+ * also how the Replay page decides what belongs to a period. The table is
+ * keyed by (site, session) and partitioned by month of start time; without
+ * the bound every list request read all of the site's replay metadata.
+ */
+export const buildReplaySessionsSubquery = (query: TimeWindowParams) => `
+ SELECT session_id
+ FROM session_replay_metadata_v2
+ FINAL
+ WHERE site_id = {siteId:Int32}
+ AND event_count >= 2
+ ${getTimeStatement(query, "start_time")}`;
+
+/** Which of these session ids have a replay: a key lookup, no window needed. */
+export const REPLAY_LOOKUP_QUERY = `
+ SELECT session_id
+ FROM session_replay_metadata_v2
+ FINAL
+ WHERE site_id = {siteId:Int32}
+ AND session_id IN ({sessionIds:Array(String)})
+ AND event_count >= 2`;
+
+/** The condition a view adds over the aggregated sessions, or null for `all`. */
+export function buildViewCondition(view: SessionView | undefined, query: TimeWindowParams): string | null {
+ switch (view) {
+ case "identified":
+ return "identified_user_id != ''";
+ case "replay":
+ return `session_id IN (${buildReplaySessionsSubquery(query)})`;
+ case "converted":
+ return "notEmpty(converted_goal_ids)";
+ case "bounced":
+ // The dashboard's definition of a bounce (see siteMetrics): exactly one pageview.
+ return "pageviews = 1";
+ case "errors":
+ return "errors > 0";
+ default:
+ return null;
+ }
+}
+
+/** Min/max conditions over the aggregated sessions, with their bound values. */
+export function buildRangeConditions(params: SessionListParams): {
+ conditions: string[];
+ queryParams: Record<string, number>;
+} {
+ const ranges: [name: string, column: string, value: number | undefined, operator: ">=" | "<="][] = [
+ ["minPageviews", "pageviews", params.min_pageviews, ">="],
+ ["maxPageviews", "pageviews", params.max_pageviews, "<="],
+ ["minEvents", SESSION_EVENT_TOTAL, params.min_events, ">="],
+ ["maxEvents", SESSION_EVENT_TOTAL, params.max_events, "<="],
+ ["minDuration", "session_duration", params.min_duration, ">="],
+ ["maxDuration", "session_duration", params.max_duration, "<="],
+ ];
+
+ const conditions: string[] = [];
+ const queryParams: Record<string, number> = {};
+ for (const [name, column, value, operator] of ranges) {
+ if (value === undefined) continue;
+ conditions.push(`${column} ${operator} {${name}:Int32}`);
+ queryParams[name] = value;
+ }
+ return { conditions, queryParams };
+}
+
+/**
+ * The outer ORDER BY. Rows that tie on the sort column fall back to the
+ * session start and then the id, so two pages of one request never share or
+ * skip a row.
+ */
+export function buildSessionOrder(sortBy: SessionSort = "ended", sortOrder: "asc" | "desc" = "desc"): string {
+ const direction = sortOrder === "asc" ? "ASC" : "DESC";
+ const column = SESSION_SORT_COLUMNS[sortBy];
+ const tieBreak = sortBy === "started" ? "" : `, session_start ${direction}`;
+ return `ORDER BY ${column} ${direction}${tieBreak}, session_id ${direction}`;
+}
diff --git a/server/src/api/analytics/types.ts b/server/src/api/analytics/types.ts
index 13e62033c..827ebaa5d 100644
--- a/server/src/api/analytics/types.ts
+++ b/server/src/api/analytics/types.ts
@@ -4,11 +4,16 @@ import type { Filter, FilterType, FilterParameter, TimeBucket, WebVitalMetric, P
// Re-export for other modules
export { Filter, FilterType, FilterParameter, TimeBucket, WebVitalMetric, PercentileLevel };
+/** Loads that reported each metric, and how many of those were good and poor. */
+export type WebVitalRatingCounts = {
+ [K in WebVitalMetric as `${K}_${"count" | "good" | "poor"}`]: number;
+};
+
export type PerformanceOverviewMetrics = {
[K in WebVitalMetric as `${K}_${PercentileLevel}`]: number | null;
-} & {
- total_performance_events: number;
-};
+} & WebVitalRatingCounts & {
+ total_performance_events: number;
+ };
export type PerformanceTimeSeriesPoint = {
time: string;
diff --git a/server/src/api/analytics/users/getUserGoals.test.ts b/server/src/api/analytics/users/getUserGoals.test.ts
new file mode 100644
index 000000000..93fc4a0cc
--- /dev/null
+++ b/server/src/api/analytics/users/getUserGoals.test.ts
@@ -0,0 +1,161 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ goals: [] as Record<string, unknown>[],
+ rows: [] as Record<string, unknown>[],
+ queries: [] as { query: string; params: Record<string, unknown> }[],
+}));
+
+vi.mock("../../../db/postgres/postgres.js", () => ({
+ db: {
+ select: () => ({
+ from: () => ({
+ where: () => ({
+ orderBy: () => ({
+ limit: async () => state.goals,
+ }),
+ }),
+ }),
+ }),
+ },
+}));
+
+vi.mock("../../../db/postgres/schema.js", () => ({
+ goals: { siteId: "site_id", goalId: "goal_id" },
+}));
+
+vi.mock("drizzle-orm", () => ({
+ asc: (column: unknown) => column,
+ eq: (_column: unknown, value: unknown) => value,
+}));
+
+vi.mock("../utils/analyticsQuery.js", async () => {
+ const actual = await vi.importActual<typeof import("../utils/analyticsQuery.js")>("../utils/analyticsQuery.js");
+ return {
+ ...actual,
+ runAnalyticsQuery: vi.fn(async (spec: { query: string; params: Record<string, unknown> }) => {
+ state.queries.push(spec);
+ return state.rows;
+ }),
+ };
+});
+
+vi.mock("../../../db/clickhouse/clickhouse.js", () => ({ clickhouse: { query: vi.fn() } }));
+
+import { getUserGoals, getUserSessionGoals } from "./getUserGoals.js";
+
+const pricing = { goalId: 3, name: "Viewed pricing", goalType: "path", config: { pathPattern: "/pricing" } };
+const signup = { goalId: 7, name: "Signup", goalType: "event", config: { eventName: "signup" } };
+const unusable = { goalId: 9, name: null, goalType: "event", config: {} };
+
+const call = async (
+ handler: typeof getUserGoals | typeof getUserSessionGoals,
+ query: Record<string, unknown> = {},
+ extra = {}
+) => {
+ const reply = {
+ statusCode: 200,
+ payload: undefined as any,
+ status(code: number) {
+ this.statusCode = code;
+ return this;
+ },
+ send(payload: unknown) {
+ this.payload = payload;
+ return this;
+ },
+ };
+ const request = {
+ params: { siteId: "1", userId: "alice" },
+ query: { start_date: "2026-09-01", end_date: "2026-09-30", time_zone: "UTC", ...query },
+ log: { error: vi.fn(), debug: vi.fn() },
+ ...extra,
+ };
+ await handler(request as never, reply as never);
+ return reply;
+};
+
+describe("getUserGoals", () => {
+ beforeEach(() => {
+ state.goals = [pricing, signup, unusable];
+ state.rows = [];
+ state.queries = [];
+ });
+
+ it("returns every site goal, with this user's sessions and latest completion in the window", async () => {
+ state.rows = [
+ {
+ goal_3_sessions: 4,
+ goal_3_last: "2026-09-28 10:02:11",
+ goal_7_sessions: 0,
+ // maxIf over no rows is the epoch.
+ goal_7_last: "1970-01-01 00:00:00",
+ },
+ ];
+
+ const reply = await call(getUserGoals);
+
+ expect(reply.payload.data).toEqual([
+ { goalId: 3, name: "Viewed pricing", goalType: "path", sessions: 4, last_completed: "2026-09-28 10:02:11" },
+ { goalId: 7, name: "Signup", goalType: "event", sessions: 0, last_completed: null },
+ { goalId: 9, name: null, goalType: "event", sessions: 0, last_completed: null },
+ ]);
+ expect(state.queries[0].params).toEqual({ userId: "alice", site: 1 });
+ });
+
+ it("answers without querying when the site has no goals", async () => {
+ state.goals = [];
+
+ const reply = await call(getUserGoals);
+
+ expect(reply.payload.data).toEqual([]);
+ expect(state.queries).toHaveLength(0);
+ });
+
+ it("refuses a bearer credential that cannot read goals", async () => {
+ const reply = await call(getUserGoals, {}, { bearerAuth: true, bearerStatements: { users: ["read"] } });
+
+ expect(reply.statusCode).toBe(403);
+ expect(state.queries).toHaveLength(0);
+ });
+});
+
+describe("getUserSessionGoals", () => {
+ beforeEach(() => {
+ state.goals = [pricing, signup];
+ state.rows = [];
+ state.queries = [];
+ });
+
+ it("maps each listed session to the goals it completed and leaves out the ones that completed none", async () => {
+ state.rows = [
+ { session_id: "s1", goal_3: 2, goal_7: 1 },
+ { session_id: "s2", goal_3: 0, goal_7: 0 },
+ { session_id: "s3", goal_3: 0, goal_7: 1 },
+ ];
+
+ const reply = await call(getUserSessionGoals, { session_ids: JSON.stringify(["s1", "s2", "s3"]) });
+
+ expect(reply.payload.data).toEqual([
+ { session_id: "s1", goal_ids: [3, 7] },
+ { session_id: "s3", goal_ids: [7] },
+ ]);
+ expect(state.queries[0].params).toEqual({ userId: "alice", site: 1, sessionIds: ["s1", "s2", "s3"] });
+ });
+
+ it("rejects a missing or malformed session list", async () => {
+ expect((await call(getUserSessionGoals)).statusCode).toBe(400);
+ expect((await call(getUserSessionGoals, { session_ids: "s1" })).statusCode).toBe(400);
+ expect(state.queries).toHaveLength(0);
+ });
+
+ it("refuses a bearer credential that cannot read goals", async () => {
+ const reply = await call(
+ getUserSessionGoals,
+ { session_ids: JSON.stringify(["s1"]) },
+ { bearerAuth: true, bearerStatements: { users: ["read"] } }
+ );
+
+ expect(reply.statusCode).toBe(403);
+ });
+});
diff --git a/server/src/api/analytics/users/getUserGoals.ts b/server/src/api/analytics/users/getUserGoals.ts
new file mode 100644
index 000000000..7799ef54e
--- /dev/null
+++ b/server/src/api/analytics/users/getUserGoals.ts
@@ -0,0 +1,214 @@
+import { FilterParams } from "@rybbit/shared";
+import { asc, eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import { db } from "../../../db/postgres/postgres.js";
+import { goals } from "../../../db/postgres/schema.js";
+import { hasScope, scopeToString } from "../../../lib/scopes.js";
+import { buildGoalCondition } from "../goals/goalConditions.js";
+import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { buildUserEventScope } from "./userEventScope.js";
+
+type GoalRow = typeof goals.$inferSelect;
+
+const GOALS_READ = { resource: "goals", action: "read" } as const;
+
+// These routes are guarded by users:read. A scoped bearer credential must also
+// hold goals:read, or it could read goal names it cannot list directly.
+const lacksGoalsScope = (req: FastifyRequest) =>
+ !!req.bearerAuth && !hasScope(req.bearerStatements ?? null, GOALS_READ);
+const insufficientScope = (res: FastifyReply) =>
+ res.status(403).send({ error: "Insufficient scope", required: scopeToString(GOALS_READ) });
+
+/** A goal the site defines, with the SQL predicate an event must meet to complete it. */
+export interface GoalCondition {
+ goalId: number;
+ condition: string;
+}
+
+// One pair of aggregates per goal goes into a single statement, so the number
+// of goals a profile evaluates is capped. The goals page allows 100 per page.
+export const MAX_USER_GOALS = 100;
+
+// The profile lists 25 sessions a page; the cap leaves room without letting a
+// caller hand over an unbounded IN list.
+export const MAX_SESSION_IDS = 50;
+
+export interface UserGoal {
+ goalId: number;
+ name: string | null;
+ goalType: string;
+ /** Sessions in the window in which this user completed the goal. */
+ sessions: number;
+ /** The latest completion in the window, UTC. Null when there is none. */
+ last_completed: string | null;
+}
+
+export interface UserSessionGoals {
+ session_id: string;
+ goal_ids: number[];
+}
+
+export interface GetUserGoalsRequest {
+ Params: {
+ siteId: string;
+ userId: string;
+ };
+ Querystring: FilterParams;
+}
+
+export interface GetUserSessionGoalsRequest {
+ Params: {
+ siteId: string;
+ userId: string;
+ };
+ Querystring: FilterParams<{ session_ids?: string }>;
+}
+
+const loadSiteGoals = (siteId: number): Promise<GoalRow[]> =>
+ db.select().from(goals).where(eq(goals.siteId, siteId)).orderBy(asc(goals.goalId)).limit(MAX_USER_GOALS);
+
+// Goals whose configuration yields no predicate (an event goal with no event
+// name, say) cannot be completed and are left out of the SQL.
+export const toGoalConditions = (siteGoals: Pick<GoalRow, "goalId" | "goalType" | "config">[]): GoalCondition[] =>
+ siteGoals.flatMap(goal => {
+ const condition = buildGoalCondition(goal);
+ return condition ? [{ goalId: goal.goalId, condition }] : [];
+ });
+
+/**
+ * Per goal: the sessions in which this user completed it, and when they last
+ * did, inside the selected window. Conditional aggregation over one scan of the
+ * user's events, the same shape the goals page uses for the whole site.
+ */
+export const buildUserGoalsQuery = (
+ query: GetUserGoalsRequest["Querystring"],
+ siteId: number,
+ conditions: GoalCondition[]
+): string | null => {
+ if (conditions.length === 0) return null;
+
+ const { withFilteredSessions, scopedEvents } = buildUserEventScope(query, siteId);
+
+ const aggregates = conditions.map(
+ ({ goalId, condition }) => `
+ COUNT(DISTINCT IF(${condition}, session_id, NULL)) AS goal_${goalId}_sessions,
+ maxIf(timestamp, ${condition}) AS goal_${goalId}_last`
+ );
+
+ return `
+ ${withFilteredSessions}
+ SELECT ${aggregates.join(",")}
+ FROM ${scopedEvents}
+ `;
+};
+
+/**
+ * Which goals each of the given sessions completed. Bounded three ways: the
+ * selected window, the user, and the explicit list of session ids (one page of
+ * the profile's session list).
+ */
+export const buildUserSessionGoalsQuery = (
+ query: GetUserSessionGoalsRequest["Querystring"],
+ siteId: number,
+ conditions: GoalCondition[]
+): string | null => {
+ if (conditions.length === 0) return null;
+
+ const { withFilteredSessions, scopedEvents } = buildUserEventScope(query, siteId);
+
+ const aggregates = conditions.map(
+ ({ goalId, condition }) => `
+ countIf(${condition}) AS goal_${goalId}`
+ );
+
+ return `
+ ${withFilteredSessions}
+ SELECT
+ session_id,${aggregates.join(",")}
+ FROM ${scopedEvents}
+ WHERE session_id IN ({sessionIds:Array(String)})
+ GROUP BY session_id
+ `;
+};
+
+const sessionIdsSchema = z.array(z.string().min(1).max(128)).min(1).max(MAX_SESSION_IDS);
+
+/** The `session_ids` query param: a JSON array of 1 to 50 session ids. Null when it is anything else. */
+export const parseSessionIds = (raw: unknown): string[] | null => {
+ if (typeof raw !== "string") return null;
+ try {
+ const parsed = sessionIdsSchema.safeParse(JSON.parse(raw));
+ return parsed.success ? [...new Set(parsed.data)] : null;
+ } catch {
+ return null;
+ }
+};
+
+// maxIf over no matching rows is the epoch, not NULL.
+const completedAt = (value: unknown): string | null =>
+ typeof value === "string" && !value.startsWith("1970-01-01") ? value : null;
+
+export const getUserGoals = analyticsRoute<GetUserGoalsRequest>(
+ "user goals",
+ async (req: FastifyRequest<GetUserGoalsRequest>, res: FastifyReply) => {
+ if (lacksGoalsScope(req as FastifyRequest)) return insufficientScope(res);
+
+ const siteId = Number(req.params.siteId);
+ const siteGoals = await loadSiteGoals(siteId);
+
+ const goalsQuery = buildUserGoalsQuery(req.query, siteId, toGoalConditions(siteGoals));
+ const rows = goalsQuery
+ ? await runAnalyticsQuery<Record<string, unknown>>({
+ query: goalsQuery,
+ params: { userId: req.params.userId, site: siteId },
+ })
+ : [];
+ const row = rows[0] ?? {};
+
+ const data: UserGoal[] = siteGoals.map(goal => {
+ const sessions = Number(row[`goal_${goal.goalId}_sessions`] ?? 0);
+ return {
+ goalId: goal.goalId,
+ name: goal.name,
+ goalType: goal.goalType,
+ sessions,
+ last_completed: sessions > 0 ? completedAt(row[`goal_${goal.goalId}_last`]) : null,
+ };
+ });
+
+ return res.send({ data });
+ }
+);
+
+export const getUserSessionGoals = analyticsRoute<GetUserSessionGoalsRequest>(
+ "user session goals",
+ async (req: FastifyRequest<GetUserSessionGoalsRequest>, res: FastifyReply) => {
+ if (lacksGoalsScope(req as FastifyRequest)) return insufficientScope(res);
+
+ const siteId = Number(req.params.siteId);
+
+ const sessionIds = parseSessionIds(req.query.session_ids);
+ if (!sessionIds) {
+ return res.status(400).send({ error: `session_ids must be a JSON array of 1 to ${MAX_SESSION_IDS} session ids` });
+ }
+
+ const conditions = toGoalConditions(await loadSiteGoals(siteId));
+ const sessionGoalsQuery = buildUserSessionGoalsQuery(req.query, siteId, conditions);
+ if (!sessionGoalsQuery) {
+ return res.send({ data: [] });
+ }
+
+ const rows = await runAnalyticsQuery<Record<string, unknown> & { session_id: string }>({
+ query: sessionGoalsQuery,
+ params: { userId: req.params.userId, site: siteId, sessionIds },
+ });
+
+ const data: UserSessionGoals[] = rows.flatMap(row => {
+ const goalIds = conditions.filter(({ goalId }) => Number(row[`goal_${goalId}`] ?? 0) > 0).map(c => c.goalId);
+ return goalIds.length > 0 ? [{ session_id: row.session_id, goal_ids: goalIds }] : [];
+ });
+
+ return res.send({ data });
+ }
+);
diff --git a/server/src/api/analytics/users/getUserInfo.ts b/server/src/api/analytics/users/getUserInfo.ts
index d5853065b..6f029e281 100644
--- a/server/src/api/analytics/users/getUserInfo.ts
+++ b/server/src/api/analytics/users/getUserInfo.ts
@@ -4,10 +4,8 @@ import { eq, and } from "drizzle-orm";
import { db } from "../../../db/postgres/postgres.js";
import { userProfiles, userAliases } from "../../../db/postgres/schema.js";
import { SESSION_CHANNEL_AGG, SESSION_REFERRER_AGG } from "../utils/sessionAttribution.js";
-import { buildFilteredSessionsCTE } from "../utils/sessionFilters.js";
-import { getTimeStatement } from "../utils/timeWindow.js";
-import { matchesUser } from "../utils/effectiveUserId.js";
import { runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { buildUserEventScope } from "./userEventScope.js";
interface UserPageviewData {
sessions: number;
@@ -86,25 +84,7 @@ export interface UserInfoResponse {
}
export const buildUserInfoQueries = (query: FilterParams, siteId: number) => {
- // Optional time range + dimension filters; both empty when the page is on
- // all-time with no filters, which keeps the original full-history behavior.
- const timeStatement = getTimeStatement(query);
- const filteredSessionsCTE = buildFilteredSessionsCTE(query.filters, siteId, timeStatement);
- const filteredSessionsJoin = filteredSessionsCTE ? "INNER JOIN FilteredSessions USING (session_id)" : "";
- const withFilteredSessions = filteredSessionsCTE ? `WITH ${filteredSessionsCTE}` : "";
-
- // Filters select sessions first. Every panel then reads all events in those
- // sessions, keeping the summary, vitals, locations, devices, and session list
- // on the same session-scoped semantics.
- const scopedEvents = `(
- SELECT source_events.*
- FROM events AS source_events
- ${filteredSessionsJoin}
- WHERE
- ${matchesUser("{userId:String}", "source_events")}
- AND source_events.site_id = {site:Int32}
- ${timeStatement}
- ) AS events`;
+ const { filteredSessionsCTE, withFilteredSessions, scopedEvents } = buildUserEventScope(query, siteId);
const sessionsQuery = `
WITH ${filteredSessionsCTE ? `${filteredSessionsCTE},` : ""}
diff --git a/server/src/api/analytics/users/getUserRepeatedError.ts b/server/src/api/analytics/users/getUserRepeatedError.ts
new file mode 100644
index 000000000..1d3512bea
--- /dev/null
+++ b/server/src/api/analytics/users/getUserRepeatedError.ts
@@ -0,0 +1,112 @@
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { buildUserEventScope } from "./userEventScope.js";
+
+export interface GetUserRepeatedErrorRequest {
+ Params: {
+ siteId: string;
+ userId: string;
+ };
+ Querystring: FilterParams;
+}
+
+export interface UserRepeatedError {
+ message: string;
+ session_id: string;
+ /** Times the same message was thrown in that one session. Always 2 or more. */
+ occurrences: number;
+ /** Page the first of them was thrown on. */
+ pathname: string;
+ first_seen: string;
+ last_seen: string;
+ has_replay: boolean;
+}
+
+interface RepeatedErrorRow {
+ error_message: string | number;
+ session_id: string;
+ occurrences: number;
+ pathname: string | number | null;
+ first_seen: string;
+ last_seen: string;
+}
+
+/**
+ * The profile's one insight: the most recent session in the window in which
+ * this user hit the same error message more than once. A rule, not a
+ * judgement: one message, one session, a count of at least two.
+ */
+export const buildUserRepeatedErrorQuery = (query: GetUserRepeatedErrorRequest["Querystring"], siteId: number) => {
+ const { withFilteredSessions, scopedEvents } = buildUserEventScope(query, siteId);
+
+ return `
+ ${withFilteredSessions}
+ SELECT
+ JSONExtractString(toString(props), 'message') AS error_message,
+ session_id,
+ count() AS occurrences,
+ argMin(pathname, timestamp) AS pathname,
+ MIN(timestamp) AS first_seen,
+ MAX(timestamp) AS last_seen
+ FROM ${scopedEvents}
+ WHERE
+ type = 'error'
+ AND JSONExtractString(toString(props), 'message') <> ''
+ GROUP BY
+ error_message,
+ session_id
+ HAVING
+ occurrences >= 2
+ ORDER BY
+ last_seen DESC
+ LIMIT 1
+ `;
+};
+
+// Same definition of "has a replay" as the session list: a recording with at
+// least two events. The table is keyed by (site_id, session_id).
+export const SESSION_HAS_REPLAY_QUERY = `
+ SELECT count() AS replays
+ FROM session_replay_metadata_v2
+ FINAL
+ WHERE site_id = {site:Int32}
+ AND session_id = {sessionId:String}
+ AND event_count >= 2
+ `;
+
+export const getUserRepeatedError = analyticsRoute<GetUserRepeatedErrorRequest>(
+ "user repeated error",
+ async (req: FastifyRequest<GetUserRepeatedErrorRequest>, res: FastifyReply) => {
+ const { siteId, userId } = req.params;
+ const site = Number(siteId);
+
+ const rows = await runAnalyticsQuery<RepeatedErrorRow>({
+ query: buildUserRepeatedErrorQuery(req.query, site),
+ params: { userId, site },
+ });
+
+ const repeated = rows[0];
+ if (!repeated) {
+ return res.send({ data: null });
+ }
+
+ const replayRows = await runAnalyticsQuery<{ replays: number }>({
+ query: SESSION_HAS_REPLAY_QUERY,
+ params: { site, sessionId: repeated.session_id },
+ });
+
+ const data: UserRepeatedError = {
+ // processResults turns a numeric-looking message ("404") into a number.
+ message: String(repeated.error_message),
+ session_id: repeated.session_id,
+ occurrences: Number(repeated.occurrences),
+ pathname: String(repeated.pathname ?? ""),
+ first_seen: repeated.first_seen,
+ last_seen: repeated.last_seen,
+ has_replay: Number(replayRows[0]?.replays ?? 0) > 0,
+ };
+
+ return res.send({ data });
+ }
+);
diff --git a/server/src/api/analytics/users/getUserSegments.test.ts b/server/src/api/analytics/users/getUserSegments.test.ts
new file mode 100644
index 000000000..fbf30df76
--- /dev/null
+++ b/server/src/api/analytics/users/getUserSegments.test.ts
@@ -0,0 +1,148 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ actor: { userId: null as string | null, hasSiteAccess: false, canManage: false, canManageSite: false },
+ organizationId: "org_1" as string | null,
+ segments: [] as Record<string, unknown>[],
+ counts: {} as Record<string, number>,
+ queries: [] as { query: string; params: Record<string, unknown> }[],
+}));
+
+vi.mock("../segments/segmentAccess.js", async () => {
+ const actual = await vi.importActual<typeof import("../segments/segmentAccess.js")>("../segments/segmentAccess.js");
+ return {
+ ...actual,
+ getSiteOrganizationId: async () => state.organizationId,
+ resolveSegmentActor: async () => state.actor,
+ };
+});
+
+vi.mock("../../../db/postgres/postgres.js", () => ({
+ db: { query: { segments: { findMany: async () => state.segments } } },
+}));
+vi.mock("../../../lib/auth.js", () => ({ auth: { api: {} } }));
+
+vi.mock("../utils/analyticsQuery.js", async () => {
+ const actual = await vi.importActual<typeof import("../utils/analyticsQuery.js")>("../utils/analyticsQuery.js");
+ return {
+ ...actual,
+ runAnalyticsQuery: vi.fn(async (spec: { query: string; params: Record<string, unknown> }) => {
+ state.queries.push(spec);
+ return [state.counts];
+ }),
+ };
+});
+
+import { getUserSegments, MAX_USER_SEGMENTS } from "./getUserSegments.js";
+
+const country = (code: string) => ({ parameter: "country", type: "equals", value: [code] });
+
+const segment = (segmentId: number, name: string, isPublic: boolean, filters: unknown[] = [country("SE")]) => ({
+ segmentId,
+ name,
+ isPublic,
+ filters,
+ siteId: 1,
+ organizationId: "org_1",
+ userId: "owner",
+});
+
+const call = async (extra: Record<string, unknown> = {}) => {
+ const reply = {
+ statusCode: 200,
+ payload: undefined as any,
+ status(code: number) {
+ this.statusCode = code;
+ return this;
+ },
+ send(payload: unknown) {
+ this.payload = payload;
+ return this;
+ },
+ };
+ const request = {
+ params: { siteId: "1", userId: "alice" },
+ query: { start_date: "2026-09-01", end_date: "2026-09-30", time_zone: "UTC" },
+ log: { error: vi.fn(), debug: vi.fn() },
+ ...extra,
+ };
+ await getUserSegments(request as never, reply as never);
+ return reply;
+};
+
+describe("getUserSegments", () => {
+ beforeEach(() => {
+ state.actor = { userId: "u1", hasSiteAccess: true, canManage: false, canManageSite: false };
+ state.organizationId = "org_1";
+ state.segments = [];
+ state.counts = {};
+ state.queries = [];
+ });
+
+ it("lists the segments this user's sessions match, largest first, out of the user's total", async () => {
+ state.segments = [segment(1, "Docs readers", false), segment(2, "Organic", true), segment(3, "Unmatched", false)];
+ state.counts = { segment_1: 3, segment_2: 34, segment_3: 0, total_sessions: 42 };
+
+ const reply = await call();
+
+ expect(reply.payload.data).toEqual({
+ segments: [
+ { segmentId: 2, name: "Organic", filters: [country("SE")], sessions: 34 },
+ { segmentId: 1, name: "Docs readers", filters: [country("SE")], sessions: 3 },
+ ],
+ total_sessions: 42,
+ truncated: false,
+ });
+ expect(state.queries).toHaveLength(1);
+ expect(state.queries[0].params).toEqual({ userId: "alice", site: 1 });
+ });
+
+ it("evaluates only public segments for a public or private-link viewer", async () => {
+ state.actor = { userId: null, hasSiteAccess: false, canManage: false, canManageSite: false };
+ state.segments = [segment(1, "Private", false), segment(2, "Public", true)];
+ state.counts = { segment_1: 9, segment_2: 4, total_sessions: 10 };
+
+ const reply = await call();
+
+ expect(state.queries[0].query).toContain("Segment_2 AS (");
+ expect(state.queries[0].query).not.toContain("Segment_1");
+ expect(reply.payload.data.segments).toEqual([
+ { segmentId: 2, name: "Public", filters: [country("SE")], sessions: 4 },
+ ]);
+ });
+
+ it("refuses a bearer credential that cannot read segments", async () => {
+ state.segments = [segment(1, "Docs readers", false)];
+
+ const reply = await call({ bearerAuth: true, bearerStatements: { users: ["read"] } });
+
+ expect(reply.statusCode).toBe(403);
+ expect(state.queries).toHaveLength(0);
+ });
+
+ it("runs nothing when the site has no segments with filters", async () => {
+ state.segments = [segment(1, "Empty", false, [])];
+
+ const reply = await call();
+
+ expect(reply.payload.data).toEqual({ segments: [], total_sessions: 0, truncated: false });
+ expect(state.queries).toHaveLength(0);
+ });
+
+ it("caps how many segments one request evaluates and says so", async () => {
+ state.segments = Array.from({ length: MAX_USER_SEGMENTS + 3 }, (_, i) => segment(i + 1, `Segment ${i + 1}`, false));
+
+ const reply = await call();
+
+ expect(state.queries[0].query.match(/Segment_\d+ AS \(/g)).toHaveLength(MAX_USER_SEGMENTS);
+ expect(reply.payload.data.truncated).toBe(true);
+ });
+
+ it("404s an unknown site", async () => {
+ state.organizationId = null;
+
+ const reply = await call();
+
+ expect(reply.statusCode).toBe(404);
+ });
+});
diff --git a/server/src/api/analytics/users/getUserSegments.ts b/server/src/api/analytics/users/getUserSegments.ts
new file mode 100644
index 000000000..a650fed8a
--- /dev/null
+++ b/server/src/api/analytics/users/getUserSegments.ts
@@ -0,0 +1,194 @@
+import type { Filter, FilterParams } from "@rybbit/shared";
+import { asc } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { db } from "../../../db/postgres/postgres.js";
+import { segments } from "../../../db/postgres/schema.js";
+import { hasScope, scopeToString } from "../../../lib/scopes.js";
+import { mergeSegmentFilters } from "../segments/expandSegmentParam.js";
+import {
+ canReadSegment,
+ getSiteOrganizationId,
+ resolveSegmentActor,
+ segmentsForSiteCondition,
+} from "../segments/segmentAccess.js";
+import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { matchesUser } from "../utils/effectiveUserId.js";
+import { validateFilters } from "../utils/query-validation.js";
+import { buildFilteredSessionsCTE } from "../utils/sessionFilters.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
+
+const SEGMENTS_READ = { resource: "segments", action: "read" } as const;
+
+// Each segment is one more pass over the user's events in the window, so the
+// number evaluated per request is capped. Segments are taken in name order.
+export const MAX_USER_SEGMENTS = 20;
+
+export interface SegmentFilters {
+ segmentId: number;
+ filters: Filter[];
+}
+
+export interface UserSegmentMatch {
+ segmentId: number;
+ name: string;
+ /** The segment's own filters, as the segment list returns them, for linking to its sessions. */
+ filters: Filter[];
+ /** Sessions of this user, in the window, that the segment's filters select. */
+ sessions: number;
+}
+
+export interface UserSegmentsResponse {
+ segments: UserSegmentMatch[];
+ /** This user's sessions in the window: what each segment's count is out of. */
+ total_sessions: number;
+ /** True when the site has more segments than one request evaluates. */
+ truncated: boolean;
+}
+
+export interface GetUserSegmentsRequest {
+ Params: {
+ siteId: string;
+ userId: string;
+ };
+ Querystring: FilterParams;
+}
+
+/**
+ * How many of one user's sessions each saved segment selects.
+ *
+ * A segment is a saved filter set, so each one is counted with the same
+ * session-filter CTE every filtered report uses. The scan underneath is
+ * narrowed to this user by passing the user predicate along with the time
+ * window: the builders apply that fragment to the CTE's own scan and to every
+ * session-level subquery they emit, so no part of the statement reads another
+ * visitor's events. The page's own filters are ANDed into each segment, which
+ * keeps every count a subset of `total_sessions`.
+ *
+ * Returns null when no segment has usable filters. Binds `{userId:String}` and
+ * `{site:Int32}`.
+ */
+export const buildUserSegmentsQuery = (
+ query: GetUserSegmentsRequest["Querystring"],
+ siteId: number,
+ segmentFilters: SegmentFilters[]
+): { query: string; segmentIds: number[] } | null => {
+ // Kept in the time statement's own shape (a fragment that opens with "AND"),
+ // because the filter builders strip exactly that prefix for their subqueries.
+ const timeStatement = getTimeStatement(query).trim();
+ const userStatement = `AND ${matchesUser("{userId:String}")}`;
+ const userWindow = timeStatement ? `${timeStatement} ${userStatement}` : userStatement;
+ const pageFilters = query.filters ? validateFilters(query.filters) : [];
+
+ const ctes: string[] = [];
+ const segmentIds: number[] = [];
+ for (const { segmentId, filters } of segmentFilters) {
+ let cte: string | null = null;
+ try {
+ cte = buildFilteredSessionsCTE(
+ JSON.stringify(mergeSegmentFilters(filters, pageFilters)),
+ siteId,
+ userWindow,
+ `Segment_${segmentId}`
+ );
+ } catch {
+ // A stored filter the builders reject (a regex saved before validation
+ // tightened, say) drops that segment rather than the whole list.
+ cte = null;
+ }
+ if (!cte) continue;
+ ctes.push(cte);
+ segmentIds.push(segmentId);
+ }
+
+ if (ctes.length === 0) return null;
+
+ const pageSessionsCTE = pageFilters.length
+ ? buildFilteredSessionsCTE(JSON.stringify(pageFilters), siteId, userWindow, "PageSessions")
+ : null;
+ if (pageSessionsCTE) ctes.push(pageSessionsCTE);
+
+ const totalSessions = pageSessionsCTE
+ ? "(SELECT count() FROM PageSessions)"
+ : `(
+ SELECT count(DISTINCT session_id)
+ FROM events
+ WHERE site_id = {site:Int32}
+ ${userWindow}
+ )`;
+
+ return {
+ segmentIds,
+ query: `
+ WITH ${ctes.join(",\n ")}
+ SELECT
+ ${segmentIds.map(id => `(SELECT count() FROM Segment_${id}) AS segment_${id}`).join(",\n ")},
+ ${totalSessions} AS total_sessions
+ `,
+ };
+};
+
+export const getUserSegments = analyticsRoute<GetUserSegmentsRequest>(
+ "user segments",
+ async (req: FastifyRequest<GetUserSegmentsRequest>, res: FastifyReply) => {
+ const siteId = Number(req.params.siteId);
+
+ // The route guard checked users:read. A scoped bearer credential must also
+ // hold segments:read, or this would name segments it cannot list directly.
+ if (req.bearerAuth && !hasScope(req.bearerStatements ?? null, SEGMENTS_READ)) {
+ return res.status(403).send({ error: "Insufficient scope", required: scopeToString(SEGMENTS_READ) });
+ }
+
+ const organizationId = await getSiteOrganizationId(siteId);
+ if (!organizationId) {
+ return res.status(404).send({ error: "Site not found" });
+ }
+
+ const [actor, rows] = await Promise.all([
+ resolveSegmentActor(req, siteId, organizationId),
+ db.query.segments.findMany({
+ where: segmentsForSiteCondition(siteId, organizationId),
+ orderBy: [asc(segments.name)],
+ }),
+ ]);
+
+ // Same visibility as the segment list: public and private-link viewers
+ // only ever see public segments.
+ const readable = rows.filter(row => canReadSegment(row, actor) && row.filters.length > 0);
+ const evaluated = readable.slice(0, MAX_USER_SEGMENTS);
+ const empty: UserSegmentsResponse = { segments: [], total_sessions: 0, truncated: false };
+
+ const built = buildUserSegmentsQuery(
+ req.query,
+ siteId,
+ evaluated.map(row => ({ segmentId: row.segmentId, filters: row.filters }))
+ );
+ if (!built) {
+ return res.send({ data: empty });
+ }
+
+ const result = await runAnalyticsQuery<Record<string, number>>({
+ query: built.query,
+ params: { userId: req.params.userId, site: siteId },
+ });
+ const counts = result[0] ?? {};
+
+ const matches: UserSegmentMatch[] = evaluated
+ .filter(row => built.segmentIds.includes(row.segmentId))
+ .map(row => ({
+ segmentId: row.segmentId,
+ name: row.name,
+ filters: row.filters,
+ sessions: Number(counts[`segment_${row.segmentId}`] ?? 0),
+ }))
+ .filter(match => match.sessions > 0)
+ .sort((a, b) => b.sessions - a.sessions || a.name.localeCompare(b.name));
+
+ const data: UserSegmentsResponse = {
+ segments: matches,
+ total_sessions: Number(counts.total_sessions ?? 0),
+ truncated: readable.length > evaluated.length,
+ };
+
+ return res.send({ data });
+ }
+);
diff --git a/server/src/api/analytics/users/getUserSummary.ts b/server/src/api/analytics/users/getUserSummary.ts
new file mode 100644
index 000000000..06bfe541f
--- /dev/null
+++ b/server/src/api/analytics/users/getUserSummary.ts
@@ -0,0 +1,73 @@
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import SqlString from "sqlstring";
+import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { buildUserEventScope } from "./userEventScope.js";
+
+export interface GetUserSummaryRequest {
+ Params: {
+ siteId: string;
+ userId: string;
+ };
+ Querystring: FilterParams;
+}
+
+export interface UserSummary {
+ sessions: number;
+ pageviews: number;
+ events: number;
+ /** Average session length in seconds. */
+ duration: number;
+ /** Days, in the request's timezone, on which the user started a session. */
+ active_days: number;
+}
+
+/**
+ * The profile's stat band for one window. The page asks for it twice, once for
+ * the selected period and once for the comparison period, so both sides of a
+ * delta come from the same query. Unlike the profile summary it never 404s:
+ * a window with no sessions is a row of zeros, which is what a delta needs.
+ */
+export const buildUserSummaryQuery = (query: GetUserSummaryRequest["Querystring"], siteId: number) => {
+ const { filteredSessionsCTE, scopedEvents } = buildUserEventScope(query, siteId);
+ const timeZone = query.time_zone || "UTC";
+
+ return `
+ WITH ${filteredSessionsCTE ? `${filteredSessionsCTE},` : ""}
+ sessions AS (
+ SELECT
+ session_id,
+ MIN(timestamp) AS session_start,
+ dateDiff('second', MIN(timestamp), MAX(timestamp)) AS session_duration,
+ countIf(type = 'pageview') AS pageviews,
+ countIf(type = 'custom_event') AS events
+ FROM ${scopedEvents}
+ GROUP BY
+ session_id
+ )
+ SELECT
+ count() AS sessions,
+ if(count() = 0, 0, round(avg(session_duration))) AS duration,
+ sum(pageviews) AS pageviews,
+ sum(events) AS events,
+ uniqExact(toDate(session_start, ${SqlString.escape(timeZone)})) AS active_days
+ FROM
+ sessions
+ `;
+};
+
+const EMPTY_SUMMARY: UserSummary = { sessions: 0, pageviews: 0, events: 0, duration: 0, active_days: 0 };
+
+export const getUserSummary = analyticsRoute<GetUserSummaryRequest>(
+ "user summary",
+ async (req: FastifyRequest<GetUserSummaryRequest>, res: FastifyReply) => {
+ const { siteId, userId } = req.params;
+
+ const rows = await runAnalyticsQuery<UserSummary>({
+ query: buildUserSummaryQuery(req.query, Number(siteId)),
+ params: { userId, site: Number(siteId) },
+ });
+
+ return res.send({ data: rows[0] ?? EMPTY_SUMMARY });
+ }
+);
diff --git a/server/src/api/analytics/users/getUserTraitBreakdown.ts b/server/src/api/analytics/users/getUserTraitBreakdown.ts
new file mode 100644
index 000000000..5f9fe9186
--- /dev/null
+++ b/server/src/api/analytics/users/getUserTraitBreakdown.ts
@@ -0,0 +1,158 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { analyticsRoute } from "../utils/analyticsQuery.js";
+import {
+ CohortRow,
+ MAX_SCOPED_USER_IDS,
+ resolveSearchScope,
+ resolveTraitCohort,
+ userNarrowingSchema,
+ UsersQuerystring,
+} from "./userScope.js";
+
+export interface GetUserTraitBreakdownRequest {
+ Params: { siteId: string };
+ Querystring: UsersQuerystring & { key?: string };
+}
+
+/** Totals for a set of users. Sessions, pageviews and events are sums; the client divides for averages. */
+export interface TraitGroupStats {
+ users: number;
+ sessions: number;
+ pageviews: number;
+ events: number;
+}
+
+export interface TraitBreakdown {
+ key: string;
+ /** True when more identified users were active than can be joined to their traits; nothing else is filled in. */
+ limited: boolean;
+ /** The ceiling `limited` refers to. */
+ limit: number;
+ /** Everyone in the period, and how many of them are identified. */
+ totals: (TraitGroupStats & { identified: number }) | null;
+ /** The largest values, by users. */
+ groups: (TraitGroupStats & { value: string })[];
+ /** Every value past the largest ones, together. */
+ other: (TraitGroupStats & { values: number }) | null;
+ /** Users with no value for the key: anonymous users and identified users without it. */
+ none: TraitGroupStats | null;
+}
+
+/** Group rows shown before the rest are folded into `other`. */
+export const MAX_TRAIT_GROUPS = 25;
+
+const emptyStats = (): TraitGroupStats => ({ users: 0, sessions: 0, pageviews: 0, events: 0 });
+
+const add = (stats: TraitGroupStats, row: CohortRow) => {
+ stats.users += row.users;
+ stats.sessions += row.sessions;
+ stats.pageviews += row.pageviews;
+ stats.events += row.events;
+};
+
+/**
+ * Groups the period's users by their value for one trait. Every user lands in
+ * exactly one of `groups`, `other` or `none`, so the parts sum to `totals`.
+ */
+export function groupByTraitValue(
+ key: string,
+ rows: CohortRow[],
+ values: Map<string, string>,
+ maxGroups = MAX_TRAIT_GROUPS
+): TraitBreakdown {
+ const totals = { ...emptyStats(), identified: 0 };
+ const none = emptyStats();
+ const byValue = new Map<string, TraitGroupStats>();
+
+ for (const row of rows) {
+ add(totals, row);
+ if (row.identified_user_id !== "") totals.identified += row.users;
+
+ const value = row.identified_user_id === "" ? undefined : values.get(row.identified_user_id);
+ if (value === undefined) {
+ add(none, row);
+ continue;
+ }
+ let group = byValue.get(value);
+ if (!group) {
+ group = emptyStats();
+ byValue.set(value, group);
+ }
+ add(group, row);
+ }
+
+ const ranked = [...byValue]
+ .map(([value, stats]) => ({ value, ...stats }))
+ .sort((a, b) => b.users - a.users || a.value.localeCompare(b.value));
+
+ const rest = ranked.slice(maxGroups);
+ const other = rest.length
+ ? rest.reduce(
+ (sum, group) => ({
+ values: sum.values + 1,
+ users: sum.users + group.users,
+ sessions: sum.sessions + group.sessions,
+ pageviews: sum.pageviews + group.pageviews,
+ events: sum.events + group.events,
+ }),
+ { values: 0, ...emptyStats() }
+ )
+ : null;
+
+ return {
+ key,
+ limited: false,
+ limit: MAX_SCOPED_USER_IDS,
+ totals,
+ groups: ranked.slice(0, maxGroups),
+ other,
+ none,
+ };
+}
+
+/**
+ * The period's users grouped by one trait.
+ *
+ * Traits live in Postgres and activity in ClickHouse, so this is a join across
+ * the two stores (see `resolveTraitCohort`). It takes the same period, filters,
+ * search and quick filters as the users list, which is what keeps a group's
+ * count equal to the rows that open under it.
+ */
+export const getUserTraitBreakdown = analyticsRoute<GetUserTraitBreakdownRequest>(
+ "user trait breakdown",
+ async (req: FastifyRequest<GetUserTraitBreakdownRequest>, res: FastifyReply) => {
+ const siteId = Number(req.params.siteId);
+ const { key } = req.query;
+
+ if (!key || key.length > 200) {
+ return res.status(400).send({ error: "key query parameter is required" });
+ }
+ const parsed = userNarrowingSchema.safeParse(req.query);
+ if (!parsed.success) {
+ return res.status(400).send({ error: parsed.error.issues[0]?.message ?? "Invalid query parameters" });
+ }
+
+ const search = await resolveSearchScope(req.query, siteId);
+ if (search.matchingUserIds?.length === 0) {
+ return res.send({ data: { ...groupByTraitValue(key, [], new Map()), searchLimited: false } });
+ }
+
+ const cohort = await resolveTraitCohort(req.query, siteId, key, { matchingUserIds: search.matchingUserIds });
+ if (cohort.limited) {
+ const limited: TraitBreakdown = {
+ key,
+ limited: true,
+ limit: MAX_SCOPED_USER_IDS,
+ totals: null,
+ groups: [],
+ other: null,
+ none: null,
+ };
+ return res.send({ data: { ...limited, searchLimited: search.limited } });
+ }
+
+ return res.send({
+ data: { ...groupByTraitValue(key, cohort.rows, cohort.values), searchLimited: search.limited },
+ });
+ }
+);
diff --git a/server/src/api/analytics/users/getUsers.ts b/server/src/api/analytics/users/getUsers.ts
index 44da580de..a782a62ef 100644
--- a/server/src/api/analytics/users/getUsers.ts
+++ b/server/src/api/analytics/users/getUsers.ts
@@ -1,6 +1,4 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { sql, SQL } from "drizzle-orm";
-import { db } from "../../../db/postgres/postgres.js";
import { enrichWithTraits } from "../utils/utils.js";
import { getTimeStatement } from "../utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
@@ -8,6 +6,14 @@ import { SESSION_CHANNEL_AGG, SESSION_REFERRER_AGG } from "../utils/sessionAttri
import { buildFilteredSessionsCTE } from "../utils/sessionFilters.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
import { effectiveUserId } from "../utils/effectiveUserId.js";
+import {
+ buildUserNarrowing,
+ resolveSearchScope,
+ resolveTraitCohort,
+ UserNarrowingParams,
+ userNarrowingSchema,
+ UserScope,
+} from "./userScope.js";
export type GetUsersResponse = {
user_id: string; // Device fingerprint
@@ -32,32 +38,27 @@ export interface GetUsersRequest {
Params: {
siteId: string;
};
- Querystring: FilterParams<{
- page?: string;
- page_size?: string;
- sort_by?: string;
- sort_order?: string;
- identified_only?: string;
- search?: string;
- search_field?: string;
- }>;
+ Querystring: FilterParams<
+ UserNarrowingParams & {
+ page?: string;
+ page_size?: string;
+ sort_by?: string;
+ sort_order?: string;
+ }
+ >;
}
export const buildUsersQuery = (
query: GetUsersRequest["Querystring"],
siteId: number,
- matchingUserIds: string[] | null,
+ scope: UserScope | null,
isCountQuery: boolean = false
) => {
- const {
- filters,
- sort_by: sortBy = "last_seen",
- sort_order: sortOrder = "desc",
- identified_only: identifiedOnly = "false",
- } = query;
- // Search results force the identified-only view: matching user IDs come from
- // Postgres profiles, which only exist for identified users.
- const filterIdentified = identifiedOnly === "true" || matchingUserIds !== null;
+ const { filters, sort_by: sortBy = "last_seen", sort_order: sortOrder = "desc" } = query;
+ const narrowing = buildUserNarrowing(query, scope ?? {});
+ // Ids resolved in Postgres (a profile search, a trait group) force the
+ // identified-only view: profiles only exist for identified users.
+ const filterIdentified = query.identified_only === "true" || !!scope?.matchingUserIds;
// Validate sort parameters
const validSortFields = ["first_seen", "last_seen", "pageviews", "sessions", "events"];
@@ -74,6 +75,33 @@ export const buildUsersQuery = (
// Query to get total count
if (isCountQuery) {
+ // A minimum session count or "new" is a property of the user, not of any
+ // one event, so the count has to build the per-user rows it filters.
+ if (narrowing.needsUserAggregate) {
+ return `
+${withFilteredSessions}
+SELECT count() AS total_count
+FROM (
+ SELECT
+ ${effectiveUserId("events")} AS effective_user_id,
+ argMax(identified_user_id, timestamp) AS identified_user_id,
+ count(DISTINCT session_id) AS sessions
+ FROM (
+ SELECT *
+ FROM events
+ ${filteredSessionsJoin}
+ WHERE
+ site_id = {siteId:Int32}
+ ${timeStatement}
+ ${narrowing.eventConditions}
+ ) AS events
+ GROUP BY effective_user_id
+)
+WHERE 1 = 1
+${narrowing.userConditions}
+`;
+ }
+
return filterIdentified
? `
${withFilteredSessions}
@@ -86,7 +114,7 @@ FROM (
site_id = {siteId:Int32}
AND identified_user_id != ''
${timeStatement}
- ${matchingUserIds ? "AND events.identified_user_id IN ({matchingUserIds:Array(String)})" : ""}
+ ${narrowing.eventConditions}
)
`
: `
@@ -98,7 +126,7 @@ ${filteredSessionsJoin}
WHERE
site_id = {siteId:Int32}
${timeStatement}
- ${matchingUserIds ? "AND events.identified_user_id IN ({matchingUserIds:Array(String)})" : ""}
+ ${narrowing.eventConditions}
`;
}
@@ -137,7 +165,7 @@ AggregatedUsers AS (
WHERE
site_id = {siteId:Int32}
${timeStatement}
- ${matchingUserIds ? "AND events.identified_user_id IN ({matchingUserIds:Array(String)})" : ""}
+ ${narrowing.eventConditions}
) AS events
GROUP BY
effective_user_id
@@ -146,8 +174,8 @@ SELECT
*
FROM AggregatedUsers
WHERE 1 = 1
-${filterIdentified ? "AND identified_user_id != ''" : ""}
-ORDER BY ${actualSortBy} ${actualSortOrder}
+${narrowing.userConditions}
+ORDER BY ${actualSortBy} ${actualSortOrder}, effective_user_id ASC
LIMIT {limit:Int32} OFFSET {offset:Int32}
`;
};
@@ -155,61 +183,76 @@ LIMIT {limit:Int32} OFFSET {offset:Int32}
export const getUsers = analyticsRoute<GetUsersRequest>(
"users",
async (req: FastifyRequest<GetUsersRequest>, res: FastifyReply) => {
- const { page = "1", page_size: pageSize = "100", search, search_field: searchField = "username" } = req.query;
- const site = req.params.siteId;
-
- // Search for matching user IDs in Postgres when search is provided
- const MAX_MATCHING_USER_IDS = 10000;
- let matchingUserIds: string[] | null = null;
- if (search && search.trim()) {
- const searchTerm = `%${search.trim()}%`;
- const siteId = Number(site);
-
- const fieldConditions: Record<string, SQL> = {
- username: sql`traits->>'username' ILIKE ${searchTerm}`,
- name: sql`traits->>'name' ILIKE ${searchTerm}`,
- email: sql`traits->>'email' ILIKE ${searchTerm}`,
- user_id: sql`user_id ILIKE ${searchTerm}`,
- };
- const condition = fieldConditions[searchField] ?? fieldConditions.username;
-
- const searchResult = await db.execute<{ user_id: string }>(sql`
- SELECT user_id FROM user_profiles
- WHERE site_id = ${siteId} AND ${condition}
- LIMIT ${MAX_MATCHING_USER_IDS}
- `);
-
- matchingUserIds = searchResult.map(r => r.user_id);
- if (matchingUserIds.length === 0) {
- return res.send({
- data: [],
- totalCount: 0,
- page: parseInt(page, 10),
- pageSize: parseInt(pageSize, 10),
- });
- }
+ const parsed = userNarrowingSchema.safeParse(req.query);
+ if (!parsed.success) {
+ return res.status(400).send({ error: parsed.error.issues[0]?.message ?? "Invalid query parameters" });
}
+ const { page = "1", page_size: pageSize = "100" } = req.query;
+ const { trait_key: traitKey, trait_value: traitValue, trait_missing: traitMissing } = parsed.data;
+ const siteId = Number(req.params.siteId);
const pageNum = parseInt(page, 10);
const pageSizeNum = parseInt(pageSize, 10);
+
+ if (traitKey && traitValue === undefined && traitMissing !== "true") {
+ return res.status(400).send({ error: "trait_key needs trait_value or trait_missing=true" });
+ }
+
+ const empty = (flags: { searchLimited?: boolean; breakdownLimited?: boolean } = {}) =>
+ res.send({ data: [], totalCount: 0, page: pageNum, pageSize: pageSizeNum, ...flags });
+
+ // A name, username or email search resolves to identified ids in Postgres.
+ const search = await resolveSearchScope(req.query, siteId);
+ if (search.matchingUserIds?.length === 0) {
+ return empty();
+ }
+ let scope: UserScope = { matchingUserIds: search.matchingUserIds };
+
+ // One group of a trait breakdown: the people in the period whose trait has
+ // this value, or who have no value for it.
+ if (traitKey) {
+ const cohort = await resolveTraitCohort(req.query, siteId, traitKey, scope);
+ if (cohort.limited) {
+ return empty({ searchLimited: search.limited, breakdownLimited: true });
+ }
+ if (traitMissing === "true" && scope.matchingUserIds) {
+ // Already limited to the searched ids: drop the ones with a value
+ // rather than sending a second list.
+ const ids = scope.matchingUserIds.filter(userId => !cohort.values.has(userId));
+ if (ids.length === 0) {
+ return empty({ searchLimited: search.limited });
+ }
+ scope = { matchingUserIds: ids };
+ } else if (traitMissing === "true") {
+ scope = { excludedUserIds: [...cohort.values.keys()] };
+ } else {
+ const ids = [...cohort.values].filter(([, value]) => value === traitValue).map(([userId]) => userId);
+ if (ids.length === 0) {
+ return empty({ searchLimited: search.limited });
+ }
+ scope = { matchingUserIds: ids };
+ }
+ }
+
+ const { params: narrowingParams } = buildUserNarrowing(req.query, scope);
const offset = (pageNum - 1) * pageSizeNum;
// Execute both queries in parallel
const [data, countData] = await Promise.all([
runAnalyticsQuery<Omit<GetUsersResponse[number], "traits">>({
- query: buildUsersQuery(req.query, Number(site), matchingUserIds, false),
+ query: buildUsersQuery(req.query, siteId, scope, false),
params: {
- siteId: Number(site),
+ siteId,
limit: pageSizeNum,
offset,
- ...(matchingUserIds ? { matchingUserIds } : {}),
+ ...narrowingParams,
},
}),
runAnalyticsQuery<{ total_count: number }>({
- query: buildUsersQuery(req.query, Number(site), matchingUserIds, true),
+ query: buildUsersQuery(req.query, siteId, scope, true),
params: {
- siteId: Number(site),
- ...(matchingUserIds ? { matchingUserIds } : {}),
+ siteId,
+ ...narrowingParams,
},
}),
]);
@@ -217,13 +260,15 @@ export const getUsers = analyticsRoute<GetUsersRequest>(
const totalCount = countData[0]?.total_count || 0;
// Enrich with traits from Postgres
- const dataWithTraits = await enrichWithTraits(data, Number(site));
+ const dataWithTraits = await enrichWithTraits(data, siteId);
return res.send({
data: dataWithTraits,
totalCount,
page: pageNum,
pageSize: pageSizeNum,
+ // True when more profiles matched the search than can be looked up at once.
+ searchLimited: search.limited,
});
}
);
diff --git a/server/src/api/analytics/users/getUsersSummary.ts b/server/src/api/analytics/users/getUsersSummary.ts
new file mode 100644
index 000000000..5090aacdc
--- /dev/null
+++ b/server/src/api/analytics/users/getUsersSummary.ts
@@ -0,0 +1,140 @@
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { effectiveUserId } from "../utils/effectiveUserId.js";
+import { buildFilteredSessionsCTE } from "../utils/sessionFilters.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
+import { buildSeenBeforeSubquery, NEW_USER_LOOKBACK_DAYS } from "./userScope.js";
+
+export interface GetUsersSummaryRequest {
+ Params: { siteId: string };
+ Querystring: FilterParams;
+}
+
+export interface UsersSummary {
+ users: number;
+ identified_users: number;
+ /** Sum of every user's session count, so it divides into sessions per user. */
+ sessions: number;
+ identified_sessions: number;
+ /** Null for an all-time request: there is no earlier period to have been seen in. */
+ new_users: number | null;
+ returning_users: number | null;
+ /** How far back "new" looks, in days. */
+ lookback_days: number;
+ /** Users with at least `power_min_sessions` sessions in the period. */
+ power_users: number;
+ power_min_sessions: number;
+}
+
+/** How many users had this many sessions, split by identified and new. */
+export interface SessionHistogramRow {
+ sessions: number;
+ identified: number;
+ is_new: number;
+ users: number;
+}
+
+/**
+ * Far more rows than a real site produces: `k` distinct session counts need at
+ * least k(k+1)/2 sessions between them. The handler refuses a result that
+ * reaches the limit rather than summing a truncated one.
+ */
+export const HISTOGRAM_ROW_LIMIT = 100_000;
+
+/** Share of users a "power user" has to match or beat on sessions. */
+const POWER_USER_QUANTILE = 0.95;
+/** One session is a visit, not a habit, however the distribution falls. */
+const POWER_USER_FLOOR = 2;
+
+/**
+ * The period's users as a histogram of sessions per user. Every stat-band
+ * figure is a sum over it, so one pass over the period answers all of them.
+ * Binds `{siteId:Int32}`.
+ */
+export function buildUsersSummaryQuery(query: FilterParams, siteId: number): string {
+ const timeStatement = getTimeStatement(query);
+ const filteredSessionsCTE = buildFilteredSessionsCTE(query.filters, siteId, timeStatement);
+ const seenBefore = buildSeenBeforeSubquery(query);
+
+ return `
+WITH ${filteredSessionsCTE ? `${filteredSessionsCTE},` : ""}
+UserStats AS (
+ SELECT
+ ${effectiveUserId("events")} AS effective_user_id,
+ argMax(events.identified_user_id, events.timestamp) != '' AS identified,
+ count(DISTINCT events.session_id) AS sessions
+ FROM events
+ ${filteredSessionsCTE ? "INNER JOIN FilteredSessions USING (session_id)" : ""}
+ WHERE
+ site_id = {siteId:Int32}
+ ${timeStatement}
+ GROUP BY effective_user_id
+)
+SELECT
+ sessions,
+ identified,
+ ${seenBefore ? `effective_user_id NOT IN ${seenBefore}` : "1"} AS is_new,
+ count() AS users
+FROM UserStats
+GROUP BY sessions, identified, is_new
+ORDER BY sessions ASC
+LIMIT ${HISTOGRAM_ROW_LIMIT}
+ `;
+}
+
+/**
+ * The smallest session count that at least `POWER_USER_QUANTILE` of users are
+ * at or below, floored at two sessions.
+ */
+export function powerUserThreshold(rows: SessionHistogramRow[]): number {
+ const total = rows.reduce((sum, row) => sum + row.users, 0);
+ const sorted = [...rows].sort((a, b) => a.sessions - b.sessions);
+
+ let seen = 0;
+ for (const row of sorted) {
+ seen += row.users;
+ if (seen >= total * POWER_USER_QUANTILE) {
+ return Math.max(POWER_USER_FLOOR, row.sessions);
+ }
+ }
+ return POWER_USER_FLOOR;
+}
+
+export function summarizeUsers(rows: SessionHistogramRow[], hasLookback: boolean): UsersSummary {
+ const sum = (pick: (row: SessionHistogramRow) => number) => rows.reduce((total, row) => total + pick(row), 0);
+
+ const users = sum(row => row.users);
+ const newUsers = sum(row => (row.is_new ? row.users : 0));
+ const powerMinSessions = powerUserThreshold(rows);
+
+ return {
+ users,
+ identified_users: sum(row => (row.identified ? row.users : 0)),
+ sessions: sum(row => row.sessions * row.users),
+ identified_sessions: sum(row => (row.identified ? row.sessions * row.users : 0)),
+ new_users: hasLookback ? newUsers : null,
+ returning_users: hasLookback ? users - newUsers : null,
+ lookback_days: NEW_USER_LOOKBACK_DAYS,
+ power_users: sum(row => (row.sessions >= powerMinSessions ? row.users : 0)),
+ power_min_sessions: powerMinSessions,
+ };
+}
+
+export const getUsersSummary = analyticsRoute<GetUsersSummaryRequest>(
+ "users summary",
+ async (req: FastifyRequest<GetUsersSummaryRequest>, res: FastifyReply) => {
+ const siteId = Number(req.params.siteId);
+
+ const rows = await runAnalyticsQuery<SessionHistogramRow>({
+ query: buildUsersSummaryQuery(req.query, siteId),
+ params: { siteId },
+ });
+
+ if (rows.length >= HISTOGRAM_ROW_LIMIT) {
+ throw new Error("Users summary histogram exceeded its row limit");
+ }
+
+ return res.send({ data: summarizeUsers(rows, buildSeenBeforeSubquery(req.query) !== null) });
+ }
+);
diff --git a/server/src/api/analytics/users/userEventScope.ts b/server/src/api/analytics/users/userEventScope.ts
new file mode 100644
index 000000000..7340cfbff
--- /dev/null
+++ b/server/src/api/analytics/users/userEventScope.ts
@@ -0,0 +1,39 @@
+import { FilterParams } from "@rybbit/shared";
+import { matchesUser } from "../utils/effectiveUserId.js";
+import { buildFilteredSessionsCTE } from "../utils/sessionFilters.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
+
+/**
+ * The slice of `events` every user-profile panel reads: one user's events on
+ * one site, inside the selected window, in the sessions the page's filters
+ * select. Built in one place so the stat band, the goals card and the insight
+ * row cannot disagree with the profile summary about which sessions count.
+ *
+ * Queries built from it bind `{userId:String}` and `{site:Int32}`.
+ */
+export const buildUserEventScope = (
+ query: Pick<FilterParams, "filters"> & Parameters<typeof getTimeStatement>[0],
+ siteId: number
+) => {
+ // Optional time range + dimension filters; both empty when the page is on
+ // all-time with no filters, which keeps the original full-history behavior.
+ const timeStatement = getTimeStatement(query);
+ const filteredSessionsCTE = buildFilteredSessionsCTE(query.filters, siteId, timeStatement);
+ const filteredSessionsJoin = filteredSessionsCTE ? "INNER JOIN FilteredSessions USING (session_id)" : "";
+ const withFilteredSessions = filteredSessionsCTE ? `WITH ${filteredSessionsCTE}` : "";
+
+ // Filters select sessions first. Every panel then reads all events in those
+ // sessions, keeping the summary, vitals, locations, devices, and session list
+ // on the same session-scoped semantics.
+ const scopedEvents = `(
+ SELECT source_events.*
+ FROM events AS source_events
+ ${filteredSessionsJoin}
+ WHERE
+ ${matchesUser("{userId:String}", "source_events")}
+ AND source_events.site_id = {site:Int32}
+ ${timeStatement}
+ ) AS events`;
+
+ return { timeStatement, filteredSessionsCTE, withFilteredSessions, scopedEvents };
+};
diff --git a/server/src/api/analytics/users/userProfileQueries.test.ts b/server/src/api/analytics/users/userProfileQueries.test.ts
new file mode 100644
index 000000000..11b1e8a8e
--- /dev/null
+++ b/server/src/api/analytics/users/userProfileQueries.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../db/clickhouse/clickhouse.js", () => ({
+ clickhouse: { query: vi.fn() },
+}));
+vi.mock("../../../db/postgres/postgres.js", () => ({
+ db: {},
+}));
+// The segments handler reaches auth-utils through segmentAccess; these tests
+// only build SQL, so keep the auth initializer out of them.
+vi.mock("../../../lib/auth.js", () => ({ auth: { api: {} } }));
+
+import {
+ buildUserGoalsQuery,
+ buildUserSessionGoalsQuery,
+ MAX_SESSION_IDS,
+ parseSessionIds,
+ toGoalConditions,
+} from "./getUserGoals.js";
+import { buildUserRepeatedErrorQuery } from "./getUserRepeatedError.js";
+import { buildUserSegmentsQuery } from "./getUserSegments.js";
+import { buildUserSummaryQuery } from "./getUserSummary.js";
+
+const USER_PREDICATE = "identified_user_id = {userId:String}";
+const campaignFilter = { parameter: "utm_campaign", type: "equals", value: ["launch"] };
+const pathnameFilter = { parameter: "pathname", type: "contains", value: ["/docs"] };
+
+const range = (filters = "") => ({
+ filters,
+ start_date: "2026-09-01",
+ end_date: "2026-09-30",
+ time_zone: "Europe/Stockholm",
+});
+const allTime = (filters = "") => ({ filters, start_date: "", end_date: "", time_zone: "UTC" });
+
+const goalRows = [
+ { goalId: 3, goalType: "path", config: { pathPattern: "/pricing" } },
+ { goalId: 7, goalType: "event", config: { eventName: "signup" } },
+ // No event name: cannot be completed, so it never reaches the SQL.
+ { goalId: 9, goalType: "event", config: {} },
+];
+
+// Every scan of `events` in a statement, with the WHERE clause that bounds it.
+const eventScans = (sql: string) => sql.split(/FROM events\b/).slice(1);
+
+describe("user summary query", () => {
+ it("reads one user's sessions inside the window and counts active days in the request's timezone", () => {
+ const sql = buildUserSummaryQuery(range(), 1);
+
+ expect(sql).toContain(USER_PREDICATE);
+ expect(sql).toContain("source_events.site_id = {site:Int32}");
+ expect(sql).toContain("toDateTime('2026-09-01', 'Europe/Stockholm')");
+ expect(sql).toContain("uniqExact(toDate(session_start, 'Europe/Stockholm')) AS active_days");
+ expect(sql).toContain("if(count() = 0, 0, round(avg(session_duration))) AS duration");
+ expect(sql).not.toContain("FilteredSessions");
+ });
+
+ it("applies the page's filters the way the profile summary does", () => {
+ const sql = buildUserSummaryQuery(range(JSON.stringify([campaignFilter])), 1);
+
+ expect(sql).toContain("FilteredSessions AS");
+ expect(sql).toContain("INNER JOIN FilteredSessions USING (session_id)");
+ expect(sql.match(/utm_campaign = 'launch'/g)).toHaveLength(1);
+ });
+});
+
+describe("user goals queries", () => {
+ const conditions = toGoalConditions(goalRows);
+
+ it("skips goals that have no usable condition", () => {
+ expect(conditions.map(condition => condition.goalId)).toEqual([3, 7]);
+ });
+
+ it("counts converting sessions and the latest completion per goal over one scan of the user's events", () => {
+ const sql = buildUserGoalsQuery(range(), 1, conditions)!;
+
+ expect(sql).toContain("AS goal_3_sessions");
+ expect(sql).toContain("AS goal_3_last");
+ expect(sql).toContain("AS goal_7_sessions");
+ expect(sql).not.toContain("goal_9");
+ expect(sql).toContain(USER_PREDICATE);
+ expect(sql).toContain("toDateTime('2026-09-01', 'Europe/Stockholm')");
+ expect(eventScans(sql)).toHaveLength(1);
+ });
+
+ it("has nothing to run for a site without goals", () => {
+ expect(buildUserGoalsQuery(range(), 1, [])).toBeNull();
+ expect(buildUserSessionGoalsQuery(range(), 1, [])).toBeNull();
+ });
+
+ it("limits the per-session lookup to the listed sessions of this user", () => {
+ const sql = buildUserSessionGoalsQuery(range(), 1, conditions)!;
+
+ expect(sql).toContain("WHERE session_id IN ({sessionIds:Array(String)})");
+ expect(sql).toContain("GROUP BY session_id");
+ expect(sql).toContain("AS goal_3");
+ expect(sql).toContain("AS goal_7");
+ expect(sql).toContain(USER_PREDICATE);
+ });
+
+ it("accepts only a bounded JSON array of session ids", () => {
+ expect(parseSessionIds(JSON.stringify(["a", "b", "a"]))).toEqual(["a", "b"]);
+ expect(parseSessionIds(undefined)).toBeNull();
+ expect(parseSessionIds("not json")).toBeNull();
+ expect(parseSessionIds(JSON.stringify([]))).toBeNull();
+ expect(parseSessionIds(JSON.stringify([1, 2]))).toBeNull();
+ expect(parseSessionIds(JSON.stringify("a"))).toBeNull();
+ expect(parseSessionIds(JSON.stringify(Array.from({ length: MAX_SESSION_IDS + 1 }, (_, i) => `s${i}`)))).toBeNull();
+ });
+});
+
+describe("user repeated error query", () => {
+ it("returns the latest session in which one message was thrown at least twice", () => {
+ const sql = buildUserRepeatedErrorQuery(range(), 1);
+
+ expect(sql).toContain("type = 'error'");
+ expect(sql).toContain("error_message,\n session_id");
+ expect(sql).toContain("occurrences >= 2");
+ expect(sql).toContain("last_seen DESC");
+ expect(sql).toContain("LIMIT 1");
+ expect(sql).toContain(USER_PREDICATE);
+ expect(sql).toContain("toDateTime('2026-09-01', 'Europe/Stockholm')");
+ });
+});
+
+describe("user segments query", () => {
+ const segments = [
+ { segmentId: 4, filters: [campaignFilter] as never },
+ { segmentId: 11, filters: [pathnameFilter] as never },
+ ];
+
+ it("counts each segment with its own session CTE and reports the user's total", () => {
+ const built = buildUserSegmentsQuery(range(), 1, segments)!;
+
+ expect(built.segmentIds).toEqual([4, 11]);
+ expect(built.query).toContain("Segment_4 AS (");
+ expect(built.query).toContain("Segment_11 AS (");
+ expect(built.query).toContain("(SELECT count() FROM Segment_4) AS segment_4");
+ expect(built.query).toContain("(SELECT count() FROM Segment_11) AS segment_11");
+ expect(built.query).toContain("AS total_sessions");
+ });
+
+ it("bounds every scan, including the filters' own subqueries, to the user and the window", () => {
+ const { query } = buildUserSegmentsQuery(range(), 1, segments)!;
+ const scans = eventScans(query);
+
+ // Two segment CTEs, the pathname subquery inside the second, and the total.
+ expect(scans).toHaveLength(4);
+ for (const scan of scans) {
+ const where = scan.split(/GROUP BY|\)\s*AS total_sessions/)[0];
+ expect(where).toContain(USER_PREDICATE);
+ expect(where).toContain("toDateTime('2026-09-01', 'Europe/Stockholm')");
+ }
+ });
+
+ it("stays well-formed on an all-time window, where there is no time predicate to lead with", () => {
+ const { query } = buildUserSegmentsQuery(allTime(), 1, segments)!;
+
+ expect(query).not.toMatch(/AND\s+AND/);
+ expect(query).not.toMatch(/WHERE\s+AND/);
+ for (const scan of eventScans(query)) {
+ expect(scan).toContain(USER_PREDICATE);
+ }
+ });
+
+ it("narrows each segment and the total by the page's own filters", () => {
+ const country = { parameter: "country", type: "equals", value: ["SE"] };
+ const { query } = buildUserSegmentsQuery(range(JSON.stringify([country])), 1, segments)!;
+
+ expect(query).toContain("PageSessions AS (");
+ expect(query).toContain("(SELECT count() FROM PageSessions) AS total_sessions");
+ // Once in each segment and once in the total.
+ expect(query.match(/country = 'SE'/g)).toHaveLength(3);
+ });
+
+ it("drops a segment whose stored filters cannot be compiled and keeps the rest", () => {
+ const broken = { segmentId: 5, filters: [{ parameter: "pathname", type: "regex", value: ["(?=x)"] }] as never };
+ const built = buildUserSegmentsQuery(range(), 1, [broken, segments[0]])!;
+
+ expect(built.segmentIds).toEqual([4]);
+ expect(built.query).not.toContain("Segment_5");
+ });
+
+ it("has nothing to run when no segment has filters", () => {
+ expect(buildUserSegmentsQuery(range(), 1, [])).toBeNull();
+ expect(buildUserSegmentsQuery(range(), 1, [{ segmentId: 2, filters: [] }])).toBeNull();
+ });
+});
diff --git a/server/src/api/analytics/users/userQueries.clickhouse.test.ts b/server/src/api/analytics/users/userQueries.clickhouse.test.ts
new file mode 100644
index 000000000..040624e38
--- /dev/null
+++ b/server/src/api/analytics/users/userQueries.clickhouse.test.ts
@@ -0,0 +1,189 @@
+import { createClient } from "@clickhouse/client";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+// Run against any ClickHouse using CLICKHOUSE_TEST_URL and optional
+// CLICKHOUSE_TEST_USER / CLICKHOUSE_TEST_PASSWORD. Every query supplies its own
+// events CTE: no tables, migrations or production data are needed.
+vi.mock("../../../db/clickhouse/clickhouse.js", () => ({ clickhouse: {} }));
+vi.mock("../../../db/postgres/postgres.js", () => ({ db: {} }));
+
+import { buildUsersQuery, GetUsersRequest } from "./getUsers.js";
+import { buildUsersSummaryQuery, SessionHistogramRow, summarizeUsers } from "./getUsersSummary.js";
+import { buildCohortQuery, buildUserNarrowing, CohortRow, UserScope } from "./userScope.js";
+
+// site, time, session, device id, identified user, event type, country
+const events: [number, string, string, string, string, string, string][] = [
+ // An anonymous visitor who was also here inside the lookback: returning.
+ [1, "2026-08-01 10:00:00", "a-old", "dev-a", "", "pageview", "US"],
+ [1, "2026-09-10 10:00:00", "a-1", "dev-a", "", "pageview", "US"],
+ [1, "2026-09-10 10:01:00", "a-1", "dev-a", "", "pageview", "US"],
+ // An anonymous visitor seen for the first time.
+ [1, "2026-09-10 11:00:00", "b-1", "dev-b", "", "pageview", "DE"],
+ // Identified, three sessions, seen inside the lookback: returning.
+ [1, "2026-07-15 09:00:00", "ann-old", "dev-c", "ann", "pageview", "US"],
+ [1, "2026-09-10 09:00:00", "ann-1", "dev-c", "ann", "pageview", "US"],
+ [1, "2026-09-11 09:00:00", "ann-2", "dev-c", "ann", "pageview", "US"],
+ [1, "2026-09-12 09:00:00", "ann-3", "dev-c", "ann", "custom_event", "US"],
+ // Identified, one session.
+ [1, "2026-09-11 12:00:00", "bob-1", "dev-d", "bob", "pageview", "US"],
+ [1, "2026-09-11 12:01:00", "bob-1", "dev-d", "bob", "custom_event", "US"],
+ // Identified, two sessions.
+ [1, "2026-09-10 15:00:00", "cy-1", "dev-e", "cy", "pageview", "DE"],
+ [1, "2026-09-12 15:00:00", "cy-2", "dev-e", "cy", "pageview", "DE"],
+ // Last seen before the lookback begins: new again, by the bounded definition.
+ [1, "2026-01-01 08:00:00", "dee-old", "dev-f", "dee", "pageview", "US"],
+ [1, "2026-09-12 08:00:00", "dee-1", "dev-f", "dee", "pageview", "US"],
+ // Outside the period, and another site reusing the same ids.
+ [1, "2026-08-20 08:00:00", "z-1", "dev-z", "", "pageview", "US"],
+ [2, "2026-09-11 08:00:00", "a-1", "dev-a", "ann", "pageview", "US"],
+];
+
+const fixture = `WITH events AS (
+ SELECT *, '' AS region, '' AS city, 'en' AS language, 'Chrome' AS browser, '120' AS browser_version,
+ 'macOS' AS operating_system, '14' AS operating_system_version, 'Desktop' AS device_type,
+ toUInt16(1440) AS screen_width, toUInt16(900) AS screen_height, '' AS referrer, 'Direct' AS channel,
+ 'example.com' AS hostname, '' AS tag
+ FROM values(
+ 'site_id Int32, timestamp DateTime, session_id String, user_id String, identified_user_id String, type String, country String',
+ ${events.map(row => `(${row.map(value => (typeof value === "number" ? value : `'${value}'`)).join(",")})`).join(",")}
+ )
+)`;
+
+type Query = GetUsersRequest["Querystring"];
+const period: Query = { filters: "", start_date: "2026-09-10", end_date: "2026-09-12", time_zone: "UTC" };
+const germany = JSON.stringify([{ parameter: "country", type: "equals", value: ["DE"] }]);
+
+describe.skipIf(!process.env.CLICKHOUSE_TEST_URL)("Users page queries against ClickHouse", () => {
+ let client: ReturnType<typeof createClient>;
+
+ beforeAll(() => {
+ client = createClient({
+ url: process.env.CLICKHOUSE_TEST_URL,
+ username: process.env.CLICKHOUSE_TEST_USER || "default",
+ password: process.env.CLICKHOUSE_TEST_PASSWORD || "",
+ compression: { request: false, response: false },
+ clickhouse_settings: { readonly: "2", max_threads: 2, max_execution_time: 10 },
+ });
+ });
+ afterAll(async () => {
+ await client.close();
+ });
+
+ async function run<T>(query: string, params: Record<string, unknown>) {
+ const sql = /^\s*WITH\s*\S/.test(query) ? query.replace(/^\s*WITH\b/, `${fixture},`) : `${fixture} ${query}`;
+ const result = await client.query({ query: sql, query_params: params, format: "JSONEachRow" });
+ return result.json<T>();
+ }
+
+ /** The listed users, in order, and what the count query says. */
+ async function list(query: Query, scope: UserScope | null = null) {
+ const { params } = buildUserNarrowing(query, scope ?? {});
+ const rows = await run<{ effective_user_id: string; sessions: string }>(buildUsersQuery(query, 1, scope, false), {
+ siteId: 1,
+ limit: 100,
+ offset: 0,
+ ...params,
+ });
+ const count = await run<{ total_count: string }>(buildUsersQuery(query, 1, scope, true), { siteId: 1, ...params });
+ return { ids: rows.map(row => row.effective_user_id), total: Number(count[0]?.total_count ?? 0) };
+ }
+
+ it("lists everyone in the period, newest first, and counts the same people", async () => {
+ expect(await list(period)).toEqual({ ids: ["cy", "ann", "dee", "bob", "dev-b", "dev-a"], total: 6 });
+ });
+
+ it.each<[string, Partial<Query>, UserScope | null, string[]]>([
+ ["identified only", { identified_only: "true" }, null, ["cy", "ann", "dee", "bob"]],
+ ["a minimum session count", { min_sessions: "2" }, null, ["cy", "ann"]],
+ ["new in the period", { new_only: "true" }, null, ["cy", "dee", "bob", "dev-b"]],
+ ["new and identified", { new_only: "true", identified_only: "true" }, null, ["cy", "dee", "bob"]],
+ ["a user-id search, any case", { search: "DEV-", search_field: "user_id" }, null, ["dev-b", "dev-a"]],
+ ["a user-id search on a custom id", { search: "an", search_field: "user_id" }, null, ["ann"]],
+ ["ids resolved in Postgres", {}, { matchingUserIds: ["ann", "bob", "nobody"] }, ["ann", "bob"]],
+ ["ids left out", {}, { excludedUserIds: ["ann", "bob"] }, ["cy", "dee", "dev-b", "dev-a"]],
+ ["a session filter", { filters: germany }, null, ["cy", "dev-b"]],
+ ["a session filter and a quick filter", { filters: germany, min_sessions: "2" }, null, ["cy"]],
+ ["nobody", { min_sessions: "50" }, null, []],
+ ])("narrows the list and its count by %s", async (_name, extra, scope, expected) => {
+ expect(await list({ ...period, ...extra }, scope)).toEqual({ ids: expected, total: expected.length });
+ });
+
+ it("treats everyone as new over all time", async () => {
+ const allTime: Query = { filters: "", start_date: "", end_date: "", time_zone: "UTC", new_only: "true" };
+ expect((await list(allTime)).total).toBe(7);
+ });
+
+ it("summarises the same period for the stat band", async () => {
+ const rows = await run<Record<keyof SessionHistogramRow, string>>(buildUsersSummaryQuery(period, 1), { siteId: 1 });
+ const histogram = rows.map(row => ({
+ sessions: Number(row.sessions),
+ identified: Number(row.identified),
+ is_new: Number(row.is_new),
+ users: Number(row.users),
+ }));
+
+ expect(summarizeUsers(histogram, true)).toEqual({
+ users: 6,
+ identified_users: 4,
+ sessions: 9,
+ identified_sessions: 7,
+ // dev-a and ann were seen in the 90 days before; dee's last visit is older than that.
+ new_users: 4,
+ returning_users: 2,
+ lookback_days: 90,
+ power_users: 1,
+ power_min_sessions: 3,
+ });
+ });
+
+ it("applies filters to the summary but not to what counts as seen before", async () => {
+ const rows = await run<Record<keyof SessionHistogramRow, string>>(
+ buildUsersSummaryQuery({ ...period, filters: germany }, 1),
+ { siteId: 1 }
+ );
+ expect(rows.reduce((sum, row) => sum + Number(row.users), 0)).toBe(2);
+ expect(rows.every(row => Number(row.is_new) === 1)).toBe(true);
+ });
+
+ it("returns one cohort row per identified user and one for all anonymous users", async () => {
+ const narrowing = buildUserNarrowing(period);
+ const rows = await run<Record<keyof CohortRow, string>>(buildCohortQuery(period, 1, narrowing), {
+ siteId: 1,
+ cohortLimit: 100,
+ });
+
+ expect(rows.map(row => [row.identified_user_id, Number(row.users), Number(row.sessions)])).toEqual([
+ ["", 2, 2],
+ ["ann", 1, 3],
+ ["bob", 1, 1],
+ ["cy", 1, 2],
+ ["dee", 1, 1],
+ ]);
+ expect(rows.map(row => [Number(row.pageviews), Number(row.events)])).toEqual([
+ [3, 0],
+ [2, 1],
+ [1, 1],
+ [2, 0],
+ [1, 0],
+ ]);
+ });
+
+ it("keeps the anonymous row when the cohort limit cuts identified users", async () => {
+ const rows = await run<Record<keyof CohortRow, string>>(buildCohortQuery(period, 1, buildUserNarrowing(period)), {
+ siteId: 1,
+ cohortLimit: 3,
+ });
+ expect(rows.map(row => row.identified_user_id)).toEqual(["", "ann", "bob"]);
+ });
+
+ it("applies the quick filters to the cohort, so a group matches its rows", async () => {
+ const query = { ...period, min_sessions: "2" };
+ const narrowing = buildUserNarrowing(query);
+ const rows = await run<Record<keyof CohortRow, string>>(buildCohortQuery(query, 1, narrowing), {
+ siteId: 1,
+ cohortLimit: 100,
+ ...narrowing.params,
+ });
+ expect(rows.map(row => row.identified_user_id)).toEqual(["ann", "cy"]);
+ });
+});
diff --git a/server/src/api/analytics/users/userScope.test.ts b/server/src/api/analytics/users/userScope.test.ts
new file mode 100644
index 000000000..edade695b
--- /dev/null
+++ b/server/src/api/analytics/users/userScope.test.ts
@@ -0,0 +1,285 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../db/clickhouse/clickhouse.js", () => ({
+ clickhouse: { query: vi.fn() },
+}));
+vi.mock("../../../db/postgres/postgres.js", () => ({
+ db: {},
+}));
+
+import { groupByTraitValue } from "./getUserTraitBreakdown.js";
+import { buildUsersQuery } from "./getUsers.js";
+import { buildUsersSummaryQuery, powerUserThreshold, summarizeUsers } from "./getUsersSummary.js";
+import {
+ buildCohortQuery,
+ buildUserNarrowing,
+ CohortRow,
+ getLookbackParams,
+ userNarrowingSchema,
+} from "./userScope.js";
+
+const base = { filters: "", start_date: "2026-09-01", end_date: "2026-09-30", time_zone: "Europe/Berlin" };
+const allTime = { filters: "", start_date: "", end_date: "", time_zone: "UTC" };
+
+describe("getLookbackParams", () => {
+ it("ends a date range's lookback on the day before the period starts", () => {
+ expect(getLookbackParams(base, 90)).toEqual({
+ start_date: "2026-06-03",
+ end_date: "2026-08-31",
+ time_zone: "Europe/Berlin",
+ });
+ });
+
+ it("ends a datetime range's lookback at the instant the period starts", () => {
+ expect(
+ getLookbackParams(
+ { start_datetime: "2026-09-10T12:00:00Z", end_datetime: "2026-09-11T12:00:00Z", time_zone: "UTC" },
+ 30
+ )
+ ).toEqual({ start_datetime: "2026-08-11 12:00:00", end_datetime: "2026-09-10 12:00:00", time_zone: "UTC" });
+ });
+
+ it("moves a past-minutes window back by whole days", () => {
+ expect(getLookbackParams({ past_minutes_start: 60, past_minutes_end: 0, time_zone: "UTC" }, 1)).toEqual({
+ past_minutes_start: 1500,
+ past_minutes_end: 60,
+ time_zone: "UTC",
+ });
+ });
+
+ it("has no lookback for an all-time or unusable window", () => {
+ expect(getLookbackParams(allTime)).toBeNull();
+ expect(getLookbackParams({ start_date: "not-a-date", end_date: "2026-09-30", time_zone: "UTC" })).toBeNull();
+ expect(getLookbackParams({ ...base, time_zone: "Nowhere/Invalid" })).toBeNull();
+ });
+});
+
+describe("userNarrowingSchema", () => {
+ it("accepts the Users page's params and coerces the session floor", () => {
+ const parsed = userNarrowingSchema.parse({ ...base, new_only: "true", min_sessions: "4", trait_key: "plan" });
+ expect(parsed).toMatchObject({ new_only: "true", min_sessions: 4, trait_key: "plan" });
+ });
+
+ it.each([
+ { min_sessions: "0" },
+ { min_sessions: "1; DROP TABLE events" },
+ { new_only: "yes" },
+ { trait_key: "" },
+ { search: "x".repeat(201) },
+ ])("rejects %o", params => {
+ expect(userNarrowingSchema.safeParse(params).success).toBe(false);
+ });
+});
+
+describe("buildUserNarrowing", () => {
+ it("adds nothing for a plain request", () => {
+ expect(buildUserNarrowing(base)).toEqual({
+ eventConditions: "",
+ userConditions: "",
+ needsUserAggregate: false,
+ params: {},
+ });
+ });
+
+ it("binds every value instead of interpolating it", () => {
+ const hostile = "'; DROP TABLE events; --";
+ const narrowing = buildUserNarrowing(
+ { ...base, search: hostile, search_field: "user_id", min_sessions: "3" },
+ { matchingUserIds: [hostile], excludedUserIds: [hostile] }
+ );
+
+ const sql = narrowing.eventConditions + narrowing.userConditions;
+ expect(sql).not.toContain("DROP TABLE");
+ expect(sql).toContain("{matchingUserIds:Array(String)}");
+ expect(sql).toContain("{excludedUserIds:Array(String)}");
+ expect(sql).toContain("{userIdSearch:String}");
+ expect(sql).toContain("{minSessions:UInt32}");
+ expect(narrowing.params).toEqual({
+ matchingUserIds: [hostile],
+ excludedUserIds: [hostile],
+ userIdSearch: hostile,
+ minSessions: 3,
+ });
+ });
+
+ it("searches ids in ClickHouse only for the user-id field", () => {
+ expect(buildUserNarrowing({ ...base, search: "mara", search_field: "name" }).eventConditions).toBe("");
+ expect(buildUserNarrowing({ ...base, search: " a1d7 ", search_field: "user_id" })).toMatchObject({
+ params: { userIdSearch: "a1d7" },
+ userConditions: "",
+ });
+ });
+
+ it("treats Postgres-resolved ids as identified without the flag", () => {
+ expect(buildUserNarrowing(base, { matchingUserIds: ["u1"] }).userConditions).toBe("AND identified_user_id != ''");
+ expect(buildUserNarrowing(base, { excludedUserIds: ["u1"] }).userConditions).toBe("");
+ });
+
+ it("bounds the new-user lookback to the period and the window before it", () => {
+ const { userConditions, needsUserAggregate } = buildUserNarrowing({ ...base, new_only: "true" });
+
+ expect(needsUserAggregate).toBe(true);
+ expect(userConditions).toContain("AND effective_user_id NOT IN (");
+ expect(userConditions).toContain("toDateTime('2026-06-03', 'Europe/Berlin')");
+ expect(userConditions).toContain("toDateTime('2026-08-31', 'Europe/Berlin')");
+ expect(userConditions).toContain("toDateTime('2026-09-01', 'Europe/Berlin')");
+ expect(userConditions.match(/site_id = \{siteId:Int32\}/g)).toHaveLength(2);
+ });
+
+ it("drops the new-user condition for all time, where everyone is new", () => {
+ expect(buildUserNarrowing({ ...allTime, new_only: "true" })).toMatchObject({
+ userConditions: "",
+ needsUserAggregate: false,
+ });
+ });
+});
+
+describe("users list with narrowing", () => {
+ it("keeps the cheap count when nothing needs per-user rows", () => {
+ const count = buildUsersQuery({ ...base, identified_only: "true" }, 1, null, true);
+ expect(count).toContain("SELECT DISTINCT identified_user_id");
+ expect(count).not.toContain("GROUP BY effective_user_id");
+ });
+
+ it("counts per-user rows when a quick filter reads them, with the list's own conditions", () => {
+ const query = { ...base, min_sessions: "5", new_only: "true", identified_only: "true" };
+ const list = buildUsersQuery(query, 1, null, false);
+ const count = buildUsersQuery(query, 1, null, true);
+
+ for (const sql of [list, count]) {
+ expect(sql).toContain("GROUP BY");
+ expect(sql).toContain("AND identified_user_id != ''");
+ expect(sql).toContain("AND sessions >= {minSessions:UInt32}");
+ expect(sql).toContain("AND effective_user_id NOT IN (");
+ }
+ expect(count).toContain("SELECT count() AS total_count");
+ });
+
+ it("limits and excludes ids at the event level in both queries", () => {
+ for (const isCount of [false, true]) {
+ expect(buildUsersQuery(base, 1, { matchingUserIds: ["u1"] }, isCount)).toContain(
+ "AND events.identified_user_id IN ({matchingUserIds:Array(String)})"
+ );
+ expect(buildUsersQuery(base, 1, { excludedUserIds: ["u1"] }, isCount)).toContain(
+ "AND events.identified_user_id NOT IN ({excludedUserIds:Array(String)})"
+ );
+ }
+ });
+
+ it("breaks sort ties on the user so pages do not overlap", () => {
+ expect(buildUsersQuery({ ...base, sort_by: "sessions", sort_order: "asc" }, 1, null)).toContain(
+ "ORDER BY sessions ASC, effective_user_id ASC"
+ );
+ expect(buildUsersQuery({ ...base, sort_by: "sessions; DROP TABLE events" }, 1, null)).toContain(
+ "ORDER BY last_seen DESC, effective_user_id ASC"
+ );
+ });
+});
+
+describe("cohort and summary queries", () => {
+ const filters = JSON.stringify([{ parameter: "country", type: "equals", value: ["DE"] }]);
+
+ it("scope the cohort to the period, the filters and the narrowing, under a limit", () => {
+ const query = { ...base, filters, min_sessions: "2" };
+ const sql = buildCohortQuery(query, 1, buildUserNarrowing(query));
+
+ expect(sql).toContain("FilteredSessions AS");
+ expect(sql).toContain("INNER JOIN FilteredSessions USING (session_id)");
+ expect(sql).toContain("toDateTime('2026-09-01', 'Europe/Berlin')");
+ expect(sql).toContain("AND sessions >= {minSessions:UInt32}");
+ expect(sql).toContain("ORDER BY identified_user_id = '' DESC");
+ expect(sql).toContain("LIMIT {cohortLimit:Int32}");
+ });
+
+ it("builds the summary over the same sessions, with a bounded lookback", () => {
+ const sql = buildUsersSummaryQuery({ ...base, filters }, 1);
+
+ expect(sql).toContain("INNER JOIN FilteredSessions USING (session_id)");
+ expect(sql).toContain("effective_user_id NOT IN (");
+ expect(sql).toContain("toDateTime('2026-06-03', 'Europe/Berlin')");
+ expect(sql).toContain("GROUP BY sessions, identified, is_new");
+ expect(sql).toMatch(/LIMIT \d+/);
+ });
+
+ it("skips the lookback for all time", () => {
+ expect(buildUsersSummaryQuery(allTime, 1)).not.toContain("NOT IN");
+ });
+});
+
+describe("summarizeUsers", () => {
+ const rows = [
+ { sessions: 1, identified: 0, is_new: 1, users: 90 },
+ { sessions: 1, identified: 0, is_new: 0, users: 4 },
+ { sessions: 3, identified: 1, is_new: 0, users: 4 },
+ { sessions: 10, identified: 1, is_new: 1, users: 2 },
+ ];
+
+ it("sums the histogram into the stat band's figures", () => {
+ expect(summarizeUsers(rows, true)).toEqual({
+ users: 100,
+ identified_users: 6,
+ sessions: 126,
+ identified_sessions: 32,
+ new_users: 92,
+ returning_users: 8,
+ lookback_days: 90,
+ power_users: 6,
+ power_min_sessions: 3,
+ });
+ });
+
+ it("reports no new or returning split without a lookback", () => {
+ expect(summarizeUsers(rows, false)).toMatchObject({ new_users: null, returning_users: null, users: 100 });
+ });
+
+ it("is all zeros for an empty period", () => {
+ expect(summarizeUsers([], true)).toMatchObject({ users: 0, sessions: 0, new_users: 0, power_users: 0 });
+ });
+
+ it("never calls a single session a power user", () => {
+ expect(powerUserThreshold([{ sessions: 1, identified: 0, is_new: 1, users: 1000 }])).toBe(2);
+ expect(powerUserThreshold([])).toBe(2);
+ });
+});
+
+describe("groupByTraitValue", () => {
+ const row = (identified_user_id: string, sessions: number, users = 1): CohortRow => ({
+ identified_user_id,
+ users,
+ sessions,
+ pageviews: sessions * 2,
+ events: sessions,
+ });
+ const rows = [row("", 50, 40), row("ann", 9), row("bob", 3), row("cy", 2), row("dee", 1), row("eve", 4)];
+ const values = new Map([
+ ["ann", "Pro"],
+ ["bob", "Pro"],
+ ["cy", "Free"],
+ ["dee", ""],
+ ]);
+
+ it("puts every user in exactly one group, largest first", () => {
+ const breakdown = groupByTraitValue("plan", rows, values);
+
+ expect(breakdown.groups).toEqual([
+ { value: "Pro", users: 2, sessions: 12, pageviews: 24, events: 12 },
+ { value: "", users: 1, sessions: 1, pageviews: 2, events: 1 },
+ { value: "Free", users: 1, sessions: 2, pageviews: 4, events: 2 },
+ ]);
+ // Anonymous users and the identified user without the trait.
+ expect(breakdown.none).toEqual({ users: 41, sessions: 54, pageviews: 108, events: 54 });
+ expect(breakdown.other).toBeNull();
+ expect(breakdown.totals).toEqual({ users: 45, identified: 5, sessions: 69, pageviews: 138, events: 69 });
+
+ const parts = [...breakdown.groups, breakdown.none!];
+ expect(parts.reduce((sum, part) => sum + part.users, 0)).toBe(breakdown.totals!.users);
+ expect(parts.reduce((sum, part) => sum + part.sessions, 0)).toBe(breakdown.totals!.sessions);
+ });
+
+ it("folds values past the limit into one row", () => {
+ const breakdown = groupByTraitValue("plan", rows, values, 1);
+
+ expect(breakdown.groups.map(group => group.value)).toEqual(["Pro"]);
+ expect(breakdown.other).toEqual({ values: 2, users: 2, sessions: 3, pageviews: 6, events: 3 });
+ });
+});
diff --git a/server/src/api/analytics/users/userScope.ts b/server/src/api/analytics/users/userScope.ts
new file mode 100644
index 000000000..390ff69f8
--- /dev/null
+++ b/server/src/api/analytics/users/userScope.ts
@@ -0,0 +1,375 @@
+import { FilterParams } from "@rybbit/shared";
+import { and, eq, inArray, sql, SQL } from "drizzle-orm";
+import { z } from "zod";
+import { db } from "../../../db/postgres/postgres.js";
+import { userProfiles } from "../../../db/postgres/schema.js";
+import { runAnalyticsQuery } from "../utils/analyticsQuery.js";
+import { effectiveUserId } from "../utils/effectiveUserId.js";
+import { buildFilteredSessionsCTE } from "../utils/sessionFilters.js";
+import { getTimeStatement, parseDateTimeMs, resolveTimeWindow, TimeWindowParams } from "../utils/timeWindow.js";
+
+/**
+ * Which users the Users page is looking at, beyond the shared period and
+ * filters: the quick filters (identified, new, a minimum session count), the
+ * search box, and one group of a trait breakdown.
+ *
+ * The list, its count, the trait breakdown and the rows inside each trait
+ * group all narrow through this module, so a group's count and the rows that
+ * open under it cannot disagree.
+ */
+
+/**
+ * A user is new in a period when nothing was seen from them in this many days
+ * before it. The window is fixed because the true definition (never seen
+ * before) would scan a site's whole history on every page load; 90 days is the
+ * retention report's default horizon.
+ */
+export const NEW_USER_LOOKBACK_DAYS = 90;
+
+/**
+ * Ceiling on the identified ids handed to ClickHouse as a query parameter.
+ * Parameters travel in the request URL, which ClickHouse caps at 1 MiB.
+ */
+export const MAX_SCOPED_USER_IDS = 10_000;
+
+const flag = z.enum(["true", "false"]).optional();
+
+/** The Users page's own query params, on top of the shared time and filter params. */
+export const userNarrowingSchema = z.object({
+ identified_only: flag,
+ new_only: flag,
+ min_sessions: z.coerce.number().int().min(1).max(1_000_000).optional(),
+ search: z.string().max(200).optional(),
+ search_field: z.string().max(50).optional(),
+ trait_key: z.string().min(1).max(200).optional(),
+ trait_value: z.string().max(2000).optional(),
+ trait_missing: flag,
+});
+
+export type UserNarrowingParams = {
+ identified_only?: string;
+ new_only?: string;
+ min_sessions?: string | number;
+ search?: string;
+ search_field?: string;
+ trait_key?: string;
+ trait_value?: string;
+ trait_missing?: string;
+};
+
+export type UsersQuerystring = FilterParams<UserNarrowingParams>;
+
+/** Identified ids resolved in Postgres that the ClickHouse query is limited to, or leaves out. */
+export interface UserScope {
+ matchingUserIds?: string[] | null;
+ excludedUserIds?: string[] | null;
+}
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+const shiftDate = (date: string, days: number) =>
+ new Date(Date.parse(`${date}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10);
+
+const toDateTimeParam = (ms: number) => new Date(ms).toISOString().slice(0, 19).replace("T", " ");
+
+/**
+ * The window of `days` that ends where the requested one begins, in the same
+ * form the request used. Null for an all-time request, which has no "before".
+ *
+ * Mirrors the precedence of `resolveTimeWindow`: a date range, then a datetime
+ * range, then past minutes.
+ */
+export function getLookbackParams(params: TimeWindowParams, days = NEW_USER_LOOKBACK_DAYS): TimeWindowParams | null {
+ const { time_zone } = params;
+ const usable = (candidate: TimeWindowParams) => !resolveTimeWindow(candidate).isAllTime;
+ let lookback: TimeWindowParams | null = null;
+
+ if (
+ params.start_date &&
+ params.end_date &&
+ usable({ start_date: params.start_date, end_date: params.end_date, time_zone })
+ ) {
+ // Both bounds are whole days in the site's timezone: the day before the
+ // period starts is the last day of the lookback.
+ lookback = {
+ start_date: shiftDate(params.start_date, -days),
+ end_date: shiftDate(params.start_date, -1),
+ time_zone,
+ };
+ } else if (
+ params.start_datetime &&
+ params.end_datetime &&
+ usable({ start_datetime: params.start_datetime, end_datetime: params.end_datetime, time_zone })
+ ) {
+ const start = parseDateTimeMs(params.start_datetime);
+ lookback = {
+ start_datetime: toDateTimeParam(start - days * DAY_MS),
+ end_datetime: toDateTimeParam(start),
+ time_zone,
+ };
+ } else if (params.past_minutes_start !== undefined && params.past_minutes_end !== undefined && usable(params)) {
+ const start = Number(params.past_minutes_start);
+ lookback = { past_minutes_start: start + days * 24 * 60, past_minutes_end: start, time_zone };
+ }
+
+ // Never hand back a window that would resolve to all time: the caller scans it.
+ return lookback && usable(lookback) ? lookback : null;
+}
+
+const EVENT_USER = effectiveUserId("events");
+
+/**
+ * Whether one-row-per-user aggregates (`effective_user_id`) were also seen in
+ * the lookback before the period. The inner `IN` keeps the lookback scan's
+ * result to people who are in the period at all.
+ *
+ * Null when the request is all time.
+ */
+export function buildSeenBeforeSubquery(query: TimeWindowParams): string | null {
+ const lookback = getLookbackParams(query);
+ if (!lookback) return null;
+
+ return `(
+ SELECT ${EVENT_USER}
+ FROM events
+ WHERE site_id = {siteId:Int32}
+ ${getTimeStatement(lookback)}
+ AND ${EVENT_USER} IN (
+ SELECT ${EVENT_USER}
+ FROM events
+ WHERE site_id = {siteId:Int32}
+ ${getTimeStatement(query)}
+ )
+ )`;
+}
+
+export interface UserNarrowing {
+ /** Predicates on raw `events` rows, each already prefixed with `AND`. */
+ eventConditions: string;
+ /**
+ * Predicates on one-row-per-user aggregates exposing `effective_user_id`,
+ * `identified_user_id` and `sessions`, each already prefixed with `AND`.
+ */
+ userConditions: string;
+ /** True when `userConditions` needs more than the identified flag, so a count has to aggregate per user. */
+ needsUserAggregate: boolean;
+ /** Bound parameters the fragments refer to. */
+ params: Record<string, unknown>;
+}
+
+const isUserIdSearch = (query: UserNarrowingParams) => !!query.search?.trim() && query.search_field === "user_id";
+
+/**
+ * Compiles the Users page's narrowing into SQL fragments. Every value is a
+ * bound parameter; nothing from the request is interpolated.
+ */
+export function buildUserNarrowing(query: UsersQuerystring, scope: UserScope = {}): UserNarrowing {
+ const eventConditions: string[] = [];
+ const userConditions: string[] = [];
+ const params: Record<string, unknown> = {};
+ let needsUserAggregate = false;
+
+ if (scope.matchingUserIds) {
+ eventConditions.push("AND events.identified_user_id IN ({matchingUserIds:Array(String)})");
+ params.matchingUserIds = scope.matchingUserIds;
+ }
+ if (scope.excludedUserIds?.length) {
+ eventConditions.push("AND events.identified_user_id NOT IN ({excludedUserIds:Array(String)})");
+ params.excludedUserIds = scope.excludedUserIds;
+ }
+ if (isUserIdSearch(query)) {
+ // The id a user is listed and linked by: the custom id when identified, the
+ // device id otherwise. Searched here because anonymous users have no profile
+ // in Postgres to search.
+ eventConditions.push(`AND positionCaseInsensitiveUTF8(${EVENT_USER}, {userIdSearch:String}) > 0`);
+ params.userIdSearch = query.search!.trim();
+ }
+
+ // Ids resolved in Postgres are identified by construction.
+ if (query.identified_only === "true" || scope.matchingUserIds) {
+ userConditions.push("AND identified_user_id != ''");
+ }
+ if (query.min_sessions !== undefined && query.min_sessions !== "") {
+ userConditions.push("AND sessions >= {minSessions:UInt32}");
+ params.minSessions = Number(query.min_sessions);
+ needsUserAggregate = true;
+ }
+ if (query.new_only === "true") {
+ const seenBefore = buildSeenBeforeSubquery(query);
+ // All time has no "before": everyone in it is new.
+ if (seenBefore) {
+ userConditions.push(`AND effective_user_id NOT IN ${seenBefore}`);
+ needsUserAggregate = true;
+ }
+ }
+
+ return {
+ eventConditions: eventConditions.join("\n "),
+ userConditions: userConditions.join("\n"),
+ needsUserAggregate,
+ params,
+ };
+}
+
+const SEARCHABLE_TRAITS = ["username", "name", "email"] as const;
+
+/**
+ * Resolves a name, username or email search to the identified ids whose
+ * profile matches. Those fields are traits, which live in Postgres and only
+ * exist for identified users. A user-id search is not resolved here: it runs
+ * in ClickHouse and covers anonymous users too (see `buildUserNarrowing`).
+ *
+ * `limited` reports that more profiles matched than can be passed to
+ * ClickHouse, so the caller can say the result is partial instead of
+ * presenting it as complete.
+ */
+export async function resolveSearchScope(
+ query: UserNarrowingParams,
+ siteId: number
+): Promise<{ matchingUserIds: string[] | null; limited: boolean }> {
+ const term = query.search?.trim();
+ if (!term || isUserIdSearch(query)) {
+ return { matchingUserIds: null, limited: false };
+ }
+
+ const field = SEARCHABLE_TRAITS.find(candidate => candidate === query.search_field) ?? "username";
+ const pattern = `%${term}%`;
+ const conditions: Record<(typeof SEARCHABLE_TRAITS)[number], SQL> = {
+ username: sql`traits->>'username' ILIKE ${pattern}`,
+ name: sql`traits->>'name' ILIKE ${pattern}`,
+ email: sql`traits->>'email' ILIKE ${pattern}`,
+ };
+
+ // Most recently updated first, so a capped result keeps the profiles most
+ // likely to be active in the period.
+ const rows = await db.execute<{ user_id: string }>(sql`
+ SELECT user_id FROM user_profiles
+ WHERE site_id = ${siteId} AND ${conditions[field]}
+ ORDER BY updated_at DESC
+ LIMIT ${MAX_SCOPED_USER_IDS + 1}
+ `);
+
+ const ids = rows.map(row => row.user_id);
+ return { matchingUserIds: ids.slice(0, MAX_SCOPED_USER_IDS), limited: ids.length > MAX_SCOPED_USER_IDS };
+}
+
+/** One identified user's activity in the period, or every anonymous user's summed (`identified_user_id` is ''). */
+export interface CohortRow {
+ identified_user_id: string;
+ users: number;
+ sessions: number;
+ pageviews: number;
+ events: number;
+}
+
+/**
+ * Activity in the period, one row per identified user plus one row for all
+ * anonymous users together. Binds `{siteId:Int32}` and `{cohortLimit:Int32}`.
+ *
+ * The anonymous row sorts first so the limit can only ever cut identified
+ * users, which is how the caller tells that there were too many.
+ */
+export function buildCohortQuery(query: UsersQuerystring, siteId: number, narrowing: UserNarrowing): string {
+ const timeStatement = getTimeStatement(query);
+ const filteredSessionsCTE = buildFilteredSessionsCTE(query.filters, siteId, timeStatement);
+
+ return `
+WITH ${filteredSessionsCTE ? `${filteredSessionsCTE},` : ""}
+UserStats AS (
+ SELECT
+ ${EVENT_USER} AS effective_user_id,
+ argMax(identified_user_id, timestamp) AS identified_user_id,
+ count(DISTINCT session_id) AS sessions,
+ countIf(type = 'pageview') AS pageviews,
+ countIf(type = 'custom_event') AS custom_events
+ FROM (
+ SELECT *
+ FROM events
+ ${filteredSessionsCTE ? "INNER JOIN FilteredSessions USING (session_id)" : ""}
+ WHERE
+ site_id = {siteId:Int32}
+ ${timeStatement}
+ ${narrowing.eventConditions}
+ ) AS events
+ GROUP BY effective_user_id
+)
+SELECT
+ identified_user_id,
+ count() AS users,
+ sum(sessions) AS sessions,
+ sum(pageviews) AS pageviews,
+ sum(custom_events) AS events
+FROM (
+ -- Filtered a level down: the sums above reuse the column names the conditions read.
+ SELECT *
+ FROM UserStats
+ WHERE 1 = 1
+ ${narrowing.userConditions}
+)
+GROUP BY identified_user_id
+ORDER BY identified_user_id = '' DESC, identified_user_id ASC
+LIMIT {cohortLimit:Int32}
+ `;
+}
+
+export type TraitCohort =
+ | { limited: true }
+ | {
+ limited: false;
+ /** The anonymous row, when there is one, and one row per identified user. */
+ rows: CohortRow[];
+ /** The trait's value for each identified user in the period that has one. */
+ values: Map<string, string>;
+ };
+
+const PROFILE_CHUNK = 5000;
+
+/**
+ * Joins the two stores for one trait: who was active in the period comes from
+ * ClickHouse, what each of those people's trait says comes from Postgres.
+ *
+ * ClickHouse goes first because the people active in a period are far fewer
+ * than a site's profiles. Past `MAX_SCOPED_USER_IDS` identified users the join
+ * is refused (`limited`) rather than answered from a sample.
+ */
+export async function resolveTraitCohort(
+ query: UsersQuerystring,
+ siteId: number,
+ traitKey: string,
+ scope: UserScope
+): Promise<TraitCohort> {
+ const narrowing = buildUserNarrowing(query, scope);
+ const rows = await runAnalyticsQuery<CohortRow>({
+ query: buildCohortQuery(query, siteId, narrowing),
+ // One more than the ceiling shows it was passed; one more again for the anonymous row.
+ params: { siteId, cohortLimit: MAX_SCOPED_USER_IDS + 2, ...narrowing.params },
+ });
+
+ const identifiedIds = rows.filter(row => row.identified_user_id !== "").map(row => row.identified_user_id);
+ if (identifiedIds.length > MAX_SCOPED_USER_IDS) {
+ return { limited: true };
+ }
+
+ const values = new Map<string, string>();
+ for (let start = 0; start < identifiedIds.length; start += PROFILE_CHUNK) {
+ const profiles = await db
+ .select({
+ userId: userProfiles.userId,
+ value: sql<string | null>`${userProfiles.traits}->>${traitKey}`,
+ })
+ .from(userProfiles)
+ .where(
+ and(
+ eq(userProfiles.siteId, siteId),
+ inArray(userProfiles.userId, identifiedIds.slice(start, start + PROFILE_CHUNK)),
+ // A key that is absent and a key set to null both mean the user has no value.
+ sql`${userProfiles.traits}->>${traitKey} IS NOT NULL`
+ )
+ );
+ for (const profile of profiles) {
+ if (profile.value !== null) values.set(profile.userId, profile.value);
+ }
+ }
+
+ return { limited: false, rows, values };
+}
diff --git a/server/src/api/analytics/users/userTraitHandlers.test.ts b/server/src/api/analytics/users/userTraitHandlers.test.ts
new file mode 100644
index 000000000..9da7cea06
--- /dev/null
+++ b/server/src/api/analytics/users/userTraitHandlers.test.ts
@@ -0,0 +1,293 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ clickhouseQuery: vi.fn(),
+}));
+
+vi.mock("../../../db/clickhouse/clickhouse.js", () => ({
+ clickhouse: { query: mocks.clickhouseQuery },
+}));
+
+vi.mock("../../../db/postgres/postgres.js", async () => {
+ const { PGlite } = await import("@electric-sql/pglite");
+ const { drizzle } = await import("drizzle-orm/pglite");
+ const schema = await import("../../../db/postgres/schema.js");
+ const client = new PGlite();
+ const real = drizzle(client, { schema });
+ // postgres-js hands back the rows themselves from execute(); PGlite wraps them.
+ const db = new Proxy(real, {
+ get(target, prop) {
+ if (prop === "execute") return async (query: any) => (await target.execute(query)).rows;
+ const value = (target as any)[prop];
+ return typeof value === "function" ? value.bind(target) : value;
+ },
+ });
+ return { db, sql: client };
+});
+
+import { sql as pgClient } from "../../../db/postgres/postgres.js";
+import { getUserTraitBreakdown } from "./getUserTraitBreakdown.js";
+import { getUsers } from "./getUsers.js";
+import { MAX_SCOPED_USER_IDS } from "./userScope.js";
+
+const pg = pgClient as unknown as { exec: (query: string) => Promise<unknown>; close: () => Promise<void> };
+
+const SITE = 1;
+const BULK_SITE = 2;
+const period = { filters: "", start_date: "2026-09-01", end_date: "2026-09-30", time_zone: "UTC" };
+
+const profile = (id: string, traits: Record<string, unknown>) =>
+ `(${SITE}, '${id}', '${JSON.stringify(traits)}'::jsonb)`;
+
+function replyStub() {
+ const reply: any = { statusCode: 200 };
+ reply.status = (code: number) => {
+ reply.statusCode = code;
+ return reply;
+ };
+ reply.send = (body: unknown) => {
+ reply.body = body;
+ return reply;
+ };
+ return reply;
+}
+
+const request = (siteId: number, query: Record<string, unknown>) =>
+ ({ params: { siteId: String(siteId) }, query, log: { error: vi.fn(), debug: vi.fn() } }) as any;
+
+type Call = { query: string; query_params: Record<string, any> };
+const calls = (): Call[] => mocks.clickhouseQuery.mock.calls.map(([call]) => call);
+const isCohort = (call: Call) => call.query.includes("UserStats AS");
+const isList = (call: Call) => call.query.includes("AggregatedUsers AS");
+
+const cohortRow = (identified_user_id: string, users: number, sessions: number) => ({
+ identified_user_id,
+ users,
+ sessions,
+ pageviews: sessions * 3,
+ events: sessions,
+});
+
+// Who ClickHouse says was active in the period. "dormant" has a profile but is not among them.
+const activeCohort = [
+ cohortRow("", 40, 44),
+ cohortRow("ann", 1, 9),
+ cohortRow("bob", 1, 3),
+ cohortRow("cy", 1, 2),
+ cohortRow("dee", 1, 1),
+ cohortRow("eve", 1, 4),
+];
+
+/** Answers ClickHouse: the cohort for a cohort query, one list row per requested id, and a count. */
+function answerWith(cohort: unknown[]) {
+ mocks.clickhouseQuery.mockImplementation(async (call: Call) => {
+ let rows: unknown[] = [{ total_count: 99 }];
+ if (isCohort(call)) rows = cohort;
+ else if (isList(call)) {
+ rows = (call.query_params.matchingUserIds ?? ["anon-device"]).map((id: string) => ({
+ user_id: `device-${id}`,
+ identified_user_id: call.query_params.matchingUserIds ? id : "",
+ sessions: 1,
+ }));
+ }
+ return { json: async () => rows };
+ });
+}
+
+beforeAll(async () => {
+ await pg.exec(`
+ CREATE TABLE user_profiles (
+ site_id integer NOT NULL,
+ user_id text NOT NULL,
+ traits jsonb DEFAULT '{}'::jsonb,
+ created_at timestamp DEFAULT now() NOT NULL,
+ updated_at timestamp DEFAULT now() NOT NULL,
+ PRIMARY KEY (site_id, user_id)
+ );
+ INSERT INTO user_profiles (site_id, user_id, traits) VALUES
+ ${profile("ann", { name: "Ann Lee", plan: "Pro" })},
+ ${profile("bob", { name: "Bob Marsh", plan: "Pro" })},
+ ${profile("cy", { name: "Cy Annan", plan: "Free" })},
+ ${profile("dee", { name: "Dee Ruiz", plan: null })},
+ ${profile("eve", { name: "Eve Stone" })},
+ ${profile("dormant", { name: "Dormant Dora", plan: "Pro" })};
+ INSERT INTO user_profiles (site_id, user_id, traits)
+ SELECT ${BULK_SITE}, 'bulk-' || n, '{"name": "Bulk Person"}'::jsonb
+ FROM generate_series(1, ${MAX_SCOPED_USER_IDS + 1}) AS n;
+ `);
+});
+
+afterAll(async () => {
+ await pg.close();
+});
+
+beforeEach(() => {
+ mocks.clickhouseQuery.mockReset();
+ answerWith(activeCohort);
+});
+
+describe("getUserTraitBreakdown", () => {
+ it("groups the people active in the period by the trait stored in Postgres", async () => {
+ const reply = replyStub();
+ await getUserTraitBreakdown(request(SITE, { ...period, key: "plan" }), reply);
+
+ expect(reply.body.data).toEqual({
+ key: "plan",
+ limited: false,
+ limit: MAX_SCOPED_USER_IDS,
+ totals: { users: 45, identified: 5, sessions: 63, pageviews: 189, events: 63 },
+ groups: [
+ // Dormant Dora is Pro too, but was not here in the period.
+ { value: "Pro", users: 2, sessions: 12, pageviews: 36, events: 12 },
+ { value: "Free", users: 1, sessions: 2, pageviews: 6, events: 2 },
+ ],
+ other: null,
+ // Anonymous users, the user whose plan is null and the user without the key.
+ none: { users: 42, sessions: 49, pageviews: 147, events: 49 },
+ searchLimited: false,
+ });
+ });
+
+ it("asks ClickHouse for one identified user past the ceiling, and passes the quick filters on", async () => {
+ await getUserTraitBreakdown(request(SITE, { ...period, key: "plan", min_sessions: "3" }), replyStub());
+
+ expect(calls()).toHaveLength(1);
+ expect(calls()[0].query_params).toEqual({ siteId: SITE, cohortLimit: MAX_SCOPED_USER_IDS + 2, minSessions: 3 });
+ expect(calls()[0].query).toContain("AND sessions >= {minSessions:UInt32}");
+ });
+
+ it("refuses to group a sample when too many identified users were active", async () => {
+ answerWith([
+ cohortRow("", 5, 5),
+ ...Array.from({ length: MAX_SCOPED_USER_IDS + 1 }, (_, index) => cohortRow(`u${index}`, 1, 1)),
+ ]);
+ const reply = replyStub();
+ await getUserTraitBreakdown(request(SITE, { ...period, key: "plan" }), reply);
+
+ expect(reply.body.data).toMatchObject({ limited: true, limit: MAX_SCOPED_USER_IDS, totals: null, groups: [] });
+ });
+
+ it("groups only the searched users", async () => {
+ // The cohort ClickHouse returns once it is limited to the two profiles named Ann*/Annan.
+ answerWith([cohortRow("ann", 1, 9), cohortRow("cy", 1, 2)]);
+ const reply = replyStub();
+ await getUserTraitBreakdown(request(SITE, { ...period, key: "plan", search: "ANN", search_field: "name" }), reply);
+
+ expect(calls()[0].query_params.matchingUserIds.sort()).toEqual(["ann", "cy"]);
+ expect(reply.body.data.groups.map((group: { value: string }) => group.value)).toEqual(["Free", "Pro"]);
+ expect(reply.body.data.none).toEqual({ users: 0, sessions: 0, pageviews: 0, events: 0 });
+ });
+
+ it("needs a key", async () => {
+ const reply = replyStub();
+ await getUserTraitBreakdown(request(SITE, period), reply);
+
+ expect(reply.statusCode).toBe(400);
+ expect(mocks.clickhouseQuery).not.toHaveBeenCalled();
+ });
+});
+
+describe("getUsers for a trait group", () => {
+ it("lists the active users whose trait has the value, with their traits", async () => {
+ const reply = replyStub();
+ await getUsers(request(SITE, { ...period, trait_key: "plan", trait_value: "Pro" }), reply);
+
+ const list = calls().find(isList)!;
+ expect(list.query_params.matchingUserIds.sort()).toEqual(["ann", "bob"]);
+ expect(list.query_params.excludedUserIds).toBeUndefined();
+ expect(reply.body.data.map((row: any) => [row.identified_user_id, row.traits.name])).toEqual([
+ ["ann", "Ann Lee"],
+ ["bob", "Bob Marsh"],
+ ]);
+ expect(reply.body.totalCount).toBe(99);
+ });
+
+ it("lists everyone without a value by leaving out those who have one", async () => {
+ await getUsers(request(SITE, { ...period, trait_key: "plan", trait_missing: "true" }), replyStub());
+
+ const list = calls().find(isList)!;
+ expect(list.query_params.excludedUserIds.sort()).toEqual(["ann", "bob", "cy"]);
+ expect(list.query_params.matchingUserIds).toBeUndefined();
+ // Not forced to identified: anonymous users have no plan either.
+ expect(list.query).not.toContain("AND identified_user_id != ''");
+ });
+
+ it("narrows a search to the matches without a value, in one list", async () => {
+ // Ann Lee, Dee Ruiz and Eve Stone have an "e" in their name and were all active.
+ answerWith([cohortRow("ann", 1, 9), cohortRow("dee", 1, 1), cohortRow("eve", 1, 4)]);
+ await getUsers(
+ request(SITE, { ...period, trait_key: "plan", trait_missing: "true", search: "e", search_field: "name" }),
+ replyStub()
+ );
+
+ expect(calls().find(isCohort)!.query_params.matchingUserIds.sort()).toEqual(["ann", "dee", "eve"]);
+ const list = calls().find(isList)!;
+ // Ann has a plan; Dee's is null and Eve has none.
+ expect(list.query_params.matchingUserIds.sort()).toEqual(["dee", "eve"]);
+ expect(list.query_params.excludedUserIds).toBeUndefined();
+ });
+
+ it("answers an empty group without asking ClickHouse for the list", async () => {
+ const reply = replyStub();
+ await getUsers(request(SITE, { ...period, trait_key: "plan", trait_value: "Enterprise" }), reply);
+
+ expect(reply.body).toMatchObject({ data: [], totalCount: 0 });
+ expect(calls().filter(isList)).toHaveLength(0);
+ });
+
+ it("says so instead of listing when the period has too many identified users", async () => {
+ answerWith(Array.from({ length: MAX_SCOPED_USER_IDS + 1 }, (_, index) => cohortRow(`u${index}`, 1, 1)));
+ const reply = replyStub();
+ await getUsers(request(SITE, { ...period, trait_key: "plan", trait_value: "Pro" }), reply);
+
+ expect(reply.body).toMatchObject({ data: [], totalCount: 0, breakdownLimited: true });
+ });
+
+ it.each([
+ [{ trait_key: "plan" }, "trait_key needs trait_value or trait_missing=true"],
+ [{ min_sessions: "0" }, expect.any(String)],
+ [{ new_only: "1" }, expect.any(String)],
+ ])("rejects %o", async (params, error) => {
+ const reply = replyStub();
+ await getUsers(request(SITE, { ...period, ...params }), reply);
+
+ expect(reply.statusCode).toBe(400);
+ expect(reply.body.error).toEqual(error);
+ expect(mocks.clickhouseQuery).not.toHaveBeenCalled();
+ });
+});
+
+describe("getUsers search", () => {
+ it("resolves a name search to profile ids, ignoring case", async () => {
+ const reply = replyStub();
+ await getUsers(request(SITE, { ...period, search: "marsh", search_field: "name" }), reply);
+
+ expect(calls().every(call => call.query_params.matchingUserIds?.join() === "bob")).toBe(true);
+ expect(reply.body.searchLimited).toBe(false);
+ });
+
+ it("searches ids in ClickHouse, where anonymous users are, without touching profiles", async () => {
+ await getUsers(request(SITE, { ...period, search: "a1d7", search_field: "user_id" }), replyStub());
+
+ const list = calls().find(isList)!;
+ expect(list.query_params.userIdSearch).toBe("a1d7");
+ expect(list.query_params.matchingUserIds).toBeUndefined();
+ expect(list.query).not.toContain("AND identified_user_id != ''");
+ });
+
+ it("answers a search nobody matches without asking ClickHouse", async () => {
+ const reply = replyStub();
+ await getUsers(request(SITE, { ...period, search: "zzz", search_field: "email" }), reply);
+
+ expect(reply.body).toMatchObject({ data: [], totalCount: 0 });
+ expect(mocks.clickhouseQuery).not.toHaveBeenCalled();
+ });
+
+ it("flags a search that matches more profiles than it can look up", async () => {
+ const reply = replyStub();
+ await getUsers(request(BULK_SITE, { ...period, search: "bulk", search_field: "name" }), reply);
+
+ expect(calls().find(isList)!.query_params.matchingUserIds).toHaveLength(MAX_SCOPED_USER_IDS);
+ expect(reply.body.searchLimited).toBe(true);
+ });
+});
diff --git a/server/src/api/routes.ts b/server/src/api/routes.ts
index 64138b206..08e790353 100644
--- a/server/src/api/routes.ts
+++ b/server/src/api/routes.ts
@@ -44,17 +44,25 @@ import {
generateCustomQuery,
getEventBucketed,
getEventNames,
+ getEventNameStats,
+ getEventsOverview,
+ getSilentEvents,
getAutocaptureEvents,
getAutocaptureValues,
getEventProperties,
getEvents,
getFunnel,
getFunnelStepSessions,
+ getFunnelSummaries,
getFunnels,
+ getGoalPreview,
getGoalSessions,
getGoalTimeSeries,
getGoals,
+ getGoalsSummary,
getJourneys,
+ getJourneySessions,
+ getJourneySummary,
getLiveUsercount,
getMetric,
getMetricLite,
@@ -67,6 +75,9 @@ import {
getSiteCardsLite,
getSiteCards,
getPageTitles,
+ getPages,
+ getPagesSummary,
+ getPageTrends,
getPerformanceByDimension,
getPerformanceOverview,
getPerformanceTimeSeries,
@@ -74,13 +85,21 @@ import {
getSession,
getSessionLocations,
getSessions,
+ getSessionsSummary,
getSiteEventCount,
+ getUserGoals,
getUserInfo,
+ getUserRepeatedError,
+ getUserSegments,
getUserSessionCount,
+ getUserSessionGoals,
+ getUserSummary,
+ getUserTraitBreakdown,
getUserTraitKeys,
getUserTraitValueUsers,
getUserTraitValues,
getUsers,
+ getUsersSummary,
identifyUser,
runCustomQuery,
runDashboardCardQuery,
@@ -279,6 +298,8 @@ const publicSegmentsRead = publicSite("segments:read");
// one query per card), and /generate spends OpenRouter credit. Cap per user.
const customQueryRateLimit = { max: 60, timeWindow: "1 minute" };
const generateQueryRateLimit = { max: 20, timeWindow: "1 minute" };
+// The inline goal form asks for a preview as the pattern is typed (debounced).
+const goalPreviewRateLimit = { max: 60, timeWindow: "1 minute" };
const withRateLimit = <T extends { preHandler: unknown; config?: object }>(
opts: T,
limit: { max: number; timeWindow: string }
@@ -300,6 +321,9 @@ async function analyticsRoutes(fastify: FastifyInstance) {
fastify.get("/sites/:siteId/metric-lite", cachedAnalyticsRead, getMetricLite);
fastify.get("/sites/:siteId/metric", cachedAnalyticsRead, getMetric);
fastify.get("/sites/:siteId/page-titles", cachedAnalyticsRead, getPageTitles);
+ fastify.get("/sites/:siteId/pages", cachedAnalyticsRead, getPages);
+ fastify.get("/sites/:siteId/pages/summary", cachedAnalyticsRead, getPagesSummary);
+ fastify.get("/sites/:siteId/pages/trends", cachedAnalyticsRead, getPageTrends);
fastify.get("/sites/:siteId/errors/names", publicAnalyticsRead, getErrorNames);
fastify.get("/sites/:siteId/errors/events", publicAnalyticsRead, getErrorEvents);
fastify.get("/sites/:siteId/errors/time-series", publicAnalyticsRead, getErrorBucketed);
@@ -307,31 +331,48 @@ async function analyticsRoutes(fastify: FastifyInstance) {
fastify.get("/sites/:siteId/has-data", publicSitesRead, getSiteHasData);
fastify.get("/sites/:siteId/is-public", publicSitesRead, getSiteIsPublic);
fastify.get("/sites/:siteId/sessions", publicSessionsRead, getSessions);
+ fastify.get("/sites/:siteId/sessions/summary", publicSessionsRead, getSessionsSummary);
fastify.get("/sites/:siteId/sessions/:sessionId", publicSessionsRead, getSession);
fastify.get("/sites/:siteId/events", publicEventsRead, getEvents);
fastify.get("/sites/:siteId/events/time-series", publicEventsRead, getEventBucketed);
fastify.get("/sites/:siteId/events/count", publicEventsRead, getSiteEventCount);
fastify.get("/sites/:siteId/users", publicUsersRead, getUsers);
+ fastify.get("/sites/:siteId/users/summary", publicUsersRead, getUsersSummary);
fastify.get("/sites/:siteId/users/session-count", publicUsersRead, getUserSessionCount);
fastify.get("/sites/:siteId/users/:userId", publicUsersRead, getUserInfo);
+ fastify.get("/sites/:siteId/users/:userId/summary", publicUsersRead, getUserSummary);
+ fastify.get("/sites/:siteId/users/:userId/goals", publicUsersRead, getUserGoals);
+ fastify.get("/sites/:siteId/users/:userId/session-goals", publicUsersRead, getUserSessionGoals);
+ fastify.get("/sites/:siteId/users/:userId/segments", publicUsersRead, getUserSegments);
+ fastify.get("/sites/:siteId/users/:userId/repeated-error", publicUsersRead, getUserRepeatedError);
fastify.post("/sites/:siteId/users/identify", site("users:write"), identifyUser);
fastify.put("/sites/:siteId/users/:userId/traits", site("users:write"), updateUserTraits);
fastify.delete("/sites/:siteId/users/:userId", site("users:delete"), deleteUser);
fastify.get("/sites/:siteId/user-traits/keys", publicUsersRead, getUserTraitKeys);
fastify.get("/sites/:siteId/user-traits/values", publicUsersRead, getUserTraitValues);
fastify.get("/sites/:siteId/user-traits/users", publicUsersRead, getUserTraitValueUsers);
+ fastify.get("/sites/:siteId/user-traits/breakdown", publicUsersRead, getUserTraitBreakdown);
fastify.get("/sites/:siteId/sessions/locations", publicSessionsRead, getSessionLocations);
fastify.get("/sites/:siteId/funnels", publicFunnelsRead, getFunnels);
+ fastify.get("/sites/:siteId/funnels/summary", publicFunnelsRead, getFunnelSummaries);
fastify.get("/sites/:siteId/journeys", publicAnalyticsRead, getJourneys);
+ fastify.get("/sites/:siteId/journeys/summary", publicAnalyticsRead, getJourneySummary);
+ fastify.get("/sites/:siteId/journeys/sessions", publicSessionsRead, getJourneySessions);
fastify.post("/sites/:siteId/funnels/analyze", publicFunnelsRead, getFunnel);
fastify.post("/sites/:siteId/funnels/:stepNumber/sessions", publicFunnelsRead, getFunnelStepSessions);
fastify.post("/sites/:siteId/funnels", site("funnels:write"), createFunnel);
fastify.delete("/sites/:siteId/funnels/:funnelId", site("funnels:write"), deleteFunnel);
fastify.get("/sites/:siteId/goals", publicGoalsRead, getGoals);
+ fastify.get("/sites/:siteId/goals/summary", publicGoalsRead, getGoalsSummary);
fastify.get("/sites/:siteId/goals/time-series", publicGoalsRead, getGoalTimeSeries);
fastify.get("/sites/:siteId/goals/:goalId/sessions", publicGoalsRead, getGoalSessions);
fastify.post("/sites/:siteId/goals", site("goals:write"), createGoal);
+ fastify.post(
+ "/sites/:siteId/goals/preview",
+ withRateLimit(site("goals:write"), goalPreviewRateLimit),
+ getGoalPreview
+ );
fastify.delete("/sites/:siteId/goals/:goalId", site("goals:write"), deleteGoal);
fastify.put("/sites/:siteId/goals/:goalId", site("goals:write"), updateGoal);
// Timeline annotations. Read is public-guarded so public dashboards and
@@ -370,6 +411,9 @@ async function analyticsRoutes(fastify: FastifyInstance) {
fastify.delete("/sites/:siteId/experiments/:experimentId", site("experiments:write"), deleteExperiment);
fastify.get("/sites/:siteId/experiments/:experimentId/results", site("experiments:read"), getExperimentResults);
fastify.get("/sites/:siteId/events/names", cachedEventsRead, getEventNames);
+ fastify.get("/sites/:siteId/events/names/stats", cachedEventsRead, getEventNameStats);
+ fastify.get("/sites/:siteId/events/overview", cachedEventsRead, getEventsOverview);
+ fastify.get("/sites/:siteId/events/silent", cachedEventsRead, getSilentEvents);
fastify.get("/sites/:siteId/events/properties", publicEventsRead, getEventProperties);
fastify.get("/sites/:siteId/events/autocapture", cachedEventsRead, getAutocaptureEvents);
fastify.get("/sites/:siteId/events/autocapture-values", publicEventsRead, getAutocaptureValues);