📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Use v2 stats API
Blue Mouse3fcf31f9554d
diff --git a/backend/apps/cloud/src/analytics/v2/analytics-v2.service.ts b/backend/apps/cloud/src/analytics/v2/analytics-v2.service.tsindex 0ea8df850..9dbcabeb8 100644--- a/backend/apps/cloud/src/analytics/v2/analytics-v2.service.ts+++ b/backend/apps/cloud/src/analytics/v2/analytics-v2.service.ts@@ -9,6 +9,7 @@ import utc from 'dayjs/plugin/utc'import { clickhouse } from '../../common/integrations/clickhouse'import { AppLoggerService } from '../../logger/logger.service'+import { MAX_METRICS_IN_VIEW } from '../../project/dto/create-project-view.dto'import { IFunnel, PerfMeasure } from '../interfaces'import {AnalyticsService,@@ -625,6 +626,57 @@ export class AnalyticsV2Service {})}+ async getTrafficCustomMetrics(+ pid: string,+ dto: V2BaseQueryDto & { metrics: string },+ ): Promise<V2Envelope<unknown[]>> {+ const dataType: V2DataType = 'traffic'+ const filters = this.prepareFilters(dto.filters, dataType)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ })++ const parsedMetrics = this.analyticsService.parseMetrics(dto.metrics)++ if (parsedMetrics.length > MAX_METRICS_IN_VIEW) {+ throw new UnprocessableEntityException(+ `The maximum number of metrics within one request is ${MAX_METRICS_IN_VIEW}`,+ )+ }++ if (!parsedMetrics.length) {+ return envelope([], this.baseMeta(pid, timeframe, filters.appliedFilters))+ }++ const meta = await this.analyticsService.getMetaResults(+ pid,+ parsedMetrics,+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ timeframe.safeTimezone,+ timeframe.period ?? undefined,+ dto.from,+ dto.to,+ )++ return envelope(+ meta ?? [],+ this.baseMeta(pid, timeframe, filters.appliedFilters),+ )+ }+async getTrafficPageProperties(pid: string,dto: V2BaseQueryDto & { limit?: number; offset?: number },diff --git a/backend/apps/cloud/src/analytics/v2/controllers/traffic-v2.controller.ts b/backend/apps/cloud/src/analytics/v2/controllers/traffic-v2.controller.tsindex 9ab8806ef..157186653 100644--- a/backend/apps/cloud/src/analytics/v2/controllers/traffic-v2.controller.ts+++ b/backend/apps/cloud/src/analytics/v2/controllers/traffic-v2.controller.ts@@ -27,6 +27,7 @@ import { PublicProjectCacheInterceptor } from '../../protection/public-project-cimport { AnalyticsV2Service } from '../analytics-v2.service'import {V2CustomEventsTimeseriesDto,+ V2CustomMetricsQueryDto,V2EventMetadataQueryDto,V2PropertyMetadataQueryDto,} from '../dto/project.dto'@@ -157,6 +158,34 @@ export class TrafficV2Controller {return this.analyticsV2Service.getTrafficCustomEvents(pid, query)}+ @Get('custom-metrics')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Custom metrics',+ description:+ 'Sum / average of numeric custom event metadata values for the selected period and the previous one (project view custom metrics).',+ })+ async getCustomMetrics(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2CustomMetricsQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}`,+ 'GET /v2/projects/:pid/traffic/custom-metrics',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getTrafficCustomMetrics(pid, query)+ }+@Get('custom-events/timeseries')@Auth(true, true)@CacheableAnalytics()diff --git a/backend/apps/cloud/src/analytics/v2/dto/project.dto.ts b/backend/apps/cloud/src/analytics/v2/dto/project.dto.tsindex c25d14520..44dddc3a9 100644--- a/backend/apps/cloud/src/analytics/v2/dto/project.dto.ts+++ b/backend/apps/cloud/src/analytics/v2/dto/project.dto.ts@@ -107,6 +107,16 @@ export class V2DimensionValuesQueryDto {type?: 'traffic' | 'errors'}+export class V2CustomMetricsQueryDto extends V2BaseQueryDto {+ @ApiProperty({+ description:+ 'JSON array of custom metric definitions (project view custom events)',+ })+ @IsNotEmpty()+ @IsString()+ metrics: string+}+export class V2EventMetadataQueryDto extends V2BaseQueryDto {@ApiProperty({ description: 'Custom event name to return metadata for' })@IsNotEmpty()diff --git a/backend/apps/cloud/tsconfig.app.json b/backend/apps/cloud/tsconfig.app.jsonindex 3818f9d2d..536502cbc 100644--- a/backend/apps/cloud/tsconfig.app.json+++ b/backend/apps/cloud/tsconfig.app.json@@ -7,7 +7,7 @@"esModuleInterop": true,"experimentalDecorators": true,"allowSyntheticDefaultImports": true,- "target": "es2017",+ "target": "es2022","sourceMap": true,"outDir": "./dist","baseUrl": "./",diff --git a/backend/jest.v2.config.js b/backend/jest.v2.config.jsindex d69e8c4e3..463fb95bb 100644--- a/backend/jest.v2.config.js+++ b/backend/jest.v2.config.js@@ -1,12 +1,17 @@/*** Scoped jest setup for the v2 analytics API. Only covers the pure modules- * under apps/cloud/src/analytics/v2 (registry, filter translator, query- * builder, mappers) — it is not a general backend test runner.+ * under apps/{cloud,community}/src/analytics/v2 (registry, filter translator,+ * query builder, mappers) — it is not a general backend test runner. The v2+ * source is duplicated per app (repo convention); running the specs against+ * both copies keeps them from drifting.*/module.exports = {preset: 'ts-jest',testEnvironment: 'node',- roots: ['<rootDir>/apps/cloud/src/analytics/v2'],+ roots: [+ '<rootDir>/apps/cloud/src/analytics/v2',+ '<rootDir>/apps/community/src/analytics/v2',+ ],testMatch: ['**/*.spec.ts'],moduleNameMapper: {// common/constants instantiates a Redis client at import time; the v2diff --git a/docs/content/docs/api/stats-v2.mdx b/docs/content/docs/api/stats-v2.mdxindex 8312d27f9..bd31d901d 100644--- a/docs/content/docs/api/stats-v2.mdx+++ b/docs/content/docs/api/stats-v2.mdx@@ -268,6 +268,10 @@ curl 'https://api.swetrix.com/v2/projects/YOUR_PROJECT_ID/traffic/custom-events/Aggregated metadata key/value counts for one custom event (v1 `/log/meta` equivalent). Requires `event`; returns `data: [{ "key": "Affiliate", "value": "Yes", "count": 1 }, ...]`.+### GET /v2/projects/:pid/traffic/custom-metrics++Sum / average of numeric custom event metadata values for the selected period and the previous one (powers dashboard "custom metric" cards). `metrics` is a JSON array of metric definitions (`{ "customEventName", "metaKey", "metaValueType": "integer" | "float" }`). Returns `data: [{ "key": "<metaKey>", "current": { "sum", "avg" }, "previous": { "sum", "avg" } }, ...]`.+### GET /v2/projects/:pid/traffic/page-propertiesCounts of pageview metadata (page property) keys: `data: [{ "property": "author", "count": 30 }, ...]`. Cannot be combined with custom-event filters (`422`).diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.tsindex 32c0bab14..0494c1933 100644--- a/web/app/api/api.server.ts+++ b/web/app/api/api.server.ts@@ -732,26 +732,6 @@ export interface AnalyticsFilter {isContains?: boolean}-export interface TrafficLogResponse {- params?: Record<string, { name: string; count: number }[]>- chart: {- x: string[]- visits: number[]- uniques: number[]- sdur: number[]- bounces?: number[]- }- customs: Record<string, number>- properties: Record<string, number>- appliedFilters?: AnalyticsFilter[]- timeBucket?: string[]- meta?: {- key: string- current: { sum: number; avg: number }- previous: { sum: number; avg: number }- }[]-}-interface OverallPeriodStats {all: numberunique?: number@@ -788,34 +768,6 @@ function serializeFiltersForUrl(filters: AnalyticsFilter[]): string {return JSON.stringify(filters)}-export async function getProjectDataServer(- request: Request,- pid: string,- params: AnalyticsParams,-): Promise<ServerFetchResult<TrafficLogResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('timeBucket', params.timeBucket)- queryParams.append('period', params.period)- queryParams.append('filters', serializeFiltersForUrl(params.filters))- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)- if (params.mode) queryParams.append('mode', params.mode)- if (params.metrics) queryParams.append('metrics', params.metrics)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<TrafficLogResponse>(- request,- `log?${queryParams.toString()}`,- { headers },- )-}-export async function getOverallStatsServer(request: Request,pids: string[],@@ -848,123 +800,6 @@ export async function getOverallStatsServer()}-interface CustomEventsChartResponse {- chart?: {- events?: Record<string, unknown>- }-}--export async function getCustomEventsDataServer(- request: Request,- pid: string,- params: AnalyticsParams,- customEvents: string[],-): Promise<ServerFetchResult<CustomEventsChartResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('timeBucket', params.timeBucket)- queryParams.append('period', params.period)- queryParams.append('filters', serializeFiltersForUrl(params.filters))- queryParams.append('customEvents', JSON.stringify(customEvents))- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<CustomEventsChartResponse>(- request,- `log/customEvents?${queryParams.toString()}`,- { headers },- )-}--export interface PerformanceDataResponse {- params: Record<string, { name: string; count: number }[]>- chart: {- x: string[]- dns?: number[]- tls?: number[]- conn?: number[]- response?: number[]- render?: number[]- domLoad?: number[]- pageLoad?: number[]- ttfb?: number[]- p50?: number[]- p75?: number[]- p95?: number[]- }- appliedFilters: AnalyticsFilter[]- timeBucket?: string[]-}--export async function getPerfDataServer(- request: Request,- pid: string,- params: AnalyticsParams & { measure?: string },-): Promise<ServerFetchResult<PerformanceDataResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('timeBucket', params.timeBucket)- queryParams.append('period', params.period)- queryParams.append('filters', serializeFiltersForUrl(params.filters))- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)- if (params.measure) queryParams.append('measure', params.measure)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<PerformanceDataResponse>(- request,- `log/performance?${queryParams.toString()}`,- { headers },- )-}--export interface PerformanceOverallObject {- current: { frontend: number; backend: number; network: number }- previous: { frontend: number; backend: number; network: number }- frontendChange: number- backendChange: number- networkChange: number-}--export async function getPerformanceOverallStatsServer(- request: Request,- pids: string[],- params: AnalyticsParams & { measure?: string },-): Promise<ServerFetchResult<Record<string, PerformanceOverallObject>>> {- const pidsParam = `[${pids.map((pid) => `"${pid}"`).join(',')}]`-- const queryParams = new URLSearchParams()- queryParams.append('pids', pidsParam)- queryParams.append('period', params.period)- queryParams.append('filters', serializeFiltersForUrl(params.filters))- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)- if (params.measure) queryParams.append('measure', params.measure)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<Record<string, PerformanceOverallObject>>(- request,- `log/performance/birdseye?${queryParams.toString()}`,- { headers },- )-}-interface Session {psid: stringcc: string | null@@ -988,13 +823,6 @@ interface Session {replayExpiresAt?: string | null}-export interface SessionsResponse {- sessions: Session[]- take: number- skip: number- appliedFilters: AnalyticsFilter[]-}-type SessionReplayPrivacy = 'total' | 'normal' | 'none'export interface SessionReplayListItem extends Session {@@ -1016,44 +844,6 @@ export interface SessionReplaysResponse {appliedFilters: AnalyticsFilter[]}-export type SessionEventType = 'traffic' | 'performance' | 'error'--export async function getSessionsServer(- request: Request,- pid: string,- params: AnalyticsParams & {- take?: number- skip?: number- sessionEvent?: SessionEventType- },-): Promise<ServerFetchResult<SessionsResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('period', params.period)- queryParams.append('filters', serializeFiltersForUrl(params.filters))- queryParams.append('take', String(params.take || 30))- queryParams.append('skip', String(params.skip || 0))- if (params.sessionEvent) {- queryParams.append('sessionEvent', params.sessionEvent)- }- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<SessionsResponse>(- request,- `log/sessions?${queryParams.toString()}`,- {- headers,- },- )-}-export async function getSessionReplaysServer(request: Request,pid: string,@@ -1086,64 +876,12 @@ export async function getSessionReplaysServer()}-export interface FunnelSessionsResponse {- sessions: Session[]- take: number- skip: number-}-export interface GoalSessionsResponse {sessions: Session[]take: numberskip: number}-export async function getFunnelSessionsServer(- request: Request,- pid: string,- params: {- period: string- from?: string- to?: string- timezone?: string- funnelId?: string- step: number- take?: number- skip?: number- password?: string- filters?: AnalyticsFilter[]- dropoff?: boolean- },-): Promise<ServerFetchResult<FunnelSessionsResponse>> {- const step = Math.max(1, Math.floor(Number(params.step) || 1))- const take = Math.min(150, Math.max(1, Math.floor(Number(params.take) || 30)))- const skip = Math.max(0, Math.floor(Number(params.skip) || 0))-- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('period', params.period)- queryParams.append('step', String(step))- queryParams.append('take', String(take))- queryParams.append('skip', String(skip))- queryParams.append('filters', JSON.stringify(params.filters || []))- if (params.funnelId) queryParams.append('funnelId', params.funnelId)- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)- if (params.dropoff) queryParams.append('dropoff', 'true')-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<FunnelSessionsResponse>(- request,- `log/funnel-sessions?${queryParams.toString()}`,- { headers },- )-}-export async function getGoalSessionsServer(request: Request,goalId: string,@@ -1173,15 +911,6 @@ export async function getGoalSessionsServer()}-interface PageflowItem {- type: 'pageview' | 'event' | 'error' | 'sale' | 'subscription' | 'refund'- value: string- created: string- metadata?: { key: string; value: string }[]- amount?: number- currency?: string-}-export interface SessionReplayMetadata {hasReplay: booleanreplayId: string@@ -1218,74 +947,6 @@ export interface SessionReplayExportResponse {error?: string}-export interface SessionDetailsResponse {- details: {- psid: string- cc: string | null- os: string | null- osv: string | null- br: string | null- brv: string | null- dv: string | null- lc: string | null- ref: string | null- so: string | null- me: string | null- ca: string | null- te: string | null- co: string | null- rg: string | null- ct: string | null- pageviews: number- customEvents: number- errors: number- revenue?: number- refunds?: number- created: string- sdur?: number- isLive?: boolean- profileId: string | null- isIdentified: 1 | 0- isFirstSession: 1 | 0- }- chart?: {- x: string[]- pageviews?: number[]- customEvents?: number[]- errors?: number[]- }- pages?: PageflowItem[]- timeBucket?: string- replay?: SessionReplayMetadata | null-}--export async function getSessionServer(- request: Request,- pid: string,- psid: string,- timezone: string,- password?: string,-): Promise<ServerFetchResult<SessionDetailsResponse>> {- const queryParams = new URLSearchParams({- pid,- psid,- timezone,- })-- const headers: Record<string, string> = {}- if (password) {- headers['x-password'] = password- }-- return serverFetch<SessionDetailsResponse>(- request,- `log/session?${queryParams.toString()}`,- {- headers,- },- )-}-export async function getSessionReplayServer(request: Request,pid: string,@@ -1349,177 +1010,28 @@ export async function deleteSessionReplayServer()}-interface SwetrixError {- eid: string- name: string- message: string- filename: string- count: number- last_seen: string- status: 'active' | 'regressed' | 'fixed' | 'resolved'- users: number- sessions: number-}+// ============================================================================+// MARK: Feature Flags API (Deferred Loading)+// ============================================================================-export interface ErrorsResponse {- errors: SwetrixError[]+export interface TargetingRule {+ column: string+ filter: string+ isExclusive: boolean}-export async function getErrorsServer(- request: Request,- pid: string,- params: AnalyticsParams & {- take?: number- skip?: number- options?: Record<string, unknown>- },-): Promise<ServerFetchResult<ErrorsResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('timeBucket', params.timeBucket)- queryParams.append('period', params.period)- queryParams.append('filters', serializeFiltersForUrl(params.filters))- queryParams.append('options', JSON.stringify(params.options || {}))- queryParams.append('take', String(params.take || 30))- queryParams.append('skip', String(params.skip || 0))- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<ErrorsResponse>(- request,- `log/errors?${queryParams.toString()}`,- { headers },- )+export interface FeatureFlagSchedule {+ enabled?: boolean+ rolloutPercentage?: number+ applyAt: string}-export interface ErrorDetailsResponse {- details: {- eid: string- name: string- message: string- filename: string- lineno: number- colno: number- count: number- last_seen: string- first_seen: string- status: 'active' | 'regressed' | 'fixed' | 'resolved'- users: number- sessions: number- stackTrace?: string- }- chart?: {- x: string[]- occurrences: number[]- affectedUsers: number[]- }- params?: Record<string, { name: string; count: number }[]>- metadata?: { key: string; value: string; count: number }[]- timeBucket?: string-}--export async function getErrorServer(- request: Request,- pid: string,- eid: string,- params: AnalyticsParams & { options?: Record<string, unknown> },-): Promise<ServerFetchResult<ErrorDetailsResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('eid', eid)- queryParams.append('timeBucket', params.timeBucket)- queryParams.append('period', params.period)- queryParams.append('filters', serializeFiltersForUrl(params.filters))- queryParams.append('options', JSON.stringify(params.options || {}))- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<ErrorDetailsResponse>(- request,- `log/get-error?${queryParams.toString()}`,- {- headers,- },- )-}--export interface ErrorOverviewResponse {- chart?: {- x: string[]- occurrences: number[]- affectedUsers: number[]- }- stats?: {- totalErrors: number- uniqueErrors: number- affectedUsers: number- errorRate?: number- affectedSessions?: number- }- appliedFilters?: AnalyticsFilter[]-}--export async function getErrorOverviewServer(- request: Request,- pid: string,- params: AnalyticsParams & { options?: Record<string, unknown> },-): Promise<ServerFetchResult<ErrorOverviewResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('timeBucket', params.timeBucket)- queryParams.append('period', params.period)- queryParams.append('filters', serializeFiltersForUrl(params.filters))- queryParams.append('options', JSON.stringify(params.options || {}))- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<ErrorOverviewResponse>(- request,- `log/error-overview?${queryParams.toString()}`,- { headers },- )-}--// ============================================================================-// MARK: Feature Flags API (Deferred Loading)-// ============================================================================--export interface TargetingRule {- column: string- filter: string- isExclusive: boolean-}--export interface FeatureFlagSchedule {- enabled?: boolean- rolloutPercentage?: number- applyAt: string-}--export type FeatureFlagStatus =- | 'enabled'- | 'disabled'- | 'scheduled'- | 'killed'- | 'stale'+export type FeatureFlagStatus =+ | 'enabled'+ | 'disabled'+ | 'scheduled'+ | 'killed'+ | 'stale'export type FeatureFlagStaleReason =| 'not_evaluated_recently'@@ -1795,131 +1307,6 @@ export async function getGoalChartServer()}-// ============================================================================-// MARK: Funnels API (Deferred Loading)-// ============================================================================--export interface FunnelDataResponse {- funnel: {- value: string- events: number- eventsPerc: number- eventsPercStep: number- dropoff: number- dropoffPerc: number- dropoffPercStep: number- topCountries: Record<string, number>- topSources: Record<string, number>- breakdowns?: ConversionBreakdowns- }[]- totalPageviews: number- timeToConvert?: ConversionTimeToConvert-}--export async function getFunnelDataServer(- request: Request,- pid: string,- funnelId: string,- period: string,- from: string,- to: string,- timezone: string,- password?: string,- filters: AnalyticsFilter[] = [],-): Promise<ServerFetchResult<FunnelDataResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('period', period)- queryParams.append('funnelId', funnelId)- queryParams.append('filters', JSON.stringify(filters))- if (from) queryParams.append('from', from)- if (to) queryParams.append('to', to)- if (timezone) queryParams.append('timezone', timezone)-- const headers: Record<string, string> = {}- if (password) {- headers['x-password'] = password- }-- return serverFetch<FunnelDataResponse>(- request,- `log/funnel?${queryParams.toString()}`,- {- headers,- },- )-}--// ============================================================================-// MARK: Captcha API (Deferred Loading)-// ============================================================================--interface CaptchaPanelData {- name: string- count: number- cc?: string-}--interface CaptchaChartData {- x: string[]- results?: number[]- generated?: number[]- passed?: number[]- failed?: number[]- validationFailed?: number[]- replayed?: number[]-}--interface CaptchaSummaryData {- generated: number- passed: number- passRate: number | null- solveP50: number- solveP75: number- solveP95: number- difficulty: CaptchaPanelData[]- solveTime: CaptchaPanelData[]-}--export interface CaptchaDataResponse {- params: Record<string, CaptchaPanelData[]>- chart?: CaptchaChartData- summary?: CaptchaSummaryData- previousSummary?: CaptchaSummaryData | null-}--export async function getCaptchaDataServer(- request: Request,- pid: string,- timeBucket = 'hour',- period = '3d',- filters: AnalyticsFilter[] = [],- from = '',- to = '',- password?: string,-): Promise<ServerFetchResult<CaptchaDataResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('timeBucket', timeBucket)- queryParams.append('period', period)- queryParams.append('filters', JSON.stringify(filters))- if (from) queryParams.append('from', from)- if (to) queryParams.append('to', to)-- const headers: Record<string, string> = {}- if (password) {- headers['x-password'] = password- }-- return serverFetch<CaptchaDataResponse>(- request,- `log/captcha?${queryParams.toString()}`,- {- headers,- },- )-}-// ============================================================================// MARK: Experiments API (Deferred Loading)// ============================================================================@@ -2039,179 +1426,6 @@ export async function getGoalServer(return serverFetch<Goal>(request, `goal/${goalId}`)}-// ============================================================================-// MARK: Profiles API (Deferred Loading)-// ============================================================================--export interface ApiProfile {- profileId: string- isIdentified: boolean- sessionsCount: number- pageviewsCount: number- eventsCount: number- errorsCount: number- firstSeen: string- lastSeen: string- cc: string | null- os: string | null- br: string | null- dv: string | null-}--export interface ProfilesResponse {- profiles: ApiProfile[]-}--export async function getProfilesServer(- request: Request,- pid: string,- period = '7d',- filters: AnalyticsFilter[] = [],- from = '',- to = '',- take = 30,- skip = 0,- timezone = '',- profileType: 'all' | 'anonymous' | 'identified' = 'all',- password?: string,-): Promise<ServerFetchResult<ProfilesResponse>> {- const params = new URLSearchParams()- params.append('pid', pid)- params.append('take', String(take))- params.append('skip', String(skip))- params.append('period', period)- params.append('filters', JSON.stringify(filters))- params.append('profileType', profileType)- if (from) params.append('from', from)- if (to) params.append('to', to)- if (timezone) params.append('timezone', timezone)-- const headers: Record<string, string> = {}- if (password) {- headers['x-password'] = password- }-- return serverFetch<ProfilesResponse>(- request,- `log/profiles?${params.toString()}`,- { headers },- )-}--interface ProfileDetails {- profileId: string- isIdentified: boolean- sessionsCount: number- pageviewsCount: number- eventsCount: number- errorsCount: number- firstSeen: string- lastSeen: string- avgDuration: number- cc: string | null- rg: string | null- ct: string | null- os: string | null- osv: string | null- br: string | null- brv: string | null- dv: string | null- lc: string | null- totalRevenue?: number- revenueCurrency?: string- topPages?: { page: string; count: number }[]- activityCalendar?: { date: string; pageviews: number; events: number }[]-}--export type ProfileDetailsResponse = ProfileDetails--export async function getProfileServer(- request: Request,- pid: string,- profileId: string,- timezone = '',- password?: string,-): Promise<ServerFetchResult<ProfileDetailsResponse>> {- const params = new URLSearchParams()- params.append('pid', pid)- params.append('profileId', profileId)- if (timezone) params.append('timezone', timezone)-- const headers: Record<string, string> = {}- if (password) {- headers['x-password'] = password- }-- return serverFetch<ProfileDetailsResponse>(- request,- `log/profile?${params.toString()}`,- {- headers,- },- )-}--interface ProfileSession {- psid: string- cc: string | null- os: string | null- br: string | null- dv: string | null- pageviews: number- customEvents: number- errors: number- revenue?: number- refunds?: number- created: string- sessionStart?: string- lastActivity?: string- sdur?: number- duration?: number- active?: boolean- isLive?: 1 | 0 | boolean- pages?: PageflowItem[]-}--export interface ProfileSessionsResponse {- sessions: ProfileSession[]-}--export async function getProfileSessionsServer(- request: Request,- pid: string,- profileId: string,- period = 'all',- filters: AnalyticsFilter[] = [],- from = '',- to = '',- take = 30,- skip = 0,- timezone = '',- password?: string,-): Promise<ServerFetchResult<ProfileSessionsResponse>> {- const params = new URLSearchParams()- params.append('pid', pid)- params.append('profileId', profileId)- params.append('take', String(take))- params.append('skip', String(skip))- params.append('period', period)- params.append('filters', JSON.stringify(filters))- if (from) params.append('from', from)- if (to) params.append('to', to)- if (timezone) params.append('timezone', timezone)-- const headers: Record<string, string> = {}- if (password) {- headers['x-password'] = password- }-- return serverFetch<ProfileSessionsResponse>(- request,- `log/profile/sessions?${params.toString()}`,- { headers },- )-}-// ============================================================================// MARK: Projects API// ============================================================================@@ -2265,156 +1479,6 @@ export async function getProjectServer(return serverFetch<Project>(request, `project/${pid}`, { headers })}-// ============================================================================-// MARK: Custom Events Metadata API-// ============================================================================--export interface CustomEventsMetadataResponse {- result: Array<{ key: string; value: string; count: number }>-}--export async function getCustomEventsMetadataServer(- request: Request,- pid: string,- event: string,- params: {- timeBucket?: string- period?: string- from?: string- to?: string- timezone?: string- password?: string- } = {},-): Promise<ServerFetchResult<CustomEventsMetadataResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('event', event)- queryParams.append('timeBucket', params.timeBucket || 'hour')- queryParams.append('period', params.period || '1d')- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<CustomEventsMetadataResponse>(- request,- `log/meta?${queryParams.toString()}`,- {- headers,- },- )-}--// ============================================================================-// MARK: Property Metadata API-// ============================================================================--export interface PropertyMetadataResponse {- result: Array<{ key: string; value: string; count: number }>-}--export async function getPropertyMetadataServer(- request: Request,- pid: string,- property: string,- params: {- timeBucket?: string- period?: string- from?: string- to?: string- filters?: AnalyticsFilter[]- timezone?: string- password?: string- } = {},-): Promise<ServerFetchResult<PropertyMetadataResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('property', property)- queryParams.append('timeBucket', params.timeBucket || 'hour')- queryParams.append('period', params.period || '1d')- queryParams.append('filters', JSON.stringify(params.filters || []))- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<PropertyMetadataResponse>(- request,- `log/property?${queryParams.toString()}`,- {- headers,- },- )-}--// ============================================================================-// MARK: Error Sessions API-// ============================================================================--export interface ErrorAffectedSession {- psid: string- profileId: string | null- cc: string | null- br: string | null- os: string | null- firstErrorAt: string- lastErrorAt: string- errorCount: number-}--export interface ErrorSessionsResponse {- sessions: ErrorAffectedSession[]- total: number-}--export async function getErrorSessionsServer(- request: Request,- pid: string,- eid: string,- params: {- timeBucket?: string- period?: string- from?: string- to?: string- filters?: AnalyticsFilter[]- timezone?: string- take?: number- skip?: number- password?: string- } = {},-): Promise<ServerFetchResult<ErrorSessionsResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('eid', eid)- queryParams.append('timeBucket', params.timeBucket || 'hour')- queryParams.append('period', params.period || '7d')- queryParams.append('take', String(params.take || 10))- queryParams.append('skip', String(params.skip || 0))- queryParams.append('filters', serializeFiltersForUrl(params.filters || []))- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<ErrorSessionsResponse>(- request,- `log/error-sessions?${queryParams.toString()}`,- { headers },- )-}-// ============================================================================// MARK: Live Visitors API// ============================================================================@@ -2440,31 +1504,6 @@ export async function getLiveVisitorsServer(})}-export interface LiveVisitorInfo {- psid: string- dv: string- br: string- os: string- cc: string-}--export async function getLiveVisitorsInfoServer(- request: Request,- pid: string,- password?: string,-): Promise<ServerFetchResult<LiveVisitorInfo[]>> {- const headers: Record<string, string> = {}- if (password) {- headers['x-password'] = password- }-- return serverFetch<LiveVisitorInfo[]>(- request,- `log/live-visitors?pid=${pid}`,- { headers },- )-}-// ============================================================================// MARK: Bot Protection Stats API// ============================================================================@@ -2498,55 +1537,6 @@ export async function getBotProtectionStatsServer()}-// ============================================================================-// MARK: Custom Events Chart API-// ============================================================================--export interface ProjectDataCustomEventsResponse {- chart?: {- events?: Record<string, { x: string[]; y: number[] }>- }- customs?: Record<string, number>-}--export async function getProjectDataCustomEventsServer(- request: Request,- pid: string,- params: {- timeBucket?: string- period?: string- filters?: AnalyticsFilter[]- from?: string- to?: string- timezone?: string- customEvents?: string[]- password?: string- } = {},-): Promise<ServerFetchResult<ProjectDataCustomEventsResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('timeBucket', params.timeBucket || 'hour')- queryParams.append('period', params.period || '3d')- queryParams.append('filters', JSON.stringify(params.filters || []))- queryParams.append('customEvents', JSON.stringify(params.customEvents || []))- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<ProjectDataCustomEventsResponse>(- request,- `log/custom-events?${queryParams.toString()}`,- {- headers,- },- )-}-// ============================================================================// MARK: SSO API// ============================================================================@@ -2661,68 +1651,6 @@ export async function processSSOTokenServer(})}-// ============================================================================-// MARK: User Flow API-// ============================================================================--interface UserFlowNode {- id: string- name: string- count: number-}--interface UserFlowLink {- source: string- target: string- value: number-}--interface UserFlowData {- nodes: UserFlowNode[]- links: UserFlowLink[]-}--export interface UserFlowResponse {- ascending: UserFlowData- descending: UserFlowData-}--export async function getUserFlowServer(- request: Request,- pid: string,- params: {- timeBucket?: string- period?: string- filters?: AnalyticsFilter[]- from?: string- to?: string- timezone?: string- password?: string- } = {},-): Promise<ServerFetchResult<UserFlowResponse>> {- const queryParams = new URLSearchParams()- queryParams.append('pid', pid)- queryParams.append('timeBucket', params.timeBucket || 'hour')- queryParams.append('period', params.period || '3d')- queryParams.append('filters', JSON.stringify(params.filters || []))- if (params.from) queryParams.append('from', params.from)- if (params.to) queryParams.append('to', params.to)- if (params.timezone) queryParams.append('timezone', params.timezone)-- const headers: Record<string, string> = {}- if (params.password) {- headers['x-password'] = params.password- }-- return serverFetch<UserFlowResponse>(- request,- `log/user-flow?${queryParams.toString()}`,- {- headers,- },- )-}-// ============================================================================// MARK: Filters API// ============================================================================@@ -2775,50 +1703,6 @@ export async function getDataDeletionPreviewServer()}-export async function getErrorsFiltersServer(- request: Request,- pid: string,- type: string,- password?: string,-): Promise<ServerFetchResult<string[]>> {- const headers: Record<string, string> = {}- if (password) {- headers['x-password'] = password- }-- return serverFetch<string[]>(- request,- `log/errors-filters?pid=${pid}&type=${type}`,- { headers },- )-}--export interface VersionFilter {- name: string- version: string-}--export async function getVersionFiltersServer(- request: Request,- pid: string,- type: 'traffic' | 'errors',- column: 'br' | 'os',- password?: string,-): Promise<ServerFetchResult<VersionFilter[]>> {- const headers: Record<string, string> = {}- if (password) {- headers['x-password'] = password- }-- return serverFetch<VersionFilter[]>(- request,- `log/filters/versions?pid=${pid}&type=${type}&column=${column}`,- {- headers,- },- )-}-// ============================================================================// MARK: Google Search Console API// ============================================================================diff --git a/web/app/api/v2/client.ts b/web/app/api/v2/client.tsnew file mode 100644index 000000000..6ba5f437a--- /dev/null+++ b/web/app/api/v2/client.ts@@ -0,0 +1,85 @@+import { V2Envelope } from './types'++class V2ApiError extends Error {+ status: number++ constructor(status: number, message: string) {+ super(message)+ this.name = 'V2ApiError'+ this.status = status+ }+}++export type V2QueryParams = Record<+ string,+ string | number | boolean | string[] | object | null | undefined+>++const serializeParams = (params: V2QueryParams): string => {+ const searchParams = new URLSearchParams()++ for (const [key, value] of Object.entries(params)) {+ if (value === undefined || value === null) {+ continue+ }++ if (Array.isArray(value)) {+ if (value.length === 0) {+ continue+ }++ // filters (objects) -> JSON; plain values (metrics, events) -> CSV+ if (typeof value[0] === 'object') {+ searchParams.set(key, JSON.stringify(value))+ } else {+ searchParams.set(key, value.join(','))+ }+ continue+ }++ if (typeof value === 'object') {+ searchParams.set(key, JSON.stringify(value))+ continue+ }++ searchParams.set(key, String(value))+ }++ const qs = searchParams.toString()+ return qs ? `?${qs}` : ''+}++/**+ * Fetches a v2 analytics API endpoint through the /api/v2 proxy route+ * (which attaches auth and project-password headers server-side).+ *+ * `path` is relative to /v2/, e.g. `projects/<pid>/traffic/breakdown`.+ */+export async function fetchV2<T>(+ path: string,+ params: V2QueryParams = {},+ signal?: AbortSignal,+): Promise<V2Envelope<T>> {+ const response = await fetch(`/api/v2/${path}${serializeParams(params)}`, {+ signal,+ })++ let body: any = null+ try {+ body = await response.json()+ } catch {+ // non-JSON error response+ }++ if (!response.ok) {+ const message =+ (Array.isArray(body?.message)+ ? body.message.join('; ')+ : body?.message) ||+ body?.error ||+ `Request failed with status ${response.status}`+ throw new V2ApiError(response.status, message)+ }++ return body as V2Envelope<T>+}diff --git a/web/app/api/v2/endpoints.ts b/web/app/api/v2/endpoints.tsnew file mode 100644index 000000000..ad1550576--- /dev/null+++ b/web/app/api/v2/endpoints.ts@@ -0,0 +1,267 @@+import { fetchV2, V2QueryParams } from './client'+import {+ BreakdownRow,+ CaptchaSummaryData,+ CustomEventRow,+ DimensionValues,+ ErrorListItem,+ LiveVisitorsData,+ MetadataRow,+ MetricSums,+ PagePropertyRow,+ PerformanceSummaryData,+ TimeseriesRow,+ TrafficSummaryData,+ UserFlowData,+ V2CommonParams,+ V2DataType,+} from './types'++type Common = V2CommonParams & V2QueryParams++type SummaryData<T extends V2DataType> = T extends 'traffic'+ ? TrafficSummaryData+ : T extends 'performance'+ ? PerformanceSummaryData+ : T extends 'captcha'+ ? CaptchaSummaryData+ : Record<string, unknown>++export const getSummary = <T extends V2DataType>(+ pid: string,+ dataType: T,+ params: Common & { measure?: string },+ signal?: AbortSignal,+) =>+ fetchV2<SummaryData<T>>(`projects/${pid}/${dataType}/summary`, params, signal)++export const getTimeseries = (+ pid: string,+ dataType: V2DataType,+ params: Common & {+ metrics?: string[]+ timeBucket?: string+ mode?: 'periodical' | 'cumulative'+ measure?: string+ },+ signal?: AbortSignal,+) =>+ fetchV2<TimeseriesRow[]>(+ `projects/${pid}/${dataType}/timeseries`,+ params,+ signal,+ )++export const getBreakdown = (+ pid: string,+ dataType: V2DataType,+ params: Common & {+ dimension: string+ metrics?: string[]+ limit?: number+ offset?: number+ sort?: string+ measure?: string+ },+ signal?: AbortSignal,+) =>+ fetchV2<BreakdownRow[]>(+ `projects/${pid}/${dataType}/breakdown`,+ params,+ signal,+ )++export const getCustomEvents = (+ pid: string,+ params: Common & { limit?: number; offset?: number },+ signal?: AbortSignal,+) =>+ fetchV2<CustomEventRow[]>(+ `projects/${pid}/traffic/custom-events`,+ params,+ signal,+ )++export const getCustomEventsTimeseries = (+ pid: string,+ params: Common & { events: string[]; timeBucket?: string },+ signal?: AbortSignal,+) =>+ fetchV2<TimeseriesRow[]>(+ `projects/${pid}/traffic/custom-events/timeseries`,+ params,+ signal,+ )++export const getCustomEventsMetadata = (+ pid: string,+ params: Common & { event: string },+ signal?: AbortSignal,+) =>+ fetchV2<MetadataRow[]>(+ `projects/${pid}/traffic/custom-events/metadata`,+ params,+ signal,+ )++export const getCustomMetrics = (+ pid: string,+ params: Common & { metrics: string },+ signal?: AbortSignal,+) =>+ fetchV2<{ key: string; current: MetricSums; previous: MetricSums }[]>(+ `projects/${pid}/traffic/custom-metrics`,+ params,+ signal,+ )++export const getPageProperties = (+ pid: string,+ params: Common & { limit?: number; offset?: number },+ signal?: AbortSignal,+) =>+ fetchV2<PagePropertyRow[]>(+ `projects/${pid}/traffic/page-properties`,+ params,+ signal,+ )++export const getPagePropertiesMetadata = (+ pid: string,+ params: Common & { property: string },+ signal?: AbortSignal,+) =>+ fetchV2<MetadataRow[]>(+ `projects/${pid}/traffic/page-properties/metadata`,+ params,+ signal,+ )++export const getUserFlow = (+ pid: string,+ params: Common,+ signal?: AbortSignal,+) => fetchV2<UserFlowData>(`projects/${pid}/traffic/user-flow`, params, signal)++export const getErrorsList = (+ pid: string,+ params: Common & { limit?: number; offset?: number; show_resolved?: boolean },+ signal?: AbortSignal,+) => fetchV2<ErrorListItem[]>(`projects/${pid}/errors`, params, signal)++export const getErrorsOverview = (+ pid: string,+ params: Common & { timeBucket?: string },+ signal?: AbortSignal,+) =>+ fetchV2<Record<string, any>>(+ `projects/${pid}/errors/overview`,+ params,+ signal,+ )++export const getErrorDetails = (+ pid: string,+ eid: string,+ params: Common & { timeBucket?: string },+ signal?: AbortSignal,+) =>+ fetchV2<Record<string, any>>(`projects/${pid}/errors/${eid}`, params, signal)++export const getErrorSessions = (+ pid: string,+ eid: string,+ params: Common & { limit?: number; offset?: number },+ signal?: AbortSignal,+) => fetchV2<any[]>(`projects/${pid}/errors/${eid}/sessions`, params, signal)++export const getSessionsList = (+ pid: string,+ params: Common & {+ limit?: number+ offset?: number+ event_type?: 'traffic' | 'performance' | 'error'+ },+ signal?: AbortSignal,+) => fetchV2<any[]>(`projects/${pid}/sessions`, params, signal)++export const getSessionDetails = (+ pid: string,+ psid: string,+ params: { timezone?: string } & V2QueryParams,+ signal?: AbortSignal,+) =>+ fetchV2<Record<string, any>>(+ `projects/${pid}/sessions/${psid}`,+ params,+ signal,+ )++export const getProfilesList = (+ pid: string,+ params: Common & {+ limit?: number+ offset?: number+ profile_type?: 'all' | 'anonymous' | 'identified'+ search?: string+ },+ signal?: AbortSignal,+) => fetchV2<any[]>(`projects/${pid}/profiles`, params, signal)++export const getProfileDetails = (+ pid: string,+ profileId: string,+ params: { timezone?: string } & V2QueryParams,+ signal?: AbortSignal,+) =>+ fetchV2<Record<string, any>>(+ `projects/${pid}/profiles/${encodeURIComponent(profileId)}`,+ params,+ signal,+ )++export const getProfileSessions = (+ pid: string,+ profileId: string,+ params: Common & { limit?: number; offset?: number },+ signal?: AbortSignal,+) =>+ fetchV2<any[]>(+ `projects/${pid}/profiles/${encodeURIComponent(profileId)}/sessions`,+ params,+ signal,+ )++export const getFunnel = (+ pid: string,+ params: Common & { funnelId?: string; steps?: string[] },+ signal?: AbortSignal,+) => fetchV2<Record<string, any>>(`projects/${pid}/funnel`, params, signal)++export const getFunnelSessions = (+ pid: string,+ params: Common & {+ funnelId?: string+ steps?: string[]+ step: number+ dropoff?: boolean+ limit?: number+ offset?: number+ },+ signal?: AbortSignal,+) => fetchV2<any[]>(`projects/${pid}/funnel/sessions`, params, signal)++export const getLiveVisitors = (pid: string, signal?: AbortSignal) =>+ fetchV2<LiveVisitorsData>(`projects/${pid}/live-visitors`, {}, signal)++export const getDimensionValues = (+ pid: string,+ dimension: string,+ params: { type?: V2DataType } & V2QueryParams,+ signal?: AbortSignal,+) =>+ fetchV2<DimensionValues>(+ `projects/${pid}/dimensions/${dimension}/values`,+ params,+ signal,+ )diff --git a/web/app/api/v2/types.ts b/web/app/api/v2/types.tsnew file mode 100644index 000000000..0a04c0f51--- /dev/null+++ b/web/app/api/v2/types.ts@@ -0,0 +1,169 @@+export type V2DataType = 'traffic' | 'performance' | 'errors' | 'captcha'++export type V2FilterOperator = 'is' | 'is_not' | 'contains' | 'contains_not'++export interface V2Filter {+ dimension: string+ operator: V2FilterOperator+ value: string | null | (string | null)[]+ /** Required for event_metadata / page_property filters */+ key?: string+}++interface V2Meta {+ pid: string+ period?: string | null+ from?: string+ to?: string+ timezone?: string+ appliedFilters?: V2Filter[]+ /** Breakdown / list endpoints */+ total?: number+ limit?: number+ offset?: number+ sort?: string+ dimension?: string+ metrics?: string[]+ /** Timeseries endpoints */+ timeBucket?: string+ allowedTimeBuckets?: string[] | null+ mode?: string+ /** Live visitors */+ windowMinutes?: number+ [key: string]: unknown+}++export interface V2Envelope<T> {+ data: T+ meta: V2Meta+}++export type V2CommonParams = {+ period?: string+ from?: string+ to?: string+ timezone?: string+ filters?: V2Filter[]+}++/** { value: 'US', country?: ..., visitors: 119, pageviews: 267, ... } */+export interface BreakdownRow {+ value: string | null+ [metricOrExtraField: string]: unknown+}++/** { timestamp: '2026-07-01T00:00:00Z', visitors: 120, ... } */+export interface TimeseriesRow {+ timestamp: string+ [metric: string]: number | string+}++interface TrafficSummaryStats {+ visitors: number+ pageviews: number+ users: number+ bounce_rate: number+ session_duration: number+}++export interface TrafficSummaryData {+ current: TrafficSummaryStats+ previous: TrafficSummaryStats+ change: TrafficSummaryStats+}++interface PerformanceSummaryStats {+ frontend: number+ network: number+ backend: number+}++export interface PerformanceSummaryData {+ current: PerformanceSummaryStats+ previous: PerformanceSummaryStats+ change: PerformanceSummaryStats+}++interface CaptchaSummaryStats {+ generated: number+ passed: number+ passRate: number | null+ solveP50: number | null+ solveP75: number | null+ solveP95: number | null+ difficulty: { value: string; count: number }[]+ solveTime: { value: string; count: number }[]+}++export interface CaptchaSummaryData {+ current: CaptchaSummaryStats+ previous: CaptchaSummaryStats | null+}++export interface CustomEventRow {+ event: string+ count: number+}++export interface MetricSums {+ sum: number+ avg: number+}++export interface PagePropertyRow {+ property: string+ count: number+}++export interface MetadataRow {+ key: string+ value: string+ count: number+}++interface UserFlowNode {+ id: string+}++interface UserFlowLink {+ source: string+ target: string+ value: number+}++interface UserFlowGraph {+ nodes: UserFlowNode[]+ links: UserFlowLink[]+}++export interface UserFlowData {+ ascending: UserFlowGraph+ descending: UserFlowGraph+}++export interface ErrorListItem {+ eid: string+ name: string+ message: string | null+ filename: string | null+ count: number+ last_seen: string+ users: number+ sessions: number+ status: 'active' | 'regressed' | 'resolved'+}++export interface LiveVisitor {+ psid: string+ device: string | null+ browser: string | null+ os: string | null+ country: string | null+}++export interface LiveVisitorsData {+ count: number+ visitors: LiveVisitor[]+}++export type DimensionValues = string[] | { name: string; version: string }[]diff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.tsindex 72580d098..e28d88afb 100644--- a/web/app/hooks/useAnalyticsProxy.ts+++ b/web/app/hooks/useAnalyticsProxy.ts@@ -1,35 +1,22 @@import { useCallback, useRef, useState } from 'react'import type {- SessionsResponse,SessionReplaysResponse,SessionReplayResponse,DeleteSessionReplayResponse,SessionReplayExportResponse,- ErrorsResponse,FeatureFlagStats,FeatureFlagProfilesResponse,GoalStats,GoalChartData,- CaptchaDataResponse,ExperimentResults,Experiment,Goal,GoalsResponse,FeatureFlagsResponse,- ProfilesResponse,- ProfileDetailsResponse,- ProfileSessionsResponse,- VersionFilter,- CustomEventsMetadataResponse,- PropertyMetadataResponse,- ErrorSessionsResponse,LiveStats,- LiveVisitorInfo,BotProtectionStats,BotProtectionPeriod,- ProjectDataCustomEventsResponse,- UserFlowResponse,GSCDashboardResponse,RevenueStatus,RevenueDataResponse,@@ -78,36 +65,6 @@ async function postAnalytics<T>(payload: unknown): Promise<ProxyResponse<T>> {return result}-export function useSessionsProxy() {- const [data, setData] = useState<SessionsResponse | null>(null)- const [error, setError] = useState<string | null>(null)- const [isLoading, setIsLoading] = useState(false)-- const fetchSessions = useCallback(- async (projectId: string, params: ClientAnalyticsParams) => {- setIsLoading(true)- setError(null)-- try {- const result = await postAnalytics<SessionsResponse>({- action: 'getSessions',- projectId,- params,- })- setData(result.data)- setError(result.error)- } catch (err) {- setError(err instanceof Error ? err.message : 'Unknown error')- } finally {- setIsLoading(false)- }- },- [],- )-- return { fetchSessions, data, error, isLoading }-}-export function useSessionReplaysProxy() {const [data, setData] = useState<SessionReplaysResponse | null>(null)const [error, setError] = useState<string | null>(null)@@ -282,36 +239,6 @@ export function useSessionReplayExportProxy() {}}-export function useErrorsProxy() {- const [data, setData] = useState<ErrorsResponse | null>(null)- const [error, setError] = useState<string | null>(null)- const [isLoading, setIsLoading] = useState(false)-- const fetchErrors = useCallback(- async (projectId: string, params: ClientAnalyticsParams) => {- setIsLoading(true)- setError(null)-- try {- const result = await postAnalytics<ErrorsResponse>({- action: 'getErrors',- projectId,- params,- })- setData(result.data)- setError(result.error)- } catch (err) {- setError(err instanceof Error ? err.message : 'Unknown error')- } finally {- setIsLoading(false)- }- },- [],- )-- return { fetchErrors, data, error, isLoading }-}-export function useFeatureFlagStatsProxy() {const [data, setData] = useState<FeatureFlagStats | null>(null)const [error, setError] = useState<string | null>(null)@@ -440,38 +367,6 @@ export function useGoalChartProxy() {return { fetchChart, data, error, isLoading }}-export function useCaptchaProxy() {- const [data, setData] = useState<CaptchaDataResponse | null>(null)- const [error, setError] = useState<string | null>(null)- const [isLoading, setIsLoading] = useState(false)-- const fetchCaptcha = useCallback(- async (projectId: string, params: ClientAnalyticsParams) => {- setIsLoading(true)- setError(null)-- try {- const result = await postAnalytics<CaptchaDataResponse>({- action: 'getCaptchaData',- projectId,- params,- })- setData(result.data)- setError(result.error)- return result.data- } catch (err) {- setError(err instanceof Error ? err.message : 'Unknown error')- return null- } finally {- setIsLoading(false)- }- },- [],- )-- return { fetchCaptcha, data, error, isLoading }-}-export function useExperimentResultsProxy() {const [data, setData] = useState<ExperimentResults | null>(null)const [error, setError] = useState<string | null>(null)@@ -626,117 +521,6 @@ export function useProjectFeatureFlagsProxy() {return { fetchFeatureFlags, data, error, isLoading }}-export function useProfilesProxy() {- const [data, setData] = useState<ProfilesResponse | null>(null)- const [error, setError] = useState<string | null>(null)- const [isLoading, setIsLoading] = useState(false)-- const fetchProfiles = useCallback(- async (- projectId: string,- params: ClientAnalyticsParams & {- profileType?: 'all' | 'anonymous' | 'identified'- } = {},- ) => {- setIsLoading(true)- setError(null)-- try {- const result = await postAnalytics<ProfilesResponse>({- action: 'getProfiles',- projectId,- params,- })- setData(result.data)- setError(result.error)- return result.data- } catch (err) {- setError(err instanceof Error ? err.message : 'Unknown error')- return null- } finally {- setIsLoading(false)- }- },- [],- )-- return { fetchProfiles, data, error, isLoading }-}--export function useProfileProxy() {- const [data, setData] = useState<ProfileDetailsResponse | null>(null)- const [error, setError] = useState<string | null>(null)- const [isLoading, setIsLoading] = useState(false)-- const fetchProfile = useCallback(- async (- projectId: string,- profileId: string,- params: ClientAnalyticsParams = {},- ) => {- setIsLoading(true)- setError(null)-- try {- const result = await postAnalytics<ProfileDetailsResponse>({- action: 'getProfile',- projectId,- profileId,- params,- })- setData(result.data)- setError(result.error)- return result.data- } catch (err) {- setError(err instanceof Error ? err.message : 'Unknown error')- return null- } finally {- setIsLoading(false)- }- },- [],- )-- return { fetchProfile, data, error, isLoading }-}--export function useProfileSessionsProxy() {- const [data, setData] = useState<ProfileSessionsResponse | null>(null)- const [error, setError] = useState<string | null>(null)- const [isLoading, setIsLoading] = useState(false)-- const fetchProfileSessions = useCallback(- async (- projectId: string,- profileId: string,- params: ClientAnalyticsParams = {},- ) => {- setIsLoading(true)- setError(null)-- try {- const result = await postAnalytics<ProfileSessionsResponse>({- action: 'getProfileSessions',- projectId,- profileId,- params,- })- setData(result.data)- setError(result.error)- return result.data- } catch (err) {- setError(err instanceof Error ? err.message : 'Unknown error')- return null- } finally {- setIsLoading(false)- }- },- [],- )-- return { fetchProfileSessions, data, error, isLoading }-}-export function useFiltersProxy() {const fetchFilters = useCallback(async (projectId: string, filterType: string): Promise<string[] | null> => {@@ -756,48 +540,7 @@ export function useFiltersProxy() {[],)- const fetchErrorsFilters = useCallback(- async (projectId: string, filterType: string): Promise<string[] | null> => {- try {- const result = await postAnalytics<string[]>({- action: 'getErrorsFilters',- projectId,- filterType,- params: {},- })- return result.data- } catch (err) {- console.error('[useFiltersProxy] Error:', err)- throw err- }- },- [],- )-- const fetchVersionFilters = useCallback(- async (- projectId: string,- dataType: 'traffic' | 'errors',- filterColumn: 'br' | 'os',- ): Promise<VersionFilter[] | null> => {- try {- const result = await postAnalytics<VersionFilter[]>({- action: 'getVersionFilters',- projectId,- dataType,- filterColumn,- params: {},- })- return result.data- } catch (err) {- console.error('[useFiltersProxy] Error:', err)- throw err- }- },- [],- )-- return { fetchFilters, fetchErrorsFilters, fetchVersionFilters }+ return { fetchFilters }}export function useDataDeletionPreviewProxy() {@@ -827,95 +570,6 @@ export function useDataDeletionPreviewProxy() {return { fetchPreview }}-export function useCustomEventsMetadataProxy() {- const fetchMetadata = useCallback(- async (- projectId: string,- event: string,- params: ClientAnalyticsParams = {},- ): Promise<CustomEventsMetadataResponse | null> => {- try {- const result = await postAnalytics<CustomEventsMetadataResponse>({- action: 'getCustomEventsMetadata',- projectId,- event,- params,- })- return result.data- } catch (err) {- console.error('[useCustomEventsMetadataProxy] Error:', err)- throw err- }- },- [],- )-- return { fetchMetadata }-}--export function usePropertyMetadataProxy() {- const fetchMetadata = useCallback(- async (- projectId: string,- property: string,- params: ClientAnalyticsParams = {},- ): Promise<PropertyMetadataResponse | null> => {- try {- const result = await postAnalytics<PropertyMetadataResponse>({- action: 'getPropertyMetadata',- projectId,- property,- params,- })- return result.data- } catch (err) {- console.error('[usePropertyMetadataProxy] Error:', err)- throw err- }- },- [],- )-- return { fetchMetadata }-}--export function useErrorSessionsProxy() {- const [data, setData] = useState<ErrorSessionsResponse | null>(null)- const [error, setError] = useState<string | null>(null)- const [isLoading, setIsLoading] = useState(false)-- const fetchErrorSessions = useCallback(- async (- projectId: string,- errorId: string,- params: ClientAnalyticsParams = {},- ) => {- setIsLoading(true)- setError(null)-- try {- const result = await postAnalytics<ErrorSessionsResponse>({- action: 'getErrorSessions',- projectId,- errorId,- params,- })- setData(result.data)- setError(result.error)- return result.data- } catch (err) {- setError(err instanceof Error ? err.message : 'Unknown error')- return null- } finally {- setIsLoading(false)- }- },- [],- )-- return { fetchErrorSessions, data, error, isLoading }-}-export function useLiveVisitorsProxy() {const fetchLiveVisitors = useCallback(async (pids: string[]): Promise<LiveStats | null> => {@@ -938,24 +592,7 @@ export function useLiveVisitorsProxy() {[],)- const fetchLiveVisitorsInfo = useCallback(- async (projectId: string): Promise<LiveVisitorInfo[] | null> => {- try {- const result = await postAnalytics<LiveVisitorInfo[]>({- action: 'getLiveVisitorsInfo',- projectId,- params: {},- })- return result.data- } catch (err) {- console.error('[useLiveVisitorsProxy] Error:', err)- throw err- }- },- [],- )-- return { fetchLiveVisitors, fetchLiveVisitorsInfo }+ return { fetchLiveVisitors }}export function useBotProtectionStatsProxy() {@@ -982,64 +619,6 @@ export function useBotProtectionStatsProxy() {return { fetchBotProtectionStats }}-export function useProjectDataCustomEventsProxy() {- const fetchCustomEvents = useCallback(- async (- projectId: string,- customEvents: string[],- params: ClientAnalyticsParams = {},- ): Promise<ProjectDataCustomEventsResponse | null> => {- try {- const result = await postAnalytics<ProjectDataCustomEventsResponse>({- action: 'getProjectDataCustomEvents',- projectId,- customEvents,- params,- })- return result.data- } catch (err) {- console.error('[useProjectDataCustomEventsProxy] Error:', err)- throw err- }- },- [],- )-- return { fetchCustomEvents }-}--export function useUserFlowProxy() {- const [data, setData] = useState<UserFlowResponse | null>(null)- const [error, setError] = useState<string | null>(null)- const [isLoading, setIsLoading] = useState(false)-- const fetchUserFlow = useCallback(- async (projectId: string, params: ClientAnalyticsParams = {}) => {- setIsLoading(true)- setError(null)-- try {- const result = await postAnalytics<UserFlowResponse>({- action: 'getUserFlow',- projectId,- params,- })- setData(result.data)- setError(result.error)- return result.data- } catch (err) {- setError(err instanceof Error ? err.message : 'Unknown error')- return null- } finally {- setIsLoading(false)- }- },- [],- )-- return { fetchUserFlow, data, error, isLoading }-}-export function useGSCDashboardProxy() {const [data, setData] = useState<GSCDashboardResponse | null>(null)const [error, setError] = useState<string | null>(null)diff --git a/web/app/hooks/useInViewOnce.ts b/web/app/hooks/useInViewOnce.tsnew file mode 100644index 000000000..22b742c1e--- /dev/null+++ b/web/app/hooks/useInViewOnce.ts@@ -0,0 +1,53 @@+import { useEffect, useRef, useState } from 'react'++interface UseInViewOnceOptions {+ rootMargin?: string+ /** Skip observing entirely (treated as already in view) */+ disabled?: boolean+}++/**+ * Latching IntersectionObserver hook: `hasBeenInView` flips to true the first+ * time the element comes near the viewport and stays true afterwards, so+ * queries gated on it keep refetching normally once loaded.+ *+ * Renders `false` on the server and on the first client render (no hydration+ * mismatch), then flips on mount for elements already in view.+ */+export const useInViewOnce = <T extends HTMLElement = HTMLDivElement>({+ rootMargin = '400px 0px',+ disabled,+}: UseInViewOnceOptions = {}) => {+ const ref = useRef<T | null>(null)+ const [hasBeenInView, setHasBeenInView] = useState(false)++ useEffect(() => {+ if (disabled || hasBeenInView) {+ if (disabled) setHasBeenInView(true)+ return+ }++ const element = ref.current++ if (!element || typeof IntersectionObserver === 'undefined') {+ setHasBeenInView(true)+ return+ }++ const observer = new IntersectionObserver(+ (entries) => {+ if (entries.some((entry) => entry.isIntersecting)) {+ setHasBeenInView(true)+ observer.disconnect()+ }+ },+ { rootMargin },+ )++ observer.observe(element)++ return () => observer.disconnect()+ }, [disabled, hasBeenInView, rootMargin])++ return { ref, hasBeenInView }+}diff --git a/web/app/hooks/v2/useV2Queries.ts b/web/app/hooks/v2/useV2Queries.tsnew file mode 100644index 000000000..a9fa691af--- /dev/null+++ b/web/app/hooks/v2/useV2Queries.ts@@ -0,0 +1,510 @@+import {+ keepPreviousData,+ useInfiniteQuery,+ useQuery,+} from '@tanstack/react-query'+import { useMemo } from 'react'+import { useSearchParams } from 'react-router'++import * as v2 from '~/api/v2/endpoints'+import { V2CommonParams, V2DataType, V2Filter } from '~/api/v2/types'+import { VALID_DIMENSIONS_BY_TYPE } from '~/lib/v2Dimensions'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'+import { useCurrentProject } from '~/providers/CurrentProjectProvider'++/**+ * Stable, normalized common params (time range + timezone + filters valid for+ * the given data type) derived from the project view context. Embedded in+ * every query key, so any change refetches exactly the affected queries.+ */+export const useV2CommonParams = (dataType: V2DataType) => {+ const { id: pid } = useCurrentProject()+ const { period, timezone, filters } = useViewProjectContext()+ const [searchParams] = useSearchParams()++ const from = searchParams.get('from') || undefined+ const to = searchParams.get('to') || undefined++ return useMemo(() => {+ const validDimensions = VALID_DIMENSIONS_BY_TYPE[dataType]+ const applicableFilters = filters.filter((filter) =>+ validDimensions.includes(filter.dimension),+ )++ const isCustomRange = period === 'custom' && from && to++ const common: V2CommonParams = {+ ...(isCustomRange ? { from, to } : { period }),+ timezone,+ filters: applicableFilters,+ }++ return { pid, common }+ }, [pid, dataType, period, from, to, timezone, filters])+}++/** Compare range (from/to) when compare mode is active, null otherwise */+const useCompareParams = () => {+ const { isActiveCompare } = useViewProjectContext()+ const [searchParams] = useSearchParams()++ const compareFrom = searchParams.get('compareFrom')+ const compareTo = searchParams.get('compareTo')++ if (!isActiveCompare || !compareFrom || !compareTo) {+ return null+ }++ return { from: compareFrom, to: compareTo }+}++const compareOverride = (+ common: V2CommonParams,+ compare: { from: string; to: string },+): V2CommonParams => {+ const { period: _period, ...rest } = common+ return { ...rest, from: compare.from, to: compare.to }+}++export const useSummaryQuery = <T extends V2DataType>(+ dataType: T,+ opts: { measure?: string; enabled?: boolean } = {},+) => {+ const { pid, common } = useV2CommonParams(dataType)+ const params = { ...common, measure: opts.measure }++ return useQuery({+ queryKey: ['v2', pid, dataType, 'summary', params],+ queryFn: ({ signal }) => v2.getSummary(pid, dataType, params, signal),+ placeholderData: keepPreviousData,+ enabled: opts.enabled,+ })+}++/** Summary over the compare range; disabled when compare mode is off */+export const useCompareSummaryQuery = <T extends V2DataType>(+ dataType: T,+ opts: { measure?: string; enabled?: boolean } = {},+) => {+ const { pid, common } = useV2CommonParams(dataType)+ const compare = useCompareParams()+ const params = compare+ ? { ...compareOverride(common, compare), measure: opts.measure }+ : null++ return useQuery({+ queryKey: ['v2', pid, dataType, 'summary', params],+ queryFn: ({ signal }) => v2.getSummary(pid, dataType, params!, signal),+ placeholderData: keepPreviousData,+ enabled: Boolean(params) && opts.enabled !== false,+ })+}++interface TimeseriesOpts {+ metrics?: string[]+ mode?: 'periodical' | 'cumulative'+ measure?: string+ enabled?: boolean+}++export const useTimeseriesQuery = (+ dataType: V2DataType,+ opts: TimeseriesOpts = {},+) => {+ const { pid, common } = useV2CommonParams(dataType)+ const { timeBucket } = useViewProjectContext()+ const params = {+ ...common,+ timeBucket: timeBucket || undefined,+ metrics: opts.metrics,+ mode: opts.mode,+ measure: opts.measure,+ }++ return useQuery({+ queryKey: ['v2', pid, dataType, 'timeseries', params],+ queryFn: ({ signal }) => v2.getTimeseries(pid, dataType, params, signal),+ placeholderData: keepPreviousData,+ enabled: opts.enabled,+ })+}++export const useCompareTimeseriesQuery = (+ dataType: V2DataType,+ opts: TimeseriesOpts = {},+) => {+ const { pid, common } = useV2CommonParams(dataType)+ const { timeBucket } = useViewProjectContext()+ const compare = useCompareParams()+ const params = compare+ ? {+ ...compareOverride(common, compare),+ timeBucket: timeBucket || undefined,+ metrics: opts.metrics,+ mode: opts.mode,+ measure: opts.measure,+ }+ : null++ return useQuery({+ queryKey: ['v2', pid, dataType, 'timeseries', params],+ queryFn: ({ signal }) => v2.getTimeseries(pid, dataType, params!, signal),+ placeholderData: keepPreviousData,+ enabled: Boolean(params) && opts.enabled !== false,+ })+}++interface BreakdownOpts {+ dimension: string+ metrics?: string[]+ limit?: number+ offset?: number+ sort?: string+ measure?: string+ /** Extra filters merged on top of the shared ones (e.g. version drill-down) */+ extraFilters?: V2Filter[]+ enabled?: boolean+}++export const useBreakdownQuery = (+ dataType: V2DataType,+ opts: BreakdownOpts,+) => {+ const { pid, common } = useV2CommonParams(dataType)+ const params = {+ ...common,+ filters: opts.extraFilters+ ? [...(common.filters || []), ...opts.extraFilters]+ : common.filters,+ dimension: opts.dimension,+ metrics: opts.metrics,+ limit: opts.limit,+ offset: opts.offset,+ sort: opts.sort,+ measure: opts.measure,+ }++ return useQuery({+ queryKey: ['v2', pid, dataType, 'breakdown', params],+ queryFn: ({ signal }) => v2.getBreakdown(pid, dataType, params, signal),+ placeholderData: keepPreviousData,+ enabled: opts.enabled,+ })+}++const DETAILS_PAGE_SIZE = 100++/** Infinite offset-paged breakdown for the details modal */+export const useBreakdownDetailsQuery = (+ dataType: V2DataType,+ opts: Omit<BreakdownOpts, 'limit' | 'offset'>,+) => {+ const { pid, common } = useV2CommonParams(dataType)+ const params = {+ ...common,+ filters: opts.extraFilters+ ? [...(common.filters || []), ...opts.extraFilters]+ : common.filters,+ dimension: opts.dimension,+ metrics: opts.metrics,+ sort: opts.sort,+ measure: opts.measure,+ }++ return useInfiniteQuery({+ queryKey: ['v2', pid, dataType, 'breakdown-details', params],+ queryFn: ({ signal, pageParam }) =>+ v2.getBreakdown(+ pid,+ dataType,+ { ...params, limit: DETAILS_PAGE_SIZE, offset: pageParam },+ signal,+ ),+ initialPageParam: 0,+ getNextPageParam: (lastPage, pages) => {+ const total = lastPage.meta.total ?? 0+ const loaded = pages.reduce((acc, page) => acc + page.data.length, 0)+ return loaded < total ? loaded : undefined+ },+ placeholderData: keepPreviousData,+ enabled: opts.enabled,+ })+}++export const useCustomEventsQuery = (+ opts: { limit?: number; enabled?: boolean } = {},+) => {+ const { pid, common } = useV2CommonParams('traffic')+ const params = { ...common, limit: opts.limit }++ return useQuery({+ queryKey: ['v2', pid, 'traffic', 'custom-events', params],+ queryFn: ({ signal }) => v2.getCustomEvents(pid, params, signal),+ placeholderData: keepPreviousData,+ enabled: opts.enabled,+ })+}++export const useCustomEventsTimeseriesQuery = (+ events: string[],+ opts: { enabled?: boolean } = {},+) => {+ const { pid, common } = useV2CommonParams('traffic')+ const { timeBucket } = useViewProjectContext()+ const params = { ...common, timeBucket: timeBucket || undefined, events }++ return useQuery({+ queryKey: ['v2', pid, 'traffic', 'custom-events-timeseries', params],+ queryFn: ({ signal }) => v2.getCustomEventsTimeseries(pid, params, signal),+ placeholderData: keepPreviousData,+ enabled: events.length > 0 && opts.enabled !== false,+ })+}++/** Project-view custom metrics (sum/avg of numeric event metadata) cards */+export const useCustomMetricsQuery = (+ customMetrics: unknown[],+ opts: { enabled?: boolean } = {},+) => {+ const { pid, common } = useV2CommonParams('traffic')+ const metrics = customMetrics.length ? JSON.stringify(customMetrics) : null+ const params = { ...common, metrics: metrics! }++ return useQuery({+ queryKey: ['v2', pid, 'traffic', 'custom-metrics', params],+ queryFn: ({ signal }) => v2.getCustomMetrics(pid, params, signal),+ placeholderData: keepPreviousData,+ enabled: Boolean(metrics) && opts.enabled !== false,+ })+}++export const usePagePropertiesQuery = (+ opts: { limit?: number; enabled?: boolean } = {},+) => {+ const { pid, common } = useV2CommonParams('traffic')+ const params = { ...common, limit: opts.limit }++ return useQuery({+ queryKey: ['v2', pid, 'traffic', 'page-properties', params],+ queryFn: ({ signal }) => v2.getPageProperties(pid, params, signal),+ placeholderData: keepPreviousData,+ enabled: opts.enabled,+ })+}++export const useUserFlowQuery = (opts: { enabled?: boolean } = {}) => {+ const { pid, common } = useV2CommonParams('traffic')++ return useQuery({+ queryKey: ['v2', pid, 'traffic', 'user-flow', common],+ queryFn: ({ signal }) => v2.getUserFlow(pid, common, signal),+ placeholderData: keepPreviousData,+ enabled: opts.enabled,+ })+}++const LIST_PAGE_SIZE = 30++const listNextPageParam = (pageSize: number) => {+ return (lastPage: { data: unknown[] }, pages: { data: unknown[] }[]) =>+ lastPage.data.length === pageSize+ ? pages.reduce((acc, page) => acc + page.data.length, 0)+ : undefined+}++export const useErrorsListQuery = (+ opts: { showResolved?: boolean; enabled?: boolean } = {},+) => {+ const { pid, common } = useV2CommonParams('errors')+ const params = { ...common, show_resolved: opts.showResolved }++ return useInfiniteQuery({+ queryKey: ['v2', pid, 'errors', 'list', params],+ queryFn: ({ signal, pageParam }) =>+ v2.getErrorsList(+ pid,+ { ...params, limit: LIST_PAGE_SIZE, offset: pageParam },+ signal,+ ),+ initialPageParam: 0,+ getNextPageParam: listNextPageParam(LIST_PAGE_SIZE),+ placeholderData: keepPreviousData,+ enabled: opts.enabled,+ })+}++export const useErrorsOverviewQuery = (opts: { enabled?: boolean } = {}) => {+ const { pid, common } = useV2CommonParams('errors')+ const { timeBucket } = useViewProjectContext()+ const params = { ...common, timeBucket: timeBucket || undefined }++ return useQuery({+ queryKey: ['v2', pid, 'errors', 'overview', params],+ queryFn: ({ signal }) => v2.getErrorsOverview(pid, params, signal),+ placeholderData: keepPreviousData,+ enabled: opts.enabled,+ })+}++export const useErrorDetailsQuery = (+ eid: string | null,+ opts: { enabled?: boolean } = {},+) => {+ const { pid, common } = useV2CommonParams('errors')+ const { timeBucket } = useViewProjectContext()+ const params = { ...common, timeBucket: timeBucket || undefined }++ return useQuery({+ queryKey: ['v2', pid, 'errors', 'details', eid, params],+ queryFn: ({ signal }) => v2.getErrorDetails(pid, eid!, params, signal),+ placeholderData: keepPreviousData,+ enabled: Boolean(eid) && opts.enabled !== false,+ })+}++const ERROR_SESSIONS_PAGE_SIZE = 10++export const useErrorSessionsQuery = (+ eid: string | null,+ opts: { enabled?: boolean } = {},+) => {+ const { pid, common } = useV2CommonParams('errors')++ return useInfiniteQuery({+ queryKey: ['v2', pid, 'errors', 'sessions', eid, common],+ queryFn: ({ signal, pageParam }) =>+ v2.getErrorSessions(+ pid,+ eid!,+ { ...common, limit: ERROR_SESSIONS_PAGE_SIZE, offset: pageParam },+ signal,+ ),+ initialPageParam: 0,+ getNextPageParam: listNextPageParam(ERROR_SESSIONS_PAGE_SIZE),+ placeholderData: keepPreviousData,+ enabled: Boolean(eid) && opts.enabled !== false,+ })+}++export const useSessionsListQuery = (+ opts: {+ eventType?: 'traffic' | 'performance' | 'error'+ enabled?: boolean+ } = {},+) => {+ const { pid, common } = useV2CommonParams('traffic')+ const params = { ...common, event_type: opts.eventType }++ return useInfiniteQuery({+ queryKey: ['v2', pid, 'sessions', 'list', params],+ queryFn: ({ signal, pageParam }) =>+ v2.getSessionsList(+ pid,+ { ...params, limit: LIST_PAGE_SIZE, offset: pageParam },+ signal,+ ),+ initialPageParam: 0,+ getNextPageParam: listNextPageParam(LIST_PAGE_SIZE),+ placeholderData: keepPreviousData,+ enabled: opts.enabled,+ })+}++export const useSessionDetailsQuery = (+ psid: string | null,+ opts: { enabled?: boolean } = {},+) => {+ const { id: pid } = useCurrentProject()+ const { timezone } = useViewProjectContext()+ const params = { timezone }++ return useQuery({+ queryKey: ['v2', pid, 'sessions', 'details', psid, params],+ queryFn: ({ signal }) => v2.getSessionDetails(pid, psid!, params, signal),+ placeholderData: keepPreviousData,+ enabled: Boolean(psid) && opts.enabled !== false,+ })+}++export const useProfilesListQuery = (+ opts: {+ profileType?: 'all' | 'anonymous' | 'identified'+ search?: string+ enabled?: boolean+ } = {},+) => {+ const { pid, common } = useV2CommonParams('traffic')+ const params = {+ ...common,+ profile_type: opts.profileType,+ search: opts.search || undefined,+ }++ return useInfiniteQuery({+ queryKey: ['v2', pid, 'profiles', 'list', params],+ queryFn: ({ signal, pageParam }) =>+ v2.getProfilesList(+ pid,+ { ...params, limit: LIST_PAGE_SIZE, offset: pageParam },+ signal,+ ),+ initialPageParam: 0,+ getNextPageParam: listNextPageParam(LIST_PAGE_SIZE),+ placeholderData: keepPreviousData,+ enabled: opts.enabled,+ })+}++export const useProfileDetailsQuery = (+ profileId: string | null,+ opts: { enabled?: boolean } = {},+) => {+ const { id: pid } = useCurrentProject()+ const { timezone } = useViewProjectContext()+ const params = { timezone }++ return useQuery({+ queryKey: ['v2', pid, 'profiles', 'details', profileId, params],+ queryFn: ({ signal }) =>+ v2.getProfileDetails(pid, profileId!, params, signal),+ placeholderData: keepPreviousData,+ enabled: Boolean(profileId) && opts.enabled !== false,+ })+}++export const useProfileSessionsQuery = (+ profileId: string | null,+ opts: { enabled?: boolean } = {},+) => {+ const { pid, common } = useV2CommonParams('traffic')++ return useInfiniteQuery({+ queryKey: ['v2', pid, 'profiles', 'sessions', profileId, common],+ queryFn: ({ signal, pageParam }) =>+ v2.getProfileSessions(+ pid,+ profileId!,+ { ...common, limit: LIST_PAGE_SIZE, offset: pageParam },+ signal,+ ),+ initialPageParam: 0,+ getNextPageParam: listNextPageParam(LIST_PAGE_SIZE),+ placeholderData: keepPreviousData,+ enabled: Boolean(profileId) && opts.enabled !== false,+ })+}++export const useFunnelQuery = (+ funnelId: string | null,+ opts: { enabled?: boolean } = {},+) => {+ const { pid, common } = useV2CommonParams('traffic')+ const params = { ...common, funnelId: funnelId! }++ return useQuery({+ queryKey: ['v2', pid, 'funnel', params],+ queryFn: ({ signal }) => v2.getFunnel(pid, params, signal),+ placeholderData: keepPreviousData,+ enabled: Boolean(funnelId) && opts.enabled !== false,+ })+}diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.tsindex d91b3c024..4ee8a3ce2 100644--- a/web/app/lib/constants/index.ts+++ b/web/app/lib/constants/index.ts@@ -225,58 +225,6 @@ export const PERIOD_PAIRS_COMPARE = {DISABLE: 'disable',} as const-// the order of panels in the project view-export const TRAFFIC_PANELS_ORDER = [- 'location',- 'pg',- 'devices',- 'traffic-sources',- 'network',-]-export const PERFORMANCE_PANELS_ORDER = ['location', 'pg', 'devices', 'network']-export const ERROR_PANELS_ORDER = ['location', 'pg', 'devices', 'network']-export const FILTERS_PANELS_ORDER = [- 'pg',- 'entryPage',- 'exitPage',- 'host',- 'cc',- 'rg',- 'ct',- 'lc',- 'dv',- 'br',- 'brv',- 'os',- 'osv',- 'ref',- 'so',- 'me',- 'ca',- 'te',- 'co',- 'isp',- 'og',- 'ut',- 'ctp',-]-export const ERRORS_FILTERS_PANELS_ORDER = [- 'cc',- 'rg',- 'ct',- 'pg',- 'br',- 'brv',- 'os',- 'osv',- 'lc',- 'dv',- 'isp',- 'og',- 'ut',- 'ctp',-]-// the maximum amount of months user can go back when picking a date in flat picker (project view)export const MAX_MONTHS_IN_PAST = 24diff --git a/web/app/lib/models/Entry.ts b/web/app/lib/models/Entry.tsindex c8c6250ac..571fdfea9 100644--- a/web/app/lib/models/Entry.ts+++ b/web/app/lib/models/Entry.ts@@ -4,8 +4,3 @@ export interface Entry {cc?: stringrgc?: string}--export interface CountryEntry extends Entry {- cc: string- rgc?: string-}diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.tsindex c2e2acf2d..88af6d8d9 100644--- a/web/app/lib/models/Project.ts+++ b/web/app/lib/models/Project.ts@@ -73,18 +73,6 @@ export interface Annotation {created: string}-export interface SwetrixError {- eid: string- name: string- message: string- filename: string- count: number- last_seen: string- status: 'active' | 'regressed' | 'fixed' | 'resolved'- users: number- sessions: number-}-type SessionReplayPrivacy = 'total' | 'normal' | 'none'export interface SessionReplayMetadata {@@ -99,17 +87,16 @@ export interface SessionReplayMetadata {export interface Session {psid: string- cc: string | null+ country: string | nullos: string | null- br: string | null+ browser: string | nullpageviews: numbercustomEvents: numbererrors: numberrevenue?: numberrefunds?: number- created: stringisLive: 1 | 0- sdur?: number+ duration?: number | nullsessionStart: stringlastActivity: string@@ -123,24 +110,24 @@ export interface Session {}export interface SessionDetails {- cc: string | null+ country: string | nullos: string | null- osv: string | null- br: string | null- brv: string | null- lc: string | null- ref: string | null- so: string | null- me: string | null- ca: string | null- te: string | null- co: string | null- rg: string | null- ct: string | null- dv: string | null+ os_version: string | null+ browser: string | null+ browser_version: string | null+ locale: string | null+ referrer: string | null+ utm_source: string | null+ utm_medium: string | null+ utm_campaign: string | null+ utm_term: string | null+ utm_content: string | null+ region: string | null+ city: string | null+ device: string | nullprofileId: string | null- sdur?: number+ duration?: numberisLive?: booleanrevenue?: numberrefunds?: number@@ -155,19 +142,19 @@ export interface Profile {errorsCount: numberfirstSeen: stringlastSeen: string- cc: string | null+ country: string | nullos: string | null- br: string | null- dv: string | null+ browser: string | null+ device: string | null}export interface ProfileDetails extends Profile {avgDuration: number- rg: string | null- ct: string | null- lc: string | null- osv: string | null- brv: string | null+ region: string | null+ city: string | null+ locale: string | null+ os_version: string | null+ browser_version: string | nulltopPages: { page: string; count: number }[]activityCalendar: { date: string; pageviews: number; events: number }[]totalRevenue?: numberdiff --git a/web/app/lib/v2Dimensions.ts b/web/app/lib/v2Dimensions.tsnew file mode 100644index 000000000..6e2bd7c16--- /dev/null+++ b/web/app/lib/v2Dimensions.ts@@ -0,0 +1,137 @@+import { V2DataType } from '~/api/v2/types'++// Frontend mirror of backend/apps/*/src/analytics/v2/registry/dimensions.ts.+// v1 short codes are kept only as URL aliases so old shared links keep working.++export const V1_TO_V2_DIMENSION: Record<string, string> = {+ cc: 'country',+ rg: 'region',+ ct: 'city',+ pg: 'page',+ host: 'host',+ lc: 'locale',+ br: 'browser',+ brv: 'browser_version',+ os: 'os',+ osv: 'os_version',+ dv: 'device',+ ref: 'referrer',+ refn: 'referrer_name',+ so: 'utm_source',+ me: 'utm_medium',+ ca: 'utm_campaign',+ te: 'utm_term',+ co: 'utm_content',+ isp: 'isp',+ og: 'organization',+ ut: 'user_type',+ ctp: 'connection_type',+ entryPage: 'entry_page',+ exitPage: 'exit_page',+ ev: 'event',+}++/** Keyed filter families: URL key `event_metadata:<key>` (legacy `ev:key:<key>`) */+export const KEYED_DIMENSIONS = ['event_metadata', 'page_property'] as const++export const V1_KEYED_PREFIX_TO_V2: Record<string, string> = {+ 'ev:key:': 'event_metadata',+ 'tag:key:': 'page_property',+}++const TRAFFIC_DIMENSIONS = [+ 'country',+ 'region',+ 'city',+ 'page',+ 'host',+ 'locale',+ 'browser',+ 'browser_version',+ 'os',+ 'os_version',+ 'device',+ 'referrer',+ 'referrer_name',+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'utm_term',+ 'utm_content',+ 'isp',+ 'organization',+ 'user_type',+ 'connection_type',+ 'entry_page',+ 'exit_page',+ 'event',+ 'event_metadata',+ 'page_property',+]++const PERFORMANCE_DIMENSIONS = [+ 'country',+ 'region',+ 'city',+ 'page',+ 'host',+ 'browser',+ 'browser_version',+ 'device',+ 'isp',+ 'organization',+ 'user_type',+ 'connection_type',+]++const ERROR_DIMENSIONS = [+ 'country',+ 'region',+ 'city',+ 'page',+ 'host',+ 'locale',+ 'browser',+ 'browser_version',+ 'os',+ 'os_version',+ 'device',+ 'isp',+ 'organization',+ 'user_type',+ 'connection_type',+ 'entry_page',+ 'exit_page',+ 'error_name',+ 'error_message',+ 'error_filename',+ 'page_property',+]++const CAPTCHA_DIMENSIONS = [+ 'country',+ 'browser',+ 'os',+ 'device',+ 'captcha_event',+ 'captcha_difficulty',+ 'captcha_reason',+ 'solve_time',+]++export const VALID_DIMENSIONS_BY_TYPE: Record<V2DataType, string[]> = {+ traffic: TRAFFIC_DIMENSIONS,+ performance: PERFORMANCE_DIMENSIONS,+ errors: ERROR_DIMENSIONS,+ captcha: CAPTCHA_DIMENSIONS,+}++/** Every dimension name that may appear as a URL filter key */+export const ALL_VALID_DIMENSIONS = Array.from(+ new Set([+ ...TRAFFIC_DIMENSIONS,+ ...PERFORMANCE_DIMENSIONS,+ ...ERROR_DIMENSIONS,+ ...CAPTCHA_DIMENSIONS,+ ]),+)diff --git a/web/app/pages/Project/Settings/components/DeleteDataModal.tsx b/web/app/pages/Project/Settings/components/DeleteDataModal.tsxindex 3c34720f6..746fe119b 100644--- a/web/app/pages/Project/Settings/components/DeleteDataModal.tsx+++ b/web/app/pages/Project/Settings/components/DeleteDataModal.tsx@@ -23,8 +23,10 @@ import Modal from '~/ui/Modal'import { Text } from '~/ui/Text'import { cn } from '~/utils/generic'+import type { V2Filter } from '~/api/v2/types'+import { v2FilterToLegacy } from '~/utils/analyticsUrl'+import FilterRowsEditor from '../../View/components/FilterRowsEditor'-import type { Filter } from '../../View/interfaces/traffic'const EMPTY_TN_MAPPING: Record<string, string> = {}@@ -277,7 +279,7 @@ const DeleteDataModal = ({ pid, isOpen, onClose }: DeleteDataModalProps) => {i18n: { language },} = useTranslation('common')- const [filters, setFilters] = useState<Filter[]>([])+ const [filters, setFilters] = useState<V2Filter[]>([])const [period, setPeriod] = useState<PeriodKey>('all')const [customRange, setCustomRange] = useState<Date[]>([])// null = follow the auto default (every type that has matching rows)@@ -319,7 +321,8 @@ const DeleteDataModal = ({ pid, isOpen, onClose }: DeleteDataModalProps) => {const handle = setTimeout(() => {fetchPreview(pid, {- filters,+ // the deletion preview endpoint is still v1 — convert at the boundary+ filters: filters.map(v2FilterToLegacy),from: range.from ?? undefined,to: range.to ?? undefined,})@@ -411,7 +414,7 @@ const DeleteDataModal = ({ pid, isOpen, onClose }: DeleteDataModalProps) => {const formData = new FormData()formData.set('intent', 'delete-data')- formData.set('filters', JSON.stringify(filters))+ formData.set('filters', JSON.stringify(filters.map(v2FilterToLegacy)))formData.set('types', JSON.stringify([...selectedTypes]))if (range.from) formData.set('from', range.from)if (range.to) formData.set('to', range.to)diff --git a/web/app/pages/Project/View/Panels.tsx b/web/app/pages/Project/View/Panels.tsxindex 074766a74..2ea1d9489 100644--- a/web/app/pages/Project/View/Panels.tsx+++ b/web/app/pages/Project/View/Panels.tsx@@ -47,10 +47,8 @@ import { createPortal } from 'react-dom'import { Link } from '~/ui/Link'import { LinkProps, useNavigate } from 'react-router'-import { useProjectDataCustomEventsProxy } from '~/hooks/useAnalyticsProxy'import { PROJECT_TABS } from '~/lib/constants'import { Entry } from '~/lib/models/Entry'-import { useCurrentProject } from '~/providers/CurrentProjectProvider'import Button from '~/ui/Button'import Dropdown from '~/ui/Dropdown'import Input from '~/ui/Input'@@ -69,18 +67,27 @@ import { nFormatter, getLocaleDisplayName } from '~/utils/generic'import countries from '~/utils/isoCountries'import { MainChart } from './components/MainChart'-import { Customs, Filter } from './interfaces/traffic'+import { V2Filter } from '~/api/v2/types'+import { Customs } from './interfaces/traffic'+import { RefetchIndicator } from './v2/loading'import { useViewProjectContext } from './ViewProject'+import { useCustomEventsTimeseriesQuery } from '~/hooks/v2/useV2Queries'import {- getFormatDate,getSettingsCustomEventsStacked,typeNameMapping,} from './ViewProject.helpers'+import { pivotCustomEventsTimeseries } from './v2/adapters'const ENTRIES_PER_PANEL = 8const ENTRIES_PER_CUSTOM_EVENTS_PANEL = 7const CUSTOM_EVENTS_TOP_LIMITS = [1, 3, 5, 10] as const-const UTM_TRACKING_PANEL_IDS = new Set(['so', 'me', 'ca', 'te', 'co'])+const UTM_TRACKING_PANEL_IDS = new Set([+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'utm_term',+ 'utm_content',+])const PANEL_HEADER_ACTIONS_CLASS ='panel-header-actions flex min-w-0 max-w-full items-center gap-2.5 overflow-x-auto overflow-y-hidden pb-0.5 scrollbar-thin'const PANEL_EMPTY_STATE_DOCS = {@@ -214,6 +221,8 @@ interface PanelContainerProps {activeTabId?: stringonDetailsClick?: () => voiddropdownPlaceholder?: string+ /** Background refetch in progress — show a subtle top bar, keep stale data */+ isRefetching?: boolean}const PanelContainer = ({@@ -229,6 +238,7 @@ const PanelContainer = ({activeTabId,onDetailsClick,dropdownPlaceholder,+ isRefetching,}: PanelContainerProps) => {const { t } = useTranslation('common')const underlineId = useId()@@ -236,7 +246,7 @@ const PanelContainer = ({return (<divclassName={cx(- 'isolate overflow-hidden rounded-lg border border-gray-200 bg-white px-4 pb-3 dark:border-slate-800/60 dark:bg-slate-900/25',+ 'relative isolate overflow-hidden rounded-lg border border-gray-200 bg-white px-4 pb-3 dark:border-slate-800/60 dark:bg-slate-900/25',hideHeader ? 'pt-3' : 'pt-5',{'col-span-full sm:col-span-2':@@ -244,6 +254,7 @@ const PanelContainer = ({},)}>+ {isRefetching ? <RefetchIndicator /> : null}{!hideHeader ? (<div className='mb-2 flex items-center justify-between gap-4'><Text@@ -334,10 +345,11 @@ const PanelContainer = ({</div>) : null}<div- className={+ className={cx(contentClassName ??- 'relative flex h-[19.6rem] flex-col overflow-hidden'- }+ 'relative flex h-[19.6rem] flex-col overflow-hidden',+ isRefetching && 'opacity-75 transition-opacity duration-200',+ )}>{children}</div>@@ -362,7 +374,7 @@ const PanelContainer = ({interface CustomEventsProps {customs?: CustomschartData: any- filters: Filter[]+ filters: V2Filter[]getCustomEventMetadata: (event: string) => Promise<any>getFilterLink: (column: string, value: string | null) => LinkProps['to']}@@ -612,10 +624,7 @@ const CustomEvents = ({getFilterLink,}: CustomEventsProps) => {const { t } = useTranslation('common')- const { id } = useCurrentProject()- const { timeBucket, timezone, period, dateRange, timeFormat, rotateXAxis } =- useViewProjectContext()- const { fetchCustomEvents } = useProjectDataCustomEventsProxy()+ const { timeBucket, timeFormat, rotateXAxis } = useViewProjectContext()const [detailsOpened, setDetailsOpened] = useState(false)const [activeEvents, setActiveEvents] = useState<any>({})@@ -624,11 +633,6 @@ const CustomEvents = ({const [eventsData, setEventsData] = useState<any>(customs)const [triggerEventWhenFiltersChange, setTriggerEventWhenFiltersChange] =useState<string | null>(null)- const [stackedChartLoading, setStackedChartLoading] = useState(false)- const [stackedChart, setStackedChart] = useState<{- x: string[]- events: Record<string, Array<number | string>>- } | null>(null)const [chartTopLimit, setChartTopLimit] =useState<(typeof CUSTOM_EVENTS_TOP_LIMITS)[number]>(5)@@ -677,68 +681,18 @@ const CustomEvents = ({})}, [customs])- useEffect(() => {- let cancelled = false-- const loadStackedChart = async () => {- if (!id || _isEmpty(topEventsForChart)) {- setStackedChart(null)- return- }-- setStackedChartLoading(true)-- try {- const isCustomPeriod = period === 'custom' && dateRange- const from = isCustomPeriod ? getFormatDate(dateRange![0]) : ''- const to = isCustomPeriod ? getFormatDate(dateRange![1]) : ''- const periodValue = isCustomPeriod ? '' : period-- const data = await fetchCustomEvents(id, topEventsForChart, {- timeBucket,- period: periodValue,- filters,- from,- to,- timezone,- })-- if (cancelled) {- return- }-- setStackedChart((data?.chart as unknown as typeof stackedChart) || null)- } catch (reason) {- console.error(- '[ERROR](CustomEvents) Failed to load stacked custom events chart',- reason,- )- if (!cancelled) {- setStackedChart(null)- }- } finally {- if (!cancelled) {- setStackedChartLoading(false)- }- }+ const stackedChartQuery = useCustomEventsTimeseriesQuery(topEventsForChart)+ const stackedChartLoading = stackedChartQuery.isLoading+ const stackedChart = useMemo(() => {+ if (_isEmpty(topEventsForChart) || !stackedChartQuery.data) {+ return null}- loadStackedChart()-- return () => {- cancelled = true- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [- id,- timeBucket,- period,- dateRange,- timezone,- filters,- topEventsForChart,- fetchCustomEvents,- ])+ return pivotCustomEventsTimeseries(+ stackedChartQuery.data.data,+ topEventsForChart,+ )+ }, [stackedChartQuery.data, topEventsForChart])useEffect(() => {setEventsMetadata({})@@ -846,7 +800,7 @@ const CustomEvents = ({}const _getFilterLink = (column: string | null, value: string | null) => {- return getFilterLink('ev' + (column ? `:key:${column}` : ''), value)+ return getFilterLink(column ? `event_metadata:${column}` : 'event', value)}const CustomEventsTable = () => (@@ -1152,10 +1106,10 @@ interface MetadataKeyPanelProps {) => Promise<{ result: Array<{ key: string; value: string; count: number }> }>getFilterLink: (column: string, value: string | null) => LinkProps['to']chartData: any- filters: Filter[]+ filters: V2Filter[]activeKey: stringonKeyChange: (key: string) => void- filterPrefix: 'ev:key' | 'tag:key'+ filterPrefix: 'event_metadata' | 'page_property'// For 'property' mode: dropdown shows property keys, values are for that key// For 'customEvent' mode: dropdown shows event names, values show ALL metadata for that event (grouped by key)mode: 'property' | 'customEvent'@@ -1654,7 +1608,7 @@ interface CombinedMetadataPanelProps {}getFilterLink: (column: string, value: string | null) => LinkProps['to']chartData: any- filters: Filter[]+ filters: V2Filter[]}const CombinedMetadataPanel = ({@@ -1686,8 +1640,8 @@ const CombinedMetadataPanel = ({}, [activeMode, hasProperty, hasCustomEvent])const activeSection = activeMode === 'property' ? property : customEvent- const activeFilterPrefix: 'ev:key' | 'tag:key' =- activeMode === 'property' ? 'tag:key' : 'ev:key'+ const activeFilterPrefix: 'event_metadata' | 'page_property' =+ activeMode === 'property' ? 'page_property' : 'event_metadata'const dropdownItems = useMemo(() => activeSection.metadataKeys.map((key) => ({ id: key, label: key })),@@ -1872,6 +1826,13 @@ interface PanelProps {rowTooltipRenderer?: (entry: Entry) => React.ReactNode/** When true with rowTooltipRenderer, tooltip is fixed to the cursor (chart-style) instead of Radix anchor positioning. */rowTooltipFollowCursor?: boolean+ /** Background refetch in progress — subtle top bar, stale data stays visible */+ isRefetching?: boolean+ /** Total number of dimension values on the server (may exceed loaded rows) */+ serverTotal?: number+ /** Loads the next page of entries into the details table */+ onLoadMore?: () => void+ loadingMore?: boolean}interface DetailsTableProps extends Pick<@@ -1886,6 +1847,9 @@ interface DetailsTableProps extends Pick<| 'valueMapper'| 'getFilterLink'| 'activeTab'+ | 'serverTotal'+ | 'onLoadMore'+ | 'loadingMore'> {total: numbercloseDetails: () => void@@ -1915,6 +1879,9 @@ const DetailsTable = ({hidePercentageInDetails,detailsExtraColumns,activeTab = PROJECT_TABS.traffic,+ serverTotal,+ onLoadMore,+ loadingMore,}: DetailsTableProps) => {const {t,@@ -1932,7 +1899,7 @@ const DetailsTable = ({const getNameLabel = useCallback((entry: Entry): string => {- if (activeTabId === 'cc') {+ if (activeTabId === 'country') {const code = entry.cc || entry.nametry {const countryName = code ? countries.getName(code, language) : ''@@ -1942,7 +1909,7 @@ const DetailsTable = ({}}- if (activeTabId === 'lc') {+ if (activeTabId === 'locale') {try {return (getLocaleDisplayName(entry?.name, language) || entry?.name || ''@@ -2240,6 +2207,26 @@ const DetailsTable = ({</div></div></div>+ {onLoadMore ? (+ <div className='mt-2 flex items-center justify-center gap-3'>+ <Button+ variant='secondary'+ size='sm'+ type='button'+ onClick={onLoadMore}+ disabled={loadingMore}+ className='gap-1.5'+ >+ {loadingMore ? <Spin className='m-0!' /> : null}+ {t('project.loadMore')}+ </Button>+ {serverTotal ? (+ <Text size='sm' colour='muted'>+ {data.length} / {nFormatter(serverTotal, 1)}+ </Text>+ ) : null}+ </div>+ ) : null}</div>)}@@ -2272,6 +2259,10 @@ const Panel = ({selectedRow,rowTooltipRenderer,rowTooltipFollowCursor = false,+ isRefetching,+ serverTotal,+ onLoadMore,+ loadingMore,}: PanelProps) => {const ctx = useViewProjectContext()const dataLoading = dataLoadingProp ?? ctx.dataLoading@@ -2332,6 +2323,7 @@ const Panel = ({tabs={tabs}onTabChange={onTabChange}activeTabId={activeTabId}+ isRefetching={isRefetching}>{customRenderer ? (customRenderer()@@ -2722,6 +2714,9 @@ const Panel = ({hidePercentageInDetails={hidePercentageInDetails}detailsExtraColumns={detailsExtraColumns}activeTab={activeTab}+ serverTotal={serverTotal}+ onLoadMore={onLoadMore}+ loadingMore={loadingMore}/>}size='large'diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsxindex bd2dea069..4901c338d 100644--- a/web/app/pages/Project/View/ViewProject.helpers.tsx+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx@@ -2316,37 +2316,38 @@ const getSettingsPerf = (}const typeNameMapping = (t: typeof i18next.t) => ({- cc: t('project.mapping.cc'),+ country: t('project.mapping.cc'),host: t('project.mapping.host'),- rg: t('project.mapping.rg'),- ct: t('project.mapping.ct'),- pg: t('project.mapping.pg'),+ region: t('project.mapping.rg'),+ city: t('project.mapping.ct'),+ page: t('project.mapping.pg'),keywords: t('project.seo.topQueries'),- entryPage: t('project.entryPages'),- exitPage: t('project.exitPages'),- lc: t('project.mapping.lc'),- ref: t('project.mapping.ref'),- refn: t('project.mapping.ref'),- dv: t('project.mapping.dv'),- br: t('project.mapping.br'),- brv: t('project.mapping.brv'),+ entry_page: t('project.entryPages'),+ exit_page: t('project.exitPages'),+ locale: t('project.mapping.lc'),+ referrer: t('project.mapping.ref'),+ referrer_name: t('project.mapping.ref'),+ device: t('project.mapping.dv'),+ browser: t('project.mapping.br'),+ browser_version: t('project.mapping.brv'),os: t('project.mapping.os'),- osv: t('project.mapping.osv'),- so: t('project.mapping.so'),- me: t('project.mapping.me'),- ca: t('project.mapping.ca'),- te: t('project.mapping.te'),- co: t('project.mapping.co'),+ os_version: t('project.mapping.osv'),+ utm_source: t('project.mapping.so'),+ utm_medium: t('project.mapping.me'),+ utm_campaign: t('project.mapping.ca'),+ utm_term: t('project.mapping.te'),+ utm_content: t('project.mapping.co'),isp: t('project.mapping.isp'),- og: t('project.mapping.og'),- ut: t('project.mapping.ut'),- ctp: t('project.mapping.ctp'),- ev: t('project.event'),+ organization: t('project.mapping.og'),+ user_type: t('project.mapping.ut'),+ connection_type: t('project.mapping.ctp'),+ event: t('project.event'),+ event_metadata: t('project.metamapping.ev.key'),+ page_property: t('project.metamapping.tag.key'),+ error_name: t('project.mapping.error_name'),+ error_message: t('project.mapping.error_message'),+ error_filename: t('project.mapping.error_filename'),userFlow: t('project.mapping.userFlow'),- 'tag:key': t('project.metamapping.tag.key'),- 'tag:value': t('project.metamapping.tag.value'),- 'ev:key': t('project.metamapping.ev.key'),- 'ev:value': t('project.metamapping.ev.value'),searchEngine: t('project.mapping.searchEngine'),aiReferral: t('project.mapping.aiReferral'),captcha_event: t('project.event'),@@ -2355,7 +2356,6 @@ const typeNameMapping = (t: typeof i18next.t) => ({solve_time: t('project.mapping.solve_time'),// Combined panel typeslocation: t('project.location'),- browser: t('project.browser'),devices: t('project.devices'),network: t('project.network'),map: t('project.map'),@@ -2363,14 +2363,14 @@ const typeNameMapping = (t: typeof i18next.t) => ({const iconClassName = 'w-5 h-5'const panelIconMapping = {- cc: <MapPinIcon className={iconClassName} />,- pg: <FileTextIcon className={iconClassName} />,- lc: <TranslateIcon className={iconClassName} />,- ref: <ArrowCircleRightIcon className={iconClassName} />,- dv: <DevicesIcon className={iconClassName} />,- br: <CompassIcon className={iconClassName} />,+ country: <MapPinIcon className={iconClassName} />,+ page: <FileTextIcon className={iconClassName} />,+ locale: <TranslateIcon className={iconClassName} />,+ referrer: <ArrowCircleRightIcon className={iconClassName} />,+ device: <DevicesIcon className={iconClassName} />,+ browser: <CompassIcon className={iconClassName} />,os: <MonitorPlayIcon className={iconClassName} />,- so: <ShareIcon className={iconClassName} />,+ utm_source: <ShareIcon className={iconClassName} />,isp: <GlobeIcon className={iconClassName} />,}diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex 6e02f59c9..157517877 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -1,3 +1,4 @@+import { useQueryClient } from '@tanstack/react-query'import cx from 'clsx'import dayjs from 'dayjs'import { AnimatePresence, motion } from 'motion/react'@@ -94,12 +95,9 @@ import ProjectSidebar, {MobileSidebarTrigger,} from './components/ProjectSidebar'import SearchFilters from './components/SearchFilters'-import {- Filter,- ProjectView,- ProjectViewCustomEvent,-} from './interfaces/traffic'-import { parseFilters } from './utils/filters'+import { ProjectView, ProjectViewCustomEvent } from './interfaces/traffic'+import { V2Filter } from '~/api/v2/types'+import { parseFiltersFromUrl } from '~/utils/analyticsUrl'import {getProjectViewCreateType,getProjectViewFilterOptions,@@ -107,7 +105,6 @@ import {import {getFormatDate,typeNameMapping,- CHART_METRICS_MAPPING,SHORTCUTS_TABS_LISTENERS,SHORTCUTS_TABS_MAP,SHORTCUTS_GENERAL_LISTENERS,@@ -146,7 +143,7 @@ interface ViewProjectContextType {size: ReturnType<typeof useSize>[1]dataLoading: booleanactiveTab: keyof typeof PROJECT_TABS- filters: Filter[]+ filters: V2Filter[]projectViews: ProjectView[]projectViewsLoading: boolean | nullloadProjectViews: (forced?: boolean) => void@@ -171,11 +168,11 @@ interface ViewProjectContextType {onMainChartZoom: (domain: [Date, Date] | null) => voidshouldEnableZoom: boolean- getFilterLink: (column: string, value: string | null) => LinkProps['to']+ getFilterLink: (dimension: string, value: string | null) => LinkProps['to']getVersionFilterLink: (parent: string | null,version: string | null,- panelType: 'br' | 'os',+ panelType: 'browser' | 'os',) => stringupdatePeriod: (newPeriod: { period: Period; label?: string }) => void@@ -193,16 +190,9 @@ interface ViewProjectContextType {}interface RefreshTriggersContextType {- captchaRefreshTrigger: numbergoalsRefreshTrigger: numberexperimentsRefreshTrigger: numberfeatureFlagsRefreshTrigger: number- sessionsRefreshTrigger: number- errorsRefreshTrigger: number- performanceRefreshTrigger: number- trafficRefreshTrigger: number- funnelsRefreshTrigger: number- profilesRefreshTrigger: numberreplaysRefreshTrigger: numberseoRefreshTrigger: number}@@ -262,24 +252,17 @@ const defaultViewProjectContext: ViewProjectContextType = {}const defaultRefreshTriggersContext: RefreshTriggersContextType = {- captchaRefreshTrigger: 0,goalsRefreshTrigger: 0,experimentsRefreshTrigger: 0,featureFlagsRefreshTrigger: 0,- sessionsRefreshTrigger: 0,- errorsRefreshTrigger: 0,- performanceRefreshTrigger: 0,- trafficRefreshTrigger: 0,- funnelsRefreshTrigger: 0,- profilesRefreshTrigger: 0,replaysRefreshTrigger: 0,seoRefreshTrigger: 0,}-export const ViewProjectContext = createContext<ViewProjectContextType>(+const ViewProjectContext = createContext<ViewProjectContextType>(defaultViewProjectContext,)-export const RefreshTriggersContext = createContext<RefreshTriggersContextType>(+const RefreshTriggersContext = createContext<RefreshTriggersContextType>(defaultRefreshTriggersContext,)@@ -335,6 +318,7 @@ const ViewProjectContent = () => {}, [isMapFullscreen])const navigate = useNavigate()+ const queryClient = useQueryClient()const [searchParams, setSearchParams] = useSearchParams()@@ -352,32 +336,12 @@ const ViewProjectContent = () => {const [isAddAViewOpened, setIsAddAViewOpened] = useState(false)const [dataLoading] = useState(false)- const [captchaRefreshTrigger, setCaptchaRefreshTrigger] = useState(0)const [goalsRefreshTrigger, setGoalsRefreshTrigger] = useState(0)const [experimentsRefreshTrigger, setExperimentsRefreshTrigger] = useState(0)const [featureFlagsRefreshTrigger, setFeatureFlagsRefreshTrigger] =useState(0)- const [sessionsRefreshTrigger, setSessionsRefreshTrigger] = useState(0)- const [errorsRefreshTrigger, setErrorsRefreshTrigger] = useState(0)- const [performanceRefreshTrigger, setPerformanceRefreshTrigger] = useState(0)- const [trafficRefreshTrigger, setTrafficRefreshTrigger] = useState(0)- const [funnelsRefreshTrigger, setFunnelsRefreshTrigger] = useState(0)- const [profilesRefreshTrigger, setProfilesRefreshTrigger] = useState(0)const [replaysRefreshTrigger, setReplaysRefreshTrigger] = useState(0)const [seoRefreshTrigger, setSeoRefreshTrigger] = useState(0)- const [activeChartMetrics] = useState<- Record<keyof typeof CHART_METRICS_MAPPING, boolean>- >({- [CHART_METRICS_MAPPING.unique]: true,- [CHART_METRICS_MAPPING.views]: false,- [CHART_METRICS_MAPPING.sessionDuration]: false,- [CHART_METRICS_MAPPING.bounce]: false,- [CHART_METRICS_MAPPING.viewsPerUnique]: false,- [CHART_METRICS_MAPPING.trendlines]: false,- [CHART_METRICS_MAPPING.cumulativeMode]: false,- [CHART_METRICS_MAPPING.customEvents]: false,- [CHART_METRICS_MAPPING.revenue]: false,- } as Record<keyof typeof CHART_METRICS_MAPPING, boolean>)const customMetrics = useMemo<ProjectViewCustomEvent[]>(() => {const raw = searchParams.get('metrics')if (!raw) return []@@ -387,8 +351,8 @@ const ViewProjectContent = () => {return []}}, [searchParams])- const filters = useMemo<Filter[]>(() => {- return parseFilters(searchParams)+ const filters = useMemo<V2Filter[]>(() => {+ return parseFiltersFromUrl(searchParams)}, [searchParams])const tnMapping = typeNameMapping(t)@@ -535,10 +499,6 @@ const ViewProjectContent = () => {const viewsLoadFetcher = useFetcher<ProjectViewActionData>()- const mode = activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode]- ? 'cumulative'- : 'periodical'-const loadProjectViews = useCallback((forced?: boolean) => {if (!forced && projectViewsLoading !== null) {@@ -576,18 +536,16 @@ const ViewProjectContent = () => {}, [viewsLoadFetcher.state, viewsLoadFetcher.data])const getVersionFilterLink = useCallback(- (parent: string | null, version: string | null, panelType: 'br' | 'os') => {+ (+ parent: string | null,+ version: string | null,+ panelType: 'browser' | 'os',+ ) => {const filterParams = new URLSearchParams(searchParams.toString())- if (panelType === 'br') {- // Apply both browser and browser version filters together- filterParams.set('br', parent ?? 'null')- filterParams.set('brv', version ?? 'null')- } else if (panelType === 'os') {- // Apply both OS and OS version filters together- filterParams.set('os', parent ?? 'null')- filterParams.set('osv', version ?? 'null')- }+ // Apply both the parent (browser/os) and version filters together+ filterParams.set(panelType, parent ?? 'null')+ filterParams.set(`${panelType}_version`, version ?? 'null')return `?${filterParams.toString()}`},@@ -916,71 +874,60 @@ const ViewProjectContent = () => {[dataLoading, searchParams, setSearchParams],)+ // Tabs fully served by the v2 per-dimension API: refresh = invalidate queries+ const V2_TABS = useMemo(+ () =>+ new Set<keyof typeof PROJECT_TABS>([+ PROJECT_TABS.traffic,+ PROJECT_TABS.performance,+ PROJECT_TABS.sessions,+ PROJECT_TABS.errors,+ PROJECT_TABS.funnels,+ PROJECT_TABS.profiles,+ PROJECT_TABS.captcha,+ ]),+ [],+ )+const refreshStats = useCallback(async (_isManual = true) => {- if (!authLoading && !dataLoading) {- if (activeTab === PROJECT_TABS.funnels) {- setFunnelsRefreshTrigger((prev) => prev + 1)- return- }-- if (activeTab === PROJECT_TABS.profiles) {- setProfilesRefreshTrigger((prev) => prev + 1)- return- }-- if (activeTab === PROJECT_TABS.captcha) {- setCaptchaRefreshTrigger((prev) => prev + 1)- return- }-- if (activeTab === PROJECT_TABS.goals) {- setGoalsRefreshTrigger((prev) => prev + 1)- return- }-- if (activeTab === PROJECT_TABS.experiments) {- setExperimentsRefreshTrigger((prev) => prev + 1)- return- }-- if (activeTab === PROJECT_TABS.featureFlags) {- setFeatureFlagsRefreshTrigger((prev) => prev + 1)- return- }+ if (authLoading || dataLoading) {+ return+ }- if (activeTab === PROJECT_TABS.sessions) {- setSessionsRefreshTrigger((prev) => prev + 1)- return- }+ if (V2_TABS.has(activeTab)) {+ await queryClient.invalidateQueries({ queryKey: ['v2', id] })+ return+ }- if (activeTab === PROJECT_TABS.replays) {- setReplaysRefreshTrigger((prev) => prev + 1)- return- }+ if (activeTab === PROJECT_TABS.goals) {+ setGoalsRefreshTrigger((prev) => prev + 1)+ return+ }- if (activeTab === PROJECT_TABS.errors) {- setErrorsRefreshTrigger((prev) => prev + 1)- return- }+ if (activeTab === PROJECT_TABS.experiments) {+ setExperimentsRefreshTrigger((prev) => prev + 1)+ return+ }- if (activeTab === PROJECT_TABS.performance) {- setPerformanceRefreshTrigger((prev) => prev + 1)- return- }+ if (activeTab === PROJECT_TABS.featureFlags) {+ setFeatureFlagsRefreshTrigger((prev) => prev + 1)+ return+ }- if (activeTab === PROJECT_TABS.traffic) {- setTrafficRefreshTrigger((prev) => prev + 1)- return- }+ if (activeTab === PROJECT_TABS.replays) {+ setReplaysRefreshTrigger((prev) => prev + 1)+ return+ }- if (activeTab === PROJECT_TABS.seo) {- setSeoRefreshTrigger((prev) => prev + 1)- return- }+ if (activeTab === PROJECT_TABS.seo) {+ // The SEO tab mixes GSC data (trigger-driven) with v2 referral data+ await queryClient.invalidateQueries({ queryKey: ['v2', id] })+ setSeoRefreshTrigger((prev) => prev + 1)+ return}},- [authLoading, dataLoading, activeTab],+ [authLoading, dataLoading, activeTab, queryClient, id, V2_TABS],)useEffect(() => {@@ -1070,32 +1017,35 @@ const ViewProjectContent = () => {return daysDiff > 1}, [period, dateRange, isTouchDevice])+ // `dimension` is a v2 dimension name, optionally keyed (`event_metadata:plan`)const getFilterLink = useCallback(- (column: string, value: string | null): LinkProps['to'] => {- const isFilterActive =- filters.findIndex(- (filter) => filter.column === column && filter.filter === value,- ) >= 0+ (dimension: string, value: string | null): LinkProps['to'] => {+ const urlValue = value ?? 'null'+ const variants = [+ dimension,+ `!${dimension}`,+ `~${dimension}`,+ `^${dimension}`,+ ]+ const isFilterActive = variants.some((key) =>+ searchParams.getAll(key).includes(urlValue),+ )const newSearchParams = new URLSearchParams(searchParams.toString())- let searchString = ''if (isFilterActive) {- newSearchParams.delete(column, value ?? 'null')- newSearchParams.delete(`!${column}`, value ?? 'null')- newSearchParams.delete(`~${column}`, value ?? 'null')- newSearchParams.delete(`^${column}`, value ?? 'null')- searchString = newSearchParams.toString()+ for (const key of variants) {+ newSearchParams.delete(key, urlValue)+ }} else {- newSearchParams.append(column, value ?? 'null')- searchString = newSearchParams.toString()+ newSearchParams.append(dimension, urlValue)}return {- search: searchString,+ search: newSearchParams.toString(),}},- [filters, searchParams],+ [searchParams],)const setChartTypeOnClick = useCallback((type: keyof typeof chartTypes) => {@@ -1310,30 +1260,16 @@ const ViewProjectContent = () => {const refreshTriggersValue = useMemo(() => ({- captchaRefreshTrigger,goalsRefreshTrigger,experimentsRefreshTrigger,featureFlagsRefreshTrigger,- sessionsRefreshTrigger,- errorsRefreshTrigger,- performanceRefreshTrigger,- trafficRefreshTrigger,- funnelsRefreshTrigger,- profilesRefreshTrigger,replaysRefreshTrigger,seoRefreshTrigger,}),[- captchaRefreshTrigger,goalsRefreshTrigger,experimentsRefreshTrigger,featureFlagsRefreshTrigger,- sessionsRefreshTrigger,- errorsRefreshTrigger,- performanceRefreshTrigger,- trafficRefreshTrigger,- funnelsRefreshTrigger,- profilesRefreshTrigger,replaysRefreshTrigger,seoRefreshTrigger,],@@ -1604,7 +1540,6 @@ const ViewProjectContent = () => {customMetrics={customMetrics}onRemoveCustomMetric={onRemoveCustomMetric}resetCustomMetrics={resetCustomMetrics}- mode={mode}/>) : null}{activeTab === PROJECT_TABS.performance ? (diff --git a/web/app/pages/Project/View/components/AddAViewModal.tsx b/web/app/pages/Project/View/components/AddAViewModal.tsxindex b90e4d44c..a9d137ba3 100644--- a/web/app/pages/Project/View/components/AddAViewModal.tsx+++ b/web/app/pages/Project/View/components/AddAViewModal.tsx@@ -8,14 +8,15 @@ import { useTranslation } from 'react-i18next'import { useFetcher } from 'react-router'import { toast } from 'sonner'+import { V2Filter } from '~/api/v2/types'import { ProjectViewActionData } from '~/routes/projects.$id'import Input from '~/ui/Input'import Modal from '~/ui/Modal'import Select from '~/ui/Select'import { Text } from '~/ui/Text'+import { legacyFilterToV2, v2FilterToLegacy } from '~/utils/analyticsUrl'import {- Filter as FilterType,ProjectView,ProjectViewCustomEvent,ProjectViewCustomEventMetaValueType,@@ -23,6 +24,14 @@ import {import FilterRowsEditor from './FilterRowsEditor'+// Saved project views keep the legacy filter shape server-side; convert to+// the v2 shape at this boundary (unmappable legacy filters are dropped).+const projectViewFiltersToV2 = (view?: ProjectView): V2Filter[] =>+ (view?.filters || []).flatMap((filter) => {+ const converted = legacyFilterToV2(filter)+ return converted ? [converted] : []+ })+interface AddAViewModalProps {onSubmit: () => voidshowModal: boolean@@ -212,13 +221,17 @@ const AddAViewModal = ({const { t } = useTranslation('common')const fetcher = useFetcher<ProjectViewActionData>()const [name, setName] = useState(defaultView?.name || '')- const [activeFilters, setActiveFilters] = useState<FilterType[]>(- defaultView?.filters || [],+ const [activeFilters, setActiveFilters] = useState<V2Filter[]>(() =>+ projectViewFiltersToV2(defaultView),)const [customEvents, setCustomEvents] = useState<Partial<ProjectViewCustomEvent>[]>(defaultView?.customEvents || [])const [errors, setErrors] = useState<AddAViewModalErrors>({})+ const initialFilters = useMemo(+ () => projectViewFiltersToV2(defaultView),+ [defaultView],+ )useEffect(() => {if (!defaultView) {@@ -227,7 +240,7 @@ const AddAViewModal = ({if (defaultView.filters) {// eslint-disable-next-line react-hooks/set-state-in-effect -- Syncing form state with defaultView prop- setActiveFilters(defaultView.filters)+ setActiveFilters(projectViewFiltersToV2(defaultView))}if (defaultView.customEvents) {@@ -332,7 +345,10 @@ const AddAViewModal = ({const metricsToSubmit = supportsCustomMetrics? customEvents: defaultView?.customEvents || []- formData.append('filters', JSON.stringify(activeFilters))+ formData.append(+ 'filters',+ JSON.stringify(activeFilters.map(v2FilterToLegacy)),+ )formData.append('customEvents', JSON.stringify(metricsToSubmit))formData.append('name', name)@@ -389,7 +405,7 @@ const AddAViewModal = ({<FilterRowsEditoractive={showModal}tnMapping={tnMapping}- initialFilters={defaultView?.filters}+ initialFilters={initialFilters}type={filterDataType}filterOptions={filterOptions}onChange={setActiveFilters}diff --git a/web/app/pages/Project/View/components/FilterRowsEditor.tsx b/web/app/pages/Project/View/components/FilterRowsEditor.tsxindex 8169bf07f..47e584608 100644--- a/web/app/pages/Project/View/components/FilterRowsEditor.tsx+++ b/web/app/pages/Project/View/components/FilterRowsEditor.tsx@@ -18,11 +18,9 @@ import {} from 'react'import { useTranslation } from 'react-i18next'-import { useFiltersProxy } from '~/hooks/useAnalyticsProxy'-import {- FILTERS_PANELS_ORDER,- ERRORS_FILTERS_PANELS_ORDER,-} from '~/lib/constants'+import { getDimensionValues } from '~/api/v2/endpoints'+import { V2Filter, V2FilterOperator } from '~/api/v2/types'+import { KEYED_DIMENSIONS, VALID_DIMENSIONS_BY_TYPE } from '~/lib/v2Dimensions'import { useOptionalCurrentProject } from '~/providers/CurrentProjectProvider'import { useTheme } from '~/providers/ThemeProvider'import FilterValueInput, {@@ -31,28 +29,26 @@ import FilterValueInput, {parseVersionValue,} from '~/ui/FilterValueInput'import { Text } from '~/ui/Text'+import { filterToUrlValue } from '~/utils/analyticsUrl'import countries from '~/utils/isoCountries'-import { Filter as FilterType } from '../interfaces/traffic'import { cn } from '~/utils/generic'-type FilterOperator = 'is' | 'isNot' | 'contains' | 'notContains'-interface FilterRow {id: stringcolumn: string- operator: FilterOperator+ operator: V2FilterOperatorvalue: string}interface FilterRowsEditorProps {active: booleantnMapping: Record<string, string>- initialFilters?: FilterType[]- currentFilters?: FilterType[]+ initialFilters?: V2Filter[]+ currentFilters?: V2Filter[]type: 'traffic' | 'errors'filterOptions?: string[]- onChange: (filters: FilterType[]) => void+ onChange: (filters: V2Filter[]) => voidresetKey?: stringprefetchOnOpen?: booleanshowCurrentFilters?: boolean@@ -61,27 +57,42 @@ interface FilterRowsEditorProps {projectId?: string}-const EMPTY_FILTERS: FilterType[] = []+const EMPTY_FILTERS: V2Filter[] = []-const OPERATORS: { value: FilterOperator; labelKey: string }[] = [+const OPERATORS: { value: V2FilterOperator; labelKey: string }[] = [{ value: 'is', labelKey: 'common.is' },- { value: 'isNot', labelKey: 'common.isNot' },+ { value: 'is_not', labelKey: 'common.isNot' },{ value: 'contains', labelKey: 'project.contains.is' },- { value: 'notContains', labelKey: 'project.contains.not' },+ { value: 'contains_not', labelKey: 'project.contains.not' },]-const getMetadataColumnBase = (column: string) => {- if (column === 'ev:key' || column.startsWith('ev:key:')) return 'ev:key'- if (column === 'tag:key' || column.startsWith('tag:key:')) return 'tag:key'- if (column === 'ev:value') return 'ev:value'- if (column === 'tag:value') return 'tag:value'- return column+// A row's `column` is a v2 dimension name, optionally with a metadata key+// (`event_metadata:plan`). A bare keyed dimension (`event_metadata`) means+// "has this metadata key" — its value is the key itself.+const parseRowColumn = (+ column: string,+): { dimension: string; key?: string } => {+ for (const dimension of KEYED_DIMENSIONS) {+ if (column.startsWith(`${dimension}:`)) {+ return { dimension, key: column.substring(dimension.length + 1) }+ }+ }++ return { dimension: column }}+const getMetadataColumnBase = (column: string) =>+ parseRowColumn(column).dimension++const isKeyedColumn = (column: string) =>+ (KEYED_DIMENSIONS as readonly string[]).includes(+ getMetadataColumnBase(column),+ )+const getOperatorsForColumn = (column: string) => {- if (column.startsWith('ev:key') || column.startsWith('tag:key')) {+ if (isKeyedColumn(column)) {return OPERATORS.filter(- (operator) => operator.value === 'is' || operator.value === 'isNot',+ (operator) => operator.value === 'is' || operator.value === 'is_not',)}@@ -90,8 +101,8 @@ const getOperatorsForColumn = (column: string) => {const normalizeFilterOperator = (column: string,- operator: FilterOperator,-): FilterOperator => {+ operator: V2FilterOperator,+): V2FilterOperator => {const operatorOptions = getOperatorsForColumn(column)return operatorOptions.some((option) => option.value === operator)@@ -112,32 +123,10 @@ const createFilterRow = ({const createEmptyFilterRow = (): FilterRow => createFilterRow()-const operatorToFilter = (- operator: FilterOperator,-): { isExclusive: boolean; isContains: boolean } => {- switch (operator) {- case 'is':- return { isExclusive: false, isContains: false }- case 'isNot':- return { isExclusive: true, isContains: false }- case 'contains':- return { isExclusive: false, isContains: true }- case 'notContains':- return { isExclusive: true, isContains: true }- }-}+const filterToRowColumn = (filter: V2Filter): string =>+ filter.key ? `${filter.dimension}:${filter.key}` : filter.dimension-const filterToOperator = ({- isExclusive,- isContains,-}: FilterType): FilterOperator => {- if (isContains && isExclusive) return 'notContains'- if (isContains) return 'contains'- if (isExclusive) return 'isNot'- return 'is'-}--const filtersToRows = (filters: FilterType[] = []): FilterRow[] => {+const filtersToRows = (filters: V2Filter[] = []): FilterRow[] => {const usedIndexes = new Set<number>()return filters.flatMap((filter, index) => {@@ -145,15 +134,15 @@ const filtersToRows = (filters: FilterType[] = []): FilterRow[] => {return []}- if (filter.column === 'br' || filter.column === 'os') {- const versionColumn = filter.column === 'br' ? 'brv' : 'osv'- const operator = filterToOperator(filter)+ if (filter.dimension === 'browser' || filter.dimension === 'os') {+ const versionDimension =+ filter.dimension === 'browser' ? 'browser_version' : 'os_version'const versionIndex = filters.findIndex((candidate, candidateIndex) =>candidateIndex !== index &&!usedIndexes.has(candidateIndex) &&- candidate.column === versionColumn &&- filterToOperator(candidate) === operator,+ candidate.dimension === versionDimension &&+ candidate.operator === filter.operator,)if (versionIndex !== -1) {@@ -162,11 +151,11 @@ const filtersToRows = (filters: FilterType[] = []): FilterRow[] => {return [createFilterRow({- column: versionColumn,- operator,+ column: versionDimension,+ operator: filter.operator,value: createVersionValue(- filter.filter,- filters[versionIndex].filter,+ filterToUrlValue(filter),+ filterToUrlValue(filters[versionIndex]),),}),]@@ -177,9 +166,9 @@ const filtersToRows = (filters: FilterType[] = []): FilterRow[] => {return [createFilterRow({- column: filter.column,- operator: filterToOperator(filter),- value: filter.filter,+ column: filterToRowColumn(filter),+ operator: filter.operator,+ value: filterToUrlValue(filter),}),]})@@ -206,79 +195,55 @@ const InlineButton = ({</button>)-const filterRowsToFilters = (filterRows: FilterRow[], language: string) => {- const validFilters: FilterType[] = []+const filterRowsToFilters = (+ filterRows: FilterRow[],+ language: string,+): V2Filter[] => {+ const validFilters: V2Filter[] = []filterRows.filter((row) => row.column && row.value).forEach((row) => {- const { isExclusive, isContains } = operatorToFilter(row.operator)-- if (row.column === 'brv') {- const parsed = parseVersionValue(row.value)- if (parsed) {- validFilters.push({- column: 'br',- filter: parsed.parent,- isExclusive,- isContains,- })- validFilters.push({- column: 'brv',- filter: parsed.version,- isExclusive,- isContains,- })- } else {- validFilters.push({- column: 'brv',- filter: row.value,- isExclusive,- isContains,- })- }- return- }-- if (row.column === 'osv') {+ if (row.column === 'browser_version' || row.column === 'os_version') {+ const parentDimension =+ row.column === 'browser_version' ? 'browser' : 'os'const parsed = parseVersionValue(row.value)if (parsed) {validFilters.push({- column: 'os',- filter: parsed.parent,- isExclusive,- isContains,+ dimension: parentDimension,+ operator: row.operator,+ value: parsed.parent,})validFilters.push({- column: 'osv',- filter: parsed.version,- isExclusive,- isContains,+ dimension: row.column,+ operator: row.operator,+ value: parsed.version,})} else {validFilters.push({- column: 'osv',- filter: row.value,- isExclusive,- isContains,+ dimension: row.column,+ operator: row.operator,+ value: row.value,})}return}let processedValue = row.value- if (row.column === 'cc') {+ if (row.column === 'country') {const alpha2 = countries.getAlpha2Code(row.value, language)if (alpha2) {processedValue = alpha2}}+ const { dimension, key } = parseRowColumn(row.column)+validFilters.push({- column: row.column,- filter: processedValue,- isExclusive,- isContains,+ dimension,+ operator: row.operator,+ value: processedValue === 'null' ? null : processedValue,+ ...(key ? { key } : {}),})})@@ -311,14 +276,17 @@ const FilterRowsEditor = ({>({})const [loadingColumns, setLoadingColumns] = useState<Set<string>>(new Set())const inFlightRef = useRef<Set<string>>(new Set())- const { fetchFilters, fetchErrorsFilters, fetchVersionFilters } =- useFiltersProxy()- const panelOptions = filterOptions?.length- ? filterOptions- : type === 'traffic'- ? FILTERS_PANELS_ORDER- : ERRORS_FILTERS_PANELS_ORDER+ const panelOptions = useMemo(+ () =>+ filterOptions?.length+ ? filterOptions+ : VALID_DIMENSIONS_BY_TYPE[type].filter(+ (dimension) =>+ !(KEYED_DIMENSIONS as readonly string[]).includes(dimension),+ ),+ [filterOptions, type],+ )const filters = useMemo(() => filterRowsToFilters(filterRows, language),@@ -327,16 +295,15 @@ const FilterRowsEditor = ({const getColumnLabel = useCallback((column: string) => {- if (column.startsWith('ev:key:')) {- return t('project.metamapping.ev.dynamicKey', {- key: column.replace(/^ev:key:/, ''),- })- }-- if (column.startsWith('tag:key:')) {- return t('project.metamapping.tag.dynamicKey', {- key: column.replace(/^tag:key:/, ''),- })+ const { dimension, key } = parseRowColumn(column)++ if (key) {+ return t(+ `project.metamapping.${dimension === 'page_property' ? 'tag' : 'ev'}.dynamicKey`,+ {+ key,+ },+ )}return tnMapping[column] || t(`project.mapping.${column}`)@@ -359,11 +326,11 @@ const FilterRowsEditor = ({const fetchFilterValues = useCallback(async (column: string) => {- if (- (getMetadataColumnBase(column) !== column || column.includes(':')) &&- !column.startsWith('ev:') &&- !column.startsWith('tag:')- ) {+ const { dimension, key } = parseRowColumn(column)++ // No autocomplete for keyed columns with a fixed key+ // (event_metadata:plan) or dimensions the API doesn't know about.+ if (key || !VALID_DIMENSIONS_BY_TYPE[type].includes(dimension)) {setFilterValuesCache((prev) =>prev[column] ? prev : { ...prev, [column]: [] },)@@ -381,25 +348,12 @@ const FilterRowsEditor = ({inFlightRef.current.add(column)setLoadingColumns((prev) => new Set(prev).add(column))try {- let result: string[] = []-- if (column === 'brv') {- const dataType = type === 'errors' ? 'errors' : 'traffic'- const pairs = await fetchVersionFilters(id, dataType, 'br')- if (pairs) {- result = pairs.map((p) => createVersionValue(p.name, p.version))- }- } else if (column === 'osv') {- const dataType = type === 'errors' ? 'errors' : 'traffic'- const pairs = await fetchVersionFilters(id, dataType, 'os')- if (pairs) {- result = pairs.map((p) => createVersionValue(p.name, p.version))- }- } else if (type === 'errors') {- result = (await fetchErrorsFilters(id, column)) || []- } else {- result = (await fetchFilters(id, column)) || []- }+ const { data } = await getDimensionValues(id, dimension, { type })+ const result = (data || []).map((item) =>+ typeof item === 'string'+ ? item+ : createVersionValue(item.name, item.version),+ )setFilterValuesCache((prev) => ({ ...prev, [column]: result }))} catch (error) {console.error('Failed to fetch filter values:', error)@@ -413,15 +367,7 @@ const FilterRowsEditor = ({})}},- [- id,- type,- filterValuesCache,- loadingColumns,- fetchFilters,- fetchErrorsFilters,- fetchVersionFilters,- ],+ [id, type, filterValuesCache, loadingColumns],)useEffect(() => {@@ -711,47 +657,47 @@ const FilterRowsEditor = ({{t('project.currentFilters')}</Text><div className='flex flex-wrap gap-2'>- {currentFilters.map(- ({ column, filter, isExclusive, isContains }) => {- let displayFilter = filter- if (column === 'cc') {- displayFilter = countries.getName(filter, language) || filter- }- const operatorLabel = isContains- ? isExclusive+ {currentFilters.map((filter) => {+ const { dimension, operator } = filter+ const value = filterToUrlValue(filter)++ let displayFilter = value+ if (dimension === 'country') {+ displayFilter = countries.getName(value, language) || value+ }+ const operatorLabel =+ operator === 'contains'+ ? t('project.contains.is')+ : operator === 'contains_not'? t('project.contains.not')- : t('project.contains.is')- : isExclusive- ? t('common.isNot')- : t('common.is')-- return (+ : operator === 'is_not'+ ? t('common.isNot')+ : t('common.is')++ return (+ <span+ key={`${filterToRowColumn(filter)}-${value}-${operator}`}+ className='inline-flex items-center gap-1 rounded-full bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700 dark:bg-slate-700 dark:text-gray-300'+ >+ <span className='text-gray-500 dark:text-gray-400'>+ {getColumnLabel(filterToRowColumn(filter))}+ </span><span- key={`${column}-${filter}-${isExclusive}-${isContains}`}- className='inline-flex items-center gap-1 rounded-full bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700 dark:bg-slate-700 dark:text-gray-300'+ className={cx({+ 'text-green-600 dark:text-green-400': operator === 'is',+ 'text-red-600 dark:text-red-400': operator === 'is_not',+ 'text-yellow-600 dark:text-yellow-400':+ operator === 'contains',+ 'text-orange-600 dark:text-orange-400':+ operator === 'contains_not',+ })}>- <span className='text-gray-500 dark:text-gray-400'>- {getColumnLabel(column)}- </span>- <span- className={cx({- 'text-green-600 dark:text-green-400':- !isExclusive && !isContains,- 'text-red-600 dark:text-red-400':- isExclusive && !isContains,- 'text-yellow-600 dark:text-yellow-400':- !isExclusive && isContains,- 'text-orange-600 dark:text-orange-400':- isExclusive && isContains,- })}- >- {operatorLabel}- </span>- <span className='font-semibold'>{displayFilter}</span>+ {operatorLabel}</span>- )- },- )}+ <span className='font-semibold'>{displayFilter}</span>+ </span>+ )+ })}</div></div>) : null}diff --git a/web/app/pages/Project/View/components/Filters.tsx b/web/app/pages/Project/View/components/Filters.tsxindex 4c8542f4d..7f7ad26f4 100644--- a/web/app/pages/Project/View/components/Filters.tsx+++ b/web/app/pages/Project/View/components/Filters.tsx@@ -1,7 +1,5 @@import _isEmpty from 'lodash/isEmpty'import _map from 'lodash/map'-import _replace from 'lodash/replace'-import _startsWith from 'lodash/startsWith'import _truncate from 'lodash/truncate'import { FunnelIcon, XIcon } from '@phosphor-icons/react'import { AnimatePresence, motion } from 'motion/react'@@ -10,35 +8,91 @@ import { useTranslation } from 'react-i18next'import { Link } from '~/ui/Link'import { useSearchParams } from 'react-router'+import { V2Filter, V2FilterOperator } from '~/api/v2/types'+import {+ filterToUrlKey,+ filterToUrlValue,+ isFilterUrlKey,+ parseFilterKey,+} from '~/utils/analyticsUrl'import { getLocaleDisplayName, cn } from '~/utils/generic'import countries from '~/utils/isoCountries'-import { isFilterValid } from '../utils/filters'import { splitProjectViewFiltersByTab } from '../utils/projectViewSegments'import { useViewProjectContext } from '../ViewProject'+const OPERATOR_CYCLE: Record<V2FilterOperator, V2FilterOperator> = {+ is: 'is_not',+ is_not: 'contains',+ contains: 'contains_not',+ contains_not: 'is',+}++const TOGGLE_TITLE_KEY: Record<V2FilterOperator, string> = {+ is: 'toggleFilterToIsNot',+ is_not: 'toggleFilterToContains',+ contains: 'toggleFilterToNotContains',+ contains_not: 'toggleFilterToIs',+}++const operatorLabel = (+ t: (key: string) => string,+ operator: V2FilterOperator,+) => {+ if (operator === 'contains') {+ return t('project.contains.is')+ }++ if (operator === 'contains_not') {+ return t('project.contains.not')+ }++ return t(`common.${operator === 'is_not' ? 'isNot' : 'is'}`)+}++/**+ * Returns true if a URL search param entry represents the given filter. Legacy+ * v1 keys (cc, pg, ...) parse to the same shape, so old shared links can be+ * removed / toggled too.+ */+const isFilterUrlEntry = (+ filter: V2Filter,+ rawKey: string,+ rawValue: string,+) => {+ const parsed = parseFilterKey(rawKey)++ if (+ !parsed ||+ parsed.dimension !== filter.dimension ||+ parsed.key !== filter.key ||+ parsed.operator !== filter.operator+ ) {+ return false+ }++ const normalisedValue =+ rawValue === '' || rawValue === 'null' ? null : rawValue++ return normalisedValue === (filter.value ?? null)+}+interface FilterProps {- column: string- filter: string- isExclusive: boolean+ filter: V2FiltertnMapping: Record<string, string>canChangeExclusive?: booleanremovable?: booleanonChangeExclusive?: (e: MouseEvent) => voidonRemoveFilter?: (e: MouseEvent) => void- isContains?: boolean}const Filter = ({- column,filter,- isExclusive,tnMapping,canChangeExclusive,removable,onChangeExclusive,onRemoveFilter,- isContains,}: FilterProps) => {const { dataLoading } = useViewProjectContext()const [searchParams] = useSearchParams()@@ -47,109 +101,91 @@ const Filter = ({i18n: { language },} = useTranslation('common')- let displayColumn = tnMapping[column]- let displayFilter = filter+ const { dimension, operator, key } = filter+ const value = Array.isArray(filter.value)+ ? filter.value.map((item) => item ?? 'null').join(', ')+ : filter.value++ let displayColumn = tnMapping[dimension] || dimension+ let displayFilter: string = value ?? 'null'- if (column === 'cc') {- displayFilter = countries.getName(filter, language) as string+ if (dimension === 'country' && value) {+ displayFilter = countries.getName(value, language) || value}- if (column === 'pg') {- displayFilter = filter || t('common.notSet')+ if (dimension === 'page') {+ displayFilter = value || t('common.notSet')}- if (column === 'lc') {- displayFilter = getLocaleDisplayName(displayFilter, language)+ if (dimension === 'locale' && value) {+ displayFilter = getLocaleDisplayName(value, language)}// Normalise "null" filter values to human-friendly labels- if (- (displayFilter as unknown as string)?.toString().toLowerCase() === 'null'- ) {- if (column === 'ref') {+ if (value === null || value.toLowerCase() === 'null') {+ if (dimension === 'referrer') {displayFilter = t('project.directNone')- } else if (column === 'host') {+ } else if (dimension === 'host') {displayFilter = t('project.unknownHost')} else {displayFilter = t('common.notSet')}}- if (_startsWith(column, 'ev:key:')) {- const key = _replace(column, /^ev:key:/, '')- displayColumn = t('project.metamapping.ev.dynamicKey', {- key,- })- }-- if (_startsWith(column, 'tag:key:')) {- const key = _replace(column, /^tag:key:/, '')- displayColumn = t('project.metamapping.tag.dynamicKey', {- key,- })+ if (key) {+ displayColumn = t(+ `project.metamapping.${dimension === 'page_property' ? 'tag' : 'ev'}.dynamicKey`,+ {+ key,+ },+ )}const truncatedFilter = _truncate(displayFilter)const createRemoveFilterPath = () => {- const newSearchParams = new URLSearchParams(searchParams.toString())- const paramKeyInUrl = isContains- ? isExclusive- ? `^${column}`- : `~${column}`- : isExclusive- ? `!${column}`- : column- newSearchParams.delete(paramKeyInUrl, filter)+ const newSearchParams = new URLSearchParams()++ for (const [rawKey, rawValue] of searchParams.entries()) {+ if (isFilterUrlEntry(filter, rawKey, rawValue)) {+ continue+ }++ newSearchParams.append(rawKey, rawValue)+ }+return { search: newSearchParams.toString() }}const createToggleExclusivePath = () => {- const newSearchParams = new URLSearchParams(searchParams.toString())+ const newSearchParams = new URLSearchParams()- const getKey = (contains: boolean, exclusive: boolean) =>- contains- ? exclusive- ? `^${column}`- : `~${column}`- : exclusive- ? `!${column}`- : column-- const c = Boolean(isContains)- const e = Boolean(isExclusive)-- const oldParamKey = getKey(c, e)-- let nextContains = c- let nextExclusive = e-- if (!c && !e) {- // is -> is not- nextContains = false- nextExclusive = true- } else if (!c && e) {- // is not -> contains- nextContains = true- nextExclusive = false- } else if (c && !e) {- // contains -> not contains- nextContains = true- nextExclusive = true- } else {- // not contains -> is- nextContains = false- nextExclusive = false+ for (const [rawKey, rawValue] of searchParams.entries()) {+ if (isFilterUrlEntry(filter, rawKey, rawValue)) {+ continue+ }++ newSearchParams.append(rawKey, rawValue)}- const newParamKey = getKey(nextContains, nextExclusive)+ const nextFilter: V2Filter = {+ ...filter,+ operator: OPERATOR_CYCLE[operator],+ }- newSearchParams.delete(oldParamKey, filter)- newSearchParams.append(newParamKey, filter)+ newSearchParams.append(+ filterToUrlKey(nextFilter),+ filterToUrlValue(nextFilter),+ )return { search: newSearchParams.toString() }}+ const toggleLabel = t(`project.${TOGGLE_TITLE_KEY[operator]}`, {+ column: displayColumn,+ filter: truncatedFilter,+ })+return (<spantitle={truncatedFilter === displayFilter ? undefined : displayFilter}@@ -167,10 +203,10 @@ const Filter = ({to={createToggleExclusivePath()}className={cn('cursor-pointer hover:underline', {'cursor-wait': dataLoading,- 'text-green-600 dark:text-green-400': !isExclusive && !isContains,- 'text-red-600 dark:text-red-400': isExclusive && !isContains,- 'text-yellow-600 dark:text-yellow-400': !isExclusive && isContains,- 'text-orange-600 dark:text-orange-400': isExclusive && isContains,+ 'text-green-600 dark:text-green-400': operator === 'is',+ 'text-red-600 dark:text-red-400': operator === 'is_not',+ 'text-yellow-600 dark:text-yellow-400': operator === 'contains',+ 'text-orange-600 dark:text-orange-400': operator === 'contains_not',})}onClick={(e: MouseEvent) => {if (dataLoading) {@@ -179,49 +215,13 @@ const Filter = ({}onChangeExclusive?.(e)}}- title={(() => {- const c = Boolean(isContains)- const e = Boolean(isExclusive)- const nextKey =- !c && !e- ? 'toggleFilterToIsNot'- : !c && e- ? 'toggleFilterToContains'- : c && !e- ? 'toggleFilterToNotContains'- : 'toggleFilterToIs'- return t(`project.${nextKey}`, {- column: displayColumn,- filter: truncatedFilter,- })- })()}- aria-label={(() => {- const c = Boolean(isContains)- const e = Boolean(isExclusive)- const nextKey =- !c && !e- ? 'toggleFilterToIsNot'- : !c && e- ? 'toggleFilterToContains'- : c && !e- ? 'toggleFilterToNotContains'- : 'toggleFilterToIs'- return t(`project.${nextKey}`, {- column: displayColumn,- filter: truncatedFilter,- })- })()}+ title={toggleLabel}+ aria-label={toggleLabel}>- {isContains- ? t(`project.contains.${isExclusive ? 'not' : 'is'}`)- : t(`common.${isExclusive ? 'isNot' : 'is'}`)}+ {operatorLabel(t, operator)}</Link>) : (- <span>- {isContains- ? t(`project.contains.${isExclusive ? 'not' : 'is'}`)- : t(`common.${isExclusive ? 'isNot' : 'is'}`)}- </span>+ <span>{operatorLabel(t, operator)}</span>)} <span className='font-semibold text-gray-800 dark:text-gray-50'>@@ -269,6 +269,9 @@ interface FiltersProps {className?: string}+const getFilterKey = (filter: V2Filter) =>+ `${filterToUrlKey(filter)}-${filterToUrlValue(filter)}`+const Filters = ({ tnMapping, className }: FiltersProps) => {const { activeTab, dataLoading, filters } = useViewProjectContext()const { t } = useTranslation('common')@@ -284,12 +287,7 @@ const Filters = ({ tnMapping, className }: FiltersProps) => {const entries = Array.from(searchParams.entries())for (const [key] of entries) {- let processedKey = key- if (key.startsWith('!') || key.startsWith('~') || key.startsWith('^')) {- processedKey = key.substring(1)- }-- if (!isFilterValid(processedKey, true)) {+ if (!isFilterUrlKey(key)) {continue}@@ -314,47 +312,37 @@ const Filters = ({ tnMapping, className }: FiltersProps) => {<FunnelIcon className='size-5 shrink-0 text-gray-500 dark:text-gray-400' /><div className='flex flex-wrap'><AnimatePresence mode='popLayout' initial={false}>- {_map(supported, (props) => {- const { column, filter, isExclusive, isContains } = props- const key = `${column}-${filter}-${isExclusive}-${isContains}`-- return (- <motion.span- key={key}- layout- initial={{ opacity: 0, scale: 0.92 }}- animate={{ opacity: 1, scale: 1 }}- exit={{ opacity: 0, scale: 0.92 }}- transition={{ duration: 0.15, ease: [0.23, 1, 0.32, 1] }}- className='inline-flex'- >- <Filter- tnMapping={tnMapping}- canChangeExclusive- removable- {...props}- />- </motion.span>- )- })}- {_map(unsupported, (props) => {- const { column, filter, isExclusive, isContains } = props- const key = `unsupported-${column}-${filter}-${isExclusive}-${isContains}`-- return (- <motion.span- key={key}- layout- initial={{ opacity: 0, scale: 0.92 }}- animate={{ opacity: 0.6, scale: 1 }}- exit={{ opacity: 0, scale: 0.92 }}- transition={{ duration: 0.15, ease: [0.23, 1, 0.32, 1] }}- className='inline-flex'- >- <Filter tnMapping={tnMapping} removable {...props} />- </motion.span>- )- })}+ {_map(supported, (filter) => (+ <motion.span+ key={getFilterKey(filter)}+ layout+ initial={{ opacity: 0, scale: 0.92 }}+ animate={{ opacity: 1, scale: 1 }}+ exit={{ opacity: 0, scale: 0.92 }}+ transition={{ duration: 0.15, ease: [0.23, 1, 0.32, 1] }}+ className='inline-flex'+ >+ <Filter+ tnMapping={tnMapping}+ canChangeExclusive+ removable+ filter={filter}+ />+ </motion.span>+ ))}+ {_map(unsupported, (filter) => (+ <motion.span+ key={`unsupported-${getFilterKey(filter)}`}+ layout+ initial={{ opacity: 0, scale: 0.92 }}+ animate={{ opacity: 0.6, scale: 1 }}+ exit={{ opacity: 0, scale: 0.92 }}+ transition={{ duration: 0.15, ease: [0.23, 1, 0.32, 1] }}+ className='inline-flex'+ >+ <Filter tnMapping={tnMapping} removable filter={filter} />+ </motion.span>+ ))}</AnimatePresence></div>{unsupported.length > 0 ? (diff --git a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsxindex 3b58957ce..3fcafed16 100644--- a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx+++ b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx@@ -6,8 +6,8 @@ import { useTranslation } from 'react-i18next'import { useLocation } from 'react-router'import { Link } from '~/ui/Link'-import type { LiveVisitorInfo } from '~/api/api.server'-import { useLiveVisitorsProxy } from '~/hooks/useAnalyticsProxy'+import { getLiveVisitors as getLiveVisitorsV2 } from '~/api/v2/endpoints'+import type { LiveVisitor } from '~/api/v2/types'import {FLOW_TIMING,FLOW_VALUE_CLASS,@@ -29,8 +29,7 @@ const LiveVisitorsDropdown = () => {const location = useLocation()const [isDropdownVisible, setIsDropdownVisible] = useState(false)const [isLoading, setIsLoading] = useState(true)- const [liveInfo, setLiveInfo] = useState<LiveVisitorInfo[]>([])- const { fetchLiveVisitorsInfo } = useLiveVisitorsProxy()+ const [liveInfo, setLiveInfo] = useState<LiveVisitor[]>([])const flowLiveVisitors = useFlowValue(liveVisitors)// The translation interpolates the amount into the sentence, so split it@@ -45,11 +44,11 @@ const LiveVisitorsDropdown = () => {try {// Getting live sessions list and updating live visitors count to make sure it matches the list length- const [info] = await Promise.all([- fetchLiveVisitorsInfo(id),+ const [{ data }] = await Promise.all([+ getLiveVisitorsV2(id),updateLiveVisitors(),])- setLiveInfo(info || [])+ setLiveInfo(data.visitors || [])} catch (reason) {console.error('[LiveVisitorsDropdown] getLiveVisitors:', reason)}@@ -138,7 +137,7 @@ const LiveVisitorsDropdown = () => {</Text>) : (<div className='flex w-full min-w-0 flex-col gap-1.5 py-1.5'>- {_map(liveInfo, ({ psid, dv, br, os, cc }) => {+ {_map(liveInfo, ({ psid, device, browser, os, country }) => {const params = new URLSearchParams(location.search)params.set('psid', psid)params.set('tab', PROJECT_TABS.sessions)@@ -152,15 +151,17 @@ const LiveVisitorsDropdown = () => {<div className='flex w-5 shrink-0 items-center'><FlagclassName='rounded-xs'- country={cc}+ country={country}size={18}alt=''aria-hidden='true'/></div><div className='min-w-0 truncate'>{os}</div>- <div className='min-w-0 truncate'>{br}</div>- <div className='min-w-0 truncate capitalize'>{dv}</div>+ <div className='min-w-0 truncate'>{browser}</div>+ <div className='min-w-0 truncate capitalize'>+ {device}+ </div></Link>)})}diff --git a/web/app/pages/Project/View/components/NoEvents.tsx b/web/app/pages/Project/View/components/NoEvents.tsxindex 90ad55c78..d61cd8a25 100644--- a/web/app/pages/Project/View/components/NoEvents.tsx+++ b/web/app/pages/Project/View/components/NoEvents.tsx@@ -3,15 +3,15 @@ import _isEmpty from 'lodash/isEmpty'import { memo } from 'react'import { useTranslation } from 'react-i18next'+import { V2Filter } from '~/api/v2/types'import { Text } from '~/ui/Text'-import { Filter } from '../interfaces/traffic'import { typeNameMapping } from '../ViewProject.helpers'import Filters from './Filters'interface NoEventsProps {- filters: Filter[]+ filters: V2Filter[]}const NoEvents = ({ filters }: NoEventsProps) => {diff --git a/web/app/pages/Project/View/components/ProjectViewHeaderActions.tsx b/web/app/pages/Project/View/components/ProjectViewHeaderActions.tsxindex d5683a362..bf79a4f25 100644--- a/web/app/pages/Project/View/components/ProjectViewHeaderActions.tsx+++ b/web/app/pages/Project/View/components/ProjectViewHeaderActions.tsx@@ -10,14 +10,16 @@ import { useTranslation } from 'react-i18next'import { useFetcher, useSearchParams } from 'react-router'import { toast } from 'sonner'+import { V2Filter } from '~/api/v2/types'import { PROJECT_TABS } from '~/lib/constants'import { useCurrentProject } from '~/providers/CurrentProjectProvider'import { ProjectViewActionData } from '~/routes/projects.$id'import Dropdown from '~/ui/Dropdown'import { Text } from '~/ui/Text'import { trackCustom } from '~/utils/analytics'+import { legacyFilterToV2 } from '~/utils/analyticsUrl'-import { Filter, ProjectView } from '../interfaces/traffic'+import { ProjectView } from '../interfaces/traffic'import {splitProjectViewFiltersByTab,supportsProjectViewSegments,@@ -57,13 +59,13 @@ const isAddViewItem = (item: ProjectViewMenuItem): item is AddViewItem =>const isEmptyViewItem = (item: ProjectViewMenuItem): item is EmptyViewItem =>'notClickable' in item-const getFilterSearchParamKey = (filter: Filter) => {- if (filter.isContains) {- return filter.isExclusive ? `^${filter.column}` : `~${filter.column}`- }-- return filter.isExclusive ? `!${filter.column}` : filter.column-}+// Saved project views keep the legacy filter shape server-side; convert to+// the v2 shape at this boundary (unmappable legacy filters are dropped).+const projectViewFiltersToV2 = (view: ProjectView): V2Filter[] =>+ (view.filters || []).flatMap((filter) => {+ const converted = legacyFilterToV2(filter)+ return converted ? [converted] : []+ })const iconButtonClassName ='rounded-md p-1 hover:bg-gray-50 hover:text-gray-900 dark:hover:bg-slate-900 dark:hover:text-slate-200'@@ -137,11 +139,20 @@ const ProjectViewHeaderActions = ({}}, [deleteFetcher.state, deleteFetcher.data, loadProjectViews, t])- const getFilterColumnLabel = (column: string) => {+ const getFilterColumnLabel = (filter: V2Filter) => {+ if (filter.key) {+ return t(+ `project.metamapping.${filter.dimension === 'page_property' ? 'tag' : 'ev'}.dynamicKey`,+ {+ key: filter.key,+ },+ )+ }+return (- tnMapping[column] ||- t(`project.mapping.${column}`, {- defaultValue: column,+ tnMapping[filter.dimension] ||+ t(`project.mapping.${filter.dimension}`, {+ defaultValue: filter.dimension,}))}@@ -167,7 +178,7 @@ const ProjectViewHeaderActions = ({}const { supported, unsupported } = splitProjectViewFiltersByTab(- item.filters || [],+ projectViewFiltersToV2(item),activeTab,)const hasTrafficMetrics = (item.customEvents?.length || 0) > 0@@ -177,7 +188,7 @@ const ProjectViewHeaderActions = ({supported.length > 0 ||(activeTab === PROJECT_TABS.traffic && hasTrafficMetrics)const unsupportedTitle = unsupported- .map(({ column }) => getFilterColumnLabel(column))+ .map(getFilterColumnLabel).join(', ')return (@@ -274,7 +285,7 @@ const ProjectViewHeaderActions = ({}const { supported } = splitProjectViewFiltersByTab(- item.filters || [],+ projectViewFiltersToV2(item),activeTab,)const hasSupportedFilters = supported.length > 0@@ -288,28 +299,12 @@ const ProjectViewHeaderActions = ({}let newParams = new URLSearchParams(searchParams)- const supportedFilterKeys = new Set(- supported.map(getFilterSearchParamKey),- )-- filters.forEach((filter) => {- const key = getFilterSearchParamKey(filter)-- if (!supportedFilterKeys.has(key)) {- newParams.delete(key)- }- })newParams.delete('metrics')- if (hasSupportedFilters) {- newParams = getFiltersUrlParams(- filters,- supported,- true,- newParams,- )- }+ // override=true replaces every filter param (including legacy+ // aliases) with the segment's filters+ newParams = getFiltersUrlParams(filters, supported, true, newParams)if (hasTrafficMetrics) {newParams.set('metrics', JSON.stringify(item.customEvents))diff --git a/web/app/pages/Project/View/components/SearchFilters.tsx b/web/app/pages/Project/View/components/SearchFilters.tsxindex f4572e6c1..e7cffccba 100644--- a/web/app/pages/Project/View/components/SearchFilters.tsx+++ b/web/app/pages/Project/View/components/SearchFilters.tsx@@ -3,35 +3,42 @@ import { useState } from 'react'import { useTranslation } from 'react-i18next'import { useNavigate, useSearchParams } from 'react-router'+import { V2Filter } from '~/api/v2/types'import Modal from '~/ui/Modal'--import { Filter as FilterType } from '../interfaces/traffic'-import { isFilterValid } from '../utils/filters'+import {+ filterToUrlKey,+ filterToUrlValue,+ isFilterUrlKey,+} from '~/utils/analyticsUrl'import FilterRowsEditor from './FilterRowsEditor'export const getFiltersUrlParams = (- filters: FilterType[],- newFilters: FilterType[],+ filters: V2Filter[],+ newFilters: V2Filter[],override: boolean,searchParams: URLSearchParams,) => {const currentUrlParams = new URLSearchParams(searchParams.toString())- const resultingFilters: FilterType[] = []+ const resultingFilters: V2Filter[] = []if (override) {resultingFilters.push(...newFilters)} else {- const finalUniqueFiltersMap = new Map<string, FilterType>()+ const finalUniqueFiltersMap = new Map<string, V2Filter>()newFilters.forEach((filter) => {- const mapKey = `${filter.isExclusive ? '!' : ''}${filter.isContains ? '~' : ''}${filter.column}=${filter.filter}`- finalUniqueFiltersMap.set(mapKey, filter)+ finalUniqueFiltersMap.set(+ `${filterToUrlKey(filter)}=${filterToUrlValue(filter)}`,+ filter,+ )})filters.forEach((filter) => {- const mapKey = `${filter.isExclusive ? '!' : ''}${filter.isContains ? '~' : ''}${filter.column}=${filter.filter}`- finalUniqueFiltersMap.set(mapKey, filter)+ finalUniqueFiltersMap.set(+ `${filterToUrlKey(filter)}=${filterToUrlValue(filter)}`,+ filter,+ )})resultingFilters.push(...Array.from(finalUniqueFiltersMap.values()))@@ -40,21 +47,13 @@ export const getFiltersUrlParams = (const newUrlParams = new URLSearchParams()for (const [key, value] of currentUrlParams.entries()) {- let processedKey = key- if (key.startsWith('!') || key.startsWith('~') || key.startsWith('^')) {- processedKey = key.substring(1)- }- if (!isFilterValid(processedKey, true)) {+ if (!isFilterUrlKey(key)) {newUrlParams.append(key, value)}}resultingFilters.forEach((filter) => {- let filterKey = filter.isExclusive ? `!${filter.column}` : filter.column- if (filter.isContains) {- filterKey = filter.isExclusive ? `^${filter.column}` : `~${filter.column}`- }- newUrlParams.append(filterKey, filter.filter)+ newUrlParams.append(filterToUrlKey(filter), filterToUrlValue(filter))})return newUrlParams@@ -64,7 +63,7 @@ interface SearchFiltersProps {showModal: booleansetShowModal: (show: boolean) => voidtnMapping: Record<string, string>- filters: FilterType[]+ filters: V2Filter[]type: 'traffic' | 'errors'filterOptions?: string[]}@@ -78,7 +77,7 @@ const SearchFilters = ({filterOptions,}: SearchFiltersProps) => {const { t } = useTranslation('common')- const [draftFilters, setDraftFilters] = useState<FilterType[]>([])+ const [draftFilters, setDraftFilters] = useState<V2Filter[]>([])const [searchParams] = useSearchParams()const navigate = useNavigate()diff --git a/web/app/pages/Project/View/interfaces/traffic.ts b/web/app/pages/Project/View/interfaces/traffic.tsindex ce630b6dc..c80358840 100644--- a/web/app/pages/Project/View/interfaces/traffic.ts+++ b/web/app/pages/Project/View/interfaces/traffic.ts@@ -1,6 +1,7 @@import { TimeBucket } from '~/lib/constants'-export interface Filter {+// Legacy (v1) filter shape — still used by saved project views (server-side format)+interface Filter {column: stringfilter: stringisExclusive: boolean@@ -35,18 +36,18 @@ interface Param {count: number}-export type Params = Record<string, Param[]>+type Params = Record<string, Param[]>export type Customs = Record<string, number>-export type Properties = Record<string, number>+type Properties = Record<string, number>interface Metric {sum: numberavg: number}-export interface TrafficMeta {+interface TrafficMeta {key: stringcurrent: Metricprevious: Metricdiff --git a/web/app/pages/Project/View/utils/filters.tsx b/web/app/pages/Project/View/utils/filters.tsxindex 1d258d833..fa0291664 100644--- a/web/app/pages/Project/View/utils/filters.tsx+++ b/web/app/pages/Project/View/utils/filters.tsx@@ -1,11 +1,3 @@-import _includes from 'lodash/includes'-import _keys from 'lodash/keys'-import _reduce from 'lodash/reduce'-import _some from 'lodash/some'-import _startsWith from 'lodash/startsWith'--import { Filter } from '../interfaces/traffic'-export const ERROR_FILTERS_MAPPING = {showResolved: 'showResolved',}@@ -16,102 +8,3 @@ export const FILTER_CHART_METRICS_MAPPING_FOR_COMPARE = ['trendlines','customEvents',]--const validFilters = [- 'host',- 'cc',- 'rg',- 'ct',- 'pg',- 'entryPage',- 'exitPage',- 'lc',- 'ref',- 'refn',- 'dv',- 'br',- 'brv',- 'os',- 'osv',- 'so',- 'me',- 'ca',- 'te',- 'co',- 'isp',- 'og',- 'ut',- 'ctp',- 'ev',- 'keywords',- 'tag:key',- 'tag:value',- 'ev:key',- 'ev:value',-]-// dynamic filters is when a filter column starts with a specific value and is followed by some arbitrary string-// this is done to build a connnection between dynamic column and value (e.g. for custom event metadata or page properties)-const validDynamicFilters = ['ev:key:', 'tag:key:']--export const isFilterValid = (filter: string, checkDynamicFilters = false) => {- // normalise by removing operator prefixes from the URL key- let normalised = filter- if (- _startsWith(normalised, '!') ||- _startsWith(normalised, '~') ||- _startsWith(normalised, '^')- ) {- normalised = normalised.substring(1)- }-- if (_includes(validFilters, normalised)) {- return true- }-- if (- checkDynamicFilters &&- _some(validDynamicFilters, (prefix) => _startsWith(normalised, prefix))- ) {- return true- }-- return false-}--export const parseFilters = (searchParams: URLSearchParams): Filter[] => {- const filters: Filter[] = []-- const entries = Array.from(searchParams.entries())-- for (const [key, value] of entries) {- let actualColumn = key-- let isExclusive = false- let isContains = false-- if (key.startsWith('!')) {- isExclusive = true- actualColumn = key.substring(1)- } else if (key.startsWith('~')) {- isContains = true- actualColumn = key.substring(1)- } else if (key.startsWith('^')) {- isExclusive = true- isContains = true- actualColumn = key.substring(1)- }-- if (!isFilterValid(actualColumn, true)) {- continue- }-- filters.push({- column: actualColumn,- filter: value,- isExclusive: isExclusive,- isContains,- })- }-- return filters-}diff --git a/web/app/pages/Project/View/utils/projectViewSegments.ts b/web/app/pages/Project/View/utils/projectViewSegments.tsindex 436c7b256..97c1e19ed 100644--- a/web/app/pages/Project/View/utils/projectViewSegments.ts+++ b/web/app/pages/Project/View/utils/projectViewSegments.ts@@ -1,54 +1,35 @@-import {- ERRORS_FILTERS_PANELS_ORDER,- FILTERS_PANELS_ORDER,- PROJECT_TABS,-} from '~/lib/constants'--import { Filter } from '../interfaces/traffic'+import { V2Filter } from '~/api/v2/types'+import { PROJECT_TABS } from '~/lib/constants'+import { VALID_DIMENSIONS_BY_TYPE } from '~/lib/v2Dimensions'type ProjectTab = keyof typeof PROJECT_TABS-const TRAFFIC_FILTER_OPTIONS = FILTERS_PANELS_ORDER.includes('ev')- ? FILTERS_PANELS_ORDER- : FILTERS_PANELS_ORDER.flatMap((column) =>- column === 'exitPage' ? [column, 'ev'] : [column],- )--const TRAFFIC_FILTER_COLUMNS = [- ...TRAFFIC_FILTER_OPTIONS,- 'refn',- 'ev:key',- 'tag:key',- 'tag:value',-]--const PERFORMANCE_FILTER_COLUMNS = [- 'pg',- 'host',- 'cc',- 'rg',- 'ct',- 'dv',- 'br',- 'brv',- 'isp',- 'og',- 'ut',- 'ctp',-]--const ERRORS_FILTER_COLUMNS = [- 'host',- ...ERRORS_FILTERS_PANELS_ORDER,- 'entryPage',- 'exitPage',- 'tag:key',- 'tag:value',-]--const CAPTCHA_FILTER_COLUMNS = ['cc', 'br', 'os', 'dv']--const SEO_FILTER_COLUMNS = ['pg', 'keywords', 'cc', 'dv']+// Dimensions that carry a key (event_metadata:plan) are never offered in the+// filter editors directly — they're only created from panel clicks — but they+// are supported when applying segments / rendering chips.+const KEYED_FILTER_DIMENSIONS = ['event_metadata', 'page_property']++// referrer_name shares a display label with referrer, so offering both in the+// column dropdown would be confusing.+const HIDDEN_FILTER_OPTIONS = [...KEYED_FILTER_DIMENSIONS, 'referrer_name']++const TRAFFIC_FILTER_OPTIONS = VALID_DIMENSIONS_BY_TYPE.traffic.filter(+ (dimension) => !HIDDEN_FILTER_OPTIONS.includes(dimension),+)++const TRAFFIC_FILTER_COLUMNS = VALID_DIMENSIONS_BY_TYPE.traffic++const PERFORMANCE_FILTER_COLUMNS = VALID_DIMENSIONS_BY_TYPE.performance++const ERRORS_FILTER_OPTIONS = VALID_DIMENSIONS_BY_TYPE.errors.filter(+ (dimension) => !HIDDEN_FILTER_OPTIONS.includes(dimension),+)++const ERRORS_FILTER_COLUMNS = VALID_DIMENSIONS_BY_TYPE.errors++const CAPTCHA_FILTER_COLUMNS = VALID_DIMENSIONS_BY_TYPE.captcha++const SEO_FILTER_COLUMNS = ['page', 'keywords', 'country', 'device']const ANALYTICS_TABS = new Set<ProjectTab>([PROJECT_TABS.traffic,@@ -63,23 +44,26 @@ const ANALYTICS_TABS = new Set<ProjectTab>([const FILTER_OPTIONS_BY_TAB: Partial<Record<ProjectTab, string[]>> = {[PROJECT_TABS.traffic]: TRAFFIC_FILTER_OPTIONS,[PROJECT_TABS.performance]: PERFORMANCE_FILTER_COLUMNS,- [PROJECT_TABS.seo]: ['pg', 'cc', 'dv'],+ [PROJECT_TABS.seo]: ['page', 'country', 'device'],[PROJECT_TABS.sessions]: TRAFFIC_FILTER_OPTIONS,[PROJECT_TABS.replays]: TRAFFIC_FILTER_OPTIONS,[PROJECT_TABS.profiles]: TRAFFIC_FILTER_OPTIONS,[PROJECT_TABS.funnels]: TRAFFIC_FILTER_OPTIONS,[PROJECT_TABS.goals]: TRAFFIC_FILTER_OPTIONS,[PROJECT_TABS.experiments]: TRAFFIC_FILTER_OPTIONS,- [PROJECT_TABS.errors]: ['host', ...ERRORS_FILTERS_PANELS_ORDER],+ [PROJECT_TABS.errors]: ERRORS_FILTER_OPTIONS,[PROJECT_TABS.captcha]: CAPTCHA_FILTER_COLUMNS,}-const supportsDynamicFilter = (column: string, tab: ProjectTab) => {- if (column.startsWith('ev:key:')) {+const supportsKeyedFilter = (+ filter: Pick<V2Filter, 'dimension' | 'key'>,+ tab: ProjectTab,+) => {+ if (filter.dimension === 'event_metadata') {return ANALYTICS_TABS.has(tab)}- if (column.startsWith('tag:key:')) {+ if (filter.dimension === 'page_property') {return ANALYTICS_TABS.has(tab) || tab === PROJECT_TABS.errors}@@ -111,22 +95,22 @@ const getSupportedColumns = (tab: ProjectTab) => {}const isProjectTabFilterSupported = (- filter: Pick<Filter, 'column'>,+ filter: Pick<V2Filter, 'dimension' | 'key'>,tab: ProjectTab,) => {- if (supportsDynamicFilter(filter.column, tab)) {- return true+ if (filter.key) {+ return supportsKeyedFilter(filter, tab)}- return getSupportedColumns(tab).includes(filter.column)+ return getSupportedColumns(tab).includes(filter.dimension)}export const splitProjectViewFiltersByTab = (- filters: Filter[] = [],+ filters: V2Filter[] = [],tab: ProjectTab,) => {- const supported: Filter[] = []- const unsupported: Filter[] = []+ const supported: V2Filter[] = []+ const unsupported: V2Filter[] = []filters.forEach((filter) => {if (isProjectTabFilterSupported(filter, tab)) {diff --git a/web/app/pages/Project/View/v2/BreakdownPanel.tsx b/web/app/pages/Project/View/v2/BreakdownPanel.tsxnew file mode 100644index 000000000..713e0f679--- /dev/null+++ b/web/app/pages/Project/View/v2/BreakdownPanel.tsx@@ -0,0 +1,278 @@+import { ArrowsClockwiseIcon, WarningOctagonIcon } from '@phosphor-icons/react'+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { LinkProps } from 'react-router'++import { V2DataType } from '~/api/v2/types'+import { useBreakdownDetailsQuery } from '~/hooks/v2/useV2Queries'+import { useInViewOnce } from '~/hooks/useInViewOnce'+import { Entry } from '~/lib/models/Entry'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'+import Button from '~/ui/Button'+import { Text } from '~/ui/Text'+import { getItem, setItem } from '~/utils/localstorage'++import { Panel, PanelContainer } from '../Panels'+import { groupVersionRows, mapBreakdownRows } from './adapters'+import { PanelSkeleton } from './loading'++export interface BreakdownSubTab {+ /** Sub-tab id — the v2 dimension name, or a sentinel like 'map' / 'userFlow' */+ id: string+ label: string+ /** v2 dimension to query; omit for sentinel tabs rendered via `render` */+ dimension?: string+ /** Custom body for sentinel tabs (map, user flow) — data-independent */+ render?: () => React.ReactNode+ /** Lazily fetch a version drill-down breakdown for this sub-tab */+ versionsDimension?: 'browser_version' | 'os_version'+ versionsParentField?: 'browser' | 'os'+}++interface BreakdownPanelProps {+ dataType: V2DataType+ /** Stable panel identity for sub-tab persistence (e.g. 'location', 'pages') */+ panelId: string+ name: string+ icon: React.ReactNode+ /** Nested arrays render as a dropdown tab group (PanelContainer semantics) */+ subTabs: (BreakdownSubTab | BreakdownSubTab[])[]+ /** Metric used for row counts / sorting (visitors, load_time, occurrences, events) */+ primaryMetric?: string+ metrics?: string[]+ /** Performance measure (median / average / p75 / p95) */+ measure?: string+ rowMapper?: (entry: Entry, subTabId: string) => React.ReactNode+ valueMapper?: (value: number, subTabId: string) => number+ /** Post-process fetched entries (e.g. group referrers by domain) */+ transformEntries?: (entries: Entry[], subTabId: string) => Entry[]+ /** Sub-tab ids whose entries render capitalized */+ capitalize?: string[]+ /** Override filter link building (defaults to context getFilterLink) */+ getFilterLink?: (+ dimension: string,+ value: string | null,+ subTabId: string,+ ) => LinkProps['to']+ getVersionFilterLink?: (+ parent: string | null,+ version: string | null,+ subTabId: string,+ ) => LinkProps['to'] | string+ valuesHeaderName?: string+ highlightColour?: 'blue' | 'red' | 'orange'+ onActiveSubTabChange?: (subTabId: string) => void+}++const subTabStorageKey = (dataType: string, panelId: string) =>+ `v2PanelTab:${dataType}:${panelId}`++/**+ * One dashboard breakdown card: owns its own v2 breakdown query (gated on+ * viewport visibility), sub-tab switching, lazy version drill-down and+ * paginated details, and renders the existing Panel visuals.+ */+export const BreakdownPanel = ({+ dataType,+ panelId,+ name,+ icon,+ subTabs,+ primaryMetric = 'visitors',+ metrics,+ measure,+ rowMapper,+ valueMapper,+ transformEntries,+ capitalize,+ getFilterLink: getFilterLinkProp,+ getVersionFilterLink,+ valuesHeaderName,+ highlightColour,+ onActiveSubTabChange,+}: BreakdownPanelProps) => {+ const { t } = useTranslation('common')+ const { getFilterLink: getFilterLinkContext } = useViewProjectContext()+ const { ref, hasBeenInView } = useInViewOnce()++ const flatSubTabs = useMemo(() => subTabs.flat(), [subTabs])++ const [activeSubTabId, setActiveSubTabId] = useState<string>(() => {+ const stored = getItem(subTabStorageKey(dataType, panelId))+ if (stored && flatSubTabs.some((tab) => tab.id === stored)) {+ return stored as string+ }+ return flatSubTabs[0].id+ })++ const activeSubTab =+ flatSubTabs.find((tab) => tab.id === activeSubTabId) || flatSubTabs[0]++ const onSubTabChange = (tabId: string) => {+ setActiveSubTabId(tabId)+ setItem(subTabStorageKey(dataType, panelId), tabId)+ onActiveSubTabChange?.(tabId)+ }++ const isSentinel = !activeSubTab.dimension++ const query = useBreakdownDetailsQuery(dataType, {+ dimension: activeSubTab.dimension || '',+ metrics,+ measure,+ sort: `${primaryMetric}:desc`,+ enabled: hasBeenInView && !isSentinel,+ })++ const versionsQuery = useBreakdownDetailsQuery(dataType, {+ dimension: activeSubTab.versionsDimension || '',+ metrics,+ measure,+ sort: `${primaryMetric}:desc`,+ enabled: hasBeenInView && Boolean(activeSubTab.versionsDimension),+ })++ const entries = useMemo(() => {+ const mapped = mapBreakdownRows(+ query.data?.pages.flatMap((page) => page.data),+ primaryMetric,+ )+ return transformEntries ? transformEntries(mapped, activeSubTabId) : mapped+ }, [query.data, primaryMetric, transformEntries, activeSubTabId])++ const versionData = useMemo(() => {+ if (!activeSubTab.versionsDimension || !versionsQuery.data) {+ return undefined+ }++ return groupVersionRows(+ versionsQuery.data.pages.flatMap((page) => page.data),+ activeSubTab.versionsParentField || 'browser',+ primaryMetric,+ )+ }, [activeSubTab, versionsQuery.data, primaryMetric])++ const total = query.data?.pages[0]?.meta.total++ // A single sub-tab is just the dimension itself — no tab bar needed+ const containerTabs =+ flatSubTabs.length > 1+ ? subTabs.map((tab) =>+ Array.isArray(tab)+ ? tab.map(({ id, label }) => ({ id, label }))+ : { id: tab.id, label: tab.label },+ )+ : undefined++ if (isSentinel) {+ return (+ <div ref={ref}>+ <PanelContainer+ name={name}+ icon={icon}+ type={activeSubTabId}+ tabs={containerTabs}+ onTabChange={onSubTabChange}+ activeTabId={activeSubTabId}+ >+ {activeSubTab.render?.()}+ </PanelContainer>+ </div>+ )+ }++ if (query.isLoading || (!hasBeenInView && !query.data)) {+ return (+ <div ref={ref}>+ <PanelContainer+ name={name}+ icon={icon}+ type={activeSubTabId}+ tabs={containerTabs}+ onTabChange={onSubTabChange}+ activeTabId={activeSubTabId}+ >+ <PanelSkeleton />+ </PanelContainer>+ </div>+ )+ }++ if (query.isError) {+ return (+ <div ref={ref}>+ <PanelContainer+ name={name}+ icon={icon}+ type={activeSubTabId}+ tabs={containerTabs}+ onTabChange={onSubTabChange}+ activeTabId={activeSubTabId}+ >+ <div className='flex h-full flex-1 flex-col items-center justify-center px-4 py-8 text-center'>+ <div className='mb-3 flex size-10 items-center justify-center rounded-lg bg-gray-100 dark:bg-slate-900'>+ <WarningOctagonIcon className='size-5 text-gray-400 dark:text-slate-500' />+ </div>+ <Text as='p' size='sm' colour='secondary'>+ {t('apiNotifications.somethingWentWrong')}+ </Text>+ <Button+ className='mt-3 gap-1.5'+ onClick={() => query.refetch()}+ variant='secondary'+ size='sm'+ >+ <ArrowsClockwiseIcon className='size-4' />+ {t('project.refreshStats')}+ </Button>+ </div>+ </PanelContainer>+ </div>+ )+ }++ return (+ <div ref={ref}>+ <Panel+ key={activeSubTabId}+ icon={icon}+ id={activeSubTab.dimension || activeSubTabId}+ name={name}+ data={entries}+ serverTotal={total}+ tabs={containerTabs}+ onTabChange={onSubTabChange}+ activeTabId={activeSubTabId}+ rowMapper={+ rowMapper ? (entry) => rowMapper(entry, activeSubTabId) : undefined+ }+ valueMapper={+ valueMapper+ ? (value) => valueMapper(value, activeSubTabId)+ : undefined+ }+ capitalize={capitalize?.includes(activeSubTabId)}+ getFilterLink={(dimension, value) =>+ getFilterLinkProp+ ? getFilterLinkProp(dimension, value, activeSubTabId)+ : getFilterLinkContext(dimension, value)+ }+ versionData={versionData}+ getVersionFilterLink={+ getVersionFilterLink+ ? (parent, version) =>+ getVersionFilterLink(parent, version, activeSubTabId)+ : undefined+ }+ valuesHeaderName={valuesHeaderName}+ highlightColour={highlightColour}+ dataLoading={query.isFetching && !query.isFetchingNextPage}+ isRefetching={+ query.isFetching && !query.isLoading && !query.isFetchingNextPage+ }+ onLoadMore={query.hasNextPage ? () => query.fetchNextPage() : undefined}+ loadingMore={query.isFetchingNextPage}+ />+ </div>+ )+}diff --git a/web/app/pages/Project/View/v2/TrafficMap.tsx b/web/app/pages/Project/View/v2/TrafficMap.tsxnew file mode 100644index 000000000..c7aadd8c7--- /dev/null+++ b/web/app/pages/Project/View/v2/TrafficMap.tsx@@ -0,0 +1,66 @@+import { Suspense, lazy, useMemo } from 'react'+import { useNavigate } from 'react-router'++import { useBreakdownQuery } from '~/hooks/v2/useV2Queries'+import { MapLoader } from '~/pages/Project/View/components/MapLoader'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'++import { mapBreakdownRows } from './adapters'++const InteractiveMap = lazy(+ () => import('~/pages/Project/View/components/InteractiveMap'),+)++const MAP_CLICK_TYPE_TO_DIMENSION = { cc: 'country', rg: 'region' } as const++/**+ * Interactive location map fed by its own country + region breakdown queries+ * (deduped with the location panel's queries via react-query cache).+ */+export const TrafficMap = ({ isFullscreen }: { isFullscreen: boolean }) => {+ const navigate = useNavigate()+ const { getFilterLink, setIsMapFullscreen } = useViewProjectContext()++ const countryQuery = useBreakdownQuery('traffic', {+ dimension: 'country',+ limit: 100,+ sort: 'visitors:desc',+ })+ const regionQuery = useBreakdownQuery('traffic', {+ dimension: 'region',+ limit: 100,+ sort: 'visitors:desc',+ })++ const countryData = useMemo(+ () => mapBreakdownRows(countryQuery.data?.data),+ [countryQuery.data],+ )+ const regionData = useMemo(+ () => mapBreakdownRows(regionQuery.data?.data),+ [regionQuery.data],+ )+ const total = useMemo(+ () => countryData.reduce((acc, curr) => acc + curr.count, 0),+ [countryData],+ )++ if (countryQuery.isLoading) {+ return <MapLoader />+ }++ return (+ <Suspense fallback={<MapLoader />}>+ <InteractiveMap+ data={countryData}+ regionData={regionData}+ total={total}+ onClick={(mapType, key) => {+ navigate(getFilterLink(MAP_CLICK_TYPE_TO_DIMENSION[mapType], key))+ }}+ onFullscreenToggle={setIsMapFullscreen}+ isFullscreen={isFullscreen}+ />+ </Suspense>+ )+}diff --git a/web/app/pages/Project/View/v2/adapters.ts b/web/app/pages/Project/View/v2/adapters.tsnew file mode 100644index 000000000..f050be139--- /dev/null+++ b/web/app/pages/Project/View/v2/adapters.ts@@ -0,0 +1,159 @@+import {+ BreakdownRow,+ MetadataRow,+ TimeseriesRow,+ TrafficSummaryData,+ V2Filter,+} from '~/api/v2/types'+import { Entry } from '~/lib/models/Entry'+import { OverallObject } from '~/lib/models/Project'++// Adapters that pivot v2 API responses into the shapes the existing UI+// components (Panel, DetailsTable, InteractiveMap, billboard chart pipeline)+// already consume, so those components stay untouched.++/** Breakdown rows -> Panel entries ({ value, <metric> } -> { name, count }) */+export const mapBreakdownRows = (+ rows: BreakdownRow[] | undefined,+ primaryMetric = 'visitors',+): Entry[] => {+ if (!rows) return []++ return rows.map((row) => ({+ name: row.value,+ count: Number(row[primaryMetric] ?? 0),+ ...(typeof row.country === 'string' ? { cc: row.country } : {}),+ ...(typeof row.region_code === 'string' ? { rgc: row.region_code } : {}),+ }))+}++/**+ * Version breakdown rows (browser_version / os_version, which carry their+ * parent as an extra field) -> { parent: Entry[] } map for Panel drill-down.+ */+export const groupVersionRows = (+ rows: BreakdownRow[] | undefined,+ parentField: 'browser' | 'os',+ primaryMetric = 'visitors',+): Record<string, Entry[]> => {+ const grouped: Record<string, Entry[]> = {}++ for (const row of rows || []) {+ const parent = row[parentField]+ if (typeof parent !== 'string' || !parent) continue++ if (!grouped[parent]) {+ grouped[parent] = []+ }++ grouped[parent].push({+ name: row.value,+ count: Number(row[primaryMetric] ?? 0),+ })+ }++ return grouped+}++/** Metadata rows -> the { result } shape KVTableContainer consumes */+export const metadataToResult = (rows: MetadataRow[] | undefined) => ({+ result: rows || [],+})++/** True when a custom-event filter is applied (metric cards collapse to Events) */+export const hasCustomEventFilter = (filters: V2Filter[]): boolean =>+ filters.some(+ (filter) =>+ filter.dimension === 'event' || filter.dimension === 'event_metadata',+ )++/** v2 traffic summary -> the OverallObject shape MetricCards consumes */+export const summaryToOverall = (+ summary: TrafficSummaryData | undefined,+ customEVFilterApplied = false,+): Partial<OverallObject> => {+ if (!summary) return {}++ const mapPeriod = (period: TrafficSummaryData['current']) => ({+ unique: period.visitors,+ all: period.pageviews,+ users: period.users,+ bounceRate: period.bounce_rate,+ sdur: period.session_duration,+ })++ return {+ current: mapPeriod(summary.current),+ previous: mapPeriod(summary.previous),+ change: summary.change.pageviews,+ uniqueChange: summary.change.visitors,+ usersChange: summary.change.users,+ bounceRateChange: summary.change.bounce_rate,+ sdurChange: summary.change.session_duration,+ customEVFilterApplied,+ }+}++/**+ * v2 ISO timestamp -> the 'YYYY-MM-DD HH:mm:ss' wall-time string the chart+ * pipeline expects. The timestamp is already in the requested timezone, so we+ * take its literal date-time part instead of letting Date/dayjs re-shift it+ * into the browser timezone.+ */+const toChartX = (timestamp: string): string =>+ timestamp.slice(0, 19).replace('T', ' ')++export interface TrafficChartData {+ x: string[]+ visits: number[]+ uniques: number[]+ sdur: number[]+ bounces: number[]+ [key: string]: number[] | string[]+}++/**+ * Traffic timeseries rows -> the columnar chart shape getColumns()/getSettings()+ * consume. `bounces` is reconstructed as a count because getColumns computes+ * the percentage from bounces/uniques.+ */+export const pivotTrafficTimeseries = (+ rows: TimeseriesRow[] | undefined,+): TrafficChartData => {+ const x: string[] = []+ const visits: number[] = []+ const uniques: number[] = []+ const sdur: number[] = []+ const bounces: number[] = []++ for (const row of rows || []) {+ const rowUniques = Number(row.visitors ?? 0)+ x.push(toChartX(row.timestamp))+ uniques.push(rowUniques)+ visits.push(Number(row.pageviews ?? 0))+ sdur.push(Number(row.session_duration ?? 0))+ bounces.push((Number(row.bounce_rate ?? 0) * rowUniques) / 100)+ }++ return { x, visits, uniques, sdur, bounces }+}++/** Custom events timeseries rows -> { x, events } for the stacked chart */+export const pivotCustomEventsTimeseries = (+ rows: TimeseriesRow[] | undefined,+ events: string[],+): { x: string[]; events: Record<string, number[]> } => {+ const x: string[] = []+ const series: Record<string, number[]> = Object.fromEntries(+ events.map((event) => [event, []]),+ )++ for (const row of rows || []) {+ x.push(toChartX(row.timestamp))+ for (const event of events) {+ series[event].push(Number(row[event] ?? 0))+ }+ }++ return { x, events: series }+}diff --git a/web/app/pages/Project/View/v2/loading.tsx b/web/app/pages/Project/View/v2/loading.tsxnew file mode 100644index 000000000..d09cc346f--- /dev/null+++ b/web/app/pages/Project/View/v2/loading.tsx@@ -0,0 +1,81 @@+import cx from 'clsx'++// Subtle per-panel loading primitives for the v2 per-dimension dashboard.+// First load -> skeleton; refetch -> thin indeterminate bar + dimmed body+// (data stays visible via react-query's keepPreviousData).++/** Thin indeterminate progress bar pinned to the top edge of a card */+export const RefetchIndicator = ({ className }: { className?: string }) => (+ <div+ aria-hidden+ className={cx(+ 'absolute inset-x-0 top-0 z-10 h-0.5 overflow-hidden',+ className,+ )}+ >+ <div+ className='absolute h-full rounded-full bg-linear-to-r from-slate-400 via-slate-700 to-slate-900 dark:from-slate-500 dark:via-slate-200 dark:to-white'+ style={{+ animation:+ 'indeterminate1 1.8s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite',+ }}+ />+ <div+ className='absolute h-full rounded-full bg-linear-to-r from-slate-700 to-slate-900 opacity-70 dark:from-slate-300 dark:to-white'+ style={{+ animation:+ 'indeterminate2 1.8s cubic-bezier(0.165, 0.84, 0.44, 1) infinite',+ animationDelay: '1s',+ }}+ />+ </div>+)++// Deterministic widths so SSR and client render identically+const SKELETON_ROW_WIDTHS = [+ '72%',+ '58%',+ '80%',+ '46%',+ '64%',+ '38%',+ '54%',+ '30%',+]++/** Pulse rows shaped like panel entries; rendered inside PanelContainer */+export const PanelSkeleton = ({ rows = 8 }: { rows?: number }) => (+ <div className='flex h-full flex-col justify-start gap-3 pt-2' aria-busy>+ {SKELETON_ROW_WIDTHS.slice(0, rows).map((width, i) => (+ <div key={i} className='flex animate-pulse items-center justify-between'>+ <div+ className='h-5 rounded-sm bg-gray-200 dark:bg-slate-800'+ style={{ width }}+ />+ <div className='h-5 w-10 rounded-sm bg-gray-200 dark:bg-slate-800' />+ </div>+ ))}+ </div>+)++/** Pulse block sized like the main chart */+export const ChartSkeleton = ({ className }: { className?: string }) => (+ <div+ aria-busy+ className={cx(+ 'h-80 animate-pulse rounded-lg bg-gray-200 md:h-[420px] dark:bg-slate-800',+ className,+ )}+ />+)++export const MetricCardsSkeleton = ({ cards = 4 }: { cards?: number }) => (+ <div className='mb-4 flex flex-wrap justify-center gap-5 lg:justify-start'>+ {Array.from({ length: cards }).map((_, i) => (+ <div key={i} className='flex animate-pulse flex-col'>+ <div className='mb-2 h-4 w-24 rounded-sm bg-gray-200 dark:bg-slate-800' />+ <div className='h-8 w-16 rounded-sm bg-gray-200 dark:bg-slate-800' />+ </div>+ ))}+ </div>+)diff --git a/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx b/web/app/pages/Project/tabs/Captcha/CaptchaView.tsxindex 9cc44e99c..0332dfe24 100644--- a/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx+++ b/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx@@ -1,4 +1,3 @@-import cx from 'clsx'import _isEmpty from 'lodash/isEmpty'import _map from 'lodash/map'import {@@ -6,64 +5,56 @@ import {MapPinIcon,MonitorIcon,DevicesIcon,- GlobeIcon,GaugeIcon,WarningIcon,ClockIcon,ShieldCheckIcon,} from '@phosphor-icons/react'-import { useState, useEffect, useMemo, useContext, useRef } from 'react'+import { useMemo, useRef, useCallback } from 'react'import { useTranslation } from 'react-i18next'-import { useSearchParams } from 'react-router'-import { useCaptchaProxy } from '~/hooks/useAnalyticsProxy'-import useSize from '~/hooks/useSize'import {- chartTypes,- BROWSER_LOGO_MAP,- OS_LOGO_MAP,- OS_LOGO_MAP_DARK,-} from '~/lib/constants'+ useCompareSummaryQuery,+ useSummaryQuery,+ useTimeseriesQuery,+} from '~/hooks/v2/useV2Queries'+import { chartTypes } from '~/lib/constants'+import { Entry } from '~/lib/models/Entry'import { MetricCard } from '~/pages/Project/tabs/Traffic/MetricCards'import { useCurrentProject } from '~/providers/CurrentProjectProvider'import { useTheme } from '~/providers/ThemeProvider'-import Loader from '~/ui/Loader'-import LoadingBar from '~/ui/LoadingBar'import { nFormatter } from '~/utils/generic'import CCRow from '../../View/components/CCRow'import DashboardHeader from '../../View/components/DashboardHeader'import Filters from '../../View/components/Filters'import ProjectViewHeaderActions from '../../View/components/ProjectViewHeaderActions'-import { Filter } from '../../View/interfaces/traffic'-import { Panel } from '../../View/Panels'-import { parseFilters } from '../../View/utils/filters'-import {- ViewProjectContext,- RefreshTriggersContext,-} from '../../View/ViewProject'-import { deviceIconMapping } from '../../View/ViewProject.helpers'+import { BreakdownPanel, BreakdownSubTab } from '../../View/v2/BreakdownPanel'+import { ChartSkeleton, MetricCardsSkeleton } from '../../View/v2/loading'+import { useViewProjectContext } from '../../View/ViewProject'+import { getDeviceRowMapper } from '../../View/ViewProject.helpers'+import { pivotCaptchaTimeseries } from './adapters'import { CaptchaChart } from './CaptchaChart'import NoCaptchaEvents from './NoCaptchaEvents'import WaitingForCaptchaEvent from './WaitingForCaptchaEvent'const PANELS_ORDER = [- 'cc',- 'br',+ 'country',+ 'browser','os',- 'dv',+ 'device','captcha_event','captcha_difficulty','solve_time','captcha_reason',-]+] as constconst iconClassName = 'w-6 h-6'const panelIconMapping: Record<string, React.ReactNode> = {- cc: <MapPinIcon className={iconClassName} />,- dv: <DevicesIcon className={iconClassName} />,- br: <CompassIcon className={iconClassName} />,+ country: <MapPinIcon className={iconClassName} />,+ device: <DevicesIcon className={iconClassName} />,+ browser: <CompassIcon className={iconClassName} />,os: <MonitorIcon className={iconClassName} />,captcha_event: <ShieldCheckIcon className={iconClassName} />,captcha_difficulty: <GaugeIcon className={iconClassName} />,@@ -72,9 +63,9 @@ const panelIconMapping: Record<string, React.ReactNode> = {}export const captchaTypeNameMapping = (t: any) => ({- cc: t('project.mapping.cc'),- dv: t('project.mapping.dv'),- br: t('project.mapping.br'),+ country: t('project.mapping.cc'),+ device: t('project.mapping.dv'),+ browser: t('project.mapping.br'),os: t('project.mapping.os'),captcha_event: t('project.mapping.captcha_event'),captcha_difficulty: t('project.mapping.captcha_difficulty'),@@ -86,45 +77,35 @@ interface CaptchaViewProps {projectId: string}-const CaptchaView = ({ projectId }: CaptchaViewProps) => {+const CaptchaView = (_props: CaptchaViewProps) => {const { theme } = useTheme()const { project } = useCurrentProject()- const { captchaRefreshTrigger } = useContext(RefreshTriggersContext)- const {- period,- timeBucket,- dateRange,- timeFormat,- size,- activePeriodCompare,- } = useContext(ViewProjectContext)- const [searchParams] = useSearchParams()- const isEmbedded = searchParams.get('embedded') === 'true'- const isMountedRef = useRef(true)- const captchaProxy = useCaptchaProxy()+ const { timeBucket, timeFormat, filters, rotateXAxis } =+ useViewProjectContext()const {t,i18n: { language },} = useTranslation('common')- const [panelsData, setPanelsData] = useState<any>({})- const [chartData, setChartData] = useState<{- x: string[]- results?: number[]- generated?: number[]- passed?: number[]- failed?: number[]- validationFailed?: number[]- replayed?: number[]- } | null>(null)- const [summaryData, setSummaryData] = useState<any | null>(null)- const [summaryCompareData, setSummaryCompareData] = useState<any | null>(null)- const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)- const [analyticsLoading, setAnalyticsLoading] = useState(true)- const [dataLoading, setDataLoading] = useState(false)-- const rotateXAxis = useMemo(() => size.width > 0 && size.width < 500, [size])+ // Track if we've ever shown actual content to prevent NoCaptchaEvents flash+ const hasShownContentRef = useRef(false)++ const summaryQuery = useSummaryQuery('captcha')+ const compareSummaryQuery = useCompareSummaryQuery('captcha')+ const timeseriesQuery = useTimeseriesQuery('captcha')++ const summary = summaryQuery.data?.data+ const summaryData = summary?.current ?? null+ // Custom compare range when compare mode is active; otherwise the previous+ // period returned alongside the summary (null for period=all)+ const summaryCompareData =+ compareSummaryQuery.data?.data.current ?? summary?.previous ?? null++ const chartData = useMemo(+ () => pivotCaptchaTimeseries(timeseriesQuery.data?.data),+ [timeseriesQuery.data],+ )const dataNames = useMemo(() => ({@@ -138,147 +119,111 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {[t],)- const filters = useMemo<Filter[]>(() => {- return parseFilters(searchParams)- }, [searchParams])-const tnMapping = captchaTypeNameMapping(t)- const [ref] = useSize() as any- useEffect(() => {- isMountedRef.current = true- return () => {- isMountedRef.current = false- }- }, [])-- const getFormatDate = (date: Date) => {- const yyyy = date.getFullYear()- let mm: string | number = date.getMonth() + 1- let dd: string | number = date.getDate()- if (dd < 10) dd = `0${dd}`- if (mm < 10) mm = `0${mm}`- return `${yyyy}-${mm}-${dd}`+ const summaryLoaded = Boolean(summaryQuery.data)++ const isPanelsDataEmptyRaw =+ summaryLoaded && !summaryData?.generated && !summaryData?.passed++ if (summaryLoaded && !isPanelsDataEmptyRaw) {+ hasShownContentRef.current = true}- const loadCaptcha = async () => {- setDataLoading(true)+ const isPanelsDataEmpty = isPanelsDataEmptyRaw && !hasShownContentRef.current++ const isInitialLoading =+ (summaryQuery.isLoading || timeseriesQuery.isLoading) &&+ !hasShownContentRef.current++ const panels = useMemo(+ () =>+ _map(PANELS_ORDER, (dimension) => ({+ dimension,+ name: tnMapping[dimension],+ subTabs: [+ { id: dimension, label: tnMapping[dimension], dimension },+ ] as BreakdownSubTab[],+ })),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [t],+ )- try {- let from = ''- let to = ''+ const formatReason = useCallback(+ (value?: string | null) =>+ value+ ? t(`project.captchaAnalytics.reasons.${value}`, {+ defaultValue: value,+ })+ : 'N/A',+ [t],+ )- if (dateRange) {- from = getFormatDate(dateRange[0])- to = getFormatDate(dateRange[1])+ const formatDifficulty = useCallback(+ (value?: string | null) => {+ switch (Number(value)) {+ case 2:+ return t('project.settings.captcha.difficultyLevels.veryEasy')+ case 3:+ return t('project.settings.captcha.difficultyLevels.easy')+ case 4:+ return t('project.settings.captcha.difficultyLevels.medium')+ case 5:+ return t('project.settings.captcha.difficultyLevels.hard')+ case 6:+ return t('project.settings.captcha.difficultyLevels.veryHard')+ default:+ return t('project.captchaAnalytics.difficultyValue', { value })}+ },+ [t],+ )- const requestParams = {- timeBucket,- period: period === 'custom' && dateRange ? '' : period,- filters,- from: period === 'custom' && dateRange ? from : '',- to: period === 'custom' && dateRange ? to : '',- }- const compareFrom = searchParams.get('compareFrom') || ''- const compareTo = searchParams.get('compareTo') || ''- const compareEnabled =- searchParams.get('compare') === 'true' && compareFrom && compareTo- const shouldFetchCustomCompare =- compareEnabled && activePeriodCompare !== 'previous'-- const [data, compareData] = await Promise.all([- captchaProxy.fetchCaptcha(projectId, requestParams),- shouldFetchCustomCompare- ? captchaProxy.fetchCaptcha(projectId, {- ...requestParams,- period: '',- from: compareFrom,- to: compareTo,- })- : Promise.resolve(null),- ])-- if (!isMountedRef.current) return-- if (_isEmpty(data)) {- setAnalyticsLoading(false)- setDataLoading(false)- setIsPanelsDataEmpty(true)- setChartData(null)- setSummaryData(null)- setSummaryCompareData(null)- return+ const rowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const { name: entryName, cc } = entry++ if (subTabId === 'country') {+ if (cc !== undefined) {+ return (+ <CCRow cc={cc} name={entryName || undefined} language={language} />+ )+ }+ return <CCRow cc={entryName} language={language} />}- const { params, chart, summary, previousSummary } = data-- if (chart && chart.x) {- setChartData(chart)- } else {- setChartData(null)+ if (+ subTabId === 'browser' ||+ subTabId === 'os' ||+ subTabId === 'device'+ ) {+ const v1Tab =+ subTabId === 'browser' ? 'br' : subTabId === 'os' ? 'os' : 'dv'+ const mapper = getDeviceRowMapper(v1Tab, theme, t) as+ | ((entry: Entry) => React.ReactNode)+ | undefined+ return mapper ? mapper(entry) : entryName}- const hasData =- !_isEmpty(params) || !_isEmpty(chart?.x) || !_isEmpty(summary)-- setPanelsData({- types: PANELS_ORDER,- data: params || {},- })- setIsPanelsDataEmpty(!hasData)-- setSummaryData(summary || null)- setSummaryCompareData(- shouldFetchCustomCompare- ? compareData?.summary || null- : previousSummary || null,- )- setAnalyticsLoading(false)- setDataLoading(false)- } catch (reason) {- if (!isMountedRef.current) return- setAnalyticsLoading(false)- setDataLoading(false)- setIsPanelsDataEmpty(true)- setChartData(null)- setSummaryData(null)- setSummaryCompareData(null)- console.error('[ERROR](loadCaptcha) Loading captcha data failed:', reason)- }- }+ if (subTabId === 'captcha_event') {+ return t(`project.captchaAnalytics.events.${entryName}`, {+ defaultValue: entryName ?? 'N/A',+ })+ }- useEffect(() => {- loadCaptcha()- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [filters, dateRange, period, timeBucket, projectId, activePeriodCompare])+ if (subTabId === 'captcha_reason') {+ return formatReason(entryName)+ }- // Refresh captcha data when refresh button is clicked- useEffect(() => {- if (captchaRefreshTrigger > 0) {- loadCaptcha()- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [captchaRefreshTrigger])-- const getFilterLink = (column: string, value: string | null) => {- const isFilterActive =- filters.findIndex(- (filter) => filter.column === column && filter.filter === value,- ) >= 0- const newSearchParams = new URLSearchParams(searchParams.toString())-- if (isFilterActive) {- newSearchParams.delete(column, value ?? 'null')- } else {- newSearchParams.append(column, value ?? 'null')- }+ if (subTabId === 'captcha_difficulty') {+ return formatDifficulty(entryName)+ }- return { search: newSearchParams.toString() }- }+ return entryName+ },+ [language, theme, t, formatReason, formatDifficulty],+ )- // Check if we have existing data- const hasExistingData = chartData !== null || !_isEmpty(panelsData.types)const formatNumber = (value: number, type: 'main' | 'badge') =>`${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`const isFiniteNumber = (value: unknown): value is number =>@@ -297,26 +242,7 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {value ? `${Number(value).toFixed(2)}s` : 'N/A'const formatSecondsChange = (value: number) =>`${value > 0 ? '+' : value < 0 ? '-' : ''}${Math.abs(Number(value || 0)).toFixed(2)}s`- const formatReason = (value?: string | null) =>- value- ? t(`project.captchaAnalytics.reasons.${value}`, { defaultValue: value })- : 'N/A'- const formatDifficulty = (value?: string | null) => {- switch (Number(value)) {- case 2:- return t('project.settings.captcha.difficultyLevels.veryEasy')- case 3:- return t('project.settings.captcha.difficultyLevels.easy')- case 4:- return t('project.settings.captcha.difficultyLevels.medium')- case 5:- return t('project.settings.captcha.difficultyLevels.hard')- case 6:- return t('project.settings.captcha.difficultyLevels.veryHard')- default:- return t('project.captchaAnalytics.difficultyValue', { value })- }- }+const summaryCards = summaryData? [{@@ -339,13 +265,13 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {},{label: t('project.captchaAnalytics.passRate'),- value: summaryData.passRate,- change: summaryCompareData- ? isFiniteNumber(summaryData.passRate) &&- isFiniteNumber(summaryCompareData.passRate)+ value: summaryData.passRate as number,+ change:+ summaryCompareData &&+ isFiniteNumber(summaryData.passRate) &&+ isFiniteNumber(summaryCompareData.passRate)? summaryData.passRate - summaryCompareData.passRate- : undefined- : undefined,+ : undefined,goodChangeDirection: 'down' as const,valueMapper: formatPercent,},@@ -354,9 +280,9 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {value: summaryData.solveP50 || 0,change:summaryCompareData &&- summaryData.solveP50 > 0 &&- summaryCompareData.solveP50 > 0- ? summaryData.solveP50 - summaryCompareData.solveP50+ (summaryData.solveP50 || 0) > 0 &&+ (summaryCompareData.solveP50 || 0) > 0+ ? (summaryData.solveP50 || 0) - (summaryCompareData.solveP50 || 0): undefined,goodChangeDirection: 'up' as const,valueMapper: (value: number, type: 'main' | 'badge') =>@@ -372,26 +298,29 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {return <WaitingForCaptchaEvent />}- // Show Loader only on initial load (no existing data)- if (analyticsLoading && !hasExistingData) {+ const headerRightContent = <ProjectViewHeaderActions tnMapping={tnMapping} />++ if (isInitialLoading) {return (- <div- className={cx('flex flex-col bg-gray-50 dark:bg-slate-950', {- 'min-h-including-header': !isEmbedded,- 'min-h-screen': isEmbedded,- })}- >- <Loader />- </div>+ <>+ <DashboardHeader+ showLiveVisitors={false}+ rightContent={headerRightContent}+ />+ <div className='relative overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>+ <MetricCardsSkeleton />+ <ChartSkeleton className='mt-4 h-80 md:h-80' />+ </div>+ </>)}- if (isPanelsDataEmpty && !dataLoading) {+ if (isPanelsDataEmpty) {return (<><DashboardHeadershowLiveVisitors={false}- rightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}+ rightContent={headerRightContent}/><NoCaptchaEvents filters={filters} /></>@@ -402,248 +331,49 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {<><DashboardHeadershowLiveVisitors={false}- rightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}+ rightContent={headerRightContent}/>- <div ref={ref}>- {dataLoading && hasExistingData ? <LoadingBar /> : null}- <div>- <Filters className='mb-3' tnMapping={tnMapping} />- {chartData ? (- <CaptchaChart- chart={chartData}- timeBucket={timeBucket}- timeFormat={timeFormat}- rotateXAxis={rotateXAxis}- chartType={chartTypes.line}- dataNames={dataNames}- >- {summaryCards.length ? (- <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>- {summaryCards.map((card) => (- <MetricCard- key={card.label}- label={card.label}- value={card.value}- change={card.change}- goodChangeDirection={card.goodChangeDirection}- valueMapper={card.valueMapper}- />- ))}- </div>- ) : null}- </CaptchaChart>- ) : null}- <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>- {panelsData.types- ? _map(PANELS_ORDER, (type: keyof typeof tnMapping) => {- const panelName = tnMapping[type]- const panelIcon = panelIconMapping[type]- const panelData = panelsData.data?.[type] || []-- if (type === 'cc') {- const rowMapper = (entry: any) => {- const { name: entryName, cc } = entry- if (cc) {- return (- <CCRow cc={cc} name={entryName} language={language} />- )- }- return <CCRow cc={entryName} language={language} />- }-- return (- <Panel- key={type}- icon={panelIcon}- id={type}- getFilterLink={getFilterLink}- name={panelName}- data={panelData}- rowMapper={rowMapper}- activeTabId={type}- />- )- }-- if (type === 'dv') {- return (- <Panel- key={type}- icon={panelIcon}- id={type}- getFilterLink={getFilterLink}- name={panelName}- data={panelData}- rowMapper={(entry: {- name: keyof typeof deviceIconMapping- }) => {- const { name: entryName } = entry- const icon = deviceIconMapping[entryName]- if (!icon) {- return entryName- }- return (- <>- {icon}- - {entryName}- </>- )- }}- capitalize- activeTabId={type}- />- )- }-- if (type === 'br') {- const rowMapper = (entry: any) => {- const { name: entryName } = entry- // @ts-expect-error- const logoUrl = BROWSER_LOGO_MAP[entryName]- if (!logoUrl) {- return (- <>- <GlobeIcon className='h-5 w-5' />- - {entryName}- </>- )- }- return (- <>- <img src={logoUrl} className='h-5 w-5' alt='' />- - {entryName}- </>- )- }-- return (- <Panel- key={type}- icon={panelIcon}- id={type}- getFilterLink={getFilterLink}- name={panelName}- data={panelData}- rowMapper={rowMapper}- activeTabId={type}- />- )- }-- if (type === 'os') {- const rowMapper = (entry: any) => {- const { name: entryName } = entry- // @ts-expect-error- const logoUrlLight = OS_LOGO_MAP[entryName]- // @ts-expect-error- const logoUrlDark = OS_LOGO_MAP_DARK[entryName]- let logoUrl =- theme === 'dark' ? logoUrlDark : logoUrlLight- logoUrl ||= logoUrlLight-- if (!logoUrl) {- return (- <>- <GlobeIcon className='h-5 w-5' />- - {entryName}- </>- )- }-- return (- <>- <img- src={logoUrl}- className='h-5 w-5 dark:fill-gray-50'- alt=''- />- - {entryName}- </>- )- }-- return (- <Panel- key={type}- icon={panelIcon}- id={type}- getFilterLink={getFilterLink}- name={panelName}- data={panelData}- rowMapper={rowMapper}- activeTabId={type}- />- )- }-- if (type === 'captcha_event') {- return (- <Panel- key={type}- icon={panelIcon}- id={type}- getFilterLink={getFilterLink}- name={panelName}- data={panelData}- rowMapper={(entry: any) =>- t(`project.captchaAnalytics.events.${entry.name}`, {- defaultValue: entry.name,- })- }- activeTabId={type}- />- )- }-- if (type === 'captcha_reason') {- return (- <Panel- key={type}- icon={panelIcon}- id={type}- getFilterLink={getFilterLink}- name={panelName}- data={panelData}- rowMapper={(entry: any) => formatReason(entry.name)}- activeTabId={type}- />- )- }-- if (type === 'captcha_difficulty') {- return (- <Panel- key={type}- icon={panelIcon}- id={type}- getFilterLink={getFilterLink}- name={panelName}- data={panelData}- rowMapper={(entry: any) => formatDifficulty(entry.name)}- activeTabId={type}- />- )- }-- return (- <Panel- key={type}- icon={panelIcon}- id={type}- getFilterLink={getFilterLink}- name={panelName}- data={panelData}- activeTabId={type}- />- )- })- : null}- </div>+ <div>+ <Filters className='mb-3' tnMapping={tnMapping} />+ {!_isEmpty(chartData.x) ? (+ <CaptchaChart+ chart={chartData}+ timeBucket={timeBucket}+ timeFormat={timeFormat}+ rotateXAxis={rotateXAxis}+ chartType={chartTypes.line}+ dataNames={dataNames}+ >+ {summaryCards.length ? (+ <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>+ {summaryCards.map((card) => (+ <MetricCard+ key={card.label}+ label={card.label}+ value={card.value}+ change={card.change}+ goodChangeDirection={card.goodChangeDirection}+ valueMapper={card.valueMapper}+ />+ ))}+ </div>+ ) : null}+ </CaptchaChart>+ ) : null}+ <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>+ {panels.map((panel) => (+ <BreakdownPanel+ key={panel.dimension}+ dataType='captcha'+ panelId={panel.dimension}+ name={panel.name}+ icon={panelIconMapping[panel.dimension]}+ subTabs={panel.subTabs}+ primaryMetric='events'+ rowMapper={rowMapper}+ capitalize={['device']}+ />+ ))}</div></div></>diff --git a/web/app/pages/Project/tabs/Captcha/NoCaptchaEvents.tsx b/web/app/pages/Project/tabs/Captcha/NoCaptchaEvents.tsxindex f35c85236..74cfb2cf4 100644--- a/web/app/pages/Project/tabs/Captcha/NoCaptchaEvents.tsx+++ b/web/app/pages/Project/tabs/Captcha/NoCaptchaEvents.tsx@@ -3,15 +3,15 @@ import _isEmpty from 'lodash/isEmpty'import { memo } from 'react'import { useTranslation } from 'react-i18next'+import { V2Filter } from '~/api/v2/types'import { Text } from '~/ui/Text'import Filters from '../../View/components/Filters'-import { Filter } from '../../View/interfaces/traffic'import { captchaTypeNameMapping } from './CaptchaView'interface NoCaptchaEventsProps {- filters: Filter[]+ filters: V2Filter[]}const NoCaptchaEvents = ({ filters }: NoCaptchaEventsProps) => {diff --git a/web/app/pages/Project/tabs/Captcha/adapters.ts b/web/app/pages/Project/tabs/Captcha/adapters.tsnew file mode 100644index 000000000..519925747--- /dev/null+++ b/web/app/pages/Project/tabs/Captcha/adapters.ts@@ -0,0 +1,42 @@+import { TimeseriesRow } from '~/api/v2/types'++/**+ * v2 ISO timestamp -> the 'YYYY-MM-DD HH:mm:ss' wall-time string the chart+ * pipeline expects. The timestamp is already in the requested timezone, so we+ * take its literal date-time part instead of letting Date/dayjs re-shift it+ * into the browser timezone.+ */+const toChartX = (timestamp: string): string =>+ timestamp.slice(0, 19).replace('T', ' ')++export interface CaptchaChartData {+ x: string[]+ generated: number[]+ passed: number[]+ failed: number[]+ validationFailed: number[]+ replayed: number[]+}++/** Captcha timeseries rows -> the columnar shape getSettingsCaptcha consumes */+export const pivotCaptchaTimeseries = (+ rows: TimeseriesRow[] | undefined,+): CaptchaChartData => {+ const x: string[] = []+ const generated: number[] = []+ const passed: number[] = []+ const failed: number[] = []+ const validationFailed: number[] = []+ const replayed: number[] = []++ for (const row of rows || []) {+ x.push(toChartX(row.timestamp))+ generated.push(Number(row.generated ?? 0))+ passed.push(Number(row.passed ?? 0))+ failed.push(Number(row.failed ?? 0))+ validationFailed.push(Number(row.validation_failed ?? 0))+ replayed.push(Number(row.replayed ?? 0))+ }++ return { x, generated, passed, failed, validationFailed, replayed }+}diff --git a/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx b/web/app/pages/Project/tabs/Errors/ErrorDetails.tsxindex d41160eef..972208d42 100644--- a/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx+++ b/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx@@ -9,22 +9,17 @@ import {UsersIcon,CaretRightIcon,} from '@phosphor-icons/react'-import { useMemo, useState, useEffect, useCallback, useRef } from 'react'+import { useMemo, useState, useEffect, useRef } from 'react'import { useTranslation } from 'react-i18next'import { Link } from '~/ui/Link'import { useLocation } from 'react-router'-import type {- ErrorAffectedSession,- ErrorDetailsResponse,-} from '~/api/api.server'-import { useErrorSessionsProxy } from '~/hooks/useAnalyticsProxy'+import { useErrorSessionsQuery } from '~/hooks/v2/useV2Queries'import {BROWSER_LOGO_MAP,OS_LOGO_MAP,OS_LOGO_MAP_DARK,} from '~/lib/constants'-import { useCurrentProject } from '~/providers/CurrentProjectProvider'import { useTheme } from '~/providers/ThemeProvider'import { Badge } from '~/ui/Badge'import Flag from '~/ui/Flag'@@ -35,16 +30,13 @@ import { Text } from '~/ui/Text'import { getRelativeDateIfPossible } from '~/utils/date'import { cn } from '~/utils/generic'+import type { ErrorDetailsInfo, ErrorSessionItem } from './types'+const STACK_PREVIEW_LINES_COUNT = 5interface ErrorDetailsProps {- details: ErrorDetailsResponse['details']+ details: ErrorDetailsInfochart?: React.ReactNode- period?: string- from?: string- to?: string- timeBucket?: string- projectPassword?: string}const BrowserIcon = ({ browser }: { browser: string | null }) => {@@ -148,7 +140,7 @@ const ToolbarButton = ({)interface SessionRowProps {- session: ErrorAffectedSession+ session: ErrorSessionItemonClick?: () => void}@@ -178,10 +170,10 @@ const SessionRow = ({ session, onClick }: SessionRowProps) => {><div className='flex min-w-0 flex-1 items-center gap-3'><div className='flex shrink-0 items-center gap-1.5'>- {session.cc ? (+ {session.country ? (<FlagclassName='rounded-xs'- country={session.cc}+ country={session.country}size={16}alt=''aria-hidden='true'@@ -189,7 +181,7 @@ const SessionRow = ({ session, onClick }: SessionRowProps) => {) : (<span className='inline-block size-4 rounded-xs bg-gray-200 dark:bg-slate-800' />)}- <BrowserIcon browser={session.br} />+ <BrowserIcon browser={session.browser} /><OSIcon os={session.os} theme={theme} /></div><div className='flex min-w-0 flex-col'>@@ -215,40 +207,29 @@ const SessionRow = ({ session, onClick }: SessionRowProps) => {)}-export const ErrorDetails = ({- details,- chart,- period = '7d',- from = '',- to = '',- timeBucket = 'hour',-}: ErrorDetailsProps) => {+export const ErrorDetails = ({ details, chart }: ErrorDetailsProps) => {const { t } = useTranslation('common')- const { id } = useCurrentProject()- const { fetchErrorSessions } = useErrorSessionsProxy()const [isStackTraceExpanded, setIsStackTraceExpanded] = useState(false)const [isCopiedStack, setIsCopiedStack] = useState(false)const [isCopiedEid, setIsCopiedEid] = useState(false)const [isCopiedFile, setIsCopiedFile] = useState(false)- const [sessions, setSessions] = useState<ErrorAffectedSession[]>([])- const [sessionsLoading, setSessionsLoading] = useState<boolean | null>(null)- const [sessionsTotal, setSessionsTotal] = useState(0)- const [sessionsSkip, setSessionsSkip] = useState(0)const [isSessionsModalOpened, setIsSessionsModalOpened] = useState(false)const sessionsModalListRef = useRef<HTMLDivElement | null>(null)- const isMountedRef = useRef(true)const SESSIONS_PREVIEW_COUNT = 5- const SESSIONS_MODAL_TAKE = 25- useEffect(() => {- isMountedRef.current = true- return () => {- isMountedRef.current = false- }- }, [])+ const sessionsQuery = useErrorSessionsQuery(details.eid)+ const sessions = useMemo(+ () =>+ (sessionsQuery.data?.pages.flatMap((page) => page.data) ||+ []) as ErrorSessionItem[],+ [sessionsQuery.data],+ )+ const sessionsLoading = sessionsQuery.isLoading+ const canLoadMoreSessions = Boolean(sessionsQuery.hasNextPage)+ const sessionsCountLabel = `${sessions.length.toLocaleString()}${canLoadMoreSessions ? '+' : ''}`const status: { label: string; colour: 'red' | 'yellow' | 'slate' } =useMemo(() => {@@ -265,7 +246,6 @@ export const ErrorDetails = ({() => (details.stackTrace ? details.stackTrace.split('\n') : []),[details.stackTrace],)- const canLoadMoreSessions = sessions.length < sessionsTotalconst fileLocation = useMemo(() => {if (!details.filename) return ''@@ -279,6 +259,7 @@ export const ErrorDetails = ({setIsCopiedStack(false)setIsCopiedEid(false)setIsCopiedFile(false)+ setIsSessionsModalOpened(false)// eslint-disable-next-line react-hooks/exhaustive-deps}, [details.eid])@@ -318,63 +299,6 @@ export const ErrorDetails = ({}}- const loadSessions = useCallback(- async (reset = false) => {- if (sessionsLoading) return-- setSessionsLoading(true)- const skip = reset ? 0 : sessionsSkip-- try {- const result = await fetchErrorSessions(id, details.eid, {- timeBucket,- period,- from,- to,- take: reset ? SESSIONS_PREVIEW_COUNT : SESSIONS_MODAL_TAKE,- skip,- })-- if (!isMountedRef.current) return-- if (result) {- if (reset) {- setSessions(result.sessions)- } else {- setSessions((prev) => [...prev, ...result.sessions])- }- setSessionsTotal(result.total)- setSessionsSkip(skip + result.sessions.length)- }- } catch (reason) {- console.error('[ErrorDetails] Failed to load sessions:', reason)- } finally {- if (isMountedRef.current) {- setSessionsLoading(false)- }- }- },- [- id,- details.eid,- timeBucket,- period,- from,- to,- sessionsLoading,- sessionsSkip,- fetchErrorSessions,- ],- )-- useEffect(() => {- setSessions([])- setSessionsSkip(0)- setIsSessionsModalOpened(false)- loadSessions(true)- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [details.eid, period, from, to])-const formatStackTraceLine = (line: string) => {const atMatch = line.match(/(\s*at\s+)([^(]+)(\s*\(([^)]+)\))?/)const fileMatch = line.match(/([^:]+):(\d+):(\d+)/)@@ -586,11 +510,7 @@ export const ErrorDetails = ({</span>}meta={- sessionsTotal > 0- ? sessionsTotal.toLocaleString()- : sessionsLoading && sessions.length === 0- ? '…'- : '0'+ sessionsLoading && sessions.length === 0 ? '…' : sessionsCountLabel}>{sessionsLoading && sessions.length === 0 ? (@@ -610,14 +530,15 @@ export const ErrorDetails = ({<SessionRow key={session.psid} session={session} />))}</div>- {sessionsTotal > SESSIONS_PREVIEW_COUNT ? (+ {sessions.length > SESSIONS_PREVIEW_COUNT ||+ canLoadMoreSessions ? (<buttontype='button'onClick={() => setIsSessionsModalOpened(true)}className='flex w-full items-center justify-center gap-1.5 border-t border-gray-200 px-4 py-2 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100/60 hover:text-gray-900 dark:border-slate-800/60 dark:text-slate-400 dark:hover:bg-slate-800/40 dark:hover:text-slate-200'>{t('project.showAllXSessions', {- x: sessionsTotal.toLocaleString(),+ x: sessionsCountLabel,})}</button>) : null}@@ -635,7 +556,7 @@ export const ErrorDetails = ({<UsersIcon className='size-4 text-gray-500 dark:text-slate-400' />{t('project.affectedSessionsList')}<Text size='xs' colour='muted' className='font-mono font-normal'>- {sessionsTotal.toLocaleString()}+ {sessionsCountLabel}</Text></span>}@@ -655,9 +576,9 @@ export const ErrorDetails = ({</div><InfiniteScrollTriggerhasMore={canLoadMoreSessions}- isLoading={!!sessionsLoading}- onLoadMore={() => loadSessions()}- disabled={!!sessionsLoading}+ isLoading={sessionsQuery.isFetchingNextPage}+ onLoadMore={() => sessionsQuery.fetchNextPage()}+ disabled={sessionsQuery.isFetching}root={sessionsModalListRef}/></div>diff --git a/web/app/pages/Project/tabs/Errors/ErrorsMap.tsx b/web/app/pages/Project/tabs/Errors/ErrorsMap.tsxnew file mode 100644index 000000000..0b44dbbc7--- /dev/null+++ b/web/app/pages/Project/tabs/Errors/ErrorsMap.tsx@@ -0,0 +1,82 @@+import { Suspense, lazy, useMemo } from 'react'+import { useNavigate } from 'react-router'++import { useBreakdownQuery } from '~/hooks/v2/useV2Queries'+import { Entry } from '~/lib/models/Entry'+import { MapLoader } from '~/pages/Project/View/components/MapLoader'+import { mapBreakdownRows } from '~/pages/Project/View/v2/adapters'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'++const InteractiveMap = lazy(+ () => import('~/pages/Project/View/components/InteractiveMap'),+)++const MAP_CLICK_TYPE_TO_DIMENSION = { cc: 'country', rg: 'region' } as const++interface ErrorsMapProps {+ /** Static per-error data (details view); when set, no queries are fired */+ staticCountryData?: Entry[]+ staticRegionData?: Entry[]+}++/**+ * Error occurrences location map. Project-wide it feeds itself via country ++ * region breakdown queries (deduped with the location panel's queries through+ * the react-query cache); on the error-details view it renders the per-error+ * `params` payload passed in statically.+ */+export const ErrorsMap = ({+ staticCountryData,+ staticRegionData,+}: ErrorsMapProps) => {+ const navigate = useNavigate()+ const { getFilterLink } = useViewProjectContext()+ const isStatic = Boolean(staticCountryData)++ const countryQuery = useBreakdownQuery('errors', {+ dimension: 'country',+ limit: 100,+ sort: 'occurrences:desc',+ enabled: !isStatic,+ })+ const regionQuery = useBreakdownQuery('errors', {+ dimension: 'region',+ limit: 100,+ sort: 'occurrences:desc',+ enabled: !isStatic,+ })++ const countryData = useMemo(+ () =>+ staticCountryData ??+ mapBreakdownRows(countryQuery.data?.data, 'occurrences'),+ [staticCountryData, countryQuery.data],+ )+ const regionData = useMemo(+ () =>+ staticRegionData ??+ mapBreakdownRows(regionQuery.data?.data, 'occurrences'),+ [staticRegionData, regionQuery.data],+ )+ const total = useMemo(+ () => countryData.reduce((acc, curr) => acc + curr.count, 0),+ [countryData],+ )++ if (!isStatic && countryQuery.isLoading) {+ return <MapLoader />+ }++ return (+ <Suspense fallback={<MapLoader />}>+ <InteractiveMap+ data={countryData}+ regionData={regionData}+ total={total}+ onClick={(mapType, key) => {+ navigate(getFilterLink(MAP_CLICK_TYPE_TO_DIMENSION[mapType], key))+ }}+ />+ </Suspense>+ )+}diff --git a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx b/web/app/pages/Project/tabs/Errors/ErrorsView.tsxindex 274e92ceb..a16d156bd 100644--- a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx+++ b/web/app/pages/Project/tabs/Errors/ErrorsView.tsx@@ -1,9 +1,9 @@+import { useQueryClient } from '@tanstack/react-query'import type { ChartOptions } from 'billboard.js'import { area, bar } from 'billboard.js'import cx from 'clsx'import * as d3 from 'd3'import dayjs from 'dayjs'-import _debounce from 'lodash/debounce'import _isEmpty from 'lodash/isEmpty'import _map from 'lodash/map'import _size from 'lodash/size'@@ -15,39 +15,20 @@ import {WarningIcon,UserIcon,} from '@phosphor-icons/react'-import {- useState,- useEffect,- useMemo,- useRef,- useCallback,- lazy,- Suspense,- use,-} from 'react'-import { useIsPresent } from 'motion/react'+import { useState, useEffect, useMemo, useRef, useCallback } from 'react'import { useTranslation } from 'react-i18next'import { Link } from '~/ui/Link'-import {- useLocation,- useSearchParams,- useNavigate,- useFetcher,- useLoaderData,- useRevalidator,- type LinkProps,-} from 'react-router'+import { useLocation, useSearchParams, useFetcher } from 'react-router'import { ClientOnly } from 'remix-utils/client-only'-import { MapLoader } from '~/pages/Project/View/components/MapLoader'import { toast } from 'sonner'-import type {- ErrorsResponse,- ErrorDetailsResponse,- ErrorOverviewResponse,-} from '~/api/api.server'-import { useErrorsProxy } from '~/hooks/useAnalyticsProxy'+import type { ErrorListItem } from '~/api/v2/types'+import {+ useErrorDetailsQuery,+ useErrorsListQuery,+ useErrorsOverviewQuery,+} from '~/hooks/v2/useV2Queries'import {TimeFormat,tbsFormatMapper,@@ -55,14 +36,18 @@ import {tbsFormatMapperTooltip,tbsFormatMapperTooltip24h,chartTypes,- ERROR_PANELS_ORDER,} from '~/lib/constants'-import { CountryEntry, Entry } from '~/lib/models/Entry'-import { SwetrixError } from '~/lib/models/Project'+import { Entry } from '~/lib/models/Entry'import { ErrorChart } from '~/pages/Project/tabs/Errors/ErrorChart'import { ErrorDetails } from '~/pages/Project/tabs/Errors/ErrorDetails'+import { ErrorsMap } from '~/pages/Project/tabs/Errors/ErrorsMap'import NoErrorDetails from '~/pages/Project/tabs/Errors/NoErrorDetails'+import type {+ ErrorDetailsData,+ ErrorsOverviewData,+} from '~/pages/Project/tabs/Errors/types'import WaitingForAnError from '~/pages/Project/tabs/Errors/WaitingForAnError'+import PageLinkRow from '~/pages/Project/tabs/Traffic/PageLinkRow'import { SessionsDrawer } from '~/pages/Project/tabs/Traffic/SessionsDrawer'import CCRow from '~/pages/Project/View/components/CCRow'import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'@@ -70,14 +55,16 @@ import Filters from '~/pages/Project/View/components/Filters'import NoEvents from '~/pages/Project/View/components/NoEvents'import ProjectViewHeaderActions from '~/pages/Project/View/components/ProjectViewHeaderActions'import TabErrorBoundary from '~/pages/Project/View/components/TabErrorBoundary'-import { Panel, MetadataPanel } from '~/pages/Project/View/Panels'+import { MetadataPanel, Panel } from '~/pages/Project/View/Panels'import { ERROR_FILTERS_MAPPING } from '~/pages/Project/View/utils/filters'+import { BreakdownSubTab } from '~/pages/Project/View/v2/BreakdownPanel'import {- useViewProjectContext,- useRefreshTriggers,-} from '~/pages/Project/View/ViewProject'+ ChartSkeleton,+ PanelSkeleton,+ RefetchIndicator,+} from '~/pages/Project/View/v2/loading'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'import {- getFormatDate,typeNameMapping,panelIconMapping,getDeviceRowMapper,@@ -89,31 +76,19 @@ import {getChartPointWindow,type ChartDataPointClick,} from '~/pages/Project/View/utils/chartPoint'-import {- useCurrentProject,- useProjectPassword,-} from '~/providers/CurrentProjectProvider'+import { useCurrentProject } from '~/providers/CurrentProjectProvider'import { useTheme } from '~/providers/ThemeProvider'-import type {- ProjectViewActionData,- ProjectLoaderData,-} from '~/routes/projects.$id'+import type { ProjectViewActionData } from '~/routes/projects.$id'import { Badge } from '~/ui/Badge'import BillboardChart from '~/ui/BillboardChart'import Checkbox from '~/ui/Checkbox'import Dropdown from '~/ui/Dropdown'import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'import Loader from '~/ui/Loader'-import LoadingBar from '~/ui/LoadingBar'import { Text } from '~/ui/Text'import Tooltip from '~/ui/Tooltip'import { getRelativeDateIfPossible } from '~/utils/date'import { getLocaleDisplayName, nFormatter } from '~/utils/generic'-import { LoaderView } from '../../View/components/LoaderView'--const InteractiveMap = lazy(- () => import('~/pages/Project/View/components/InteractiveMap'),-)const calculateOptimalTicks = (data: number[],@@ -323,6 +298,177 @@ const getErrorTrendsChartSettings = (}}+// Sub-tab ids (v2 dimension names) -> keys of the per-error `params` payload+// (still v1-keyed in the details response)+const PER_ERROR_SUBTAB_TO_V1: Record<string, string> = {+ country: 'cc',+ region: 'rg',+ city: 'ct',+ locale: 'lc',+ page: 'pg',+ host: 'host',+ browser: 'br',+ os: 'os',+ device: 'dv',+ isp: 'isp',+ organization: 'og',+ user_type: 'ut',+ connection_type: 'ctp',+}++interface PerErrorPanelsProps {+ params: ErrorDetailsData['params']+ locationSubTabs: BreakdownSubTab[]+ pagesSubTabs: BreakdownSubTab[]+ devicesSubTabs: BreakdownSubTab[]+ networkSubTabs: BreakdownSubTab[]+ locationRowMapper: (entry: Entry, subTabId: string) => React.ReactNode+ pagesRowMapper: (entry: Entry, subTabId: string) => React.ReactNode+ devicesRowMapper: (entry: Entry, subTabId: string) => React.ReactNode+ networkRowMapper: (entry: Entry, subTabId: string) => React.ReactNode+ isRefetching: boolean+}++/**+ * Breakdown panels scoped to ONE error group. The v2 error-details response+ * still ships the per-error `params` payload (eid is not a filterable+ * dimension), so these are fed statically instead of via BreakdownPanel.+ */+const PerErrorPanels = ({+ params,+ locationSubTabs,+ pagesSubTabs,+ devicesSubTabs,+ networkSubTabs,+ locationRowMapper,+ pagesRowMapper,+ devicesRowMapper,+ networkRowMapper,+ isRefetching,+}: PerErrorPanelsProps) => {+ const { t } = useTranslation('common')+ const { getFilterLink, getVersionFilterLink } = useViewProjectContext()++ const [activeTabs, setActiveTabs] = useState({+ location: 'country',+ pages: 'page',+ devices: 'browser',+ network: 'isp',+ })++ const setPanelTab = (panel: keyof typeof activeTabs, tab: string) =>+ setActiveTabs((prev) => ({ ...prev, [panel]: tab }))++ const toEntries = (subTabId: string): Entry[] =>+ (params?.[PER_ERROR_SUBTAB_TO_V1[subTabId]] || []) as Entry[]++ const versionData = useMemo(() => {+ const browserVersions: Record<string, Entry[]> = {}+ const osVersions: Record<string, Entry[]> = {}++ for (const entry of (params?.brv || []) as any[]) {+ const { br, name, count } = entry+ if (!br) continue+ ;(browserVersions[br] ||= []).push({ name, count })+ }+ for (const entry of (params?.osv || []) as any[]) {+ const { os, name, count } = entry+ if (!os) continue+ ;(osVersions[os] ||= []).push({ name, count })+ }++ return { browserVersions, osVersions }+ }, [params])++ const panels: {+ panelKey: keyof typeof activeTabs+ name: string+ icon: React.ReactNode+ subTabs: BreakdownSubTab[]+ rowMapper: (entry: Entry, subTabId: string) => React.ReactNode+ }[] = [+ {+ panelKey: 'location',+ name: t('project.location'),+ icon: panelIconMapping.country,+ subTabs: locationSubTabs,+ rowMapper: locationRowMapper,+ },+ {+ panelKey: 'pages',+ name: t('project.pages'),+ icon: panelIconMapping.page,+ subTabs: pagesSubTabs,+ rowMapper: pagesRowMapper,+ },+ {+ panelKey: 'devices',+ name: t('project.devices'),+ icon: panelIconMapping.os,+ subTabs: devicesSubTabs,+ rowMapper: devicesRowMapper,+ },+ {+ panelKey: 'network',+ name: t('project.network'),+ icon: panelIconMapping.isp,+ subTabs: networkSubTabs,+ rowMapper: networkRowMapper,+ },+ ]++ return (+ <>+ {panels.map(({ panelKey, name, icon, subTabs, rowMapper }) => {+ const activeTabId = activeTabs[panelKey]++ return (+ <Panel+ key={`${panelKey}-${activeTabId}`}+ id={activeTabId}+ name={name}+ icon={icon}+ tabs={subTabs.map(({ id, label }) => ({ id, label }))}+ onTabChange={(tab) => setPanelTab(panelKey, tab)}+ activeTabId={activeTabId}+ data={toEntries(activeTabId)}+ rowMapper={(entry) => rowMapper(entry, activeTabId)}+ getFilterLink={getFilterLink}+ highlightColour='red'+ valuesHeaderName={t('project.occurrences')}+ isRefetching={isRefetching}+ customRenderer={+ activeTabId === 'map'+ ? () => (+ <ErrorsMap+ staticCountryData={toEntries('country')}+ staticRegionData={toEntries('region')}+ />+ )+ : undefined+ }+ capitalize={activeTabId === 'device'}+ versionData={+ activeTabId === 'browser'+ ? versionData.browserVersions+ : activeTabId === 'os'+ ? versionData.osVersions+ : undefined+ }+ getVersionFilterLink={(parent, version) =>+ getVersionFilterLink(+ parent,+ version,+ activeTabId === 'browser' ? 'browser' : 'os',+ )+ }+ />+ )+ })}+ </>+ )+}+interface StatCardProps {icon: React.ReactNodevalue: string | number@@ -346,7 +492,7 @@ const StatCard = ({ icon, value, label }: StatCardProps) => ()interface ErrorItemProps {- error: SwetrixError+ error: ErrorListItem}const ErrorItem = ({ error }: ErrorItemProps) => {@@ -517,86 +663,24 @@ const ErrorItem = ({ error }: ErrorItemProps) => {)}-const ERRORS_TAKE = 30--interface DeferredErrorsData {- errorsData: ErrorsResponse | null- errorDetails: ErrorDetailsResponse | null- errorOverview: ErrorOverviewResponse | null-}--function ErrorsDataResolver({- children,-}: {- children: (data: DeferredErrorsData) => React.ReactNode-}) {- const isPresent = useIsPresent()- const previousDataRef = useRef<DeferredErrorsData | null>(null)- const {- errorsData: errorsDataPromise,- errorDetails: errorDetailsPromise,- errorOverview: errorOverviewPromise,- } = useLoaderData<ProjectLoaderData>()- const shouldUsePreviousData = !isPresent && !!previousDataRef.current-- const errorsData = shouldUsePreviousData- ? previousDataRef.current!.errorsData- : errorsDataPromise- ? use(errorsDataPromise)- : null- const errorDetails = shouldUsePreviousData- ? previousDataRef.current!.errorDetails- : errorDetailsPromise- ? use(errorDetailsPromise)- : null- const errorOverview = shouldUsePreviousData- ? previousDataRef.current!.errorOverview- : errorOverviewPromise- ? use(errorOverviewPromise)- : null-- const deferredData = useMemo(- () => ({ errorsData, errorDetails, errorOverview }),- [errorsData, errorDetails, errorOverview],- )-- if (isPresent) {- previousDataRef.current = deferredData- }-- return <>{children(deferredData)}</>-}-function ErrorsViewWrapper() {const [searchParams] = useSearchParams()- const { errorsRefreshTrigger } = useRefreshTriggers()- const resetKey = `errors:${searchParams.toString()}:${errorsRefreshTrigger}`+ const resetKey = `errors:${searchParams.toString()}`return (<TabErrorBoundarytitleKey='dashboard.failedToLoadErrors'resetKey={resetKey}>- <Suspense fallback={<LoaderView />}>- <ErrorsDataResolver>- {(deferredData) => <ErrorsViewInner deferredData={deferredData} />}- </ErrorsDataResolver>- </Suspense>+ <ErrorsViewInner /></TabErrorBoundary>)}-interface ErrorsViewInnerProps {- deferredData: DeferredErrorsData-}--const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {+const ErrorsViewInner = () => {const { id, projectPath, allowedToManage, project } = useCurrentProject()- const projectPassword = useProjectPassword(id)- const revalidator = useRevalidator()- const errorsProxy = useErrorsProxy()- const { errorsRefreshTrigger } = useRefreshTriggers()- const { timeBucket, timeFormat, period, dateRange, timezone, filters, size } =+ const queryClient = useQueryClient()+ const { timeBucket, timeFormat, timezone, filters, size } =useViewProjectContext()const {t,@@ -604,48 +688,17 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {} = useTranslation('common')const { theme } = useTheme()const [searchParams] = useSearchParams()- const isEmbedded = searchParams.get('embedded') === 'true'- const navigate = useNavigate()const errorStatusFetcher = useFetcher<ProjectViewActionData>()const lastHandledStatusData = useRef<ProjectViewActionData | null>(null)- const pendingStatusUpdate = useRef<'resolved' | 'active' | null>(null)- const from = dateRange ? getFormatDate(dateRange[0]) : ''- const to = dateRange ? getFormatDate(dateRange[1]) : ''const tnMapping = typeNameMapping(t)const rotateXAxis = useMemo(() => size.width > 0 && size.width < 500, [size])- // Initialize state from deferred data- const initialDataProcessed = useRef(false)- const errorsProxyRequestRef = useRef<{- mode: 'append' | 'replace'- limit?: number- } | null>(null)- const preserveErrorsRevalidationRef = useRef(false)- const preserveErrorsRevalidationStartedRef = useRef(false)-const [errorOptions, setErrorOptions] = useState<Record<string, boolean>>({[ERROR_FILTERS_MAPPING.showResolved]: false,})+ const showResolved = errorOptions[ERROR_FILTERS_MAPPING.showResolved]- // Overview from loader- const overview = deferredData.errorOverview- const overviewLoading = revalidator.state === 'loading'-- const isMountedRef = useRef(true)-- const [errorsLoading, setErrorsLoading] = useState<boolean | null>(() =>- deferredData.errorsData ? false : null,- )- const [errors, setErrors] = useState<SwetrixError[]>(- () => deferredData.errorsData?.errors || [],- )- const [errorsSkip, setErrorsSkip] = useState(- () => deferredData.errorsData?.errors?.length || 0,- )- const [canLoadMoreErrors, setCanLoadMoreErrors] = useState(- () => (deferredData.errorsData?.errors?.length || 0) >= ERRORS_TAKE,- )const [sessionsDrawer, setSessionsDrawer] = useState<{from: stringto: string@@ -655,35 +708,25 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {const activeEID = useMemo(() => searchParams.get('eid'), [searchParams])- // Error details from loader- const activeError = useMemo(() => {- if (deferredData.errorDetails) {- return {- details: deferredData.errorDetails.details,- chart: deferredData.errorDetails.chart,- params: deferredData.errorDetails.params,- metadata: deferredData.errorDetails.metadata,- timeBucket: deferredData.errorDetails.timeBucket,- }- }- return null- }, [deferredData.errorDetails])-- const errorLoading = activeEID ? revalidator.state === 'loading' : false-- const errorStatusUpdating = errorStatusFetcher.state !== 'idle'+ // --- v2 queries ---- const [errorsActiveTabs, setErrorsActiveTabs] = useState<{- location: 'cc' | 'rg' | 'ct' | 'lc' | 'map'- page: 'pg' | 'host'- device: 'br' | 'os' | 'dv'- network: 'isp' | 'og' | 'ut' | 'ctp'- }>({- location: 'cc',- page: 'pg',- device: 'br',- network: 'isp',+ const errorsListQuery = useErrorsListQuery({+ showResolved,+ enabled: !activeEID,})+ const overviewQuery = useErrorsOverviewQuery({ enabled: !activeEID })+ const detailsQuery = useErrorDetailsQuery(activeEID)++ const errors = useMemo(+ () =>+ (errorsListQuery.data?.pages.flatMap((page) => page.data) ||+ []) as ErrorListItem[],+ [errorsListQuery.data],+ )+ const overview = overviewQuery.data?.data as ErrorsOverviewData | undefined+ const activeError = activeEID+ ? (detailsQuery.data?.data as ErrorDetailsData | undefined)+ : undefinedconst pureSearchParams = useMemo(() => {const newSearchParams = new URLSearchParams(searchParams.toString())@@ -691,142 +734,7 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {return newSearchParams.toString()}, [searchParams])- useEffect(() => {- isMountedRef.current = true- return () => {- isMountedRef.current = false- }- }, [])-- // Process deferred data on mount- useEffect(() => {- if (initialDataProcessed.current) return- initialDataProcessed.current = true-- if (deferredData.errorsData) {- const errorsList = deferredData.errorsData.errors || []- setErrors(errorsList)- setErrorsSkip(ERRORS_TAKE)- setCanLoadMoreErrors(errorsList.length >= ERRORS_TAKE)- } else {- setErrors([])- setCanLoadMoreErrors(false)- }- setErrorsLoading(false)- }, [deferredData])-- // Sync state when revalidation completes with new data- useEffect(() => {- if (!initialDataProcessed.current) return- if (revalidator.state === 'idle') {- if (preserveErrorsRevalidationRef.current) {- if (preserveErrorsRevalidationStartedRef.current) {- preserveErrorsRevalidationRef.current = false- preserveErrorsRevalidationStartedRef.current = false- setErrorsLoading(false)- }- return- }-- if (deferredData.errorsData) {- const errorsList = deferredData.errorsData.errors || []- setErrors(errorsList)- setErrorsSkip(ERRORS_TAKE)- setCanLoadMoreErrors(errorsList.length >= ERRORS_TAKE)- } else {- setErrors([])- setCanLoadMoreErrors(false)- }- setErrorsLoading(false)- } else if (revalidator.state === 'loading') {- if (preserveErrorsRevalidationRef.current) {- preserveErrorsRevalidationStartedRef.current = true- }- setErrorsLoading(true)- }- }, [revalidator.state, deferredData])-- // Load more errors via proxy- const loadMoreErrors = useCallback(() => {- if (errorsLoading || errorsProxy.isLoading) return-- errorsProxyRequestRef.current = { mode: 'append' }- errorsProxy.fetchErrors(id, {- timeBucket,- period: period === 'custom' ? '' : period,- from: from || undefined,- to: to || undefined,- timezone: timezone || '',- filters,- take: ERRORS_TAKE,- skip: errorsSkip,- options: errorOptions,- })- }, [- id,- timeBucket,- period,- from,- to,- timezone,- filters,- errorsSkip,- errorOptions,- errorsLoading,- errorsProxy,- ])-- // Handle proxy response for pagination- useEffect(() => {- if (revalidator.state === 'loading') return-- if (errorsProxy.data && !errorsProxy.isLoading) {- const proxyRequest = errorsProxyRequestRef.current- if (!proxyRequest) {- return- }-- const newErrors = errorsProxy.data.errors || []- if (proxyRequest.mode === 'replace') {- const visibleErrors = newErrors.slice(0, proxyRequest.limit)- setErrors(visibleErrors)- setErrorsSkip(visibleErrors.length)- setCanLoadMoreErrors(newErrors.length > (proxyRequest.limit || 0))- } else {- setErrors((prev) => [...prev, ...newErrors])- setErrorsSkip((prev) => prev + newErrors.length)- setCanLoadMoreErrors(newErrors.length >= ERRORS_TAKE)- }- setErrorsLoading(false)- errorsProxyRequestRef.current = null- }- if (errorsProxy.error) {- toast.error(errorsProxy.error)- setErrorsLoading(false)- errorsProxyRequestRef.current = null- }- }, [- errorsProxy.data,- errorsProxy.error,- errorsProxy.isLoading,- revalidator.state,- ])-- const updateStatusInErrors = useCallback(- (status: 'active' | 'resolved') => {- if (!activeError?.details?.eid) return-- setErrors((prevErrors) => {- return prevErrors.map((error) => {- if (error.eid === activeError.details.eid) {- return { ...error, status }- }- return error- })- })- },- [activeError?.details?.eid],- )+ const errorStatusUpdating = errorStatusFetcher.state !== 'idle'// Handle error status update responseuseEffect(() => {@@ -837,25 +745,18 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {const { intent, success, error } = errorStatusFetcher.dataif (intent === 'update-error-status') {- if (success && pendingStatusUpdate.current) {- updateStatusInErrors(pendingStatusUpdate.current)- if (activeEID) {- revalidator.revalidate()- }+ if (success) {+ queryClient.invalidateQueries({ queryKey: ['v2'] })toast.success(t('apiNotifications.errorStatusUpdated'))- pendingStatusUpdate.current = null} else if (error) {toast.error(error)- pendingStatusUpdate.current = null}}- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [errorStatusFetcher.state, errorStatusFetcher.data, t, activeEID])+ }, [errorStatusFetcher.state, errorStatusFetcher.data, t, queryClient])const markErrorAsResolved = () => {if (errorStatusUpdating || !activeEID || !activeError?.details?.eid) return- pendingStatusUpdate.current = 'resolved'errorStatusFetcher.submit({ intent: 'update-error-status', eid: activeEID, status: 'resolved' },{ method: 'POST', action: projectPath },@@ -865,21 +766,15 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {const markErrorAsActive = () => {if (errorStatusUpdating || !activeEID || !activeError?.details?.eid) return- pendingStatusUpdate.current = 'active'errorStatusFetcher.submit({ intent: 'update-error-status', eid: activeEID, status: 'active' },{ method: 'POST', action: projectPath },)}- const switchActiveErrorFilter = useMemo(- () =>- _debounce((pairID: string) => {- setErrorOptions((prev) => ({ ...prev, [pairID]: !prev[pairID] }))- setErrorsSkip(0)- }, 0),- [],- )+ const switchActiveErrorFilter = useCallback((pairID: string) => {+ setErrorOptions((prev) => ({ ...prev, [pairID]: !prev[pairID] }))+ }, [])const errorFilters = useMemo(() => {return [@@ -891,19 +786,23 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {]}, [t, errorOptions])+ // The overview chart is bucketed by the backend-resolved time bucket, which+ // may differ from the currently selected one+ const overviewTimeBucket = overview?.timeBucket || timeBucket+const handleOverviewDataPointClick = useCallback((d: { x: Date; index: number; xValue?: string }) => {setSessionsDrawer(getChartPointWindow({x: d.x,xValue: d.xValue,- timeBucket,+ timeBucket: overviewTimeBucket,timezone,timeFormat,}),)},- [timeBucket, timeFormat, timezone],+ [overviewTimeBucket, timeFormat, timezone],)const handleActiveErrorDataPointClick = useCallback(@@ -930,41 +829,12 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {],)- useEffect(() => {- if (errorsRefreshTrigger > 0) {- if (!activeEID) {- if (errorsProxy.isLoading) {- return- }-- const limit = Math.max(errors.length, ERRORS_TAKE)- errorsProxyRequestRef.current = { mode: 'replace', limit }- preserveErrorsRevalidationRef.current = true- setErrorsLoading(true)- errorsProxy.fetchErrors(id, {- timeBucket,- period: period === 'custom' ? '' : period,- from: from || undefined,- to: to || undefined,- timezone: timezone || '',- filters,- take: limit + 1,- skip: 0,- options: errorOptions,- })- }-- revalidator.revalidate()- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [errorsRefreshTrigger])-const chartOptions = useMemo(() => {if (!overview?.chart || !overview.chart.x || overview.chart.x.length === 0)return nullreturn getErrorTrendsChartSettings(overview.chart,- timeBucket,+ overviewTimeBucket,timeFormat,chartTypes.line,{@@ -974,9 +844,16 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {handleOverviewDataPointClick,t('project.exploreSessions'),)- }, [overview?.chart, timeBucket, timeFormat, handleOverviewDataPointClick, t])+ }, [+ overview?.chart,+ overviewTimeBucket,+ timeFormat,+ handleOverviewDataPointClick,+ t,+ ])- const hasErrorsRaw = !_isEmpty(errors) || overview?.stats?.totalErrors+ const hasErrorsRaw =+ !_isEmpty(errors) || Boolean(overview?.stats?.totalErrors)// Track if we've ever shown actual content to prevent NoEvents flash during exit animationconst hasShownContentRef = useRef(false)@@ -988,81 +865,183 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {// Don't show NoEvents if we've previously shown content (prevents flash during tab switch)const hasErrors = hasErrorsRaw || hasShownContentRef.current- const getFilterLink = useCallback(- (column: string, value: string | null): LinkProps['to'] => {- const isFilterActive =- filters.findIndex(- (filter) => filter.column === column && filter.filter === value,- ) >= 0- const newSearchParams = new URLSearchParams(searchParams.toString())-- if (isFilterActive) {- newSearchParams.delete(column)- } else {- if (value === null) {- newSearchParams.set(column, 'null')- } else {- newSearchParams.set(column, value)- }- }+ const isInitialLoading =+ (overviewQuery.isLoading || errorsListQuery.isLoading) &&+ !hasShownContentRef.current- return { search: newSearchParams.toString() }- },- [filters, searchParams],+ const isRefetching =+ (overviewQuery.isFetching && !overviewQuery.isLoading) ||+ (errorsListQuery.isFetching &&+ !errorsListQuery.isLoading &&+ !errorsListQuery.isFetchingNextPage)++ const dataNames = useMemo(+ () => ({+ occurrences: t('project.totalErrors'),+ affectedUsers: t('project.affectedUsers'),+ }),+ [t],+ )++ // --- Breakdown panels (error details view) ---++ const locationSubTabs = useMemo<BreakdownSubTab[]>(+ () => [+ { id: 'country', label: t('project.mapping.cc'), dimension: 'country' },+ { id: 'region', label: t('project.mapping.rg'), dimension: 'region' },+ { id: 'city', label: t('project.mapping.ct'), dimension: 'city' },+ { id: 'locale', label: t('project.mapping.lc'), dimension: 'locale' },+ {+ id: 'map',+ label: t('project.mapping.map'),+ render: () => <ErrorsMap />,+ },+ ],+ [t],+ )++ const pagesSubTabs = useMemo<BreakdownSubTab[]>(+ () => [+ { id: 'page', label: t('project.mapping.pg'), dimension: 'page' },+ { id: 'host', label: t('project.mapping.host'), dimension: 'host' },+ ],+ [t],+ )++ const devicesSubTabs = useMemo<BreakdownSubTab[]>(+ () => [+ {+ id: 'browser',+ label: t('project.mapping.br'),+ dimension: 'browser',+ versionsDimension: 'browser_version' as const,+ versionsParentField: 'browser' as const,+ },+ {+ id: 'os',+ label: t('project.mapping.os'),+ dimension: 'os',+ versionsDimension: 'os_version' as const,+ versionsParentField: 'os' as const,+ },+ { id: 'device', label: t('project.mapping.dv'), dimension: 'device' },+ ],+ [t],)- const getVersionFilterLink = useCallback(- (parent: string | null, version: string | null, panelType: 'br' | 'os') => {- const filterParams = new URLSearchParams(searchParams.toString())+ const networkSubTabs = useMemo<BreakdownSubTab[]>(+ () => [+ { id: 'isp', label: t('project.mapping.isp'), dimension: 'isp' },+ {+ id: 'organization',+ label: t('project.mapping.og'),+ dimension: 'organization',+ },+ {+ id: 'user_type',+ label: t('project.mapping.ut'),+ dimension: 'user_type',+ },+ {+ id: 'connection_type',+ label: t('project.mapping.ctp'),+ dimension: 'connection_type',+ },+ ],+ [t],+ )++ const locationRowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const { name: entryName, cc } = entry++ if (subTabId === 'locale') {+ if (entryName === null) {+ return <CCRow cc={null} language={language} />+ }++ const entryNameArray = entryName.split('-')+ const displayName = getLocaleDisplayName(entryName, language)++ return (+ <CCRow+ cc={entryNameArray[entryNameArray.length - 1]}+ name={displayName}+ language={language}+ />+ )+ }- if (panelType === 'br') {- filterParams.set('br', parent ?? 'null')- filterParams.set('brv', version ?? 'null')- } else if (panelType === 'os') {- filterParams.set('os', parent ?? 'null')- filterParams.set('osv', version ?? 'null')+ if (cc !== undefined) {+ return (+ <CCRow cc={cc} name={entryName || undefined} language={language} />+ )}- return `?${filterParams.toString()}`+ return <CCRow cc={entryName} language={language} />},- [searchParams],+ [language],)- const createVersionDataMapping = useMemo(() => {- const browserDataSource = activeError?.params?.brv- const osDataSource = activeError?.params?.osv+ const pagesRowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const { name: entryName } = entry- const browserVersions: { [key: string]: Entry[] } = {}- const osVersions: { [key: string]: Entry[] } = {}+ if (!entryName) {+ return (+ <span className='italic'>+ {subTabId === 'host'+ ? t('project.unknownHost')+ : t('common.notSet')}+ </span>+ )+ }- if (browserDataSource) {- browserDataSource.forEach((entry: any) => {- const { br, name, count } = entry- if (!browserVersions[br]) {- browserVersions[br] = []- }- browserVersions[br].push({ name, count })- })- }+ let decodedUri = entryName- if (osDataSource) {- osDataSource.forEach((entry: any) => {- const { os, name, count } = entry- if (!osVersions[os]) {- osVersions[os] = []- }- osVersions[os].push({ name, count })- })- }+ try {+ decodedUri = decodeURIComponent(entryName)+ } catch {+ // do nothing+ }- return { browserVersions, osVersions }- }, [activeError?.params?.brv, activeError?.params?.osv])+ if (subTabId === 'page' && project?.websiteUrl) {+ return (+ <PageLinkRow pagePath={decodedUri} websiteUrl={project.websiteUrl} />+ )+ }- const dataNames = useMemo(- () => ({- occurrences: t('project.totalErrors'),- affectedUsers: t('project.affectedUsers'),- }),+ return decodedUri+ },+ [t, project?.websiteUrl],+ )++ const devicesRowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const v1Tab =+ subTabId === 'browser' ? 'br' : subTabId === 'os' ? 'os' : 'dv'+ const mapper = getDeviceRowMapper(v1Tab, theme, t) as+ | ((entry: Entry) => React.ReactNode)+ | undefined+ return mapper ? mapper(entry) : entry.name+ },+ [theme, t],+ )++ const networkRowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const { name: entryName } = entry+ if (!entryName) {+ return <span className='italic'>{t('common.notSet')}</span>+ }+ if (subTabId === 'user_type') {+ return getUsageTypeLabel(entryName, t)+ }+ if (subTabId === 'connection_type') {+ return getConnectionTypeLabel(entryName, t)+ }+ return entryName+ },[t],)@@ -1084,6 +1063,9 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {}if (activeEID) {+ const detailsLoading = detailsQuery.isLoading+ const detailsRefetching = detailsQuery.isFetching && !detailsQuery.isLoading+const resolveButton =allowedToManage &&activeError &&@@ -1096,7 +1078,7 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {'group relative rounded-md border border-transparent bg-transparent px-3 py-1.5 text-sm font-medium text-gray-700 transition-all ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-slate-900 focus:outline-hidden dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:focus:ring-slate-300',{'cursor-not-allowed opacity-50':- errorLoading && !errorStatusUpdating,+ detailsRefetching && !errorStatusUpdating,'animate-pulse cursor-not-allowed': errorStatusUpdating,},)}@@ -1114,7 +1096,7 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {'group relative rounded-md border border-transparent bg-transparent px-3 py-1.5 text-sm font-medium text-gray-700 transition-all ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-slate-900 focus:outline-hidden dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:focus:ring-slate-300',{'cursor-not-allowed opacity-50':- errorLoading && !errorStatusUpdating,+ detailsRefetching && !errorStatusUpdating,'animate-pulse cursor-not-allowed': errorStatusUpdating,},)}@@ -1125,9 +1107,6 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {return (<div>- {errorLoading && activeError ? <LoadingBar /> : null}- {errorsLoading && !_isEmpty(errors) ? <LoadingBar /> : null}-<DashboardHeaderbackLink={`?${pureSearchParams}`}showLiveVisitors={false}@@ -1138,313 +1117,87 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {<Filters className='mb-3' tnMapping={tnMapping} />- {activeError?.details ? (- <ErrorDetails- details={activeError.details}- period={period}- from={dateRange ? getFormatDate(dateRange[0]) : undefined}- to={dateRange ? getFormatDate(dateRange[1]) : undefined}- timeBucket={timeBucket}- projectPassword={projectPassword}- chart={- <ErrorChart- chart={activeError?.chart}- timeBucket={activeError?.timeBucket}- timeFormat={timeFormat}- rotateXAxis={rotateXAxis}- chartType={chartTypes.line}- dataNames={dataNames}- onDataPointClick={handleActiveErrorDataPointClick}- stats={[- {- key: 'occurrences',- label: t('project.occurrences'),- value: nFormatter(activeError.details.count || 0, 1),- },- {- key: 'users',- label: t('dashboard.users'),- value: nFormatter(activeError.details.users || 0, 1),- },- {- key: 'firstSeen',- label: t('dashboard.firstSeen'),- value:- getRelativeDateIfPossible(- activeError.details.first_seen,- language,- ) || '-',- },- {- key: 'lastSeen',- label: t('dashboard.lastSeen'),- value:- getRelativeDateIfPossible(- activeError.details.last_seen,- language,- ) || '-',- },- ]}- />- }- />+ {detailsLoading ? (+ <div className='space-y-3'>+ <ChartSkeleton className='h-80 md:h-80' />+ <div className='grid grid-cols-1 gap-3 sm:grid-cols-2'>+ <PanelSkeleton />+ <PanelSkeleton />+ </div>+ </div>) : null}- <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>- {!_isEmpty(activeError?.params)- ? _map(ERROR_PANELS_ORDER, (type: keyof typeof tnMapping) => {- if (type === 'location') {- const locationTabs = [- { id: 'cc', label: t('project.mapping.cc') },- { id: 'rg', label: t('project.mapping.rg') },- { id: 'ct', label: t('project.mapping.ct') },- { id: 'lc', label: t('project.mapping.lc') },- { id: 'map', label: 'Map' },- ]-- const rowMapper = (entry: CountryEntry) => {- const { name: entryName, cc } = entry-- if (errorsActiveTabs.location === 'lc') {- if (entryName === null) {- return <CCRow cc={null} language={language} />- }- const entryNameArray = entryName.split('-')- const displayName = getLocaleDisplayName(- entryName,- language,- )-- return (- <CCRow- cc={entryNameArray[entryNameArray.length - 1]}- name={displayName}- language={language}- />- )- }-- if (cc !== undefined) {- return (- <CCRow- cc={cc}- name={entryName || undefined}- language={language}- />- )- }-- return <CCRow cc={entryName} language={language} />- }-- return (- <Panel- key={errorsActiveTabs.location}- icon={panelIconMapping.cc}- id={errorsActiveTabs.location}- getFilterLink={getFilterLink}- name={t('project.location')}- tabs={locationTabs}- onTabChange={(tab) =>- setErrorsActiveTabs({- ...errorsActiveTabs,- location: tab as 'cc' | 'rg' | 'ct' | 'lc' | 'map',- })- }- activeTabId={errorsActiveTabs.location}- data={- activeError?.params?.[errorsActiveTabs.location] || []- }- rowMapper={rowMapper}- customRenderer={- errorsActiveTabs.location === 'map'- ? () => {- const countryData = activeError?.params?.cc || []- const regionData = activeError?.params?.rg || []- const total = countryData.reduce(- (acc, curr) => acc + curr.count,- 0,- )-- return (- <Suspense fallback={<MapLoader />}>- <InteractiveMap- data={countryData}- regionData={regionData}- total={total}- onClick={(type, key) => {- const link = getFilterLink(type, key)- navigate(link)- }}- />- </Suspense>- )- }- : undefined- }- valuesHeaderName={t('project.occurrences')}- highlightColour='red'- />- )- }-- if (type === 'devices') {- const deviceTabs = [- { id: 'br', label: t('project.mapping.br') },- { id: 'os', label: t('project.mapping.os') },- { id: 'dv', label: t('project.mapping.dv') },- ]-- return (- <Panel- key={errorsActiveTabs.device}- icon={panelIconMapping.os}- id={errorsActiveTabs.device}- getFilterLink={getFilterLink}- name={t('project.devices')}- tabs={deviceTabs}- onTabChange={(tab) =>- setErrorsActiveTabs({- ...errorsActiveTabs,- device: tab as 'br' | 'os' | 'dv',- })- }- activeTabId={errorsActiveTabs.device}- data={- activeError?.params?.[errorsActiveTabs.device] || []- }- rowMapper={getDeviceRowMapper(- errorsActiveTabs.device,- theme,- t,- )}- capitalize={errorsActiveTabs.device === 'dv'}- versionData={- errorsActiveTabs.device === 'br'- ? createVersionDataMapping.browserVersions- : errorsActiveTabs.device === 'os'- ? createVersionDataMapping.osVersions- : undefined- }- getVersionFilterLink={(parent, version) =>- getVersionFilterLink(- parent,- version,- errorsActiveTabs.device === 'br' ? 'br' : 'os',- )- }- valuesHeaderName={t('project.occurrences')}- highlightColour='red'- />- )- }-- if (type === 'network') {- const networkTabs = [- { id: 'isp', label: t('project.mapping.isp') },- { id: 'og', label: t('project.mapping.og') },- { id: 'ut', label: t('project.mapping.ut') },- { id: 'ctp', label: t('project.mapping.ctp') },- ]-- const activeNetworkTab = errorsActiveTabs.network-- return (- <Panel- key={activeNetworkTab}- icon={panelIconMapping.isp}- id={activeNetworkTab}- getFilterLink={getFilterLink}- name={t('project.network')}- tabs={networkTabs}- onTabChange={(tab) =>- setErrorsActiveTabs({- ...errorsActiveTabs,- network: tab as 'isp' | 'og' | 'ut' | 'ctp',- })- }- activeTabId={activeNetworkTab}- data={activeError?.params?.[activeNetworkTab] || []}- rowMapper={({ name: entryName }) => {- if (!entryName) {- return (- <span className='italic'>{t('common.notSet')}</span>- )- }- if (activeNetworkTab === 'ut') {- return getUsageTypeLabel(entryName, t)- }- if (activeNetworkTab === 'ctp') {- return getConnectionTypeLabel(entryName, t)- }- return entryName- }}- valuesHeaderName={t('project.occurrences')}- highlightColour='red'- />- )- }-- if (type === 'pg') {- const pageTabs = [- { id: 'pg', label: t('project.mapping.pg') },- { id: 'host', label: t('project.mapping.host') },- ]-- return (- <Panel- key={errorsActiveTabs.page}- icon={panelIconMapping.pg}- id={errorsActiveTabs.page}- getFilterLink={getFilterLink}- rowMapper={({ name: entryName }) => {- if (!entryName) {- return (- <span className='italic'>- {errorsActiveTabs.page === 'pg'- ? t('common.notSet')- : t('project.unknownHost')}- </span>- )- }-- let decodedUri = entryName as string-- try {- decodedUri = decodeURIComponent(entryName)- } catch {- // do nothing- }-- return decodedUri- }}- name={t('project.pages')}- tabs={pageTabs}- onTabChange={(tab) =>- setErrorsActiveTabs({- ...errorsActiveTabs,- page: tab as 'pg' | 'host',- })- }- activeTabId={errorsActiveTabs.page}- data={activeError?.params?.[errorsActiveTabs.page] || []}- valuesHeaderName={t('project.occurrences')}- highlightColour='red'- />- )- }-- return null- })- : null}- {activeError?.metadata ? (- <MetadataPanel metadata={activeError.metadata} />- ) : null}- </div>+ {activeError?.details ? (+ <div className='relative'>+ {detailsRefetching ? <RefetchIndicator /> : null}+ <ErrorDetails+ details={activeError.details}+ chart={+ <ErrorChart+ chart={activeError.chart}+ timeBucket={activeError.timeBucket}+ timeFormat={timeFormat}+ rotateXAxis={rotateXAxis}+ chartType={chartTypes.line}+ dataNames={dataNames}+ onDataPointClick={handleActiveErrorDataPointClick}+ stats={[+ {+ key: 'occurrences',+ label: t('project.occurrences'),+ value: nFormatter(activeError.details.count || 0, 1),+ },+ {+ key: 'users',+ label: t('dashboard.users'),+ value: nFormatter(activeError.details.users || 0, 1),+ },+ {+ key: 'firstSeen',+ label: t('dashboard.firstSeen'),+ value:+ getRelativeDateIfPossible(+ activeError.details.first_seen,+ language,+ ) || '-',+ },+ {+ key: 'lastSeen',+ label: t('dashboard.lastSeen'),+ value:+ getRelativeDateIfPossible(+ activeError.details.last_seen,+ language,+ ) || '-',+ },+ ]}+ />+ }+ />+ </div>+ ) : null}- {_isEmpty(activeError) && errorLoading ? <Loader /> : null}+ {activeError?.details ? (+ <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>+ <PerErrorPanels+ params={activeError.params}+ locationSubTabs={locationSubTabs}+ pagesSubTabs={pagesSubTabs}+ devicesSubTabs={devicesSubTabs}+ networkSubTabs={networkSubTabs}+ locationRowMapper={locationRowMapper}+ pagesRowMapper={pagesRowMapper}+ devicesRowMapper={devicesRowMapper}+ networkRowMapper={networkRowMapper}+ isRefetching={detailsRefetching}+ />+ {activeError?.metadata ? (+ <MetadataPanel metadata={activeError.metadata} />+ ) : null}+ </div>+ ) : null}- {!errorLoading && _isEmpty(activeError) ? <NoErrorDetails /> : null}+ {!detailsLoading && !activeError?.details ? <NoErrorDetails /> : null}<SessionsDrawerisOpen={!!sessionsDrawer}onClose={() => setSessionsDrawer(null)}@@ -1463,24 +1216,6 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {)}- // List view - Initial loading state- if (- (overviewLoading === null || overviewLoading) &&- !overview &&- _isEmpty(errors)- ) {- return (- <div- className={cx('flex flex-col bg-gray-50 dark:bg-slate-950', {- 'min-h-including-header': !isEmbedded,- 'min-h-screen': isEmbedded,- })}- >- <Loader />- </div>- )- }-const filtersDropdown = hasErrors ? (<Dropdownitems={errorFilters}@@ -1510,6 +1245,45 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {/>) : null+ // List view - Initial loading state+ if (isInitialLoading) {+ return (+ <div>+ <DashboardHeader+ showLiveVisitors+ showSearchButton={false}+ hideTimeBucket+ rightContent={+ <ProjectViewHeaderActions+ tnMapping={tnMapping}+ extraActions={filtersDropdown}+ />+ }+ />+ <div className='flex flex-col gap-2 lg:flex-row'>+ <div className='w-full rounded-lg border border-gray-200 bg-white p-4 lg:w-[65%] dark:border-slate-800/60 dark:bg-slate-900/25'>+ <div+ aria-busy+ className='h-[220px] animate-pulse rounded-md bg-gray-200 dark:bg-slate-800'+ />+ </div>+ <div className='grid w-full grid-cols-2 gap-2 lg:w-[35%]'>+ {Array.from({ length: 4 }).map((_, i) => (+ <div+ key={i}+ aria-busy+ className='h-26 animate-pulse rounded-lg bg-gray-200 dark:bg-slate-800'+ />+ ))}+ </div>+ </div>+ <div className='mt-4'>+ <PanelSkeleton />+ </div>+ </div>+ )+ }+return (<div><DashboardHeader@@ -1524,13 +1298,9 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {}/>- {(overviewLoading || errorsLoading) && (overview || !_isEmpty(errors)) ? (- <LoadingBar />- ) : null}-{hasErrors ? <Filters className='mb-3' tnMapping={tnMapping} /> : null}- {!hasErrors && errorsLoading === false && overviewLoading === false ? (+ {!hasErrors && !overviewQuery.isLoading && !errorsListQuery.isLoading ? (<NoEvents filters={filters} />) : null}@@ -1538,7 +1308,8 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {<><div className='flex flex-col gap-2 lg:flex-row'>{chartOptions && overview?.chart ? (- <div className='w-full rounded-lg border border-gray-200 bg-white p-4 lg:w-[65%] dark:border-slate-800/60 dark:bg-slate-900/25'>+ <div className='relative w-full overflow-hidden rounded-lg border border-gray-200 bg-white p-4 lg:w-[65%] dark:border-slate-800/60 dark:bg-slate-900/25'>+ {isRefetching ? <RefetchIndicator /> : null}<BillboardChart options={chartOptions} className='h-[220px]' /></div>) : null}@@ -1567,7 +1338,8 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {</div></div>- <div className='mt-4'>+ <div className='relative mt-4'>+ {isRefetching ? <RefetchIndicator /> : null}<Text as='h3' weight='semibold' className='mb-3'>{t('project.recentErrors')}</Text>@@ -1588,10 +1360,10 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {</ClientOnly><InfiniteScrollTrigger- hasMore={canLoadMoreErrors}- isLoading={!!errorsLoading}- onLoadMore={loadMoreErrors}- disabled={!!errorsLoading}+ hasMore={Boolean(errorsListQuery.hasNextPage)}+ isLoading={errorsListQuery.isFetchingNextPage}+ onLoadMore={() => errorsListQuery.fetchNextPage()}+ disabled={errorsListQuery.isFetching}/></div></>diff --git a/web/app/pages/Project/tabs/Errors/types.ts b/web/app/pages/Project/tabs/Errors/types.tsnew file mode 100644index 000000000..84f95fad7--- /dev/null+++ b/web/app/pages/Project/tabs/Errors/types.ts@@ -0,0 +1,73 @@+// Local response shapes for the v2 errors endpoints+// (GET /v2/projects/:pid/errors, /errors/overview, /errors/:eid, /errors/:eid/sessions).+// The overview and details charts are already columnar ({ x, occurrences,+// affectedUsers }) with labels shifted to the requested timezone, so no+// pivoting is needed before handing them to ErrorChart.++interface ErrorsChartData {+ x: string[]+ occurrences: number[]+ affectedUsers: number[]+}++export interface ErrorsOverviewData {+ stats: {+ totalErrors: number+ uniqueErrors: number+ affectedSessions: number+ affectedUsers: number+ errorRate: number+ }+ mostFrequentError: {+ eid: string+ name: string+ message: string | null+ count: number+ usersAffected: number+ lastSeen: string+ } | null+ chart: ErrorsChartData+ timeBucket: string+}++export interface ErrorDetailsInfo {+ eid: string+ name: string+ message: string | null+ filename: string | null+ colno: number | null+ lineno: number | null+ stackTrace: string | null+ count: number+ status: 'active' | 'regressed' | 'resolved' | null+ first_seen: string+ last_seen: string+ users?: number+}++interface ErrorMetadataRow {+ key: string+ value: string+ count: number+}++export interface ErrorDetailsData {+ details: ErrorDetailsInfo+ metadata: ErrorMetadataRow[]+ /** Per-dimension breakdowns scoped to the error group, keyed by v1 names (cc, rg, br, ...) */+ params: Record<string, { name: string | null; count: number }[]>+ chart: ErrorsChartData+ timeBucket: string+}++/** Rows of GET /errors/:eid/sessions — entity keys renamed to v2 names */+export interface ErrorSessionItem {+ psid: string+ profileId: string | null+ country: string | null+ browser: string | null+ os: string | null+ firstErrorAt: string+ lastErrorAt: string+ errorCount: number+}diff --git a/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx b/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsxindex 8bdfa2598..249743885 100644--- a/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx+++ b/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx@@ -59,6 +59,7 @@ import { Badge } from '~/ui/Badge'import Modal from '~/ui/Modal'import { Text } from '~/ui/Text'import Tooltip from '~/ui/Tooltip'+import { v2FilterToLegacy } from '~/utils/analyticsUrl'import { nFormatter } from '~/utils/generic'import ExperimentSettingsModal from './ExperimentSettingsModal'@@ -767,7 +768,8 @@ const ExperimentResults = ({from,to,timezone,- filters,+ // experiments endpoints are still v1 — convert at the boundary+ filters: filters.map(v2FilterToLegacy),}),])diff --git a/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx b/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsxindex 01f535c6e..e55ca1751 100644--- a/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx+++ b/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx@@ -45,6 +45,7 @@ import Modal from '~/ui/Modal'import StatusPage from '~/ui/StatusPage'import { Text } from '~/ui/Text'import Tooltip from '~/ui/Tooltip'+import { v2FilterToLegacy } from '~/utils/analyticsUrl'import routes from '~/utils/routes'import ExperimentResults from './ExperimentResults'@@ -845,6 +846,8 @@ const ExperimentsView = ({const { id } = useCurrentProject()const { experimentsRefreshTrigger } = useRefreshTriggers()const { filters, timeBucket } = useViewProjectContext()+ // experiments endpoints are still v1 — convert filters at the boundary+ const legacyFilters = useMemo(() => filters.map(v2FilterToLegacy), [filters])const { t } = useTranslation()const [searchParams, setSearchParams] = useSearchParams()const listFetcher = useFetcher<ProjectViewActionData>()@@ -1305,7 +1308,7 @@ const ExperimentsView = ({from={from}to={to}timezone={timezone}- filters={filters}+ filters={legacyFilters}/>))}</ul>diff --git a/web/app/pages/Project/tabs/Funnels/FunnelsList.tsx b/web/app/pages/Project/tabs/Funnels/FunnelsList.tsxindex 498474ecd..c53792180 100644--- a/web/app/pages/Project/tabs/Funnels/FunnelsList.tsx+++ b/web/app/pages/Project/tabs/Funnels/FunnelsList.tsx@@ -10,34 +10,32 @@ import {ArrowRightIcon,CaretDownIcon,} from '@phosphor-icons/react'-import {- Suspense,- use,- useEffect,- useMemo,- useRef,- type ReactNode,-} from 'react'+import { useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'-import type { FunnelDataResponse } from '~/api/api.server'-import type { Funnel } from '~/lib/models/Project'+import type { AnalyticsFunnel, Funnel } from '~/lib/models/Project'import { FunnelChart } from '~/pages/Project/tabs/Funnels/FunnelChart'+import {+ ChartSkeleton,+ RefetchIndicator,+} from '~/pages/Project/View/v2/loading'import { useAuth } from '~/providers/AuthProvider'import Button from '~/ui/Button'-import Spin from '~/ui/icons/Spin'import { Text } from '~/ui/Text'import { nLocaleFormatter } from '~/utils/generic'+export interface FunnelData {+ funnel: AnalyticsFunnel[]+ totalPageviews: number+}+interface FunnelsListProps {funnels?: Funnel[]activeFunnelId: string | null- funnelDataPromise?: Promise<FunnelDataResponse | null>+ funnelData: FunnelData | null+ funnelDataLoading: boolean+ funnelDataRefetching: booleanonToggleFunnel: (id: string) => void- onFunnelDataResolved: (- funnelId: string,- funnelData: FunnelDataResponse | null,- ) => voidonBarClick: (stepIndex: number) => voidopenFunnelSettings: (funnel?: Funnel) => voiddeleteFunnel: (id: string) => void@@ -48,12 +46,10 @@ interface FunnelsListProps {interface FunnelCardProps {funnel: FunnelisExpanded: boolean- funnelDataPromise?: Promise<FunnelDataResponse | null>+ funnelData: FunnelData | null+ funnelDataLoading: boolean+ funnelDataRefetching: booleanonToggleFunnel: (id: string) => void- onFunnelDataResolved: (- funnelId: string,- funnelData: FunnelDataResponse | null,- ) => voidonBarClick: (stepIndex: number) => voidopenFunnelSettings: (funnel: Funnel) => voiddeleteFunnel: (id: string) => void@@ -67,7 +63,7 @@ interface AddFunnelProps {const STEPS_MAX_HEIGHT = 42-const getFunnelSummary = (funnelData?: FunnelDataResponse | null) => {+const getFunnelSummary = (funnelData?: FunnelData | null) => {if (!funnelData || _isEmpty(funnelData.funnel)) {return null}@@ -87,35 +83,6 @@ const getFunnelSummary = (funnelData?: FunnelDataResponse | null) => {}}-const FunnelDataResolver = ({- funnelId,- funnelDataPromise,- onFunnelDataResolved,- children,-}: {- funnelId: string- funnelDataPromise?: Promise<FunnelDataResponse | null>- onFunnelDataResolved: (- funnelId: string,- funnelData: FunnelDataResponse | null,- ) => void- children: (funnelData: FunnelDataResponse | null) => ReactNode-}) => {- const funnelData = funnelDataPromise ? use(funnelDataPromise) : null-- useEffect(() => {- onFunnelDataResolved(funnelId, funnelData)- }, [funnelData, funnelId, onFunnelDataResolved])-- return <>{children(funnelData)}</>-}--const FunnelChartLoading = () => (- <div className='flex h-[260px] items-center justify-center'>- <Spin className='size-8' />- </div>-)-const FunnelSteps = ({ steps }: { steps: string[] }) => {const containerRef = useRef<HTMLDivElement>(null)@@ -165,7 +132,7 @@ const FunnelExpandedChart = ({funnelData,onBarClick,}: {- funnelData: FunnelDataResponse | null+ funnelData: FunnelData | nullonBarClick: (stepIndex: number) => void}) => {const { t } = useTranslation('common')@@ -220,9 +187,10 @@ const FunnelExpandedChart = ({const FunnelCard = ({funnel,isExpanded,- funnelDataPromise,+ funnelData,+ funnelDataLoading,+ funnelDataRefetching,onToggleFunnel,- onFunnelDataResolved,onBarClick,openFunnelSettings,deleteFunnel,@@ -233,6 +201,7 @@ const FunnelCard = ({return (<li className='relative mb-3 overflow-hidden rounded-lg border border-gray-200 bg-gray-50 transition-colors dark:border-slate-800/60 dark:bg-slate-900/25'>+ {isExpanded && funnelDataRefetching ? <RefetchIndicator /> : null}<div className='flex transition-colors hover:bg-gray-200/70 dark:hover:bg-slate-900/60'><buttontype='button'@@ -303,23 +272,13 @@ const FunnelCard = ({id={`funnel-${funnel.id}-details`}className='border-t border-gray-200 px-4 py-4 sm:px-6 dark:border-slate-700'>- {funnelDataPromise ? (- <Suspense fallback={<FunnelChartLoading />}>- <FunnelDataResolver- funnelId={funnel.id}- funnelDataPromise={funnelDataPromise}- onFunnelDataResolved={onFunnelDataResolved}- >- {(funnelData) => (- <FunnelExpandedChart- funnelData={funnelData}- onBarClick={onBarClick}- />- )}- </FunnelDataResolver>- </Suspense>+ {funnelDataLoading ? (+ <ChartSkeleton className='h-80 md:h-80' />) : (- <FunnelChartLoading />+ <FunnelExpandedChart+ funnelData={funnelData}+ onBarClick={onBarClick}+ />)}</div>) : null}@@ -360,9 +319,10 @@ const AddFunnel = ({ openFunnelSettings }: AddFunnelProps) => {const FunnelsList = ({funnels,activeFunnelId,- funnelDataPromise,+ funnelData,+ funnelDataLoading,+ funnelDataRefetching,onToggleFunnel,- onFunnelDataResolved,onBarClick,openFunnelSettings,deleteFunnel,@@ -378,9 +338,10 @@ const FunnelsList = ({key={funnel.id}funnel={funnel}isExpanded={activeFunnelId === funnel.id}- funnelDataPromise={funnelDataPromise}+ funnelData={funnelData}+ funnelDataLoading={funnelDataLoading}+ funnelDataRefetching={funnelDataRefetching}onToggleFunnel={onToggleFunnel}- onFunnelDataResolved={onFunnelDataResolved}onBarClick={onBarClick}deleteFunnel={deleteFunnel}openFunnelSettings={openFunnelSettings}diff --git a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsxindex 482f0749b..2d1d710ab 100644--- a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx+++ b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx@@ -1,3 +1,4 @@+import { useQueryClient } from '@tanstack/react-query'import _filter from 'lodash/filter'import _find from 'lodash/find'import _includes from 'lodash/includes'@@ -5,39 +6,29 @@ import _isEmpty from 'lodash/isEmpty'import { FunnelIcon, PlusIcon } from '@phosphor-icons/react'import { useState, useEffect, useMemo, useCallback, useRef } from 'react'import { Trans, useTranslation } from 'react-i18next'-import {- useSearchParams,- useFetcher,- useLoaderData,- useRevalidator,-} from 'react-router'+import { useSearchParams, useFetcher } from 'react-router'import { toast } from 'sonner'-import type { FunnelDataResponse } from '~/api/api.server'+import { useFunnelQuery } from '~/hooks/v2/useV2Queries'import { DOCS_URL, FUNNELS_PERIOD_PAIRS } from '~/lib/constants'-import type { Funnel } from '~/lib/models/Project'+import type { AnalyticsFunnel, Funnel } from '~/lib/models/Project'import NewFunnel from '~/modals/NewFunnel'-import FunnelsList from '~/pages/Project/tabs/Funnels/FunnelsList'+import FunnelsList, {+ type FunnelData,+} from '~/pages/Project/tabs/Funnels/FunnelsList'import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'import Filters from '~/pages/Project/View/components/Filters'import ProjectViewHeaderActions from '~/pages/Project/View/components/ProjectViewHeaderActions'import TabErrorBoundary from '~/pages/Project/View/components/TabErrorBoundary'-import {- useViewProjectContext,- useRefreshTriggers,-} from '~/pages/Project/View/ViewProject'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'import { useAuth } from '~/providers/AuthProvider'import {useCurrentProject,useProjectPassword,} from '~/providers/CurrentProjectProvider'-import type {- ProjectLoaderData,- ProjectViewActionData,-} from '~/routes/projects.$id'+import type { ProjectViewActionData } from '~/routes/projects.$id'import Button from '~/ui/Button'import { Link } from '~/ui/Link'-import LoadingBar from '~/ui/LoadingBar'import { Text } from '~/ui/Text'import routes from '~/utils/routes'@@ -50,26 +41,21 @@ interface FunnelsViewProps {const FUNNELS_DOCS_URL = `${DOCS_URL}/analytics-dashboard/funnels`const FunnelsView = ({ tnMapping }: FunnelsViewProps) => {- const { funnelData: funnelDataPromise } = useLoaderData<ProjectLoaderData>()const { id, projectPath, project, mergeProject, allowedToManage } =useCurrentProject()const projectPassword = useProjectPassword(id)- const revalidator = useRevalidator()const { isAuthenticated } = useAuth()- const { funnelsRefreshTrigger } = useRefreshTriggers()const { periodPairs, period, timezone, timeFormat, filters } =useViewProjectContext()const { t } = useTranslation('common')const [searchParams, setSearchParams] = useSearchParams()+ const queryClient = useQueryClient()const fetcher = useFetcher<ProjectViewActionData>()const lastHandledData = useRef<ProjectViewActionData | null>(null)const deletedFunnelId = useRef<string | null>(null)- const lastRefreshTrigger = useRef(funnelsRefreshTrigger)const [isNewFunnelOpened, setIsNewFunnelOpened] = useState(false)const [funnelToEdit, setFunnelToEdit] = useState<Funnel | undefined>()- const [funnelAnalytics, setFunnelAnalytics] =- useState<FunnelDataResponse | null>(null)const [sessionsDrawer, setSessionsDrawer] = useState<{stepIndex: numberlabel: string@@ -96,15 +82,43 @@ const FunnelsView = ({ tnMapping }: FunnelsViewProps) => {return _find(project.funnels, (funnel) => funnel.id === funnelId) || null}, [searchParams, project])+ const funnelQuery = useFunnelQuery(activeFunnel?.id ?? null)++ // keepPreviousData keeps data visible on period/filter refetch, but a stale+ // chart of ANOTHER funnel should not flash while switching between funnels+ const displayedFunnelIdRef = useRef<string | null>(null)+ if (funnelQuery.data && !funnelQuery.isPlaceholderData) {+ displayedFunnelIdRef.current = activeFunnel?.id ?? null+ }+ const isStaleFunnelData =+ funnelQuery.isPlaceholderData &&+ displayedFunnelIdRef.current !== (activeFunnel?.id ?? null)++ const funnelAnalytics = useMemo<FunnelData | null>(() => {+ const data = funnelQuery.data?.data++ if (!data) {+ return null+ }++ return {+ funnel: (data.steps || []) as AnalyticsFunnel[],+ totalPageviews: Number(data.totalPageviews || 0),+ }+ }, [funnelQuery.data])++ const displayedFunnelAnalytics = isStaleFunnelData ? null : funnelAnalytics+ const funnelDataLoading = funnelQuery.isLoading || isStaleFunnelData+ const funnelDataRefetching =+ funnelQuery.isFetching && !funnelDataLoading && Boolean(funnelQuery.data)+const funnelActionLoading = fetcher.state !== 'idle'- const analyticsLoading = revalidator.state === 'loading'const hasFunnels = !_isEmpty(project?.funnels)- const resetKey = `funnels:${searchParams.toString()}:${funnelsRefreshTrigger}`+ const resetKey = `funnels:${searchParams.toString()}`const clearActiveFunnel = useCallback(() => {const nextSearchParams = new URLSearchParams(searchParams.toString())nextSearchParams.delete('funnelId')- setFunnelAnalytics(null)setSessionsDrawer(null)setSearchParams(nextSearchParams)}, [searchParams, setSearchParams])@@ -119,7 +133,6 @@ const FunnelsView = ({ tnMapping }: FunnelsViewProps) => {nextSearchParams.set('funnelId', funnelId)}- setFunnelAnalytics(null)setSessionsDrawer(null)setSearchParams(nextSearchParams)},@@ -136,17 +149,7 @@ const FunnelsView = ({ tnMapping }: FunnelsViewProps) => {setFunnelToEdit(undefined)}, [])- const handleFunnelDataResolved = useCallback(- (funnelId: string, funnelData: FunnelDataResponse | null) => {- if (activeFunnel?.id === funnelId) {- setFunnelAnalytics(funnelData)- }- },- [activeFunnel?.id],- )-useEffect(() => {- setFunnelAnalytics(null)setSessionsDrawer(null)}, [activeFunnel?.id])@@ -173,10 +176,11 @@ const FunnelsView = ({ tnMapping }: FunnelsViewProps) => {{ method: 'POST', action: projectPath },)- const updatedFunnelId = (fetcher.data.data as { id?: string })?.id- if (updatedFunnelId && activeFunnel?.id === updatedFunnelId) {- revalidator.revalidate()- }+ // Steps may have changed - drop cached funnel analytics+ queryClient.invalidateQueries({ queryKey: ['v2', id, 'funnel'] })+ queryClient.invalidateQueries({+ queryKey: ['v2', id, 'funnel-sessions'],+ })} else if (intent === 'delete-funnel') {toast.success(t('apiNotifications.funnelDeleted'))fetcher.submit(@@ -205,9 +209,9 @@ const FunnelsView = ({ tnMapping }: FunnelsViewProps) => {projectPath,fetcher,activeFunnel?.id,- revalidator,clearActiveFunnel,mergeProject,+ queryClient,])const onFunnelCreate = (name: string, steps: string[]) => {@@ -240,24 +244,17 @@ const FunnelsView = ({ tnMapping }: FunnelsViewProps) => {const handleBarClick = useCallback((stepIndex: number) => {- if (!funnelAnalytics?.funnel?.[stepIndex]) return+ if (!displayedFunnelAnalytics?.funnel?.[stepIndex]) return- const step = funnelAnalytics.funnel[stepIndex]+ const step = displayedFunnelAnalytics.funnel[stepIndex]setSessionsDrawer({stepIndex,label: step.value,})},- [funnelAnalytics],+ [displayedFunnelAnalytics],)- useEffect(() => {- if (funnelsRefreshTrigger > lastRefreshTrigger.current) {- lastRefreshTrigger.current = funnelsRefreshTrigger- revalidator.revalidate()- }- }, [funnelsRefreshTrigger, revalidator])-return (<TabErrorBoundarytitleKey='dashboard.failedToLoadFunnels'@@ -270,17 +267,15 @@ const FunnelsView = ({ tnMapping }: FunnelsViewProps) => {rightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}/><Filters className='mb-3' tnMapping={tnMapping} />- {activeFunnel && analyticsLoading && funnelAnalytics ? (- <LoadingBar />- ) : null}{hasFunnels ? (<FunnelsListfunnels={project?.funnels}activeFunnelId={activeFunnel?.id || null}- funnelDataPromise={funnelDataPromise}+ funnelData={displayedFunnelAnalytics}+ funnelDataLoading={funnelDataLoading}+ funnelDataRefetching={funnelDataRefetching}onToggleFunnel={handleToggleFunnel}- onFunnelDataResolved={handleFunnelDataResolved}onBarClick={handleBarClick}openFunnelSettings={openFunnelSettings}deleteFunnel={onFunnelDelete}@@ -367,7 +362,8 @@ const FunnelsView = ({ tnMapping }: FunnelsViewProps) => {dropoff={Boolean(sessionsDrawer?.dropoff)}showDropoffToggle={!!sessionsDrawer &&- sessionsDrawer.stepIndex < (funnelAnalytics?.funnel?.length || 0) - 1+ sessionsDrawer.stepIndex <+ (displayedFunnelAnalytics?.funnel?.length || 0) - 1}onDropoffChange={(dropoff) =>setSessionsDrawer((current) =>@@ -377,8 +373,10 @@ const FunnelsView = ({ tnMapping }: FunnelsViewProps) => {totalCount={sessionsDrawer? sessionsDrawer.dropoff- ? funnelAnalytics?.funnel?.[sessionsDrawer.stepIndex + 1]?.dropoff- : funnelAnalytics?.funnel?.[sessionsDrawer.stepIndex]?.events+ ? displayedFunnelAnalytics?.funnel?.[sessionsDrawer.stepIndex + 1]+ ?.dropoff+ : displayedFunnelAnalytics?.funnel?.[sessionsDrawer.stepIndex]+ ?.events: undefined}/>diff --git a/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx b/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsxindex 4f516cf48..37c21cbec 100644--- a/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx+++ b/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx@@ -23,7 +23,8 @@ import Input from '~/ui/Input'import Loader from '~/ui/Loader'import Select from '~/ui/Select'import { Text } from '~/ui/Text'-import type { Filter as FilterType } from '../../View/interfaces/traffic'+import type { V2Filter, V2FilterOperator } from '~/api/v2/types'+import { legacyFilterToV2, v2FilterToLegacy } from '~/utils/analyticsUrl'import FilterRowsEditor from '../../View/components/FilterRowsEditor'const GOAL_TYPES = [@@ -46,136 +47,153 @@ const CONDITION_RELATIONS: { value: GoalConditionRelation; label: string }[] = [{ value: 'OR', label: 'OR' },]+// v2 dimension names; the bare keyed dimensions (page_property /+// event_metadata) mean "has this metadata key" — the value is the key itself.const GOAL_CONDITION_FILTER_OPTIONS = [- 'pg',- 'ev',+ 'page',+ 'event','host',- 'cc',- 'dv',- 'br',+ 'country',+ 'device',+ 'browser','os',- 'ref',- 'so',- 'me',- 'ca',- 'te',- 'co',- 'tag:key',- 'ev:key',+ 'referrer',+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'utm_term',+ 'utm_content',+ 'page_property',+ 'event_metadata',]const createConditionId = () =>globalThis.crypto?.randomUUID?.() || Math.random().toString(36).slice(2)-const filterToConditionOperator = ({- isExclusive,- isContains,-}: FilterType): GoalCondition['operator'] => {- if (isContains && isExclusive) return 'not_contains'- if (isContains) return 'contains'- if (isExclusive) return 'not_equals'+const filterToConditionOperator = (+ operator: V2FilterOperator,+): GoalCondition['operator'] => {+ if (operator === 'contains_not') return 'not_contains'+ if (operator === 'contains') return 'contains'+ if (operator === 'is_not') return 'not_equals'return 'equals'}-const conditionOperatorToFilterFlags = (+const conditionOperatorToV2Operator = (operator: GoalCondition['operator'],-) => ({- isExclusive: operator === 'not_equals' || operator === 'not_contains',- isContains: operator === 'contains' || operator === 'not_contains',-})+): V2FilterOperator => {+ if (operator === 'not_contains') return 'contains_not'+ if (operator === 'contains') return 'contains'+ if (operator === 'not_equals') return 'is_not'+ return 'is'+}++const getMetadataConditionDimension = (eventType: GoalCondition['eventType']) =>+ eventType === 'custom_event' ? 'event_metadata' : 'page_property'-const getMetadataConditionPrefix = (eventType: GoalCondition['eventType']) =>- eventType === 'custom_event' ? 'ev:key' : 'tag:key'+const filterToCondition = (filter: V2Filter): GoalCondition | null => {+ const value = typeof filter.value === 'string' ? filter.value : ''-const filterToCondition = (filter: FilterType): GoalCondition | null => {- if (!filter.column || !filter.filter) return null+ if (!filter.dimension || !value) return null- if (filter.column === 'ev') {+ if (filter.dimension === 'event') {return {id: createConditionId(),eventType: 'custom_event',field: 'event_name',- operator: filterToConditionOperator(filter),- value: filter.filter,- }- }-- if (filter.column === 'ev:key' || filter.column === 'tag:key') {- return {- id: createConditionId(),- eventType: filter.column === 'ev:key' ? 'custom_event' : 'pageview',- field: 'metadata',- operator: filter.isExclusive ? 'not_exists' : 'exists',- metadataKey: filter.filter,+ operator: filterToConditionOperator(filter.operator),+ value,}}if (- filter.column.startsWith('ev:key:') ||- filter.column.startsWith('tag:key:')+ filter.dimension === 'event_metadata' ||+ filter.dimension === 'page_property') {+ const eventType =+ filter.dimension === 'event_metadata' ? 'custom_event' : 'pageview'++ if (!filter.key) {+ // bare keyed dimension = "has this metadata key"; value is the key+ return {+ id: createConditionId(),+ eventType,+ field: 'metadata',+ operator: filter.operator === 'is_not' ? 'not_exists' : 'exists',+ metadataKey: value,+ }+ }+return {id: createConditionId(),- eventType: filter.column.startsWith('ev:key:')- ? 'custom_event'- : 'pageview',+ eventType,field: 'metadata',- operator: filterToConditionOperator(filter),- metadataKey: filter.column- .replace(/^ev:key:/, '')- .replace(/^tag:key:/, ''),- value: filter.filter,+ operator: filterToConditionOperator(filter.operator),+ metadataKey: filter.key,+ value,}}+ // goal conditions keep the legacy v1 column codes in `field`+ const { column } = v2FilterToLegacy(filter)+return {id: createConditionId(),- eventType: filter.column === 'pg' ? 'pageview' : 'any',- field: filter.column,- operator: filterToConditionOperator(filter),- value: filter.filter,+ eventType: filter.dimension === 'page' ? 'pageview' : 'any',+ field: column,+ operator: filterToConditionOperator(filter.operator),+ value,}}-const conditionToFilter = (condition: GoalCondition): FilterType | null => {+const conditionToFilter = (condition: GoalCondition): V2Filter | null => {if (condition.field === 'metadata') {if (!condition.metadataKey) return null- const prefix = getMetadataConditionPrefix(condition.eventType)+ const dimension = getMetadataConditionDimension(condition.eventType)if (condition.operator === 'exists' ||condition.operator === 'not_exists') {return {- column: prefix,- filter: condition.metadataKey,- isExclusive: condition.operator === 'not_exists',- isContains: false,+ dimension,+ operator: condition.operator === 'not_exists' ? 'is_not' : 'is',+ value: condition.metadataKey,}}if (!condition.value) return null- const flags = conditionOperatorToFilterFlags(condition.operator)return {- column: `${prefix}:${condition.metadataKey}`,- filter: condition.value,- ...flags,+ dimension,+ key: condition.metadataKey,+ operator: conditionOperatorToV2Operator(condition.operator),+ value: condition.value,}}if (!condition.value) return null- const flags = conditionOperatorToFilterFlags(condition.operator)- return {- column:- condition.field === 'event' || condition.field === 'event_name'- ? 'ev'- : condition.field,- filter: condition.value,- ...flags,+ if (condition.field === 'event' || condition.field === 'event_name') {+ return {+ dimension: 'event',+ operator: conditionOperatorToV2Operator(condition.operator),+ value: condition.value,+ }}++ const operator = conditionOperatorToV2Operator(condition.operator)++ // `field` holds a legacy v1 column code; unknown fields stay unmapped+ const converted = legacyFilterToV2({+ column: condition.field,+ filter: condition.value,+ isExclusive: operator === 'is_not' || operator === 'contains_not',+ isContains: operator === 'contains' || operator === 'contains_not',+ })++ return converted}interface GoalSettingsModalProps {@@ -215,9 +233,9 @@ const GoalSettingsModal = ({const [conditionsRelation, setConditionsRelation] =useState<GoalConditionRelation>('AND')const [conditionInitialFilters, setConditionInitialFilters] = useState<- FilterType[]+ V2Filter[]>([])- const [conditionFilters, setConditionFilters] = useState<FilterType[]>([])+ const [conditionFilters, setConditionFilters] = useState<V2Filter[]>([])const [unmappedConditions, setUnmappedConditions] = useState<GoalCondition[]>([],)@@ -225,7 +243,7 @@ const GoalSettingsModal = ({const isSaving = fetcher.state === 'submitting'- const resetConditionFilters = useCallback((filters: FilterType[] = []) => {+ const resetConditionFilters = useCallback((filters: V2Filter[] = []) => {setConditionInitialFilters(filters)setConditionFilters(filters)setUnmappedConditions([])@@ -260,7 +278,7 @@ const GoalSettingsModal = ({goal.conditions?.conditions?.length ? 'conditions' : 'simple',)setConditionsRelation(goal.conditions?.relation || 'AND')- const mappedFilters: FilterType[] = []+ const mappedFilters: V2Filter[] = []const nextUnmappedConditions: GoalCondition[] = []const loadedConditions = goal.conditions?.conditions || []diff --git a/web/app/pages/Project/tabs/Goals/GoalsView.tsx b/web/app/pages/Project/tabs/Goals/GoalsView.tsxindex 8194b1652..bfcfda928 100644--- a/web/app/pages/Project/tabs/Goals/GoalsView.tsx+++ b/web/app/pages/Project/tabs/Goals/GoalsView.tsx@@ -81,6 +81,7 @@ import ProgressRing from '~/ui/ProgressRing'import StatusPage from '~/ui/StatusPage'import { Text } from '~/ui/Text'import Tooltip from '~/ui/Tooltip'+import { v2FilterToLegacy } from '~/utils/analyticsUrl'import { escapeHtml, nFormatter } from '~/utils/generic'import countries from '~/utils/isoCountries'import routes from '~/utils/routes'@@ -953,7 +954,8 @@ const GoalsViewInner = ({from,to,timezone,- filters,+ // goals endpoints are still v1 — convert filters at the boundary+ filters: filters.map(v2FilterToLegacy),})if (isMountedRef.current) {setGoalStats((prev) => ({ ...prev, [goalId]: stats }))@@ -982,7 +984,8 @@ const GoalsViewInner = ({to,timeBucket,timezone,- filters,+ // goals endpoints are still v1 — convert filters at the boundary+ filters: filters.map(v2FilterToLegacy),})if (isMountedRef.current && result) {setGoalChartData((prev) => ({ ...prev, [goalId]: result.chart }))diff --git a/web/app/pages/Project/tabs/Performance/PerformanceMap.tsx b/web/app/pages/Project/tabs/Performance/PerformanceMap.tsxnew file mode 100644index 000000000..f418356e6--- /dev/null+++ b/web/app/pages/Project/tabs/Performance/PerformanceMap.tsx@@ -0,0 +1,76 @@+import { Suspense, lazy, useMemo } from 'react'+import { useNavigate } from 'react-router'++import { useBreakdownQuery } from '~/hooks/v2/useV2Queries'+import { MapLoader } from '~/pages/Project/View/components/MapLoader'+import { mapBreakdownRows } from '~/pages/Project/View/v2/adapters'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'++const InteractiveMap = lazy(+ () => import('~/pages/Project/View/components/InteractiveMap'),+)++const MAP_CLICK_TYPE_TO_DIMENSION = { cc: 'country', rg: 'region' } as const++/**+ * Interactive location map fed by its own country + region performance+ * breakdown queries (deduped with the location panel's queries via the+ * react-query cache).+ */+export const PerformanceMap = ({+ isFullscreen,+ measure,+}: {+ isFullscreen: boolean+ measure?: string+}) => {+ const navigate = useNavigate()+ const { getFilterLink, setIsMapFullscreen } = useViewProjectContext()++ const countryQuery = useBreakdownQuery('performance', {+ dimension: 'country',+ metrics: ['load_time'],+ measure,+ limit: 100,+ sort: 'load_time:desc',+ })+ const regionQuery = useBreakdownQuery('performance', {+ dimension: 'region',+ metrics: ['load_time'],+ measure,+ limit: 100,+ sort: 'load_time:desc',+ })++ const countryData = useMemo(+ () => mapBreakdownRows(countryQuery.data?.data, 'load_time'),+ [countryQuery.data],+ )+ const regionData = useMemo(+ () => mapBreakdownRows(regionQuery.data?.data, 'load_time'),+ [regionQuery.data],+ )+ const total = useMemo(+ () => countryData.reduce((acc, curr) => acc + curr.count, 0),+ [countryData],+ )++ if (countryQuery.isLoading) {+ return <MapLoader />+ }++ return (+ <Suspense fallback={<MapLoader />}>+ <InteractiveMap+ data={countryData}+ regionData={regionData}+ total={total}+ onClick={(mapType, key) => {+ navigate(getFilterLink(MAP_CLICK_TYPE_TO_DIMENSION[mapType], key))+ }}+ onFullscreenToggle={setIsMapFullscreen}+ isFullscreen={isFullscreen}+ />+ </Suspense>+ )+}diff --git a/web/app/pages/Project/tabs/Performance/PerformanceView.tsx b/web/app/pages/Project/tabs/Performance/PerformanceView.tsxindex b00d5db8e..e13f69898 100644--- a/web/app/pages/Project/tabs/Performance/PerformanceView.tsx+++ b/web/app/pages/Project/tabs/Performance/PerformanceView.tsx@@ -1,38 +1,27 @@import cx from 'clsx'import dayjs from 'dayjs'import _isEmpty from 'lodash/isEmpty'-import _keys from 'lodash/keys'-import _map from 'lodash/map'import { EyeIcon, PercentIcon } from '@phosphor-icons/react'-import {- useState,- useEffect,- useMemo,- useRef,- useCallback,- lazy,- Suspense,- use,-} from 'react'+import React, { useState, useMemo, useRef, useCallback } from 'react'import { createPortal } from 'react-dom'import { useTranslation } from 'react-i18next'+import { useSearchParams } from 'react-router'+import {- useNavigate,- useSearchParams,- useLoaderData,- useRevalidator,-} from 'react-router'--import type {- PerformanceDataResponse,- PerformanceOverallObject,-} from '~/api/api.server'+ useCompareSummaryQuery,+ useCompareTimeseriesQuery,+ useSummaryQuery,+ useTimeseriesQuery,+} from '~/hooks/v2/useV2Queries'import { useAnnotations } from '~/hooks/useAnnotations'-import { PERFORMANCE_PANELS_ORDER } from '~/lib/constants'-import { CountryEntry } from '~/lib/models/Entry'-import { OverallPerformanceObject } from '~/lib/models/Project'+import { Entry } from '~/lib/models/Entry'import AnnotationModal from '~/modals/AnnotationModal'import { PerformanceChart } from '~/pages/Project/tabs/Performance/PerformanceChart'+import { PerformanceMap } from '~/pages/Project/tabs/Performance/PerformanceMap'+import {+ perfSummaryToOverall,+ pivotPerformanceTimeseries,+} from '~/pages/Project/tabs/Performance/perfAdapters'import { PerformanceMetricCards } from '~/pages/Project/tabs/Traffic/MetricCards'import { SessionsDrawer } from '~/pages/Project/tabs/Traffic/SessionsDrawer'import PageLinkRow from '~/pages/Project/tabs/Traffic/PageLinkRow'@@ -40,15 +29,18 @@ import CCRow from '~/pages/Project/View/components/CCRow'import { ChartContextMenu } from '~/pages/Project/View/components/ChartContextMenu'import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'import Filters from '~/pages/Project/View/components/Filters'-import { MapLoader } from '~/pages/Project/View/components/MapLoader'import NoEvents from '~/pages/Project/View/components/NoEvents'import ProjectViewHeaderActions from '~/pages/Project/View/components/ProjectViewHeaderActions'import TabErrorBoundary from '~/pages/Project/View/components/TabErrorBoundary'-import { Panel } from '~/pages/Project/View/Panels'import {- useViewProjectContext,- useRefreshTriggers,-} from '~/pages/Project/View/ViewProject'+ BreakdownPanel,+ BreakdownSubTab,+} from '~/pages/Project/View/v2/BreakdownPanel'+import {+ ChartSkeleton,+ MetricCardsSkeleton,+} from '~/pages/Project/View/v2/loading'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'import {panelIconMapping,CHART_METRICS_MAPPING_PERF,@@ -60,96 +52,31 @@ import {import { getChartPointWindow } from '~/pages/Project/View/utils/chartPoint'import { useCurrentProject } from '~/providers/CurrentProjectProvider'import { useTheme } from '~/providers/ThemeProvider'-import type { ProjectLoaderData } from '~/routes/projects.$id'import Dropdown from '~/ui/Dropdown'-import LoadingBar from '~/ui/LoadingBar'import { getStringFromTime, getTimeFromSeconds } from '~/utils/generic'-import { LoaderView } from '../../View/components/LoaderView'import { ChartTypeSwitcher } from '../../View/components/ChartTypeSwitcher'import WaitingForAnEvent from '../../View/components/WaitingForAnEvent'-const InteractiveMap = lazy(- () => import('~/pages/Project/View/components/InteractiveMap'),-)-interface PerformanceViewProps {tnMapping: Record<string, string>}-interface DeferredPerfData {- perfData: PerformanceDataResponse | null- perfOverallStats: Record<string, PerformanceOverallObject> | null- perfCompareData: PerformanceDataResponse | null- perfOverallCompareStats: Record<string, PerformanceOverallObject> | null-}--function PerfDataResolver({- children,-}: {- children: (data: DeferredPerfData) => React.ReactNode-}) {- const {- perfData: perfDataPromise,- perfOverallStats: perfOverallStatsPromise,- perfCompareData: perfCompareDataPromise,- perfOverallCompareStats: perfOverallCompareStatsPromise,- } = useLoaderData<ProjectLoaderData>()-- const perfData = perfDataPromise ? use(perfDataPromise) : null- const perfOverallStats = perfOverallStatsPromise- ? use(perfOverallStatsPromise)- : null- const perfCompareData = perfCompareDataPromise- ? use(perfCompareDataPromise)- : null- const perfOverallCompareStats = perfOverallCompareStatsPromise- ? use(perfOverallCompareStatsPromise)- : null-- return (- <>- {children({- perfData,- perfOverallStats,- perfCompareData,- perfOverallCompareStats,- })}- </>- )-}-function PerformanceViewWrapper(props: PerformanceViewProps) {const [searchParams] = useSearchParams()- const { performanceRefreshTrigger } = useRefreshTriggers()- const resetKey = `performance:${searchParams.toString()}:${performanceRefreshTrigger}`+ const resetKey = `performance:${searchParams.toString()}`return (<TabErrorBoundarytitleKey='dashboard.failedToLoadPerformance'resetKey={resetKey}>- <Suspense fallback={<LoaderView />}>- <PerfDataResolver>- {(deferredData) => (- <PerformanceViewInner {...props} deferredData={deferredData} />- )}- </PerfDataResolver>- </Suspense>+ <PerformanceViewInner {...props} /></TabErrorBoundary>)}-interface PerformanceViewInnerProps extends PerformanceViewProps {- deferredData: DeferredPerfData-}--const PerformanceViewInner = ({- tnMapping,- deferredData,-}: PerformanceViewInnerProps) => {+const PerformanceViewInner = ({ tnMapping }: PerformanceViewProps) => {const { id, project, allowedToManage } = useCurrentProject()- const revalidator = useRevalidator()- const { performanceRefreshTrigger } = useRefreshTriggers()const {timezone,filters,@@ -163,10 +90,8 @@ const PerformanceViewInner = ({onMainChartZoom,shouldEnableZoom,// Filter functions from context- getFilterLink,getVersionFilterLink,isMapFullscreen,- setIsMapFullscreen,fullscreenMapRef,} = useViewProjectContext()@@ -191,68 +116,17 @@ const PerformanceViewInner = ({i18n: { language },} = useTranslation('common')const { theme } = useTheme()- const navigate = useNavigate()const [searchParams, setSearchParams] = useSearchParams()- // State for data - initialized from loader, can be overridden by client-side fetches- const [dataLoading, setDataLoading] = useState(false)- const [panelsData, setPanelsData] = useState<any>(() => {- if (deferredData.perfData?.params) {- return {- types: _keys(deferredData.perfData.params),- data: deferredData.perfData.params,- }- }- return { data: {} }- })- const [chartData, setChartData] = useState<any>(- () => deferredData.perfData?.chart || {},- )- const [overall, setOverall] = useState<Partial<OverallPerformanceObject>>(- () => {- if (deferredData.perfOverallStats && id) {- return deferredData.perfOverallStats[id] || {}- }- return {}- },- )const [sessionsDrawer, setSessionsDrawer] = useState<{from: stringto: stringlabel: string} | null>(null)- // Track if we've ever shown actual content to prevent NoEvents flash during exit animation+ // Track if we've ever shown actual content to prevent NoEvents flashconst hasShownContentRef = useRef(false)- const isPanelsDataEmptyRaw = _isEmpty(panelsData.data)-- // Track when we've shown content to prevent NoEvents flash during exit animation- if (!isPanelsDataEmptyRaw) {- hasShownContentRef.current = true- }-- // Don't show NoEvents if we've previously shown content (prevents flash during tab switch)- const isPanelsDataEmpty = isPanelsDataEmptyRaw && !hasShownContentRef.current-- // Sync state when loader provides new data (e.g., after URL changes)- useEffect(() => {- if (revalidator.state === 'idle' && deferredData.perfData) {- const { chart, params } = deferredData.perfData- setChartData(chart || {})- setPanelsData({- types: _keys(params),- data: params,- })- if (deferredData.perfOverallStats && id) {- setOverall(deferredData.perfOverallStats[id] || {})- }- setDataLoading(false)- } else if (revalidator.state === 'loading') {- setDataLoading(true)- }- }, [revalidator.state, deferredData, id])-// Get chart metrics and measure from URL params (SSR-friendly)const activeChartMetrics =searchParams.get('perfMetric') || CHART_METRICS_MAPPING_PERF.timing@@ -272,12 +146,75 @@ const PerformanceViewInner = ({setSearchParams(newParams)}- const overallCompare: Partial<OverallPerformanceObject> = useMemo(() => {- if (deferredData.perfOverallCompareStats && id) {- return deferredData.perfOverallCompareStats[id] || {}- }- return {}- }, [deferredData.perfOverallCompareStats, id])+ // The 'quantiles' allocation is a timeseries-only measure driven by the+ // metric dropdown; everywhere else we fall back to the regular measure.+ const effectiveMeasure =+ activeChartMetrics === CHART_METRICS_MAPPING_PERF.quantiles+ ? CHART_MEASURES_MAPPING_PERF.quantiles+ : activeMeasure+ const panelsMeasure =+ effectiveMeasure === CHART_MEASURES_MAPPING_PERF.quantiles+ ? CHART_MEASURES_MAPPING_PERF.median+ : activeMeasure++ // --- v2 queries ---++ const summaryQuery = useSummaryQuery('performance', {+ measure: activeMeasure,+ })+ const compareSummaryQuery = useCompareSummaryQuery('performance', {+ measure: activeMeasure,+ })+ const timeseriesQuery = useTimeseriesQuery('performance', {+ measure: effectiveMeasure,+ })+ const compareTimeseriesQuery = useCompareTimeseriesQuery('performance', {+ measure: effectiveMeasure,+ })++ const overall = useMemo(+ () => perfSummaryToOverall(summaryQuery.data?.data),+ [summaryQuery.data],+ )+ const overallCompare = useMemo(+ () => perfSummaryToOverall(compareSummaryQuery.data?.data),+ [compareSummaryQuery.data],+ )++ const chartData = useMemo(+ () =>+ pivotPerformanceTimeseries(timeseriesQuery.data?.data, effectiveMeasure),+ [timeseriesQuery.data, effectiveMeasure],+ )+ const chartDataCompare = useMemo(+ () =>+ compareTimeseriesQuery.data+ ? pivotPerformanceTimeseries(+ compareTimeseriesQuery.data.data,+ effectiveMeasure,+ )+ : undefined,+ [compareTimeseriesQuery.data, effectiveMeasure],+ )++ const summaryLoaded = Boolean(summaryQuery.data)++ const isPanelsDataEmptyRaw =+ summaryLoaded &&+ !overall.current?.frontend &&+ !overall.current?.network &&+ !overall.current?.backend++ if (summaryLoaded && !isPanelsDataEmptyRaw) {+ hasShownContentRef.current = true+ }++ // Don't show NoEvents if we've previously shown content (prevents flash during tab switch)+ const isPanelsDataEmpty = isPanelsDataEmptyRaw && !hasShownContentRef.current++ const isInitialLoading =+ (summaryQuery.isLoading || timeseriesQuery.isLoading) &&+ !hasShownContentRef.currentconst handleDataPointClick = useCallback((d: { x: Date; index: number; xValue?: string }) => {@@ -294,14 +231,9 @@ const PerformanceViewInner = ({[timeBucket, timeFormat, timezone],)- const chartDataCompare: any = useMemo(- () => deferredData.perfCompareData?.chart || {},- [deferredData.perfCompareData],- )-// Filter annotations to only those within the chart's visible x-axis rangeconst filteredAnnotations = useMemo(() => {- const xAxis = (chartData as { x?: string[] })?.x+ const xAxis = chartData?.xif (!annotations?.length || !xAxis?.length) return annotations || []const rangeStart = dayjs(xAxis[0]).startOf('day')@@ -316,19 +248,6 @@ const PerformanceViewInner = ({})}, [annotations, chartData])- // Panel active tabs- const [activeTabs, setActiveTabs] = useState<{- location: 'cc' | 'rg' | 'ct' | 'map'- page: 'pg' | 'host'- device: 'br' | 'os' | 'dv'- network: 'isp' | 'og' | 'ut' | 'ctp'- }>({- location: 'cc',- page: 'pg',- device: 'br',- network: 'isp',- })-const chartMetrics = useMemo(() => [{@@ -411,47 +330,178 @@ const PerformanceViewInner = ({[t],)- // Version data mapping for browser/OS versions- const createVersionDataMapping = useMemo(() => {- const browserDataSource = panelsData.data?.brv-- const browserVersions: {- [key: string]: { name: string; count: number }[]- } = {}-- if (browserDataSource) {- browserDataSource.forEach((entry: any) => {- const { br, name, count } = entry- if (!browserVersions[br]) {- browserVersions[br] = []- }- browserVersions[br].push({ name, count })- })- }-- return { browserVersions }- }, [panelsData.data?.brv])-- // Handle refresh trigger- useEffect(() => {- if (performanceRefreshTrigger > 0) {- revalidator.revalidate()- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [performanceRefreshTrigger])+ // --- Panels ---++ const locationSubTabs = useMemo<BreakdownSubTab[]>(+ () => [+ { id: 'country', label: t('project.mapping.cc'), dimension: 'country' },+ { id: 'region', label: t('project.mapping.rg'), dimension: 'region' },+ { id: 'city', label: t('project.mapping.ct'), dimension: 'city' },+ {+ id: 'map',+ label: t('project.mapping.map'),+ render: () => (+ <PerformanceMap isFullscreen={false} measure={panelsMeasure} />+ ),+ },+ ],+ [t, panelsMeasure],+ )++ const pagesSubTabs = useMemo<BreakdownSubTab[]>(+ () => [+ { id: 'page', label: t('project.mapping.pg'), dimension: 'page' },+ { id: 'host', label: t('project.mapping.host'), dimension: 'host' },+ ],+ [t],+ )++ const devicesSubTabs = useMemo<BreakdownSubTab[]>(+ () => [+ {+ id: 'browser',+ label: t('project.mapping.br'),+ dimension: 'browser',+ versionsDimension: 'browser_version' as const,+ versionsParentField: 'browser' as const,+ },+ { id: 'device', label: t('project.mapping.dv'), dimension: 'device' },+ ],+ [t],+ )++ const networkSubTabs = useMemo<(BreakdownSubTab | BreakdownSubTab[])[]>(+ () => [+ [+ { id: 'isp', label: t('project.mapping.isp'), dimension: 'isp' },+ {+ id: 'organization',+ label: t('project.mapping.og'),+ dimension: 'organization',+ },+ {+ id: 'user_type',+ label: t('project.mapping.ut'),+ dimension: 'user_type',+ },+ {+ id: 'connection_type',+ label: t('project.mapping.ctp'),+ dimension: 'connection_type',+ },+ ],+ ],+ [t],+ )++ const locationRowMapper = useCallback(+ (entry: Entry) => {+ const { name: entryName, cc } = entry++ if (cc !== undefined) {+ return (+ <CCRow cc={cc} name={entryName || undefined} language={language} />+ )+ }++ return <CCRow cc={entryName} language={language} />+ },+ [language],+ )++ const pagesRowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const { name: entryName } = entry++ if (!entryName) {+ return (+ <span className='italic'>+ {subTabId === 'host'+ ? t('project.unknownHost')+ : t('common.notSet')}+ </span>+ )+ }++ let decodedUri = entryName++ try {+ decodedUri = decodeURIComponent(entryName)+ } catch {+ // do nothing+ }++ if (subTabId === 'page' && project?.websiteUrl) {+ return (+ <PageLinkRow pagePath={decodedUri} websiteUrl={project.websiteUrl} />+ )+ }++ return decodedUri+ },+ [t, project?.websiteUrl],+ )++ const devicesRowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const v1Tab = subTabId === 'browser' ? 'br' : 'dv'+ const mapper = getDeviceRowMapper(v1Tab, theme, t) as+ | ((entry: Entry) => React.ReactNode)+ | undefined+ return mapper ? mapper(entry) : entry.name+ },+ [theme, t],+ )++ const networkRowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const { name: entryName } = entry+ if (!entryName) {+ return <span className='italic'>{t('common.notSet')}</span>+ }+ if (subTabId === 'user_type') {+ return getUsageTypeLabel(entryName, t)+ }+ if (subTabId === 'connection_type') {+ return getConnectionTypeLabel(entryName, t)+ }+ return entryName+ },+ [t],+ )++ // Panel values are load times in seconds -> render as '1.2s' / '350ms'.+ // Panel's valueMapper is typed as number -> number but has always accepted+ // display strings at runtime (v1 did the same via @ts-expect-error).+ const loadTimeValueMapper = useCallback(+ (value: number) =>+ getStringFromTime(getTimeFromSeconds(value), true) as unknown as number,+ [],+ )// Show waiting state if project has no traffic data yetif (!project?.isDataExists) {return <WaitingForAnEvent />}- // Show no events if data is empty+ const headerRightContent = <ProjectViewHeaderActions tnMapping={tnMapping} />++ if (isInitialLoading) {+ return (+ <>+ <DashboardHeader rightContent={headerRightContent} />+ <div className='relative overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>+ <MetricCardsSkeleton cards={3} />+ <ChartSkeleton className='mt-4 h-80 md:h-80' />+ </div>+ </>+ )+ }+if (isPanelsDataEmpty) {return (<>- <DashboardHeader- rightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}- />+ <DashboardHeader rightContent={headerRightContent} /><NoEvents filters={filters} /></>)@@ -459,48 +509,15 @@ const PerformanceViewInner = ({// Fullscreen map view - takes over the entire content areaif (isMapFullscreen && fullscreenMapRef.current) {- const countryData = panelsData.data?.cc || []- const regionData = panelsData.data?.rg || []- const total = countryData.reduce(- (acc: number, curr: any) => acc + curr.count,- 0,- )-return createPortal(- <Suspense- fallback={- <div className='flex h-full flex-1 items-center justify-center'>- <div className='flex flex-col items-center gap-2'>- <div className='h-8 w-8 animate-spin rounded-full border-2 border-indigo-400 border-t-transparent' />- <span className='text-sm text-neutral-600 dark:text-neutral-300'>- Loading map...- </span>- </div>- </div>- }- >- <InteractiveMap- data={countryData}- regionData={regionData}- total={total}- onClick={(type, key) => {- const link = getFilterLink(type, key)- navigate(link)- }}- onFullscreenToggle={setIsMapFullscreen}- isFullscreen={true}- />- </Suspense>,+ <PerformanceMap isFullscreen measure={panelsMeasure} />,fullscreenMapRef.current,)}return (<>- <DashboardHeader- rightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}- />- {dataLoading && !isPanelsDataEmpty ? <LoadingBar /> : null}+ <DashboardHeader rightContent={headerRightContent} /><div className={cx({ hidden: isPanelsDataEmpty })}>{!isPanelsDataEmpty ? (<Filters className='mb-3' tnMapping={tnMapping} />@@ -556,15 +573,19 @@ const PerformanceViewInner = ({/></div>- {!_isEmpty(overall) ? (+ {summaryQuery.isLoading ? (+ <MetricCardsSkeleton cards={3} />+ ) : !_isEmpty(overall) ? (<PerformanceMetricCardsoverall={overall}overallCompare={overallCompare}/>) : null}- {activeChartMetrics && !_isEmpty(chartData) ? (+ {timeseriesQuery.isLoading ? (+ <ChartSkeleton className='mt-5 h-80 md:mt-0 md:h-80' />+ ) : activeChartMetrics && !_isEmpty(chartData.x) ? (<div- onContextMenu={(e) => handleChartContextMenu(e, chartData?.x)}+ onContextMenu={(e) => handleChartContextMenu(e, chartData.x)}className='relative'><PerformanceChart@@ -586,254 +607,66 @@ const PerformanceViewInner = ({) : null}</div><div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>- {!_isEmpty(panelsData.types)- ? _map(PERFORMANCE_PANELS_ORDER, (type: keyof typeof tnMapping) => {- if (type === 'location') {- const locationTabs = [- { id: 'cc', label: t('project.mapping.cc') },- { id: 'rg', label: t('project.mapping.rg') },- { id: 'ct', label: t('project.mapping.ct') },- { id: 'map', label: 'Map' },- ]-- const rowMapper = (entry: CountryEntry) => {- const { name: entryName, cc } = entry-- if (cc !== undefined) {- return (- <CCRow- cc={cc}- name={entryName || undefined}- language={language}- />- )- }-- return <CCRow cc={entryName} language={language} />- }-- return (- <Panel- key={activeTabs.location}- icon={panelIconMapping.cc}- id={activeTabs.location}- getFilterLink={getFilterLink}- name={t('project.location')}- tabs={locationTabs}- onTabChange={(tab) =>- setActiveTabs({- ...activeTabs,- location: tab as 'cc' | 'rg' | 'ct' | 'map',- })- }- activeTabId={activeTabs.location}- data={panelsData.data[activeTabs.location]}- rowMapper={rowMapper}- // @ts-expect-error- valueMapper={(value) =>- getStringFromTime(getTimeFromSeconds(value), true)- }- customRenderer={- activeTabs.location === 'map'- ? () => {- const countryData = panelsData.data?.cc || []- const regionData = panelsData.data?.rg || []- const total = countryData.reduce(- (acc: number, curr: any) => acc + curr.count,- 0,- )-- return (- <Suspense fallback={<MapLoader />}>- <InteractiveMap- data={countryData}- regionData={regionData}- total={total}- onClick={(type, key) => {- const link = getFilterLink(type, key)- navigate(link)- }}- onFullscreenToggle={setIsMapFullscreen}- isFullscreen={false}- />- </Suspense>- )- }- : undefined- }- valuesHeaderName={t('project.loadTime')}- highlightColour='orange'- />- )- }-- if (type === 'devices') {- const deviceTabs = [- { id: 'br', label: t('project.mapping.br') },- { id: 'dv', label: t('project.mapping.dv') },- ]-- return (- <Panel- key={activeTabs.device}- icon={panelIconMapping.os}- id={activeTabs.device}- getFilterLink={getFilterLink}- name={t('project.devices')}- tabs={deviceTabs}- onTabChange={(tab) =>- setActiveTabs({- ...activeTabs,- device: tab as 'br' | 'dv',- })- }- activeTabId={activeTabs.device}- data={panelsData.data[activeTabs.device]}- rowMapper={getDeviceRowMapper(- activeTabs.device,- theme,- t,- )}- capitalize={activeTabs.device === 'dv'}- versionData={- activeTabs.device === 'br'- ? createVersionDataMapping.browserVersions- : undefined- }- getVersionFilterLink={(parent, version) =>- getVersionFilterLink(parent, version, 'br')- }- // @ts-expect-error- valueMapper={(value) =>- getStringFromTime(getTimeFromSeconds(value), true)- }- valuesHeaderName={t('project.loadTime')}- highlightColour='orange'- />- )- }-- if (type === 'network') {- const networkTabs = [- [- { id: 'isp', label: t('project.mapping.isp') },- { id: 'og', label: t('project.mapping.og') },- { id: 'ut', label: t('project.mapping.ut') },- { id: 'ctp', label: t('project.mapping.ctp') },- ],- ]-- const activeNetworkTab = activeTabs.network-- return (- <Panel- key={activeNetworkTab}- icon={panelIconMapping.isp}- id={activeNetworkTab}- getFilterLink={getFilterLink}- name={t('project.network')}- tabs={networkTabs}- onTabChange={(tab) =>- setActiveTabs({- ...activeTabs,- network: tab as 'isp' | 'og' | 'ut' | 'ctp',- })- }- activeTabId={activeNetworkTab}- data={panelsData.data[activeNetworkTab]}- rowMapper={({ name: entryName }) => {- if (!entryName) {- return (- <span className='italic'>{t('common.notSet')}</span>- )- }- if (activeNetworkTab === 'ut') {- return getUsageTypeLabel(entryName, t)- }- if (activeNetworkTab === 'ctp') {- return getConnectionTypeLabel(entryName, t)- }- return entryName- }}- // @ts-expect-error- valueMapper={(value) =>- getStringFromTime(getTimeFromSeconds(value), true)- }- valuesHeaderName={t('project.loadTime')}- highlightColour='orange'- />- )- }-- if (type === 'pg') {- const pageTabs = [- { id: 'pg', label: t('project.mapping.pg') },- {- id: 'host',- label: t('project.mapping.host'),- },- ]-- return (- <Panel- key={activeTabs.page}- icon={panelIconMapping.pg}- id={activeTabs.page}- getFilterLink={getFilterLink}- rowMapper={({ name: entryName }) => {- if (!entryName) {- return (- <span className='italic'>- {activeTabs.page === 'pg'- ? t('common.notSet')- : t('project.unknownHost')}- </span>- )- }-- let decodedUri = entryName as string-- try {- decodedUri = decodeURIComponent(entryName)- } catch {- // do nothing- }-- // For page paths (pg tab), show with clickable link- if (activeTabs.page === 'pg' && project?.websiteUrl) {- return (- <PageLinkRow- pagePath={decodedUri}- websiteUrl={project.websiteUrl}- />- )- }-- return decodedUri- }}- name={t('project.pages')}- tabs={pageTabs}- onTabChange={(tab) =>- setActiveTabs({- ...activeTabs,- page: tab as 'pg' | 'host',- })- }- activeTabId={activeTabs.page}- data={panelsData.data[activeTabs.page]}- // @ts-expect-error- valueMapper={(value) =>- getStringFromTime(getTimeFromSeconds(value), true)- }- valuesHeaderName={t('project.loadTime')}- highlightColour='orange'- />- )- }-- return null- })- : null}+ <BreakdownPanel+ dataType='performance'+ highlightColour='orange'+ panelId='location'+ name={t('project.location')}+ icon={panelIconMapping.country}+ subTabs={locationSubTabs}+ primaryMetric='load_time'+ metrics={['load_time']}+ measure={panelsMeasure}+ rowMapper={locationRowMapper}+ valueMapper={loadTimeValueMapper}+ valuesHeaderName={t('project.loadTime')}+ />+ <BreakdownPanel+ dataType='performance'+ highlightColour='orange'+ panelId='pages'+ name={t('project.pages')}+ icon={panelIconMapping.page}+ subTabs={pagesSubTabs}+ primaryMetric='load_time'+ metrics={['load_time']}+ measure={panelsMeasure}+ rowMapper={pagesRowMapper}+ valueMapper={loadTimeValueMapper}+ valuesHeaderName={t('project.loadTime')}+ />+ <BreakdownPanel+ dataType='performance'+ highlightColour='orange'+ panelId='devices'+ name={t('project.devices')}+ icon={panelIconMapping.os}+ subTabs={devicesSubTabs}+ primaryMetric='load_time'+ metrics={['load_time']}+ measure={panelsMeasure}+ rowMapper={devicesRowMapper}+ valueMapper={loadTimeValueMapper}+ capitalize={['device']}+ getVersionFilterLink={(parent, version) =>+ getVersionFilterLink(parent, version, 'browser')+ }+ valuesHeaderName={t('project.loadTime')}+ />+ <BreakdownPanel+ dataType='performance'+ highlightColour='orange'+ panelId='network'+ name={t('project.network')}+ icon={panelIconMapping.isp}+ subTabs={networkSubTabs}+ primaryMetric='load_time'+ metrics={['load_time']}+ measure={panelsMeasure}+ rowMapper={networkRowMapper}+ valueMapper={loadTimeValueMapper}+ valuesHeaderName={t('project.loadTime')}+ /></div><AnnotationModalisOpened={isAnnotationModalOpen}diff --git a/web/app/pages/Project/tabs/Performance/perfAdapters.ts b/web/app/pages/Project/tabs/Performance/perfAdapters.tsnew file mode 100644index 000000000..3a69ae6f2--- /dev/null+++ b/web/app/pages/Project/tabs/Performance/perfAdapters.ts@@ -0,0 +1,89 @@+import { PerformanceSummaryData, TimeseriesRow } from '~/api/v2/types'+import { OverallPerformanceObject } from '~/lib/models/Project'++// Adapters that pivot v2 performance API responses into the shapes the+// existing UI components (PerformanceMetricCards, getColumnsPerf chart+// pipeline) already consume, so those components stay untouched.++/** v2 performance summary -> the shape PerformanceMetricCards consumes */+export const perfSummaryToOverall = (+ summary: PerformanceSummaryData | undefined,+): Partial<OverallPerformanceObject> => {+ if (!summary) return {}++ return {+ current: summary.current,+ previous: summary.previous,+ frontendChange: summary.change.frontend,+ backendChange: summary.change.backend,+ networkChange: summary.change.network,+ }+}++/**+ * v2 ISO timestamp -> the 'YYYY-MM-DD HH:mm:ss' wall-time string the chart+ * pipeline expects. The timestamp is already in the requested timezone, so we+ * take its literal date-time part instead of letting Date/dayjs re-shift it+ * into the browser timezone.+ */+const toChartX = (timestamp: string): string =>+ timestamp.slice(0, 19).replace('T', ' ')++/**+ * Performance timeseries rows -> the columnar shape getColumnsPerf() consumes:+ * { x, dns, tls, conn, response, render, domLoad, ttfb } (note the key renames+ * connection -> conn, dom_load -> domLoad), or { x, p50, p75, p95 } when+ * measure === 'quantiles'. The chart pipeline is typed Record<string, string[]>+ * but has always carried numbers at runtime (v1 did the same), hence the cast.+ */+export const pivotPerformanceTimeseries = (+ rows: TimeseriesRow[] | undefined,+ measure: string,+): Record<string, string[]> => {+ const x: string[] = []++ if (measure === 'quantiles') {+ const p50: number[] = []+ const p75: number[] = []+ const p95: number[] = []++ for (const row of rows || []) {+ x.push(toChartX(row.timestamp))+ p50.push(Number(row.p50 ?? 0))+ p75.push(Number(row.p75 ?? 0))+ p95.push(Number(row.p95 ?? 0))+ }++ return { x, p50, p75, p95 } as unknown as Record<string, string[]>+ }++ const dns: number[] = []+ const tls: number[] = []+ const conn: number[] = []+ const response: number[] = []+ const render: number[] = []+ const domLoad: number[] = []+ const ttfb: number[] = []++ for (const row of rows || []) {+ x.push(toChartX(row.timestamp))+ dns.push(Number(row.dns ?? 0))+ tls.push(Number(row.tls ?? 0))+ conn.push(Number(row.connection ?? 0))+ response.push(Number(row.response ?? 0))+ render.push(Number(row.render ?? 0))+ domLoad.push(Number(row.dom_load ?? 0))+ ttfb.push(Number(row.ttfb ?? 0))+ }++ return {+ x,+ dns,+ tls,+ conn,+ response,+ render,+ domLoad,+ ttfb,+ } as unknown as Record<string, string[]>+}diff --git a/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx b/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsxindex 5187780b7..23b0dce53 100644--- a/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx+++ b/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx@@ -65,11 +65,11 @@ interface PageflowItem {currency?: string}-interface ProfileSession {+export interface ProfileSession {psid: string- cc: string | null+ country: string | nullos: string | null- br: string | null+ browser: string | nullpageviews: numbercustomEvents: numbererrors: number@@ -79,7 +79,7 @@ interface ProfileSession {sessionStart?: stringlastActivity?: stringisLive?: 1 | 0 | boolean- sdur?: number+ duration?: number | nullpages?: PageflowItem[]}@@ -155,8 +155,8 @@ const formatVersionLabel = (name: string | null, version: string | null) => {}const getSessionDuration = (session: ProfileSession) => {- if (session.sdur != null) {- return session.sdur+ if (session.duration != null) {+ return session.duration}const interactionPages = (session.pages || []).filter(@@ -431,13 +431,15 @@ const ProfileSessionFlow = ({},]: []),- ...(session.br+ ...(session.browser? [{key: 'browser',- label: session.br,- tooltip: session.br,- icon: <BrowserIcon browser={session.br} className='size-3.5' />,+ label: session.browser,+ tooltip: session.browser,+ icon: (+ <BrowserIcon browser={session.browser} className='size-3.5' />+ ),},]: []),@@ -620,14 +622,17 @@ export const ProfileDetails = ({const statusTooltip = details.lastSeen? t('project.lastSeenAgo', { time: lastSeenAgo }): t('project.unknown')- const countryName = details.cc- ? countries.getName(details.cc, language) || details.cc+ const countryName = details.country+ ? countries.getName(details.country, language) || details.country: nullconst locationSummary =- [countryName, details.rg, details.ct].filter(Boolean).join(', ') ||+ [countryName, details.region, details.city].filter(Boolean).join(', ') ||t('project.unknown')- const osTooltipLabel = formatVersionLabel(details.os, details.osv)- const browserTooltipLabel = formatVersionLabel(details.br, details.brv)+ const osTooltipLabel = formatVersionLabel(details.os, details.os_version)+ const browserTooltipLabel = formatVersionLabel(+ details.browser,+ details.browser_version,+ )const profilePlatformParts: PlatformPart[] = [...(details.os? [@@ -639,13 +644,13 @@ export const ProfileDetails = ({},]: []),- ...(details.br+ ...(details.browser? [{key: 'browser',- label: details.br,- tooltip: browserTooltipLabel || details.br,- icon: <BrowserIcon browser={details.br} className='size-4' />,+ label: details.browser,+ tooltip: browserTooltipLabel || details.browser,+ icon: <BrowserIcon browser={details.browser} className='size-4' />,},]: []),@@ -803,10 +808,10 @@ export const ProfileDetails = ({colour='primary'className='flex h-6 items-center justify-center'>- {details.cc ? (+ {details.country ? (<FlagclassName='rounded-xs'- country={details.cc}+ country={details.country}size={16}alt=''aria-hidden='true'@@ -983,16 +988,18 @@ export const ProfileDetails = ({<InfoRowlabel={t('project.mapping.lc')}value={- details.lc ? getLocaleDisplayName(details.lc, language) : '-'+ details.locale+ ? getLocaleDisplayName(details.locale, language)+ : '-'}/><InfoRowlabel={t('project.mapping.dv')}value={- details.dv ? (+ details.device ? (<>- <DeviceIcon device={details.dv} />- {_capitalize(details.dv)}+ <DeviceIcon device={details.device} />+ {_capitalize(details.device)}</>) : ('-'diff --git a/web/app/pages/Project/tabs/Profiles/Profiles.tsx b/web/app/pages/Project/tabs/Profiles/Profiles.tsxindex a1c918a9c..05124c320 100644--- a/web/app/pages/Project/tabs/Profiles/Profiles.tsx+++ b/web/app/pages/Project/tabs/Profiles/Profiles.tsx@@ -152,15 +152,15 @@ const ProfileRow = ({ profile, timeFormat }: ProfileRowProps) => {<div className='flex items-center gap-1.5'><Tooltiptext={- profile.cc- ? countries.getName(profile.cc, language) ||- profile.cc+ profile.country+ ? countries.getName(profile.country, language) ||+ profile.country: t('project.unknownCountry')}tooltipNode={<div className='flex h-[22px] w-[22px] items-center justify-center rounded bg-gray-100/80 ring-1 ring-gray-200/50 dark:bg-slate-800/80 dark:ring-slate-700/50'><Flag- country={profile.cc}+ country={profile.country}size={14}className='rounded-[2px]'aria-hidden='true'@@ -181,11 +181,11 @@ const ProfileRow = ({ profile, timeFormat }: ProfileRowProps) => {}/><Tooltip- text={profile.br || t('project.unknown')}+ text={profile.browser || t('project.unknown')}tooltipNode={<div className='flex h-[22px] w-[22px] items-center justify-center rounded bg-gray-100/80 ring-1 ring-gray-200/50 dark:bg-slate-800/80 dark:ring-slate-700/50'><BrowserIcon- browser={profile.br}+ browser={profile.browser}className='size-3.5'/></div>diff --git a/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx b/web/app/pages/Project/tabs/Profiles/ProfilesView.tsxindex 8bca43290..e1bbee186 100644--- a/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx+++ b/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx@@ -1,87 +1,42 @@import _isEmpty from 'lodash/isEmpty'-import { useState, useEffect, useMemo, useRef } from 'react'+import { useState, useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'import { useSearchParams } from 'react-router'-import { ApiProfile } from '~/api/api.server'import {- useProfilesProxy,- useProfileProxy,- useProfileSessionsProxy,-} from '~/hooks/useAnalyticsProxy'+ useProfileDetailsQuery,+ useProfileSessionsQuery,+ useProfilesListQuery,+} from '~/hooks/v2/useV2Queries'import {Profile,ProfileDetails as ProfileDetailsType,- Session,} from '~/lib/models/Project'import NoProfiles from '~/pages/Project/tabs/Profiles/components/NoProfiles'-import { ProfileDetails } from '~/pages/Project/tabs/Profiles/ProfileDetails'+import {+ ProfileDetails,+ type ProfileSession,+} from '~/pages/Project/tabs/Profiles/ProfileDetails'import { Profiles } from '~/pages/Project/tabs/Profiles/Profiles'import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'import ProjectViewHeaderActions from '~/pages/Project/View/components/ProjectViewHeaderActions'-import {- useViewProjectContext,- useRefreshTriggers,-} from '~/pages/Project/View/ViewProject'-import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'-import {- useCurrentProject,- useProjectPassword,-} from '~/providers/CurrentProjectProvider'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'+import { useCurrentProject } from '~/providers/CurrentProjectProvider'import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'import LoadingBar from '~/ui/LoadingBar'import Filters from '../../View/components/Filters'import { LoaderView } from '../../View/components/LoaderView'-const mapApiProfileToUI = (apiProfile: ApiProfile): Profile => ({- profileId: apiProfile.profileId,- isIdentified: apiProfile.isIdentified,- sessionsCount: apiProfile.sessionsCount,- pageviewsCount: apiProfile.pageviewsCount,- eventsCount: apiProfile.eventsCount,- errorsCount: apiProfile.errorsCount,- firstSeen: apiProfile.firstSeen,- lastSeen: apiProfile.lastSeen,- cc: apiProfile.cc,- os: apiProfile.os,- br: apiProfile.br,- dv: apiProfile.dv,-})--const SESSIONS_TAKE = 30-interface ProfilesViewProps {tnMapping: Record<string, string>}const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {- const { id, project } = useCurrentProject()- const projectPassword = useProjectPassword(id)- const { profilesRefreshTrigger } = useRefreshTriggers()- const { timezone, period, dateRange, filters, timeFormat } =- useViewProjectContext()+ const { project } = useCurrentProject()+ const { filters, timeFormat } = useViewProjectContext()const { t } = useTranslation('common')const [searchParams] = useSearchParams()- const profilesProxy = useProfilesProxy()- const profileProxy = useProfileProxy()- const profileSessionsProxy = useProfileSessionsProxy()-- const [profilesSkip, setProfilesSkip] = useState(0)- const [canLoadMoreProfiles, setCanLoadMoreProfiles] = useState(false)- const [profiles, setProfiles] = useState<Profile[]>([])- const [profilesLoading, setProfilesLoading] = useState<boolean | null>(null)- const [activeProfile, setActiveProfile] = useState<ProfileDetailsType | null>(- null,- )- const [profileLoading, setProfileLoading] = useState(false)- const [profileSessions, setProfileSessions] = useState<Session[]>([])- const [profileSessionsLoading, setProfileSessionsLoading] = useState<- boolean | null- >(null)- const [profileSessionsSkip, setProfileSessionsSkip] = useState(0)- const [canLoadMoreProfileSessions, setCanLoadMoreProfileSessions] =- useState(false)const [profileTypeFilter, setProfileTypeFilter] = useState<'all' | 'anonymous' | 'identified'>('all')@@ -90,264 +45,45 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {return searchParams.get('profileId')}, [searchParams])- const prevActiveProfileIdRef = useRef<string | null>(activeProfileId)- const profilesRequestIdRef = useRef(0)- const profileRequestIdRef = useRef(0)- const profileSessionsRequestIdRef = useRef(0)- const skipNextProfilesAutoLoadRef = useRef(false)- const isMountedRef = useRef(true)-- useEffect(() => {- isMountedRef.current = true- return () => {- isMountedRef.current = false- }- }, [])-- const loadProfiles = async (- forcedSkip?: number,- override?: boolean,- options: { take?: number; limit?: number } = {},- ) => {- if (profilesLoading) {- return- }-- const requestId = ++profilesRequestIdRef.current- setProfilesLoading(true)-- try {- const skip = typeof forcedSkip === 'number' ? forcedSkip : profilesSkip- let from = ''- let to = ''-- if (dateRange) {- from = getFormatDate(dateRange[0])- to = getFormatDate(dateRange[1])- }-- const dataProfiles = await profilesProxy.fetchProfiles(id, {- period: period === 'custom' && dateRange ? 'custom' : period,- filters,- from: period === 'custom' && dateRange ? from : '',- to: period === 'custom' && dateRange ? to : '',- take: options.take || SESSIONS_TAKE,- skip,- timezone,- profileType: profileTypeFilter,- })-- if (requestId === profilesRequestIdRef.current && isMountedRef.current) {- const profilesList = (dataProfiles?.profiles || []).map(- mapApiProfileToUI,- )- const visibleProfiles =- typeof options.limit === 'number'- ? profilesList.slice(0, options.limit)- : profilesList-- if (override) {- setProfiles(visibleProfiles)- } else {- setProfiles((prev) => [...prev, ...visibleProfiles])- }- setProfilesSkip(skip + visibleProfiles.length)-- if (typeof options.limit === 'number') {- setCanLoadMoreProfiles(profilesList.length > options.limit)- } else {- setCanLoadMoreProfiles(- profilesList.length >= (options.take || SESSIONS_TAKE),- )- }- }- } catch (reason) {- console.error(- '[ERROR](loadProfiles) Loading profiles data failed:',- reason,- )- } finally {- if (requestId === profilesRequestIdRef.current && isMountedRef.current) {- setProfilesLoading(false)- }- }- }-- const loadProfile = async (- profileId: string,- options: { sessionsTake?: number; sessionsLimit?: number } = {},- ) => {- const requestId = ++profileRequestIdRef.current- const hasExistingProfileData =- !!activeProfile && activeProfile.profileId === profileId-- setProfileLoading(true)- if (!hasExistingProfileData) {- setProfileSessions([])- setProfileSessionsSkip(0)- setCanLoadMoreProfileSessions(false)- }-- try {- const data = await profileProxy.fetchProfile(id, profileId, {- timezone,- })-- if (- requestId === profileRequestIdRef.current &&- isMountedRef.current &&- data- ) {- setActiveProfile(data as unknown as ProfileDetailsType)- loadProfileSessionsData(profileId, 0, true, {- take: options.sessionsTake,- limit: options.sessionsLimit,- })+ const profilesQuery = useProfilesListQuery({+ profileType: profileTypeFilter,+ enabled: !activeProfileId,+ })+ const profileDetailsQuery = useProfileDetailsQuery(activeProfileId)+ const profileSessionsQuery = useProfileSessionsQuery(activeProfileId)++ const profiles = useMemo(() => {+ const rows = (profilesQuery.data?.pages || []).flatMap(+ (page) => page.data,+ ) as unknown as Profile[]++ // Deduplicate by profileId: offset-based pages may overlap when new+ // profiles arrive between page loads+ const seen = new Set<string>()+ return rows.filter((profile) => {+ if (seen.has(profile.profileId)) {+ return false}- } catch (reason) {- console.error('[ERROR](loadProfile) Loading profile data failed:', reason)- if (requestId === profileRequestIdRef.current && isMountedRef.current) {- setActiveProfile(null)- }- } finally {- if (requestId === profileRequestIdRef.current && isMountedRef.current) {- setProfileLoading(false)- }- }- }-- const loadProfileSessionsData = async (- profileId: string,- forcedSkip?: number,- override?: boolean,- options: { take?: number; limit?: number } = {},- ) => {- if (profileSessionsLoading) {- return- }-- const requestId = ++profileSessionsRequestIdRef.current- setProfileSessionsLoading(true)-- try {- const skip =- typeof forcedSkip === 'number' ? forcedSkip : profileSessionsSkip-- const dataSessions = await profileSessionsProxy.fetchProfileSessions(- id,- profileId,- {- period: 'all',- filters: [],- take: options.take || SESSIONS_TAKE,- skip,- timezone,- },- )-- if (- requestId === profileSessionsRequestIdRef.current &&- isMountedRef.current- ) {- const sessionsList = (dataSessions?.sessions ||- []) as unknown as Session[]- const visibleSessions =- typeof options.limit === 'number'- ? sessionsList.slice(0, options.limit)- : sessionsList+ seen.add(profile.profileId)+ return true+ })+ }, [profilesQuery.data])++ const profileSessions = useMemo(+ () =>+ (profileSessionsQuery.data?.pages || []).flatMap(+ (page) => page.data,+ ) as unknown as ProfileSession[],+ [profileSessionsQuery.data],+ )- if (override) {- setProfileSessions(visibleSessions)- } else {- setProfileSessions((prev) => [...prev, ...visibleSessions])- }- setProfileSessionsSkip(skip + visibleSessions.length)+ // Track if we've shown content in the current data set to prevent NoProfiles flash+ const hasShownContentRef = useRef(false)- if (typeof options.limit === 'number') {- setCanLoadMoreProfileSessions(sessionsList.length > options.limit)- } else {- setCanLoadMoreProfileSessions(- sessionsList.length >= (options.take || SESSIONS_TAKE),- )- }- }- } catch (reason) {- console.error(- '[ERROR](loadProfileSessions) Loading profile sessions failed:',- reason,- )- } finally {- if (- requestId === profileSessionsRequestIdRef.current &&- isMountedRef.current- ) {- setProfileSessionsLoading(false)- }- }+ if (profilesQuery.data) {+ hasShownContentRef.current = !_isEmpty(profiles)}- useEffect(() => {- if (!project || activeProfileId) {- return- }-- if (skipNextProfilesAutoLoadRef.current) {- skipNextProfilesAutoLoadRef.current = false- return- }-- setProfilesSkip(0)- loadProfiles(0, true)- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [- dateRange,- filters,- id,- period,- projectPassword,- timezone,- project,- activeProfileId,- profileTypeFilter,- ])-- useEffect(() => {- if (!activeProfileId || !project) {- return- }-- loadProfile(activeProfileId)- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [activeProfileId, project, timezone, projectPassword, id])-- useEffect(() => {- const prevProfileId = prevActiveProfileIdRef.current- prevActiveProfileIdRef.current = activeProfileId-- if (prevProfileId && !activeProfileId) {- setProfilesSkip(0)- skipNextProfilesAutoLoadRef.current = true- loadProfiles(0, true)- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [activeProfileId])-- useEffect(() => {- if (profilesRefreshTrigger > 0) {- if (activeProfileId) {- const limit = Math.max(profileSessions.length, SESSIONS_TAKE)- loadProfile(activeProfileId, {- sessionsTake: limit + 1,- sessionsLimit: limit,- })- } else {- const limit = Math.max(profiles.length, SESSIONS_TAKE)- loadProfiles(0, true, { take: limit + 1, limit })- }- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [profilesRefreshTrigger])-if (activeProfileId) {const backSearchParams = (() => {const params = new URLSearchParams(searchParams)@@ -355,22 +91,26 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {return params.toString()})()+ const activeProfile =+ (profileDetailsQuery.data?.data as unknown as+ | ProfileDetailsType+ | undefined) || null+return (<div>- {profileLoading && !activeProfile ? (+ {profileDetailsQuery.isLoading && !activeProfile ? (<LoaderView />) : (<ProfileDetailsdetails={activeProfile}sessions={profileSessions}- sessionsLoading={profileSessionsLoading}+ sessionsLoading={+ profileSessionsQuery.isLoading ||+ profileSessionsQuery.isFetchingNextPage+ }timeFormat={timeFormat}- onLoadMoreSessions={() => {- if (activeProfileId) {- loadProfileSessionsData(activeProfileId)- }- }}- canLoadMoreSessions={canLoadMoreProfileSessions}+ onLoadMoreSessions={() => profileSessionsQuery.fetchNextPage()}+ canLoadMoreSessions={Boolean(profileSessionsQuery.hasNextPage)}currency={project?.revenueCurrency}websiteUrl={project?.websiteUrl}backLink={`?${backSearchParams}`}@@ -381,35 +121,37 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {)}+ const profilesLoading = profilesQuery.isLoading+ const profilesRefetching =+ profilesQuery.isFetching &&+ !profilesQuery.isLoading &&+ !profilesQuery.isFetchingNextPage+return (<><DashboardHeadershowLiveVisitorsrightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}profileTypeFilter={profileTypeFilter}- onProfileTypeFilterChange={(type) => {- setProfileTypeFilter(type)- setProfilesSkip(0)- }}+ onProfileTypeFilterChange={setProfileTypeFilter}/>- {profilesLoading && !_isEmpty(profiles) ? <LoadingBar /> : null}+ {profilesRefetching && !_isEmpty(profiles) ? <LoadingBar /> : null}{!_isEmpty(profiles) ? (<Filters className='mb-3' tnMapping={tnMapping} />) : null}- {(profilesLoading === null || profilesLoading) && _isEmpty(profiles) ? (- <LoaderView />- ) : null}- {typeof profilesLoading === 'boolean' &&- !profilesLoading &&- _isEmpty(profiles) ? (+ {profilesLoading && _isEmpty(profiles) ? <LoaderView /> : null}+ {!profilesQuery.isFetching &&+ profilesQuery.data &&+ _isEmpty(profiles) &&+ !hasShownContentRef.current ? (<NoProfiles filters={filters} />) : null}<Profiles profiles={profiles} timeFormat={timeFormat} /><InfiniteScrollTrigger- hasMore={canLoadMoreProfiles}- isLoading={profilesLoading || profilesLoading === null}- onLoadMore={() => loadProfiles()}- disabled={profilesLoading || profilesLoading === null}+ hasMore={Boolean(profilesQuery.hasNextPage)}+ isLoading={profilesQuery.isFetchingNextPage}+ onLoadMore={() => profilesQuery.fetchNextPage()}+ disabled={profilesQuery.isFetching}className={profilesLoading && _isEmpty(profiles) ? 'hidden' : ''}/></>diff --git a/web/app/pages/Project/tabs/Profiles/components/NoProfiles.tsx b/web/app/pages/Project/tabs/Profiles/components/NoProfiles.tsxindex 59c355e2a..a3e6fbdeb 100644--- a/web/app/pages/Project/tabs/Profiles/components/NoProfiles.tsx+++ b/web/app/pages/Project/tabs/Profiles/components/NoProfiles.tsx@@ -3,13 +3,13 @@ import { UserIcon, FunnelIcon } from '@phosphor-icons/react'import { memo } from 'react'import { useTranslation } from 'react-i18next'+import { V2Filter } from '~/api/v2/types'import Filters from '~/pages/Project/View/components/Filters'-import { Filter } from '~/pages/Project/View/interfaces/traffic'import { typeNameMapping } from '~/pages/Project/View/ViewProject.helpers'import { Text } from '~/ui/Text'interface NoProfilesProps {- filters: Filter[]+ filters: V2Filter[]}const NoProfiles = ({ filters }: NoProfilesProps) => {diff --git a/web/app/pages/Project/tabs/Replays/NoReplays.tsx b/web/app/pages/Project/tabs/Replays/NoReplays.tsxindex 6e050a956..b60f63258 100644--- a/web/app/pages/Project/tabs/Replays/NoReplays.tsx+++ b/web/app/pages/Project/tabs/Replays/NoReplays.tsx@@ -8,9 +8,9 @@ import _isEmpty from 'lodash/isEmpty'import { memo } from 'react'import { Trans, useTranslation } from 'react-i18next'+import { V2Filter } from '~/api/v2/types'import { DOCS_URL } from '~/lib/constants'import Filters from '~/pages/Project/View/components/Filters'-import { Filter } from '~/pages/Project/View/interfaces/traffic'import { typeNameMapping } from '~/pages/Project/View/ViewProject.helpers'import { Text } from '~/ui/Text'@@ -22,7 +22,7 @@ const setupStepKeys = [] as constinterface NoReplaysProps {- filters: Filter[]+ filters: V2Filter[]hasReplayData: boolean}diff --git a/web/app/pages/Project/tabs/Replays/ReplaysView.tsx b/web/app/pages/Project/tabs/Replays/ReplaysView.tsxindex 751d3657b..1a631c191 100644--- a/web/app/pages/Project/tabs/Replays/ReplaysView.tsx+++ b/web/app/pages/Project/tabs/Replays/ReplaysView.tsx@@ -36,6 +36,7 @@ import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'import LoadingBar from '~/ui/LoadingBar'import Modal from '~/ui/Modal'import StatusPage from '~/ui/StatusPage'+import { v2FilterToLegacy } from '~/utils/analyticsUrl'import routes from '~/utils/routes'import { LoaderView } from '../../View/components/LoaderView'@@ -186,7 +187,8 @@ const ReplaysViewInner = ({from,to,timezone,- filters,+ // the replays endpoint is still v1 — convert filters at the boundary+ filters: filters.map(v2FilterToLegacy),take,skip,}diff --git a/web/app/pages/Project/tabs/SEO/SEOView.tsx b/web/app/pages/Project/tabs/SEO/SEOView.tsxindex 1eec0264e..5fed4ae5d 100644--- a/web/app/pages/Project/tabs/SEO/SEOView.tsx+++ b/web/app/pages/Project/tabs/SEO/SEOView.tsx@@ -14,19 +14,14 @@ import {import dayjs from 'dayjs'import _isEmpty from 'lodash/isEmpty'import _round from 'lodash/round'-import React, {- useEffect,- useCallback,- useMemo,- useRef,- use,- useState,-} from 'react'+import React, { useEffect, useCallback, useMemo, useRef, useState } from 'react'import { Trans, useTranslation } from 'react-i18next'import { Link } from '~/ui/Link'-import { useLoaderData, useSearchParams } from 'react-router'+import { useSearchParams } from 'react-router'import { useGSCDashboardProxy } from '~/hooks/useAnalyticsProxy'+import { useBreakdownQuery } from '~/hooks/v2/useV2Queries'+import { mapBreakdownRows } from '~/pages/Project/View/v2/adapters'import { useAnnotations } from '~/hooks/useAnnotations'import { DOCS_URL } from '~/lib/constants'import type { TimeBucket } from '~/lib/constants'@@ -58,7 +53,6 @@ import RefRow from '~/pages/Project/tabs/Traffic/RefRow'import CCRow from '~/pages/Project/View/components/CCRow'import { useCurrentProject } from '~/providers/CurrentProjectProvider'import { useTheme } from '~/providers/ThemeProvider'-import type { ProjectLoaderData } from '~/routes/projects.$id'import Checkbox from '~/ui/Checkbox'import Dropdown from '~/ui/Dropdown'import Loader from '~/ui/Loader'@@ -234,18 +228,16 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {}))}, [])- const { trafficData: trafficDataPromise } = useLoaderData<ProjectLoaderData>()-- const trafficData = trafficDataPromise ? use(trafficDataPromise) : null+ const referrerQuery = useBreakdownQuery('traffic', {+ dimension: 'referrer',+ limit: 100,+ sort: 'visitors:desc',+ })- const refEntries: Entry[] = useMemo(() => {- const refParams = trafficData?.params?.ref- if (!refParams) return []- return refParams.map((r: { name: string; count: number }) => ({- name: r.name,- count: r.count,- }))- }, [trafficData])+ const refEntries: Entry[] = useMemo(+ () => mapBreakdownRows(referrerQuery.data?.data),+ [referrerQuery.data],+ )const searchEngineEntries = useMemo(() => getSearchEngineReferrals(refEntries),@@ -966,7 +958,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {<CompactReferralPaneltitle={t('project.seo.searchEngines')}data={searchEngineEntries}- icon={panelIconMapping.ref}+ icon={panelIconMapping.referrer}rowMapper={refRowMapper}/><CompactReferralPanel@@ -1040,7 +1032,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {<Panelname={t('project.seo.topPages')}data={topPagesAsEntries}- icon={panelIconMapping.pg}+ icon={panelIconMapping.page}id='pg'activeTabId='pg'disableRowClick={false}@@ -1123,7 +1115,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {<Panelname={t('project.devices')}data={topDevicesAsEntries}- icon={panelIconMapping.dv}+ icon={panelIconMapping.device}id='device'activeTabId='dv'disableRowClickdiff --git a/web/app/pages/Project/tabs/SEO/seo-utils.ts b/web/app/pages/Project/tabs/SEO/seo-utils.tsindex e5c55028f..e1c3e6ce4 100644--- a/web/app/pages/Project/tabs/SEO/seo-utils.ts+++ b/web/app/pages/Project/tabs/SEO/seo-utils.ts@@ -1,7 +1,8 @@import dayjs from 'dayjs'import isoWeek from 'dayjs/plugin/isoWeek'import quarterOfYear from 'dayjs/plugin/quarterOfYear'-import type { Filter } from '~/pages/Project/View/interfaces/traffic'+import type { V2Filter } from '~/api/v2/types'+import { v2FilterToLegacy, type LegacyFilter } from '~/utils/analyticsUrl'dayjs.extend(isoWeek)dayjs.extend(quarterOfYear)@@ -125,17 +126,18 @@ export const aggregateDateSeries = (})}-export const getGSCCompatibleFilters = (filters: Filter[]): Filter[] => {+// The GSC endpoints still consume the legacy v1 filter shape+export const getGSCCompatibleFilters = (+ filters: V2Filter[],+): LegacyFilter[] => {return filters.flatMap((filter) => {if (- filter.column === 'pg' ||- filter.column === 'keywords' ||- filter.column === 'cc' ||- filter.column === 'country' ||- filter.column === 'dv' ||- filter.column === 'device'+ filter.dimension === 'page' ||+ filter.dimension === 'keywords' ||+ filter.dimension === 'country' ||+ filter.dimension === 'device') {- return [filter]+ return [v2FilterToLegacy(filter)]}return []diff --git a/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx b/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsxindex 22e6a03ce..fa818a0f6 100644--- a/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx+++ b/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx@@ -196,8 +196,8 @@ export const SessionDetailView = ({const sessionDuration = useMemo(() => {if (!activeSession?.details) return 0- if (activeSession.details.sdur && activeSession.details.sdur > 0) {- return activeSession.details.sdur+ if (activeSession.details.duration && activeSession.details.duration > 0) {+ return activeSession.details.duration}if (!_isEmpty(activeSession.pages)) {@@ -249,14 +249,17 @@ export const SessionDetailView = ({return <Loader />}- const countryName = details.cc- ? countries.getName(details.cc, language) || details.cc+ const countryName = details.country+ ? countries.getName(details.country, language) || details.country: nullconst locationSummary =- [countryName, details.rg, details.ct].filter(Boolean).join(', ') ||+ [countryName, details.region, details.city].filter(Boolean).join(', ') ||t('project.unknown')- const osTooltipLabel = formatVersionLabel(details.os, details.osv)- const browserTooltipLabel = formatVersionLabel(details.br, details.brv)+ const osTooltipLabel = formatVersionLabel(details.os, details.os_version)+ const browserTooltipLabel = formatVersionLabel(+ details.browser,+ details.browser_version,+ )const platformParts: PlatformPart[] = [...(details.os? [@@ -268,13 +271,13 @@ export const SessionDetailView = ({},]: []),- ...(details.br+ ...(details.browser? [{key: 'browser',- label: details.br,- tooltip: browserTooltipLabel || details.br,- icon: <BrowserIcon browser={details.br} className='size-4' />,+ label: details.browser,+ tooltip: browserTooltipLabel || details.browser,+ icon: <BrowserIcon browser={details.browser} className='size-4' />,},]: []),@@ -346,11 +349,11 @@ export const SessionDetailView = ({? t('project.online'): t('project.endOfSession')const campaignRows = [- { label: t('project.mapping.so'), value: details.so },- { label: t('project.mapping.me'), value: details.me },- { label: t('project.mapping.ca'), value: details.ca },- { label: t('project.mapping.te'), value: details.te },- { label: t('project.mapping.co'), value: details.co },+ { label: t('project.mapping.so'), value: details.utm_source },+ { label: t('project.mapping.me'), value: details.utm_medium },+ { label: t('project.mapping.ca'), value: details.utm_campaign },+ { label: t('project.mapping.te'), value: details.utm_term },+ { label: t('project.mapping.co'), value: details.utm_content },].filter(({ value }) => value)const durationText = details.isLive? sessionOnlineFor || t('dashboard.live')@@ -473,7 +476,7 @@ export const SessionDetailView = ({pages={activeSession?.pages || []}timeFormat={timeFormat}zoomedTimeRange={zoomedTimeRange}- sdur={activeSession?.details?.sdur}+ sdur={activeSession?.details?.duration}isLive={activeSession?.details?.isLive}websiteUrl={websiteUrl}/>@@ -532,10 +535,10 @@ export const SessionDetailView = ({colour='primary'className='flex h-6 items-center justify-center'>- {details.cc ? (+ {details.country ? (<FlagclassName='rounded-xs'- country={details.cc}+ country={details.country}size={16}alt=''aria-hidden='true'@@ -690,11 +693,11 @@ export const SessionDetailView = ({<InfoRowlabel={t('project.mapping.ref')}value={- details.ref ? (+ details.referrer ? (<Tooltiptext={<Text size='xs' colour='inherit'>- {details.ref}+ {details.referrer}</Text>}tooltipNode={@@ -703,7 +706,9 @@ export const SessionDetailView = ({<spanclassName='truncate'title={- _size(details.ref) > 34 ? details.ref : undefined+ _size(details.referrer) > 34+ ? details.referrer+ : undefined}><Text@@ -713,7 +718,7 @@ export const SessionDetailView = ({colour='inherit'truncate>- {_truncate(details.ref, { length: 34 })}+ {_truncate(details.referrer, { length: 34 })}</Text></span></div>@@ -727,7 +732,9 @@ export const SessionDetailView = ({<InfoRowlabel={t('project.mapping.lc')}value={- details.lc ? getLocaleDisplayName(details.lc, language) : '-'+ details.locale+ ? getLocaleDisplayName(details.locale, language)+ : '-'}/></div>diff --git a/web/app/pages/Project/tabs/Sessions/Sessions.tsx b/web/app/pages/Project/tabs/Sessions/Sessions.tsxindex f4d01d59e..43093793b 100644--- a/web/app/pages/Project/tabs/Sessions/Sessions.tsx+++ b/web/app/pages/Project/tabs/Sessions/Sessions.tsx@@ -104,9 +104,9 @@ export const Session = ({let sessionDurationString = ''if (!session.isLive) {- if (session.sdur != null && session.sdur > 0) {+ if (session.duration != null && session.duration > 0) {sessionDurationString = getStringFromTime(- getTimeFromSeconds(session.sdur),+ getTimeFromSeconds(session.duration),)} else {const diffSeconds = dayjs@@ -283,15 +283,15 @@ export const Session = ({<div className='flex items-center gap-1.5'><Tooltiptext={- session.cc- ? countries.getName(session.cc, language) ||- session.cc+ session.country+ ? countries.getName(session.country, language) ||+ session.country: t('project.unknownCountry')}tooltipNode={<div className='flex h-[22px] w-[22px] items-center justify-center rounded bg-gray-100/80 ring-1 ring-gray-200/50 dark:bg-slate-800/80 dark:ring-slate-700/50'><Flag- country={session.cc}+ country={session.country}size={14}className='rounded-[2px]'aria-hidden='true'@@ -312,11 +312,11 @@ export const Session = ({}/><Tooltip- text={session.br || t('project.unknown')}+ text={session.browser || t('project.unknown')}tooltipNode={<div className='flex h-[22px] w-[22px] items-center justify-center rounded bg-gray-100/80 ring-1 ring-gray-200/50 dark:bg-slate-800/80 dark:ring-slate-700/50'><BrowserIcon- browser={session.br}+ browser={session.browser}className='size-3.5'/></div>diff --git a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx b/web/app/pages/Project/tabs/Sessions/SessionsView.tsxindex 0aba7bec1..7e090e910 100644--- a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx+++ b/web/app/pages/Project/tabs/Sessions/SessionsView.tsx@@ -1,12 +1,14 @@import _isEmpty from 'lodash/isEmpty'-import { useState, useEffect, useMemo, useRef, Suspense, use } from 'react'+import { useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'-import { useSearchParams, useLoaderData, useRevalidator } from 'react-router'+import { useSearchParams } from 'react-router'-import type { SessionsResponse, SessionDetailsResponse } from '~/api/api.server'-import { useSessionsProxy } from '~/hooks/useAnalyticsProxy'import {- Session,+ useSessionDetailsQuery,+ useSessionsListQuery,+} from '~/hooks/v2/useV2Queries'+import {+ Session as SessionType,SessionDetails as SessionDetailsType,SessionReplayMetadata,} from '~/lib/models/Project'@@ -18,42 +20,28 @@ import Filters from '~/pages/Project/View/components/Filters'import ProjectViewHeaderActions from '~/pages/Project/View/components/ProjectViewHeaderActions'import TabErrorBoundary from '~/pages/Project/View/components/TabErrorBoundary'import {- useViewProjectContext,- useRefreshTriggers,-} from '~/pages/Project/View/ViewProject'-import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'+ PanelSkeleton,+ RefetchIndicator,+} from '~/pages/Project/View/v2/loading'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'import { useCurrentProject } from '~/providers/CurrentProjectProvider'-import type { ProjectLoaderData } from '~/routes/projects.$id'import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'-import Loader from '~/ui/Loader'-import LoadingBar from '~/ui/LoadingBar'import StatusPage from '~/ui/StatusPage'import routes from '~/utils/routes'-import { LoaderView } from '../../View/components/LoaderView'--const SESSIONS_TAKE = 30-interface PageflowItem {- type: 'pageview' | 'event' | 'error' | 'sale' | 'subscription' | 'refund'- value: string- created: string- metadata?: { key: string; value: string }[]- amount?: number- currency?: string-}+import type { PageflowEvent } from './Pageflow'-interface ActiveSession {- details: SessionDetailsType+interface SessionDetailsData {+ psid?: string+ pages?: PageflowEvent[]+ details?: SessionDetailsTypechart?: {x: string[]pageviews?: number[]customEvents?: number[]errors?: number[]}- pages?: PageflowItem[]- timeBucket?: string- sessionStart?: string- lastActivity?: string+ timeBucket?: string | nullreplay?: SessionReplayMetadata | null}@@ -62,148 +50,94 @@ interface SessionsViewProps {rotateXAxis: boolean}-interface DeferredSessionsData {- sessionsData: SessionsResponse | null- sessionDetails: SessionDetailsResponse | null-}--function SessionsDataResolver({- children,-}: {- children: (data: DeferredSessionsData) => React.ReactNode-}) {- const {- sessionsData: sessionsDataPromise,- sessionDetails: sessionDetailsPromise,- } = useLoaderData<ProjectLoaderData>()-- const sessionsData = sessionsDataPromise ? use(sessionsDataPromise) : null- const sessionDetails = sessionDetailsPromise- ? use(sessionDetailsPromise)- : null-- return <>{children({ sessionsData, sessionDetails })}</>-}-function SessionsViewWrapper(props: SessionsViewProps) {const [searchParams] = useSearchParams()- const { sessionsRefreshTrigger } = useRefreshTriggers()- const resetKey = `sessions:${searchParams.toString()}:${sessionsRefreshTrigger}`+ const resetKey = `sessions:${searchParams.toString()}`return (<TabErrorBoundarytitleKey='dashboard.failedToLoadSessions'resetKey={resetKey}>- <Suspense fallback={<LoaderView />}>- <SessionsDataResolver>- {(deferredData) => (- <SessionsViewInner {...props} deferredData={deferredData} />- )}- </SessionsDataResolver>- </Suspense>+ <SessionsViewInner {...props} /></TabErrorBoundary>)}-interface SessionsViewInnerProps extends SessionsViewProps {- deferredData: DeferredSessionsData-}--const SessionsViewInner = ({- tnMapping,- rotateXAxis,- deferredData,-}: SessionsViewInnerProps) => {- const { id, project } = useCurrentProject()- const revalidator = useRevalidator()- const { sessionsRefreshTrigger } = useRefreshTriggers()- const { timezone, period, dateRange, filters, timeFormat } =- useViewProjectContext()+const SessionsViewInner = ({ tnMapping, rotateXAxis }: SessionsViewProps) => {+ const { project } = useCurrentProject()+ const { timezone, filters, timeFormat } = useViewProjectContext()const { t } = useTranslation('common')const [searchParams] = useSearchParams()- // Proxy for pagination- const sessionsProxy = useSessionsProxy()-- // Session list state - derived from loader- const [sessions, setSessions] = useState<Session[]>(- () => deferredData.sessionsData?.sessions || [],- )- const [sessionsSkip, setSessionsSkip] = useState(SESSIONS_TAKE)- const [canLoadMoreSessions, setCanLoadMoreSessions] = useState(- () => (deferredData.sessionsData?.sessions?.length || 0) >= SESSIONS_TAKE,- )-const activePSID = useMemo(() => {return searchParams.get('psid')}, [searchParams])- // Session detail - derived from loader when available- const activeSession: ActiveSession | null = useMemo(() => {- if (deferredData.sessionDetails) {- const apiDetails = deferredData.sessionDetails.details- const matchingSession = sessions.find((s) => s.psid === activePSID)- const pages = deferredData.sessionDetails.pages- const lastPage =- pages && pages.length > 0 ? pages[pages.length - 1] : null- const details: SessionDetailsType = {- cc: apiDetails.cc,- os: apiDetails.os,- osv: apiDetails.osv || null,- br: apiDetails.br,- brv: apiDetails.brv || null,- lc: apiDetails.lc || null,- ref: apiDetails.ref || null,- so: apiDetails.so || null,- me: apiDetails.me || null,- ca: apiDetails.ca || null,- te: apiDetails.te || null,- co: apiDetails.co || null,- rg: apiDetails.rg || null,- ct: apiDetails.ct || null,- dv: apiDetails.dv,- profileId: apiDetails.profileId,- sdur: apiDetails.sdur,- isLive: matchingSession- ? matchingSession.isLive === 1- : apiDetails.isLive,- revenue: apiDetails.revenue ?? matchingSession?.revenue,- refunds: apiDetails.refunds ?? matchingSession?.refunds,- }- return {- details,- chart: deferredData.sessionDetails.chart,- pages,- timeBucket: deferredData.sessionDetails.timeBucket,- sessionStart: matchingSession?.sessionStart || apiDetails.created,- lastActivity:- matchingSession?.lastActivity ||- lastPage?.created ||- apiDetails.created,- replay: deferredData.sessionDetails.replay,+ const listQuery = useSessionsListQuery({ enabled: !activePSID })+ const detailsQuery = useSessionDetailsQuery(activePSID)++ const sessions = useMemo(() => {+ const rows = (listQuery.data?.pages || []).flatMap(+ (page) => page.data,+ ) as unknown as SessionType[]++ // Deduplicate by psid: offset-based pages may overlap when new sessions+ // arrive between page loads+ const seen = new Set<string>()+ return rows.filter((session) => {+ if (seen.has(session.psid)) {+ return false}- }- return null- }, [deferredData.sessionDetails, sessions, activePSID])+ seen.add(session.psid)+ return true+ })+ }, [listQuery.data])- const sessionsLoading =- revalidator.state === 'loading' || sessionsProxy.isLoading+ // Track if we've shown content in the current data set to prevent NoSessions flash+ const hasShownContentRef = useRef(false)- const [error, setError] = useState<string | null>(null)+ if (listQuery.data) {+ hasShownContentRef.current = !_isEmpty(sessions)+ }- const isMountedRef = useRef(true)+ // Session detail - derived from the v2 details query+ const activeSession = useMemo(() => {+ const data = detailsQuery.data?.data as SessionDetailsData | undefined+ if (!data) {+ return null+ }- // Track when loader data was last applied to detect stale proxy responses- const loaderUpdateCounterRef = useRef(0)- const proxyRequestRef = useRef<{- mode: 'append' | 'replace'- loaderUpdateCounter: number- limit?: number- } | null>(null)+ const matchingSession = sessions.find((s) => s.psid === activePSID)+ const pages = data.pages || []+ const lastPage = pages.length > 0 ? pages[pages.length - 1] : null+ const apiDetails = (data.details || {}) as SessionDetailsType++ const details: SessionDetailsType = {+ ...apiDetails,+ isLive: matchingSession+ ? matchingSession.isLive === 1+ : apiDetails.isLive,+ revenue: apiDetails.revenue ?? matchingSession?.revenue,+ refunds: apiDetails.refunds ?? matchingSession?.refunds,+ }- // Track if we've shown content in the current data set to prevent NoSessions flash during exit animation- const hasShownContentRef = useRef(false)+ return {+ details,+ chart: data.chart,+ pages,+ timeBucket: data.timeBucket || undefined,+ sessionStart: matchingSession?.sessionStart || pages[0]?.created,+ lastActivity: matchingSession?.lastActivity || lastPage?.created,+ replay: data.replay,+ }+ }, [detailsQuery.data, sessions, activePSID])++ const sessionsLoading = listQuery.isLoading+ const sessionsRefetching =+ listQuery.isFetching &&+ !listQuery.isLoading &&+ !listQuery.isFetchingNextPage// Search params without the session id. Needed for the back button.const pureSearchParams = useMemo(() => {@@ -221,147 +155,16 @@ const SessionsViewInner = ({[t],)- // Cleanup on unmount- useEffect(() => {- isMountedRef.current = true- return () => {- isMountedRef.current = false- }- }, [])-- // Sync sessions state when loader provides new data- useEffect(() => {- if (deferredData.sessionsData && revalidator.state === 'idle') {- const sessionsList = deferredData.sessionsData.sessions || []- setSessions(sessionsList)- setSessionsSkip(SESSIONS_TAKE)- setCanLoadMoreSessions(sessionsList.length >= SESSIONS_TAKE)- // Increment counter to invalidate any in-flight proxy responses- loaderUpdateCounterRef.current += 1- proxyRequestRef.current = null- // Reset content tracking when loader provides empty results (e.g., after filter change)- if (_isEmpty(sessionsList)) {- hasShownContentRef.current = false- } else {- hasShownContentRef.current = true- }- }- }, [revalidator.state, deferredData.sessionsData])+ const queryError = activePSID ? detailsQuery.error : listQuery.error- // Handle proxy response for pagination- useEffect(() => {- if (revalidator.state === 'loading') return-- if (sessionsProxy.data && !sessionsProxy.isLoading) {- const proxyRequest = proxyRequestRef.current- if (!proxyRequest) {- return- }-- // Ignore stale proxy responses that were initiated before the last loader update- if (proxyRequest.loaderUpdateCounter < loaderUpdateCounterRef.current) {- return- }-- const newSessions = sessionsProxy.data.sessions || []- setError(null)-- if (proxyRequest.mode === 'replace') {- const visibleSessions = newSessions.slice(0, proxyRequest.limit)- setSessions(visibleSessions)- setSessionsSkip(visibleSessions.length)- setCanLoadMoreSessions(newSessions.length > (proxyRequest.limit || 0))- hasShownContentRef.current = !_isEmpty(visibleSessions)- } else {- setSessions((prev) => {- // Deduplicate: only add sessions whose psid is not already present- const existingIds = new Set(prev.map((s) => s.psid))- const uniqueNewSessions = newSessions.filter(- (s) => !existingIds.has(s.psid),- )- return [...prev, ...uniqueNewSessions]- })- setSessionsSkip((prev) => prev + newSessions.length)- setCanLoadMoreSessions(newSessions.length >= SESSIONS_TAKE)- }-- proxyRequestRef.current = null- }- if (sessionsProxy.error) {- setError(sessionsProxy.error)- proxyRequestRef.current = null- }- }, [- sessionsProxy.data,- sessionsProxy.error,- sessionsProxy.isLoading,- revalidator.state,- ])-- const getSessionsParams = (take: number, skip: number) => {- let from: string | undefined- let to: string | undefined-- if (dateRange) {- from = getFormatDate(dateRange[0])- to = getFormatDate(dateRange[1])- }-- return {- timeBucket: 'day',- period: period === 'custom' ? '' : period,- from,- to,- timezone,- filters,- take,- skip,- }- }-- // Load more sessions via proxy- const loadMoreSessions = () => {- if (sessionsLoading) return-- // Track when this proxy request was initiated relative to loader updates- proxyRequestRef.current = {- mode: 'append',- loaderUpdateCounter: loaderUpdateCounterRef.current,- }-- sessionsProxy.fetchSessions(- id,- getSessionsParams(SESSIONS_TAKE, sessionsSkip),- )- }-- useEffect(() => {- if (sessionsRefreshTrigger > 0) {- if (!activePSID && !sessionsLoading) {- const limit = Math.max(sessions.length, SESSIONS_TAKE)- proxyRequestRef.current = {- mode: 'replace',- loaderUpdateCounter: loaderUpdateCounterRef.current,- limit,- }- sessionsProxy.fetchSessions(id, getSessionsParams(limit + 1, 0))- return- }-- revalidator.revalidate()- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [sessionsRefreshTrigger])-- // Session detail loading state- const sessionLoading = activePSID ? revalidator.state === 'loading' : false-- if (error && !sessionsLoading) {+ if (queryError) {return (<StatusPagetype='error'title={t('apiNotifications.somethingWentWrong')}- description={t('apiNotifications.errorCode', { error })}+ description={t('apiNotifications.errorCode', {+ error: queryError.message,+ })}actions={[{label: t('dashboard.reloadPage'),@@ -380,7 +183,7 @@ const SessionsViewInner = ({<SessionDetailViewactiveSession={activeSession}sessionId={activePSID}- sessionLoading={sessionLoading}+ sessionLoading={detailsQuery.isLoading}timeFormat={timeFormat}rotateXAxis={rotateXAxis}dataNames={dataNames}@@ -399,13 +202,16 @@ const SessionsViewInner = ({showLiveVisitorsrightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}/>- {sessionsLoading && !_isEmpty(sessions) ? <LoadingBar /> : null}- <div>+ <div className='relative'>+ {sessionsRefetching && !_isEmpty(sessions) ? (+ <RefetchIndicator />+ ) : null}{!_isEmpty(sessions) ? (<Filters className='mb-3' tnMapping={tnMapping} />) : null}- {sessionsLoading && _isEmpty(sessions) ? <Loader /> : null}- {!sessionsLoading &&+ {sessionsLoading && _isEmpty(sessions) ? <PanelSkeleton /> : null}+ {!listQuery.isFetching &&+ listQuery.data &&_isEmpty(sessions) &&!hasShownContentRef.current ? (<NoSessions filters={filters} />@@ -417,10 +223,10 @@ const SessionsViewInner = ({currency={project?.revenueCurrency}/><InfiniteScrollTrigger- hasMore={canLoadMoreSessions}- isLoading={sessionsLoading}- onLoadMore={loadMoreSessions}- disabled={sessionsLoading}+ hasMore={Boolean(listQuery.hasNextPage)}+ isLoading={listQuery.isFetchingNextPage}+ onLoadMore={() => listQuery.fetchNextPage()}+ disabled={listQuery.isFetching}className={sessionsLoading && _isEmpty(sessions) ? 'hidden' : ''}spinnerClassName='mr-0! ml-0!'/>diff --git a/web/app/pages/Project/tabs/Sessions/components/NoSessions.tsx b/web/app/pages/Project/tabs/Sessions/components/NoSessions.tsxindex eec415a22..51dba8df2 100644--- a/web/app/pages/Project/tabs/Sessions/components/NoSessions.tsx+++ b/web/app/pages/Project/tabs/Sessions/components/NoSessions.tsx@@ -3,13 +3,13 @@ import _isEmpty from 'lodash/isEmpty'import { memo } from 'react'import { useTranslation } from 'react-i18next'+import { V2Filter } from '~/api/v2/types'import Filters from '~/pages/Project/View/components/Filters'-import { Filter } from '~/pages/Project/View/interfaces/traffic'import { typeNameMapping } from '~/pages/Project/View/ViewProject.helpers'import { Text } from '~/ui/Text'interface NoSessionsProps {- filters: Filter[]+ filters: V2Filter[]}const NoSessions = ({ filters }: NoSessionsProps) => {diff --git a/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsxindex 2cfe5ff61..c008ce9cb 100644--- a/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx+++ b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx@@ -9,14 +9,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { useLocation } from 'react-router'-import type {- SessionsResponse,- FunnelSessionsResponse,- GoalSessionsResponse,- ErrorSessionsResponse,- ErrorAffectedSession,- SessionEventType,-} from '~/api/api.server'+import * as v2api from '~/api/v2/endpoints'+import type { V2Filter } from '~/api/v2/types'import type { Session as SessionType } from '~/lib/models/Project'import {Drawer,@@ -40,28 +34,45 @@ import { BrowserIcon, OSIcon } from '../SharedIcons'const SESSIONS_TAKE = 30-type SessionsPageResult =- | SessionsResponse- | FunnelSessionsResponse- | GoalSessionsResponse- | ErrorSessionsResponse+type SessionEventType = 'traffic' | 'performance' | 'error'++interface ErrorAffectedSession {+ psid: string+ profileId?: string | null+ country: string | null+ os: string | null+ browser: string | null+ firstErrorAt: string+ lastErrorAt: string+ errorCount: number+}type DrawerSession = SessionType | ErrorAffectedSession-async function fetchSessionsPage(- action: string,+/**+ * Goal sessions have no v2 endpoint yet, so they still go through the v1+ * analytics proxy. The response uses v1 short keys - map them to the v2+ * readable keys the shared <Session /> renderer expects.+ */+const mapV1SessionKeys = (session: Record<string, any>): SessionType =>+ ({+ ...session,+ country: session.country ?? session.cc ?? null,+ browser: session.browser ?? session.br ?? null,+ duration: session.duration ?? session.sdur,+ }) as SessionType++async function fetchGoalSessionsPage(projectId: string,params: Record<string, unknown>,signal?: AbortSignal,- rootParams?: Record<string, unknown>,-): Promise<SessionsPageResult | null> {+): Promise<SessionType[]> {const response = await fetch('/api/analytics', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({- action,+ action: 'getGoalSessions',projectId,- ...rootParams,params,}),signal,@@ -72,7 +83,7 @@ async function fetchSessionsPage(}const result = (await response.json()) as {- data: SessionsPageResult | null+ data: { sessions?: Record<string, any>[] } | nullerror: string | null}@@ -80,18 +91,7 @@ async function fetchSessionsPage(throw new Error(result.error)}- return result.data-}--const mapErrorSession = (session: ErrorAffectedSession): ErrorAffectedSession =>- session--const getResultSessions = (result: SessionsPageResult): DrawerSession[] => {- if ('total' in result) {- return result.sessions.map(mapErrorSession)- }-- return result.sessions+ return (result.data?.sessions || []).map(mapV1SessionKeys)}const isErrorAffectedSession = (@@ -137,9 +137,9 @@ const ErrorSession = ({ session }: { session: ErrorAffectedSession }) => {<div className='flex flex-wrap items-center gap-x-3 gap-y-2'><div className='flex items-center gap-1.5'><div className='flex h-[22px] w-[22px] items-center justify-center rounded bg-gray-100/80 ring-1 ring-gray-200/50 dark:bg-slate-800/80 dark:ring-slate-700/50'>- {session.cc ? (+ {session.country ? (<Flag- country={session.cc}+ country={session.country}size={14}className='rounded-[2px]'aria-hidden='true'@@ -156,7 +156,10 @@ const ErrorSession = ({ session }: { session: ErrorAffectedSession }) => {/></div><div className='flex h-[22px] w-[22px] items-center justify-center rounded bg-gray-100/80 ring-1 ring-gray-200/50 dark:bg-slate-800/80 dark:ring-slate-700/50'>- <BrowserIcon browser={session.br} className='size-3.5' />+ <BrowserIcon+ browser={session.browser}+ className='size-3.5'+ /></div></div><div className='h-3 w-px bg-gray-200 dark:bg-slate-700' />@@ -192,7 +195,7 @@ interface SessionsDrawerProps {projectId: stringtimezone: stringtimeFormat: '12-hour' | '24-hour'- filters?: any[]+ filters?: V2Filter[]period?: stringfunnelId?: stringfunnelStep?: number@@ -236,7 +239,6 @@ export const SessionsDrawer = ({const [sessions, setSessions] = useState<DrawerSession[]>([])const [skip, setSkip] = useState(0)const [hasMore, setHasMore] = useState(true)- const [resultTotalCount, setResultTotalCount] = useState<number | null>(null)const [initialLoading, setInitialLoading] = useState(true)const [loadingMore, setLoadingMore] = useState(false)const [error, setError] = useState<string | null>(null)@@ -251,74 +253,69 @@ export const SessionsDrawer = ({append: boolean,signal?: AbortSignal,): Promise<boolean> => {- let result: SessionsPageResult | null = null+ let newSessions: DrawerSession[] = []++ // v2 accepts ISO datetimes for from/to; fall back to the period+ // otherwise (backend defaults 'custom' without a range)+ const commonParams = {+ ...(from && to ? { from, to } : { period }),+ timezone,+ filters: stableFilters,+ }try {if (isFunnelMode) {- result = await fetchSessionsPage(- 'getFunnelSessions',+ const result = await v2api.getFunnelSessions(projectId,{- period,- from,- to,- timezone,+ ...commonParams,funnelId,- step: funnelStep,- filters: stableFilters,+ step: funnelStep!,dropoff,- take: SESSIONS_TAKE,- skip: currentSkip,+ limit: SESSIONS_TAKE,+ offset: currentSkip,},signal,)- } else if (isGoalMode) {- result = await fetchSessionsPage(- 'getGoalSessions',+ newSessions = result.data as unknown as SessionType[]+ } else if (isErrorMode) {+ const result = await v2api.getErrorSessions(projectId,+ errorId!,{- period,- from,- to,- timezone,- goalId,- take: SESSIONS_TAKE,- skip: currentSkip,+ ...commonParams,+ limit: SESSIONS_TAKE,+ offset: currentSkip,},signal,)- } else if (isErrorMode) {- result = await fetchSessionsPage(- 'getErrorSessions',+ newSessions = result.data as unknown as ErrorAffectedSession[]+ } else if (isGoalMode) {+ newSessions = await fetchGoalSessionsPage(projectId,{period,from,to,timezone,- filters: stableFilters,+ goalId,take: SESSIONS_TAKE,skip: currentSkip,},signal,- { errorId },)} else {- result = await fetchSessionsPage(- 'getSessions',+ const result = await v2api.getSessionsList(projectId,{- period,- from,- to,- timezone,- filters: stableFilters,- sessionEvent,- take: SESSIONS_TAKE,- skip: currentSkip,+ ...commonParams,+ event_type: sessionEvent,+ limit: SESSIONS_TAKE,+ offset: currentSkip,},signal,)+ newSessions = result.data as unknown as SessionType[]}} catch (e) {if (signal?.aborted) return false@@ -334,24 +331,14 @@ export const SessionsDrawer = ({setError(null)- if (result) {- const newSessions = getResultSessions(result)- const nextTotalCount = 'total' in result ? result.total : null-- if (append) {- setSessions((prev) => [...prev, ...newSessions])- } else {- setSessions(newSessions)- }-- setResultTotalCount(nextTotalCount)- setHasMore(- nextTotalCount != null- ? currentSkip + newSessions.length < nextTotalCount- : newSessions.length >= SESSIONS_TAKE,- )+ if (append) {+ setSessions((prev) => [...prev, ...newSessions])+ } else {+ setSessions(newSessions)}+ setHasMore(newSessions.length >= SESSIONS_TAKE)+return true},[@@ -385,7 +372,6 @@ export const SessionsDrawer = ({setSessions([])setSkip(0)setHasMore(true)- setResultTotalCount(null)setError(null)const timer = setTimeout(() => {@@ -402,8 +388,6 @@ export const SessionsDrawer = ({}}, [isOpen, period, from, to, loadSessions])- const displayTotalCount = totalCount ?? resultTotalCount-const loadMore = useCallback(async () => {if (loadingRef.current || !hasMore) returnloadingRef.current = true@@ -472,7 +456,7 @@ export const SessionsDrawer = ({</div><div className='ml-3 flex shrink-0 items-center gap-2'>{!initialLoading &&- (displayTotalCount != null || sessions.length > 0) ? (+ (totalCount != null || sessions.length > 0) ? (<Textas='span'size='xs'@@ -481,8 +465,8 @@ export const SessionsDrawer = ({className='inline-flex items-center gap-1 rounded-md bg-gray-100 px-2 py-1 dark:bg-slate-800'><UsersIcon className='size-3.5' />- {displayTotalCount != null ? (- displayTotalCount+ {totalCount != null ? (+ totalCount) : (<>{sessions.length}diff --git a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx b/web/app/pages/Project/tabs/Traffic/TrafficView.tsxindex 656886671..bab2cf0fb 100644--- a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx+++ b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx@@ -14,39 +14,35 @@ import React, {useEffect,useMemo,useRef,- lazy,- Suspense,useCallback,use,+ Suspense,} from 'react'import { createPortal } from 'react-dom'-import { motion, useIsPresent } from 'motion/react'+import { motion } from 'motion/react'import { useTranslation } from 'react-i18next'-import {- useNavigate,- useSearchParams,- useLoaderData,- useRevalidator,-} from 'react-router'+import { useSearchParams, useLoaderData } from 'react-router'import { toast } from 'sonner'-import type {- TrafficLogResponse as ServerTrafficLogResponse,- OverallObject as ServerOverallObject,-} from '~/api/api.server'-import {- useCustomEventsMetadataProxy,- usePropertyMetadataProxy,- useRevenueProxy,-} from '~/hooks/useAnalyticsProxy'+import * as v2api from '~/api/v2/endpoints'+import { useRevenueProxy } from '~/hooks/useAnalyticsProxy'import { useAnnotations } from '~/hooks/useAnnotations'-import { TRAFFIC_PANELS_ORDER, isSelfhosted } from '~/lib/constants'-import { CountryEntry, Entry } from '~/lib/models/Entry'-import { OverallObject } from '~/lib/models/Project'+import {+ useCompareSummaryQuery,+ useCompareTimeseriesQuery,+ useCustomEventsQuery,+ useCustomEventsTimeseriesQuery,+ useCustomMetricsQuery,+ usePagePropertiesQuery,+ useSummaryQuery,+ useTimeseriesQuery,+ useV2CommonParams,+} from '~/hooks/v2/useV2Queries'+import { isSelfhosted } from '~/lib/constants'+import { Entry } from '~/lib/models/Entry'import AnnotationModal from '~/modals/AnnotationModal'import CustomEventsSubmenu from '~/pages/Project/tabs/Traffic/CustomEventsSubmenu'import CustomMetrics from '~/pages/Project/tabs/Traffic/CustomMetrics'-import { MapLoader } from '~/pages/Project/View/components/MapLoader'import {MetricCard,MetricCards,@@ -66,25 +62,31 @@ import NoEvents from '~/pages/Project/View/components/NoEvents'import ProjectViewHeaderActions from '~/pages/Project/View/components/ProjectViewHeaderActions'import TabErrorBoundary from '~/pages/Project/View/components/TabErrorBoundary'import WaitingForAnEvent from '~/pages/Project/View/components/WaitingForAnEvent'+import { ProjectViewCustomEvent } from '~/pages/Project/View/interfaces/traffic'import {- Customs,- TrafficMeta,- Params,- ProjectViewCustomEvent,- Properties,-} from '~/pages/Project/View/interfaces/traffic'-import {- Panel,CustomEvents,CombinedMetadataPanel,} from '~/pages/Project/View/Panels'import { FILTER_CHART_METRICS_MAPPING_FOR_COMPARE } from '~/pages/Project/View/utils/filters'import {- useViewProjectContext,- useRefreshTriggers,-} from '~/pages/Project/View/ViewProject'+ BreakdownPanel,+ BreakdownSubTab,+} from '~/pages/Project/View/v2/BreakdownPanel'+import {+ hasCustomEventFilter,+ mapBreakdownRows,+ metadataToResult,+ pivotCustomEventsTimeseries,+ pivotTrafficTimeseries,+ summaryToOverall,+} from '~/pages/Project/View/v2/adapters'+import {+ ChartSkeleton,+ MetricCardsSkeleton,+} from '~/pages/Project/View/v2/loading'+import { TrafficMap } from '~/pages/Project/View/v2/TrafficMap'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'import {- getFormatDate,panelIconMapping,noRegionPeriods,CHART_METRICS_MAPPING,@@ -98,98 +100,19 @@ import { useTheme } from '~/providers/ThemeProvider'import type { ProjectLoaderData } from '~/routes/projects.$id'import Checkbox from '~/ui/Checkbox'import Dropdown from '~/ui/Dropdown'-import LoadingBar from '~/ui/LoadingBar'import Tooltip from '~/ui/Tooltip'import { getLocaleDisplayName, nLocaleFormatter } from '~/utils/generic'import { groupRefEntries } from '~/utils/referrers'-import { LoaderView } from '../../View/components/LoaderView'import { ChartTypeSwitcher } from '../../View/components/ChartTypeSwitcher'dayjs.extend(utc)dayjs.extend(timezonePlugin)-const InteractiveMap = lazy(- () => import('~/pages/Project/View/components/InteractiveMap'),-)--interface PanelsData {- types?: string[]- data: Params- customs?: Customs- properties?: Properties- meta?: TrafficMeta[]-}-interface TrafficViewProps {tnMapping: Record<string, string>customMetrics: ProjectViewCustomEvent[]onRemoveCustomMetric: (metricId: string) => voidresetCustomMetrics: () => void- mode: 'periodical' | 'cumulative'-}--interface DeferredTrafficData {- trafficData: ServerTrafficLogResponse | null- overallStats: Record<string, ServerOverallObject> | null- trafficCompareData: ServerTrafficLogResponse | null- overallCompareStats: Record<string, ServerOverallObject> | null- customEventsData: { chart?: { events?: Record<string, unknown> } } | null-}--function TrafficDataResolver({- children,-}: {- children: (data: DeferredTrafficData) => React.ReactNode-}) {- const isPresent = useIsPresent()- const previousDataRef = useRef<DeferredTrafficData | null>(null)- const {- trafficData: trafficDataPromise,- overallStats: overallStatsPromise,- trafficCompareData: trafficComparePromise,- overallCompareStats: overallComparePromise,- customEventsData: customEventsPromise,- } = useLoaderData<ProjectLoaderData>()- const shouldUsePreviousData = !isPresent && !!previousDataRef.current-- const trafficData = shouldUsePreviousData- ? previousDataRef.current!.trafficData- : trafficDataPromise- ? use(trafficDataPromise)- : null- const overallStats = shouldUsePreviousData- ? previousDataRef.current!.overallStats- : overallStatsPromise- ? use(overallStatsPromise)- : null- const trafficCompareData = shouldUsePreviousData- ? previousDataRef.current!.trafficCompareData- : trafficComparePromise- ? use(trafficComparePromise)- : null- const overallCompareStats = shouldUsePreviousData- ? previousDataRef.current!.overallCompareStats- : overallComparePromise- ? use(overallComparePromise)- : null- const customEventsData = shouldUsePreviousData- ? previousDataRef.current!.customEventsData- : customEventsPromise- ? use(customEventsPromise)- : null- const currentData: DeferredTrafficData = {- trafficData,- overallStats,- trafficCompareData,- overallCompareStats,- customEventsData,- }-- if (isPresent) {- previousDataRef.current = currentData- }-- return <>{children(currentData)}</>}function HasImportedIndicator() {@@ -217,67 +140,43 @@ function HasImportedIndicator() {function TrafficViewWrapper(props: TrafficViewProps) {const [searchParams] = useSearchParams()- const { trafficRefreshTrigger } = useRefreshTriggers()- const resetKey = `traffic:${searchParams.toString()}:${trafficRefreshTrigger}`+ const resetKey = `traffic:${searchParams.toString()}`return (<TabErrorBoundarytitleKey='dashboard.failedToLoadTraffic'resetKey={resetKey}>- <Suspense fallback={<LoaderView />}>- <TrafficDataResolver>- {(deferredData) => (- <TrafficViewInner {...props} deferredData={deferredData} />- )}- </TrafficDataResolver>- </Suspense>+ <TrafficViewInner {...props} /></TabErrorBoundary>)}-interface TrafficViewInnerProps extends TrafficViewProps {- deferredData: DeferredTrafficData-}-const TrafficViewInner = ({tnMapping,customMetrics,onRemoveCustomMetric,resetCustomMetrics,- mode: _mode,- deferredData,-}: TrafficViewInnerProps) => {+}: TrafficViewProps) => {const { id, project, allowedToManage } = useCurrentProject()- const revalidator = useRevalidator()- const { fetchMetadata: fetchCustomEventsMetadata } =- useCustomEventsMetadataProxy()- const { fetchMetadata: fetchPropertyMetadata } = usePropertyMetadataProxy()const { fetchRevenueStatus, fetchRevenueData } = useRevenueProxy()- const { trafficRefreshTrigger } = useRefreshTriggers()const {timezone,period,- dateRange,filters,timeFormat,timeBucket,activePeriod,- // Comparison state from contextisActiveCompare,activePeriodCompare,- // Chart state from contextchartType,setChartTypeOnClick,rotateXAxis,- // Zoom state from contextonMainChartZoom,shouldEnableZoom,- // Filter functions from contextgetFilterLink,getVersionFilterLink,isMapFullscreen,- setIsMapFullscreen,fullscreenMapRef,} = useViewProjectContext()const {@@ -285,13 +184,12 @@ const TrafficViewInner = ({i18n: { language },} = useTranslation('common')const { theme } = useTheme()- const navigate = useNavigate()const [searchParams, setSearchParams] = useSearchParams()+ const { pid, common } = useV2CommonParams('traffic')- // Track if we've ever shown actual content to prevent NoEvents flash during exit animation+ // Track if we've ever shown actual content to prevent NoEvents flashconst hasShownContentRef = useRef(false)- // Annotations hookconst {annotations,isAnnotationModalOpen,@@ -314,6 +212,11 @@ const TrafficViewInner = ({label: string} | null>(null)+ const [metadataActiveKeys, setMetadataActiveKeys] = useState({+ property: '',+ customEvent: '',+ })+const handleDataPointClick = useCallback((d: { x: Date; index: number; xValue?: string }) => {setSessionsDrawer(@@ -329,64 +232,123 @@ const TrafficViewInner = ({[timeBucket, timeFormat, timezone],)- const panelsData: PanelsData = useMemo(() => {- if (deferredData.trafficData) {- return {- types: _keys(deferredData.trafficData.params || {}),- data: deferredData.trafficData.params || {},- customs: deferredData.trafficData.customs,- properties: deferredData.trafficData.properties,- meta: deferredData.trafficData.meta,- }+ // Chart metrics state+ const [activeChartMetrics, setActiveChartMetrics] = useState({+ [CHART_METRICS_MAPPING.unique]: true,+ [CHART_METRICS_MAPPING.views]: false,+ [CHART_METRICS_MAPPING.sessionDuration]: false,+ [CHART_METRICS_MAPPING.bounce]: false,+ [CHART_METRICS_MAPPING.viewsPerUnique]: false,+ [CHART_METRICS_MAPPING.trendlines]: false,+ [CHART_METRICS_MAPPING.cumulativeMode]: false,+ [CHART_METRICS_MAPPING.customEvents]: false,+ [CHART_METRICS_MAPPING.revenue]: false,+ })++ const activeChartMetricsCustomEvents = useMemo(() => {+ const param = searchParams.get('customEvents')+ return param ? param.split(',').filter(Boolean) : []+ }, [searchParams])++ // --- v2 queries ---++ const summaryQuery = useSummaryQuery('traffic')+ const compareSummaryQuery = useCompareSummaryQuery('traffic')++ const timeseriesMetrics = useMemo(() => {+ const metrics = ['visitors', 'pageviews']+ if (activeChartMetrics[CHART_METRICS_MAPPING.sessionDuration]) {+ metrics.push('session_duration')+ }+ if (activeChartMetrics[CHART_METRICS_MAPPING.bounce]) {+ metrics.push('bounce_rate')}- return { data: {} }- }, [deferredData.trafficData])+ return metrics+ }, [activeChartMetrics])- const baseChartData = useMemo(- () => deferredData.trafficData?.chart || {},- [deferredData.trafficData],+ const chartMode = activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode]+ ? ('cumulative' as const)+ : ('periodical' as const)++ const timeseriesQuery = useTimeseriesQuery('traffic', {+ metrics: timeseriesMetrics,+ mode: chartMode,+ })+ const compareTimeseriesQuery = useCompareTimeseriesQuery('traffic', {+ metrics: timeseriesMetrics,+ mode: chartMode,+ })++ const customEventsQuery = useCustomEventsQuery({ limit: 100 })+ const pagePropertiesQuery = usePagePropertiesQuery({ limit: 100 })+ const customEventsTimeseriesQuery = useCustomEventsTimeseriesQuery(+ activeChartMetricsCustomEvents,)+ const customMetricsQuery = useCustomMetricsQuery(customMetrics)- const overall: Partial<OverallObject> = useMemo(() => {- if (deferredData.overallStats && id) {- return deferredData.overallStats[id] || {}- }- return {}- }, [deferredData.overallStats, id])+ const customs = useMemo(+ () =>+ Object.fromEntries(+ (customEventsQuery.data?.data || []).map((row) => [+ row.event,+ row.count,+ ]),+ ),+ [customEventsQuery.data],+ )+ const properties = useMemo(+ () =>+ Object.fromEntries(+ (pagePropertiesQuery.data?.data || []).map((row) => [+ row.property,+ row.count,+ ]),+ ),+ [pagePropertiesQuery.data],+ )- const dataLoading = revalidator.state === 'loading'+ const customEVFilterApplied = useMemo(+ () => hasCustomEventFilter(filters),+ [filters],+ )- // Derive compare data from loader- const overallCompare: Partial<OverallObject> = useMemo(() => {- if (deferredData.overallCompareStats && id) {- return deferredData.overallCompareStats[id] || {}- }- return {}- }, [deferredData.overallCompareStats, id])+ const overall = useMemo(+ () => summaryToOverall(summaryQuery.data?.data, customEVFilterApplied),+ [summaryQuery.data, customEVFilterApplied],+ )+ const overallCompare = useMemo(+ () =>+ summaryToOverall(compareSummaryQuery.data?.data, customEVFilterApplied),+ [compareSummaryQuery.data, customEVFilterApplied],+ )+ const baseChartData = useMemo(+ () => pivotTrafficTimeseries(timeseriesQuery.data?.data),+ [timeseriesQuery.data],+ )const dataChartCompare = useMemo(- () => deferredData.trafficCompareData?.chart || {},- [deferredData.trafficCompareData],+ () =>+ compareTimeseriesQuery.data+ ? pivotTrafficTimeseries(compareTimeseriesQuery.data.data)+ : {},+ [compareTimeseriesQuery.data],)-- // Derive custom events data from loaderconst customEventsChartData = useMemo(() =>- (deferredData.customEventsData?.chart?.events || {}) as Record<- string,- string[]- >,- [deferredData.customEventsData],+ pivotCustomEventsTimeseries(+ customEventsTimeseriesQuery.data?.data,+ activeChartMetricsCustomEvents,+ ).events as unknown as Record<string, string[]>,+ [customEventsTimeseriesQuery.data, activeChartMetricsCustomEvents],)- // Revenue state (still fetched client-side for now)+ // Revenue state (still fetched via the v1 proxy — no v2 equivalent)const [isRevenueConnected, setIsRevenueConnected] = useState(false)const [revenueOverlay, setRevenueOverlay] = useState<{revenue: number[]refundsAmount: number[]} | null>(null)- // Merge base chart with revenue dataconst chartData = useMemo(() => {if (revenueOverlay) {return { ...baseChartData, ...revenueOverlay }@@ -394,62 +356,28 @@ const TrafficViewInner = ({return baseChartData}, [baseChartData, revenueOverlay])- const isPanelsDataEmptyRaw = useMemo(() => {- const data = panelsData.data || {}- const isPanelDataEmpty =- _isEmpty(data) || Object.values(data).every((value) => _isEmpty(value))+ const summaryLoaded = Boolean(summaryQuery.data)+ const customsLoaded = Boolean(customEventsQuery.data)- return isPanelDataEmpty && _isEmpty(panelsData.customs)- }, [panelsData.data, panelsData.customs])+ const isPanelsDataEmptyRaw =+ summaryLoaded &&+ customsLoaded &&+ !overall.current?.all &&+ !overall.current?.unique &&+ _isEmpty(customs)- // Track when we've shown content to prevent NoEvents flash during exit animation- if (!isPanelsDataEmptyRaw) {+ if (summaryLoaded && customsLoaded && !isPanelsDataEmptyRaw) {hasShownContentRef.current = true}- // Don't show NoEvents if we've previously shown content (prevents flash during tab switch)const isPanelsDataEmpty = isPanelsDataEmptyRaw && !hasShownContentRef.current- // Chart metrics state- const [activeChartMetrics, setActiveChartMetrics] = useState({- [CHART_METRICS_MAPPING.unique]: true,- [CHART_METRICS_MAPPING.views]: false,- [CHART_METRICS_MAPPING.sessionDuration]: false,- [CHART_METRICS_MAPPING.bounce]: false,- [CHART_METRICS_MAPPING.viewsPerUnique]: false,- [CHART_METRICS_MAPPING.trendlines]: false,- [CHART_METRICS_MAPPING.cumulativeMode]: false,- [CHART_METRICS_MAPPING.customEvents]: false,- [CHART_METRICS_MAPPING.revenue]: false,- })- // Get custom events from URL params (SSR-friendly)- const activeChartMetricsCustomEvents = useMemo(() => {- const param = searchParams.get('customEvents')- return param ? param.split(',').filter(Boolean) : []- }, [searchParams])-- // Panel active tabs- const [panelsActiveTabs, setPanelsActiveTabs] = useState<{- location: 'cc' | 'rg' | 'ct' | 'lc' | 'map'- page: 'pg' | 'host' | 'userFlow' | 'entryPage' | 'exitPage'- device: 'br' | 'os' | 'dv'- network: 'isp' | 'og' | 'ut' | 'ctp'- source: 'ref' | 'so' | 'me' | 'ca' | 'te' | 'co'- customEvMetadata: string- pageviewMetadata: string- }>({- location: 'cc',- page: 'pg',- device: 'br',- network: 'isp',- source: 'ref',- customEvMetadata: '',- pageviewMetadata: '',- })+ const isInitialLoading =+ (summaryQuery.isLoading || customEventsQuery.isLoading) &&+ !hasShownContentRef.currentconst isMountedRef = useRef(true)- // Cleanup on unmountuseEffect(() => {isMountedRef.current = truereturn () => {@@ -480,37 +408,6 @@ const TrafficViewInner = ({loadRevenueStatus()}, [id, fetchRevenueStatus])- // Version data mapping for browser/OS versions- const createVersionDataMapping = useMemo(() => {- const browserDataSource = panelsData.data?.brv- const osDataSource = panelsData.data?.osv-- const browserVersions: { [key: string]: Entry[] } = {}- const osVersions: { [key: string]: Entry[] } = {}-- if (browserDataSource) {- browserDataSource.forEach((entry: any) => {- const { br, name, count } = entry- if (!browserVersions[br]) {- browserVersions[br] = []- }- browserVersions[br].push({ name, count })- })- }-- if (osDataSource) {- osDataSource.forEach((entry: any) => {- const { os, name, count } = entry- if (!osVersions[os]) {- osVersions[os] = []- }- osVersions[os].push({ name, count })- })- }-- return { browserVersions, osVersions }- }, [panelsData.data?.brv, panelsData.data?.osv])-const chartMetrics = useMemo(() =>[@@ -578,22 +475,15 @@ const TrafficViewInner = ({)const chartMetricsCustomEvents = useMemo(() => {- if (!_isEmpty(panelsData.customs)) {- return _map(_keys(panelsData.customs), (key) => ({+ if (!_isEmpty(customs)) {+ return _map(_keys(customs), (key) => ({id: key,label: key,active: _includes(activeChartMetricsCustomEvents, key),}))}return []- }, [panelsData, activeChartMetricsCustomEvents])-- const dataNamesCustomEvents = useMemo(() => {- if (!_isEmpty(panelsData.customs)) {- return { ..._keys(panelsData.customs) }- }- return {}- }, [panelsData])+ }, [customs, activeChartMetricsCustomEvents])const dataNames = useMemo(() => ({@@ -610,9 +500,12 @@ const TrafficViewInner = ({sessionDuration: t('dashboard.sessionDuration'),revenue: t('dashboard.revenue'),refundsAmount: t('dashboard.refunds'),- ...dataNamesCustomEvents,+ ..._keys(customs).reduce(+ (acc, key) => ({ ...acc, [key]: key }),+ {} as Record<string, string>,+ ),}),- [t, dataNamesCustomEvents],+ [t, customs],)const checkIfAllMetricsAreDisabled = useMemo(@@ -624,9 +517,8 @@ const TrafficViewInner = ({[activeChartMetrics, activeChartMetricsCustomEvents],)- // Filter annotations to only those within the chart's visible x-axis rangeconst filteredAnnotations = useMemo(() => {- const xAxis = (chartData as { x?: string[] })?.x+ const xAxis = chartData?.xif (!annotations?.length || !xAxis?.length) return annotations || []const rangeStart = dayjs(xAxis[0]).startOf('day')@@ -693,14 +585,7 @@ const TrafficViewInner = ({[searchParams, setSearchParams],)- const setPanelTab = (panel: keyof typeof panelsActiveTabs, tab: string) => {- setPanelsActiveTabs((prev) => ({- ...prev,- [panel]: tab,- }))- }-- // Load revenue data (the only remaining client-side fetch)+ // Load revenue data when the revenue metric is enabledconst loadRevenueData = useCallback(async () => {if (!project ||@@ -712,26 +597,17 @@ const TrafficViewInner = ({return}- // Early return if base chart x-axis is not yet available- const chart = baseChartData as { x?: string[] }+ const chart = baseChartDataif (!Array.isArray(chart?.x) || chart.x.length === 0) {setRevenueOverlay(null)return}try {- let from: string | undefined- let to: string | undefined-- if (dateRange) {- from = getFormatDate(dateRange[0])- to = getFormatDate(dateRange[1])- }-const revResult = await fetchRevenueData(id, {period: period === 'custom' ? 'custom' : period,- from,- to,+ from: common.from,+ to: common.to,timezone,timeBucket,})@@ -740,7 +616,6 @@ const TrafficViewInner = ({const revY = revChart?.revenue || []const revRefunds = revChart?.refundsAmount || []- // Align revenue series to the main traffic chart x-axislet revenueData: number[] = []let refundsData: number[] = []@@ -770,7 +645,8 @@ const TrafficViewInner = ({project,activeChartMetrics.revenue,isRevenueConnected,- dateRange,+ common.from,+ common.to,period,timezone,timeBucket,@@ -779,77 +655,351 @@ const TrafficViewInner = ({fetchRevenueData,])- const getCustomEventMetadata = async (event: string) => {- let result- if (period === 'custom' && dateRange) {- result = await fetchCustomEventsMetadata(id, event, {- timeBucket,- period: '',- from: getFormatDate(dateRange[0]),- to: getFormatDate(dateRange[1]),- timezone,- })- } else {- result = await fetchCustomEventsMetadata(id, event, {- timeBucket,- period,- timezone,- })- }+ useEffect(() => {+ loadRevenueData()+ }, [loadRevenueData])- return result || { result: [] }- }+ const getCustomEventMetadata = useCallback(+ async (event: string) =>+ metadataToResult(+ (await v2api.getCustomEventsMetadata(pid, { ...common, event })).data,+ ),+ [pid, common],+ )- const _getPropertyMetadata = async (property: string) => {- let result- if (period === 'custom' && dateRange) {- result = await fetchPropertyMetadata(id, property, {- timeBucket,- period: '',- from: getFormatDate(dateRange[0]),- to: getFormatDate(dateRange[1]),- filters,- timezone,- })- } else {- result = await fetchPropertyMetadata(id, property, {- timeBucket,- period,- filters,- timezone,- })- }+ const getPropertyMetadata = useCallback(+ async (property: string) =>+ metadataToResult(+ (await v2api.getPagePropertiesMetadata(pid, { ...common, property }))+ .data,+ ),+ [pid, common],+ )- return result || { result: [] }- }+ const hasRefNameFilter = useMemo(+ () => filters.some((f) => f.dimension === 'referrer_name'),+ [filters],+ )- // Load revenue data when revenue metric is enabled- useEffect(() => {- loadRevenueData()- }, [loadRevenueData, fetchRevenueData])+ // --- Panels ---- // Handle refresh trigger - use revalidator for URL-based data- useEffect(() => {- if (trafficRefreshTrigger > 0) {- revalidator.revalidate()+ const locationSubTabs = useMemo<BreakdownSubTab[]>(+ () => [+ { id: 'country', label: t('project.mapping.cc'), dimension: 'country' },+ { id: 'region', label: t('project.mapping.rg'), dimension: 'region' },+ { id: 'city', label: t('project.mapping.ct'), dimension: 'city' },+ { id: 'locale', label: t('project.mapping.lc'), dimension: 'locale' },+ {+ id: 'map',+ label: t('project.mapping.map'),+ render: () => <TrafficMap isFullscreen={false} />,+ },+ ],+ [t],+ )++ const pagesSubTabs = useMemo<BreakdownSubTab[]>(+ () => [+ { id: 'page', label: t('project.mapping.pg'), dimension: 'page' },+ {+ id: 'entry_page',+ label: t('project.entryPages'),+ dimension: 'entry_page',+ },+ {+ id: 'exit_page',+ label: t('project.exitPages'),+ dimension: 'exit_page',+ },+ {+ id: 'userFlow',+ label: t('project.mapping.userFlow'),+ render: () => <UserFlow isReversed={false} setReversed={() => {}} />,+ },+ { id: 'host', label: t('project.mapping.host'), dimension: 'host' },+ ],+ [t],+ )++ const devicesSubTabs = useMemo<BreakdownSubTab[]>(+ () => [+ {+ id: 'browser',+ label: t('project.mapping.br'),+ dimension: 'browser',+ versionsDimension: 'browser_version' as const,+ versionsParentField: 'browser' as const,+ },+ {+ id: 'os',+ label: t('project.mapping.os'),+ dimension: 'os',+ versionsDimension: 'os_version' as const,+ versionsParentField: 'os' as const,+ },+ { id: 'device', label: t('project.mapping.dv'), dimension: 'device' },+ ],+ [t],+ )++ const sourcesSubTabs = useMemo<(BreakdownSubTab | BreakdownSubTab[])[]>(+ () => [+ {+ id: 'referrer',+ label: t('project.mapping.ref'),+ dimension: 'referrer',+ },+ [+ {+ id: 'utm_source',+ label: t('project.mapping.so'),+ dimension: 'utm_source',+ },+ {+ id: 'utm_medium',+ label: t('project.mapping.me'),+ dimension: 'utm_medium',+ },+ {+ id: 'utm_campaign',+ label: t('project.mapping.ca'),+ dimension: 'utm_campaign',+ },+ {+ id: 'utm_term',+ label: t('project.mapping.te'),+ dimension: 'utm_term',+ },+ {+ id: 'utm_content',+ label: t('project.mapping.co'),+ dimension: 'utm_content',+ },+ ],+ ],+ [t],+ )++ const networkSubTabs = useMemo<(BreakdownSubTab | BreakdownSubTab[])[]>(+ () => [+ [+ { id: 'isp', label: t('project.mapping.isp'), dimension: 'isp' },+ {+ id: 'organization',+ label: t('project.mapping.og'),+ dimension: 'organization',+ },+ {+ id: 'user_type',+ label: t('project.mapping.ut'),+ dimension: 'user_type',+ },+ {+ id: 'connection_type',+ label: t('project.mapping.ctp'),+ dimension: 'connection_type',+ },+ ],+ ],+ [t],+ )++ const locationRowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const { name: entryName, cc } = entry++ if (subTabId === 'locale') {+ if (entryName === null) {+ return <CCRow cc={null} language={language} />+ }++ const entryNameArray = entryName.split('-')+ const displayName = getLocaleDisplayName(entryName, language)++ return (+ <CCRow+ cc={entryNameArray[entryNameArray.length - 1]}+ name={displayName}+ language={language}+ />+ )+ }++ if (cc !== undefined) {+ return (+ <CCRow cc={cc} name={entryName || undefined} language={language} />+ )+ }++ return <CCRow cc={entryName} language={language} />+ },+ [language],+ )++ const pagesRowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const { name: entryName } = entry++ if (!entryName) {+ return (+ <span className='italic'>+ {subTabId === 'host'+ ? t('project.unknownHost')+ : t('common.notSet')}+ </span>+ )+ }++ let decodedUri = entryName++ try {+ decodedUri = decodeURIComponent(entryName)+ } catch {+ // do nothing+ }++ if (subTabId === 'page' && project?.websiteUrl) {+ return (+ <PageLinkRow pagePath={decodedUri} websiteUrl={project.websiteUrl} />+ )+ }++ return decodedUri+ },+ [t, project?.websiteUrl],+ )++ const devicesRowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const v1Tab =+ subTabId === 'browser' ? 'br' : subTabId === 'os' ? 'os' : 'dv'+ const mapper = getDeviceRowMapper(v1Tab, theme, t) as+ | ((entry: Entry) => React.ReactNode)+ | undefined+ return mapper ? mapper(entry) : entry.name+ },+ [theme, t],+ )++ const networkRowMapper = useCallback(+ (entry: Entry, subTabId: string) => {+ const { name: entryName } = entry+ if (!entryName) {+ return <span className='italic'>{t('common.notSet')}</span>+ }+ if (subTabId === 'user_type') {+ return getUsageTypeLabel(entryName, t)+ }+ if (subTabId === 'connection_type') {+ return getConnectionTypeLabel(entryName, t)+ }+ return entryName+ },+ [t],+ )++ const sourcesRowMapper = useCallback((entry: Entry, subTabId: string) => {+ const { name: entryName } = entry+ if (subTabId === 'referrer') {+ return <RefRow rowName={entryName} />+ }+ try {+ return decodeURIComponent(entryName as string)+ } catch {+ return entryName}- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [trafficRefreshTrigger])+ }, [])++ const sourcesTransformEntries = useCallback(+ (entries: Entry[], subTabId: string) => {+ if (subTabId === 'referrer' && !hasRefNameFilter) {+ return groupRefEntries(entries)+ }+ return entries+ },+ [hasRefNameFilter],+ )++ const sourcesGetFilterLink = useCallback(+ (dimension: string, value: string | null, subTabId: string) => {+ if (subTabId === 'referrer') {+ // If grouped by name/domain (no referrer_name filter active) -> filter by referrer_name+ return getFilterLink(+ hasRefNameFilter || value === null ? 'referrer' : 'referrer_name',+ value,+ )+ }+ return getFilterLink(dimension, value)+ },+ [getFilterLink, hasRefNameFilter],+ )const exportTypes = useMemo(() => [{label: t('project.asCSV'),- onClick: () =>- onCSVExportClick(- { data: panelsData.data, types: panelsData.types || [] },- id,- tnMapping,- language,- ),+ onClick: async () => {+ const dimensions = [+ 'country',+ 'region',+ 'city',+ 'locale',+ 'page',+ 'entry_page',+ 'exit_page',+ 'host',+ 'browser',+ 'browser_version',+ 'os',+ 'os_version',+ 'device',+ 'referrer',+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'utm_term',+ 'utm_content',+ 'isp',+ 'organization',+ 'user_type',+ 'connection_type',+ ]++ try {+ const results = await Promise.all(+ dimensions.map((dimension) =>+ v2api+ .getBreakdown(pid, 'traffic', {+ ...common,+ dimension,+ limit: 100,+ sort: 'visitors:desc',+ })+ .catch(() => null),+ ),+ )++ const data: Record<string, Entry[]> = {}+ dimensions.forEach((dimension, index) => {+ const result = results[index]+ if (result && result.data.length > 0) {+ data[dimension] = mapBreakdownRows(result.data)+ }+ })++ onCSVExportClick(+ { data, types: _keys(data) },+ id,+ tnMapping,+ language,+ )+ } catch {+ toast.error(t('apiNotifications.somethingWentWrong'))+ }+ },},],- [t, panelsData, id, tnMapping, language],+ [t, pid, common, id, tnMapping, language],)// Show waiting state if project has no traffic data yet@@ -861,7 +1011,18 @@ const TrafficViewInner = ({<ProjectViewHeaderActions tnMapping={tnMapping} exportTypes={exportTypes} />)- // Show no events if data is empty+ if (isInitialLoading) {+ return (+ <>+ <DashboardHeader rightContent={headerRightContent} />+ <div className='relative overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>+ <MetricCardsSkeleton />+ <ChartSkeleton className='mt-4 h-80 md:h-80' />+ </div>+ </>+ )+ }+if (isPanelsDataEmpty) {return (<>@@ -873,46 +1034,12 @@ const TrafficViewInner = ({// Fullscreen map view - takes over the entire content areaif (isMapFullscreen && fullscreenMapRef.current) {- const countryData = panelsData.data?.cc || []- const regionData = panelsData.data?.rg || []- const total = countryData.reduce(- (acc: number, curr: any) => acc + curr.count,- 0,- )-- return createPortal(- <Suspense- fallback={- <div className='flex h-full flex-1 items-center justify-center'>- <div className='flex flex-col items-center gap-2'>- <div className='h-8 w-8 animate-spin rounded-full border-2 border-indigo-400 border-t-transparent' />- <span className='text-sm text-neutral-600 dark:text-neutral-300'>- Loading map...- </span>- </div>- </div>- }- >- <InteractiveMap- data={countryData}- regionData={regionData}- total={total}- onClick={(mapType, key) => {- const link = getFilterLink(mapType, key)- navigate(link)- }}- onFullscreenToggle={setIsMapFullscreen}- isFullscreen={true}- />- </Suspense>,- fullscreenMapRef.current,- )+ return createPortal(<TrafficMap isFullscreen />, fullscreenMapRef.current)}return (<><DashboardHeader rightContent={headerRightContent} />- {dataLoading && !isPanelsDataEmpty ? <LoadingBar /> : null}<div className={cx({ hidden: isPanelsDataEmpty })}>{!isPanelsDataEmpty ? (<Filters className='mb-3' tnMapping={tnMapping} />@@ -955,7 +1082,7 @@ const TrafficViewInner = ({const conflicted = isConflicted(conflicts)if (pairID === CHART_METRICS_MAPPING.customEvents) {- if (_isEmpty(panelsData.customs)) {+ if (_isEmpty(customs)) {return (<span className='flex cursor-not-allowed items-center p-2'><ProhibitIcon className='mr-2 h-4 w-4' />@@ -1012,7 +1139,9 @@ const TrafficViewInner = ({<HasImportedIndicator /></Suspense></div>- {!_isEmpty(overall) ? (+ {summaryQuery.isLoading ? (+ <MetricCardsSkeleton />+ ) : !_isEmpty(overall) ? (<motion.divinitial='hidden'animate='visible'@@ -1024,37 +1153,40 @@ const TrafficViewInner = ({overallCompare={overallCompare}activePeriodCompare={activePeriodCompare}/>- {!_isEmpty(panelsData.meta)- ? _map(panelsData.meta, ({ key, current, previous }) => (- <React.Fragment key={key}>- <MetricCard- label={t('project.metrics.xAvg', { x: key })}- value={current.avg}- change={current.avg - previous.avg}- goodChangeDirection='down'- valueMapper={(value, type) =>- `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`- }- />- <MetricCard- label={t('project.metrics.xTotal', { x: key })}- value={current.sum}- change={current.sum - previous.sum}- goodChangeDirection='down'- valueMapper={(value, type) =>- `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`- }- />- </React.Fragment>- ))+ {!_isEmpty(customMetricsQuery.data?.data)+ ? _map(+ customMetricsQuery.data?.data,+ ({ key, current, previous }) => (+ <React.Fragment key={key}>+ <MetricCard+ label={t('project.metrics.xAvg', { x: key })}+ value={current.avg}+ change={current.avg - previous.avg}+ goodChangeDirection='down'+ valueMapper={(value, type) =>+ `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`+ }+ />+ <MetricCard+ label={t('project.metrics.xTotal', { x: key })}+ value={current.sum}+ change={current.sum - previous.sum}+ goodChangeDirection='down'+ valueMapper={(value, type) =>+ `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`+ }+ />+ </React.Fragment>+ ),+ ): null}</motion.div>) : null}- {!checkIfAllMetricsAreDisabled && !_isEmpty(chartData) ? (+ {timeseriesQuery.isLoading ? (+ <ChartSkeleton className='mt-5 h-80 md:mt-0 md:h-80' />+ ) : !checkIfAllMetricsAreDisabled && !_isEmpty(chartData.x) ? (<div- onContextMenu={(e) =>- handleChartContextMenu(e, (chartData as any).x)- }+ onContextMenu={(e) => handleChartContextMenu(e, chartData.x)}className='relative'><TrafficChart@@ -1080,346 +1212,82 @@ const TrafficViewInner = ({) : null}</div><div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>- {!_isEmpty(panelsData.types)- ? _map(TRAFFIC_PANELS_ORDER, (type: string) => {- if (type === 'location') {- const locationTabs = [- { id: 'cc', label: t('project.mapping.cc') },- { id: 'rg', label: t('project.mapping.rg') },- { id: 'ct', label: t('project.mapping.ct') },- { id: 'lc', label: t('project.mapping.lc') },- { id: 'map', label: t('project.mapping.map') },- ]-- const rowMapper = (entry: CountryEntry) => {- const { name: entryName, cc } = entry-- if (panelsActiveTabs.location === 'lc') {- if (entryName === null) {- return <CCRow cc={null} language={language} />- }-- const entryNameArray = entryName.split('-')- const displayName = getLocaleDisplayName(- entryName,- language,- )-- return (- <CCRow- cc={entryNameArray[entryNameArray.length - 1]}- name={displayName}- language={language}- />- )- }-- if (cc !== undefined) {- return (- <CCRow- cc={cc}- name={entryName || undefined}- language={language}- />- )- }-- return <CCRow cc={entryName} language={language} />- }-- return (- <Panel- key={panelsActiveTabs.location}- icon={panelIconMapping.cc}- id={panelsActiveTabs.location}- getFilterLink={getFilterLink}- name={t('project.location')}- tabs={locationTabs}- onTabChange={(tab) => setPanelTab('location', tab)}- activeTabId={panelsActiveTabs.location}- data={panelsData.data[panelsActiveTabs.location]}- rowMapper={rowMapper}- customRenderer={- panelsActiveTabs.location === 'map'- ? () => {- const countryData = panelsData.data?.cc || []- const regionData = panelsData.data?.rg || []- const total = countryData.reduce(- (acc, curr) => acc + curr.count,- 0,- )-- return (- <Suspense fallback={<MapLoader />}>- <InteractiveMap- data={countryData}- regionData={regionData}- total={total}- onClick={(mapType, key) => {- const link = getFilterLink(mapType, key)- navigate(link)- }}- onFullscreenToggle={setIsMapFullscreen}- isFullscreen={false}- />- </Suspense>- )- }- : undefined- }- />- )- }-- if (type === 'devices') {- const deviceTabs = [- { id: 'br', label: t('project.mapping.br') },- { id: 'os', label: t('project.mapping.os') },- { id: 'dv', label: t('project.mapping.dv') },- ]-- return (- <Panel- key={panelsActiveTabs.device}- icon={panelIconMapping.os}- id={panelsActiveTabs.device}- getFilterLink={getFilterLink}- name={t('project.devices')}- tabs={deviceTabs}- onTabChange={(tab) => setPanelTab('device', tab)}- activeTabId={panelsActiveTabs.device}- data={panelsData.data[panelsActiveTabs.device]}- rowMapper={getDeviceRowMapper(- panelsActiveTabs.device,- theme,- t,- )}- capitalize={panelsActiveTabs.device === 'dv'}- versionData={- panelsActiveTabs.device === 'br'- ? createVersionDataMapping.browserVersions- : panelsActiveTabs.device === 'os'- ? createVersionDataMapping.osVersions- : undefined- }- getVersionFilterLink={(parent, version) =>- getVersionFilterLink(- parent,- version,- panelsActiveTabs.device === 'br' ? 'br' : 'os',- )- }- />- )- }-- if (type === 'network') {- const networkTabs = [- [- { id: 'isp', label: t('project.mapping.isp') },- { id: 'og', label: t('project.mapping.og') },- { id: 'ut', label: t('project.mapping.ut') },- { id: 'ctp', label: t('project.mapping.ctp') },- ],- ]-- const activeNetworkTab = panelsActiveTabs.network-- return (- <Panel- key={activeNetworkTab}- icon={panelIconMapping.isp}- id={activeNetworkTab}- getFilterLink={getFilterLink}- name={t('project.network')}- tabs={networkTabs}- onTabChange={(tab) => setPanelTab('network', tab)}- activeTabId={activeNetworkTab}- data={panelsData.data[activeNetworkTab]}- rowMapper={({ name: entryName }) => {- if (!entryName) {- return (- <span className='italic'>{t('common.notSet')}</span>- )- }- if (activeNetworkTab === 'ut') {- return getUsageTypeLabel(entryName, t)- }- if (activeNetworkTab === 'ctp') {- return getConnectionTypeLabel(entryName, t)- }- return entryName- }}- />- )- }-- if (type === 'pg') {- const pageTabs = [- { id: 'pg', label: t('project.mapping.pg') },- { id: 'entryPage', label: t('project.entryPages') },- { id: 'exitPage', label: t('project.exitPages') },- { id: 'userFlow', label: t('project.mapping.userFlow') },- {- id: 'host',- label: t('project.mapping.host'),- },- ]-- return (- <Panel- key={panelsActiveTabs.page}- icon={panelIconMapping.pg}- id={panelsActiveTabs.page}- getFilterLink={getFilterLink}- rowMapper={({ name: entryName }) => {- if (!entryName) {- return (- <span className='italic'>- {panelsActiveTabs.page === 'host'- ? t('project.unknownHost')- : t('common.notSet')}- </span>- )- }-- let decodedUri = entryName as string-- try {- decodedUri = decodeURIComponent(entryName)- } catch {- // do nothing- }-- // For page paths (pg tab), show with clickable link- if (- panelsActiveTabs.page === 'pg' &&- project?.websiteUrl- ) {- return (- <PageLinkRow- pagePath={decodedUri}- websiteUrl={project.websiteUrl}- />- )- }-- return decodedUri- }}- name={t('project.pages')}- tabs={pageTabs}- onTabChange={(tab) => setPanelTab('page', tab)}- activeTabId={panelsActiveTabs.page}- data={panelsData.data[panelsActiveTabs.page]}- customRenderer={- panelsActiveTabs.page === 'userFlow'- ? () => (- <UserFlow- isReversed={false}- setReversed={() => {}}- />- )- : undefined- }- />- )- }-- if (type === 'traffic-sources') {- const hasRefNameFilter = filters.some(- (f) => f.column === 'refn',- )- const trafficSourcesTabs = [- { id: 'ref', label: t('project.mapping.ref') },- [- { id: 'so', label: t('project.mapping.so') },- { id: 'me', label: t('project.mapping.me') },- { id: 'ca', label: t('project.mapping.ca') },- { id: 'te', label: t('project.mapping.te') },- { id: 'co', label: t('project.mapping.co') },- ],- ]-- const getTrafficSourcesRowMapper = (activeTab: string) => {- if (activeTab === 'ref') {- // eslint-disable-next-line- return ({ name: entryName }: any) => (- <RefRow rowName={entryName} />- )- }- return ({ name: entryName }: any) => {- try {- return decodeURIComponent(entryName)- } catch {- return entryName- }- }- }-- return (- <Panel- key={panelsActiveTabs.source}- icon={panelIconMapping.ref}- id={panelsActiveTabs.source}- getFilterLink={(column: string, value: string | null) => {- if (panelsActiveTabs.source === 'ref') {- // If grouped by name/domain (no refn filter active) -> filter by refn- return getFilterLink(- hasRefNameFilter || value === null ? 'ref' : 'refn',- value,- )- }- return getFilterLink(column, value)- }}- name={t('project.trafficSources')}- tabs={trafficSourcesTabs}- onTabChange={(tab) => setPanelTab('source', tab)}- activeTabId={panelsActiveTabs.source}- data={- panelsActiveTabs.source === 'ref'- ? (() => {- const raw = panelsData.data?.ref || []- return hasRefNameFilter- ? (raw as unknown as Entry[])- : (groupRefEntries(- raw as any,- ) as unknown as Entry[])- })()- : (panelsData.data[- panelsActiveTabs.source- ] as unknown as Entry[])- }- rowMapper={getTrafficSourcesRowMapper(- panelsActiveTabs.source,- )}- />- )- }-- return null- })- : null}+ <BreakdownPanel+ dataType='traffic'+ panelId='location'+ name={t('project.location')}+ icon={panelIconMapping.country}+ subTabs={locationSubTabs}+ rowMapper={locationRowMapper}+ />+ <BreakdownPanel+ dataType='traffic'+ panelId='pages'+ name={t('project.pages')}+ icon={panelIconMapping.page}+ subTabs={pagesSubTabs}+ rowMapper={pagesRowMapper}+ />+ <BreakdownPanel+ dataType='traffic'+ panelId='devices'+ name={t('project.devices')}+ icon={panelIconMapping.os}+ subTabs={devicesSubTabs}+ rowMapper={devicesRowMapper}+ capitalize={['device']}+ getVersionFilterLink={(parent, version, subTabId) =>+ getVersionFilterLink(+ parent,+ version,+ subTabId === 'browser' ? 'browser' : 'os',+ )+ }+ />+ <BreakdownPanel+ dataType='traffic'+ panelId='traffic-sources'+ name={t('project.trafficSources')}+ icon={panelIconMapping.referrer}+ subTabs={sourcesSubTabs}+ rowMapper={sourcesRowMapper}+ transformEntries={sourcesTransformEntries}+ getFilterLink={sourcesGetFilterLink}+ />+ <BreakdownPanel+ dataType='traffic'+ panelId='network'+ name={t('project.network')}+ icon={panelIconMapping.isp}+ subTabs={networkSubTabs}+ rowMapper={networkRowMapper}+ />{/* Combined Metadata Panel - holds both pageview properties and custom event metadata */}<CombinedMetadataPaneltitle={t('project.metadata')}property={{- metadataKeys: _keys(panelsData.properties),- getMetadataValues: _getPropertyMetadata,- activeKey: panelsActiveTabs.pageviewMetadata,- onKeyChange: (key) => setPanelTab('pageviewMetadata', key),+ metadataKeys: _keys(properties),+ getMetadataValues: getPropertyMetadata,+ activeKey: metadataActiveKeys.property,+ onKeyChange: (key) =>+ setMetadataActiveKeys((prev) => ({ ...prev, property: key })),}}customEvent={{- metadataKeys: _keys(panelsData.customs),+ metadataKeys: _keys(customs),getMetadataValues: getCustomEventMetadata,- activeKey: panelsActiveTabs.customEvMetadata,- onKeyChange: (key) => setPanelTab('customEvMetadata', key),+ activeKey: metadataActiveKeys.customEvent,+ onKeyChange: (key) =>+ setMetadataActiveKeys((prev) => ({+ ...prev,+ customEvent: key,+ })),}}getFilterLink={getFilterLink}chartData={chartData}filters={filters}/><CustomEvents- customs={panelsData.customs}+ customs={customs}filters={filters}getFilterLink={getFilterLink}chartData={chartData}diff --git a/web/app/pages/Project/tabs/Traffic/UserFlow.tsx b/web/app/pages/Project/tabs/Traffic/UserFlow.tsxindex 25f4617f9..2c5f7b7e8 100644--- a/web/app/pages/Project/tabs/Traffic/UserFlow.tsx+++ b/web/app/pages/Project/tabs/Traffic/UserFlow.tsx@@ -1,79 +1,26 @@import { ResponsiveSankey } from '@nivo/sankey'import { ArrowClockwiseIcon, TreeStructureIcon } from '@phosphor-icons/react'import _isEmpty from 'lodash/isEmpty'-import { useEffect, useState, memo, useMemo } from 'react'+import { memo } from 'react'import { useTranslation } from 'react-i18next'-import { toast } from 'sonner'-import { useUserFlowProxy } from '~/hooks/useAnalyticsProxy'-import type { UserFlowResponse } from '~/api/api.server'+import { useUserFlowQuery } from '~/hooks/v2/useV2Queries'import { PanelEmptyState } from '~/pages/Project/View/Panels'import Button from '~/ui/Button'import Loader from '~/ui/Loader'import { Text } from '~/ui/Text'-import { useCurrentProject } from '../../../../providers/CurrentProjectProvider'-import { useViewProjectContext } from '../../View/ViewProject'-import { getFormatDate } from '../../View/ViewProject.helpers'-interface UserFlowProps {isReversed?: booleansetReversed: () => void}const UserFlow = ({ setReversed, isReversed }: UserFlowProps) => {- const { dateRange, period, timeBucket, timezone, filters } =- useViewProjectContext()- const { id } = useCurrentProject()const { t } = useTranslation('common')- const [isLoading, setIsLoading] = useState<boolean | null>(null)- const [userFlow, setUserFlow] = useState<UserFlowResponse | null>(null)- const { fetchUserFlow: fetchUserFlowProxy } = useUserFlowProxy()-- const [from, to] = useMemo(() => {- if (!dateRange) {- return [undefined, undefined]- }-- return [getFormatDate(dateRange[0]), getFormatDate(dateRange[1])]- }, [dateRange])-- const fetchUserFlow = async () => {- if (isLoading) {- return- }-- setIsLoading(true)-- try {- const result = await fetchUserFlowProxy(id, {- timeBucket,- period,- filters,- from,- to,- timezone,- })- if (result) {- setUserFlow(result as UserFlowResponse)- }- } catch (error: any) {- toast.error(- typeof error === 'string'- ? error- : t('apiNotifications.somethingWentWrong'),- )- } finally {- setIsLoading(false)- }- }-- useEffect(() => {- fetchUserFlow()- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [filters, period, timeBucket, from, to, timezone, id])+ const { data, isLoading } = useUserFlowQuery()+ const userFlow = data?.data- if (isLoading || isLoading === null) {+ if (isLoading) {return <Loader />}diff --git a/web/app/providers/CurrentProjectProvider.tsx b/web/app/providers/CurrentProjectProvider.tsxindex 47a4a3c47..40e853948 100644--- a/web/app/providers/CurrentProjectProvider.tsx+++ b/web/app/providers/CurrentProjectProvider.tsx@@ -16,7 +16,7 @@ import {} from 'react-router'import { toast } from 'sonner'-import { useLiveVisitorsProxy } from '~/hooks/useAnalyticsProxy'+import { getLiveVisitors } from '~/api/v2/endpoints'import {LIVE_VISITORS_UPDATE_INTERVAL,LS_PROJECTS_PROTECTED_KEY,@@ -275,7 +275,6 @@ const useLiveVisitors = (project: Project | null) => {const projectId = project?.idconst isLocked = project?.isLockedconst [liveVisitors, setLiveVisitors] = useState(0)- const { fetchLiveVisitors } = useLiveVisitorsProxy()const updateLiveVisitors = useCallback(async () => {if (!projectId || isLocked) {@@ -283,14 +282,12 @@ const useLiveVisitors = (project: Project | null) => {}try {- const result = await fetchLiveVisitors([projectId])- if (result) {- setLiveVisitors(result[projectId] || 0)- }+ const { data } = await getLiveVisitors(projectId)+ setLiveVisitors(data.count || 0)} catch (reason) {console.error('Failed to update live visitors:', reason)}- }, [projectId, isLocked, fetchLiveVisitors])+ }, [projectId, isLocked])useEffect(() => {if (!projectId || isLocked) {diff --git a/web/app/root.tsx b/web/app/root.tsxindex 246e3c717..dee313967 100644--- a/web/app/root.tsx+++ b/web/app/root.tsx@@ -4,6 +4,7 @@ import {CaretUpIcon,WifiSlashIcon,} from '@phosphor-icons/react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import BillboardCss from 'billboard.js/dist/billboard.min.css?url'import cx from 'clsx'import _replace from 'lodash/replace'@@ -461,6 +462,19 @@ const RouteScripts = () => {const Body = () => {const { isAuthed, user, totalMonthlyEvents } = useLoaderData<typeof loader>()const { theme } = useTheme()+ const [queryClient] = useState(+ () =>+ new QueryClient({+ defaultOptions: {+ queries: {+ staleTime: 60_000,+ gcTime: 5 * 60_000,+ retry: 1,+ refetchOnWindowFocus: false,+ },+ },+ }),+ )return (<body@@ -469,16 +483,18 @@ const Body = () => {'bg-slate-950': theme === 'dark',})}>- <AuthProvider- initialIsAuthenticated={isAuthed}- initialUser={user}- initialTotalMonthlyEvents={totalMonthlyEvents}- >- {/* Drops transform-based motion (keeps opacity) for prefers-reduced-motion users */}- <MotionConfig reducedMotion='user'>- <AppWrapper />- </MotionConfig>- </AuthProvider>+ <QueryClientProvider client={queryClient}>+ <AuthProvider+ initialIsAuthenticated={isAuthed}+ initialUser={user}+ initialTotalMonthlyEvents={totalMonthlyEvents}+ >+ {/* Drops transform-based motion (keeps opacity) for prefers-reduced-motion users */}+ <MotionConfig reducedMotion='user'>+ <AppWrapper />+ </MotionConfig>+ </AuthProvider>+ </QueryClientProvider><ScrollRestoration /><RouteScripts /><Scripts />diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.tsindex d24bd1b62..d2d560c00 100644--- a/web/app/routes/api.analytics.ts+++ b/web/app/routes/api.analytics.ts@@ -5,39 +5,24 @@ import {} from 'react-router'import {- getSessionsServer,getSessionReplaysServer,getSessionReplayServer,deleteSessionReplayServer,- getFunnelSessionsServer,getGoalSessionsServer,- getErrorsServer,getFeatureFlagStatsServer,getFeatureFlagProfilesServer,getGoalStatsServer,getGoalChartServer,- getCaptchaDataServer,getExperimentResultsServer,getExperimentServer,getGoalServer,getProjectGoalsServer,getProjectFeatureFlagsServer,- getProfilesServer,- getProfileServer,- getProfileSessionsServer,getProjectServer,getFiltersServer,getDataDeletionPreviewServer,- getErrorsFiltersServer,- getVersionFiltersServer,- getCustomEventsMetadataServer,- getPropertyMetadataServer,- getErrorSessionsServer,getLiveVisitorsServer,- getLiveVisitorsInfoServer,getBotProtectionStatsServer,- getProjectDataCustomEventsServer,- getUserFlowServer,getGSCKeywordsServer,getGSCDashboardServer,getGSCDetailsServer,@@ -46,37 +31,23 @@ import {getOverallStatsServer,type AnalyticsParams,type AnalyticsFilter,- type SessionsResponse,type SessionReplaysResponse,type SessionReplayResponse,type DeleteSessionReplayResponse,- type FunnelSessionsResponse,type GoalSessionsResponse,- type ErrorsResponse,type FeatureFlagStats,type FeatureFlagProfilesResponse,type GoalStats,type GoalChartData,- type CaptchaDataResponse,type ExperimentResults,type Experiment,type Goal,type GoalsResponse,type FeatureFlagsResponse,- type ProfilesResponse,- type ProfileDetailsResponse,- type ProfileSessionsResponse,type Project,- type VersionFilter,- type CustomEventsMetadataResponse,- type PropertyMetadataResponse,- type ErrorSessionsResponse,type LiveStats,- type LiveVisitorInfo,type BotProtectionStats,type BotProtectionPeriod,- type ProjectDataCustomEventsResponse,- type UserFlowResponse,type GSCKeywordsResponse,type GSCDashboardResponse,type GSCDetailsResponse,@@ -104,60 +75,38 @@ function formatDateForBackend(dateStr: string | undefined): string | undefined {interface ProxyRequest {action:- | 'getSessions'| 'getSessionReplays'| 'getSessionReplay'| 'deleteSessionReplay'- | 'getErrors'| 'getFeatureFlagStats'| 'getFeatureFlagProfiles'| 'getGoalStats'| 'getGoalChart'- | 'getCaptchaData'| 'getExperimentResults'| 'getExperiment'| 'getGoal'| 'getProjectGoals'| 'getProjectFeatureFlags'- | 'getProfiles'- | 'getProfile'- | 'getProfileSessions'| 'getProject'| 'getFilters'| 'getDataDeletionPreview'- | 'getErrorsFilters'- | 'getVersionFilters'- | 'getCustomEventsMetadata'- | 'getPropertyMetadata'- | 'getErrorSessions'| 'getLiveVisitors'- | 'getLiveVisitorsInfo'| 'getBotProtectionStats'- | 'getProjectDataCustomEvents'- | 'getUserFlow'| 'getGSCKeywords'| 'getGSCDashboard'| 'getGSCDetails'| 'getRevenueStatus'| 'getRevenueData'| 'getOverallStats'- | 'getFunnelSessions'| 'getGoalSessions'projectId: stringpids?: string[]flagId?: stringgoalId?: stringexperimentId?: string- profileId?: stringpsid?: stringreplayId?: string- errorId?: stringfilterType?: string- filterColumn?: 'br' | 'os'- dataType?: 'traffic' | 'errors'- event?: string- property?: string- customEvents?: string[]params: {timeBucket?: stringperiod?: string@@ -167,15 +116,10 @@ interface ProxyRequest {filters?: AnalyticsFilter[]take?: numberskip?: number- options?: Record<string, unknown>resultFilter?: stringsearch?: string- profileType?: 'all' | 'anonymous' | 'identified'page?: stringquery?: string- funnelId?: string- step?: number- dropoff?: booleangoalId?: stringsessionEvent?: 'traffic' | 'performance' | 'error'}@@ -213,22 +157,6 @@ export async function action({ request }: ActionFunctionArgs) {try {switch (action) {- case 'getSessions': {- const result = await getSessionsServer(- request,- projectId,- analyticsParams,- )- return data<ProxyResponse<SessionsResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-case 'getSessionReplays': {const result = await getSessionReplaysServer(request,@@ -304,30 +232,6 @@ export async function action({ request }: ActionFunctionArgs) {})}- case 'getFunnelSessions': {- const result = await getFunnelSessionsServer(request, projectId, {- period: analyticsParams.period,- from: analyticsParams.from,- to: analyticsParams.to,- timezone: analyticsParams.timezone,- funnelId: params.funnelId,- step: params.step ?? 1,- take: params.take,- skip: params.skip,- password: analyticsParams.password,- filters: params.filters || [],- dropoff: params.dropoff,- })- return data<ProxyResponse<FunnelSessionsResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-case 'getGoalSessions': {const goalId = body.goalId || params.goalIdif (!goalId) {@@ -355,19 +259,6 @@ export async function action({ request }: ActionFunctionArgs) {})}- case 'getErrors': {- const errorsParams = { ...analyticsParams, options: params.options }- const result = await getErrorsServer(request, projectId, errorsParams)- return data<ProxyResponse<ErrorsResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-case 'getFeatureFlagStats': {if (!body.flagId) {return data<ProxyResponse<null>>(@@ -474,27 +365,6 @@ export async function action({ request }: ActionFunctionArgs) {})}- case 'getCaptchaData': {- const result = await getCaptchaDataServer(- request,- projectId,- params.timeBucket || 'hour',- params.period || '3d',- params.filters || [],- formatDateForBackend(params.from) || '',- formatDateForBackend(params.to) || '',- password || undefined,- )- return data<ProxyResponse<CaptchaDataResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-case 'getExperimentResults': {if (!body.experimentId) {return data<ProxyResponse<null>>(@@ -594,84 +464,6 @@ export async function action({ request }: ActionFunctionArgs) {})}- case 'getProfiles': {- const result = await getProfilesServer(- request,- projectId,- params.period || '7d',- params.filters || [],- formatDateForBackend(params.from) || '',- formatDateForBackend(params.to) || '',- params.take || 30,- params.skip || 0,- params.timezone || '',- params.profileType || 'all',- password || undefined,- )- return data<ProxyResponse<ProfilesResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-- case 'getProfile': {- if (!body.profileId) {- return data<ProxyResponse<null>>(- { data: null, error: 'profileId is required' },- { status: 400 },- )- }- const result = await getProfileServer(- request,- projectId,- body.profileId,- params.timezone || '',- password || undefined,- )- return data<ProxyResponse<ProfileDetailsResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-- case 'getProfileSessions': {- if (!body.profileId) {- return data<ProxyResponse<null>>(- { data: null, error: 'profileId is required' },- { status: 400 },- )- }- const result = await getProfileSessionsServer(- request,- projectId,- body.profileId,- params.period || 'all',- params.filters || [],- formatDateForBackend(params.from) || '',- formatDateForBackend(params.to) || '',- params.take || 30,- params.skip || 0,- params.timezone || '',- password || undefined,- )- return data<ProxyResponse<ProfileSessionsResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-case 'getProject': {const result = await getProjectServer(request,@@ -727,147 +519,6 @@ export async function action({ request }: ActionFunctionArgs) {})}- case 'getErrorsFilters': {- if (!body.filterType) {- return data<ProxyResponse<null>>(- { data: null, error: 'filterType is required' },- { status: 400 },- )- }- const result = await getErrorsFiltersServer(- request,- projectId,- body.filterType,- password || undefined,- )- return data<ProxyResponse<string[]>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-- case 'getVersionFilters': {- if (!body.filterColumn || !body.dataType) {- return data<ProxyResponse<null>>(- { data: null, error: 'filterColumn and dataType are required' },- { status: 400 },- )- }- const result = await getVersionFiltersServer(- request,- projectId,- body.dataType,- body.filterColumn,- password || undefined,- )- return data<ProxyResponse<VersionFilter[]>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-- case 'getCustomEventsMetadata': {- if (!body.event) {- return data<ProxyResponse<null>>(- { data: null, error: 'event is required' },- { status: 400 },- )- }- const result = await getCustomEventsMetadataServer(- request,- projectId,- body.event,- {- timeBucket: params.timeBucket,- period: params.period,- from: formatDateForBackend(params.from),- to: formatDateForBackend(params.to),- timezone: params.timezone,- password: password || undefined,- },- )- return data<ProxyResponse<CustomEventsMetadataResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-- case 'getPropertyMetadata': {- if (!body.property) {- return data<ProxyResponse<null>>(- { data: null, error: 'property is required' },- { status: 400 },- )- }- const result = await getPropertyMetadataServer(- request,- projectId,- body.property,- {- timeBucket: params.timeBucket,- period: params.period,- from: formatDateForBackend(params.from),- to: formatDateForBackend(params.to),- filters: params.filters,- timezone: params.timezone,- password: password || undefined,- },- )- return data<ProxyResponse<PropertyMetadataResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-- case 'getErrorSessions': {- if (!body.errorId) {- return data<ProxyResponse<null>>(- { data: null, error: 'errorId is required' },- { status: 400 },- )- }- const result = await getErrorSessionsServer(- request,- projectId,- body.errorId,- {- timeBucket: params.timeBucket,- period: params.period,- from: formatDateForBackend(params.from),- to: formatDateForBackend(params.to),- filters: params.filters,- timezone: params.timezone,- take: params.take,- skip: params.skip,- password: password || undefined,- },- )- return data<ProxyResponse<ErrorSessionsResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-case 'getLiveVisitors': {const pids = body.pids || [projectId]const result = await getLiveVisitorsServer(@@ -885,22 +536,6 @@ export async function action({ request }: ActionFunctionArgs) {})}- case 'getLiveVisitorsInfo': {- const result = await getLiveVisitorsInfoServer(- request,- projectId,- password || undefined,- )- return data<ProxyResponse<LiveVisitorInfo[]>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-case 'getBotProtectionStats': {const period = (params.period as BotProtectionPeriod) || '30d'const validPeriods: BotProtectionPeriod[] = ['7d', '30d', '90d']@@ -921,51 +556,6 @@ export async function action({ request }: ActionFunctionArgs) {})}- case 'getProjectDataCustomEvents': {- const result = await getProjectDataCustomEventsServer(- request,- projectId,- {- timeBucket: params.timeBucket,- period: params.period,- filters: params.filters,- from: formatDateForBackend(params.from),- to: formatDateForBackend(params.to),- timezone: params.timezone,- customEvents: body.customEvents,- password: password || undefined,- },- )- return data<ProxyResponse<ProjectDataCustomEventsResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-- case 'getUserFlow': {- const result = await getUserFlowServer(request, projectId, {- timeBucket: params.timeBucket,- period: params.period,- filters: params.filters,- from: formatDateForBackend(params.from),- to: formatDateForBackend(params.to),- timezone: params.timezone,- password: password || undefined,- })- return data<ProxyResponse<UserFlowResponse>>({- data: result.data,- error: result.error- ? Array.isArray(result.error)- ? result.error.join(', ')- : result.error- : null,- })- }-case 'getGSCKeywords': {const result = await getGSCKeywordsServer(request, projectId, {period: params.period,diff --git a/web/app/routes/api.v2.$.ts b/web/app/routes/api.v2.$.tsnew file mode 100644index 000000000..3f144442c--- /dev/null+++ b/web/app/routes/api.v2.$.ts@@ -0,0 +1,35 @@+import { type LoaderFunctionArgs, data } from 'react-router'++import { serverFetch } from '~/api/api.server'+import {+ createHeadersWithCookies,+ getProjectPasswordCookie,+} from '~/utils/session.server'++// Proxies GET /api/v2/projects/<pid>/... to the backend /v2/projects/<pid>/...+// analytics API. Keeps auth tokens (httpOnly cookies -> Bearer, with refresh)+// and the per-project password cookie (-> x-password) server-side.+const V2_PATH_REGEX = /^projects\/([a-zA-Z0-9-]{1,64})(\/|$)/++export async function loader({ request, params }: LoaderFunctionArgs) {+ const path = params['*'] || ''++ const match = path.match(V2_PATH_REGEX)++ if (!match) {+ return data({ error: 'Invalid v2 API path' }, { status: 400 })+ }++ const pid = match[1]+ const password = getProjectPasswordCookie(request, pid)+ const { search } = new URL(request.url)++ const result = await serverFetch(request, `v2/${path}${search}`, {+ headers: password ? { 'x-password': password } : undefined,+ })++ return data(result.data ?? { error: result.error }, {+ status: result.status,+ headers: createHeadersWithCookies(result.cookies),+ })+}diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsxindex 00790f9f2..7ae93b220 100644--- a/web/app/routes/projects.$id.tsx+++ b/web/app/routes/projects.$id.tsx@@ -1,48 +1,26 @@-import _includes from 'lodash/includes'-import _some from 'lodash/some'import _split from 'lodash/split'-import _startsWith from 'lodash/startsWith'import { useTranslation } from 'react-i18next'import {+ data,+ redirect,type ActionFunctionArgs,type LinksFunction,type LoaderFunctionArgs,type MetaFunction,+ type ShouldRevalidateFunctionArgs,} from 'react-router'-import { data, redirect } from 'react-router'import {serverFetch,authMeServer,- getProjectDataServer,- getOverallStatsServer,- getCustomEventsDataServer,- getPerfDataServer,- getPerformanceOverallStatsServer,- getSessionsServer,getSessionReplaysServer,- getSessionServer,- getErrorsServer,- getErrorServer,- getErrorOverviewServer,getProjectFeatureFlagsServer,getProjectGoalsServer,- getFunnelDataServer,- type TrafficLogResponse,- type OverallObject,- type PerformanceDataResponse,- type PerformanceOverallObject,- type SessionsResponse,type SessionReplaysResponse,- type SessionDetailsResponse,- type ErrorsResponse,- type ErrorDetailsResponse,- type ErrorOverviewResponse,type FeatureFlagsResponse,type GoalsResponse,- type FunnelDataResponse,- type AnalyticsFilter,} from '~/api/api.server'+import { parseFiltersFromUrl, v2FilterToLegacy } from '~/utils/analyticsUrl'import { useRequiredParams } from '~/hooks/useRequiredParams'import {DEFAULT_TIMEZONE,@@ -378,143 +356,81 @@ export const meta: MetaFunction<typeof loader> = ({]}-const validFilters = [- 'host',- 'cc',- 'rg',- 'ct',- 'pg',- 'entryPage',- 'exitPage',- 'lc',- 'ref',- 'refn',- 'dv',- 'br',- 'brv',- 'os',- 'osv',- 'so',- 'me',- 'ca',- 'te',- 'co',- 'isp',- 'og',- 'ut',- 'ctp',- 'ev',- 'tag:key',- 'tag:value',- 'ev:key',- 'ev:value',-]-const validDynamicFilters = ['ev:key:', 'tag:key:']+export interface ProjectLoaderData {+ project: Project | null+ isPasswordRequired: boolean+ error?: string+ // Session replays (v1 - no v2 equivalent yet)+ replaysData?: Promise<SessionReplaysResponse | null>+ // Feature Flags data+ featureFlagsData?: Promise<FeatureFlagsResponse | null>+ // Goals data+ goalsData?: Promise<GoalsResponse | null>+ // Data import+ hasImportedData?: Promise<boolean>+}-function isFilterValid(filter: string, checkDynamicFilters = false) {- let normalised = filter- if (- _startsWith(normalised, '!') ||- _startsWith(normalised, '~') ||- _startsWith(normalised, '^')- ) {- normalised = normalised.substring(1)+// Tabs whose data still comes from this loader (v1 endpoints). All other tabs+// fetch client-side via the v2 API, so URL param changes (period, filters,+// timeBucket, ...) must not re-run the loader for them.+const LOADER_BACKED_TABS = new Set<string>([+ PROJECT_TABS.replays,+ PROJECT_TABS.featureFlags,+ PROJECT_TABS.goals,+])++export function shouldRevalidate({+ currentUrl,+ nextUrl,+ formAction,+ defaultShouldRevalidate,+}: ShouldRevalidateFunctionArgs) {+ // Route actions (goal/funnel/view CRUD, password submission) may change+ // loader data+ if (formAction) {+ return defaultShouldRevalidate}- if (_includes(validFilters, normalised)) {+ if (currentUrl.pathname !== nextUrl.pathname) {+ return true+ }++ const currentTab = currentUrl.searchParams.get('tab') || PROJECT_TABS.traffic+ const nextTab = nextUrl.searchParams.get('tab') || PROJECT_TABS.traffic++ if (currentTab !== nextTab) {return true}if (- checkDynamicFilters &&- _some(validDynamicFilters, (prefix) => _startsWith(normalised, prefix))+ nextUrl.searchParams.get('password') !==+ currentUrl.searchParams.get('password')) {return true}- return false-}--function parseFiltersFromUrl(searchParams: URLSearchParams): AnalyticsFilter[] {- const filters: AnalyticsFilter[] = []-- const entries = Array.from(searchParams.entries())-- for (const [key, value] of entries) {- let actualColumn = key-- let isExclusive = false- let isContains = false-- if (key.startsWith('!')) {- isExclusive = true- actualColumn = key.substring(1)- } else if (key.startsWith('~')) {- isContains = true- actualColumn = key.substring(1)- } else if (key.startsWith('^')) {- isExclusive = true- isContains = true- actualColumn = key.substring(1)- }-- if (!isFilterValid(actualColumn, true)) {- continue- }-- filters.push({- column: actualColumn,- filter: value,- isExclusive: isExclusive,- isContains,- })+ if (LOADER_BACKED_TABS.has(nextTab)) {+ return defaultShouldRevalidate}- return filters-}+ // The traffic tab's "has imported data" indicator depends on the period+ if (+ nextTab === PROJECT_TABS.traffic &&+ (nextUrl.searchParams.get('period') !==+ currentUrl.searchParams.get('period') ||+ nextUrl.searchParams.get('from') !==+ currentUrl.searchParams.get('from') ||+ nextUrl.searchParams.get('to') !== currentUrl.searchParams.get('to'))+ ) {+ return true+ }-export interface ProjectLoaderData {- project: Project | null- isPasswordRequired: boolean- error?: string- // Traffic data- trafficData?: Promise<TrafficLogResponse | null>- overallStats?: Promise<Record<string, OverallObject> | null>- trafficCompareData?: Promise<TrafficLogResponse | null>- overallCompareStats?: Promise<Record<string, OverallObject> | null>- customEventsData?: Promise<{- chart?: { events?: Record<string, unknown> }- } | null>- // Performance data- perfData?: Promise<PerformanceDataResponse | null>- perfOverallStats?: Promise<Record<string, PerformanceOverallObject> | null>- perfCompareData?: Promise<PerformanceDataResponse | null>- perfOverallCompareStats?: Promise<Record<- string,- PerformanceOverallObject- > | null>- // Sessions data- sessionsData?: Promise<SessionsResponse | null>- replaysData?: Promise<SessionReplaysResponse | null>- sessionDetails?: Promise<SessionDetailsResponse | null>- // Errors data- errorsData?: Promise<ErrorsResponse | null>- errorDetails?: Promise<ErrorDetailsResponse | null>- errorOverview?: Promise<ErrorOverviewResponse | null>- // Feature Flags data- featureFlagsData?: Promise<FeatureFlagsResponse | null>- // Goals data- goalsData?: Promise<GoalsResponse | null>- // Funnels data- funnelData?: Promise<FunnelDataResponse | null>- // Data import- hasImportedData?: Promise<boolean>+ return false}export async function loader({ request, params }: LoaderFunctionArgs) {const { id: projectId } = paramsconst url = new URL(request.url)- const seoTabId = !isSelfhosted ? PROJECT_TABS.seo : nullconst passwordFromQuery = url.searchParams.get('password') || ''const passwordFromCookie = getProjectPasswordCookie(request, projectId || '')@@ -572,7 +488,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}- // Parse URL params for analytics data+ // Parse URL params (most analytics are fetched client-side via the v2 API;+ // the loader only feeds the tabs still on v1: replays, feature flags, goals)const tab =(url.searchParams.get('tab') as keyof typeof PROJECT_TABS) ||PROJECT_TABS.traffic@@ -581,33 +498,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const from = formatDateForBackend(url.searchParams.get('from') || '')const to = formatDateForBackend(url.searchParams.get('to') || '')const timezone = url.searchParams.get('timezone') || userTimezone- const filters = parseFiltersFromUrl(url.searchParams)+ // v1 endpoints still consume the legacy filter shape+ const filters = parseFiltersFromUrl(url.searchParams).map(v2FilterToLegacy)// Ensure the time bucket is valid for the selected period and date rangeconst timeBucket = getValidTimeBucket(period, urlTimeBucket, from, to)- // Performance-specific params- const measure = url.searchParams.get('measure') || 'median'- const perfMetric = url.searchParams.get('perfMetric') || 'timing' // 'timing' or 'quantiles'-- // Compare params- const compareEnabled = url.searchParams.get('compare') === 'true'- const compareFrom = formatDateForBackend(- url.searchParams.get('compareFrom') || '',- )- const compareTo = formatDateForBackend(- url.searchParams.get('compareTo') || '',- )-- // Traffic custom events params- const customEventsParam = url.searchParams.get('customEvents') || ''- const customEvents = customEventsParam- ? customEventsParam.split(',').filter(Boolean)- : []-- // Segment custom metrics (JSON-encoded ProjectViewCustomEvent[])- const metricsParam = url.searchParams.get('metrics') || undefined-const analyticsParams = {timeBucket,period,@@ -616,137 +512,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {to: to || undefined,timezone,password: password || undefined,- metrics: metricsParam,}// Initialize deferred data promises- let trafficData: Promise<TrafficLogResponse | null> | undefined- let overallStats: Promise<Record<string, OverallObject> | null> | undefined- let trafficCompareData: Promise<TrafficLogResponse | null> | undefined- let overallCompareStats:- | Promise<Record<string, OverallObject> | null>- | undefined- let customEventsData:- | Promise<{ chart?: { events?: Record<string, unknown> } } | null>- | undefined- let perfData: Promise<PerformanceDataResponse | null> | undefined- let perfOverallStats:- | Promise<Record<string, PerformanceOverallObject> | null>- | undefined- let perfCompareData: Promise<PerformanceDataResponse | null> | undefined- let perfOverallCompareStats:- | Promise<Record<string, PerformanceOverallObject> | null>- | undefined- let sessionsData: Promise<SessionsResponse | null> | undefinedlet replaysData: Promise<SessionReplaysResponse | null> | undefined- let sessionDetails: Promise<SessionDetailsResponse | null> | undefined- let errorsData: Promise<ErrorsResponse | null> | undefined- let errorDetails: Promise<ErrorDetailsResponse | null> | undefined- let errorOverview: Promise<ErrorOverviewResponse | null> | undefinedlet featureFlagsData: Promise<FeatureFlagsResponse | null> | undefinedlet goalsData: Promise<GoalsResponse | null> | undefined- let funnelData: Promise<FunnelDataResponse | null> | undefinedlet hasImportedData: Promise<boolean> | undefined// Only fetch data if project is valid and not lockedif (project && !project.isLocked && projectId) {- if (tab === PROJECT_TABS.traffic) {- trafficData = getProjectDataServer(- request,- projectId,- analyticsParams,- ).then((res) => res.data)- overallStats = getOverallStatsServer(- request,- [projectId],- analyticsParams,- ).then((res) => res.data)-- // Fetch compare data if enabled- if (compareEnabled && compareFrom && compareTo) {- const compareParams = {- ...analyticsParams,- period: 'custom' as const,- from: compareFrom,- to: compareTo,- }- trafficCompareData = getProjectDataServer(- request,- projectId,- compareParams,- ).then((res) => res.data)- overallCompareStats = getOverallStatsServer(- request,- [projectId],- compareParams,- ).then((res) => res.data)- }-- // Fetch custom events data if any custom events are selected- if (customEvents.length > 0) {- customEventsData = getCustomEventsDataServer(- request,- projectId,- analyticsParams,- customEvents,- ).then((res) => res.data)- }- } else if (seoTabId && tab === seoTabId) {- trafficData = getProjectDataServer(- request,- projectId,- analyticsParams,- ).then((res) => res.data)- } else if (tab === PROJECT_TABS.performance) {- // Use measure from URL, or 'quantiles' if perfMetric is quantiles- const effectiveMeasure =- perfMetric === 'quantiles' ? 'quantiles' : measure- const perfParams = { ...analyticsParams, measure: effectiveMeasure }- perfData = getPerfDataServer(request, projectId, perfParams).then(- (res) => res.data,- )- perfOverallStats = getPerformanceOverallStatsServer(- request,- [projectId],- perfParams,- ).then((res) => res.data)-- if (compareEnabled && compareFrom && compareTo) {- const compareParams = {- ...perfParams,- period: 'custom' as const,- from: compareFrom,- to: compareTo,- }- perfCompareData = getPerfDataServer(- request,- projectId,- compareParams,- ).then((res) => res.data)- perfOverallCompareStats = getPerformanceOverallStatsServer(- request,- [projectId],- compareParams,- ).then((res) => res.data)- }- } else if (tab === PROJECT_TABS.sessions) {- sessionsData = getSessionsServer(- request,- projectId,- analyticsParams,- ).then((res) => res.data)- // Fetch session details if psid is in URL- const psid = url.searchParams.get('psid')- if (psid) {- sessionDetails = getSessionServer(- request,- projectId,- psid,- timezone,- password || undefined,- ).then((res) => res.data)- }- } else if (+ if (tab === PROJECT_TABS.replays &&(isSelfhosted || project.featureAccess?.replays === true)) {@@ -755,25 +531,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {projectId,analyticsParams,).then((res) => res.data)- } else if (tab === PROJECT_TABS.errors) {- errorsData = getErrorsServer(request, projectId, analyticsParams).then(- (res) => res.data,- )- errorOverview = getErrorOverviewServer(- request,- projectId,- analyticsParams,- ).then((res) => res.data)- // Fetch error details if eid is in URL- const eid = url.searchParams.get('eid')- if (eid) {- errorDetails = getErrorServer(- request,- projectId,- eid,- analyticsParams,- ).then((res) => res.data)- }} else if (tab === PROJECT_TABS.featureFlags &&(isSelfhosted || project.featureAccess?.featureFlags === true)@@ -785,25 +542,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {goalsData = getProjectGoalsServer(request, projectId).then((res) => res.data,)- } else if (tab === PROJECT_TABS.funnels) {- // Fetch funnel data if funnelId is in URL- const funnelId = url.searchParams.get('funnelId')- if (funnelId) {- const funnelFrom = from || ''- const funnelTo = to || ''- const funnelPeriod = period === 'custom' ? '' : period- funnelData = getFunnelDataServer(- request,- projectId,- funnelId,- funnelPeriod,- funnelFrom,- funnelTo,- timezone,- password || undefined,- filters,- ).then((res) => res.data)- }}const importRange = computeDateRangeForPeriod(period, from, to)@@ -824,24 +562,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {{project,isPasswordRequired: false,- trafficData,- overallStats,- trafficCompareData,- overallCompareStats,- customEventsData,- perfData,- perfOverallStats,- perfCompareData,- perfOverallCompareStats,- sessionsData,replaysData,- sessionDetails,- errorsData,- errorDetails,- errorOverview,featureFlagsData,goalsData,- funnelData,hasImportedData,},{ headers: createHeadersWithCookies(cookies) },diff --git a/web/app/ui/FilterValueInput.tsx b/web/app/ui/FilterValueInput.tsxindex 9ecd3e1ee..759690b3e 100644--- a/web/app/ui/FilterValueInput.tsx+++ b/web/app/ui/FilterValueInput.tsx@@ -32,6 +32,7 @@ import {DevicesIcon,TagIcon,TelevisionIcon,+ WarningIcon,WatchIcon,} from '@phosphor-icons/react'import {@@ -55,36 +56,38 @@ import countries from '~/utils/isoCountries'const ITEM_HEIGHT = 36-// Icon mapping for filter categories+// Icon mapping for filter categories (keyed by v2 dimension names)export const filterCategoryIcons: Record<string, ReactNode> = {- cc: <MapPinIcon className='size-4' />,- rg: <MapTrifoldIcon className='size-4' />,- ct: <BuildingIcon className='size-4' />,- pg: <FileTextIcon className='size-4' />,- entryPage: <SignInIcon className='size-4' />,- exitPage: <SignOutIcon className='size-4' />,+ country: <MapPinIcon className='size-4' />,+ region: <MapTrifoldIcon className='size-4' />,+ city: <BuildingIcon className='size-4' />,+ page: <FileTextIcon className='size-4' />,+ entry_page: <SignInIcon className='size-4' />,+ exit_page: <SignOutIcon className='size-4' />,host: <HardDrivesIcon className='size-4' />,- br: <CompassIcon className='size-4' />,- brv: <CompassIcon className='size-4' />,+ browser: <CompassIcon className='size-4' />,+ browser_version: <CompassIcon className='size-4' />,os: <MonitorPlayIcon className='size-4' />,- osv: <MonitorPlayIcon className='size-4' />,- ref: <LinkIcon className='size-4' />,- so: <ShareIcon className='size-4' />,- me: <RadioIcon className='size-4' />,- ca: <MegaphoneIcon className='size-4' />,- te: <TagIcon className='size-4' />,- co: <FileIcon className='size-4' />,- lc: <TranslateIcon className='size-4' />,- dv: <DevicesIcon className='size-4' />,+ os_version: <MonitorPlayIcon className='size-4' />,+ referrer: <LinkIcon className='size-4' />,+ referrer_name: <LinkIcon className='size-4' />,+ utm_source: <ShareIcon className='size-4' />,+ utm_medium: <RadioIcon className='size-4' />,+ utm_campaign: <MegaphoneIcon className='size-4' />,+ utm_term: <TagIcon className='size-4' />,+ utm_content: <FileIcon className='size-4' />,+ locale: <TranslateIcon className='size-4' />,+ device: <DevicesIcon className='size-4' />,isp: <GlobeIcon className='size-4' />,- og: <BuildingIcon className='size-4' />,- ut: <CpuIcon className='size-4' />,- ctp: <LinkIcon className='size-4' />,- ev: <RadioIcon className='size-4' />,- 'ev:key': <TagIcon className='size-4' />,- 'ev:value': <TagIcon className='size-4' />,- 'tag:key': <TagIcon className='size-4' />,- 'tag:value': <TagIcon className='size-4' />,+ organization: <BuildingIcon className='size-4' />,+ user_type: <CpuIcon className='size-4' />,+ connection_type: <LinkIcon className='size-4' />,+ event: <RadioIcon className='size-4' />,+ event_metadata: <TagIcon className='size-4' />,+ page_property: <TagIcon className='size-4' />,+ error_name: <WarningIcon className='size-4' />,+ error_message: <WarningIcon className='size-4' />,+ error_filename: <FileIcon className='size-4' />,}const deviceIconMapping: Record<string, ReactNode> = {@@ -161,11 +164,11 @@ const FilterValueInput = ({const getLabelForItem = useCallback((item: string) => {- if (column === 'cc') {+ if (column === 'country') {return countries.getName(item, language) || item}// Handle combined version values (e.g., "Chrome|||120.5" -> "Chrome 120.5")- if (column === 'brv' || column === 'osv') {+ if (column === 'browser_version' || column === 'os_version') {const parsed = parseVersionValue(item)if (parsed) {return `${parsed.parent} ${parsed.version}`@@ -178,7 +181,7 @@ const FilterValueInput = ({const getIconForItem = useCallback((item: string): ReactNode => {- if (column === 'cc') {+ if (column === 'country') {return (<FlagclassName='shrink-0 rounded-xs'@@ -190,7 +193,7 @@ const FilterValueInput = ({)}- if (column === 'br') {+ if (column === 'browser') {// @ts-expect-error - dynamic key accessconst logoUrl = BROWSER_LOGO_MAP[item]if (logoUrl) {@@ -200,7 +203,7 @@ const FilterValueInput = ({}// For browser versions, show browser icon- if (column === 'brv') {+ if (column === 'browser_version') {const parsed = parseVersionValue(item)if (parsed) {// @ts-expect-error - dynamic key access@@ -233,7 +236,7 @@ const FilterValueInput = ({}// For OS versions, show OS icon- if (column === 'osv') {+ if (column === 'os_version') {const parsed = parseVersionValue(item)if (parsed) {// @ts-expect-error - dynamic key access@@ -256,7 +259,7 @@ const FilterValueInput = ({return <GlobeIcon className='size-4 shrink-0' />}- if (column === 'dv') {+ if (column === 'device') {const icon = deviceIconMapping[item]if (icon) {return <span className='shrink-0'>{icon}</span>@@ -264,7 +267,7 @@ const FilterValueInput = ({return <QuestionMarkIcon className='size-4 shrink-0' />}- if (column === 'lc') {+ if (column === 'locale') {const countryCode = item.split('-').pop()if (countryCode && countries.getName(countryCode, language)) {return (@@ -279,10 +282,10 @@ const FilterValueInput = ({}}- const baseColumn = column.startsWith('ev:key:')- ? 'ev:key'- : column.startsWith('tag:key:')- ? 'tag:key'+ const baseColumn = column.startsWith('event_metadata:')+ ? 'event_metadata'+ : column.startsWith('page_property:')+ ? 'page_property': columnconst categoryIcon =filterCategoryIcons[column] || filterCategoryIcons[baseColumn]@@ -344,7 +347,7 @@ const FilterValueInput = ({e.preventDefault()if (inputValue.trim()) {// For country codes, try to find the alpha2 code- if (column === 'cc') {+ if (column === 'country') {const alpha2 = countries.getAlpha2Code(inputValue, language)if (alpha2) {onChange(alpha2)@@ -424,7 +427,7 @@ const FilterValueInput = ({<buttontype='button'onClick={() => {- if (column === 'cc') {+ if (column === 'country') {const alpha2 = countries.getAlpha2Code(inputValue,language,diff --git a/web/app/utils/analyticsUrl.ts b/web/app/utils/analyticsUrl.tsnew file mode 100644index 000000000..61ea5d909--- /dev/null+++ b/web/app/utils/analyticsUrl.ts@@ -0,0 +1,200 @@+import { V2Filter, V2FilterOperator } from '~/api/v2/types'+import {+ ALL_VALID_DIMENSIONS,+ KEYED_DIMENSIONS,+ V1_KEYED_PREFIX_TO_V2,+ V1_TO_V2_DIMENSION,+} from '~/lib/v2Dimensions'++// Filters live in the URL as `<prefix><dimension>=<value>` search params:+// country=US -> { dimension: 'country', operator: 'is', value: 'US' }+// !country=US -> is_not+// ~page=/blog -> contains+// ^page=/blog -> contains_not+// Keyed dimensions carry their key after a colon:+// event_metadata:plan=free+// The literal value `null` (or an empty value) means "unknown" and maps to+// v2 `value: null` — same convention v1 links used.+// v1 short codes (`cc`, `pg`, `ev:key:plan`, ...) are accepted on parse only,+// so old shared links keep working.++const OPERATOR_BY_PREFIX: Record<string, V2FilterOperator> = {+ '!': 'is_not',+ '~': 'contains',+ '^': 'contains_not',+}++const PREFIX_BY_OPERATOR: Record<V2FilterOperator, string> = {+ is: '',+ is_not: '!',+ contains: '~',+ contains_not: '^',+}++interface ParsedFilterKey {+ dimension: string+ key?: string+ operator: V2FilterOperator+}++/** Parses a URL search param key into { dimension, key?, operator }, or null */+export const parseFilterKey = (rawKey: string): ParsedFilterKey | null => {+ let operator: V2FilterOperator = 'is'+ let key = rawKey++ const prefixOperator = OPERATOR_BY_PREFIX[key.charAt(0)]+ if (prefixOperator) {+ operator = prefixOperator+ key = key.substring(1)+ }++ // legacy keyed filters: ev:key:<k> / tag:key:<k>+ for (const [prefix, dimension] of Object.entries(V1_KEYED_PREFIX_TO_V2)) {+ if (key.startsWith(prefix)) {+ const metaKey = key.substring(prefix.length)+ if (!metaKey) return null+ return { dimension, key: metaKey, operator }+ }+ }++ // keyed filters: event_metadata:<k> / page_property:<k>+ for (const dimension of KEYED_DIMENSIONS) {+ if (key.startsWith(`${dimension}:`)) {+ const metaKey = key.substring(dimension.length + 1)+ if (!metaKey) return null+ return { dimension, key: metaKey, operator }+ }+ }++ // legacy v1 short codes+ const aliased = V1_TO_V2_DIMENSION[key]+ if (aliased) {+ return { dimension: aliased, operator }+ }++ if (ALL_VALID_DIMENSIONS.includes(key)) {+ return { dimension: key, operator }+ }++ // Not a v2 dimension, but a valid filter on tabs with their own data source+ // (GSC keywords on the SEO tab). Never sent to the v2 API.+ if (key === 'keywords') {+ return { dimension: key, operator }+ }++ return null+}++/** Builds the canonical URL search param key for a filter */+export const filterToUrlKey = (+ filter: Pick<V2Filter, 'dimension' | 'operator' | 'key'>,+): string => {+ const prefix = PREFIX_BY_OPERATOR[filter.operator]+ const dimension = filter.key+ ? `${filter.dimension}:${filter.key}`+ : filter.dimension+ return `${prefix}${dimension}`+}++export const filterToUrlValue = (filter: V2Filter): string => {+ if (Array.isArray(filter.value)) {+ return filter.value.map((v) => v ?? 'null').join(',')+ }+ return filter.value ?? 'null'+}++/** Parses all filters from URL search params into the v2 filter shape */+export const parseFiltersFromUrl = (+ searchParams: URLSearchParams,+): V2Filter[] => {+ const filters: V2Filter[] = []++ for (const [rawKey, rawValue] of searchParams.entries()) {+ const parsed = parseFilterKey(rawKey)++ if (!parsed) {+ continue+ }++ filters.push({+ dimension: parsed.dimension,+ operator: parsed.operator,+ value: rawValue === '' || rawValue === 'null' ? null : rawValue,+ ...(parsed.key ? { key: parsed.key } : {}),+ })+ }++ return filters+}++/**+ * Returns true if the given URL search param key is a filter (used to strip+ * or toggle filters without touching unrelated params like `period`).+ */+export const isFilterUrlKey = (rawKey: string): boolean =>+ parseFilterKey(rawKey) !== null++/** Legacy saved-view filter shape (kept server-side; converted at the edges) */+export interface LegacyFilter {+ column: string+ filter: string+ isExclusive: boolean+ isContains?: boolean+}++export const legacyFilterToV2 = (legacy: LegacyFilter): V2Filter | null => {+ let dimension: string | undefined+ let key: string | undefined++ for (const [prefix, keyed] of Object.entries(V1_KEYED_PREFIX_TO_V2)) {+ if (legacy.column.startsWith(prefix)) {+ dimension = keyed+ key = legacy.column.substring(prefix.length)+ break+ }+ }++ if (!dimension) {+ dimension =+ V1_TO_V2_DIMENSION[legacy.column] ||+ (ALL_VALID_DIMENSIONS.includes(legacy.column) ? legacy.column : undefined)+ }++ if (!dimension) {+ return null+ }++ const operator: V2FilterOperator = legacy.isContains+ ? legacy.isExclusive+ ? 'contains_not'+ : 'contains'+ : legacy.isExclusive+ ? 'is_not'+ : 'is'++ return {+ dimension,+ operator,+ value: legacy.filter === '' ? null : legacy.filter,+ ...(key ? { key } : {}),+ }+}++export const v2FilterToLegacy = (filter: V2Filter): LegacyFilter => {+ const column = filter.key+ ? filter.dimension === 'event_metadata'+ ? `ev:key:${filter.key}`+ : `tag:key:${filter.key}`+ : (Object.entries(V1_TO_V2_DIMENSION).find(+ ([, v2]) => v2 === filter.dimension,+ )?.[0] ?? filter.dimension)++ return {+ column,+ filter: filterToUrlValue(filter),+ isExclusive:+ filter.operator === 'is_not' || filter.operator === 'contains_not',+ isContains:+ filter.operator === 'contains' || filter.operator === 'contains_not',+ }+}diff --git a/web/package-lock.json b/web/package-lock.jsonindex 324f142b7..4c806e310 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -19,6 +19,7 @@"@rrweb/replay": "2.1.0","@swetrix/node": "^3.2.0","@takumi-rs/image-response": "^1.8.7",+ "@tanstack/react-query": "^5.101.2","@tanstack/react-virtual": "^3.14.3","@ua-parser-js/pro-business": "^2.0.10","billboard.js": "^3.18.0",@@ -4755,6 +4756,32 @@"@takumi-rs/helpers": "1.8.7"}},+ "node_modules/@tanstack/query-core": {+ "version": "5.101.2",+ "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.101.2.tgz",+ "integrity": "sha512-hH5MLoJhF7KaIGd7q3xTXGXvslI+GYlM1Z/35aSHHWaCJWB7XvTSHYuV3eM7tw+aE0mT/xMro4M4Q9rCGHT0lw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ }+ },+ "node_modules/@tanstack/react-query": {+ "version": "5.101.2",+ "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.101.2.tgz",+ "integrity": "sha512-seDkr6kzGzX1okaaTtZPtgA688CDPlXUz1C6xSg0ESqn04Vuc8tlrYms1s3de+znBqhPVxFRfpAfUf+6XvfPWg==",+ "license": "MIT",+ "dependencies": {+ "@tanstack/query-core": "5.101.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ },+ "peerDependencies": {+ "react": "^18 || ^19"+ }+ },"node_modules/@tanstack/react-virtual": {"version": "3.14.3","resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.14.3.tgz",diff --git a/web/package.json b/web/package.jsonindex 1edbdf29d..d55590096 100644--- a/web/package.json+++ b/web/package.json@@ -32,6 +32,7 @@"@rrweb/replay": "2.1.0","@swetrix/node": "^3.2.0","@takumi-rs/image-response": "^1.8.7",+ "@tanstack/react-query": "^5.101.2","@tanstack/react-virtual": "^3.14.3","@ua-parser-js/pro-business": "^2.0.10","billboard.js": "^3.18.0",diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex a1c556c4e..6bba4a941 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -2093,6 +2093,9 @@"og": "Organisation","ut": "Usage type","ctp": "Connection type",+ "error_name": "Error name",+ "error_message": "Error message",+ "error_filename": "Filename","searchEngine": "Search engine","aiReferral": "AI referral","captcha_event": "Challenge status",