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!

fix: analytics comparison features

Blue Mousef1450a9c5165
diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsx
index f3beec6fa..db53e21e0 100644
--- a/web/app/pages/Project/View/ViewProject.helpers.tsx
+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx
@@ -873,108 +873,94 @@ const getSettings = (
).join('')}</ul>`
}
- return `
- <ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-800 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-lg z-50'>
+ // Get dates from first item
+ const firstItem = item[0]
+ const firstIndex = firstItem?.index ?? 0
+ const currentX = firstItem?.x as Date | string | undefined
+ const currentDate = currentX
+ ? (currentX instanceof Date ? currentX : new Date(currentX))
+ : null
+ const compareDate = compareChart?.x?.[firstIndex]
+
+ const xDataValue = currentDate
+ ? (timeFormat === TimeFormat['24-hour']
+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(currentDate)
+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(currentDate))
+ : ''
+ const xDataValueCompare = compareDate
+ ? (timeFormat === TimeFormat['24-hour']
+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
+ dayjs(compareDate).toDate(),
+ )
+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
+ dayjs(compareDate).toDate(),
+ ))
+ : ''
+
+ // Filter out compare series items
+ const filteredItems = item.filter(
+ (el: { id: string }) =>
+ el.id !== 'uniqueCompare' &&
+ el.id !== 'totalCompare' &&
+ el.id !== 'bounceCompare' &&
+ el.id !== 'sessionDurationCompare',
+ )
+
+ // Build current period section
+ const currentSection = `
+ <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-gray-600'>${xDataValue}</li>
${_map(
- item,
- (el: {
- id: string
- index: number
- name: string
- value: string
- x: Date
- }) => {
- const { id, index, name, value, x } = el
+ filteredItems,
+ (el: { id: string; name: string; value: string }) => {
+ const displayValue =
+ el.id === 'sessionDuration'
+ ? getStringFromTime(getTimeFromSeconds(el.value))
+ : el.value
+ return `
+ <li class='flex justify-between items-center py-px leading-snug'>
+ <div class='flex items-center min-w-0 mr-4'>
+ <div class='w-2.5 h-2.5 rounded-xs mr-1.5 shrink-0' style='background-color:${color(el.id)}'></div>
+ <span class="truncate">${el.name}</span>
+ </div>
+ <span class='font-mono whitespace-nowrap'>${displayValue}</span>
+ </li>`
+ },
+ ).join('')}`
- const xDataValueCompare =
- timeFormat === TimeFormat['24-hour']
- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
- dayjs(compareChart?.x[index]).toDate(),
- )
- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
- dayjs(compareChart?.x[index]).toDate(),
- )
- const xDataValue =
- timeFormat === TimeFormat['24-hour']
- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
- x as unknown as Date,
- )
- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
- x as unknown as Date,
- )
- const valueCompare =
- id === 'sessionDuration'
+ // Build compare period section
+ const compareSection = xDataValueCompare
+ ? `
+ <li class='font-semibold pb-1 mb-1 mt-3 pt-2 border-t border-b border-gray-200 dark:border-gray-600'>${xDataValueCompare}</li>
+ ${_map(
+ filteredItems,
+ (el: { id: string; index: number; name: string }) => {
+ const compareValue =
+ el.id === 'sessionDuration'
? getStringFromTime(
getTimeFromSeconds(
- compareChart?.[typesOptionsToTypesCompare?.[id]]?.[
- index
+ compareChart?.[typesOptionsToTypesCompare?.[el.id]]?.[
+ el.index
],
),
)
- : compareChart?.[typesOptionsToTypesCompare[id]]?.[index]
-
- if (
- id === 'uniqueCompare' ||
- id === 'totalCompare' ||
- id === 'bounceCompare' ||
- id === 'sessionDurationCompare'
- ) {
- return ''
- }
-
- if (id === 'sessionDuration') {
- return `
- <div class='flex justify-between items-center py-px leading-snug'>
- <div class='flex items-center min-w-0 mr-4'>
- <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(id)}></div>
- <span class="truncate">${name}</span>
- </div>
- </div>
- <hr class='border-gray-200 dark:border-gray-600 my-1' />
- <li class='ml-2 mb-2'>
- <p class='flex justify-between'>
- <span class="mr-2">${xDataValue}</span> -
- <span class='font-mono whitespace-nowrap'>${getStringFromTime(getTimeFromSeconds(value))}</span>
- </p>
- ${
- valueCompare &&
- Number(
- compareChart?.[typesOptionsToTypesCompare?.[id]]?.[index],
- ) > 0
- ? `<p class='flex justify-between'>
- <span class="mr-2">${xDataValueCompare}</span> -
- <span class='font-mono whitespace-nowrap'>${valueCompare}</span>
- </p>`
- : ''
- }
- </li>
- `
- }
-
+ : compareChart?.[typesOptionsToTypesCompare[el.id]]?.[el.index]
+ if (compareValue === undefined || compareValue === null) return ''
return `
- <div class='flex justify-between items-center py-px leading-snug'>
- <div class='flex items-center min-w-0 mr-4'>
- <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(id)}></div>
- <span class="truncate">${name}</span>
- </div>
- </div>
- <hr class='border-gray-200 dark:border-gray-600 my-1' />
- <li class='ml-2 mb-2'>
- <p class='flex justify-between'>
- <span class="mr-2">${xDataValue}</span> - <span class='font-mono whitespace-nowrap'>${value}</span>
- </p>
- ${
- valueCompare
- ? `<p class='flex justify-between'>
- <span class="mr-2">${xDataValueCompare}</span> -
- <span class='font-mono whitespace-nowrap'>${valueCompare}</span>
- </p>`
- : ''
- }
- </li>
- `
+ <li class='flex justify-between items-center py-px leading-snug'>
+ <div class='flex items-center min-w-0 mr-4'>
+ <div class='w-2.5 h-2.5 rounded-xs mr-1.5 shrink-0 opacity-60' style='background-color:${color(el.id)}'></div>
+ <span class="truncate opacity-75">${el.name}</span>
+ </div>
+ <span class='font-mono whitespace-nowrap opacity-75'>${compareValue}</span>
+ </li>`
},
- ).join('')}
+ ).join('')}`
+ : ''
+
+ return `
+ <ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-800 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-lg z-50'>
+ ${currentSection}
+ ${compareSection}
</ul>`
},
},
@@ -1988,69 +1974,81 @@ const getSettingsPerf = (
).join('')}</ul>`
}
- return `
- <ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-800 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-lg z-50'>
- ${_map(
- item,
- (el: {
- id: string
- index: number
- name: string
- value: string
- x: Date
- }) => {
- const { id, index, name, value, x } = el
+ // Get dates from first item
+ const firstItem = item[0]
+ const firstIndex = firstItem?.index ?? 0
+ const currentX = firstItem?.x as Date | string | undefined
+ const currentDate = currentX
+ ? (currentX instanceof Date ? currentX : new Date(currentX))
+ : null
+ const compareDate = compareChart?.x?.[firstIndex]
+
+ const xDataValue = currentDate
+ ? (timeFormat === TimeFormat['24-hour']
+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(currentDate)
+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(currentDate))
+ : ''
+ const xDataValueCompare = compareDate
+ ? (timeFormat === TimeFormat['24-hour']
+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
+ dayjs(compareDate).toDate(),
+ )
+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
+ dayjs(compareDate).toDate(),
+ ))
+ : ''
- const xDataValueCompare =
- timeFormat === TimeFormat['24-hour']
- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
- dayjs(compareChart?.x[index]).toDate(),
- )
- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
- dayjs(compareChart?.x[index]).toDate(),
- )
- const xDataValue =
- timeFormat === TimeFormat['24-hour']
- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
- x as unknown as Date,
- )
- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
- x as unknown as Date,
- )
- const valueCompare = getValueForTooltipPerfomance(
- compareChart,
- id,
- index,
- )
+ // Filter out compare series items
+ const filteredItems = item.filter(
+ (el: { id: string }) => !_includes(perfomanceChartCompare, el.id),
+ )
- if (_includes(perfomanceChartCompare, id)) {
- return ''
- }
+ // Build current period section
+ const currentSection = `
+ <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-gray-600'>${xDataValue}</li>
+ ${_map(
+ filteredItems,
+ (el: { id: string; name: string; value: string }) => {
+ return `
+ <li class='flex justify-between items-center py-px leading-snug'>
+ <div class='flex items-center min-w-0 mr-4'>
+ <div class='w-2.5 h-2.5 rounded-xs mr-1.5 shrink-0' style='background-color:${color(el.id)}'></div>
+ <span class="truncate">${el.name}</span>
+ </div>
+ <span class='font-mono whitespace-nowrap'>${getStringFromTime(getTimeFromSeconds(el.value), true)}</span>
+ </li>`
+ },
+ ).join('')}`
- return `
- <div class='flex justify-between items-center py-px leading-snug'>
- <div class='flex items-center min-w-0 mr-4'>
- <div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(id)}></div>
- <span class="truncate">${name}</span>
- </div>
- </div>
- <hr class='border-gray-200 dark:border-gray-600 my-1' />
- <li class='ml-2 mb-2'>
- <p class='flex justify-between'>
- <span class="mr-2">${xDataValue}</span> - <span class='font-mono whitespace-nowrap'>${getStringFromTime(getTimeFromSeconds(value), true)}</span>
- </p>
- ${
- valueCompare
- ? `<p class='flex justify-between'>
- <span class="mr-2">${xDataValueCompare}</span> -
- <span class='font-mono whitespace-nowrap'>${getStringFromTime(getTimeFromSeconds(valueCompare), true)}</span>
- </p>`
- : ''
- }
- </li>
- `
- },
- ).join('')}
+ // Build compare period section
+ const compareSection = xDataValueCompare
+ ? `
+ <li class='font-semibold pb-1 mb-1 mt-3 pt-2 border-t border-b border-gray-200 dark:border-gray-600'>${xDataValueCompare}</li>
+ ${_map(
+ filteredItems,
+ (el: { id: string; index: number; name: string }) => {
+ const compareValue = getValueForTooltipPerfomance(
+ compareChart,
+ el.id,
+ el.index,
+ )
+ if (compareValue === undefined || compareValue === null) return ''
+ return `
+ <li class='flex justify-between items-center py-px leading-snug'>
+ <div class='flex items-center min-w-0 mr-4'>
+ <div class='w-2.5 h-2.5 rounded-xs mr-1.5 shrink-0 opacity-60' style='background-color:${color(el.id)}'></div>
+ <span class="truncate opacity-75">${el.name}</span>
+ </div>
+ <span class='font-mono whitespace-nowrap opacity-75'>${getStringFromTime(getTimeFromSeconds(compareValue), true)}</span>
+ </li>`
+ },
+ ).join('')}`
+ : ''
+
+ return `
+ <ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-800 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-lg z-50'>
+ ${currentSection}
+ ${compareSection}
</ul>`
},
},
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 1d962f877..d55a447a0 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -366,7 +366,22 @@ const ViewProjectContent = () => {
return preferences.period || '7d'
}, [searchParams, preferences.period])
- const [dateRangeCompare, setDateRangeCompare] = useState<null | Date[]>(null)
+ // Extract compare params from URL early (needed for state initialization)
+ const urlCompareEnabled = searchParams.get('compare') === 'true'
+ const urlCompareFrom = searchParams.get('compareFrom')
+ const urlCompareTo = searchParams.get('compareTo')
+
+ // Initialize dateRangeCompare from URL params if available
+ const [dateRangeCompare, setDateRangeCompare] = useState<null | Date[]>(() => {
+ if (urlCompareFrom && urlCompareTo) {
+ const fromDate = new Date(urlCompareFrom)
+ const toDate = new Date(urlCompareTo)
+ if (!Number.isNaN(fromDate.getTime()) && !Number.isNaN(toDate.getTime())) {
+ return [fromDate, toDate]
+ }
+ }
+ return null
+ })
const dateRange = useMemo<Date[] | null>(() => {
if (period !== 'custom') {
@@ -541,11 +556,25 @@ const ViewProjectContent = () => {
period: string
}[]
>(tbPeriodPairsCompare(t, undefined, language))
+
+ // Initialize compare state from URL params or localStorage
const [isActiveCompare, setIsActiveCompare] = useState(
- getItem(LS_IS_ACTIVE_COMPARE_KEY) === 'true',
+ urlCompareEnabled || getItem(LS_IS_ACTIVE_COMPARE_KEY) === 'true',
)
+
+ // Determine initial activePeriodCompare based on URL params
+ const getInitialActivePeriodCompare = () => {
+ if (urlCompareFrom && urlCompareTo) {
+ return 'custom'
+ }
+ if (urlCompareEnabled) {
+ return 'previous'
+ }
+ return 'previous'
+ }
+
const [activePeriodCompare, setActivePeriodCompare] = useState(
- periodPairsCompare[0].period,
+ getInitialActivePeriodCompare(),
)
const maxRangeCompare = useMemo(() => {
if (!isActiveCompare) {
@@ -561,6 +590,92 @@ const ViewProjectContent = () => {
return findActivePeriod?.countDays || 0
}, [isActiveCompare, period, dateRange, periodPairs])
+ // Sync compare state to URL params for SSR data fetching
+ useEffect(() => {
+ const newSearchParams = new URLSearchParams(searchParams.toString())
+ let shouldUpdate = false
+
+ if (isActiveCompare) {
+ // Set compare=true in URL
+ if (newSearchParams.get('compare') !== 'true') {
+ newSearchParams.set('compare', 'true')
+ shouldUpdate = true
+ }
+
+ // Calculate compare dates
+ let compareFrom: string | null = null
+ let compareTo: string | null = null
+
+ if (activePeriodCompare === 'previous') {
+ // Calculate previous period dates based on current period
+ const currentActivePeriod = _find(periodPairs, (p) => p.period === period)
+
+ if (period === 'custom' && dateRange) {
+ // For custom period, calculate the same duration before the start date
+ const from = dayjs.utc(dateRange[0])
+ const to = dayjs.utc(dateRange[1])
+ const daysDiff = to.diff(from, 'day') + 1
+
+ const prevTo = from.subtract(1, 'day')
+ const prevFrom = prevTo.subtract(daysDiff - 1, 'day')
+
+ compareFrom = prevFrom.format('YYYY-MM-DD')
+ compareTo = prevTo.format('YYYY-MM-DD')
+ } else if (currentActivePeriod?.countDays) {
+ // For preset periods, use countDays to calculate previous period
+ const now = dayjs.utc()
+ const periodDays = currentActivePeriod.countDays
+
+ // Current period: (now - periodDays) to now
+ // Previous period: (now - 2*periodDays) to (now - periodDays - 1)
+ const prevTo = now.subtract(periodDays, 'day').subtract(1, 'day')
+ const prevFrom = prevTo.subtract(periodDays - 1, 'day')
+
+ compareFrom = prevFrom.format('YYYY-MM-DD')
+ compareTo = prevTo.format('YYYY-MM-DD')
+ }
+ } else if (activePeriodCompare === 'custom' && dateRangeCompare) {
+ // Use custom compare date range
+ compareFrom = dayjs.utc(dateRangeCompare[0]).format('YYYY-MM-DD')
+ compareTo = dayjs.utc(dateRangeCompare[1]).format('YYYY-MM-DD')
+ }
+
+ if (compareFrom && compareTo) {
+ if (newSearchParams.get('compareFrom') !== compareFrom) {
+ newSearchParams.set('compareFrom', compareFrom)
+ shouldUpdate = true
+ }
+ if (newSearchParams.get('compareTo') !== compareTo) {
+ newSearchParams.set('compareTo', compareTo)
+ shouldUpdate = true
+ }
+ }
+ } else {
+ // Remove compare params from URL when compare is disabled
+ if (newSearchParams.has('compare')) {
+ newSearchParams.delete('compare')
+ shouldUpdate = true
+ }
+ if (newSearchParams.has('compareFrom')) {
+ newSearchParams.delete('compareFrom')
+ shouldUpdate = true
+ }
+ if (newSearchParams.has('compareTo')) {
+ newSearchParams.delete('compareTo')
+ shouldUpdate = true
+ }
+ }
+
+ if (shouldUpdate) {
+ setSearchParams(newSearchParams)
+ }
+ }, [isActiveCompare, activePeriodCompare, dateRangeCompare, period, dateRange, periodPairs, searchParams, setSearchParams])
+
+ // Persist isActiveCompare to localStorage
+ useEffect(() => {
+ setItem(LS_IS_ACTIVE_COMPARE_KEY, isActiveCompare ? 'true' : 'false')
+ }, [isActiveCompare])
+
useEffect(() => {
if (!project) {
return