📈 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
Move live visitors calculation to project provider
Blue Mouseceec40f858e6
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex 9e255099d..ffe55cd6f 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -46,7 +46,6 @@ import { toast } from 'sonner'import {getProjectData,getOverallStats,- getLiveVisitors,getPerfData,getProjectDataCustomEvents,getTrafficCompareData,@@ -73,7 +72,6 @@ import Header from '~/components/Header'import useSize from '~/hooks/useSize'import {tbPeriodPairs,- LIVE_VISITORS_UPDATE_INTERVAL,DEFAULT_TIMEZONE,CDN_URL,isDevelopment,@@ -234,7 +232,8 @@ export const useViewProjectContext = () => {}const ViewProject = () => {- const { id, project, preferences, updatePreferences, extensions, mergeProject, allowedToManage } = useCurrentProject()+ const { id, project, preferences, updatePreferences, extensions, mergeProject, allowedToManage, liveVisitors } =+ useCurrentProject()const projectPassword = useProjectPassword(id)const { theme } = useTheme()@@ -270,8 +269,6 @@ const ViewProject = () => {return tabs.split(',')}, [searchParams])- const [liveVisitors, setLiveVisitors] = useState(0)-const [panelsData, setPanelsData] = useState<{types: (keyof Params)[]data: Params@@ -2165,27 +2162,6 @@ const ViewProject = () => {setSessionsLoading(null)}- useEffect(() => {- if (!project || project.isLocked) {- return- }-- const updateLiveVisitors = async () => {- const { id: pid } = project- const result = await getLiveVisitors([pid], projectPassword)-- setLiveVisitors(result[pid])- }-- updateLiveVisitors()-- const interval = setInterval(async () => {- await updateLiveVisitors()- }, LIVE_VISITORS_UPDATE_INTERVAL)-- return () => clearInterval(interval)- }, [project, projectPassword])-const updatePeriod = (newPeriod: { period: Period; label?: string }) => {if (period === newPeriod.period) {return@@ -2631,17 +2607,7 @@ const ViewProject = () => {{/* If tab is funnels - then display a funnel name, otherwise a project name */}{activeTab === PROJECT_TABS.funnels ? activeFunnel?.name : project.name}</h2>- {activeTab !== PROJECT_TABS.funnels ? (- <LiveVisitorsDropdown- onSessionSelect={(psid) => {- setDashboardTab(PROJECT_TABS.sessions)- const newSearchParams = new URLSearchParams(searchParams.toString())- newSearchParams.set('psid', psid)- setSearchParams(newSearchParams)- }}- live={liveVisitors}- />- ) : null}+ {activeTab !== PROJECT_TABS.funnels ? <LiveVisitorsDropdown /> : null}</div><div className='mx-auto mt-3 flex w-full max-w-[420px] flex-wrap items-center justify-center space-x-2 gap-y-1 sm:mx-0 sm:w-auto sm:max-w-none sm:flex-nowrap sm:justify-between lg:mt-0'>{activeTab !== PROJECT_TABS.funnels ? (diff --git a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsxindex a3db1c0a7..eff203730 100644--- a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx+++ b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx@@ -1,6 +1,6 @@import { ChevronDownIcon, ChevronUpIcon, XMarkIcon } from '@heroicons/react/24/outline'import _map from 'lodash/map'-import React, { useState, useEffect } from 'react'+import React, { useState } from 'react'import { useTranslation } from 'react-i18next'import OutsideClickHandler from 'react-outside-click-handler'import { Link } from 'react-router'@@ -12,58 +12,64 @@ import PulsatingCircle from '~/ui/icons/PulsatingCircle'import { useCurrentProject, useProjectPassword } from '../../../../providers/CurrentProjectProvider'-interface LiveVisitorsDropdownProps {- live: number | string- onSessionSelect: (psid: string) => void-}--const LiveVisitorsDropdown = ({ live, onSessionSelect }: LiveVisitorsDropdownProps) => {- const { id } = useCurrentProject()+const LiveVisitorsDropdown = () => {+ const { id, liveVisitors, updateLiveVisitors } = useCurrentProject()const projectPassword = useProjectPassword(id)const { t } = useTranslation()- const [show, setShow] = useState(false)- const [loading, setLoading] = useState(true)+ const [isDropdownVisible, setIsDropdownVisible] = useState(false)+ const [isLoading, setIsLoading] = useState(true)const [liveInfo, setLiveInfo] = useState<GetLiveVisitorsInfo[]>([])const getLiveVisitors = async () => {+ setIsLoading(true)+try {- const info = await getLiveVisitorsInfo(id, projectPassword)+ // Getting live sessions list and updating live visitors count to make sure it matches the list length+ const [info] = await Promise.all([getLiveVisitorsInfo(id, projectPassword), updateLiveVisitors()])setLiveInfo(info)} catch (reason) {console.error('[LiveVisitorsDropdown] getLiveVisitors:', reason)- } finally {- setLoading(false)}++ setIsLoading(false)}- useEffect(() => {- if (show) {- getLiveVisitors()+ const onOpen = async () => {+ if (isDropdownVisible) {+ setIsDropdownVisible(false)+ return}- }, [show]) // eslint-disable-line react-hooks/exhaustive-deps++ setIsDropdownVisible(true)+ await getLiveVisitors()+ }return (- <OutsideClickHandler onOutsideClick={() => setShow(false)}>+ <OutsideClickHandler onOutsideClick={() => setIsDropdownVisible(false)}><divclassName='relative flex h-5 cursor-pointer items-center font-mono text-base text-gray-900 dark:text-gray-50'- onClick={() => setShow(!show)}+ onClick={onOpen}><PulsatingCircle className='mr-1.5' type='small' /><span className='tracking-tighter'>{t('dashboard.xLiveVisitors', {- amount: live || 0,+ amount: liveVisitors,})}{' '}</span>- {show ? <ChevronUpIcon className='ml-1 inline h-4 w-4' /> : <ChevronDownIcon className='ml-1 inline h-4 w-4' />}- {show ? (+ {isDropdownVisible ? (+ <ChevronUpIcon className='ml-1 inline h-4 w-4' />+ ) : (+ <ChevronDownIcon className='ml-1 inline h-4 w-4' />+ )}+ {isDropdownVisible ? (<divclassName={`scrollbar-thin absolute top-3 right-0 z-10 mt-2 max-h-[200px] cursor-auto overflow-y-auto rounded-md border border-black/10 bg-white text-gray-900 dark:border-slate-700/50 dark:bg-slate-900 ${- liveInfo.length === 0 ? 'min-w-[200px]' : 'min-w-max'+ liveInfo.length === 0 || isLoading ? 'min-w-[200px]' : 'min-w-max'}`}><div className='flex w-full flex-col p-2'><p className='text-sm font-semibold text-gray-900 dark:text-gray-50'>{t('dashboard.liveVisitors')}</p>- {loading ? (+ {isLoading ? (<p className='text-sm text-gray-900 dark:text-gray-50'>{t('common.loading')}</p>) : (<div className='table w-full border-separate border-spacing-y-2'>@@ -78,13 +84,6 @@ const LiveVisitorsDropdown = ({ live, onSessionSelect }: LiveVisitorsDropdownPro<Linkkey={psid}className='group table-row cursor-pointer text-sm text-gray-900 dark:text-gray-50'- onClick={(e: React.MouseEvent<HTMLAnchorElement>) => {- e.preventDefault()- e.stopPropagation()- window.history.pushState({}, '', stringifiedUrl)-- onSessionSelect(psid)- }}to={stringifiedUrl}><div className='table-cell rounded-l-lg bg-gray-100 pr-2 align-middle group-hover:bg-gray-200 dark:bg-slate-800 dark:group-hover:bg-slate-700'>@@ -108,7 +107,7 @@ const LiveVisitorsDropdown = ({ live, onSessionSelect }: LiveVisitorsDropdownPro</div><XMarkIconclassName='absolute top-2 right-2 h-5 w-5 cursor-pointer text-gray-900 dark:text-gray-50'- onClick={() => setShow(!show)}+ onClick={() => setIsDropdownVisible(false)}/></div>) : null}diff --git a/web/app/providers/CurrentProjectProvider.tsx b/web/app/providers/CurrentProjectProvider.tsxindex 7dff73b06..602627896 100644--- a/web/app/providers/CurrentProjectProvider.tsx+++ b/web/app/providers/CurrentProjectProvider.tsx@@ -4,8 +4,14 @@ import { useTranslation } from 'react-i18next'import { useNavigate, useSearchParams } from 'react-router'import { toast } from 'sonner'-import { checkPassword, getInstalledExtensions, getProject } from '~/api'-import { isSelfhosted, LS_PROJECTS_PROTECTED_KEY, Period, TimeBucket } from '~/lib/constants'+import { checkPassword, getInstalledExtensions, getLiveVisitors, getProject } from '~/api'+import {+ isSelfhosted,+ LIVE_VISITORS_UPDATE_INTERVAL,+ LS_PROJECTS_PROTECTED_KEY,+ Period,+ TimeBucket,+} from '~/lib/constants'import { Extension, type Project } from '~/lib/models/Project'import { getItemJSON, removeItem } from '~/utils/localstorage'import routes from '~/utils/routes'@@ -23,6 +29,8 @@ interface CurrentProjectContextType {allowedToManage: booleanupdatePreferences: (prefs: ProjectPreferences) => voidmergeProject: (project: Partial<Project>) => void+ liveVisitors: number+ updateLiveVisitors: () => Promise<void>}const CurrentProjectContext = createContext<CurrentProjectContextType | undefined>(undefined)@@ -32,11 +40,11 @@ interface CurrentProjectProviderProps {children: React.ReactNode}-export const useProjectPassword = (id: string) => {+export const useProjectPassword = (id?: string) => {const [searchParams] = useSearchParams()const projectPassword = useMemo(- () => searchParams.get('password') || getItemJSON(LS_PROJECTS_PROTECTED_KEY)?.[id] || '',+ () => searchParams.get('password') || getItemJSON(LS_PROJECTS_PROTECTED_KEY)?.[id || ''] || '',[id, searchParams],)@@ -157,11 +165,43 @@ const useProjectPreferences = (id: string) => {return { preferences, updatePreferences }}+const useLiveVisitors = (project: Project | null) => {+ const projectPassword = useProjectPassword(project?.id)+ const [liveVisitors, setLiveVisitors] = useState(0)++ const updateLiveVisitors = useCallback(async () => {+ if (!project || project.isLocked) {+ return+ }++ const { id: pid } = project+ const result = await getLiveVisitors([pid], projectPassword)+ setLiveVisitors(result[pid] || 0)+ }, [project, projectPassword])++ useEffect(() => {+ if (!project || project.isLocked) {+ return+ }++ updateLiveVisitors()++ const interval = setInterval(async () => {+ await updateLiveVisitors()+ }, LIVE_VISITORS_UPDATE_INTERVAL)++ return () => clearInterval(interval)+ }, [project, updateLiveVisitors])++ return { liveVisitors, updateLiveVisitors }+}+export const CurrentProjectProvider = ({ children, id }: CurrentProjectProviderProps) => {const { project, mergeProject } = useProject(id)const { isAuthenticated } = useAuth()const { preferences, updatePreferences } = useProjectPreferences(id)const [extensions, setExtensions] = useState<Extension[]>([])+ const { liveVisitors, updateLiveVisitors } = useLiveVisitors(project)useEffect(() => {if (!project || isSelfhosted || !isAuthenticated) {@@ -191,6 +231,8 @@ export const CurrentProjectProvider = ({ children, id }: CurrentProjectProviderPextensions,mergeProject,allowedToManage: project?.role === 'owner' || project?.role === 'admin',+ liveVisitors,+ updateLiveVisitors,}}>{children}