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!

captcha settings and analytics

kruzhambus18ef37fa649a
diff --git a/src/pages/Captcha/Settings/CaptchaSettings.container.jsx b/src/pages/Captcha/Settings/CaptchaSettings.container.jsx
new file mode 100644
index 000000000..ae858a09b
--- /dev/null
+++ b/src/pages/Captcha/Settings/CaptchaSettings.container.jsx
@@ -0,0 +1,51 @@
+import { connect } from 'react-redux'
+import UIActions from 'redux/actions/ui'
+import { alertsActions } from 'redux/actions/alerts'
+import { errorsActions } from 'redux/actions/errors'
+
+import { tabForSharedProject } from 'redux/constants'
+import ProjectSettings from './CaptchaSettings'
+
+const mapStateToProps = (state) => ({
+ projects: state.ui.projects.projects,
+ sharedProjects: state.ui.projects.sharedProjects,
+ isLoading: state.ui.projects.isLoading,
+ user: state.auth.user,
+ isSharedProject: state.ui.projects.dashboardTabs === tabForSharedProject,
+})
+
+const mapDispatchToProps = (dispatch) => ({
+ updateProjectFailed: (message) => {
+ dispatch(errorsActions.updateProjectFailed(message))
+ },
+ createNewProjectFailed: (message) => {
+ dispatch(errorsActions.createNewProjectFailed(message))
+ },
+ newProject: (message) => {
+ dispatch(alertsActions.newProject(message))
+ },
+ projectDeleted: (message) => {
+ dispatch(alertsActions.projectDeleted(message))
+ },
+ deleteProjectFailed: (message) => {
+ dispatch(errorsActions.deleteProjectFailed(message))
+ },
+ loadProjects: (shared) => {
+ if (shared) {
+ dispatch(UIActions.loadSharedProjects())
+ } else {
+ dispatch(UIActions.loadProjects())
+ }
+ },
+ removeProject: (pid, shared) => {
+ dispatch(UIActions.removeProject(pid, shared))
+ },
+ deleteProjectCache: (pid) => {
+ dispatch(UIActions.deleteProjectCache(pid))
+ },
+ showError: (message) => {
+ dispatch(errorsActions.genericError(message))
+ },
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(ProjectSettings)
diff --git a/src/pages/Captcha/Settings/CaptchaSettings.jsx b/src/pages/Captcha/Settings/CaptchaSettings.jsx
new file mode 100644
index 000000000..07704362f
--- /dev/null
+++ b/src/pages/Captcha/Settings/CaptchaSettings.jsx
@@ -0,0 +1,377 @@
+/* eslint-disable react/forbid-prop-types */
+import React, {
+ useState, useEffect, useMemo, memo,
+} from 'react'
+import { useLocation, useHistory, useParams } from 'react-router-dom'
+import { useTranslation } from 'react-i18next'
+import cx from 'clsx'
+import _isEmpty from 'lodash/isEmpty'
+import _size from 'lodash/size'
+import _replace from 'lodash/replace'
+import _find from 'lodash/find'
+import _join from 'lodash/join'
+import _isString from 'lodash/isString'
+import _split from 'lodash/split'
+import _keys from 'lodash/keys'
+import _map from 'lodash/map'
+import _includes from 'lodash/includes'
+import PropTypes from 'prop-types'
+import { ExclamationTriangleIcon, TrashIcon } from '@heroicons/react/24/outline'
+
+import Title from 'components/Title'
+import { withAuthentication, auth } from 'hoc/protected'
+import { isSelfhosted } from 'redux/constants'
+import {
+ createProject, updateProject, deleteProject, resetProject,
+} from 'api'
+import Input from 'ui/Input'
+import Button from 'ui/Button'
+import Checkbox from 'ui/Checkbox'
+import Modal from 'ui/Modal'
+import { nanoid } from 'utils/random'
+import { trackCustom } from 'utils/analytics'
+import routes from 'routes'
+
+const MAX_NAME_LENGTH = 50
+const MAX_ORIGINS_LENGTH = 300
+const MAX_IPBLACKLIST_LENGTH = 300
+
+const ProjectSettings = ({
+ updateProjectFailed, createNewProjectFailed, newProject, projectDeleted, deleteProjectFailed,
+ loadProjects, isLoading, projects, showError, removeProject, user, isSharedProject, sharedProjects,
+ deleteProjectCache,
+}) => {
+ const { t } = useTranslation('common')
+ const { pathname } = useLocation()
+ const { id } = useParams()
+ const project = useMemo(() => _find([...projects, ..._map(sharedProjects, (item) => item.project)], p => p.id === id) || {}, [projects, id, sharedProjects])
+ const isSettings = !_isEmpty(id) && (_replace(routes.project_settings, ':id', id) === pathname)
+ const history = useHistory()
+
+ const [form, setForm] = useState({
+ name: '',
+ id: id || nanoid(),
+ public: false,
+ })
+ const [validated, setValidated] = useState(false)
+ const [errors, setErrors] = useState({})
+ const [beenSubmitted, setBeenSubmitted] = useState(false)
+ const [showDelete, setShowDelete] = useState(false)
+ const [showReset, setShowReset] = useState(false)
+ const [projectDeleting, setProjectDeleting] = useState(false)
+ const [projectResetting, setProjectResetting] = useState(false)
+ const [projectSaving, setProjectSaving] = useState(false)
+
+ useEffect(() => {
+ if (!user.isActive && !isSelfhosted) {
+ showError(t('project.settings.verify'))
+ history.push(routes.dashboard)
+ }
+
+ if (!isLoading && isSettings && !projectDeleting) {
+ if (_isEmpty(project) || project?.uiHidden) {
+ showError(t('project.noExist'))
+ history.push(routes.dashboard)
+ } else {
+ setForm({
+ ...project,
+ ipBlacklist: _isString(project.ipBlacklist) ? project.ipBlacklist : _join(project.ipBlacklist, ', '),
+ origins: _isString(project.origins) ? project.origins : _join(project.origins, ', '),
+ })
+ }
+ }
+ }, [user, project, isLoading, isSettings, history, showError, projectDeleting, t])
+
+ const onSubmit = async (data) => {
+ if (!projectSaving) {
+ setProjectSaving(true)
+ try {
+ const formalisedData = {
+ ...data,
+ origins: _isEmpty(data.origins) ? null : _map(_split(data.origins, ','), (origin) => {
+ try {
+ if (_includes(origin, 'localhost')) {
+ return origin
+ }
+ return new URL(origin).host
+ } catch (e) {
+ return origin
+ }
+ }),
+ ipBlacklist: _isEmpty(data.ipBlacklist) ? null : _split(data.ipBlacklist, ','),
+ }
+ if (isSettings) {
+ await updateProject(id, formalisedData)
+ newProject(t('project.settings.updated'))
+ } else {
+ await createProject(formalisedData)
+ trackCustom('PROJECT_CREATED')
+ newProject(t('project.settings.created'))
+ }
+
+ loadProjects(isSharedProject)
+ history.push(routes.dashboard)
+ } catch (e) {
+ if (isSettings) {
+ updateProjectFailed(e)
+ } else {
+ createNewProjectFailed(e)
+ }
+ } finally {
+ setProjectSaving(false)
+ }
+ }
+ }
+
+ const onDelete = async () => {
+ setShowDelete(false)
+ if (!projectDeleting) {
+ setProjectDeleting(true)
+ try {
+ await deleteProject(id)
+ removeProject(id, isSharedProject)
+ projectDeleted(t('project.settings.deleted'))
+ history.push(routes.dashboard)
+ } catch (e) {
+ deleteProjectFailed(e)
+ } finally {
+ setProjectDeleting(false)
+ }
+ }
+ }
+
+ const onReset = async () => {
+ setShowReset(false)
+ if (!projectResetting) {
+ setProjectResetting(true)
+ try {
+ await resetProject(id)
+ deleteProjectCache(id)
+ projectDeleted(t('project.settings.resetted'))
+ history.push(routes.dashboard)
+ } catch (e) {
+ deleteProjectFailed(e)
+ } finally {
+ setProjectResetting(false)
+ }
+ }
+ }
+
+ const validate = () => {
+ const allErrors = {}
+
+ if (_isEmpty(form.name)) {
+ allErrors.name = t('project.settings.noNameError')
+ }
+
+ if (_size(form.name) > MAX_NAME_LENGTH) {
+ allErrors.name = t('project.settings.pxCharsError', { amount: MAX_NAME_LENGTH })
+ }
+
+ if (_size(form.origins) > MAX_ORIGINS_LENGTH) {
+ allErrors.origins = t('project.settings.oxCharsError', { amount: MAX_ORIGINS_LENGTH })
+ }
+
+ if (_size(form.ipBlacklist) > MAX_IPBLACKLIST_LENGTH) {
+ allErrors.ipBlacklist = t('project.settings.oxCharsError', { amount: MAX_IPBLACKLIST_LENGTH })
+ }
+
+ const valid = _isEmpty(_keys(allErrors))
+
+ setErrors(allErrors)
+ setValidated(valid)
+ }
+
+ useEffect(() => {
+ validate()
+ }, [form]) // eslint-disable-line
+
+ const handleInput = event => {
+ const { target } = event
+ const value = target.type === 'checkbox' ? target.checked : target.value
+
+ setForm(oldForm => ({
+ ...oldForm,
+ [target.name]: value,
+ }))
+ }
+
+ const handleSubmit = e => {
+ e.preventDefault()
+ e.stopPropagation()
+ setBeenSubmitted(true)
+
+ if (validated) {
+ onSubmit(form)
+ }
+ }
+
+ const onCancel = () => {
+ history.push(isSettings ? _replace(routes.project, ':id', id) : routes.dashboard)
+ }
+
+ const title = isSettings ? `${t('project.settings.settings')} ${form.name}` : t('project.settings.create')
+
+ return (
+ <Title title={title}>
+ <div
+ className={cx('min-h-min-footer bg-gray-50 dark:bg-gray-800 flex flex-col py-6 px-4 sm:px-6 lg:px-8', {
+ 'pb-40': isSettings,
+ })}
+ >
+ <form className='max-w-7xl w-full mx-auto' onSubmit={handleSubmit}>
+ <h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>
+ {title}
+ </h2>
+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.general')}
+ </h3>
+ <Input
+ name='name'
+ id='name'
+ type='text'
+ label={t('project.settings.name')}
+ value={form.name}
+ placeholder='My awesome project'
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.name : null}
+ />
+ <Input
+ name='id'
+ id='id'
+ type='text'
+ label={t('project.settings.pid')}
+ value={form.id}
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.id : null}
+ disabled
+ />
+ {isSettings ? (
+ <>
+ <Input
+ name='origins'
+ id='origins'
+ type='text'
+ label={t('project.settings.origins')}
+ hint={t('project.settings.originsHint')}
+ value={form.origins || ''}
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.origins : null}
+ />
+ <Input
+ name='ipBlacklist'
+ id='ipBlacklist'
+ type='text'
+ label={t('project.settings.ipBlacklist')}
+ hint={t('project.settings.ipBlacklistHint')}
+ value={form.ipBlacklist || ''}
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.ipBlacklist : null}
+ isBeta
+ />
+ <Checkbox
+ checked={Boolean(form.active)}
+ onChange={handleInput}
+ name='active'
+ id='active'
+ className='mt-4'
+ label={t('project.settings.enabled')}
+ hint={t('project.settings.enabledHint')}
+ />
+ <Checkbox
+ checked={Boolean(form.public)}
+ onChange={handleInput}
+ name='public'
+ id='public'
+ className='mt-4'
+ label={t('project.settings.public')}
+ hint={t('project.settings.publicHint')}
+ />
+ <div className='flex justify-between mt-8 h-20 sm:h-min'>
+ <div className='flex flex-wrap items-center'>
+ <Button className='mr-2 border-indigo-100 dark:text-gray-50 dark:border-gray-700 dark:bg-gray-700 dark:hover:bg-gray-600' onClick={onCancel} secondary regular>
+ {t('common.cancel')}
+ </Button>
+ <Button type='submit' loading={projectSaving} primary regular>
+ {t('common.save')}
+ </Button>
+ </div>
+ {!project.shared && (
+ <div className='flex flex-wrap items-center justify-end'>
+ <Button onClick={() => !projectResetting && setShowReset(true)} loading={projectDeleting} semiDanger semiSmall>
+ <TrashIcon className='w-5 h-5 mr-1' />
+ {t('project.settings.reset')}
+ </Button>
+ <Button className='ml-2' onClick={() => !projectDeleting && setShowDelete(true)} loading={projectDeleting} danger semiSmall>
+ <ExclamationTriangleIcon className='w-5 h-5 mr-1' />
+ {t('project.settings.delete')}
+ </Button>
+ </div>
+ )}
+ </div>
+ <hr className='mt-2 sm:mt-5 border-gray-200 dark:border-gray-600' />
+ </>
+ ) : (
+ <p className='text-gray-500 dark:text-gray-300 italic mt-1 mb-4 text-sm'>
+ {t('project.settings.createHint')}
+ </p>
+ )}
+
+ {!isSettings && (
+ <div>
+ <Button className='mr-2 border-indigo-100 dark:text-gray-50 dark:border-gray-700 dark:bg-gray-700 dark:hover:bg-gray-600' onClick={onCancel} secondary regular>
+ {t('common.cancel')}
+ </Button>
+ <Button type='submit' loading={projectSaving} primary regular>
+ {t('common.save')}
+ </Button>
+ </div>
+ )}
+ </form>
+ <Modal
+ onClose={() => setShowDelete(false)}
+ onSubmit={onDelete}
+ submitText={t('project.settings.delete')}
+ closeText={t('common.close')}
+ title={t('project.settings.qDelete')}
+ message={t('project.settings.deleteHint')}
+ submitType='danger'
+ type='error'
+ isOpened={showDelete}
+ />
+ <Modal
+ onClose={() => setShowReset(false)}
+ onSubmit={onReset}
+ submitText={t('project.settings.reset')}
+ closeText={t('common.close')}
+ title={t('project.settings.qReset')}
+ message={t('project.settings.resetHint')}
+ submitType='danger'
+ type='error'
+ isOpened={showReset}
+ />
+ </div>
+ </Title>
+ )
+}
+
+ProjectSettings.propTypes = {
+ updateProjectFailed: PropTypes.func.isRequired,
+ createNewProjectFailed: PropTypes.func.isRequired,
+ newProject: PropTypes.func.isRequired,
+ projectDeleted: PropTypes.func.isRequired,
+ deleteProjectFailed: PropTypes.func.isRequired,
+ loadProjects: PropTypes.func.isRequired,
+ projects: PropTypes.arrayOf(PropTypes.object).isRequired,
+ showError: PropTypes.func.isRequired,
+ isLoading: PropTypes.bool.isRequired,
+ user: PropTypes.object.isRequired,
+ isSharedProject: PropTypes.bool.isRequired,
+ deleteProjectCache: PropTypes.func.isRequired,
+}
+
+export default memo(withAuthentication(ProjectSettings, auth.authenticated))
diff --git a/src/pages/Captcha/Settings/index.jsx b/src/pages/Captcha/Settings/index.jsx
new file mode 100644
index 000000000..1ce8f6fd4
--- /dev/null
+++ b/src/pages/Captcha/Settings/index.jsx
@@ -0,0 +1,3 @@
+import ProjectSettings from './CaptchaSettings.container'
+
+export default ProjectSettings
diff --git a/src/pages/Captcha/View/Panels.jsx b/src/pages/Captcha/View/Panels.jsx
new file mode 100644
index 000000000..2ee44bec6
--- /dev/null
+++ b/src/pages/Captcha/View/Panels.jsx
@@ -0,0 +1,711 @@
+import React, {
+ memo, useState, useEffect, useMemo, Fragment,
+} from 'react'
+import { ArrowSmallUpIcon, ArrowSmallDownIcon } from '@heroicons/react/24/solid'
+import {
+ FunnelIcon, MapIcon, Bars4Icon, ArrowsPointingOutIcon, ChartPieIcon, PuzzlePieceIcon,
+} from '@heroicons/react/24/outline'
+import cx from 'clsx'
+import PropTypes from 'prop-types'
+import { pie } from 'billboard.js'
+import _keys from 'lodash/keys'
+import _values from 'lodash/values'
+import _map from 'lodash/map'
+import _isEmpty from 'lodash/isEmpty'
+import _isFunction from 'lodash/isFunction'
+import _reduce from 'lodash/reduce'
+import _round from 'lodash/round'
+import _find from 'lodash/find'
+import _includes from 'lodash/includes'
+import _floor from 'lodash/floor'
+import _size from 'lodash/size'
+import _slice from 'lodash/slice'
+import _sum from 'lodash/sum'
+
+import Progress from 'ui/Progress'
+import PulsatingCircle from 'ui/icons/PulsatingCircle'
+import Modal from 'ui/Modal'
+import Chart from 'ui/Chart'
+import LiveVisitorsDropdown from './components/LiveVisitorsDropdown'
+import InteractiveMap from './components/InteractiveMap'
+import { iconClassName } from './ViewCaptcha.helpers'
+
+const ENTRIES_PER_PANEL = 5
+
+const panelsWithBars = ['cc', 'ce', 'os', 'br', 'dv']
+
+// function that checks if there are custom tabs for a specific type
+const checkCustomTabs = (panelID, customTabs) => {
+ if (_isEmpty(customTabs)) return false
+
+ return Boolean(_find(customTabs, (el) => el.panelID === panelID))
+}
+
+const checkIfBarsNeeded = (panelID) => {
+ return _includes(panelsWithBars, panelID)
+}
+
+// noSwitch - 'previous' and 'next' buttons
+const PanelContainer = ({
+ name, children, noSwitch, icon, type, openModal, activeFragment, setActiveFragment, customTabs,
+}) => (
+ <div
+ className={cx('relative bg-white dark:bg-gray-750 pt-5 px-4 min-h-72 sm:pt-6 sm:px-6 shadow rounded-lg overflow-hidden', {
+ 'pb-12': !noSwitch,
+ 'pb-5': noSwitch,
+ })}
+ >
+ <div className='flex items-center justify-between mb-2'>
+ <h3 className='flex items-center text-lg leading-6 font-semibold text-gray-900 dark:text-gray-50'>
+ {icon && (
+ <>
+ {icon}
+ &nbsp;
+ </>
+ )}
+ {name}
+ </h3>
+ <div className='flex'>
+ {(checkIfBarsNeeded(type) || checkCustomTabs(type, customTabs)) && (
+ <Bars4Icon
+ className={cx(iconClassName, 'cursor-pointer', {
+ 'text-blue-500': activeFragment === 0,
+ 'text-gray-900 dark:text-gray-50': activeFragment === 1,
+ })}
+ onClick={() => setActiveFragment(0)}
+ />
+ )}
+
+ {/* if it is a Country tab */}
+ {type === 'cc' && (
+ <>
+ <MapIcon
+ className={cx(iconClassName, 'ml-2 cursor-pointer', {
+ 'text-blue-500': activeFragment === 1,
+ 'text-gray-900 dark:text-gray-50': activeFragment === 0,
+ })}
+ onClick={() => setActiveFragment(1)}
+ />
+ <ArrowsPointingOutIcon
+ className={cx(iconClassName, 'ml-2 cursor-pointer text-gray-900 dark:text-gray-50', {
+ hidden: activeFragment === 0,
+ })}
+ onClick={openModal}
+ />
+ </>
+ )}
+ {/* if this tab using Circle showing stats panel */}
+ {(type === 'ce' || type === 'os' || type === 'br' || type === 'dv') && (
+ <ChartPieIcon
+ className={cx(iconClassName, 'ml-2 cursor-pointer', {
+ 'text-blue-500': activeFragment === 1,
+ 'text-gray-900 dark:text-gray-50': activeFragment === 0,
+ })}
+ onClick={() => setActiveFragment(1)}
+ />
+ )}
+ {checkCustomTabs(type, customTabs) && (
+ <>
+ {_map(customTabs, ({ extensionID, panelID }) => (
+ <PuzzlePieceIcon
+ key={`${extensionID}-${panelID}`}
+ className={cx(iconClassName, 'ml-2 cursor-pointer', {
+ 'text-blue-500': activeFragment === extensionID,
+ 'text-gray-900 dark:text-gray-50': activeFragment === 0,
+ })}
+ onClick={() => setActiveFragment(extensionID)}
+ />
+ ))}
+ </>
+ )}
+ </div>
+ </div>
+ {/* for other tabs */}
+ <div className='flex flex-col h-full scroll-auto overflow-auto'>
+ {children}
+ </div>
+ </div>
+)
+
+PanelContainer.propTypes = {
+ name: PropTypes.string.isRequired,
+ children: PropTypes.node.isRequired,
+ noSwitch: PropTypes.bool,
+ activeFragment: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
+ setActiveFragment: PropTypes.func,
+ icon: PropTypes.node,
+}
+
+PanelContainer.defaultProps = {
+ icon: null,
+ noSwitch: false,
+ activeFragment: 0,
+ setActiveFragment: () => { },
+}
+
+// First tab with stats
+const Overview = ({
+ overall, chartData, activePeriod, t, live, sessionDurationAVG, projectId,
+}) => {
+ const pageviewsDidGrowUp = overall.percChange >= 0
+ const uniqueDidGrowUp = overall.percChangeUnique >= 0
+ const pageviews = _sum(chartData?.visits) || 0
+ const uniques = _sum(chartData?.uniques) || 0
+ let bounceRate = 0
+
+ if (pageviews > 0) {
+ bounceRate = _round((uniques * 100) / pageviews, 1)
+ }
+
+ return (
+ <PanelContainer name={t('project.overview')} noSwitch>
+ <div className='flex text-lg justify-between'>
+ <div className='flex items-center dark:text-gray-50'>
+ <PulsatingCircle className='mr-1.5' type='big' />
+ {t('dashboard.liveVisitors')}
+ :
+ </div>
+ <LiveVisitorsDropdown projectId={projectId} live={live} />
+ </div>
+ {!_isEmpty(chartData) && (
+ <>
+ <p className='text-lg font-semibold dark:text-gray-50'>
+ {t('project.statsFor')}
+ <span className='lowercase'>
+ &nbsp;
+ {activePeriod.label}
+ </span>
+ </p>
+
+ <div className='flex justify-between'>
+ <p className='text-lg dark:text-gray-50'>
+ {t('dashboard.pageviews')}
+ :
+ </p>
+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl'>
+ {pageviews}
+ </p>
+ </div>
+
+ <div className='flex justify-between'>
+ <p className='text-lg dark:text-gray-50'>
+ {t('dashboard.unique')}
+ :
+ </p>
+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl'>
+ {uniques}
+ </p>
+ </div>
+
+ <div className='flex justify-between'>
+ <p className='text-lg dark:text-gray-50'>
+ {t('dashboard.bounceRate')}
+ :
+ </p>
+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl'>
+ {bounceRate}
+ %
+ </p>
+ </div>
+ <div className='flex justify-between'>
+ <p className='text-lg dark:text-gray-50'>
+ {t('dashboard.sessionDuration')}
+ :
+ </p>
+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl'>
+ {sessionDurationAVG}
+ </p>
+ </div>
+ <hr className='my-2 border-gray-200 dark:border-gray-600' />
+ </>
+ )}
+ <p className='text-lg font-semibold dark:text-gray-50'>
+ {t('project.weeklyStats')}
+ </p>
+ <div className='flex justify-between'>
+ <p className='text-lg dark:text-gray-50'>
+ {t('dashboard.pageviews')}
+ :
+ </p>
+ <dd className='flex items-baseline'>
+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-lg'>
+ {overall.thisWeek}
+ </p>
+ <p
+ className={cx('flex text-sm -ml-1 items-baseline', {
+ 'text-green-600': pageviewsDidGrowUp,
+ 'text-red-600': !pageviewsDidGrowUp,
+ })}
+ >
+ {pageviewsDidGrowUp ? (
+ <>
+ <ArrowSmallUpIcon className='self-center flex-shrink-0 h-4 w-4 text-green-500' />
+ <span className='sr-only'>
+ {t('dashboard.inc')}
+ </span>
+ </>
+ ) : (
+ <>
+ <ArrowSmallDownIcon className='self-center flex-shrink-0 h-4 w-4 text-red-500' />
+ <span className='sr-only'>
+ {t('dashboard.dec')}
+ </span>
+ </>
+ )}
+ {overall.percChange}
+ %
+ </p>
+ </dd>
+ </div>
+ <div className='flex justify-between'>
+ <p className='text-lg dark:text-gray-50'>
+ {t('dashboard.unique')}
+ :
+ </p>
+ <dd className='flex items-baseline'>
+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-lg'>
+ {overall.thisWeekUnique}
+ </p>
+ <p
+ className={cx('flex text-sm -ml-1 items-baseline', {
+ 'text-green-600': uniqueDidGrowUp,
+ 'text-red-600': !uniqueDidGrowUp,
+ })}
+ >
+ {uniqueDidGrowUp ? (
+ <>
+ <ArrowSmallUpIcon className='self-center flex-shrink-0 h-4 w-4 text-green-500' />
+ <span className='sr-only'>
+ {t('dashboard.inc')}
+ </span>
+ </>
+ ) : (
+ <>
+ <ArrowSmallDownIcon className='self-center flex-shrink-0 h-4 w-4 text-red-500' />
+ <span className='sr-only'>
+ {t('dashboard.dec')}
+ </span>
+ </>
+ )}
+ {overall.percChangeUnique}
+ %
+ </p>
+ </dd>
+ </div>
+ </PanelContainer>
+ )
+}
+
+// Options for circle chart showing the stats of data
+const getPieOptions = (customs, uniques, t) => {
+ const tQuantity = t('project.quantity')
+ const tConversion = t('project.conversion')
+ const tRatio = t('project.ratio')
+ const quantity = _values(customs)
+ const conversion = _map(quantity, (el) => _round((el / uniques) * 100, 2))
+
+ return {
+ tooltip: {
+ contents: {
+ text: {
+ QUANTITY: _values(customs),
+ CONVERSION: conversion,
+ },
+ template: `
+ <ul class='bg-gray-100 dark:text-gray-50 dark:bg-gray-700 rounded-md shadow-md px-3 py-1'>
+ {{
+ <li class='flex'>
+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:{=COLOR}></div>
+ <span>{=NAME}</span>
+ </li>
+ <hr class='border-gray-200 dark:border-gray-600' />
+ <li class='flex justify-between'>
+ <span>${tQuantity}</span>
+ <span class='pl-4'>{=QUANTITY}</span>
+ </li>
+ <li class='flex justify-between'>
+ <span>${tConversion}</span>
+ <span class='pl-4'>{=CONVERSION}%</span>
+ </li>
+ <li class='flex justify-between'>
+ <span>${tRatio}</span>
+ <span class='pl-4'>{=VALUE}</span>
+ </li>
+ }}
+ </ul>`,
+ },
+ },
+ }
+}
+
+// Tabs with custom events like submit form, press button, go to the link rate etc.
+const CustomEvents = ({
+ customs, chartData, onFilter, t,
+}) => {
+ const keys = _keys(customs)
+ const uniques = _sum(chartData.uniques)
+ const [chartOptions, setChartOptions] = useState({})
+ const [activeFragment, setActiveFragment] = useState(0)
+
+ useEffect(() => {
+ if (!_isEmpty(chartData)) {
+ const options = getPieOptions(customs, uniques, t)
+ setChartOptions({
+ data: {
+ columns: _map(keys, (ev) => [ev, customs[ev]]),
+ type: pie(),
+ },
+ ...options,
+ })
+ }
+ }, [chartData, customs, t]) // eslint-disable-line react-hooks/exhaustive-deps
+
+ // for showing chart circle of stats a data
+ if (activeFragment === 1 && !_isEmpty(chartData)) {
+ return (
+ <PanelContainer
+ name={t('project.customEv')}
+ type='ce'
+ setActiveFragment={setActiveFragment}
+ activeFragment={activeFragment}
+ >
+ {_isEmpty(chartData) ? (
+ <p className='mt-1 text-base text-gray-700 dark:text-gray-300'>
+ {t('project.noParamData')}
+ </p>
+ ) : (
+ <Chart
+ options={chartOptions}
+ current='panels-ce'
+ />
+ )}
+ </PanelContainer>
+ )
+ }
+
+ return (
+ <PanelContainer name={t('project.customEv')} type='ce' setActiveFragment={setActiveFragment} activeFragment={activeFragment}>
+ <table className='table-fixed'>
+ <thead>
+ <tr className='text-gray-900 dark:text-gray-50'>
+ <th className='w-4/6 text-left'>{t('project.event')}</th>
+ <th className='w-1/6 text-right'>
+ {t('project.quantity')}
+ &nbsp;&nbsp;
+ </th>
+ <th className='w-1/6 text-right'>{t('project.conversion')}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {_map(keys, (ev) => (
+ <tr
+ key={ev}
+ className='text-gray-900 dark:text-gray-50 group hover:bg-gray-100 hover:dark:bg-gray-700 cursor-pointer'
+ onClick={() => onFilter('ev', ev)}
+ >
+ <td className='text-left flex items-center'>
+ {ev}
+ <FunnelIcon className='ml-2 w-4 h-4 text-gray-500 hidden group-hover:block dark:text-gray-300' />
+ </td>
+ <td className='text-right'>
+ {customs[ev]}
+ &nbsp;&nbsp;
+ </td>
+ <td className='text-right'>
+ {_round((customs[ev] / uniques) * 100, 2)}
+ %
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </PanelContainer>
+ )
+}
+
+CustomEvents.propTypes = {
+ customs: PropTypes.objectOf(PropTypes.number).isRequired,
+ onFilter: PropTypes.func.isRequired,
+ t: PropTypes.func.isRequired,
+ // eslint-disable-next-line react/forbid-prop-types
+ chartData: PropTypes.objectOf(PropTypes.any).isRequired,
+}
+
+const Panel = ({
+ name, data, rowMapper, valueMapper, capitalize, linkContent, t, icon, id, hideFilters, onFilter, customTabs,
+}) => {
+ const [page, setPage] = useState(0)
+ const currentIndex = page * ENTRIES_PER_PANEL
+ const keys = useMemo(() => _keys(data).sort((a, b) => data[b] - data[a]), [data])
+ const keysToDisplay = useMemo(() => _slice(keys, currentIndex, currentIndex + 5), [keys, currentIndex])
+ const total = useMemo(() => _reduce(keys, (prev, curr) => prev + data[curr], 0), [keys]) // eslint-disable-line
+ const [activeFragment, setActiveFragment] = useState(0)
+ const [modal, setModal] = useState(false)
+ const canGoPrev = () => page > 0
+ const canGoNext = () => page < _floor((_size(keys) - 1) / ENTRIES_PER_PANEL)
+
+ const _onFilter = hideFilters ? () => { } : onFilter
+
+ useEffect(() => {
+ const sizeKeys = _size(keys)
+
+ if (currentIndex > sizeKeys) {
+ setPage(_floor(sizeKeys / ENTRIES_PER_PANEL))
+ }
+ }, [currentIndex, keys])
+
+ useEffect(() => {
+ setPage(0)
+ }, [data])
+
+ const onPrevious = () => {
+ if (canGoPrev()) {
+ setPage(page - 1)
+ }
+ }
+
+ const onNext = () => {
+ if (canGoNext()) {
+ setPage(page + 1)
+ }
+ }
+ // Showing map of stats a data
+ if (id === 'cc' && activeFragment === 1 && !_isEmpty(data)) {
+ return (
+ <PanelContainer
+ name={name}
+ icon={icon}
+ type={id}
+ activeFragment={activeFragment}
+ setActiveFragment={setActiveFragment}
+ openModal={() => setModal(true)}
+ customTabs={customTabs}
+ >
+ <InteractiveMap
+ data={data}
+ total={total}
+ onClickCountry={(key) => _onFilter(id, key)}
+ />
+ <Modal
+ onClose={() => setModal(false)}
+ closeText={t('common.close')}
+ isOpened={modal}
+ message={(
+ <InteractiveMap
+ data={data}
+ total={total}
+ onClickCountry={(key) => _onFilter(id, key)}
+ />
+ )}
+ size='large'
+ />
+ </PanelContainer>
+ )
+ }
+ // Showing chart of stats a data (start if)
+ if ((id === 'os' || id === 'br' || id === 'dv') && activeFragment === 1 && !_isEmpty(data)) {
+ const tQuantity = t('project.quantity')
+ const tRatio = t('project.ratio')
+ const mappedData = _map(data, valueMapper)
+
+ const options = {
+ data: {
+ columns: _map(data, (e, index) => [index, e]),
+ type: pie(),
+ },
+ tooltip: {
+ contents: {
+ text: {
+ QUANTITY: _values(mappedData),
+ },
+ template: `
+ <ul class='bg-gray-100 dark:text-gray-50 dark:bg-gray-700 rounded-md shadow-md px-3 py-1'>
+ {{
+ <li class='flex'>
+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:{=COLOR}></div>
+ <span>{=NAME}</span>
+ </li>
+ <hr class='border-gray-200 dark:border-gray-600' />
+ <li class='flex justify-between'>
+ <span>${tQuantity}</span>
+ <span class='pl-4'>{=QUANTITY}</span>
+ </li>
+ <li class='flex justify-between'>
+ <span>${tRatio}</span>
+ <span class='pl-4'>{=VALUE}</span>
+ </li>
+ }}
+ </ul>`,
+ },
+ },
+ }
+
+ return (
+ <PanelContainer
+ name={name}
+ icon={icon}
+ type={id}
+ setActiveFragment={setActiveFragment}
+ activeFragment={activeFragment}
+ customTabs={customTabs}
+ >
+ {_isEmpty(data) ? (
+ <p className='mt-1 text-base text-gray-700 dark:text-gray-300'>
+ {t('project.noParamData')}
+ </p>
+ ) : (
+ <Chart
+ options={options}
+ current={`Panels-${id}`}
+ />
+ )}
+ </PanelContainer>
+ )
+ }
+ // Showing chart of stats a data (end if)
+
+ // Showing custom tabs (Extensions Marketplace)
+ // todo: check activeFragment for being equal to customTabs -> extensionID + panelID
+ if (!_isEmpty(customTabs) && typeof activeFragment === 'string' && !_isEmpty(data)) {
+ const content = _find(customTabs, (tab) => tab.extensionID === activeFragment).tabContent
+
+ return (
+ <PanelContainer
+ name={name}
+ icon={icon}
+ type={id}
+ activeFragment={activeFragment}
+ setActiveFragment={setActiveFragment}
+ openModal={() => setModal(true)}
+ customTabs={customTabs}
+ >
+ {/* eslint-disable-next-line react/no-danger */}
+ <div dangerouslySetInnerHTML={{ __html: content }} />
+ </PanelContainer>
+ )
+ }
+
+ return (
+ <PanelContainer name={name} icon={icon} type={id} activeFragment={activeFragment} setActiveFragment={setActiveFragment} customTabs={customTabs}>
+ {_isEmpty(data) ? (
+ <p className='mt-1 text-base text-gray-700 dark:text-gray-300'>
+ {t('project.noParamData')}
+ </p>
+ ) : _map(keysToDisplay, key => {
+ const perc = _round((data[key] / total) * 100, 2)
+ const rowData = _isFunction(rowMapper) ? rowMapper(key) : key
+ const valueData = _isFunction(valueMapper) ? valueMapper(data[key]) : data[key]
+
+ return (
+ <Fragment key={key}>
+ <div
+ className={cx('flex justify-between mt-[0.32rem] first:mt-0 dark:text-gray-50 rounded', {
+ 'group hover:bg-gray-100 hover:dark:bg-gray-700 cursor-pointer': !hideFilters,
+ })}
+ onClick={() => _onFilter(id, key)}
+ >
+ {linkContent ? (
+ <a
+ className={cx('flex items-center label hover:underline text-blue-600 dark:text-blue-500', { capitalize })}
+ href={rowData}
+ target='_blank'
+ rel='noopener noreferrer nofollow'
+ aria-label={`${rowData} (opens in a new tab)`}
+ >
+ {rowData}
+ {!hideFilters && (
+ <FunnelIcon className='ml-2 w-4 h-4 text-gray-500 hidden group-hover:block dark:text-gray-300' />
+ )}
+ </a>
+ ) : (
+ <span className={cx('flex items-center label', { capitalize })}>
+ {rowData}
+ {!hideFilters && (
+ <FunnelIcon className='ml-2 w-4 h-4 text-gray-500 hidden group-hover:block dark:text-gray-300' />
+ )}
+ </span>
+ )}
+ <span className='ml-3 dark:text-gray-50'>
+ {valueData}
+ &nbsp;
+ <span className='text-gray-500 dark:text-gray-200 font-light'>
+ (
+ {perc}
+ %)
+ </span>
+ </span>
+ </div>
+ <Progress now={perc} />
+ </Fragment>
+ )
+ })}
+ {/* for pagination in tabs */}
+ {_size(keys) > 5 && (
+ <div className='absolute bottom-0 w-card-toggle-sm sm:w-card-toggle'>
+ <div className='flex justify-between select-none mb-2'>
+ <span
+ className={cx('text-gray-500 dark:text-gray-200 font-light', {
+ hoverable: canGoPrev(),
+ disabled: !canGoPrev(),
+ })}
+ role='button'
+ onClick={onPrevious}
+ tabIndex={0}
+ >
+ &lt;
+ &nbsp;
+ {t('project.prev')}
+ </span>
+ <span
+ className={cx('text-gray-500 dark:text-gray-200 font-light', {
+ hoverable: canGoNext(),
+ disabled: !canGoNext(),
+ })}
+ role='button'
+ onClick={onNext}
+ tabIndex={0}
+ >
+ {t('project.next')}
+ &nbsp;
+ &gt;
+ </span>
+ </div>
+ </div>
+ )}
+ </PanelContainer>
+ )
+}
+
+Panel.propTypes = {
+ name: PropTypes.string.isRequired,
+ data: PropTypes.objectOf(PropTypes.number).isRequired,
+ id: PropTypes.string,
+ rowMapper: PropTypes.func,
+ valueMapper: PropTypes.func,
+ onFilter: PropTypes.func,
+ capitalize: PropTypes.bool,
+ linkContent: PropTypes.bool,
+ hideFilters: PropTypes.bool,
+ icon: PropTypes.node,
+}
+
+Panel.defaultProps = {
+ id: null,
+ rowMapper: null,
+ valueMapper: null,
+ capitalize: false,
+ linkContent: false,
+ onFilter: () => { },
+ hideFilters: false,
+ icon: null,
+}
+
+const PanelMemo = memo(Panel)
+const OverviewMemo = memo(Overview)
+const CustomEventsMemo = memo(CustomEvents)
+
+export {
+ PanelMemo as Panel,
+ OverviewMemo as Overview,
+ CustomEventsMemo as CustomEvents,
+}
diff --git a/src/pages/Captcha/View/ViewCaptcha.container.jsx b/src/pages/Captcha/View/ViewCaptcha.container.jsx
new file mode 100644
index 000000000..9e7dc6c29
--- /dev/null
+++ b/src/pages/Captcha/View/ViewCaptcha.container.jsx
@@ -0,0 +1,76 @@
+import { connect } from 'react-redux'
+import { errorsActions } from 'redux/actions/errors'
+import UIActions from 'redux/actions/ui'
+import { tabForSharedProject } from 'redux/constants'
+import { alertsActions } from 'redux/actions/alerts'
+
+import ViewProject from './ViewCaptcha'
+
+const mapStateToProps = (state) => {
+ if (state.ui.projects.dashboardTabs === tabForSharedProject) {
+ return {
+ projects: state.ui.projects.projects,
+ sharedProjects: state.ui.projects.sharedProjects,
+ isLoading: state.ui.projects.isLoadingShared,
+ cache: state.ui.cache.analytics,
+ cachePerf: state.ui.cache.analyticsPerf,
+ projectViewPrefs: state.ui.cache.projectViewPrefs,
+ authenticated: state.auth.authenticated,
+ timezone: state.auth.user.timezone,
+ isPaidTierUsed: state.auth.isPaidTierUsed,
+ extensions: state.ui.misc.extensions,
+ user: state.auth.user,
+ projectTab: state.ui.projects.projectTab,
+ }
+ }
+
+ return {
+ projects: state.ui.projects.projects,
+ sharedProjects: state.ui.projects.sharedProjects,
+ isLoading: state.ui.projects.isLoading,
+ cache: state.ui.cache.analytics,
+ cachePerf: state.ui.cache.analyticsPerf,
+ projectViewPrefs: state.ui.cache.projectViewPrefs,
+ authenticated: state.auth.authenticated,
+ timezone: state.auth.user.timezone,
+ isPaidTierUsed: state.auth.isPaidTierUsed,
+ extensions: state.ui.misc.extensions,
+ user: state.auth.user,
+ projectTab: state.ui.projects.projectTab,
+ }
+}
+
+const mapDispatchToProps = (dispatch) => ({
+ showError: (message) => {
+ dispatch(errorsActions.genericError(message))
+ },
+ setProjectCache: (pid, data, key) => {
+ dispatch(UIActions.setProjectCache(pid, data, key))
+ },
+ setProjectViewPrefs: (pid, period, timeBucket, rangeDate) => {
+ dispatch(UIActions.setProjectViewPrefs(pid, period, timeBucket, rangeDate))
+ },
+ setProjectCachePerf: (pid, data, key) => {
+ dispatch(UIActions.setProjectCachePerf(pid, data, key))
+ },
+ setPublicProject: (project) => {
+ dispatch(UIActions.setPublicProject(project))
+ },
+ setProjects: (project, shared) => {
+ dispatch(UIActions.setProjects(project, shared))
+ },
+ setLiveStatsForProject: (id, count) => {
+ dispatch(UIActions.setLiveStatsForProject(id, count))
+ },
+ generateAlert: (message, type) => {
+ dispatch(alertsActions.generateAlerts(message, type))
+ },
+ setProjectTab: (tabs) => {
+ dispatch(UIActions.setProjectTab(tabs))
+ },
+ setProjectForcastCache: (pid, data, key) => {
+ dispatch(UIActions.setProjectForcastCache(pid, data, key))
+ },
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(ViewProject)
diff --git a/src/pages/Captcha/View/ViewCaptcha.helpers.jsx b/src/pages/Captcha/View/ViewCaptcha.helpers.jsx
new file mode 100644
index 000000000..289c76708
--- /dev/null
+++ b/src/pages/Captcha/View/ViewCaptcha.helpers.jsx
@@ -0,0 +1,579 @@
+import { saveAs } from 'file-saver'
+import {
+ GlobeEuropeAfricaIcon, LanguageIcon, DocumentTextIcon, DeviceTabletIcon,
+ ArrowRightCircleIcon, MagnifyingGlassIcon, ServerIcon,
+} from '@heroicons/react/24/outline'
+import * as d3 from 'd3'
+import dayjs from 'dayjs'
+import {
+ area, areaSpline, spline, bar,
+} from 'billboard.js'
+import _forEach from 'lodash/forEach'
+import _map from 'lodash/map'
+import _split from 'lodash/split'
+import _replace from 'lodash/replace'
+import _isEmpty from 'lodash/isEmpty'
+import _keys from 'lodash/keys'
+import _size from 'lodash/size'
+import _round from 'lodash/round'
+import _fill from 'lodash/fill'
+import _reduce from 'lodash/reduce'
+import _last from 'lodash/last'
+import JSZip from 'jszip'
+
+import {
+ TimeFormat, chartTypes, tbsFormatMapper, tbsFormatMapper24h,
+} from 'redux/constants'
+import { getTimeFromSeconds, getStringFromTime, sumArrays } from 'utils/generic'
+import countries from 'utils/isoCountries'
+
+const getAvg = (arr) => {
+ const total = _reduce(arr, (acc, c) => acc + c, 0)
+ return total / _size(arr)
+}
+
+const getSum = (arr) => {
+ return _reduce(arr, (acc, c) => acc + c, 0)
+}
+
+const transformAIChartData = (data) => {
+ const transformedData = {
+ x: [],
+ sdur: [],
+ uniques: [],
+ visits: [],
+ }
+
+ _forEach(data, (d) => {
+ if (d.x) {
+ transformedData.x = d.x
+ }
+ if (d.sdur) {
+ transformedData.sdur = d.sdur
+ }
+ if (d.uniques) {
+ transformedData.uniques = d.uniques
+ }
+ if (d.visits) {
+ transformedData.visits = d.visits
+ }
+ })
+
+ return transformedData
+}
+
+const trendline = (data) => {
+ const xData = _map(_fill(new Array(_size(data)), 0), (_, i) => i + 1)
+ const yData = data
+
+ const xMean = getAvg(xData)
+ const yMean = getAvg(yData)
+
+ const xMinusxMean = _map(xData, (val) => val - xMean)
+ const yMinusyMean = _map(yData, (val) => val - yMean)
+
+ const xMinusxMeanSq = _map(xMinusxMean, (val) => val ** 2)
+
+ const xy = []
+ for (let x = 0; x < _size(data); ++x) {
+ xy.push(xMinusxMean[x] * yMinusyMean[x])
+ }
+
+ const xySum = getSum(xy)
+
+ const b1 = xySum / getSum(xMinusxMeanSq)
+
+ const b0 = yMean - b1 * xMean
+
+ const trendData = []
+ for (let x = 0; x < _size(data); ++x) {
+ const y = _round(b0 + b1 * x, 2)
+ if (y < 0) {
+ trendData.push(0)
+ } else {
+ trendData.push(y)
+ }
+ }
+
+ return trendData
+}
+
+const getExportFilename = (prefix) => {
+ // turn something like 2022-03-02T19:31:00.100Z into 2022-03-02
+ const date = _split(_replace(_split(new Date().toISOString(), '.')[0], /:/g, '-'), 'T')[0]
+ return `${prefix}-${date}.zip`
+}
+
+const convertToCSV = (array) => {
+ let str = 'name,value,perc\r\n'
+
+ for (let i = 0; i < _size(array); ++i) {
+ let line = ''
+
+ _forEach(array[i], (index) => {
+ if (line !== '') line += ','
+ line += index
+ })
+
+ str += `${line}\r\n`
+ }
+
+ return str
+}
+
+const onCSVExportClick = (data, pid, tnMapping, language) => {
+ const { data: rowData, types } = data
+ const zip = new JSZip()
+
+ _forEach(types, (item) => {
+ if (_isEmpty(rowData[item])) {
+ return
+ }
+
+ const rowKeys = _keys(rowData[item])
+ let total = 0
+
+ _forEach(rowKeys, (e) => {
+ total += rowData[item][e]
+ })
+
+ const csvData = _map(rowKeys, (e) => {
+ const perc = _round(((rowData[item][e] / total) * 100) || 0, 2)
+
+ if (item === 'cc') {
+ const name = countries.getName(e, language)
+ return [name, rowData[item][e], `${perc}%`]
+ }
+
+ return [e, rowData[item][e], `${perc}%`]
+ })
+
+ zip.file(`${tnMapping[item]}.csv`, convertToCSV(csvData))
+ })
+
+ zip.generateAsync({ type: 'blob' }).then((content) => {
+ saveAs(content, getExportFilename(`swetrix-${pid}`))
+ })
+}
+
+const CHART_METRICS_MAPPING = {
+ unique: 'unique',
+ views: 'views',
+ bounce: 'bounce',
+ viewsPerUnique: 'viewsPerUnique',
+ trendlines: 'trendlines',
+ sessionDuration: 'sessionDuration',
+}
+
+const CHART_METRICS_MAPPING_PERF = {
+ full: 'full',
+ timing: 'timing',
+ network: 'network',
+ frontend: 'frontend',
+ backend: 'backend',
+}
+
+// function to filter the data for the chart
+const getColumns = (chart, activeChartMetrics) => {
+ const {
+ views, bounce, viewsPerUnique, unique, trendlines, sessionDuration,
+ } = activeChartMetrics
+
+ const columns = [
+ ['x', ..._map(chart.x, el => dayjs(el).toDate())],
+ ]
+
+ if (unique) {
+ columns.push(['unique', ...chart.uniques])
+ if (trendlines) {
+ columns.push(['trendlineUnique', ...trendline(chart.uniques)])
+ }
+ }
+
+ if (views) {
+ columns.push(['total', ...chart.visits])
+ if (trendlines) {
+ columns.push(['trendlineTotal', ...trendline(chart.visits)])
+ }
+ }
+
+ if (bounce) {
+ const bounceArray = _map(chart.uniques, (el, i) => {
+ return _round((el * 100) / chart.visits[i], 1) || 0
+ })
+ columns.push(
+ ['bounce', ...bounceArray],
+ )
+ }
+
+ if (viewsPerUnique) {
+ const viewsPerUniqueArray = _map(chart.visits, (el, i) => {
+ if (chart.uniques[i] === 0 || chart.uniques[i] === undefined) {
+ return 0
+ }
+ return _round(el / chart.uniques[i], 1)
+ })
+ columns.push(['viewsPerUnique', ...viewsPerUniqueArray])
+ }
+
+ if (sessionDuration) {
+ columns.push(['sessionDuration', ...chart.sdur])
+ }
+
+ return columns
+}
+
+const getColumnsPerf = (chart, activeChartMetrics) => {
+ const columns = [
+ ['x', ..._map(chart.x, el => dayjs(el).toDate())],
+ ]
+
+ if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.full) {
+ columns.push(['dns', ...chart.dns])
+ columns.push(['tls', ...chart.tls])
+ columns.push(['conn', ...chart.conn])
+ columns.push(['response', ...chart.response])
+ columns.push(['render', ...chart.render])
+ columns.push(['dom_load', ...chart.domLoad])
+ columns.push(['ttfb', ...chart.ttfb])
+ }
+
+ if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.timing) {
+ columns.push(['frontend', ...sumArrays(chart.render, chart.domLoad)])
+ columns.push(['network', ...sumArrays(chart.dns, chart.tls, chart.conn, chart.response)])
+ columns.push(['backend', ...chart.ttfb])
+ }
+
+ if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.network) {
+ columns.push(['dns', ...chart.dns])
+ columns.push(['tls', ...chart.tls])
+ columns.push(['conn', ...chart.conn])
+ columns.push(['response', ...chart.response])
+ }
+
+ if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.frontend) {
+ columns.push(['render', ...chart.render])
+ columns.push(['dom_load', ...chart.domLoad])
+ }
+
+ if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.backend) {
+ columns.push(['ttfb', ...chart.ttfb])
+ }
+
+ return columns
+}
+
+// setting the default values for the time period dropdown
+const noRegionPeriods = ['custom', 'yesterday']
+
+// function to get the settings and data for the chart(main diagram)
+const getSettings = (chart, timeBucket, activeChartMetrics, applyRegions, timeFormat, forecasedChartData, rotateXAxias, chartType) => {
+ const xAxisSize = _size(chart.x)
+ const lines = []
+ const modifiedChart = { ...chart }
+ let regions
+
+ if (!_isEmpty(forecasedChartData)) {
+ lines.push({
+ value: _last(chart?.x),
+ text: 'Forecast',
+ })
+ modifiedChart.x = [...modifiedChart.x, ...forecasedChartData.x]
+ modifiedChart.uniques = [...modifiedChart.uniques, ...forecasedChartData.uniques]
+ modifiedChart.visits = [...modifiedChart.visits, ...forecasedChartData.visits]
+ modifiedChart.sdur = [...modifiedChart.sdur, ...forecasedChartData.sdur]
+ }
+
+ if (applyRegions) {
+ let regionStart
+
+ if (xAxisSize > 1) {
+ regionStart = dayjs(chart.x[xAxisSize - 2]).toDate()
+ } else {
+ regionStart = dayjs(chart.x[xAxisSize - 1]).toDate()
+ }
+
+ regions = {
+ unique: [
+ {
+ start: regionStart,
+ style: {
+ dasharray: '6 2',
+ },
+ },
+ ],
+ total: [
+ {
+ start: regionStart,
+ style: {
+ dasharray: '6 2',
+ },
+ },
+ ],
+ bounce: [
+ {
+ start: regionStart,
+ style: {
+ dasharray: '6 2',
+ },
+ },
+ ],
+ viewsPerUnique: [
+ {
+ start: regionStart,
+ style: {
+ dasharray: '6 2',
+ },
+ },
+ ],
+ }
+ }
+
+ return {
+ data: {
+ x: 'x',
+ columns: getColumns(modifiedChart, activeChartMetrics),
+ types: {
+ unique: chartType === chartTypes.line ? area() : bar(),
+ total: chartType === chartTypes.line ? area() : bar(),
+ bounce: chartType === chartTypes.line ? spline() : bar(),
+ viewsPerUnique: chartType === chartTypes.line ? spline() : bar(),
+ trendlineUnique: spline(),
+ trendlineTotal: spline(),
+ sessionDuration: chartType === chartTypes.line ? spline() : bar(),
+ },
+ colors: {
+ unique: '#2563EB',
+ total: '#D97706',
+ bounce: '#2AC4B3',
+ viewsPerUnique: '#F87171',
+ trendlineUnique: '#436abf',
+ trendlineTotal: '#eba14b',
+ sessionDuration: '#c945ed',
+ },
+ regions,
+ axes: {
+ bounce: 'y2',
+ sessionDuration: 'y2',
+ },
+ },
+ grid: {
+ x: {
+ lines,
+ },
+ },
+ axis: {
+ x: {
+ clipPath: false,
+ tick: {
+ fit: true,
+ rotate: rotateXAxias ? 45 : 0,
+ format: timeFormat === TimeFormat['24-hour'] ? (x) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x) : null,
+ },
+ localtime: timeFormat === TimeFormat['24-hour'],
+ type: 'timeseries',
+ },
+ y2: {
+ show: activeChartMetrics.bounce || activeChartMetrics.sessionDuration,
+ tick: {
+ format: activeChartMetrics.bounce ? (d) => `${d}%` : (d) => getStringFromTime(getTimeFromSeconds(d)),
+ },
+ min: activeChartMetrics.bounce ? 10 : null,
+ max: activeChartMetrics.bounce ? 100 : null,
+ default: activeChartMetrics.bounce ? [10, 100] : null,
+ },
+ },
+ tooltip: {
+ format: {
+ title: (x) => d3.timeFormat(tbsFormatMapper[timeBucket])(x),
+ },
+ contents: {
+ template: `
+ <ul class='bg-gray-100 dark:text-gray-50 dark:bg-gray-700 rounded-md shadow-md px-3 py-1'>
+ <li class='font-semibold'>{=TITLE}</li>
+ <hr class='border-gray-200 dark:border-gray-600' />
+ {{
+ <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}></div>
+ <span>{=NAME}</span>
+ </div>
+ <span class='pl-4'>{=VALUE}</span>
+ </li>
+ }}
+ </ul>`,
+ },
+ },
+ point: {
+ focus: {
+ only: xAxisSize > 1,
+ },
+ pattern: [
+ 'circle',
+ ],
+ r: 3,
+ },
+ legend: {
+ usePoint: true,
+ item: {
+ tile: {
+ width: 10,
+ },
+ },
+ },
+ area: {
+ linearGradient: true,
+ },
+ padding: {
+ right: (rotateXAxias && !(activeChartMetrics.bounce || activeChartMetrics.sessionDuration)) && 35,
+ left: 40,
+ },
+ bindto: '#dataChart',
+ }
+}
+
+const getSettingsPerf = (chart, timeBucket, activeChartMetrics, rotateXAxias, chartType) => {
+ const xAxisSize = _size(chart.x)
+
+ return {
+ data: {
+ x: 'x',
+ xFormat: tbsFormatMapper[timeBucket],
+ columns: getColumnsPerf(chart, activeChartMetrics),
+ types: {
+ dns: chartType === chartTypes.line ? areaSpline() : bar(),
+ tls: chartType === chartTypes.line ? areaSpline() : bar(),
+ conn: chartType === chartTypes.line ? areaSpline() : bar(),
+ response: chartType === chartTypes.line ? areaSpline() : bar(),
+ render: chartType === chartTypes.line ? areaSpline() : bar(),
+ dom_load: chartType === chartTypes.line ? areaSpline() : bar(),
+ ttfb: chartType === chartTypes.line ? areaSpline() : bar(),
+ frontend: chartType === chartTypes.line ? areaSpline() : bar(),
+ network: chartType === chartTypes.line ? areaSpline() : bar(),
+ backend: chartType === chartTypes.line ? areaSpline() : bar(),
+ },
+ colors: {
+ dns: '#EC4319',
+ tls: '#F27059',
+ conn: '#F7A265',
+ response: '#F5D376',
+ render: '#709775',
+ dom_load: '#A5E6AB',
+ ttfb: '#00A8E8',
+ frontend: '#709775',
+ network: '#F7A265',
+ backend: '#00A8E8',
+ },
+ groups: [
+ ['dns', 'tls', 'conn', 'response', 'render', 'dom_load', 'ttfb', 'frontend', 'network', 'backend'],
+ ],
+ },
+ axis: {
+ x: {
+ type: 'timeseries',
+ tick: {
+ format: tbsFormatMapper[timeBucket],
+ rotate: rotateXAxias ? 45 : 0,
+ },
+ },
+ y: {
+ tick: {
+ format: (d) => getStringFromTime(getTimeFromSeconds(d), true),
+ },
+ },
+ },
+ tooltip: {
+ format: {
+ title: (x) => d3.timeFormat(tbsFormatMapper[timeBucket])(x),
+ },
+ contents: {
+ template: `
+ <ul class='bg-gray-100 dark:text-gray-50 dark:bg-gray-700 rounded-md shadow-md px-3 py-1'>
+ <li class='font-semibold'>{=TITLE}</li>
+ <hr class='border-gray-200 dark:border-gray-600' />
+ {{
+ <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}></div>
+ <span>{=NAME}</span>
+ </div>
+ <span class='pl-4'>{=VALUE}</span>
+ </li>
+ }}
+ </ul>`,
+ },
+ },
+ point: {
+ focus: {
+ only: xAxisSize > 1,
+ },
+ pattern: [
+ 'circle',
+ ],
+ r: 3,
+ },
+ legend: {
+ usePoint: true,
+ item: {
+ tile: {
+ width: 10,
+ },
+ },
+ },
+ area: {
+ linearGradient: true,
+ },
+ padding: {
+ right: rotateXAxias && 35,
+ },
+ bindto: '#dataChart',
+ }
+}
+
+const validTimeBacket = ['hour', 'day', 'week', 'month']
+const validPeriods = ['custom', 'today', 'yesterday', '1d', '7d', '4w', '3M', '12M', '24M']
+const paidPeriods = ['12M', '24M']
+const validFilters = ['cc', 'pg', 'lc', 'ref', 'dv', 'br', 'os', 'so', 'me', 'ca', 'lt', 'ev']
+
+const typeNameMapping = (t) => ({
+ cc: t('project.mapping.cc'),
+ pg: t('project.mapping.pg'),
+ lc: t('project.mapping.lc'),
+ ref: t('project.mapping.ref'),
+ dv: t('project.mapping.dv'),
+ br: t('project.mapping.br'),
+ os: t('project.mapping.os'),
+ so: 'utm_source',
+ me: 'utm_medium',
+ ca: 'utm_campaign',
+ lt: t('project.mapping.lt'),
+ ev: t('project.event'),
+})
+
+const iconClassName = 'w-6 h-6'
+const panelIconMapping = {
+ cc: <GlobeEuropeAfricaIcon className={iconClassName} />,
+ pg: <DocumentTextIcon className={iconClassName} />,
+ lc: <LanguageIcon className={iconClassName} />,
+ ref: <ArrowRightCircleIcon className={iconClassName} />,
+ dv: <DeviceTabletIcon className={iconClassName} />,
+ br: <MagnifyingGlassIcon className={iconClassName} />,
+ os: <ServerIcon className={iconClassName} />,
+}
+
+// This function return date using the same format as the backend
+const getFormatDate = (date) => {
+ const yyyy = date.getFullYear()
+ let mm = date.getMonth() + 1
+ let dd = date.getDate()
+ if (dd < 10) dd = `0${dd}`
+ if (mm < 10) mm = `0${mm}`
+ return `${yyyy}-${mm}-${dd}`
+}
+
+export {
+ iconClassName, getFormatDate, panelIconMapping, typeNameMapping, validFilters,
+ validPeriods, validTimeBacket, paidPeriods, noRegionPeriods, getSettings,
+ getExportFilename, getColumns, onCSVExportClick, CHART_METRICS_MAPPING,
+ CHART_METRICS_MAPPING_PERF, getColumnsPerf, getSettingsPerf, transformAIChartData,
+}
diff --git a/src/pages/Captcha/View/ViewCaptcha.jsx b/src/pages/Captcha/View/ViewCaptcha.jsx
new file mode 100644
index 000000000..ac9e47db2
--- /dev/null
+++ b/src/pages/Captcha/View/ViewCaptcha.jsx
@@ -0,0 +1,1822 @@
+/* eslint-disable react/forbid-prop-types, react/no-unstable-nested-components, react/display-name */
+import React, {
+ useState, useEffect, useMemo, memo, useRef, Fragment, useCallback,
+} from 'react'
+import useSize from 'hooks/useSize'
+import { useHistory, useParams, Link } from 'react-router-dom'
+import domToImage from 'dom-to-image'
+import { saveAs } from 'file-saver'
+import bb from 'billboard.js'
+import {
+ ArrowDownTrayIcon, Cog8ToothIcon, ArrowPathIcon, CurrencyDollarIcon, ChartBarIcon, BoltIcon, BellIcon, PresentationChartBarIcon, PresentationChartLineIcon,
+} from '@heroicons/react/24/outline'
+import cx from 'clsx'
+import dayjs from 'dayjs'
+import { useTranslation } from 'react-i18next'
+import _keys from 'lodash/keys'
+import _map from 'lodash/map'
+import _includes from 'lodash/includes'
+import _last from 'lodash/last'
+import _isEmpty from 'lodash/isEmpty'
+import _replace from 'lodash/replace'
+import _values from 'lodash/values'
+import _find from 'lodash/find'
+import _filter from 'lodash/filter'
+import _startsWith from 'lodash/startsWith'
+import _debounce from 'lodash/debounce'
+import _some from 'lodash/some'
+import PropTypes from 'prop-types'
+import * as SwetrixSDK from '@swetrix/sdk'
+
+import { SWETRIX_PID } from 'utils/analytics'
+import { getTimeFromSeconds, getStringFromTime } from 'utils/generic'
+import { getItem, setItem } from 'utils/localstorage'
+import Title from 'components/Title'
+import EventsRunningOutBanner from 'components/EventsRunningOutBanner'
+import {
+ tbPeriodPairs, getProjectCacheKey, LIVE_VISITORS_UPDATE_INTERVAL, DEFAULT_TIMEZONE, CDN_URL, isDevelopment,
+ timeBucketToDays, getProjectCacheCustomKey, roleViewer, MAX_MONTHS_IN_PAST, MAX_MONTHS_IN_PAST_FREE, PROJECT_TABS, TimeFormat, getProjectForcastCacheKey, chartTypes,
+} from 'redux/constants'
+import Button from 'ui/Button'
+import Loader from 'ui/Loader'
+import Dropdown from 'ui/Dropdown'
+import Checkbox from 'ui/Checkbox'
+import Select from 'ui/Select'
+import FlatPicker from 'ui/Flatpicker'
+import Robot from 'ui/icons/Robot'
+import PaidFeature from 'modals/PaidFeature'
+import Forecast from 'modals/Forecast'
+import routes from 'routes'
+import {
+ getProjectData, getProject, getOverallStats, getLiveVisitors, getPerfData,
+} from 'api'
+import { getChartPrediction } from 'api/ai'
+import {
+ Panel, Overview, CustomEvents,
+} from './Panels'
+import {
+ onCSVExportClick, getFormatDate, panelIconMapping, typeNameMapping, validFilters, validPeriods,
+ validTimeBacket, paidPeriods, noRegionPeriods, getSettings, getColumns, CHART_METRICS_MAPPING,
+ CHART_METRICS_MAPPING_PERF, getSettingsPerf, transformAIChartData,
+} from './ViewCaptcha.helpers'
+import CCRow from './components/CCRow'
+import RefRow from './components/RefRow'
+import NoEvents from './components/NoEvents'
+import Filters from './components/Filters'
+import ProjectAlertsView from '../Alerts/View'
+import './styles.css'
+
+const PROJECT_TABS_VALUES = _values(PROJECT_TABS)
+
+const ViewProject = ({
+ projects, isLoading: _isLoading, showError, cache, cachePerf, setProjectCache, projectViewPrefs, setProjectViewPrefs, setPublicProject,
+ setLiveStatsForProject, authenticated, timezone, user, sharedProjects, isPaidTierUsed, extensions, generateAlert, setProjectCachePerf,
+ projectTab, setProjectTab, setProjects, setProjectForcastCache,
+}) => {
+ const { t, i18n: { language } } = useTranslation('common')
+ const [periodPairs, setPeriodPairs] = useState(tbPeriodPairs(t))
+ const [customExportTypes, setCustomExportTypes] = useState([])
+ const [customPanelTabs, setCustomPanelTabs] = useState([])
+ const [sdkInstance, setSdkInstance] = useState(null)
+ const dashboardRef = useRef(null)
+ const { id } = useParams()
+ const history = useHistory()
+ const project = useMemo(() => _find([...projects, ..._map(sharedProjects, (item) => item.project)], p => p.id === id) || {}, [projects, id, sharedProjects])
+ const isSharedProject = useMemo(() => {
+ const foundProject = _find([..._map(sharedProjects, (item) => item.project)], p => p.id === id)
+ return !_isEmpty(foundProject)
+ }, [id, sharedProjects])
+ const [areFiltersParsed, setAreFiltersParsed] = useState(false)
+ const [areFiltersPerfParsed, setAreFiltersPerfParsed] = useState(false)
+ const [areTimeBucketParsed, setAreTimeBucketParsed] = useState(false)
+ const [arePeriodParsed, setArePeriodParsed] = useState(false)
+ const [panelsData, setPanelsData] = useState({})
+ const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)
+ const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)
+ const [isForecastOpened, setIsForecastOpened] = useState(false)
+ const [analyticsLoading, setAnalyticsLoading] = useState(true)
+ const [period, setPeriod] = useState(projectViewPrefs[id]?.period || periodPairs[3].period)
+ const [timeBucket, setTimebucket] = useState(projectViewPrefs[id]?.timeBucket || periodPairs[3].tbs[1])
+ const activePeriod = useMemo(() => _find(periodPairs, p => p.period === period), [period, periodPairs])
+ const [chartData, setChartData] = useState({})
+ const [mainChart, setMainChart] = useState(null)
+ const [dataLoading, setDataLoading] = useState(false)
+ const [activeChartMetrics, setActiveChartMetrics] = useState({
+ [CHART_METRICS_MAPPING.unique]: true,
+ [CHART_METRICS_MAPPING.views]: false,
+ [CHART_METRICS_MAPPING.sessionDuration]: false,
+ [CHART_METRICS_MAPPING.bounce]: false,
+ [CHART_METRICS_MAPPING.viewsPerUnique]: false,
+ [CHART_METRICS_MAPPING.trendlines]: false,
+ })
+ const [activeChartMetricsPerf, setActiveChartMetricsPerf] = useState(CHART_METRICS_MAPPING_PERF.timing)
+ const [sessionDurationAVG, setSessionDurationAVG] = useState(null)
+ const checkIfAllMetricsAreDisabled = useMemo(() => !_some(activeChartMetrics, (value) => value), [activeChartMetrics])
+ const [filters, setFilters] = useState([])
+ const [filtersPerf, setFiltersPerf] = useState([])
+ // That is needed when using 'Export as image' feature,
+ // Because headless browser cannot do a request to the DDG API due to absense of The Same Origin Policy header
+ const [showIcons, setShowIcons] = useState(true)
+ const isLoading = authenticated ? _isLoading : false
+ const tnMapping = typeNameMapping(t)
+ const refCalendar = useRef(null)
+ const localStorageDateRange = projectViewPrefs[id]?.rangeDate
+ const [dateRange, setDateRange] = useState(localStorageDateRange ? [new Date(localStorageDateRange[0]), new Date(localStorageDateRange[1])] : null)
+ const [activeTab, setActiveTab] = useState(() => {
+ const url = new URL(window.location)
+ const { searchParams } = url
+ const tab = searchParams.get('tab')
+
+ if (_includes(PROJECT_TABS_VALUES, tab)) {
+ return tab
+ }
+
+ return projectTab || PROJECT_TABS.traffic
+ })
+
+ // TODO: THIS SHOULD BE MOVED TO REDUCERS WITH CACHE FUNCTIONALITY
+ // I PUT IT HERE JUST TO SEE IF IT WORKS WELL
+ const [forecasedChartData, setForecasedChartData] = useState({})
+
+ const [chartDataPerf, setChartDataPerf] = useState({})
+ const [isPanelsDataEmptyPerf, setIsPanelsDataEmptyPerf] = useState(false)
+ const [panelsDataPerf, setPanelsDataPerf] = useState({})
+ const timeFormat = useMemo(() => user.timeFormat || TimeFormat['12-hour'], [user])
+ const [ref, size] = useSize()
+ const rotateXAxias = useMemo(() => (size.width > 0 && size.width < 500), [size])
+ const [chartType, setChartType] = useState(getItem('chartType') || chartTypes.line)
+
+ const tabs = useMemo(() => {
+ return [
+ {
+ id: PROJECT_TABS.traffic,
+ label: t('dashboard.traffic'),
+ icon: ChartBarIcon,
+ },
+ {
+ id: PROJECT_TABS.performance,
+ label: t('dashboard.performance'),
+ icon: BoltIcon,
+ },
+ {
+ id: PROJECT_TABS.alerts,
+ label: t('dashboard.alerts'),
+ icon: BellIcon,
+ },
+ ]
+ }, [t])
+
+ const activeTabLabel = useMemo(() => _find(tabs, tab => tab.id === activeTab)?.label, [tabs, activeTab])
+
+ const { name } = project
+
+ const sharedRoles = useMemo(() => _find(user.sharedProjects, p => p.project.id === id)?.role || {}, [user, id])
+
+ const chartMetrics = useMemo(() => {
+ return [
+ {
+ id: CHART_METRICS_MAPPING.unique,
+ label: t('dashboard.unique'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.unique],
+ },
+ {
+ id: CHART_METRICS_MAPPING.views,
+ label: t('project.showAll'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.views],
+ },
+ {
+ id: CHART_METRICS_MAPPING.sessionDuration,
+ label: t('dashboard.sessionDuration'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.sessionDuration],
+ conflicts: [CHART_METRICS_MAPPING.bounce],
+ },
+ {
+ id: CHART_METRICS_MAPPING.bounce,
+ label: t('dashboard.bounceRate'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.bounce],
+ conflicts: [CHART_METRICS_MAPPING.sessionDuration],
+ },
+ {
+ id: CHART_METRICS_MAPPING.viewsPerUnique,
+ label: t('dashboard.viewsPerUnique'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.viewsPerUnique],
+ },
+ {
+ id: CHART_METRICS_MAPPING.trendlines,
+ label: t('dashboard.trendlines'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.trendlines],
+ },
+ ]
+ }, [t, activeChartMetrics])
+
+ const chartMetricsPerf = useMemo(() => {
+ return [
+ {
+ id: CHART_METRICS_MAPPING_PERF.full,
+ label: t('dashboard.timingFull'),
+ active: _includes(activeChartMetricsPerf, CHART_METRICS_MAPPING_PERF.full),
+ },
+ {
+ id: CHART_METRICS_MAPPING_PERF.timing,
+ label: t('dashboard.timing'),
+ active: _includes(activeChartMetricsPerf, CHART_METRICS_MAPPING_PERF.timing),
+ },
+ {
+ id: CHART_METRICS_MAPPING_PERF.network,
+ label: t('dashboard.network'),
+ active: _includes(activeChartMetricsPerf, CHART_METRICS_MAPPING_PERF.network),
+ },
+ {
+ id: CHART_METRICS_MAPPING_PERF.frontend,
+ label: t('dashboard.frontend'),
+ active: _includes(activeChartMetricsPerf, CHART_METRICS_MAPPING_PERF.frontend),
+ },
+ {
+ id: CHART_METRICS_MAPPING_PERF.backend,
+ label: t('dashboard.backend'),
+ active: _includes(activeChartMetricsPerf, CHART_METRICS_MAPPING_PERF.backend),
+ },
+ ]
+ }, [t, activeChartMetricsPerf])
+
+ 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'),
+ }
+ }, [t])
+
+ 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])
+
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const switchActiveChartMetric = useCallback(_debounce((pairID) => {
+ if (activeTab === PROJECT_TABS.performance) {
+ setActiveChartMetricsPerf(pairID)
+ } else {
+ setActiveChartMetrics(prev => ({ ...prev, [pairID]: !prev[pairID] }))
+ }
+ }, 0), [activeTab])
+
+ const onErrorLoading = () => {
+ showError(t('project.noExist'))
+ history.push(routes.dashboard)
+ }
+
+ // this function is used for requesting the data from the API
+ const loadAnalytics = async (forced = false, newFilters = null) => {
+ if (!forced && (isLoading || _isEmpty(project) || dataLoading)) {
+ return
+ }
+
+ setDataLoading(true)
+ try {
+ let data
+ let key
+ let from
+ let to
+
+ if (dateRange) {
+ from = getFormatDate(dateRange[0])
+ to = getFormatDate(dateRange[1])
+ key = getProjectCacheCustomKey(from, to, timeBucket)
+ } else {
+ key = getProjectCacheKey(period, timeBucket)
+ }
+
+ if (!forced && !_isEmpty(cache[id]) && !_isEmpty(cache[id][key])) {
+ data = cache[id][key]
+ } else {
+ if (period === 'custom' && dateRange) {
+ data = await getProjectData(id, timeBucket, '', newFilters || filters, from, to, timezone)
+ } else {
+ data = await getProjectData(id, timeBucket, period, newFilters || filters, '', '', timezone)
+ }
+
+ setProjectCache(id, data || {}, key)
+ }
+
+ const sdkData = {
+ ...(data || {}),
+ filters: newFilters || filters,
+ timezone,
+ timeBucket,
+ period,
+ from,
+ to,
+ }
+
+ if (_isEmpty(data)) {
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ setIsPanelsDataEmpty(true)
+ sdkInstance?._emitEvent('load', sdkData)
+ return
+ }
+
+ const {
+ chart, params, customs, appliedFilters, avgSdur,
+ } = data
+ sdkInstance?._emitEvent('load', sdkData)
+ const processedSdur = getTimeFromSeconds(avgSdur)
+
+ setSessionDurationAVG(getStringFromTime(processedSdur))
+
+ if (!_isEmpty(appliedFilters)) {
+ setFilters(appliedFilters)
+ }
+
+ if (_isEmpty(params)) {
+ setIsPanelsDataEmpty(true)
+ } else {
+ const applyRegions = !_includes(noRegionPeriods, activePeriod.period)
+ const bbSettings = getSettings(chart, timeBucket, activeChartMetrics, applyRegions, timeFormat, forecasedChartData, rotateXAxias, chartType)
+ setChartData(chart)
+
+ setPanelsData({
+ types: _keys(params),
+ data: params,
+ customs,
+ })
+
+ if (activeTab === PROJECT_TABS.traffic) {
+ if (!_isEmpty(mainChart)) {
+ mainChart.destroy()
+ }
+
+ setMainChart(() => {
+ const generete = bb.generate(bbSettings)
+ generete.data.names(dataNames)
+ return generete
+ })
+ }
+
+ setIsPanelsDataEmpty(false)
+ }
+
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ } catch (e) {
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ console.error('[ERROR](loadAnalytics) Loading analytics data failed')
+ console.error(e)
+ }
+ }
+
+ const loadAnalyticsPerf = async (forced = false, newFilters = null) => {
+ if (!forced && (isLoading || _isEmpty(project) || dataLoading)) {
+ return
+ }
+
+ setDataLoading(true)
+ try {
+ let dataPerf
+ let key
+ let from
+ let to
+
+ if (dateRange) {
+ from = getFormatDate(dateRange[0])
+ to = getFormatDate(dateRange[1])
+ key = getProjectCacheCustomKey(from, to, timeBucket)
+ } else {
+ key = getProjectCacheKey(period, timeBucket)
+ }
+
+ if (!forced && !_isEmpty(cachePerf[id]) && !_isEmpty(cachePerf[id][key])) {
+ dataPerf = cachePerf[id][key]
+ } else {
+ if (period === 'custom' && dateRange) {
+ dataPerf = await getPerfData(id, timeBucket, '', newFilters || filtersPerf, from, to, timezone)
+ } else {
+ dataPerf = await getPerfData(id, timeBucket, period, newFilters || filtersPerf, '', '', timezone)
+ }
+
+ setProjectCachePerf(id, dataPerf || {}, key)
+ }
+
+ const {
+ appliedFilters,
+ } = dataPerf
+
+ if (!_isEmpty(appliedFilters)) {
+ setFilters(appliedFilters)
+ }
+
+ if (_isEmpty(dataPerf)) {
+ setIsPanelsDataEmptyPerf(true)
+ setDataLoading(false)
+ setAnalyticsLoading(false)
+ return
+ }
+
+ if (_isEmpty(dataPerf.params)) {
+ setIsPanelsDataEmptyPerf(true)
+ } else {
+ const { chart: chartPerf } = dataPerf
+ const bbSettings = getSettingsPerf(chartPerf, timeBucket, activeChartMetricsPerf, rotateXAxias, chartType)
+ setChartDataPerf(chartPerf)
+
+ setPanelsDataPerf({
+ types: _keys(dataPerf.params),
+ data: dataPerf.params,
+ })
+
+ if (activeTab === PROJECT_TABS.performance) {
+ if (!_isEmpty(mainChart)) {
+ mainChart.destroy()
+ }
+
+ setMainChart(() => {
+ const generete = bb.generate(bbSettings)
+ generete.data.names(dataNamesPerf)
+ return generete
+ })
+ }
+
+ setIsPanelsDataEmptyPerf(false)
+ }
+
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ } catch (e) {
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ console.error('[ERROR](loadAnalytics) Loading analytics data failed')
+ console.error(e)
+ }
+ }
+
+ // this funtion is used for requesting the data from the API when the filter is changed
+ const filterHandler = (column, filter, isExclusive = false) => {
+ let newFilters
+ let newFiltersPerf
+ const columnPerf = `${column}_perf`
+
+ if (activeTab === PROJECT_TABS.performance) {
+ if (_find(filtersPerf, (f) => f.column === column)) {
+ newFiltersPerf = _filter(filtersPerf, (f) => f.column !== column)
+
+ const url = new URL(window.location)
+ url.searchParams.delete(columnPerf)
+ const { pathname, search } = url
+ history.push({
+ pathname,
+ search,
+ state: {
+ scrollToTopDisable: true,
+ },
+ })
+ setFiltersPerf(newFiltersPerf)
+ } else {
+ newFiltersPerf = [
+ ...filtersPerf,
+ { column, filter, isExclusive },
+ ]
+
+ const url = new URL(window.location)
+ url.searchParams.append(columnPerf, filter)
+ const { pathname, search } = url
+ history.push({
+ pathname,
+ search,
+ state: {
+ scrollToTopDisable: true,
+ },
+ })
+ setFiltersPerf(newFiltersPerf)
+ }
+ } else {
+ // eslint-disable-next-line no-lonely-if
+ if (_find(filters, (f) => f.column === column) /* && f.filter === filter) */) {
+ // selected filter is already included into the filters array -> removing it
+ // removing filter from the state
+ newFilters = _filter(filters, (f) => f.column !== column)
+ setFilters(newFilters)
+
+ // removing filter from the page URL
+ const url = new URL(window.location)
+ url.searchParams.delete(column)
+ const { pathname, search } = url
+ history.push({
+ pathname,
+ search,
+ state: {
+ scrollToTopDisable: true,
+ },
+ })
+ } else {
+ // selected filter is not present in the filters array -> applying it
+ // sroting filter in the state
+ newFilters = [
+ ...filters,
+ { column, filter, isExclusive },
+ ]
+ setFilters(newFilters)
+
+ // storing filter in the page URL
+ const url = new URL(window.location)
+ url.searchParams.append(column, filter)
+ const { pathname, search } = url
+ history.push({
+ pathname,
+ search,
+ state: {
+ scrollToTopDisable: true,
+ },
+ })
+ }
+ }
+
+ sdkInstance?._emitEvent('filtersupdate', newFilters)
+ if (activeTab === PROJECT_TABS.performance) {
+ loadAnalyticsPerf(true, newFiltersPerf)
+ } else {
+ loadAnalytics(true, newFilters)
+ }
+ }
+
+ // this function is used for requesting the data from the API when the exclusive filter is changed
+ const onChangeExclusive = (column, filter, isExclusive) => {
+ let newFilters
+ if (activeTab === PROJECT_TABS.performance) {
+ newFilters = _map(filtersPerf, (f) => {
+ if (f.column === column && f.filter === filter) {
+ return {
+ ...f,
+ isExclusive,
+ }
+ }
+
+ return f
+ })
+ setFiltersPerf(newFilters)
+ loadAnalyticsPerf(true, newFilters)
+ } else {
+ newFilters = _map(filters, (f) => {
+ if (f.column === column && f.filter === filter) {
+ return {
+ ...f,
+ isExclusive,
+ }
+ }
+
+ return f
+ })
+ setFilters(newFilters)
+ loadAnalytics(true, newFilters)
+ }
+
+ // storing exclusive filter in the page URL
+ const url = new URL(window.location)
+
+ if (activeTab === PROJECT_TABS.performance) {
+ const columnPerf = `${column}_perf`
+ url.searchParams.delete(columnPerf)
+ url.searchParams.append(columnPerf, filter)
+ } else {
+ url.searchParams.delete(column)
+ url.searchParams.append(column, filter)
+ }
+
+ const { pathname, search } = url
+ history.push({
+ pathname,
+ search,
+ state: {
+ scrollToTopDisable: true,
+ },
+ })
+ sdkInstance?._emitEvent('filtersupdate', newFilters)
+ }
+
+ const refreshStats = () => {
+ if (!isLoading && !dataLoading) {
+ if (activeTab === PROJECT_TABS.performance) {
+ loadAnalyticsPerf(true)
+ } else {
+ loadAnalytics(true)
+ }
+ }
+ }
+
+ const onForecastOpen = () => {
+ if (isLoading || dataLoading) {
+ return
+ }
+
+ if (!_isEmpty(forecasedChartData)) {
+ setForecasedChartData({})
+ return
+ }
+
+ setIsForecastOpened(true)
+ }
+
+ const onForecastSubmit = async (periodToForecast) => {
+ setIsForecastOpened(false)
+ setDataLoading(true)
+ const key = getProjectForcastCacheKey(period, timeBucket, periodToForecast)
+ const data = cache[id][key]
+
+ if (!_isEmpty(data)) {
+ setForecasedChartData(data)
+ setDataLoading(false)
+ return
+ }
+
+ try {
+ const result = await getChartPrediction(chartData, periodToForecast, timeBucket)
+ const transformed = transformAIChartData(result)
+ setProjectForcastCache(id, transformed, key)
+ setForecasedChartData(transformed)
+ } catch (e) {
+ console.error(`[onForecastSubmit] Error: ${e}`)
+ }
+
+ setDataLoading(false)
+ }
+
+ useEffect(() => {
+ loadAnalytics()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [forecasedChartData])
+
+ useEffect(() => {
+ const url = new URL(window.location)
+ url.searchParams.delete('tab')
+
+ url.searchParams.append('tab', activeTab)
+ const { pathname, search } = url
+ history.push({
+ pathname,
+ search,
+ state: {
+ scrollToTopDisable: true,
+ },
+ })
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [activeTab])
+
+ useEffect(() => {
+ if (activeTab === PROJECT_TABS.traffic) {
+ if (!isLoading && !_isEmpty(chartData) && !_isEmpty(mainChart)) {
+ if (activeChartMetrics.views || activeChartMetrics.unique || activeChartMetrics.viewsPerUnique || activeChartMetrics.trendlines) {
+ mainChart.load({
+ columns: getColumns(chartData, activeChartMetrics),
+ })
+ }
+
+ if (activeChartMetrics.bounce || activeChartMetrics.sessionDuration || activeChartMetrics.views || activeChartMetrics.unique) {
+ const applyRegions = !_includes(noRegionPeriods, activePeriod.period)
+ const bbSettings = getSettings(chartData, timeBucket, activeChartMetrics, applyRegions, timeFormat, forecasedChartData, rotateXAxias, chartType)
+
+ if (!_isEmpty(mainChart)) {
+ mainChart.destroy()
+ }
+
+ setMainChart(() => {
+ const generete = bb.generate(bbSettings)
+ generete.data.names(dataNames)
+ return generete
+ })
+ }
+
+ if (!activeChartMetrics.bounce || !activeChartMetrics.sessionDuration || activeChartMetrics.views || activeChartMetrics.unique) {
+ const applyRegions = !_includes(noRegionPeriods, activePeriod.period)
+ const bbSettings = getSettings(chartData, timeBucket, activeChartMetrics, applyRegions, timeFormat, forecasedChartData, rotateXAxias, chartType)
+
+ if (!_isEmpty(mainChart)) {
+ mainChart.destroy()
+ }
+
+ setMainChart(() => {
+ const generete = bb.generate(bbSettings)
+ generete.data.names(dataNames)
+ return generete
+ })
+ }
+
+ if (!activeChartMetrics.views) {
+ mainChart.unload({
+ ids: 'total',
+ })
+ }
+
+ if (!activeChartMetrics.unique) {
+ mainChart.unload({
+ ids: 'unique',
+ })
+ }
+
+ if (!activeChartMetrics.viewsPerUnique) {
+ mainChart.unload({
+ ids: 'viewsPerUnique',
+ })
+ }
+ }
+ } else if (!isLoading && !_isEmpty(chartDataPerf) && !_isEmpty(mainChart)) {
+ const bbSettings = getSettingsPerf(chartDataPerf, timeBucket, activeChartMetricsPerf, rotateXAxias, chartType)
+
+ if (!_isEmpty(mainChart)) {
+ mainChart.destroy()
+ }
+
+ setMainChart(() => {
+ const generete = bb.generate(bbSettings)
+ generete.data.names(dataNamesPerf)
+ return generete
+ })
+ }
+ }, [isLoading, activeChartMetrics, chartData, chartDataPerf, activeChartMetricsPerf]) // eslint-disable-line
+
+ // Initialising Swetrix SDK instance
+ useEffect(() => {
+ let sdk = null
+ if (!_isEmpty(extensions)) {
+ const processedExtensions = _map(extensions, (ext) => {
+ const { id: extId, fileURL } = ext
+ return {
+ id: extId,
+ cdnURL: `${CDN_URL}file/${fileURL}`,
+ }
+ })
+
+ sdk = new SwetrixSDK(processedExtensions, {
+ debug: isDevelopment,
+ }, {
+ onAddExportDataRow: (label, onClick) => {
+ setCustomExportTypes((prev) => [
+ ...prev,
+ {
+ label,
+ onClick,
+ },
+ ])
+ },
+ onRemoveExportDataRow: (label) => {
+ setCustomExportTypes((prev) => _filter(prev, (row) => row.label !== label))
+ },
+ onAddPanelTab: (extensionID, panelID, tabContent, onOpen) => {
+ setCustomPanelTabs((prev) => [
+ ...prev,
+ {
+ extensionID,
+ panelID,
+ tabContent,
+ onOpen,
+ },
+ ])
+ },
+ onRemovePanelTab: (extensionID, panelID) => {
+ setCustomPanelTabs((prev) => _filter(prev, (row) => row.extensionID !== extensionID && row.panelID !== panelID))
+ },
+ })
+ setSdkInstance(sdk)
+ }
+
+ return () => {
+ if (sdk) {
+ sdk._destroy()
+ }
+ }
+ }, [extensions])
+
+ // Supplying 'timeupdate' event to the SDK after loading
+ useEffect(() => {
+ sdkInstance?._emitEvent('timeupdate', {
+ period,
+ timeBucket,
+ dateRange: period === 'custom' ? dateRange : null,
+ })
+ }, [sdkInstance]) // eslint-disable-line
+
+ // Supplying 'projectinfo' event to the SDK after loading
+ useEffect(() => {
+ if (_isEmpty(project)) {
+ return
+ }
+
+ const {
+ active: isActive, created, public: isPublic,
+ } = project
+
+ sdkInstance?._emitEvent('projectinfo', {
+ id, name, isActive, created, isPublic,
+ })
+ }, [sdkInstance, name]) // eslint-disable-line
+
+ useEffect(() => {
+ setPeriodPairs(tbPeriodPairs(t))
+ }, [t])
+
+ // Parsing initial filters from the address bar
+ useEffect(() => {
+ // using try/catch because new URL is not supported by browsers like IE, so at least analytics would work without parsing filters
+ if (activeTab === PROJECT_TABS.performance) {
+ try {
+ const url = new URL(window.location)
+ const { searchParams } = url
+ const initialFilters = []
+ // eslint-disable-next-line lodash/prefer-lodash-method
+ searchParams.forEach((value, key) => {
+ if (!_includes(key, '_perf')) {
+ return
+ }
+
+ const keyPerf = _replace(key, '_perf', '')
+
+ if (!_includes(validFilters, keyPerf)) {
+ return
+ }
+
+ const isExclusive = _startsWith(value, '!')
+ initialFilters.push({
+ column: keyPerf,
+ filter: isExclusive ? value.substring(1) : value,
+ isExclusive,
+ })
+ })
+
+ setFiltersPerf(initialFilters)
+ } finally {
+ setAreFiltersPerfParsed(true)
+ }
+ } else {
+ try {
+ const url = new URL(window.location)
+ const { searchParams } = url
+ const initialFilters = []
+ // eslint-disable-next-line lodash/prefer-lodash-method
+ searchParams.forEach((value, key) => {
+ if (!_includes(validFilters, key)) {
+ return
+ }
+
+ const isExclusive = _startsWith(value, '!')
+ initialFilters.push({
+ column: key,
+ filter: isExclusive ? value.substring(1) : value,
+ isExclusive,
+ })
+ })
+ setFilters(initialFilters)
+ } finally {
+ setAreFiltersParsed(true)
+ }
+ }
+ }, [activeTab])
+
+ useEffect(() => {
+ if (arePeriodParsed) {
+ try {
+ const url = new URL(window.location)
+ const { searchParams } = url
+ const intialTimeBucket = searchParams.get('timeBucket')
+ // eslint-disable-next-line lodash/prefer-lodash-method
+ if (!_includes(validTimeBacket, intialTimeBucket)) {
+ return
+ }
+ const newPeriodFull = _find(periodPairs, (el) => el.period === period)
+ if (!_includes(newPeriodFull.tbs, intialTimeBucket)) {
+ return
+ }
+ setTimebucket(intialTimeBucket)
+ } finally {
+ setAreTimeBucketParsed(true)
+ }
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [arePeriodParsed])
+
+ const onRangeDateChange = (dates, onRender) => {
+ const days = Math.ceil(Math.abs(dates[1].getTime() - dates[0].getTime()) / (1000 * 3600 * 24))
+ const url = new URL(window.location)
+
+ // setting allowed time buckets for the specified date range (period)
+ // eslint-disable-next-line no-restricted-syntax
+ for (const index in timeBucketToDays) {
+ if (timeBucketToDays[index].lt >= days) {
+ let eventEmitTimeBucket = timeBucket
+
+ if (!onRender && !_includes(timeBucketToDays[index].tb, timeBucket)) {
+ // eslint-disable-next-line prefer-destructuring
+ eventEmitTimeBucket = timeBucketToDays[index].tb[0]
+ url.searchParams.delete('timeBucket')
+ url.searchParams.append('timeBucket', eventEmitTimeBucket)
+ const { pathname, search } = url
+ history.push({
+ pathname,
+ search,
+ state: {
+ scrollToTopDisable: true,
+ },
+ })
+ setTimebucket(eventEmitTimeBucket)
+ }
+
+ url.searchParams.delete('period')
+ url.searchParams.delete('from')
+ url.searchParams.delete('to')
+ url.searchParams.append('period', 'custom')
+ url.searchParams.append('from', dates[0].toISOString())
+ url.searchParams.append('to', dates[1].toISOString())
+
+ const { pathname, search } = url
+ history.push({
+ pathname,
+ search,
+ state: {
+ scrollToTopDisable: true,
+ },
+ })
+
+ setPeriodPairs(tbPeriodPairs(t, timeBucketToDays[index].tb, dates))
+ setPeriod('custom')
+ setProjectViewPrefs(id, 'custom', timeBucketToDays[index].tb[0], dates)
+
+ sdkInstance?._emitEvent('timeupdate', {
+ period: 'custom',
+ timeBucket: eventEmitTimeBucket,
+ dateRange: dates,
+ })
+
+ break
+ }
+ }
+ }
+
+ useEffect(() => {
+ if (areFiltersParsed && areTimeBucketParsed && arePeriodParsed) {
+ if (activeTab === PROJECT_TABS.traffic) {
+ loadAnalytics()
+ }
+ }
+ if (areFiltersPerfParsed) {
+ if (activeTab === PROJECT_TABS.performance) {
+ loadAnalyticsPerf()
+ }
+ }
+ }, [project, period, timeBucket, periodPairs, areFiltersParsed, areTimeBucketParsed, arePeriodParsed, t, activeTab, areFiltersPerfParsed]) // eslint-disable-line
+
+ useEffect(() => {
+ if (dateRange && arePeriodParsed) {
+ onRangeDateChange(dateRange)
+ }
+ }, [dateRange, t, arePeriodParsed]) // eslint-disable-line
+
+ useEffect(() => {
+ const updateLiveVisitors = async () => {
+ const { id: pid } = project
+ const result = await getLiveVisitors([pid])
+
+ setLiveStatsForProject(pid, result[pid])
+ }
+
+ let interval
+ if (project.uiHidden) {
+ updateLiveVisitors()
+ interval = setInterval(async () => {
+ await updateLiveVisitors()
+ }, LIVE_VISITORS_UPDATE_INTERVAL)
+ }
+
+ return () => clearInterval(interval)
+ }, [project.id, setLiveStatsForProject]) // eslint-disable-line react-hooks/exhaustive-deps
+
+ useEffect(() => {
+ if (!isLoading && _isEmpty(project)) {
+ getProject(id)
+ .then(projectRes => {
+ if (!_isEmpty(projectRes)) {
+ if (projectRes.isPublic && !projectRes.isOwner) {
+ getOverallStats([id])
+ .then(res => {
+ setPublicProject({
+ ...projectRes,
+ overall: res[id],
+ live: 'N/A',
+ isPublicVisitors: true,
+ })
+ })
+ .catch(e => {
+ console.error(e)
+ onErrorLoading()
+ })
+ } else {
+ getOverallStats([id])
+ .then(res => {
+ setProjects([...projects, {
+ ...projectRes,
+ overall: res[id],
+ live: 'N/A',
+ }])
+ })
+ .then(() => {
+ return getLiveVisitors([id])
+ })
+ .then(res => {
+ setLiveStatsForProject(id, res[id])
+ })
+ .catch(e => {
+ console.error(e)
+ onErrorLoading()
+ })
+ }
+ } else {
+ onErrorLoading()
+ }
+ })
+ .catch(e => {
+ console.error(e)
+ onErrorLoading()
+ })
+ }
+ }, [isLoading, project, id, setPublicProject]) // eslint-disable-line
+
+ const updatePeriod = (newPeriod) => {
+ const newPeriodFull = _find(periodPairs, (el) => el.period === newPeriod.period)
+ let tb = timeBucket
+ const url = new URL(window.location)
+ if (_isEmpty(newPeriodFull)) return
+
+ if (!_includes(newPeriodFull.tbs, timeBucket)) {
+ tb = _last(newPeriodFull.tbs)
+ url.searchParams.delete('timeBucket')
+ url.searchParams.append('timeBucket', tb)
+ setTimebucket(tb)
+ }
+
+ if (newPeriod.period !== 'custom') {
+ url.searchParams.delete('period')
+ url.searchParams.delete('from')
+ url.searchParams.delete('to')
+ url.searchParams.append('period', newPeriod.period)
+ setProjectViewPrefs(id, newPeriod.period, tb)
+ setPeriod(newPeriod.period)
+ setDateRange(null)
+ }
+ const { pathname, search } = url
+ history.push({
+ pathname,
+ search,
+ state: {
+ scrollToTopDisable: true,
+ },
+ })
+ sdkInstance?._emitEvent('timeupdate', {
+ period: newPeriod.period,
+ timeBucket: tb,
+ dateRange: newPeriod.period === 'custom' ? dateRange : null,
+ })
+ setForecasedChartData({})
+ }
+
+ const updateTimebucket = (newTimebucket) => {
+ const url = new URL(window.location)
+ url.searchParams.delete('timeBucket')
+ url.searchParams.append('timeBucket', newTimebucket)
+ const { pathname, search } = url
+ history.push({
+ pathname,
+ search,
+ state: {
+ scrollToTopDisable: true,
+ },
+ })
+ setTimebucket(newTimebucket)
+ setProjectViewPrefs(id, period, newTimebucket, dateRange)
+ sdkInstance?._emitEvent('timeupdate', {
+ period,
+ timeBucket: newTimebucket,
+ dateRange,
+ })
+ setForecasedChartData({})
+ }
+
+ const openSettingsHandler = () => {
+ history.push(_replace(routes.project_settings, ':id', id))
+ }
+
+ const exportAsImageHandler = async () => {
+ setShowIcons(false)
+ try {
+ const blob = await domToImage.toBlob(dashboardRef.current)
+ saveAs(blob, `swetrix-${dayjs().format('YYYY-MM-DD-HH-mm-ss')}.png`)
+ } catch (e) {
+ showError(t('project.exportImgError'))
+ console.error('[ERROR] Error while generating export image.')
+ console.error(e)
+ } finally {
+ setShowIcons(true)
+ }
+ }
+
+ useEffect(() => {
+ try {
+ const url = new URL(window.location)
+ const { searchParams } = url
+ const intialPeriod = searchParams.get('period')
+ const tab = searchParams.get('tab')
+
+ if (tab === PROJECT_TABS.performance) {
+ setProjectTab(PROJECT_TABS.performance)
+ }
+
+ if (!_includes(validPeriods, intialPeriod) || (!isSharedProject && id !== SWETRIX_PID && !isPaidTierUsed && _includes(paidPeriods, intialPeriod))) {
+ return
+ }
+
+ if (intialPeriod === 'custom') {
+ const from = new Date(searchParams.get('from'))
+ const to = new Date(searchParams.get('to'))
+ if (from.getDate() && to.getDate()) {
+ onRangeDateChange([from, to], true)
+ setDateRange([from, to])
+ }
+ return
+ }
+
+ setPeriodPairs(tbPeriodPairs(t))
+ setDateRange(null)
+ updatePeriod({ period: intialPeriod })
+ } finally {
+ setArePeriodParsed(true)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
+ const isConflicted = (conflicts) => {
+ const conflicted = conflicts && _some(conflicts, (conflict) => {
+ const conflictPair = _find(chartMetrics, (metric) => metric.id === conflict)
+ return conflictPair && conflictPair.active
+ })
+ return conflicted
+ }
+
+ const resetFilters = () => {
+ const url = new URL(window.location)
+ const { searchParams } = url
+ // eslint-disable-next-line lodash/prefer-lodash-method
+ searchParams.forEach((value, key) => {
+ if (!_includes(validFilters, key)) {
+ return
+ }
+ searchParams.delete(key)
+ })
+ const { pathname, search } = url
+ history.push({
+ pathname,
+ search,
+ state: {
+ scrollToTopDisable: true,
+ },
+ })
+ setFilters([])
+ setFiltersPerf([])
+ if (activeTab === PROJECT_TABS.performance) {
+ loadAnalyticsPerf(true, [])
+ } else {
+ loadAnalytics(true, [])
+ }
+ }
+
+ const exportTypes = [
+ { label: t('project.asImage'), onClick: exportAsImageHandler },
+ {
+ label: t('project.asCSV'),
+ onClick: () => {
+ if (activeTab === PROJECT_TABS.performance) {
+ return onCSVExportClick(panelsDataPerf, id, tnMapping, language)
+ }
+ return onCSVExportClick(panelsData, id, tnMapping, language)
+ },
+ },
+ ]
+
+ // function set chart type and save to local storage
+ const setChartTypeOnClick = (type) => {
+ setItem('chartType', type)
+ setChartType(type)
+ }
+
+ // useEffect to change chart if we change chart type
+ useEffect(() => {
+ if (activeTab === PROJECT_TABS.performance) {
+ loadAnalyticsPerf()
+ } else {
+ loadAnalytics()
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [chartType])
+
+ if (!isLoading) {
+ return (
+ <Title title={name}>
+ <EventsRunningOutBanner />
+ <div ref={ref}>
+ <div
+ className={cx(
+ 'bg-gray-50 dark:bg-gray-800 py-6 px-2 sm:px-4 lg:px-8',
+ {
+ 'min-h-min-footer': authenticated || activeTab === PROJECT_TABS.alerts,
+ 'min-h-min-footer-ad': !authenticated && activeTab !== PROJECT_TABS.alerts,
+ },
+ )}
+ ref={dashboardRef}
+ >
+ {/* Tabs selector */}
+ <div>
+ <div className='sm:hidden'>
+ <Select
+ items={tabs}
+ keyExtractor={(item) => item.id}
+ labelExtractor={(item) => item.label}
+ onSelect={(label) => {
+ const selected = _find(tabs, (tab) => tab.label === label)
+ setProjectTab(selected.id)
+ setActiveTab(selected.id)
+ }}
+ title={activeTabLabel}
+ />
+ </div>
+ <div className='hidden sm:block'>
+ <div>
+ <nav className='-mb-px flex space-x-4' aria-label='Tabs'>
+ {_map(tabs, tab => {
+ const isCurrent = tab.id === activeTab
+
+ return (
+ <div
+ key={tab.id}
+ onClick={() => {
+ setProjectTab(tab.id)
+ setActiveTab(tab.id)
+ }}
+ className={cx(
+ isCurrent
+ ? 'border-indigo-700 text-indigo-700 dark:text-indigo-500 dark:border-indigo-500'
+ : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:border-gray-300 dark:hover:text-gray-300',
+ 'group inline-flex items-center whitespace-nowrap py-2 px-1 border-b-2 font-bold text-md cursor-pointer',
+ )}
+ aria-current={isCurrent ? 'page' : undefined}
+ >
+ <tab.icon
+ className={cx(
+ isCurrent ? 'text-indigo-700 dark:text-indigo-500' : 'text-gray-500 group-hover:text-gray-500 dark:text-gray-400 dark:group-hover:text-gray-300',
+ '-ml-0.5 mr-2 h-5 w-5',
+ )}
+ aria-hidden='true'
+ />
+ <span>
+ {tab.label}
+ </span>
+ </div>
+ )
+ })}
+ </nav>
+ </div>
+ </div>
+ </div>
+ {activeTab !== PROJECT_TABS.alerts && (
+ <>
+ <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}
+ </h2>
+ <div className='flex mt-3 md:mt-0 max-w-[420px] flex-wrap items-center sm:max-w-none justify-between w-full sm:w-auto mx-auto sm:mx-0'>
+ <div className='md:border-r border-gray-200 dark:border-gray-600 md:pr-3 sm:mr-3'>
+ <button
+ type='button'
+ onClick={refreshStats}
+ className={cx('relative shadow-sm rounded-md mt-[1px] px-3 md:px-4 py-2 bg-white text-sm font-medium hover:bg-gray-50 dark:bg-gray-700 dark:hover:bg-gray-600 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>
+ </div>
+ <div
+ className={cx('md:border-r border-gray-200 dark:border-gray-600 md:pr-3 sm:mr-3', {
+ hidden: activeTab !== PROJECT_TABS.traffic,
+ })}
+ >
+ <button
+ type='button'
+ onClick={onForecastOpen}
+ disabled={!_isEmpty(filters)}
+ className={cx('relative shadow-sm rounded-md mt-[1px] px-3 md:px-4 py-2 bg-white text-sm font-medium hover:bg-gray-50 dark:bg-gray-700 dark:hover:bg-gray-600 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 || !_isEmpty(filters),
+ '!bg-gray-200 dark:!bg-gray-600 !border dark:!border-gray-500 !border-gray-300': !_isEmpty(forecasedChartData),
+ })}
+ >
+ <Robot containerClassName='w-5 h-5' className='text-gray-700 dark:text-gray-50' />
+ </button>
+ </div>
+ <div className='md:border-r border-gray-200 dark:border-gray-600 md:pr-3 sm:mr-3'>
+ <span className='relative z-0 inline-flex shadow-sm rounded-md'>
+ {_map(activePeriod.tbs, (tb, index, { length }) => (
+ <button
+ key={tb}
+ type='button'
+ onClick={() => updateTimebucket(tb)}
+ className={cx(
+ 'relative capitalize inline-flex items-center px-3 md:px-4 py-2 border bg-white text-sm font-medium hover:bg-gray-50 dark:bg-gray-700 dark:hover:bg-gray-600 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',
+ {
+ '-ml-px': index > 0,
+ 'rounded-l-md': index === 0,
+ 'rounded-r-md': 1 + index === length,
+ 'z-10 border-indigo-500 text-indigo-600 dark:border-gray-200 dark:text-gray-50': timeBucket === tb,
+ 'text-gray-700 dark:text-gray-50 border-gray-300 dark:border-gray-800 ': timeBucket !== tb,
+ },
+ )}
+ >
+ {t(`project.${tb}`)}
+ </button>
+ ))}
+ </span>
+ </div>
+ <Dropdown
+ items={periodPairs}
+ title={activePeriod.label}
+ labelExtractor={(pair) => {
+ const label = pair.dropdownLabel || pair.label
+
+ // disable limitation for shared projects as project hosts already have a paid plan
+ // disable limitation for Swetrix public project (for demonstration purposes)
+ if (!isSharedProject && id !== SWETRIX_PID && !isPaidTierUsed && pair.access === 'paid') {
+ return (
+ <span className='flex items-center'>
+ <CurrencyDollarIcon className='w-4 h-4 mr-1' />
+ {label}
+ </span>
+ )
+ }
+
+ return label
+ }}
+ keyExtractor={(pair) => pair.label}
+ onSelect={(pair) => {
+ if (!isSharedProject && id !== SWETRIX_PID && !isPaidTierUsed && pair.access === 'paid') {
+ setIsPaidFeatureOpened(true)
+ return
+ }
+
+ if (pair.isCustomDate) {
+ setTimeout(() => {
+ refCalendar.current.openCalendar()
+ }, 100)
+ } else {
+ setPeriodPairs(tbPeriodPairs(t))
+ setDateRange(null)
+ updatePeriod(pair)
+ }
+ }}
+ />
+ <FlatPicker
+ ref={refCalendar}
+ onChange={(date) => setDateRange(date)}
+ value={dateRange}
+ maxDateMonths={(isPaidTierUsed || id === SWETRIX_PID || isSharedProject) ? MAX_MONTHS_IN_PAST : MAX_MONTHS_IN_PAST_FREE}
+ />
+ </div>
+ </div>
+ <div>
+ <div className='flex flex-row flex-wrap items-center justify-center md:justify-end h-10 mt-2 md:mt-5 mb-4'>
+ {activeTab === PROJECT_TABS.traffic ? (
+ !isPanelsDataEmpty && (
+ <Dropdown
+ items={chartMetrics}
+ title={t('project.metricVis')}
+ labelExtractor={(pair) => {
+ const {
+ label, id: pairID, active, conflicts,
+ } = pair
+
+ const conflicted = isConflicted(conflicts)
+
+ return (
+ <Checkbox
+ className={cx({ hidden: isPanelsDataEmpty || analyticsLoading })}
+ label={label}
+ disabled={conflicted}
+ id={pairID}
+ checked={active}
+ />
+ )
+ }}
+ 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) => {
+ const {
+ label,
+ } = pair
+
+ return label
+ }}
+ keyExtractor={(pair) => pair.id}
+ onSelect={({ id: pairID }) => {
+ switchActiveChartMetric(pairID)
+ }}
+ />
+ )
+ )}
+ <Dropdown
+ items={[...exportTypes, ...customExportTypes]}
+ title={[
+ <ArrowDownTrayIcon key='download-icon' className='w-5 h-5 mr-2' />,
+ <Fragment key='export-data'>
+ {t('project.exportData')}
+ </Fragment>,
+ ]}
+ labelExtractor={item => item.label}
+ keyExtractor={item => item.label}
+ onSelect={item => item.onClick(panelsData, t)}
+ className={cx('ml-3', { hidden: isPanelsDataEmpty || analyticsLoading })}
+ />
+ {(!project?.isPublicVisitors && !(sharedRoles === roleViewer.role)) && (
+ <Button
+ onClick={openSettingsHandler}
+ className='relative flex justify-center items-center py-2 !pr-3 !pl-1 md:pr-4 md:pl-2 ml-3 text-sm dark:text-gray-50 dark:border-gray-800 dark:bg-gray-700 dark:hover:bg-gray-600'
+ secondary
+ >
+ <Cog8ToothIcon className='w-5 h-5 mr-1' />
+ {t('common.settings')}
+ </Button>
+ )}
+ </div>
+ </div>
+ <div
+ className={cx({
+ hidden: isPanelsDataEmpty || analyticsLoading,
+ })}
+ >
+ <div className='mt-14 xs:mt-0' />
+ <div className='relative'>
+ <div className={cx('absolute right-0 z-10 -top-2', {
+ 'right-[90px]': activeChartMetrics[CHART_METRICS_MAPPING.sessionDuration],
+ 'right-[60px]': activeChartMetrics[CHART_METRICS_MAPPING.bounce],
+ })}
+ >
+ <button
+ type='button'
+ onClick={() => setChartTypeOnClick(chartTypes.bar)}
+ className={cx('px-2.5 py-1.5 text-xs rounded-md text-gray-700 bg-white hover:bg-gray-50 border-transparent !border-0 dark:text-gray-50 dark:bg-gray-800 dark:hover:bg-gray-700 focus:outline-none focus:!ring-0 focus:!ring-offset-0 focus:!ring-transparent', {
+ 'text-indigo-600 dark:text-indigo-500 shadow-md': chartType === chartTypes.bar,
+ 'text-gray-400 dark:text-gray-500': chartType !== chartTypes.bar,
+ })}
+ >
+ <PresentationChartBarIcon className='w-6 h-6' />
+ </button>
+ <button
+ type='button'
+ onClick={() => setChartTypeOnClick(chartTypes.line)}
+ className={cx('px-2.5 py-1.5 text-xs rounded-md text-gray-700 bg-white hover:bg-gray-50 border-transparent !border-0 dark:text-gray-50 dark:bg-gray-800 dark:hover:bg-gray-700 focus:!outline-0 focus:!ring-0 focus:!ring-offset-0 focus:!ring-transparent', {
+ 'text-indigo-600 dark:text-indigo-500 shadow-md': chartType === chartTypes.line,
+ 'text-gray-400 dark:text-gray-500': chartType !== chartTypes.line,
+ })}
+ >
+ <PresentationChartLineIcon className='w-6 h-6' />
+ </button>
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+ {(activeTab === PROJECT_TABS.alerts && (isSharedProject || project?.isPublicVisitors || !authenticated)) && (
+ <div className='p-5 mt-5 bg-gray-700 rounded-xl'>
+ <div className='flex items-center text-gray-50'>
+ <BellIcon className='w-8 h-8 mr-2' />
+ <p className='font-bold text-3xl'>
+ {t('dashboard.alerts')}
+ </p>
+ </div>
+ <p className='text-lg whitespace-pre-wrap mt-2 text-gray-100'>
+ {t('dashboard.alertsDesc')}
+ </p>
+ <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?.isPublicVisitors && authenticated) && (
+ <ProjectAlertsView projectId={id} />
+ )}
+ {(analyticsLoading && activeTab !== PROJECT_TABS.alerts) && (
+ <Loader />
+ )}
+ {(isPanelsDataEmpty && activeTab === PROJECT_TABS.traffic) && (
+ <NoEvents filters={filters} resetFilters={resetFilters} pid={id} />
+ )}
+ {(isPanelsDataEmptyPerf && activeTab === PROJECT_TABS.performance) && (
+ <NoEvents filters={filters} resetFilters={resetFilters} pid={id} />
+ )}
+ {activeTab === PROJECT_TABS.traffic && (
+ <div className={cx('pt-4 md:pt-0', { hidden: isPanelsDataEmpty || analyticsLoading })}>
+ <div
+ className={cx('h-80', {
+ hidden: checkIfAllMetricsAreDisabled,
+ })}
+ >
+ <div className='h-80' id='dataChart' />
+ </div>
+ <Filters
+ filters={filters}
+ onRemoveFilter={filterHandler}
+ onChangeExclusive={onChangeExclusive}
+ tnMapping={tnMapping}
+ />
+ {dataLoading && (
+ <div className='loader bg-transparent static mt-4' id='loader'>
+ <div className='loader-head'>
+ <div className='first' />
+ <div className='second' />
+ </div>
+ </div>
+ )}
+ <div className='mt-5 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3'>
+ {!_isEmpty(project.overall) && (
+ <Overview
+ t={t}
+ overall={project.overall}
+ chartData={chartData}
+ activePeriod={activePeriod}
+ sessionDurationAVG={sessionDurationAVG}
+ live={project.live}
+ projectId={id}
+ />
+ )}
+ {_map(panelsData.types, (type) => {
+ const panelName = tnMapping[type]
+ const panelIcon = panelIconMapping[type]
+ const customTabs = _filter(customPanelTabs, tab => tab.panelID === type)
+
+ if (type === 'cc') {
+ return (
+ <Panel
+ t={t}
+ key={type}
+ icon={panelIcon}
+ id={type}
+ onFilter={filterHandler}
+ name={panelName}
+ data={panelsData.data[type]}
+ customTabs={customTabs}
+ rowMapper={(rowName) => (
+ <CCRow rowName={rowName} language={language} />
+ )}
+ />
+ )
+ }
+
+ if (type === 'dv') {
+ return (
+ <Panel
+ t={t}
+ key={type}
+ icon={panelIcon}
+ id={type}
+ onFilter={filterHandler}
+ name={panelName}
+ data={panelsData.data[type]}
+ customTabs={customTabs}
+ capitalize
+ />
+ )
+ }
+
+ if (type === 'ref') {
+ return (
+ <Panel
+ t={t}
+ key={type}
+ icon={panelIcon}
+ id={type}
+ onFilter={filterHandler}
+ name={panelName}
+ data={panelsData.data[type]}
+ customTabs={customTabs}
+ rowMapper={(rowName) => (
+ <RefRow rowName={rowName} showIcons={showIcons} />
+ )}
+ />
+ )
+ }
+
+ return (
+ <Panel
+ t={t}
+ key={type}
+ icon={panelIcon}
+ id={type}
+ onFilter={filterHandler}
+ name={panelName}
+ data={panelsData.data[type]}
+ customTabs={customTabs}
+ />
+ )
+ })}
+ {!_isEmpty(panelsData.customs) && (
+ <CustomEvents
+ t={t}
+ customs={panelsData.customs}
+ onFilter={filterHandler}
+ chartData={chartData}
+ />
+ )}
+ </div>
+ </div>
+ )}
+ {activeTab === PROJECT_TABS.performance && (
+ <div className={cx('pt-4 md:pt-0', { hidden: isPanelsDataEmptyPerf || analyticsLoading })}>
+ <div
+ className={cx('h-80', {
+ hidden: checkIfAllMetricsAreDisabled,
+ })}
+ >
+ <div className='h-80' id='dataChart' />
+ </div>
+ <Filters
+ filters={filtersPerf}
+ onRemoveFilter={filterHandler}
+ onChangeExclusive={onChangeExclusive}
+ tnMapping={tnMapping}
+ />
+ {dataLoading && (
+ <div className='loader bg-transparent static mt-4' id='loader'>
+ <div className='loader-head'>
+ <div className='first' />
+ <div className='second' />
+ </div>
+ </div>
+ )}
+ <div className='mt-5 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3'>
+ {_map(panelsDataPerf.types, (type) => {
+ const panelName = tnMapping[type]
+ const panelIcon = panelIconMapping[type]
+ const customTabs = _filter(customPanelTabs, tab => tab.panelID === type)
+
+ if (type === 'cc') {
+ return (
+ <Panel
+ t={t}
+ key={type}
+ icon={panelIcon}
+ id={type}
+ onFilter={filterHandler}
+ name={panelName}
+ data={panelsDataPerf.data[type]}
+ customTabs={customTabs}
+ rowMapper={(rowName) => (
+ <CCRow rowName={rowName} language={language} />
+ )}
+ valueMapper={(value) => getStringFromTime(getTimeFromSeconds(value), true)}
+ />
+ )
+ }
+
+ if (type === 'dv') {
+ return (
+ <Panel
+ t={t}
+ key={type}
+ icon={panelIcon}
+ id={type}
+ onFilter={filterHandler}
+ name={panelName}
+ data={panelsDataPerf.data[type]}
+ customTabs={customTabs}
+ valueMapper={(value) => getStringFromTime(getTimeFromSeconds(value), true)}
+ capitalize
+ />
+ )
+ }
+
+ return (
+ <Panel
+ t={t}
+ key={type}
+ icon={panelIcon}
+ id={type}
+ onFilter={filterHandler}
+ name={panelName}
+ data={panelsDataPerf.data[type]}
+ customTabs={customTabs}
+ valueMapper={(value) => getStringFromTime(getTimeFromSeconds(value), true)}
+ />
+ )
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ {!authenticated && activeTab !== PROJECT_TABS.alerts && (
+ <div className='bg-indigo-600'>
+ <div className='w-11/12 mx-auto pb-16 pt-12 px-4 sm:px-6 lg:px-8 lg:flex lg:items-center lg:justify-between'>
+ <h2 className='text-3xl sm:text-4xl font-bold tracking-tight text-gray-900'>
+ <span className='block text-white'>{t('project.ad')}</span>
+ <span className='block text-gray-300'>
+ {t('main.exploreService')}
+ </span>
+ </h2>
+ <div className='mt-6 space-y-4 sm:space-y-0 sm:flex sm:space-x-5'>
+ <Link
+ to={routes.signup}
+ className='flex items-center justify-center px-3 py-2 border border-transparent text-lg font-medium rounded-md shadow-sm text-indigo-800 bg-indigo-50 hover:bg-indigo-100'
+ aria-label={t('titles.signup')}
+ >
+ {t('common.getStarted')}
+ </Link>
+ <Link
+ to={routes.main}
+ className='flex items-center justify-center px-3 py-2 border border-transparent text-lg font-medium rounded-md shadow-sm text-indigo-800 bg-indigo-50 hover:bg-indigo-100'
+ >
+ {t('common.explore')}
+ </Link>
+ </div>
+ </div>
+ </div>
+ )}
+ <PaidFeature
+ isOpened={isPaidFeatureOpened}
+ onClose={() => setIsPaidFeatureOpened(false)}
+ />
+ <Forecast
+ isOpened={isForecastOpened}
+ onClose={() => setIsForecastOpened(false)}
+ onSubmit={onForecastSubmit}
+ activeTB={t(`project.${timeBucket}`)}
+ tb={timeBucket}
+ />
+ </Title>
+ )
+ }
+
+ return (
+ <Title title={name}>
+ <div className='min-h-min-footer bg-gray-50 dark:bg-gray-800'>
+ <Loader />
+ </div>
+ </Title>
+ )
+}
+
+ViewProject.propTypes = {
+ projects: PropTypes.arrayOf(PropTypes.object).isRequired,
+ sharedProjects: PropTypes.arrayOf(PropTypes.object).isRequired,
+ cache: PropTypes.objectOf(PropTypes.object).isRequired,
+ projectViewPrefs: PropTypes.objectOf(PropTypes.object).isRequired,
+ showError: PropTypes.func.isRequired,
+ setProjectCache: PropTypes.func.isRequired,
+ setProjectViewPrefs: PropTypes.func.isRequired,
+ isLoading: PropTypes.bool.isRequired,
+ setPublicProject: PropTypes.func.isRequired,
+ setLiveStatsForProject: PropTypes.func.isRequired,
+ authenticated: PropTypes.bool.isRequired,
+ extensions: PropTypes.arrayOf(PropTypes.object).isRequired,
+ isPaidTierUsed: PropTypes.bool.isRequired,
+ timezone: PropTypes.string,
+}
+
+ViewProject.defaultProps = {
+ timezone: DEFAULT_TIMEZONE,
+}
+
+export default memo(ViewProject)
diff --git a/src/pages/Captcha/View/components/CCRow.jsx b/src/pages/Captcha/View/components/CCRow.jsx
new file mode 100644
index 000000000..2f9452b2b
--- /dev/null
+++ b/src/pages/Captcha/View/components/CCRow.jsx
@@ -0,0 +1,32 @@
+import React, { memo } from 'react'
+import Flag from 'react-flagkit'
+import countries from 'utils/isoCountries'
+import PropTypes from 'prop-types'
+
+/**
+ * Component to render country flag in the 'Countries' panel.
+ *
+ * @param {string} rowName - The country code.
+ * @param {string} language - Language to use for country name.
+ * @returns {JSX.Element}
+ */
+const CCRow = ({ rowName, language }) => (
+ <>
+ <Flag
+ className='rounded-sm'
+ country={rowName}
+ size={21}
+ alt=''
+ aria-hidden='true'
+ />
+ &nbsp;&nbsp;
+ {countries.getName(rowName, language)}
+ </>
+)
+
+CCRow.propTypes = {
+ rowName: PropTypes.string.isRequired,
+ language: PropTypes.string.isRequired,
+}
+
+export default memo(CCRow)
diff --git a/src/pages/Captcha/View/components/Filters.jsx b/src/pages/Captcha/View/components/Filters.jsx
new file mode 100644
index 000000000..2eb6158db
--- /dev/null
+++ b/src/pages/Captcha/View/components/Filters.jsx
@@ -0,0 +1,93 @@
+import React, { memo } from 'react'
+import _truncate from 'lodash/truncate'
+import _map from 'lodash/map'
+import PropTypes from 'prop-types'
+import { useTranslation } from 'react-i18next'
+
+import countries from 'utils/isoCountries'
+
+/**
+ * This component is used for showing the filter in panel
+ * @returns {JSX.Element}
+ */
+const Filter = ({
+ column, filter, isExclusive, onRemoveFilter, onChangeExclusive, tnMapping, language, t,
+}) => {
+ const displayColumn = tnMapping[column]
+ let displayFilter = filter
+
+ if (column === 'cc') {
+ displayFilter = countries.getName(filter, language)
+ }
+
+ displayFilter = _truncate(displayFilter)
+
+ return (
+ <span className='inline-flex rounded-md items-center py-0.5 pl-2.5 pr-1 mr-2 mt-2 text-sm font-medium bg-gray-200 text-gray-800 dark:text-gray-50 dark:bg-gray-700'>
+ {displayColumn}
+ &nbsp;
+ <span className='text-blue-400 border-blue-400 border-b-2 border-dotted cursor-pointer' onClick={() => onChangeExclusive(column, filter, !isExclusive)}>
+ {t(`common.${isExclusive ? 'isNot' : 'is'}`)}
+ </span>
+ &nbsp;
+ &quot;
+ {displayFilter}
+ &quot;
+ <button
+ onClick={() => onRemoveFilter(column, filter)}
+ type='button'
+ className='flex-shrink-0 ml-0.5 h-4 w-4 rounded-full inline-flex items-center justify-center text-gray-800 hover:text-gray-900 hover:bg-gray-300 focus:bg-gray-300 focus:text-gray-900 dark:text-gray-50 dark:bg-gray-700 dark:hover:text-gray-300 dark:hover:bg-gray-800 dark:focus:bg-gray-800 dark:focus:text-gray-300 focus:outline-none '
+ >
+ <span className='sr-only'>Remove filter</span>
+ <svg className='h-2 w-2' stroke='currentColor' fill='none' viewBox='0 0 8 8'>
+ <path strokeLinecap='round' strokeWidth='1.5' d='M1 1l6 6m0-6L1 7' />
+ </svg>
+ </button>
+ </span>
+ )
+}
+
+/**
+ * This component is used for rendering the filter panel.
+ *
+ * @param {array} filters - Active filters.
+ * @param {function} onRemoveFilter - Callback to remove a filter.
+ * @param {function} onChangeExclusive - Callback to change the exclusive status of a filter.
+ * @param {object} tnMapping - Mapping of column names to translated names.
+ * @returns {JSX.Element}
+ */
+const Filters = ({
+ filters, onRemoveFilter, onChangeExclusive, tnMapping,
+}) => {
+ const { t, i18n: { language } } = useTranslation('common')
+
+ return (
+ <div className='flex justify-center md:justify-start flex-wrap -mt-2'>
+ {_map(filters, (props) => {
+ const { column, filter } = props
+ const key = `${column}${filter}`
+
+ return (
+ <Filter key={key} onRemoveFilter={onRemoveFilter} onChangeExclusive={onChangeExclusive} language={language} t={t} tnMapping={tnMapping} {...props} />
+ )
+ })}
+ </div>
+ )
+}
+
+Filters.propTypes = {
+ filters: PropTypes.arrayOf(PropTypes.shape({
+ column: PropTypes.string,
+ filter: PropTypes.string,
+ isExclusive: PropTypes.bool,
+ })),
+ onRemoveFilter: PropTypes.func.isRequired,
+ onChangeExclusive: PropTypes.func.isRequired,
+ tnMapping: PropTypes.objectOf(PropTypes.string).isRequired,
+}
+
+Filters.defaultProps = {
+ filters: [],
+}
+
+export default memo(Filters)
diff --git a/src/pages/Captcha/View/components/InteractiveMap.jsx b/src/pages/Captcha/View/components/InteractiveMap.jsx
new file mode 100644
index 000000000..ec078aee3
--- /dev/null
+++ b/src/pages/Captcha/View/components/InteractiveMap.jsx
@@ -0,0 +1,122 @@
+import React, { memo, useState } from 'react'
+import cx from 'clsx'
+import _map from 'lodash/map'
+import { useTranslation } from 'react-i18next'
+import PropTypes from 'prop-types'
+import countries from 'utils/isoCountries'
+import { PROJECT_TABS } from 'redux/constants'
+import { getTimeFromSeconds, getStringFromTime } from 'utils/generic'
+
+import countriesList from 'utils/countries'
+import { useSelector } from 'react-redux'
+
+const InteractiveMap = ({ data, onClickCountry, total }) => {
+ const { t, i18n: { language } } = useTranslation('common')
+ const [hoverShow, setHoverShow] = useState(false)
+ const [dataHover, setDataHover] = useState(null)
+ const [cursorPosition, setCursorPosition] = useState(null)
+
+ const projectTab = useSelector((state) => state.ui.projects.projectTab)
+ const isTrafficTab = projectTab === PROJECT_TABS.traffic
+
+ const onMouseMove = (e) => {
+ const rect = e.currentTarget.getBoundingClientRect()
+ const pageX = e.clientX - rect.left
+ const pageY = e.clientY - rect.top
+ setCursorPosition({ pageX, pageY })
+ }
+
+ return (
+ <div className='relative'>
+ <svg id='map' viewBox='0 0 1050 650' className='w-full h-full' onMouseMove={onMouseMove}>
+ <g>
+ {_map(countriesList, (item, index) => {
+ const ccData = data[index] || 0
+ const perc = ((ccData / total) * 100) || 0
+
+ return (
+ <path
+ key={index}
+ id={index}
+ className={isTrafficTab
+ ? cx({
+ 'hover:opacity-90': perc > 0,
+ 'fill-[#cfd1d4] dark:fill-[#465d7e46]': perc === 0,
+ 'fill-[#92b2e7] dark:fill-[#292d77]': perc > 0 && perc < 3,
+ 'fill-[#6f9be3] dark:fill-[#363391]': perc >= 3 && perc < 10,
+ 'fill-[#5689db] dark:fill-[#4842be]': perc >= 10 && perc < 20,
+ 'fill-[#3b82f6] dark:fill-[#6357ff]': perc >= 20,
+ 'cursor-pointer': Boolean(ccData),
+ }) : cx({
+ 'hover:opacity-90': ccData > 0,
+ 'fill-[#cfd1d4] dark:fill-[#465d7e46]': ccData === 0,
+ 'fill-[#92b2e7] dark:fill-[#292d77]': ccData > 0 && ccData < 1,
+ 'fill-[#6f9be3] dark:fill-[#363391]': ccData >= 1 && ccData < 2,
+ 'fill-[#5689db] dark:fill-[#4842be]': ccData >= 2 && ccData < 3,
+ 'fill-[#3b82f6] dark:fill-[#6357ff]': ccData >= 3 && ccData < 5,
+ 'fill-[#f78a8a]': ccData >= 5 && ccData < 7,
+ 'fill-[#f76b6b]': ccData >= 7 && ccData < 10,
+ 'fill-[#f74b4b]': ccData >= 10,
+ 'cursor-pointer': Boolean(ccData),
+ })}
+ d={item.d}
+ onClick={() => perc !== 0 && onClickCountry(index)}
+ onMouseEnter={() => {
+ if (ccData) {
+ setHoverShow(true)
+ setDataHover({
+ countries: countries.getName(index, language),
+ data: ccData,
+ })
+ }
+ }}
+ onMouseLeave={() => {
+ setHoverShow(false)
+ }}
+ />
+ )
+ })}
+ </g>
+ </svg>
+ <div>
+ {hoverShow && cursorPosition && (
+ <div
+ className='border absolute z-30 text-xs bg-gray-100 dark:bg-gray-800 dark:shadow-gray-850 dark:border-gray-850 dark:text-gray-200 p-1 rounded-md'
+ style={{
+ top: cursorPosition.pageY + 20,
+ left: cursorPosition.pageX - 20,
+ }}
+ >
+ <strong>{dataHover.countries}</strong>
+ <br />
+ {isTrafficTab ? t('project.unique') : t('dashboard.pageLoad')}
+ :
+ &nbsp;
+ <strong
+ className={cx({
+ 'dark:text-indigo-400': isTrafficTab || dataHover.data < 5,
+ 'dark:text-red-400': !isTrafficTab && dataHover.data >= 5,
+ })}
+ >
+ {isTrafficTab ? dataHover.data : getStringFromTime(getTimeFromSeconds(dataHover.data), true)}
+ </strong>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
+
+InteractiveMap.propTypes = {
+ onClickCountry: PropTypes.func,
+ data: PropTypes.objectOf(PropTypes.number),
+ total: PropTypes.number,
+}
+
+InteractiveMap.defaultProps = {
+ data: {},
+ onClickCountry: () => { },
+ total: 0,
+}
+
+export default memo(InteractiveMap)
diff --git a/src/pages/Captcha/View/components/LiveVisitorsDropdown.jsx b/src/pages/Captcha/View/components/LiveVisitorsDropdown.jsx
new file mode 100644
index 000000000..dbe4269a0
--- /dev/null
+++ b/src/pages/Captcha/View/components/LiveVisitorsDropdown.jsx
@@ -0,0 +1,87 @@
+import React, { useState, useEffect } from 'react'
+import _map from 'lodash/map'
+import { useTranslation } from 'react-i18next'
+import OutsideClickHandler from 'react-outside-click-handler'
+import {
+ ChevronDownIcon, ChevronUpIcon, XMarkIcon,
+} from '@heroicons/react/24/outline'
+import Flag from 'react-flagkit'
+
+import { getLiveVisitorsInfo } from 'api'
+
+const LiveVisitorsDropdown = ({ live, projectId }) => {
+ const { t } = useTranslation()
+ const [show, setShow] = useState(false)
+ const [liveInfo, setLiveInfo] = useState([])
+ const [loading, setLoading] = useState(true)
+
+ const getLiveVisitors = async () => {
+ await getLiveVisitorsInfo(projectId)
+ .then((res) => {
+ setLiveInfo(res)
+ })
+ .catch((err) => {
+ console.log(err)
+ })
+ .finally(() => {
+ setLoading(false)
+ })
+ }
+
+ useEffect(() => {
+ if (show) {
+ getLiveVisitors()
+ }
+ }, [show]) // eslint-disable-line react-hooks/exhaustive-deps
+
+ return (
+ <OutsideClickHandler
+ onOutsideClick={() => setShow(false)}
+ >
+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl cursor-pointer' onClick={() => setShow(!show)}>
+ {live}
+ {' '}
+ {show ? <ChevronUpIcon className='inline w-5 h-5' /> : <ChevronDownIcon className='inline w-5 h-5' />}
+ </p>
+ {show && (
+ <div className='absolute z-10 mt-2 right-0 top-20 text-gray-900 bg-white border border-gray-200 rounded-md shadow-lg dark:bg-gray-800 dark:border-gray-700 min-w-[250px] max-h-[200px] overflow-scroll'>
+ <div className='flex flex-col w-full p-2'>
+ <p className='text-sm font-semibold text-gray-900 dark:text-gray-50'>
+ {t('dashboard.liveVisitors')}
+ </p>
+ {loading ? (
+ <p className='text-sm text-gray-900 dark:text-gray-50'>
+ {t('common.loading')}
+ </p>
+ ) : (
+ _map(liveInfo, ({
+ dv, br, os, cc,
+ }, index) => (
+ <div key={`${dv}${br}${os}${cc}${index}`} className='flex flex-row items-center justify-between w-full p-2 mt-2 text-sm text-gray-900 bg-gray-100 rounded-md dark:text-gray-50 dark:bg-gray-700'>
+ <div className='flex flex-row items-center'>
+ <Flag
+ className='rounded-sm mr-2'
+ country={cc}
+ size={21}
+ alt=''
+ aria-hidden='true'
+ />
+ <p className='mr-2'>{os}</p>
+ <p className='mr-2'>{br}</p>
+ <p className='mr-2 capitalize'>{dv}</p>
+ </div>
+ <p className='text-xs font-semibold text-green-500'>
+ {t('dashboard.live')}
+ </p>
+ </div>
+ ))
+ )}
+ </div>
+ <XMarkIcon className='absolute top-2 right-2 w-5 h-5 text-gray-900 cursor-pointer dark:text-gray-50' onClick={() => setShow(!show)} />
+ </div>
+ )}
+ </OutsideClickHandler>
+ )
+}
+
+export default LiveVisitorsDropdown
diff --git a/src/pages/Captcha/View/components/NoEvents.jsx b/src/pages/Captcha/View/components/NoEvents.jsx
new file mode 100644
index 000000000..b89ef0282
--- /dev/null
+++ b/src/pages/Captcha/View/components/NoEvents.jsx
@@ -0,0 +1,123 @@
+import React, {
+ memo, useEffect, useState, useRef,
+} from 'react'
+import { useTranslation, Trans } from 'react-i18next'
+import Prism from 'prismjs'
+import { ClipboardDocumentIcon } from '@heroicons/react/24/outline'
+import _isEmpty from 'lodash/isEmpty'
+import PropTypes from 'prop-types'
+
+import Code from 'ui/Code'
+import Button from 'ui/Button'
+import { getUMDBuildExample } from 'pages/Docs/examples'
+import { DOCS_URL } from 'redux/constants'
+
+/**
+ * This component is used to display text if the data is not available.
+ *
+ * @param {array} filters - Active filters.
+ * @param {function} resetFilters - Callback to reset all filters.
+ * @param {string} pid - Project ID.
+ * @returns {JSX.Element}
+ */
+const NoEvents = ({
+ filters, resetFilters, pid,
+}) => {
+ const { t } = useTranslation('common')
+ const [copied, setCopied] = useState(false)
+ const umdBuildExample = getUMDBuildExample(pid)
+
+ const copyTimerRef = useRef(null)
+
+ const setToClipboard = (value) => {
+ if (!copied) {
+ navigator.clipboard.writeText(value)
+ setCopied(true)
+ copyTimerRef.current = setTimeout(() => {
+ setCopied(false)
+ }, 2000)
+ }
+ }
+
+ useEffect(() => {
+ Prism.highlightAll()
+
+ return () => {
+ clearTimeout(copyTimerRef.current)
+ }
+ }, [])
+
+ return (
+ <div className='flex flex-col py-6 sm:px-6 lg:px-8 mt-5'>
+ <div className='max-w-7xl w-full mx-auto text-gray-900 dark:text-gray-50'>
+ <h2 className='text-4xl text-center leading-tight my-3'>
+ {t('project.noEvTitle')}
+ </h2>
+ <h2 className='text-2xl mb-8 text-center leading-snug'>
+ <Trans
+ t={t}
+ i18nKey='project.noEvContent'
+ components={{
+ // eslint-disable-next-line jsx-a11y/anchor-has-content
+ url: <a href={DOCS_URL} className='hover:underline text-blue-600' target='_blank' rel='noreferrer noopener' />,
+ }}
+ />
+ </h2>
+ {!_isEmpty(filters) && (
+ <div className='!flex !mx-auto'>
+ <Button
+ onClick={resetFilters}
+ className='!flex !mx-auto'
+ primary
+ giant
+ >
+ {t('project.resetFilters')}
+ </Button>
+ </div>
+ )}
+ {_isEmpty(filters) && (
+ <>
+ <hr className='mt-3 mb-2 border-gray-200 dark:border-gray-600' />
+ <h2 className='text-2xl mb-2 text-center leading-snug'>
+ {t('project.codeExample')}
+ </h2>
+ <div className='relative'>
+ <Code text={umdBuildExample} language='html' />
+ <div className='absolute top-3 right-5'>
+ <Button
+ type='button'
+ onClick={() => setToClipboard(umdBuildExample)}
+ className='opacity-80 hover:opacity-100'
+ noBorder
+ >
+ <ClipboardDocumentIcon className='w-6 h-6 text-gray-100' />
+ {copied && (
+ <div className='animate-appear cursor-auto rounded p-1 absolute sm:top-0 top-0.5 right-8 text-xs text-green-500'>
+ {t('common.copied')}
+ </div>
+ )}
+ </Button>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
+
+NoEvents.propTypes = {
+ filters: PropTypes.arrayOf(PropTypes.shape({
+ column: PropTypes.string,
+ filter: PropTypes.string,
+ isExclusive: PropTypes.bool,
+ })),
+ resetFilters: PropTypes.func.isRequired,
+ pid: PropTypes.string.isRequired,
+}
+
+NoEvents.defaultProps = {
+ filters: [],
+}
+
+export default memo(NoEvents)
diff --git a/src/pages/Captcha/View/components/RefRow.jsx b/src/pages/Captcha/View/components/RefRow.jsx
new file mode 100644
index 000000000..9847c7956
--- /dev/null
+++ b/src/pages/Captcha/View/components/RefRow.jsx
@@ -0,0 +1,57 @@
+import React, { memo } from 'react'
+import _isEmpty from 'lodash/isEmpty'
+import PropTypes from 'prop-types'
+
+/**
+ * Component that renders a link row in the 'Referrer' panel.
+ *
+ * @param {string} rowName - A link itself (e.g. https://google.com) to render in the row.
+ * @param {boolean} showIcons - Whether to show favicon icons near links or not.
+ * @returns {JSX.Element}
+ */
+const RefRow = ({ rowName, showIcons }) => {
+ let isUrl = true
+ let url = rowName
+
+ try {
+ url = new URL(rowName)
+ } catch {
+ isUrl = false
+ }
+
+ return (
+ <div>
+ {showIcons && isUrl && !_isEmpty(url.hostname) && (
+ <img
+ className='w-5 h-5 mr-1.5 float-left'
+ src={`https://icons.duckduckgo.com/ip3/${url.hostname}.ico`}
+ alt=''
+ aria-hidden='true'
+ />
+ )}
+ {isUrl ? (
+ <a
+ className='flex label overflow-visible hover:underline text-blue-600 dark:text-blue-500'
+ href={rowName}
+ target='_blank'
+ rel='noopener noreferrer nofollow'
+ onClick={(e) => e.stopPropagation()}
+ aria-label={`${rowName} (opens in a new tab)`}
+ >
+ {rowName}
+ </a>
+ ) : (
+ <span className='flex label overflow-visible hover:underline text-blue-600 dark:text-blue-500'>
+ {rowName}
+ </span>
+ )}
+ </div>
+ )
+}
+
+RefRow.propTypes = {
+ rowName: PropTypes.string.isRequired,
+ showIcons: PropTypes.bool.isRequired,
+}
+
+export default memo(RefRow)
diff --git a/src/pages/Captcha/View/index.jsx b/src/pages/Captcha/View/index.jsx
new file mode 100644
index 000000000..0c9f97005
--- /dev/null
+++ b/src/pages/Captcha/View/index.jsx
@@ -0,0 +1,3 @@
+import ViewProject from './ViewCaptcha.container'
+
+export default ViewProject
diff --git a/src/pages/Captcha/View/styles.css b/src/pages/Captcha/View/styles.css
new file mode 100644
index 000000000..f8a7a141b
--- /dev/null
+++ b/src/pages/Captcha/View/styles.css
@@ -0,0 +1,7 @@
+html.dark .bb-legend-item text {
+ fill: #f9fafb;
+}
+
+html.dark .bb-axis {
+ fill: #f9fafb;
+}
diff --git a/src/pages/Dashboard/Dashboard.jsx b/src/pages/Dashboard/Dashboard.jsx
index 564306967..7b2f6f654 100644
--- a/src/pages/Dashboard/Dashboard.jsx
+++ b/src/pages/Dashboard/Dashboard.jsx
@@ -191,7 +191,7 @@ const Dashboard = ({
const onNewProject = () => {
if (user.isActive || isSelfhosted) {
if (dashboardTabs === tabForCaptchaProject) {
- history.push('/dashboard/captcha/new')
+ history.push(routes.new_captcha)
} else {
history.push(routes.new_project)
}
@@ -201,7 +201,7 @@ const Dashboard = ({
}
useEffect(() => {
- if (sharedTotal <= 0) {
+ if (sharedTotal <= 0 && tabProjects === tabForSharedProject) {
setDashboardTabs(tabForOwnedProject)
setTabProjects(tabForOwnedProject)
}
@@ -257,24 +257,43 @@ const Dashboard = ({
</span>
</div>
<div className='mt-6'>
- {sharedTotal > 0 && (
<nav className='-mb-px flex space-x-8'>
- {_map(tabsForDashboard, (tab) => (
- <button
- key={tab.name}
- type='button'
- onClick={() => setTabProjects(tab.name)}
- className={cx('whitespace-nowrap pb-4 px-1 border-b-2 font-medium text-md', {
- 'border-indigo-500 text-indigo-600 dark:text-indigo-500': tabProjects === tab.name,
- 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300 dark:hover:border-gray-300': tabProjects !== tab.name,
- })}
- aria-current={tab.name === tabProjects ? 'page' : undefined}
- >
- {t(tab.label)}
- </button>
- ))}
+ {_map(tabsForDashboard, (tab) => {
+ if (tab.name === tabForSharedProject) {
+ if (sharedTotal > 0) {
+ return (
+ <button
+ key={tab.name}
+ type='button'
+ onClick={() => setTabProjects(tab.name)}
+ className={cx('whitespace-nowrap pb-4 px-1 border-b-2 font-medium text-md', {
+ 'border-indigo-500 text-indigo-600 dark:text-indigo-500': tabProjects === tab.name,
+ 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300 dark:hover:border-gray-300': tabProjects !== tab.name,
+ })}
+ aria-current={tab.name === tabProjects ? 'page' : undefined}
+ >
+ {t(tab.label)}
+ </button>
+ )
+ }
+ return null
+ }
+ return (
+ <button
+ key={tab.name}
+ type='button'
+ onClick={() => setTabProjects(tab.name)}
+ className={cx('whitespace-nowrap pb-4 px-1 border-b-2 font-medium text-md', {
+ 'border-indigo-500 text-indigo-600 dark:text-indigo-500': tabProjects === tab.name,
+ 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300 dark:hover:border-gray-300': tabProjects !== tab.name,
+ })}
+ aria-current={tab.name === tabProjects ? 'page' : undefined}
+ >
+ {t(tab.label)}
+ </button>
+ )
+ })}
</nav>
- )}
</div>
{isLoading ? (
<Title title={t('titles.dashboard')}>
diff --git a/src/routes.js b/src/routes.js
index d50c739f2..10cbaaa66 100644
--- a/src/routes.js
+++ b/src/routes.js
@@ -10,7 +10,9 @@ const routes = Object.freeze({
verify: '/verify/:id',
change_email: '/change-email/:id',
new_project: '/projects/new',
+ new_captcha: '/captchas/new',
project_settings: '/projects/settings/:id',
+ captcha_settings: '/captchas/settings/:id',
project: '/projects/:id',
features: '/features',
billing: '/billing',