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!

Update funnels UI to display them on the same page

Blue Mouse4406dd2e6c7d
diff --git a/web/app/pages/Project/tabs/Funnels/FunnelsList.tsx b/web/app/pages/Project/tabs/Funnels/FunnelsList.tsx
index 2863e718c..a0b05ce6e 100644
--- a/web/app/pages/Project/tabs/Funnels/FunnelsList.tsx
+++ b/web/app/pages/Project/tabs/Funnels/FunnelsList.tsx
@@ -1,4 +1,5 @@
import cx from 'clsx'
+import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import {
SlidersHorizontalIcon,
@@ -7,19 +8,37 @@ import {
FileTextIcon,
CursorClickIcon,
ArrowRightIcon,
+ CaretDownIcon,
} from '@phosphor-icons/react'
-import { type MouseEvent, useMemo, useRef } from 'react'
+import {
+ Suspense,
+ use,
+ useEffect,
+ useMemo,
+ useRef,
+ type ReactNode,
+} from 'react'
import { useTranslation } from 'react-i18next'
-import { Link } from '~/ui/Link'
-import { useSearchParams } from 'react-router'
-import { Funnel } from '~/lib/models/Project'
+import type { FunnelDataResponse } from '~/api/api.server'
+import type { Funnel } from '~/lib/models/Project'
+import { FunnelChart } from '~/pages/Project/tabs/Funnels/FunnelChart'
import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
+import Spin from '~/ui/icons/Spin'
import { Text } from '~/ui/Text'
+import { nLocaleFormatter } from '~/utils/generic'
interface FunnelsListProps {
- funnels?: any[]
+ funnels?: Funnel[]
+ activeFunnelId: string | null
+ funnelDataPromise?: Promise<FunnelDataResponse | null>
+ onToggleFunnel: (id: string) => void
+ onFunnelDataResolved: (
+ funnelId: string,
+ funnelData: FunnelDataResponse | null,
+ ) => void
+ onBarClick: (stepIndex: number) => void
openFunnelSettings: (funnel?: Funnel) => void
deleteFunnel: (id: string) => void
loading: boolean
@@ -28,6 +47,14 @@ interface FunnelsListProps {
interface FunnelCardProps {
funnel: Funnel
+ isExpanded: boolean
+ funnelDataPromise?: Promise<FunnelDataResponse | null>
+ onToggleFunnel: (id: string) => void
+ onFunnelDataResolved: (
+ funnelId: string,
+ funnelData: FunnelDataResponse | null,
+ ) => void
+ onBarClick: (stepIndex: number) => void
openFunnelSettings: (funnel: Funnel) => void
deleteFunnel: (id: string) => void
loading: boolean
@@ -40,6 +67,55 @@ interface AddFunnelProps {
const STEPS_MAX_HEIGHT = 42
+const getFunnelSummary = (funnelData?: FunnelDataResponse | null) => {
+ if (!funnelData || _isEmpty(funnelData.funnel)) {
+ return null
+ }
+
+ const stepsCount = funnelData.funnel.length
+ const startVisitors = funnelData.funnel[0]?.events || 0
+ const endVisitors = funnelData.funnel[stepsCount - 1]?.events || 0
+ const conversionRate = Number(
+ ((endVisitors / Math.max(startVisitors, 1)) * 100).toFixed(2),
+ )
+
+ return {
+ stepsCount,
+ startVisitors,
+ endVisitors,
+ conversionRate,
+ }
+}
+
+const FunnelDataResolver = ({
+ funnelId,
+ funnelDataPromise,
+ onFunnelDataResolved,
+ children,
+}: {
+ funnelId: string
+ funnelDataPromise?: Promise<FunnelDataResponse | null>
+ onFunnelDataResolved: (
+ funnelId: string,
+ funnelData: FunnelDataResponse | null,
+ ) => void
+ children: (funnelData: FunnelDataResponse | null) => ReactNode
+}) => {
+ const funnelData = funnelDataPromise ? use(funnelDataPromise) : null
+
+ useEffect(() => {
+ onFunnelDataResolved(funnelId, funnelData)
+ }, [funnelData, funnelId, onFunnelDataResolved])
+
+ return <>{children(funnelData)}</>
+}
+
+const FunnelChartLoading = () => (
+ <div className='flex h-[260px] items-center justify-center'>
+ <Spin className='size-8' />
+ </div>
+)
+
const FunnelSteps = ({ steps }: { steps: string[] }) => {
const containerRef = useRef<HTMLDivElement>(null)
@@ -85,73 +161,163 @@ const FunnelSteps = ({ steps }: { steps: string[] }) => {
)
}
+const FunnelExpandedChart = ({
+ funnelData,
+ onBarClick,
+}: {
+ funnelData: FunnelDataResponse | null
+ onBarClick: (stepIndex: number) => void
+}) => {
+ const { t } = useTranslation('common')
+ const funnelSummary = useMemo(
+ () => getFunnelSummary(funnelData),
+ [funnelData],
+ )
+
+ if (!funnelData?.funnel || _isEmpty(funnelData.funnel)) {
+ return (
+ <div className='flex h-[260px] items-center justify-center'>
+ <Text as='p' colour='muted'>
+ {t('project.noData')}
+ </Text>
+ </div>
+ )
+ }
+
+ return (
+ <>
+ {funnelSummary ? (
+ <div>
+ <Text as='p' weight='medium' className='lg:text-left'>
+ {t('project.funnelSummary.xStepFunnel', {
+ x: funnelSummary.stepsCount,
+ })}
+ <span className='mx-2 text-gray-400'>β€’</span>
+ {t('project.funnelSummary.conversionRateShort', {
+ x: funnelSummary.conversionRate,
+ })}
+ </Text>
+ <Text as='p' className='text-center lg:text-left'>
+ {t('project.funnelSummary.startShort')}:{' '}
+ {nLocaleFormatter(funnelSummary.startVisitors)}
+ <span className='mx-1'>β†’</span>
+ {t('project.funnelSummary.endShort')}:{' '}
+ {nLocaleFormatter(funnelSummary.endVisitors)}
+ </Text>
+ </div>
+ ) : null}
+ <FunnelChart
+ funnel={funnelData.funnel}
+ totalPageviews={funnelData.totalPageviews}
+ t={t}
+ className='mt-5 h-80 [&_svg]:!overflow-visible'
+ onBarClick={onBarClick}
+ />
+ </>
+ )
+}
+
const FunnelCard = ({
funnel,
+ isExpanded,
+ funnelDataPromise,
+ onToggleFunnel,
+ onFunnelDataResolved,
+ onBarClick,
openFunnelSettings,
deleteFunnel,
loading,
allowedToManage,
}: FunnelCardProps) => {
const { t } = useTranslation()
- const [searchParams] = useSearchParams()
-
- const search = useMemo(() => {
- const params = new URLSearchParams(searchParams)
- params.set('funnelId', funnel.id)
- return params.toString()
- }, [funnel.id, searchParams])
return (
- <Link
- to={{
- search,
- }}
- className='min-h-[120px] cursor-pointer overflow-hidden rounded-lg border border-gray-200 bg-gray-50 transition-colors hover:bg-gray-200/70 dark:border-slate-800/60 dark:bg-slate-900/25 dark:hover:bg-slate-900/60'
- >
- <div className='px-4 py-4'>
- <div className='flex items-center justify-between'>
- <Text as='p' size='base' weight='semibold' truncate>
- {funnel.name}
- </Text>
- <div className='flex shrink-0 items-center gap-1'>
+ <li className='relative mb-3 overflow-hidden rounded-lg border border-gray-200 bg-gray-50 transition-colors dark:border-slate-800/60 dark:bg-slate-900/25'>
+ <div className='flex transition-colors hover:bg-gray-200/70 dark:hover:bg-slate-900/60'>
+ <button
+ type='button'
+ aria-expanded={isExpanded}
+ aria-controls={`funnel-${funnel.id}-details`}
+ onClick={() => onToggleFunnel(funnel.id)}
+ className='flex min-w-0 flex-1 cursor-pointer justify-between gap-x-6 px-4 py-4 text-left focus-visible:ring-2 focus-visible:ring-slate-900 focus-visible:outline-hidden focus-visible:ring-inset sm:px-6 sm:pr-2 dark:focus-visible:ring-slate-300'
+ >
+ <div className='min-w-0 flex-auto'>
+ <Text
+ as='p'
+ weight='semibold'
+ truncate
+ className='flex items-center gap-x-1.5'
+ >
+ <FunnelIcon className='size-4 text-teal-500' />
+ <span>{funnel.name}</span>
+ </Text>
+ {funnel.steps?.length > 0 && <FunnelSteps steps={funnel.steps} />}
+ </div>
+ <div className='flex shrink-0 items-center gap-x-4'>
+ <CaretDownIcon
+ className={cx(
+ 'size-5 text-gray-500 transition-transform dark:text-gray-400',
+ {
+ 'rotate-180': isExpanded,
+ },
+ )}
+ />
+ </div>
+ </button>
+ <div className='flex shrink-0 items-center gap-1 py-4 pr-4 sm:pr-6'>
+ <Button
+ variant='icon'
+ type='button'
+ onClick={() => openFunnelSettings(funnel)}
+ aria-label={t('common.settings')}
+ className='p-1.5 text-gray-800 dark:text-slate-400 dark:hover:text-slate-300'
+ >
+ <SlidersHorizontalIcon className='size-4' />
+ </Button>
+ {allowedToManage ? (
<Button
variant='icon'
type='button'
- onClick={(e: MouseEvent<HTMLButtonElement>) => {
- e.preventDefault()
- e.stopPropagation()
- openFunnelSettings(funnel)
- }}
- aria-label={t('common.settings')}
- className='p-1.5 text-gray-800 dark:text-slate-400 dark:hover:text-slate-300'
+ onClick={() => deleteFunnel(funnel.id)}
+ aria-label={t('common.delete')}
+ className={cx(
+ 'p-1.5 text-gray-800 dark:text-slate-400 dark:hover:text-slate-300',
+ {
+ 'cursor-not-allowed': loading,
+ },
+ )}
>
- <SlidersHorizontalIcon className='size-5' />
+ <TrashIcon className='size-4' />
</Button>
- {allowedToManage ? (
- <Button
- variant='icon'
- type='button'
- onClick={(e: MouseEvent<HTMLButtonElement>) => {
- e.preventDefault()
- e.stopPropagation()
- deleteFunnel(funnel.id)
- }}
- aria-label={t('common.delete')}
- className={cx(
- 'p-1.5 text-gray-800 dark:text-slate-400 dark:hover:text-slate-300',
- {
- 'cursor-not-allowed': loading,
- },
- )}
- >
- <TrashIcon className='size-5' />
- </Button>
- ) : null}
- </div>
+ ) : null}
</div>
- {funnel.steps?.length > 0 && <FunnelSteps steps={funnel.steps} />}
</div>
- </Link>
+ {isExpanded ? (
+ <div
+ id={`funnel-${funnel.id}-details`}
+ className='border-t border-gray-200 px-4 py-4 sm:px-6 dark:border-slate-700'
+ >
+ {funnelDataPromise ? (
+ <Suspense fallback={<FunnelChartLoading />}>
+ <FunnelDataResolver
+ funnelId={funnel.id}
+ funnelDataPromise={funnelDataPromise}
+ onFunnelDataResolved={onFunnelDataResolved}
+ >
+ {(funnelData) => (
+ <FunnelExpandedChart
+ funnelData={funnelData}
+ onBarClick={onBarClick}
+ />
+ )}
+ </FunnelDataResolver>
+ </Suspense>
+ ) : (
+ <FunnelChartLoading />
+ )}
+ </div>
+ ) : null}
+ </li>
)
}
@@ -163,27 +329,35 @@ const AddFunnel = ({ openFunnelSettings }: AddFunnelProps) => {
}
return (
- <li
- onClick={onClick}
- className='group flex h-auto min-h-[120px] cursor-pointer items-center justify-center rounded-lg border border-dashed border-gray-300 transition-colors hover:border-gray-400 dark:border-gray-500 dark:hover:border-gray-600'
- >
- <div>
- <FunnelIcon className='mx-auto h-12 w-12 text-gray-400 transition-colors group-hover:text-gray-500 dark:text-gray-200 group-hover:dark:text-gray-400' />
- <Text
- as='span'
- size='sm'
- weight='semibold'
- className='mt-2 block group-hover:dark:text-gray-400'
- >
- {t('dashboard.newFunnel')}
- </Text>
- </div>
+ <li className='mb-3'>
+ <button
+ type='button'
+ onClick={onClick}
+ className='group flex min-h-[96px] w-full cursor-pointer items-center justify-center rounded-lg border border-dashed border-gray-300 transition-colors hover:border-gray-400 focus-visible:ring-2 focus-visible:ring-slate-900 focus-visible:ring-offset-2 focus-visible:outline-hidden dark:border-gray-500 dark:hover:border-gray-600 dark:focus-visible:ring-slate-300 dark:focus-visible:ring-offset-slate-950'
+ >
+ <div>
+ <FunnelIcon className='mx-auto h-12 w-12 text-gray-400 transition-colors group-hover:text-gray-500 dark:text-gray-200 group-hover:dark:text-gray-400' />
+ <Text
+ as='span'
+ size='sm'
+ weight='semibold'
+ className='mt-2 block group-hover:dark:text-gray-400'
+ >
+ {t('dashboard.newFunnel')}
+ </Text>
+ </div>
+ </button>
</li>
)
}
const FunnelsList = ({
funnels,
+ activeFunnelId,
+ funnelDataPromise,
+ onToggleFunnel,
+ onFunnelDataResolved,
+ onBarClick,
openFunnelSettings,
deleteFunnel,
loading,
@@ -192,11 +366,16 @@ const FunnelsList = ({
const { isAuthenticated } = useAuth()
return (
- <div role='list' className='grid grid-cols-1 gap-3 lg:grid-cols-3'>
+ <ul className='mt-4'>
{_map(funnels, (funnel) => (
<FunnelCard
key={funnel.id}
funnel={funnel}
+ isExpanded={activeFunnelId === funnel.id}
+ funnelDataPromise={funnelDataPromise}
+ onToggleFunnel={onToggleFunnel}
+ onFunnelDataResolved={onFunnelDataResolved}
+ onBarClick={onBarClick}
deleteFunnel={deleteFunnel}
openFunnelSettings={openFunnelSettings}
loading={loading}
@@ -206,7 +385,7 @@ const FunnelsList = ({
{isAuthenticated && allowedToManage ? (
<AddFunnel openFunnelSettings={openFunnelSettings} />
) : null}
- </div>
+ </ul>
)
}
diff --git a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
index fed34d4b9..23f8cf20a 100644
--- a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
+++ b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
@@ -1,20 +1,10 @@
-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 { FunnelIcon, PlusIcon } from '@phosphor-icons/react'
-import {
- useState,
- useEffect,
- useMemo,
- useCallback,
- useRef,
- Suspense,
- use,
-} from 'react'
+import { useState, useEffect, useMemo, useCallback, useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link } from '~/ui/Link'
import {
useSearchParams,
useFetcher,
@@ -25,9 +15,8 @@ import { toast } from 'sonner'
import type { FunnelDataResponse } from '~/api/api.server'
import { FUNNELS_PERIOD_PAIRS } from '~/lib/constants'
-import { Funnel, AnalyticsFunnel } from '~/lib/models/Project'
+import type { Funnel } from '~/lib/models/Project'
import NewFunnel from '~/modals/NewFunnel'
-import { FunnelChart } from '~/pages/Project/tabs/Funnels/FunnelChart'
import FunnelsList from '~/pages/Project/tabs/Funnels/FunnelsList'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
import Filters from '~/pages/Project/View/components/Filters'
@@ -46,52 +35,19 @@ import type {
ProjectViewActionData,
} from '~/routes/projects.$id'
import Button from '~/ui/Button'
-import Loader from '~/ui/Loader'
+import { Link } from '~/ui/Link'
import LoadingBar from '~/ui/LoadingBar'
import { Text } from '~/ui/Text'
-import { nLocaleFormatter } from '~/utils/generic'
import routes from '~/utils/routes'
-import { SessionsDrawer } from '../Traffic/SessionsDrawer'
-import { LoaderView } from '../../View/components/LoaderView'
-interface DeferredFunnelData {
- funnelData: FunnelDataResponse | null
-}
-
-function FunnelDataResolver({
- children,
-}: {
- children: (data: DeferredFunnelData) => React.ReactNode
-}) {
- const { funnelData: funnelDataPromise } = useLoaderData<ProjectLoaderData>()
- const funnelData = funnelDataPromise ? use(funnelDataPromise) : null
- return <>{children({ funnelData })}</>
-}
+import { SessionsDrawer } from '../Traffic/SessionsDrawer'
interface FunnelsViewProps {
tnMapping: Record<string, string>
}
-function FunnelsViewWrapper({ tnMapping }: FunnelsViewProps) {
- return (
- <Suspense fallback={<LoaderView />}>
- <FunnelDataResolver>
- {(deferredData) => (
- <FunnelsViewInner deferredData={deferredData} tnMapping={tnMapping} />
- )}
- </FunnelDataResolver>
- </Suspense>
- )
-}
-
-interface FunnelsViewInnerProps extends FunnelsViewProps {
- deferredData: DeferredFunnelData
-}
-
-const FunnelsViewInner = ({
- deferredData,
- tnMapping,
-}: FunnelsViewInnerProps) => {
+const FunnelsView = ({ tnMapping }: FunnelsViewProps) => {
+ const { funnelData: funnelDataPromise } = useLoaderData<ProjectLoaderData>()
const { id, project, mergeProject, allowedToManage } = useCurrentProject()
const projectPassword = useProjectPassword(id)
const revalidator = useRevalidator()
@@ -99,58 +55,29 @@ const FunnelsViewInner = ({
const { funnelsRefreshTrigger } = useRefreshTriggers()
const { periodPairs, period, timezone, timeFormat, filters } =
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] = useSearchParams()
- const isEmbedded = searchParams.get('embedded') === 'true'
-
- const isMountedRef = useRef(true)
+ const [searchParams, setSearchParams] = useSearchParams()
const fetcher = useFetcher<ProjectViewActionData>()
const lastHandledData = useRef<ProjectViewActionData | null>(null)
+ const deletedFunnelId = useRef<string | null>(null)
+ const lastRefreshTrigger = useRef(funnelsRefreshTrigger)
- // Funnels state
const [isNewFunnelOpened, setIsNewFunnelOpened] = useState(false)
- const [funnelToEdit, setFunnelToEdit] = useState<Funnel | undefined>(
- undefined,
- )
- const [dataLoading, setDataLoading] = useState(false)
+ const [funnelToEdit, setFunnelToEdit] = useState<Funnel | undefined>()
+ const [funnelAnalytics, setFunnelAnalytics] =
+ useState<FunnelDataResponse | null>(null)
const [sessionsDrawer, setSessionsDrawer] = useState<{
stepIndex: number
label: string
dropoff?: boolean
} | null>(null)
- // Initialize funnelAnalytics from loader data
- const [funnelAnalytics, setFunnelAnalytics] = useState<{
- funnel: AnalyticsFunnel[]
- totalPageviews: number
- } | null>(() => {
- if (deferredData.funnelData) {
- return {
- funnel: deferredData.funnelData.funnel,
- totalPageviews: deferredData.funnelData.totalPageviews,
- }
- }
- return null
- })
-
- const funnelActionLoading = fetcher.state !== 'idle'
- const analyticsLoading = revalidator.state === 'loading'
-
- // 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])
+ const timeBucketSelectorItems = useMemo(() => {
+ return _filter(periodPairs, (el) => {
+ return _includes(FUNNELS_PERIOD_PAIRS, el.period)
+ })
+ }, [periodPairs])
- // Get active funnel from URL
const activeFunnel = useMemo(() => {
if (!project) {
return null
@@ -165,15 +92,59 @@ const FunnelsViewInner = ({
return _find(project.funnels, (funnel) => funnel.id === funnelId) || null
}, [searchParams, project])
- // Cleanup on unmount
- useEffect(() => {
- isMountedRef.current = true
- return () => {
- isMountedRef.current = false
- }
+ const funnelActionLoading = fetcher.state !== 'idle'
+ const analyticsLoading = revalidator.state === 'loading'
+ const hasFunnels = !_isEmpty(project?.funnels)
+
+ const clearActiveFunnel = useCallback(() => {
+ const nextSearchParams = new URLSearchParams(searchParams.toString())
+ nextSearchParams.delete('funnelId')
+ setFunnelAnalytics(null)
+ setSessionsDrawer(null)
+ setSearchParams(nextSearchParams)
+ }, [searchParams, setSearchParams])
+
+ const handleToggleFunnel = useCallback(
+ (funnelId: string) => {
+ const nextSearchParams = new URLSearchParams(searchParams.toString())
+
+ if (nextSearchParams.get('funnelId') === funnelId) {
+ nextSearchParams.delete('funnelId')
+ } else {
+ nextSearchParams.set('funnelId', funnelId)
+ }
+
+ setFunnelAnalytics(null)
+ setSessionsDrawer(null)
+ setSearchParams(nextSearchParams)
+ },
+ [searchParams, setSearchParams],
+ )
+
+ const openFunnelSettings = useCallback((funnel?: Funnel) => {
+ setFunnelToEdit(funnel)
+ setIsNewFunnelOpened(true)
+ }, [])
+
+ const closeFunnelSettings = useCallback(() => {
+ setIsNewFunnelOpened(false)
+ setFunnelToEdit(undefined)
}, [])
- // Handle fetcher responses
+ const handleFunnelDataResolved = useCallback(
+ (funnelId: string, funnelData: FunnelDataResponse | null) => {
+ if (activeFunnel?.id === funnelId) {
+ setFunnelAnalytics(funnelData)
+ }
+ },
+ [activeFunnel?.id],
+ )
+
+ useEffect(() => {
+ setFunnelAnalytics(null)
+ setSessionsDrawer(null)
+ }, [activeFunnel?.id])
+
useEffect(() => {
if (fetcher.state !== 'idle' || !fetcher.data) return
if (lastHandledData.current === fetcher.data) return
@@ -184,25 +155,21 @@ const FunnelsViewInner = ({
if (success) {
if (intent === 'create-funnel') {
toast.success(t('apiNotifications.funnelCreated'))
- setIsNewFunnelOpened(false)
- setFunnelToEdit(undefined)
- // Reload funnels list
+ closeFunnelSettings()
fetcher.submit(
{ intent: 'get-funnels', password: projectPassword },
{ method: 'POST', action: `/projects/${id}` },
)
} else if (intent === 'update-funnel') {
toast.success(t('apiNotifications.funnelUpdated'))
- setIsNewFunnelOpened(false)
- setFunnelToEdit(undefined)
+ closeFunnelSettings()
fetcher.submit(
{ intent: 'get-funnels', password: projectPassword },
{ method: 'POST', action: `/projects/${id}` },
)
- // If the updated funnel is currently being viewed, revalidate to refresh analytics
+
const updatedFunnelId = (fetcher.data.data as { id?: string })?.id
if (updatedFunnelId && activeFunnel?.id === updatedFunnelId) {
- setDataLoading(true)
revalidator.revalidate()
}
} else if (intent === 'delete-funnel') {
@@ -211,22 +178,30 @@ const FunnelsViewInner = ({
{ intent: 'get-funnels', password: projectPassword },
{ method: 'POST', action: `/projects/${id}` },
)
+
+ if (deletedFunnelId.current === activeFunnel?.id) {
+ clearActiveFunnel()
+ }
+ deletedFunnelId.current = null
} else if (intent === 'get-funnels' && fetcher.data.data) {
mergeProject({ funnels: fetcher.data.data as Funnel[] })
}
} else if (error) {
toast.error(error)
+ deletedFunnelId.current = null
}
}, [
fetcher.state,
fetcher.data,
t,
- id,
+ closeFunnelSettings,
projectPassword,
+ id,
fetcher,
- mergeProject,
activeFunnel?.id,
revalidator,
+ clearActiveFunnel,
+ mergeProject,
])
const onFunnelCreate = (name: string, steps: string[]) => {
@@ -250,43 +225,13 @@ const FunnelsViewInner = ({
const onFunnelDelete = (funnelId: string) => {
if (funnelActionLoading) return
+ deletedFunnelId.current = funnelId
fetcher.submit(
{ intent: 'delete-funnel', funnelId },
{ method: 'POST', action: `/projects/${id}` },
)
}
- // Sync funnelAnalytics when loader data changes
- useEffect(() => {
- if (deferredData.funnelData && revalidator.state === 'idle') {
- setFunnelAnalytics({
- funnel: deferredData.funnelData.funnel,
- totalPageviews: deferredData.funnelData.totalPageviews,
- })
- setDataLoading(false)
- }
- }, [deferredData.funnelData, revalidator.state])
-
- 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 handleBarClick = useCallback(
(stepIndex: number) => {
if (!funnelAnalytics?.funnel?.[stepIndex]) return
@@ -300,246 +245,78 @@ const FunnelsViewInner = ({
[funnelAnalytics],
)
- // When activeFunnel changes (URL params) and we have loader data, sync it
- // The actual data fetching happens via the loader when URL changes
useEffect(() => {
- if (!project || !activeFunnel) return
-
- // If we have loader data for this funnel, use it
- if (deferredData.funnelData) {
- setFunnelAnalytics({
- funnel: deferredData.funnelData.funnel,
- totalPageviews: deferredData.funnelData.totalPageviews,
- })
- } else {
- // No loader data yet, trigger revalidation
- setDataLoading(true)
- revalidator.revalidate()
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [activeFunnel?.id])
-
- // Handle refresh trigger from parent
- useEffect(() => {
- if (funnelsRefreshTrigger > 0) {
- if (activeFunnel?.id) {
- setDataLoading(true)
- }
+ if (funnelsRefreshTrigger > lastRefreshTrigger.current) {
+ lastRefreshTrigger.current = funnelsRefreshTrigger
revalidator.revalidate()
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [funnelsRefreshTrigger])
-
- // Show loader during initial load when viewing a specific funnel (only when no data yet)
- if (activeFunnel && analyticsLoading && !funnelAnalytics) {
- return (
- <div
- className={cx('flex flex-col bg-gray-50 dark:bg-slate-950', {
- 'min-h-including-header': !isEmbedded,
- 'min-h-screen': isEmbedded,
- })}
- >
- <Loader />
- </div>
- )
- }
-
- // Render funnel detail view
- if (activeFunnel) {
- return (
- <>
- <DashboardHeader
- backLink={`?${pureSearchParams}`}
- backButtonLabel={t('project.backToFunnels')}
- showLiveVisitors={false}
- hideTimeBucket
- timeBucketSelectorItems={timeBucketSelectorItems}
- rightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}
- leftContent={
- <Text
- as='h2'
- size='xl'
- weight='bold'
- className='wrap-break-word break-all'
- >
- {activeFunnel?.name}
- </Text>
- }
- />
- <Filters className='mb-3' tnMapping={tnMapping} />
- {dataLoading && funnelAnalytics ? <LoadingBar /> : null}
-
- {/* Funnel Chart */}
- <div className='relative overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
- {funnelSummary ? (
- <>
- <Text as='p' weight='medium' className='lg:text-left'>
- {t('project.funnelSummary.xStepFunnel', {
- x: funnelSummary.stepsCount,
- })}
- <span className='mx-2 text-gray-400'>β€’</span>
- {t('project.funnelSummary.conversionRateShort', {
- x: funnelSummary.conversionRate,
- })}
- </Text>
- <Text as='p' className='text-center lg:text-left'>
- {t('project.funnelSummary.startShort')}:{' '}
- {nLocaleFormatter(funnelSummary.startVisitors)}
- <span className='mx-1'>β†’</span>
- {t('project.funnelSummary.endShort')}:{' '}
- {nLocaleFormatter(funnelSummary.endVisitors)}
- </Text>
- </>
- ) : null}
- {funnelAnalytics?.funnel ? (
- <FunnelChart
- funnel={funnelAnalytics.funnel}
- totalPageviews={funnelAnalytics.totalPageviews}
- t={t}
- className='mt-5 h-80 [&_svg]:!overflow-visible'
- onBarClick={handleBarClick}
- />
- ) : null}
- </div>
+ }, [funnelsRefreshTrigger, revalidator])
- {/* 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}
- />
-
- <SessionsDrawer
- isOpen={!!sessionsDrawer}
- onClose={() => setSessionsDrawer(null)}
- label={sessionsDrawer?.label || ''}
- projectId={id}
- timezone={timezone}
- timeFormat={timeFormat}
- period={period}
- from={searchParams.get('from') || undefined}
- to={searchParams.get('to') || undefined}
- filters={filters}
- funnelId={activeFunnel?.id}
- funnelStep={sessionsDrawer ? sessionsDrawer.stepIndex + 1 : undefined}
- dropoff={Boolean(sessionsDrawer?.dropoff)}
- showDropoffToggle={
- !!sessionsDrawer &&
- sessionsDrawer.stepIndex <
- (funnelAnalytics?.funnel?.length || 0) - 1
- }
- onDropoffChange={(dropoff) =>
- setSessionsDrawer((current) =>
- current ? { ...current, dropoff } : current,
- )
- }
- totalCount={
- sessionsDrawer
- ? sessionsDrawer.dropoff
- ? funnelAnalytics?.funnel?.[sessionsDrawer.stepIndex + 1]
- ?.dropoff
- : funnelAnalytics?.funnel?.[sessionsDrawer.stepIndex]?.events
- : undefined
- }
- />
- </>
- )
- }
+ return (
+ <>
+ <DashboardHeader
+ showLiveVisitors
+ hideTimeBucket
+ timeBucketSelectorItems={timeBucketSelectorItems}
+ rightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}
+ />
+ <Filters className='mb-3' tnMapping={tnMapping} />
+ {activeFunnel && analyticsLoading && funnelAnalytics ? (
+ <LoadingBar />
+ ) : null}
- // Render funnels list view
- if (!_isEmpty(project?.funnels)) {
- return (
- <>
+ {hasFunnels ? (
<FunnelsList
- openFunnelSettings={(funnel?: Funnel) => {
- if (funnel) {
- setFunnelToEdit(funnel)
- setIsNewFunnelOpened(true)
- return
- }
-
- setIsNewFunnelOpened(true)
- }}
funnels={project?.funnels}
+ activeFunnelId={activeFunnel?.id || null}
+ funnelDataPromise={funnelDataPromise}
+ onToggleFunnel={handleToggleFunnel}
+ onFunnelDataResolved={handleFunnelDataResolved}
+ onBarClick={handleBarClick}
+ openFunnelSettings={openFunnelSettings}
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='mx-auto w-full max-w-2xl py-16 text-center'>
- <div className='mx-auto mb-6 flex size-14 items-center justify-center rounded-xl bg-gray-100 dark:bg-slate-900'>
- <FunnelIcon className='size-7 text-gray-700 dark:text-gray-200' />
- </div>
- <Text as='h3' size='xl' weight='medium' className='tracking-tight'>
- {t('dashboard.funnels')}
- </Text>
- <Text
- as='p'
- size='sm'
- colour='secondary'
- className='mx-auto mt-2 max-w-md whitespace-pre-wrap'
- >
- {t('dashboard.funnelsDesc')}
- </Text>
- <div className='mt-6'>
- {isAuthenticated ? (
- <Button size='lg' onClick={() => setIsNewFunnelOpened(true)}>
- <PlusIcon className='mr-1.5 size-4' />
- {t('dashboard.newFunnel')}
- </Button>
- ) : (
- <Link
- to={routes.signup}
- aria-label={t('titles.signup')}
- className='inline-flex items-center justify-center rounded-md border border-transparent bg-slate-900 px-4 py-2 text-sm font-medium text-white shadow-xs transition-colors hover:bg-slate-700 dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-white'
- >
- {t('header.startForFree')}
- </Link>
- )}
+ ) : (
+ <div className='mx-auto w-full max-w-2xl py-16 text-center'>
+ <div className='mx-auto mb-6 flex size-14 items-center justify-center rounded-xl bg-gray-100 dark:bg-slate-900'>
+ <FunnelIcon className='size-7 text-gray-700 dark:text-gray-200' />
+ </div>
+ <Text as='h3' size='xl' weight='medium' className='tracking-tight'>
+ {t('dashboard.funnels')}
+ </Text>
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mx-auto mt-2 max-w-md whitespace-pre-wrap'
+ >
+ {t('dashboard.funnelsDesc')}
+ </Text>
+ <div className='mt-6'>
+ {isAuthenticated ? (
+ <Button size='lg' onClick={() => setIsNewFunnelOpened(true)}>
+ <PlusIcon className='mr-1.5 size-4' />
+ {t('dashboard.newFunnel')}
+ </Button>
+ ) : (
+ <Link
+ to={routes.signup}
+ aria-label={t('titles.signup')}
+ className='inline-flex items-center justify-center rounded-md border border-transparent bg-slate-900 px-4 py-2 text-sm font-medium text-white shadow-xs transition-colors hover:bg-slate-700 dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-white'
+ >
+ {t('header.startForFree')}
+ </Link>
+ )}
+ </div>
</div>
- </div>
+ )}
+
<NewFunnel
funnel={funnelToEdit}
isOpened={isNewFunnelOpened}
- onClose={() => {
- setIsNewFunnelOpened(false)
- setFunnelToEdit(undefined)
- }}
+ onClose={closeFunnelSettings}
onSubmit={async (name: string, steps: string[]) => {
if (funnelToEdit) {
await onFunnelEdit(funnelToEdit.id, name, steps)
@@ -550,10 +327,40 @@ const FunnelsViewInner = ({
}}
loading={funnelActionLoading}
/>
+
+ <SessionsDrawer
+ isOpen={!!sessionsDrawer}
+ onClose={() => setSessionsDrawer(null)}
+ label={sessionsDrawer?.label || ''}
+ projectId={id}
+ timezone={timezone}
+ timeFormat={timeFormat}
+ period={period}
+ from={searchParams.get('from') || undefined}
+ to={searchParams.get('to') || undefined}
+ filters={filters}
+ funnelId={activeFunnel?.id}
+ funnelStep={sessionsDrawer ? sessionsDrawer.stepIndex + 1 : undefined}
+ dropoff={Boolean(sessionsDrawer?.dropoff)}
+ showDropoffToggle={
+ !!sessionsDrawer &&
+ sessionsDrawer.stepIndex < (funnelAnalytics?.funnel?.length || 0) - 1
+ }
+ onDropoffChange={(dropoff) =>
+ setSessionsDrawer((current) =>
+ current ? { ...current, dropoff } : current,
+ )
+ }
+ totalCount={
+ sessionsDrawer
+ ? sessionsDrawer.dropoff
+ ? funnelAnalytics?.funnel?.[sessionsDrawer.stepIndex + 1]?.dropoff
+ : funnelAnalytics?.funnel?.[sessionsDrawer.stepIndex]?.events
+ : undefined
+ }
+ />
</>
)
}
-const FunnelsView = FunnelsViewWrapper
-
export default FunnelsView