📈 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
separate sessions tab
Blue Mouse3cce7dca8fd9
diff --git a/web/app/pages/Project/Sessions/View/SessionsView.tsx b/web/app/pages/Project/Sessions/View/SessionsView.tsxnew file mode 100644index 000000000..2c7ca6ff0--- /dev/null+++ b/web/app/pages/Project/Sessions/View/SessionsView.tsx@@ -0,0 +1,347 @@+import { XCircleIcon } from '@heroicons/react/24/outline'+import cx from 'clsx'+import _isEmpty from 'lodash/isEmpty'+import { ChevronLeftIcon, DownloadIcon } from 'lucide-react'+import { useState, useEffect, useMemo, useRef } from 'react'+import { useTranslation } from 'react-i18next'+import { Link, useSearchParams } from 'react-router'++import { getSessions, getSession } from '~/api'+import { Session, SessionDetails as SessionDetailsType } from '~/lib/models/Project'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'+import Filters from '~/pages/Project/View/components/Filters'+import NoEvents from '~/pages/Project/View/components/NoEvents'+import { RefreshStatsButton } from '~/pages/Project/View/components/RefreshStatsButton'+import { SessionDetailView } from '~/pages/Project/View/components/SessionDetailView'+import { Sessions } from '~/pages/Project/View/components/Sessions'+import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'+import { useCurrentProject } from '~/providers/CurrentProjectProvider'+import { useProjectPassword } from '~/providers/CurrentProjectProvider'+import Loader from '~/ui/Loader'+import Spin from '~/ui/icons/Spin'+import routes from '~/utils/routes'++const SESSIONS_TAKE = 30++interface PageflowItem {+ type: 'pageview' | 'event' | 'error'+ value: string+ created: string+ metadata?: { key: string; value: string }[]+}++interface ActiveSession {+ details: SessionDetailsType+ chart?: {+ x: string[]+ pageviews?: number[]+ customEvents?: number[]+ errors?: number[]+ }+ pages?: PageflowItem[]+ timeBucket?: string+}++interface SessionsViewProps {+ tnMapping: Record<string, string>+ chartType: string+ rotateXAxis: boolean+}++const SessionsView = ({ tnMapping, chartType, rotateXAxis }: SessionsViewProps) => {+ const { id, project } = useCurrentProject()+ const projectPassword = useProjectPassword(id)+ const { sessionsRefreshTrigger, timezone, period, dateRange, filters, timeFormat } = useViewProjectContext()+ const { t } = useTranslation('common')+ const [searchParams] = useSearchParams()++ // Session list state+ const [sessions, setSessions] = useState<Session[]>([])+ const [sessionsLoading, setSessionsLoading] = useState<boolean | null>(null)+ const [sessionsSkip, setSessionsSkip] = useState(0)+ const [canLoadMoreSessions, setCanLoadMoreSessions] = useState(false)+ const sessionsRequestIdRef = useRef(0)++ // Session detail state+ const [activeSession, setActiveSession] = useState<ActiveSession | null>(null)+ const [sessionLoading, setSessionLoading] = useState(false)++ const [error, setError] = useState<string | null>(null)++ const isMountedRef = useRef(true)+ const prevActivePSIDRef = useRef<string | null>(null)+ const skipNextSessionsAutoLoadRef = useRef(false)++ const activePSID = useMemo(() => {+ return searchParams.get('psid')+ }, [searchParams])++ // Search params without the session id. Needed for the back button.+ const pureSearchParams = useMemo(() => {+ const newSearchParams = new URLSearchParams(searchParams.toString())+ newSearchParams.delete('psid')+ return newSearchParams.toString()+ }, [searchParams])++ const dataNames = useMemo(+ () => ({+ pageviews: t('dashboard.pageviews'),+ customEvents: t('dashboard.events'),+ errors: t('dashboard.errors'),+ }),+ [t],+ )++ // Cleanup on unmount+ useEffect(() => {+ isMountedRef.current = true+ return () => {+ isMountedRef.current = false+ }+ }, [])++ // Reset sessions when filters change+ useEffect(() => {+ sessionsRequestIdRef.current += 1+ setSessionsSkip(0)+ setSessions([])+ setSessionsLoading(null)+ }, [filters])++ const loadSessions = async (forcedSkip?: number, override?: boolean) => {+ if (sessionsLoading) {+ return+ }++ const requestId = sessionsRequestIdRef.current+ setSessionsLoading(true)++ try {+ const skip = typeof forcedSkip === 'number' ? forcedSkip : sessionsSkip+ let dataSessions: { sessions: Session[] }+ let from+ let to++ if (dateRange) {+ from = getFormatDate(dateRange[0])+ to = getFormatDate(dateRange[1])+ }++ if (period === 'custom' && dateRange) {+ dataSessions = await getSessions(id, '', filters, from, to, SESSIONS_TAKE, skip, timezone, projectPassword)+ } else {+ dataSessions = await getSessions(id, period, filters, '', '', SESSIONS_TAKE, skip, timezone, projectPassword)+ }++ if (requestId === sessionsRequestIdRef.current && isMountedRef.current) {+ if (override) {+ setSessions(dataSessions?.sessions || [])+ } else {+ setSessions((prev) => [...prev, ...(dataSessions?.sessions || [])])+ }+ setSessionsSkip((prev) => {+ if (typeof forcedSkip === 'number') {+ return SESSIONS_TAKE + forcedSkip+ }++ return SESSIONS_TAKE + prev+ })++ if (dataSessions?.sessions?.length < SESSIONS_TAKE) {+ setCanLoadMoreSessions(false)+ } else {+ setCanLoadMoreSessions(true)+ }+ }+ } catch (reason: any) {+ console.error('[ERROR](loadSessions) Loading sessions data failed:', reason)+ if (isMountedRef.current) {+ setError(reason?.message || reason?.toString() || 'Unknown error')+ }+ } finally {+ if (requestId === sessionsRequestIdRef.current && isMountedRef.current) {+ setSessionsLoading(false)+ }+ }+ }++ const loadSession = async (psid: string) => {+ if (sessionLoading) {+ return+ }++ setSessionLoading(true)++ try {+ const session = await getSession(id, psid, timezone, projectPassword)+ if (isMountedRef.current) {+ setActiveSession(session)+ }+ } catch (reason: any) {+ console.error('[ERROR] (loadSession)(getSession)', reason)+ if (isMountedRef.current) {+ setError(reason?.message || reason?.toString() || 'Unknown error')+ }+ } finally {+ if (isMountedRef.current) {+ setSessionLoading(false)+ }+ }+ }++ // Handle session detail loading+ useEffect(() => {+ if (!activePSID) {+ setActiveSession(null)+ // Coming back from a session detail to the list: reset pagination and reload first page+ if (prevActivePSIDRef.current) {+ skipNextSessionsAutoLoadRef.current = true+ setSessionsSkip(0)+ loadSessions(0, true)+ }+ prevActivePSIDRef.current = null+ return+ }++ loadSession(activePSID)+ prevActivePSIDRef.current = activePSID+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [period, dateRange, activePSID])++ // Load sessions list+ useEffect(() => {+ if (!project || activePSID) {+ return+ }++ if (skipNextSessionsAutoLoadRef.current) {+ skipNextSessionsAutoLoadRef.current = false+ return+ }++ loadSessions()+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [dateRange, filters, id, period, timezone, project, activePSID])++ // Handle refresh trigger+ useEffect(() => {+ if (sessionsRefreshTrigger > 0) {+ if (activePSID) {+ loadSession(activePSID)+ } else {+ setSessionsSkip(0)+ loadSessions(0, true)+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [sessionsRefreshTrigger])++ const refreshStats = () => {+ if (activePSID) {+ loadSession(activePSID)+ } else {+ setSessionsSkip(0)+ loadSessions(0, true)+ }+ }++ if (error && sessionsLoading === false) {+ return (+ <div className='bg-gray-50 px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8 dark:bg-slate-900'>+ <div className='mx-auto max-w-max'>+ <main className='sm:flex'>+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />+ <div className='sm:ml-6'>+ <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>+ <h1 className='text-4xl font-extrabold text-gray-900 sm:text-5xl dark:text-gray-50'>+ {t('apiNotifications.somethingWentWrong')}+ </h1>+ <p className='mt-4 text-2xl font-medium text-gray-700 dark:text-gray-200'>+ {t('apiNotifications.errorCode', { error })}+ </p>+ </div>+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>+ <button+ type='button'+ onClick={() => window.location.reload()}+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden'+ >+ {t('dashboard.reloadPage')}+ </button>+ <Link+ to={routes.contact}+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'+ >+ {t('notFoundPage.support')}+ </Link>+ </div>+ </div>+ </main>+ </div>+ </div>+ )+ }++ // Session Detail View+ if (activePSID) {+ return (+ <div className='mt-4'>+ <div className='mx-auto mt-2 mb-4 flex max-w-max items-center space-x-4 lg:mx-0'>+ <Link+ to={{+ search: pureSearchParams,+ }}+ className='flex items-center text-sm text-gray-900 underline decoration-dashed hover:decoration-solid dark:text-gray-100'+ >+ <ChevronLeftIcon className='mr-1 size-3' />+ {t('project.backToSessions')}+ </Link>+ <RefreshStatsButton onRefresh={refreshStats} />+ </div>+ <SessionDetailView+ activeSession={activeSession}+ sessionLoading={sessionLoading}+ timeFormat={timeFormat}+ chartType={chartType}+ rotateXAxis={rotateXAxis}+ dataNames={dataNames}+ />+ </div>+ )+ }++ // Sessions List View+ return (+ <div className='mt-4'>+ {!_isEmpty(sessions) ? <Filters tnMapping={tnMapping} /> : null}+ {(sessionsLoading === null || sessionsLoading) && _isEmpty(sessions) ? <Loader /> : null}+ {typeof sessionsLoading === 'boolean' && !sessionsLoading && _isEmpty(sessions) ? (+ <NoEvents filters={filters} />+ ) : null}+ <Sessions sessions={sessions} timeFormat={timeFormat} />+ {canLoadMoreSessions ? (+ <button+ type='button'+ title={t('project.loadMore')}+ onClick={() => loadSessions()}+ className={cx(+ 'relative mx-auto mt-2 flex items-center rounded-md border border-transparent p-2 text-sm font-medium text-gray-700 hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:bg-slate-900 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',+ {+ 'cursor-not-allowed opacity-50': sessionsLoading || sessionsLoading === null,+ hidden: sessionsLoading && _isEmpty(sessions),+ },+ )}+ >+ {sessionsLoading ? (+ <Spin className='mr-2 size-5' />+ ) : (+ <DownloadIcon className='mr-2 h-5 w-5' strokeWidth={1.5} />+ )}+ {t('project.loadMore')}+ </button>+ ) : null}+ </div>+ )+}++export default SessionsViewdiff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex 1c624cf49..540371836 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -72,8 +72,6 @@ import {deleteFunnel,getFunnelData,getPerformanceOverallStats,- getSessions,- getSession,getPropertyMetadata,getProjectViews,deleteProjectView,@@ -128,7 +126,6 @@ import {AnalyticsFunnel,OverallObject,OverallPerformanceObject,- SessionDetails as SessionDetailsModel,Session,Annotation,Profile,@@ -166,6 +163,7 @@ import AskAIView from '../AskAI'import ErrorsView from '../Errors/View/ErrorsView'import FeatureFlagsView from '../FeatureFlags/View'import GoalsView from '../Goals/View'+import SessionsView from '../Sessions/View/SessionsView'import AddAViewModal from './components/AddAViewModal'import CCRow from './components/CCRow'@@ -183,16 +181,11 @@ import LiveVisitorsDropdown from './components/LiveVisitorsDropdown'import LockedDashboard from './components/LockedDashboard'import { MetricCard, MetricCards, PerformanceMetricCards } from './components/MetricCards'import NoEvents from './components/NoEvents'-import NoSessionDetails from './components/NoSessionDetails'-import { Pageflow } from './components/Pageflow'import { PerformanceChart } from './components/PerformanceChart'import ProjectSidebar from './components/ProjectSidebar'import { RefreshStatsButton } from './components/RefreshStatsButton'import RefRow from './components/RefRow'import SearchFilters, { getFiltersUrlParams } from './components/SearchFilters'-import { SessionChart } from './components/SessionChart'-import { SessionDetails } from './components/SessionDetails'-import { Sessions } from './components/Sessions'import TBPeriodSelector from './components/TBPeriodSelector'import { TrafficChart } from './components/TrafficChart'import { UserDetails } from './components/UserDetails'@@ -399,6 +392,7 @@ interface ViewProjectContextType {captchaRefreshTrigger: numbergoalsRefreshTrigger: numberfeatureFlagsRefreshTrigger: number+ sessionsRefreshTrigger: number// FunctionsupdatePeriod: (newPeriod: { period: Period; label?: string }) => void@@ -425,6 +419,7 @@ const defaultViewProjectContext: ViewProjectContextType = {captchaRefreshTrigger: 0,goalsRefreshTrigger: 0,featureFlagsRefreshTrigger: 0,+ sessionsRefreshTrigger: 0,updatePeriod: () => {},updateTimebucket: (_newTimebucket) => {},refCalendar: { current: null } as any,@@ -538,6 +533,7 @@ const ViewProjectContent = () => {const [captchaRefreshTrigger, setCaptchaRefreshTrigger] = useState(0)const [goalsRefreshTrigger, setGoalsRefreshTrigger] = useState(0)const [featureFlagsRefreshTrigger, setFeatureFlagsRefreshTrigger] = useState(0)+ const [sessionsRefreshTrigger, setSessionsRefreshTrigger] = useState(0)const [activeChartMetrics, setActiveChartMetrics] = useState<Record<keyof typeof CHART_METRICS_MAPPING, boolean>>({[CHART_METRICS_MAPPING.unique]: true,[CHART_METRICS_MAPPING.views]: false,@@ -672,25 +668,6 @@ const ViewProjectContent = () => {const [isHotkeysHelpOpened, setIsHotkeysHelpOpened] = useState(false)- // sessions- const [sessionsSkip, setSessionsSkip] = useState(0)- const [canLoadMoreSessions, setCanLoadMoreSessions] = useState(false)- const [sessions, setSessions] = useState<Session[]>([])- const [sessionsLoading, setSessionsLoading] = useState<boolean | null>(null) // null - not loaded, true - loading, false - loaded- const [activeSession, setActiveSession] = useState<{- [key: string]: any- details: SessionDetailsModel- } | null>(null)- const [sessionLoading, setSessionLoading] = useState(false)- const activePSID = useMemo(() => {- return searchParams.get('psid')- }, [searchParams])- const prevActivePSIDRef = useRef<string | null>(activePSID)- const [zoomedTimeRange, setZoomedTimeRange] = useState<[Date, Date] | null>(null)- const [sessionChartInstance, _setSessionChartInstance] = useState<any>(null)- const sessionsRequestIdRef = useRef(0)- const skipNextSessionsAutoLoadRef = useRef(false)-// profiles / usersconst [profilesSkip, setProfilesSkip] = useState(0)const [canLoadMoreProfiles, setCanLoadMoreProfiles] = useState(false)@@ -710,6 +687,11 @@ const ViewProjectContent = () => {const profilesRequestIdRef = useRef(0)const skipNextProfilesAutoLoadRef = useRef(false)+ // Check if we're viewing a specific session detail+ const activePSID = useMemo(() => {+ return searchParams.get('psid')+ }, [searchParams])+const [funnelToEdit, setFunnelToEdit] = useState<Funnel | undefined>(undefined)const [funnelActionLoading, setFunnelActionLoading] = useState(false)const [funnelAnalytics, setFunnelAnalytics] = useState<{@@ -759,14 +741,6 @@ const ViewProjectContent = () => {annotation: null,})- // Reset sessions when filters change so lists reload with correct pagination- useEffect(() => {- sessionsRequestIdRef.current += 1- setSessionsSkip(0)- setSessions([])- setSessionsLoading(null)- }, [filters])-const mode = activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode] ? 'cumulative' : 'periodical'const loadProjectViews = async (forced?: boolean) => {@@ -1844,97 +1818,6 @@ const ViewProjectContent = () => {return getPropertyMetadata(id, event, timeBucket, period, '', '', filters, timezone, projectPassword)}- const loadSession = async (psid: string) => {- if (sessionLoading) {- return- }-- setSessionLoading(true)-- try {- const session = await getSession(id, psid, timezone, projectPassword)-- setActiveSession(session)- } catch (reason: any) {- console.error('[ERROR] (loadSession)(getSession)', reason)- toast.error(reason)- }-- setSessionLoading(false)- }-- useEffect(() => {- if (!activePSID) {- setActiveSession(null)- // Coming back from a session detail to the list: reset pagination and reload first page- if (prevActivePSIDRef.current) {- skipNextSessionsAutoLoadRef.current = true- setSessionsSkip(0)- loadSessions(0, true)- }- prevActivePSIDRef.current = null- return- }-- loadSession(activePSID)- prevActivePSIDRef.current = activePSID- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [period, dateRange, timeBucket, activePSID])-- const loadSessions = async (forcedSkip?: number, override?: boolean) => {- if (sessionsLoading) {- return- }-- const requestId = sessionsRequestIdRef.current- setSessionsLoading(true)-- try {- const skip = typeof forcedSkip === 'number' ? forcedSkip : sessionsSkip- let dataSessions: { sessions: Session[] }- let from- let to-- if (dateRange) {- from = getFormatDate(dateRange[0])- to = getFormatDate(dateRange[1])- }-- if (period === 'custom' && dateRange) {- dataSessions = await getSessions(id, '', filters, from, to, SESSIONS_TAKE, skip, timezone, projectPassword)- } else {- dataSessions = await getSessions(id, period, filters, '', '', SESSIONS_TAKE, skip, timezone, projectPassword)- }-- if (requestId === sessionsRequestIdRef.current) {- if (override) {- setSessions(dataSessions?.sessions || [])- } else {- setSessions((prev) => [...prev, ...(dataSessions?.sessions || [])])- }- setSessionsSkip((prev) => {- if (typeof forcedSkip === 'number') {- return SESSIONS_TAKE + forcedSkip- }-- return SESSIONS_TAKE + prev- })-- if (dataSessions?.sessions?.length < SESSIONS_TAKE) {- setCanLoadMoreSessions(false)- } else {- setCanLoadMoreSessions(true)- }- }- } catch (reason) {- console.error('[ERROR](loadSessions) Loading sessions data failed:', reason)- } finally {- if (requestId === sessionsRequestIdRef.current) {- setSessionsLoading(false)- }- }- }-const loadProfiles = async (forcedSkip?: number, override?: boolean) => {if (profilesLoading) {return@@ -2372,17 +2255,6 @@ const ViewProjectContent = () => {return}- if (activeTab === PROJECT_TABS.sessions) {- if (activePSID) {- await loadSession(activePSID)- return- }-- setSessionsSkip(0)- loadSessions(0, true)- return- }-if (activeTab === PROJECT_TABS.profiles) {if (activeProfileId) {await loadProfile(activeProfileId)@@ -2409,11 +2281,16 @@ const ViewProjectContent = () => {return}+ if (activeTab === PROJECT_TABS.sessions) {+ setSessionsRefreshTrigger((prev) => prev + 1)+ return+ }+loadAnalytics()}},// eslint-disable-next-line react-hooks/exhaustive-deps- [authLoading, dataLoading, activeTab, activePSID, activeProfileId],+ [authLoading, dataLoading, activeTab, activeProfileId],)useEffect(() => {@@ -2513,21 +2390,6 @@ const ViewProjectContent = () => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [activeFunnel, activeTab, authLoading, project, dateRange, period, timeBucket])- useEffect(() => {- if (authLoading || activeTab !== PROJECT_TABS.sessions || authLoading || !project || activePSID) {- return- }-- if (skipNextSessionsAutoLoadRef.current) {- // We've explicitly loaded the first page already when closing a session detail- skipNextSessionsAutoLoadRef.current = false- return- }-- loadSessions()- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [activeTab, dateRange, filters, id, period, projectPassword, timezone, authLoading, project, activePSID])-// Load profiles list when users tab is activeuseEffect(() => {if (authLoading || activeTab !== PROJECT_TABS.profiles || !project || activeProfileId) {@@ -2732,8 +2594,6 @@ const ViewProjectContent = () => {newSearchParams.delete('to')newSearchParams.set('period', newPeriod)- setSessionsSkip(0)-updatePreferences({period: newPeriod,rangeDate: undefined,@@ -2770,13 +2630,6 @@ const ViewProjectContent = () => {navigate(_replace(routes.project_settings, ':id', id))}- const resetSessionChartZoom = () => {- if (sessionChartInstance) {- sessionChartInstance.unzoom()- }- setZoomedTimeRange(null)- }-const onMainChartZoom = (domain: [Date, Date] | null) => {if (!domain) {return@@ -3087,6 +2940,7 @@ const ViewProjectContent = () => {captchaRefreshTrigger,goalsRefreshTrigger,featureFlagsRefreshTrigger,+ sessionsRefreshTrigger,// FunctionsupdatePeriod,@@ -3097,11 +2951,7 @@ const ViewProjectContent = () => {}}><>- {(dataLoading && !isAutoRefreshing) ||- (sessionsLoading && !_isEmpty(sessions)) ||- (profilesLoading && !_isEmpty(profiles)) ? (- <LoadingBar />- ) : null}+ {(dataLoading && !isAutoRefreshing) || (profilesLoading && !_isEmpty(profiles)) ? <LoadingBar /> : null}{!isEmbedded ? <Header /> : null}<EventsRunningOutBanner /><div@@ -3574,90 +3424,8 @@ const ViewProjectContent = () => {)}</>) : null}- {activeTab === PROJECT_TABS.sessions && !activePSID ? (- <>- {!_isEmpty(sessions) ? <Filters tnMapping={tnMapping} /> : null}- {(sessionsLoading === null || sessionsLoading) && _isEmpty(sessions) ? <Loader /> : null}- {typeof sessionsLoading === 'boolean' && !sessionsLoading && _isEmpty(sessions) ? (- <NoEvents filters={filters} />- ) : null}- <Sessions sessions={sessions} timeFormat={timeFormat} />- {canLoadMoreSessions ? (- <button- type='button'- title={t('project.loadMore')}- onClick={() => loadSessions()}- className={cx(- 'relative mx-auto mt-2 flex items-center rounded-md border border-transparent p-2 text-sm font-medium text-gray-700 hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:bg-slate-900 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',- {- 'cursor-not-allowed opacity-50': sessionsLoading || sessionsLoading === null,- hidden: sessionsLoading && _isEmpty(sessions),- },- )}- >- <DownloadIcon className='mr-2 h-5 w-5' strokeWidth={1.5} />- {t('project.loadMore')}- </button>- ) : null}- </>- ) : null}- {activeTab === PROJECT_TABS.sessions && activePSID ? (- <>- <div className='mx-auto mt-2 mb-4 flex max-w-max items-center space-x-4 lg:mx-0'>- <Link- to={{- search: pureSearchParams,- }}- onClick={resetSessionChartZoom}- className='flex items-center text-sm text-gray-900 underline decoration-dashed hover:decoration-solid dark:text-gray-100'- >- <ChevronLeftIcon className='mr-1 size-3' />- {t('project.backToSessions')}- </Link>- <RefreshStatsButton onRefresh={refreshStats} />- </div>- {activeSession?.details ? (- <SessionDetails details={activeSession?.details} pages={activeSession?.pages} />- ) : null}- {!_isEmpty(activeSession?.chart) ? (- <div className='relative'>- <SessionChart- chart={activeSession?.chart}- timeBucket={activeSession?.timeBucket}- timeFormat={timeFormat}- rotateXAxis={rotateXAxis}- chartType={chartType}- dataNames={dataNames}- onZoom={setZoomedTimeRange}- />- {zoomedTimeRange ? (- <button- onClick={resetSessionChartZoom}- className='absolute top-2 right-0 z-10 rounded border bg-white px-2 py-1 text-xs text-gray-800 hover:bg-gray-100 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-200 hover:dark:bg-slate-700'- >- {t('project.resetZoom')}- </button>- ) : null}- </div>- ) : null}-- {_isEmpty(activeSession) && sessionLoading ? (- <Loader />- ) : (- <Pageflow- pages={activeSession?.pages}- timeFormat={timeFormat}- zoomedTimeRange={zoomedTimeRange}- sdur={activeSession?.details?.sdur}- />- )}- {activeSession !== null &&- _isEmpty(activeSession?.chart) &&- _isEmpty(activeSession?.pages) &&- !sessionLoading ? (- <NoSessionDetails />- ) : null}- </>+ {activeTab === PROJECT_TABS.sessions ? (+ <SessionsView tnMapping={tnMapping} chartType={chartType} rotateXAxis={rotateXAxis} />) : null}{activeTab === PROJECT_TABS.errors ? <ErrorsView /> : null}{activeTab === PROJECT_TABS.alerts && project.role === 'owner' && isAuthenticated ? (diff --git a/web/app/pages/Project/View/components/SessionDetailView.tsx b/web/app/pages/Project/View/components/SessionDetailView.tsxnew file mode 100644index 000000000..9580aac89--- /dev/null+++ b/web/app/pages/Project/View/components/SessionDetailView.tsx@@ -0,0 +1,337 @@+import cx from 'clsx'+import dayjs from 'dayjs'+import _capitalize from 'lodash/capitalize'+import _isEmpty from 'lodash/isEmpty'+import _size from 'lodash/size'+import _truncate from 'lodash/truncate'+import {+ GlobeIcon,+ MonitorIcon,+ SmartphoneIcon,+ TabletIcon,+ ClockIcon,+ MapPinIcon,+ LanguagesIcon,+ LinkIcon,+ TagIcon,+} from 'lucide-react'+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'++import { BROWSER_LOGO_MAP, OS_LOGO_MAP, OS_LOGO_MAP_DARK } from '~/lib/constants'+import { SessionDetails as SessionDetailsType } from '~/lib/models/Project'+import { useTheme } from '~/providers/ThemeProvider'+import Loader from '~/ui/Loader'+import { getLocaleDisplayName, getStringFromTime, getTimeFromSeconds } from '~/utils/generic'++import CCRow from './CCRow'+import NoSessionDetails from './NoSessionDetails'+import { Pageflow } from './Pageflow'+import { SessionChart } from './SessionChart'++interface PageflowItem {+ type: 'pageview' | 'event' | 'error'+ value: string+ created: string+ metadata?: { key: string; value: string }[]+}++interface SessionDetailViewProps {+ activeSession: {+ details: SessionDetailsType+ chart?: {+ x: string[]+ pageviews?: number[]+ customEvents?: number[]+ errors?: number[]+ }+ pages?: PageflowItem[]+ timeBucket?: string+ } | null+ sessionLoading: boolean+ timeFormat: '12-hour' | '24-hour'+ chartType: string+ rotateXAxis: boolean+ dataNames: Record<string, string>+}++// Info Row Component+const InfoRow = ({ icon, label, value }: { icon: React.ReactNode; label: string; value: React.ReactNode }) => (+ <div className='flex items-center justify-between border-b border-gray-100 py-2.5 last:border-0 dark:border-slate-700/50'>+ <span className='flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400'>+ {icon}+ {label}+ </span>+ <span className='flex items-center gap-1.5 text-sm font-medium text-gray-900 dark:text-white'>{value}</span>+ </div>+)++// Device Icon Component+const DeviceIcon = ({ device }: { device: string | null }) => {+ const deviceLower = device?.toLowerCase() || ''+ if (deviceLower === 'mobile') return <SmartphoneIcon className='h-4 w-4' />+ if (deviceLower === 'tablet') return <TabletIcon className='h-4 w-4' />+ return <MonitorIcon className='h-4 w-4' />+}++// Browser Icon Component+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='' />+}++// OS Icon Component+const OSIcon = ({ os, theme }: { os: string | null; theme: string }) => {+ if (!os) return <GlobeIcon className='h-4 w-4' />++ const logoPathLight = OS_LOGO_MAP[os as keyof typeof OS_LOGO_MAP]+ const logoPathDark = OS_LOGO_MAP_DARK[os as keyof typeof OS_LOGO_MAP_DARK]++ let logoPath = theme === 'dark' ? logoPathDark : logoPathLight+ logoPath ||= logoPathLight++ if (!logoPath) return <GlobeIcon className='h-4 w-4' />++ return <img src={`/${logoPath}`} className='h-4 w-4' alt='' />+}++export const SessionDetailView = ({+ activeSession,+ sessionLoading,+ timeFormat,+ chartType,+ rotateXAxis,+ dataNames,+}: SessionDetailViewProps) => {+ const {+ t,+ i18n: { language },+ } = useTranslation('common')+ const { theme } = useTheme()+ const [zoomedTimeRange, setZoomedTimeRange] = useState<[Date, Date] | null>(null)++ // Calculate session duration from pages if sdur is 0 or not available+ const sessionDuration = useMemo(() => {+ if (!activeSession?.details) return 0++ if (activeSession.details.sdur && activeSession.details.sdur > 0) {+ return activeSession.details.sdur+ }++ // Fallback: calculate duration from pageview timestamps only+ if (!_isEmpty(activeSession.pages)) {+ const pageviews = activeSession.pages!.filter((p) => p.type === 'pageview')+ if (pageviews.length >= 1) {+ const firstPageview = pageviews[0]+ const lastPageview = pageviews[pageviews.length - 1]+ const diffSeconds = dayjs(lastPageview.created).diff(dayjs(firstPageview.created), 'seconds')+ if (diffSeconds > 0) {+ return diffSeconds+ }+ }+ }++ return 0+ }, [activeSession?.details?.sdur, activeSession?.pages])++ const resetZoom = () => {+ setZoomedTimeRange(null)+ }++ if (_isEmpty(activeSession) && sessionLoading) {+ return <Loader />+ }++ if (activeSession !== null && _isEmpty(activeSession?.chart) && _isEmpty(activeSession?.pages) && !sessionLoading) {+ return <NoSessionDetails />+ }++ const details = activeSession?.details++ if (!details) {+ return <Loader />+ }++ return (+ <div className='space-y-6'>+ {/* Main Content - Two Column Layout */}+ <div className='flex flex-col gap-6 lg:flex-row'>+ {/* Left Column - Session Details */}+ <div className='space-y-4 lg:w-[380px]'>+ {/* Session Info Card */}+ <div className='rounded-xl border border-gray-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-800'>+ <h3 className='mb-3 text-xs font-semibold tracking-wide text-gray-900 uppercase dark:text-gray-50'>+ {t('project.sessionInfo')}+ </h3>+ <div>+ {/* Session Duration */}+ <InfoRow+ icon={<ClockIcon className='h-4 w-4' />}+ label={t('dashboard.sessionDuration')}+ value={+ details.isLive ? (+ <span className='flex items-center font-semibold text-red-500'>+ <span className='mr-1.5 h-2.5 w-2.5 animate-pulse rounded-full bg-red-500' />+ {t('dashboard.live').toUpperCase()}+ </span>+ ) : sessionDuration > 0 ? (+ getStringFromTime(getTimeFromSeconds(sessionDuration))+ ) : (+ 'N/A'+ )+ }+ />+ {/* Referrer */}+ <InfoRow+ icon={<LinkIcon className='h-4 w-4' />}+ label={t('project.mapping.ref')}+ value={+ details.ref ? (+ <span title={_size(details.ref) > 25 ? details.ref : undefined}>+ {_truncate(details.ref, { length: 25 })}+ </span>+ ) : (+ t('project.directNone')+ )+ }+ />+ </div>+ </div>++ {/* Location & Device Card */}+ <div className='rounded-xl border border-gray-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-800'>+ <h3 className='mb-3 text-xs font-semibold tracking-wide text-gray-900 uppercase dark:text-gray-50'>+ {t('project.locationAndDevice')}+ </h3>+ <div>+ <InfoRow+ icon={<MapPinIcon className='h-4 w-4' />}+ label={t('project.mapping.cc')}+ value={details.cc ? <CCRow size={16} cc={details.cc} language={language} /> : '-'}+ />+ {details.rg ? (+ <InfoRow icon={<MapPinIcon className='h-4 w-4' />} label={t('project.mapping.rg')} value={details.rg} />+ ) : null}+ {details.ct ? (+ <InfoRow icon={<MapPinIcon className='h-4 w-4' />} label={t('project.mapping.ct')} value={details.ct} />+ ) : null}+ <InfoRow+ icon={<LanguagesIcon className='h-4 w-4' />}+ label={t('project.mapping.lc')}+ value={details.lc ? getLocaleDisplayName(details.lc, language) : '-'}+ />+ <InfoRow+ icon={<DeviceIcon device={details.dv} />}+ label={t('project.mapping.dv')}+ value={details.dv ? _capitalize(details.dv) : '-'}+ />+ <InfoRow+ icon={<BrowserIcon browser={details.br} />}+ label={t('project.mapping.br')}+ value={+ details.br ? (+ <>+ {details.br}+ {details.brv ? ` v${details.brv}` : ''}+ </>+ ) : (+ '-'+ )+ }+ />+ <InfoRow+ icon={<OSIcon os={details.os} theme={theme} />}+ label={t('project.mapping.os')}+ value={+ details.os ? (+ <>+ {details.os}+ {details.osv ? ` v${details.osv}` : ''}+ </>+ ) : (+ '-'+ )+ }+ />+ </div>+ </div>++ {/* UTM Campaigns Card */}+ {details.so || details.me || details.ca || details.te || details.co ? (+ <div className='rounded-xl border border-gray-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-800'>+ <h3 className='mb-3 text-xs font-semibold tracking-wide text-gray-900 uppercase dark:text-gray-50'>+ {t('project.campaigns')}+ </h3>+ <div>+ {details.so ? (+ <InfoRow icon={<TagIcon className='h-4 w-4' />} label={t('project.mapping.so')} value={details.so} />+ ) : null}+ {details.me ? (+ <InfoRow icon={<TagIcon className='h-4 w-4' />} label={t('project.mapping.me')} value={details.me} />+ ) : null}+ {details.ca ? (+ <InfoRow icon={<TagIcon className='h-4 w-4' />} label={t('project.mapping.ca')} value={details.ca} />+ ) : null}+ {details.te ? (+ <InfoRow icon={<TagIcon className='h-4 w-4' />} label={t('project.mapping.te')} value={details.te} />+ ) : null}+ {details.co ? (+ <InfoRow icon={<TagIcon className='h-4 w-4' />} label={t('project.mapping.co')} value={details.co} />+ ) : null}+ </div>+ </div>+ ) : null}+ </div>++ {/* Right Column - Chart */}+ <div className='flex-1'>+ {!_isEmpty(activeSession?.chart) ? (+ <div className='rounded-xl border border-gray-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-800'>+ <div className='mb-3 flex items-center justify-between'>+ <h3 className='text-xs font-semibold tracking-wide text-gray-900 uppercase dark:text-gray-50'>+ {t('project.sessionActivity')}+ </h3>+ {zoomedTimeRange ? (+ <button+ onClick={resetZoom}+ className='rounded border bg-white px-2 py-1 text-xs text-gray-800 hover:bg-gray-100 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-200 hover:dark:bg-slate-700'+ >+ {t('project.resetZoom')}+ </button>+ ) : null}+ </div>+ <SessionChart+ chart={activeSession?.chart}+ timeBucket={activeSession?.timeBucket}+ timeFormat={timeFormat}+ rotateXAxis={rotateXAxis}+ chartType={chartType}+ dataNames={dataNames}+ onZoom={setZoomedTimeRange}+ className='h-[300px] [&_svg]:overflow-visible!'+ />+ </div>+ ) : null}+ </div>+ </div>++ {/* Pageflow Section - Full Width Below */}+ <div className='rounded-xl border border-gray-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-800'>+ <h3 className='mb-4 text-xs font-semibold tracking-wide text-gray-900 uppercase dark:text-gray-50'>+ {t('project.pageflow')}+ </h3>+ <Pageflow+ pages={activeSession?.pages || []}+ timeFormat={timeFormat}+ zoomedTimeRange={zoomedTimeRange}+ sdur={activeSession?.details?.sdur}+ />+ </div>+ </div>+ )+}diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex fa6e6478f..46a6f0e9a 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -1197,6 +1197,9 @@"viewSession": "View session","topPages": "Top pages","locationAndDevice": "Location & Device",+ "sessionInfo": "Session info",+ "sessionActivity": "Session activity",+ "pageflow": "Page flow","userSessions": "Sessions","noSessions": "No sessions found for this user.","unknown": "Unknown",