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!

autorefresh functionality

Blue Mouse7e106e25033d
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index f95193d72..ff21c5c3b 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -27,7 +27,6 @@ import {
BellRingIcon,
ChartNoAxesColumnIcon,
FilterIcon,
- RotateCw,
BookmarkIcon,
PencilIcon,
DownloadIcon,
@@ -175,6 +174,7 @@ import NoEvents from './components/NoEvents'
import NoSessionDetails from './components/NoSessionDetails'
import { Pageflow } from './components/Pageflow'
import { PerformanceChart } from './components/PerformanceChart'
+import { RefreshStatsButton } from './components/RefreshStatsButton'
import RefRow from './components/RefRow'
import SearchFilters, { getFiltersUrlParams } from './components/SearchFilters'
import { SessionChart } from './components/SessionChart'
@@ -363,6 +363,7 @@ const ViewProjectContent = () => {
const [chartData, setChartData] = useState<TrafficLogResponse['chart'] & { [key: string]: number[] }>({})
// prevY2NeededRef removed - no longer needed with new chart management
const [dataLoading, setDataLoading] = useState(false)
+ const [isAutoRefreshing, setIsAutoRefreshing] = useState(false)
const [activeChartMetrics, setActiveChartMetrics] = useState<Record<keyof typeof CHART_METRICS_MAPPING, boolean>>({
[CHART_METRICS_MAPPING.unique]: true,
[CHART_METRICS_MAPPING.views]: false,
@@ -2046,43 +2047,51 @@ const ViewProjectContent = () => {
}
}, [funnelAnalytics])
- const refreshStats = async () => {
- if (!authLoading && !dataLoading) {
- if (activeTab === PROJECT_TABS.performance) {
- loadAnalyticsPerf()
- return
+ const refreshStats = useCallback(
+ async (isManual = true) => {
+ if (!isManual) {
+ setIsAutoRefreshing(true)
}
- if (activeTab === PROJECT_TABS.funnels) {
- loadFunnelsData()
- return
- }
+ if (!authLoading && !dataLoading) {
+ if (activeTab === PROJECT_TABS.performance) {
+ loadAnalyticsPerf()
+ return
+ }
- if (activeTab === PROJECT_TABS.sessions) {
- if (activePSID) {
- await loadSession(activePSID)
+ if (activeTab === PROJECT_TABS.funnels) {
+ loadFunnelsData()
return
}
- resetSessions()
- loadSessions(0)
- return
- }
+ if (activeTab === PROJECT_TABS.sessions) {
+ if (activePSID) {
+ await loadSession(activePSID)
+ return
+ }
- if (activeTab === PROJECT_TABS.errors) {
- if (activeEID) {
- await loadError(activeEID)
+ resetSessions()
+ loadSessions(0)
return
}
- resetErrors()
- loadErrors(0)
- return
- }
+ if (activeTab === PROJECT_TABS.errors) {
+ if (activeEID) {
+ await loadError(activeEID)
+ return
+ }
- loadAnalytics()
- }
- }
+ resetErrors()
+ loadErrors(0)
+ return
+ }
+
+ loadAnalytics()
+ }
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [authLoading, dataLoading, activeTab, activePSID, activeEID],
+ )
useEffect(() => {
if (activeTab !== PROJECT_TABS.traffic || authLoading || !project) return
@@ -2345,6 +2354,13 @@ const ViewProjectContent = () => {
setPeriodPairsCompare(tbPeriodPairsCompare(t, undefined, language))
}, [t, language])
+ // Reset isAutoRefreshing when loading completes
+ useEffect(() => {
+ if (!dataLoading) {
+ setIsAutoRefreshing(false)
+ }
+ }, [dataLoading])
+
const resetSessions = () => {
sessionsRequestIdRef.current += 1
setSessionsSkip(0)
@@ -2785,7 +2801,7 @@ const ViewProjectContent = () => {
}}
>
<>
- {dataLoading ? <LoadingBar /> : null}
+ {dataLoading && !isAutoRefreshing ? <LoadingBar /> : null}
{!isEmbedded ? <Header /> : null}
<EventsRunningOutBanner />
<div
@@ -2825,19 +2841,7 @@ const ViewProjectContent = () => {
<div className='mx-auto mt-3 flex w-full max-w-[420px] flex-wrap items-center justify-center gap-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 ? (
<>
- <button
- type='button'
- title={t('project.refreshStats')}
- onClick={refreshStats}
- className={cx(
- 'relative rounded-md border border-transparent p-2 text-sm font-medium transition-colors hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
- {
- 'cursor-not-allowed opacity-50': authLoading || dataLoading,
- },
- )}
- >
- <RotateCw className='h-5 w-5 text-gray-700 dark:text-gray-50' />
- </button>
+ <RefreshStatsButton onRefresh={refreshStats} />
<div
className={cx('border-gray-200 dark:border-gray-600', {
// @ts-expect-error
@@ -3072,19 +3076,7 @@ const ViewProjectContent = () => {
/>
) : null}
{activeTab === PROJECT_TABS.funnels ? (
- <button
- type='button'
- title={t('project.refreshStats')}
- onClick={refreshStats}
- className={cx(
- 'relative rounded-md border border-transparent p-2 text-sm font-medium transition-colors hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
- {
- 'cursor-not-allowed opacity-50': authLoading || dataLoading,
- },
- )}
- >
- <RotateCw className='h-5 w-5 text-gray-700 dark:text-gray-50' />
- </button>
+ <RefreshStatsButton onRefresh={refreshStats} />
) : null}
<div className='flex items-center'>
<TBPeriodSelector
@@ -3298,21 +3290,7 @@ const ViewProjectContent = () => {
<ChevronLeftIcon className='mr-1 size-3' />
{t('project.backToSessions')}
</Link>
- <button
- type='button'
- title={t('project.refreshStats')}
- onClick={refreshStats}
- className={cx(
- 'flex items-center text-sm text-gray-900 transition-colors hover:text-gray-600 dark:text-gray-100 dark:hover:text-gray-300',
- {
- 'cursor-not-allowed': authLoading || dataLoading || sessionLoading,
- },
- )}
- disabled={authLoading || dataLoading || sessionLoading}
- >
- <RotateCw className='mr-1 size-4' />
- {t('project.refresh')}
- </button>
+ <RefreshStatsButton onRefresh={refreshStats} />
</div>
{activeSession?.details ? <SessionDetails details={activeSession?.details} /> : null}
{!_isEmpty(activeSession?.chart) ? (
diff --git a/web/app/pages/Project/View/components/RefreshStatsButton.tsx b/web/app/pages/Project/View/components/RefreshStatsButton.tsx
new file mode 100644
index 000000000..3d7e13d0f
--- /dev/null
+++ b/web/app/pages/Project/View/components/RefreshStatsButton.tsx
@@ -0,0 +1,108 @@
+import { RotateCw } from 'lucide-react'
+import { useState, useEffect, useRef } from 'react'
+import { useTranslation } from 'react-i18next'
+
+import { useAuth } from '~/providers/AuthProvider'
+import { cn } from '~/utils/generic'
+
+import { useViewProjectContext } from '../ViewProject'
+
+const AUTO_REFRESH_INTERVAL_SECONDS = 30
+const REFRESH_INTERVAL_MS = AUTO_REFRESH_INTERVAL_SECONDS * 1000
+
+interface RefreshStatsButtonProps {
+ onRefresh: (isManual: boolean) => Promise<void>
+}
+
+export const RefreshStatsButton = ({ onRefresh }: RefreshStatsButtonProps) => {
+ const { isLoading: authLoading } = useAuth()
+ const { dataLoading } = useViewProjectContext()
+ const { t } = useTranslation('common')
+ const [progress, setProgress] = useState(0)
+ const [isRefreshing, setIsRefreshing] = useState(false)
+ const startTimeRef = useRef(Date.now())
+ const hasTriggeredRefresh = useRef(false)
+
+ useEffect(() => {
+ let animationFrameId: number
+
+ const animate = () => {
+ const elapsed = Date.now() - startTimeRef.current
+ const newProgress = Math.min((elapsed / REFRESH_INTERVAL_MS) * 100, 100)
+ setProgress(newProgress)
+
+ // Check if we should trigger auto-refresh
+ if (newProgress >= 100 && !hasTriggeredRefresh.current && !isRefreshing && !authLoading && !dataLoading) {
+ hasTriggeredRefresh.current = true
+ ;(async () => {
+ setIsRefreshing(true)
+ await onRefresh(false)
+ setIsRefreshing(false)
+ // Reset timer after refresh completes
+ startTimeRef.current = Date.now()
+ hasTriggeredRefresh.current = false
+ setProgress(0)
+ })()
+ }
+
+ animationFrameId = requestAnimationFrame(animate)
+ }
+
+ animationFrameId = requestAnimationFrame(animate)
+
+ return () => cancelAnimationFrame(animationFrameId)
+ }, [onRefresh, isRefreshing, authLoading, dataLoading])
+
+ const handleManualRefresh = async () => {
+ if (authLoading || dataLoading || isRefreshing) return
+ setIsRefreshing(true)
+ startTimeRef.current = Date.now()
+ hasTriggeredRefresh.current = false
+ setProgress(0)
+ await onRefresh(true)
+ setIsRefreshing(false)
+ }
+
+ const remainingSeconds = Math.max(1, Math.ceil(AUTO_REFRESH_INTERVAL_SECONDS * (1 - progress / 100)))
+ const showSpinner = isRefreshing || dataLoading
+
+ return (
+ <button
+ type='button'
+ title={t('project.refreshStats')}
+ onClick={handleManualRefresh}
+ className={cn(
+ 'group relative rounded-md border border-transparent bg-gray-50 p-2 hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:bg-slate-900 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
+ {
+ 'cursor-not-allowed opacity-50': authLoading,
+ },
+ )}
+ >
+ <div className='relative h-5 w-5'>
+ <RotateCw
+ className={cn('absolute inset-0 h-5 w-5 text-gray-400/80 dark:text-slate-600', {
+ 'animate-spin': showSpinner,
+ })}
+ />
+ {!showSpinner ? (
+ <div
+ className='absolute inset-0'
+ style={{
+ maskImage: `conic-gradient(from 80deg, black ${progress}%, transparent ${progress}%)`,
+ WebkitMaskImage: `conic-gradient(from 80deg, black ${progress}%, transparent ${progress}%)`,
+ }}
+ >
+ <RotateCw className='h-5 w-5 text-gray-700 dark:text-gray-50' />
+ </div>
+ ) : null}
+ {showSpinner ? (
+ <RotateCw className='absolute inset-0 h-5 w-5 animate-spin text-gray-700 dark:text-gray-50' />
+ ) : null}
+ </div>
+ <div className='pointer-events-none absolute bottom-full left-1/2 mb-2 -translate-x-1/2 rounded bg-gray-900 px-2 py-1 text-xs whitespace-nowrap text-white opacity-0 transition-opacity group-hover:opacity-100 dark:bg-slate-700'>
+ {showSpinner ? t('project.refreshing') : t('project.refreshingIn', { seconds: remainingSeconds })}
+ <div className='absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-gray-900 dark:border-t-slate-700' />
+ </div>
+ </button>
+ )
+}
diff --git a/web/public/locales/de.json b/web/public/locales/de.json
index 330ccd619..90b34cda9 100644
--- a/web/public/locales/de.json
+++ b/web/public/locales/de.json
@@ -1127,6 +1127,8 @@
"markAsActive": "Als aktiv markieren",
"refreshStats": "Statistiken aktualisieren",
"refresh": "Aktualisieren",
+ "refreshingIn": "Aktualisierung in {{seconds}} Sekunden",
+ "refreshing": "Aktualisieren...",
"resetZoom": "Zoom zurücksetzen",
"noEventsForSelectedPeriod": "Für den ausgewählten Zeitraum sind keine Ereignisse vorhanden.",
"barChart": "Balkendiagramm",
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index b30d6f27c..fe0c9d0a9 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -1127,6 +1127,8 @@
"markAsActive": "Mark as active",
"refreshStats": "Refresh stats",
"refresh": "Refresh",
+ "refreshingIn": "Refreshing in {{seconds}} seconds",
+ "refreshing": "Refreshing...",
"resetZoom": "Reset zoom",
"noEventsForSelectedPeriod": "There are no events for the selected time period.",
"barChart": "Bar chart",
diff --git a/web/public/locales/fr.json b/web/public/locales/fr.json
index 82dbdfa56..70c9f6c81 100644
--- a/web/public/locales/fr.json
+++ b/web/public/locales/fr.json
@@ -1127,6 +1127,8 @@
"markAsActive": "Marquer comme actif",
"refreshStats": "Actualiser les statistiques",
"refresh": "Actualiser",
+ "refreshingIn": "Actualisation dans {{seconds}} secondes",
+ "refreshing": "Actualisation...",
"resetZoom": "Réinitialiser le zoom",
"noEventsForSelectedPeriod": "Il n'y a pas d'événements pour la période sélectionnée.",
"barChart": "Graphique en barres",
diff --git a/web/public/locales/pl.json b/web/public/locales/pl.json
index 1047d26bf..bc5d658ca 100644
--- a/web/public/locales/pl.json
+++ b/web/public/locales/pl.json
@@ -1127,6 +1127,8 @@
"markAsActive": "Oznacz jako aktywne",
"refreshStats": "Odśwież statystyki",
"refresh": "Odśwież",
+ "refreshingIn": "Odświeżanie za {{seconds}} sek.",
+ "refreshing": "Odświeżanie...",
"resetZoom": "Resetuj powiększenie",
"noEventsForSelectedPeriod": "Brak zdarzeń dla wybranego przedziału czasowego.",
"barChart": "Wykres słupkowy",
diff --git a/web/public/locales/uk.json b/web/public/locales/uk.json
index 0a11db1b7..a61d55368 100644
--- a/web/public/locales/uk.json
+++ b/web/public/locales/uk.json
@@ -1127,6 +1127,8 @@
"markAsActive": "Позначити як активну",
"refreshStats": "Оновити статистику",
"refresh": "Оновити",
+ "refreshingIn": "Оновлення через {{seconds}} секунди",
+ "refreshing": "Оновлення...",
"resetZoom": "Скинути масштаб",
"noEventsForSelectedPeriod": "Немає подій за вибраний період часу.",
"barChart": "Гістограма",