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!

(feature) Funnels (#374)

Andrii Romasiun88293d527383
diff --git a/app/api/index.ts b/app/api/index.ts
index 6a0411434..6b49b318a 100644
--- a/app/api/index.ts
+++ b/app/api/index.ts
@@ -517,6 +517,53 @@ export const getPerfData = (
: error.response.data.message
})
+export const getFunnelData = (
+ pid: string,
+ period: string = '3d',
+ from: string = '',
+ to: string = '',
+ timezone: string = '',
+ funnelId: string = '',
+ password: string | undefined = '',
+) =>
+ api
+ .get(
+ `log/funnel?pid=${pid}&period=${period}&from=${from}&to=${to}&timezone=${timezone}&funnelId=${funnelId}`,
+ {
+ headers: {
+ 'x-password': password,
+ },
+ },
+ )
+ .then((response) => response.data)
+ .catch((error) => {
+ debug('%s', error)
+ throw _isEmpty(error.response.data?.message)
+ ? error.response.data
+ : error.response.data.message
+ })
+
+export const getFunnels = (
+ pid: string,
+ password: string | undefined = '',
+) =>
+ api
+ .get(
+ `project/funnels/${pid}`,
+ {
+ headers: {
+ 'x-password': password,
+ },
+ },
+ )
+ .then((response) => response.data)
+ .catch((error) => {
+ debug('%s', error)
+ throw _isEmpty(error.response.data?.message)
+ ? error.response.data
+ : error.response.data.message
+ })
+
export const getCaptchaData = (
pid: string,
tb: string = 'hour',
@@ -850,6 +897,39 @@ export const addSubscriber = (id: string, data: {
: error.response.data.message
})
+export const addFunnel = (pid: string, name: string, steps: string[]) =>
+ api
+ .post('project/funnel', { pid, name, steps })
+ .then((response): any => response.data)
+ .catch((error) => {
+ debug('%s', error)
+ throw _isEmpty(error.response.data?.message)
+ ? error.response.data
+ : error.response.data.message
+ })
+
+export const updateFunnel = (id: string, pid: string, name: string, steps: string[]) =>
+ api
+ .patch('project/funnel', { id, name, steps, pid })
+ .then((response): any => response.data)
+ .catch((error) => {
+ debug('%s', error)
+ throw _isEmpty(error.response.data?.message)
+ ? error.response.data
+ : error.response.data.message
+ })
+
+export const deleteFunnel = (id: string, pid: string) =>
+ api
+ .delete(`project/funnel/${id}/${pid}`)
+ .then((response): any => response.data)
+ .catch((error) => {
+ debug('%s', error)
+ throw _isEmpty(error.response.data?.message)
+ ? error.response.data
+ : error.response.data.message
+ })
+
export const getSubscribers = (id: string, offset: number, limit: number) =>
api
.get(`project/${id}/subscribers?offset=${offset}&limit=${limit}`)
diff --git a/app/modals/NewFunnel.tsx b/app/modals/NewFunnel.tsx
new file mode 100644
index 000000000..8c42ca8af
--- /dev/null
+++ b/app/modals/NewFunnel.tsx
@@ -0,0 +1,157 @@
+import React, { useState, useEffect, useMemo } from 'react'
+import _map from 'lodash/map'
+import _every from 'lodash/every'
+import cx from 'clsx'
+import { TrashIcon } from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+
+import Modal from 'ui/Modal'
+import Input from 'ui/Input'
+import Select from 'ui/Select'
+import { MIN_FUNNEL_STEPS, MAX_FUNNEL_STEPS } from 'redux/constants'
+import { getFilters } from 'api'
+import { IFunnel } from 'redux/models/IProject'
+
+interface INewFunnel {
+ onClose: () => void,
+ onSubmit: (name: string, steps: string[]) => Promise<void>,
+ isOpened: boolean,
+ pid: string,
+ loading: boolean,
+ funnel?: IFunnel,
+}
+
+const INITIAL_FUNNEL_STEPS = [null, null]
+
+const NewFunnel = ({
+ onClose, onSubmit, isOpened, pid, funnel, loading,
+}: INewFunnel): JSX.Element => {
+ const { t } = useTranslation('common')
+ const [name, setName] = useState<string>(funnel?.name || '')
+ const [steps, setSteps] = useState<any[]>(funnel?.steps || INITIAL_FUNNEL_STEPS)
+ const [filters, setFilters] = useState<string[]>([])
+ const allStepsFulfilled = useMemo(() => _every(steps, (step) => step), [steps])
+
+ useEffect(() => {
+ if (!isOpened) {
+ return
+ }
+
+ setName(funnel?.name || '')
+ setSteps(funnel?.steps || INITIAL_FUNNEL_STEPS)
+ }, [isOpened, funnel])
+
+ useEffect(() => {
+ const getFiltersData = async () => {
+ let pgFilters: string[] = []
+ let ceFilters: string[] = []
+
+ const promises = [
+ (async () => {
+ pgFilters = await getFilters(pid, 'pg')
+ })(),
+ (async () => {
+ ceFilters = await getFilters(pid, 'ev')
+ })(),
+ ]
+
+ try {
+ await Promise.all(promises)
+ } catch (reason) {
+ console.error('[ERROR] (NewFunnel -> getFiltersData):', reason)
+ }
+
+ setFilters([...pgFilters, ...ceFilters])
+ }
+
+ getFiltersData()
+ }, [pid])
+
+ const _onClose = () => {
+ setTimeout(() => {
+ setName('')
+ setSteps(INITIAL_FUNNEL_STEPS)
+ }, 300)
+ onClose()
+ }
+
+ const _onSubmit = async () => {
+ if (!name || !allStepsFulfilled) {
+ return
+ }
+
+ await onSubmit(name, steps)
+ _onClose()
+ }
+
+ return (
+ <Modal
+ isLoading={loading}
+ onClose={_onClose}
+ onSubmit={_onSubmit}
+ submitText={t('common.continue')}
+ message={(
+ <div>
+ <Input
+ name='funnel-name-input'
+ type='text'
+ label={t('modals.funnels.name')}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <p className='mt-5 text-sm font-medium text-gray-700 dark:text-gray-200'>
+ {t('modals.funnels.steps')}
+ </p>
+ {_map(steps, (step, index) => (
+ <div key={index} className='flex items-center space-x-2 mt-1'>
+ <Select
+ className='w-full !ml-0'
+ buttonClassName={cx({
+ 'h-9': !step,
+ })}
+ items={filters}
+ keyExtractor={(item) => item}
+ labelExtractor={(item) => item}
+ onSelect={(item) => {
+ const newSteps = [...steps]
+ newSteps[index] = item
+ setSteps(newSteps)
+ }}
+ title={step || ''}
+ />
+ {steps.length > MIN_FUNNEL_STEPS && (
+ <TrashIcon
+ role='button'
+ aria-label='Remove step'
+ className='h-5 w-5 text-gray-400 dark:text-gray-200 hover:text-gray-500 dark:hover:text-gray-300 cursor-pointer'
+ onClick={() => {
+ const newSteps = [...steps]
+ newSteps.splice(index, 1)
+ setSteps(newSteps)
+ }}
+ />
+ )}
+ </div>
+ ))}
+ {steps.length < MAX_FUNNEL_STEPS && (
+ <p
+ onClick={() => {
+ setSteps([...steps, null])
+ }}
+ role='button'
+ className='mt-2 cursor-pointer text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'
+ >
+ + {t('modals.funnels.addStep')}
+ </p>
+ )}
+ </div>
+ )}
+ title={funnel ? t('modals.funnels.editTitle') : t('modals.funnels.addTitle')}
+ isOpened={isOpened}
+ submitDisabled={!name || !allStepsFulfilled}
+ overflowVisible
+ />
+ )
+}
+
+export default NewFunnel
diff --git a/app/pages/Captcha/Settings/CaptchaSettings.tsx b/app/pages/Captcha/Settings/CaptchaSettings.tsx
index b14dfbfaf..6999ea9fa 100644
--- a/app/pages/Captcha/Settings/CaptchaSettings.tsx
+++ b/app/pages/Captcha/Settings/CaptchaSettings.tsx
@@ -404,6 +404,7 @@ const CaptchaSettings = ({
labelExtractor={(item) => `${item.name} | ${item.id}`}
keyExtractor={(item) => item.id}
onSelect={(item) => setReuseProjectId(item)}
+ capitalise
/>
)}
{isSettings ? (
diff --git a/app/pages/Dashboard/Dashboard.tsx b/app/pages/Dashboard/Dashboard.tsx
index 92e7a25a9..5def0a4b8 100644
--- a/app/pages/Dashboard/Dashboard.tsx
+++ b/app/pages/Dashboard/Dashboard.tsx
@@ -547,6 +547,7 @@ const Dashboard = ({
}
}}
title={activeTabLabel}
+ capitalise
/>
</div>
<div className='hidden sm:block'>
diff --git a/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx b/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx
index ac99fedc1..c9560c813 100644
--- a/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx
+++ b/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx
@@ -293,6 +293,7 @@ const ProjectAlertsSettings = ({
queryMetric: key,
}))
}}
+ capitalise
/>
</div>
{form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS && (
@@ -322,6 +323,7 @@ const ProjectAlertsSettings = ({
queryCondition: key,
}))
}}
+ capitalise
/>
</div>
<Input
@@ -349,6 +351,7 @@ const ProjectAlertsSettings = ({
queryTime: key,
}))
}}
+ capitalise
/>
</div>
{isSettings ? (
diff --git a/app/pages/Project/View/ViewProject.container.tsx b/app/pages/Project/View/ViewProject.container.tsx
index 7aedcc729..5842a8463 100644
--- a/app/pages/Project/View/ViewProject.container.tsx
+++ b/app/pages/Project/View/ViewProject.container.tsx
@@ -17,6 +17,7 @@ const mapStateToProps = (state: StateType) => {
isLoading: state.ui.projects.isLoadingShared,
cache: state.ui.cache.analytics,
cachePerf: state.ui.cache.analyticsPerf,
+ cacheFunnels: state.ui.cache.funnels,
projectViewPrefs: state.ui.cache.projectViewPrefs,
authenticated: state.auth.authenticated,
authLoading: state.auth.loading,
@@ -38,6 +39,7 @@ const mapStateToProps = (state: StateType) => {
authLoading: state.auth.loading,
cache: state.ui.cache.analytics,
cachePerf: state.ui.cache.analyticsPerf,
+ cacheFunnels: state.ui.cache.funnels,
projectViewPrefs: state.ui.cache.projectViewPrefs,
authenticated: state.auth.authenticated,
timezone: state.auth.user.timezone,
@@ -79,6 +81,13 @@ const mapDispatchToProps = (dispatch: AppDispatch) => ({
key,
}))
},
+ setFunnelsCache: (pid: string, data: any, key: string) => {
+ dispatch(UIActions.setFunnelsCache({
+ pid,
+ data,
+ key,
+ }))
+ },
setPublicProject: (project: Partial<IProject | ISharedProject>) => {
dispatch(UIActions.setPublicProject({
project,
@@ -90,6 +99,12 @@ const mapDispatchToProps = (dispatch: AppDispatch) => ({
shared,
}))
},
+ updateProject: (pid: string, project: Partial<IProject | ISharedProject>) => {
+ dispatch(UIActions.updateProject({
+ pid,
+ project,
+ }))
+ },
setLiveStatsForProject: (id: string, count: number) => {
dispatch(UIActions.setLiveStatsProject({
id,
diff --git a/app/pages/Project/View/ViewProject.helpers.tsx b/app/pages/Project/View/ViewProject.helpers.tsx
index d88a4b085..e9f1e27a2 100644
--- a/app/pages/Project/View/ViewProject.helpers.tsx
+++ b/app/pages/Project/View/ViewProject.helpers.tsx
@@ -15,6 +15,7 @@ import _map from 'lodash/map'
import _split from 'lodash/split'
import _replace from 'lodash/replace'
import _isEmpty from 'lodash/isEmpty'
+import _startsWith from 'lodash/startsWith'
import _keys from 'lodash/keys'
import _size from 'lodash/size'
import _round from 'lodash/round'
@@ -35,6 +36,7 @@ import {
getTimeFromSeconds, getStringFromTime, sumArrays, nFormatter,
} from 'utils/generic'
import countries from 'utils/isoCountries'
+import { IAnalyticsFunnel } from 'redux/models/IProject'
const getAvg = (arr: any) => {
const total = _reduce(arr, (acc, c) => acc + c, 0)
@@ -592,8 +594,8 @@ const getSettings = (
value: string,
x: Date,
}) => {
- if (el.id === 'sessionDuration') {
- return `
+ if (el.id === 'sessionDuration') {
+ return `
<li class='flex justify-between'>
<div class='flex justify-items-start'>
<div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(el.id)}></div>
@@ -602,13 +604,13 @@ const getSettings = (
<span class='pl-4'>${getStringFromTime(getTimeFromSeconds(el.value))}</span>
</li>
`
- }
+ }
- if (el.id === 'trendlineUnique' || el.id === 'trendlineTotal') {
- return ''
- }
+ if (el.id === 'trendlineUnique' || el.id === 'trendlineTotal') {
+ return ''
+ }
- return `
+ return `
<li class='flex justify-between'>
<div class='flex justify-items-start'>
<div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(el.id)}></div>
@@ -617,7 +619,7 @@ const getSettings = (
<span class='pl-4'>${el.value}</span>
</li>
`
- }).join('')}`
+ }).join('')}`
}
return `
@@ -629,20 +631,20 @@ const getSettings = (
value: string,
x: Date,
}) => {
- const {
- id, index, name, value, x,
- } = el
+ const {
+ id, index, name, value, x,
+ } = el
- const xDataValueCompare = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(dayjs(compareChart?.x[index]).toDate()) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(dayjs(compareChart?.x[index]).toDate())
- const xDataValue = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(x) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(x)
- const valueCompare = id === 'sessionDuration' ? getStringFromTime(getTimeFromSeconds(compareChart?.[typesOptionsToTypesCompare?.[id]]?.[index])) : compareChart?.[typesOptionsToTypesCompare[id]]?.[index]
+ const xDataValueCompare = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(dayjs(compareChart?.x[index]).toDate()) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(dayjs(compareChart?.x[index]).toDate())
+ const xDataValue = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(x) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(x)
+ const valueCompare = id === 'sessionDuration' ? getStringFromTime(getTimeFromSeconds(compareChart?.[typesOptionsToTypesCompare?.[id]]?.[index])) : compareChart?.[typesOptionsToTypesCompare[id]]?.[index]
- if (id === 'uniqueCompare' || id === 'totalCompare' || id === 'bounceCompare' || id === 'sessionDurationCompare') {
- return ''
- }
+ if (id === 'uniqueCompare' || id === 'totalCompare' || id === 'bounceCompare' || id === 'sessionDurationCompare') {
+ return ''
+ }
- if (id === 'sessionDuration') {
- return `
+ if (id === 'sessionDuration') {
+ return `
<div class='flex justify-between'>
<div class='flex justify-items-start'>
<div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(id)}></div>
@@ -661,9 +663,9 @@ const getSettings = (
</p>` : ''}
</li>
`
- }
+ }
- return `
+ return `
<div class='flex justify-between'>
<div class='flex justify-items-start'>
<div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(id)}></div>
@@ -681,7 +683,7 @@ const getSettings = (
</p>` : ''}
</li>
`
- }).join('')}
+ }).join('')}
</ul>`
},
},
@@ -714,12 +716,151 @@ const getSettings = (
}
}
+// function to get the settings and data for the funnels chart
+const getSettingsFunnels = (
+ funnel: IAnalyticsFunnel[],
+ totalPageviews: number,
+ t: (key: string, params?: any) => string,
+) => {
+ const values = _map(funnel, (step) => {
+ if (_startsWith(step.value, '/')) {
+ return t('project.visitPage', { page: step.value })
+ }
+
+ return step.value
+ })
+ const events = _map(funnel, (step) => step.events)
+ const dropoff = _map(funnel, (step) => step.dropoff)
+
+ return {
+ data: {
+ x: 'x',
+ columns: [
+ ['x', ...values],
+ ['dropoff', ...dropoff],
+ ['events', ...events],
+ ],
+ types: {
+ events: bar(),
+ dropoff: bar(),
+ },
+ colors: {
+ events: '#2563eb', // blue-600
+ dropoff: 'rgba(37, 99, 235, 0.2)', // blue-600 + opacity
+ },
+ groups: [
+ ['events', 'dropoff'],
+ ],
+ order: (a: any, b: any) => {
+ return a.id < b.id
+ },
+ },
+ transition: {
+ duration: 500,
+ },
+ resize: {
+ auto: true,
+ timer: false,
+ },
+ axis: {
+ x: {
+ type: 'category',
+ },
+ y: {
+ tick: {
+ format: (d: number) => nFormatter(d, 1),
+ },
+ },
+ },
+ tooltip: {
+ contents: (items: any, _: any, __: any, color: any) => {
+ const { index } = items[0]
+ const step = funnel[index]
+ const stepTitle = values[index]
+ const prevStepTitle = values[index - 1]
+
+ const prevStepHtml = prevStepTitle ? `
+ <span>${prevStepTitle}</span>
+ ` : ''
+
+ const title = `
+ <p class='font-semibold flex space-x-2 items-center tracking-tight'>
+ ${prevStepHtml}
+ <svg fill='none' viewBox='0 0 24 24' stroke-width='1.5' class='w-4 h-4'>
+ <path class='stroke-gray-400 dark:stroke-gray-200' stroke-linecap='round' stroke-linejoin='round' d='M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3' />
+ </svg>
+ <span>${stepTitle}</span>
+ </p>
+ `
+
+ const events = `
+ <tr class='tracking-tight'>
+ <td class='pr-7'>
+ <div class='w-3 h-3 rounded-sm mr-1 float-left mt-1.5' style=background-color:${color('events')}></div>
+ <span class='font-semibold'>
+ ${_startsWith(step.value, '/') ? t('project.visitors') : t('project.events')}
+ </span>
+ </td>
+ <td class='pr-3 font-semibold text-right'>
+ ${step.events}
+ </td>
+ <td class='text-right'>
+ ${step.eventsPercStep}%
+ </td>
+ </tr>
+ `
+
+ const dropoff = `
+ <tr class='tracking-tight'>
+ <td class='pr-7'>
+ <div class='w-3 h-3 rounded-sm mr-1 float-left mt-1.5' style="background-color:${color('dropoff')}"}></div>
+ <span class='font-semibold'>
+ ${index === 0 ? t('project.neverEnteredTheFunnel') : t('project.dropoff')}
+ </span>
+ </td>
+ <td class='pr-3 font-semibold text-right'>
+ ${index === 0 ? totalPageviews - step.events : step.dropoff}
+ </td>
+ <td class='text-right'>
+ ${index === 0 ? _round(((totalPageviews - step.events) / totalPageviews) * 100, 2) : step.dropoffPercStep}%
+ </td>
+ </tr>
+ `
+
+ return `
+ <div class='bg-gray-100 dark:text-gray-50 dark:bg-slate-800 rounded-md shadow-md px-3 py-1'>
+ ${title}
+ <hr class='border-gray-200 dark:border-gray-600' />
+ <table class='table-fixed'>
+ <thead>
+ <tr>
+ <th className='w-3/5'></th>
+ <th className='w-1/5'></th>
+ <th className='w-1/5'></th>
+ </tr>
+ </thead>
+ <tbody>
+ ${events}
+ ${dropoff}
+ </tbody>
+ </table>
+ </div>
+ `
+ },
+ },
+ padding: {
+ left: 40,
+ },
+ bindto: '#dataChart',
+ }
+}
+
const perfomanceChartCompare = ['dnsCompare', 'tlsCompare', 'connCompare', 'responseCompare', 'renderCompare', 'dom_loadCompare', 'ttfbCompare', 'frontendCompare', 'networkCompare', 'backendCompare']
const getSettingsPerf = (
chart: {
- [key: string]: string[]
-},
+ [key: string]: string[]
+ },
timeBucket: string,
activeChartMetrics: string,
rotateXAxias: boolean,
@@ -814,16 +955,16 @@ const getSettingsPerf = (
if (_isEmpty(compareChart)) {
return `<ul class='bg-gray-100 dark:text-gray-50 dark:bg-slate-800 rounded-md shadow-md px-3 py-1'>
<li class='font-semibold'>${timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
-}</li>
+ }</li>
<hr class='border-gray-200 dark:border-gray-600' />
${_map(item, (el: {
- id: string,
- index: number,
- name: string,
- value: string,
- x: Date,
- }) => {
- return `
+ id: string,
+ index: number,
+ name: string,
+ value: string,
+ x: Date,
+ }) => {
+ return `
<li class='flex justify-between'>
<div class='flex justify-items-start'>
<div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(el.id)}></div>
@@ -832,31 +973,31 @@ const getSettingsPerf = (
<span class='pl-4'>${getStringFromTime(getTimeFromSeconds(el.value), true)}</span>
</li>
`
- }).join('')}`
+ }).join('')}`
}
return `
<ul class='bg-gray-100 dark:text-gray-50 dark:bg-slate-800 rounded-md shadow-md px-3 py-1'>
${_map(item, (el: {
- id: string,
- index: number,
- name: string,
- value: string,
- x: Date,
- }) => {
- const {
- id, index, name, value, x,
- } = el
-
- const xDataValueCompare = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(dayjs(compareChart?.x[index]).toDate()) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(dayjs(compareChart?.x[index]).toDate())
- const xDataValue = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(x) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(x)
- const valueCompare = getValueForTooltipPerfomance(compareChart, id, index)
-
- if (_includes(perfomanceChartCompare, id)) {
- return ''
- }
+ id: string,
+ index: number,
+ name: string,
+ value: string,
+ x: Date,
+ }) => {
+ const {
+ id, index, name, value, x,
+ } = el
+
+ const xDataValueCompare = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(dayjs(compareChart?.x[index]).toDate()) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(dayjs(compareChart?.x[index]).toDate())
+ const xDataValue = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(x) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(x)
+ const valueCompare = getValueForTooltipPerfomance(compareChart, id, index)
+
+ if (_includes(perfomanceChartCompare, id)) {
+ return ''
+ }
- return `
+ return `
<div class='flex justify-between'>
<div class='flex justify-items-start'>
<div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(id)}></div>
@@ -874,7 +1015,7 @@ const getSettingsPerf = (
</p>` : ''}
</li>
`
- }).join('')}
+ }).join('')}
</ul>`
},
},
@@ -973,4 +1114,5 @@ export {
validPeriods, validTimeBacket, noRegionPeriods, getSettings,
getExportFilename, getColumns, onCSVExportClick, CHART_METRICS_MAPPING,
CHART_METRICS_MAPPING_PERF, getColumnsPerf, getSettingsPerf, transformAIChartData, FILTER_CHART_METRICS_MAPPING_FOR_COMPARE,
+ getSettingsFunnels,
}
diff --git a/app/pages/Project/View/ViewProject.tsx b/app/pages/Project/View/ViewProject.tsx
index cddda9d0f..8a3a34292 100644
--- a/app/pages/Project/View/ViewProject.tsx
+++ b/app/pages/Project/View/ViewProject.tsx
@@ -12,6 +12,7 @@ import bb from 'billboard.js'
import {
ArrowDownTrayIcon, Cog8ToothIcon, ArrowPathIcon, ChartBarIcon, BoltIcon, BellIcon,
PresentationChartBarIcon, PresentationChartLineIcon, NoSymbolIcon, MagnifyingGlassIcon,
+ FunnelIcon, ChevronLeftIcon,
} from '@heroicons/react/24/outline'
import cx from 'clsx'
import dayjs from 'dayjs'
@@ -49,9 +50,10 @@ import {
timeBucketToDays, getProjectCacheCustomKey, MAX_MONTHS_IN_PAST, PROJECT_TABS, TimeFormat, getProjectForcastCacheKey, chartTypes, roleAdmin,
TRAFFIC_PANELS_ORDER, PERFORMANCE_PANELS_ORDER, isSelfhosted, tbPeriodPairsCompare, PERIOD_PAIRS_COMPARE, filtersPeriodPairs, IS_ACTIVE_COMPARE,
PROJECTS_PROTECTED, getProjectCacheCustomKeyPerf, isBrowser, TITLE_SUFFIX, FILTERS_PANELS_ORDER, KEY_FOR_ALL_TIME, MARKETPLACE_URL,
+ getFunnelsCacheKey, getFunnelsCacheCustomKey,
} from 'redux/constants'
import { IUser } from 'redux/models/IUser'
-import { IProject, ILiveStats } from 'redux/models/IProject'
+import { IProject, ILiveStats, IFunnel, IAnalyticsFunnel } from 'redux/models/IProject'
import { IProjectForShared, ISharedProject } from 'redux/models/ISharedProject'
import { ICountryEntry } from 'redux/models/IEntry'
import Loader from 'ui/Loader'
@@ -61,12 +63,14 @@ import Select from 'ui/Select'
import FlatPicker from 'ui/Flatpicker'
import Robot from 'ui/icons/Robot'
import Forecast from 'modals/Forecast'
+import NewFunnel from 'modals/NewFunnel'
import routes from 'routesPath'
import Header from 'components/Header'
import Footer from 'components/Footer'
import {
getProjectData, getProject, getOverallStats, getLiveVisitors, getPerfData, getProjectDataCustomEvents,
- getProjectCompareData, checkPassword, getCustomEventsMetadata,
+ getProjectCompareData, checkPassword, getCustomEventsMetadata, addFunnel, updateFunnel, deleteFunnel,
+ getFunnelData, getFunnels,
} from 'api'
import { getChartPrediction } from 'api/ai'
import {
@@ -76,8 +80,10 @@ import {
onCSVExportClick, getFormatDate, panelIconMapping, typeNameMapping, validFilters, validPeriods,
validTimeBacket, noRegionPeriods, getSettings, getColumns, CHART_METRICS_MAPPING,
CHART_METRICS_MAPPING_PERF, getSettingsPerf, transformAIChartData, FILTER_CHART_METRICS_MAPPING_FOR_COMPARE,
+ getSettingsFunnels,
} from './ViewProject.helpers'
import CCRow from './components/CCRow'
+import FunnelsList from './components/FunnelsList'
import RefRow from './components/RefRow'
import NoEvents from './components/NoEvents'
import SearchFilters from './components/SearchFilters'
@@ -129,13 +135,16 @@ interface IViewProject {
ssrAuthenticated: boolean,
queryPassword: string | null,
authLoading: boolean,
+ cacheFunnels: any,
+ setFunnelsCache: (pid: string, data: any, key: string) => void,
+ updateProject: (pid: string, project: Partial<IProject | ISharedProject>) => void,
}
const ViewProject = ({
projects, isLoading: _isLoading, showError, cache, cachePerf, setProjectCache, projectViewPrefs, setProjectViewPrefs, setPublicProject,
setLiveStatsForProject, authenticated: csrAuthenticated, timezone, user, sharedProjects, extensions, generateAlert, setProjectCachePerf,
projectTab, setProjectTab, setProjects, setProjectForcastCache, customEventsPrefs, setCustomEventsPrefs, liveStats, password, theme,
- ssrTheme, embedded, ssrAuthenticated, queryPassword, authLoading,
+ ssrTheme, embedded, ssrAuthenticated, queryPassword, authLoading, cacheFunnels, setFunnelsCache, updateProject,
}: IViewProject) => {
const authenticated = isBrowser
? authLoading
@@ -216,6 +225,7 @@ const ViewProject = ({
// isPanelsDataEmpty is a true we are display components <NoEvents /> and do not show dropdowns with activeChartMetrics
const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState<boolean>(false)
const [isForecastOpened, setIsForecastOpened] = useState<boolean>(false)
+ const [isNewFunnelOpened, setIsNewFunnelOpened] = useState<boolean>(false)
// analyticsLoading is a boolean for show loader on chart
const [analyticsLoading, setAnalyticsLoading] = useState<boolean>(true)
// period using for logic with update data on chart. Set when user change period in dropdown and when we parse query params from url
@@ -277,8 +287,98 @@ const ViewProject = ({
return projectTab || PROJECT_TABS.traffic
})
+ const [activeFunnel, setActiveFunnel] = useState<IFunnel | null>(null)
+ const [funnelToEdit, setFunnelToEdit] = useState<IFunnel | undefined>(undefined)
+ const [funnelActionLoading, setFunnelActionLoading] = useState<boolean>(false)
+
const mode = activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode] ? 'cumulative' : 'periodical'
+ const onFunnelCreate = async (name: string, steps: string[]) => {
+ if (funnelActionLoading) {
+ return
+ }
+
+ setFunnelActionLoading(true)
+
+ try {
+ const funnel = await addFunnel(id, name, steps)
+ console.log(funnel)
+ } catch (reason: any) {
+ console.error('[ERROR] (onFunnelCreate)(addFunnel)', reason)
+ showError(reason)
+ }
+
+ try {
+ const funnels = await getFunnels(id, projectPassword)
+
+ updateProject(id, {
+ funnels,
+ })
+ } catch (reason: any) {
+ console.error('[ERROR] (onFunnelCreate)(getFunnels)', reason)
+ }
+
+ generateAlert(t('apiNotifications.funnelCreated'), 'success')
+ setFunnelActionLoading(false)
+ }
+
+ const onFunnelEdit = async (funnelId: string, name: string, steps: string[]) => {
+ if (funnelActionLoading) {
+ return
+ }
+
+ setFunnelActionLoading(true)
+
+ try {
+ const funnel = await updateFunnel(funnelId, id, name, steps)
+ console.log(funnel)
+ } catch (reason: any) {
+ console.error('[ERROR] (onFunnelEdit)(updateFunnel)', reason)
+ showError(reason)
+ }
+
+ try {
+ const funnels = await getFunnels(id, projectPassword)
+
+ updateProject(id, {
+ funnels,
+ })
+ } catch (reason: any) {
+ console.error('[ERROR] (onFunnelCreate)(getFunnels)', reason)
+ }
+
+ generateAlert(t('apiNotifications.funnelUpdated'), 'success')
+ 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)
+ showError(reason)
+ }
+
+ try {
+ const funnels = await getFunnels(id, projectPassword)
+
+ updateProject(id, {
+ funnels,
+ })
+ } catch (reason: any) {
+ console.error('[ERROR] (onFunnelCreate)(getFunnels)', reason)
+ }
+
+ generateAlert(t('apiNotifications.funnelDeleted'), 'success')
+ setFunnelActionLoading(false)
+ }
+
useEffect(() => {
// @ts-ignore
const url = new URL(window.location)
@@ -491,35 +591,36 @@ const ViewProject = ({
}, [panelsData])
// dataNames is a list of metrics for chart
- const dataNames = useMemo(() => {
- return {
- unique: t('project.unique'),
- total: t('project.total'),
- bounce: `${t('dashboard.bounceRate')} (%)`,
- viewsPerUnique: t('dashboard.viewsPerUnique'),
- trendlineTotal: t('project.trendlineTotal'),
- trendlineUnique: t('project.trendlineUnique'),
- sessionDuration: t('dashboard.sessionDuration'),
- ...dataNamesCustomEvents,
- }
- }, [t, dataNamesCustomEvents])
+ const dataNames = useMemo(() => ({
+ unique: t('project.unique'),
+ total: t('project.total'),
+ bounce: `${t('dashboard.bounceRate')} (%)`,
+ viewsPerUnique: t('dashboard.viewsPerUnique'),
+ trendlineTotal: t('project.trendlineTotal'),
+ trendlineUnique: t('project.trendlineUnique'),
+ sessionDuration: t('dashboard.sessionDuration'),
+ ...dataNamesCustomEvents,
+ }), [t, dataNamesCustomEvents])
// dataNamesPerf is a list of metrics for chart in performance tab
- const dataNamesPerf = useMemo(() => {
- return {
- full: t('dashboard.timing'),
- network: t('dashboard.network'),
- frontend: t('dashboard.frontend'),
- backend: t('dashboard.backend'),
- dns: t('dashboard.dns'),
- tls: t('dashboard.tls'),
- conn: t('dashboard.conn'),
- response: t('dashboard.response'),
- render: t('dashboard.render'),
- dom_load: t('dashboard.domLoad'),
- ttfb: t('dashboard.ttfb'),
- }
- }, [t])
+ const dataNamesPerf = useMemo(() => ({
+ full: t('dashboard.timing'),
+ network: t('dashboard.network'),
+ frontend: t('dashboard.frontend'),
+ backend: t('dashboard.backend'),
+ dns: t('dashboard.dns'),
+ tls: t('dashboard.tls'),
+ conn: t('dashboard.conn'),
+ response: t('dashboard.response'),
+ render: t('dashboard.render'),
+ dom_load: t('dashboard.domLoad'),
+ ttfb: t('dashboard.ttfb'),
+ }), [t])
+
+ const dataNamesFunnel = useMemo(() => ({
+ dropoff: t('project.dropoff'),
+ events: t('project.visitors'),
+ }), [t])
// tabs is a tabs for project
const tabs: {
@@ -557,6 +658,11 @@ const ViewProject = ({
return [
...selfhostedOnly,
+ {
+ id: PROJECT_TABS.funnels,
+ label: t('dashboard.funnels'),
+ icon: FunnelIcon,
+ },
{
id: PROJECT_TABS.alerts,
label: t('dashboard.alerts'),
@@ -645,9 +751,9 @@ const ViewProject = ({
// set chart data
setMainChart(() => {
// @ts-ignore
- const generete = bb.generate(bbSettings)
- generete.data.names(dataNames)
- return generete
+ const generate = bb.generate(bbSettings)
+ generate.data.names(dataNames)
+ return generate
})
} catch (e) {
console.error('[ERROR] FAILED TO LOAD CUSTOM EVENTS', e)
@@ -846,9 +952,9 @@ const ViewProject = ({
if (activeTab === PROJECT_TABS.traffic) {
setMainChart(() => {
// @ts-ignore
- const generete = bb.generate(bbSettings)
- generete.data.names(dataNames)
- return generete
+ const generate = bb.generate(bbSettings)
+ generate.data.names(dataNames)
+ return generate
})
}
@@ -1016,9 +1122,9 @@ const ViewProject = ({
if (activeTab === PROJECT_TABS.performance) {
setMainChart(() => {
// @ts-ignore
- const generete = bb.generate(bbSettings)
- generete.data.names(dataNamesPerf)
- return generete
+ const generate = bb.generate(bbSettings)
+ generate.data.names(dataNamesPerf)
+ return generate
})
}
@@ -1036,6 +1142,66 @@ const ViewProject = ({
}
}
+ const loadFunnelsData = useCallback(async (forced = false) => {
+ if (!activeFunnel) {
+ return
+ }
+
+ if (!forced && (isLoading || _isEmpty(project) || dataLoading)) {
+ return
+ }
+
+ setDataLoading(true)
+
+ try {
+ let dataFunnel: { funnel: IAnalyticsFunnel[], totalPageviews: number }
+ let key
+ let from
+ let to
+
+ if (dateRange) {
+ from = getFormatDate(dateRange[0])
+ to = getFormatDate(dateRange[1])
+ key = getFunnelsCacheCustomKey(id, activeFunnel.id, from, to)
+ } else {
+ key = getFunnelsCacheKey(id, activeFunnel.id, period)
+ }
+
+ if (!forced && !_isEmpty(cacheFunnels[id]) && !_isEmpty(cacheFunnels[id][key])) {
+ dataFunnel = cacheFunnels[id][key]
+ } else {
+ if (period === 'custom' && dateRange) {
+ dataFunnel = await getFunnelData(id, '', from, to, timezone, activeFunnel.id, projectPassword)
+ } else {
+ dataFunnel = await getFunnelData(id, period, '', '', timezone, activeFunnel.id, projectPassword)
+ }
+
+ setFunnelsCache(id, dataFunnel || {}, key)
+ }
+
+ const { funnel, totalPageviews } = dataFunnel
+
+ const bbSettings = getSettingsFunnels(funnel, totalPageviews, t)
+
+ if (activeTab === PROJECT_TABS.funnels) {
+ setMainChart(() => {
+ // @ts-ignore
+ const generate = bb.generate(bbSettings)
+ generate.data.names(dataNamesFunnel)
+ return generate
+ })
+ }
+
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ } catch (e) {
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ console.error('[ERROR](loadFunnelsData) Loading funnels data failed')
+ console.error(e)
+ }
+ }, [activeFunnel, activeTab, cacheFunnels, dataLoading, dateRange, id, isLoading, period, project, projectPassword, timezone, setFunnelsCache, t, dataNamesFunnel])
+
// this funtion is used for requesting the data from the API when the filter is changed
const filterHandler = (column: string, filter: any, isExclusive = false) => {
let newFilters
@@ -1247,9 +1413,15 @@ const ViewProject = ({
if (!isLoading && !dataLoading) {
if (activeTab === PROJECT_TABS.performance) {
loadAnalyticsPerf(true)
- } else {
- loadAnalytics(true)
+ return
+ }
+
+ if (activeTab === PROJECT_TABS.funnels) {
+ loadFunnelsData(true)
+ return
}
+
+ loadAnalytics(true)
}
}
@@ -1325,9 +1497,9 @@ const ViewProject = ({
setMainChart(() => {
// @ts-ignore
- const generete = bb.generate(bbSettings)
- generete.data.names(dataNames)
- return generete
+ const generate = bb.generate(bbSettings)
+ generate.data.names(dataNames)
+ return generate
})
}
@@ -1354,9 +1526,9 @@ const ViewProject = ({
setMainChart(() => {
// @ts-ignore
- const generete = bb.generate(bbSettings)
- generete.data.names(dataNamesPerf)
- return generete
+ const generate = bb.generate(bbSettings)
+ generate.data.names(dataNamesPerf)
+ return generate
})
}
}, [isLoading, activeChartMetrics, chartData, chartDataPerf, activeChartMetricsPerf, dataChartCompare]) // eslint-disable-line
@@ -1608,15 +1780,11 @@ const ViewProject = ({
return
}
- if (areFiltersParsed && areTimeBucketParsed && arePeriodParsed) {
- if (activeTab === PROJECT_TABS.traffic) {
- loadAnalytics()
- }
+ if (areFiltersParsed && areTimeBucketParsed && arePeriodParsed && activeTab === PROJECT_TABS.traffic) {
+ loadAnalytics()
}
- if (areFiltersPerfParsed && areTimeBucketParsed && arePeriodParsed) {
- if (activeTab === PROJECT_TABS.performance) {
- loadAnalyticsPerf()
- }
+ if (areFiltersPerfParsed && areTimeBucketParsed && arePeriodParsed && activeTab === PROJECT_TABS.performance) {
+ loadAnalyticsPerf()
}
}, [project, period, chartType, filters, forecasedChartData, timeBucket, periodPairs, areFiltersParsed, areTimeBucketParsed, arePeriodParsed, t, activeTab, areFiltersPerfParsed]) // eslint-disable-line
@@ -1625,19 +1793,23 @@ const ViewProject = ({
return
}
- if (areFiltersParsed && areTimeBucketParsed && arePeriodParsed) {
- if (activeTab === PROJECT_TABS.traffic) {
- loadAnalytics()
- }
+ if (areFiltersParsed && areTimeBucketParsed && arePeriodParsed && activeTab === PROJECT_TABS.traffic) {
+ loadAnalytics()
}
- if (areFiltersPerfParsed && areTimeBucketParsed && arePeriodParsed) {
- if (activeTab === PROJECT_TABS.performance) {
- loadAnalyticsPerf()
- }
+ if (areFiltersPerfParsed && areTimeBucketParsed && arePeriodParsed && activeTab === PROJECT_TABS.performance) {
+ loadAnalyticsPerf()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [project, period, chartType, filters, forecasedChartData, areFiltersParsed, areTimeBucketParsed, arePeriodParsed, activeTab, areFiltersPerfParsed])
+ useEffect(() => {
+ if (!project || !activeFunnel) {
+ return
+ }
+
+ loadFunnelsData()
+ }, [project, activeFunnel, loadFunnelsData, period, t])
+
// using this for fix some bugs with update custom events data for chart
useEffect(() => {
if (!_isEmpty(activeChartMetricsCustomEvents)) {
@@ -1899,7 +2071,9 @@ const ViewProject = ({
if (isActiveCompare) {
if (activeTab === PROJECT_TABS.performance) {
loadAnalyticsPerf()
- } else {
+ }
+
+ if (activeTab === PROJECT_TABS.traffic) {
loadAnalytics()
}
}
@@ -1950,11 +2124,12 @@ const ViewProject = ({
}
}}
title={activeTabLabel}
+ capitalise
/>
</div>
<div className='hidden sm:block'>
<div>
- <nav className='-mb-px flex space-x-4' aria-label='Tabs'>
+ <nav className='-mb-px flex space-x-4 overflow-x-auto' aria-label='Tabs'>
{_map(tabs, tab => {
const isCurrent = tab.id === activeTab
const isSettings = tab.id === 'settings'
@@ -1993,143 +2168,144 @@ const ViewProject = ({
</div>
</div>
</div>
- {activeTab !== PROJECT_TABS.alerts && (
+ {activeTab !== PROJECT_TABS.alerts && (activeFunnel || activeTab !== PROJECT_TABS.funnels) && (
<>
<div className='flex flex-col md:flex-row items-center md:items-start justify-between mt-2'>
<h2 className='text-3xl font-bold text-gray-900 dark:text-gray-50 break-words break-all'>
- {name}
+ {/* If tab is funnels - then display a funnel name, otherwise a project name */}
+ {activeTab === PROJECT_TABS.funnels ? activeFunnel?.name : name}
</h2>
<div className='flex items-center mt-3 md:mt-0 max-w-[420px] flex-wrap sm:flex-nowrap sm:max-w-none justify-center sm:justify-between w-full sm:w-auto mx-auto sm:mx-0 space-x-2 gap-y-1'>
- <Dropdown
- items={[...exportTypes, ...customExportTypes, { label: t('project.lookingForMore'), lookingForMore: true, onClick: () => {} }]}
- title={[
- <ArrowDownTrayIcon key='download-icon' className='w-5 h-5 mr-2' />,
- <Fragment key='export-data'>
- {t('project.exportData')}
- </Fragment>,
- ]}
- labelExtractor={item => {
- const { label, lookingForMore } = item
-
- if (lookingForMore) {
- return (
- <a href={MARKETPLACE_URL} target='_blank' rel='noreferrer'>
- {label}
- </a>
- )
- }
-
- return label
- }}
- keyExtractor={item => item.label}
- onSelect={item => item.onClick(panelsData, t)}
- className={cx('ml-3', { hidden: isPanelsDataEmpty || analyticsLoading })}
- />
- {activeTab === PROJECT_TABS.traffic ? (
- !isPanelsDataEmpty && (
- <Dropdown
- items={isActiveCompare ? _filter(chartMetrics, (el) => {
- return !_includes(FILTER_CHART_METRICS_MAPPING_FOR_COMPARE, el.id)
- }) : chartMetrics}
- title={t('project.metricVis')}
- 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='px-4 py-2 flex items-center cursor-not-allowed'>
- <NoSymbolIcon className='w-5 h-5 mr-1' />
- {label}
- </span>
- )
- }
+ {activeTab !== PROJECT_TABS.funnels && (
+ <Dropdown
+ items={[...exportTypes, ...customExportTypes, { label: t('project.lookingForMore'), lookingForMore: true, onClick: () => { } }]}
+ title={[
+ <ArrowDownTrayIcon key='download-icon' className='w-5 h-5 mr-2' />,
+ <Fragment key='export-data'>
+ {t('project.exportData')}
+ </Fragment>,
+ ]}
+ labelExtractor={item => {
+ const { label, lookingForMore } = item
+
+ if (lookingForMore) {
+ return (
+ <a href={MARKETPLACE_URL} target='_blank' rel='noreferrer'>
+ {label}
+ </a>
+ )
+ }
+ return label
+ }}
+ keyExtractor={item => item.label}
+ onSelect={item => item.onClick(panelsData, t)}
+ className={cx('ml-3', { hidden: isPanelsDataEmpty || analyticsLoading })}
+ />
+ )}
+ {activeTab === PROJECT_TABS.traffic && !isPanelsDataEmpty && (
+ <Dropdown
+ items={isActiveCompare ? _filter(chartMetrics, (el) => {
+ return !_includes(FILTER_CHART_METRICS_MAPPING_FOR_COMPARE, el.id)
+ }) : chartMetrics}
+ title={t('project.metricVis')}
+ labelExtractor={(pair) => {
+ const {
+ label, id: pairID, active, conflicts,
+ } = pair
+
+ const conflicted = isConflicted(conflicts)
+
+ if (pairID === CHART_METRICS_MAPPING.customEvents) {
+ if (_isEmpty(panelsData.customs)) {
return (
- <Dropdown
- menuItemsClassName='max-w-[300px] max-h-[300px] overflow-auto'
- items={chartMetricsCustomEvents}
- title={label}
- labelExtractor={(event) => (
- <Checkbox
- className={cx({ hidden: isPanelsDataEmpty || analyticsLoading })}
- label={_size(event.label) > CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH ? (
- <span title={event.label}>
- {_truncate(event.label, { length: CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH })}
- </span>
- ) : event.label}
- id={event.id}
- onChange={() => { }}
- checked={event.active}
- />
- )}
- buttonClassName='group-hover:bg-gray-200 dark:group-hover:bg-slate-700 px-4 py-2 inline-flex w-full bg-white text-sm font-medium text-gray-700 dark:text-gray-50 dark:border-gray-800 dark:bg-slate-800'
- keyExtractor={(event) => event.id}
- onSelect={(event, e) => {
- e?.stopPropagation()
- e?.preventDefault()
-
- setActiveChartMetricsCustomEvents((prev) => {
- const newActiveChartMetricsCustomEvents = [...prev]
- const index = _findIndex(prev, (item) => item === event.id)
- if (index === -1) {
- newActiveChartMetricsCustomEvents.push(event.id)
- } else {
- newActiveChartMetricsCustomEvents.splice(index, 1)
- }
- return newActiveChartMetricsCustomEvents
- })
- }}
- />
+ <span className='px-4 py-2 flex items-center cursor-not-allowed'>
+ <NoSymbolIcon className='w-5 h-5 mr-1' />
+ {label}
+ </span>
)
}
return (
- <Checkbox
- className={cx('px-4 py-2', { hidden: isPanelsDataEmpty || analyticsLoading })}
- label={label}
- disabled={conflicted}
- id={pairID}
- checked={active}
+ <Dropdown
+ menuItemsClassName='max-w-[300px] max-h-[300px] overflow-auto'
+ items={chartMetricsCustomEvents}
+ title={label}
+ labelExtractor={(event) => (
+ <Checkbox
+ className={cx({ hidden: isPanelsDataEmpty || analyticsLoading })}
+ label={_size(event.label) > CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH ? (
+ <span title={event.label}>
+ {_truncate(event.label, { length: CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH })}
+ </span>
+ ) : event.label}
+ id={event.id}
+ onChange={() => { }}
+ checked={event.active}
+ />
+ )}
+ buttonClassName='group-hover:bg-gray-200 dark:group-hover:bg-slate-700 px-4 py-2 inline-flex w-full bg-white text-sm font-medium text-gray-700 dark:text-gray-50 dark:border-gray-800 dark:bg-slate-800'
+ keyExtractor={(event) => event.id}
+ onSelect={(event, e) => {
+ e?.stopPropagation()
+ e?.preventDefault()
+
+ setActiveChartMetricsCustomEvents((prev) => {
+ const newActiveChartMetricsCustomEvents = [...prev]
+ const index = _findIndex(prev, (item) => item === event.id)
+ if (index === -1) {
+ newActiveChartMetricsCustomEvents.push(event.id)
+ } else {
+ newActiveChartMetricsCustomEvents.splice(index, 1)
+ }
+ return newActiveChartMetricsCustomEvents
+ })
+ }}
/>
)
- }}
- selectItemClassName='group text-gray-700 dark:text-gray-50 dark:border-gray-800 dark:bg-slate-800 block text-sm cursor-pointer hover:bg-gray-200 dark:hover:bg-slate-700'
- keyExtractor={(pair) => pair.id}
- onSelect={({ id: pairID, conflicts }) => {
- if (isConflicted(conflicts)) {
- generateAlert(t('project.conflictMetric'), 'error')
- return
- }
+ }
- if (pairID === CHART_METRICS_MAPPING.customEvents) {
- return
- }
+ return (
+ <Checkbox
+ className={cx('px-4 py-2', { hidden: isPanelsDataEmpty || analyticsLoading })}
+ label={label}
+ disabled={conflicted}
+ id={pairID}
+ checked={active}
+ />
+ )
+ }}
+ selectItemClassName='group text-gray-700 dark:text-gray-50 dark:border-gray-800 dark:bg-slate-800 block text-sm cursor-pointer hover:bg-gray-200 dark:hover:bg-slate-700'
+ keyExtractor={(pair) => pair.id}
+ onSelect={({ id: pairID, conflicts }) => {
+ if (isConflicted(conflicts)) {
+ generateAlert(t('project.conflictMetric'), 'error')
+ return
+ }
- switchActiveChartMetric(pairID)
- }}
- />
- )) : (
- !isPanelsDataEmptyPerf && (
- <Dropdown
- items={chartMetricsPerf}
- className='min-w-[170px] xs:min-w-0'
- title={(
- <p>
- {_find(chartMetricsPerf, ({ id: chartId }) => chartId === activeChartMetricsPerf)?.label}
- </p>
- )}
- labelExtractor={(pair) => pair.label}
- keyExtractor={(pair) => pair.id}
- onSelect={({ id: pairID }) => {
- switchActiveChartMetric(pairID)
- }}
- />
- )
+ if (pairID === CHART_METRICS_MAPPING.customEvents) {
+ return
+ }
+
+ switchActiveChartMetric(pairID)
+ }}
+ />
+ )}
+ {activeTab === PROJECT_TABS.performance && !isPanelsDataEmptyPerf && (
+ <Dropdown
+ items={chartMetricsPerf}
+ className='min-w-[170px] xs:min-w-0'
+ title={(
+ <p>
+ {_find(chartMetricsPerf, ({ id: chartId }) => chartId === activeChartMetricsPerf)?.label}
+ </p>
+ )}
+ labelExtractor={(pair) => pair.label}
+ keyExtractor={(pair) => pair.id}
+ onSelect={({ id: pairID }) => {
+ switchActiveChartMetric(pairID)
+ }}
+ />
)}
<Dropdown
items={isActiveCompare ? _filter(periodPairs, (el) => {
@@ -2142,7 +2318,7 @@ const ViewProject = ({
keyExtractor={(pair) => pair.label}
onSelect={(pair) => {
if (pair.period === PERIOD_PAIRS_COMPARE.COMPARE) {
- if (activeTab !== PROJECT_TABS.traffic && activeTab !== PROJECT_TABS.performance) {
+ if (activeTab === PROJECT_TABS.alerts) {
return
}
@@ -2197,6 +2373,18 @@ const ViewProject = ({
/>
</>
)}
+ {activeTab === PROJECT_TABS.funnels && (
+ <button
+ type='button'
+ title={t('project.refreshStats')}
+ onClick={refreshStats}
+ className={cx('relative shadow-sm rounded-md px-3 md:px-4 py-2 bg-white text-sm font-medium hover:bg-gray-50 dark:bg-slate-800 dark:hover:bg-slate-700 focus:z-10 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 focus:dark:ring-gray-200 focus:dark:border-gray-200', {
+ 'cursor-not-allowed opacity-50': isLoading || dataLoading,
+ })}
+ >
+ <ArrowPathIcon className='w-5 h-5 text-gray-700 dark:text-gray-50' />
+ </button>
+ )}
<FlatPicker
className='!mx-0'
ref={refCalendar}
@@ -2219,7 +2407,16 @@ const ViewProject = ({
/>
</div>
</div>
- <div>
+ {activeTab === PROJECT_TABS.funnels && (
+ <button
+ onClick={() => setActiveFunnel(null)}
+ className='flex items-center text-base font-normal underline decoration-dashed hover:decoration-solid mb-4 mx-auto md:mx-0 mt-2 md:mt-0 text-gray-900 dark:text-gray-100'
+ >
+ <ChevronLeftIcon className='w-4 h-4' />
+ {t('project.backToFunnels')}
+ </button>
+ )}
+ {activeTab !== PROJECT_TABS.funnels && (
<div className='flex flex-row flex-wrap items-center justify-center md:justify-end h-10 mt-2 md:mt-5 mb-4 space-x-3 space-y-1 md:space-y-0'>
<div>
<button
@@ -2265,7 +2462,7 @@ const ViewProject = ({
<MagnifyingGlassIcon className='w-5 h-5 text-gray-700 dark:text-gray-50' />
</button>
</div>
- <div className={cx('md:border-r border-gray-200 dark:border-gray-600 md:pr-3 sm:mr-3 space-x-2', {
+ <div className={cx('border-gray-200 dark:border-gray-600 md:pr-3 sm:mr-3 space-x-2 md:border-r', {
hidden: isPanelsDataEmpty || analyticsLoading || checkIfAllMetricsAreDisabled,
})}
>
@@ -2316,7 +2513,7 @@ const ViewProject = ({
</span>
</div>
</div>
- </div>
+ )}
</>
)}
{(activeTab === PROJECT_TABS.alerts && (isSharedProject || !project?.isOwner || !authenticated)) && (
@@ -2335,10 +2532,53 @@ const ViewProject = ({
</Link>
</div>
)}
+ {(activeTab === PROJECT_TABS.funnels && !activeFunnel && !_isEmpty(project.funnels) && (
+ <FunnelsList
+ openFunnelSettings={(funnel?: IFunnel) => {
+ if (funnel) {
+ setFunnelToEdit(funnel)
+ setIsNewFunnelOpened(true)
+ return
+ }
+
+ setIsNewFunnelOpened(true)
+ }}
+ openFunnel={setActiveFunnel}
+ funnels={project.funnels}
+ deleteFunnel={onFunnelDelete}
+ loading={funnelActionLoading}
+ />
+ ))}
+ {(activeTab === PROJECT_TABS.funnels && !activeFunnel && _isEmpty(project.funnels) && (
+ <div className='p-5 mt-5 bg-gray-700 rounded-xl'>
+ <div className='flex items-center text-gray-50'>
+ <FunnelIcon className='w-8 h-8 mr-2' />
+ <p className='font-bold text-3xl'>
+ {t('dashboard.funnels')}
+ </p>
+ </div>
+ <p className='text-lg whitespace-pre-wrap mt-2 text-gray-100'>
+ {t('dashboard.funnelsDesc')}
+ </p>
+ {authenticated ? (
+ <button
+ type='button'
+ onClick={() => setIsNewFunnelOpened(true)}
+ className='inline-block select-none mt-6 bg-white py-2 px-3 md:px-4 border border-transparent rounded-md text-base font-medium text-gray-700 hover:bg-indigo-50'
+ >
+ {t('dashboard.newFunnel')}
+ </button>
+ ) : (
+ <Link to={routes.signup} className='inline-block select-none mt-6 bg-white py-2 px-3 md:px-4 border border-transparent rounded-md text-base font-medium text-gray-700 hover:bg-indigo-50' aria-label={t('titles.signup')}>
+ {t('common.getStarted')}
+ </Link>
+ )}
+ </div>
+ ))}
{(activeTab === PROJECT_TABS.alerts && !isSharedProject && project?.isOwner && authenticated) && (
<ProjectAlertsView projectId={id} />
)}
- {(analyticsLoading && activeTab !== PROJECT_TABS.alerts) && (
+ {(analyticsLoading && activeTab !== PROJECT_TABS.alerts && activeTab !== PROJECT_TABS.funnels) && (
<Loader />
)}
{(isPanelsDataEmpty && activeTab === PROJECT_TABS.traffic) && (
@@ -2673,6 +2913,21 @@ const ViewProject = ({
</div>
</div>
)}
+ {activeTab === PROJECT_TABS.funnels && (
+ <div className={cx('pt-4 md:pt-0', { hidden: !activeFunnel || analyticsLoading })}>
+ <div className='h-80'>
+ <div className='h-80 mt-5 md:mt-0' id='dataChart' />
+ </div>
+ {dataLoading && (
+ <div className='!bg-transparent static mt-4' id='loader'>
+ <div className='loader-head dark:!bg-slate-800'>
+ <div className='first dark:!bg-slate-600' />
+ <div className='second dark:!bg-slate-600' />
+ </div>
+ </div>
+ )}
+ </div>
+ )}
</div>
</div>
{!authenticated && activeTab !== PROJECT_TABS.alerts && !embedded && (
@@ -2709,6 +2964,24 @@ const ViewProject = ({
activeTB={t(`project.${timeBucket}`)}
tb={timeBucket}
/>
+ <NewFunnel
+ pid={id}
+ 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
t={t}
showModal={showFiltersSearch}
@@ -2760,6 +3033,7 @@ ViewProject.propTypes = {
embedded: PropTypes.bool.isRequired,
ssrAuthenticated: PropTypes.bool.isRequired,
authLoading: PropTypes.bool.isRequired,
+ updateProject: PropTypes.func.isRequired,
queryPassword: PropTypes.string,
}
diff --git a/app/pages/Project/View/components/FunnelsList.tsx b/app/pages/Project/View/components/FunnelsList.tsx
new file mode 100644
index 000000000..85def6faf
--- /dev/null
+++ b/app/pages/Project/View/components/FunnelsList.tsx
@@ -0,0 +1,119 @@
+import React from 'react'
+import _map from 'lodash/map'
+import cx from 'clsx'
+import { useTranslation } from 'react-i18next'
+import {
+ AdjustmentsVerticalIcon, PlusCircleIcon, TrashIcon,
+} from '@heroicons/react/24/outline'
+import { IFunnel } from 'redux/models/IProject'
+
+interface IFunnelsList {
+ funnels?: any[]
+ openFunnelSettings: (funnel?: IFunnel) => void
+ openFunnel: (funnel: IFunnel) => void
+ deleteFunnel: (id: string) => void
+ loading: boolean
+}
+
+interface IFunnelCard {
+ funnel: IFunnel
+ openFunnelSettings: (funnel: IFunnel) => void
+ openFunnel: (funnel: IFunnel) => void
+ deleteFunnel: (id: string) => void
+ loading: boolean
+}
+
+interface IAddFunnel {
+ openFunnelSettings: (funnel?: IFunnel) => void
+}
+
+const FunnelCard = ({
+ funnel, openFunnelSettings, openFunnel, deleteFunnel, loading,
+}: IFunnelCard): JSX.Element => {
+ const { t } = useTranslation()
+
+ return (
+ <li
+ onClick={() => openFunnel(funnel)}
+ className='overflow-hidden min-h-[120px] rounded-xl border border-gray-200 cursor-pointer bg-gray-50 hover:bg-gray-100 dark:bg-slate-800 dark:hover:bg-slate-700 dark:border-slate-800/25'
+ >
+ <div className='py-4 px-4'>
+ <div className='flex justify-between items-center'>
+ <p className='text-lg font-semibold text-slate-900 dark:text-gray-50 truncate'>
+ {funnel.name}
+ </p>
+ <div
+ className='flex items-center gap-2'
+ >
+ <button
+ type='button'
+ onClick={(e) => {
+ e.stopPropagation()
+ openFunnelSettings(funnel)
+ }}
+ aria-label={t('common.settings')}
+ >
+ <AdjustmentsVerticalIcon className='w-6 h-6 text-gray-800 dark:text-slate-400 hover:text-gray-900 dark:hover:text-slate-500' />
+ </button>
+ <TrashIcon
+ onClick={(e) => {
+ e.stopPropagation()
+ deleteFunnel(funnel.id)
+ }}
+ role='button'
+ aria-label={t('common.delete')}
+ className={cx('w-6 h-6 text-gray-800 dark:text-slate-400 hover:text-gray-900 dark:hover:text-slate-500', {
+ 'cursor-not-allowed': loading,
+ })}
+ />
+ </div>
+ </div>
+ </div>
+ </li>
+ )
+}
+
+const AddFunnel = ({ openFunnelSettings }: IAddFunnel): JSX.Element => {
+ const { t } = useTranslation()
+
+ const onClick = () => {
+ openFunnelSettings()
+ }
+
+ return (
+ <li onClick={onClick} className='flex cursor-pointer justify-center items-center rounded-lg border-2 border-dashed h-auto min-h-[120px] group border-gray-300 hover:border-gray-400'>
+ <div>
+ <PlusCircleIcon className='mx-auto h-12 w-12 text-gray-400 dark:text-gray-200 group-hover:text-gray-500 group-hover:dark:text-gray-400' />
+ <span className='mt-2 block text-sm font-semibold text-gray-900 dark:text-gray-50 group-hover:dark:text-gray-400'>
+ {t('dashboard.newFunnel')}
+ </span>
+ </div>
+ </li>
+ )
+}
+
+/**
+ * Component to render a list of funnels.
+ *
+ * @param {string} name - Row name to override country name with.
+ * @returns {JSX.Element}
+ */
+const FunnelsList = ({ funnels, openFunnelSettings, openFunnel, deleteFunnel, loading }: IFunnelsList): JSX.Element => (
+ <ul className='grid grid-cols-1 gap-x-6 gap-y-3 lg:gap-y-6 lg:grid-cols-3 mt-2'>
+ {_map(funnels, (funnel) => (
+ <FunnelCard
+ key={funnel.id}
+ funnel={funnel}
+ deleteFunnel={deleteFunnel}
+ openFunnelSettings={openFunnelSettings}
+ openFunnel={openFunnel}
+ loading={loading}
+ />
+ ))}
+ <AddFunnel
+ openFunnelSettings={openFunnelSettings}
+ />
+ </ul>
+)
+
+export default FunnelsList
diff --git a/app/pages/UserSettings/UserSettings.tsx b/app/pages/UserSettings/UserSettings.tsx
index 1e4b4bda9..c7c2de2d5 100644
--- a/app/pages/UserSettings/UserSettings.tsx
+++ b/app/pages/UserSettings/UserSettings.tsx
@@ -534,6 +534,7 @@ const UserSettings = ({
}
}}
title={activeTabLabel}
+ capitalise
/>
</div>
<div className='hidden sm:block'>
@@ -646,22 +647,6 @@ const UserSettings = ({
</Button>
</>
)}
- {/* Theme type switch */}
- {/* <hr className='mt-5 border-gray-200 dark:border-gray-600' />
- <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
- {t('profileSettings.theme')}
- </h3>
- <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-2 mb-4'>
- <div>
- <Select
- title={themeType}
- label={t('profileSettings.selectTheme')}
- className='w-full'
- items={[THEME_TYPE.classic, THEME_TYPE.christmas]}
- onSelect={(f) => setAsyncThemeType(f)}
- />
- </div>
- </div> */}
{!isSelfhosted && (
<>
<hr className='mt-5 border-gray-200 dark:border-gray-600' />
@@ -885,6 +870,7 @@ const UserSettings = ({
_findIndex(translatedTimeFormat, (freq) => freq === f)
],
}))}
+ capitalise
/>
</div>
</div>
@@ -931,6 +917,7 @@ const UserSettings = ({
onSelect={(f) => _setReportFrequency(
reportFrequencies[_findIndex(translatedFrequencies, (freq) => freq === f)],
)}
+ capitalise
/>
</div>
</div>
diff --git a/app/redux/constants/index.ts b/app/redux/constants/index.ts
index 151ec7c48..be8087331 100644
--- a/app/redux/constants/index.ts
+++ b/app/redux/constants/index.ts
@@ -273,6 +273,8 @@ export const getProjectForcastCacheKey = (period: string, timeBucket: string, pe
export const getProjectCacheCustomKey = (from: string, to: string, timeBucket: string, mode: 'periodical' | 'cumulative', filters: any): string => `cst${from}${to}${timeBucket}-${mode}${filters ? JSON.stringify(filters) : ''}}`
export const getProjectCacheCustomKeyPerf = (from: string, to: string, timeBucket: string, filters: any): string => `${from}-${to}-${timeBucket}perf${filters ? JSON.stringify(filters) : ''}`
export const getUserFlowCacheKey = (pid: string, period: string, filters: any): string => `${pid}${period}userflow${filters ? JSON.stringify(filters) : ''}`
+export const getFunnelsCacheKey = (pid: string, funnelId: string, period: string): string => `${pid}${funnelId}${period}funnels`
+export const getFunnelsCacheCustomKey = (pid: string, funnelId: string, from: string, to: string): string => `${pid}${funnelId}${from}${to}funnels`
// Cookies
export const GDPR_REQUEST: string = 'gdpr_request'
@@ -284,9 +286,12 @@ export const REFRESH_TOKEN: string = 'refresh_token'
// LocalStorage
export const PAGE_FORCE_REFRESHED = 'page-force-refreshed'
export const PROJECTS_PROTECTED = 'projects_protected'
-
export const IS_ACTIVE_COMPARE = 'is-active-compare'
+// Funnels
+export const MIN_FUNNEL_STEPS = 2
+export const MAX_FUNNEL_STEPS = 10
+
// List of languages with translations available
export const whitelist: string[] = ['en', 'uk', 'pl', 'de', 'sv', 'el', 'ru', 'hi', 'zh']
export const whitelistWithCC = {
@@ -382,11 +387,13 @@ export const tabsForDashboard: IDashboardTabs[] = [
const SELFHOSTED_PROJECT_TABS: IStringObject = {
traffic: 'traffic',
performance: 'performance',
+ funnels: 'funnels',
}
const PRODUCTION_PROJECT_TABS: IStringObject = {
traffic: 'traffic',
performance: 'performance',
+ funnels: 'funnels',
alerts: 'alerts',
}
diff --git a/app/redux/models/IProject.ts b/app/redux/models/IProject.ts
index 02cc4fbbf..dccbabe39 100644
--- a/app/redux/models/IProject.ts
+++ b/app/redux/models/IProject.ts
@@ -1,75 +1,92 @@
export interface IOvervallObject {
- thisWeek?: number
- lastWeek?: number
- thisWeekUnique?: number
- lastWeekUnique?: number
- percChange?: number
- total?: number
- percChangeUnique?: number
+ thisWeek?: number
+ lastWeek?: number
+ thisWeekUnique?: number
+ lastWeekUnique?: number
+ percChange?: number
+ total?: number
+ percChangeUnique?: number
}
export interface IOverall {
- [key: string]: IOvervallObject
+ [key: string]: IOvervallObject
}
export interface IUserShareProject {
- email: string
+ email: string
}
export interface ILiveStats {
- [key: string]: number
+ [key: string]: number
}
export interface IShareOwnerProject {
- id: string
- confirmed: boolean
- role: string
- created: string
- updated: string
- user: IUserShareProject
+ id: string
+ confirmed: boolean
+ role: string
+ created: string
+ updated: string
+ user: IUserShareProject
}
export interface IProjectNames {
- name: string
- id: string
- isCaptchaProject: boolean
+ name: string
+ id: string
+ isCaptchaProject: boolean
+}
+
+export interface IFunnel {
+ id: string
+ name: string
+ steps: string[]
+ created: string
+}
+
+export interface IAnalyticsFunnel {
+ value: string
+ events: number
+ eventsPerc: number
+ eventsPercStep: number
+ dropoff: number
+ dropoffPercStep: number
}
export interface IProject {
- id: string
- name: string
- origins: string[] | string | null
- ipBlacklist: string[] | null | string
- active: boolean
- public: boolean
- isAnalyticsProject: boolean
- isCaptchaProject: boolean
- isCaptchaEnabled: boolean
- captchaSecretKey: string | null
- created: string
- share?: IShareOwnerProject[]
- isOwner: boolean
- overall: IOvervallObject
- uiHidden: boolean
- isPublic?: boolean
- isTransferring?: boolean
- isPasswordProtected?: boolean
- password?: string
+ id: string
+ name: string
+ origins: string[] | string | null
+ ipBlacklist: string[] | null | string
+ active: boolean
+ public: boolean
+ isAnalyticsProject: boolean
+ isCaptchaProject: boolean
+ isCaptchaEnabled: boolean
+ captchaSecretKey: string | null
+ created: string
+ share?: IShareOwnerProject[]
+ isOwner: boolean
+ overall: IOvervallObject
+ uiHidden: boolean
+ funnels: IFunnel[]
+ isPublic?: boolean
+ isTransferring?: boolean
+ isPasswordProtected?: boolean
+ password?: string
}
export interface ICaptchaProject {
- id: string
- name: string
- origins: string[] | string | null
- ipBlacklist: string[] | null | string
- active: boolean
- public: boolean
- isAnalyticsProject: boolean
- isCaptchaProject: boolean
- isCaptchaEnabled: boolean
- captchaSecretKey: string | null
- created: string
- isOwner: boolean
- overall: IOvervallObject
- uiHidden: boolean
+ id: string
+ name: string
+ origins: string[] | string | null
+ ipBlacklist: string[] | null | string
+ active: boolean
+ public: boolean
+ isAnalyticsProject: boolean
+ isCaptchaProject: boolean
+ isCaptchaEnabled: boolean
+ captchaSecretKey: string | null
+ created: string
+ isOwner: boolean
+ overall: IOvervallObject
+ uiHidden: boolean
}
diff --git a/app/redux/reducers/ui/cache.ts b/app/redux/reducers/ui/cache.ts
index 0057722eb..1c01be712 100644
--- a/app/redux/reducers/ui/cache.ts
+++ b/app/redux/reducers/ui/cache.ts
@@ -28,6 +28,7 @@ export const getInitialViewPrefs = (LS_VIEW: string) => {
interface IInitialState {
analytics: any
analyticsPerf: any
+ funnels: any
captchaAnalytics: any
captchaProjectsViewPrefs: any
customEventsPrefs: any
@@ -51,6 +52,7 @@ interface IInitialState {
const initialState: IInitialState = {
analytics: {},
analyticsPerf: {},
+ funnels: {},
captchaAnalytics: {},
captchaProjectsViewPrefs: getInitialViewPrefs(LS_CAPTCHA_VIEW_PREFS_SETTING) || {},
projectViewPrefs: getInitialViewPrefs(LS_VIEW_PREFS_SETTING),
@@ -190,6 +192,15 @@ const cacheSlice = createSlice({
},
}
},
+ setFunnelsCache(state, { payload }: PayloadAction<{ pid: string, key: string, data: any }>) {
+ state.funnels = {
+ ...state.funnels,
+ [payload.pid]: {
+ ...state.funnels[payload.pid],
+ [payload.key]: payload.data,
+ },
+ }
+ },
setProjectForecastCache(state, { payload }: PayloadAction<{ pid: string, key: string, data: any }>) {
state.analytics = {
...state.analytics,
diff --git a/app/redux/reducers/ui/projects.ts b/app/redux/reducers/ui/projects.ts
index f72dc003f..fc3564662 100644
--- a/app/redux/reducers/ui/projects.ts
+++ b/app/redux/reducers/ui/projects.ts
@@ -9,28 +9,28 @@ import { ISharedProject } from 'redux/models/ISharedProject'
import { IAlerts } from 'redux/models/IAlerts'
interface IInitialState {
- projects: IProject[]
- sharedProjects: ISharedProject[]
- captchaProjects: ICaptchaProject[]
- isLoading: boolean
- isLoadingShared: boolean
- isLoadingCaptcha: boolean
- error: null | string
- totalMonthlyEvents: number | null
- total: number
- sharedTotal: number
- captchaTotal: number
- dashboardPaginationPage: number
- dashboardPaginationPageShared: number
- dashboardPaginationPageCaptcha: number
- dashboardTabs: string
- projectTab: string
- alerts: IAlerts[]
- subscribers: any[]
- liveStats: ILiveStats
- password: {
- [key: string]: string
- }
+ projects: IProject[]
+ sharedProjects: ISharedProject[]
+ captchaProjects: ICaptchaProject[]
+ isLoading: boolean
+ isLoadingShared: boolean
+ isLoadingCaptcha: boolean
+ error: null | string
+ totalMonthlyEvents: number | null
+ total: number
+ sharedTotal: number
+ captchaTotal: number
+ dashboardPaginationPage: number
+ dashboardPaginationPageShared: number
+ dashboardPaginationPageCaptcha: number
+ dashboardTabs: string
+ projectTab: string
+ alerts: IAlerts[]
+ subscribers: any[]
+ liveStats: ILiveStats
+ password: {
+ [key: string]: string
+ }
}
const initialState: IInitialState = {
@@ -72,6 +72,19 @@ const projectsSlice = createSlice({
state.projects = payload.projects as IProject[]
}
},
+ updateProject(state, { payload }: PayloadAction<{ project: Partial<IProject | ISharedProject>, pid: string }>) {
+ const { pid, project } = payload
+
+ state.projects = _map(current(state.projects), (res) => {
+ if (res.id === pid) {
+ return {
+ ...res,
+ ...project,
+ }
+ }
+ return res
+ })
+ },
setCaptchaProjects(state, { payload }: PayloadAction<ICaptchaProject[]>) {
state.isLoadingCaptcha = false
state.captchaProjects = payload
@@ -104,7 +117,7 @@ const projectsSlice = createSlice({
removeCaptchaProject(state, { payload }: PayloadAction<string>) {
state.captchaProjects = _filter(state.captchaProjects, (project) => project.id !== payload)
},
- setLiveStats(state, { payload }: PayloadAction<{ data: any}>) {
+ setLiveStats(state, { payload }: PayloadAction<{ data: any }>) {
const { data } = payload
state.liveStats = {
diff --git a/app/ui/Modal.tsx b/app/ui/Modal.tsx
index 6b1d6130e..8a1c46cf4 100644
--- a/app/ui/Modal.tsx
+++ b/app/ui/Modal.tsx
@@ -18,16 +18,18 @@ interface IModal {
onSubmit?: () => void,
closeText?: string,
submitText?: string,
+ submitDisabled?: boolean,
submitType?: 'regular' | 'danger',
size?: 'regular' | 'large',
customButtons?: JSX.Element,
isBeta?: boolean,
isLoading?: boolean,
+ overflowVisible?: boolean,
}
const Modal = ({
className, type, title, message, isOpened, onClose, onSubmit, closeText, submitText,
- submitType, size, customButtons, isBeta, isLoading,
+ submitType, size, customButtons, isBeta, isLoading, submitDisabled, overflowVisible,
}: IModal): JSX.Element => (
<Transition.Root show={isOpened} as={Fragment}>
<Dialog
@@ -64,9 +66,11 @@ const Modal = ({
leaveTo='opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95'
>
<div
- className={cx('inline-block align-bottom bg-white dark:bg-slate-900 rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:px-5 sm:py-4', {
+ className={cx('inline-block align-bottom bg-white dark:bg-slate-900 rounded-lg px-4 pt-5 pb-4 text-left shadow-xl transform transition-all sm:my-8 sm:align-middle sm:px-5 sm:py-4', {
'sm:max-w-lg sm:w-full': size === 'regular',
'max-w-5xl w-full': size === 'large',
+ 'overflow-visible': overflowVisible,
+ 'overflow-hidden': !overflowVisible,
})}
>
<div className='sm:flex sm:items-start'>
@@ -129,8 +133,11 @@ const Modal = ({
<button
type='button'
className={cx('w-full inline-flex justify-center rounded-md shadow-sm px-4 py-2 text-base font-medium text-white sm:ml-3 sm:w-auto sm:text-sm', {
- 'bg-indigo-600 hover:bg-indigo-700': submitType === 'regular',
- 'bg-red-600 hover:bg-red-700': submitType === 'danger',
+ 'bg-indigo-600': submitType === 'regular',
+ 'bg-red-600': submitType === 'danger',
+ 'cursor-not-allowed opacity-70': submitDisabled,
+ 'hover:bg-indigo-700': submitType === 'regular' && !submitDisabled,
+ 'hover:bg-red-700': submitType === 'danger' && !submitDisabled,
})}
onClick={onSubmit}
>
@@ -169,11 +176,13 @@ Modal.propTypes = {
onSubmit: PropTypes.func,
closeText: PropTypes.string,
submitText: PropTypes.string,
+ submitDisabled: PropTypes.bool,
submitType: PropTypes.oneOf(['regular', 'danger']),
size: PropTypes.oneOf(['regular', 'large']),
customButtons: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),
isBeta: PropTypes.bool,
isLoading: PropTypes.bool,
+ overflowVisible: PropTypes.bool,
}
Modal.defaultProps = {
@@ -183,6 +192,7 @@ Modal.defaultProps = {
onSubmit: () => { },
closeText: null,
submitText: null,
+ submitDisabled: false,
submitType: 'regular',
size: 'regular',
type: null,
@@ -190,6 +200,7 @@ Modal.defaultProps = {
customButtons: null,
isBeta: false,
isLoading: false,
+ overflowVisible: false,
}
export default memo(Modal)
diff --git a/app/ui/Pagination.tsx b/app/ui/Pagination.tsx
index efb88595e..459e264ae 100644
--- a/app/ui/Pagination.tsx
+++ b/app/ui/Pagination.tsx
@@ -53,7 +53,7 @@ const Pagination = ({
type='button'
onClick={() => setPage(item)}
className={cx({
- 'border-indigo-500 text-indigo-600 dark:text-indigo-400 border-t-2 pt-4 px-4 inline-flex items-center text-sm font-medium': item === page,
+ 'border-slate-900 text-slate-900 dark:text-gray-50 dark:border-gray-50 border-t-2 pt-4 px-4 inline-flex items-center text-sm font-medium': item === page,
'border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 dark:hover:text-gray-400 hover:border-gray-300 border-t-2 pt-4 px-4 inline-flex items-center text-sm font-medium': item !== page,
})}
>
diff --git a/app/ui/Select.tsx b/app/ui/Select.tsx
index 14a7a0f4e..c3ef56d11 100644
--- a/app/ui/Select.tsx
+++ b/app/ui/Select.tsx
@@ -9,6 +9,8 @@ interface ISelect {
title?: string,
label: string,
className?: string,
+ buttonClassName?: string,
+ capitalise?: boolean,
items: any[],
id?: string,
labelExtractor?: (item: any, index: number) => string,
@@ -18,16 +20,24 @@ interface ISelect {
}
const Select = ({
- title, label, className, items, labelExtractor, keyExtractor, iconExtractor, onSelect, id,
+ title, label, className, items, labelExtractor, keyExtractor, iconExtractor, onSelect, id, buttonClassName, capitalise,
}: ISelect): JSX.Element => (
// @ts-ignore
- <Listbox id={id || ''} className={className} value={title} onChange={onSelect}>
+ <Listbox id={id || ''} value={title} onChange={onSelect}>
{({ open }) => (
<>
<Listbox.Label className='block text-sm whitespace-pre-line font-medium text-gray-700 dark:text-gray-100'>{label}</Listbox.Label>
- <div className='mt-1 relative'>
- <Listbox.Button className='relative w-full bg-white border border-gray-300 dark:text-gray-50 dark:border-gray-800 dark:bg-slate-800 rounded-md shadow-sm pl-3 pr-10 py-2 text-left cursor-default focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm'>
- <span className='block truncate first-letter:capitalize'>{title}</span>
+ <div className={cx('mt-1 relative', className)}>
+ <Listbox.Button
+ className={cx('relative w-full bg-white border border-gray-300 dark:text-gray-50 dark:border-gray-800 dark:bg-slate-800 rounded-md shadow-sm pl-3 pr-10 py-2 text-left cursor-default focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm', buttonClassName)}
+ >
+ <span
+ className={cx('block truncate', {
+ 'first-letter:capitalize': capitalise,
+ })}
+ >
+ {title}
+ </span>
<span className='absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none'>
<ChevronUpDownIcon className='h-5 w-5 text-gray-400' aria-hidden='true' />
</span>
@@ -56,9 +66,10 @@ const Select = ({
{({ selected, active }) => (
<>
<span
- className={cx('block truncate first-letter:capitalize', {
+ className={cx('block truncate', {
'font-semibold': selected,
'font-normal': !selected,
+ 'first-letter:capitalize': capitalise,
})}
>
{labelExtractor ? labelExtractor(item, index) : item}
@@ -101,6 +112,8 @@ Select.propTypes = {
PropTypes.string, PropTypes.object,
])),
className: PropTypes.string,
+ buttonClassName: PropTypes.string,
+ capitalise: PropTypes.bool,
labelExtractor: PropTypes.func,
iconExtractor: PropTypes.func,
keyExtractor: PropTypes.func,
@@ -109,6 +122,8 @@ Select.propTypes = {
Select.defaultProps = {
className: '',
+ buttonClassName: '',
+ capitalise: false,
labelExtractor: null,
keyExtractor: null,
iconExtractor: null,
diff --git a/app/ui/TimezonePicker.tsx b/app/ui/TimezonePicker.tsx
index 1f3cf0d0e..9b852cbca 100644
--- a/app/ui/TimezonePicker.tsx
+++ b/app/ui/TimezonePicker.tsx
@@ -94,6 +94,7 @@ const TimezoneSelect = ({
labelExtractor={labelExtractor}
keyExtractor={keyExtractor}
onSelect={handleChange}
+ capitalise
/>
)
}
diff --git a/app/ui/__test__/Select.test.tsx b/app/ui/__test__/Select.test.tsx
index 58cc07313..2cf843a12 100644
--- a/app/ui/__test__/Select.test.tsx
+++ b/app/ui/__test__/Select.test.tsx
@@ -17,11 +17,13 @@ describe('Select', () => {
keyExtractor?: (item: any, index: number) => string,
iconExtractor?: (item: any, index: number) => JSX.Element | null,
onSelect: (item: any) => void,
+ capitalise: boolean,
} = {
title: 'Select Title',
label: 'Select',
items: [],
onSelect: () => {},
+ capitalise: true,
}
afterEach(() => {
diff --git a/public/locales/en.json b/public/locales/en.json
index 738910393..a3584e49d 100644
--- a/public/locales/en.json
+++ b/public/locales/en.json
@@ -35,7 +35,10 @@
"socialAccountLinked": "The Swetrix account has been linked with your selected provider",
"socialAccountUninked": "The Swetrix account has been unlinked from the selected provider",
"enterPassword": "Please enter the password",
- "incorrectPassword": "Incorrect password, please try again."
+ "incorrectPassword": "Incorrect password, please try again.",
+ "funnelCreated": "The funnel has been created",
+ "funnelUpdated": "The funnel has been updated",
+ "funnelDeleted": "The funnel has been deleted"
},
"common": {
"features": "Features",
@@ -462,6 +465,7 @@
},
"dashboard": {
"newProject": "New project",
+ "newFunnel": "New funnel",
"newCaptchaProject": "New CAPTCHA project",
"verifyEmailTitle": "Please, verify the email address first",
"verifyEmailDesc": "To start using our service and creating your projects, you first need to confirm your email address.\n\nA link to confirm your account was sent to the email address you provided during registration, if it was not delivered - you can request the link again in your account settings.",
@@ -490,8 +494,10 @@
"cumulativeMode": "Cumulative mode",
"traffic": "Traffic",
"performance": "Performance",
+ "funnels": "Funnels",
"alerts": "Alerts",
"alertsDesc": "Automated alerts are a powerful tool that allow you to run automated tasks when specific events occur.\nWe can automatically monitor your project for traffic spikes and notify you via Telegram.",
+ "funnelsDesc": "Funnels are a powerful tool that allow you to track the conversion rate of your users through a series of steps.\nThe analysis provided by the marketing funnel gives you the ability to discover potential problems, improve your website, and boost your conversion rate.",
"frontend": "Frontend",
"backend": "Backend",
"network": "Network",
@@ -564,6 +570,12 @@
"noEvTitle": "No events yet",
"showAll": "Show all views",
"trendlineUnique": "Unique visitors trendline",
+ "backToFunnels": "Back to funnels list",
+ "visitPage": "Visit {{page}}",
+ "visitors": "Visitors",
+ "events": "Events",
+ "dropoff": "Dropoff",
+ "neverEnteredTheFunnel": "Never entered the funnel",
"trendlineTotal": "Pageviews trendline",
"noEvContent": "No events have been captured for the specified timeframe.\nIf you haven't tracked any events yet, you can check out our <url>Docs</url> to easily integrate tracking into your app.",
"noCaptchaEv": "No events have been captured for the specified timeframe.\nIf you haven't set up CAPTCHA yet, you can check out our <url>Docs</url> to easily integrate it into your app.",
@@ -760,6 +772,13 @@
"title": "Traffic forecast",
"desc": "This is a rough estimate of how much traffic you can expect to get on your website, based on Swetrix AI models.",
"input": "The quantity of '{{frequency}}' you want to forecast"
+ },
+ "funnels": {
+ "addTitle": "Add funnel",
+ "editTitle": "Edit funnel",
+ "name": "Funnel name",
+ "steps": "Funnel steps",
+ "addStep": "Add one more step"
}
},
"pricing": {