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!

move funnels stuff to a separate component

Blue Mouse1533cf6f9acc
diff --git a/web/app/pages/Project/Funnels/View/FunnelsView.tsx b/web/app/pages/Project/Funnels/View/FunnelsView.tsx
new file mode 100644
index 000000000..1d9c3f3b7
--- /dev/null
+++ b/web/app/pages/Project/Funnels/View/FunnelsView.tsx
@@ -0,0 +1,459 @@
+import cx from 'clsx'
+import _filter from 'lodash/filter'
+import _find from 'lodash/find'
+import _includes from 'lodash/includes'
+import _isEmpty from 'lodash/isEmpty'
+import { ChevronLeftIcon, FilterIcon } from 'lucide-react'
+import { useState, useEffect, useMemo, useRef } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Link, useSearchParams } from 'react-router'
+import { toast } from 'sonner'
+
+import { addFunnel, updateFunnel, deleteFunnel, getFunnelData, getFunnels } from '~/api'
+import { MAX_MONTHS_IN_PAST, FUNNELS_PERIOD_PAIRS } from '~/lib/constants'
+import { Funnel, AnalyticsFunnel } from '~/lib/models/Project'
+import NewFunnel from '~/modals/NewFunnel'
+import { FunnelChart } from '~/pages/Project/View/components/FunnelChart'
+import FunnelsList from '~/pages/Project/View/components/FunnelsList'
+import { RefreshStatsButton } from '~/pages/Project/View/components/RefreshStatsButton'
+import TBPeriodSelector from '~/pages/Project/View/components/TBPeriodSelector'
+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'
+import { useAuth } from '~/providers/AuthProvider'
+import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import DatePicker from '~/ui/Datepicker'
+import Loader from '~/ui/Loader'
+import { Text } from '~/ui/Text'
+import { nLocaleFormatter } from '~/utils/generic'
+import routes from '~/utils/routes'
+
+const FunnelsView = () => {
+ const { id, project, mergeProject, allowedToManage } = useCurrentProject()
+ const projectPassword = useProjectPassword(id)
+ const { isAuthenticated } = useAuth()
+ const { timezone, period, dateRange, activePeriod, periodPairs, updatePeriod, refCalendar, funnelsRefreshTrigger } =
+ useViewProjectContext()
+
+ // Filter periods to only include those valid for funnels
+ const timeBucketSelectorItems = useMemo(() => {
+ return _filter(periodPairs, (el) => {
+ return _includes(FUNNELS_PERIOD_PAIRS, el.period)
+ })
+ }, [periodPairs])
+ const { t } = useTranslation('common')
+ const [searchParams, setSearchParams] = useSearchParams()
+
+ const isMountedRef = useRef(true)
+
+ // Funnels state
+ const [isNewFunnelOpened, setIsNewFunnelOpened] = useState(false)
+ const [funnelToEdit, setFunnelToEdit] = useState<Funnel | undefined>(undefined)
+ const [funnelActionLoading, setFunnelActionLoading] = useState(false)
+ const [dataLoading, setDataLoading] = useState(false)
+ const [analyticsLoading, setAnalyticsLoading] = useState(true)
+ const [funnelAnalytics, setFunnelAnalytics] = useState<{
+ funnel: AnalyticsFunnel[]
+ totalPageviews: number
+ } | null>(null)
+
+ // Search params without the funnel id. Needed for the back button.
+ const pureSearchParams = useMemo(() => {
+ const newSearchParams = new URLSearchParams(searchParams.toString())
+ newSearchParams.delete('funnelId')
+ return newSearchParams.toString()
+ }, [searchParams])
+
+ // Get active funnel from URL
+ const activeFunnel = useMemo(() => {
+ if (!project) {
+ return null
+ }
+
+ const funnelId = searchParams.get('funnelId')
+
+ if (!funnelId) {
+ return null
+ }
+
+ return _find(project.funnels, (funnel) => funnel.id === funnelId) || null
+ }, [searchParams, project])
+
+ // Cleanup on unmount
+ useEffect(() => {
+ isMountedRef.current = true
+ return () => {
+ isMountedRef.current = false
+ }
+ }, [])
+
+ const onFunnelCreate = async (name: string, steps: string[]) => {
+ if (funnelActionLoading) {
+ return
+ }
+
+ setFunnelActionLoading(true)
+
+ try {
+ await addFunnel(id, name, steps)
+ } catch (reason: any) {
+ console.error('[ERROR] (onFunnelCreate)(addFunnel)', reason)
+ toast.error(reason)
+ }
+
+ try {
+ const funnels = await getFunnels(id, projectPassword)
+ mergeProject({ funnels })
+ } catch (reason: any) {
+ console.error('[ERROR] (onFunnelCreate)(getFunnels)', reason)
+ }
+
+ toast.success(t('apiNotifications.funnelCreated'))
+ setFunnelActionLoading(false)
+ }
+
+ const onFunnelEdit = async (funnelId: string, name: string, steps: string[]) => {
+ if (funnelActionLoading) {
+ return
+ }
+
+ setFunnelActionLoading(true)
+
+ try {
+ await updateFunnel(funnelId, id, name, steps)
+ } catch (reason: any) {
+ console.error('[ERROR] (onFunnelEdit)(updateFunnel)', reason)
+ toast.error(reason)
+ }
+
+ try {
+ const funnels = await getFunnels(id, projectPassword)
+ mergeProject({ funnels })
+ } catch (reason: any) {
+ console.error('[ERROR] (onFunnelEdit)(getFunnels)', reason)
+ }
+
+ toast.success(t('apiNotifications.funnelUpdated'))
+ setFunnelActionLoading(false)
+ }
+
+ const onFunnelDelete = async (funnelId: string) => {
+ if (funnelActionLoading) {
+ return
+ }
+
+ setFunnelActionLoading(true)
+
+ try {
+ await deleteFunnel(funnelId, id)
+ } catch (reason: any) {
+ console.error('[ERROR] (onFunnelDelete)(deleteFunnel)', reason)
+ toast.error(reason)
+ }
+
+ try {
+ const funnels = await getFunnels(id, projectPassword)
+ mergeProject({ funnels })
+ } catch (reason: any) {
+ console.error('[ERROR] (onFunnelDelete)(getFunnels)', reason)
+ }
+
+ toast.success(t('apiNotifications.funnelDeleted'))
+ setFunnelActionLoading(false)
+ }
+
+ const loadFunnelsData = async () => {
+ if (!activeFunnel?.id) {
+ return
+ }
+
+ setDataLoading(true)
+
+ try {
+ let dataFunnel: { funnel: AnalyticsFunnel[]; totalPageviews: number }
+ let from
+ let to
+
+ if (dateRange) {
+ from = getFormatDate(dateRange[0])
+ to = getFormatDate(dateRange[1])
+ }
+
+ if (period === 'custom' && dateRange) {
+ dataFunnel = await getFunnelData(id, '', from, to, timezone, activeFunnel.id, projectPassword)
+ } else {
+ dataFunnel = await getFunnelData(id, period, '', '', timezone, activeFunnel.id, projectPassword)
+ }
+
+ const { funnel, totalPageviews } = dataFunnel
+
+ if (isMountedRef.current) {
+ setFunnelAnalytics({ funnel, totalPageviews })
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ }
+ } catch (reason) {
+ if (isMountedRef.current) {
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ console.error('[ERROR](loadFunnelsData) Loading funnels data failed:', reason)
+ }
+ }
+ }
+
+ const funnelSummary = useMemo(() => {
+ if (!funnelAnalytics || _isEmpty(funnelAnalytics.funnel)) {
+ return null
+ }
+
+ const stepsCount = funnelAnalytics.funnel.length
+ const startVisitors = funnelAnalytics.funnel[0]?.events || 0
+ const endVisitors = funnelAnalytics.funnel[stepsCount - 1]?.events || 0
+ const conversionRate = Number(((endVisitors / Math.max(startVisitors, 1)) * 100).toFixed(2))
+
+ return {
+ stepsCount,
+ startVisitors,
+ endVisitors,
+ conversionRate,
+ }
+ }, [funnelAnalytics])
+
+ const refreshStats = async (_isManual: boolean = true) => {
+ if (!dataLoading) {
+ await loadFunnelsData()
+ }
+ }
+
+ const resetDateRange = () => {
+ const newSearchParams = new URLSearchParams(searchParams.toString())
+ newSearchParams.delete('from')
+ newSearchParams.delete('to')
+ setSearchParams(newSearchParams)
+ }
+
+ // Load funnels data when activeFunnel changes
+ useEffect(() => {
+ if (!project) return
+
+ loadFunnelsData()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [activeFunnel, project, dateRange, period])
+
+ // Handle refresh trigger from parent
+ useEffect(() => {
+ if (funnelsRefreshTrigger > 0) {
+ loadFunnelsData()
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [funnelsRefreshTrigger])
+
+ // Show loader during initial load when viewing a specific funnel
+ if (activeFunnel && analyticsLoading) {
+ return <Loader />
+ }
+
+ // Render funnel detail view
+ if (activeFunnel) {
+ return (
+ <>
+ {/* Funnel Header */}
+ <div className='relative top-0 z-20 -mt-2 flex flex-col items-center justify-between bg-gray-50/50 py-2 backdrop-blur-md lg:sticky lg:flex-row dark:bg-slate-900/50'>
+ <div className='flex flex-wrap items-center justify-center gap-2'>
+ <Text as='h2' size='xl' weight='bold' className='break-words break-all'>
+ {activeFunnel?.name}
+ </Text>
+ </div>
+ <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'>
+ <RefreshStatsButton onRefresh={refreshStats} />
+ <div className='flex items-center'>
+ <TBPeriodSelector
+ activePeriod={activePeriod}
+ items={timeBucketSelectorItems}
+ title={activePeriod?.label}
+ onSelect={(pair) => {
+ if (dataLoading) {
+ return
+ }
+
+ if (pair.isCustomDate) {
+ setTimeout(() => {
+ refCalendar.current?.openCalendar?.()
+ }, 100)
+ } else {
+ resetDateRange()
+ updatePeriod(pair)
+ }
+ }}
+ />
+ <DatePicker
+ ref={refCalendar}
+ onChange={([from, to]) => {
+ const newSearchParams = new URLSearchParams(searchParams.toString())
+ newSearchParams.set('from', from.toISOString())
+ newSearchParams.set('to', to.toISOString())
+ newSearchParams.set('period', 'custom')
+ setSearchParams(newSearchParams)
+ }}
+ value={dateRange || []}
+ maxDateMonths={MAX_MONTHS_IN_PAST}
+ maxRange={0}
+ />
+ </div>
+ </div>
+ </div>
+
+ {/* Back to funnels link */}
+ <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.backToFunnels')}
+ </Link>
+ </div>
+
+ {/* Funnel Chart */}
+ <div
+ className={cx(
+ 'relative overflow-hidden rounded-lg border border-gray-300 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-800/25',
+ { hidden: analyticsLoading },
+ )}
+ >
+ {funnelSummary ? (
+ <>
+ <p className='font-medium text-gray-900 lg:text-left dark:text-gray-50'>
+ {t('project.funnelSummary.xStepFunnel', { x: funnelSummary.stepsCount })}
+ <span className='mx-2 text-gray-400'>•</span>
+ {t('project.funnelSummary.conversionRateShort', { x: funnelSummary.conversionRate })}
+ </p>
+ <p className='text-center text-gray-900 lg:text-left dark:text-gray-50'>
+ {t('project.funnelSummary.startShort')}: {nLocaleFormatter(funnelSummary.startVisitors)}
+ <span className='mx-1'>→</span>
+ {t('project.funnelSummary.endShort')}: {nLocaleFormatter(funnelSummary.endVisitors)}
+ </p>
+ </>
+ ) : null}
+ {funnelAnalytics?.funnel ? (
+ <FunnelChart
+ funnel={funnelAnalytics.funnel}
+ totalPageviews={funnelAnalytics.totalPageviews}
+ t={t}
+ className='mt-5 h-80 [&_svg]:!overflow-visible'
+ />
+ ) : null}
+ </div>
+
+ {/* New Funnel Modal */}
+ <NewFunnel
+ funnel={funnelToEdit}
+ isOpened={isNewFunnelOpened}
+ onClose={() => {
+ setIsNewFunnelOpened(false)
+ setFunnelToEdit(undefined)
+ }}
+ onSubmit={async (name: string, steps: string[]) => {
+ if (funnelToEdit) {
+ await onFunnelEdit(funnelToEdit.id, name, steps)
+ return
+ }
+
+ await onFunnelCreate(name, steps)
+ }}
+ loading={funnelActionLoading}
+ />
+ </>
+ )
+ }
+
+ // Render funnels list view
+ if (!_isEmpty(project?.funnels)) {
+ return (
+ <>
+ <FunnelsList
+ openFunnelSettings={(funnel?: Funnel) => {
+ if (funnel) {
+ setFunnelToEdit(funnel)
+ setIsNewFunnelOpened(true)
+ return
+ }
+
+ setIsNewFunnelOpened(true)
+ }}
+ funnels={project?.funnels}
+ deleteFunnel={onFunnelDelete}
+ loading={funnelActionLoading}
+ allowedToManage={allowedToManage}
+ />
+ <NewFunnel
+ funnel={funnelToEdit}
+ isOpened={isNewFunnelOpened}
+ onClose={() => {
+ setIsNewFunnelOpened(false)
+ setFunnelToEdit(undefined)
+ }}
+ onSubmit={async (name: string, steps: string[]) => {
+ if (funnelToEdit) {
+ await onFunnelEdit(funnelToEdit.id, name, steps)
+ return
+ }
+
+ await onFunnelCreate(name, steps)
+ }}
+ loading={funnelActionLoading}
+ />
+ </>
+ )
+ }
+
+ // Render empty state
+ return (
+ <>
+ <div className='mt-5 rounded-xl bg-gray-700 p-5'>
+ <div className='flex items-center text-gray-50'>
+ <FilterIcon className='mr-2 h-8 w-8' strokeWidth={1.5} />
+ <p className='text-3xl font-bold'>{t('dashboard.funnels')}</p>
+ </div>
+ <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>{t('dashboard.funnelsDesc')}</p>
+ {isAuthenticated ? (
+ <button
+ type='button'
+ onClick={() => setIsNewFunnelOpened(true)}
+ className='mt-6 block max-w-max rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium text-slate-900 hover:bg-indigo-50 md:px-4'
+ >
+ {t('dashboard.newFunnel')}
+ </button>
+ ) : (
+ <Link
+ to={routes.signup}
+ className='mt-6 block max-w-max rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium text-slate-900 hover:bg-indigo-50 md:px-4'
+ aria-label={t('titles.signup')}
+ >
+ {t('header.startForFree')}
+ </Link>
+ )}
+ </div>
+ <NewFunnel
+ funnel={funnelToEdit}
+ isOpened={isNewFunnelOpened}
+ onClose={() => {
+ setIsNewFunnelOpened(false)
+ setFunnelToEdit(undefined)
+ }}
+ onSubmit={async (name: string, steps: string[]) => {
+ if (funnelToEdit) {
+ await onFunnelEdit(funnelToEdit.id, name, steps)
+ return
+ }
+
+ await onFunnelCreate(name, steps)
+ }}
+ loading={funnelActionLoading}
+ />
+ </>
+ )
+}
+
+export default FunnelsView
diff --git a/web/app/pages/Project/Funnels/View/index.tsx b/web/app/pages/Project/Funnels/View/index.tsx
new file mode 100644
index 000000000..27bd315c5
--- /dev/null
+++ b/web/app/pages/Project/Funnels/View/index.tsx
@@ -0,0 +1 @@
+export { default } from './FunnelsView'
diff --git a/web/app/pages/Project/Traffic/View/TrafficView.tsx b/web/app/pages/Project/Traffic/View/TrafficView.tsx
new file mode 100644
index 000000000..33adf6771
--- /dev/null
+++ b/web/app/pages/Project/Traffic/View/TrafficView.tsx
@@ -0,0 +1,1150 @@
+import cx from 'clsx'
+import dayjs from 'dayjs'
+import _filter from 'lodash/filter'
+import _find from 'lodash/find'
+import _includes from 'lodash/includes'
+import _isEmpty from 'lodash/isEmpty'
+import _keys from 'lodash/keys'
+import _map from 'lodash/map'
+import _some from 'lodash/some'
+import { BanIcon, ChartColumnBigIcon, ChartLineIcon, EyeIcon } from 'lucide-react'
+import React, { useState, useEffect, useMemo, useRef, lazy, Suspense, useCallback } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useNavigate, Link, useSearchParams } from 'react-router'
+import { toast } from 'sonner'
+
+import {
+ getProjectData,
+ getOverallStats,
+ getProjectDataCustomEvents,
+ getTrafficCompareData,
+ getCustomEventsMetadata,
+ getPropertyMetadata,
+ getGSCKeywords,
+} from '~/api'
+import { TRAFFIC_PANELS_ORDER, chartTypes, PERIOD_PAIRS_COMPARE, isSelfhosted, type TimeBucket } from '~/lib/constants'
+import { CountryEntry, Entry } from '~/lib/models/Entry'
+import { Annotation, OverallObject } from '~/lib/models/Project'
+import CCRow from '~/pages/Project/View/components/CCRow'
+import CustomMetrics from '~/pages/Project/View/components/CustomMetrics'
+import Filters from '~/pages/Project/View/components/Filters'
+import { MetricCard, MetricCards } from '~/pages/Project/View/components/MetricCards'
+import NoEvents from '~/pages/Project/View/components/NoEvents'
+import RefRow from '~/pages/Project/View/components/RefRow'
+import { TrafficChart } from '~/pages/Project/View/components/TrafficChart'
+import UserFlow from '~/pages/Project/View/components/UserFlow'
+import {
+ Customs,
+ TrafficMeta,
+ Params,
+ ProjectViewCustomEvent,
+ Properties,
+ TrafficLogResponse,
+} from '~/pages/Project/View/interfaces/traffic'
+import { Panel, Metadata as MetadataGeneric } from '~/pages/Project/View/Panels'
+import { FILTER_CHART_METRICS_MAPPING_FOR_COMPARE } from '~/pages/Project/View/utils/filters'
+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import {
+ getFormatDate,
+ panelIconMapping,
+ noRegionPeriods,
+ CHART_METRICS_MAPPING,
+ getDeviceRowMapper,
+} from '~/pages/Project/View/ViewProject.helpers'
+import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import { useTheme } from '~/providers/ThemeProvider'
+import Checkbox from '~/ui/Checkbox'
+import Dropdown from '~/ui/Dropdown'
+import Loader from '~/ui/Loader'
+import { periodToCompareDate } from '~/utils/compareConvertDate'
+import { getLocaleDisplayName, nLocaleFormatter } from '~/utils/generic'
+import { groupRefEntries } from '~/utils/referrers'
+import routes from '~/utils/routes'
+
+import CustomEventsSubmenu from '../../View/components/CustomEventsSubmenu'
+
+const InteractiveMap = lazy(() => import('~/pages/Project/View/components/InteractiveMap'))
+
+interface PanelsData {
+ types?: string[]
+ data: Params
+ customs?: Customs
+ properties?: Properties
+ meta?: TrafficMeta[]
+}
+
+type KeywordEntry = Entry & { impressions: number; position: number; ctr: number }
+
+interface TrafficViewProps {
+ tnMapping: Record<string, string>
+ chartType: string
+ rotateXAxis: boolean
+ isActiveCompare: boolean
+ dateRangeCompare: Date[] | null
+ activePeriodCompare: string | null
+ compareDisable: () => void
+ annotations: Annotation[]
+ onChartContextMenu: (e: React.MouseEvent, xAxisData: string[]) => void
+ getFilterLink: (column: string, value: string | null) => any
+ getVersionFilterLink: (parent: string | null, version: string | null, panelType: 'br' | 'os') => string
+ onMainChartZoom: (domain: [Date, Date] | null) => void
+ shouldEnableZoom: boolean
+ setChartTypeOnClick: (type: 'line' | 'bar') => void
+ customMetrics: ProjectViewCustomEvent[]
+ onCustomMetric: (metrics: ProjectViewCustomEvent[]) => void
+ onRemoveCustomMetric: (metricId: string) => void
+ resetCustomMetrics: () => void
+ mode: 'periodical' | 'cumulative'
+ sdkInstance: any
+}
+
+const TrafficView = ({
+ tnMapping,
+ chartType,
+ rotateXAxis,
+ isActiveCompare,
+ dateRangeCompare,
+ activePeriodCompare,
+ compareDisable,
+ annotations,
+ onChartContextMenu,
+ getFilterLink,
+ getVersionFilterLink,
+ onMainChartZoom,
+ shouldEnableZoom,
+ setChartTypeOnClick,
+ customMetrics,
+ onCustomMetric,
+ onRemoveCustomMetric,
+ resetCustomMetrics,
+ mode,
+ sdkInstance,
+}: TrafficViewProps) => {
+ const { id, project } = useCurrentProject()
+ const projectPassword = useProjectPassword(id)
+ const { trafficRefreshTrigger, timezone, period, dateRange, filters, timeFormat, timeBucket, activePeriod } =
+ useViewProjectContext()
+ const {
+ t,
+ i18n: { language },
+ } = useTranslation('common')
+ const { theme } = useTheme()
+ const navigate = useNavigate()
+ const [searchParams, setSearchParams] = useSearchParams()
+
+ // Traffic-specific state
+ const [dataLoading, setDataLoading] = useState(false)
+ const [analyticsLoading, setAnalyticsLoading] = useState(true)
+ const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)
+ const [panelsData, setPanelsData] = useState<PanelsData>({ data: {} })
+ const [chartData, setChartData] = useState<any>({})
+ const [overall, setOverall] = useState<Partial<OverallObject>>({})
+ const [overallCompare, setOverallCompare] = useState<Partial<OverallObject>>({})
+ const [dataChartCompare, setDataChartCompare] = useState<any>({})
+ const [customEventsChartData, setCustomEventsChartData] = useState<any>({})
+
+ // Chart metrics state
+ const [activeChartMetrics, setActiveChartMetrics] = useState({
+ [CHART_METRICS_MAPPING.unique]: true,
+ [CHART_METRICS_MAPPING.views]: false,
+ [CHART_METRICS_MAPPING.sessionDuration]: false,
+ [CHART_METRICS_MAPPING.bounce]: false,
+ [CHART_METRICS_MAPPING.viewsPerUnique]: false,
+ [CHART_METRICS_MAPPING.trendlines]: false,
+ [CHART_METRICS_MAPPING.cumulativeMode]: false,
+ [CHART_METRICS_MAPPING.customEvents]: false,
+ })
+ const [activeChartMetricsCustomEvents, setActiveChartMetricsCustomEvents] = useState<string[]>([])
+
+ // Panel active tabs
+ const [panelsActiveTabs, setPanelsActiveTabs] = useState<{
+ location: 'cc' | 'rg' | 'ct' | 'lc' | 'map'
+ page: 'pg' | 'host' | 'userFlow' | 'entryPage' | 'exitPage'
+ device: 'br' | 'os' | 'dv'
+ source: 'ref' | 'so' | 'me' | 'ca' | 'te' | 'co' | 'keywords'
+ metadata: 'ce' | 'props'
+ }>({
+ location: 'cc',
+ page: 'pg',
+ device: 'br',
+ source: 'ref',
+ metadata: 'ce',
+ })
+
+ // GSC Keywords state
+ const [keywords, setKeywords] = useState<KeywordEntry[]>([])
+ const [keywordsLoading, setKeywordsLoading] = useState(false)
+ const [keywordsNotConnected, setKeywordsNotConnected] = useState(false)
+
+ const isMountedRef = useRef(true)
+
+ // Cleanup on unmount
+ useEffect(() => {
+ isMountedRef.current = true
+ return () => {
+ isMountedRef.current = false
+ }
+ }, [])
+
+ // Version data mapping for browser/OS versions
+ const createVersionDataMapping = useMemo(() => {
+ const browserDataSource = panelsData.data?.brv
+ const osDataSource = panelsData.data?.osv
+
+ const browserVersions: { [key: string]: Entry[] } = {}
+ const osVersions: { [key: string]: Entry[] } = {}
+
+ if (browserDataSource) {
+ browserDataSource.forEach((entry: any) => {
+ const { br, name, count } = entry
+ if (!browserVersions[br]) {
+ browserVersions[br] = []
+ }
+ browserVersions[br].push({ name, count })
+ })
+ }
+
+ if (osDataSource) {
+ osDataSource.forEach((entry: any) => {
+ const { os, name, count } = entry
+ if (!osVersions[os]) {
+ osVersions[os] = []
+ }
+ osVersions[os].push({ name, count })
+ })
+ }
+
+ return { browserVersions, osVersions }
+ }, [panelsData.data?.brv, panelsData.data?.osv])
+
+ const chartMetrics = useMemo(
+ () => [
+ {
+ id: CHART_METRICS_MAPPING.unique,
+ label: t('dashboard.sessions'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.unique],
+ },
+ {
+ id: CHART_METRICS_MAPPING.views,
+ label: t('project.showAll'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.views],
+ },
+ {
+ id: CHART_METRICS_MAPPING.sessionDuration,
+ label: t('dashboard.sessionDuration'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.sessionDuration],
+ conflicts: [CHART_METRICS_MAPPING.bounce],
+ },
+ {
+ id: CHART_METRICS_MAPPING.bounce,
+ label: t('dashboard.bounceRate'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.bounce],
+ conflicts: [CHART_METRICS_MAPPING.sessionDuration],
+ },
+ {
+ id: CHART_METRICS_MAPPING.viewsPerUnique,
+ label: t('dashboard.viewsPerUnique'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.viewsPerUnique],
+ },
+ {
+ id: CHART_METRICS_MAPPING.trendlines,
+ label: t('dashboard.trendlines'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.trendlines],
+ },
+ {
+ id: CHART_METRICS_MAPPING.cumulativeMode,
+ label: t('dashboard.cumulativeMode'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode],
+ },
+ {
+ id: CHART_METRICS_MAPPING.customEvents,
+ label: t('project.customEv'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.customEvents],
+ },
+ ],
+ [t, activeChartMetrics],
+ )
+
+ const chartMetricsCustomEvents = useMemo(() => {
+ if (!_isEmpty(panelsData.customs)) {
+ return _map(_keys(panelsData.customs), (key) => ({
+ id: key,
+ label: key,
+ active: _includes(activeChartMetricsCustomEvents, key),
+ }))
+ }
+ return []
+ }, [panelsData, activeChartMetricsCustomEvents])
+
+ const dataNamesCustomEvents = useMemo(() => {
+ if (!_isEmpty(panelsData.customs)) {
+ return { ..._keys(panelsData.customs) }
+ }
+ return {}
+ }, [panelsData])
+
+ const dataNames = useMemo(
+ () => ({
+ unique: t('dashboard.sessions'),
+ total: t('project.total'),
+ pageviews: t('project.pageviews'),
+ customEvents: t('project.customEvents'),
+ errors: t('project.errors'),
+ bounce: `${t('dashboard.bounceRate')} (%)`,
+ viewsPerUnique: t('dashboard.viewsPerUnique'),
+ trendlineTotal: t('project.trendlineTotal'),
+ trendlineUnique: t('project.trendlineUnique'),
+ occurrences: t('project.occurrences'),
+ sessionDuration: t('dashboard.sessionDuration'),
+ ...dataNamesCustomEvents,
+ }),
+ [t, dataNamesCustomEvents],
+ )
+
+ const checkIfAllMetricsAreDisabled = useMemo(
+ () => !_some({ ...activeChartMetrics, ...activeChartMetricsCustomEvents }, (value) => value),
+ [activeChartMetrics, activeChartMetricsCustomEvents],
+ )
+
+ const isConflicted = useCallback(
+ (conflicts: string[] | undefined) => {
+ if (!conflicts) return false
+ return conflicts.some((id) => activeChartMetrics[id as keyof typeof activeChartMetrics])
+ },
+ [activeChartMetrics],
+ )
+
+ const switchTrafficChartMetric = useCallback(
+ (pairID: string, conflicts?: string[]) => {
+ if (isConflicted(conflicts)) {
+ toast.error(t('project.conflictMetric'))
+ return
+ }
+
+ if (pairID === CHART_METRICS_MAPPING.customEvents) {
+ return
+ }
+
+ setActiveChartMetrics((prev) => ({
+ ...prev,
+ [pairID]: !prev[pairID as keyof typeof prev],
+ }))
+ },
+ [isConflicted, t],
+ )
+
+ const switchCustomEventChart = useCallback((id: string) => {
+ setActiveChartMetricsCustomEvents((prev) => {
+ if (_includes(prev, id)) {
+ return _filter(prev, (item) => item !== id)
+ }
+ return [...prev, id]
+ })
+ }, [])
+
+ const setPanelTab = (panel: keyof typeof panelsActiveTabs, tab: string) => {
+ setPanelsActiveTabs((prev) => ({
+ ...prev,
+ [panel]: tab,
+ }))
+ }
+
+ const loadAnalytics = async () => {
+ if (!project) return
+
+ setDataLoading(true)
+
+ try {
+ let data: TrafficLogResponse & { overall?: OverallObject }
+ let dataCompare: (TrafficLogResponse & { overall?: OverallObject }) | null = null
+ let from
+ let fromCompare: string | undefined
+ let to
+ let toCompare: string | undefined
+ let customEventsChart = customEventsChartData
+ let rawOverall: any
+
+ if (isActiveCompare) {
+ if (dateRangeCompare && activePeriodCompare === PERIOD_PAIRS_COMPARE.CUSTOM) {
+ let start
+ let end
+ let diff
+ const startCompare = dayjs.utc(dateRangeCompare[0])
+ const endCompare = dayjs.utc(dateRangeCompare[1])
+ const diffCompare = endCompare.diff(startCompare, 'day')
+
+ if (activePeriod?.period === 'custom' && dateRange) {
+ start = dayjs.utc(dateRange[0])
+ end = dayjs.utc(dateRange[1])
+ diff = end.diff(start, 'day')
+ }
+
+ // @ts-expect-error
+ if (activePeriod?.period === 'custom' ? diffCompare <= diff : diffCompare <= activePeriod?.countDays) {
+ fromCompare = getFormatDate(dateRangeCompare[0])
+ toCompare = getFormatDate(dateRangeCompare[1])
+ } else {
+ toast.error(t('project.compareDateRangeError'))
+ compareDisable()
+ }
+ } else {
+ let date
+ if (dateRange) {
+ date = _find(periodToCompareDate, (item) => item.period === period)?.formula(dateRange)
+ } else {
+ date = _find(periodToCompareDate, (item) => item.period === period)?.formula()
+ }
+
+ if (date) {
+ fromCompare = date.from
+ toCompare = date.to
+ }
+ }
+
+ if (!_isEmpty(fromCompare) && !_isEmpty(toCompare)) {
+ dataCompare =
+ (await getTrafficCompareData(
+ id,
+ timeBucket,
+ '',
+ filters,
+ fromCompare,
+ toCompare,
+ timezone,
+ projectPassword,
+ mode,
+ )) || {}
+ const compareOverall = await getOverallStats(
+ [id],
+ timeBucket,
+ 'custom',
+ fromCompare,
+ toCompare,
+ timezone,
+ filters,
+ projectPassword,
+ )
+
+ // @ts-expect-error
+ dataCompare.overall = compareOverall[id]
+ }
+ }
+
+ if (dateRange) {
+ from = getFormatDate(dateRange[0])
+ to = getFormatDate(dateRange[1])
+ }
+
+ if (period === 'custom' && dateRange) {
+ data = await getProjectData(
+ id,
+ timeBucket,
+ '',
+ filters,
+ customMetrics,
+ from,
+ to,
+ timezone,
+ projectPassword,
+ mode,
+ )
+ if (activeChartMetricsCustomEvents.length > 0) {
+ customEventsChart = await getProjectDataCustomEvents(
+ id,
+ timeBucket,
+ '',
+ filters,
+ from,
+ to,
+ timezone,
+ activeChartMetricsCustomEvents,
+ projectPassword,
+ )
+ }
+ rawOverall = await getOverallStats([id], timeBucket, period, from, to, timezone, filters, projectPassword)
+ } else {
+ data = await getProjectData(
+ id,
+ timeBucket,
+ period,
+ filters,
+ customMetrics,
+ '',
+ '',
+ timezone,
+ projectPassword,
+ mode,
+ )
+ if (activeChartMetricsCustomEvents.length > 0) {
+ customEventsChart = await getProjectDataCustomEvents(
+ id,
+ timeBucket,
+ period,
+ filters,
+ '',
+ '',
+ timezone,
+ activeChartMetricsCustomEvents,
+ projectPassword,
+ )
+ }
+ rawOverall = await getOverallStats([id], timeBucket, period, '', '', timezone, filters, projectPassword)
+ }
+
+ customEventsChart = customEventsChart?.chart ? customEventsChart.chart.events : customEventsChartData
+
+ if (isMountedRef.current) {
+ setCustomEventsChartData(customEventsChart)
+ data.overall = rawOverall[id]
+ setOverall(rawOverall[id])
+
+ const sdkData = {
+ ...(data || {}),
+ filters,
+ timezone,
+ timeBucket,
+ period,
+ from,
+ to,
+ }
+
+ if (_keys(data).length < 2) {
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ setIsPanelsDataEmpty(true)
+ sdkInstance?._emitEvent('load', sdkData)
+ return
+ }
+
+ const { chart, params, customs, properties, meta } = data
+ let newTimebucket = timeBucket
+ sdkInstance?._emitEvent('load', sdkData)
+
+ if (period === 'all' && !_isEmpty(data.timeBucket)) {
+ newTimebucket = _includes(data.timeBucket, timeBucket) ? timeBucket : (data.timeBucket?.[0] as TimeBucket)
+
+ const newSearchParams = new URLSearchParams(searchParams.toString())
+ newSearchParams.set('timeBucket', newTimebucket)
+ setSearchParams(newSearchParams)
+ }
+
+ if (!_isEmpty(dataCompare)) {
+ if (!_isEmpty(dataCompare?.chart)) {
+ setDataChartCompare(dataCompare.chart)
+ }
+
+ if (!_isEmpty(dataCompare?.overall)) {
+ setOverallCompare(dataCompare.overall)
+ }
+ }
+
+ if (_isEmpty(params)) {
+ setIsPanelsDataEmpty(true)
+ } else {
+ setChartData(chart as any)
+
+ setPanelsData({
+ types: _keys(params),
+ data: params,
+ customs,
+ properties,
+ meta,
+ })
+
+ setIsPanelsDataEmpty(false)
+ }
+
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ }
+ } catch (reason) {
+ if (isMountedRef.current) {
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ setIsPanelsDataEmpty(true)
+ console.error('[ERROR](loadAnalytics) Loading analytics data failed')
+ console.error(reason)
+ }
+ }
+ }
+
+ const getCustomEventMetadata = async (event: string) => {
+ if (period === 'custom' && dateRange) {
+ return getCustomEventsMetadata(
+ id,
+ event,
+ timeBucket,
+ '',
+ getFormatDate(dateRange[0]),
+ getFormatDate(dateRange[1]),
+ timezone,
+ projectPassword,
+ )
+ }
+
+ return getCustomEventsMetadata(id, event, timeBucket, period, '', '', timezone, projectPassword)
+ }
+
+ const _getPropertyMetadata = async (property: string) => {
+ if (period === 'custom' && dateRange) {
+ return getPropertyMetadata(
+ id,
+ property,
+ timeBucket,
+ '',
+ getFormatDate(dateRange[0]),
+ getFormatDate(dateRange[1]),
+ filters,
+ timezone,
+ projectPassword,
+ )
+ }
+
+ return getPropertyMetadata(id, property, timeBucket, period, '', '', filters, timezone, projectPassword)
+ }
+
+ // Load GSC Keywords when the traffic sources panel switches to 'keywords'
+ useEffect(() => {
+ const loadKeywords = async () => {
+ if (!project) return
+ if (panelsActiveTabs.source !== 'keywords') return
+ if (keywordsLoading) return
+
+ // Skip if we already have keywords loaded and period/filters haven't changed
+ if (keywords.length > 0) return
+
+ setKeywordsLoading(true)
+ try {
+ let from
+ let to
+
+ if (dateRange) {
+ from = getFormatDate(dateRange[0])
+ to = getFormatDate(dateRange[1])
+ }
+
+ const data =
+ period === 'custom' && dateRange
+ ? await getGSCKeywords(id, '', from, to, timezone, projectPassword)
+ : await getGSCKeywords(id, period, '', '', timezone, projectPassword)
+
+ if (isMountedRef.current) {
+ if (data.notConnected) {
+ setKeywordsNotConnected(true)
+ setKeywords([])
+ } else {
+ setKeywordsNotConnected(false)
+ setKeywords(data.keywords || [])
+ }
+ }
+ } catch (error) {
+ console.error('[ERROR] Loading GSC keywords failed:', error)
+ if (isMountedRef.current) {
+ setKeywordsNotConnected(true)
+ setKeywords([])
+ }
+ } finally {
+ if (isMountedRef.current) {
+ setKeywordsLoading(false)
+ }
+ }
+ }
+
+ loadKeywords()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [panelsActiveTabs.source, period, dateRange, timezone, id, project])
+
+ // Load analytics on mount and when dependencies change
+ useEffect(() => {
+ if (!project) return
+ loadAnalytics()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ mode,
+ customMetrics,
+ filters,
+ project,
+ isActiveCompare,
+ dateRange,
+ period,
+ timeBucket,
+ dateRangeCompare,
+ activePeriodCompare,
+ ])
+
+ // Handle custom events chart loading
+ useEffect(() => {
+ if (!project) return
+ if (activeChartMetricsCustomEvents.length === 0) {
+ setCustomEventsChartData({})
+ return
+ }
+ loadAnalytics()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [activeChartMetricsCustomEvents])
+
+ // Handle refresh trigger
+ useEffect(() => {
+ if (trafficRefreshTrigger > 0) {
+ loadAnalytics()
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [trafficRefreshTrigger])
+
+ // Show loader during initial load
+ if (analyticsLoading) {
+ return <Loader />
+ }
+
+ // Show no events if data is empty
+ if (isPanelsDataEmpty) {
+ return <NoEvents filters={filters} />
+ }
+
+ const ChartTypeSwitcher = ({ type, onSwitch }: { type: string; onSwitch: (type: 'line' | 'bar') => void }) => {
+ if (type === chartTypes.bar) {
+ return (
+ <button
+ type='button'
+ title={t('project.lineChart')}
+ onClick={() => onSwitch('line')}
+ className='rounded-md border border-transparent bg-gray-50 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 dark:bg-slate-900 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200'
+ >
+ <ChartLineIcon className='h-5 w-5 text-gray-700 dark:text-gray-50' />
+ </button>
+ )
+ }
+
+ return (
+ <button
+ type='button'
+ title={t('project.barChart')}
+ onClick={() => onSwitch('bar')}
+ className='rounded-md border border-transparent bg-gray-50 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 dark:bg-slate-900 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200'
+ >
+ <ChartColumnBigIcon className='h-5 w-5 text-gray-700 dark:text-gray-50' />
+ </button>
+ )
+ }
+
+ return (
+ <div className={cx({ hidden: isPanelsDataEmpty || analyticsLoading })}>
+ <div className='relative overflow-hidden rounded-lg border border-gray-300 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-800/25'>
+ <div className='mb-3 flex w-full items-center justify-end gap-2 lg:absolute lg:top-2 lg:right-2 lg:mb-0 lg:w-auto lg:justify-normal'>
+ <Dropdown
+ header={t('project.metricVis')}
+ items={
+ isActiveCompare
+ ? _filter(chartMetrics, (el) => !_includes(FILTER_CHART_METRICS_MAPPING_FOR_COMPARE, el.id))
+ : chartMetrics
+ }
+ title={[<EyeIcon key='eye-icon' aria-label={t('project.metricVis')} className='h-5 w-5' />]}
+ labelExtractor={(pair) => {
+ const { label, id: pairID, active, conflicts } = pair
+
+ const conflicted = isConflicted(conflicts)
+
+ if (pairID === CHART_METRICS_MAPPING.customEvents) {
+ if (_isEmpty(panelsData.customs)) {
+ return (
+ <span className='flex cursor-not-allowed items-center p-2'>
+ <BanIcon className='mr-2 h-4 w-4' strokeWidth={1.5} />
+ {label}
+ </span>
+ )
+ }
+
+ return (
+ <CustomEventsSubmenu
+ label={label}
+ chartMetricsCustomEvents={chartMetricsCustomEvents}
+ switchCustomEventChart={switchCustomEventChart}
+ />
+ )
+ }
+
+ return (
+ <Checkbox
+ classes={{
+ label: cx('p-2', { hidden: analyticsLoading }),
+ }}
+ label={label}
+ disabled={conflicted}
+ checked={active}
+ onChange={() => {
+ switchTrafficChartMetric(pairID, conflicts)
+ }}
+ />
+ )
+ }}
+ buttonClassName='!px-2 bg-gray-50 rounded-md border border-transparent hover:border-gray-300 hover:bg-white dark:bg-slate-900 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200'
+ selectItemClassName='p-0'
+ keyExtractor={(pair) => pair.id}
+ onSelect={({ id: pairID, conflicts }, e) => {
+ e?.stopPropagation()
+ e?.preventDefault()
+
+ if (pairID !== CHART_METRICS_MAPPING.customEvents) {
+ switchTrafficChartMetric(pairID, conflicts)
+ }
+ }}
+ chevron='mini'
+ headless
+ />
+ <ChartTypeSwitcher onSwitch={setChartTypeOnClick} type={chartType} />
+ </div>
+ {!_isEmpty(overall) ? (
+ <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>
+ <MetricCards overall={overall} overallCompare={overallCompare} activePeriodCompare={activePeriodCompare} />
+ {!_isEmpty(panelsData.meta)
+ ? _map(panelsData.meta, ({ key, current, previous }) => (
+ <React.Fragment key={key}>
+ <MetricCard
+ label={t('project.metrics.xAvg', { x: key })}
+ value={current.avg}
+ change={current.avg - previous.avg}
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`
+ }
+ />
+ <MetricCard
+ label={t('project.metrics.xTotal', { x: key })}
+ value={current.sum}
+ change={current.sum - previous.sum}
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`
+ }
+ />
+ </React.Fragment>
+ ))
+ : null}
+ </div>
+ ) : null}
+ {!checkIfAllMetricsAreDisabled && !_isEmpty(chartData) ? (
+ <div onContextMenu={(e) => onChartContextMenu(e, chartData.x)} className='relative'>
+ <TrafficChart
+ chartData={chartData}
+ timeBucket={timeBucket}
+ activeChartMetrics={activeChartMetrics}
+ applyRegions={!_includes(noRegionPeriods, activePeriod?.period)}
+ timeFormat={timeFormat}
+ rotateXAxis={rotateXAxis}
+ chartType={chartType}
+ customEventsChartData={customEventsChartData}
+ dataChartCompare={dataChartCompare}
+ onZoom={onMainChartZoom}
+ enableZoom={shouldEnableZoom}
+ dataNames={dataNames}
+ className='mt-5 h-80 md:mt-0 [&_svg]:overflow-visible!'
+ annotations={annotations}
+ />
+ </div>
+ ) : null}
+ </div>
+ {!isPanelsDataEmpty ? <Filters tnMapping={tnMapping} /> : null}
+ <CustomMetrics
+ metrics={customMetrics}
+ onRemoveMetric={(metricId) => onRemoveCustomMetric(metricId)}
+ resetMetrics={resetCustomMetrics}
+ />
+ <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>
+ {!_isEmpty(panelsData.types)
+ ? _map(TRAFFIC_PANELS_ORDER, (type: string) => {
+ if (type === 'location') {
+ const locationTabs = [
+ { id: 'cc', label: t('project.mapping.cc') },
+ { id: 'rg', label: t('project.mapping.rg') },
+ { id: 'ct', label: t('project.mapping.ct') },
+ { id: 'lc', label: t('project.mapping.lc') },
+ { id: 'map', label: 'Map' },
+ ]
+
+ const rowMapper = (entry: CountryEntry) => {
+ const { name: entryName, cc } = entry
+
+ if (panelsActiveTabs.location === 'lc') {
+ if (entryName === null) {
+ return <CCRow cc={null} language={language} />
+ }
+
+ const entryNameArray = entryName.split('-')
+ const displayName = getLocaleDisplayName(entryName, language)
+
+ return (
+ <CCRow cc={entryNameArray[entryNameArray.length - 1]} name={displayName} language={language} />
+ )
+ }
+
+ if (cc !== undefined) {
+ return <CCRow cc={cc} name={entryName || undefined} language={language} />
+ }
+
+ return <CCRow cc={entryName} language={language} />
+ }
+
+ return (
+ <Panel
+ key={panelsActiveTabs.location}
+ icon={panelIconMapping.cc}
+ id={panelsActiveTabs.location}
+ getFilterLink={getFilterLink}
+ name={t('project.location')}
+ tabs={locationTabs}
+ onTabChange={(tab) => setPanelTab('location', tab)}
+ activeTabId={panelsActiveTabs.location}
+ data={panelsData.data[panelsActiveTabs.location]}
+ rowMapper={rowMapper}
+ customRenderer={
+ panelsActiveTabs.location === 'map'
+ ? () => {
+ const countryData = panelsData.data?.cc || []
+ const regionData = panelsData.data?.rg || []
+ const total = countryData.reduce((acc, curr) => acc + curr.count, 0)
+
+ return (
+ <Suspense
+ fallback={
+ <div className='flex h-full items-center justify-center'>
+ <div className='flex flex-col items-center gap-2'>
+ <div className='h-8 w-8 animate-spin rounded-full border-2 border-blue-400 border-t-transparent'></div>
+ <span className='text-sm text-neutral-600 dark:text-neutral-300'>
+ Loading map...
+ </span>
+ </div>
+ </div>
+ }
+ >
+ <InteractiveMap
+ data={countryData}
+ regionData={regionData}
+ total={total}
+ onClick={(mapType, key) => {
+ const link = getFilterLink(mapType, key)
+ navigate(link)
+ }}
+ />
+ </Suspense>
+ )
+ }
+ : undefined
+ }
+ />
+ )
+ }
+
+ if (type === 'devices') {
+ const deviceTabs = [
+ { id: 'br', label: t('project.mapping.br') },
+ { id: 'os', label: t('project.mapping.os') },
+ { id: 'dv', label: t('project.mapping.dv') },
+ ]
+
+ return (
+ <Panel
+ key={panelsActiveTabs.device}
+ icon={panelIconMapping.os}
+ id={panelsActiveTabs.device}
+ getFilterLink={getFilterLink}
+ name={t('project.devices')}
+ tabs={deviceTabs}
+ onTabChange={(tab) => setPanelTab('device', tab)}
+ activeTabId={panelsActiveTabs.device}
+ data={panelsData.data[panelsActiveTabs.device]}
+ rowMapper={getDeviceRowMapper(panelsActiveTabs.device, theme, t)}
+ capitalize={panelsActiveTabs.device === 'dv'}
+ versionData={
+ panelsActiveTabs.device === 'br'
+ ? createVersionDataMapping.browserVersions
+ : panelsActiveTabs.device === 'os'
+ ? createVersionDataMapping.osVersions
+ : undefined
+ }
+ getVersionFilterLink={(parent, version) =>
+ getVersionFilterLink(parent, version, panelsActiveTabs.device === 'br' ? 'br' : 'os')
+ }
+ />
+ )
+ }
+
+ if (type === 'pg') {
+ const pageTabs = [
+ { id: 'pg', label: t('project.mapping.pg') },
+ { id: 'entryPage', label: t('project.entryPages') },
+ { id: 'exitPage', label: t('project.exitPages') },
+ { id: 'userFlow', label: t('project.mapping.userFlow') },
+ {
+ id: 'host',
+ label: t('project.mapping.host'),
+ },
+ ]
+
+ return (
+ <Panel
+ key={panelsActiveTabs.page}
+ icon={panelIconMapping.pg}
+ id={panelsActiveTabs.page}
+ getFilterLink={getFilterLink}
+ rowMapper={({ name: entryName }) => {
+ if (!entryName) {
+ return (
+ <span className='italic'>
+ {panelsActiveTabs.page === 'host' ? t('project.unknownHost') : t('common.notSet')}
+ </span>
+ )
+ }
+
+ let decodedUri = entryName as string
+
+ try {
+ decodedUri = decodeURIComponent(entryName)
+ } catch {
+ // do nothing
+ }
+
+ return decodedUri
+ }}
+ name={t('project.pages')}
+ tabs={pageTabs}
+ onTabChange={(tab) => setPanelTab('page', tab)}
+ activeTabId={panelsActiveTabs.page}
+ data={panelsData.data[panelsActiveTabs.page]}
+ customRenderer={
+ panelsActiveTabs.page === 'userFlow'
+ ? () => <UserFlow isReversed={false} setReversed={() => {}} />
+ : undefined
+ }
+ />
+ )
+ }
+
+ if (type === 'traffic-sources') {
+ const hasRefNameFilter = filters.some((f) => f.column === 'refn')
+ const trafficSourcesTabs = [
+ { id: 'ref', label: t('project.mapping.ref') },
+ !isSelfhosted && { id: 'keywords', label: t('project.mapping.keywords') },
+ [
+ { id: 'so', label: t('project.mapping.so') },
+ { id: 'me', label: t('project.mapping.me') },
+ { id: 'ca', label: t('project.mapping.ca') },
+ { id: 'te', label: t('project.mapping.te') },
+ { id: 'co', label: t('project.mapping.co') },
+ ],
+ ].filter((x) => !!x)
+
+ const getTrafficSourcesRowMapper = (activeTab: string) => {
+ if (activeTab === 'ref') {
+ // eslint-disable-next-line
+ return ({ name: entryName }: any) => <RefRow rowName={entryName} />
+ }
+ return ({ name: entryName }: any) => decodeURIComponent(entryName)
+ }
+
+ return (
+ <Panel
+ key={panelsActiveTabs.source}
+ icon={panelIconMapping.ref}
+ id={panelsActiveTabs.source}
+ getFilterLink={(column: string, value: string | null) => {
+ if (panelsActiveTabs.source === 'ref') {
+ // If grouped by name/domain (no refn filter active) -> filter by refn
+ return getFilterLink(hasRefNameFilter || value === null ? 'ref' : 'refn', value)
+ }
+ return getFilterLink(column, value)
+ }}
+ name={t('project.trafficSources')}
+ tabs={trafficSourcesTabs}
+ onTabChange={(tab) => setPanelTab('source', tab)}
+ activeTabId={panelsActiveTabs.source}
+ data={
+ panelsActiveTabs.source === 'keywords'
+ ? keywords
+ : panelsActiveTabs.source === 'ref'
+ ? (() => {
+ const raw = panelsData.data?.ref || []
+ return hasRefNameFilter
+ ? (raw as unknown as Entry[])
+ : (groupRefEntries(raw as any) as unknown as Entry[])
+ })()
+ : (panelsData.data[panelsActiveTabs.source] as unknown as Entry[])
+ }
+ valuesHeaderName={panelsActiveTabs.source === 'keywords' ? t('project.clicks') : undefined}
+ rowMapper={getTrafficSourcesRowMapper(panelsActiveTabs.source)}
+ disableRowClick={panelsActiveTabs.source === 'keywords'}
+ hidePercentageInDetails={panelsActiveTabs.source === 'keywords'}
+ detailsExtraColumns={
+ panelsActiveTabs.source === 'keywords'
+ ? [
+ {
+ header: t('project.impressions'),
+ render: (entry: any) => entry.impressions,
+ sortLabel: 'impressions',
+ getSortValue: (entry: any) => Number(entry.impressions || 0),
+ },
+ {
+ header: t('project.position'),
+ render: (entry: any) => entry.position,
+ sortLabel: 'position',
+ getSortValue: (entry: any) => Number(entry.position || 0),
+ },
+ {
+ header: t('project.ctr'),
+ render: (entry: any) => `${entry.ctr}%`,
+ sortLabel: 'ctr',
+ getSortValue: (entry: any) => Number(entry.ctr || 0),
+ },
+ ]
+ : undefined
+ }
+ customRenderer={
+ panelsActiveTabs.source === 'keywords'
+ ? keywordsLoading
+ ? () => <Loader />
+ : keywordsNotConnected
+ ? () => (
+ <div className='mt-4 text-center'>
+ <p className='text-sm text-gray-800 dark:text-gray-200'>
+ {['owner', 'admin'].includes(project?.role || '')
+ ? t('project.connectGsc')
+ : t('project.gscConnectionRequired')}
+ </p>
+ {['owner', 'admin'].includes(project?.role || '') ? (
+ <Link
+ to={`${routes.project_settings.replace(':id', id)}?tab=integrations`}
+ className='mt-2 inline-flex items-center rounded-md border border-gray-300 bg-white px-3 py-1 text-sm text-gray-800 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
+ >
+ {t('project.goToProjectSettings')}
+ </Link>
+ ) : null}
+ </div>
+ )
+ : undefined
+ : undefined
+ }
+ />
+ )
+ }
+
+ return null
+ })
+ : null}
+ {!_isEmpty(panelsData.data) ? (
+ <MetadataGeneric
+ customs={panelsData.customs}
+ properties={panelsData.properties}
+ filters={filters}
+ getFilterLink={getFilterLink}
+ chartData={chartData}
+ getCustomEventMetadata={getCustomEventMetadata}
+ getPropertyMetadata={_getPropertyMetadata}
+ onTabChange={(tab) => setPanelTab('metadata', tab)}
+ activeTabId={panelsActiveTabs.metadata}
+ />
+ ) : null}
+ </div>
+ </div>
+ )
+}
+
+export default TrafficView
diff --git a/web/app/pages/Project/View/Panels.tsx b/web/app/pages/Project/View/Panels.tsx
index f84eb4672..8fa2b14fc 100644
--- a/web/app/pages/Project/View/Panels.tsx
+++ b/web/app/pages/Project/View/Panels.tsx
@@ -265,8 +265,8 @@ export type CustomTab = {
}
interface MetadataProps {
- customs: Customs
- properties: Properties
+ customs?: Customs
+ properties?: Properties
chartData: any
filters: Filter[]
getCustomEventMetadata: (event: string) => Promise<any>
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 8427175c3..faadec3bc 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -4,54 +4,32 @@ import dayjs from 'dayjs'
import { AnimatePresence, motion } from 'framer-motion'
import _filter from 'lodash/filter'
import _find from 'lodash/find'
-import _findIndex from 'lodash/findIndex'
import _includes from 'lodash/includes'
import _isEmpty from 'lodash/isEmpty'
import _isString from 'lodash/isString'
-import _keys from 'lodash/keys'
import _map from 'lodash/map'
-import _pickBy from 'lodash/pickBy'
import _replace from 'lodash/replace'
-import _some from 'lodash/some'
import _uniqBy from 'lodash/uniqBy'
import {
MoonIcon,
SunIcon,
ChevronLeftIcon,
- SearchIcon,
BugIcon,
GaugeIcon,
- Trash2Icon,
UsersIcon,
UserIcon,
BellRingIcon,
ChartNoAxesColumnIcon,
FilterIcon,
- BookmarkIcon,
- PencilIcon,
DownloadIcon,
SettingsIcon,
- BanIcon,
- ChartColumnIcon,
- ChartLineIcon,
- EyeIcon,
KeyboardIcon,
TargetIcon,
PuzzleIcon,
SparklesIcon,
FlagIcon,
} from 'lucide-react'
-import React, {
- useState,
- useEffect,
- useMemo,
- useRef,
- useCallback,
- createContext,
- useContext,
- lazy,
- Suspense,
-} from 'react'
+import React, { useState, useEffect, useMemo, useRef, useCallback, createContext, useContext, lazy } from 'react'
import { useHotkeys } from 'react-hotkeys-hook'
import { useTranslation } from 'react-i18next'
import { useNavigate, Link, useSearchParams, LinkProps } from 'react-router'
@@ -59,20 +37,8 @@ import { ClientOnly } from 'remix-utils/client-only'
import { toast } from 'sonner'
import {
- getProjectData,
- getOverallStats,
- getProjectDataCustomEvents,
- getTrafficCompareData,
- getCustomEventsMetadata,
- addFunnel,
- updateFunnel,
- deleteFunnel,
- getFunnelData,
- getPropertyMetadata,
getProjectViews,
deleteProjectView,
- getFunnels,
- getGSCKeywords,
getAnnotations,
createAnnotation,
updateAnnotation,
@@ -92,18 +58,15 @@ import {
CDN_URL,
isDevelopment,
timeBucketToDays,
- MAX_MONTHS_IN_PAST,
PROJECT_TABS,
TimeFormat,
chartTypes,
- TRAFFIC_PANELS_ORDER,
isSelfhosted,
tbPeriodPairsCompare,
PERIOD_PAIRS_COMPARE,
FILTERS_PERIOD_PAIRS,
LS_IS_ACTIVE_COMPARE_KEY,
TITLE_SUFFIX,
- MARKETPLACE_URL,
TBPeriodPairsProps,
ERROR_PERIOD_PAIRS,
FUNNELS_PERIOD_PAIRS,
@@ -115,34 +78,18 @@ import {
languages,
languageFlag,
} from '~/lib/constants'
-import { CountryEntry, Entry } from '~/lib/models/Entry'
-import {
- Funnel,
- AnalyticsFunnel,
- OverallObject,
- Session,
- Annotation,
- Profile,
- ProfileDetails,
-} from '~/lib/models/Project'
+import { Session, Annotation, Profile, ProfileDetails } from '~/lib/models/Project'
import AnnotationModal from '~/modals/AnnotationModal'
-import NewFunnel from '~/modals/NewFunnel'
import ViewProjectHotkeys from '~/modals/ViewProjectHotkeys'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
-import Checkbox from '~/ui/Checkbox'
-import DatePicker from '~/ui/Datepicker'
import Dropdown from '~/ui/Dropdown'
import Flag from '~/ui/Flag'
import Loader from '~/ui/Loader'
import LoadingBar from '~/ui/LoadingBar'
import Select from '~/ui/Select'
-import { Text } from '~/ui/Text'
-import { trackCustom } from '~/utils/analytics'
-import { periodToCompareDate } from '~/utils/compareConvertDate'
-import { getLocaleDisplayName, nLocaleFormatter, removeDuplicates } from '~/utils/generic'
+import { removeDuplicates } from '~/utils/generic'
import { getItem, setItem } from '~/utils/localstorage'
-import { groupRefEntries } from '~/utils/referrers'
import routes from '~/utils/routes'
import { useCurrentProject, useProjectPassword } from '../../../providers/CurrentProjectProvider'
@@ -150,34 +97,25 @@ import ProjectAlertsView from '../Alerts/View'
import AskAIView from '../AskAI'
import ErrorsView from '../Errors/View/ErrorsView'
import FeatureFlagsView from '../FeatureFlags/View'
+import FunnelsView from '../Funnels/View'
import GoalsView from '../Goals/View'
import PerformanceView from '../Performance/View/PerformanceView'
import SessionsView from '../Sessions/View/SessionsView'
+import TrafficView from '../Traffic/View/TrafficView'
import AddAViewModal from './components/AddAViewModal'
-import CCRow from './components/CCRow'
import { ChartContextMenu } from './components/ChartContextMenu'
import { ChartManagerProvider } from './components/ChartManager'
-import CustomEventsSubmenu from './components/CustomEventsSubmenu'
-import CustomMetrics from './components/CustomMetrics'
-import Filters from './components/Filters'
const CaptchaView = lazy(() => import('./components/CaptchaView'))
-import { FunnelChart } from './components/FunnelChart'
-import FunnelsList from './components/FunnelsList'
-const InteractiveMap = lazy(() => import('./components/InteractiveMap'))
+import DashboardHeader from './components/DashboardHeader'
// Keywords list now reuses shared Panel UI; dedicated component removed from render
-import LiveVisitorsDropdown from './components/LiveVisitorsDropdown'
import LockedDashboard from './components/LockedDashboard'
-import { MetricCard, MetricCards } from './components/MetricCards'
import NoEvents from './components/NoEvents'
import ProjectSidebar from './components/ProjectSidebar'
import { RefreshStatsButton } from './components/RefreshStatsButton'
-import RefRow from './components/RefRow'
-import SearchFilters, { getFiltersUrlParams } from './components/SearchFilters'
-import TBPeriodSelector from './components/TBPeriodSelector'
-import { TrafficChart } from './components/TrafficChart'
+import SearchFilters from './components/SearchFilters'
+import TrafficHeaderActions from './components/TrafficHeaderActions'
import { UserDetails } from './components/UserDetails'
-import UserFlow from './components/UserFlow'
import { Users, UsersFilter } from './components/Users'
import WaitingForAnEvent from './components/WaitingForAnEvent'
import {
@@ -188,22 +126,18 @@ import {
ProjectView,
ProjectViewCustomEvent,
Properties,
- TrafficLogResponse,
} from './interfaces/traffic'
-import { Panel, Metadata as MetadataGeneric, type CustomTab } from './Panels'
-import { FILTER_CHART_METRICS_MAPPING_FOR_COMPARE, parseFilters } from './utils/filters'
+import { type CustomTab } from './Panels'
+import { parseFilters } from './utils/filters'
import {
onCSVExportClick,
getFormatDate,
- panelIconMapping,
typeNameMapping,
- noRegionPeriods,
CHART_METRICS_MAPPING,
SHORTCUTS_TABS_LISTENERS,
SHORTCUTS_TABS_MAP,
SHORTCUTS_GENERAL_LISTENERS,
SHORTCUTS_TIMEBUCKETS_LISTENERS,
- getDeviceRowMapper,
} from './ViewProject.helpers'
const SESSIONS_TAKE = 30
@@ -380,6 +314,8 @@ interface ViewProjectContextType {
featureFlagsRefreshTrigger: number
sessionsRefreshTrigger: number
performanceRefreshTrigger: number
+ trafficRefreshTrigger: number
+ funnelsRefreshTrigger: number
// Functions
updatePeriod: (newPeriod: { period: Period; label?: string }) => void
@@ -408,6 +344,8 @@ const defaultViewProjectContext: ViewProjectContextType = {
featureFlagsRefreshTrigger: 0,
sessionsRefreshTrigger: 0,
performanceRefreshTrigger: 0,
+ trafficRefreshTrigger: 0,
+ funnelsRefreshTrigger: 0,
updatePeriod: () => {},
updateTimebucket: (_newTimebucket) => {},
refCalendar: { current: null } as any,
@@ -420,46 +358,8 @@ export const useViewProjectContext = () => {
return context
}
-const ChartTypeSwitcher = ({
- className,
- onSwitch,
- type,
-}: {
- className?: string
- onSwitch: (type: 'line' | 'bar') => void
- type: 'line' | 'bar'
-}) => {
- const { t } = useTranslation('common')
-
- return (
- <div className={className}>
- {type === chartTypes.bar ? (
- <button
- type='button'
- title={t('project.lineChart')}
- onClick={() => onSwitch(chartTypes.line)}
- className='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'
- >
- <ChartLineIcon className='h-5 w-5 text-gray-700 dark:text-gray-50' />
- </button>
- ) : null}
- {type === chartTypes.line ? (
- <button
- type='button'
- title={t('project.barChart')}
- onClick={() => onSwitch(chartTypes.bar)}
- className='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'
- >
- <ChartColumnIcon className='h-5 w-5 text-gray-700 dark:text-gray-50' />
- </button>
- ) : null}
- </div>
- )
-}
-
const ViewProjectContent = () => {
- const { id, project, preferences, updatePreferences, extensions, mergeProject, allowedToManage, liveVisitors } =
- useCurrentProject()
+ const { id, project, preferences, updatePreferences, extensions, allowedToManage, liveVisitors } = useCurrentProject()
const projectPassword = useProjectPassword(id)
const { theme, setTheme } = useTheme()
@@ -476,8 +376,6 @@ const ViewProjectContent = () => {
const [customPanelTabs, setCustomPanelTabs] = useState<CustomTab[]>([])
const [sdkInstance, setSdkInstance] = useState<SwetrixSDK | null>(null)
- const [activeChartMetricsCustomEvents, setActiveChartMetricsCustomEvents] = useState<string[]>([])
-
const dashboardRef = useRef<HTMLDivElement>(null)
const navigate = useNavigate()
@@ -495,7 +393,8 @@ const ViewProjectContent = () => {
return tabs.split(',')
}, [searchParams])
- const [panelsData, setPanelsData] = useState<{
+ // Traffic data state - now handled by TrafficView, kept for export compatibility
+ const [_panelsData, _setPanelsData] = useState<{
types: (keyof Params)[]
data: Params
customs: Customs
@@ -504,25 +403,22 @@ const ViewProjectContent = () => {
// @ts-expect-error
}>({})
const [customExportTypes, setCustomExportTypes] = useState<
- { label: string; onClick: (data: typeof panelsData, tFunction: typeof t) => void }[]
+ { label: string; onClick: (data: typeof _panelsData, tFunction: typeof t) => void }[]
>([])
- const [overall, setOverall] = useState<Partial<OverallObject>>({})
- const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)
- const [isNewFunnelOpened, setIsNewFunnelOpened] = useState(false)
const [isAddAViewOpened, setIsAddAViewOpened] = useState(false)
- const [analyticsLoading, setAnalyticsLoading] = useState(true)
+ const [analyticsLoading, _setAnalyticsLoading] = useState(true)
- // @ts-expect-error
- const [chartData, setChartData] = useState<TrafficLogResponse['chart'] & { [key: string]: number[] }>({})
// prevY2NeededRef removed - no longer needed with new chart management
- const [dataLoading, setDataLoading] = useState(false)
+ const [dataLoading, _setDataLoading] = useState(false)
const [isAutoRefreshing, setIsAutoRefreshing] = useState(false)
const [captchaRefreshTrigger, setCaptchaRefreshTrigger] = useState(0)
const [goalsRefreshTrigger, setGoalsRefreshTrigger] = useState(0)
const [featureFlagsRefreshTrigger, setFeatureFlagsRefreshTrigger] = useState(0)
const [sessionsRefreshTrigger, setSessionsRefreshTrigger] = useState(0)
const [performanceRefreshTrigger, setPerformanceRefreshTrigger] = useState(0)
- const [activeChartMetrics, setActiveChartMetrics] = useState<Record<keyof typeof CHART_METRICS_MAPPING, boolean>>({
+ const [trafficRefreshTrigger, setTrafficRefreshTrigger] = useState(0)
+ const [funnelsRefreshTrigger, setFunnelsRefreshTrigger] = useState(0)
+ const [activeChartMetrics, _setActiveChartMetrics] = useState<Record<keyof typeof CHART_METRICS_MAPPING, boolean>>({
[CHART_METRICS_MAPPING.unique]: true,
[CHART_METRICS_MAPPING.views]: false,
[CHART_METRICS_MAPPING.sessionDuration]: false,
@@ -533,24 +429,11 @@ const ViewProjectContent = () => {
[CHART_METRICS_MAPPING.customEvents]: false,
...(preferences.metricsVisualisation || {}),
})
- const checkIfAllMetricsAreDisabled = useMemo(
- () => !_some({ ...activeChartMetrics, ...activeChartMetricsCustomEvents }, (value) => value),
- [activeChartMetrics, activeChartMetricsCustomEvents],
- )
const [customMetrics, setCustomMetrics] = useState<ProjectViewCustomEvent[]>([])
const filters = useMemo<Filter[]>(() => {
return parseFilters(searchParams)
}, [searchParams])
- // Search params without the session id, error id or funnel id. Needed for the back button.
- const pureSearchParams = useMemo(() => {
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.delete('psid')
- newSearchParams.delete('eid')
- newSearchParams.delete('funnelId')
- return newSearchParams.toString()
- }, [searchParams])
-
const tnMapping = typeNameMapping(t)
const refCalendar = useRef(null)
const refCalendarCompare = useRef(null)
@@ -678,26 +561,6 @@ const ViewProjectContent = () => {
return searchParams.get('psid')
}, [searchParams])
- const [funnelToEdit, setFunnelToEdit] = useState<Funnel | undefined>(undefined)
- const [funnelActionLoading, setFunnelActionLoading] = useState(false)
- const [funnelAnalytics, setFunnelAnalytics] = useState<{
- funnel: AnalyticsFunnel[]
- totalPageviews: number
- } | null>(null)
- const activeFunnel = useMemo(() => {
- if (!project) {
- return null
- }
-
- const funnelId = searchParams.get('funnelId')
-
- if (!funnelId) {
- return null
- }
-
- return _find(project.funnels, (funnel) => funnel.id === funnelId) || null
- }, [searchParams, project])
-
// null -> not loaded yet
const [projectViews, setProjectViews] = useState<ProjectView[]>([])
const [projectViewsLoading, setProjectViewsLoading] = useState<boolean | null>(null) // // null - not loaded, true - loading, false - loaded
@@ -768,81 +631,6 @@ const ViewProjectContent = () => {
setProjectViewDeleting(false)
}
- const onFunnelCreate = async (name: string, steps: string[]) => {
- if (funnelActionLoading) {
- return
- }
-
- setFunnelActionLoading(true)
-
- try {
- await addFunnel(id, name, steps)
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelCreate)(addFunnel)', reason)
- toast.error(reason)
- }
-
- try {
- const funnels = await getFunnels(id, projectPassword)
- mergeProject({ funnels })
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelCreate)(getFunnels)', reason)
- }
-
- toast.success(t('apiNotifications.funnelCreated'))
- setFunnelActionLoading(false)
- }
-
- const onFunnelEdit = async (funnelId: string, name: string, steps: string[]) => {
- if (funnelActionLoading) {
- return
- }
-
- setFunnelActionLoading(true)
-
- try {
- await updateFunnel(funnelId, id, name, steps)
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelEdit)(updateFunnel)', reason)
- toast.error(reason)
- }
-
- try {
- const funnels = await getFunnels(id, projectPassword)
- mergeProject({ funnels })
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelCreate)(getFunnels)', reason)
- }
-
- toast.success(t('apiNotifications.funnelUpdated'))
- setFunnelActionLoading(false)
- }
-
- const onFunnelDelete = async (funnelId: string) => {
- if (funnelActionLoading) {
- return
- }
-
- setFunnelActionLoading(true)
-
- try {
- await deleteFunnel(funnelId, id)
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelDelete)(deleteFunnel)', reason)
- toast.error(reason)
- }
-
- try {
- const funnels = await getFunnels(id, projectPassword)
- mergeProject({ funnels })
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelCreate)(getFunnels)', reason)
- }
-
- toast.success(t('apiNotifications.funnelDeleted'))
- setFunnelActionLoading(false)
- }
-
// Annotation functions
const loadAnnotations = async () => {
if (annotationsLoading) {
@@ -999,34 +787,6 @@ const ViewProjectContent = () => {
setContextMenu((prev) => ({ ...prev, isOpen: false }))
}
- const [panelsActiveTabs, setPanelsActiveTabs] = useState<{
- location: 'cc' | 'rg' | 'ct' | 'lc' | 'map'
- page: 'pg' | 'host' | 'userFlow' | 'entryPage' | 'exitPage'
- device: 'br' | 'os' | 'dv'
- source: 'ref' | 'so' | 'me' | 'ca' | 'te' | 'co' | 'keywords'
- metadata: 'ce' | 'props'
- }>({
- location: 'cc',
- page: 'pg',
- device: 'br',
- source: 'ref',
- metadata: 'ce',
- })
-
- const setPanelTab = (
- panel: keyof typeof panelsActiveTabs,
- tab: (typeof panelsActiveTabs)[keyof typeof panelsActiveTabs],
- ) => {
- const extensionTab = customPanelTabs.find((el) => el.panelID === panel && el.tabContent === tab)
-
- extensionTab?.onOpen?.()
-
- setPanelsActiveTabs((prev) => ({
- ...prev,
- [panel]: tab,
- }))
- }
-
const getVersionFilterLink = (parent: string | null, version: string | null, panelType: 'br' | 'os') => {
const filterParams = new URLSearchParams(searchParams.toString())
@@ -1043,22 +803,9 @@ const ViewProjectContent = () => {
return `?${filterParams.toString()}`
}
- // GSC Keywords state
- type KeywordEntry = Entry & { impressions: number; position: number; ctr: number }
- const [keywordsLoading, setKeywordsLoading] = useState<boolean>(false)
- const [keywordsNotConnected, setKeywordsNotConnected] = useState<boolean>(false)
- const [keywords, setKeywords] = useState<KeywordEntry[]>([])
-
const timeFormat = useMemo<'12-hour' | '24-hour'>(() => user?.timeFormat || TimeFormat['12-hour'], [user])
const [ref, size] = useSize()
const rotateXAxis = useMemo(() => size.width > 0 && size.width < 500, [size])
- const customEventsChartData = useMemo(
- () =>
- _pickBy(preferences.customEvents, (value, keyCustomEvents) =>
- _includes(activeChartMetricsCustomEvents, keyCustomEvents),
- ),
- [preferences.customEvents, activeChartMetricsCustomEvents],
- )
const [chartType, setChartType] = useState<keyof typeof chartTypes>(
(getItem('chartType') as keyof typeof chartTypes) || chartTypes.line,
)
@@ -1071,12 +818,6 @@ const ViewProjectContent = () => {
>(tbPeriodPairsCompare(t, undefined, language))
const [isActiveCompare, setIsActiveCompare] = useState(getItem(LS_IS_ACTIVE_COMPARE_KEY) === 'true')
const [activePeriodCompare, setActivePeriodCompare] = useState(periodPairsCompare[0].period)
- const activeDropdownLabelCompare = useMemo(
- () => _find(periodPairsCompare, (p) => p.period === activePeriodCompare)?.label,
- [periodPairsCompare, activePeriodCompare],
- )
- const [dataChartCompare, setDataChartCompare] = useState<any>({})
- const [overallCompare, setOverallCompare] = useState<Partial<OverallObject>>({})
const maxRangeCompare = useMemo(() => {
if (!isActiveCompare) {
return 0
@@ -1091,36 +832,6 @@ const ViewProjectContent = () => {
return findActivePeriod?.countDays || 0
}, [isActiveCompare, period, dateRange, periodPairs])
- const createVersionDataMapping = useMemo(() => {
- const browserDataSource = panelsData.data?.brv
- const osDataSource = panelsData.data?.osv
-
- const browserVersions: { [key: string]: Entry[] } = {}
- const osVersions: { [key: string]: Entry[] } = {}
-
- if (browserDataSource) {
- browserDataSource.forEach((entry: any) => {
- const { br, name, count } = entry
- if (!browserVersions[br]) {
- browserVersions[br] = []
- }
- browserVersions[br].push({ name, count })
- })
- }
-
- if (osDataSource) {
- osDataSource.forEach((entry: any) => {
- const { os, name, count } = entry
- if (!osVersions[os]) {
- osVersions[os] = []
- }
- osVersions[os].push({ name, count })
- })
- }
-
- return { browserVersions, osVersions }
- }, [panelsData.data?.brv, panelsData.data?.osv])
-
useEffect(() => {
if (!project) {
return
@@ -1167,100 +878,6 @@ const ViewProjectContent = () => {
const [showFiltersSearch, setShowFiltersSearch] = useState(false)
- const isConflicted = (conflicts?: string[]) => {
- if (!conflicts) {
- return false
- }
-
- return _some(conflicts, (conflict) => {
- const conflictPair = _find(chartMetrics, (metric) => metric.id === conflict)
- return conflictPair && conflictPair.active
- })
- }
-
- const chartMetrics = useMemo(() => {
- return [
- {
- id: CHART_METRICS_MAPPING.unique,
- label: t('dashboard.sessions'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.unique],
- },
- {
- id: CHART_METRICS_MAPPING.views,
- label: t('project.showAll'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.views],
- },
- {
- id: CHART_METRICS_MAPPING.sessionDuration,
- label: t('dashboard.sessionDuration'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.sessionDuration],
- conflicts: [CHART_METRICS_MAPPING.bounce],
- },
- {
- id: CHART_METRICS_MAPPING.bounce,
- label: t('dashboard.bounceRate'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.bounce],
- conflicts: [CHART_METRICS_MAPPING.sessionDuration],
- },
- {
- id: CHART_METRICS_MAPPING.viewsPerUnique,
- label: t('dashboard.viewsPerUnique'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.viewsPerUnique],
- },
- {
- id: CHART_METRICS_MAPPING.trendlines,
- label: t('dashboard.trendlines'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.trendlines],
- },
- {
- id: CHART_METRICS_MAPPING.cumulativeMode,
- label: t('dashboard.cumulativeMode'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode],
- },
- {
- id: CHART_METRICS_MAPPING.customEvents,
- label: t('project.customEv'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.customEvents],
- },
- ]
- }, [t, activeChartMetrics])
-
- const chartMetricsCustomEvents = useMemo(() => {
- if (!_isEmpty(panelsData.customs)) {
- return _map(_keys(panelsData.customs), (key) => ({
- id: key,
- label: key,
- active: _includes(activeChartMetricsCustomEvents, key),
- }))
- }
- return []
- }, [panelsData, activeChartMetricsCustomEvents])
-
- const dataNamesCustomEvents = useMemo(() => {
- if (!_isEmpty(panelsData.customs)) {
- return { ..._keys(panelsData.customs) }
- }
- return {}
- }, [panelsData])
-
- const dataNames = useMemo(
- () => ({
- unique: t('dashboard.sessions'),
- total: t('project.total'),
- pageviews: t('project.pageviews'),
- customEvents: t('project.customEvents'),
- errors: t('project.errors'),
- bounce: `${t('dashboard.bounceRate')} (%)`,
- viewsPerUnique: t('dashboard.viewsPerUnique'),
- trendlineTotal: t('project.trendlineTotal'),
- trendlineUnique: t('project.trendlineUnique'),
- occurrences: t('project.occurrences'),
- sessionDuration: t('dashboard.sessionDuration'),
- ...dataNamesCustomEvents,
- }),
- [t, dataNamesCustomEvents],
- )
-
// @ts-expect-error
const tabs: {
id: keyof typeof PROJECT_TABS | 'settings'
@@ -1353,359 +970,12 @@ const ViewProjectContent = () => {
const activeTabLabel = useMemo(() => _find(tabs, (tab) => tab.id === activeTab)?.label, [tabs, activeTab])
- const switchTrafficChartMetric = (pairID: keyof typeof CHART_METRICS_MAPPING, conflicts?: string[]) => {
- if (isConflicted(conflicts)) {
- toast.error(t('project.conflictMetric'))
- return
- }
-
- if (pairID === CHART_METRICS_MAPPING.customEvents) {
- return
- }
-
- setActiveChartMetrics((prev) => {
- const newActiveChartMetrics = { ...prev, [pairID]: !prev[pairID] }
- updatePreferences({
- metricsVisualisation: newActiveChartMetrics,
- })
- return newActiveChartMetrics
- })
- }
-
- const switchCustomEventChart = (id: string) => {
- setActiveChartMetricsCustomEvents((prev) => {
- const newActiveChartMetricsCustomEvents = [...prev]
- const index = _findIndex(prev, (item) => item === id)
- if (index === -1) {
- newActiveChartMetricsCustomEvents.push(id)
- } else {
- newActiveChartMetricsCustomEvents.splice(index, 1)
- }
- return newActiveChartMetricsCustomEvents
- })
- }
-
- const loadCustomEvents = async () => {
- if (_isEmpty(panelsData.customs)) {
- return
- }
-
- let data = null
- let from
- let to
-
- try {
- setDataLoading(true)
-
- if (dateRange) {
- from = getFormatDate(dateRange[0])
- to = getFormatDate(dateRange[1])
- }
-
- if (activeChartMetricsCustomEvents.length > 0) {
- if (period === 'custom' && dateRange) {
- data = await getProjectDataCustomEvents(
- id,
- timeBucket,
- '',
- filters,
- from,
- to,
- timezone,
- activeChartMetricsCustomEvents,
- projectPassword,
- )
- } else {
- data = await getProjectDataCustomEvents(
- id,
- timeBucket,
- period,
- filters,
- '',
- '',
- timezone,
- activeChartMetricsCustomEvents,
- projectPassword,
- )
- }
- }
-
- const events = data?.chart ? data.chart.events : customEventsChartData
-
- updatePreferences({
- customEvents: events,
- })
- } catch (reason) {
- console.error('[ERROR] Failed to load custom events:', reason)
- } finally {
- setDataLoading(false)
- }
- }
-
const compareDisable = () => {
setIsActiveCompare(false)
setDateRangeCompare(null)
- setDataChartCompare({})
- setOverallCompare({})
setActivePeriodCompare(periodPairsCompare[0].period)
}
- const loadAnalytics = async () => {
- setDataLoading(true)
- try {
- let data: TrafficLogResponse & {
- overall?: OverallObject
- }
- let dataCompare:
- | (TrafficLogResponse & {
- overall?: OverallObject
- })
- | null = null
- let from
- let fromCompare: string | undefined
- let to
- let toCompare: string | undefined
- let customEventsChart = customEventsChartData
- let rawOverall: any
-
- if (isActiveCompare) {
- if (dateRangeCompare && activePeriodCompare === PERIOD_PAIRS_COMPARE.CUSTOM) {
- let start
- let end
- let diff
- const startCompare = dayjs.utc(dateRangeCompare[0])
- const endCompare = dayjs.utc(dateRangeCompare[1])
- const diffCompare = endCompare.diff(startCompare, 'day')
-
- if (activePeriod?.period === 'custom' && dateRange) {
- start = dayjs.utc(dateRange[0])
- end = dayjs.utc(dateRange[1])
- diff = end.diff(start, 'day')
- }
-
- // @ts-expect-error
- if (activePeriod?.period === 'custom' ? diffCompare <= diff : diffCompare <= activePeriod?.countDays) {
- fromCompare = getFormatDate(dateRangeCompare[0])
- toCompare = getFormatDate(dateRangeCompare[1])
- } else {
- toast.error(t('project.compareDateRangeError'))
- compareDisable()
- }
- } else {
- let date
- if (dateRange) {
- date = _find(periodToCompareDate, (item) => item.period === period)?.formula(dateRange)
- } else {
- date = _find(periodToCompareDate, (item) => item.period === period)?.formula()
- }
-
- if (date) {
- fromCompare = date.from
- toCompare = date.to
- }
- }
-
- if (!_isEmpty(fromCompare) && !_isEmpty(toCompare)) {
- dataCompare =
- (await getTrafficCompareData(
- id,
- timeBucket,
- '',
- filters,
- fromCompare,
- toCompare,
- timezone,
- projectPassword,
- mode,
- )) || {}
- const compareOverall = await getOverallStats(
- [id],
- timeBucket,
- 'custom',
- fromCompare,
- toCompare,
- timezone,
- filters,
- projectPassword,
- )
-
- // @ts-expect-error
- dataCompare.overall = compareOverall[id]
- }
- }
-
- if (dateRange) {
- from = getFormatDate(dateRange[0])
- to = getFormatDate(dateRange[1])
- }
-
- if (period === 'custom' && dateRange) {
- data = await getProjectData(
- id,
- timeBucket,
- '',
- filters,
- customMetrics,
- from,
- to,
- timezone,
- projectPassword,
- mode,
- )
- if (activeChartMetricsCustomEvents.length > 0) {
- customEventsChart = await getProjectDataCustomEvents(
- id,
- timeBucket,
- '',
- filters,
- from,
- to,
- timezone,
- activeChartMetricsCustomEvents,
- projectPassword,
- )
- }
- rawOverall = await getOverallStats([id], timeBucket, period, from, to, timezone, filters, projectPassword)
- } else {
- data = await getProjectData(
- id,
- timeBucket,
- period,
- filters,
- customMetrics,
- '',
- '',
- timezone,
- projectPassword,
- mode,
- )
- if (activeChartMetricsCustomEvents.length > 0) {
- customEventsChart = await getProjectDataCustomEvents(
- id,
- timeBucket,
- period,
- filters,
- '',
- '',
- timezone,
- activeChartMetricsCustomEvents,
- projectPassword,
- )
- }
- rawOverall = await getOverallStats([id], timeBucket, period, '', '', timezone, filters, projectPassword)
- }
-
- customEventsChart = customEventsChart?.chart ? customEventsChart.chart.events : customEventsChartData
-
- updatePreferences({
- customEvents: customEventsChart,
- })
-
- data.overall = rawOverall[id]
- setOverall(rawOverall[id])
-
- const sdkData = {
- ...(data || {}),
- filters,
- timezone,
- timeBucket,
- period,
- from,
- to,
- }
-
- if (_keys(data).length < 2) {
- setAnalyticsLoading(false)
- setDataLoading(false)
- setIsPanelsDataEmpty(true)
- sdkInstance?._emitEvent('load', sdkData)
- return
- }
-
- const { chart, params, customs, properties, meta } = data
- let newTimebucket = timeBucket
- sdkInstance?._emitEvent('load', sdkData)
-
- if (period === 'all' && !_isEmpty(data.timeBucket)) {
- newTimebucket = _includes(data.timeBucket, timeBucket) ? timeBucket : (data.timeBucket?.[0] as TimeBucket)
-
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.set('timeBucket', newTimebucket)
- setSearchParams(newSearchParams)
- }
-
- if (!_isEmpty(dataCompare)) {
- if (!_isEmpty(dataCompare?.chart)) {
- setDataChartCompare(dataCompare.chart)
- }
-
- if (!_isEmpty(dataCompare?.overall)) {
- setOverallCompare(dataCompare.overall)
- }
- }
-
- if (_isEmpty(params)) {
- setIsPanelsDataEmpty(true)
- } else {
- setChartData(chart as any)
-
- setPanelsData({
- types: _keys(params),
- data: params,
- customs,
- properties,
- meta,
- })
-
- setIsPanelsDataEmpty(false)
- }
-
- setAnalyticsLoading(false)
- setDataLoading(false)
- } catch (reason) {
- setAnalyticsLoading(false)
- setDataLoading(false)
- setIsPanelsDataEmpty(true)
- console.error('[ERROR](loadAnalytics) Loading analytics data failed')
- console.error(reason)
- }
- }
-
- const getCustomEventMetadata = async (event: string) => {
- if (period === 'custom' && dateRange) {
- return getCustomEventsMetadata(
- id,
- event,
- timeBucket,
- '',
- getFormatDate(dateRange[0]),
- getFormatDate(dateRange[1]),
- timezone,
- projectPassword,
- )
- }
-
- return getCustomEventsMetadata(id, event, timeBucket, period, '', '', timezone, projectPassword)
- }
-
- const _getPropertyMetadata = async (event: string) => {
- if (period === 'custom' && dateRange) {
- return getPropertyMetadata(
- id,
- event,
- timeBucket,
- '',
- getFormatDate(dateRange[0]),
- getFormatDate(dateRange[1]),
- filters,
- timezone,
- projectPassword,
- )
- }
-
- return getPropertyMetadata(id, event, timeBucket, period, '', '', filters, timezone, projectPassword)
- }
-
const loadProfiles = async (forcedSkip?: number, override?: boolean) => {
if (profilesLoading) {
return
@@ -1882,46 +1152,6 @@ const ViewProjectContent = () => {
}
}
- const loadFunnelsData = async () => {
- if (!activeFunnel?.id) {
- return
- }
-
- setDataLoading(true)
-
- try {
- let dataFunnel: { funnel: AnalyticsFunnel[]; totalPageviews: number }
- let from
- let to
-
- if (dateRange) {
- from = getFormatDate(dateRange[0])
- to = getFormatDate(dateRange[1])
- }
-
- if (period === 'custom' && dateRange) {
- dataFunnel = await getFunnelData(id, '', from, to, timezone, activeFunnel.id, projectPassword)
- } else {
- dataFunnel = await getFunnelData(id, period, '', '', timezone, activeFunnel.id, projectPassword)
- }
-
- const { funnel, totalPageviews } = dataFunnel
-
- setFunnelAnalytics({ funnel, totalPageviews })
-
- // Unhide the wrapper first, then mount the chart on the next tick
- setAnalyticsLoading(false)
- setDataLoading(false)
-
- await new Promise((resolve) => setTimeout(resolve, 1))
- } catch (reason) {
- setAnalyticsLoading(false)
- setDataLoading(false)
-
- console.error('[ERROR](loadFunnelsData) Loading funnels data failed:', reason)
- }
- }
-
const onCustomMetric = (metrics: ProjectViewCustomEvent[]) => {
if (activeTab !== PROJECT_TABS.traffic) {
return
@@ -1958,24 +1188,6 @@ const ViewProjectContent = () => {
setSearchParams(newSearchParams)
}
- const funnelSummary = useMemo(() => {
- if (!funnelAnalytics || _isEmpty(funnelAnalytics.funnel)) {
- return null
- }
-
- const stepsCount = funnelAnalytics.funnel.length
- const startVisitors = funnelAnalytics.funnel[0]?.events || 0
- const endVisitors = funnelAnalytics.funnel[stepsCount - 1]?.events || 0
- const conversionRate = Number(((endVisitors / Math.max(startVisitors, 1)) * 100).toFixed(2))
-
- return {
- stepsCount,
- startVisitors,
- endVisitors,
- conversionRate,
- }
- }, [funnelAnalytics])
-
const refreshStats = useCallback(
async (isManual = true) => {
if (!isManual) {
@@ -1984,7 +1196,7 @@ const ViewProjectContent = () => {
if (!authLoading && !dataLoading) {
if (activeTab === PROJECT_TABS.funnels) {
- loadFunnelsData()
+ setFunnelsRefreshTrigger((prev) => prev + 1)
return
}
@@ -2024,20 +1236,16 @@ const ViewProjectContent = () => {
return
}
- loadAnalytics()
+ if (activeTab === PROJECT_TABS.traffic) {
+ setTrafficRefreshTrigger((prev) => prev + 1)
+ return
+ }
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[authLoading, dataLoading, activeTab, activeProfileId],
)
- useEffect(() => {
- if (activeTab !== PROJECT_TABS.traffic || authLoading || !project) return
-
- loadAnalytics()
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [mode, activeTab, customMetrics, filters, authLoading, project, isActiveCompare, dateRange, period, timeBucket])
-
// Load annotations when project loads
useEffect(() => {
if (authLoading || !project) {
@@ -2048,68 +1256,6 @@ const ViewProjectContent = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [authLoading, project])
- useEffect(() => {
- if (activeTab !== PROJECT_TABS.traffic || authLoading || !project) {
- return
- }
-
- loadCustomEvents()
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [activeChartMetricsCustomEvents, activeTab, authLoading, project])
-
- // Load GSC Keywords when the traffic sources panel switches to 'keywords'
- useEffect(() => {
- const loadKeywords = async () => {
- if (authLoading || !project) return
- if (activeTab !== PROJECT_TABS.traffic) return
- if (panelsActiveTabs.source !== 'keywords') return
- if (keywordsLoading) return
-
- setKeywordsLoading(true)
- setKeywordsNotConnected(false)
-
- try {
- let from: string | undefined
- let to: string | undefined
- if (dateRange) {
- from = getFormatDate(dateRange[0])
- to = getFormatDate(dateRange[1])
- }
-
- const res = await getGSCKeywords(id, period, from, to, timezone, projectPassword)
- const list = (res?.keywords || []).map(
- (k: { name: string; count: number; impressions: number; position: number; ctr: number }) => ({
- name: k.name,
- count: k.count,
- impressions: k.impressions,
- position: k.position,
- ctr: k.ctr,
- }),
- )
- setKeywords(list)
- } catch (error: any) {
- const message = typeof error === 'string' ? error : error?.message
- if (message && (message as string).toLowerCase().includes('search console')) {
- setKeywordsNotConnected(true)
- } else {
- toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))
- }
- } finally {
- setKeywordsLoading(false)
- }
- }
-
- loadKeywords()
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [activeTab, panelsActiveTabs.source, period, dateRange, timezone, id, project, authLoading])
-
- useEffect(() => {
- if (activeTab !== PROJECT_TABS.funnels || authLoading || !project) return
-
- loadFunnelsData()
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [activeFunnel, activeTab, authLoading, project, dateRange, period, timeBucket])
-
// Load profiles list when users tab is active
useEffect(() => {
if (authLoading || activeTab !== PROJECT_TABS.profiles || !project || activeProfileId) {
@@ -2417,7 +1563,7 @@ const ViewProjectContent = () => {
{
label: t('project.asCSV'),
onClick: () => {
- return onCSVExportClick(panelsData, id, tnMapping, language)
+ return onCSVExportClick(_panelsData, id, tnMapping, language)
},
},
]
@@ -2659,6 +1805,8 @@ const ViewProjectContent = () => {
featureFlagsRefreshTrigger,
sessionsRefreshTrigger,
performanceRefreshTrigger,
+ trafficRefreshTrigger,
+ funnelsRefreshTrigger,
// Functions
updatePeriod,
@@ -2710,308 +1858,48 @@ const ViewProjectContent = () => {
>
{activeTab !== PROJECT_TABS.alerts &&
activeTab !== PROJECT_TABS.ai &&
- (activeTab !== PROJECT_TABS.sessions || !activePSID) &&
- (activeFunnel || activeTab !== PROJECT_TABS.funnels) ? (
- <>
- <div className='relative top-0 z-20 -mt-2 flex flex-col items-center justify-between bg-gray-50/50 py-2 backdrop-blur-md lg:sticky lg:flex-row dark:bg-slate-900/50'>
- <div className='flex flex-wrap items-center justify-center gap-2'>
- {activeTab === PROJECT_TABS.funnels ? (
- <Text as='h2' size='xl' weight='bold' className='break-words break-all'>
- {activeFunnel?.name}
- </Text>
- ) : 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 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 ? (
- <>
- <RefreshStatsButton onRefresh={refreshStats} />
- <div
- className={cx('border-gray-200 dark:border-gray-600', {
- // @ts-expect-error
- 'lg:border-r': activeTab === PROJECT_TABS.funnels,
- hidden: activeTab === PROJECT_TABS.errors,
- })}
- >
- <button
- type='button'
- title={t('project.search')}
- onClick={() => {
- if (dataLoading) {
- return
- }
-
- setShowFiltersSearch(true)
- }}
- 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,
- },
- )}
- >
- <SearchIcon className='h-5 w-5 text-gray-700 dark:text-gray-50' />
- </button>
- </div>
- {activeTab === PROJECT_TABS.traffic ? (
- <Dropdown
- header={t('project.segments')}
- onClick={() => loadProjectViews()}
- loading={projectViewsLoading || projectViewsLoading === null}
- items={_filter(
- [
- ...projectViews,
- allowedToManage && {
- id: 'add-a-view',
- name: t('project.addASegment'),
- createView: true,
- },
- !allowedToManage &&
- _isEmpty(projectViews) && {
- id: 'no-views',
- name: t('project.noSegmentsYet'),
- notClickable: true,
- },
- ],
- (x) => !!x,
- )}
- title={[<BookmarkIcon key='bookmark-icon' className='h-5 w-5' />]}
- labelExtractor={(item, close) => {
- // @ts-expect-error
- if (item.createView) {
- return item.name
- }
-
- if (item.id === 'no-views') {
- return <Text colour='secondary'>{item.name}</Text>
- }
-
- return (
- <div
- className={cx('flex items-center justify-between space-x-4', {
- 'cursor-wait': dataLoading,
- })}
- >
- <span>{item.name}</span>
- {allowedToManage ? (
- <div className='flex cursor-pointer space-x-1'>
- <button
- onClick={(e) => {
- e.stopPropagation()
- setProjectViewToUpdate(item)
- close()
- setIsAddAViewOpened(true)
- }}
- aria-label={t('common.settings')}
- className='rounded-md p-1 hover:bg-gray-50 hover:text-gray-900 dark:hover:bg-slate-800 dark:hover:text-slate-200'
- >
- <PencilIcon className='size-3' />
- </button>
- <button
- onClick={(e) => {
- e.stopPropagation()
- close()
- onProjectViewDelete(item.id)
- }}
- aria-label={t('common.settings')}
- className={cx(
- 'rounded-md p-1 hover:bg-gray-50 hover:text-gray-900 dark:hover:bg-slate-800 dark:hover:text-slate-200',
- {
- 'cursor-not-allowed': projectViewDeleting,
- },
- )}
- >
- <Trash2Icon className='size-3' />
- </button>
- </div>
- ) : null}
- </div>
- )
- }}
- keyExtractor={(item) => item.id}
- onSelect={(item: ProjectView, e) => {
- // @ts-expect-error
- if (item.createView) {
- e?.stopPropagation()
- setIsAddAViewOpened(true)
-
- return
- }
-
- if (item.filters && !_isEmpty(item.filters)) {
- const newUrlParams = getFiltersUrlParams(
- filters,
- item.filters,
- true,
- searchParams,
- )
- setSearchParams(newUrlParams)
- }
-
- if (item.customEvents && !_isEmpty(item.customEvents)) {
- onCustomMetric(item.customEvents)
- }
- }}
- chevron='mini'
- buttonClassName='!p-2 rounded-md hover:bg-white border border-gray-50/0 hover:border-gray-300 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:z-10 focus:outline-hidden focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 focus:dark:ring-gray-200'
- headless
- />
- ) : null}
- {activeTab === PROJECT_TABS.traffic ? (
- <Dropdown
- header={t('project.exportData')}
- items={_filter(
- [
- ...exportTypes,
- ...customExportTypes,
- !isSelfhosted && {
- label: t('project.lookingForMore'),
- lookingForMore: true,
- onClick: () => {},
- },
- ],
- (el) => !!el,
- )}
- title={[<DownloadIcon key='download-icon' className='h-5 w-5' />]}
- labelExtractor={(item) => item.label}
- keyExtractor={(item) => item.label}
- onSelect={(item, e) => {
- // @ts-expect-error lookingForMore is defined as an exception above
- if (item.lookingForMore) {
- e?.stopPropagation()
- window.open(MARKETPLACE_URL, '_blank')
-
- return
- }
-
- trackCustom('DASHBOARD_EXPORT', {
- type: item.label === t('project.asCSV') ? 'csv' : 'extension',
- })
-
- item.onClick(panelsData, t)
- }}
- chevron='mini'
- buttonClassName='!p-2 rounded-md hover:bg-white border border-gray-50/0 hover:border-gray-300 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:z-10 focus:outline-hidden focus:ring-1 focus:ring-indigo-500 focus:dark:ring-gray-200'
- headless
- />
- ) : null}
- </>
- ) : null}
- {activeTab === PROJECT_TABS.funnels ? (
- <RefreshStatsButton onRefresh={refreshStats} />
- ) : null}
- <div className='flex items-center'>
- <TBPeriodSelector
- classes={{
- timeBucket: activeTab === PROJECT_TABS.errors ? 'hidden' : '',
- }}
- activePeriod={activePeriod}
- items={timeBucketSelectorItems}
- title={activePeriod?.label}
- onSelect={(pair) => {
- if (dataLoading) {
- return
- }
-
- if (pair.period === PERIOD_PAIRS_COMPARE.COMPARE) {
- // @ts-expect-error
- if (activeTab === PROJECT_TABS.alerts) {
- return
- }
-
- if (isActiveCompare) {
- compareDisable()
- } else {
- setIsActiveCompare(true)
- }
-
- return
- }
-
- if (pair.isCustomDate) {
- setTimeout(() => {
- // @ts-expect-error
- refCalendar.current.openCalendar()
- }, 100)
- } else {
- resetDateRange()
- updatePeriod(pair)
- }
- }}
- />
- <DatePicker
- ref={refCalendar}
- onChange={([from, to]) => {
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.set('from', from.toISOString())
- newSearchParams.set('to', to.toISOString())
- newSearchParams.set('period', 'custom')
- setSearchParams(newSearchParams)
- }}
- value={dateRange || []}
- maxDateMonths={MAX_MONTHS_IN_PAST}
- maxRange={0}
- />
- <DatePicker
- ref={refCalendarCompare}
- onChange={(date) => {
- setDateRangeCompare(date)
- setActivePeriodCompare(PERIOD_PAIRS_COMPARE.CUSTOM)
- setPeriodPairsCompare(tbPeriodPairsCompare(t, date, language))
- }}
- value={dateRangeCompare || []}
- maxDateMonths={MAX_MONTHS_IN_PAST}
- maxRange={maxRangeCompare}
- />
- </div>
- {isActiveCompare && activeTab !== PROJECT_TABS.errors ? (
- <>
- <div className='text-md mx-2 font-medium whitespace-pre-line text-gray-600 dark:text-gray-200'>
- vs
- </div>
- <Dropdown
- items={periodPairsCompare}
- title={activeDropdownLabelCompare}
- labelExtractor={(pair) => pair.label}
- keyExtractor={(pair) => pair.label}
- onSelect={(pair) => {
- if (pair.period === PERIOD_PAIRS_COMPARE.DISABLE) {
- compareDisable()
- return
- }
-
- if (pair.period === PERIOD_PAIRS_COMPARE.CUSTOM) {
- setTimeout(() => {
- // @ts-expect-error
- refCalendarCompare.current.openCalendar()
- }, 100)
- } else {
- setPeriodPairsCompare(tbPeriodPairsCompare(t, undefined, language))
- setDateRangeCompare(null)
- setActivePeriodCompare(pair.period)
- }
- }}
- chevron='mini'
- headless
- />
- </>
- ) : null}
- </div>
- </div>
- {activeTab === PROJECT_TABS.funnels ? (
- <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.backToFunnels')}
- </Link>
- </div>
- ) : null}
- </>
+ activeTab !== PROJECT_TABS.funnels &&
+ (activeTab !== PROJECT_TABS.sessions || !activePSID) ? (
+ <DashboardHeader
+ refreshStats={refreshStats}
+ timeBucketSelectorItems={timeBucketSelectorItems}
+ isActiveCompare={isActiveCompare}
+ setIsActiveCompare={setIsActiveCompare}
+ compareDisable={compareDisable}
+ maxRangeCompare={maxRangeCompare}
+ dateRangeCompare={dateRangeCompare}
+ setDateRangeCompare={setDateRangeCompare}
+ activePeriodCompare={activePeriodCompare}
+ setActivePeriodCompare={setActivePeriodCompare}
+ periodPairsCompare={periodPairsCompare}
+ setPeriodPairsCompare={setPeriodPairsCompare}
+ setShowFiltersSearch={setShowFiltersSearch}
+ resetDateRange={resetDateRange}
+ refCalendar={refCalendar}
+ refCalendarCompare={refCalendarCompare}
+ showSearchButton={activeTab !== PROJECT_TABS.errors}
+ hideTimeBucket={activeTab === PROJECT_TABS.errors}
+ rightContent={
+ activeTab === PROJECT_TABS.traffic ? (
+ <TrafficHeaderActions
+ projectViews={projectViews}
+ projectViewsLoading={projectViewsLoading}
+ projectViewDeleting={projectViewDeleting}
+ loadProjectViews={loadProjectViews}
+ onProjectViewDelete={onProjectViewDelete}
+ setProjectViewToUpdate={setProjectViewToUpdate}
+ setIsAddAViewOpened={setIsAddAViewOpened}
+ onCustomMetric={onCustomMetric}
+ filters={filters}
+ allowedToManage={allowedToManage}
+ dataLoading={dataLoading}
+ exportTypes={exportTypes}
+ customExportTypes={customExportTypes}
+ panelsData={_panelsData}
+ />
+ ) : null
+ }
+ />
) : null}
{activeTab === PROJECT_TABS.alerts && (project.role !== 'owner' || !isAuthenticated) ? (
<div className='mt-5 rounded-xl bg-gray-700 p-5'>
@@ -3029,49 +1917,7 @@ const ViewProjectContent = () => {
</Link>
</div>
) : null}
- {activeTab === PROJECT_TABS.funnels && !activeFunnel && !_isEmpty(project.funnels) ? (
- <FunnelsList
- openFunnelSettings={(funnel?: Funnel) => {
- if (funnel) {
- setFunnelToEdit(funnel)
- setIsNewFunnelOpened(true)
- return
- }
-
- setIsNewFunnelOpened(true)
- }}
- funnels={project.funnels}
- deleteFunnel={onFunnelDelete}
- loading={funnelActionLoading}
- allowedToManage={allowedToManage}
- />
- ) : null}
- {activeTab === PROJECT_TABS.funnels && !activeFunnel && _isEmpty(project.funnels) ? (
- <div className='mt-5 rounded-xl bg-gray-700 p-5'>
- <div className='flex items-center text-gray-50'>
- <FilterIcon className='mr-2 h-8 w-8' strokeWidth={1.5} />
- <p className='text-3xl font-bold'>{t('dashboard.funnels')}</p>
- </div>
- <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>{t('dashboard.funnelsDesc')}</p>
- {isAuthenticated ? (
- <button
- type='button'
- onClick={() => setIsNewFunnelOpened(true)}
- className='mt-6 block max-w-max rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium text-slate-900 hover:bg-indigo-50 md:px-4'
- >
- {t('dashboard.newFunnel')}
- </button>
- ) : (
- <Link
- to={routes.signup}
- className='mt-6 block max-w-max rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium text-slate-900 hover:bg-indigo-50 md:px-4'
- aria-label={t('titles.signup')}
- >
- {t('header.startForFree')}
- </Link>
- )}
- </div>
- ) : null}
+ {activeTab === PROJECT_TABS.funnels ? <FunnelsView /> : null}
{activeTab === PROJECT_TABS.profiles && !activeProfileId ? (
<>
<UsersFilter
@@ -3167,465 +2013,29 @@ const ViewProjectContent = () => {
) : null}
{activeTab === PROJECT_TABS.ai ? <AskAIView projectId={id} /> : null}
{activeTab === PROJECT_TABS.captcha ? <CaptchaView projectId={id} /> : null}
- {analyticsLoading && activeTab === PROJECT_TABS.traffic ? <Loader /> : null}
- {isPanelsDataEmpty && activeTab === PROJECT_TABS.traffic ? <NoEvents filters={filters} /> : null}
{activeTab === PROJECT_TABS.traffic ? (
- <div className={cx({ hidden: isPanelsDataEmpty || analyticsLoading })}>
- <div className='relative overflow-hidden rounded-lg border border-gray-300 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-800/25'>
- <div className='mb-3 flex w-full items-center justify-end gap-2 lg:absolute lg:top-2 lg:right-2 lg:mb-0 lg:w-auto lg:justify-normal'>
- <Dropdown
- header={t('project.metricVis')}
- items={
- isActiveCompare
- ? _filter(chartMetrics, (el) => {
- return !_includes(FILTER_CHART_METRICS_MAPPING_FOR_COMPARE, el.id)
- })
- : chartMetrics
- }
- title={[
- <EyeIcon key='eye-icon' aria-label={t('project.metricVis')} className='h-5 w-5' />,
- ]}
- labelExtractor={(pair) => {
- const { label, id: pairID, active, conflicts } = pair
-
- const conflicted = isConflicted(conflicts)
-
- if (pairID === CHART_METRICS_MAPPING.customEvents) {
- if (_isEmpty(panelsData.customs)) {
- return (
- <span className='flex cursor-not-allowed items-center p-2'>
- <BanIcon className='mr-2 h-4 w-4' strokeWidth={1.5} />
- {label}
- </span>
- )
- }
-
- return (
- <CustomEventsSubmenu
- label={label}
- chartMetricsCustomEvents={chartMetricsCustomEvents}
- switchCustomEventChart={switchCustomEventChart}
- />
- )
- }
-
- return (
- <Checkbox
- classes={{
- label: cx('p-2', { hidden: analyticsLoading }),
- }}
- label={label}
- disabled={conflicted}
- checked={active}
- onChange={() => {
- switchTrafficChartMetric(pairID, conflicts)
- }}
- />
- )
- }}
- buttonClassName='!px-2 bg-gray-50 rounded-md border border-transparent hover:border-gray-300 hover:bg-white dark:bg-slate-900 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200'
- selectItemClassName='p-0'
- keyExtractor={(pair) => pair.id}
- onSelect={({ id: pairID, conflicts }, e) => {
- e?.stopPropagation()
- e?.preventDefault()
-
- if (pairID !== CHART_METRICS_MAPPING.customEvents) {
- switchTrafficChartMetric(pairID, conflicts)
- }
- }}
- chevron='mini'
- headless
- />
- <ChartTypeSwitcher onSwitch={setChartTypeOnClick} type={chartType} />
- </div>
- {!_isEmpty(overall) ? (
- <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>
- <MetricCards
- overall={overall}
- overallCompare={overallCompare}
- activePeriodCompare={activePeriodCompare}
- />
- {!_isEmpty(panelsData.meta)
- ? _map(panelsData.meta, ({ key, current, previous }) => (
- <React.Fragment key={key}>
- <MetricCard
- label={t('project.metrics.xAvg', { x: key })}
- value={current.avg}
- change={current.avg - previous.avg}
- goodChangeDirection='down'
- valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`
- }
- />
- <MetricCard
- label={t('project.metrics.xTotal', { x: key })}
- value={current.sum}
- change={current.sum - previous.sum}
- goodChangeDirection='down'
- valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`
- }
- />
- </React.Fragment>
- ))
- : null}
- </div>
- ) : null}
- {!checkIfAllMetricsAreDisabled && !_isEmpty(chartData) ? (
- <div onContextMenu={(e) => handleChartContextMenu(e, chartData.x)} className='relative'>
- <TrafficChart
- chartData={chartData}
- timeBucket={timeBucket}
- activeChartMetrics={activeChartMetrics}
- applyRegions={!_includes(noRegionPeriods, activePeriod?.period)}
- timeFormat={timeFormat}
- rotateXAxis={rotateXAxis}
- chartType={chartType}
- customEventsChartData={customEventsChartData}
- dataChartCompare={dataChartCompare}
- onZoom={onMainChartZoom}
- enableZoom={shouldEnableZoom}
- dataNames={dataNames}
- className='mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible'
- annotations={annotations}
- />
- </div>
- ) : null}
- </div>
- {!isPanelsDataEmpty ? <Filters tnMapping={tnMapping} /> : null}
- <CustomMetrics
- metrics={customMetrics}
- onRemoveMetric={(id) => onRemoveCustomMetric(id)}
- resetMetrics={resetCustomMetrics}
- />
- <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>
- {!_isEmpty(panelsData.types)
- ? _map(TRAFFIC_PANELS_ORDER, (type: string) => {
- if (type === 'location') {
- const locationTabs = [
- { id: 'cc', label: t('project.mapping.cc') },
- { id: 'rg', label: t('project.mapping.rg') },
- { id: 'ct', label: t('project.mapping.ct') },
- { id: 'lc', label: t('project.mapping.lc') },
- { id: 'map', label: 'Map' },
- ]
-
- const rowMapper = (entry: CountryEntry) => {
- const { name: entryName, cc } = entry
-
- if (panelsActiveTabs.location === 'lc') {
- if (entryName === null) {
- return <CCRow cc={null} language={language} />
- }
-
- const entryNameArray = entryName.split('-')
- const displayName = getLocaleDisplayName(entryName, language)
-
- return (
- <CCRow
- cc={entryNameArray[entryNameArray.length - 1]}
- name={displayName}
- language={language}
- />
- )
- }
-
- if (cc !== undefined) {
- return <CCRow cc={cc} name={entryName || undefined} language={language} />
- }
-
- return <CCRow cc={entryName} language={language} />
- }
-
- return (
- <Panel
- key={panelsActiveTabs.location}
- icon={panelIconMapping.cc}
- id={panelsActiveTabs.location}
- getFilterLink={getFilterLink}
- name={t('project.location')}
- tabs={locationTabs}
- onTabChange={(tab) =>
- setPanelsActiveTabs({
- ...panelsActiveTabs,
- location: tab as 'cc' | 'rg' | 'ct' | 'lc' | 'map',
- })
- }
- activeTabId={panelsActiveTabs.location}
- data={panelsData.data[panelsActiveTabs.location]}
- rowMapper={rowMapper}
- customRenderer={
- panelsActiveTabs.location === 'map'
- ? () => {
- const countryData = panelsData.data?.cc || []
- const regionData = panelsData.data?.rg || []
- const total = countryData.reduce((acc, curr) => acc + curr.count, 0)
-
- return (
- <Suspense
- fallback={
- <div className='flex h-full items-center justify-center'>
- <div className='flex flex-col items-center gap-2'>
- <div className='h-8 w-8 animate-spin rounded-full border-2 border-blue-400 border-t-transparent'></div>
- <span className='text-sm text-neutral-600 dark:text-neutral-300'>
- Loading map...
- </span>
- </div>
- </div>
- }
- >
- <InteractiveMap
- data={countryData}
- regionData={regionData}
- total={total}
- onClick={(type, key) => {
- const link = getFilterLink(type, key)
- navigate(link)
- }}
- />
- </Suspense>
- )
- }
- : undefined
- }
- />
- )
- }
-
- if (type === 'devices') {
- const deviceTabs = [
- { id: 'br', label: t('project.mapping.br') },
- { id: 'os', label: t('project.mapping.os') },
- { id: 'dv', label: t('project.mapping.dv') },
- ]
-
- return (
- <Panel
- key={panelsActiveTabs.device}
- icon={panelIconMapping.os}
- id={panelsActiveTabs.device}
- getFilterLink={getFilterLink}
- name={t('project.devices')}
- tabs={deviceTabs}
- onTabChange={(tab) =>
- setPanelsActiveTabs({ ...panelsActiveTabs, device: tab as 'br' | 'os' | 'dv' })
- }
- activeTabId={panelsActiveTabs.device}
- data={panelsData.data[panelsActiveTabs.device]}
- rowMapper={getDeviceRowMapper(panelsActiveTabs.device, theme, t)}
- capitalize={panelsActiveTabs.device === 'dv'}
- versionData={
- panelsActiveTabs.device === 'br'
- ? createVersionDataMapping.browserVersions
- : panelsActiveTabs.device === 'os'
- ? createVersionDataMapping.osVersions
- : undefined
- }
- getVersionFilterLink={(parent, version) =>
- getVersionFilterLink(
- parent,
- version,
- panelsActiveTabs.device === 'br' ? 'br' : 'os',
- )
- }
- />
- )
- }
-
- if (type === 'pg') {
- const pageTabs = [
- { id: 'pg', label: t('project.mapping.pg') },
- { id: 'entryPage', label: t('project.entryPages') },
- { id: 'exitPage', label: t('project.exitPages') },
- { id: 'userFlow', label: t('project.mapping.userFlow') },
- {
- id: 'host',
- label: t('project.mapping.host'),
- },
- ]
-
- return (
- <Panel
- key={panelsActiveTabs.page}
- icon={panelIconMapping.pg}
- id={panelsActiveTabs.page}
- getFilterLink={getFilterLink}
- rowMapper={({ name: entryName }) => {
- if (!entryName) {
- return (
- <span className='italic'>
- {panelsActiveTabs.page === 'host'
- ? t('project.unknownHost')
- : t('common.notSet')}
- </span>
- )
- }
-
- let decodedUri = entryName as string
-
- try {
- decodedUri = decodeURIComponent(entryName)
- } catch {
- // do nothing
- }
-
- return decodedUri
- }}
- name={t('project.pages')}
- tabs={pageTabs}
- onTabChange={(tab) =>
- setPanelsActiveTabs({
- ...panelsActiveTabs,
- page: tab as 'pg' | 'host' | 'userFlow' | 'entryPage' | 'exitPage',
- })
- }
- activeTabId={panelsActiveTabs.page}
- data={panelsData.data[panelsActiveTabs.page]}
- customRenderer={
- panelsActiveTabs.page === 'userFlow'
- ? () => <UserFlow isReversed={false} setReversed={() => {}} />
- : undefined
- }
- />
- )
- }
-
- if (type === 'traffic-sources') {
- const hasRefNameFilter = filters.some((f) => f.column === 'refn')
- const trafficSourcesTabs = [
- { id: 'ref', label: t('project.mapping.ref') },
- !isSelfhosted && { id: 'keywords', label: t('project.mapping.keywords') },
- [
- { id: 'so', label: t('project.mapping.so') },
- { id: 'me', label: t('project.mapping.me') },
- { id: 'ca', label: t('project.mapping.ca') },
- { id: 'te', label: t('project.mapping.te') },
- { id: 'co', label: t('project.mapping.co') },
- ],
- ].filter((x) => !!x)
-
- const getTrafficSourcesRowMapper = (activeTab: string) => {
- if (activeTab === 'ref') {
- // eslint-disable-next-line
- return ({ name: entryName }: any) => <RefRow rowName={entryName} />
- }
- return ({ name: entryName }: any) => decodeURIComponent(entryName)
- }
-
- return (
- <Panel
- key={panelsActiveTabs.source}
- icon={panelIconMapping.ref}
- id={panelsActiveTabs.source}
- getFilterLink={(column: string, value: string | null) => {
- if (panelsActiveTabs.source === 'ref') {
- // If grouped by name/domain (no refn filter active) -> filter by refn
- return getFilterLink(
- hasRefNameFilter || value === null ? 'ref' : 'refn',
- value,
- )
- }
- return getFilterLink(column, value)
- }}
- name={t('project.trafficSources')}
- tabs={trafficSourcesTabs}
- onTabChange={(tab) =>
- setPanelsActiveTabs({
- ...panelsActiveTabs,
- source: tab as 'ref' | 'so' | 'me' | 'ca' | 'te' | 'co' | 'keywords',
- })
- }
- activeTabId={panelsActiveTabs.source}
- data={
- panelsActiveTabs.source === 'keywords'
- ? keywords
- : panelsActiveTabs.source === 'ref'
- ? (() => {
- const raw = panelsData.data?.ref || []
- return hasRefNameFilter
- ? (raw as unknown as Entry[])
- : (groupRefEntries(raw as any) as unknown as Entry[])
- })()
- : (panelsData.data[panelsActiveTabs.source] as unknown as Entry[])
- }
- valuesHeaderName={
- panelsActiveTabs.source === 'keywords' ? t('project.clicks') : undefined
- }
- rowMapper={getTrafficSourcesRowMapper(panelsActiveTabs.source)}
- disableRowClick={panelsActiveTabs.source === 'keywords'}
- hidePercentageInDetails={panelsActiveTabs.source === 'keywords'}
- detailsExtraColumns={
- panelsActiveTabs.source === 'keywords'
- ? [
- {
- header: t('project.impressions'),
- render: (entry: any) => entry.impressions,
- sortLabel: 'impressions',
- getSortValue: (entry: any) => Number(entry.impressions || 0),
- },
- {
- header: t('project.position'),
- render: (entry: any) => entry.position,
- sortLabel: 'position',
- getSortValue: (entry: any) => Number(entry.position || 0),
- },
- {
- header: t('project.ctr'),
- render: (entry: any) => `${entry.ctr}%`,
- sortLabel: 'ctr',
- getSortValue: (entry: any) => Number(entry.ctr || 0),
- },
- ]
- : undefined
- }
- customRenderer={
- panelsActiveTabs.source === 'keywords'
- ? keywordsLoading
- ? () => <Loader />
- : keywordsNotConnected
- ? () => (
- <div className='mt-4 text-center'>
- <p className='text-sm text-gray-800 dark:text-gray-200'>
- {['owner', 'admin'].includes(project?.role || '')
- ? t('project.connectGsc')
- : t('project.gscConnectionRequired')}
- </p>
- {['owner', 'admin'].includes(project?.role || '') ? (
- <Link
- to={`${routes.project_settings.replace(':id', id)}?tab=integrations`}
- className='mt-2 inline-flex items-center rounded-md border border-gray-300 bg-white px-3 py-1 text-sm text-gray-800 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
- >
- {t('project.goToProjectSettings')}
- </Link>
- ) : null}
- </div>
- )
- : undefined
- : undefined
- }
- />
- )
- }
-
- return null
- })
- : null}
- {!_isEmpty(panelsData.data) ? (
- <MetadataGeneric
- customs={panelsData.customs}
- properties={panelsData.properties}
- filters={filters}
- getFilterLink={getFilterLink}
- chartData={chartData}
- getCustomEventMetadata={getCustomEventMetadata}
- getPropertyMetadata={_getPropertyMetadata}
- onTabChange={(tab) => setPanelTab('metadata', tab as 'ce' | 'props')}
- activeTabId={panelsActiveTabs.metadata}
- />
- ) : null}
- </div>
- </div>
+ <TrafficView
+ tnMapping={tnMapping}
+ chartType={chartType}
+ rotateXAxis={rotateXAxis}
+ isActiveCompare={isActiveCompare}
+ dateRangeCompare={dateRangeCompare}
+ activePeriodCompare={activePeriodCompare}
+ compareDisable={compareDisable}
+ annotations={annotations}
+ onChartContextMenu={handleChartContextMenu}
+ getFilterLink={getFilterLink}
+ getVersionFilterLink={getVersionFilterLink}
+ onMainChartZoom={onMainChartZoom}
+ shouldEnableZoom={shouldEnableZoom}
+ setChartTypeOnClick={setChartTypeOnClick}
+ customMetrics={customMetrics}
+ onCustomMetric={onCustomMetric}
+ onRemoveCustomMetric={onRemoveCustomMetric}
+ resetCustomMetrics={resetCustomMetrics}
+ mode={mode}
+ sdkInstance={sdkInstance}
+ />
) : null}
{activeTab === PROJECT_TABS.performance ? (
<PerformanceView
@@ -3645,37 +2055,6 @@ const ViewProjectContent = () => {
setChartTypeOnClick={setChartTypeOnClick}
/>
) : null}
- {activeTab === PROJECT_TABS.funnels ? (
- <div
- className={cx(
- 'relative overflow-hidden rounded-lg border border-gray-300 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-800/25',
- { hidden: !activeFunnel || analyticsLoading },
- )}
- >
- {funnelSummary ? (
- <>
- <p className='font-medium text-gray-900 lg:text-left dark:text-gray-50'>
- {t('project.funnelSummary.xStepFunnel', { x: funnelSummary.stepsCount })}
- <span className='mx-2 text-gray-400'>•</span>
- {t('project.funnelSummary.conversionRateShort', { x: funnelSummary.conversionRate })}
- </p>
- <p className='text-center text-gray-900 lg:text-left dark:text-gray-50'>
- {t('project.funnelSummary.startShort')}: {nLocaleFormatter(funnelSummary.startVisitors)}
- <span className='mx-1'>→</span>
- {t('project.funnelSummary.endShort')}: {nLocaleFormatter(funnelSummary.endVisitors)}
- </p>
- </>
- ) : null}
- {funnelAnalytics?.funnel ? (
- <FunnelChart
- funnel={funnelAnalytics.funnel}
- totalPageviews={funnelAnalytics.totalPageviews}
- t={t}
- className='mt-5 h-80 [&_svg]:!overflow-visible'
- />
- ) : null}
- </div>
- ) : null}
</motion.div>
</AnimatePresence>
@@ -3770,23 +2149,6 @@ const ViewProjectContent = () => {
</div>
</div>
<ViewProjectHotkeys isOpened={isHotkeysHelpOpened} onClose={() => setIsHotkeysHelpOpened(false)} />
- <NewFunnel
- funnel={funnelToEdit}
- isOpened={isNewFunnelOpened}
- onClose={() => {
- setIsNewFunnelOpened(false)
- setFunnelToEdit(undefined)
- }}
- onSubmit={async (name: string, steps: string[]) => {
- if (funnelToEdit) {
- await onFunnelEdit(funnelToEdit.id, name, steps)
- return
- }
-
- await onFunnelCreate(name, steps)
- }}
- loading={funnelActionLoading}
- />
<SearchFilters
type={activeTab === PROJECT_TABS.errors ? 'errors' : 'traffic'}
showModal={showFiltersSearch}
diff --git a/web/app/pages/Project/View/components/CustomEventsSubmenu.tsx b/web/app/pages/Project/View/components/CustomEventsSubmenu.tsx
index 0f4f4a43b..129210747 100644
--- a/web/app/pages/Project/View/components/CustomEventsSubmenu.tsx
+++ b/web/app/pages/Project/View/components/CustomEventsSubmenu.tsx
@@ -161,7 +161,6 @@ const CustomEventsSubmenu: React.FC<CustomEventsSubmenuProps> = ({
className='max-w-max'
onClick={(e) => {
e.stopPropagation()
- e.preventDefault()
}}
>
<Checkbox
diff --git a/web/app/pages/Project/View/components/DashboardHeader.tsx b/web/app/pages/Project/View/components/DashboardHeader.tsx
new file mode 100644
index 000000000..c502c3398
--- /dev/null
+++ b/web/app/pages/Project/View/components/DashboardHeader.tsx
@@ -0,0 +1,248 @@
+import cx from 'clsx'
+import dayjs from 'dayjs'
+import _find from 'lodash/find'
+import { SearchIcon } from 'lucide-react'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import { useSearchParams } from 'react-router'
+
+import { MAX_MONTHS_IN_PAST, PERIOD_PAIRS_COMPARE, TBPeriodPairsProps } from '~/lib/constants'
+import { useAuth } from '~/providers/AuthProvider'
+import DatePicker from '~/ui/Datepicker'
+import Dropdown from '~/ui/Dropdown'
+
+import { useViewProjectContext } from '../ViewProject'
+
+import LiveVisitorsDropdown from './LiveVisitorsDropdown'
+import { RefreshStatsButton } from './RefreshStatsButton'
+import TBPeriodSelector from './TBPeriodSelector'
+
+interface DashboardHeaderProps {
+ // Required props
+ refreshStats: (isManual: boolean) => Promise<void>
+ timeBucketSelectorItems: TBPeriodPairsProps[]
+ isActiveCompare: boolean
+ setIsActiveCompare: (value: boolean) => void
+ compareDisable: () => void
+ maxRangeCompare: number
+ dateRangeCompare: Date[] | null
+ setDateRangeCompare: (value: Date[] | null) => void
+ activePeriodCompare: string
+ setActivePeriodCompare: (value: string) => void
+ periodPairsCompare: { label: string; period: string }[]
+ setPeriodPairsCompare: (value: { label: string; period: string }[]) => void
+ setShowFiltersSearch: (value: boolean) => void
+ resetDateRange: () => void
+
+ // Refs
+ refCalendar: React.RefObject<any>
+ refCalendarCompare: React.RefObject<any>
+
+ // Optional props
+ showLiveVisitors?: boolean
+ showRefreshButton?: boolean
+ showSearchButton?: boolean
+ showPeriodSelector?: boolean
+ hideTimeBucket?: boolean
+
+ // Right side content (for segments/export dropdowns)
+ rightContent?: React.ReactNode
+}
+
+export const DashboardHeader = ({
+ refreshStats,
+ timeBucketSelectorItems,
+ isActiveCompare,
+ setIsActiveCompare,
+ compareDisable,
+ maxRangeCompare,
+ dateRangeCompare,
+ setDateRangeCompare,
+ activePeriodCompare,
+ setActivePeriodCompare,
+ periodPairsCompare,
+ setPeriodPairsCompare,
+ setShowFiltersSearch,
+ resetDateRange,
+ refCalendar,
+ refCalendarCompare,
+ showLiveVisitors = true,
+ showRefreshButton = true,
+ showSearchButton = true,
+ showPeriodSelector = true,
+ hideTimeBucket = false,
+ rightContent,
+}: DashboardHeaderProps) => {
+ const { isLoading: authLoading } = useAuth()
+ const { dataLoading, activePeriod, dateRange, updatePeriod } = useViewProjectContext()
+ const {
+ t,
+ i18n: { language },
+ } = useTranslation('common')
+ const [searchParams, setSearchParams] = useSearchParams()
+
+ const activeDropdownLabelCompare = _find(periodPairsCompare, (p) => p.period === activePeriodCompare)?.label
+
+ const tbPeriodPairsCompare = (tFn: typeof t, customDateRange?: Date[], lng?: string) => {
+ const result = [
+ {
+ label: tFn('project.previousPeriod'),
+ period: PERIOD_PAIRS_COMPARE.PREVIOS,
+ },
+ {
+ label: tFn('project.customDate'),
+ period: PERIOD_PAIRS_COMPARE.CUSTOM,
+ },
+ {
+ label: tFn('project.disableCompare'),
+ period: PERIOD_PAIRS_COMPARE.DISABLE,
+ },
+ ]
+
+ if (customDateRange) {
+ const from = dayjs(customDateRange[0]).locale(lng || 'en')
+ const to = dayjs(customDateRange[1]).locale(lng || 'en')
+
+ const label = from.isSame(to, 'day')
+ ? from.format('D MMM YYYY')
+ : `${from.format('D MMM')} - ${to.format('D MMM YYYY')}`
+
+ return [
+ {
+ label,
+ period: PERIOD_PAIRS_COMPARE.CUSTOM,
+ isCustomDate: true,
+ },
+ ...result.filter((p) => p.period !== PERIOD_PAIRS_COMPARE.CUSTOM),
+ ]
+ }
+
+ return result
+ }
+
+ return (
+ <div className='relative top-0 z-20 -mt-2 flex flex-col items-center justify-between bg-gray-50/50 py-2 backdrop-blur-md lg:sticky lg:flex-row dark:bg-slate-900/50'>
+ <div className='flex flex-wrap items-center justify-center gap-2'>
+ {showLiveVisitors ? <LiveVisitorsDropdown /> : null}
+ </div>
+ <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'>
+ {showRefreshButton ? <RefreshStatsButton onRefresh={refreshStats} /> : null}
+ {showSearchButton ? (
+ <div className='border-gray-200 dark:border-gray-600'>
+ <button
+ type='button'
+ title={t('project.search')}
+ onClick={() => {
+ if (dataLoading) {
+ return
+ }
+
+ setShowFiltersSearch(true)
+ }}
+ 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,
+ },
+ )}
+ >
+ <SearchIcon className='h-5 w-5 text-gray-700 dark:text-gray-50' />
+ </button>
+ </div>
+ ) : null}
+ {rightContent}
+ {showPeriodSelector ? (
+ <div className='flex items-center'>
+ <TBPeriodSelector
+ classes={{
+ timeBucket: hideTimeBucket ? 'hidden' : '',
+ }}
+ activePeriod={activePeriod}
+ items={timeBucketSelectorItems}
+ title={activePeriod?.label}
+ onSelect={(pair) => {
+ if (dataLoading) {
+ return
+ }
+
+ if (pair.period === PERIOD_PAIRS_COMPARE.COMPARE) {
+ if (isActiveCompare) {
+ compareDisable()
+ } else {
+ setIsActiveCompare(true)
+ }
+
+ return
+ }
+
+ if (pair.isCustomDate) {
+ setTimeout(() => {
+ refCalendar.current?.openCalendar()
+ }, 100)
+ } else {
+ resetDateRange()
+ updatePeriod(pair)
+ }
+ }}
+ />
+ <DatePicker
+ ref={refCalendar}
+ onChange={([from, to]) => {
+ const newSearchParams = new URLSearchParams(searchParams.toString())
+ newSearchParams.set('from', from.toISOString())
+ newSearchParams.set('to', to.toISOString())
+ newSearchParams.set('period', 'custom')
+ setSearchParams(newSearchParams)
+ }}
+ value={dateRange || []}
+ maxDateMonths={MAX_MONTHS_IN_PAST}
+ maxRange={0}
+ />
+ <DatePicker
+ ref={refCalendarCompare}
+ onChange={(date) => {
+ setDateRangeCompare(date)
+ setActivePeriodCompare(PERIOD_PAIRS_COMPARE.CUSTOM)
+ setPeriodPairsCompare(tbPeriodPairsCompare(t, date, language))
+ }}
+ value={dateRangeCompare || []}
+ maxDateMonths={MAX_MONTHS_IN_PAST}
+ maxRange={maxRangeCompare}
+ />
+ </div>
+ ) : null}
+ {isActiveCompare ? (
+ <>
+ <div className='text-md mx-2 font-medium whitespace-pre-line text-gray-600 dark:text-gray-200'>vs</div>
+ <Dropdown
+ items={periodPairsCompare}
+ title={activeDropdownLabelCompare}
+ labelExtractor={(pair) => pair.label}
+ keyExtractor={(pair) => pair.label}
+ onSelect={(pair) => {
+ if (pair.period === PERIOD_PAIRS_COMPARE.DISABLE) {
+ compareDisable()
+ return
+ }
+
+ if (pair.period === PERIOD_PAIRS_COMPARE.CUSTOM) {
+ setTimeout(() => {
+ refCalendarCompare.current?.openCalendar()
+ }, 100)
+ } else {
+ setPeriodPairsCompare(tbPeriodPairsCompare(t, undefined, language))
+ setDateRangeCompare(null)
+ setActivePeriodCompare(pair.period)
+ }
+ }}
+ chevron='mini'
+ headless
+ />
+ </>
+ ) : null}
+ </div>
+ </div>
+ )
+}
+
+export default DashboardHeader
diff --git a/web/app/pages/Project/View/components/TrafficHeaderActions.tsx b/web/app/pages/Project/View/components/TrafficHeaderActions.tsx
new file mode 100644
index 000000000..61962fec6
--- /dev/null
+++ b/web/app/pages/Project/View/components/TrafficHeaderActions.tsx
@@ -0,0 +1,206 @@
+import cx from 'clsx'
+import _filter from 'lodash/filter'
+import _isEmpty from 'lodash/isEmpty'
+import { BookmarkIcon, DownloadIcon, PencilIcon, Trash2Icon } from 'lucide-react'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import { useSearchParams } from 'react-router'
+
+import { isSelfhosted, MARKETPLACE_URL } from '~/lib/constants'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+import Dropdown from '~/ui/Dropdown'
+import { Text } from '~/ui/Text'
+import { trackCustom } from '~/utils/analytics'
+
+import { Filter, ProjectView, ProjectViewCustomEvent } from '../interfaces/traffic'
+
+import { getFiltersUrlParams } from './SearchFilters'
+
+interface ExportType {
+ label: string
+ onClick: (data: any, tFunction: any) => void
+}
+
+interface TrafficHeaderActionsProps {
+ // Segments dropdown props
+ projectViews: ProjectView[]
+ projectViewsLoading: boolean | null
+ projectViewDeleting: boolean
+ loadProjectViews: () => Promise<void>
+ onProjectViewDelete: (viewId: string) => Promise<void>
+ setProjectViewToUpdate: (view: ProjectView | undefined) => void
+ setIsAddAViewOpened: (value: boolean) => void
+ onCustomMetric: (metrics: ProjectViewCustomEvent[]) => void
+ filters: Filter[]
+ allowedToManage: boolean
+ dataLoading: boolean
+
+ // Export dropdown props
+ exportTypes: ExportType[]
+ customExportTypes: ExportType[]
+ panelsData: any
+}
+
+export const TrafficHeaderActions = ({
+ projectViews,
+ projectViewsLoading,
+ projectViewDeleting,
+ loadProjectViews,
+ onProjectViewDelete,
+ setProjectViewToUpdate,
+ setIsAddAViewOpened,
+ onCustomMetric,
+ filters,
+ allowedToManage,
+ dataLoading,
+ exportTypes,
+ customExportTypes,
+ panelsData,
+}: TrafficHeaderActionsProps) => {
+ const { t } = useTranslation('common')
+ const { id } = useCurrentProject()
+ const [searchParams, setSearchParams] = useSearchParams()
+
+ return (
+ <>
+ {/* Segments Dropdown */}
+ <Dropdown
+ header={t('project.segments')}
+ onClick={() => loadProjectViews()}
+ loading={projectViewsLoading || projectViewsLoading === null}
+ items={_filter(
+ [
+ ...projectViews,
+ allowedToManage && {
+ id: 'add-a-view',
+ name: t('project.addASegment'),
+ createView: true,
+ },
+ !allowedToManage &&
+ _isEmpty(projectViews) && {
+ id: 'no-views',
+ name: t('project.noSegmentsYet'),
+ notClickable: true,
+ },
+ ],
+ (x) => !!x,
+ )}
+ title={[<BookmarkIcon key='bookmark-icon' className='h-5 w-5' />]}
+ labelExtractor={(item, close) => {
+ // @ts-expect-error
+ if (item.createView) {
+ return item.name
+ }
+
+ if (item.id === 'no-views') {
+ return <Text colour='secondary'>{item.name}</Text>
+ }
+
+ return (
+ <div
+ className={cx('flex items-center justify-between space-x-4', {
+ 'cursor-wait': dataLoading,
+ })}
+ >
+ <span>{item.name}</span>
+ {allowedToManage ? (
+ <div className='flex cursor-pointer space-x-1'>
+ <button
+ onClick={(e) => {
+ e.stopPropagation()
+ setProjectViewToUpdate(item)
+ close()
+ setIsAddAViewOpened(true)
+ }}
+ aria-label={t('common.settings')}
+ className='rounded-md p-1 hover:bg-gray-50 hover:text-gray-900 dark:hover:bg-slate-800 dark:hover:text-slate-200'
+ >
+ <PencilIcon className='size-3' />
+ </button>
+ <button
+ onClick={(e) => {
+ e.stopPropagation()
+ close()
+ onProjectViewDelete(item.id)
+ }}
+ aria-label={t('common.settings')}
+ className={cx(
+ 'rounded-md p-1 hover:bg-gray-50 hover:text-gray-900 dark:hover:bg-slate-800 dark:hover:text-slate-200',
+ {
+ 'cursor-not-allowed': projectViewDeleting,
+ },
+ )}
+ >
+ <Trash2Icon className='size-3' />
+ </button>
+ </div>
+ ) : null}
+ </div>
+ )
+ }}
+ keyExtractor={(item) => item.id}
+ onSelect={(item: ProjectView, e) => {
+ // @ts-expect-error
+ if (item.createView) {
+ e?.stopPropagation()
+ setIsAddAViewOpened(true)
+
+ return
+ }
+
+ if (item.filters && !_isEmpty(item.filters)) {
+ const newUrlParams = getFiltersUrlParams(filters, item.filters, true, searchParams)
+ setSearchParams(newUrlParams)
+ }
+
+ if (item.customEvents && !_isEmpty(item.customEvents)) {
+ onCustomMetric(item.customEvents)
+ }
+ }}
+ chevron='mini'
+ buttonClassName='!p-2 rounded-md hover:bg-white border border-gray-50/0 hover:border-gray-300 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:z-10 focus:outline-hidden focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 focus:dark:ring-gray-200'
+ headless
+ />
+
+ {/* Export Dropdown */}
+ <Dropdown
+ header={t('project.exportData')}
+ items={_filter(
+ [
+ ...exportTypes,
+ ...customExportTypes,
+ !isSelfhosted && {
+ label: t('project.lookingForMore'),
+ lookingForMore: true,
+ onClick: () => {},
+ },
+ ],
+ (el) => !!el,
+ )}
+ title={[<DownloadIcon key='download-icon' className='h-5 w-5' />]}
+ labelExtractor={(item) => item.label}
+ keyExtractor={(item) => item.label}
+ onSelect={(item, e) => {
+ // @ts-expect-error lookingForMore is defined as an exception above
+ if (item.lookingForMore) {
+ e?.stopPropagation()
+ window.open(MARKETPLACE_URL, '_blank')
+
+ return
+ }
+
+ trackCustom('DASHBOARD_EXPORT', {
+ type: item.label === t('project.asCSV') ? 'csv' : 'extension',
+ })
+
+ item.onClick(panelsData, t)
+ }}
+ chevron='mini'
+ buttonClassName='!p-2 rounded-md hover:bg-white border border-gray-50/0 hover:border-gray-300 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:z-10 focus:outline-hidden focus:ring-1 focus:ring-indigo-500 focus:dark:ring-gray-200'
+ headless
+ />
+ </>
+ )
+}
+
+export default TrafficHeaderActions