📈 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
Allow users to click on a date on the chart and pull sessions for that date
Blue Mouse8a9e30501b66
diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsxindex 383d4fcd7..6e3212fe3 100644--- a/web/app/pages/Project/View/ViewProject.helpers.tsx+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx@@ -600,6 +600,7 @@ const getSettings = (annotations?: Annotation[],period?: string,timezone?: string,+ onDataPointClick?: (d: { x: Date; index: number }) => void,): ChartOptions => {const xAxisSize = _size(chart.x)@@ -713,6 +714,13 @@ const getSettings = (data: {x: 'x',columns: [...columns, ...customEventsToArray],+ onclick: onDataPointClick+ ? (d: any) => {+ if (d?.x) {+ onDataPointClick({ x: d.x, index: d.index })+ }+ }+ : undefined,types: {unique: chartType === chartTypes.line ? area() : bar(),uniqueCompare: chartType === chartTypes.line ? line() : bar(),@@ -899,7 +907,9 @@ const getSettings = (</li>`},- ).join('')}</ul>`+ ).join(+ '',+ )}${onDataPointClick ? `<li class='pt-1 mt-1 border-t border-gray-200 dark:border-slate-700/80 text-[10px] text-gray-400 dark:text-slate-500'>Click to explore sessions</li>` : ''}</ul>`}// Get dates from first item@@ -994,6 +1004,7 @@ const getSettings = (<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-md z-50'>${currentSection}${compareSection}+ ${onDataPointClick ? `<li class='pt-1 mt-1 border-t border-gray-200 dark:border-slate-700/80 text-[10px] text-gray-400 dark:text-slate-500'>Click to explore sessions</li>` : ''}</ul>`},},@@ -1003,9 +1014,11 @@ const getSettings = (: {focus: {only: xAxisSize > 1,+ expand: onDataPointClick ? { enabled: true, r: 5 } : undefined,},pattern: ['circle'],r: 2,+ sensitivity: onDataPointClick ? 50 : undefined,},legend: {item: {@@ -1032,53 +1045,76 @@ const getSettings = (ratio: 0.15,},},- onrendered: activeChartMetrics.revenue- ? function () {- // Revenue chart styling:- // - revenue: solid orange stroke (handled by CSS)- // - refunds: dashed orange stroke + light fill- // - when refunds value is 0, remove stroke to avoid "cap" lines- const chart = this as any-- // Guard against accessing chart internals after destruction- // This prevents "Cannot read properties of null" errors- if (!chart || !chart.$ || !chart.$.bar?.bars) {- return- }+ onrendered:+ activeChartMetrics.revenue || onDataPointClick+ ? function () {+ const chartInstance = this as any++ if (!chartInstance || !chartInstance.$) return++ try {+ if (activeChartMetrics.revenue && chartInstance.$.bar?.bars) {+ chartInstance.$.bar.bars.each(function (+ this: SVGPathElement,+ d: any,+ ) {+ const value = Number(d?.value || 0)++ if (d?.id === 'refundsAmount') {+ if (value > 0) {+ this.style.stroke = '#ea580c'+ this.style.strokeWidth = '1.5px'+ this.style.strokeDasharray = '6,4'+ this.style.display = ''+ } else {+ this.style.strokeDasharray = ''+ this.style.strokeWidth = '0'+ this.style.stroke = 'none'+ this.style.display = 'none'+ }+ } else if (d?.id === 'revenue') {+ if (value === 0) {+ this.style.strokeWidth = '0'+ this.style.stroke = 'none'+ this.style.display = 'none'+ } else {+ this.style.strokeWidth = '1.5px'+ this.style.stroke = '#ea580c'+ this.style.display = ''+ }+ }+ })+ }++ if (onDataPointClick) {+ const svg = chartInstance.$.svg?.node()+ if (!svg) return++ const eventRectsGroup = svg.querySelector('.bb-event-rects')+ if (!eventRectsGroup || eventRectsGroup.__clickAttached) return+ eventRectsGroup.__clickAttached = true- try {- chart.$.bar.bars.each(function (this: SVGPathElement, d: any) {- const value = Number(d?.value || 0)-- if (d?.id === 'refundsAmount') {- if (value > 0) {- this.style.stroke = '#ea580c'- this.style.strokeWidth = '1.5px'- this.style.strokeDasharray = '6,4'- this.style.display = ''- } else {- this.style.strokeDasharray = ''- this.style.strokeWidth = '0'- this.style.stroke = 'none'- this.style.display = 'none'- }- } else if (d?.id === 'revenue') {- if (value === 0) {- this.style.strokeWidth = '0'- this.style.stroke = 'none'- this.style.display = 'none'- } else {- this.style.strokeWidth = '1.5px'- this.style.stroke = '#ea580c'- this.style.display = ''- }+ eventRectsGroup.addEventListener('click', (e: MouseEvent) => {+ const target = e.target as SVGRectElement+ if (!target?.classList?.contains('bb-event-rect')) return++ const rects =+ eventRectsGroup.querySelectorAll('.bb-event-rect')+ const index = Array.from(rects).indexOf(target)+ if (index === -1) return++ const xs = chartInstance.data.xs()+ const xValues = Object.values(xs)[0] as Date[] | undefined+ if (!xValues || index >= xValues.length) return++ onDataPointClick({ x: xValues[index], index })+ })}- })- } catch {- // Ignore errors during render if chart is being destroyed+ } catch {+ // ignore+ }}- }- : undefined,+ : undefined,zoom:onZoom && enableZoom !== false? {diff --git a/web/app/pages/Project/View/components/ChartContextMenu.tsx b/web/app/pages/Project/View/components/ChartContextMenu.tsxindex 1d21a39e7..81b0ea24c 100644--- a/web/app/pages/Project/View/components/ChartContextMenu.tsx+++ b/web/app/pages/Project/View/components/ChartContextMenu.tsx@@ -1,5 +1,10 @@import cx from 'clsx'-import { PencilIcon, PlusIcon, TrashIcon } from '@phosphor-icons/react'+import {+ PencilIcon,+ PlusIcon,+ TrashIcon,+ UsersIcon,+} from '@phosphor-icons/react'import { useEffect, useRef } from 'react'import { useTranslation } from 'react-i18next'@@ -13,6 +18,7 @@ interface ChartContextMenuProps {onAddAnnotation: () => voidonEditAnnotation?: () => voidonDeleteAnnotation?: () => void+ onExploreSessions?: () => voidexistingAnnotation?: Annotation | nullallowedToManage: boolean}@@ -25,6 +31,7 @@ export const ChartContextMenu = ({onAddAnnotation,onEditAnnotation,onDeleteAnnotation,+ onExploreSessions,existingAnnotation,allowedToManage,}: ChartContextMenuProps) => {@@ -67,45 +74,29 @@ export const ChartContextMenu = ({return null}- // If not allowed to manage, show a message- if (!allowedToManage) {- return (- <div- ref={menuRef}- className='fixed z-[9999] min-w-[160px] rounded-md border border-gray-200 bg-white py-1 shadow-md dark:border-slate-700 dark:bg-slate-900'- style={{- left: x,- top: y,- }}- >- <div className='px-3 py-2 text-sm text-gray-500 dark:text-gray-400'>- {t('project.annotationsViewOnly')}- </div>- </div>- )- }-- const menuItems = existingAnnotation- ? [- {- label: t('project.editAnnotation'),- icon: PencilIcon,- onClick: onEditAnnotation,- },- {- label: t('project.deleteAnnotation'),- icon: TrashIcon,- onClick: onDeleteAnnotation,- danger: true,- },- ]- : [- {- label: t('project.addAnnotation'),- icon: PlusIcon,- onClick: onAddAnnotation,- },- ]+ const annotationItems = allowedToManage+ ? existingAnnotation+ ? [+ {+ label: t('project.editAnnotation'),+ icon: PencilIcon,+ onClick: onEditAnnotation,+ },+ {+ label: t('project.deleteAnnotation'),+ icon: TrashIcon,+ onClick: onDeleteAnnotation,+ danger: true,+ },+ ]+ : [+ {+ label: t('project.addAnnotation'),+ icon: PlusIcon,+ onClick: onAddAnnotation,+ },+ ]+ : []return (<div@@ -116,7 +107,30 @@ export const ChartContextMenu = ({top: y,}}>- {menuItems.map((item) => (+ {onExploreSessions ? (+ <>+ <button+ type='button'+ onClick={() => {+ onExploreSessions()+ onClose()+ }}+ className='flex w-full items-center gap-2 px-3 py-2 text-left text-sm text-gray-700 transition-colors hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-slate-800'+ >+ <UsersIcon className='h-4 w-4' />+ {t('project.exploreSessions')}+ </button>+ {annotationItems.length > 0 ? (+ <div className='my-1 border-t border-gray-200 dark:border-slate-700' />+ ) : null}+ </>+ ) : null}+ {!allowedToManage && !onExploreSessions ? (+ <div className='px-3 py-2 text-sm text-gray-500 dark:text-gray-400'>+ {t('project.annotationsViewOnly')}+ </div>+ ) : null}+ {annotationItems.map((item) => (<buttonkey={item.label}type='button'diff --git a/web/app/pages/Project/tabs/Sessions/Sessions.tsx b/web/app/pages/Project/tabs/Sessions/Sessions.tsxindex cab7cee57..6107c0bed 100644--- a/web/app/pages/Project/tabs/Sessions/Sessions.tsx+++ b/web/app/pages/Project/tabs/Sessions/Sessions.tsx@@ -82,7 +82,7 @@ const Separator = () => (</svg>)-const Session = ({+export const Session = ({session,timeFormat,hideNewReturnBadge,diff --git a/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsxnew file mode 100644index 000000000..e65c71ac1--- /dev/null+++ b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx@@ -0,0 +1,244 @@+import {+ Dialog,+ DialogBackdrop,+ DialogPanel,+ DialogTitle,+} from '@headlessui/react'+import { XIcon, UsersIcon } from '@phosphor-icons/react'+import _map from 'lodash/map'+import { useCallback, useEffect, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'++import type { SessionsResponse } from '~/api/api.server'+import type { Session as SessionType } from '~/lib/models/Project'+import Loader from '~/ui/Loader'+import Spin from '~/ui/icons/Spin'+import { Text } from '~/ui/Text'++import { Session } from '../Sessions/Sessions'++const SESSIONS_TAKE = 30++async function fetchSessionsPage(+ projectId: string,+ params: Record<string, unknown>,+): Promise<SessionsResponse | null> {+ const response = await fetch('/api/analytics', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ action: 'getSessions',+ projectId,+ params,+ }),+ })++ if (!response.ok) return null++ const result = (await response.json()) as {+ data: SessionsResponse | null+ }+ return result.data+}++interface SessionsDrawerProps {+ isOpen: boolean+ onClose: () => void+ from: string+ to: string+ label: string+ projectId: string+ timezone: string+ timeFormat: '12-hour' | '24-hour'+ filters?: any[]+}++export const SessionsDrawer = ({+ isOpen,+ onClose,+ from,+ to,+ label,+ projectId,+ timezone,+ timeFormat,+ filters = [],+}: SessionsDrawerProps) => {+ const { t } = useTranslation('common')+ const [sessions, setSessions] = useState<SessionType[]>([])+ const [skip, setSkip] = useState(0)+ const [hasMore, setHasMore] = useState(true)+ const [initialLoading, setInitialLoading] = useState(true)+ const [loadingMore, setLoadingMore] = useState(false)+ const sentinelRef = useRef<HTMLDivElement>(null)+ const scrollContainerRef = useRef<HTMLDivElement>(null)+ const loadingRef = useRef(false)++ const loadSessions = useCallback(+ async (currentSkip: number, append: boolean) => {+ const result = await fetchSessionsPage(projectId, {+ period: 'custom',+ from,+ to,+ timezone,+ filters,+ take: SESSIONS_TAKE,+ skip: currentSkip,+ })++ if (result) {+ const newSessions = result.sessions ?? []+ if (append) {+ setSessions((prev) => [...prev, ...newSessions])+ } else {+ setSessions(newSessions)+ }+ setHasMore(newSessions.length >= SESSIONS_TAKE)+ }+ },+ [projectId, from, to, timezone, filters],+ )++ useEffect(() => {+ if (!isOpen) return++ setInitialLoading(true)+ setSessions([])+ setSkip(0)+ setHasMore(true)++ loadSessions(0, false).finally(() => {+ setInitialLoading(false)+ })+ }, [isOpen, from, to, loadSessions])++ const loadMore = useCallback(async () => {+ if (loadingRef.current || !hasMore) return+ loadingRef.current = true+ setLoadingMore(true)++ const nextSkip = skip + SESSIONS_TAKE+ setSkip(nextSkip)+ await loadSessions(nextSkip, true)++ loadingRef.current = false+ setLoadingMore(false)+ }, [skip, hasMore, loadSessions])++ useEffect(() => {+ if (!isOpen || initialLoading || !hasMore) return++ const sentinel = sentinelRef.current+ if (!sentinel) return++ const observer = new IntersectionObserver(+ (entries) => {+ if (entries[0]?.isIntersecting) {+ loadMore()+ }+ },+ {+ root: scrollContainerRef.current,+ rootMargin: '200px',+ },+ )++ observer.observe(sentinel)+ return () => observer.disconnect()+ }, [isOpen, initialLoading, hasMore, loadMore])++ return (+ <Dialog className='relative z-50' open={isOpen} onClose={onClose}>+ <DialogBackdrop+ transition+ className='fixed inset-0 bg-gray-500/50 transition-opacity duration-300 ease-out data-closed:opacity-0 dark:bg-black/60'+ />++ <div className='fixed inset-0 overflow-hidden'>+ <div className='absolute inset-0 overflow-hidden'>+ <div className='pointer-events-none fixed inset-y-0 right-0 flex max-w-full pl-10'>+ <DialogPanel+ transition+ className='pointer-events-auto w-screen max-w-lg transform-gpu transition-transform duration-300 ease-out data-closed:translate-x-full data-closed:duration-200'+ >+ <div className='flex h-full flex-col bg-white shadow-xl dark:bg-slate-900'>+ {/* Header */}+ <div className='border-b border-gray-200 px-4 py-4 sm:px-5 dark:border-slate-700/80'>+ <div className='flex items-start justify-between'>+ <div className='min-w-0'>+ <DialogTitle className='text-base font-semibold text-gray-900 dark:text-gray-50'>+ {t('project.sessions')}+ </DialogTitle>+ <Text className='mt-0.5 truncate text-sm'>{label}</Text>+ </div>+ <div className='ml-3 flex shrink-0 items-center gap-2'>+ {!initialLoading && sessions.length > 0 ? (+ <span className='inline-flex items-center gap-1 rounded-md bg-gray-100 px-2 py-1 text-xs font-medium text-gray-600 dark:bg-slate-800 dark:text-gray-300'>+ <UsersIcon className='size-3.5' />+ {sessions.length}+ {hasMore ? '+' : ''}+ </span>+ ) : null}+ <button+ type='button'+ onClick={onClose}+ className='rounded-md p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-slate-800 dark:hover:text-gray-300'+ >+ <span className='sr-only'>{t('common.close')}</span>+ <XIcon className='size-5' />+ </button>+ </div>+ </div>+ </div>++ {/* Body */}+ <div+ ref={scrollContainerRef}+ className='flex-1 overflow-y-auto px-4 py-3 sm:px-5'+ >+ {initialLoading ? (+ <div className='flex items-center justify-center py-16'>+ <Loader />+ </div>+ ) : sessions.length === 0 ? (+ <div className='flex flex-col items-center justify-center py-16 text-center'>+ <UsersIcon+ className='size-10 text-gray-300 dark:text-slate-600'+ weight='duotone'+ />+ <Text className='mt-3 text-sm'>+ {t('project.noSessionsFound')}+ </Text>+ </div>+ ) : (+ <>+ <ul>+ {_map(sessions, (session) => (+ <Session+ key={session.psid}+ session={session}+ timeFormat={timeFormat}+ />+ ))}+ </ul>+ {hasMore ? (+ <div+ ref={sentinelRef}+ className='flex items-center justify-center py-4'+ >+ {loadingMore ? (+ <Spin className='text-gray-400 dark:text-slate-500' />+ ) : null}+ </div>+ ) : null}+ </>+ )}+ </div>+ </div>+ </DialogPanel>+ </div>+ </div>+ </div>+ </Dialog>+ )+}diff --git a/web/app/pages/Project/tabs/Traffic/TrafficChart.tsx b/web/app/pages/Project/tabs/Traffic/TrafficChart.tsxindex 926102b2d..8210e8301 100644--- a/web/app/pages/Project/tabs/Traffic/TrafficChart.tsx+++ b/web/app/pages/Project/tabs/Traffic/TrafficChart.tsx@@ -23,6 +23,7 @@ interface TrafficChartProps {annotations?: Annotation[]period?: stringtimezone?: string+ onDataPointClick?: (d: { x: Date; index: number }) => void}export const TrafficChart = ({@@ -42,6 +43,7 @@ export const TrafficChart = ({annotations,period,timezone,+ onDataPointClick,}: TrafficChartProps) => {const options: ChartOptions = useMemo(() => {return getSettings(@@ -59,6 +61,7 @@ export const TrafficChart = ({annotations,period,timezone,+ onDataPointClick,)}, [chartData,@@ -75,6 +78,7 @@ export const TrafficChart = ({annotations,period,timezone,+ onDataPointClick,])const deps = useMemo(diff --git a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx b/web/app/pages/Project/tabs/Traffic/TrafficView.tsxindex e931988b0..d7c4174dc 100644--- a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx+++ b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx@@ -52,6 +52,7 @@ import {} from '~/pages/Project/tabs/Traffic/MetricCards'import PageLinkRow from '~/pages/Project/tabs/Traffic/PageLinkRow'import RefRow from '~/pages/Project/tabs/Traffic/RefRow'+import { SessionsDrawer } from '~/pages/Project/tabs/Traffic/SessionsDrawer'import { TrafficChart } from '~/pages/Project/tabs/Traffic/TrafficChart'import TrafficHeaderActions from '~/pages/Project/tabs/Traffic/TrafficHeaderActions'import UserFlow from '~/pages/Project/tabs/Traffic/UserFlow'@@ -327,6 +328,57 @@ const TrafficViewInner = ({closeContextMenu,} = useAnnotations()+ const [sessionsDrawer, setSessionsDrawer] = useState<{+ from: string+ to: string+ label: string+ } | null>(null)++ const handleDataPointClick = useCallback(+ (d: { x: Date; index: number }) => {+ const date = dayjs(d.x)+ let from: string+ let to: string+ let label: string++ switch (timeBucket) {+ case 'minute':+ from = date.startOf('minute').toISOString()+ to = date.endOf('minute').toISOString()+ label = date.format('MMM D, YYYY HH:mm')+ break+ case 'hour':+ from = date.startOf('hour').toISOString()+ to = date.endOf('hour').toISOString()+ label = date.format(+ timeFormat === '24-hour'+ ? 'MMM D, YYYY HH:00 - HH:59'+ : 'MMM D, YYYY h:00 - h:59 A',+ )+ break+ case 'month':+ from = date.startOf('month').toISOString()+ to = date.endOf('month').toISOString()+ label = date.format('MMMM YYYY')+ break+ case 'year':+ from = date.startOf('year').toISOString()+ to = date.endOf('year').toISOString()+ label = date.format('YYYY')+ break+ case 'day':+ default:+ from = date.startOf('day').toISOString()+ to = date.endOf('day').toISOString()+ label = date.format('dddd, MMM D, YYYY')+ break+ }++ setSessionsDrawer({ from, to, label })+ },+ [timeBucket, timeFormat],+ )+const panelsData: PanelsData = useMemo(() => {if (deferredData.trafficData) {return {@@ -1072,6 +1124,7 @@ const TrafficViewInner = ({className='mt-5 h-80 md:mt-0 [&_svg]:overflow-visible!'annotations={filteredAnnotations}period={activePeriod?.period}+ onDataPointClick={handleDataPointClick}timezone={timezone}/></div>@@ -1431,9 +1484,36 @@ const TrafficViewInner = ({}: undefined}+ onExploreSessions={+ contextMenu.date+ ? () => {+ const date = dayjs(contextMenu.date, 'YYYY-MM-DD')+ if (!date.isValid()) return++ setSessionsDrawer({+ from: date.startOf('day').toISOString(),+ to: date.endOf('day').toISOString(),+ label: date.format('dddd, MMM D, YYYY'),+ })+ }+ : undefined+ }existingAnnotation={contextMenu.annotation}allowedToManage={allowedToManage}/>+ {sessionsDrawer ? (+ <SessionsDrawer+ isOpen={!!sessionsDrawer}+ onClose={() => setSessionsDrawer(null)}+ from={sessionsDrawer.from}+ to={sessionsDrawer.to}+ label={sessionsDrawer.label}+ projectId={id}+ timezone={timezone}+ timeFormat={timeFormat as '12-hour' | '24-hour'}+ filters={filters}+ />+ ) : null}</div></>)diff --git a/web/app/styles/ProjectViewStyle.css b/web/app/styles/ProjectViewStyle.cssindex 7c8e37db3..0668089fa 100644--- a/web/app/styles/ProjectViewStyle.css+++ b/web/app/styles/ProjectViewStyle.css@@ -231,6 +231,22 @@ body.dark .bb-ygrid {}}+/* Clickable chart area */+#traffic-chart .bb-event-rects .bb-event-rect {+ cursor: pointer;+}++#traffic-chart .bb-lines path,+#traffic-chart .bb-areas path {+ pointer-events: stroke;+ cursor: pointer;+}++#traffic-chart .bb-circles circle,+#traffic-chart .bb-bars path {+ cursor: pointer;+}+/* Annotation lines */.bb-xgrid-line.annotation-line,.bb-ygrid-line.annotation-line {diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 8f32f3d71..1e63f9b82 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -1621,6 +1621,8 @@"noProfilesFiltersDesc": "No profiles have been recorded for the specified period or applied filters, please try a different period or change the filters applied.","noSessionsTitle": "No sessions yet","noSessionsContent": "No sessions have been recorded for the specified period, please try a different period.",+ "noSessionsFound": "No sessions found for this period.",+ "exploreSessions": "Explore sessions","noSessionsFiltersDesc": "No sessions have been recorded for the specified period or applied filters, please try a different period or change the filters applied.","noCaptchaEv": "No events have been captured for the specified timeframe.\nIf you haven't set up CAPTCHA yet, you can check out our <url>Docs</url> to easily integrate it into your app.","mapping": {