Skip to content

📈 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!

Clean-up profile details UI

Blue Mousecf87d8052301
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index fbaa47187..c16f6dcdf 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -2696,14 +2696,7 @@ export class AnalyticsController {
@CurrentUserId() uid: string,
@Headers() headers: { 'x-password'?: string },
) {
- const {
- pid,
- profileId,
- timezone = DEFAULT_TIMEZONE,
- period,
- from,
- to,
- } = data
+ const { pid, profileId, timezone = DEFAULT_TIMEZONE } = data
await this.analyticsService.checkProjectAccess(
pid,
@@ -2714,55 +2707,22 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
this.logger.log(
- `pid: ${pid}, profileId: ${profileId}, period: ${period}`,
+ `pid: ${pid}, profileId: ${profileId}`,
'GET /analytics/profile',
)
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
- let timeBucket
- let diff
-
- if (period === 'all') {
- const res = await this.analyticsService.calculateTimeBucketForAllTime(
- pid,
- ['pageview', 'custom_event', 'error'],
- )
- timeBucket = res.timeBucket[0]
- diff = res.diff
- } else {
- timeBucket = getLowestPossibleTimeBucket(period, from, to)
- }
-
- const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
- from,
- to,
- timeBucket,
- period,
- safeTimezone,
- diff,
- )
-
- const [details, topPages, activityCalendar, chart] = await Promise.all([
+ const [details, topPages, activityCalendar] = await Promise.all([
this.analyticsService.getProfileDetails(pid, profileId, safeTimezone),
this.analyticsService.getProfileTopPages(pid, profileId),
this.analyticsService.getProfileActivityCalendar(pid, profileId),
- this.analyticsService.getProfileChartData(
- pid,
- profileId,
- timeBucket,
- groupFromUTC,
- groupToUTC,
- safeTimezone,
- ),
])
return {
...details,
topPages,
activityCalendar,
- chart,
- timeBucket,
}
}
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 86a450e78..7cfecb6d9 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -6089,6 +6089,14 @@ export class AnalyticsService {
AND profileId = {profileId:String}
`
+ const queryErrors = `
+ SELECT count() AS errorsCount
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type = 'error'
+ AND profileId = {profileId:String}
+ `
+
const queryDetails = `
SELECT
any(cc) AS cc,
@@ -6131,6 +6139,7 @@ export class AnalyticsService {
avgDurationResult,
pageviewsResult,
eventsResult,
+ errorsResult,
detailsResult,
revenueResult,
] = await Promise.all([
@@ -6146,6 +6155,9 @@ export class AnalyticsService {
clickhouse
.query({ query: queryEvents, query_params: params })
.then((resultSet) => resultSet.json()),
+ clickhouse
+ .query({ query: queryErrors, query_params: params })
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryDetails, query_params: params })
.then((resultSet) => resultSet.json()),
@@ -6161,6 +6173,7 @@ export class AnalyticsService {
const avgDuration = (avgDurationResult.data[0] || {}) as Record<string, any>
const pageviews = (pageviewsResult.data[0] || {}) as Record<string, any>
const events = (eventsResult.data[0] || {}) as Record<string, any>
+ const errors = (errorsResult.data[0] || {}) as Record<string, any>
const details = (detailsResult.data[0] || {}) as Record<string, any>
const revenue = (revenueResult.data[0] || {}) as Record<string, any>
@@ -6170,6 +6183,7 @@ export class AnalyticsService {
sessionsCount: sessionCount.sessionsCount || 0,
pageviewsCount: pageviews.pageviewsCount || 0,
eventsCount: events.eventsCount || 0,
+ errorsCount: errors.errorsCount || 0,
firstSeen: sessionCount.firstSeen,
lastSeen: sessionCount.lastSeen,
avgDuration: avgDuration.avgDuration || 0,
@@ -6242,115 +6256,6 @@ export class AnalyticsService {
return data as { date: string; pageviews: number; events: number }[]
}
- async getProfileChartData(
- pid: string,
- profileId: string,
- timeBucket: string,
- from: string,
- to: string,
- safeTimezone: string,
- ): Promise<{
- x: string[]
- pageviews: number[]
- customEvents: number[]
- errors: number[]
- }> {
- const timeBucketFunc =
- timeBucketConversion[timeBucket] || timeBucketConversion.day
-
- const queryPageviews = `
- SELECT
- ${timeBucketFunc}(toTimeZone(created, {timezone:String})) AS time,
- count() AS count
- FROM events
- WHERE pid = {pid:FixedString(12)}
- AND type = 'pageview'
- AND profileId = {profileId:String}
- AND created BETWEEN {from:String} AND {to:String}
- GROUP BY time
- ORDER BY time ASC
- `
-
- const queryEvents = `
- SELECT
- ${timeBucketFunc}(toTimeZone(created, {timezone:String})) AS time,
- count() AS count
- FROM events
- WHERE pid = {pid:FixedString(12)}
- AND type = 'custom_event'
- AND profileId = {profileId:String}
- AND created BETWEEN {from:String} AND {to:String}
- GROUP BY time
- ORDER BY time ASC
- `
-
- const queryErrors = `
- SELECT
- ${timeBucketFunc}(toTimeZone(created, {timezone:String})) AS time,
- count() AS count
- FROM events
- WHERE pid = {pid:FixedString(12)}
- AND type = 'error'
- AND profileId = {profileId:String}
- AND created BETWEEN {from:String} AND {to:String}
- GROUP BY time
- ORDER BY time ASC
- `
-
- const params = { pid, profileId, from, to, timezone: safeTimezone }
-
- const [pageviewsResult, eventsResult, errorsResult] = await Promise.all([
- clickhouse
- .query({ query: queryPageviews, query_params: params })
- .then((resultSet) => resultSet.json()),
- clickhouse
- .query({ query: queryEvents, query_params: params })
- .then((resultSet) => resultSet.json()),
- clickhouse
- .query({ query: queryErrors, query_params: params })
- .then((resultSet) => resultSet.json()),
- ])
-
- // Merge all timestamps and create aligned data
- const allTimes = new Set<string>()
- const pageviewsMap = new Map<string, number>()
- const eventsMap = new Map<string, number>()
- const errorsMap = new Map<string, number>()
-
- for (const row of pageviewsResult.data as {
- time: string
- count: number
- }[]) {
- allTimes.add(row.time)
- pageviewsMap.set(row.time, Number(row.count))
- }
-
- for (const row of eventsResult.data as {
- time: string
- count: number
- }[]) {
- allTimes.add(row.time)
- eventsMap.set(row.time, Number(row.count))
- }
-
- for (const row of errorsResult.data as {
- time: string
- count: number
- }[]) {
- allTimes.add(row.time)
- errorsMap.set(row.time, Number(row.count))
- }
-
- const sortedTimes = Array.from(allTimes).sort()
-
- return {
- x: sortedTimes,
- pageviews: sortedTimes.map((t) => pageviewsMap.get(t) || 0),
- customEvents: sortedTimes.map((t) => eventsMap.get(t) || 0),
- errors: sortedTimes.map((t) => errorsMap.get(t) || 0),
- }
- }
-
private buildProfileSessionsEventsCTE(
filtersQuery: string,
customEVFilterApplied: boolean,
@@ -6390,6 +6295,129 @@ export class AnalyticsService {
)`
}
+ async getProfileSessionPageflows(
+ pid: string,
+ psids: string[],
+ safeTimezone: string,
+ ): Promise<Map<string, any[]>> {
+ if (_isEmpty(psids)) {
+ return new Map()
+ }
+
+ const query = `
+ WITH events_with_meta AS (
+ SELECT
+ multiIf(event_type = 'pageview', 'pageview', event_type = 'custom_event', 'event', 'error') AS type,
+ multiIf(
+ event_type = 'pageview', toString(pg),
+ event_type = 'custom_event', toString(event_name),
+ toString(error_name)
+ ) AS value,
+ toTimeZone(created, {timezone:String}) AS created,
+ toString(psid) AS psid,
+ if(
+ event_type = 'error',
+ arrayFilter(x -> x.2 != '' AND x.2 != '0', [
+ tuple('message', COALESCE(error_message, '')),
+ tuple('lineno', ifNull(toString(lineno), '')),
+ tuple('colno', ifNull(toString(colno), '')),
+ tuple('filename', COALESCE(error_filename, ''))
+ ]),
+ arrayFilter(x -> x.1 != '' AND x.2 != '', arrayZip(meta_key, meta_value))
+ ) AS metadata
+ FROM (
+ SELECT
+ type AS event_type,
+ pg,
+ event_name,
+ error_name,
+ error_message,
+ lineno,
+ colno,
+ error_filename,
+ created,
+ psid,
+ meta.key AS meta_key,
+ meta.value AS meta_value
+ FROM events
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event', 'error')
+ AND psid IS NOT NULL
+ AND toString(psid) IN {psids:Array(String)}
+ )
+
+ UNION ALL
+
+ SELECT
+ type,
+ COALESCE(toString(product_name), toString(product_id), if(type = 'refund', 'Refund', 'Sale')) AS value,
+ toTimeZone(created, {timezone:String}) AS created,
+ toString(session_id) AS psid,
+ [
+ tuple('amount', toString(amount)),
+ tuple('currency', toString(currency)),
+ tuple('transaction_id', toString(transaction_id)),
+ tuple('status', toString(status)),
+ tuple('provider', toString(provider))
+ ] AS metadata
+ FROM (
+ SELECT
+ argMax(type, synced_at) AS type,
+ argMax(product_name, synced_at) AS product_name,
+ argMax(product_id, synced_at) AS product_id,
+ argMax(created, synced_at) AS created,
+ session_id,
+ argMax(amount, synced_at) AS amount,
+ argMax(currency, synced_at) AS currency,
+ transaction_id,
+ argMax(status, synced_at) AS status,
+ argMax(provider, synced_at) AS provider
+ FROM revenue
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND session_id IS NOT NULL
+ AND toString(session_id) IN {psids:Array(String)}
+ AND revenue.type IN ('sale', 'refund')
+ GROUP BY session_id, transaction_id
+ )
+ )
+
+ SELECT
+ type,
+ value,
+ created,
+ psid,
+ metadata
+ FROM events_with_meta
+ ORDER BY psid ASC, created ASC
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { pid, psids, timezone: safeTimezone },
+ })
+ .then((resultSet) => resultSet.json<IPageflow>())
+
+ const pageflows = new Map<string, any[]>()
+ const processedPages = this.processPageflow(data as IPageflow[]) as any[]
+
+ for (const page of processedPages) {
+ const sessionId = page.psid ? String(page.psid) : null
+ if (!sessionId) {
+ continue
+ }
+
+ const { psid: _psid, ...pageData } = page
+ const existing = pageflows.get(sessionId) || []
+ existing.push(pageData)
+ pageflows.set(sessionId, existing)
+ }
+
+ return pageflows
+ }
+
async getProfileSessionsList(
pid: string,
profileId: string,
@@ -6506,7 +6534,17 @@ export class AnalyticsService {
})
.then((resultSet) => resultSet.json())
- return data as object[]
+ const sessions = data as any[]
+ const pageflows = await this.getProfileSessionPageflows(
+ pid,
+ sessions.map((session) => String(session.psid)).filter(Boolean),
+ safeTimezone,
+ )
+
+ return sessions.map((session) => ({
+ ...session,
+ pages: pageflows.get(String(session.psid)) || [],
+ }))
}
async getErrorsList(
diff --git a/backend/apps/cloud/src/analytics/interfaces/index.ts b/backend/apps/cloud/src/analytics/interfaces/index.ts
index a1bf62359..55938e04d 100644
--- a/backend/apps/cloud/src/analytics/interfaces/index.ts
+++ b/backend/apps/cloud/src/analytics/interfaces/index.ts
@@ -212,6 +212,7 @@ export interface IPageflow {
type: 'pageview' | 'event' | 'error' | 'sale' | 'refund'
value: string
created: string
+ psid?: string
metadata?: [string, string][]
}
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index 8d1d42ea1..297cc89c9 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -2485,14 +2485,7 @@ export class AnalyticsController {
@CurrentUserId() uid: string,
@Headers() headers: { 'x-password'?: string },
) {
- const {
- pid,
- profileId,
- timezone = DEFAULT_TIMEZONE,
- period,
- from,
- to,
- } = data
+ const { pid, profileId, timezone = DEFAULT_TIMEZONE } = data
await this.analyticsService.checkProjectAccess(
pid,
@@ -2501,55 +2494,22 @@ export class AnalyticsController {
)
this.logger.log(
- `pid: ${pid}, profileId: ${profileId}, period: ${period}`,
+ `pid: ${pid}, profileId: ${profileId}`,
'GET /analytics/profile',
)
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
- let timeBucket
- let diff
-
- if (period === 'all') {
- const res = await this.analyticsService.calculateTimeBucketForAllTime(
- pid,
- 'pageview',
- )
- timeBucket = res.timeBucket[0]
- diff = res.diff
- } else {
- timeBucket = getLowestPossibleTimeBucket(period, from, to)
- }
-
- const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
- from,
- to,
- timeBucket,
- period,
- safeTimezone,
- diff,
- )
-
- const [details, topPages, activityCalendar, chart] = await Promise.all([
+ const [details, topPages, activityCalendar] = await Promise.all([
this.analyticsService.getProfileDetails(pid, profileId, safeTimezone),
this.analyticsService.getProfileTopPages(pid, profileId),
this.analyticsService.getProfileActivityCalendar(pid, profileId),
- this.analyticsService.getProfileChartData(
- pid,
- profileId,
- timeBucket,
- groupFromUTC,
- groupToUTC,
- safeTimezone,
- ),
])
return {
...details,
topPages,
activityCalendar,
- chart,
- timeBucket,
}
}
diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.ts
index 4095b3454..87bc2a261 100644
--- a/backend/apps/community/src/analytics/analytics.service.ts
+++ b/backend/apps/community/src/analytics/analytics.service.ts
@@ -6619,115 +6619,6 @@ export class AnalyticsService {
return data as { date: string; pageviews: number; events: number }[]
}
- async getProfileChartData(
- pid: string,
- profileId: string,
- timeBucket: string,
- from: string,
- to: string,
- safeTimezone: string,
- ): Promise<{
- x: string[]
- pageviews: number[]
- customEvents: number[]
- errors: number[]
- }> {
- const timeBucketFunc =
- timeBucketConversion[timeBucket] || timeBucketConversion.day
-
- const queryPageviews = `
- SELECT
- ${timeBucketFunc}(toTimeZone(created, {timezone:String})) AS time,
- count() AS count
- FROM events
- WHERE pid = {pid:FixedString(12)}
- AND type = 'pageview'
- AND profileId = {profileId:String}
- AND created BETWEEN {from:String} AND {to:String}
- GROUP BY time
- ORDER BY time ASC
- `
-
- const queryEvents = `
- SELECT
- ${timeBucketFunc}(toTimeZone(created, {timezone:String})) AS time,
- count() AS count
- FROM events
- WHERE pid = {pid:FixedString(12)}
- AND type = 'custom_event'
- AND profileId = {profileId:String}
- AND created BETWEEN {from:String} AND {to:String}
- GROUP BY time
- ORDER BY time ASC
- `
-
- const queryErrors = `
- SELECT
- ${timeBucketFunc}(toTimeZone(created, {timezone:String})) AS time,
- count() AS count
- FROM events
- WHERE pid = {pid:FixedString(12)}
- AND type = 'error'
- AND profileId = {profileId:String}
- AND created BETWEEN {from:String} AND {to:String}
- GROUP BY time
- ORDER BY time ASC
- `
-
- const params = { pid, profileId, from, to, timezone: safeTimezone }
-
- const [pageviewsResult, eventsResult, errorsResult] = await Promise.all([
- clickhouse
- .query({ query: queryPageviews, query_params: params })
- .then((resultSet) => resultSet.json()),
- clickhouse
- .query({ query: queryEvents, query_params: params })
- .then((resultSet) => resultSet.json()),
- clickhouse
- .query({ query: queryErrors, query_params: params })
- .then((resultSet) => resultSet.json()),
- ])
-
- // Merge all timestamps and create aligned data
- const allTimes = new Set<string>()
- const pageviewsMap = new Map<string, number>()
- const eventsMap = new Map<string, number>()
- const errorsMap = new Map<string, number>()
-
- for (const row of pageviewsResult.data as {
- time: string
- count: number
- }[]) {
- allTimes.add(row.time)
- pageviewsMap.set(row.time, Number(row.count))
- }
-
- for (const row of eventsResult.data as {
- time: string
- count: number
- }[]) {
- allTimes.add(row.time)
- eventsMap.set(row.time, Number(row.count))
- }
-
- for (const row of errorsResult.data as {
- time: string
- count: number
- }[]) {
- allTimes.add(row.time)
- errorsMap.set(row.time, Number(row.count))
- }
-
- const sortedTimes = Array.from(allTimes).sort()
-
- return {
- x: sortedTimes,
- pageviews: sortedTimes.map((t) => pageviewsMap.get(t) || 0),
- customEvents: sortedTimes.map((t) => eventsMap.get(t) || 0),
- errors: sortedTimes.map((t) => errorsMap.get(t) || 0),
- }
- }
-
private buildProfileSessionsEventsCTE(
filtersQuery: string,
customEVFilterApplied: boolean,
@@ -6767,6 +6658,96 @@ export class AnalyticsService {
)`
}
+ async getProfileSessionPageflows(
+ pid: string,
+ psids: string[],
+ safeTimezone: string,
+ ): Promise<Map<string, any[]>> {
+ if (_isEmpty(psids)) {
+ return new Map()
+ }
+
+ const query = `
+ WITH events_with_meta AS (
+ SELECT
+ multiIf(event_type = 'pageview', 'pageview', event_type = 'custom_event', 'event', 'error') AS type,
+ multiIf(
+ event_type = 'pageview', toString(pg),
+ event_type = 'custom_event', toString(event_name),
+ toString(error_name)
+ ) AS value,
+ created AS created_utc,
+ toTimeZone(created, {timezone:String}) AS created_local,
+ toString(psid) AS psid,
+ if(
+ event_type = 'error',
+ [
+ tuple('message', COALESCE(error_message, '')),
+ tuple('lineno', toString(COALESCE(lineno, 0))),
+ tuple('colno', toString(COALESCE(colno, 0))),
+ tuple('filename', COALESCE(error_filename, ''))
+ ],
+ arrayFilter(x -> x.1 != '' AND x.2 != '', arrayZip(meta_key, meta_value))
+ ) AS metadata
+ FROM (
+ SELECT
+ type AS event_type,
+ pg,
+ event_name,
+ error_name,
+ error_message,
+ lineno,
+ colno,
+ error_filename,
+ created,
+ psid,
+ meta.key AS meta_key,
+ meta.value AS meta_value
+ FROM events
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event', 'error')
+ AND psid IS NOT NULL
+ AND toString(psid) IN {psids:Array(String)}
+ )
+ )
+
+ SELECT
+ type,
+ value,
+ created_local AS created,
+ created_utc,
+ psid,
+ metadata
+ FROM events_with_meta
+ ORDER BY psid ASC, created_utc ASC
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { pid, psids, timezone: safeTimezone },
+ })
+ .then((resultSet) => resultSet.json<IPageflow>())
+
+ const pageflows = new Map<string, any[]>()
+ const processedPages = this.processPageflow(data as IPageflow[]) as any[]
+
+ for (const page of processedPages) {
+ const sessionId = page.psid ? String(page.psid) : null
+ if (!sessionId) {
+ continue
+ }
+
+ const { psid: _psid, ...pageData } = page
+ const existing = pageflows.get(sessionId) || []
+ existing.push(pageData)
+ pageflows.set(sessionId, existing)
+ }
+
+ return pageflows
+ }
+
async getProfileSessionsList(
pid: string,
profileId: string,
@@ -6883,6 +6864,16 @@ export class AnalyticsService {
})
.then((resultSet) => resultSet.json())
- return data as object[]
+ const sessions = data as any[]
+ const pageflows = await this.getProfileSessionPageflows(
+ pid,
+ sessions.map((session) => String(session.psid)).filter(Boolean),
+ safeTimezone,
+ )
+
+ return sessions.map((session) => ({
+ ...session,
+ pages: pageflows.get(String(session.psid)) || [],
+ }))
}
}
diff --git a/backend/apps/community/src/analytics/interfaces/index.ts b/backend/apps/community/src/analytics/interfaces/index.ts
index fdff59e5d..dca60debf 100644
--- a/backend/apps/community/src/analytics/interfaces/index.ts
+++ b/backend/apps/community/src/analytics/interfaces/index.ts
@@ -213,6 +213,7 @@ export interface IPageflow {
value: string
created: string
created_utc?: string
+ psid?: string
metadata?: [string, string][]
}
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 62c2cb1f7..ba70e9979 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -652,7 +652,9 @@ export async function getBlogPostWithCategory(
const result = await serverFetch<BlogPostContent>(
request,
`v1/blog/${category}/${slug}`,
- { skipAuth: true },
+ {
+ skipAuth: true,
+ },
)
if (result.error || !result.data) {
@@ -996,7 +998,9 @@ export async function getSessionsServer(
return serverFetch<SessionsResponse>(
request,
`log/sessions?${queryParams.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -1157,7 +1161,9 @@ export async function getSessionServer(
return serverFetch<SessionDetailsResponse>(
request,
`log/session?${queryParams.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -1261,7 +1267,9 @@ export async function getErrorServer(
return serverFetch<ErrorDetailsResponse>(
request,
`log/get-error?${queryParams.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -1626,7 +1634,9 @@ export async function getFunnelDataServer(
return serverFetch<FunnelDataResponse>(
request,
`log/funnel?${queryParams.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -1692,7 +1702,9 @@ export async function getCaptchaDataServer(
return serverFetch<CaptchaDataResponse>(
request,
`log/captcha?${queryParams.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -1876,38 +1888,36 @@ export async function getProfilesServer(
interface ProfileDetails {
profileId: string
- isAnonymous: boolean
- created: string
- pageviews: number
- sessions: number
- customEvents: number
- errors: number
- revenue?: number
- refunds?: number
- revenueCurrency?: string
+ isIdentified: boolean
+ sessionsCount: number
+ pageviewsCount: number
+ eventsCount: number
+ errorsCount: number
+ firstSeen: string
lastSeen: string
- country?: string
- city?: string
- region?: string
- locale?: string
- os?: string
- browser?: string
- device?: string
- properties?: Record<string, unknown>
- eventsInPeriod?: number
- sessionsInPeriod?: number
-}
-
-export interface ProfileDetailsResponse extends ProfileDetails {
- chart: unknown
- timeBucket: 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,
- period = '7d',
+ period = 'all',
from = '',
to = '',
timezone = '',
@@ -1929,7 +1939,9 @@ export async function getProfileServer(
return serverFetch<ProfileDetailsResponse>(
request,
`log/profile?${params.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -1945,9 +1957,13 @@ interface ProfileSession {
revenue?: number
refunds?: number
created: string
+ sessionStart?: string
+ lastActivity?: string
+ sdur?: number
duration?: number
active?: boolean
- isLive?: boolean
+ isLive?: 1 | 0 | boolean
+ pages?: PageflowItem[]
}
export interface ProfileSessionsResponse {
@@ -1958,7 +1974,7 @@ export async function getProfileSessionsServer(
request: Request,
pid: string,
profileId: string,
- period = '3d',
+ period = 'all',
filters: AnalyticsFilter[] = [],
from = '',
to = '',
@@ -2076,7 +2092,9 @@ export async function getCustomEventsMetadataServer(
return serverFetch<CustomEventsMetadataResponse>(
request,
`log/meta?${queryParams.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -2120,7 +2138,9 @@ export async function getPropertyMetadataServer(
return serverFetch<PropertyMetadataResponse>(
request,
`log/property?${queryParams.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -2261,7 +2281,9 @@ export async function getBotProtectionStatsServer(
return serverFetch<BotProtectionStats>(
request,
`log/bot-stats?pid=${pid}&period=${period}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -2484,7 +2506,9 @@ export async function getUserFlowServer(
return serverFetch<UserFlowResponse>(
request,
`log/user-flow?${queryParams.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -2621,7 +2645,9 @@ export async function getGSCKeywordsServer(
return serverFetch<GSCKeywordsResponse>(
request,
`log/keywords?${queryParams.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -2749,7 +2775,9 @@ export async function getGSCDashboardServer(
return serverFetch<GSCDashboardResponse>(
request,
`log/gsc-dashboard?${queryParams.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -2796,7 +2824,9 @@ export async function getGSCDetailsServer(
return serverFetch<GSCDetailsResponse>(
request,
`log/gsc-details?${queryParams.toString()}`,
- { headers },
+ {
+ headers,
+ },
)
}
@@ -2902,6 +2932,8 @@ export async function getIpLookupServer(
return serverFetch<IpLookupResponse>(
request,
`tools/ip-lookup?${queryParams.toString()}`,
- { skipAuth: true },
+ {
+ skipAuth: true,
+ },
)
}
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index 64195dfa5..1b3df89cb 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -152,13 +152,6 @@ export interface ProfileDetails extends Profile {
brv: string | null
topPages: { page: string; count: number }[]
activityCalendar: { date: string; pageviews: number; events: number }[]
- chart?: {
- x: string[]
- pageviews: number[]
- customEvents: number[]
- errors: number[]
- }
- timeBucket?: string
totalRevenue?: number
revenueCurrency?: string
}
diff --git a/web/app/pages/Project/View/Panels.tsx b/web/app/pages/Project/View/Panels.tsx
index e2118e684..34c00cbdf 100644
--- a/web/app/pages/Project/View/Panels.tsx
+++ b/web/app/pages/Project/View/Panels.tsx
@@ -60,6 +60,7 @@ import {
TooltipRoot,
TooltipTrigger,
TooltipContent,
+ tooltipContentClasses,
} from '~/ui/Tooltip'
import { nFormatter, getLocaleDisplayName } from '~/utils/generic'
import countries from '~/utils/isoCountries'
@@ -2443,7 +2444,7 @@ const Panel = ({
{rowTooltipRenderer && !rowTooltipFollowCursor ? (
<TooltipRoot>
<TooltipTrigger asChild>{rowBarEl}</TooltipTrigger>
- <TooltipContent className='max-w-xs rounded-md bg-gray-50 px-2 py-1 text-xs text-gray-900 shadow-md ring-1 ring-black/10 md:text-sm dark:bg-slate-900 dark:text-gray-50'>
+ <TooltipContent contentVariant='chart'>
{rowTooltipRenderer(entry)}
</TooltipContent>
</TooltipRoot>
@@ -2554,7 +2555,10 @@ const Panel = ({
typeof document !== 'undefined'
? createPortal(
<div
- className='pointer-events-none fixed z-50 max-w-xs rounded-md bg-gray-50 px-2 py-1 text-xs text-gray-900 shadow-md ring-1 ring-black/10 md:text-sm dark:bg-slate-900 dark:text-gray-50'
+ className={tooltipContentClasses({
+ contentVariant: 'chart',
+ className: 'pointer-events-none fixed',
+ })}
style={{
left: (() => {
const pad = 8
diff --git a/web/app/pages/Project/View/components/PasswordRequiredModal.tsx b/web/app/pages/Project/View/components/PasswordRequiredModal.tsx
index 28af03179..f9f1b0f2d 100644
--- a/web/app/pages/Project/View/components/PasswordRequiredModal.tsx
+++ b/web/app/pages/Project/View/components/PasswordRequiredModal.tsx
@@ -112,7 +112,6 @@ const PasswordRequiredModal = ({
variant='secondary'
className='border-indigo-100 dark:border-slate-700/50 dark:bg-slate-900 dark:text-gray-50 dark:hover:bg-slate-800'
as={Link}
- // @ts-expect-error
to={routes.main}
>
{t('common.cancel')}
diff --git a/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx b/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx
index 4a8ee45db..1ed2cc3bd 100644
--- a/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx
+++ b/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx
@@ -1,34 +1,35 @@
-import cx from 'clsx'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import _capitalize from 'lodash/capitalize'
import _isEmpty from 'lodash/isEmpty'
import {
+ ArrowSquareOutIcon,
+ CaretDownIcon,
ClockIcon,
- CalendarDotsIcon,
- FileTextIcon,
- MonitorIcon,
+ CurrencyDollarIcon,
+ CursorClickIcon,
DeviceMobileIcon,
DeviceTabletIcon,
+ FileTextIcon,
GlobeIcon,
- CurrencyDollarIcon,
+ MonitorIcon,
+ SignInIcon,
UserListIcon,
- CursorClickIcon,
+ WarningIcon,
} from '@phosphor-icons/react'
-import { useMemo } from 'react'
+import { useMemo, useState } from 'react'
+import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
-import {
- BROWSER_LOGO_MAP,
- OS_LOGO_MAP,
- OS_LOGO_MAP_DARK,
-} from '~/lib/constants'
-import {
- ProfileDetails as ProfileDetailsType,
- Session,
-} from '~/lib/models/Project'
+import { PROJECT_TABS } from '~/lib/constants'
+import { ProfileDetails as ProfileDetailsType } from '~/lib/models/Project'
+import { BackButton } from '~/pages/Project/View/components/BackButton'
+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
import Button from '~/ui/Button'
+import Flag from '~/ui/Flag'
+import PulsatingCircle from '~/ui/icons/PulsatingCircle'
import Loader from '~/ui/Loader'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
@@ -38,11 +39,11 @@ import {
getStringFromTime,
getTimeFromSeconds,
} from '~/utils/generic'
+import countries from '~/utils/isoCountries'
import { getProfileDisplayName, ProfileAvatar } from '~/utils/profileAvatars'
-import CCRow from '../../View/components/CCRow'
-import { SessionChart } from '../Sessions/SessionChart'
-import { Sessions } from '../Sessions/Sessions'
+import { BrowserIcon, OSIcon } from '../SharedIcons'
+import { Pageflow } from '../Sessions/Pageflow'
dayjs.extend(relativeTime)
@@ -51,6 +52,59 @@ const RECENTLY_ACTIVE_THRESHOLD_MINUTES = 30
type OnlineStatus = 'online' | 'recently_active' | 'offline'
+interface PageflowItem {
+ type: 'pageview' | 'event' | 'error' | 'sale' | 'refund'
+ value: string
+ created: string
+ metadata?: { key: string; value: string }[]
+ amount?: number
+ currency?: string
+}
+
+interface ProfileSession {
+ psid: string
+ cc: string | null
+ os: string | null
+ br: string | null
+ pageviews: number
+ customEvents: number
+ errors: number
+ revenue?: number
+ refunds?: number
+ created?: string
+ sessionStart?: string
+ lastActivity?: string
+ isLive?: 1 | 0 | boolean
+ sdur?: number
+ pages?: PageflowItem[]
+}
+
+interface ProfileDetailsProps {
+ details: ProfileDetailsType | null
+ sessions: ProfileSession[]
+ sessionsLoading: boolean | null
+ timeFormat: '12-hour' | '24-hour'
+ onLoadMoreSessions: () => void
+ canLoadMoreSessions: boolean
+ currency?: string
+ websiteUrl?: string | null
+ backLink?: string
+ backButtonLabel?: string
+}
+
+interface ActivityDay {
+ date: string
+ pageviews: number
+ events: number
+}
+
+interface PlatformPart {
+ key: string
+ label: string
+ tooltip: string
+ icon?: ReactNode
+}
+
const getOnlineStatus = (lastSeen: string | undefined): OnlineStatus => {
if (!lastSeen) return 'offline'
@@ -69,22 +123,105 @@ const getOnlineStatus = (lastSeen: string | undefined): OnlineStatus => {
return 'offline'
}
-interface ProfileDetailsProps {
- details: ProfileDetailsType | null
- sessions: Session[]
- sessionsLoading: boolean | null
- timeFormat: '12-hour' | '24-hour'
- onLoadMoreSessions: () => void
- canLoadMoreSessions: boolean
- currency?: string
+const formatDateTime = (
+ value: string | null | undefined,
+ language: string,
+ timeFormat: '12-hour' | '24-hour',
+ timezone: string,
+) => {
+ if (!value) return null
+
+ const date = dayjs(value)
+ if (!date.isValid()) return null
+
+ return date.toDate().toLocaleDateString(language, {
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric',
+ hour: 'numeric',
+ minute: 'numeric',
+ hourCycle: timeFormat === '12-hour' ? 'h12' : 'h23',
+ timeZone: timezone,
+ })
}
-interface ActivityDay {
- date: string
- pageviews: number
- events: number
+const formatVersionLabel = (name: string | null, version: string | null) => {
+ if (!name) return null
+ return `${name}${version ? ` ${version}` : ''}`
}
+const getSessionDuration = (session: ProfileSession) => {
+ if (session.sdur && session.sdur > 0) {
+ return session.sdur
+ }
+
+ const pages = session.pages || []
+ if (pages.length < 2) {
+ return 0
+ }
+
+ const first = dayjs(pages[0].created)
+ const last = dayjs(pages[pages.length - 1].created)
+ if (!first.isValid() || !last.isValid()) {
+ return 0
+ }
+
+ return Math.max(0, last.diff(first, 'second'))
+}
+
+const isSessionLive = (value: ProfileSession['isLive']) =>
+ value === true || value === 1
+
+const InfoRow = ({
+ label,
+ value,
+ valueClassName,
+}: {
+ label: string
+ value: ReactNode
+ valueClassName?: string
+}) => (
+ <div className='grid grid-cols-[minmax(0,1fr)_minmax(0,1.35fr)] items-center gap-3 border-b border-gray-100 py-1.5 last:border-0 dark:border-slate-800/80'>
+ <Text size='sm' colour='secondary' className='min-w-0'>
+ {label}
+ </Text>
+ <Text
+ as='div'
+ size='sm'
+ weight='medium'
+ colour='primary'
+ className={cn(
+ 'flex min-w-0 items-center justify-end gap-1 text-right wrap-break-word',
+ valueClassName,
+ )}
+ >
+ {value}
+ </Text>
+ </div>
+)
+
+const PanelSection = ({
+ title,
+ children,
+}: {
+ title: ReactNode
+ children: ReactNode
+}) => (
+ <section className='border-t border-gray-100 pt-3 first:border-t-0 first:pt-0 dark:border-slate-800/80'>
+ <Text
+ as='h3'
+ size='xs'
+ weight='semibold'
+ colour='primary'
+ className='mb-1.5 uppercase'
+ tracking='wide'
+ >
+ {title}
+ </Text>
+ {children}
+ </section>
+)
+
const ActivityCalendar = ({
data,
}: {
@@ -153,154 +290,330 @@ const ActivityCalendar = ({
const dayLabels = ['S', 'M', 'T', 'W', 'T', 'F', 'S']
const TooltipContent = ({ day }: { day: ActivityDay }) => (
- <ul className='min-w-[120px] text-xs'>
- <li className='mb-1 border-b border-gray-200 pb-1 font-semibold dark:border-slate-600'>
- {dayjs(day.date).format('MMM D, YYYY')}
- </li>
- <li className='flex items-center justify-between py-px leading-snug'>
- <div className='flex items-center'>
- <span>{t('dashboard.pageviews')}</span>
- </div>
- <span className='ml-4 font-mono'>{day.pageviews}</span>
- </li>
- <li className='flex items-center justify-between py-px leading-snug'>
- <div className='flex items-center'>
- <span>{t('dashboard.events')}</span>
- </div>
- <span className='ml-4 font-mono'>{day.events}</span>
- </li>
+ <ul className='min-w-[120px]'>
+ <Text
+ as='li'
+ size='xs'
+ weight='semibold'
+ colour='inherit'
+ className='mb-1 border-b border-gray-200 pb-1 dark:border-slate-800'
+ >
+ {dayjs(day.date).format('ddd, MMM D, YYYY')}
+ </Text>
+ <Text
+ as='li'
+ size='xs'
+ colour='inherit'
+ className='flex items-center justify-between py-px leading-snug'
+ >
+ <Text as='span' size='xs' colour='inherit'>
+ {t('dashboard.pageviews')}
+ </Text>
+ <Text as='span' size='xs' colour='inherit' className='ml-4 font-mono'>
+ {day.pageviews}
+ </Text>
+ </Text>
+ <Text
+ as='li'
+ size='xs'
+ colour='inherit'
+ className='flex items-center justify-between py-px leading-snug'
+ >
+ <Text as='span' size='xs' colour='inherit'>
+ {t('dashboard.events')}
+ </Text>
+ <Text as='span' size='xs' colour='inherit' className='ml-4 font-mono'>
+ {day.events}
+ </Text>
+ </Text>
</ul>
)
return (
- <div className='w-full'>
- <div className='mb-1 flex gap-[3px] pl-4'>
- {weeks.map((week, weekIdx) => {
- const monthLabel = monthLabels.find((m) => m.weekIndex === weekIdx)
- return (
- <div
- key={weekIdx}
- className='flex-1 text-[10px] leading-none text-gray-400 dark:text-gray-500'
- >
- {monthLabel?.month}
- </div>
- )
- })}
- </div>
- <div className='flex gap-[3px]'>
- <div className='flex w-3 shrink-0 flex-col gap-[3px] text-[9px] leading-none text-gray-400 dark:text-gray-500'>
- {dayLabels.map((d, i) => (
- <div
- key={i}
- className='flex aspect-square items-center justify-end'
- >
- {i % 2 === 1 ? d : ''}
- </div>
- ))}
- </div>
- <div className='flex flex-1 gap-[3px]'>
- {weeks.map((week, weekIdx) => (
- <div key={weekIdx} className='flex flex-1 flex-col gap-[3px]'>
- {week.map((day, dayIdx) => (
- <Tooltip
- key={dayIdx}
- text={<TooltipContent day={day} />}
- tooltipNode={
- <div
- className={cn(
- 'aspect-square w-full rounded-[2px] transition-opacity hover:opacity-80',
- getColor(day.pageviews, day.events),
- )}
- />
- }
- delay={100}
- disableHoverableContent
- />
- ))}
- </div>
- ))}
- </div>
- </div>
+ <div
+ className='grid w-full gap-[3px]'
+ style={{
+ gridTemplateColumns: `1rem repeat(${weeks.length}, minmax(0, 1fr))`,
+ }}
+ >
+ <div />
+ {weeks.map((week, weekIdx) => {
+ const monthLabel = monthLabels.find((m) => m.weekIndex === weekIdx)
+ return (
+ <Text
+ as='div'
+ size='xxs'
+ colour='muted'
+ key={weekIdx}
+ className='min-h-3 leading-none'
+ style={{
+ gridColumn: weekIdx + 2,
+ gridRow: 1,
+ }}
+ >
+ {monthLabel?.month}
+ </Text>
+ )
+ })}
+
+ {dayLabels.map((d, dayIdx) => (
+ <Text
+ as='div'
+ size='xxs'
+ colour='muted'
+ key={dayIdx}
+ className='flex h-full items-center justify-end pr-1 text-[9px] leading-none'
+ style={{
+ gridColumn: 1,
+ gridRow: dayIdx + 2,
+ }}
+ >
+ {dayIdx % 2 === 1 ? d : ''}
+ </Text>
+ ))}
+
+ {weeks.map((week, weekIdx) =>
+ week.map((day, dayIdx) => (
+ <Tooltip
+ asChild
+ key={`${weekIdx}-${day.date}`}
+ text={<TooltipContent day={day} />}
+ contentVariant='chart'
+ tooltipNode={
+ <div
+ className={cn(
+ 'aspect-square w-full rounded-[2px] transition-opacity hover:opacity-80',
+ getColor(day.pageviews, day.events),
+ )}
+ style={{
+ gridColumn: weekIdx + 2,
+ gridRow: dayIdx + 2,
+ }}
+ />
+ }
+ delay={0}
+ disableHoverableContent
+ />
+ )),
+ )}
</div>
)
}
-const StatItem = ({
+const DeviceIcon = ({ device }: { device: string | null }) => {
+ const deviceLower = device?.toLowerCase() || ''
+ if (deviceLower === 'mobile') return <DeviceMobileIcon className='h-4 w-4' />
+ if (deviceLower === 'tablet') return <DeviceTabletIcon className='h-4 w-4' />
+ return <MonitorIcon className='h-4 w-4' />
+}
+
+const SessionMetric = ({
icon,
label,
value,
+ colour = 'secondary',
}: {
- icon: React.ReactNode
+ icon: ReactNode
label: string
- value: string | number
+ value: number
+ colour?: 'secondary' | 'error'
}) => (
- <div>
- <Text
- size='xxs'
- weight='medium'
- colour='muted'
- className='mb-0.5 flex items-center gap-1.5 uppercase'
- >
- {icon}
- {label}
- </Text>
- <Text size='lg' weight='semibold' colour='primary'>
- {value}
- </Text>
- </div>
+ <Tooltip
+ text={label}
+ tooltipNode={
+ <Text
+ as='span'
+ size='xs'
+ colour={colour}
+ weight='medium'
+ className='flex items-center gap-1'
+ >
+ {icon}
+ {value}
+ </Text>
+ }
+ />
)
-const InfoRow = ({
- label,
- value,
+const ProfileSessionFlow = ({
+ session,
+ index,
+ timeFormat,
+ websiteUrl,
}: {
- label: string
- value: React.ReactNode
-}) => (
- <div className='flex items-start justify-between gap-3 border-b border-gray-100 py-2 last:border-0 dark:border-slate-700/50'>
- <Text size='sm' colour='muted' className='shrink-0'>
- {label}
- </Text>
- <Text
- size='sm'
- weight='medium'
- colour='primary'
- className='flex min-w-0 flex-wrap items-center justify-end gap-1 text-right'
- >
- {value}
- </Text>
- </div>
-)
-
-const DeviceIcon = ({ device }: { device: string | null }) => {
- const deviceLower = device?.toLowerCase() || ''
- if (deviceLower === 'mobile') return <DeviceMobileIcon className='h-4 w-4' />
- if (deviceLower === 'tablet') return <DeviceTabletIcon className='h-4 w-4' />
- return <MonitorIcon className='h-4 w-4' />
-}
-
-const BrowserIcon = ({ browser }: { browser: string | null }) => {
- if (!browser) return <GlobeIcon className='h-4 w-4' />
-
- const logoUrl = BROWSER_LOGO_MAP[browser as keyof typeof BROWSER_LOGO_MAP]
-
- if (!logoUrl) return <GlobeIcon className='h-4 w-4' />
-
- return <img src={logoUrl} className='h-4 w-4' alt='' />
-}
-
-const OSIcon = ({ os, theme }: { os: string | null; theme: string }) => {
- if (!os) return <GlobeIcon className='h-4 w-4' />
+ session: ProfileSession
+ index: number
+ timeFormat: '12-hour' | '24-hour'
+ websiteUrl?: string | null
+}) => {
+ const {
+ t,
+ i18n: { language },
+ } = useTranslation('common')
+ const { id: projectId } = useCurrentProject()
+ const { timezone } = useViewProjectContext()
+ const { theme } = useTheme()
+ const [isExpanded, setIsExpanded] = useState(index === 0)
- const logoUrlLight = OS_LOGO_MAP[os as keyof typeof OS_LOGO_MAP]
- const logoUrlDark = OS_LOGO_MAP_DARK[os as keyof typeof OS_LOGO_MAP_DARK]
+ const pages = session.pages || []
+ const startedAt = session.sessionStart || session.created || null
+ const duration = getSessionDuration(session)
+ const durationLabel = getStringFromTime(getTimeFromSeconds(duration))
+ const formattedStart =
+ formatDateTime(startedAt, language, timeFormat, timezone) || '-'
+ const sessionHref = `/projects/${projectId}?tab=${PROJECT_TABS.sessions}&psid=${encodeURIComponent(session.psid)}`
+ const live = isSessionLive(session.isLive)
+ const platformParts: PlatformPart[] = [
+ ...(session.os
+ ? [
+ {
+ key: 'os',
+ label: session.os,
+ tooltip: session.os,
+ icon: <OSIcon os={session.os} theme={theme} className='size-3.5' />,
+ },
+ ]
+ : []),
+ ...(session.br
+ ? [
+ {
+ key: 'browser',
+ label: session.br,
+ tooltip: session.br,
+ icon: <BrowserIcon browser={session.br} className='size-3.5' />,
+ },
+ ]
+ : []),
+ ]
- let logoUrl = theme === 'dark' ? logoUrlDark : logoUrlLight
- logoUrl ||= logoUrlLight
+ return (
+ <article className='border-t border-gray-100 first:border-t-0 dark:border-slate-800/80'>
+ <div className='flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between'>
+ <Button
+ variant='ghost'
+ size='sm'
+ aria-expanded={isExpanded}
+ onClick={() => setIsExpanded((value) => !value)}
+ className='min-w-0 flex-1 justify-start gap-2 px-0 py-0 text-left hover:bg-transparent dark:hover:bg-transparent dark:hover:text-gray-300'
+ >
+ <CaretDownIcon
+ className={cn(
+ 'size-4 shrink-0 text-gray-400 transition-transform duration-200 ease-out motion-reduce:transition-none dark:text-slate-500',
+ isExpanded && 'rotate-180',
+ )}
+ aria-hidden
+ />
+ <span className='min-w-0 flex-1'>
+ <span className='mb-0.5 flex min-w-0 flex-wrap items-center gap-1'>
+ <Text
+ as='span'
+ size='sm'
+ weight='semibold'
+ colour='primary'
+ truncate
+ className='min-w-0'
+ >
+ {formattedStart}
+ </Text>
+ <Text as='span' size='xs' colour='secondary' className='shrink-0'>
+ •
+ </Text>
+ <Text
+ as='span'
+ size='sm'
+ weight='medium'
+ colour='secondary'
+ className='shrink-0'
+ >
+ {durationLabel}
+ </Text>
+ {live ? (
+ <PulsatingCircle
+ className='relative ml-1 shrink-0'
+ type='small'
+ />
+ ) : null}
+ </span>
+ {platformParts.length > 0 ? (
+ <span className='mt-1 flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1'>
+ {platformParts.map(({ key, label, tooltip, icon }) => (
+ <Text
+ key={key}
+ as='span'
+ size='xs'
+ colour='secondary'
+ weight='medium'
+ title={tooltip}
+ className='inline-flex min-w-0 items-center gap-1'
+ >
+ <span className='flex size-3.5 shrink-0 items-center justify-center'>
+ {icon}
+ </span>
+ <span className='min-w-0 truncate'>{label}</span>
+ </Text>
+ ))}
+ </span>
+ ) : null}
+ </span>
+ </Button>
- if (!logoUrl) return <GlobeIcon className='h-4 w-4' />
+ <div className='flex shrink-0 flex-wrap items-center gap-3 pl-6 sm:pl-0'>
+ <SessionMetric
+ icon={<FileTextIcon className='size-3.5' />}
+ label={t('dashboard.pageviews')}
+ value={session.pageviews || 0}
+ />
+ <SessionMetric
+ icon={<CursorClickIcon className='size-3.5' />}
+ label={t('dashboard.events')}
+ value={session.customEvents || 0}
+ />
+ {session.errors > 0 ? (
+ <SessionMetric
+ icon={<WarningIcon className='size-3.5' />}
+ label={t('dashboard.errors')}
+ value={session.errors}
+ colour='error'
+ />
+ ) : null}
+ <Tooltip
+ asChild
+ text={t('project.viewSession')}
+ ariaLabel={t('project.viewSession')}
+ tooltipNode={
+ <Button
+ to={sessionHref}
+ variant='icon'
+ aria-label={t('project.viewSession')}
+ className='size-7 p-1.5'
+ >
+ <ArrowSquareOutIcon className='size-4' />
+ </Button>
+ }
+ disableHoverableContent
+ />
+ </div>
+ </div>
- return <img src={logoUrl} className='h-4 w-4' alt='' />
+ {isExpanded ? (
+ <div className='border-t border-gray-100 px-4 py-4 dark:border-slate-800/80'>
+ {_isEmpty(pages) ? (
+ <Text size='sm' colour='secondary' className='py-3 text-center'>
+ {t('project.noSessionDetails')}
+ </Text>
+ ) : (
+ <Pageflow
+ pages={pages}
+ timeFormat={timeFormat}
+ sdur={duration}
+ isLive={live}
+ websiteUrl={websiteUrl}
+ />
+ )}
+ </div>
+ ) : null}
+ </article>
+ )
}
export const ProfileDetails = ({
@@ -311,11 +624,15 @@ export const ProfileDetails = ({
onLoadMoreSessions,
canLoadMoreSessions,
currency,
+ websiteUrl,
+ backLink,
+ backButtonLabel,
}: ProfileDetailsProps) => {
const {
t,
i18n: { language },
} = useTranslation('common')
+ const { timezone } = useViewProjectContext()
const { theme } = useTheme()
const displayName = useMemo(() => {
@@ -333,259 +650,411 @@ export const ProfileDetails = ({
[details?.lastSeen],
)
- const formatDate = (date: string | undefined) => {
- if (!date) return '-'
- return dayjs(date).format('MMM D, YYYY')
- }
-
- const dataNames = useMemo(
- () => ({
- pageviews: t('dashboard.pageviews'),
- customEvents: t('dashboard.events'),
- errors: t('dashboard.errors'),
- }),
- [t],
- )
-
if (!details) return <Loader />
const avgDurationStr = details.avgDuration
? getStringFromTime(getTimeFromSeconds(details.avgDuration))
: '-'
+ const revenueCurrency = details.revenueCurrency || currency || 'USD'
+ const firstSeen =
+ formatDateTime(details.firstSeen, language, timeFormat, timezone) || '-'
+ const lastSeen =
+ formatDateTime(details.lastSeen, language, timeFormat, timezone) || '-'
+ const statusTooltip = details.lastSeen
+ ? t('project.lastSeenAgo', { time: lastSeenAgo })
+ : t('project.unknown')
+ const countryName = details.cc
+ ? countries.getName(details.cc, language) || details.cc
+ : null
+ const locationSummary =
+ [countryName, details.rg, details.ct].filter(Boolean).join(', ') ||
+ t('project.unknown')
+ const osTooltipLabel = formatVersionLabel(details.os, details.osv)
+ const browserTooltipLabel = formatVersionLabel(details.br, details.brv)
+ const profilePlatformParts: PlatformPart[] = [
+ ...(details.os
+ ? [
+ {
+ key: 'os',
+ label: details.os,
+ tooltip: osTooltipLabel || details.os,
+ icon: <OSIcon os={details.os} theme={theme} className='size-4' />,
+ },
+ ]
+ : []),
+ ...(details.br
+ ? [
+ {
+ key: 'browser',
+ label: details.br,
+ tooltip: browserTooltipLabel || details.br,
+ icon: <BrowserIcon browser={details.br} className='size-4' />,
+ },
+ ]
+ : []),
+ ]
+ const visibleProfilePlatformParts =
+ profilePlatformParts.length > 0
+ ? profilePlatformParts
+ : [
+ {
+ key: 'unknown',
+ label: t('project.unknown'),
+ tooltip: t('project.unknown'),
+ },
+ ]
+
+ const statusNode = (
+ <Tooltip
+ asChild
+ text={
+ <Text size='xs' colour='inherit'>
+ {statusTooltip}
+ </Text>
+ }
+ ariaLabel={statusTooltip}
+ tooltipNode={
+ <Text
+ as='button'
+ type='button'
+ colour='secondary'
+ className='inline-flex h-6 w-6 shrink-0 cursor-default items-center justify-center rounded-md bg-transparent p-0 transition-colors outline-none focus-visible:ring-2 focus-visible:ring-slate-900 dark:focus-visible:ring-slate-300'
+ >
+ <span
+ className={cn(
+ 'block rounded-full ring-2 ring-white dark:ring-slate-900',
+ onlineStatus === 'online' && 'h-2.5 w-2.5 bg-green-500',
+ onlineStatus === 'recently_active' && 'h-2.5 w-2.5 bg-yellow-500',
+ onlineStatus === 'offline' &&
+ 'h-2 w-2 border-2 border-gray-300 dark:border-slate-600',
+ )}
+ />
+ </Text>
+ }
+ disableHoverableContent
+ />
+ )
return (
- <div className='flex flex-col gap-3 lg:flex-row'>
- <div className='space-y-3 lg:w-[380px]'>
- <div className='rounded-lg border border-gray-200 bg-white p-5 dark:border-slate-800/60 dark:bg-slate-900/25'>
- <div className='flex items-center gap-4'>
- <div className='relative shrink-0'>
- <ProfileAvatar profileId={details.profileId} size={42} />
- {onlineStatus !== 'offline' && (
- <Tooltip
- text={t('project.lastSeenAgo', { time: lastSeenAgo })}
- className='absolute -right-0.5 -bottom-0.5'
- tooltipNode={
- <span
- className={cx(
- 'block h-3 w-3 rounded-full ring-2 ring-white dark:ring-slate-800',
- onlineStatus === 'online' && 'bg-green-500',
- onlineStatus === 'recently_active' && 'bg-yellow-500',
- )}
- />
- }
- />
- )}
- </div>
- <div className='flex flex-col gap-0.5'>
- <Text size='base' weight='bold' colour='primary'>
- {displayName}
- </Text>
- <Text size='xs' colour='muted' code>
- {details.profileId}
- </Text>
- </div>
- </div>
- <div className='mt-5 grid grid-cols-2 gap-x-4 gap-y-5'>
- <StatItem
- icon={<UserListIcon className='h-3.5 w-3.5' />}
- label={t('project.sessions')}
- value={details.sessionsCount || 0}
- />
- <StatItem
- icon={<FileTextIcon className='h-3.5 w-3.5' />}
- label={t('dashboard.pageviews')}
- value={details.pageviewsCount || 0}
- />
- <StatItem
- icon={<CursorClickIcon className='h-3.5 w-3.5' />}
- label={t('dashboard.events')}
- value={details.eventsCount || 0}
- />
- <StatItem
- icon={<ClockIcon className='h-3.5 w-3.5' />}
- label={t('project.avgDuration')}
- value={avgDurationStr}
- />
- <StatItem
- icon={<CalendarDotsIcon className='h-3.5 w-3.5' />}
- label={t('project.firstSeen')}
- value={formatDate(details.firstSeen)}
- />
- <StatItem
- icon={<CalendarDotsIcon className='h-3.5 w-3.5' />}
- label={t('project.lastSeen')}
- value={formatDate(details.lastSeen)}
- />
- {details.totalRevenue !== undefined && details.totalRevenue > 0 ? (
- <StatItem
- icon={
- <CurrencyDollarIcon className='h-3.5 w-3.5 text-emerald-500' />
- }
- label={t('dashboard.revenue')}
- value={new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: details.revenueCurrency || 'USD',
- minimumFractionDigits: 2,
- }).format(details.totalRevenue)}
- />
- ) : null}
- </div>
+ <div className='grid gap-x-3 gap-y-2 lg:grid-cols-[minmax(0,1fr)_360px] lg:items-start xl:grid-cols-[minmax(0,1fr)_390px]'>
+ {backLink ? (
+ <div className='order-1 lg:hidden'>
+ <BackButton to={backLink} label={backButtonLabel} className='w-fit' />
</div>
+ ) : null}
- <div className='rounded-lg border border-gray-200 bg-white p-5 dark:border-slate-800/60 dark:bg-slate-900/25'>
- <Text
- as='h3'
- size='xs'
- weight='semibold'
- colour='primary'
- className='mb-3 uppercase'
- tracking='wide'
- >
- {t('project.locationAndDevice')}
- </Text>
- <div>
- <InfoRow
- label={t('project.mapping.cc')}
- value={
- details.cc ? (
- <CCRow size={16} cc={details.cc} language={language} />
- ) : (
- '-'
- )
- }
- />
- {details.rg ? (
- <InfoRow label={t('project.mapping.rg')} value={details.rg} />
- ) : null}
- <InfoRow
- label={t('project.mapping.lc')}
- value={
- details.lc ? getLocaleDisplayName(details.lc, language) : '-'
- }
- />
- <InfoRow
- label={t('project.mapping.dv')}
- value={
- details.dv ? (
- <>
- <DeviceIcon device={details.dv} />
- {_capitalize(details.dv)}
- </>
- ) : (
- '-'
- )
- }
- />
- <InfoRow
- label={t('project.mapping.br')}
- value={
- details.br ? (
- <>
- <BrowserIcon browser={details.br} />
- {details.br}
- {details.brv ? ` v${details.brv}` : ''}
- </>
- ) : (
- '-'
- )
- }
- />
- <InfoRow
- label={t('project.mapping.os')}
- value={
- details.os ? (
- <>
- <OSIcon os={details.os} theme={theme} />
- {details.os}
- {details.osv ? ` v${details.osv}` : ''}
- </>
- ) : (
- '-'
- )
- }
+ <div className='order-3 min-w-0 space-y-2 lg:order-1'>
+ {backLink ? (
+ <div className='hidden lg:block'>
+ <BackButton
+ to={backLink}
+ label={backButtonLabel}
+ className='w-fit'
/>
</div>
- </div>
-
- <div className='rounded-lg border border-gray-200 bg-white p-5 dark:border-slate-800/60 dark:bg-slate-900/25'>
- <Text
- as='h3'
- size='xs'
- weight='semibold'
- colour='primary'
- className='mb-3 uppercase'
- tracking='wide'
- >
- {t('project.activityCalendar')}
- </Text>
- <ActivityCalendar data={details.activityCalendar || []} />
- </div>
- </div>
-
- <div className='flex-1 space-y-3'>
- {details.chart && !_isEmpty(details.chart.x) ? (
- <div className='rounded-lg border border-gray-200 bg-white p-5 dark:border-slate-800/60 dark:bg-slate-900/25'>
+ ) : null}
+ <section className='min-w-0 rounded-lg border border-gray-200 bg-white py-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
+ <div className='mb-3 flex items-center justify-between gap-3 px-4'>
<Text
as='h3'
size='xs'
weight='semibold'
- colour='primary'
- className='mb-3 uppercase'
tracking='wide'
+ className='uppercase'
>
- {t('dashboard.pageviews')}
+ {t('project.userSessions')}
</Text>
- <SessionChart
- chart={details.chart}
- timeBucket={details.timeBucket}
- timeFormat={timeFormat}
- rotateXAxis={false}
- dataNames={dataNames}
- className='h-[300px] [&_svg]:overflow-visible!'
- />
+ {sessionsLoading && !_isEmpty(sessions) ? (
+ <Text size='xs' colour='secondary'>
+ {t('common.loading')}
+ </Text>
+ ) : null}
</div>
- ) : null}
- <div className='rounded-lg border border-gray-200 bg-white p-5 dark:border-slate-800/60 dark:bg-slate-900/25'>
- <Text
- as='h3'
- size='xs'
- weight='semibold'
- colour='primary'
- className='mb-3 uppercase'
- tracking='wide'
- >
- {t('project.userSessions')}
- </Text>
{sessionsLoading && sessions.length === 0 ? (
- <Loader />
+ <div className='py-8'>
+ <Loader />
+ </div>
) : sessions.length === 0 ? (
- <Text size='sm' colour='muted' className='py-4 text-center'>
+ <Text
+ size='sm'
+ colour='secondary'
+ className='px-4 py-4 text-center'
+ >
{t('project.noSessions')}
</Text>
) : (
<>
- <Sessions
- sessions={sessions}
- timeFormat={timeFormat}
- hideNewReturnBadge
- hideUserDetails
- currency={currency}
- />
+ <div>
+ {sessions.map((session, index) => (
+ <ProfileSessionFlow
+ key={session.psid}
+ session={session}
+ index={index}
+ timeFormat={timeFormat}
+ websiteUrl={websiteUrl}
+ />
+ ))}
+ </div>
{canLoadMoreSessions ? (
- <Button
- onClick={onLoadMoreSessions}
- disabled={!!sessionsLoading}
- loading={!!sessionsLoading}
- className='mt-4 w-full'
- >
- {t('project.loadMore')}
- </Button>
+ <div className='px-4 pt-4'>
+ <Button
+ onClick={onLoadMoreSessions}
+ disabled={!!sessionsLoading}
+ loading={!!sessionsLoading}
+ className='w-full'
+ >
+ {t('project.loadMore')}
+ </Button>
+ </div>
) : null}
</>
)}
- </div>
+ </section>
</div>
+
+ <aside className='order-2 mb-1 lg:sticky lg:top-14 lg:mb-0 lg:self-start'>
+ <div className='space-y-3 rounded-lg border border-gray-200 bg-white px-4 py-4 lg:min-h-[calc(100dvh-3.5rem)] dark:border-slate-800/60 dark:bg-slate-900/25'>
+ <div className='pb-1'>
+ <div className='flex items-start gap-3'>
+ <div className='relative mt-2 shrink-0'>
+ <ProfileAvatar profileId={details.profileId} size={42} />
+ </div>
+ <div className='min-w-0 flex-1'>
+ <div className='mb-0.5 flex min-w-0 items-center gap-2'>
+ <Text
+ as='h2'
+ size='lg'
+ weight='bold'
+ colour='primary'
+ truncate
+ className='min-w-0'
+ >
+ {displayName}
+ </Text>
+ {statusNode}
+ </div>
+ <Text
+ size='xs'
+ colour='secondary'
+ code
+ truncate
+ className='block min-w-0'
+ >
+ {details.profileId}
+ </Text>
+
+ <div className='mt-2 space-y-1'>
+ <div className='flex items-center gap-1'>
+ <Text
+ as='span'
+ colour='primary'
+ className='flex h-6 items-center justify-center'
+ >
+ {details.cc ? (
+ <Flag
+ className='rounded-xs'
+ country={details.cc}
+ size={16}
+ alt=''
+ aria-hidden='true'
+ />
+ ) : (
+ <GlobeIcon className='size-4' />
+ )}
+ </Text>
+ <Text
+ as='span'
+ size='sm'
+ weight='medium'
+ colour='primary'
+ truncate
+ title={locationSummary}
+ >
+ {locationSummary}
+ </Text>
+ </div>
+
+ <div className='flex min-h-6 min-w-0 items-center'>
+ {visibleProfilePlatformParts.map(
+ ({ key, label, tooltip, icon }, index) => (
+ <span
+ key={key}
+ className='flex min-w-0 items-center gap-1'
+ >
+ {index > 0 ? (
+ <Text
+ as='span'
+ size='sm'
+ weight='medium'
+ colour='primary'
+ className='shrink-0'
+ >
+ ,
+ </Text>
+ ) : null}
+ {icon ? (
+ <Tooltip
+ asChild
+ text={
+ <Text size='xs' colour='inherit'>
+ {tooltip}
+ </Text>
+ }
+ ariaLabel={tooltip}
+ tooltipNode={
+ <Text
+ as='button'
+ type='button'
+ size='sm'
+ weight='medium'
+ colour='primary'
+ truncate
+ className='inline-flex max-w-full min-w-0 cursor-default items-center gap-1 rounded-sm bg-transparent p-0 outline-none focus-visible:ring-2 focus-visible:ring-slate-900 dark:focus-visible:ring-slate-300'
+ >
+ <span className='flex size-4 shrink-0 items-center justify-center'>
+ {icon}
+ </span>
+ <span className='min-w-0 truncate'>
+ {label}
+ </span>
+ </Text>
+ }
+ disableHoverableContent
+ />
+ ) : (
+ <Text
+ as='span'
+ size='sm'
+ weight='medium'
+ colour='primary'
+ truncate
+ >
+ {label}
+ </Text>
+ )}
+ </span>
+ ),
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <PanelSection title={t('common.details')}>
+ <div>
+ <InfoRow
+ label={t('project.firstSeen')}
+ value={
+ <>
+ <SignInIcon className='h-4 w-4' />
+ {firstSeen}
+ </>
+ }
+ />
+ <InfoRow
+ label={t('project.lastSeen')}
+ value={
+ <>
+ <SignInIcon className='h-4 w-4 rotate-180' />
+ {lastSeen}
+ </>
+ }
+ />
+ <InfoRow
+ label={t('project.avgDuration')}
+ value={
+ <>
+ <ClockIcon className='h-4 w-4' />
+ {avgDurationStr}
+ </>
+ }
+ />
+ <InfoRow
+ label={t('project.sessions')}
+ value={
+ <>
+ <UserListIcon className='h-4 w-4' />
+ {details.sessionsCount || 0}
+ </>
+ }
+ />
+ <InfoRow
+ label={t('dashboard.pageviews')}
+ value={
+ <>
+ <FileTextIcon className='h-4 w-4' />
+ {details.pageviewsCount || 0}
+ </>
+ }
+ />
+ <InfoRow
+ label={t('dashboard.events')}
+ value={
+ <>
+ <CursorClickIcon className='h-4 w-4' />
+ {details.eventsCount || 0}
+ </>
+ }
+ />
+ <InfoRow
+ label={t('dashboard.errors')}
+ value={
+ <>
+ <WarningIcon className='h-4 w-4 text-red-500' />
+ {details.errorsCount || 0}
+ </>
+ }
+ />
+ {details.totalRevenue !== undefined &&
+ details.totalRevenue > 0 ? (
+ <InfoRow
+ label={t('dashboard.revenue')}
+ value={
+ <>
+ <CurrencyDollarIcon className='h-4 w-4 text-emerald-500' />
+ {new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: revenueCurrency,
+ minimumFractionDigits: 2,
+ }).format(details.totalRevenue)}
+ </>
+ }
+ />
+ ) : null}
+ </div>
+ </PanelSection>
+
+ <PanelSection title={t('project.locationAndDevice')}>
+ <div>
+ <InfoRow
+ label={t('project.mapping.lc')}
+ value={
+ details.lc ? getLocaleDisplayName(details.lc, language) : '-'
+ }
+ />
+ <InfoRow
+ label={t('project.mapping.dv')}
+ value={
+ details.dv ? (
+ <>
+ <DeviceIcon device={details.dv} />
+ {_capitalize(details.dv)}
+ </>
+ ) : (
+ '-'
+ )
+ }
+ />
+ </div>
+ </PanelSection>
+
+ <PanelSection title={t('project.activityCalendar')}>
+ <ActivityCalendar data={details.activityCalendar || []} />
+ </PanelSection>
+ </div>
+ </aside>
</div>
)
}
diff --git a/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx b/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
index 5fb203404..bfa06bb44 100644
--- a/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
+++ b/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
@@ -68,7 +68,6 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
const profileProxy = useProfileProxy()
const profileSessionsProxy = useProfileSessionsProxy()
- // Profiles state
const [profilesSkip, setProfilesSkip] = useState(0)
const [canLoadMoreProfiles, setCanLoadMoreProfiles] = useState(false)
const [profiles, setProfiles] = useState<Profile[]>([])
@@ -99,7 +98,6 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
const skipNextProfilesAutoLoadRef = useRef(false)
const isMountedRef = useRef(true)
- // Cleanup on unmount
useEffect(() => {
isMountedRef.current = true
return () => {
@@ -179,8 +177,6 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
!!activeProfile && activeProfile.profileId === profileId
setProfileLoading(true)
- // Avoid flicker on refresh: keep currently displayed details/sessions while we refetch.
- // Only reset sessions when opening a different profile (or first load).
if (!hasExistingProfileData) {
setProfileSessions([])
setProfileSessionsSkip(0)
@@ -188,18 +184,8 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
}
try {
- let from = ''
- let to = ''
-
- if (period === 'custom' && dateRange) {
- from = getFormatDate(dateRange[0])
- to = getFormatDate(dateRange[1])
- }
-
const data = await profileProxy.fetchProfile(id, profileId, {
- period: period === 'custom' && dateRange ? '' : period,
- from,
- to,
+ period: 'all',
timezone,
})
@@ -209,7 +195,6 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
data
) {
setActiveProfile(data as unknown as ProfileDetailsType)
- // Load initial sessions for the profile (override existing on refresh)
loadProfileSessionsData(profileId, 0, true)
}
} catch (reason) {
@@ -239,22 +224,13 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
try {
const skip =
typeof forcedSkip === 'number' ? forcedSkip : profileSessionsSkip
- let from = ''
- let to = ''
-
- if (period === 'custom' && dateRange) {
- from = getFormatDate(dateRange[0])
- to = getFormatDate(dateRange[1])
- }
const dataSessions = await profileSessionsProxy.fetchProfileSessions(
id,
profileId,
{
- period: period === 'custom' && dateRange ? '' : period,
- filters,
- from,
- to,
+ period: 'all',
+ filters: [],
take: SESSIONS_TAKE,
skip,
timezone,
@@ -303,7 +279,6 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
}
}
- // Load profiles list when component mounts or dependencies change
useEffect(() => {
if (!project || activeProfileId) {
return
@@ -314,7 +289,6 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
return
}
- // Reset pagination and load the first page whenever the query context changes
setProfilesSkip(0)
loadProfiles(0, true)
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -330,7 +304,6 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
profileTypeFilter,
])
- // Reload active profile when query context changes (period, date range, filters, etc.)
useEffect(() => {
if (!activeProfileId || !project) {
return
@@ -338,24 +311,13 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
loadProfile(activeProfileId)
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [
- activeProfileId,
- project,
- period,
- dateRange,
- timezone,
- filters,
- projectPassword,
- id,
- ])
+ }, [activeProfileId, project, timezone, projectPassword, id])
- // Reset profiles when navigating away from profile detail
useEffect(() => {
const prevProfileId = prevActiveProfileIdRef.current
prevActiveProfileIdRef.current = activeProfileId
if (prevProfileId && !activeProfileId) {
- // We just closed a profile detail, reset to first page
setProfilesSkip(0)
skipNextProfilesAutoLoadRef.current = true
loadProfiles(0, true)
@@ -363,7 +325,6 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeProfileId])
- // Handle refresh trigger from parent
useEffect(() => {
if (profilesRefreshTrigger > 0) {
if (activeProfileId) {
@@ -376,7 +337,6 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [profilesRefreshTrigger])
- // Profile detail view
if (activeProfileId) {
const backSearchParams = (() => {
const params = new URLSearchParams(searchParams)
@@ -385,12 +345,7 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
})()
return (
- <>
- <DashboardHeader
- backLink={`?${backSearchParams}`}
- backButtonLabel={t('project.backToUsers')}
- showLiveVisitors={false}
- />
+ <div>
{profileLoading && !activeProfile ? (
<LoaderView />
) : (
@@ -406,13 +361,15 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
}}
canLoadMoreSessions={canLoadMoreProfileSessions}
currency={project?.revenueCurrency}
+ websiteUrl={project?.websiteUrl}
+ backLink={`?${backSearchParams}`}
+ backButtonLabel={t('project.backToUsers')}
/>
)}
- </>
+ </div>
)
}
- // Profiles list view
return (
<>
<DashboardHeader
diff --git a/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx b/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx
index 19542dfed..78a1a82ce 100644
--- a/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx
+++ b/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx
@@ -559,7 +559,7 @@ export const SessionDetailView = ({
aria-hidden='true'
/>
) : (
- <GlobeIcon className='h-5 w-5' />
+ <GlobeIcon className='size-4' />
)}
</Text>
<Text
diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.ts
index d0195e6a2..d1e1250fd 100644
--- a/web/app/routes/api.analytics.ts
+++ b/web/app/routes/api.analytics.ts
@@ -540,7 +540,7 @@ export async function action({ request }: ActionFunctionArgs) {
request,
projectId,
body.profileId,
- params.period || '7d',
+ params.period || 'all',
formatDateForBackend(params.from) || '',
formatDateForBackend(params.to) || '',
params.timezone || '',
@@ -567,7 +567,7 @@ export async function action({ request }: ActionFunctionArgs) {
request,
projectId,
body.profileId,
- params.period || '3d',
+ params.period || 'all',
params.filters || [],
formatDateForBackend(params.from) || '',
formatDateForBackend(params.to) || '',
diff --git a/web/app/ui/Button.tsx b/web/app/ui/Button.tsx
index 07d533af3..57e6c9f83 100644
--- a/web/app/ui/Button.tsx
+++ b/web/app/ui/Button.tsx
@@ -1,9 +1,11 @@
import { Button as HeadlessButton } from '@headlessui/react'
-import React, { memo } from 'react'
+import React, { forwardRef, memo } from 'react'
+import type { LinkProps } from 'react-router'
import { cn } from '~/utils/generic'
import Spin from './icons/Spin'
+import { Link } from './Link'
/**
* Visual style of the button.
@@ -28,7 +30,7 @@ type ButtonVariant =
| 'icon'
/**
- * Padding + text scale.
+ * Padding.
*
* - `xs` — `px-2.5 py-1.5 text-xs` (smallest)
* - `sm` — `px-2.5 py-1.5 text-sm`
@@ -47,6 +49,8 @@ interface ButtonProps extends Omit<
variant?: ButtonVariant
size?: ButtonSize
loading?: boolean
+ to?: LinkProps['to']
+ linkProps?: Omit<LinkProps, 'to' | 'children' | 'className'>
/**
* Whether to render a focus ring on keyboard focus. Defaults to `true`.
* Set to `false` for compact toolbar buttons embedded in a list where the ring would be visual noise.
@@ -106,36 +110,74 @@ export const buttonClasses = ({
return cn(
'relative inline-flex items-center rounded-md border leading-4 font-medium select-none',
'transition-[background-color,color,box-shadow,transform] duration-150 ease-out',
- 'active:scale-[0.985] active:duration-75',
focus &&
'focus-visible:ring-2 focus-visible:ring-slate-900 focus-visible:ring-offset-2 focus-visible:outline-hidden dark:focus-visible:ring-slate-300 dark:focus-visible:ring-offset-slate-950',
- 'disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 disabled:active:scale-100',
+ 'disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50',
BUTTON_VARIANT_CLASSES[variant],
!isIcon && BUTTON_SIZE_CLASSES[size],
className,
)
}
-const Button = ({
- variant = 'primary',
- size = 'md',
- type = 'button',
- className,
- loading,
- disabled,
- focus = true,
- children,
- ...props
-}: ButtonProps) => (
- <HeadlessButton
- {...props}
- disabled={disabled || loading}
- type={type}
- className={buttonClasses({ variant, size, focus, className })}
- >
- {loading ? <Spin inherit /> : null}
- {children}
- </HeadlessButton>
+const Button = forwardRef<HTMLButtonElement | HTMLAnchorElement, ButtonProps>(
+ (
+ {
+ variant = 'primary',
+ size = 'md',
+ type = 'button',
+ className,
+ loading,
+ disabled,
+ focus = true,
+ children,
+ to,
+ linkProps,
+ ...props
+ },
+ ref,
+ ) => {
+ const isDisabled = disabled || loading
+ const classes = buttonClasses({ variant, size, focus, className })
+
+ if (to) {
+ const anchorProps = props as React.AnchorHTMLAttributes<HTMLAnchorElement>
+
+ return (
+ <Link
+ {...linkProps}
+ {...anchorProps}
+ ref={ref as React.Ref<HTMLAnchorElement>}
+ to={to}
+ aria-disabled={isDisabled || undefined}
+ tabIndex={
+ isDisabled ? -1 : (linkProps?.tabIndex ?? anchorProps.tabIndex)
+ }
+ className={cn(
+ classes,
+ isDisabled && 'pointer-events-none cursor-not-allowed opacity-50',
+ )}
+ >
+ {loading ? <Spin inherit /> : null}
+ {children}
+ </Link>
+ )
+ }
+
+ return (
+ <HeadlessButton
+ {...props}
+ ref={ref as React.Ref<HTMLButtonElement>}
+ disabled={isDisabled}
+ type={type}
+ className={classes}
+ >
+ {loading ? <Spin inherit /> : null}
+ {children}
+ </HeadlessButton>
+ )
+ },
)
+Button.displayName = 'Button'
+
export default memo(Button)
diff --git a/web/app/ui/Tooltip.tsx b/web/app/ui/Tooltip.tsx
index 9e3812240..f90fb87ec 100644
--- a/web/app/ui/Tooltip.tsx
+++ b/web/app/ui/Tooltip.tsx
@@ -11,9 +11,37 @@ const TooltipRoot = TooltipPrimitive.Root
const TooltipTrigger = TooltipPrimitive.Trigger
+type TooltipContentVariant = 'default' | 'chart'
+
+const TOOLTIP_CONTENT_VARIANT_CLASSES: Record<TooltipContentVariant, string> = {
+ default:
+ 'max-w-80 bg-slate-900 px-2.5 py-1.5 text-xs leading-relaxed font-medium text-slate-50 shadow-lg ring-1 ring-white/10 dark:bg-slate-800 dark:ring-white/5',
+ chart:
+ 'max-w-xs bg-gray-50 px-2 py-1 text-xs leading-relaxed text-gray-900 shadow-md ring-1 ring-black/10 md:text-sm dark:bg-slate-900 dark:text-gray-50',
+}
+
+const TOOLTIP_ARROW_VARIANT_CLASSES: Record<TooltipContentVariant, string> = {
+ default: 'fill-slate-900 dark:fill-slate-800',
+ chart: 'fill-gray-50 dark:fill-slate-900',
+}
+
+export const tooltipContentClasses = ({
+ contentVariant = 'default',
+ className,
+}: {
+ contentVariant?: TooltipContentVariant
+ className?: string
+} = {}) =>
+ cn(
+ 'tooltip-content z-50 origin-(--radix-tooltip-content-transform-origin) overflow-hidden rounded-md',
+ TOOLTIP_CONTENT_VARIANT_CLASSES[contentVariant],
+ className,
+ )
+
interface TooltipContentExtraProps {
withArrow?: boolean
arrowClassName?: string
+ contentVariant?: TooltipContentVariant
}
const TooltipContent = forwardRef<
@@ -27,6 +55,7 @@ const TooltipContent = forwardRef<
sideOffset = 6,
withArrow = true,
arrowClassName,
+ contentVariant = 'default',
children,
...props
},
@@ -37,16 +66,16 @@ const TooltipContent = forwardRef<
ref={ref}
forceMount
sideOffset={sideOffset}
- className={cn(
- 'tooltip-content z-50 max-w-80 origin-(--radix-tooltip-content-transform-origin) overflow-hidden rounded-md bg-slate-900 px-2.5 py-1.5 text-xs leading-relaxed font-medium text-slate-50 shadow-lg ring-1 ring-white/10 dark:bg-slate-800 dark:ring-white/5',
- className,
- )}
+ className={tooltipContentClasses({ contentVariant, className })}
{...props}
>
{children}
{withArrow ? (
<TooltipPrimitive.Arrow
- className={cn('fill-slate-900 dark:fill-slate-800', arrowClassName)}
+ className={cn(
+ TOOLTIP_ARROW_VARIANT_CLASSES[contentVariant],
+ arrowClassName,
+ )}
width={10}
height={5}
/>
@@ -62,6 +91,7 @@ interface TooltipProps {
className?: string
contentClassName?: string
arrowClassName?: string
+ contentVariant?: TooltipContentVariant
tooltipNode?: React.ReactNode
ariaLabel?: string
asChild?: boolean
@@ -81,6 +111,7 @@ const Tooltip = ({
asChild,
contentClassName,
arrowClassName,
+ contentVariant = 'default',
delay = 50,
disableHoverableContent,
}: TooltipProps) => {
@@ -103,6 +134,7 @@ const Tooltip = ({
)}
</TooltipTrigger>
<TooltipContent
+ contentVariant={contentVariant}
className={cn(
contentClassName,
disableHoverableContent && 'pointer-events-none',