🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
new events page (#845)
Goldflag25d253b9b56c
diff --git a/client/package-lock.json b/client/package-lock.jsonindex 9aae648a7..bdcf0fd1d 100644--- a/client/package-lock.json+++ b/client/package-lock.json@@ -39,6 +39,7 @@"@tanstack/react-query": "5.76.0","@tanstack/react-query-devtools": "5.76.0","@tanstack/react-table": "8.21.3",+ "@tanstack/react-virtual": "3.13.18","@types/country-flag-icons": "1.2.2","@types/papaparse": "^5.5.0","@uidotdev/usehooks": "2.4.1",@@ -2050,30 +2051,6 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0"}},- "node_modules/@nivo/annotations/node_modules/react-dom": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",- "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0",- "scheduler": "^0.23.2"- },- "peerDependencies": {- "react": "^18.3.1"- }- },- "node_modules/@nivo/annotations/node_modules/scheduler": {- "version": "0.23.2",- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",- "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0"- }- },"node_modules/@nivo/axes": {"version": "0.96.0","resolved": "https://registry.npmjs.org/@nivo/axes/-/axes-0.96.0.tgz",@@ -2154,30 +2131,6 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0"}},- "node_modules/@nivo/axes/node_modules/react-dom": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",- "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0",- "scheduler": "^0.23.2"- },- "peerDependencies": {- "react": "^18.3.1"- }- },- "node_modules/@nivo/axes/node_modules/scheduler": {- "version": "0.23.2",- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",- "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0"- }- },"node_modules/@nivo/bar": {"version": "0.96.0","resolved": "https://registry.npmjs.org/@nivo/bar/-/bar-0.96.0.tgz",@@ -2265,30 +2218,6 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0"}},- "node_modules/@nivo/bar/node_modules/react-dom": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",- "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0",- "scheduler": "^0.23.2"- },- "peerDependencies": {- "react": "^18.3.1"- }- },- "node_modules/@nivo/bar/node_modules/scheduler": {- "version": "0.23.2",- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",- "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0"- }- },"node_modules/@nivo/calendar": {"version": "0.96.0","resolved": "https://registry.npmjs.org/@nivo/calendar/-/calendar-0.96.0.tgz",@@ -2431,30 +2360,6 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0"}},- "node_modules/@nivo/core/node_modules/react-dom": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",- "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0",- "scheduler": "^0.23.2"- },- "peerDependencies": {- "react": "^18.3.1"- }- },- "node_modules/@nivo/core/node_modules/scheduler": {- "version": "0.23.2",- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",- "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0"- }- },"node_modules/@nivo/legends": {"version": "0.96.0","resolved": "https://registry.npmjs.org/@nivo/legends/-/legends-0.96.0.tgz",@@ -2555,30 +2460,6 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0"}},- "node_modules/@nivo/line/node_modules/react-dom": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",- "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0",- "scheduler": "^0.23.2"- },- "peerDependencies": {- "react": "^18.3.1"- }- },- "node_modules/@nivo/line/node_modules/scheduler": {- "version": "0.23.2",- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",- "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0"- }- },"node_modules/@nivo/scales": {"version": "0.96.0","resolved": "https://registry.npmjs.org/@nivo/scales/-/scales-0.96.0.tgz",@@ -2676,30 +2557,6 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0"}},- "node_modules/@nivo/text/node_modules/react-dom": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",- "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0",- "scheduler": "^0.23.2"- },- "peerDependencies": {- "react": "^18.3.1"- }- },- "node_modules/@nivo/text/node_modules/scheduler": {- "version": "0.23.2",- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",- "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0"- }- },"node_modules/@nivo/theming": {"version": "0.96.0","resolved": "https://registry.npmjs.org/@nivo/theming/-/theming-0.96.0.tgz",@@ -2786,30 +2643,6 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0"}},- "node_modules/@nivo/tooltip/node_modules/react-dom": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",- "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0",- "scheduler": "^0.23.2"- },- "peerDependencies": {- "react": "^18.3.1"- }- },- "node_modules/@nivo/tooltip/node_modules/scheduler": {- "version": "0.23.2",- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",- "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",- "license": "MIT",- "peer": true,- "dependencies": {- "loose-envify": "^1.1.0"- }- },"node_modules/@nivo/voronoi": {"version": "0.96.0","resolved": "https://registry.npmjs.org/@nivo/voronoi/-/voronoi-0.96.0.tgz",@@ -5410,6 +5243,23 @@"react-dom": ">=16.8"}},+ "node_modules/@tanstack/react-virtual": {+ "version": "3.13.18",+ "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.18.tgz",+ "integrity": "sha512-dZkhyfahpvlaV0rIKnvQiVoWPyURppl6w4m9IwMDpuIjcJ1sD9YGWrt0wISvgU7ewACXx2Ct46WPgI6qAD4v6A==",+ "license": "MIT",+ "dependencies": {+ "@tanstack/virtual-core": "3.13.18"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/@tanstack/table-core": {"version": "8.21.3","resolved": "https://registry.npmjs.org/@tanstack/table-core/-/table-core-8.21.3.tgz",@@ -5423,6 +5273,16 @@"url": "https://github.com/sponsors/tannerlinsley"}},+ "node_modules/@tanstack/virtual-core": {+ "version": "3.13.18",+ "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.18.tgz",+ "integrity": "sha512-Mx86Hqu1k39icq2Zusq+Ey2J6dDWTjDvEv43PJtRCoEYTLyfaPnxIQ6iy7YAOK0NV/qOEmZQ/uCufrppZxTgcg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ }+ },"node_modules/@tsconfig/svelte": {"version": "1.0.13","resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-1.0.13.tgz",@@ -5845,6 +5705,7 @@"version": "19.2.7","resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.7.tgz","integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==",+ "dev": true,"license": "MIT","dependencies": {"csstype": "^3.2.2"@@ -5854,7 +5715,7 @@"version": "19.2.3","resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz","integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",- "devOptional": true,+ "dev": true,"license": "MIT","peerDependencies": {"@types/react": "^19.2.0"diff --git a/client/package.json b/client/package.jsonindex ae1a38957..aac02f7aa 100644--- a/client/package.json+++ b/client/package.json@@ -43,6 +43,7 @@"@tanstack/react-query": "5.76.0","@tanstack/react-query-devtools": "5.76.0","@tanstack/react-table": "8.21.3",+ "@tanstack/react-virtual": "3.13.18","@types/country-flag-icons": "1.2.2","@types/papaparse": "^5.5.0","@uidotdev/usehooks": "2.4.1",diff --git a/client/src/api/analytics/endpoints/events.ts b/client/src/api/analytics/endpoints/events.tsindex 6feb3c8de..1c30d16dc 100644--- a/client/src/api/analytics/endpoints/events.ts+++ b/client/src/api/analytics/endpoints/events.ts@@ -1,34 +1,49 @@+import { Filter } from "@rybbit/shared";import { authedFetch } from "../../utils";-import { BucketedParams, CommonApiParams, PaginationParams, toBucketedQueryParams, toQueryParams } from "./types";-+import {+ BucketedParams,+ CommonApiParams,+ toBucketedQueryParams,+ toQueryParams,+} from "./types";// Event typeexport type Event = {timestamp: string;event_name: string;properties: string;+ session_id: string;user_id: string;+ identified_user_id: string;hostname: string;pathname: string;querystring: string;page_title: string;referrer: string;browser: string;+ browser_version: string;operating_system: string;+ operating_system_version: string;+ language: string;country: string;+ region: string;+ city: string;+ lat: number;+ lon: number;+ screen_width: number;+ screen_height: number;device_type: string;type: string;};-// Events response with pagination-export interface EventsResponse {+// Response types for cursor-based API+export interface NewEventsResponse {data: Event[];- pagination: {- total: number;- page: number;- pageSize: number;- totalPages: number;- };+}++export interface CursorEventsResponse {+ data: Event[];+ cursor: { hasMore: boolean; oldestTimestamp: string | null };}// Event name with count@@ -58,38 +73,78 @@ export type EventBucketedPoint = {event_count: number;};-export interface EventsParams extends CommonApiParams, PaginationParams {- pageSize?: number;-}-export interface EventBucketedParams extends BucketedParams {limit?: number;}+// Site-level event count breakdown by type+export type SiteEventCountPoint = {+ time: string;+ pageview_count: number;+ custom_event_count: number;+ performance_count: number;+ outbound_count: number;+ error_count: number;+ button_click_count: number;+ copy_count: number;+ form_submit_count: number;+ input_change_count: number;+ event_count: number;+};++export type SiteEventCountParams = BucketedParams;export interface EventPropertiesParams extends CommonApiParams {eventName: string;}/**- * Fetch paginated events- * GET /api/events/:site+ * Poll for events newer than sinceTimestamp (Realtime mode).+ * Only sends filters — no time range.*/-export async function fetchEvents(+export async function fetchNewEvents(site: string | number,- params: EventsParams-): Promise<EventsResponse> {- const queryParams = {+ params: { sinceTimestamp: string; filters?: Filter[]; timeZone: string }+): Promise<NewEventsResponse> {+ const queryParams: Record<string, any> = {+ since_timestamp: params.sinceTimestamp,+ time_zone: params.timeZone,+ start_date: "",+ end_date: "",+ };+ if (params.filters?.length) {+ queryParams.filters = params.filters;+ }++ return authedFetch<NewEventsResponse>(+ `/sites/${site}/events`,+ queryParams+ );+}++/**+ * Cursor-based fetch for historical scrolling / initial load.+ */+export async function fetchEventsCursor(+ site: string | number,+ params: CommonApiParams & {+ beforeTimestamp?: string;+ pageSize?: number;+ }+): Promise<CursorEventsResponse> {+ const queryParams: Record<string, any> = {...toQueryParams(params),- page: params.page,- page_size: params.pageSize ?? params.limit,+ page_size: params.pageSize ?? 50,};- const response = await authedFetch<EventsResponse>(+ if (params.beforeTimestamp) {+ queryParams.before_timestamp = params.beforeTimestamp;+ }++ return authedFetch<CursorEventsResponse>(`/sites/${site}/events`,queryParams);- return response;}/**@@ -162,3 +217,17 @@ export async function fetchEventBucketed(return response.data;}+/**+ * Fetch site-level event count breakdown by type+ * GET /sites/:site/events/count+ */+export async function fetchSiteEventCount(+ site: string | number,+ params: SiteEventCountParams+): Promise<SiteEventCountPoint[]> {+ const response = await authedFetch<{ data: SiteEventCountPoint[] }>(+ `/sites/${site}/events/count`,+ toBucketedQueryParams(params)+ );+ return response.data;+}diff --git a/client/src/api/analytics/endpoints/index.ts b/client/src/api/analytics/endpoints/index.tsindex f171400d2..b0e2a7775 100644--- a/client/src/api/analytics/endpoints/index.ts+++ b/client/src/api/analytics/endpoints/index.ts@@ -11,17 +11,27 @@ export type {} from "./overview";// Events endpoints-export { fetchEventBucketed, fetchEvents, fetchEventNames, fetchEventProperties, fetchOutboundLinks } from "./events";+export {+ fetchEventBucketed,+ fetchNewEvents,+ fetchEventsCursor,+ fetchEventNames,+ fetchEventProperties,+ fetchOutboundLinks,+ fetchSiteEventCount,+} from "./events";export type {Event,EventBucketedPoint,- EventsResponse,+ NewEventsResponse,+ CursorEventsResponse,EventName,EventProperty,OutboundLink,EventBucketedParams,- EventsParams,EventPropertiesParams,+ SiteEventCountPoint,+ SiteEventCountParams,} from "./events";diff --git a/client/src/api/analytics/endpoints/sessions.ts b/client/src/api/analytics/endpoints/sessions.tsindex 52881dce2..86df22151 100644--- a/client/src/api/analytics/endpoints/sessions.ts+++ b/client/src/api/analytics/endpoints/sessions.ts@@ -66,7 +66,9 @@ export interface SessionDetails {channel: string;session_end: string;session_start: string;+ session_duration: number;pageviews: number;+ events: number;entry_page: string;exit_page: string;ip: string;@@ -116,6 +118,7 @@ export type LiveSessionLocation = {export interface SessionsParams extends CommonApiParams, PaginationParams {userId?: string;+ sessionId?: string;identifiedOnly?: boolean;minPageviews?: number;minEvents?: number;@@ -142,6 +145,7 @@ export async function fetchSessions(page: params.page,limit: params.limit,user_id: params.userId,+ session_id: params.sessionId,identified_only: params.identifiedOnly,min_pageviews: params.minPageviews,min_events: params.minEvents,diff --git a/client/src/api/analytics/hooks/events/useGetEvents.ts b/client/src/api/analytics/hooks/events/useGetEvents.tsindex 88f5a7643..50d159781 100644--- a/client/src/api/analytics/hooks/events/useGetEvents.ts+++ b/client/src/api/analytics/hooks/events/useGetEvents.ts@@ -1,61 +1,88 @@import { useInfiniteQuery, useQuery } from "@tanstack/react-query";-import { Time } from "../../../../components/DateSelector/types";import { getTimezone, useStore } from "../../../../lib/store";import { buildApiParams } from "../../../utils";-import { EventsResponse, fetchEvents } from "../../endpoints";+import {+ CursorEventsResponse,+ fetchEventsCursor,+ fetchNewEvents,+} from "../../endpoints";-export interface GetEventsOptions {- time?: Time;- page?: number;- pageSize?: number;- count?: number; // For backward compatibility- isRealtime?: boolean;-}--export function useGetEvents(count = 10) {- const { site, timezone } = useStore();+/**+ * Polls for new events since a given timestamp (Realtime mode).+ * The sinceTimestamp is read from a callback at query time so the query key+ * stays stable and doesn't cause refetch storms.+ */+export function useNewEventsPoll(options: {+ getSinceTimestamp: () => string | null;+ enabled: boolean;+}) {+ const { site, filters, timezone } = useStore();+ const tz = getTimezone();return useQuery({- queryKey: ["events", site, count, timezone],- refetchInterval: 5000,- queryFn: () =>- fetchEvents(site, {- startDate: "",- endDate: "",- timeZone: getTimezone(),- limit: count,- }).then(res => res.data),- enabled: !!site,+ queryKey: ["events-poll", site, filters, timezone],+ queryFn: () => {+ const since = options.getSinceTimestamp();+ if (!since) return { data: [] };+ return fetchNewEvents(site, {+ sinceTimestamp: since,+ filters: filters?.length ? filters : undefined,+ timeZone: tz,+ });+ },+ refetchInterval: 2000,+ enabled: !!site && options.enabled,});}-// Hook with pagination and filtering support-export function useGetEventsInfinite(options: GetEventsOptions = {}) {+/**+ * Cursor-based infinite query for loading events.+ * In Realtime mode: no time range, just filters.+ * In Historical mode: uses global time + filters from store.+ */+export function useGetEventsCursor(options: {+ isRealtime: boolean;+ pageSize?: number;+}) {const { site, time, filters, timezone } = useStore();- const pageSize = options.pageSize || 20;+ const pageSize = options.pageSize ?? 50;- const params = buildApiParams(time, {- filters: filters && filters.length > 0 ? filters : undefined,- });+ // In realtime mode we skip time params; in historical mode use global time+ const params = options.isRealtime+ ? {+ startDate: "",+ endDate: "",+ timeZone: getTimezone(),+ filters: filters?.length ? filters : undefined,+ }+ : buildApiParams(time, {+ filters: filters?.length ? filters : undefined,+ });- return useInfiniteQuery<EventsResponse, Error>({- queryKey: ["events-infinite", site, time, filters, pageSize, options.isRealtime, timezone],- initialPageParam: 1,+ return useInfiniteQuery<CursorEventsResponse, Error>({+ queryKey: [+ "events-cursor",+ site,+ options.isRealtime,+ options.isRealtime ? null : time,+ filters,+ pageSize,+ timezone,+ ],+ initialPageParam: null as string | null,queryFn: async ({ pageParam }) => {- return fetchEvents(site, {+ return fetchEventsCursor(site, {...params,- page: pageParam as number,+ beforeTimestamp: (pageParam as string) ?? undefined,pageSize,- limit: options.count,});},- getNextPageParam: (lastPage: EventsResponse) => {- if (lastPage.pagination.page < lastPage.pagination.totalPages) {- return lastPage.pagination.page + 1;+ getNextPageParam: (lastPage: CursorEventsResponse) => {+ if (lastPage.cursor?.hasMore && lastPage.cursor.oldestTimestamp) {+ return lastPage.cursor.oldestTimestamp;}return undefined;},- refetchInterval: options.isRealtime ? 5000 : undefined,enabled: !!site,});}diff --git a/client/src/api/analytics/hooks/events/useGetSiteEventCount.ts b/client/src/api/analytics/hooks/events/useGetSiteEventCount.tsnew file mode 100644index 000000000..ac862e79f--- /dev/null+++ b/client/src/api/analytics/hooks/events/useGetSiteEventCount.ts@@ -0,0 +1,24 @@+import { useQuery } from "@tanstack/react-query";+import { EVENT_FILTERS } from "../../../../lib/filterGroups";+import { getFilteredFilters, useStore } from "../../../../lib/store";+import { buildApiParams } from "../../../utils";+import { fetchSiteEventCount } from "../../endpoints";++export function useGetSiteEventCount() {+ const { site, time, bucket, timezone } = useStore();++ const filteredFilters = getFilteredFilters(EVENT_FILTERS);+ const params = buildApiParams(time, {+ filters: filteredFilters.length > 0 ? filteredFilters : undefined,+ });++ return useQuery({+ queryKey: ["site-event-count", site, time, bucket, filteredFilters, timezone],+ enabled: !!site,+ queryFn: () =>+ fetchSiteEventCount(site, {+ ...params,+ bucket,+ }),+ });+}diff --git a/client/src/app/[site]/components/shared/icons/Device.tsx b/client/src/app/[site]/components/shared/icons/Device.tsxnew file mode 100644index 000000000..487313f5b--- /dev/null+++ b/client/src/app/[site]/components/shared/icons/Device.tsx@@ -0,0 +1,11 @@+import { Laptop, Smartphone } from "lucide-react";++export function DeviceIcon({ deviceType, size = 16 }: { deviceType?: string; size?: number }) {+ const type = deviceType?.toLowerCase() || "";++ if (type.includes("mobile") || type.includes("tablet")) {+ return <Smartphone width={size} height={size} />;+ }++ return <Laptop width={size} height={size} />;+}\ No newline at end of filediff --git a/client/src/app/[site]/errors/components/ErrorDetails.tsx b/client/src/app/[site]/errors/components/ErrorDetails.tsxindex 044236ecf..06299cfdb 100644--- a/client/src/app/[site]/errors/components/ErrorDetails.tsx+++ b/client/src/app/[site]/errors/components/ErrorDetails.tsx@@ -2,40 +2,28 @@import { ErrorEvent } from "@/api/analytics/endpoints";import { useGetErrorEventsInfinite } from "@/api/analytics/hooks/errors/useGetErrorEvents";-import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";-import { userLocale } from "@/lib/dateTimeUtils";import { useGetRegionName } from "@/lib/geo";import { getTimezone } from "@/lib/store";-import { getCountryName, getUserDisplayName, truncateString } from "@/lib/utils";-import { AlertTriangle, Code, Hash, Laptop, Loader2, Smartphone, TriangleAlert, User } from "lucide-react";+import { getCountryName, truncateString } from "@/lib/utils";+import { AlertTriangle, Code, Loader2, TriangleAlert } from "lucide-react";import { DateTime } from "luxon";import Link from "next/link";import { useParams } from "next/navigation";import { useMemo } from "react";+import { Avatar } from "../../../../components/Avatar";import { ErrorState } from "../../../../components/ErrorState";import { Browser } from "../../components/shared/icons/Browser";import { CountryFlag } from "../../components/shared/icons/CountryFlag";import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";-import { Avatar } from "../../../../components/Avatar";+import { DeviceIcon } from "../../components/shared/icons/Device";interface ErrorDetailsProps {errorMessage: string;}-// DeviceIcon component for displaying mobile/desktop icons-function DeviceIcon({ deviceType }: { deviceType: string | null }) {- if (!deviceType) return <Laptop className="w-4 h-4" />;-- const type = deviceType.toLowerCase();- if (type.includes("mobile") || type.includes("tablet")) {- return <Smartphone className="w-4 h-4" />;- }- return <Laptop className="w-4 h-4" />;-}-// Component to display individual error eventfunction ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {const { getRegionName } = useGetRegionName();@@ -61,7 +49,7 @@ function ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {<div className="flex items-center justify-between mb-3"><div className="flex items-center gap-4"><span className="text-sm text-neutral-700 dark:text-neutral-200">- { DateTime.fromSQL(errorEvent.timestamp, { zone: "utc" }).setZone(getTimezone()).toRelative()}+ {DateTime.fromSQL(errorEvent.timestamp, { zone: "utc" }).setZone(getTimezone()).toRelative()}</span><div className="flex items-center gap-2">{errorEvent.country && (@@ -102,7 +90,7 @@ function ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {)}<Tooltip><TooltipTrigger>- <DeviceIcon deviceType={errorEvent.device_type} />+ <DeviceIcon deviceType={errorEvent.device_type ?? ""} /></TooltipTrigger><TooltipContent><p>{errorEvent.device_type || "Unknown device"}</p>@@ -121,7 +109,7 @@ function ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {</Link></div><div className="flex items-center gap-2">-+{errorEvent.user_id && (<Tooltip>diff --git a/client/src/app/[site]/events/components/ChartLegend.tsx b/client/src/app/[site]/events/components/ChartLegend.tsxnew file mode 100644index 000000000..b1349b854--- /dev/null+++ b/client/src/app/[site]/events/components/ChartLegend.tsx@@ -0,0 +1,38 @@+"use client";++export interface LegendItem {+ id: string;+ color: string;+}++interface ChartLegendProps {+ items: LegendItem[];+ hiddenItems: Set<string>;+ onToggle: (id: string) => void;+}++export function ChartLegend({ items, hiddenItems, onToggle }: ChartLegendProps) {+ if (items.length === 0) return null;++ 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>+ );+}diff --git a/client/src/app/[site]/events/components/CustomEventsChart.tsx b/client/src/app/[site]/events/components/CustomEventsChart.tsxnew file mode 100644index 000000000..209e17a79--- /dev/null+++ b/client/src/app/[site]/events/components/CustomEventsChart.tsx@@ -0,0 +1,233 @@+"use client";++import { ResponsiveLine, SliceTooltipProps } from "@nivo/line";+import { useWindowSize } from "@uidotdev/usehooks";+import { DateTime } from "luxon";+import { useEffect, useMemo, useState } from "react";++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[];+};++export function CustomEventsChart({ eventLimit }: { eventLimit: number }) {+ 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 next = new Set(prev);+ if (next.has(eventName)) {+ next.delete(eventName);+ } else {+ next.add(eventName);+ }+ return next;+ });+ };++ 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());+ }++ 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");+ };++ 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">All event series hidden</p>+ <p className="text-xs">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].sort(+ (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} />+ </>+ );+}diff --git a/client/src/app/[site]/events/components/EventLog.tsx b/client/src/app/[site]/events/components/EventLog.tsxdeleted file mode 100644index b9b5dce01..000000000--- a/client/src/app/[site]/events/components/EventLog.tsx+++ /dev/null@@ -1,82 +0,0 @@-"use client";--import { useIntersectionObserver } from "@uidotdev/usehooks";-import { useEffect } from "react";-import { useGetEventsInfinite } from "../../../../api/analytics/hooks/events/useGetEvents";-import { NothingFound } from "../../../../components/NothingFound";-import { formatter } from "../../../../lib/utils";-import { EventLogItem, EventLogItemSkeleton } from "./EventLogItem";-import { ErrorState } from "../../../../components/ErrorState";-import { ScrollArea } from "../../../../components/ui/scroll-area";--export function EventLog() {- // Fetch events with infinite scrolling- const { data, isLoading, isError, fetchNextPage, hasNextPage, isFetchingNextPage } = useGetEventsInfinite({- pageSize: 100,- });-- // Use the intersection observer hook- const [ref, entry] = useIntersectionObserver({- threshold: 0,- root: null,- rootMargin: "0px 0px 100px 0px",- });-- // Fetch next page when intersection observer detects the target is visible- useEffect(() => {- if (entry?.isIntersecting && hasNextPage && !isFetchingNextPage && !isLoading) {- fetchNextPage();- }- }, [entry?.isIntersecting, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading]);-- // Flatten all pages of data- const allEvents = data?.pages.flatMap(page => page.data) || [];-- if (isLoading) {- return (- <div className="space-y-2">- {Array.from({ length: 100 }).map((_, index) => (- <EventLogItemSkeleton key={index} />- ))}- </div>- );- }-- if (isError) {- return (- <ErrorState- title="Failed to load events"- message="There was a problem fetching the events. Please try again later."- />- );- }-- if (allEvents.length === 0) {- return <NothingFound title={"No events found"} description={"Try a different date range or filter"} />;- }-- return (- <ScrollArea className="h-[80vh]">- <div className="h-full pr-2 overflow-x-hidden">- {allEvents.map((event, index) => (- <EventLogItem key={`${event.timestamp}-${index}`} event={event} />- ))}-- {/* Infinite scroll sentinel */}- <div ref={ref} className="py-2">- {isFetchingNextPage && (- Array.from({ length: 3 }).map((_, index) => (- <EventLogItemSkeleton key={`next-page-${index}`} />- ))- )}- </div>- </div>- {/* Pagination info */}- {data?.pages[0]?.pagination && (- <div className="text-center text-xs text-neutral-500 dark:text-neutral-400 pt-2">- Showing {allEvents.length} of {formatter(data.pages[0].pagination.total)} events- </div>- )}- </ScrollArea>- );-}diff --git a/client/src/app/[site]/events/components/EventLog/EventDetailsSheet.tsx b/client/src/app/[site]/events/components/EventLog/EventDetailsSheet.tsxnew file mode 100644index 000000000..884249c5c--- /dev/null+++ b/client/src/app/[site]/events/components/EventLog/EventDetailsSheet.tsx@@ -0,0 +1,183 @@+"use client";++import { useQuery } from "@tanstack/react-query";+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 { 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 { 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";++interface EventDetailsSheetProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ event: Event | null;+ site: string;+}++export function EventDetailsSheet({ open, onOpenChange, event, site }: EventDetailsSheetProps) {+ const selectedEventProperties = event ? parseEventProperties(event) : {};++ const sessionQuery = useQuery({+ queryKey: ["event-session", site, event?.session_id],+ queryFn: () =>+ fetchSessions(site, {+ sessionId: event?.session_id || "",+ limit: 1,+ page: 1,+ startDate: "2020-01-01",+ endDate: "2099-12-31",+ timeZone: getTimezone(),+ }).then(res => res.data[0] ?? null),+ enabled: open && !!event?.session_id && !!site,+ staleTime: 30000,+ });++ const timestamp = DateTime.fromSQL(event?.timestamp || "", { zone: "utc" })+ .setLocale(userLocale)+ .setZone(getTimezone())++ return (+ <Sheet+ open={open}+ onOpenChange={nextOpen => {+ onOpenChange(nextOpen);+ }}+ >+ <SheetContent side="right" className="w-full sm:max-w-[1000px] overflow-y-auto">+ <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>+ </div>+ </SheetTitle>+ </SheetHeader>++ {!event ? (+ <div className="text-sm text-neutral-500 dark:text-neutral-400">No event selected.</div>+ ) : (+ <div className="space-y-4">+ <div className="flex flex-col sm:flex-row justify-between gap-1.5 sm:gap-6">+ <div className="space-y-3 flex-1">+ <div className="grid grid-cols-1 gap-1 text-sm">+ <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">Timestamp</span>+ <span>+ {timestamp.toFormat(hour12 ? "MMM d, h:mm:ss a" : "dd MMM, HH:mm:ss")}+ </span>+ </div>+ <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">User</span>+ <Link+ href={`/${site}/user/${encodeURIComponent(event.identified_user_id || event.user_id)}`}+ className="hover:underline"+ >+ {getUserDisplayName({+ identified_user_id: event.identified_user_id || undefined,+ user_id: event.user_id,+ })}+ </Link>+ </div>+ <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">User ID</span>+ {truncateString(event.user_id, 24)}+ </div>+ <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">Session ID</span>+ {truncateString(event.session_id, 24)}+ </div>+ <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">Hostname</span>+ <span className="truncate max-w-[280px]">{event.hostname || "-"}</span>+ </div>+ <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">Path</span>+ <span className="truncate max-w-[280px]">{buildEventPath(event) || "-"}</span>+ </div>+ <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">Referrer</span>+ <span className="truncate max-w-[280px]">{event.referrer || "-"}</span>+ </div>+ </div>+ </div>+ <div className="space-y-3 flex-1">+ <div className="grid grid-cols-1 gap-1 text-sm">+ <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">Browser</span>+ <span className="flex items-center gap-1">+ <Browser browser={event.browser || "Unknown"} />+ {event.browser || "Unknown"}{event.browser_version ? ` ${event.browser_version}` : ""}+ </span>+ </div>+ <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">Operating System</span>+ <span className="flex items-center gap-1">+ <OperatingSystem os={event.operating_system || ""} />+ {event.operating_system || "Unknown"}{event.operating_system_version ? ` ${event.operating_system_version}` : ""}+ </span>+ </div>+ <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">Device</span>+ <span className="flex items-center gap-1">+ <DeviceIcon deviceType={event.device_type || ""} />+ {event.device_type || "Unknown"}+ </span>+ </div>+ <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">Screen</span>+ <span>{event.screen_width && event.screen_height ? `${event.screen_width} × ${event.screen_height}` : "-"}</span>+ </div>+ <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">Language</span>+ <span>{event.language || "-"}</span>+ </div>+ <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">Location</span>+ <span className="flex items-center gap-1">{event.country && <CountryFlag country={event.country} />}{[event.city, getRegionName(event.region), getCountryName(event.country)].filter(Boolean).join(", ") || "-"}</span>+ </div>+ {(isFinite(event.lat) && isFinite(event.lon)) && (+ <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">Coordinates</span>+ <span>{event.lat.toFixed(4)}, {event.lon.toFixed(4)}</span>+ </div>+ )}+ </div>+ </div>+ </div>++ {Object.keys(selectedEventProperties).length > 0 &&+ <div>+ <div className="text-sm font-medium mb-2">Properties</div>+ <pre className="text-xs bg-neutral-50 dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-md p-3 overflow-auto max-h-64">+ {JSON.stringify(selectedEventProperties, null, 2)}+ </pre>+ </div>+ }++ <div>+ <div className="text-sm font-medium mb-2">Session</div>+ {sessionQuery.isLoading ? (+ <SessionCardSkeleton count={1} />+ ) : sessionQuery.data ? (+ <SessionCard session={sessionQuery.data} expandedByDefault highlightedEventTimestamp={timestamp.toMillis()} />+ ) : (+ <div className="text-xs text-neutral-500 dark:text-neutral-400">No session data</div>+ )}+ </div>+ </div>+ )}+ </SheetContent>+ </Sheet>+ );+}diff --git a/client/src/app/[site]/events/components/EventLog/EventLog.tsx b/client/src/app/[site]/events/components/EventLog/EventLog.tsxnew file mode 100644index 000000000..8e5a2db8c--- /dev/null+++ b/client/src/app/[site]/events/components/EventLog/EventLog.tsx@@ -0,0 +1,228 @@+"use client";++import { useVirtualizer } from "@tanstack/react-virtual";+import { useParams } from "next/navigation";+import { useCallback, useState } from "react";+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 { ScrollArea } from "../../../../../components/ui/scroll-area";+import { EventDetailsSheet } from "./EventDetailsSheet";+import { EventRow } from "./EventRow";+import { RealtimeToggle } from "./RealtimeToggle";+import { useEventLogState } from "./useEventLogState";++const ALL_EVENT_TYPES = new Set(EVENT_TYPE_CONFIG.map((c) => c.value as string));++export function EventLog() {+ const { site } = useParams();+ const [sheetOpen, setSheetOpen] = useState(false);+ const [selectedEvent, setSelectedEvent] = useState<Event | null>(null);+ const [visibleTypes, setVisibleTypes] = useState<Set<string>>(ALL_EVENT_TYPES);++ const handleToggleType = useCallback((type: string) => {+ setVisibleTypes((prev) => {+ const next = new Set(prev);+ if (next.has(type)) {+ next.delete(type);+ } else {+ next.add(type);+ }+ return next;+ });+ }, []);++ const {+ isRealtime,+ toggleRealtime,+ allEvents,+ unfilteredEvents,+ isLoading,+ isError,+ isFetched,+ scrollElement,+ scrollAreaCallbackRef,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ isLive,+ bufferedCount,+ flushAndScrollToTop,+ } = useEventLogState({ visibleTypes });++ const rowVirtualizer = useVirtualizer({+ count: allEvents.length,+ getScrollElement: () => scrollElement,+ estimateSize: () => 28,+ overscan: 12,+ });++ const virtualItems = rowVirtualizer.getVirtualItems();++ // --- Infinite scroll trigger ---+ const lastItem = virtualItems[virtualItems.length - 1];+ if (+ lastItem &&+ lastItem.index >= allEvents.length - 5 &&+ hasNextPage &&+ !isFetchingNextPage &&+ !isLoading+ ) {+ fetchNextPage();+ }++ const showBody = !isLoading && !isError && allEvents.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>++ <div className="relative">+ {/* New events indicator */}+ {isRealtime && !isLive && bufferedCount > 0 && (+ <button+ onClick={flushAndScrollToTop}+ className="absolute top-12 left-1/2 -translate-x-1/2 z-30 px-3 py-1 rounded-full bg-accent-400 dark:bg-accent-600 text-white text-xs font-medium shadow-lg hover:bg-accent-300 dark:hover:bg-accent-500 transition-colors cursor-pointer"+ >+ ↑ {bufferedCount} new event{bufferedCount !== 1 ? "s" : ""}+ </button>+ )}++ <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_140px_180px_100px_1fr_1fr] px-2 py-1.5 uppercase tracking-wide text-[10px] text-neutral-500 dark:text-neutral-400">+ <div></div>+ <div>Timestamp</div>+ <div>User</div>+ <div>Device Info</div>+ <div>Page</div>+ <div>Data</div>+ </div>+ </div>++ {isLoading && (+ <div>+ {Array.from({ length: 24 }).map((_, index) => (+ <EventLogItemSkeleton key={index} showProperties={index % 3 === 0} />+ ))}+ </div>+ )}++ {isError && (+ <ErrorState+ title="Failed to load events"+ message="There was a problem fetching the events. Please try again later."+ />+ )}++ {isFetched && !isError && allEvents.length === 0 && (+ <NothingFound+ title={"No events found"}+ description={"Try a different date range or filter"}+ />+ )}++ {showBody && (+ <>+ <div className="relative">+ <div+ style={{+ height: rowVirtualizer.getTotalSize(),+ position: "relative",+ }}+ >+ {virtualItems.map((virtualRow) => {+ const event = allEvents[virtualRow.index];+ if (!event) return null;++ return (+ <div+ key={`${event.timestamp}-${virtualRow.index}`}+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ width: "100%",+ transform: `translateY(${virtualRow.start}px)`,+ }}+ >+ <EventRow+ event={event}+ site={site as string}+ onClick={(selected) => {+ setSelectedEvent(selected);+ setSheetOpen(true);+ }}+ />+ </div>+ );+ })}+ </div>+ </div>++ {isFetchingNextPage && (+ <div className="py-2">+ {Array.from({ length: 3 }).map((_, index) => (+ <EventLogItemSkeleton key={`next-page-${index}`} />+ ))}+ </div>+ )}+ </>+ )}+ </div>+ </ScrollArea>+ </div>++ <EventDetailsSheet+ open={sheetOpen}+ onOpenChange={(open) => {+ setSheetOpen(open);+ if (!open) setSelectedEvent(null);+ }}+ event={selectedEvent}+ site={site as string}+ />+ </>+ );+}++function EventLogItemSkeleton({ showProperties }: { showProperties?: boolean }) {+ return (+ <div className="grid grid-cols-[28px_140px_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>+ <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>+ <div className="flex items-center px-2">+ <div className="h-3 w-28 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" />+ </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>+ </div>+ );+}diff --git a/client/src/app/[site]/events/components/EventLog/EventRow.tsx b/client/src/app/[site]/events/components/EventLog/EventRow.tsxnew file mode 100644index 000000000..7448186ba--- /dev/null+++ b/client/src/app/[site]/events/components/EventLog/EventRow.tsx@@ -0,0 +1,159 @@+"use client";++import Link from "next/link";+import { DateTime } from "luxon";+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 { hour12, userLocale } from "../../../../../lib/dateTimeUtils";+import { getTimezone } 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 { OperatingSystem } from "../../../components/shared/icons/OperatingSystem";+import { buildEventPath, getEventTypeLabel, getMainData, parseEventProperties } from "./eventLogUtils";+import { DeviceIcon } from "../../../components/shared/icons/Device";++interface EventRowProps {+ event: Event;+ site: string;+ onClick: (event: Event) => void;+}++export function EventRow({ event, site, onClick }: EventRowProps) {+ const eventProperties = parseEventProperties(event);+ const eventTime = DateTime.fromSQL(event.timestamp, { zone: "utc" })+ .setLocale(userLocale)+ .setZone(getTimezone());+ const pagePath = buildEventPath(event);+ const pageUrl = `https://${event.hostname}${pagePath}`;+ const isPageview = event.type === "pageview";+ const eventData = isPageview ? null : getMainData(event, eventProperties);+ const userProfileId = event.identified_user_id || event.user_id;+ const displayName = getUserDisplayName({+ identified_user_id: event.identified_user_id || undefined,+ user_id: event.user_id,+ });++ return (+ <div+ className="grid grid-cols-[28px_140px_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"+ 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>++ <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>{eventTime.toRelative()}</span>+ </TooltipContent>+ </Tooltip>+ </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>++ <div className="flex space-x-1 items-center px-2 py-1">+ {event.country && (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="flex items-center">+ <CountryFlag country={event.country} />+ </div>+ </TooltipTrigger>+ <TooltipContent>+ <p>{getCountryName(event.country)}</p>+ </TooltipContent>+ </Tooltip>+ )}+ <Tooltip>+ <TooltipTrigger asChild>+ <div>+ <Browser browser={event.browser || "Unknown"} />+ </div>+ </TooltipTrigger>+ <TooltipContent>+ <p>{event.browser || "Unknown browser"}</p>+ </TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <div>+ <OperatingSystem os={event.operating_system || ""} />+ </div>+ </TooltipTrigger>+ <TooltipContent>+ <p>{event.operating_system || "Unknown OS"}</p>+ </TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <div>+ <DeviceIcon deviceType={event.device_type || ""} />+ </div>+ </TooltipTrigger>+ <TooltipContent>+ <p>{event.device_type || "Unknown device"}</p>+ </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.tsxnew file mode 100644index 000000000..fc2339061--- /dev/null+++ b/client/src/app/[site]/events/components/EventLog/RealtimeToggle.tsx@@ -0,0 +1,28 @@+export function RealtimeToggle({+ isRealtime,+ onToggle,+}: {+ isRealtime: boolean;+ onToggle: () => void;+}) {+ 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>+ );+}diff --git a/client/src/app/[site]/events/components/EventLog/eventLogUtils.tsx b/client/src/app/[site]/events/components/EventLog/eventLogUtils.tsxnew file mode 100644index 000000000..d074d809e--- /dev/null+++ b/client/src/app/[site]/events/components/EventLog/eventLogUtils.tsx@@ -0,0 +1,60 @@+"use client";++import { Event } from "../../../../../api/analytics/endpoints";+import { EVENT_TYPE_CONFIG, getEventDisplayName } from "../../../../../lib/events";++export function getEventKey(event: Event) {+ return `${event.timestamp}-${event.session_id}-${event.user_id}-${event.type}-${event.event_name ?? ""}-${event.pathname}`;+}++export function parseEventProperties(event: Event): Record<string, any> {+ if (event.properties && event.properties !== "{}") {+ try {+ return JSON.parse(event.properties);+ } catch (e) {+ console.error("Failed to parse event properties:", e);+ }+ }+ return {};+}++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>) {+ 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";++ if (isPageview) {+ return {+ label: buildEventPath(event),+ url: `https://${event.hostname}${buildEventPath(event)}`,+ };+ }++ if (isOutbound && props.url) {+ return {+ label: props.url as string,+ url: props.url as string,+ };+ }++ if (isButtonClick || isCopy || isFormSubmit || isInputChange) {+ return {+ label: getEventDisplayName({ type: event.type, event_name: event.event_name, props }),+ };+ }++ return {+ label: event.event_name || "Event",+ };+}diff --git a/client/src/app/[site]/events/components/EventLog/index.ts b/client/src/app/[site]/events/components/EventLog/index.tsnew file mode 100644index 000000000..5a4cf5759--- /dev/null+++ b/client/src/app/[site]/events/components/EventLog/index.ts@@ -0,0 +1 @@+export { EventLog } from "./EventLog";diff --git a/client/src/app/[site]/events/components/EventLog/useEventLogState.ts b/client/src/app/[site]/events/components/EventLog/useEventLogState.tsnew file mode 100644index 000000000..896b2ab16--- /dev/null+++ b/client/src/app/[site]/events/components/EventLog/useEventLogState.ts@@ -0,0 +1,235 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Event } from "../../../../../api/analytics/endpoints";+import {+ useGetEventsCursor,+ useNewEventsPoll,+} from "../../../../../api/analytics/hooks/events/useGetEvents";+import { getEventKey } from "./eventLogUtils";++const MAX_EVENTS = 10_000;+const PAGE_SIZE = 100;++export function useEventLogState(options: {+ visibleTypes: Set<string>;+} = { visibleTypes: new Set() }) {+ // --- Mode state ---+ const [isRealtime, setIsRealtime] = useState(true);++ // --- Prepended events from polling (realtime mode) ---+ const [prependedEvents, setPrependedEvents] = useState<Event[]>([]);+ const seenKeysRef = useRef(new Set<string>());+ const latestTimestampRef = useRef<string | null>(null);++ // --- Pause / buffer state ---+ const [isLive, setIsLive] = useState(true);+ const isLiveRef = useRef(true);+ isLiveRef.current = isLive;+ const isRealtimeRef = useRef(true);+ isRealtimeRef.current = isRealtime;+ const bufferedEventsRef = useRef<Event[]>([]);+ const [bufferedCount, setBufferedCount] = useState(0);++ // --- Scroll refs ---+ const [scrollElement, setScrollElement] = useState<HTMLDivElement | null>(+ null+ );+ const viewportRef = useRef<HTMLDivElement | null>(null);++ // --- Cursor query (both modes) ---+ const {+ data: cursorData,+ isLoading,+ isError,+ isFetched,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ } = useGetEventsCursor({ isRealtime, pageSize: PAGE_SIZE });++ // --- Derive cursor events from query data ---+ const cursorEvents = useMemo(+ () => cursorData?.pages.flatMap((p) => p.data) ?? [],+ [cursorData]+ );++ // --- Combined event list ---+ const mergedEvents = useMemo(() => {+ if (prependedEvents.length === 0) return cursorEvents;+ return [...prependedEvents, ...cursorEvents].slice(0, MAX_EVENTS);+ }, [prependedEvents, cursorEvents]);++ // --- Client-side type filter ---+ const { visibleTypes } = options;+ const allEvents = useMemo(() => {+ if (visibleTypes.size === 0) return mergedEvents;+ return mergedEvents.filter((ev) => visibleTypes.has(ev.type));+ }, [mergedEvents, visibleTypes]);++ // --- Rebuild seenKeys + set latestTimestamp when cursor data changes ---+ useEffect(() => {+ seenKeysRef.current = new Set(cursorEvents.map(getEventKey));+ for (const ev of prependedEvents) {+ seenKeysRef.current.add(getEventKey(ev));+ }+ if (cursorEvents.length > 0 && !latestTimestampRef.current) {+ latestTimestampRef.current = cursorEvents[0].timestamp;+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [cursorEvents]);++ // --- Poll query (realtime only) ---+ const getSinceTimestamp = useCallback(+ () => latestTimestampRef.current,+ []+ );+ const { data: pollData } = useNewEventsPoll({+ getSinceTimestamp,+ enabled: isRealtime,+ });++ // --- Handle poll results (realtime only) ---+ useEffect(() => {+ if (!isRealtime || !pollData?.data?.length) return;++ const incoming = pollData.data;+ const newEvents: Event[] = [];+ for (const ev of incoming) {+ const key = getEventKey(ev);+ if (!seenKeysRef.current.has(key)) {+ seenKeysRef.current.add(key);+ newEvents.push(ev);+ }+ }+ if (newEvents.length === 0) return;++ // Update latest timestamp+ const newestTs = newEvents[0].timestamp;+ if (+ !latestTimestampRef.current ||+ newestTs > latestTimestampRef.current+ ) {+ latestTimestampRef.current = newestTs;+ }++ if (isLiveRef.current) {+ setPrependedEvents((prev) => {+ const combined = [...newEvents, ...prev];+ if (combined.length + cursorEvents.length > MAX_EVENTS) {+ return combined.slice(0, MAX_EVENTS - cursorEvents.length);+ }+ return combined;+ });+ } else {+ bufferedEventsRef.current = [+ ...newEvents,+ ...bufferedEventsRef.current,+ ];+ setBufferedCount((c) => c + newEvents.length);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [pollData]);++ // --- Reset on mode toggle ---+ useEffect(() => {+ setPrependedEvents([]);+ seenKeysRef.current.clear();+ latestTimestampRef.current = null;+ bufferedEventsRef.current = [];+ setBufferedCount(0);+ setIsLive(true);+ }, [isRealtime]);++ // --- Callback ref: capture viewport whenever ScrollArea mounts ---+ const scrollAreaCallbackRef = useCallback(+ (node: HTMLDivElement | null) => {+ if (node) {+ const viewport = node.querySelector<HTMLDivElement>(+ '[data-slot="scroll-area-viewport"]'+ );+ if (viewport) {+ viewportRef.current = viewport;+ setScrollElement(viewport);+ }+ } else {+ viewportRef.current = null;+ setScrollElement(null);+ }+ },+ []+ );++ // --- Scroll listener for auto-pause/resume ---+ useEffect(() => {+ const viewport = viewportRef.current;+ if (!viewport) return;++ const handleScroll = () => {+ if (!isRealtimeRef.current) return;+ const atTop = viewport.scrollTop < 50;+ if (atTop && !isLiveRef.current) {+ setIsLive(true);+ if (bufferedEventsRef.current.length > 0) {+ const buffered = bufferedEventsRef.current;+ bufferedEventsRef.current = [];+ setBufferedCount(0);+ setPrependedEvents((prev) => [...buffered, ...prev]);+ }+ } else if (!atTop && isLiveRef.current) {+ setIsLive(false);+ }+ };++ viewport.addEventListener("scroll", handleScroll, { passive: true });+ return () => {+ viewport.removeEventListener("scroll", handleScroll);+ };+ }, [scrollElement]);++ // --- Flush buffer + scroll to top ---+ const flushAndScrollToTop = useCallback(() => {+ const viewport = viewportRef.current;+ if (!viewport) return;++ const buffered = bufferedEventsRef.current;+ bufferedEventsRef.current = [];+ setBufferedCount(0);+ setIsLive(true);++ if (buffered.length > 0) {+ setPrependedEvents((prev) => [...buffered, ...prev]);+ }++ viewport.scrollTop = 0;+ }, []);++ const toggleRealtime = useCallback(() => {+ setIsRealtime((prev) => !prev);+ }, []);++ return {+ // Mode+ isRealtime,+ toggleRealtime,++ // Data+ allEvents,+ unfilteredEvents: mergedEvents,+ isLoading,+ isError,+ isFetched,++ // Virtualizer support+ scrollElement,+ scrollAreaCallbackRef,++ // Infinite scroll+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,++ // Pause / buffer+ isLive,+ bufferedCount,+ flushAndScrollToTop,+ };+}diff --git a/client/src/app/[site]/events/components/EventLogItem.tsx b/client/src/app/[site]/events/components/EventLogItem.tsxdeleted file mode 100644index 2f746d444..000000000--- a/client/src/app/[site]/events/components/EventLogItem.tsx+++ /dev/null@@ -1,252 +0,0 @@-"use client";--import { Badge } from "@/components/ui/badge";-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";-import { getTimezone } from "@/lib/store";-import { Laptop, Smartphone } from "lucide-react";-import { DateTime } from "luxon";-import Link from "next/link";-import { useParams } from "next/navigation";-import { memo } from "react";-import { Event } from "../../../../api/analytics/endpoints";-import { EventTypeIcon } from "../../../../components/EventIcons";-import { getEventDisplayName, PROPS_TO_HIDE } from "../../../../lib/events";-import { getCountryName, truncateString } from "../../../../lib/utils";-import { Browser } from "../../components/shared/icons/Browser";-import { CountryFlag } from "../../components/shared/icons/CountryFlag";-import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";--// DeviceIcon component for displaying mobile/desktop icons-function DeviceIcon({ deviceType }: { deviceType: string }) {- const type = deviceType.toLowerCase();-- if (type.includes("mobile") || type.includes("tablet")) {- return <Smartphone className="w-4 h-4" />;- }-- return <Laptop className="w-4 h-4" />;-}--interface EventLogItemProps {- event: Event;-}--export function EventLogItem({ event }: EventLogItemProps) {- const { site } = useParams();-- // Parse event timestamp- const eventTime = DateTime.fromSQL(event.timestamp, {- zone: "utc",- }).setZone(getTimezone());-- // Determine event type- 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";-- const fullPath = `https://${event.hostname}${event.pathname}${event.querystring ? `${event.querystring}` : ""}`;-- // Parse event properties if they exist- let eventProperties: Record<string, any> = {};- if (event.properties && event.properties !== "{}") {- try {- eventProperties = JSON.parse(event.properties);- } catch (e) {- console.error("Failed to parse event properties:", e);- }- }-- return (- <div className="mb-3 rounded-lg bg-neutral-50 dark:bg-neutral-850/50 border border-neutral-100 dark:border-neutral-800 overflow-hidden p-3 hover:bg-neutral-100 dark:hover:bg-neutral-800/70 transition-all duration-200">- <div className="flex flex-col space-y-2">- {/* Single row with event type, name/path, device info, and timestamp */}- <div className="flex items-center gap-2 text-sm text-neutral-900 dark:text-neutral-100">- {/* Left side content */}- <div className="flex items-center gap-2 grow min-w-0">- {/* Event type icon */}- <div className="shrink-0">- <EventTypeIcon type={event.type} />- </div>-- {/* Event name or path */}- <div className="min-w-0 max-w-[40%]">- {isPageview ? (- <Link href={fullPath} target="_blank" rel="noopener noreferrer">- <div className="text-sm truncate hover:underline" title={event.pathname}>- {truncateString(`${event.pathname}${event.querystring ? `${event.querystring}` : ""}`, 64)}- </div>- </Link>- ) : isOutbound ? (- // For outbound events, show the destination URL from properties- eventProperties.url ? (- <Link href={eventProperties.url} target="_blank" rel="noopener noreferrer">- <div className="text-sm truncate hover:underline" title={eventProperties.url}>- {truncateString(eventProperties.url, 64)}- </div>- </Link>- ) : (- <div className="text-sm font-medium truncate">Outbound Link</div>- )- ) : isButtonClick || isCopy || isFormSubmit || isInputChange ? (- <div className="text-sm font-medium truncate">- {getEventDisplayName({ type: event.type, event_name: event.event_name, props: eventProperties })}- </div>- ) : (- <div className="text-sm font-medium truncate">{event.event_name}</div>- )}- </div>-- {/* Device info */}- <div className="shrink-0 flex space-x-1 items-center">- {event.country && (- <Tooltip>- <TooltipTrigger asChild>- <div className="flex items-center">- <CountryFlag country={event.country} />- </div>- </TooltipTrigger>- <TooltipContent>- <p>{getCountryName(event.country)}</p>- </TooltipContent>- </Tooltip>- )}- <Tooltip>- <TooltipTrigger asChild>- <div>- <Browser browser={event.browser || "Unknown"} />- </div>- </TooltipTrigger>- <TooltipContent>- <p>{event.browser || "Unknown browser"}</p>- </TooltipContent>- </Tooltip>- <Tooltip>- <TooltipTrigger asChild>- <div>- <OperatingSystem os={event.operating_system || ""} />- </div>- </TooltipTrigger>- <TooltipContent>- <p>{event.operating_system || "Unknown OS"}</p>- </TooltipContent>- </Tooltip>- <Tooltip>- <TooltipTrigger asChild>- <div>- <DeviceIcon deviceType={event.device_type || ""} />- </div>- </TooltipTrigger>- <TooltipContent>- <p>{event.device_type || "Unknown device"}</p>- </TooltipContent>- </Tooltip>- </div>-- {/* User ID */}- <Link href={`/${site}/user/${encodeURIComponent(event.user_id)}`} className="shrink-0">- <Tooltip>- <TooltipTrigger asChild>- <span className="text-sm font-mono text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-300">- {event.user_id.substring(0, 12)}- </span>- </TooltipTrigger>- <TooltipContent>- <p>View user profile</p>- </TooltipContent>- </Tooltip>- </Link>- </div>-- {/* Timestamp (right-aligned) */}- <div className="text-sm shrink-0 text-neutral-500 dark:text-neutral-400 ml-auto">- {eventTime.toRelative()}- </div>- </div>-- {/* Bottom row with event properties */}- {Object.keys(eventProperties).length > 0 && (() => {- const propsToHide = PROPS_TO_HIDE[event.type] || [];- const filteredProps = Object.entries(eventProperties).filter(- ([key]) => !propsToHide.includes(key)- );- if (filteredProps.length === 0) return null;-- return (- <div className="flex flex-wrap gap-1 mt-1 ml-6">- {filteredProps.map(([key, value]) => (- <Badge- key={key}- variant="outline"- className="px-1.5 py-0 h-5 text-xs bg-neutral-200 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100 font-medium truncate max-w-[90%]"- >- <span className="text-neutral-600 dark:text-neutral-300 font-light mr-1">{key}:</span>{" "}- <Tooltip>- <TooltipTrigger asChild>- <span className="truncate">- {typeof value === "object" ? JSON.stringify(value) : String(value)}- </span>- </TooltipTrigger>- <TooltipContent>- <span className="max-w-7xl">- {typeof value === "object" ? JSON.stringify(value) : String(value)}- </span>- </TooltipContent>- </Tooltip>- </Badge>- ))}- </div>- );- })()}- </div>- </div>- );-}--export const EventLogItemSkeleton = memo(() => {- // Function to get a random width class for skeletons- const getRandomWidth = () => {- const widths = ["w-16", "w-20", "w-24", "w-28", "w-32", "w-36", "w-40"];- return widths[Math.floor(Math.random() * widths.length)];- };-- return (- <div className="mb-3 rounded-lg bg-neutral-50 dark:bg-neutral-850/50 border border-neutral-100 dark:border-neutral-800 overflow-hidden p-3">- <div className="flex flex-col space-y-2">- {/* Single row skeleton */}- <div className="flex items-center gap-2">- {/* Left side content */}- <div className="flex items-center gap-2 grow">- <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded-sm animate-pulse shrink-0"></div>- <div className="h-4 w-40 bg-neutral-200 dark:bg-neutral-800 rounded animate-pulse shrink-0"></div>- <div className="flex space-x-1 shrink-0">- <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded-sm animate-pulse"></div>- <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded-sm animate-pulse"></div>- <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded-sm animate-pulse"></div>- <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded-sm animate-pulse"></div>- </div>- <div className="h-4 w-16 bg-neutral-200 dark:bg-neutral-800 rounded animate-pulse shrink-0"></div>- </div>-- {/* Timestamp (right-aligned) */}- <div className="h-4 w-24 bg-neutral-200 dark:bg-neutral-800 rounded animate-pulse shrink-0 ml-auto"></div>- </div>-- {/* Bottom row skeleton (properties) - show randomly */}- {Math.random() > 0.5 && (- <div className="flex flex-wrap gap-1 mt-1 ml-6">- {Array.from({ length: Math.floor(Math.random() * 4) + 1 }).map((_, i) => (- <div- key={i}- className="h-5 bg-neutral-200 dark:bg-neutral-800 rounded animate-pulse"- style={{ width: `${Math.random() * 60 + 40}px` }}- ></div>- ))}- </div>- )}- </div>- </div>- );-});diff --git a/client/src/app/[site]/events/components/EventTypesChart.tsx b/client/src/app/[site]/events/components/EventTypesChart.tsxnew file mode 100644index 000000000..430944200--- /dev/null+++ b/client/src/app/[site]/events/components/EventTypesChart.tsx@@ -0,0 +1,231 @@+"use client";++import { ResponsiveLine, SliceTooltipProps } from "@nivo/line";+import { useWindowSize } from "@uidotdev/usehooks";+import { DateTime } from "luxon";+import { useMemo, useState } from "react";++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"];++type DataPoint = {+ x: string;+ y: number;+ currentTime: DateTime;+};++type Series = {+ id: string;+ color: string;+ data: DataPoint[];+};++export function EventTypesChart() {+ const { bucket } = useStore();+ const { data, isLoading } = useGetSiteEventCount();+ const { width } = useWindowSize();+ const nivoTheme = useNivoTheme();+ const timezone = getTimezone();+ const [hiddenTypes, setHiddenTypes] = useState<Set<string>>(new Set());++ const toggleTypeVisibility = (typeLabel: string) => {+ setHiddenTypes((prev) => {+ const next = new Set(prev);+ if (next.has(typeLabel)) {+ next.delete(typeLabel);+ } else {+ next.add(typeLabel);+ }+ 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].sort((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: 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]);++ 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">All event types hidden</p>+ <p className="text-xs">Click a legend item to show it</p>+ </div>+ </div>+ <ChartLegend items={legendItems} hiddenItems={hiddenTypes} onToggle={toggleTypeVisibility} />+ </>+ );+ }++ 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].sort(+ (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">Total</span>+ <span className="font-semibold text-neutral-700 dark:text-neutral-200">+ {formatter(total)}+ </span>+ </div>+ </div>+ </ChartTooltip>+ );+ }}+ />+ </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.tsxindex 11ab743b3..a245c8ae8 100644--- a/client/src/app/[site]/events/components/EventsChart.tsx+++ b/client/src/app/[site]/events/components/EventsChart.tsx@@ -1,294 +1,78 @@"use client";-import { ResponsiveLine, SliceTooltipProps } from "@nivo/line";-import { useWindowSize } from "@uidotdev/usehooks";-import { DateTime } from "luxon";-import { useEffect, useMemo, useState } from "react";+import { useState } from "react";-import { useGetEventBucketed } from "@/api/analytics/hooks/events/useGetEventBucketed";import { BucketSelection } from "@/components/BucketSelection";-import { ChartTooltip } from "@/components/charts/ChartTooltip";-import { Card, CardContent, CardDescription, CardHeader, CardLoader, CardTitle } from "@/components/ui/card";+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 { Skeleton } from "@/components/ui/skeleton";-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))",-];+import { CustomEventsChart } from "./CustomEventsChart";+import { EventTypesChart } from "./EventTypesChart";const EVENT_LIMIT_OPTIONS = [1, 3, 5, 8, 10];-type EventPoint = {- x: string;- y: number;- currentTime: DateTime;-};--type EventSeries = {- id: string;- color: string;- data: EventPoint[];-};+type ChartTab = "custom_events" | "event_types";export function EventsChart() {- const { bucket } = useStore();+ const [tab, setTab] = useState<ChartTab>("custom_events");const [eventLimit, setEventLimit] = useState(5);- const { data, isLoading, isFetching } = 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 next = new Set(prev);- if (next.has(eventName)) {- next.delete(eventName);- } else {- next.add(eventName);- }- return next;- });- };-- 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());- }-- 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");- };-- const controls = (- <>- <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">- Top {option}- </SelectItem>- ))}- </SelectContent>- </Select>- <BucketSelection />- </>- );return (- <Card>- {isFetching && <CardLoader />}- <CardHeader className="flex flex-col gap-0 pb-1">- <div className="flex items-start gap-2">- <CardTitle className="flex-1">Custom Events Over Time</CardTitle>- <div className="hidden items-center gap-2 sm:flex">{controls}</div>- </div>- <div className="mt-2 flex w-full flex-wrap items-center gap-2 sm:-mt-1">- <CardDescription className="mt-0">{eventLimit === 1 ? "Top event" : `Top ${eventLimit} events`}</CardDescription>- <div className="ml-auto flex items-center gap-2 sm:hidden">{controls}</div>- </div>- </CardHeader>- <CardContent className="p-2 md:p-4 pt-0 pb-3 w-full space-y-3">-- {legendItems.length > 0 && (- <div className="mt-2 md:mt-0 flex flex-wrap gap-3 px-2 md:px-0 text-xs text-neutral-500 dark:text-neutral-400">- {legendItems.map(item => {- const isHidden = hiddenEventNames.has(item.id);- return (- <button- key={item.id}- type="button"- onClick={() => toggleEventVisibility(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>- )}-- {isLoading ? (- <Skeleton className="w-full h-[260px] rounded-md" />- ) : series.length === 0 ? (- <div className="h-[260px] w-full flex items-center justify-center">- <div className="text-center text-neutral-500">- <p className="text-sm font-medium">No custom event data available</p>- <p className="text-xs">Try adjusting your date range or filters</p>+ <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">Custom Events</TabsTrigger>+ <TabsTrigger value="event_types">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">+ Top {option}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ <BucketSelection /></div></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">All event series hidden</p>- <p className="text-xs">Click a legend item to show it</p>+ <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">+ Top {option}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ <BucketSelection /></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].sort(- (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>- )}- </CardContent>+ </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></Card>);}diff --git a/client/src/app/[site]/events/page.tsx b/client/src/app/[site]/events/page.tsxindex 5639a5e55..6bac468c2 100644--- a/client/src/app/[site]/events/page.tsx+++ b/client/src/app/[site]/events/page.tsx@@ -1,12 +1,10 @@"use client";-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { EVENT_FILTERS } from "@/lib/filterGroups";import { useGetEventNames } from "../../../api/analytics/hooks/events/useGetEventNames";import { DisabledOverlay } from "../../../components/DisabledOverlay";import { useSetPageTitle } from "../../../hooks/useSetPageTitle";import { SubHeader } from "../components/SubHeader/SubHeader";-import { EventList } from "./components/EventList";import { EventLog } from "./components/EventLog";import { EventsChart } from "./components/EventsChart";@@ -18,12 +16,10 @@ export default function EventsPage() {return (<DisabledOverlay message="Events" featurePath="events">- <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">+ <div className="p-2 md:p-4 mx-auto space-y-3"><SubHeader availableFilters={EVENT_FILTERS} />-<EventsChart />-- <Card className="h-auto lg:h-full">+ {/* <Card className="h-auto lg:h-full"><CardHeader><CardTitle>Custom Events</CardTitle>@@ -31,16 +27,9 @@ export default function EventsPage() {<CardContent><EventList events={eventNamesData || []} isLoading={isLoadingEventNames} size="large" /></CardContent>- </Card>+ </Card> */}- <Card>- <CardHeader>- <CardTitle>Event Log</CardTitle>- </CardHeader>- <CardContent>- <EventLog />- </CardContent>- </Card>+ <EventLog /></div></DisabledOverlay>);diff --git a/client/src/app/[site]/main/components/sections/Devices.tsx b/client/src/app/[site]/main/components/sections/Devices.tsxindex de3a0f2de..788ecc374 100644--- a/client/src/app/[site]/main/components/sections/Devices.tsx+++ b/client/src/app/[site]/main/components/sections/Devices.tsx@@ -8,6 +8,7 @@ import { StandardSection } from "../../../components/shared/StandardSection/Stanimport { Browser } from "../../../components/shared/icons/Browser";import { OperatingSystem } from "../../../components/shared/icons/OperatingSystem";import { Button } from "../../../../../components/ui/button";+import { DeviceIcon } from "../../../components/shared/icons/Device";type Tab = "devices" | "browsers" | "os" | "dimensions" | "browser_versions" | "os_versions";@@ -45,9 +46,7 @@ export function Devices() {getKey={e => e.value}getLabel={e => (<div className="flex gap-2 items-center">- {e.value === "Desktop" && <Monitor className="w-4 h-4" />}- {e.value === "Mobile" && <Smartphone className="w-4 h-4" />}- {e.value === "Tablet" && <Tablet className="w-4 h-4" />}+ <DeviceIcon deviceType={e.value || ""} size={16} />{e.value || "Other"}</div>)}diff --git a/client/src/app/[site]/main/components/sections/SearchConsole.tsx b/client/src/app/[site]/main/components/sections/SearchConsole.tsxindex 30475448a..b300a54c0 100644--- a/client/src/app/[site]/main/components/sections/SearchConsole.tsx+++ b/client/src/app/[site]/main/components/sections/SearchConsole.tsx@@ -1,19 +1,20 @@-import { Expand, Info, Monitor, Smartphone, SquareArrowOutUpRight, Tablet } from "lucide-react";+import { SiGoogle } from "@icons-pack/react-simple-icons";+import { round } from "lodash";+import { Expand, Info, SquareArrowOutUpRight } from "lucide-react";import { useState } from "react";+import { GSCDimension } from "../../../../../api/gsc/endpoints";import { useConnectGSC } from "../../../../../api/gsc/hooks/useConnectGSC";import { useGetGSCConnection } from "../../../../../api/gsc/hooks/useGetGSCConnection";import { useGetGSCData } from "../../../../../api/gsc/hooks/useGetGSCData";-import { GSCDimension } from "../../../../../api/gsc/endpoints";import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";import { Button } from "../../../../../components/ui/button";import { Card, CardContent, CardLoader } from "../../../../../components/ui/card";+import { ScrollArea } from "../../../../../components/ui/scroll-area";import { formatter, getCountryName, truncateString } from "../../../../../lib/utils";import { CountryFlag } from "../../../components/shared/icons/CountryFlag";+import { DeviceIcon } from "../../../components/shared/icons/Device";import { StandardSkeleton } from "../../../components/shared/StandardSection/Skeleton";import { SearchConsoleDialog } from "./SearchConsoleDialog";-import { SiGoogle } from "@icons-pack/react-simple-icons";-import { round } from "lodash";-import { ScrollArea } from "../../../../../components/ui/scroll-area";type Tab = "queries" | "pages" | "countries" | "devices";@@ -215,9 +216,7 @@ export function SearchConsole() {close={close}renderName={e => (<div className="flex gap-2 items-center">- {e === "DESKTOP" && <Monitor className="w-4 h-4" />}- {e === "MOBILE" && <Smartphone className="w-4 h-4" />}- {e === "TABLET" && <Tablet className="w-4 h-4" />}+ <DeviceIcon deviceType={e || ""} size={16} />{e === "DESKTOP" ? "Desktop" : e === "MOBILE" ? "Mobile" : e === "TABLET" ? "Tablet" : "Other"}</div>)}diff --git a/client/src/app/[site]/pages/components/PageListItem.tsx b/client/src/app/[site]/pages/components/PageListItem.tsxindex 258d2e422..db4ca604c 100644--- a/client/src/app/[site]/pages/components/PageListItem.tsx+++ b/client/src/app/[site]/pages/components/PageListItem.tsx@@ -83,7 +83,7 @@ export function PageListItem({ pageData, isLoading = false }: PageListItemProps)};return (- <Card className="w-full mb-3" onMouseEnter={() => setIsHovering(true)} onMouseLeave={() => setIsHovering(false)}>+ <Card className="w-full mb-3 overflow-visible" onMouseEnter={() => setIsHovering(true)} onMouseLeave={() => setIsHovering(false)}><CardContent className="p-3"><div className="flex flex-col md:flex-row justify-between items-start md:items-center w-full gap-4">{/* Left side: Page title/path with thumbnail */}diff --git a/client/src/app/[site]/performance/components/PerformanceChart.tsx b/client/src/app/[site]/performance/components/PerformanceChart.tsxindex e86657cba..aa7eb9657 100644--- a/client/src/app/[site]/performance/components/PerformanceChart.tsx+++ b/client/src/app/[site]/performance/components/PerformanceChart.tsx@@ -191,7 +191,7 @@ export function PerformanceChart() {: [];return (- <Card>+ <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">diff --git a/client/src/app/[site]/performance/components/PerformanceTable.tsx b/client/src/app/[site]/performance/components/PerformanceTable.tsxindex ef05360b3..c8ff5e284 100644--- a/client/src/app/[site]/performance/components/PerformanceTable.tsx+++ b/client/src/app/[site]/performance/components/PerformanceTable.tsx@@ -10,6 +10,7 @@ import {TableRow,TableSortIndicator,} from "@/components/ui/table";+import { FilterParameter } from "@rybbit/shared";import {createColumnHelper,flexRender,@@ -18,22 +19,22 @@ import {SortingState,useReactTable,} from "@tanstack/react-table";-import { Monitor, Smartphone, Tablet, SquareArrowOutUpRight } from "lucide-react";-import { useMemo, useState, useCallback } from "react";+import { SquareArrowOutUpRight } from "lucide-react";+import { useCallback, useMemo, useState } from "react";import { useGetSite } from "../../../../api/admin/hooks/useSites";-import { useGetPerformanceByDimension } from "../../../../api/analytics/hooks/performance/useGetPerformanceByDimension";import { PerformanceByDimensionItem } from "../../../../api/analytics/endpoints";+import { useGetPerformanceByDimension } from "../../../../api/analytics/hooks/performance/useGetPerformanceByDimension";import { Pagination } from "../../../../components/pagination";-import { FilterParameter } from "@rybbit/shared";-import { useStore, addFilter, removeFilter } from "../../../../lib/store";-import { PerformanceMetric, usePerformanceStore } from "../performanceStore";-import { formatMetricValue, getMetricColor, getMetricUnit } from "../utils/performanceUtils";-import { CountryFlag } from "../../components/shared/icons/CountryFlag";+import { CardLoader } from "../../../../components/ui/card";+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 { getCountryName } from "../../../../lib/utils";+import { PerformanceMetric, usePerformanceStore } from "../performanceStore";+import { formatMetricValue, getMetricColor, getMetricUnit } from "../utils/performanceUtils";import { MetricTooltip } from "./shared/MetricTooltip";-import { CardLoader } from "../../../../components/ui/card";const MetricCell = ({metric,@@ -153,13 +154,7 @@ export function PerformanceTable({ dimension, title }: PerformanceTableProps) {</>) : dimension === "device_type" ? (<>- {value === "Desktop" ? (- <Monitor className="h-4 w-4" />- ) : value === "Mobile" ? (- <Smartphone className="h-4 w-4" />- ) : value === "Tablet" ? (- <Tablet className="h-4 w-4" />- ) : null}+ <DeviceIcon deviceType={value || ""} />{value || "Other"}</>) : dimension === "browser" && value ? (@@ -377,11 +372,10 @@ export function PerformanceTable({ dimension, title }: PerformanceTableProps) {{headerGroup.headers.map(header => (<TableHeadkey={header.id}- className={`text-neutral-600 dark:text-neutral-300 ${- header.column.getCanSort()- ? "cursor-pointer hover:text-white transition-colors select-none"- : ""- }`}+ 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">diff --git a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsxindex f4f5643aa..e5d2ef9f2 100644--- a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx+++ b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx@@ -15,6 +15,7 @@ import { OperatingSystem } from "../../../components/shared/icons/OperatingSysteimport { VisitCalendar } from "./Calendar";import { EventIcon, PageviewIcon } from "../../../../../components/EventIcons";import { UserInfo, UserSessionCountResponse } from "../../../../../api/analytics/endpoints";+import { DeviceIcon } from "../../../components/shared/icons/Device";interface UserSidebarProps {data: UserInfo | undefined;@@ -215,13 +216,7 @@ export function UserSidebar({ data, isLoading, sessionCount, getRegionName }: Us<InfoRow label="Language" value={data?.language ? getLanguageName(data.language) : "—"} /><InfoRowicon={- data?.device_type === "Desktop" ? (- <Monitor className="w-4 h-4" />- ) : data?.device_type === "Mobile" ? (- <Smartphone className="w-4 h-4" />- ) : data?.device_type === "Tablet" ? (- <Tablet className="w-4 h-4" />- ) : null+ <DeviceIcon deviceType={data?.device_type || ""} size={13} />}label="Device"value={data?.device_type ?? "—"}diff --git a/client/src/app/[site]/users/page.tsx b/client/src/app/[site]/users/page.tsxindex 44485ed02..5c31eda96 100644--- a/client/src/app/[site]/users/page.tsx+++ b/client/src/app/[site]/users/page.tsx@@ -37,6 +37,7 @@ import { Browser } from "../components/shared/icons/Browser";import { CountryFlag } from "../components/shared/icons/CountryFlag";import { OperatingSystem } from "../components/shared/icons/OperatingSystem";import { SubHeader } from "../components/SubHeader/SubHeader";+import { DeviceIcon } from "../components/shared/icons/Device";// Set up column helperconst columnHelper = createColumnHelper<UsersResponse>();@@ -233,9 +234,7 @@ export default function UsersPage() {className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"onClick={e => handleFilterClick(e, "device_type", deviceType)}>- {deviceType === "Desktop" && <Monitor className="w-4 h-4" />}- {deviceType === "Mobile" && <Smartphone className="w-4 h-4" />}- {deviceType === "Tablet" && <Tablet className="w-4 h-4" />}+ <DeviceIcon deviceType={deviceType || ""} />{deviceType}</div>);diff --git a/client/src/app/components/Footer.tsx b/client/src/app/components/Footer.tsxindex 948e2e623..cdc006a5b 100644--- a/client/src/app/components/Footer.tsx+++ b/client/src/app/components/Footer.tsx@@ -13,7 +13,7 @@ export function Footer() {}return (- <footer className="border-t border-neutral-200 dark:border-neutral-850 bg-neutral-50 dark:bg-neutral-900 mt-8">+ <footer className="border-t border-neutral-200 dark:border-neutral-850 bg-neutral-50 dark:bg-neutral-900"><div className="max-w-[1100px] mx-auto px-4 py-12">{/* Main Footer Content */}<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-8">diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsxindex e8ddf42c0..c8c0b1406 100644--- a/client/src/components/Sessions/SessionCard.tsx+++ b/client/src/components/Sessions/SessionCard.tsx@@ -29,9 +29,10 @@ interface SessionCardProps {userId?: string;onClick?: () => void;expandedByDefault?: boolean;+ highlightedEventTimestamp?: number;}-export function SessionCard({ session, onClick, userId, expandedByDefault }: SessionCardProps) {+export function SessionCard({ session, onClick, userId, expandedByDefault, highlightedEventTimestamp }: SessionCardProps) {const { site } = useParams();const [expanded, setExpanded] = useState(expandedByDefault || false);const [replayDrawerOpen, setReplayDrawerOpen] = useState(false);@@ -307,7 +308,7 @@ export function SessionCard({ session, onClick, userId, expandedByDefault }: Ses</div>{/* Expanded content using SessionDetails component */}- {expanded && <SessionDetails session={session} userId={userId} />}+ {expanded && <SessionDetails session={session} userId={userId} highlightedEventTimestamp={highlightedEventTimestamp} />}{/* Replay Drawer */}{session.has_replay === 1 && (diff --git a/client/src/components/Sessions/SessionDetails/PageviewItem.tsx b/client/src/components/Sessions/SessionDetails/PageviewItem.tsxindex acd1546c4..62f01fa66 100644--- a/client/src/components/Sessions/SessionDetails/PageviewItem.tsx+++ b/client/src/components/Sessions/SessionDetails/PageviewItem.tsx@@ -129,8 +129,8 @@ function renderDetails(const propsToHide = PROPS_TO_HIDE[item.type] || [];const remainingProps = item.props? Object.entries(item.props).filter(- ([key]) => !propsToHide.includes(key)- )+ ([key]) => !propsToHide.includes(key)+ ): [];if (remainingProps.length === 0) return null;@@ -155,6 +155,7 @@ interface PageviewItemProps {isLast?: boolean;nextTimestamp?: string;showHostname?: boolean;+ highlightedEventTimestamp?: number;}export function PageviewItem({@@ -163,6 +164,7 @@ export function PageviewItem({isLast = false,nextTimestamp,showHostname = true,+ highlightedEventTimestamp,}: PageviewItemProps) {const isPageview = item.type === "pageview";const isOutbound = item.type === "outbound";@@ -176,6 +178,7 @@ export function PageviewItem({getTimezone());const formattedTime = timestamp.toFormat(hour12 ? "h:mm:ss a" : "HH:mm:ss");+ const isHighlightedEvent = highlightedEventTimestamp === DateTime.fromSQL(item.timestamp, { zone: "utc" }).toMillis();// Calculate duration if this is a pageview and we have the next timestamplet duration = null;@@ -203,7 +206,8 @@ export function PageviewItem({<divclassName={cn("flex items-center justify-center w-8 h-8 rounded-full border",- "bg-neutral-50 border-neutral-200 dark:bg-neutral-600/10 dark:border-neutral-600/25"+ "bg-neutral-50 border-neutral-200 dark:bg-neutral-600/10 dark:border-neutral-600/25",+ isHighlightedEvent && "bg-accent-400 border-accent-300 dark:bg-accent-600 dark:border-accent-500")}><span className="text-sm font-medium">{index + 1}</span>diff --git a/client/src/components/Sessions/SessionDetails/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails/SessionDetails.tsxindex ccd8189d2..260989494 100644--- a/client/src/components/Sessions/SessionDetails/SessionDetails.tsx+++ b/client/src/components/Sessions/SessionDetails/SessionDetails.tsx@@ -15,9 +15,10 @@ import { TimelineTab } from "./TimelineTab";interface SessionDetailsProps {session: GetSessionsResponse[number];userId?: string;+ highlightedEventTimestamp?: number;}-export function SessionDetails({ session, userId }: SessionDetailsProps) {+export function SessionDetails({ session, userId, highlightedEventTimestamp }: SessionDetailsProps) {const {data: sessionDetailsData,isLoading,@@ -105,6 +106,7 @@ export function SessionDetails({ session, userId }: SessionDetailsProps) {<TabsContent value="timeline"><TimelineTab+ highlightedEventTimestamp={highlightedEventTimestamp}allEvents={allEvents}filteredEvents={filteredEvents}visibleEventTypes={visibleEventTypes}diff --git a/client/src/components/Sessions/SessionDetails/SessionInfoTab.tsx b/client/src/components/Sessions/SessionDetails/SessionInfoTab.tsxindex f38883207..42f4cbd47 100644--- a/client/src/components/Sessions/SessionDetails/SessionInfoTab.tsx+++ b/client/src/components/Sessions/SessionDetails/SessionInfoTab.tsx@@ -8,6 +8,7 @@ import { useGetRegionName } from "../../../lib/geo";import { getCountryName, getLanguageName } from "../../../lib/utils";import { Avatar, generateName } from "../../Avatar";import { IdentifiedBadge } from "../../IdentifiedBadge";+import { DeviceIcon } from "../../../app/[site]/components/shared/icons/Device";interface SessionInfoTabProps {session: GetSessionsResponse[number];@@ -63,8 +64,8 @@ export function SessionInfoTab({<span className="font-medium text-neutral-600 dark:text-neutral-300">{isIdentified? (session.traits?.username as string) ||- (session.traits?.name as string) ||- session.identified_user_id+ (session.traits?.name as string) ||+ session.identified_user_id: generateName(sessionDetails.user_id)}</span>{isIdentified && (@@ -153,15 +154,7 @@ export function SessionInfoTab({Device:</span><div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">- {sessionDetails?.device_type === "Desktop" && (- <Monitor className="w-4 h-4" />- )}- {sessionDetails?.device_type === "Mobile" && (- <Smartphone className="w-4 h-4" />- )}- {sessionDetails?.device_type === "Tablet" && (- <Tablet className="w-4 h-4" />- )}+ <DeviceIcon deviceType={sessionDetails?.device_type || ""} /><span>{sessionDetails?.device_type || "Unknown"}</span></div></div>@@ -205,7 +198,7 @@ export function SessionInfoTab({</div>{sessionDetails?.screen_width &&- sessionDetails?.screen_height ? (+ sessionDetails?.screen_height ? (<div className="flex items-center gap-2 text-sm"><span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">Screen:diff --git a/client/src/components/Sessions/SessionDetails/TimelineTab.tsx b/client/src/components/Sessions/SessionDetails/TimelineTab.tsxindex 49663bd11..090b32d16 100644--- a/client/src/components/Sessions/SessionDetails/TimelineTab.tsx+++ b/client/src/components/Sessions/SessionDetails/TimelineTab.tsx@@ -15,9 +15,11 @@ interface TimelineTabProps {isFetchingNextPage: boolean;fetchNextPage: () => void;totalEvents: number;+ highlightedEventTimestamp?: number;}export function TimelineTab({+ highlightedEventTimestamp,allEvents,filteredEvents,visibleEventTypes,@@ -63,6 +65,7 @@ export function TimelineTab({isLast={index === filteredEvents.length - 1 && !hasNextPage}nextTimestamp={nextTimestamp}showHostname={showHostname}+ highlightedEventTimestamp={highlightedEventTimestamp}/>);})}diff --git a/client/src/components/ui/sheet.tsx b/client/src/components/ui/sheet.tsxindex ce24aff11..90d9b9ba6 100644--- a/client/src/components/ui/sheet.tsx+++ b/client/src/components/ui/sheet.tsx@@ -31,7 +31,7 @@ const SheetOverlay = React.forwardRef<SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;const sheetVariants = cva(- "fixed z-50 gap-4 bg-white p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out dark:bg-neutral-950",+ "fixed z-50 gap-4 bg-white p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300 data-[state=open]:animate-in data-[state=closed]:animate-out dark:bg-neutral-950",{variants: {side: {@@ -51,7 +51,7 @@ const sheetVariants = cva(interface SheetContentPropsextends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,- VariantProps<typeof sheetVariants> {}+ VariantProps<typeof sheetVariants> { }const SheetContent = React.forwardRef<React.ElementRef<typeof SheetPrimitive.Content>,diff --git a/client/src/lib/events.ts b/client/src/lib/events.tsindex 6e6803285..1bc4e90de 100644--- a/client/src/lib/events.ts+++ b/client/src/lib/events.ts@@ -19,14 +19,14 @@ export interface EventTypeConfig {}export const EVENT_TYPE_CONFIG: EventTypeConfig[] = [- { value: "pageview", label: "Pageviews", colorClass: "text-blue-400" },- { value: "custom_event", label: "Events", colorClass: "text-amber-400" },+ { value: "pageview", label: "Pageview", colorClass: "text-blue-400" },+ { value: "custom_event", label: "Event", colorClass: "text-amber-400" },{ value: "outbound", label: "Outbound", colorClass: "text-lime-400" },- { value: "button_click", label: "Button Clicks", colorClass: "text-green-400" },- { value: "copy", label: "Copies", colorClass: "text-sky-400" },- { value: "form_submit", label: "Form Submits", colorClass: "text-purple-400" },- { value: "input_change", label: "Input Changes", colorClass: "text-pink-400" },- { value: "error", label: "Errors", colorClass: "text-red-400" },+ { value: "button_click", label: "Button Click", colorClass: "text-green-400" },+ { value: "copy", label: "Copy", colorClass: "text-sky-400" },+ { value: "form_submit", label: "Form Submit", colorClass: "text-purple-400" },+ { value: "input_change", label: "Input Change", colorClass: "text-pink-400" },+ { value: "error", label: "Error", colorClass: "text-red-400" },];// ============================================================================diff --git a/client/src/providers/QueryProvider.tsx b/client/src/providers/QueryProvider.tsxindex ce6ba9b5d..a8d56c903 100644--- a/client/src/providers/QueryProvider.tsx+++ b/client/src/providers/QueryProvider.tsx@@ -10,7 +10,7 @@ export default function QueryProvider({ children }: { children: React.ReactNodereturn (<QueryClientProvider client={queryClient}>{children}- {/* <ReactQueryDevtools initialIsOpen={false} /> */}+ <ReactQueryDevtools initialIsOpen={false} /></QueryClientProvider>);}diff --git a/server/public/script-full.js b/server/public/script-full.jsindex 4b6373bbb..31a15d825 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -6,6 +6,14 @@// utils.tsfunction patternToRegex(pattern) {+ const REGEX_PREFIX = "re:";+ if (pattern.startsWith(REGEX_PREFIX)) {+ const rawRegex = pattern.slice(REGEX_PREFIX.length);+ if (!rawRegex) {+ throw new Error("Empty regex pattern");+ }+ return new RegExp(rawRegex);+ }const DOUBLE_WILDCARD_TOKEN = "__DOUBLE_ASTERISK_TOKEN__";const SINGLE_WILDCARD_TOKEN = "__SINGLE_ASTERISK_TOKEN__";let tokenized = pattern.replace(/\*\*/g, DOUBLE_WILDCARD_TOKEN).replace(/\*/g, SINGLE_WILDCARD_TOKEN);diff --git a/server/public/script.js b/server/public/script.jsindex db4255387..eb81dc83b 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var Mt=Object.defineProperty;var At=(n,t,e)=>t in n?Mt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var b=(n,t,e)=>At(n,typeof t!="symbol"?t+"":t,e);function Lt(n){let t="__DOUBLE_ASTERISK_TOKEN__",e="__SINGLE_ASTERISK_TOKEN__",i=n.replace(/\*\*/g,t).replace(/\*/g,e).replace(/[.+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),i=i.replace(new RegExp(t,"g"),".*"),i=i.replace(/\//g,"\\/");let s=i.replace(new RegExp(e,"g"),"[^/]+");return new RegExp("^"+s+"$")}function _(n,t){for(let e of t)try{if(Lt(e).test(n))return e}catch(r){console.error(`Invalid pattern: ${e}`,r)}return null}function nt(n,t){let e=null;return(...r)=>{e&&clearTimeout(e),e=setTimeout(()=>n(...r),t)}}function it(n){try{let t=window.location.hostname,e=new URL(n).hostname;return e!==t&&e!==""}catch{return!1}}function v(n,t){if(!n)return t;try{let e=JSON.parse(n);return Array.isArray(t)&&!Array.isArray(e)?t:e}catch(e){return console.error("Error parsing JSON:",e),t}}async function st(n){let t=n.getAttribute("src");if(!t)return console.error("Script src attribute is missing"),null;let e=t.split("/script.js")[0];if(!e)return console.error("Please provide a valid analytics host"),null;let r=n.getAttribute("data-site-id")||n.getAttribute("site-id");if(!r)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=n.getAttribute("data-namespace")||"rybbit",s=v(n.getAttribute("data-skip-patterns"),[]),o=v(n.getAttribute("data-mask-patterns"),[]),a=v(n.getAttribute("data-replay-mask-text-selectors"),[]),d=n.getAttribute("data-debounce")?Math.max(0,parseInt(n.getAttribute("data-debounce"))):500,u=n.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(n.getAttribute("data-replay-batch-size"))):250,g=n.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(n.getAttribute("data-replay-batch-interval"))):5e3,c=n.getAttribute("data-replay-block-class")||void 0,l=n.getAttribute("data-replay-block-selector")||void 0,p=n.getAttribute("data-replay-ignore-class")||void 0,E=n.getAttribute("data-replay-ignore-selector")||void 0,T=n.getAttribute("data-replay-mask-text-class")||void 0,w=n.getAttribute("data-replay-mask-all-inputs"),St=w!==null?w!=="false":void 0,Y=n.getAttribute("data-replay-mask-input-options"),Ct=Y?v(Y,{password:!0,email:!0}):void 0,X=n.getAttribute("data-replay-collect-fonts"),Et=X!==null?X!=="false":void 0,Z=n.getAttribute("data-replay-sampling"),wt=Z?v(Z,{}):void 0,tt=n.getAttribute("data-replay-slim-dom-options"),Pt=tt?v(tt,{}):void 0,et=n.getAttribute("data-replay-sample-rate"),It=et?Math.min(100,Math.max(0,parseInt(et,10))):void 0,h={namespace:i,analyticsHost:e,siteId:r,debounceDuration:d,sessionReplayBatchSize:u,sessionReplayBatchInterval:g,sessionReplayMaskTextSelectors:a,skipPatterns:s,maskPatterns:o,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,sessionReplayBlockClass:c,sessionReplayBlockSelector:l,sessionReplayIgnoreClass:p,sessionReplayIgnoreSelector:E,sessionReplayMaskTextClass:T,sessionReplayMaskAllInputs:St,sessionReplayMaskInputOptions:Ct,sessionReplayCollectFonts:Et,sessionReplaySampling:wt,sessionReplaySlimDOMOptions:Pt,sessionReplaySampleRate:It};try{let U=`${e}/site/tracking-config/${r}`,rt=await fetch(U,{method:"GET",credentials:"omit"});if(rt.ok){let m=await rt.json();return{...h,autoTrackPageview:m.trackInitialPageView??h.autoTrackPageview,autoTrackSpa:m.trackSpaNavigation??h.autoTrackSpa,trackQuerystring:m.trackUrlParams??h.trackQuerystring,trackOutbound:m.trackOutbound??h.trackOutbound,enableWebVitals:m.webVitals??h.enableWebVitals,trackErrors:m.trackErrors??h.trackErrors,enableSessionReplay:m.sessionReplay??h.enableSessionReplay,trackButtonClicks:m.trackButtonClicks??h.trackButtonClicks,trackCopy:m.trackCopy??h.trackCopy,trackFormInteractions:m.trackFormInteractions??h.trackFormInteractions}}else return console.warn("Failed to fetch tracking config from API, using defaults"),h}catch(U){return console.warn("Error fetching tracking config:",U),h}}var at="rybbit-replay-sampled";function Bt(n){if(n>=100)return!0;if(n<=0)return!1;try{let t=sessionStorage.getItem(at);if(t!==null)return t==="1";let e=Math.random()*100<n;return sessionStorage.setItem(at,e?"1":"0"),e}catch{return Math.random()*100<n}}var P=class{constructor(t,e,r){this.isRecording=!1;this.eventBuffer=[];this.config=t,this.userId=e,this.sendBatch=r}async initialize(){if(!this.config.enableSessionReplay)return;let t=this.config.sessionReplaySampleRate;t!==void 0&&!Bt(t)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((t,e)=>{let r=document.createElement("script");r.src=`${this.config.analyticsHost}/replay.js`,r.async=!1,r.onload=()=>{t()},r.onerror=()=>e(new Error("Failed to load rrweb")),document.head.appendChild(r)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let t={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},e={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},r={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??t,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??e};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(r.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(r),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(t){this.eventBuffer.push(t),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let t=[...this.eventBuffer];this.eventBuffer=[];let e={userId:this.userId,events:t,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(e)}catch{this.eventBuffer.unshift(...t)}}updateUserId(t){this.userId=t}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var I=class{constructor(t){this.customUserId=null;this.config=t,this.loadUserId(),t.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let t=localStorage.getItem(`${this.config.namespace}-user-id`);t&&(this.customUserId=t)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new P(this.config,this.customUserId||"",t=>this.sendSessionReplayBatch(t)),await this.sessionReplayRecorder.initialize()}catch(t){console.error("Failed to initialize session replay:",t)}}async sendSessionReplayBatch(t){try{await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!1})}catch(e){throw console.error("Failed to send session replay batch:",e),e}}createBasePayload(){let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),_(e,this.config.skipPatterns))return null;let r=_(e,this.config.maskPatterns);r&&(e=r);let i={site_id:this.config.siteId,hostname:t.hostname,pathname:e,querystring:this.config.trackQuerystring?t.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(i.user_id=this.customUserId),i}async sendTrackingData(t){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0})}catch(e){console.error("Failed to send tracking data:",e)}}track(t,e="",r={}){if(t==="custom_event"&&(!e||typeof e!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let o={...i,type:t,event_name:e,properties:["custom_event","outbound","error","button_click","copy","form_submit","input_change"].includes(t)?JSON.stringify(r):void 0};this.sendTrackingData(o)}trackPageview(){this.track("pageview")}trackEvent(t,e={}){this.track("custom_event",t,e)}trackOutbound(t,e="",r="_self"){this.track("outbound","",{url:t,text:e,target:r})}trackWebVitals(t){let e=this.createBasePayload();if(!e)return;let r={...e,type:"performance",event_name:"web-vitals",...t};this.sendTrackingData(r)}trackError(t,e={}){let r=window.location.origin,i=e.filename||"",s=t.stack||"";if(i)try{if(new URL(i).origin!==r)return}catch{}else if(s&&!s.includes(r))return;let o={message:t.message?.substring(0,500)||"Unknown error",stack:s.substring(0,2e3)||""};if(i&&(o.fileName=i),e.lineno){let a=typeof e.lineno=="string"?parseInt(e.lineno,10):e.lineno;a&&a!==0&&(o.lineNumber=a)}if(e.colno){let a=typeof e.colno=="string"?parseInt(e.colno,10):e.colno;a&&a!==0&&(o.columnNumber=a)}for(let a in e)!["lineno","colno"].includes(a)&&e[a]!==void 0&&(o[a]=e[a]);this.track("error",t.name||"Error",o)}trackButtonClick(t){this.track("button_click","",t)}trackCopy(t){this.track("copy","",t)}trackFormSubmit(t){this.track("form_submit","",t)}trackInputChange(t){this.track("input_change","",t)}identify(t,e){if(typeof t!="string"||t.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=t.trim();try{localStorage.setItem(`${this.config.namespace}-user-id`,this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sendIdentifyEvent(this.customUserId,e,!0),this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}setTraits(t){if(!t||typeof t!="object"){console.error("Traits must be an object");return}let e=this.customUserId;if(!e){console.warn("Cannot set traits without identifying user first. Call identify() first.");return}this.sendIdentifyEvent(e,t,!1)}async sendIdentifyEvent(t,e,r=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:t,traits:e,is_new_identify:r}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var mt=-1,R=n=>{addEventListener("pageshow",(t=>{t.persisted&&(mt=t.timeStamp,n(t))}),!0)},f=(n,t,e,r)=>{let i,s;return o=>{t.value>=0&&(o||r)&&(s=t.value-(i??0),(s||i===void 0)&&(i=t.value,t.delta=s,t.rating=((a,d)=>a>d[1]?"poor":a>d[0]?"needs-improvement":"good")(t.value,e),n(t)))}},J=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},K=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},S=()=>K()?.activationStart??0,y=(n,t=-1)=>{let e=K(),r="navigate";return mt>=0?r="back-forward-cache":e&&(document.prerendering||S()>0?r="prerender":document.wasDiscarded?r="restore":e.type&&(r=e.type.replace(/_/g,"-"))),{name:n,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},D=new WeakMap;function q(n,t){return D.get(n)||D.set(n,new t),D.get(n)}var F=class{constructor(){b(this,"t");b(this,"i",0);b(this,"o",[])}h(t){if(t.hadRecentInput)return;let e=this.o[0],r=this.o.at(-1);this.i&&e&&r&&t.startTime-r.startTime<1e3&&t.startTime-e.startTime<5e3?(this.i+=t.value,this.o.push(t)):(this.i=t.value,this.o=[t]),this.t?.(t)}},C=(n,t,e={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(n)){let r=new PerformanceObserver((i=>{Promise.resolve().then((()=>{t(i.getEntries())}))}));return r.observe({type:n,buffered:!0,...e}),r}}catch{}},G=n=>{let t=!1;return()=>{t||(n(),t=!0)}},k=-1,ft=new Set,ot=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,W=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let t of ft)t();isFinite(k)||(k=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",W,!0))}},A=()=>{if(k<0){let n=S();k=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((e=>e.name==="hidden"&&e.startTime>n))[0]?.startTime)??ot(),addEventListener("visibilitychange",W,!0),addEventListener("prerenderingchange",W,!0),R((()=>{setTimeout((()=>{k=ot()}))}))}return{get firstHiddenTime(){return k},onHidden(n){ft.add(n)}}},L=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},ct=[1800,3e3],Q=(n,t={})=>{L((()=>{let e=A(),r,i=y("FCP"),s=C("paint",(o=>{for(let a of o)a.name==="first-contentful-paint"&&(s.disconnect(),a.startTime<e.firstHiddenTime&&(i.value=Math.max(a.startTime-S(),0),i.entries.push(a),r(!0)))}));s&&(r=f(n,i,ct,t.reportAllChanges),R((o=>{i=y("FCP"),r=f(n,i,ct,t.reportAllChanges),J((()=>{i.value=performance.now()-o.timeStamp,r(!0)}))})))}))},lt=[.1,.25],yt=(n,t={})=>{let e=A();Q(G((()=>{let r,i=y("CLS",0),s=q(t,F),o=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},a=C("layout-shift",o);a&&(r=f(n,i,lt,t.reportAllChanges),e.onHidden((()=>{o(a.takeRecords()),r(!0)})),R((()=>{s.i=0,i=y("CLS",0),r=f(n,i,lt,t.reportAllChanges),J((()=>r()))})),setTimeout(r))})))},bt=0,H=1/0,M=0,xt=n=>{for(let t of n)t.interactionId&&(H=Math.min(H,t.interactionId),M=Math.max(M,t.interactionId),bt=M?(M-H)/7+1:0)},z,ut=()=>z?bt:performance.interactionCount??0,Ot=()=>{"interactionCount"in performance||z||(z=C("event",xt,{type:"event",buffered:!0,durationThreshold:0}))},dt=0,V=class{constructor(){b(this,"u",[]);b(this,"l",new Map);b(this,"m");b(this,"p")}v(){dt=ut(),this.u.length=0,this.l.clear()}L(){let t=Math.min(this.u.length-1,Math.floor((ut()-dt)/50));return this.u[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;let e=this.u.at(-1),r=this.l.get(t.interactionId);if(r||this.u.length<10||t.duration>e.P){if(r?t.duration>r.P?(r.entries=[t],r.P=t.duration):t.duration===r.P&&t.startTime===r.entries[0].startTime&&r.entries.push(t):(r={id:t.interactionId,entries:[t],P:t.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort(((i,s)=>s.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let s of i)this.l.delete(s.id)}this.p?.(r)}}},vt=n=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=G(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),t((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},pt=[200,500],kt=(n,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let e=A();L((()=>{Ot();let r,i=y("INP"),s=q(t,V),o=d=>{vt((()=>{for(let g of d)s.h(g);let u=s.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,r())}))},a=C("event",o,{durationThreshold:t.durationThreshold??40});r=f(n,i,pt,t.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),e.onHidden((()=>{o(a.takeRecords()),r(!0)})),R((()=>{s.v(),i=y("INP"),r=f(n,i,pt,t.reportAllChanges)})))}))},$=class{constructor(){b(this,"m")}h(t){this.m?.(t)}},ht=[2500,4e3],Rt=(n,t={})=>{L((()=>{let e=A(),r,i=y("LCP"),s=q(t,$),o=d=>{t.reportAllChanges||(d=d.slice(-1));for(let u of d)s.h(u),u.startTime<e.firstHiddenTime&&(i.value=Math.max(u.startTime-S(),0),i.entries=[u],r())},a=C("largest-contentful-paint",o);if(a){r=f(n,i,ht,t.reportAllChanges);let d=G((()=>{o(a.takeRecords()),a.disconnect(),r(!0)})),u=g=>{g.isTrusted&&(vt(d),removeEventListener(g.type,u,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,u,{capture:!0});R((g=>{i=y("LCP"),r=f(n,i,ht,t.reportAllChanges),J((()=>{i.value=performance.now()-g.timeStamp,r(!0)}))}))}}))},gt=[800,1800],j=n=>{document.prerendering?L((()=>j(n))):document.readyState!=="complete"?addEventListener("load",(()=>j(n)),!0):setTimeout(n)},Tt=(n,t={})=>{let e=y("TTFB"),r=f(n,e,gt,t.reportAllChanges);j((()=>{let i=K();i&&(e.value=Math.max(i.responseStart-S(),0),e.entries=[i],r(!0),R((()=>{e=y("TTFB",0),r=f(n,e,gt,t.reportAllChanges),r(!0)})))}))};var B=class{constructor(t){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=t}initialize(){try{Rt(this.collectMetric.bind(this)),yt(this.collectMetric.bind(this)),kt(this.collectMetric.bind(this)),Q(this.collectMetric.bind(this)),Tt(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(t){console.warn("Error initializing web vitals tracking:",t)}}collectMetric(t){if(this.sent)return;let e=t.name.toLowerCase();this.data[e]=t.value,Object.values(this.data).every(i=>i!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};var x=class{constructor(t,e){this.tracker=t,this.config=e}initialize(){document.addEventListener("click",this.handleClick.bind(this),!0)}handleClick(t){let e=t.target;this.config.trackButtonClicks&&this.isButton(e)&&this.trackButtonClick(e)}isButton(t){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;if(t.tagName==="INPUT"){let i=t.type?.toLowerCase();if(i==="submit"||i==="button")return!0}let e=t.parentElement,r=0;for(;e&&r<3;){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return!0;e=e.parentElement,r++}return!1}trackButtonClick(t){let e=this.findButton(t);if(!e||e.hasAttribute("data-rybbit-event"))return;let r={text:this.getElementText(e),...this.extractDataAttributes(e)};this.tracker.trackButtonClick(r)}extractDataAttributes(t){let e={};for(let r of t.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");e[i]=r.value}return e}findButton(t){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;if(t.tagName==="INPUT"){let i=t.type?.toLowerCase();if(i==="submit"||i==="button")return t}let e=t.parentElement,r=0;for(;e&&r<3;){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return e;e=e.parentElement,r++}return null}getElementText(t){return t.textContent?.trim().substring(0,100)||void 0}cleanup(){document.removeEventListener("click",this.handleClick.bind(this),!0)}};var O=class{constructor(t){this.tracker=t}initialize(){document.addEventListener("copy",this.handleCopy.bind(this))}handleCopy(){let t=window.getSelection();if(!t||t.isCollapsed)return;let e=t.toString(),r=e.length;if(r===0)return;let i=t.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let o={text:e.substring(0,500),...r>500&&{textLength:r},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(o)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var N=class{constructor(t,e){this.tracker=t,this.config=e,this.boundHandleSubmit=this.handleSubmit.bind(this),this.boundHandleChange=this.handleChange.bind(this)}initialize(){document.addEventListener("submit",this.boundHandleSubmit,!0),document.addEventListener("change",this.boundHandleChange,!0)}cleanup(){document.removeEventListener("submit",this.boundHandleSubmit,!0),document.removeEventListener("change",this.boundHandleChange,!0)}handleSubmit(t){let e=t.target;if(e.tagName!=="FORM")return;let r={formId:e.id||"",formName:e.name||"",formAction:e.action||"",method:(e.method||"get").toUpperCase(),fieldCount:e.elements.length,...this.extractDataAttributes(e)};this.tracker.trackFormSubmit(r)}handleChange(t){let e=t.target,r=e.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(r))return;if(r==="INPUT"){let s=e.type?.toLowerCase();if(s==="hidden"||s==="password")return}let i={element:r.toLowerCase(),inputType:r==="INPUT"?e.type?.toLowerCase():void 0,inputName:e.name||e.id||"",formId:e.form?.id||void 0,...this.extractDataAttributes(e)};this.tracker.trackInputChange(i)}extractDataAttributes(t){let e={};for(let r of t.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");e[i]=r.value}return e}};(async function(){let n=document.currentScript;if(!n){console.error("Could not find current script tag");return}let t=n.getAttribute("data-namespace")||"rybbit",e=`disable-${t}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(e)!==null){window[t]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let r=await st(n);if(!r)return;let i=new I(r);r.enableWebVitals&&new B(l=>{i.trackWebVitals(l)}).initialize();let s=null,o=null,a=null;r.trackButtonClicks&&(s=new x(i,r),s.initialize()),r.trackCopy&&(o=new O(i),o.initialize()),r.trackFormInteractions&&(a=new N(i,r),a.initialize()),r.trackErrors&&(window.addEventListener("error",c=>{i.trackError(c.error||new Error(c.message),{filename:c.filename,lineno:c.lineno,colno:c.colno})}),window.addEventListener("unhandledrejection",c=>{let l=c.reason instanceof Error?c.reason:new Error(String(c.reason));i.trackError(l,{type:"unhandledrejection"})}));let d=()=>i.trackPageview(),u=r.debounceDuration>0?nt(d,r.debounceDuration):d;function g(){if(document.addEventListener("click",function(c){let l=c.target;for(;l&&l!==document.documentElement;){if(l.hasAttribute("data-rybbit-event")){let p=l.getAttribute("data-rybbit-event");if(p){let E={};for(let T of l.attributes)if(T.name.startsWith("data-rybbit-prop-")){let w=T.name.replace("data-rybbit-prop-","");E[w]=T.value}i.trackEvent(p,E)}break}l=l.parentElement}if(r.trackOutbound){let p=c.target.closest("a");p?.href&&it(p.href)&&i.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),r.autoTrackSpa){let c=history.pushState,l=history.replaceState;history.pushState=function(...p){c.apply(this,p),u(),i.onPageChange()},history.replaceState=function(...p){l.apply(this,p),u(),i.onPageChange()},window.addEventListener("popstate",()=>{u(),i.onPageChange()}),window.addEventListener("hashchange",()=>{u(),i.onPageChange()})}}window[r.namespace]={pageview:()=>i.trackPageview(),event:(c,l={})=>i.trackEvent(c,l),error:(c,l={})=>i.trackError(c,l),trackOutbound:(c,l="",p="_self")=>i.trackOutbound(c,l,p),identify:(c,l)=>i.identify(c,l),setTraits:c=>i.setTraits(c),clearUserId:()=>i.clearUserId(),getUserId:()=>i.getUserId(),startSessionReplay:()=>i.startSessionReplay(),stopSessionReplay:()=>i.stopSessionReplay(),isSessionReplayActive:()=>i.isSessionReplayActive()},g(),window.addEventListener("beforeunload",()=>{s?.cleanup(),o?.cleanup(),i.cleanup()}),r.autoTrackPageview&&i.trackPageview()})();})();+"use strict";(()=>{var Mt=Object.defineProperty;var At=(n,t,e)=>t in n?Mt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var b=(n,t,e)=>At(n,typeof t!="symbol"?t+"":t,e);function Lt(n){if(n.startsWith("re:")){let a=n.slice(3);if(!a)throw new Error("Empty regex pattern");return new RegExp(a)}let e="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",s=n.replace(/\*\*/g,e).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),s=s.replace(new RegExp(e,"g"),".*"),s=s.replace(/\//g,"\\/");let o=s.replace(new RegExp(r,"g"),"[^/]+");return new RegExp("^"+o+"$")}function U(n,t){for(let e of t)try{if(Lt(e).test(n))return e}catch(r){console.error(`Invalid pattern: ${e}`,r)}return null}function nt(n,t){let e=null;return(...r)=>{e&&clearTimeout(e),e=setTimeout(()=>n(...r),t)}}function it(n){try{let t=window.location.hostname,e=new URL(n).hostname;return e!==t&&e!==""}catch{return!1}}function v(n,t){if(!n)return t;try{let e=JSON.parse(n);return Array.isArray(t)&&!Array.isArray(e)?t:e}catch(e){return console.error("Error parsing JSON:",e),t}}async function st(n){let t=n.getAttribute("src");if(!t)return console.error("Script src attribute is missing"),null;let e=t.split("/script.js")[0];if(!e)return console.error("Please provide a valid analytics host"),null;let r=n.getAttribute("data-site-id")||n.getAttribute("site-id");if(!r)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=n.getAttribute("data-namespace")||"rybbit",s=v(n.getAttribute("data-skip-patterns"),[]),o=v(n.getAttribute("data-mask-patterns"),[]),a=v(n.getAttribute("data-replay-mask-text-selectors"),[]),d=n.getAttribute("data-debounce")?Math.max(0,parseInt(n.getAttribute("data-debounce"))):500,u=n.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(n.getAttribute("data-replay-batch-size"))):250,g=n.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(n.getAttribute("data-replay-batch-interval"))):5e3,c=n.getAttribute("data-replay-block-class")||void 0,l=n.getAttribute("data-replay-block-selector")||void 0,p=n.getAttribute("data-replay-ignore-class")||void 0,C=n.getAttribute("data-replay-ignore-selector")||void 0,T=n.getAttribute("data-replay-mask-text-class")||void 0,w=n.getAttribute("data-replay-mask-all-inputs"),St=w!==null?w!=="false":void 0,Q=n.getAttribute("data-replay-mask-input-options"),Et=Q?v(Q,{password:!0,email:!0}):void 0,Y=n.getAttribute("data-replay-collect-fonts"),Ct=Y!==null?Y!=="false":void 0,Z=n.getAttribute("data-replay-sampling"),wt=Z?v(Z,{}):void 0,tt=n.getAttribute("data-replay-slim-dom-options"),Pt=tt?v(tt,{}):void 0,et=n.getAttribute("data-replay-sample-rate"),It=et?Math.min(100,Math.max(0,parseInt(et,10))):void 0,h={namespace:i,analyticsHost:e,siteId:r,debounceDuration:d,sessionReplayBatchSize:u,sessionReplayBatchInterval:g,sessionReplayMaskTextSelectors:a,skipPatterns:s,maskPatterns:o,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,sessionReplayBlockClass:c,sessionReplayBlockSelector:l,sessionReplayIgnoreClass:p,sessionReplayIgnoreSelector:C,sessionReplayMaskTextClass:T,sessionReplayMaskAllInputs:St,sessionReplayMaskInputOptions:Et,sessionReplayCollectFonts:Ct,sessionReplaySampling:wt,sessionReplaySlimDOMOptions:Pt,sessionReplaySampleRate:It};try{let N=`${e}/site/tracking-config/${r}`,rt=await fetch(N,{method:"GET",credentials:"omit"});if(rt.ok){let m=await rt.json();return{...h,autoTrackPageview:m.trackInitialPageView??h.autoTrackPageview,autoTrackSpa:m.trackSpaNavigation??h.autoTrackSpa,trackQuerystring:m.trackUrlParams??h.trackQuerystring,trackOutbound:m.trackOutbound??h.trackOutbound,enableWebVitals:m.webVitals??h.enableWebVitals,trackErrors:m.trackErrors??h.trackErrors,enableSessionReplay:m.sessionReplay??h.enableSessionReplay,trackButtonClicks:m.trackButtonClicks??h.trackButtonClicks,trackCopy:m.trackCopy??h.trackCopy,trackFormInteractions:m.trackFormInteractions??h.trackFormInteractions}}else return console.warn("Failed to fetch tracking config from API, using defaults"),h}catch(N){return console.warn("Error fetching tracking config:",N),h}}var at="rybbit-replay-sampled";function Bt(n){if(n>=100)return!0;if(n<=0)return!1;try{let t=sessionStorage.getItem(at);if(t!==null)return t==="1";let e=Math.random()*100<n;return sessionStorage.setItem(at,e?"1":"0"),e}catch{return Math.random()*100<n}}var P=class{constructor(t,e,r){this.isRecording=!1;this.eventBuffer=[];this.config=t,this.userId=e,this.sendBatch=r}async initialize(){if(!this.config.enableSessionReplay)return;let t=this.config.sessionReplaySampleRate;t!==void 0&&!Bt(t)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((t,e)=>{let r=document.createElement("script");r.src=`${this.config.analyticsHost}/replay.js`,r.async=!1,r.onload=()=>{t()},r.onerror=()=>e(new Error("Failed to load rrweb")),document.head.appendChild(r)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let t={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},e={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},r={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??t,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??e};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(r.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(r),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(t){this.eventBuffer.push(t),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let t=[...this.eventBuffer];this.eventBuffer=[];let e={userId:this.userId,events:t,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(e)}catch{this.eventBuffer.unshift(...t)}}updateUserId(t){this.userId=t}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var I=class{constructor(t){this.customUserId=null;this.config=t,this.loadUserId(),t.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let t=localStorage.getItem(`${this.config.namespace}-user-id`);t&&(this.customUserId=t)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new P(this.config,this.customUserId||"",t=>this.sendSessionReplayBatch(t)),await this.sessionReplayRecorder.initialize()}catch(t){console.error("Failed to initialize session replay:",t)}}async sendSessionReplayBatch(t){try{await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!1})}catch(e){throw console.error("Failed to send session replay batch:",e),e}}createBasePayload(){let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),U(e,this.config.skipPatterns))return null;let r=U(e,this.config.maskPatterns);r&&(e=r);let i={site_id:this.config.siteId,hostname:t.hostname,pathname:e,querystring:this.config.trackQuerystring?t.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(i.user_id=this.customUserId),i}async sendTrackingData(t){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0})}catch(e){console.error("Failed to send tracking data:",e)}}track(t,e="",r={}){if(t==="custom_event"&&(!e||typeof e!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let o={...i,type:t,event_name:e,properties:["custom_event","outbound","error","button_click","copy","form_submit","input_change"].includes(t)?JSON.stringify(r):void 0};this.sendTrackingData(o)}trackPageview(){this.track("pageview")}trackEvent(t,e={}){this.track("custom_event",t,e)}trackOutbound(t,e="",r="_self"){this.track("outbound","",{url:t,text:e,target:r})}trackWebVitals(t){let e=this.createBasePayload();if(!e)return;let r={...e,type:"performance",event_name:"web-vitals",...t};this.sendTrackingData(r)}trackError(t,e={}){let r=window.location.origin,i=e.filename||"",s=t.stack||"";if(i)try{if(new URL(i).origin!==r)return}catch{}else if(s&&!s.includes(r))return;let o={message:t.message?.substring(0,500)||"Unknown error",stack:s.substring(0,2e3)||""};if(i&&(o.fileName=i),e.lineno){let a=typeof e.lineno=="string"?parseInt(e.lineno,10):e.lineno;a&&a!==0&&(o.lineNumber=a)}if(e.colno){let a=typeof e.colno=="string"?parseInt(e.colno,10):e.colno;a&&a!==0&&(o.columnNumber=a)}for(let a in e)!["lineno","colno"].includes(a)&&e[a]!==void 0&&(o[a]=e[a]);this.track("error",t.name||"Error",o)}trackButtonClick(t){this.track("button_click","",t)}trackCopy(t){this.track("copy","",t)}trackFormSubmit(t){this.track("form_submit","",t)}trackInputChange(t){this.track("input_change","",t)}identify(t,e){if(typeof t!="string"||t.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=t.trim();try{localStorage.setItem(`${this.config.namespace}-user-id`,this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sendIdentifyEvent(this.customUserId,e,!0),this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}setTraits(t){if(!t||typeof t!="object"){console.error("Traits must be an object");return}let e=this.customUserId;if(!e){console.warn("Cannot set traits without identifying user first. Call identify() first.");return}this.sendIdentifyEvent(e,t,!1)}async sendIdentifyEvent(t,e,r=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:t,traits:e,is_new_identify:r}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var mt=-1,R=n=>{addEventListener("pageshow",(t=>{t.persisted&&(mt=t.timeStamp,n(t))}),!0)},f=(n,t,e,r)=>{let i,s;return o=>{t.value>=0&&(o||r)&&(s=t.value-(i??0),(s||i===void 0)&&(i=t.value,t.delta=s,t.rating=((a,d)=>a>d[1]?"poor":a>d[0]?"needs-improvement":"good")(t.value,e),n(t)))}},J=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},K=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},S=()=>K()?.activationStart??0,y=(n,t=-1)=>{let e=K(),r="navigate";return mt>=0?r="back-forward-cache":e&&(document.prerendering||S()>0?r="prerender":document.wasDiscarded?r="restore":e.type&&(r=e.type.replace(/_/g,"-"))),{name:n,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},D=new WeakMap;function q(n,t){return D.get(n)||D.set(n,new t),D.get(n)}var H=class{constructor(){b(this,"t");b(this,"i",0);b(this,"o",[])}h(t){if(t.hadRecentInput)return;let e=this.o[0],r=this.o.at(-1);this.i&&e&&r&&t.startTime-r.startTime<1e3&&t.startTime-e.startTime<5e3?(this.i+=t.value,this.o.push(t)):(this.i=t.value,this.o=[t]),this.t?.(t)}},E=(n,t,e={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(n)){let r=new PerformanceObserver((i=>{Promise.resolve().then((()=>{t(i.getEntries())}))}));return r.observe({type:n,buffered:!0,...e}),r}}catch{}},G=n=>{let t=!1;return()=>{t||(n(),t=!0)}},k=-1,ft=new Set,ot=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,W=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let t of ft)t();isFinite(k)||(k=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",W,!0))}},A=()=>{if(k<0){let n=S();k=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((e=>e.name==="hidden"&&e.startTime>n))[0]?.startTime)??ot(),addEventListener("visibilitychange",W,!0),addEventListener("prerenderingchange",W,!0),R((()=>{setTimeout((()=>{k=ot()}))}))}return{get firstHiddenTime(){return k},onHidden(n){ft.add(n)}}},L=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},ct=[1800,3e3],X=(n,t={})=>{L((()=>{let e=A(),r,i=y("FCP"),s=E("paint",(o=>{for(let a of o)a.name==="first-contentful-paint"&&(s.disconnect(),a.startTime<e.firstHiddenTime&&(i.value=Math.max(a.startTime-S(),0),i.entries.push(a),r(!0)))}));s&&(r=f(n,i,ct,t.reportAllChanges),R((o=>{i=y("FCP"),r=f(n,i,ct,t.reportAllChanges),J((()=>{i.value=performance.now()-o.timeStamp,r(!0)}))})))}))},lt=[.1,.25],yt=(n,t={})=>{let e=A();X(G((()=>{let r,i=y("CLS",0),s=q(t,H),o=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},a=E("layout-shift",o);a&&(r=f(n,i,lt,t.reportAllChanges),e.onHidden((()=>{o(a.takeRecords()),r(!0)})),R((()=>{s.i=0,i=y("CLS",0),r=f(n,i,lt,t.reportAllChanges),J((()=>r()))})),setTimeout(r))})))},bt=0,F=1/0,M=0,xt=n=>{for(let t of n)t.interactionId&&(F=Math.min(F,t.interactionId),M=Math.max(M,t.interactionId),bt=M?(M-F)/7+1:0)},z,ut=()=>z?bt:performance.interactionCount??0,Ot=()=>{"interactionCount"in performance||z||(z=E("event",xt,{type:"event",buffered:!0,durationThreshold:0}))},dt=0,V=class{constructor(){b(this,"u",[]);b(this,"l",new Map);b(this,"m");b(this,"p")}v(){dt=ut(),this.u.length=0,this.l.clear()}L(){let t=Math.min(this.u.length-1,Math.floor((ut()-dt)/50));return this.u[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;let e=this.u.at(-1),r=this.l.get(t.interactionId);if(r||this.u.length<10||t.duration>e.P){if(r?t.duration>r.P?(r.entries=[t],r.P=t.duration):t.duration===r.P&&t.startTime===r.entries[0].startTime&&r.entries.push(t):(r={id:t.interactionId,entries:[t],P:t.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort(((i,s)=>s.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let s of i)this.l.delete(s.id)}this.p?.(r)}}},vt=n=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=G(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),t((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},pt=[200,500],kt=(n,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let e=A();L((()=>{Ot();let r,i=y("INP"),s=q(t,V),o=d=>{vt((()=>{for(let g of d)s.h(g);let u=s.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,r())}))},a=E("event",o,{durationThreshold:t.durationThreshold??40});r=f(n,i,pt,t.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),e.onHidden((()=>{o(a.takeRecords()),r(!0)})),R((()=>{s.v(),i=y("INP"),r=f(n,i,pt,t.reportAllChanges)})))}))},$=class{constructor(){b(this,"m")}h(t){this.m?.(t)}},ht=[2500,4e3],Rt=(n,t={})=>{L((()=>{let e=A(),r,i=y("LCP"),s=q(t,$),o=d=>{t.reportAllChanges||(d=d.slice(-1));for(let u of d)s.h(u),u.startTime<e.firstHiddenTime&&(i.value=Math.max(u.startTime-S(),0),i.entries=[u],r())},a=E("largest-contentful-paint",o);if(a){r=f(n,i,ht,t.reportAllChanges);let d=G((()=>{o(a.takeRecords()),a.disconnect(),r(!0)})),u=g=>{g.isTrusted&&(vt(d),removeEventListener(g.type,u,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,u,{capture:!0});R((g=>{i=y("LCP"),r=f(n,i,ht,t.reportAllChanges),J((()=>{i.value=performance.now()-g.timeStamp,r(!0)}))}))}}))},gt=[800,1800],j=n=>{document.prerendering?L((()=>j(n))):document.readyState!=="complete"?addEventListener("load",(()=>j(n)),!0):setTimeout(n)},Tt=(n,t={})=>{let e=y("TTFB"),r=f(n,e,gt,t.reportAllChanges);j((()=>{let i=K();i&&(e.value=Math.max(i.responseStart-S(),0),e.entries=[i],r(!0),R((()=>{e=y("TTFB",0),r=f(n,e,gt,t.reportAllChanges),r(!0)})))}))};var B=class{constructor(t){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=t}initialize(){try{Rt(this.collectMetric.bind(this)),yt(this.collectMetric.bind(this)),kt(this.collectMetric.bind(this)),X(this.collectMetric.bind(this)),Tt(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(t){console.warn("Error initializing web vitals tracking:",t)}}collectMetric(t){if(this.sent)return;let e=t.name.toLowerCase();this.data[e]=t.value,Object.values(this.data).every(i=>i!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};var x=class{constructor(t,e){this.tracker=t,this.config=e}initialize(){document.addEventListener("click",this.handleClick.bind(this),!0)}handleClick(t){let e=t.target;this.config.trackButtonClicks&&this.isButton(e)&&this.trackButtonClick(e)}isButton(t){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;if(t.tagName==="INPUT"){let i=t.type?.toLowerCase();if(i==="submit"||i==="button")return!0}let e=t.parentElement,r=0;for(;e&&r<3;){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return!0;e=e.parentElement,r++}return!1}trackButtonClick(t){let e=this.findButton(t);if(!e||e.hasAttribute("data-rybbit-event"))return;let r={text:this.getElementText(e),...this.extractDataAttributes(e)};this.tracker.trackButtonClick(r)}extractDataAttributes(t){let e={};for(let r of t.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");e[i]=r.value}return e}findButton(t){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;if(t.tagName==="INPUT"){let i=t.type?.toLowerCase();if(i==="submit"||i==="button")return t}let e=t.parentElement,r=0;for(;e&&r<3;){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return e;e=e.parentElement,r++}return null}getElementText(t){return t.textContent?.trim().substring(0,100)||void 0}cleanup(){document.removeEventListener("click",this.handleClick.bind(this),!0)}};var O=class{constructor(t){this.tracker=t}initialize(){document.addEventListener("copy",this.handleCopy.bind(this))}handleCopy(){let t=window.getSelection();if(!t||t.isCollapsed)return;let e=t.toString(),r=e.length;if(r===0)return;let i=t.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let o={text:e.substring(0,500),...r>500&&{textLength:r},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(o)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var _=class{constructor(t,e){this.tracker=t,this.config=e,this.boundHandleSubmit=this.handleSubmit.bind(this),this.boundHandleChange=this.handleChange.bind(this)}initialize(){document.addEventListener("submit",this.boundHandleSubmit,!0),document.addEventListener("change",this.boundHandleChange,!0)}cleanup(){document.removeEventListener("submit",this.boundHandleSubmit,!0),document.removeEventListener("change",this.boundHandleChange,!0)}handleSubmit(t){let e=t.target;if(e.tagName!=="FORM")return;let r={formId:e.id||"",formName:e.name||"",formAction:e.action||"",method:(e.method||"get").toUpperCase(),fieldCount:e.elements.length,...this.extractDataAttributes(e)};this.tracker.trackFormSubmit(r)}handleChange(t){let e=t.target,r=e.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(r))return;if(r==="INPUT"){let s=e.type?.toLowerCase();if(s==="hidden"||s==="password")return}let i={element:r.toLowerCase(),inputType:r==="INPUT"?e.type?.toLowerCase():void 0,inputName:e.name||e.id||"",formId:e.form?.id||void 0,...this.extractDataAttributes(e)};this.tracker.trackInputChange(i)}extractDataAttributes(t){let e={};for(let r of t.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");e[i]=r.value}return e}};(async function(){let n=document.currentScript;if(!n){console.error("Could not find current script tag");return}let t=n.getAttribute("data-namespace")||"rybbit",e=`disable-${t}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(e)!==null){window[t]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let r=await st(n);if(!r)return;let i=new I(r);r.enableWebVitals&&new B(l=>{i.trackWebVitals(l)}).initialize();let s=null,o=null,a=null;r.trackButtonClicks&&(s=new x(i,r),s.initialize()),r.trackCopy&&(o=new O(i),o.initialize()),r.trackFormInteractions&&(a=new _(i,r),a.initialize()),r.trackErrors&&(window.addEventListener("error",c=>{i.trackError(c.error||new Error(c.message),{filename:c.filename,lineno:c.lineno,colno:c.colno})}),window.addEventListener("unhandledrejection",c=>{let l=c.reason instanceof Error?c.reason:new Error(String(c.reason));i.trackError(l,{type:"unhandledrejection"})}));let d=()=>i.trackPageview(),u=r.debounceDuration>0?nt(d,r.debounceDuration):d;function g(){if(document.addEventListener("click",function(c){let l=c.target;for(;l&&l!==document.documentElement;){if(l.hasAttribute("data-rybbit-event")){let p=l.getAttribute("data-rybbit-event");if(p){let C={};for(let T of l.attributes)if(T.name.startsWith("data-rybbit-prop-")){let w=T.name.replace("data-rybbit-prop-","");C[w]=T.value}i.trackEvent(p,C)}break}l=l.parentElement}if(r.trackOutbound){let p=c.target.closest("a");p?.href&&it(p.href)&&i.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),r.autoTrackSpa){let c=history.pushState,l=history.replaceState;history.pushState=function(...p){c.apply(this,p),u(),i.onPageChange()},history.replaceState=function(...p){l.apply(this,p),u(),i.onPageChange()},window.addEventListener("popstate",()=>{u(),i.onPageChange()}),window.addEventListener("hashchange",()=>{u(),i.onPageChange()})}}window[r.namespace]={pageview:()=>i.trackPageview(),event:(c,l={})=>i.trackEvent(c,l),error:(c,l={})=>i.trackError(c,l),trackOutbound:(c,l="",p="_self")=>i.trackOutbound(c,l,p),identify:(c,l)=>i.identify(c,l),setTraits:c=>i.setTraits(c),clearUserId:()=>i.clearUserId(),getUserId:()=>i.getUserId(),startSessionReplay:()=>i.startSessionReplay(),stopSessionReplay:()=>i.stopSessionReplay(),isSessionReplayActive:()=>i.isSessionReplayActive()},g(),window.addEventListener("beforeunload",()=>{s?.cleanup(),o?.cleanup(),i.cleanup()}),r.autoTrackPageview&&i.trackPageview()})();})();diff --git a/server/src/api/analytics/events/getEvents.ts b/server/src/api/analytics/events/getEvents.tsindex 6e498b711..0412afc16 100644--- a/server/src/api/analytics/events/getEvents.ts+++ b/server/src/api/analytics/events/getEvents.ts@@ -7,15 +7,26 @@ import { getFilterStatement } from "../utils/getFilterStatement.js";export type GetEventsResponse = {timestamp: string;event_name: string;- properties: string; // This will be populated from the props column+ properties: string;+ session_id: string;user_id: string;+ identified_user_id: string;pathname: string;querystring: string;hostname: string;referrer: string;browser: string;+ browser_version: string;operating_system: string;+ operating_system_version: string;+ language: string;country: string;+ region: string;+ city: string;+ lat: number;+ lon: number;+ screen_width: number;+ screen_height: number;device_type: string;type: string;page_title: string;@@ -26,96 +37,132 @@ interface GetEventsRequest {siteId: string;};Querystring: FilterParams<{- page?: string;page_size?: string;- count?: string; // Keeping for backward compatibility+ since_timestamp?: string;+ before_timestamp?: string;}>;}-export async function getEvents(req: FastifyRequest<GetEventsRequest>, res: FastifyReply) {- const { siteId } = req.params;- const { start_date, end_date, time_zone, filters, page = "1", page_size: pageSize = "20", count } = req.query;+const EVENT_COLUMNS = `+ timestamp,+ event_name,+ toString(props) as properties,+ session_id,+ user_id,+ identified_user_id,+ pathname,+ querystring,+ hostname,+ page_title,+ referrer,+ browser,+ browser_version,+ operating_system,+ operating_system_version,+ language,+ country,+ region,+ city,+ lat,+ lon,+ screen_width,+ screen_height,+ device_type,+ type+`;- // Use count if provided (for backward compatibility), otherwise use page_size- const limit = count ? parseInt(count, 10) : parseInt(pageSize, 10);- const offset = (parseInt(page, 10) - 1) * limit;+const EVENT_TYPE_FILTER = `AND type IN ('custom_event', 'pageview', 'outbound', 'button_click', 'copy', 'form_submit', 'input_change')`;- // Get time and filter statements if parameters are provided- const timeStatement =- start_date || end_date ? getTimeStatement(req.query) : "AND timestamp > now() - INTERVAL 30 MINUTE"; // Default to last 30 minutes if no time range specified+export async function getEvents(+ req: FastifyRequest<GetEventsRequest>,+ res: FastifyReply+) {+ const { siteId } = req.params;+ const {+ since_timestamp,+ before_timestamp,+ page_size: pageSize = "50",+ filters,+ } = req.query;- const filterStatement = filters ? getFilterStatement(filters, Number(siteId), timeStatement) : "";+ const limit = parseInt(pageSize, 10);+ const filterStatement = filters+ ? getFilterStatement(filters, Number(siteId))+ : "";try {- // First, get the total count for pagination metadata- const countQuery = `- SELECT- COUNT(*) as total- FROM events- WHERE- site_id = {siteId:Int32}- AND type IN ('custom_event', 'pageview', 'outbound', 'button_click', 'copy', 'form_submit', 'input_change')- ${timeStatement}- ${filterStatement}- `;+ // Mode A: Poll for new events since a timestamp (Realtime polling)+ if (since_timestamp) {+ const query = `+ SELECT ${EVENT_COLUMNS}+ FROM events+ WHERE+ site_id = {siteId:Int32}+ ${EVENT_TYPE_FILTER}+ AND timestamp > toDateTime64({sinceTimestamp:String}, 3)+ ${filterStatement}+ ORDER BY timestamp DESC+ LIMIT 500+ `;- const countResult = await clickhouse.query({- query: countQuery,- format: "JSONEachRow",- query_params: {- siteId: Number(siteId),- },- });+ const result = await clickhouse.query({+ query,+ format: "JSONEachRow",+ query_params: {+ siteId: Number(siteId),+ sinceTimestamp: since_timestamp,+ },+ });++ const events = await processResults<GetEventsResponse[number]>(result);+ return res.send({ data: events });+ }++ // Mode B: Cursor-based pagination (initial load or scrolling back)+ const timeStatement =+ req.query.start_date || req.query.end_date+ ? getTimeStatement(req.query)+ : "";- const countData = await processResults<{ total: number }>(countResult);- const totalCount = countData[0]?.total || 0;-- // Then, get the actual events with pagination- const eventsQuery = `- SELECT- timestamp,- event_name,- toString(props) as properties, -- Convert props Map to string- user_id,- pathname,- querystring,- hostname,- page_title,- referrer,- browser,- operating_system,- country,- device_type,- type+ let cursorCondition = "";+ const queryParams: Record<string, string | number> = {+ siteId: Number(siteId),+ limit: Number(limit),+ };++ if (before_timestamp) {+ cursorCondition = `AND timestamp < toDateTime64({beforeTimestamp:String}, 3)`;+ queryParams.beforeTimestamp = before_timestamp;+ }++ const query = `+ SELECT ${EVENT_COLUMNS}FROM eventsWHEREsite_id = {siteId:Int32}- AND type IN ('custom_event', 'pageview', 'outbound', 'button_click', 'copy', 'form_submit', 'input_change')+ ${EVENT_TYPE_FILTER}${timeStatement}+ ${cursorCondition}${filterStatement}ORDER BY timestamp DESC- LIMIT {limit:Int32} OFFSET {offset:Int32}+ LIMIT {limit:Int32}`;- const eventsResult = await clickhouse.query({- query: eventsQuery,+ const result = await clickhouse.query({+ query,format: "JSONEachRow",- query_params: {- siteId: Number(siteId),- limit: Number(limit),- offset: Number(offset),- },+ query_params: queryParams,});- const events = await processResults<GetEventsResponse[number]>(eventsResult);+ const events = await processResults<GetEventsResponse[number]>(result);+return res.send({data: events,- pagination: {- total: totalCount,- page: parseInt(page, 10),- pageSize: limit,- totalPages: Math.ceil(totalCount / limit),+ cursor: {+ hasMore: events.length === limit,+ oldestTimestamp:+ events.length > 0 ? events[events.length - 1].timestamp : null,},});} catch (error) {diff --git a/server/src/api/analytics/events/getSiteEventCount.ts b/server/src/api/analytics/events/getSiteEventCount.tsnew file mode 100644index 000000000..f661b116b--- /dev/null+++ b/server/src/api/analytics/events/getSiteEventCount.ts@@ -0,0 +1,86 @@+import { FilterParams } from "@rybbit/shared";+import { FastifyReply, FastifyRequest } from "fastify";+import { clickhouse } from "../../../db/clickhouse/clickhouse.js";+import { TimeBucket } from "../types.js";+import { getFilterStatement } from "../utils/getFilterStatement.js";+import { getTimeStatement, processResults, TimeBucketToFn } from "../utils/utils.js";++export type GetSiteEventCountResponse = {+ time: string;+ pageview_count: number;+ custom_event_count: number;+ performance_count: number;+ outbound_count: number;+ error_count: number;+ button_click_count: number;+ copy_count: number;+ form_submit_count: number;+ input_change_count: number;+ event_count: number;+}[];++interface GetSiteEventCountRequest {+ Params: {+ siteId: string;+ };+ Querystring: FilterParams<{+ bucket: TimeBucket;+ }>;+}++export async function getSiteEventCount(+ 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}` });+ }++ const timeStatement = getTimeStatement(req.query);+ const filterStatement = getFilterStatement(req.query.filters, Number(site), timeStatement);++ const query = `+ SELECT+ toDateTime(${TimeBucketToFn[bucket]}(toTimeZone(timestamp, {timeZone:String}))) AS time,+ countIf(type = 'pageview') as pageview_count,+ countIf(type = 'custom_event') as custom_event_count,+ countIf(type = 'performance') as performance_count,+ countIf(type = 'outbound') as outbound_count,+ countIf(type = 'error') as error_count,+ countIf(type = 'button_click') as button_click_count,+ countIf(type = 'copy') as copy_count,+ countIf(type = 'form_submit') as form_submit_count,+ countIf(type = 'input_change') as input_change_count,+ count() as event_count+ FROM events+ WHERE+ site_id = {siteId:Int32}+ AND type IN ('pageview', 'custom_event', 'performance', 'outbound', 'error', 'button_click', 'copy', 'form_submit', 'input_change')+ ${timeStatement}+ ${filterStatement}+ GROUP BY time+ ORDER BY time+ `;++ try {+ const result = await clickhouse.query({+ query,+ format: "JSONEachRow",+ query_params: {+ siteId: Number(site),+ timeZone,+ },+ });++ const data = await processResults<GetSiteEventCountResponse[number]>(result);+ return res.send({ data });+ } catch (error) {+ console.error("Generated Query:", query);+ console.error("Error fetching site event count:", error);+ return res.status(500).send({ error: "Failed to fetch site event count" });+ }+}diff --git a/server/src/api/analytics/getSessions.ts b/server/src/api/analytics/getSessions.tsindex 3b17232fa..746493d05 100644--- a/server/src/api/analytics/getSessions.ts+++ b/server/src/api/analytics/getSessions.ts@@ -57,6 +57,7 @@ export interface GetSessionsRequest {limit: number;page: number;user_id?: string;+ session_id?: string;identified_only?: string;min_pageviews?: string;min_events?: string;@@ -78,6 +79,7 @@ export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res:filters,page = 1,user_id: userId,+ session_id: sessionId,limit = 100,identified_only: identifiedOnly = "false",min_pageviews: minPageviewsStr,@@ -145,6 +147,7 @@ export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res:WHEREsite_id = {siteId:Int32}${userId ? ` AND (events.user_id = {user_id:String} OR events.identified_user_id = {user_id:String})` : ""}+ ${sessionId ? ` AND events.session_id = {session_id:String}` : ""}${timeStatement}GROUP BYsession_id@@ -177,6 +180,7 @@ export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res:query_params: {siteId: Number(site),user_id: userId,+ session_id: sessionId,limit: limit || 100,offset: (page - 1) * (limit || 100),minPageviews: minPageviews ?? 0,diff --git a/server/src/api/analytics/index.ts b/server/src/api/analytics/index.tsindex 6a69d0795..ddb979566 100644--- a/server/src/api/analytics/index.ts+++ b/server/src/api/analytics/index.ts@@ -4,6 +4,7 @@ export { getEventNames } from "./events/getEventNames.js";export { getEventProperties } from "./events/getEventProperties.js";export { getEvents } from "./events/getEvents.js";export { getOutboundLinks } from "./events/getOutboundLinks.js";+export { getSiteEventCount } from "./events/getSiteEventCount.js";// Funnelsdiff --git a/server/src/index.ts b/server/src/index.tsindex 05de776e0..dd38f3d01 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -44,6 +44,7 @@ import {getSession,getSessionLocations,getSessions,+ getSiteEventCount,getUserInfo,getUserSessionCount,getUsers,@@ -139,7 +140,7 @@ const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);const server = Fastify({- disableRequestLogging: true,+ // disableRequestLogging: true,logger: {// level: process.env.LOG_LEVEL || (process.env.NODE_ENV === "development" ? "debug" : "info"),level: "debug",@@ -241,6 +242,7 @@ async function analyticsRoutes(fastify: FastifyInstance) {fastify.get("/sites/:siteId/sessions/:sessionId", publicSite, getSession);fastify.get("/sites/:siteId/events", publicSite, getEvents);fastify.get("/sites/:siteId/events/bucketed", publicSite, getEventBucketed);+ fastify.get("/sites/:siteId/events/count", publicSite, getSiteEventCount);fastify.get("/sites/:siteId/users", publicSite, getUsers);fastify.get("/sites/:siteId/users/session-count", publicSite, getUserSessionCount);diff --git a/server/src/services/tracker/pageviewQueue.ts b/server/src/services/tracker/pageviewQueue.tsindex 6dd55cd94..485ed00ef 100644--- a/server/src/services/tracker/pageviewQueue.ts+++ b/server/src/services/tracker/pageviewQueue.ts@@ -21,7 +21,7 @@ const getParsedProperties = (properties: string | undefined) => {class PageviewQueue {private queue: TotalPayload[] = [];private batchSize = 5000;- private interval = 10000;+ private interval = 1000;private processing = false;private logger = createServiceLogger("pageview-queue");