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!

projects to remix

Maksim Mrugbdbac5a5e8f3
diff --git a/app/api/index.ts b/app/api/index.ts
index 63e7de455..4ed395deb 100644
--- a/app/api/index.ts
+++ b/app/api/index.ts
@@ -29,7 +29,7 @@ const envApiURL = process.env.REACT_APP_RUNNING_DEV_SCRIPT === 'true'
const baseURL: string = isSelfhosted ? window.env.API_URL : envApiURL
const api = axios.create({
- baseURL,
+ baseURL: 'https://api.swetrix.com/',
})
// Function that will be called to refresh authorization
diff --git a/app/modals/PaidFeature.tsx b/app/modals/PaidFeature.tsx
index 1a5eea186..f7505cc21 100644
--- a/app/modals/PaidFeature.tsx
+++ b/app/modals/PaidFeature.tsx
@@ -1,10 +1,10 @@
import React from 'react'
-import { useHistory } from 'react-router-dom'
+import { useNavigate } from '@remix-run/react'
import { useTranslation } from 'react-i18next'
import PropTypes from 'prop-types'
import Modal from 'ui/Modal'
-import routes from 'routes'
+import routes from 'routesPath'
const PaidFeature = ({ onClose, isOpened }: {
onClose: () => void,
@@ -13,10 +13,10 @@ const PaidFeature = ({ onClose, isOpened }: {
const { t }: {
t: (key: string, options?: { [key: string]: string | number }) => string,
} = useTranslation('common')
- const history = useHistory()
+ const navigate = useNavigate()
const onSubmit = () => {
- history.push(routes.billing)
+ navigate(routes.billing)
}
return (
diff --git a/app/routes/project/ProjectProtectedPassword/index.tsx b/app/routes/project/ProjectProtectedPassword/index.tsx
new file mode 100644
index 000000000..69255d11b
--- /dev/null
+++ b/app/routes/project/ProjectProtectedPassword/index.tsx
@@ -0,0 +1,148 @@
+import React, { useState, useEffect, memo } from 'react'
+import { useNavigate, useParams } from '@remix-run/react'
+import { useTranslation } from 'react-i18next'
+import _keys from 'lodash/keys'
+import _isEmpty from 'lodash/isEmpty'
+import _size from 'lodash/size'
+import _replace from 'lodash/replace'
+
+import routes from 'routesPath'
+import Input from 'ui/Input'
+import Button from 'ui/Button'
+import { checkPassword } from 'api'
+import { useDispatch } from 'react-redux'
+import UIActions from 'redux/reducers/ui'
+
+interface IProjectProtectedPasswordForm {
+ password: string,
+}
+
+const MAX_PASSWORD_LENGTH = 80
+
+const ProjectProtectedPassword = (): JSX.Element => {
+ const { t }: {
+ t: (key: string, optinions?: {
+ [key: string]: string | number,
+ }) => string,
+ } = useTranslation('common')
+ const [form, setForm] = useState<IProjectProtectedPasswordForm>({
+ password: '',
+ })
+ const [validated, setValidated] = useState<boolean>(false)
+ const [errors, setErrors] = useState<{
+ password?: string,
+ }>({})
+ const { id }: {
+ id: string
+ } = useParams()
+ const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)
+ const [isLoading, setIsLoading] = useState<boolean>(false)
+ const navigate = useNavigate()
+ const dispatch = useDispatch()
+
+ const validate = () => {
+ const allErrors = {} as {
+ password?: string,
+ }
+
+ if (_isEmpty(form.password)) {
+ allErrors.password = t('apiNotifications.enterPassword')
+ }
+
+ if (_size(form.password) >= MAX_PASSWORD_LENGTH) {
+ allErrors.password = t('auth.common.passwordTooLong', { amount: MAX_PASSWORD_LENGTH })
+ }
+
+ const valid = _isEmpty(_keys(allErrors))
+
+ setErrors(allErrors)
+ setValidated(valid)
+ }
+
+ useEffect(() => {
+ validate()
+ }, [form]) // eslint-disable-line
+
+ const onSubmit = async (data: IProjectProtectedPasswordForm) => {
+ if (!isLoading) {
+ setIsLoading(true)
+ await checkPassword(id, data.password)
+ .then((res) => {
+ if (res) {
+ dispatch(UIActions.setProjectProtectedPassword({
+ id,
+ password: data.password,
+ }))
+ navigate(_replace(routes.project, ':id', id))
+ }
+ setErrors({
+ password: t('apiNotifications.incorrectPassword'),
+ })
+ })
+ .catch((err) => {
+ console.log(err)
+ })
+ .finally(() => {
+ setIsLoading(false)
+ })
+ }
+ }
+
+ const handleInput = ({ target }: {
+ target: HTMLInputElement,
+ }) => {
+ const value = target.type === 'checkbox' ? target.checked : target.value
+
+ setForm(oldForm => ({
+ ...oldForm,
+ [target.name]: value,
+ }))
+ }
+
+ const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault()
+ e.stopPropagation()
+ setBeenSubmitted(true)
+
+ if (validated) {
+ onSubmit(form)
+ }
+ }
+
+ const onCancel = () => {
+ navigate(routes.main)
+ }
+
+ return (
+ <div>
+ <div className='min-h-page bg-gray-50 dark:bg-slate-900 flex flex-col py-6 px-4 sm:px-6 lg:px-8'>
+ <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'>
+ {t('titles.passwordProtected')}
+ </h2>
+ <Input
+ name='password'
+ id='password'
+ type='password'
+ label={t('auth.common.password')}
+ value={form.password}
+ placeholder={t('auth.common.password')}
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted && errors.password}
+ />
+ <div className='mt-5'>
+ <Button className='mr-2 border-indigo-100 dark:text-gray-50 dark:border-slate-700/50 dark:bg-slate-800 dark:hover:bg-slate-700' onClick={onCancel} secondary regular>
+ {t('common.cancel')}
+ </Button>
+ <Button type='submit' loading={isLoading} primary regular>
+ {t('common.continue')}
+ </Button>
+ </div>
+ </form>
+ </div>
+ </div>
+ )
+}
+
+export default memo(ProjectProtectedPassword)
diff --git a/app/routes/project/alerts/settings/$id.$pid.tsx b/app/routes/project/alerts/settings/$id.$pid.tsx
new file mode 100644
index 000000000..11117ef3e
--- /dev/null
+++ b/app/routes/project/alerts/settings/$id.$pid.tsx
@@ -0,0 +1,3 @@
+import ProjectAlertsSettings from './__ProjectAlertsSettings.container'
+
+export default ProjectAlertsSettings
diff --git a/app/routes/project/alerts/settings/__ProjectAlertsSettings.container.tsx b/app/routes/project/alerts/settings/__ProjectAlertsSettings.container.tsx
new file mode 100644
index 000000000..aa81850ab
--- /dev/null
+++ b/app/routes/project/alerts/settings/__ProjectAlertsSettings.container.tsx
@@ -0,0 +1,37 @@
+import { connect } from 'react-redux'
+import { errorsActions } from 'redux/reducers/errors'
+import UIActions from 'redux/reducers/ui'
+import { StateType, AppDispatch } from 'redux/store'
+import { IAlerts } from 'redux/models/IAlerts'
+import { alertsActions } from 'redux/reducers/alerts'
+import ProjectAlerts from './__ProjectAlertsSettings'
+
+const mapStateToProps = (state: StateType) => ({
+ alerts: state.ui.alerts.alerts,
+ user: state.auth.user,
+ total: state.ui.alerts.total,
+})
+
+const mapDispatchToProps = (dispatch: AppDispatch) => ({
+ showError: (message: string) => {
+ dispatch(errorsActions.genericError({
+ message,
+ }))
+ },
+ generateAlerts: (message: string) => {
+ dispatch(alertsActions.generateAlerts({
+ message,
+ type: 'success',
+ }))
+ },
+ setProjectAlerts: (alerts: IAlerts[]) => {
+ dispatch(UIActions.setProjectAlerts(alerts))
+ },
+ setProjectAlertsTotal: (total: number) => {
+ dispatch(UIActions.setProjectAlertsTotal({
+ total,
+ }))
+ },
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(ProjectAlerts)
diff --git a/app/routes/project/alerts/settings/__ProjectAlertsSettings.tsx b/app/routes/project/alerts/settings/__ProjectAlertsSettings.tsx
new file mode 100644
index 000000000..3ca903fca
--- /dev/null
+++ b/app/routes/project/alerts/settings/__ProjectAlertsSettings.tsx
@@ -0,0 +1,384 @@
+/* eslint-disable react/forbid-prop-types */
+import React, { useEffect, useMemo, useState } from 'react'
+import {
+ useNavigate, useParams, useLocation, Link,
+} from '@remix-run/react'
+import { useTranslation, Trans } from 'react-i18next'
+import { ExclamationTriangleIcon } from '@heroicons/react/24/outline'
+import PropTypes from 'prop-types'
+
+import _isEmpty from 'lodash/isEmpty'
+import _size from 'lodash/size'
+import _replace from 'lodash/replace'
+import _find from 'lodash/find'
+import _split from 'lodash/split'
+import _keys from 'lodash/keys'
+import _filter from 'lodash/filter'
+import _reduce from 'lodash/reduce'
+import _values from 'lodash/values'
+import _findKey from 'lodash/findKey'
+import _toNumber from 'lodash/toNumber'
+import { clsx as cx } from 'clsx'
+import Input from 'ui/Input'
+import Button from 'ui/Button'
+import Checkbox from 'ui/Checkbox'
+import Modal from 'ui/Modal'
+import {
+ PROJECT_TABS, QUERY_CONDITION, QUERY_METRIC, QUERY_TIME,
+} from 'redux/constants'
+import {
+ createAlert, updateAlert, deleteAlert, ICreateAlert,
+} from 'api'
+import { withAuthentication, auth } from 'hoc/protected'
+import routes from 'routesPath'
+import Select from 'ui/Select'
+import { IAlerts } from 'redux/models/IAlerts'
+import { IUser } from 'redux/models/IUser'
+
+const INTEGRATIONS_LINK = `${routes.user_settings}#integrations`
+
+const ProjectAlertsSettings = ({
+ alerts, setProjectAlerts, showError, user, setProjectAlertsTotal, total, generateAlerts,
+}: {
+ alerts: IAlerts[]
+ setProjectAlerts: (item: IAlerts[]) => void
+ showError: (message: string) => void
+ user: IUser
+ setProjectAlertsTotal: (num: number) => void
+ total: number
+ generateAlerts: (message: string) => void
+}): JSX.Element => {
+ const navigate = useNavigate()
+ const { id, pid }: {
+ id: string
+ pid: string
+ } = useParams()
+ const { pathname }: {
+ pathname: string
+ } = useLocation()
+ const { t }: {
+ t: (key: string, options?: {
+ [key: string]: string | number | null | undefined
+ }) => string
+ } = useTranslation('common')
+ const isSettings: boolean = !_isEmpty(id) && (_replace(_replace(routes.alert_settings, ':id', id), ':pid', pid) === pathname)
+ const alert = useMemo(() => _find(alerts, { id }), [alerts, id])
+ const [form, setForm] = useState<Partial<IAlerts>>({
+ pid,
+ name: '',
+ queryTime: QUERY_TIME.LAST_1_HOUR,
+ queryCondition: QUERY_CONDITION.GREATER_THAN,
+ queryMetric: QUERY_METRIC.PAGE_VIEWS,
+ active: true,
+ })
+ const [validated, setValidated] = useState<boolean>(false)
+ const [errors, setErrors] = useState<{
+ [key: string]: string
+ }>({})
+ const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)
+ const [showModal, setShowModal] = useState<boolean>(false)
+
+ const isIntegrationLinked = useMemo(() => {
+ return !_isEmpty(user) && user.telegramChatId && user.isTelegramChatIdConfirmed
+ }, [user])
+
+ const queryTimeTMapping: {
+ [key: string]: string
+ } = useMemo(() => {
+ const values = _values(QUERY_TIME)
+
+ return _reduce(values, (prev, curr) => {
+ const [, amount, metric] = _split(curr, '_')
+ let translated
+
+ if (metric === 'minutes') {
+ translated = t('alert.xMinutes', { amount })
+ }
+
+ if (metric === 'hour') {
+ translated = t('alert.xHour', { amount })
+ }
+
+ if (metric === 'hours') {
+ translated = t('alert.xHours', { amount })
+ }
+
+ return {
+ ...prev,
+ [curr]: translated,
+ }
+ }, {})
+ }, [t])
+
+ const queryConditionTMapping: {
+ [key: string]: string
+ } = useMemo(() => {
+ const values = _values(QUERY_CONDITION)
+
+ return _reduce(values, (prev, curr) => ({
+ ...prev,
+ [curr]: t(`alert.conditions.${curr}`),
+ }), {})
+ }, [t])
+
+ const queryMetricTMapping: {
+ [key: string]: string
+ } = useMemo(() => {
+ const values = _values(QUERY_METRIC)
+
+ return _reduce(values, (prev, curr) => ({
+ ...prev,
+ [curr]: t(`alert.metrics.${curr}`),
+ }), {})
+ }, [t])
+
+ useEffect(() => {
+ if (!_isEmpty(alert)) {
+ setForm(alert)
+ }
+ }, [alert])
+
+ const validate = () => {
+ const allErrors: {
+ [key: string]: string
+ } = {}
+
+ if (_isEmpty(form.name) || _size(form.name) < 3) {
+ allErrors.name = t('profileSettings.nameError')
+ }
+
+ if (Number.isNaN(_toNumber(form.queryValue))) {
+ allErrors.queryValue = t('alertsSettings.queryValueError')
+ }
+
+ const valid = _isEmpty(_keys(allErrors))
+
+ setErrors(allErrors)
+ setValidated(valid)
+ }
+
+ const onSubmit = (data: Partial<IAlerts>) => {
+ if (isSettings) {
+ updateAlert(id, data)
+ .then((res) => {
+ navigate(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)
+ setProjectAlerts([..._filter(alerts, (a) => a.id !== id), res])
+ generateAlerts(t('alertsSettings.alertUpdated'))
+ })
+ .catch((err) => {
+ showError(err.message || err || 'Something went wrong')
+ })
+ } else {
+ createAlert(data as ICreateAlert)
+ .then((res) => {
+ navigate(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)
+ setProjectAlerts([...alerts, res])
+ setProjectAlertsTotal(total + 1)
+ generateAlerts(t('alertsSettings.alertCreated'))
+ })
+ .catch((err) => {
+ showError(err.message || err || 'Something went wrong')
+ })
+ }
+ }
+
+ const onDelete = () => {
+ deleteAlert(id)
+ .then(() => {
+ setProjectAlerts(_filter(alerts, (a) => a.id !== id))
+ setProjectAlertsTotal(total - 1)
+ navigate(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)
+ generateAlerts(t('alertsSettings.alertDeleted'))
+ })
+ .catch((err) => {
+ showError(err.message || err || 'Something went wrong')
+ })
+ }
+
+ const onCancel = () => {
+ navigate(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)
+ }
+
+ useEffect(() => {
+ validate()
+ }, [form]) // eslint-disable-line
+
+ const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const { target } = event
+ const value = target.type === 'checkbox' ? target.checked : target.value
+
+ setForm(prevForm => ({
+ ...prevForm,
+ [target.name]: value,
+ }))
+ }
+
+ const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault()
+ e.stopPropagation()
+ setBeenSubmitted(true)
+
+ if (validated) {
+ onSubmit(form)
+ }
+ }
+
+ const title = isSettings ? t('alert.settingsOf', {
+ name: form.name,
+ }) : t('alert.create')
+
+ return (
+ <div>
+ <div
+ className={cx('min-h-min-footer bg-gray-50 dark:bg-slate-900 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>
+ {!isIntegrationLinked && (
+ <div className='flex items-center bg-blue-50 dark:text-gray-50 dark:bg-slate-800 rounded px-5 py-3 mt-2 whitespace-pre-wrap text-base'>
+ <ExclamationTriangleIcon className='w-5 h-5 mr-1' />
+ <Trans
+ // @ts-ignore
+ t={t}
+ i18nKey='alert.noIntegration'
+ components={{
+ url: <Link to={INTEGRATIONS_LINK} className='hover:underline text-blue-600 dark:text-blue-500' />,
+ }}
+ />
+ </div>
+ )}
+ <Input
+ name='name'
+ id='name'
+ type='text'
+ label={t('alert.name')}
+ value={form.name || ''}
+ placeholder={t('alert.name')}
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.name : null}
+ />
+ <Checkbox
+ checked={Boolean(form.active)}
+ onChange={handleInput}
+ name='active'
+ id='active'
+ className='mt-4'
+ label={t('alert.enabled')}
+ hint={t('alert.enabledHint')}
+ />
+ <div className='mt-4'>
+ <Select
+ id='queryMetric'
+ label={t('alert.metric')}
+ items={_values(queryMetricTMapping)}
+ title={form.queryMetric ? queryMetricTMapping[form.queryMetric] : ''}
+ onSelect={(item) => {
+ const key = _findKey(queryMetricTMapping, predicate => predicate === item)
+
+ setForm(prevForm => ({
+ ...prevForm,
+ queryMetric: key,
+ }))
+ }}
+ />
+ </div>
+ <div className='mt-4'>
+ <Select
+ id='queryCondition'
+ label={t('alert.condition')}
+ items={_values(queryConditionTMapping)}
+ title={form.queryCondition ? queryConditionTMapping[form.queryCondition] : ''}
+ onSelect={(item) => {
+ const key = _findKey(queryConditionTMapping, predicate => predicate === item)
+
+ setForm(prevForm => ({
+ ...prevForm,
+ queryCondition: key,
+ }))
+ }}
+ />
+ </div>
+ <Input
+ name='queryValue'
+ id='queryValue'
+ type='text'
+ label={t('alert.threshold')}
+ value={form.queryValue || ''}
+ placeholder='10'
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.queryValue : null}
+ />
+ <div className='mt-4'>
+ <Select
+ id='queryTime'
+ label={t('alert.time')}
+ items={_values(queryTimeTMapping)}
+ title={form.queryTime ? queryTimeTMapping[form.queryTime] : ''}
+ onSelect={(item) => {
+ const key = _findKey(queryTimeTMapping, predicate => predicate === item)
+
+ setForm(prevForm => ({
+ ...prevForm,
+ queryTime: key,
+ }))
+ }}
+ />
+ </div>
+ {isSettings ? (
+ <div className='flex justify-between items-center mt-5'>
+ <Button onClick={() => setShowModal(true)} danger semiSmall>
+ <>
+ <ExclamationTriangleIcon className='w-5 h-5 mr-1' />
+ {t('alert.delete')}
+ </>
+ </Button>
+ <div className='flex justify-between items-center'>
+ <Button className='mr-2 border-indigo-100 dark:text-gray-50 dark:border-slate-700/50 dark:bg-slate-800 dark:hover:bg-slate-700' onClick={onCancel} secondary regular>
+ {t('common.cancel')}
+ </Button>
+ <Button type='submit' primary regular>
+ {t('common.save')}
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className='mt-5 flex justify-between items-center'>
+ <Button className='mr-2 border-indigo-100 dark:text-gray-50 dark:border-slate-700/50 dark:bg-slate-800 dark:hover:bg-slate-700' onClick={onCancel} secondary regular>
+ {t('common.cancel')}
+ </Button>
+ <Button type='submit' primary regular>
+ {t('common.save')}
+ </Button>
+ </div>
+ )}
+ </form>
+ <Modal
+ onClose={() => setShowModal(false)}
+ onSubmit={onDelete}
+ submitText={t('alert.delete')}
+ closeText={t('common.close')}
+ title={t('alert.qDelete')}
+ message={t('alert.deleteHint')}
+ submitType='danger'
+ type='error'
+ isOpened={showModal}
+ />
+ </div>
+ </div>
+ )
+}
+
+ProjectAlertsSettings.propTypes = {
+ alerts: PropTypes.array.isRequired,
+ setProjectAlerts: PropTypes.func.isRequired,
+ showError: PropTypes.func.isRequired,
+ user: PropTypes.object.isRequired,
+}
+
+export default withAuthentication(ProjectAlertsSettings, auth.authenticated)
diff --git a/app/routes/project/alerts/view/__ProjectAlertsView.container.tsx b/app/routes/project/alerts/view/__ProjectAlertsView.container.tsx
new file mode 100644
index 000000000..a32d04a6c
--- /dev/null
+++ b/app/routes/project/alerts/view/__ProjectAlertsView.container.tsx
@@ -0,0 +1,13 @@
+import { connect } from 'react-redux'
+import { StateType } from 'redux/store'
+import ProjectAlerts from './__ProjectAlertsView'
+
+const mapStateToProps = (state: StateType) => ({
+ alerts: state.ui.alerts.alerts,
+ loading: state.ui.alerts.loading,
+ user: state.auth.user,
+ total: state.ui.alerts.total,
+ authenticated: state.auth.authenticated,
+})
+
+export default connect(mapStateToProps)(ProjectAlerts)
diff --git a/app/routes/project/alerts/view/__ProjectAlertsView.tsx b/app/routes/project/alerts/view/__ProjectAlertsView.tsx
new file mode 100644
index 000000000..f89093c58
--- /dev/null
+++ b/app/routes/project/alerts/view/__ProjectAlertsView.tsx
@@ -0,0 +1,214 @@
+/* eslint-disable react/forbid-prop-types */
+import React, {
+ useMemo, memo, useState,
+} from 'react'
+import dayjs from 'dayjs'
+import _map from 'lodash/map'
+import _isEmpty from 'lodash/isEmpty'
+import _replace from 'lodash/replace'
+import _values from 'lodash/values'
+import _reduce from 'lodash/reduce'
+import _filter from 'lodash/filter'
+import _trucate from 'lodash/truncate'
+import { useNavigate } from '@remix-run/react'
+import { useTranslation } from 'react-i18next'
+import PropTypes from 'prop-types'
+import {
+ BellIcon, CurrencyDollarIcon, PencilSquareIcon, FolderPlusIcon,
+} from '@heroicons/react/24/outline'
+
+import routes from 'routesPath'
+import Button from 'ui/Button'
+import PaidFeature from 'modals/PaidFeature'
+import { QUERY_METRIC, PLAN_LIMITS } from 'redux/constants'
+import { IAlerts } from 'redux/models/IAlerts'
+import { IUser } from 'redux/models/IUser'
+
+const ProjectAlerts = ({
+ projectId, alerts, loading, user, total, authenticated,
+}: {
+ projectId: string,
+ alerts: IAlerts[],
+ loading: boolean,
+ user: IUser,
+ total: number,
+ authenticated: boolean,
+}): JSX.Element => {
+ const { t, i18n: { language } }: {
+ t: (key: string) => string,
+ i18n: { language: string },
+ } = useTranslation()
+ const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState<boolean>(false)
+ const navigate = useNavigate()
+
+ // @ts-ignore
+ const limits = PLAN_LIMITS[user?.planCode] || PLAN_LIMITS.trial
+ const isLimitReached = authenticated && (total >= limits?.maxAlerts)
+
+ const projectAlerts = useMemo(() => {
+ if (loading) return []
+ return _filter(alerts, ({ pid }) => pid === projectId)
+ }, [projectId, alerts, loading])
+
+ const queryMetricTMapping: {
+ [key: string]: string,
+ } = useMemo(() => {
+ const values = _values(QUERY_METRIC)
+
+ return _reduce(values, (prev, curr) => ({
+ ...prev,
+ [curr]: t(`alert.metrics.${curr}`),
+ }), {})
+ }, [t])
+
+ const isIntegrationLinked = useMemo(() => {
+ return !_isEmpty(user) && user.telegramChatId && user.isTelegramChatIdConfirmed
+ }, [user])
+
+ const handleNewAlert = () => {
+ if (isLimitReached) {
+ setIsPaidFeatureOpened(true)
+ return
+ }
+
+ navigate(_replace(routes.create_alert, ':pid', projectId))
+ }
+
+ return (
+ <div>
+ <div className='flex justify-between items-center mt-4'>
+ {!loading && !_isEmpty(projectAlerts) && (
+ <>
+ <h2 className='text-2xl font-bold dark:text-white text-gray-800'>
+ {t('dashboard.alerts')}
+ </h2>
+ <Button
+ type='button'
+ primary
+ large
+ onClick={handleNewAlert}
+ >
+ <>
+ {isLimitReached ? (
+ <CurrencyDollarIcon className='w-5 h-5 mr-1' />
+ ) : (
+ <FolderPlusIcon className='w-5 h-5 mr-1' />
+ )}
+ {t('alert.add')}
+ </>
+ </Button>
+ </>
+ )}
+ </div>
+ <div className='mt-4'>
+ {loading && (
+ <div>
+ {t('common.loading')}
+ </div>
+ )}
+ {(!loading && _isEmpty(projectAlerts)) && (
+ <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>
+ <Button
+ onClick={handleNewAlert}
+ className='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'
+ secondary
+ large
+ >
+ <>
+ {isLimitReached && (
+ <CurrencyDollarIcon className='w-5 h-5 mr-1' />
+ )}
+ {t('alert.add')}
+ </>
+ </Button>
+ </div>
+ )}
+
+ {(!loading && !_isEmpty(projectAlerts)) && (
+ <table className='w-full mb-3 border-separate border-spacing-y-4'>
+ <tbody>
+ {_map(projectAlerts, ({
+ id, name, queryMetric, lastTriggered,
+ }) => (
+ <tr key={id} className='bg-white dark:bg-slate-900 rounded-lg shadow-lg'>
+ <td className='p-4 pr-0 rounded-l-lg justify-start'>
+ <div className='flex flex-col'>
+ <div className='text-lg font-bold dark:text-white text-gray-800 hidden lg:block'>{name}</div>
+ <div className='text-lg font-bold dark:text-white text-gray-800 hidden md:block lg:hidden'>{_trucate(name, { length: 35 })}</div>
+ <div className='text-lg font-bold dark:text-white text-gray-800 hidden sm:block md:hidden'>{_trucate(name, { length: 20 })}</div>
+ <div className='text-lg font-bold dark:text-white text-gray-800 sm:hidden'>{_trucate(name, { length: 10 })}</div>
+ <div className='text-sm dark:text-gray-400 text-gray-600'>{queryMetricTMapping[queryMetric]}</div>
+ </div>
+
+ </td>
+ <td className='py-4'>
+ <div className='flex flex-col'>
+ <div className='text-sm dark:text-gray-400 text-gray-600'>
+ {t('alert.lastTriggered')}
+ </div>
+ <div className='text-lg font-bold dark:text-white text-gray-800'>
+ {lastTriggered
+ ? (language === 'en'
+ ? dayjs(lastTriggered).locale(language).format('MMMM D, YYYY')
+ : dayjs(lastTriggered).locale(language).format('D MMMM, YYYY'))
+ : t('alert.never')}
+ </div>
+ </div>
+
+ </td>
+ <td className='rounded-r-lg p-4 pl-0'>
+ <div className='flex items-center justify-end'>
+ {!isIntegrationLinked && (
+ <p className='text-gray-800 dark:text-gray-200 text-sm mr-3'>
+ {t('alert.noNotification')}
+ </p>
+ )}
+ <Button
+ onClick={() => {
+ navigate(_replace(_replace(routes.alert_settings, ':pid', projectId), ':id', id))
+ }}
+ className='dark:text-gray-50 dark:bg-slate-800 dark:hover:bg-slate-700'
+ secondary
+ large
+ >
+ <>
+ <PencilSquareIcon className='w-4 h-4 mr-1' />
+ {t('common.edit')}
+ </>
+ </Button>
+ </div>
+
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ <PaidFeature
+ isOpened={isPaidFeatureOpened}
+ onClose={() => setIsPaidFeatureOpened(false)}
+ />
+ </div>
+ )
+}
+
+ProjectAlerts.propTypes = {
+ projectId: PropTypes.string.isRequired,
+ alerts: PropTypes.array.isRequired,
+ loading: PropTypes.bool.isRequired,
+ user: PropTypes.object.isRequired,
+ total: PropTypes.number.isRequired,
+ authenticated: PropTypes.bool.isRequired,
+}
+
+export default memo(ProjectAlerts)
diff --git a/app/routes/project/alerts/view/index.tsx b/app/routes/project/alerts/view/index.tsx
new file mode 100644
index 000000000..3f56d090a
--- /dev/null
+++ b/app/routes/project/alerts/view/index.tsx
@@ -0,0 +1,3 @@
+import ProjectAlertsView from './__ProjectAlertsView.container'
+
+export default ProjectAlertsView
diff --git a/app/routes/project/confirm-share/$id.tsx b/app/routes/project/confirm-share/$id.tsx
new file mode 100644
index 000000000..86ecf2c97
--- /dev/null
+++ b/app/routes/project/confirm-share/$id.tsx
@@ -0,0 +1,113 @@
+import React, { useState, useEffect, memo } from 'react'
+import { useDispatch } from 'react-redux'
+import { useParams, Link } from '@remix-run/react'
+import { useTranslation } from 'react-i18next'
+import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'
+import _split from 'lodash/split'
+
+import sagaActions from 'redux/sagas/actions'
+import Loader from 'ui/Loader'
+import routes from 'routesPath'
+import { AppDispatch } from 'redux/store'
+
+const Page = () => {
+ const { t }: {
+ t: (key: string) => string
+ } = useTranslation('common')
+ const dispatch: AppDispatch = useDispatch()
+ const { id }: {
+ id: string
+ } = useParams()
+ const [loading, setLoading] = useState<boolean>(true)
+ const [error, setError] = useState<string>('')
+
+ useEffect(() => {
+ setLoading(true)
+ const path = _split(window.location.pathname, '/')[1]
+
+ dispatch(
+ sagaActions.shareVerifyAsync(
+ { path, id },
+ () => setLoading(false),
+ (verifyError) => {
+ setError(verifyError)
+ setLoading(false)
+ },
+ ),
+ )
+ }, [id]) // eslint-disable-line
+
+ if (loading) {
+ return (
+ <div>
+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>
+ <Loader />
+ </div>
+ </div>
+ )
+ }
+
+ if (error) {
+ return (
+ <div>
+ <div className='bg-gray-50 dark:bg-slate-900 min-h-page px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
+ <div className='max-w-max mx-auto'>
+ <main className='sm:flex'>
+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
+ <div className='sm:ml-6'>
+ <div className='sm:border-l max-w-prose sm:border-gray-200 sm:pl-6'>
+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight sm:text-5xl'>
+ {error}
+ </h1>
+ </div>
+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
+ <Link
+ to={routes.dashboard}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
+ >
+ {t('common.dashboard')}
+ </Link>
+ <Link
+ to={routes.contact}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-50 dark:bg-slate-800 dark:hover:bg-slate-700 dark:focus:ring-gray-50'
+ >
+ {t('notFoundPage.support')}
+ </Link>
+ </div>
+ </div>
+ </main>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div>
+ <div className='bg-gray-50 dark:bg-slate-900 min-h-page px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
+ <div className='max-w-max mx-auto'>
+ <main className='sm:flex'>
+ <CheckCircleIcon className='h-12 w-12 text-green-500 dark:text-green-400' aria-hidden='true' />
+ <div className='sm:ml-6'>
+ <div className='sm:border-l max-w-prose sm:border-gray-200 sm:pl-6'>
+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight sm:text-5xl'>
+ {t('apiNotifications.acceptInvitation')}
+ </h1>
+ </div>
+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
+ <Link
+ to={routes.dashboard}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
+ >
+ {t('common.dashboard')}
+ </Link>
+ </div>
+ </div>
+ </main>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default memo(Page)
diff --git a/app/routes/project/settings/Emails/ConfirmReportsShare/index.tsx b/app/routes/project/settings/Emails/ConfirmReportsShare/index.tsx
new file mode 100644
index 000000000..753230a1b
--- /dev/null
+++ b/app/routes/project/settings/Emails/ConfirmReportsShare/index.tsx
@@ -0,0 +1,118 @@
+import React, { useState, useEffect, memo } from 'react'
+import { useParams, Link } from '@remix-run/react'
+import { useTranslation } from 'react-i18next'
+import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'
+
+import Loader from 'ui/Loader'
+
+import { confirmSubscriberInvite } from 'api'
+import routes from 'routesPath'
+
+const ConfirmReportsShare = (): JSX.Element => {
+ const { t }: {
+ t: (key: string) => string
+ } = useTranslation('common')
+ const { id }: {
+ id: string
+ } = useParams()
+ const [loading, setLoading] = useState<boolean>(true)
+ const [error, setError] = useState<string>('')
+
+ const handleConfirm = async (token: string) => {
+ try {
+ await confirmSubscriberInvite(id, token)
+ } catch (e) {
+ setError(t('apiNotifications.invalidToken'))
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ useEffect(() => {
+ setLoading(true)
+ const query = new URLSearchParams(window.location.search)
+ const token = query.get('token')
+
+ if (!token) {
+ setError(t('apiNotifications.invalidToken'))
+ setLoading(false)
+ return
+ }
+
+ handleConfirm(token)
+ }, []) // eslint-disable-line
+
+ if (loading) {
+ return (
+ <div>
+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>
+ <Loader />
+ </div>
+ </div>
+ )
+ }
+
+ if (error) {
+ return (
+ <div>
+ <div className='bg-gray-50 dark:bg-slate-900 min-h-page px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
+ <div className='max-w-max mx-auto'>
+ <main className='sm:flex'>
+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
+ <div className='sm:ml-6'>
+ <div className='sm:border-l max-w-prose sm:border-gray-200 sm:pl-6'>
+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight sm:text-5xl'>
+ {error}
+ </h1>
+ </div>
+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
+ <Link
+ to={routes.dashboard}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
+ >
+ {t('common.dashboard')}
+ </Link>
+ <Link
+ to={routes.contact}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-50 dark:bg-slate-800 dark:hover:bg-slate-700 dark:focus:ring-gray-50'
+ >
+ {t('notFoundPage.support')}
+ </Link>
+ </div>
+ </div>
+ </main>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div>
+ <div className='bg-gray-50 dark:bg-slate-900 min-h-page px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
+ <div className='max-w-max mx-auto'>
+ <main className='sm:flex'>
+ <CheckCircleIcon className='h-12 w-12 text-green-500 dark:text-green-400' aria-hidden='true' />
+ <div className='sm:ml-6'>
+ <div className='sm:border-l max-w-prose sm:border-gray-200 sm:pl-6'>
+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight sm:text-5xl'>
+ {t('apiNotifications.acceptInvitation')}
+ </h1>
+ </div>
+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
+ <Link
+ to={routes.dashboard}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
+ >
+ {t('common.dashboard')}
+ </Link>
+ </div>
+ </div>
+ </main>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default memo(ConfirmReportsShare)
diff --git a/app/routes/project/settings/Emails/Emails.container.tsx b/app/routes/project/settings/Emails/Emails.container.tsx
new file mode 100644
index 000000000..0eb84826b
--- /dev/null
+++ b/app/routes/project/settings/Emails/Emails.container.tsx
@@ -0,0 +1,37 @@
+import { connect } from 'react-redux'
+import { errorsActions } from 'redux/reducers/errors'
+import { alertsActions } from 'redux/reducers/alerts'
+import { StateType, AppDispatch } from 'redux/store'
+import Emails from './Emails'
+
+const mapStateToProps = (state: StateType) => ({
+ user: state.auth.user,
+})
+
+const mapDispatchToProps = (dispatch: AppDispatch) => ({
+ emailFailed: (message: string) => {
+ dispatch(errorsActions.genericError({
+ message,
+ }))
+ },
+ addEmail: (message: string, type = 'success') => {
+ dispatch(alertsActions.generateAlerts({
+ message,
+ type,
+ }))
+ },
+ removeEmail: (message: string, type = 'success') => {
+ dispatch(alertsActions.generateAlerts({
+ message,
+ type,
+ }))
+ },
+ reportTypeNotifiction: (message: string, type = 'success') => {
+ dispatch(alertsActions.generateAlerts({
+ message,
+ type,
+ }))
+ },
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(Emails)
diff --git a/app/routes/project/settings/Emails/Emails.tsx b/app/routes/project/settings/Emails/Emails.tsx
new file mode 100644
index 000000000..728a1cb13
--- /dev/null
+++ b/app/routes/project/settings/Emails/Emails.tsx
@@ -0,0 +1,522 @@
+import React, {
+ useState, useEffect, useRef,
+} from 'react'
+import {
+ TrashIcon, InboxStackIcon, ChevronDownIcon, CheckIcon,
+} from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+import PropTypes from 'prop-types'
+import dayjs from 'dayjs'
+import _keys from 'lodash/keys'
+import _isEmpty from 'lodash/isEmpty'
+import _filter from 'lodash/filter'
+import _map from 'lodash/map'
+import _toLower from 'lodash/toLower'
+
+import {
+ addSubscriber, removeSubscriber, getSubscribers, updateSubscriber,
+} from 'api'
+
+import { isValidEmail } from 'utils/validator'
+import useOnClickOutside from 'hooks/useOnClickOutside'
+import { reportFrequencyForEmailsOptions } from 'redux/constants'
+
+import Input from 'ui/Input'
+import Button from 'ui/Button'
+import Modal from 'ui/Modal'
+import Loader from 'ui/Loader'
+import Beta from 'ui/Beta'
+import cx from 'clsx'
+import { WarningPin } from 'ui/Pin'
+import { ISubscribers } from 'redux/models/ISubscribers'
+
+const ModalMessage = ({
+ project, handleInput, beenSubmitted, errors, form, t,
+}: {
+ project: string
+ handleInput: (e: React.ChangeEvent<HTMLInputElement>) => void
+ beenSubmitted: boolean
+ errors: {
+ email?: string
+ reportFrequency?: string
+ }
+ form: {
+ email: string
+ reportFrequency: string
+ }
+ t: (key: string, options?: {
+ [key: string]: string | number | boolean | undefined
+ }) => string
+}): JSX.Element => (
+ <div>
+ <h2 className='text-xl font-bold text-gray-700 dark:text-gray-200'>
+ {t('project.settings.inviteTo', { project })}
+ </h2>
+ <p className='mt-2 text-base text-gray-700 dark:text-gray-200'>
+ {t('project.settings.inviteDesc')}
+ </p>
+ <Input
+ name='email'
+ id='email'
+ type='email'
+ label={t('auth.common.email')}
+ value={form.email}
+ placeholder='[email protected]'
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted && errors.email}
+ />
+ <fieldset className='mt-4'>
+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
+ <label className='block text-sm font-medium text-gray-700 dark:text-gray-300' htmlFor='role'>
+ {t('project.emails.reportFrequency')}
+ </label>
+ <div className={cx('mt-1 bg-white rounded-md -space-y-px dark:bg-slate-900', { 'border-red-300 border': errors.reportFrequency })}>
+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
+ {_map(reportFrequencyForEmailsOptions, (item, index) => (
+ <div key={item.value}>
+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
+ <label className={cx('dark:border-gray-500 relative border p-4 flex cursor-pointer border-gray-200', {
+ 'bg-indigo-50 border-indigo-200 dark:bg-indigo-500 dark:border-indigo-800 z-10': item.value === form.reportFrequency,
+ 'border-gray-200': form.reportFrequency !== item.value,
+ 'rounded-tl-md rounded-tr-md': index === 0,
+ 'rounded-bl-md rounded-br-md': index === reportFrequencyForEmailsOptions.length - 1,
+ })}
+ >
+ <input
+ name='reportFrequency'
+ className='focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300'
+ id='reportFrequency'
+ type='radio'
+ value={item.value}
+ onChange={handleInput}
+ />
+ <div className='ml-3 flex flex-col'>
+ <span className={cx('block text-sm font-medium', { 'text-indigo-900 dark:text-white': form.reportFrequency === item.value, 'text-gray-700 dark:text-gray-200': form.reportFrequency !== item.value })}>
+ {t(`profileSettings.${item.value}`)}
+ </span>
+ </div>
+ </label>
+ </div>
+ ))}
+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
+ </div>
+ {errors.reportFrequency && (
+ <p className='mt-2 text-sm text-red-600 dark:text-red-500' id='email-error'>{errors.reportFrequency}</p>
+ )}
+ </fieldset>
+ </div>
+)
+
+const EmailList = ({
+ data, onRemove, t, setEmails, emailFailed, language, reportTypeNotifiction,
+}: {
+ data: {
+ id: string
+ addedAt: string
+ isConfirmed: boolean
+ projectId: string
+ email: string
+ reportFrequency: string
+ }
+ onRemove: (id: string) => void
+ t: (key: string, options?: {
+ [key: string]: string | number | boolean | undefined
+ }) => string
+ setEmails: (value: ISubscribers[] | ((prevVar: ISubscribers[]) => ISubscribers[])) => void;
+ emailFailed: (message: string) => void
+ language: string
+ reportTypeNotifiction: (message: string) => void
+}) => {
+ const [open, setOpen] = useState<boolean>(false)
+ const [showDeleteModal, setShowDeleteModal] = useState<boolean>(false)
+ const openRef = useRef<HTMLDivElement>(null)
+ useOnClickOutside(openRef, () => setOpen(false))
+ const {
+ id, addedAt, isConfirmed, projectId, email, reportFrequency,
+ } = data
+
+ const changeRole = async (reportType: {
+ value: string
+ label: string
+ }) => {
+ try {
+ const results = await updateSubscriber(projectId, id, { reportFrequency: reportType.value })
+ setEmails((prev) => {
+ const newEmails = _map(prev, (item) => {
+ if (item.id === results.id) {
+ return results
+ }
+ return item
+ })
+ return newEmails
+ })
+ reportTypeNotifiction(t('apiNotifications.roleUpdated'))
+ } catch (e) {
+ console.error(`[ERROR] Error while updating user's role: ${e}`)
+ emailFailed(t('apiNotifications.roleUpdateError'))
+ }
+
+ setOpen(false)
+ }
+
+ return (
+ <tr className='dark:bg-slate-800'>
+ <td className='whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 dark:text-white sm:pl-6'>
+ {email}
+ </td>
+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-white'>
+ {language === 'en'
+ ? dayjs(addedAt).locale(language).format('MMMM D, YYYY')
+ : dayjs(addedAt).locale(language).format('D MMMM, YYYY')}
+ </td>
+ <td className='relative whitespace-nowrap py-4 text-right text-sm font-medium pr-2'>
+ {isConfirmed ? (
+ <div ref={openRef}>
+ <button
+ onClick={() => setOpen(!open)}
+ type='button'
+ className='inline-flex items-center shadow-sm pl-2 pr-1 py-0.5 border border-gray-200 dark:border-gray-600 text-sm leading-5 font-medium rounded-full bg-white dark:bg-slate-800 text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-600'
+ >
+ {t(`profileSettings.${_toLower(reportFrequency)}`)}
+ <ChevronDownIcon
+ style={{ transform: open ? 'rotate(180deg)' : '' }}
+ className='w-4 h-4 pt-px ml-0.5'
+ />
+ </button>
+ {open && (
+ <ul className='text-left origin-top-right absolute z-10 right-0 mt-2 w-72 rounded-md shadow-lg bg-white dark:bg-slate-900 divide-y divide-gray-200 dark:divide-gray-700 focus:outline-none'>
+ {_map(reportFrequencyForEmailsOptions, (item) => (
+ <li onClick={() => changeRole(item)} className='p-4 hover:bg-indigo-600 group cursor-pointer flex justify-between items-center' key={item.value}>
+ <div>
+ <p className='font-bold text-gray-700 dark:text-gray-200 group-hover:text-gray-200'>
+ {t(`profileSettings.${_toLower(item.label)}`)}
+ </p>
+ </div>
+ {reportFrequency === item.value && (
+ <span className='text-indigo-600 group-hover:text-gray-200'>
+ <CheckIcon className='w-7 h-7 pt-px ml-1' />
+ </span>
+ )}
+ </li>
+ ))}
+ <li onClick={() => { setOpen(false); setShowDeleteModal(true) }} className='p-4 hover:bg-gray-200 dark:hover:bg-gray-700 group cursor-pointer flex justify-between items-center'>
+ <div>
+ <p className='font-bold text-red-600 dark:text-red-500'>
+ {t('project.settings.removeMember')}
+ </p>
+ </div>
+ </li>
+ </ul>
+ )}
+ </div>
+ ) : (
+ <div className='flex items-center justify-end'>
+ <WarningPin
+ label={t('common.pending')}
+ className='inline-flex items-center shadow-sm px-2.5 py-0.5 mr-3'
+ />
+ <Button
+ type='button'
+ className='bg-white text-indigo-700 rounded-md text-base font-medium hover:bg-indigo-50 dark:text-gray-50 dark:border-gray-600 dark:bg-slate-800 dark:hover:bg-slate-700'
+ small
+ onClick={() => setShowDeleteModal(true)}
+ >
+ <TrashIcon className='h-4 w-4' />
+ </Button>
+ </div>
+ )}
+ </td>
+ <td>
+ <Modal
+ onClose={() => {
+ setShowDeleteModal(false)
+ }}
+ onSubmit={() => {
+ setShowDeleteModal(false)
+ onRemove(id)
+ }}
+ submitText={t('common.yes')}
+ type='confirmed'
+ closeText={t('common.no')}
+ title={t('project.settings.removeUser', { user: email })}
+ message={t('project.settings.removeReportConfirm')}
+ isOpened={showDeleteModal}
+ />
+ </td>
+ </tr>
+ )
+}
+
+EmailList.propTypes = {
+ data: PropTypes.shape({
+ created: PropTypes.string,
+ email: PropTypes.string,
+ }),
+ onRemove: PropTypes.func.isRequired,
+ t: PropTypes.func.isRequired,
+ language: PropTypes.string.isRequired,
+}
+
+EmailList.defaultProps = {
+ data: {},
+}
+
+const NoSubscribers = ({ t }: {
+ t: (string: string) => string,
+}): JSX.Element => (
+ <div className='flex flex-col py-6 sm:px-6 lg:px-8'>
+ <div className='max-w-7xl w-full mx-auto text-gray-900 dark:text-gray-50'>
+ <h2 className='text-2xl mb-8 text-center leading-snug'>
+ {t('project.settings.noPeople')}
+ </h2>
+ </div>
+ </div>
+)
+
+const Emails = ({
+ emailFailed, addEmail, removeEmail, projectId, projectName, reportTypeNotifiction,
+}: {
+ emailFailed: (message: string, type?: string) => void
+ addEmail: (message: string, type?: string) => void
+ removeEmail: (message: string) => void
+ projectId: string
+ projectName: string
+ reportTypeNotifiction: (message: string, type?: string) => void
+}): JSX.Element => {
+ const [showModal, setShowModal] = useState<boolean>(false)
+ const { t, i18n: { language } }: {
+ t: (string: string, options?: {
+ [key: string]: string | number | boolean | undefined | null
+ }) => string,
+ i18n: { language: string },
+ } = useTranslation('common')
+ const [form, setForm] = useState<{
+ email: string,
+ reportFrequency: string,
+ }>({
+ email: '',
+ reportFrequency: reportFrequencyForEmailsOptions[3].value,
+ })
+ const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)
+ const [errors, setErrors] = useState<{
+ email?: string,
+ reportFrequency?: string,
+ }>({})
+ const [validated, setValidated] = useState<boolean>(false)
+ const [emails, setEmails] = useState<ISubscribers[]>([])
+ const [loading, setLoading] = useState(true)
+ const [paggination, setPaggination] = useState({
+ page: 1,
+ limit: 10,
+ total: 0,
+ })
+
+ const getSubcribersAsync = async () => {
+ try {
+ const { subscribers, count } = await getSubscribers(projectId, paggination.page - 1, paggination.limit)
+ setPaggination(oldPaggination => ({
+ ...oldPaggination,
+ count,
+ }))
+ setEmails(subscribers)
+ } catch (e) {
+ console.error(`[ERROR] Error while getting subscribers: ${e}`)
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ useEffect(() => {
+ getSubcribersAsync()
+ }, []) // eslint-disable-line
+
+ const validate = () => {
+ const allErrors: {
+ email?: string,
+ reportFrequency?: string,
+ } = {}
+
+ if (!isValidEmail(form.email)) {
+ allErrors.email = t('auth.common.badEmailError')
+ }
+
+ const valid = _isEmpty(_keys(allErrors))
+
+ setErrors(allErrors)
+ setValidated(valid)
+ }
+
+ useEffect(() => {
+ if (showModal) {
+ validate()
+ }
+ }, [form]) // eslint-disable-line
+
+ const handleInput = ({ target }: React.ChangeEvent<HTMLInputElement>) => {
+ const value = target.type === 'checkbox' ? target.checked : target.value
+
+ setForm(oldForm => ({
+ ...oldForm,
+ [target.name]: value,
+ }))
+ }
+
+ const onSubmit = async () => {
+ setShowModal(false)
+ setErrors({})
+ setValidated(false)
+
+ try {
+ const results = await addSubscriber(projectId, { reportFrequency: form.reportFrequency, email: form.email })
+ setEmails([...emails, results])
+ addEmail(t('apiNotifications.userInvited'))
+ } catch (e) {
+ console.error(`[ERROR] Error while inviting a user: ${e}`)
+ addEmail(t('apiNotifications.userInviteError'), 'error')
+ }
+
+ // a timeout is needed to prevent the flicker of data fields in the modal when closing
+ setTimeout(() => setForm({ email: '', reportFrequency: '' }), 300)
+ }
+
+ const handleSubmit = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
+ e.preventDefault()
+ e.stopPropagation()
+
+ setBeenSubmitted(true)
+ if (validated) {
+ onSubmit()
+ } else {
+ validate()
+ }
+ }
+
+ const closeModal = () => {
+ setShowModal(false)
+ // a timeout is needed to prevent the flicker of data fields in the modal when closing
+ setTimeout(() => setForm({ email: '', reportFrequency: '' }), 300)
+ setErrors({})
+ }
+
+ const onRemove = async (email: string) => {
+ try {
+ await removeSubscriber(projectId, email)
+ const results = _filter(emails, s => s.id !== email)
+ setEmails(results)
+ removeEmail(t('apiNotifications.emailDelete'))
+ } catch (e) {
+ console.error(`[ERROR] Error while deleting a email: ${e}`)
+ emailFailed(t('apiNotifications.emailDeleteError'))
+ }
+ }
+
+ return (
+ <div className='mt-6 mb-6'>
+ <div className='flex justify-between items-center mb-3'>
+ <div>
+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('project.emails.title')}
+ <div className='ml-5'>
+ <Beta />
+ </div>
+ </h3>
+ <p className='text-sm text-gray-500 dark:text-gray-400'>
+ {t('project.emails.description')}
+ </p>
+ </div>
+ <Button
+ className='h-8 pl-2'
+ primary
+ regular
+ type='button'
+ onClick={() => setShowModal(true)}
+ >
+ <>
+ <InboxStackIcon className='w-5 h-5 mr-1' />
+ {t('project.emails.add')}
+ </>
+ </Button>
+ </div>
+ <div>
+ <div className='mt-3 flex flex-col'>
+ <div className='-my-2 -mx-4 overflow-x-auto md:overflow-x-visible sm:-mx-6 lg:-mx-8'>
+ <div className='inline-block min-w-full py-2 md:px-6 lg:px-8'>
+ {(!loading && !_isEmpty(emails)) && (
+ <div className='shadow ring-1 ring-black ring-opacity-5 md:rounded-lg'>
+ <table className='min-w-full divide-y divide-gray-300 dark:divide-gray-600'>
+ <thead>
+ <tr className='dark:bg-slate-800'>
+ <th scope='col' className='py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6 dark:text-white'>
+ {t('auth.common.email')}
+ </th>
+ <th scope='col' className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-white'>
+ {t('auth.common.addedOn')}
+ </th>
+ <th scope='col' />
+ <th scope='col' />
+ </tr>
+ </thead>
+ <tbody className='divide-y divide-gray-300 dark:divide-gray-600'>
+ {_map(emails, email => (
+ <EmailList
+ data={email}
+ key={email.id}
+ onRemove={onRemove}
+ t={t}
+ language={language}
+ setEmails={setEmails}
+ emailFailed={emailFailed}
+ reportTypeNotifiction={reportTypeNotifiction}
+ />
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ {_isEmpty(emails) && (
+ <NoSubscribers t={t} />
+ )}
+ {loading && (
+ <Loader />
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ <Modal
+ onClose={closeModal}
+ customButtons={(
+ <button
+ type='button'
+ className='w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 text-base font-medium text-white sm:ml-3 sm:w-auto sm:text-sm bg-indigo-600 hover:bg-indigo-700'
+ onClick={handleSubmit}
+ >
+ {t('project.emails.add')}
+ </button>
+ )}
+ closeText={t('common.cancel')}
+ message={(
+ <ModalMessage
+ t={t}
+ project={projectName}
+ form={form}
+ handleInput={handleInput}
+ errors={errors}
+ beenSubmitted={beenSubmitted}
+ />
+ )}
+ isOpened={showModal}
+ />
+ </div>
+ )
+}
+
+Emails.propTypes = {
+ // eslint-disable-next-line react/forbid-prop-types
+ emailFailed: PropTypes.func.isRequired,
+ addEmail: PropTypes.func.isRequired,
+ removeEmail: PropTypes.func.isRequired,
+}
+
+export default Emails
diff --git a/app/routes/project/settings/Emails/index.tsx b/app/routes/project/settings/Emails/index.tsx
new file mode 100644
index 000000000..df0c540c1
--- /dev/null
+++ b/app/routes/project/settings/Emails/index.tsx
@@ -0,0 +1,3 @@
+import Emails from './Emails.container'
+
+export default Emails
diff --git a/app/routes/project/settings/People/People.container.tsx b/app/routes/project/settings/People/People.container.tsx
new file mode 100644
index 000000000..d39372375
--- /dev/null
+++ b/app/routes/project/settings/People/People.container.tsx
@@ -0,0 +1,47 @@
+import { connect } from 'react-redux'
+import UIActions from 'redux/reducers/ui'
+import { errorsActions } from 'redux/reducers/errors'
+import { alertsActions } from 'redux/reducers/alerts'
+import { StateType, AppDispatch } from 'redux/store'
+import { IProject } from 'redux/models/IProject'
+
+import People from './People'
+
+const mapStateToProps = (state: StateType) => ({
+ isPaidTierUsed: state.auth.isPaidTierUsed,
+})
+
+const mapDispatchToProps = (dispatch: AppDispatch) => ({
+ updateProjectFailed: (message: string) => {
+ dispatch(errorsActions.updateProjectFailed({
+ message,
+ }))
+ },
+ setProjectShareData: (data: Partial<IProject>, projectId: string, shared = false) => {
+ dispatch(UIActions.setProjectsShareData({
+ data,
+ id: projectId,
+ shared,
+ }))
+ },
+ roleUpdatedNotification: (message: string, type = 'success') => {
+ dispatch(alertsActions.roleUpdated({
+ message,
+ type,
+ }))
+ },
+ inviteUserNotification: (message: string, type = 'success') => {
+ dispatch(alertsActions.inviteUser({
+ message,
+ type,
+ }))
+ },
+ removeUserNotification: (message: string, type = 'success') => {
+ dispatch(alertsActions.removeUser({
+ message,
+ type,
+ }))
+ },
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(People)
diff --git a/app/routes/project/settings/People/People.tsx b/app/routes/project/settings/People/People.tsx
new file mode 100644
index 000000000..63c689242
--- /dev/null
+++ b/app/routes/project/settings/People/People.tsx
@@ -0,0 +1,493 @@
+import React, { useState, useEffect, useRef } from 'react'
+import { ChevronDownIcon, CheckIcon } from '@heroicons/react/24/solid'
+import { TrashIcon, UserPlusIcon, CurrencyDollarIcon } from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+import cx from 'clsx'
+import PropTypes from 'prop-types'
+import dayjs from 'dayjs'
+import _keys from 'lodash/keys'
+import _isEmpty from 'lodash/isEmpty'
+import _filter from 'lodash/filter'
+import _map from 'lodash/map'
+
+import { deleteShareProjectUsers, shareProject, changeShareRole } from 'api'
+import { isValidEmail } from 'utils/validator'
+import Input from 'ui/Input'
+import { WarningPin } from 'ui/Pin'
+import Button from 'ui/Button'
+import Modal from 'ui/Modal'
+import PaidFeature from 'modals/PaidFeature'
+import {
+ roles, roleViewer, roleAdmin, INVITATION_EXPIRES_IN,
+} from 'redux/constants'
+import useOnClickOutside from 'hooks/useOnClickOutside'
+import { IProject, IShareOwnerProject } from 'redux/models/IProject'
+
+const NoEvents = ({ t }: {
+ t: (key: string) => string
+}): JSX.Element => (
+ <div className='flex flex-col py-6 sm:px-6 lg:px-8'>
+ <div className='max-w-7xl w-full mx-auto text-gray-900 dark:text-gray-50'>
+ <h2 className='text-2xl mb-8 text-center leading-snug'>
+ {t('project.settings.noPeople')}
+ </h2>
+ </div>
+ </div>
+)
+
+const UsersList = ({
+ data, onRemove, t, share, setProjectShareData, pid, updateProjectFailed, language, roleUpdatedNotification,
+}: {
+ data: IShareOwnerProject
+ onRemove: (id: string) => void
+ t: (key: string, options?: {
+ [key: string]: string | number | null
+ }) => string
+ share?: IShareOwnerProject[]
+ setProjectShareData: (item: Partial<IProject>, id: string) => void
+ pid: string
+ updateProjectFailed: (message: string) => void
+ language: string
+ roleUpdatedNotification: (email: string, role?: string) => void
+}) => {
+ const [open, setOpen] = useState<boolean>(false)
+ const [showDeleteModal, setShowDeleteModal] = useState<boolean>(false)
+ const openRef = useRef<HTMLDivElement>(null)
+ useOnClickOutside(openRef, () => setOpen(false))
+ const {
+ id, created, confirmed, role, user,
+ } = data
+
+ const changeRole = async (newRole: string) => {
+ try {
+ const results = await changeShareRole(id, { role: newRole })
+ const newShared: IShareOwnerProject[] = _map(share, (itShare) => {
+ if (itShare.id === results.id) {
+ return { ...results, user: itShare.user }
+ }
+ return itShare
+ })
+ setProjectShareData({ share: newShared }, pid)
+ roleUpdatedNotification(t('apiNotifications.roleUpdated'))
+ } catch (e) {
+ console.error(`[ERROR] Error while updating user's role: ${e}`)
+ updateProjectFailed(t('apiNotifications.roleUpdateError'))
+ }
+
+ setOpen(false)
+ }
+
+ return (
+ <tr className='dark:bg-slate-800'>
+ <td className='whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 dark:text-white sm:pl-6'>
+ {user.email}
+ </td>
+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-white'>
+ {language === 'en'
+ ? dayjs(created).locale(language).format('MMMM D, YYYY')
+ : dayjs(created).locale(language).format('D MMMM, YYYY')}
+ </td>
+ <td className='relative whitespace-nowrap py-4 text-right text-sm font-medium pr-2'>
+ {confirmed ? (
+ <div ref={openRef}>
+ <button
+ onClick={() => setOpen(!open)}
+ type='button'
+ className='inline-flex items-center shadow-sm pl-2 pr-1 py-0.5 border border-gray-200 dark:border-gray-600 text-sm leading-5 font-medium rounded-full bg-white dark:bg-slate-800 text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-600'
+ >
+ {t(`project.settings.roles.${role}.name`)}
+ <ChevronDownIcon
+ style={{ transform: open ? 'rotate(180deg)' : '' }}
+ className='w-4 h-4 pt-px ml-0.5'
+ />
+ </button>
+ {open && (
+ <ul className='text-left origin-top-right absolute z-10 right-0 mt-2 w-72 rounded-md shadow-lg bg-white dark:bg-slate-900 divide-y divide-gray-200 dark:divide-gray-700 focus:outline-none'>
+ {_map(roles, (itRole) => (
+ <li onClick={() => changeRole(itRole)} className='p-4 hover:bg-indigo-600 group cursor-pointer flex justify-between items-center' key={itRole}>
+ <div>
+ <p className='font-bold text-gray-700 dark:text-gray-200 group-hover:text-gray-200'>
+ {t(`project.settings.roles.${itRole}.name`)}
+ </p>
+ <p className='mt-1 text-sm text-gray-500 group-hover:text-gray-200'>
+ {t(`project.settings.roles.${itRole}.shortDesc`)}
+ </p>
+ </div>
+ {role === itRole && (
+ <span className='text-indigo-600 group-hover:text-gray-200'>
+ <CheckIcon className='w-7 h-7 pt-px ml-1' />
+ </span>
+ )}
+ </li>
+ ))}
+ <li onClick={() => { setOpen(false); setShowDeleteModal(true) }} className='p-4 hover:bg-gray-200 dark:hover:bg-gray-700 group cursor-pointer flex justify-between items-center'>
+ <div>
+ <p className='font-bold text-red-600 dark:text-red-500'>
+ {t('project.settings.removeMember')}
+ </p>
+ </div>
+ </li>
+ </ul>
+ )}
+ </div>
+ ) : (
+ <div className='flex items-center justify-end'>
+ <WarningPin
+ label={t('common.pending')}
+ className='inline-flex items-center shadow-sm px-2.5 py-0.5 mr-3'
+ />
+ <Button
+ type='button'
+ className='bg-white text-indigo-700 rounded-md text-base font-medium hover:bg-indigo-50 dark:text-gray-50 dark:border-gray-600 dark:bg-slate-800 dark:hover:bg-slate-700'
+ small
+ onClick={() => setShowDeleteModal(true)}
+ >
+ <TrashIcon className='h-4 w-4' />
+ </Button>
+ </div>
+ )}
+ </td>
+ <td>
+ <Modal
+ onClose={() => {
+ setShowDeleteModal(false)
+ }}
+ onSubmit={() => {
+ setShowDeleteModal(false)
+ onRemove(id)
+ }}
+ submitText={t('common.yes')}
+ type='confirmed'
+ closeText={t('common.no')}
+ title={t('project.settings.removeUser', { user: user.email })}
+ message={t('project.settings.removeConfirm')}
+ isOpened={showDeleteModal}
+ />
+ </td>
+ </tr>
+ )
+}
+
+UsersList.propTypes = {
+ share: PropTypes.arrayOf(PropTypes.object).isRequired, // eslint-disable-line react/forbid-prop-types
+ data: PropTypes.object, // eslint-disable-line react/forbid-prop-types
+ pid: PropTypes.string.isRequired,
+ onRemove: PropTypes.func.isRequired,
+ updateProjectFailed: PropTypes.func.isRequired,
+ language: PropTypes.string.isRequired,
+}
+
+UsersList.defaultProps = {
+ data: {},
+}
+
+interface IPeopleProps {
+ project: IProject,
+ updateProjectFailed: (error: string) => void,
+ setProjectShareData: (data: Partial<IProject>, projectId: string, share?: boolean) => void,
+ roleUpdatedNotification: (email: string, role?: string) => void,
+ inviteUserNotification: (email: string, type?: string) => void,
+ removeUserNotification: (email: string) => void,
+ isPaidTierUsed: boolean,
+}
+
+const People: React.FunctionComponent<IPeopleProps> = ({
+ project, updateProjectFailed, setProjectShareData, roleUpdatedNotification, inviteUserNotification,
+ removeUserNotification, isPaidTierUsed,
+}: IPeopleProps): JSX.Element => {
+ const [showModal, setShowModal] = useState<boolean>(false)
+ const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState<boolean>(false)
+ const { t, i18n: { language } }: {
+ t: (key: string, options?: {
+ [key: string]: string | number | null
+ }) => string,
+ i18n: {
+ language: string
+ }
+ } = useTranslation('common')
+ const [form, setForm] = useState<{
+ email: string,
+ role: string,
+ }>({
+ email: '',
+ role: '',
+ })
+ const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)
+ const [errors, setErrors] = useState<{
+ email?: string,
+ role?: string,
+ }>({})
+ const [validated, setValidated] = useState<boolean>(false)
+ const { id, name, share } = project
+
+ const validate = () => {
+ const allErrors: {
+ email?: string,
+ role?: string,
+ } = {}
+
+ if (!isValidEmail(form.email)) {
+ allErrors.email = t('auth.common.badEmailError')
+ }
+
+ if (_isEmpty(form.role)) {
+ allErrors.role = t('project.settings.errorNoRole')
+ }
+
+ const valid = _isEmpty(_keys(allErrors))
+
+ setErrors(allErrors)
+ setValidated(valid)
+ }
+
+ useEffect(() => {
+ if (showModal) {
+ validate()
+ }
+ }, [form]) // eslint-disable-line
+
+ const handleInput = ({ target }: React.ChangeEvent<HTMLInputElement>) => {
+ const value = target.type === 'checkbox' ? target.checked : target.value
+
+ setForm(oldForm => ({
+ ...oldForm,
+ [target.name]: value,
+ }))
+ }
+
+ const onSubmit = async () => {
+ setShowModal(false)
+ setErrors({})
+ setValidated(false)
+
+ try {
+ const results = await shareProject(id, { email: form.email, role: form.role })
+ setProjectShareData({ share: results.share }, id)
+ inviteUserNotification(t('apiNotifications.userInvited'))
+ } catch (e) {
+ console.error(`[ERROR] Error while inviting a user: ${e}`)
+ inviteUserNotification(t('apiNotifications.userInviteError'), 'error')
+ }
+
+ // a timeout is needed to prevent the flicker of data fields in the modal when closing
+ setTimeout(() => setForm({ email: '', role: '' }), 300)
+ }
+
+ const handleSubmit = (e: React.MouseEvent<HTMLButtonElement>) => {
+ e.preventDefault()
+ e.stopPropagation()
+
+ if (!isPaidTierUsed) {
+ setIsPaidFeatureOpened(true)
+ return
+ }
+
+ setBeenSubmitted(true)
+ if (validated) {
+ onSubmit()
+ } else {
+ validate()
+ }
+ }
+
+ const closeModal = () => {
+ setShowModal(false)
+ // a timeout is needed to prevent the flicker of data fields in the modal when closing
+ setTimeout(() => setForm({ email: '', role: '' }), 300)
+ setErrors({})
+ }
+
+ const onRemove = async (userId: string) => {
+ try {
+ await deleteShareProjectUsers(id, userId)
+ const newShared = _map(_filter(share, s => s.id !== userId), s => s)
+ setProjectShareData({ share: newShared }, id)
+ removeUserNotification(t('apiNotifications.userRemoved'))
+ } catch (e) {
+ console.error(`[ERROR] Error while deleting a user: ${e}`)
+ updateProjectFailed(t('apiNotifications.userRemoveError'))
+ }
+ }
+
+ return (
+ <div className='mt-6 mb-6'>
+ <div className='flex justify-between items-center mb-3'>
+ <div>
+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('project.settings.people')}
+ </h3>
+ <p className='text-sm text-gray-500 dark:text-gray-400'>
+ {t('project.settings.inviteCoworkers')}
+ </p>
+ </div>
+ <Button
+ className='h-8 pl-2'
+ primary
+ regular
+ type='button'
+ onClick={() => setShowModal(true)}
+ >
+ <>
+ <UserPlusIcon className='w-5 h-5 mr-1' />
+ {t('project.settings.invite')}
+ </>
+ </Button>
+ </div>
+ <div>
+ {
+ _isEmpty(share) ? (
+ <NoEvents t={t} />
+ ) : (
+ <div className='mt-3 flex flex-col'>
+ <div className='-my-2 -mx-4 overflow-x-auto md:overflow-x-visible sm:-mx-6 lg:-mx-8'>
+ <div className='inline-block min-w-full py-2 md:px-6 lg:px-8'>
+ <div className='shadow ring-1 ring-black ring-opacity-5 md:rounded-lg'>
+ <table className='min-w-full divide-y divide-gray-300 dark:divide-gray-600'>
+ <thead>
+ <tr className='dark:bg-slate-800'>
+ <th scope='col' className='py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6 dark:text-white'>
+ {t('auth.common.email')}
+ </th>
+ <th scope='col' className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-white'>
+ {t('profileSettings.sharedTable.joinedOn')}
+ </th>
+ <th scope='col' />
+ <th scope='col' />
+ </tr>
+ </thead>
+ <tbody className='divide-y divide-gray-300 dark:divide-gray-600'>
+ {_map(share, user => (
+ <UsersList
+ data={user}
+ key={user.id}
+ onRemove={onRemove}
+ t={t}
+ language={language}
+ share={project.share}
+ setProjectShareData={setProjectShareData}
+ updateProjectFailed={updateProjectFailed}
+ roleUpdatedNotification={roleUpdatedNotification}
+ pid={id}
+ />
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+ }
+ </div>
+ <PaidFeature
+ isOpened={isPaidFeatureOpened}
+ onClose={() => setIsPaidFeatureOpened(false)}
+ />
+ <Modal
+ onClose={closeModal}
+ customButtons={(
+ <button
+ type='button'
+ className={cx('w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 text-base font-medium text-white sm:ml-3 sm:w-auto sm:text-sm bg-indigo-600 hover:bg-indigo-700', {
+ 'opacity-80 !px-3': !isPaidTierUsed,
+ })}
+ onClick={handleSubmit}
+ >
+ {!isPaidTierUsed && (
+ <CurrencyDollarIcon className='w-5 h-5 mr-1' />
+ )}
+ {t('common.invite')}
+ </button>
+ )}
+ closeText={t('common.cancel')}
+ message={(
+ <div>
+ <h2 className='text-xl font-bold text-gray-700 dark:text-gray-200'>
+ {t('project.settings.inviteTo', { project: name })}
+ </h2>
+ <p className='mt-2 text-base text-gray-700 dark:text-gray-200'>
+ {t('project.settings.inviteDesc')}
+ </p>
+ <p className='mt-2 text-base text-gray-700 dark:text-gray-200'>
+ {t('project.settings.inviteExpity', { amount: INVITATION_EXPIRES_IN })}
+ </p>
+ <Input
+ name='email'
+ id='email'
+ type='email'
+ label={t('auth.common.email')}
+ value={form.email}
+ placeholder='[email protected]'
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted && errors.email}
+ />
+ <fieldset className='mt-4'>
+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
+ <label className='block text-sm font-medium text-gray-700 dark:text-gray-300' htmlFor='role'>
+ {t('project.settings.role')}
+ </label>
+ <div className={cx('mt-1 bg-white rounded-md -space-y-px dark:bg-slate-900', { 'border-red-300 border': errors.role })}>
+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
+ <label className={cx('dark:border-gray-500 rounded-tl-md rounded-tr-md relative border p-4 flex cursor-pointer border-gray-200', { 'bg-indigo-50 border-indigo-200 dark:bg-indigo-500 dark:border-indigo-800 z-10': form.role === roleAdmin.role, 'border-gray-200': form.role !== roleAdmin.role })}>
+ <input
+ name='role'
+ className='focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300'
+ id='role_admin'
+ type='radio'
+ value='admin'
+ onChange={handleInput}
+ />
+ <div className='ml-3 flex flex-col'>
+ <span className={cx('block text-sm font-medium', { 'text-indigo-900 dark:text-white': form.role === roleAdmin.role, 'text-gray-700 dark:text-gray-200': form.role !== roleAdmin.role })}>
+ {t('project.settings.roles.admin.name')}
+ </span>
+ <span className={cx('block text-sm', { 'text-indigo-700 dark:text-gray-100': form.role === roleAdmin.role, 'text-gray-700 dark:text-gray-200': form.role !== roleAdmin.role })}>
+ {t('project.settings.roles.admin.desc')}
+ </span>
+ </div>
+ </label>
+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
+ <label className={cx('dark:border-gray-500 rounded-bl-md rounded-br-md relative border p-4 flex cursor-pointer border-gray-200', { 'bg-indigo-50 border-indigo-200 dark:bg-indigo-500 dark:border-indigo-800 z-10': form.role === roleViewer.role, 'border-gray-200': form.role !== roleViewer.role })}>
+ <input
+ name='role'
+ className='focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300'
+ id='role_viewer'
+ type='radio'
+ value='viewer'
+ onChange={handleInput}
+ />
+ <div className='ml-3 flex flex-col'>
+ <span className={cx('block text-sm font-medium', { 'text-indigo-900 dark:text-white': form.role === roleViewer.role, 'text-gray-700 dark:text-gray-200': form.role !== roleViewer.role })}>
+ {t('project.settings.roles.viewer.name')}
+ </span>
+ <span className={cx('block text-sm', { 'text-indigo-700 dark:text-gray-100': form.role === roleViewer.role, 'text-gray-700 dark:text-gray-200': form.role !== roleViewer.role })}>
+ {t('project.settings.roles.viewer.desc')}
+ </span>
+ </div>
+ </label>
+ </div>
+ {errors.role && (
+ <p className='mt-2 text-sm text-red-600 dark:text-red-500' id='email-error'>{errors.role}</p>
+ )}
+ </fieldset>
+ </div>
+ )}
+ isOpened={showModal}
+ />
+ </div>
+ )
+}
+
+People.propTypes = {
+ // @ts-ignore
+ // eslint-disable-next-line react/forbid-prop-types
+ project: PropTypes.object.isRequired,
+ updateProjectFailed: PropTypes.func.isRequired,
+ setProjectShareData: PropTypes.func.isRequired,
+ roleUpdatedNotification: PropTypes.func.isRequired,
+ inviteUserNotification: PropTypes.func.isRequired,
+ removeUserNotification: PropTypes.func.isRequired,
+}
+
+export default People
diff --git a/app/routes/project/settings/People/index.tsx b/app/routes/project/settings/People/index.tsx
new file mode 100644
index 000000000..e1573d0ef
--- /dev/null
+++ b/app/routes/project/settings/People/index.tsx
@@ -0,0 +1,3 @@
+import People from './People.container'
+
+export default People
diff --git a/app/routes/project/settings/ProjectSettings.container.tsx b/app/routes/project/settings/ProjectSettings.container.tsx
new file mode 100644
index 000000000..330ffd3a1
--- /dev/null
+++ b/app/routes/project/settings/ProjectSettings.container.tsx
@@ -0,0 +1,78 @@
+import { connect } from 'react-redux'
+import UIActions from 'redux/reducers/ui'
+import sagaActions from 'redux/sagas/actions'
+import { alertsActions } from 'redux/reducers/alerts'
+import { errorsActions } from 'redux/reducers/errors'
+import { StateType, AppDispatch } from 'redux/store'
+
+import { tabForSharedProject } from 'redux/constants'
+import ProjectSettings from './ProjectSettings'
+
+const mapStateToProps = (state: StateType) => ({
+ 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: AppDispatch) => ({
+ updateProjectFailed: (message: string) => {
+ dispatch(errorsActions.updateProjectFailed({
+ message,
+ }))
+ },
+ createNewProjectFailed: (message: string) => {
+ dispatch(errorsActions.createNewProjectFailed({
+ message,
+ }))
+ },
+ generateAlerts: (message: string) => {
+ dispatch(alertsActions.generateAlerts({
+ message,
+ type: 'success',
+ }))
+ },
+ projectDeleted: (message: string) => {
+ dispatch(alertsActions.generateAlerts({
+ message,
+ type: 'success',
+ }))
+ },
+ deleteProjectFailed: (message: string) => {
+ dispatch(errorsActions.deleteProjectFailed({
+ message,
+ }))
+ },
+ loadProjects: (shared: boolean) => {
+ if (shared) {
+ dispatch(sagaActions.loadSharedProjects())
+ } else {
+ dispatch(sagaActions.loadProjects())
+ }
+ },
+ removeProject: (pid: string, shared: boolean) => {
+ dispatch(UIActions.removeProject({
+ pid,
+ shared,
+ }))
+ },
+ deleteProjectCache: (pid: string) => {
+ dispatch(UIActions.deleteProjectCache({
+ pid,
+ }))
+ },
+ showError: (message: string) => {
+ dispatch(errorsActions.genericError({
+ message,
+ }))
+ },
+ setProjectProtectedPassword(id: string, password: string) {
+ dispatch(UIActions.setProjectProtectedPassword({
+ id,
+ password,
+ }))
+ },
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(ProjectSettings)
diff --git a/app/routes/project/settings/ProjectSettings.tsx b/app/routes/project/settings/ProjectSettings.tsx
new file mode 100644
index 000000000..5bef5bbad
--- /dev/null
+++ b/app/routes/project/settings/ProjectSettings.tsx
@@ -0,0 +1,653 @@
+/* eslint-disable react/forbid-prop-types */
+import React, {
+ useState, useEffect, useMemo, memo,
+} from 'react'
+import { useLocation, useNavigate, useParams } from '@remix-run/react'
+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, RocketLaunchIcon } from '@heroicons/react/24/outline'
+
+import { withAuthentication, auth } from 'hoc/protected'
+import { isSelfhosted } from 'redux/constants'
+import { IProject } from 'redux/models/IProject'
+import { IUser } from 'redux/models/IUser'
+import { IProjectForShared, ISharedProject } from 'redux/models/ISharedProject'
+import {
+ createProject, updateProject, deleteProject, resetProject, transferProject, deletePartially,
+} from 'api'
+import Input from 'ui/Input'
+import Button from 'ui/Button'
+import Checkbox from 'ui/Checkbox'
+import Modal from 'ui/Modal'
+import FlatPicker from 'ui/Flatpicker'
+import { nanoid } from 'utils/random'
+import { trackCustom } from 'utils/analytics'
+import routes from 'routesPath'
+import { getFormatDate } from '../view/__ViewProject.helpers'
+
+import People from './People'
+import Emails from './Emails'
+
+const MAX_NAME_LENGTH = 50
+const MAX_ORIGINS_LENGTH = 300
+const MAX_IPBLACKLIST_LENGTH = 300
+
+const tabDeleteDataModal = [
+ {
+ name: 'all',
+ title: 'project.settings.reseted.all',
+ },
+ {
+ name: 'partially',
+ title: 'project.settings.reseted.partially',
+ },
+]
+
+const ModalMessage = ({
+ dateRange, setDateRange, setTab, t, tab,
+}: {
+ dateRange: Date[],
+ setDateRange: (a: Date[]) => void,
+ setTab: (i: string) => void,
+ t: (key: string, options?: {
+ [key: string]: string | number | null
+ }) => string,
+ tab: string,
+}): JSX.Element => (
+ <>
+ <p className='text-gray-500 dark:text-gray-300 italic mt-1 mb-4 text-sm'>
+ {t('project.settings.resetHint')}
+ </p>
+ <div className='mt-6'>
+ <nav className='-mb-px flex space-x-6'>
+ {_map(tabDeleteDataModal, (tabDelete) => (
+ <button
+ key={tabDelete.name}
+ type='button'
+ onClick={() => setTab(tabDelete.name)}
+ className={cx('whitespace-nowrap pb-2 px-1 border-b-2 font-medium text-md', {
+ 'border-indigo-500 text-indigo-600 dark:text-gray-50 dark:border-gray-50': tabDelete.name === tab,
+ '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': tab !== tabDelete.name,
+ })}
+ >
+ {t(tabDelete.title)}
+ </button>
+ ))}
+ </nav>
+ </div>
+ {tab === tabDeleteDataModal[1].name && (
+ <>
+ <p className='text-gray-500 dark:text-gray-300 mt-4 mb-2 text-sm'>
+ {t('project.settings.reseted.partiallyDesc')}
+ </p>
+ <p className='text-gray-500 dark:text-gray-300 italic mt-1 mb-2 text-sm'>
+ {t('project.settings.reseted.partiallyHint')}
+ </p>
+ <input type='text' className='h-0 w-0 border-0 p-0 m-0 focus:text-transparent focus:border-transparent focus:shadow-none focus:ring-transparent' />
+ <FlatPicker
+ onChange={(date) => setDateRange(date)}
+ options={{
+ altInputClass: 'shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 dark:text-gray-50 dark:placeholder-gray-400 dark:border-gray-800 dark:bg-slate-800 rounded-md',
+ }}
+ value={dateRange}
+ />
+ </>
+ )}
+ {tab === tabDeleteDataModal[0].name && (
+ <p className='text-gray-500 dark:text-gray-300 italic mt-4 mb-4 text-sm'>
+ {t('project.settings.reseted.allHint')}
+ </p>
+ )}
+ </>
+)
+
+interface IForm extends Partial<IProject> {
+ origins: string | null,
+ ipBlacklist: string | null,
+}
+
+const DEFAULT_PROJECT_NAME = 'Untitled Project'
+
+const ProjectSettings = ({
+ updateProjectFailed, createNewProjectFailed, generateAlerts, projectDeleted, deleteProjectFailed,
+ loadProjects, isLoading, projects, showError, removeProject, user, isSharedProject, sharedProjects,
+ deleteProjectCache, setProjectProtectedPassword,
+}: {
+ updateProjectFailed: (message: string) => void,
+ createNewProjectFailed: (message: string) => void,
+ generateAlerts: (message: string) => void,
+ projectDeleted: (message: string) => void,
+ deleteProjectFailed: (message: string) => void,
+ loadProjects: (shared: boolean) => void,
+ isLoading: boolean,
+ projects: IProject[],
+ showError: (message: string) => void,
+ removeProject: (pid: string, shared: boolean) => void,
+ user: IUser,
+ isSharedProject: boolean,
+ sharedProjects: ISharedProject[],
+ deleteProjectCache: (pid: string) => void,
+ setProjectProtectedPassword: (pid: string, password: string) => void,
+}) => {
+ const { t }: {
+ t: (key: string, options?: {
+ [key: string]: string | number | null
+ }) => string,
+ } = useTranslation('common')
+ const { pathname } = useLocation()
+ const { id }: {
+ id: string,
+ } = useParams()
+ const project: IProjectForShared = useMemo(() => _find([...projects, ..._map(sharedProjects, (item) => item.project)], p => p.id === id) || {} as IProjectForShared, [projects, id, sharedProjects])
+ const isSettings: boolean = !_isEmpty(id) && (_replace(routes.project_settings, ':id', id) === pathname)
+ const navigate = useNavigate()
+
+ const [form, setForm] = useState<IForm>({
+ name: '',
+ id: id || nanoid(),
+ public: false,
+ origins: null,
+ ipBlacklist: null,
+ })
+ const [validated, setValidated] = useState<boolean>(false)
+ const [errors, setErrors] = useState<{
+ name?: string,
+ origins?: string,
+ ipBlacklist?: string,
+ password?: string,
+ }>({})
+ const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)
+ const [showDelete, setShowDelete] = useState<boolean>(false)
+ const [showReset, setShowReset] = useState<boolean>(false)
+ const [projectDeleting, setProjectDeleting] = useState<boolean>(false)
+ const [projectResetting, setProjectResetting] = useState<boolean>(false)
+ const [projectSaving, setProjectSaving] = useState<boolean>(false)
+ const [showTransfer, setShowTransfer] = useState<boolean>(false)
+ const [transferEmail, setTransferEmail] = useState<string>('')
+ const [dateRange, setDateRange] = useState<Date[]>([])
+ const [tab, setTab] = useState<string>(tabDeleteDataModal[0].name)
+ const [showProtected, setShowProtected] = useState<boolean>(false)
+
+ useEffect(() => {
+ if (!user.isActive && !isSelfhosted) {
+ showError(t('project.settings.verify'))
+ navigate(routes.dashboard)
+ }
+
+ if (!isLoading && isSettings && !projectDeleting) {
+ if (_isEmpty(project) || project?.uiHidden) {
+ showError(t('project.noExist'))
+ navigate(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: IForm) => {
+ 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 as Partial<IProject>)
+ generateAlerts(t('project.settings.updated'))
+ } else {
+ await createProject({
+ id: data.id || nanoid(),
+ name: data.name || DEFAULT_PROJECT_NAME,
+ })
+ trackCustom('PROJECT_CREATED')
+ generateAlerts(t('project.settings.created'))
+ }
+
+ loadProjects(isSharedProject)
+ } catch (e) {
+ if (isSettings) {
+ updateProjectFailed(e as string)
+ } else {
+ createNewProjectFailed(e as string)
+ }
+ } finally {
+ setProjectSaving(false)
+ }
+ }
+ }
+
+ const onDelete = async () => {
+ setShowDelete(false)
+ if (!projectDeleting) {
+ setProjectDeleting(true)
+ try {
+ await deleteProject(id)
+ removeProject(id, isSharedProject)
+ projectDeleted(t('project.settings.deleted'))
+ navigate(routes.dashboard)
+ } catch (e) {
+ deleteProjectFailed(e as string)
+ } finally {
+ setProjectDeleting(false)
+ }
+ }
+ }
+
+ const onReset = async () => {
+ setShowReset(false)
+ if (!projectResetting) {
+ setProjectResetting(true)
+ try {
+ if (tab === tabDeleteDataModal[1].name) {
+ if (_isEmpty(dateRange)) {
+ deleteProjectFailed(t('project.settings.noDateRange'))
+ setProjectResetting(false)
+ return
+ }
+ await deletePartially(id, {
+ from: getFormatDate(dateRange[0]),
+ to: getFormatDate(dateRange[1]),
+ })
+ } else {
+ await resetProject(id)
+ }
+ deleteProjectCache(id)
+ projectDeleted(t('project.settings.resetted'))
+ navigate(routes.dashboard)
+ } catch (e) {
+ deleteProjectFailed(e as string)
+ } finally {
+ setProjectResetting(false)
+ }
+ }
+ }
+
+ const validate = () => {
+ const allErrors: {
+ name?: string,
+ origins?: string,
+ ipBlacklist?: string,
+ password?: string,
+ } = {}
+
+ 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: React.ChangeEvent<HTMLInputElement>) => {
+ const { target } = event
+ const value = target.type === 'checkbox' ? target.checked : target.value
+
+ setForm(oldForm => ({
+ ...oldForm,
+ [target.name]: value,
+ }))
+ }
+
+ const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault()
+ e.stopPropagation()
+ setBeenSubmitted(true)
+
+ if (validated) {
+ onSubmit(form)
+ }
+ }
+
+ const onCancel = () => {
+ navigate(isSettings ? _replace(routes.project, ':id', id) : routes.dashboard)
+ }
+
+ const onTransfer = async () => {
+ await transferProject(id, transferEmail)
+ .then(() => {
+ generateAlerts(t('apiNotifications.transferRequestSent'))
+ navigate(routes.dashboard)
+ })
+ .catch((e) => {
+ showError(e as string)
+ })
+ .finally(() => {
+ setShowTransfer(false)
+ setTransferEmail('')
+ })
+ }
+
+ const onProtected = () => {
+ setBeenSubmitted(true)
+
+ if (validated) {
+ onSubmit({
+ ...form,
+ isPasswordProtected: true,
+ })
+
+ if (!_isEmpty(form.password) && !_isEmpty(form.id)) {
+ setProjectProtectedPassword(form?.id || '', form?.password || '')
+ }
+
+ setShowProtected(false)
+ }
+ }
+
+ const title = isSettings ? `${t('project.settings.settings')} ${form.name}` : t('project.settings.create')
+
+ return (
+ <div>
+ <div
+ className={cx('min-h-min-footer bg-gray-50 dark:bg-slate-900 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={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}
+ />
+ <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={(e) => {
+ if (!form.isPasswordProtected) {
+ handleInput(e)
+ }
+ }}
+ disabled={form?.isPasswordProtected}
+ name='public'
+ id='public'
+ className='mt-4'
+ label={t('project.settings.public')}
+ hint={t('project.settings.publicHint')}
+ />
+ {!isSelfhosted && (
+ <Checkbox
+ checked={Boolean(form.isPasswordProtected)}
+ onChange={() => {
+ if (!form.public && form.isPasswordProtected) {
+ setForm({
+ ...form,
+ isPasswordProtected: false,
+ })
+ return
+ }
+
+ if (!form.public) {
+ setShowProtected(true)
+ }
+ }}
+ disabled={form?.public}
+ name='isPasswordProtected'
+ id='isPasswordProtected'
+ className='mt-4'
+ label={t('project.settings.protected')}
+ hint={t('project.settings.protectedHint')}
+ />
+ )}
+ <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-slate-700/50 dark:bg-slate-800 dark:hover:bg-slate-700' 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'>
+ {!isSelfhosted && (
+ <Button className='mr-2' onClick={() => setShowTransfer(true)} semiDanger semiSmall>
+ <>
+ <RocketLaunchIcon className='w-5 h-5 mr-1' />
+ {t('project.settings.transfer')}
+ </>
+ </Button>
+ )}
+ <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>
+ {!isSelfhosted && (
+ <>
+ <hr className='mt-8 xs:mt-2 sm:mt-5 border-gray-200 dark:border-gray-600' />
+ <Emails projectId={id} projectName={project.name} />
+ </>
+ )}
+ {!isSelfhosted && !project?.shared && (
+ <>
+ <hr className='mt-2 sm:mt-5 border-gray-200 dark:border-gray-600' />
+ <People project={project} />
+ </>
+ )}
+ </>
+ ) : (
+ <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-slate-700/50 dark:bg-slate-800 dark:hover:bg-slate-700' 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={<ModalMessage setDateRange={setDateRange} dateRange={dateRange} setTab={setTab} tab={tab} t={t} />}
+ submitType='danger'
+ type='error'
+ isOpened={showReset}
+ />
+ <Modal
+ onClose={() => setShowProtected(false)}
+ onSubmit={onProtected}
+ submitText={t('common.save')}
+ closeText={t('common.cancel')}
+ title={t('project.settings.protected')}
+ message={(
+ <div>
+ <p className='text-gray-500 dark:text-gray-300 italic mt-1 mb-4 text-sm'>
+ {t('project.settings.protectedHint')}
+ </p>
+ <Input
+ name='password'
+ id='password'
+ type='password'
+ label={t('project.settings.password')}
+ value={form?.password || ''}
+ placeholder={t('project.settings.password')}
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.password : null}
+ />
+ </div>
+ )}
+ isOpened={showProtected}
+ />
+ <Modal
+ onClose={() => {
+ setShowTransfer(false)
+ }}
+ submitText={t('project.settings.transfer')}
+ closeText={t('common.cancel')}
+ message={(
+ <div>
+ <h2 className='text-xl font-bold text-gray-700 dark:text-gray-200'>
+ {t('project.settings.transferTo')}
+ </h2>
+ <p className='mt-2 text-base text-gray-700 dark:text-gray-200'>
+ {t('project.settings.transferHint', {
+ name: form.name || DEFAULT_PROJECT_NAME,
+ })}
+ </p>
+ <Input
+ name='email'
+ id='email'
+ type='email'
+ label={t('project.settings.transfereeEmail')}
+ value={transferEmail}
+ placeholder='[email protected]'
+ className='mt-4'
+ onChange={(e) => setTransferEmail(e.target.value)}
+ />
+ </div>
+ )}
+ isOpened={showTransfer}
+ onSubmit={onTransfer}
+ />
+ </div>
+ </div>
+ )
+}
+
+ProjectSettings.propTypes = {
+ updateProjectFailed: PropTypes.func.isRequired,
+ createNewProjectFailed: PropTypes.func.isRequired,
+ generateAlerts: 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/app/routes/project/settings/TransferProject/TransferProjectConfirm.tsx b/app/routes/project/settings/TransferProject/TransferProjectConfirm.tsx
new file mode 100644
index 000000000..4f47a7042
--- /dev/null
+++ b/app/routes/project/settings/TransferProject/TransferProjectConfirm.tsx
@@ -0,0 +1,115 @@
+import React, { useState, useEffect, memo } from 'react'
+import { Link } from '@remix-run/react'
+import { useTranslation } from 'react-i18next'
+import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'
+
+import Loader from 'ui/Loader'
+
+import { confirmTransferProject } from 'api'
+import routes from 'routesPath'
+
+const TransferProjectConfirm = (): JSX.Element => {
+ const { t }: {
+ t: (key: string) => string
+ } = useTranslation('common')
+ const [loading, setLoading] = useState<boolean>(true)
+ const [error, setError] = useState<string>('')
+
+ const handleConfirm = async (token: string) => {
+ try {
+ await confirmTransferProject(token)
+ } catch (e) {
+ setError(t('apiNotifications.invalidToken'))
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ useEffect(() => {
+ setLoading(true)
+ const query = new URLSearchParams(window.location.search)
+ const token = query.get('token')
+
+ if (!token) {
+ setError(t('apiNotifications.invalidToken'))
+ setLoading(false)
+ return
+ }
+
+ handleConfirm(token)
+ }, []) // eslint-disable-line
+
+ if (loading) {
+ return (
+ <div>
+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>
+ <Loader />
+ </div>
+ </div>
+ )
+ }
+
+ if (error) {
+ return (
+ <div>
+ <div className='bg-gray-50 dark:bg-slate-900 min-h-page px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
+ <div className='max-w-max mx-auto'>
+ <main className='sm:flex'>
+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
+ <div className='sm:ml-6'>
+ <div className='sm:border-l max-w-prose sm:border-gray-200 sm:pl-6'>
+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight sm:text-5xl'>
+ {error}
+ </h1>
+ </div>
+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
+ <Link
+ to={routes.dashboard}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
+ >
+ {t('common.dashboard')}
+ </Link>
+ <Link
+ to={routes.contact}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-50 dark:bg-slate-800 dark:hover:bg-slate-700 dark:focus:ring-gray-50'
+ >
+ {t('notFoundPage.support')}
+ </Link>
+ </div>
+ </div>
+ </main>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div>
+ <div className='bg-gray-50 dark:bg-slate-900 min-h-page px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
+ <div className='max-w-max mx-auto'>
+ <main className='sm:flex'>
+ <CheckCircleIcon className='h-12 w-12 text-green-500 dark:text-green-400' aria-hidden='true' />
+ <div className='sm:ml-6'>
+ <div className='sm:border-l max-w-prose sm:border-gray-200 sm:pl-6'>
+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight sm:text-5xl'>
+ {t('apiNotifications.acceptInvitation')}
+ </h1>
+ </div>
+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
+ <Link
+ to={routes.dashboard}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
+ >
+ {t('common.dashboard')}
+ </Link>
+ </div>
+ </div>
+ </main>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default memo(TransferProjectConfirm)
diff --git a/app/routes/project/settings/TransferProject/TransferProjectReject.tsx b/app/routes/project/settings/TransferProject/TransferProjectReject.tsx
new file mode 100644
index 000000000..297c6b355
--- /dev/null
+++ b/app/routes/project/settings/TransferProject/TransferProjectReject.tsx
@@ -0,0 +1,115 @@
+import React, { useState, useEffect, memo } from 'react'
+import { Link } from '@remix-run/react'
+import { useTranslation } from 'react-i18next'
+import { XCircleIcon, InformationCircleIcon } from '@heroicons/react/24/solid'
+
+import Loader from 'ui/Loader'
+
+import { rejectTransferProject } from 'api'
+import routes from 'routesPath'
+
+const TransferProjectReject = (): JSX.Element => {
+ const { t }: {
+ t: (key: string) => string
+ } = useTranslation('common')
+ const [loading, setLoading] = useState<boolean>(true)
+ const [error, setError] = useState<string>('')
+
+ const handleConfirm = async (token: string) => {
+ try {
+ await rejectTransferProject(token)
+ } catch (e) {
+ setError(t('apiNotifications.invalidToken'))
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ useEffect(() => {
+ setLoading(true)
+ const query = new URLSearchParams(window.location.search)
+ const token = query.get('token')
+
+ if (!token) {
+ setError(t('apiNotifications.invalidToken'))
+ setLoading(false)
+ return
+ }
+
+ handleConfirm(token)
+ }, []) // eslint-disable-line
+
+ if (loading) {
+ return (
+ <div>
+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>
+ <Loader />
+ </div>
+ </div>
+ )
+ }
+
+ if (error) {
+ return (
+ <div>
+ <div className='bg-gray-50 dark:bg-slate-900 min-h-page px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
+ <div className='max-w-max mx-auto'>
+ <main className='sm:flex'>
+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
+ <div className='sm:ml-6'>
+ <div className='sm:border-l max-w-prose sm:border-gray-200 sm:pl-6'>
+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight sm:text-5xl'>
+ {error}
+ </h1>
+ </div>
+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
+ <Link
+ to={routes.dashboard}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
+ >
+ {t('common.dashboard')}
+ </Link>
+ <Link
+ to={routes.contact}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-50 dark:bg-slate-800 dark:hover:bg-slate-700 dark:focus:ring-gray-50'
+ >
+ {t('notFoundPage.support')}
+ </Link>
+ </div>
+ </div>
+ </main>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div>
+ <div className='bg-gray-50 dark:bg-slate-900 min-h-page px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
+ <div className='max-w-max mx-auto'>
+ <main className='sm:flex'>
+ <InformationCircleIcon className='h-12 w-12 text-yellow-400' aria-hidden='true' />
+ <div className='sm:ml-6'>
+ <div className='sm:border-l max-w-prose sm:border-gray-200 sm:pl-6'>
+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight sm:text-5xl'>
+ {t('apiNotifications.transferProjectReject')}
+ </h1>
+ </div>
+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
+ <Link
+ to={routes.dashboard}
+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
+ >
+ {t('common.dashboard')}
+ </Link>
+ </div>
+ </div>
+ </main>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default memo(TransferProjectReject)
diff --git a/app/routes/project/settings/index.tsx b/app/routes/project/settings/index.tsx
new file mode 100644
index 000000000..91c7f9508
--- /dev/null
+++ b/app/routes/project/settings/index.tsx
@@ -0,0 +1,3 @@
+import ProjectSettings from './ProjectSettings.container'
+
+export default ProjectSettings
diff --git a/app/routes/project/view/$id.tsx b/app/routes/project/view/$id.tsx
new file mode 100644
index 000000000..a2413a7e9
--- /dev/null
+++ b/app/routes/project/view/$id.tsx
@@ -0,0 +1,3 @@
+import ViewProject from './__ViewProject.container'
+
+export default ViewProject
diff --git a/app/routes/project/view/__Panels.panels.tsx b/app/routes/project/view/__Panels.panels.tsx
new file mode 100644
index 000000000..c9b22c831
--- /dev/null
+++ b/app/routes/project/view/__Panels.panels.tsx
@@ -0,0 +1,1148 @@
+import React, {
+ memo, useState, useEffect, useMemo, Fragment,
+} from 'react'
+import {
+ ArrowLongRightIcon, ArrowLongLeftIcon,
+} from '@heroicons/react/24/solid'
+import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/20/solid'
+import {
+ FunnelIcon, MapIcon, Bars4Icon, ArrowsPointingOutIcon, ChartPieIcon, PuzzlePieceIcon, RectangleGroupIcon,
+} 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 _ceil from 'lodash/ceil'
+import _sortBy from 'lodash/sortBy'
+import _fromPairs from 'lodash/fromPairs'
+import _toPairs from 'lodash/toPairs'
+import _reverse from 'lodash/reverse'
+import { nFormatter } from 'utils/generic'
+
+import Progress from 'ui/Progress'
+import PulsatingCircle from 'ui/icons/PulsatingCircle'
+import Sort from 'ui/icons/Sort'
+import Modal from 'ui/Modal'
+import Button from 'ui/Button'
+import Chart from 'ui/Chart'
+
+import { PROJECT_TABS } from 'redux/constants'
+
+import LiveVisitorsDropdown from './components/LiveVisitorsDropdown'
+import InteractiveMap from './components/InteractiveMap'
+import UserFlow from './components/UserFlow'
+import { iconClassName } from './__ViewProject.helpers'
+
+const ENTRIES_PER_PANEL = 5
+const ENTRIES_PER_CUSTOM_EVENTS_PANEL = 6
+
+const panelsWithBars = ['cc', 'ce', 'os', 'br', 'dv', 'pg']
+
+// function that checks if there are custom tabs for a specific type
+const checkCustomTabs = (panelID: string, customTabs: any) => {
+ if (_isEmpty(customTabs)) return false
+
+ return Boolean(_find(customTabs, (el) => el.panelID === panelID))
+}
+
+const checkIfBarsNeeded = (panelID: string) => {
+ return _includes(panelsWithBars, panelID)
+}
+
+// noSwitch - 'previous' and 'next' buttons
+const PanelContainer = ({
+ name, children, noSwitch, icon, type, openModal, activeFragment, setActiveFragment, customTabs, activeTab,
+}: {
+ name: string,
+ children?: React.ReactNode,
+ noSwitch?: boolean,
+ icon?: React.ReactNode,
+ type: string,
+ openModal?: () => void,
+ activeFragment: number | string,
+ setActiveFragment: (arg: number) => void,
+ customTabs?: any,
+ activeTab?: string,
+}): JSX.Element => (
+ <div
+ className={cx('relative bg-white dark:bg-slate-800/25 dark:border dark:border-slate-800/50 pt-5 px-4 min-h-72 max-h-96 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}
+ />
+ </>
+ )}
+
+ {(type === 'pg' && activeTab !== PROJECT_TABS.performance) && (
+ <>
+ <RectangleGroupIcon
+ 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={cx('flex flex-col h-full scroll-auto', {
+ 'overflow-auto': !(type === 'pg' && activeTab !== PROJECT_TABS.performance && activeFragment === 1),
+ })}
+ >
+ {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: () => { },
+ openModal: () => { },
+ customTabs: [],
+ activeTab: '',
+}
+
+// First tab with stats
+const Overview = ({
+ overall, chartData, activePeriod, t, live, sessionDurationAVG, projectId, sessionDurationAVGCompare, isActiveCompare, dataChartCompare, activeDropdownLabelCompare, projectPassword,
+}: {
+ overall: any
+ chartData: any
+ activePeriod: any
+ t: (arg: string) => string
+ live: number | string
+ sessionDurationAVG: number
+ sessionDurationAVGCompare: number
+ isActiveCompare: boolean
+ activeDropdownLabelCompare: string | undefined
+ dataChartCompare: any
+ projectId: string
+ projectPassword: string | undefined
+}) => {
+ const pageviewsDidGrowUp = overall.percChange >= 0
+ const uniqueDidGrowUp = overall.percChangeUnique >= 0
+ const pageviews = _sum(chartData?.visits) || 0
+ const pageViewsCompare = _sum(dataChartCompare?.visits) || 0
+ const uniques = _sum(chartData?.uniques) || 0
+ const uniquesCompare = _sum(dataChartCompare?.uniques) || 0
+ let bounceRate = 0
+ let bounceRateCompare = 0
+
+ if (pageviews > 0) {
+ bounceRate = _round((uniques * 100) / pageviews, 1)
+ }
+
+ if (pageViewsCompare > 0) {
+ bounceRateCompare = _round((uniquesCompare * 100) / pageViewsCompare, 1)
+ }
+
+ return (
+ <PanelContainer name={t('project.overview')} noSwitch type='' openModal={() => {}}>
+ <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} projectPassword={projectPassword} />
+ </div>
+ {!_isEmpty(chartData) && (
+ <>
+ <p className='text-lg font-semibold dark:text-gray-50'>
+ {t('project.statsFor')}
+ <span className='lowercase'>
+ &nbsp;
+ {activePeriod.label}
+ </span>
+ {isActiveCompare && (
+ // return vs activeDropdownLabelCompare
+ <span className='text-sm text-gray-500 dark:text-gray-400'>
+ &nbsp;(
+ {activeDropdownLabelCompare}
+ )
+ </span>
+ )}
+ </p>
+
+ <div className='flex justify-between'>
+ <p className='text-lg dark:text-gray-50'>
+ {t('dashboard.pageviews')}
+ :
+ </p>
+ <p title={String(pageviews)} className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl'>
+ {nFormatter(pageviews, 1)}
+ {isActiveCompare && (
+ <span
+ title={`${pageViewsCompare > pageviews ? '+' : ''}${pageViewsCompare - pageviews}`}
+ className={cx('ml-1.5 text-sm', {
+ 'text-green-500': pageViewsCompare > pageviews,
+ 'text-red-500': pageViewsCompare < pageviews,
+ })}
+ >
+ {pageViewsCompare > pageviews ? '+' : ''}
+ {nFormatter(pageViewsCompare - pageviews, 1)}
+ </span>
+ )}
+ </p>
+ </div>
+
+ <div className='flex justify-between'>
+ <p className='text-lg dark:text-gray-50'>
+ {t('dashboard.unique')}
+ :
+ </p>
+ <p title={String(uniques)} className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl'>
+ {nFormatter(uniques, 1)}
+ {isActiveCompare && (
+ <span
+ title={`${uniquesCompare > uniques ? '+' : ''}${uniquesCompare - uniques}`}
+ className={cx('ml-1.5 text-sm', {
+ 'text-green-500': uniquesCompare > uniques,
+ 'text-red-500': uniquesCompare < uniques,
+ })}
+ >
+ {uniquesCompare > uniques ? '+' : ''}
+ {nFormatter(uniquesCompare - uniques, 1)}
+ </span>
+ )}
+ </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}
+ %
+ {isActiveCompare && (
+ <span className={cx('ml-1.5 text-sm', {
+ 'text-green-500': bounceRateCompare > bounceRate,
+ 'text-red-500': bounceRateCompare < bounceRate,
+ })}
+ >
+ {bounceRateCompare > bounceRate ? '+' : ''}
+ {_round(bounceRateCompare - bounceRate, 1)}
+ %
+ </span>
+ )}
+ </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}
+ {isActiveCompare && (
+ <span className='text-sm text-gray-500 dark:text-gray-400'>
+ &nbsp;(
+ {sessionDurationAVGCompare}
+ )
+ </span>
+ )}
+ </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>
+ <dl className='flex justify-between'>
+ <dt className='text-lg dark:text-gray-50'>
+ {t('dashboard.pageviews')}
+ :
+ </dt>
+ <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 ? (
+ <>
+ <ChevronUpIcon className='self-center flex-shrink-0 h-4 w-4 text-green-500' />
+ <span className='sr-only'>
+ {t('dashboard.inc')}
+ </span>
+ </>
+ ) : (
+ <>
+ <ChevronDownIcon 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>
+ </dl>
+ <dl className='flex justify-between'>
+ <dt className='text-lg dark:text-gray-50'>
+ {t('dashboard.unique')}
+ :
+ </dt>
+ <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 ? (
+ <>
+ <ChevronUpIcon className='self-center flex-shrink-0 h-4 w-4 text-green-500' />
+ <span className='sr-only'>
+ {t('dashboard.inc')}
+ </span>
+ </>
+ ) : (
+ <>
+ <ChevronDownIcon 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>
+ </dl>
+ </PanelContainer>
+ )
+}
+
+// Options for circle chart showing the stats of data
+const getPieOptions = (customs: any, uniques: number, t: any) => {
+ 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-slate-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-slate-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>`,
+ },
+ },
+ }
+}
+
+interface ICustomEvents {
+ customs: any
+ chartData: any
+ onFilter: any
+ t: (arg0: string) => string
+}
+
+interface ISortRows {
+ label: string
+ sortByAscend: boolean
+ sortByDescend: boolean
+}
+
+// Tabs with custom events like submit form, press button, go to the link rate etc.
+const CustomEvents = ({
+ customs, chartData, onFilter, t,
+}: ICustomEvents) => {
+ const [page, setPage] = useState(0)
+ const [customsEventsData, setCustomsEventsData] = useState<any>(customs)
+ const currentIndex = page * ENTRIES_PER_CUSTOM_EVENTS_PANEL
+ const keys = _keys(customsEventsData)
+ const keysToDisplay = useMemo(() => _slice(keys, currentIndex, currentIndex + ENTRIES_PER_CUSTOM_EVENTS_PANEL), [keys, currentIndex])
+ const uniques = _sum(chartData.uniques)
+ const [chartOptions, setChartOptions] = useState<any>({})
+ const [activeFragment, setActiveFragment] = useState<number>(0)
+ const totalPages = useMemo(() => _ceil(_size(keys) / ENTRIES_PER_CUSTOM_EVENTS_PANEL), [keys])
+ const canGoPrev = () => page > 0
+ const canGoNext = () => page < _floor((_size(keys) - 1) / ENTRIES_PER_CUSTOM_EVENTS_PANEL)
+ const [sort, setSort] = useState<ISortRows>({
+ label: 'quantity',
+ sortByAscend: false,
+ sortByDescend: false,
+ })
+
+ useEffect(() => {
+ const sizeKeys = _size(keys)
+
+ if (currentIndex > sizeKeys) {
+ setPage(_floor(sizeKeys / ENTRIES_PER_CUSTOM_EVENTS_PANEL))
+ }
+ }, [currentIndex, keys])
+
+ useEffect(() => {
+ setCustomsEventsData(customs)
+ setSort({
+ label: 'quantity',
+ sortByAscend: false,
+ sortByDescend: false,
+ })
+ }, [customs])
+
+ useEffect(() => {
+ setPage(0)
+ }, [chartData])
+
+ const onPrevious = () => {
+ if (canGoPrev()) {
+ setPage(page - 1)
+ }
+ }
+
+ const onNext = () => {
+ if (canGoNext()) {
+ setPage(page + 1)
+ }
+ }
+
+ const sortedAsc = (obj: any, sortByKeys?: boolean) => {
+ if (sortByKeys) {
+ return _fromPairs(_sortBy(_toPairs(obj), (pair) => pair[0]))
+ }
+
+ return _fromPairs(_toPairs(obj).sort((a: any, b: any) => {
+ return b[1] - a[1]
+ }))
+ }
+
+ const sortedDesc = (obj: any, sortByKeys?: boolean) => {
+ if (sortByKeys) {
+ return _fromPairs(_reverse(_sortBy(_toPairs(obj), (pair) => pair[0])))
+ }
+
+ return _fromPairs(_toPairs(obj).sort((a: any, b: any) => {
+ return a[1] - b[1]
+ }))
+ }
+
+ const onSortBy = (label: string) => {
+ const sortByKeys = label === 'event'
+
+ if (sort.sortByAscend) {
+ setCustomsEventsData(sortedDesc(customsEventsData, sortByKeys))
+ setSort({
+ label,
+ sortByAscend: false,
+ sortByDescend: true,
+ })
+ return
+ }
+
+ if (sort.sortByDescend) {
+ setCustomsEventsData(customs)
+ setSort({
+ label,
+ sortByAscend: false,
+ sortByDescend: false,
+ })
+ return
+ }
+
+ setCustomsEventsData(sortedAsc(customsEventsData, sortByKeys))
+ setSort({
+ label,
+ sortByAscend: true,
+ sortByDescend: false,
+ })
+ }
+
+ useEffect(() => {
+ if (!_isEmpty(chartData)) {
+ const options = getPieOptions(customsEventsData, uniques, t)
+ setChartOptions({
+ data: {
+ columns: _map(keys, (ev) => [ev, customsEventsData[ev]]),
+ type: pie(),
+ },
+ ...options,
+ })
+ }
+ }, [chartData, customsEventsData, 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 flex items-center cursor-pointer hover:opacity-90' onClick={() => onSortBy('event')}>
+ {t('project.event')}
+ <Sort
+ className='ml-1'
+ sortByAscend={sort.label === 'event' && sort.sortByAscend}
+ sortByDescend={sort.label === 'event' && sort.sortByDescend}
+ />
+ </th>
+ <th className='w-1/6 text-right'>
+ <p className='flex items-center cursor-pointer hover:opacity-90' onClick={() => onSortBy('quantity')}>
+ {t('project.quantity')}
+ <Sort
+ className='ml-1'
+ sortByAscend={sort.label === 'quantity' && sort.sortByAscend}
+ sortByDescend={sort.label === 'quantity' && sort.sortByDescend}
+ />
+ &nbsp;&nbsp;
+ </p>
+ </th>
+ <th className='w-1/6 text-right'>
+ <p className='flex items-center cursor-pointer hover:opacity-90' onClick={() => onSortBy('conversion')}>
+ {t('project.conversion')}
+ <Sort
+ className='ml-1'
+ sortByAscend={sort.label === 'conversion' && sort.sortByAscend}
+ sortByDescend={sort.label === 'conversion' && sort.sortByDescend}
+ />
+ </p>
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {_map(keysToDisplay, (ev) => (
+ <tr
+ key={ev}
+ className='text-gray-900 dark:text-gray-50 group hover:bg-gray-100 hover:dark:bg-slate-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'>
+ {customsEventsData[ev]}
+ &nbsp;&nbsp;
+ </td>
+ <td className='text-right'>
+ {/*
+ Added a uniques === 0 check because uniques value may be zero and dividing by zero will cause an
+ Infinity% value to be displayed.
+ */}
+ {uniques === 0 ? 100 : _round((customsEventsData[ev] / uniques) * 100, 2)}
+ %
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {/* for pagination in tabs */}
+ {_size(keys) > ENTRIES_PER_CUSTOM_EVENTS_PANEL && (
+ <div className='absolute bottom-0 w-card-toggle-sm sm:!w-card-toggle'>
+ <div className='flex justify-between select-none mb-2'>
+ <div>
+ <span className='text-gray-500 dark:text-gray-200 font-light lowercase text-xs'>
+ {_size(keys)}
+ {' '}
+ {t('project.results')}
+ </span>
+ <span className='text-gray-500 dark:text-gray-200 font-light text-xs'>
+ .
+ {' '}
+ {t('project.page')}
+ {' '}
+ {page + 1}
+ {' '}
+ /
+ {' '}
+ {totalPages}
+ </span>
+ </div>
+ <div className='flex justify-between w-[4.5rem]'>
+ <Button
+ className={cx('text-gray-500 dark:text-gray-200 font-light shadow bg-gray-100 dark:bg-slate-800 border-none px-1.5 py-0.5', {
+ 'opacity-50 cursor-not-allowed': !canGoPrev(),
+ 'hover:bg-gray-200 hover:dark:bg-slate-700': canGoPrev(),
+ })}
+ type='button'
+ onClick={onPrevious}
+ disabled={!canGoPrev()}
+ focus={false}
+ >
+ <ArrowLongLeftIcon className='w-5 h-5' />
+ </Button>
+ <Button
+ className={cx('text-gray-500 dark:text-gray-200 font-light shadow bg-gray-100 dark:bg-slate-800 border-none px-1.5 py-0.5', {
+ 'opacity-50 cursor-not-allowed': !canGoNext(),
+ 'hover:bg-gray-200 hover:dark:bg-slate-700': canGoNext(),
+ })}
+ onClick={onNext}
+ disabled={!canGoNext()}
+ type='button'
+ focus={false}
+ >
+ <ArrowLongRightIcon className='w-5 h-5' />
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+ </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,
+}
+
+interface IPanel {
+ name: string
+ data: any
+ rowMapper: any
+ valueMapper: any
+ capitalize: boolean
+ linkContent: boolean
+ t: (arg0: string) => string
+ icon: any
+ id: string
+ hideFilters: boolean
+ onFilter: any
+ customTabs?: any
+ pid?: string | null
+ period?: string | null
+ timeBucket?: string | null
+ from?: string | null
+ to?: string | null
+ timezone?: string | null
+ activeTab?: string
+ onFragmentChange?: (arg: number) => void
+ filters?: string[]
+}
+
+const Panel = ({
+ name, data, rowMapper, valueMapper, capitalize, linkContent, t, icon, id, hideFilters,
+ onFilter, customTabs, pid, period, timeBucket, from, to, timezone, activeTab, onFragmentChange, filters,
+}: IPanel): JSX.Element => {
+ 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 + ENTRIES_PER_PANEL), [keys, currentIndex])
+ const total = useMemo(() => _reduce(keys, (prev, curr) => prev + data[curr], 0), [keys]) // eslint-disable-line
+ const totalPages = useMemo(() => _ceil(_size(keys) / ENTRIES_PER_PANEL), [keys])
+ const [activeFragment, setActiveFragment] = useState(0)
+ const [modal, setModal] = useState(false)
+ const [isReversedUserFlow, setIsReversedUserFlow] = useState<boolean>(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)
+ }
+ }
+
+ const _setActiveFragment = (index: number) => {
+ setActiveFragment(index)
+
+ if (onFragmentChange) {
+ onFragmentChange(index)
+ }
+ }
+
+ // 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>
+ )
+ }
+
+ if (id === 'pg' && activeFragment === 1) {
+ return (
+ <PanelContainer
+ name={name}
+ icon={icon}
+ type={id}
+ activeFragment={activeFragment}
+ setActiveFragment={_setActiveFragment}
+ openModal={() => setModal(true)}
+ customTabs={customTabs}
+ >
+ {/* @ts-ignore */}
+ <UserFlow
+ disableLegend
+ pid={pid || ''}
+ period={period || ''}
+ timeBucket={timeBucket || ''}
+ from={from || ''}
+ to={to || ''}
+ timezone={timezone || ''}
+ filters={filters || []}
+ isReversed={isReversedUserFlow}
+ setReversed={() => setIsReversedUserFlow(!isReversedUserFlow)}
+ t={t}
+ />
+ <Modal
+ onClose={() => setModal(false)}
+ closeText={t('common.close')}
+ isOpened={modal}
+ customButtons={(
+ <button
+ type='button'
+ onClick={() => setIsReversedUserFlow(!isReversedUserFlow)}
+ className='mt-3 w-full inline-flex justify-center rounded-md dark:border-none border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:text-gray-50 dark:border-gray-600 dark:bg-slate-700 dark:hover:border-gray-600 dark:hover:bg-gray-700 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm'
+ >
+ {t('project.reverse')}
+ </button>
+ )}
+ message={(
+ <div className='h-[500px] dark:text-gray-800'>
+ {/* @ts-ignore */}
+ <UserFlow
+ pid={pid || ''}
+ period={period || ''}
+ timeBucket={timeBucket || ''}
+ from={from || ''}
+ to={to || ''}
+ timezone={timezone || ''}
+ filters={filters || []}
+ isReversed={isReversedUserFlow}
+ t={t}
+ />
+ </div>
+ )}
+ 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-slate-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-slate-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}
+ activeTab={activeTab}
+ >
+ {_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}
+ activeTab={activeTab}
+ >
+ {/* 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} activeTab={activeTab}>
+ {_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-slate-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'>
+ {activeTab === PROJECT_TABS.traffic ? nFormatter(valueData, 1) : 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) > ENTRIES_PER_PANEL && (
+ <div className='absolute bottom-0 w-card-toggle-sm sm:!w-card-toggle'>
+ <div className='flex justify-between select-none mb-2'>
+ <div>
+ <span className='text-gray-500 dark:text-gray-200 font-light lowercase text-xs'>
+ {_size(keys)}
+ {' '}
+ {t('project.results')}
+ </span>
+ <span className='text-gray-500 dark:text-gray-200 font-light text-xs'>
+ .
+ {' '}
+ {t('project.page')}
+ {' '}
+ {page + 1}
+ {' '}
+ /
+ {' '}
+ {totalPages}
+ </span>
+ </div>
+ <div className='flex justify-between w-[4.5rem]'>
+ <Button
+ className={cx('text-gray-500 dark:text-gray-200 font-light shadow bg-gray-100 dark:bg-slate-800 border-none px-1.5 py-0.5', {
+ 'opacity-50 cursor-not-allowed': !canGoPrev(),
+ 'hover:bg-gray-200 hover:dark:bg-slate-700': canGoPrev(),
+ })}
+ type='button'
+ onClick={onPrevious}
+ disabled={!canGoPrev()}
+ focus={false}
+ >
+ <ArrowLongLeftIcon className='w-5 h-5' />
+ </Button>
+ <Button
+ className={cx('text-gray-500 dark:text-gray-200 font-light shadow bg-gray-100 dark:bg-slate-800 border-none px-1.5 py-0.5', {
+ 'opacity-50 cursor-not-allowed': !canGoNext(),
+ 'hover:bg-gray-200 hover:dark:bg-slate-700': canGoNext(),
+ })}
+ onClick={onNext}
+ disabled={!canGoNext()}
+ type='button'
+ focus={false}
+ >
+ <ArrowLongRightIcon className='w-5 h-5' />
+ </Button>
+ </div>
+ </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,
+ onFragmentChange: PropTypes.func,
+}
+
+Panel.defaultProps = {
+ id: null,
+ rowMapper: null,
+ valueMapper: null,
+ capitalize: false,
+ linkContent: false,
+ onFilter: () => { },
+ hideFilters: false,
+ icon: null,
+ customTabs: [],
+ to: null,
+ from: null,
+ timezone: null,
+ timeBucket: null,
+ period: null,
+ pid: null,
+ activeTab: null,
+ onFragmentChange: () => { },
+ filters: [],
+}
+
+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/app/routes/project/view/__ViewProject.container.tsx b/app/routes/project/view/__ViewProject.container.tsx
new file mode 100644
index 000000000..04cb61d84
--- /dev/null
+++ b/app/routes/project/view/__ViewProject.container.tsx
@@ -0,0 +1,119 @@
+import { connect } from 'react-redux'
+import { errorsActions } from 'redux/reducers/errors'
+import UIActions from 'redux/reducers/ui'
+import { tabForSharedProject } from 'redux/constants'
+import { alertsActions } from 'redux/reducers/alerts'
+import { StateType, AppDispatch } from 'redux/store'
+import { IProject } from 'redux/models/IProject'
+import { ISharedProject } from 'redux/models/ISharedProject'
+
+import ViewProject from './__ViewProject'
+
+const mapStateToProps = (state: StateType) => {
+ 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,
+ extensions: state.ui.misc.extensions,
+ user: state.auth.user,
+ projectTab: state.ui.projects.projectTab,
+ customEventsPrefs: state.ui.cache.customEventsPrefs,
+ liveStats: state.ui.projects.liveStats,
+ password: state.ui.projects.password,
+ }
+ }
+
+ 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,
+ extensions: state.ui.misc.extensions,
+ user: state.auth.user,
+ projectTab: state.ui.projects.projectTab,
+ customEventsPrefs: state.ui.cache.customEventsPrefs,
+ liveStats: state.ui.projects.liveStats,
+ password: state.ui.projects.password,
+ }
+}
+
+const mapDispatchToProps = (dispatch: AppDispatch) => ({
+ showError: (message: string) => {
+ dispatch(errorsActions.genericError({
+ message,
+ }))
+ },
+ setProjectCache: (pid: string, data: any, key: string) => {
+ dispatch(UIActions.setProjectCache({
+ pid,
+ key,
+ data,
+ }))
+ },
+ setProjectViewPrefs: (pid: string, period: string, timeBucket: string, rangeDate?: Date[]) => {
+ dispatch(UIActions.setProjectViewPrefs({
+ pid,
+ period,
+ timeBucket,
+ rangeDate,
+ }))
+ },
+ setProjectCachePerf: (pid: string, data: any, key: string) => {
+ dispatch(UIActions.setProjectCachePerf({
+ pid,
+ data,
+ key,
+ }))
+ },
+ setPublicProject: (project: Partial<IProject | ISharedProject>) => {
+ dispatch(UIActions.setPublicProject({
+ project,
+ }))
+ },
+ setProjects: (project: Partial<IProject | ISharedProject>[], shared?: boolean) => {
+ dispatch(UIActions.setProjects({
+ projects: project,
+ shared,
+ }))
+ },
+ setLiveStatsForProject: (id: string, count: number) => {
+ dispatch(UIActions.setLiveStatsProject({
+ id,
+ count,
+ }))
+ },
+ generateAlert: (message: string, type: string) => {
+ dispatch(alertsActions.generateAlerts({
+ message,
+ type,
+ }))
+ },
+ setProjectTab: (tabs: string) => {
+ dispatch(UIActions.setProjectTab(tabs))
+ },
+ setProjectForcastCache: (pid: string, data: any, key: string) => {
+ dispatch(UIActions.setProjectForecastCache({
+ pid,
+ data,
+ key,
+ }))
+ },
+ setCustomEventsPrefs: (pid: string, data: any) => {
+ dispatch(UIActions.setCustomEventsPrefs({
+ pid,
+ data,
+ }))
+ },
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(ViewProject)
diff --git a/app/routes/project/view/__ViewProject.helpers.tsx b/app/routes/project/view/__ViewProject.helpers.tsx
new file mode 100644
index 000000000..d3d7ed4ce
--- /dev/null
+++ b/app/routes/project/view/__ViewProject.helpers.tsx
@@ -0,0 +1,952 @@
+import React from 'react'
+// @ts-ignore
+import { saveAs } from 'file-saver'
+import {
+ GlobeEuropeAfricaIcon, LanguageIcon, DocumentTextIcon, DeviceTabletIcon,
+ ArrowRightCircleIcon, MagnifyingGlassIcon, ServerIcon,
+} from '@heroicons/react/24/outline'
+// @ts-ignore
+import * as d3 from 'd3'
+import dayjs from 'dayjs'
+import {
+ area, areaSpline, spline, bar, line,
+} 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, tbsFormatMapperTooltip, tbsFormatMapperTooltip24h,
+} from 'redux/constants'
+import {
+ getTimeFromSeconds, getStringFromTime, sumArrays, nFormatter,
+} from 'utils/generic'
+import countries from 'utils/isoCountries'
+import _toNumber from 'lodash/toNumber'
+import _toString from 'lodash/toString'
+import _includes from 'lodash/includes'
+
+const getAvg = (arr: any) => {
+ const total = _reduce(arr, (acc, c) => acc + c, 0)
+ return total / _size(arr)
+}
+
+const getSum = (arr: any) => {
+ return _reduce(arr, (acc, c) => acc + c, 0)
+}
+
+const transformAIChartData = (data: {
+ [key: string]: any,
+}) => {
+ 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: any[]): string[] => {
+ 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(_toString(0))
+ } else {
+ trendData.push(_toString(y))
+ }
+ }
+
+ return trendData
+}
+
+const getExportFilename = (prefix: string) => {
+ // 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: any[]) => {
+ let str = 'name,value,perc\r\n'
+
+ for (let i = 0; i < _size(array); ++i) {
+ let lines = ''
+
+ _forEach(array[i], (index) => {
+ if (lines !== '') lines += ','
+ lines += index
+ })
+
+ str += `${lines}\r\n`
+ }
+
+ return str
+}
+
+const onCSVExportClick = (data: {
+ data: any,
+ types: any,
+}, pid: string, tnMapping: {
+ [key: string]: string,
+}, language: string) => {
+ 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',
+ customEvents: 'customEvents',
+}
+
+const FILTER_CHART_METRICS_MAPPING_FOR_COMPARE = ['bounce', 'viewsPerUnique', 'trendlines', 'customEvents']
+
+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: {
+ [key: string]: string[],
+}, activeChartMetrics: {
+ [key: string]: boolean,
+}, compareChart?: {
+ [key: string]: string[],
+}) => {
+ const {
+ views, bounce, viewsPerUnique, unique, trendlines, sessionDuration,
+ } = activeChartMetrics
+
+ const columns: any[] = [
+ ['x', ..._map(chart.x, el => dayjs(el).toDate())],
+ ]
+
+ if (unique) {
+ columns.push(['unique', ...chart.uniques])
+ if (trendlines) {
+ columns.push(['trendlineUnique', ...trendline(chart.uniques)])
+ }
+
+ if (compareChart?.uniques) {
+ columns.push(['uniqueCompare', ...compareChart.uniques])
+ }
+ }
+
+ if (views) {
+ columns.push(['total', ...chart.visits])
+ if (trendlines) {
+ columns.push(['trendlineTotal', ...trendline(chart.visits)])
+ }
+
+ if (compareChart?.visits) {
+ columns.push(['totalCompare', ...compareChart.visits])
+ }
+ }
+
+ if (bounce) {
+ const bounceArray = _map(chart.uniques, (el, i) => {
+ return _round((_toNumber(el) * 100) / _toNumber(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(_toNumber(el) / _toNumber(chart.uniques[i]), 1)
+ })
+ columns.push(['viewsPerUnique', ...viewsPerUniqueArray])
+ }
+
+ if (sessionDuration) {
+ columns.push(['sessionDuration', ...chart.sdur])
+
+ if (compareChart?.sdur) {
+ columns.push(['sessionDurationCompare', ...compareChart.sdur])
+ }
+ }
+
+ return columns
+}
+
+const getColumnsPerf = (chart: {
+ [key: string]: string[],
+}, activeChartMetrics: string, compareChart?: {
+ [key: string]: string[],
+}) => {
+ const columns: any[] = [
+ ['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 (compareChart?.dns && compareChart?.tls && compareChart?.conn && compareChart?.response && compareChart?.render && compareChart?.domLoad && compareChart?.ttfb) {
+ columns.push(['dnsCompare', ...compareChart.dns])
+ columns.push(['tlsCompare', ...compareChart.tls])
+ columns.push(['connCompare', ...compareChart.conn])
+ columns.push(['responseCompare', ...compareChart.response])
+ columns.push(['renderCompare', ...compareChart.render])
+ columns.push(['dom_loadCompare', ...compareChart.domLoad])
+ columns.push(['ttfbCompare', ...compareChart.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 (compareChart?.dns && compareChart?.tls && compareChart?.conn && compareChart?.response && compareChart?.render && compareChart?.domLoad && compareChart?.ttfb) {
+ columns.push(['frontendCompare', ...sumArrays(compareChart.render, compareChart.domLoad)])
+ columns.push(['networkCompare', ...sumArrays(compareChart.dns, compareChart.tls, compareChart.conn, compareChart.response)])
+ columns.push(['backendCompare', ...compareChart.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 (compareChart?.dns && compareChart?.tls && compareChart?.conn && compareChart?.response) {
+ columns.push(['dnsCompare', ...compareChart.dns])
+ columns.push(['tlsCompare', ...compareChart.tls])
+ columns.push(['connCompare', ...compareChart.conn])
+ columns.push(['responseCompare', ...compareChart.response])
+ }
+ }
+
+ if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.frontend) {
+ columns.push(['render', ...chart.render])
+ columns.push(['dom_load', ...chart.domLoad])
+
+ if (compareChart?.render && compareChart?.domLoad) {
+ columns.push(['renderCompare', ...compareChart.render])
+ columns.push(['dom_loadCompare', ...compareChart.domLoad])
+ }
+ }
+
+ if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.backend) {
+ columns.push(['ttfb', ...chart.ttfb])
+
+ if (compareChart?.ttfb) {
+ columns.push(['ttfbCompare', ...compareChart.ttfb])
+ }
+ }
+
+ return columns
+}
+
+const getValueForTooltipPerfomance = (chart: {
+ [key: string]: string[],
+}, id: string, index: number) => {
+ if (id === 'dns' || id === 'tls' || id === 'conn' || id === 'response' || id === 'render' || id === 'ttfb') {
+ return chart[id] ? chart[id][index] : 0
+ }
+
+ if (id === 'dom_load') {
+ return chart.domLoad ? chart.domLoad[index] : 0
+ }
+
+ if (id === 'frontend') {
+ const sum = sumArrays(chart.render, chart.domLoad)
+ return sum ? sum[index] : 0
+ }
+
+ if (id === 'network') {
+ const sum = sumArrays(chart.dns, chart.tls, chart.conn, chart.response)
+ return sum ? sum[index] : 0
+ }
+
+ if (id === 'backend') {
+ return chart.ttfb ? chart.ttfb[index] : 0
+ }
+
+ return 0
+}
+
+const stringToColour = (str: string) => {
+ let hash = 0
+
+ // Loop through each character in the string
+ for (let i = 0; i < str.length; i++) {
+ // Get the ASCII code for the current character
+ const charCode = str.charCodeAt(i)
+ // Update the hash value using a simple algorithm
+ hash = charCode + ((hash << 5) - hash)
+ }
+
+ // Initialise color value to #
+ let colour = '#'
+
+ // Generate 3-byte color code (RRGGBB)
+ for (let i = 0; i < 3; i++) {
+ // Get the next 8 bits of the hash value
+ const value = (hash >> (i * 8)) & 0xFF
+ // Convert the value to a 2-digit hex string
+ const hexString = (`00${value.toString(16)}`).substr(-2)
+ // Append the hex string to the color value
+ colour += hexString
+ }
+
+ // Return the resulting color value
+ return colour
+}
+
+// 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: any,
+ timeBucket: string,
+ activeChartMetrics: {
+ [key: string]: boolean,
+ },
+ applyRegions: boolean,
+ timeFormat: string,
+ forecasedChartData: {
+ [key: string]: string[],
+ },
+ rotateXAxias: boolean,
+ chartType: string,
+ customEvents?: {
+ [key: string]: string[],
+ },
+ compareChart?: {
+ [key: string]: string[],
+ },
+) => {
+ const xAxisSize = _size(chart.x)
+ const lines = []
+ const modifiedChart = { ...chart }
+ let regions
+ const customEventsToArray = customEvents ? _map(_keys(customEvents), (el) => {
+ return [el, ...customEvents[el]]
+ }) : []
+
+ let customEventsColors: {
+ [key: string]: string,
+ } = {}
+
+ if (_isEmpty(compareChart)) {
+ _forEach(_keys(customEvents), (el) => {
+ customEventsColors = {
+ ...customEventsColors,
+ [el]: stringToColour(el),
+ }
+ })
+ }
+
+ if (!_isEmpty(forecasedChartData) && _isEmpty(compareChart)) {
+ 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]
+ }
+
+ const columns = getColumns(modifiedChart, activeChartMetrics, compareChart)
+
+ 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: [...columns, ...customEventsToArray],
+ types: {
+ unique: chartType === chartTypes.line ? area() : bar(),
+ uniqueCompare: chartType === chartTypes.line ? line() : bar(),
+ total: chartType === chartTypes.line ? area() : bar(),
+ totalCompare: chartType === chartTypes.line ? line() : bar(),
+ bounce: chartType === chartTypes.line ? spline() : bar(),
+ bounceCompare: chartType === chartTypes.line ? spline() : bar(),
+ viewsPerUnique: chartType === chartTypes.line ? spline() : bar(),
+ trendlineUnique: spline(),
+ trendlineTotal: spline(),
+ sessionDuration: chartType === chartTypes.line ? spline() : bar(),
+ sessionDurationCompare: chartType === chartTypes.line ? spline() : bar(),
+ },
+ colors: {
+ unique: '#2563EB',
+ uniqueCompare: 'rgba(37, 99, 235, 0.4)',
+ total: '#D97706',
+ totalCompare: 'rgba(217, 119, 6, 0.4)',
+ bounce: '#2AC4B3',
+ bounceCompare: 'rgba(42, 196, 179, 0.4)',
+ viewsPerUnique: '#F87171',
+ trendlineUnique: '#436abf',
+ trendlineTotal: '#eba14b',
+ sessionDuration: '#c945ed',
+ sessionDurationCompare: 'rgba(201, 69, 237, 0.4)',
+ ...customEventsColors,
+ },
+ regions,
+ axes: {
+ bounce: 'y2',
+ sessionDuration: 'y2',
+ },
+ },
+ grid: {
+ x: {
+ lines,
+ },
+ },
+ transition: {
+ duration: 500,
+ },
+ resize: {
+ auto: true,
+ timer: false,
+ },
+ axis: {
+ x: {
+ clipPath: false,
+ tick: {
+ fit: true,
+ rotate: rotateXAxias ? 45 : 0,
+ format: timeFormat === TimeFormat['24-hour'] ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x) : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x),
+ },
+ localtime: timeFormat === TimeFormat['24-hour'],
+ type: 'timeseries',
+ },
+ y: {
+ tick: {
+ format: (d: number) => nFormatter(d, 1),
+ },
+ },
+ y2: {
+ show: activeChartMetrics.bounce || activeChartMetrics.sessionDuration,
+ tick: {
+ format: activeChartMetrics.bounce ? (d: string) => `${d}%` : (d: string) => getStringFromTime(getTimeFromSeconds(d)),
+ },
+ min: activeChartMetrics.bounce ? 10 : null,
+ max: activeChartMetrics.bounce ? 100 : null,
+ default: activeChartMetrics.bounce ? [10, 100] : null,
+ },
+ },
+ tooltip: {
+ contents: (item: any, _: any, __: any, color: any) => {
+ const typesOptionsToTypesCompare: {
+ [key: string]: string,
+ } = {
+ unique: 'uniques',
+ total: 'visits',
+ sessionDuration: 'sdur',
+ }
+
+ if (_isEmpty(compareChart)) {
+ return `<ul class='bg-gray-100 dark:text-gray-50 dark:bg-slate-800 rounded-md shadow-md px-3 py-1'>
+ <li class='font-semibold'>${timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)}</li>
+ <hr class='border-gray-200 dark:border-gray-600' />
+ ${_map(item, (el: {
+ id: string,
+ index: number,
+ name: string,
+ value: string,
+ x: Date,
+ }) => {
+ if (el.id === 'sessionDuration') {
+ return `
+ <li class='flex justify-between'>
+ <div class='flex justify-items-start'>
+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(el.id)}></div>
+ <span>${el.name}</span>
+ </div>
+ <span class='pl-4'>${getStringFromTime(getTimeFromSeconds(el.value))}</span>
+ </li>
+ `
+ }
+
+ if (el.id === 'trendlineUnique' || el.id === 'trendlineTotal') {
+ return ''
+ }
+
+ return `
+ <li class='flex justify-between'>
+ <div class='flex justify-items-start'>
+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(el.id)}></div>
+ <span>${el.name}</span>
+ </div>
+ <span class='pl-4'>${el.value}</span>
+ </li>
+ `
+ }).join('')}`
+ }
+
+ return `
+ <ul class='bg-gray-100 dark:text-gray-50 dark:bg-slate-800 rounded-md shadow-md px-3 py-1'>
+ ${_map(item, (el: {
+ id: string,
+ index: number,
+ name: string,
+ value: string,
+ x: Date,
+ }) => {
+ const {
+ id, index, name, value, x,
+ } = el
+
+ const xDataValueCompare = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(dayjs(compareChart?.x[index]).toDate()) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(dayjs(compareChart?.x[index]).toDate())
+ const xDataValue = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(x) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(x)
+ const valueCompare = id === 'sessionDuration' ? getStringFromTime(getTimeFromSeconds(compareChart?.[typesOptionsToTypesCompare?.[id]]?.[index])) : compareChart?.[typesOptionsToTypesCompare[id]]?.[index]
+
+ if (id === 'uniqueCompare' || id === 'totalCompare' || id === 'bounceCompare' || id === 'sessionDurationCompare') {
+ return ''
+ }
+
+ if (id === 'sessionDuration') {
+ return `
+ <div class='flex justify-between'>
+ <div class='flex justify-items-start'>
+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(id)}></div>
+ <span>${name}</span>
+ </div>
+ </div>
+ <hr class='border-gray-200 dark:border-gray-600' />
+ <li class='mt-1 ml-2'>
+ <p>
+ <span>${xDataValue}</span> -
+ <span>${getStringFromTime(getTimeFromSeconds(value))}</span>
+ </p>
+ ${(valueCompare && Number(compareChart?.[typesOptionsToTypesCompare?.[id]]?.[index]) > 0) ? `<p>
+ <span>${xDataValueCompare}</span> -
+ <span>${valueCompare}</span>
+ </p>` : ''}
+ </li>
+ `
+ }
+
+ return `
+ <div class='flex justify-between'>
+ <div class='flex justify-items-start'>
+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(id)}></div>
+ <span>${name}</span>
+ </div>
+ </div>
+ <hr class='border-gray-200 dark:border-gray-600' />
+ <li class='mt-1 ml-2'>
+ <p>
+ <span>${xDataValue}</span> - <span>${value}</span>
+ </p>
+ ${valueCompare ? `<p>
+ <span>${xDataValueCompare}</span> -
+ <span>${valueCompare}</span>
+ </p>` : ''}
+ </li>
+ `
+ }).join('')}
+ </ul>`
+ },
+ },
+ point: {
+ focus: {
+ only: xAxisSize > 1,
+ },
+ pattern: [
+ 'circle',
+ ],
+ r: 3,
+ },
+ legend: {
+ usePoint: true,
+ item: {
+ tile: {
+ width: 10,
+ },
+ },
+ hide: ['uniqueCompare', 'totalCompare', 'bounceCompare', 'sessionDurationCompare'],
+ },
+ area: {
+ linearGradient: true,
+ },
+ padding: {
+ right: (rotateXAxias && !(activeChartMetrics.bounce || activeChartMetrics.sessionDuration)) && 35,
+ left: 40,
+ },
+ bindto: '#dataChart',
+ }
+}
+
+const perfomanceChartCompare = ['dnsCompare', 'tlsCompare', 'connCompare', 'responseCompare', 'renderCompare', 'dom_loadCompare', 'ttfbCompare', 'frontendCompare', 'networkCompare', 'backendCompare']
+
+const getSettingsPerf = (
+ chart: {
+ [key: string]: string[]
+},
+ timeBucket: string,
+ activeChartMetrics: string,
+ rotateXAxias: boolean,
+ chartType: string,
+ timeFormat: string,
+ compareChart?: {
+ [key: string]: string[],
+ },
+) => {
+ const xAxisSize = _size(chart.x)
+
+ return {
+ data: {
+ x: 'x',
+ xFormat: tbsFormatMapper[timeBucket],
+ columns: getColumnsPerf(chart, activeChartMetrics, compareChart),
+ 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(),
+ dnsCompare: chartType === chartTypes.line ? spline() : bar(),
+ tlsCompare: chartType === chartTypes.line ? spline() : bar(),
+ connCompare: chartType === chartTypes.line ? spline() : bar(),
+ responseCompare: chartType === chartTypes.line ? spline() : bar(),
+ renderCompare: chartType === chartTypes.line ? spline() : bar(),
+ dom_loadCompare: chartType === chartTypes.line ? spline() : bar(),
+ ttfbCompare: chartType === chartTypes.line ? spline() : bar(),
+ frontendCompare: chartType === chartTypes.line ? spline() : bar(),
+ networkCompare: chartType === chartTypes.line ? spline() : bar(),
+ backendCompare: chartType === chartTypes.line ? spline() : bar(),
+ },
+ colors: {
+ dns: '#EC4319',
+ tls: '#F27059',
+ conn: '#F7A265',
+ response: '#F5D376',
+ render: '#709775',
+ dom_load: '#A5E6AB',
+ ttfb: '#00A8E8',
+ frontend: '#709775',
+ network: '#F7A265',
+ backend: '#00A8E8',
+ dnsCompare: 'rgba(236, 67, 25, 0.4)',
+ tlsCompare: 'rgba(242, 112, 89, 0.4)',
+ connCompare: 'rgba(247, 162, 101, 0.4)',
+ responseCompare: 'rgba(245, 211, 118, 0.4)',
+ renderCompare: 'rgba(112, 151, 117, 0.4)',
+ dom_loadCompare: 'rgba(165, 230, 171, 0.4)',
+ ttfbCompare: 'rgba(0, 168, 232, 0.4)',
+ frontendCompare: 'rgba(112, 151, 117, 0.4)',
+ networkCompare: 'rgba(247, 162, 101, 0.4)',
+ backendCompare: 'rgba(0, 168, 232, 0.4)',
+ },
+ groups: [
+ ['dns', 'tls', 'conn', 'response', 'render', 'dom_load', 'ttfb', 'frontend', 'network', 'backend'],
+ ['dnsCompare', 'tlsCompare', 'connCompare', 'responseCompare', 'renderCompare', 'dom_loadCompare', 'ttfbCompare', 'frontendCompare', 'networkCompare', 'backendCompare'],
+ ],
+ },
+ axis: {
+ x: {
+ clipPath: false,
+ tick: {
+ fit: true,
+ rotate: rotateXAxias ? 45 : 0,
+ format: timeFormat === TimeFormat['24-hour'] ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x) : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x),
+ },
+ localtime: timeFormat === TimeFormat['24-hour'],
+ type: 'timeseries',
+ },
+ y: {
+ tick: {
+ format: (d: string) => getStringFromTime(getTimeFromSeconds(d), true),
+ },
+ },
+ },
+ transition: {
+ duration: 500,
+ },
+ resize: {
+ auto: true,
+ timer: false,
+ },
+ tooltip: {
+ contents: (item: any, _: any, __: any, color: any) => {
+ if (_isEmpty(compareChart)) {
+ return `<ul class='bg-gray-100 dark:text-gray-50 dark:bg-slate-800 rounded-md shadow-md px-3 py-1'>
+ <li class='font-semibold'>${timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)}</li>
+ <hr class='border-gray-200 dark:border-gray-600' />
+ ${_map(item, (el: {
+ id: string,
+ index: number,
+ name: string,
+ value: string,
+ x: Date,
+ }) => {
+ return `
+ <li class='flex justify-between'>
+ <div class='flex justify-items-start'>
+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(el.id)}></div>
+ <span>${el.name}</span>
+ </div>
+ <span class='pl-4'>${getStringFromTime(getTimeFromSeconds(el.value), true)}</span>
+ </li>
+ `
+ }).join('')}`
+ }
+
+ return `
+ <ul class='bg-gray-100 dark:text-gray-50 dark:bg-slate-800 rounded-md shadow-md px-3 py-1'>
+ ${_map(item, (el: {
+ id: string,
+ index: number,
+ name: string,
+ value: string,
+ x: Date,
+ }) => {
+ const {
+ id, index, name, value, x,
+ } = el
+
+ const xDataValueCompare = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(dayjs(compareChart?.x[index]).toDate()) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(dayjs(compareChart?.x[index]).toDate())
+ const xDataValue = timeFormat === TimeFormat['24-hour'] ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(x) : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(x)
+ const valueCompare = getValueForTooltipPerfomance(compareChart, id, index)
+
+ if (_includes(perfomanceChartCompare, id)) {
+ return ''
+ }
+
+ return `
+ <div class='flex justify-between'>
+ <div class='flex justify-items-start'>
+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:${color(id)}></div>
+ <span>${name}</span>
+ </div>
+ </div>
+ <hr class='border-gray-200 dark:border-gray-600' />
+ <li class='mt-1 ml-2'>
+ <p>
+ <span>${xDataValue}</span> - <span>${getStringFromTime(getTimeFromSeconds(value), true)}</span>
+ </p>
+ ${valueCompare ? `<p>
+ <span>${xDataValueCompare}</span> -
+ <span>${getStringFromTime(getTimeFromSeconds(valueCompare), true)}</span>
+ </p>` : ''}
+ </li>
+ `
+ }).join('')}
+ </ul>`
+ },
+ },
+ point: {
+ focus: {
+ only: xAxisSize > 1,
+ },
+ pattern: [
+ 'circle',
+ ],
+ r: 3,
+ },
+ legend: {
+ usePoint: true,
+ item: {
+ tile: {
+ width: 10,
+ },
+ },
+ hide: perfomanceChartCompare,
+ },
+ 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 validFilters = ['cc', 'pg', 'lc', 'ref', 'dv', 'br', 'os', 'so', 'me', 'ca', 'lt', 'ev']
+
+const typeNameMapping = (t: (str: string) => string) => ({
+ 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'),
+ userFlow: t('main.competitiveFeatures.usfl'),
+})
+
+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: Date) => {
+ const yyyy = date.getFullYear()
+ let mm: string | number = date.getMonth() + 1
+ let dd: string | number = 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, noRegionPeriods, getSettings,
+ getExportFilename, getColumns, onCSVExportClick, CHART_METRICS_MAPPING,
+ CHART_METRICS_MAPPING_PERF, getColumnsPerf, getSettingsPerf, transformAIChartData, FILTER_CHART_METRICS_MAPPING_FOR_COMPARE,
+}
diff --git a/app/routes/project/view/__ViewProject.tsx b/app/routes/project/view/__ViewProject.tsx
new file mode 100644
index 000000000..e740056a8
--- /dev/null
+++ b/app/routes/project/view/__ViewProject.tsx
@@ -0,0 +1,2421 @@
+/* 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 { useNavigate, useParams, Link } from '@remix-run/react'
+// @ts-ignore
+import domToImage from 'dom-to-image'
+// @ts-ignore
+import { saveAs } from 'file-saver'
+import bb from 'billboard.js'
+import {
+ ArrowDownTrayIcon, Cog8ToothIcon, ArrowPathIcon, ChartBarIcon, BoltIcon, BellIcon,
+ PresentationChartBarIcon, PresentationChartLineIcon, NoSymbolIcon,
+} 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 _find from 'lodash/find'
+import _filter from 'lodash/filter'
+import _findIndex from 'lodash/findIndex'
+import _startsWith from 'lodash/startsWith'
+import _debounce from 'lodash/debounce'
+import _some from 'lodash/some'
+import _pickBy from 'lodash/pickBy'
+import _every from 'lodash/every'
+import _size from 'lodash/size'
+import _truncate from 'lodash/truncate'
+import _isString from 'lodash/isString'
+import PropTypes from 'prop-types'
+import * as SwetrixSDK from '@swetrix/sdk'
+
+import { withProjectProtected } from 'hoc/projectProtected'
+
+import { periodToCompareDate } from 'utils/compareConvertDate'
+
+import { getTimeFromSeconds, getStringFromTime } from 'utils/generic'
+import { getItem, setItem, removeItem } from 'utils/localstorage'
+
+import EventsRunningOutBanner from 'components/EventsRunningOutBanner'
+import {
+ tbPeriodPairs, getProjectCacheKey, LIVE_VISITORS_UPDATE_INTERVAL, DEFAULT_TIMEZONE, CDN_URL, isDevelopment,
+ timeBucketToDays, getProjectCacheCustomKey, roleViewer, MAX_MONTHS_IN_PAST, PROJECT_TABS,
+ TimeFormat, getProjectForcastCacheKey, chartTypes, roleAdmin, TRAFFIC_PANELS_ORDER, PERFORMANCE_PANELS_ORDER, isSelfhosted, tbPeriodPairsCompare,
+ PERIOD_PAIRS_COMPARE, filtersPeriodPairs, IS_ACTIVE_COMPARE, PROJECTS_PROTECTED, getProjectCacheCustomKeyPerf,
+} from 'redux/constants'
+import { IUser } from 'redux/models/IUser'
+import { IProject, ILiveStats } from 'redux/models/IProject'
+import { IProjectForShared, ISharedProject } from 'redux/models/ISharedProject'
+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 Forecast from 'modals/Forecast'
+import routes from 'routesPath'
+import {
+ getProjectData, getProject, getOverallStats, getLiveVisitors, getPerfData, getProjectDataCustomEvents, getProjectCompareData, checkPassword,
+} from 'api'
+import { getChartPrediction } from 'api/ai'
+import {
+ Panel, Overview, CustomEvents,
+} from './__Panels.panels'
+import {
+ onCSVExportClick, getFormatDate, panelIconMapping, typeNameMapping, validFilters, validPeriods,
+ validTimeBacket, noRegionPeriods, getSettings, getColumns, CHART_METRICS_MAPPING,
+ CHART_METRICS_MAPPING_PERF, getSettingsPerf, transformAIChartData, FILTER_CHART_METRICS_MAPPING_FOR_COMPARE,
+} from './__ViewProject.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/ProjectViewStyle.css'
+
+const CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH = 32
+
+interface IProjectView extends IProject {
+ isPublicVisitors?: boolean,
+}
+
+interface IViewProject {
+ projects: IProjectView[],
+ extensions: any,
+ isLoading: boolean,
+ showError: (message: string) => void,
+ cache: any,
+ cachePerf: any,
+ setProjectCache: (pid: string, data: any, key: string) => void,
+ projectViewPrefs: {
+ [key: string]: {
+ period: string,
+ timeBucket: string,
+ rangeDate?: Date[],
+ },
+ } | null,
+ setProjectViewPrefs: (pid: string, period: string, timeBucket: string, rangeDate?: Date[]) => void,
+ setPublicProject: (project: Partial<IProject | ISharedProject>) => void,
+ setLiveStatsForProject: (id: string, count: number) => void,
+ generateAlert: (message: string, type: string) => void,
+ setProjectCachePerf: (pid: string, data: any, key: string) => void,
+ setProjectForcastCache: (pid: string, data: any, key: string) => void,
+ authenticated: boolean,
+ user: IUser,
+ timezone: string,
+ sharedProjects: ISharedProject[],
+ projectTab: string,
+ setProjectTab: (tab: string) => void,
+ // eslint-disable-next-line no-unused-vars, no-shadow
+ setProjects: (projects: Partial<IProject | ISharedProject>[]) => void,
+ customEventsPrefs: any,
+ setCustomEventsPrefs: (pid: string, data: any) => void,
+ liveStats: ILiveStats,
+ password: {
+ [key: string]: string,
+ },
+}
+
+const ViewProject = ({
+ projects, isLoading: _isLoading, showError, cache, cachePerf, setProjectCache, projectViewPrefs, setProjectViewPrefs, setPublicProject,
+ setLiveStatsForProject, authenticated, timezone, user, sharedProjects, extensions, generateAlert, setProjectCachePerf,
+ projectTab, setProjectTab, setProjects, setProjectForcastCache, customEventsPrefs, setCustomEventsPrefs, liveStats, password,
+}: IViewProject) => {
+ // t is used for translation
+ const { t, i18n: { language } }: {
+ t: (key: string, options?: {
+ [key: string]: string | number | null,
+ }) => string,
+ i18n: {
+ language: string,
+ },
+ } = useTranslation('common')
+
+ // periodPairs is used for dropdown and updated when t changes
+ const [periodPairs, setPeriodPairs] = useState<{
+ label: string
+ period: string
+ tbs: string[]
+ countDays?: number
+ dropdownLabel?: string
+ isCustomDate?: boolean
+ }[]>(tbPeriodPairs(t))
+
+ // customExportTypes used for marketplace extensions if you have extensions with export
+ const [customExportTypes, setCustomExportTypes] = useState<any[]>([])
+ // customPanelTabs used for marketplace extensions if you have extensions with custom panel
+ const [customPanelTabs, setCustomPanelTabs] = useState<any[]>([])
+ // sdkInstance is a sdk used for dowland and working with marketplace extensions. DO NOT TOUCH IT
+ const [sdkInstance, setSdkInstance] = useState<any>(null)
+
+ // activeChartMetricsCustomEvents is a list of custom events for logic with api, chart and dropdown
+ const [activeChartMetricsCustomEvents, setActiveChartMetricsCustomEvents] = useState<any[]>([])
+
+ // dashboardRef is a ref for dashboard div
+ const dashboardRef = useRef<HTMLDivElement>(null)
+
+ // { id } is a project id from url
+ const { id }: {
+ id: string
+ } = useParams()
+ // navigate is a function for navigation
+ const navigate = useNavigate()
+
+ // find project by id from url from state in redux projects and sharedProjects. projects and sharedProjects loading from api in Saga on page load
+ const project: IProjectForShared = useMemo(() => _find([...projects, ..._map(sharedProjects, (item) => ({ ...item.project, role: item.role }))], p => p.id === id) || {} as IProjectForShared, [projects, id, sharedProjects])
+
+ const projectPassword: string = useMemo(() => password[id] || getItem(PROJECTS_PROTECTED)?.[id] || '', [id, password])
+
+ /* isSharedProject is a boolean check if project is shared. If isSharedProject is true,
+ we used role and other colummn from sharedProjects.
+ And it is used for remove settings button when user have role viewer or logic with Alert tabs */
+ const isSharedProject = useMemo(() => {
+ const foundProject = _find([..._map(sharedProjects, (item) => item.project)], p => p.id === id)
+ return !_isEmpty(foundProject)
+ }, [id, sharedProjects])
+
+ // areFiltersParsed used for check filters is parsed from url. If we have query params in url, we parse it and set to state
+ // when areFiltersParsed and areFiltersPerfParsed changed we call loadAnalytics or loadAnalyticsPerf and other func for load data
+ // all state with Parsed in name is used for parse query params from url
+ const [areFiltersParsed, setAreFiltersParsed] = useState<boolean>(false)
+ // similar areFiltersParsed but using for activeTab === 'performance'
+ const [areFiltersPerfParsed, setAreFiltersPerfParsed] = useState<boolean>(false)
+ // similar areFiltersParsed and areFiltersPerfParsed but using for period
+ const [arePeriodParsed, setArePeriodParsed] = useState<boolean>(false)
+ // similar areFiltersParsed and areFiltersPerfParsed but using for timeBucket
+ const [areTimeBucketParsed, setAreTimeBucketParsed] = useState<boolean>(false)
+
+ // panelsData is a data used for components <Panels /> and <CustomEvents />,
+ // also using for logic with custom events on chart and export data like csv
+ const [panelsData, setPanelsData] = useState<any>({})
+ // isPanelsDataEmpty is a true we are display components <NoEvents /> and do not show dropdowns with activeChartMetrics
+ const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState<boolean>(false)
+ const [isForecastOpened, setIsForecastOpened] = useState<boolean>(false)
+ // analyticsLoading is a boolean for show loader on chart
+ const [analyticsLoading, setAnalyticsLoading] = useState<boolean>(true)
+ // period using for logic with update data on chart. Set when user change period in dropdown and when we parse query params from url
+ const [period, setPeriod] = useState<string>(projectViewPrefs ? projectViewPrefs[id]?.period || periodPairs[3].period : periodPairs[3].period)
+ // timeBucket using for logic with update data on chart. Set when user change timeBucket in dropdown and when we parse query params from url
+ const [timeBucket, setTimebucket] = useState<string>(projectViewPrefs ? projectViewPrefs[id]?.timeBucket || periodPairs[3].tbs[1] : periodPairs[3].tbs[1])
+ // activeTab using for change tabs and display other data on chart. Like performance, traffic, custom events
+ const activePeriod = useMemo(() => _find(periodPairs, p => p.period === period), [period, periodPairs])
+ // chartData is a data for chart. It is a main data for chart
+ const [chartData, setChartData] = useState<any>({})
+ // mainChart is a ref for chart
+ const [mainChart, setMainChart] = useState<any>(null)
+ // dataLoading is a boolean for show loader on chart and do not load data when we have dataLoading === true
+ const [dataLoading, setDataLoading] = useState<boolean>(false)
+ // activeChartMetrics is a list of metrics for logic with api, chart and dropdown
+ // when user change metrics in dropdown, we change activeChartMetrics and show other data on chart
+ const [activeChartMetrics, setActiveChartMetrics] = useState<{
+ [key: string]: boolean
+ }>({
+ [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,
+ })
+ // similar activeChartMetrics but using for performance tab
+ const [activeChartMetricsPerf, setActiveChartMetricsPerf] = useState<string>(CHART_METRICS_MAPPING_PERF.timing)
+ // sessionDurationAVG using for tab overview. It is a data for session duration
+ const [sessionDurationAVG, setSessionDurationAVG] = useState<any>(null)
+ // checkIfAllMetricsAreDisabled when all metrics are disabled, we are hidden chart
+ const checkIfAllMetricsAreDisabled = useMemo(() => !_some({ ...activeChartMetrics, ...activeChartMetricsCustomEvents }, (value) => value), [activeChartMetrics, activeChartMetricsCustomEvents])
+ // filters - when we change filters we loading new data from api, update query url and update chart
+ const [filters, setFilters] = useState<any[]>([])
+ // similar filters but using for performance tab
+ const [filtersPerf, setFiltersPerf] = useState<any[]>([])
+ // 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<boolean>(true)
+
+ // isLoading is a true when we loading data from api
+ const isLoading = authenticated ? _isLoading : false
+ // tnMapping is a mapping for panels type
+ const tnMapping = typeNameMapping(t)
+ // refCalendar is a ref for calendar
+ const refCalendar = useRef(null)
+ // refCalendarCompare is a ref for calendar when compare is enabled
+ const refCalendarCompare = useRef(null)
+ // localStorageDateRange is a date range from local storage
+ const localStorageDateRange = projectViewPrefs ? projectViewPrefs[id]?.rangeDate : null
+ // dateRange is a date range for calendar
+ const [dateRange, setDateRange] = useState<null | Date[]>(localStorageDateRange ? [new Date(localStorageDateRange[0]), new Date(localStorageDateRange[1])] : null)
+ // activeTab traffic, performance, alerts
+ const [activeTab, setActiveTab] = useState<string>(() => {
+ // first we check if we have activeTab in url
+ // if we have activeTab in url, we return it
+ // if we do not have activeTab in url, we return activeTab from localStorage or default tab trafic
+ // @ts-ignore
+ const url = new URL(window.location)
+ const { searchParams } = url
+ const tab = searchParams.get('tab') as string
+
+ if (PROJECT_TABS[tab]) {
+ return tab || 'traffic'
+ }
+
+ return projectTab || PROJECT_TABS.traffic
+ })
+ // pgActiveFragment is a active fragment for pagination
+ const [pgActiveFragment, setPgActiveFragment] = useState<number>(0)
+
+ // TODO: THIS SHOULD BE MOVED TO REDUCERS WITH CACHE FUNCTIONALITY
+ // I PUT IT HERE JUST TO SEE IF IT WORKS WELL
+ // forecastData is a data for forecast chart
+ const [forecasedChartData, setForecasedChartData] = useState<any>({})
+
+ // chartDataPerf is a data for performance chart
+ const [chartDataPerf, setChartDataPerf] = useState<any>({})
+ // similar to isPanelsDataEmpty but using for performance tab
+ const [isPanelsDataEmptyPerf, setIsPanelsDataEmptyPerf] = useState<boolean>(false)
+ // similar to panelsData but using for performance tab
+ const [panelsDataPerf, setPanelsDataPerf] = useState<any>({})
+ // timeFormat is a time format for chart
+ const timeFormat = useMemo(() => user.timeFormat || TimeFormat['12-hour'], [user])
+ // ref, size using for logic with responsive chart
+ const [ref, size] = useSize() as any
+ // rotateXAxias using for logic with responsive chart
+ const rotateXAxias = useMemo(() => (size.width > 0 && size.width < 500), [size])
+ // customEventsChartData is a data for custom events on a chart
+ const customEventsChartData = useMemo(() => _pickBy(customEventsPrefs[id], (value, keyCustomEvents) => _includes(activeChartMetricsCustomEvents, keyCustomEvents)), [customEventsPrefs, id, activeChartMetricsCustomEvents])
+ // chartType is a type of chart, bar or line
+ const [chartType, setChartType] = useState<string>(getItem('chartType') as string || chartTypes.line)
+
+ // similar to periodPairs but using for compare
+ const [periodPairsCompare, setPeriodPairsCompare] = useState<{
+ label: string
+ period: string
+ }[]>(tbPeriodPairsCompare(t))
+ // similar to isActive but using for compare
+ const [isActiveCompare, setIsActiveCompare] = useState<boolean>(() => {
+ const activeCompare = getItem(IS_ACTIVE_COMPARE)
+
+ if (typeof activeCompare === 'string') {
+ return activeCompare === 'true'
+ }
+
+ if (typeof activeCompare === 'boolean') {
+ return activeCompare
+ }
+
+ return false
+ })
+ // similar to activePeriod but using for compare
+ const [activePeriodCompare, setActivePeriodCompare] = useState<string>(periodPairsCompare[0].period)
+ // activeDropdownLabelCompare is a label using for overview panels and dropdown
+ const activeDropdownLabelCompare = useMemo(() => _find(periodPairsCompare, p => p.period === activePeriodCompare)?.label, [periodPairsCompare, activePeriodCompare])
+ // dateRangeCompare is a date range for calendar when compare is enabled
+ const [dateRangeCompare, setDateRangeCompare] = useState<null | Date[]>(null)
+ // dataChartCompare is a data for chart when compare is enabled
+ const [dataChartCompare, setDataChartCompare] = useState<any>({})
+ // dataChartPerfCompare is a data for performance chart when compare is enabled
+ const [dataChartPerfCompare, setDataChartPerfCompare] = useState<any>({})
+ // maxRangeCompare is a max range for calendar when compare is enabled
+ const maxRangeCompare = useMemo(() => {
+ if (!isActiveCompare) {
+ return 0
+ }
+
+ const findActivePeriod = _find(periodPairs, p => p.period === period)
+
+ if (findActivePeriod?.period === 'custom' && dateRange) {
+ return dayjs.utc(dateRange[1]).diff(dayjs.utc(dateRange[0]), 'day')
+ }
+
+ return findActivePeriod?.countDays || 0
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isActiveCompare, period])
+ // similar for sessionDurationAVG but using in overview when compare enabled
+ const [sessionDurationAVGCompare, setSessionDurationAVGCompare] = useState<any>(null)
+
+ // tabs is a tabs for project
+ const tabs: {
+ id: string
+ label: string
+ icon: any
+ }[] = useMemo(() => {
+ const selfhostedOnly = [
+ {
+ id: PROJECT_TABS.traffic,
+ label: t('dashboard.traffic'),
+ icon: ChartBarIcon,
+ },
+ {
+ id: PROJECT_TABS.performance,
+ label: t('dashboard.performance'),
+ icon: BoltIcon,
+ },
+ ]
+
+ if (isSelfhosted) {
+ return selfhostedOnly
+ }
+
+ return [
+ ...selfhostedOnly,
+ {
+ id: PROJECT_TABS.alerts,
+ label: t('dashboard.alerts'),
+ icon: BellIcon,
+ },
+ ]
+ }, [t])
+
+ // pgPanelNameMapping is a mapping for panel names. Using for change name of panels pg if userFlow active
+ const pgPanelNameMapping = [
+ tnMapping.pg, // when fragment 0 is selected
+ tnMapping.userFlow, // when fragment 1 is selected
+ ]
+
+ // activeTabLabel is a label for active tab. Using for title in dropdown
+ const activeTabLabel = useMemo(() => _find(tabs, tab => tab.id === activeTab)?.label, [tabs, activeTab])
+
+ // { name } is a project name from project
+ const { name } = project
+
+ const pageTitle = user?.showLiveVisitorsInTitle ? `👀 ${liveStats[id]} - ${name}` : name
+
+ // sharedRoles is a role for shared project
+ const sharedRoles = useMemo(() => _find(user.sharedProjects, p => p.project.id === id)?.role || {}, [user, id])
+
+ // chartMetrics is a list of metrics for dropdown
+ 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],
+ },
+ {
+ id: CHART_METRICS_MAPPING.customEvents,
+ label: t('project.customEv'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.customEvents],
+ },
+ ]
+ }, [t, activeChartMetrics])
+
+ // chartMetricsPerf is a list of metrics for dropdown in performance tab
+ 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])
+
+ // chartMetricsCustomEvents is a list of custom events for dropdown
+ const chartMetricsCustomEvents = useMemo(() => {
+ if (!_isEmpty(panelsData.customs)) {
+ return _map(_keys(panelsData.customs), key => ({
+ id: key,
+ label: key,
+ active: _includes(activeChartMetricsCustomEvents, key),
+ }))
+ }
+ return []
+ }, [panelsData, activeChartMetricsCustomEvents])
+
+ // dataNamesCustomEvents is a list of custom events for chart
+ const dataNamesCustomEvents = useMemo(() => {
+ if (!_isEmpty(panelsData.customs)) {
+ return { ..._keys(panelsData.customs) }
+ }
+ return {}
+ }, [panelsData])
+
+ // dataNames is a list of metrics for chart
+ const dataNames = useMemo(() => {
+ return {
+ unique: t('project.unique'),
+ total: t('project.total'),
+ bounce: `${t('dashboard.bounceRate')} (%)`,
+ viewsPerUnique: t('dashboard.viewsPerUnique'),
+ trendlineTotal: t('project.trendlineTotal'),
+ trendlineUnique: t('project.trendlineUnique'),
+ sessionDuration: t('dashboard.sessionDuration'),
+ ...dataNamesCustomEvents,
+ }
+ }, [t, dataNamesCustomEvents])
+
+ // dataNamesPerf is a list of metrics for chart in performance tab
+ const dataNamesPerf = useMemo(() => {
+ return {
+ full: t('dashboard.timing'),
+ network: t('dashboard.network'),
+ frontend: t('dashboard.frontend'),
+ backend: t('dashboard.backend'),
+ dns: t('dashboard.dns'),
+ tls: t('dashboard.tls'),
+ conn: t('dashboard.conn'),
+ response: t('dashboard.response'),
+ render: t('dashboard.render'),
+ dom_load: t('dashboard.domLoad'),
+ ttfb: t('dashboard.ttfb'),
+ }
+ }, [t])
+
+ // switchActiveChartMetric is a function for change activeChartMetrics
+ // 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])
+
+ // onErrorLoading is a function for redirect to dashboard when project do not exist
+ const onErrorLoading = () => {
+ if (projectPassword) {
+ checkPassword(id, projectPassword).then((res) => {
+ if (res) {
+ navigate(_replace(routes.project, ':id', id))
+ return
+ }
+
+ showError(t('apiNotifications.incorrectPassword'))
+ navigate(_replace(routes.project_protected_password, ':id', id))
+ removeItem(PROJECTS_PROTECTED)
+ })
+ return
+ }
+
+ showError(t('project.noExist'))
+ navigate(routes.dashboard)
+ }
+
+ // loadCustomEvents is a function for load custom events data for chart from api
+ const loadCustomEvents = async () => {
+ if (_isEmpty(panelsData.customs)) {
+ return
+ }
+
+ let data = null
+ let from
+ let to
+
+ try {
+ setDataLoading(true)
+
+ if (dateRange) {
+ // if custom date range is selected
+ from = getFormatDate(dateRange[0])
+ to = getFormatDate(dateRange[1])
+ }
+
+ // customEventsChartData includes all activeChartMetricsCustomEvents return true if not false
+ const isAllActiveChartMetricsCustomEvents = _every(activeChartMetricsCustomEvents, (metric) => {
+ return _includes(_keys(customEventsChartData), metric)
+ })
+
+ // check if we need to load new date or we have data in redux/localstorage
+ if (!isAllActiveChartMetricsCustomEvents) {
+ // check if activePeriod is custom
+ if (period === 'custom' && dateRange) {
+ // activePeriod is custom
+ data = await getProjectDataCustomEvents(id, timeBucket, '', filters, from, to, timezone, activeChartMetricsCustomEvents, projectPassword)
+ } else {
+ // activePeriod is not custom
+ data = await getProjectDataCustomEvents(id, timeBucket, period, filters, '', '', timezone, activeChartMetricsCustomEvents, projectPassword)
+ }
+ }
+
+ const events = data?.chart ? data.chart.events : customEventsChartData
+
+ setCustomEventsPrefs(id, events)
+
+ const applyRegions = !_includes(noRegionPeriods, activePeriod?.period)
+ // render new settings for chart
+ const bbSettings = getSettings(chartData, timeBucket, activeChartMetrics, applyRegions, timeFormat, forecasedChartData, rotateXAxias, chartType, events)
+ // set chart data
+ setMainChart(() => {
+ // @ts-ignore
+ const generete = bb.generate(bbSettings)
+ generete.data.names(dataNames)
+ return generete
+ })
+ } catch (e) {
+ console.error('[ERROR] FAILED TO LOAD CUSTOM EVENTS', e)
+ } finally {
+ setDataLoading(false)
+ }
+ }
+
+ // loadCustomEvents when activeChartMetricsCustomEvents changed
+ useEffect(() => {
+ if (activeTab === PROJECT_TABS.traffic) {
+ loadCustomEvents()
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [activeChartMetricsCustomEvents])
+
+ // compareDisable is a function you need to use if you want to disable compare
+ const compareDisable = () => {
+ setIsActiveCompare(false)
+ setDateRangeCompare(null)
+ setDataChartCompare({})
+ setDataChartPerfCompare({})
+ setActivePeriodCompare(periodPairsCompare[0].period)
+ }
+
+ // loadAnalytics is a function for load data for chart from api
+ const loadAnalytics = async (forced = false, newFilters: any[] | null = null) => {
+ if (!forced && (isLoading || _isEmpty(project) || dataLoading)) {
+ return
+ }
+
+ setDataLoading(true)
+ try {
+ let data
+ let dataCompare
+ let key = ''
+ let keyCompare = ''
+ let from
+ let fromCompare: string | undefined
+ let to
+ let toCompare: string | undefined
+ let customEventsChart = customEventsChartData
+
+ // first we check isActiveCompare if comapre active we load compare date or check if we have data in redux/localstorage
+ // and set state dependent compare
+ if (isActiveCompare) {
+ if (dateRangeCompare && activePeriodCompare === PERIOD_PAIRS_COMPARE.CUSTOM) {
+ let start
+ let end
+ let diff
+ const startCompare = dayjs.utc(dateRangeCompare[0])
+ const endCompare = dayjs.utc(dateRangeCompare[1])
+ const diffCompare = endCompare.diff(startCompare, 'day')
+
+ if (activePeriod?.period === 'custom' && dateRange) {
+ start = dayjs.utc(dateRange[0])
+ end = dayjs.utc(dateRange[1])
+ diff = end.diff(start, 'day')
+ }
+
+ // @ts-ignore
+ if (activePeriod?.period === 'custom' ? diffCompare <= diff : diffCompare <= activePeriod?.countDays) {
+ fromCompare = getFormatDate(dateRangeCompare[0])
+ toCompare = getFormatDate(dateRangeCompare[1])
+ keyCompare = getProjectCacheCustomKey(fromCompare, toCompare, timeBucket)
+ } else {
+ showError(t('project.compareDateRangeError'))
+ compareDisable()
+ }
+ } else {
+ let date
+ if (dateRange) {
+ date = _find(periodToCompareDate, (item) => item.period === period)?.formula(dateRange)
+ } else {
+ date = _find(periodToCompareDate, (item) => item.period === period)?.formula()
+ }
+
+ if (date) {
+ fromCompare = date.from
+ toCompare = date.to
+ keyCompare = getProjectCacheCustomKey(fromCompare, toCompare, timeBucket)
+ }
+ }
+
+ if (!_isEmpty(fromCompare) && !_isEmpty(toCompare)) {
+ if (!_isEmpty(cache[id]) && !_isEmpty(cache[id][keyCompare]) && _isEmpty(newFilters || filters)) {
+ dataCompare = cache[id][keyCompare]
+ } else {
+ dataCompare = await getProjectCompareData(id, timeBucket, '', newFilters || filters, fromCompare, toCompare, timezone, projectPassword)
+ }
+ }
+
+ const processedSdur = getTimeFromSeconds(dataCompare?.avgSdur || 0)
+
+ setSessionDurationAVGCompare(getStringFromTime(processedSdur))
+
+ setProjectCache(id, dataCompare || {}, keyCompare)
+ }
+
+ // if activePeriod is custom we check dateRange and set key for cache
+ if (dateRange) {
+ from = getFormatDate(dateRange[0])
+ to = getFormatDate(dateRange[1])
+ key = getProjectCacheCustomKey(from, to, timeBucket)
+ } else {
+ key = getProjectCacheKey(period, timeBucket)
+ }
+
+ // check if we need to load new date or we have data in redux/localstorage
+ if (!forced && !_isEmpty(cache[id]) && !_isEmpty(cache[id][key]) && !_isEmpty(newFilters || filters)) {
+ data = cache[id][key]
+ } else {
+ if (period === 'custom' && dateRange) {
+ data = await getProjectData(id, timeBucket, '', newFilters || filters, from, to, timezone, projectPassword)
+ customEventsChart = await getProjectDataCustomEvents(id, timeBucket, '', filters, from, to, timezone, activeChartMetricsCustomEvents, projectPassword)
+ } else {
+ data = await getProjectData(id, timeBucket, period, newFilters || filters, '', '', timezone, projectPassword)
+ customEventsChart = await getProjectDataCustomEvents(id, timeBucket, period, filters, '', '', timezone, activeChartMetricsCustomEvents, projectPassword)
+ }
+
+ customEventsChart = customEventsChart?.chart ? customEventsChart.chart.events : customEventsChartData
+
+ setCustomEventsPrefs(id, customEventsChart)
+
+ setProjectCache(id, data || {}, key)
+ }
+
+ // using for extensions
+ 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(dataCompare) && !_isEmpty(dataCompare?.chart)) {
+ setDataChartCompare(dataCompare.chart)
+ }
+
+ if (_isEmpty(params)) {
+ setIsPanelsDataEmpty(true)
+ } else {
+ const applyRegions = !_includes(noRegionPeriods, activePeriod?.period)
+ const bbSettings = getSettings(chart, timeBucket, activeChartMetrics, applyRegions, timeFormat, forecasedChartData, rotateXAxias, chartType, customEventsChart, dataCompare?.chart)
+ setChartData(chart)
+
+ setPanelsData({
+ types: _keys(params),
+ data: params,
+ customs,
+ })
+
+ if (activeTab === PROJECT_TABS.traffic) {
+ setMainChart(() => {
+ // @ts-ignore
+ const generete = bb.generate(bbSettings)
+ generete.data.names(dataNames)
+ return generete
+ })
+ }
+
+ setIsPanelsDataEmpty(false)
+ }
+
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ } catch (e) {
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ setIsPanelsDataEmpty(true)
+ console.error('[ERROR](loadAnalytics) Loading analytics data failed')
+ console.error(e)
+ }
+ }
+
+ // similar to loadAnalytics but using for performance tab
+ const loadAnalyticsPerf = async (forced = false, newFilters: any[] | null = null) => {
+ if (!forced && (isLoading || _isEmpty(project) || dataLoading)) {
+ return
+ }
+
+ setDataLoading(true)
+ try {
+ let dataPerf
+ let key
+ let from
+ let to
+ let dataCompare
+ let keyCompare = ''
+ let fromCompare: string | undefined
+ let toCompare: string | undefined
+
+ if (isActiveCompare) {
+ if (dateRangeCompare && activePeriodCompare === PERIOD_PAIRS_COMPARE.CUSTOM) {
+ let start
+ let end
+ let diff
+ const startCompare = dayjs.utc(dateRangeCompare[0])
+ const endCompare = dayjs.utc(dateRangeCompare[1])
+ const diffCompare = endCompare.diff(startCompare, 'day')
+
+ if (activePeriod?.period === 'custom' && dateRange) {
+ start = dayjs.utc(dateRange[0])
+ end = dayjs.utc(dateRange[1])
+ diff = end.diff(start, 'day')
+ }
+
+ // @ts-ignore
+ if (activePeriod?.period === 'custom' ? diffCompare <= diff : diffCompare <= activePeriod?.countDays) {
+ fromCompare = getFormatDate(dateRangeCompare[0])
+ toCompare = getFormatDate(dateRangeCompare[1])
+ keyCompare = getProjectCacheCustomKeyPerf(fromCompare, toCompare, timeBucket)
+ } else {
+ showError(t('project.compareDateRangeError'))
+ compareDisable()
+ }
+ } else {
+ let date
+ if (dateRange) {
+ date = _find(periodToCompareDate, (item) => item.period === period)?.formula(dateRange)
+ } else {
+ date = _find(periodToCompareDate, (item) => item.period === period)?.formula()
+ }
+
+ if (date) {
+ fromCompare = date.from
+ toCompare = date.to
+ keyCompare = getProjectCacheCustomKeyPerf(fromCompare, toCompare, timeBucket)
+ }
+ }
+
+ if (!_isEmpty(fromCompare) && !_isEmpty(toCompare)) {
+ if (!_isEmpty(cache[id]) && !_isEmpty(cache[id][keyCompare]) && _isEmpty(newFilters || filtersPerf)) {
+ dataCompare = cache[id][keyCompare]
+ } else {
+ dataCompare = await getPerfData(id, timeBucket, '', newFilters || filtersPerf, fromCompare, toCompare, timezone, projectPassword)
+ }
+ }
+
+ setProjectCachePerf(id, dataCompare || {}, keyCompare)
+ }
+
+ 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, projectPassword)
+ } else {
+ dataPerf = await getPerfData(id, timeBucket, period, newFilters || filtersPerf, '', '', timezone, projectPassword)
+ }
+
+ setProjectCachePerf(id, dataPerf || {}, key)
+ }
+
+ const {
+ appliedFilters,
+ } = dataPerf
+
+ if (!_isEmpty(appliedFilters)) {
+ setFilters(appliedFilters)
+ }
+
+ if (_isEmpty(dataPerf)) {
+ setIsPanelsDataEmptyPerf(true)
+ setDataLoading(false)
+ setAnalyticsLoading(false)
+ return
+ }
+
+ if (!_isEmpty(dataCompare) && !_isEmpty(dataCompare?.chart)) {
+ setDataChartPerfCompare(dataCompare.chart)
+ }
+
+ if (_isEmpty(dataPerf.params)) {
+ setIsPanelsDataEmptyPerf(true)
+ } else {
+ const { chart: chartPerf } = dataPerf
+ const bbSettings = getSettingsPerf(chartPerf, timeBucket, activeChartMetricsPerf, rotateXAxias, chartType, timeFormat, dataCompare?.chart)
+ setChartDataPerf(chartPerf)
+
+ setPanelsDataPerf({
+ types: _keys(dataPerf.params),
+ data: dataPerf.params,
+ })
+
+ if (activeTab === PROJECT_TABS.performance) {
+ setMainChart(() => {
+ // @ts-ignore
+ const generete = bb.generate(bbSettings)
+ generete.data.names(dataNamesPerf)
+ return generete
+ })
+ }
+
+ setIsPanelsDataEmptyPerf(false)
+ }
+
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ } catch (e) {
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ setIsPanelsDataEmptyPerf(true)
+ 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: string, filter: any, 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)
+
+ // @ts-ignore
+ const url = new URL(window.location)
+ url.searchParams.delete(columnPerf)
+ const { pathname, search } = url
+ navigate(`?${search}`)
+ setFiltersPerf(newFiltersPerf)
+ } else {
+ newFiltersPerf = [
+ ...filtersPerf,
+ { column, filter, isExclusive },
+ ]
+
+ // @ts-ignore
+ const url = new URL(window.location)
+ url.searchParams.append(columnPerf, filter)
+ const { pathname, search } = url
+ navigate(`?${search}`)
+ 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
+
+ // @ts-ignore
+ const url = new URL(window.location)
+ url.searchParams.delete(column)
+ const { pathname, search } = url
+ navigate(`?${search}`)
+ } 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
+
+ // @ts-ignore
+ const url = new URL(window.location)
+ url.searchParams.append(column, filter)
+ const { pathname, search } = url
+ navigate(`?${search}`)
+ }
+ }
+
+ 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: string, filter: string, isExclusive: boolean) => {
+ 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
+ // @ts-ignore
+ 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
+ navigate(`?${search}`)
+ sdkInstance?._emitEvent('filtersupdate', newFilters)
+ }
+
+ // this function is used for requesting the data from the API when you press the reset button
+ const refreshStats = () => {
+ if (!isLoading && !dataLoading) {
+ if (activeTab === PROJECT_TABS.performance) {
+ loadAnalyticsPerf(true)
+ } else {
+ loadAnalytics(true)
+ }
+ }
+ }
+
+ // onForecastOpen is a function for open forecast modal
+ const onForecastOpen = () => {
+ if (isLoading || dataLoading) {
+ return
+ }
+
+ if (!_isEmpty(forecasedChartData)) {
+ setForecasedChartData({})
+ return
+ }
+
+ setIsForecastOpened(true)
+ }
+
+ // onForecastSubmit is a function for submit forecast modal
+ const onForecastSubmit = async (periodToForecast: string) => {
+ 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])
+
+ // this useEffect is used for parsing tab from url and set activeTab
+ useEffect(() => {
+ // @ts-ignore
+ const url = new URL(window.location)
+ url.searchParams.delete('tab')
+
+ url.searchParams.append('tab', activeTab)
+ const { pathname, search } = url
+ navigate(`?${search}`)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [activeTab])
+
+ // this useEffect is used for update chart settings when activeChartMetrics changed also using for perfomance tab
+ useEffect(() => {
+ if (activeTab === PROJECT_TABS.traffic) {
+ if ((!isLoading && !_isEmpty(chartData) && !_isEmpty(mainChart)) || (isActiveCompare && !_isEmpty(dataChartCompare) && !_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 || !activeChartMetrics.bounce || !activeChartMetrics.sessionDuration) {
+ const applyRegions = !_includes(noRegionPeriods, activePeriod?.period)
+ const bbSettings = getSettings(chartData, timeBucket, activeChartMetrics, applyRegions, timeFormat, forecasedChartData, rotateXAxias, chartType, customEventsChartData, dataChartCompare)
+
+ setMainChart(() => {
+ // @ts-ignore
+ 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, timeFormat, dataChartPerfCompare)
+
+ setMainChart(() => {
+ // @ts-ignore
+ const generete = bb.generate(bbSettings)
+ generete.data.names(dataNamesPerf)
+ return generete
+ })
+ }
+ }, [isLoading, activeChartMetrics, chartData, chartDataPerf, activeChartMetricsPerf, dataChartCompare]) // eslint-disable-line
+
+ // Initialising Swetrix SDK instance. Using for marketplace and extensions
+ useEffect(() => {
+ let sdk: any | null = null
+
+ const filteredExtensions = _filter(extensions, (ext) => _isString(ext.fileURL))
+
+ if (!_isEmpty(filteredExtensions)) {
+ const processedExtensions = _map(filteredExtensions, (ext) => {
+ const { id: extId, fileURL } = ext
+ return {
+ id: extId,
+ cdnURL: `${CDN_URL}file/${fileURL}`,
+ }
+ })
+
+ // @ts-ignore
+ sdk = new SwetrixSDK(processedExtensions, {
+ debug: isDevelopment,
+ }, {
+ onAddExportDataRow: (label: any, onClick: (e: any) => void) => {
+ setCustomExportTypes((prev) => [
+ ...prev,
+ {
+ label,
+ onClick,
+ },
+ ])
+ },
+ onRemoveExportDataRow: (label: any) => {
+ setCustomExportTypes((prev) => _filter(prev, (row) => row.label !== label))
+ },
+ onAddPanelTab: (extensionID: string, panelID: string, tabContent: any, onOpen: (a: any) => void) => {
+ setCustomPanelTabs((prev) => [
+ ...prev,
+ {
+ extensionID,
+ panelID,
+ tabContent,
+ onOpen,
+ },
+ ])
+ },
+ onRemovePanelTab: (extensionID: string, panelID: string) => {
+ 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. Using for marketplace and extensions
+ useEffect(() => {
+ sdkInstance?._emitEvent('timeupdate', {
+ period,
+ timeBucket,
+ dateRange: period === 'custom' ? dateRange : null,
+ })
+ }, [sdkInstance]) // eslint-disable-line
+
+ // Supplying 'projectinfo' event to the SDK after loading. Using for marketplace and extensions
+ 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
+
+ // when t update we update dropdowns translations
+ useEffect(() => {
+ setPeriodPairs(tbPeriodPairs(t))
+ setPeriodPairsCompare(tbPeriodPairsCompare(t))
+ }, [t])
+
+ // Parsing initial filters from url also using for perfomance tab
+ 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 {
+ // @ts-ignore
+ const url = new URL(window.location)
+ const { searchParams } = url
+ const initialFilters: any[] = []
+ // 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 {
+ // @ts-ignore
+ const url = new URL(window.location)
+ const { searchParams } = url
+ const initialFilters: any[] = []
+ // 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])
+
+ // Parsing timeBucket from url
+ useEffect(() => {
+ if (arePeriodParsed) {
+ try {
+ // @ts-ignore
+ 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 || periodPairs[3].tbs[1])
+ } finally {
+ setAreTimeBucketParsed(true)
+ }
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [arePeriodParsed])
+
+ // onRangeDateChange if is activeChartMetrics custom and we select custom date range
+ // we update url and state
+ const onRangeDateChange = (dates: Date[], onRender?: boolean) => {
+ const days = Math.ceil(Math.abs(dates[1].getTime() - dates[0].getTime()) / (1000 * 3600 * 24))
+ // @ts-ignore
+ 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
+ navigate(`?${search}`)
+ 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
+ navigate(`?${search}`)
+
+ 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 using for call loadAnalytics or loadAnalyticsPerf when smth dependencies changed
+ useEffect(() => {
+ if (areFiltersParsed && areTimeBucketParsed && arePeriodParsed) {
+ if (activeTab === PROJECT_TABS.traffic) {
+ loadAnalytics()
+ }
+ }
+ if (areFiltersPerfParsed && areTimeBucketParsed && arePeriodParsed) {
+ if (activeTab === PROJECT_TABS.performance) {
+ loadAnalyticsPerf()
+ }
+ }
+ }, [project, period, chartType, filters, forecasedChartData, timeBucket, periodPairs, areFiltersParsed, areTimeBucketParsed, arePeriodParsed, t, activeTab, areFiltersPerfParsed]) // eslint-disable-line
+
+ // using this for fix some bugs with update custom events data for chart
+ useEffect(() => {
+ if (!_isEmpty(activeChartMetricsCustomEvents)) {
+ setActiveChartMetricsCustomEvents([])
+ }
+ }, [period, filters]) // 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], projectPassword)
+
+ setLiveStatsForProject(pid, result[pid])
+ }
+
+ let interval: any = null
+ 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
+
+ // loadProject if project is empty so more often it is need for public projects
+ useEffect(() => {
+ if (!isLoading && _isEmpty(project)) {
+ getProject(id, false, projectPassword)
+ .then(projectRes => {
+ if (!_isEmpty(projectRes)) {
+ if (projectRes.isPasswordProtected && !projectRes.isOwner && _isEmpty(projectPassword)) {
+ navigate(_replace(routes.project_protected_password, ':id', id))
+ return
+ }
+
+ if ((projectRes.isPublic || projectRes?.isPasswordProtected) && !projectRes.isOwner) {
+ getOverallStats([id], projectPassword)
+ .then(res => {
+ setPublicProject({
+ ...projectRes,
+ overall: res[id],
+ isPublicVisitors: true,
+ })
+ })
+ .catch(e => {
+ console.error(e)
+ onErrorLoading()
+ })
+ } else {
+ getOverallStats([id])
+ .then(res => {
+ setProjects([...(projects as any[]), {
+ ...projectRes,
+ overall: res[id],
+ }])
+ })
+ .then(() => {
+ return getLiveVisitors([id], projectPassword)
+ })
+ .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
+
+ // updatePeriod using for update period and timeBucket also update url
+ const updatePeriod = (newPeriod: {
+ period: string
+ label?: string
+ }) => {
+ const newPeriodFull = _find(periodPairs, (el) => el.period === newPeriod.period)
+ let tb = timeBucket
+ // @ts-ignore
+ const url = new URL(window.location)
+ if (_isEmpty(newPeriodFull)) return
+
+ if (!_includes(newPeriodFull.tbs, timeBucket)) {
+ tb = _last(newPeriodFull.tbs) || 'day'
+ 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
+ navigate(`?${search}`)
+ sdkInstance?._emitEvent('timeupdate', {
+ period: newPeriod.period,
+ timeBucket: tb,
+ dateRange: newPeriod.period === 'custom' ? dateRange : null,
+ })
+ setForecasedChartData({})
+ }
+
+ // updateTimebucket using for update timeBucket also update url
+ const updateTimebucket = (newTimebucket: string) => {
+ // @ts-ignore
+ const url = new URL(window.location)
+ url.searchParams.delete('timeBucket')
+ url.searchParams.append('timeBucket', newTimebucket)
+ const { pathname, search } = url
+ navigate(`?${search}`)
+ setTimebucket(newTimebucket)
+ setProjectViewPrefs(id, period, newTimebucket, dateRange as Date[])
+ sdkInstance?._emitEvent('timeupdate', {
+ period,
+ timeBucket: newTimebucket,
+ dateRange,
+ })
+ setForecasedChartData({})
+ }
+
+ const openSettingsHandler = () => {
+ navigate(_replace(routes.project_settings, ':id', id))
+ }
+
+ // exportAsImageHandler using for export dashboard as image
+ 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)
+ }
+ }
+
+ // parse period from url when page is loaded
+ useEffect(() => {
+ try {
+ // @ts-ignore
+ const url = new URL(window.location)
+ const { searchParams } = url
+ const intialPeriod = projectViewPrefs ? searchParams.get('period') || projectViewPrefs[id]?.period : searchParams.get('period') || '7d'
+ const tab = searchParams.get('tab')
+
+ if (tab === PROJECT_TABS.performance) {
+ setProjectTab(PROJECT_TABS.performance)
+ }
+
+ if (!_includes(validPeriods, intialPeriod)) {
+ return
+ }
+
+ if (intialPeriod === 'custom') {
+ // @ts-ignore
+ const from = new Date(searchParams.get('from'))
+ // @ts-ignore
+ 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
+ }, [])
+
+ // check for conflicts in chart metrics in dropdown if conflicted disable some column of dropdown
+ const isConflicted = (conflicts: string[]) => {
+ const conflicted = conflicts && _some(conflicts, (conflict) => {
+ const conflictPair = _find(chartMetrics, (metric) => metric.id === conflict)
+ return conflictPair && conflictPair.active
+ })
+ return conflicted
+ }
+
+ // resetFilters using for reset filters and update url. Also using for components <NoEvents />
+ // its need for fix bug: when you select filter and you have not data and you can not reset filters
+ const resetFilters = () => {
+ // @ts-ignore
+ 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
+ navigate(`?${search}`)
+ 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: string) => {
+ setItem('chartType', type)
+ setChartType(type)
+ }
+
+ // loadAnalytics when compare period change or compare selected
+ useEffect(() => {
+ setItem(IS_ACTIVE_COMPARE, JSON.stringify(isActiveCompare))
+ if (activePeriodCompare === PERIOD_PAIRS_COMPARE.CUSTOM && !dateRangeCompare) {
+ return
+ }
+
+ if (isActiveCompare) {
+ if (activeTab === PROJECT_TABS.performance) {
+ loadAnalyticsPerf()
+ } else {
+ loadAnalytics()
+ }
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isActiveCompare, activePeriodCompare, dateRangeCompare])
+
+ if (!isLoading) {
+ return (
+ <div>
+ <EventsRunningOutBanner />
+ <div ref={ref} className='bg-gray-50 dark:bg-slate-900'>
+ <div
+ className={cx(
+ 'max-w-[1584px] w-full mx-auto 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)
+ if (selected) {
+ 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-gray-50 dark:border-gray-50'
+ : '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-gray-50' : '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 sm:flex-nowrap items-end sm:max-w-none justify-center sm:justify-between w-full sm:w-auto mx-auto sm:mx-0 custom-space-x-style gap-y-1'>
+ <div className='md:border-r border-gray-200 dark:border-gray-600 md:pr-3 sm:mr-3'>
+ <button
+ type='button'
+ title={t('project.refreshStats')}
+ 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-slate-800 dark:hover:bg-slate-700 focus:z-10 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 focus:dark:ring-gray-200 focus:dark:border-gray-200', {
+ 'cursor-not-allowed opacity-50': isLoading || dataLoading,
+ })}
+ >
+ <ArrowPathIcon className='w-5 h-5 text-gray-700 dark:text-gray-50' />
+ </button>
+ </div>
+ {(!isSelfhosted && !isActiveCompare) && (
+ <div
+ className={cx('md:border-r border-gray-200 dark:border-gray-600 md:pr-3 sm:mr-3', {
+ hidden: activeTab !== PROJECT_TABS.traffic || _isEmpty(chartData),
+ })}
+ >
+ <button
+ type='button'
+ title={t('modals.forecast.title')}
+ 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-slate-800 dark:hover:bg-slate-700 focus:z-10 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 focus:dark:ring-gray-200 focus:dark:border-gray-200', {
+ 'cursor-not-allowed opacity-50': isLoading || dataLoading || !_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-slate-800 dark:hover:bg-slate-700 focus:z-10 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 focus:dark:ring-gray-200 focus:dark:border-gray-200',
+ {
+ '-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-slate-200 dark:text-gray-50': timeBucket === tb,
+ 'text-gray-700 dark:text-gray-50 border-gray-300 dark:border-slate-800 ': timeBucket !== tb,
+ },
+ )}
+ >
+ {t(`project.${tb}`)}
+ </button>
+ ))}
+ </span>
+ </div>
+ <Dropdown
+ items={isActiveCompare ? _filter(periodPairs, (el) => {
+ return _includes(filtersPeriodPairs, el.period)
+ }) : _includes(filtersPeriodPairs, period) ? periodPairs : _filter(periodPairs, (el) => {
+ return el.period !== PERIOD_PAIRS_COMPARE.COMPARE
+ })}
+ title={activePeriod?.label}
+ labelExtractor={(pair) => pair.dropdownLabel || pair.label}
+ keyExtractor={(pair) => pair.label}
+ onSelect={(pair) => {
+ if (pair.period === PERIOD_PAIRS_COMPARE.COMPARE) {
+ if (activeTab !== PROJECT_TABS.traffic && activeTab !== PROJECT_TABS.performance) {
+ return
+ }
+
+ if (isActiveCompare) {
+ compareDisable()
+ } else {
+ setIsActiveCompare(true)
+ }
+
+ return
+ }
+
+ if (pair.isCustomDate) {
+ setTimeout(() => {
+ // @ts-ignore
+ refCalendar.current.openCalendar()
+ }, 100)
+ } else {
+ setPeriodPairs(tbPeriodPairs(t))
+ setDateRange(null)
+ updatePeriod(pair)
+ }
+ }}
+ />
+ {isActiveCompare && (
+ <>
+ <div className='mx-2 text-md font-medium text-gray-600 whitespace-pre-line dark:text-gray-200'>
+ vs
+ </div>
+ <Dropdown
+ items={periodPairsCompare}
+ title={activeDropdownLabelCompare}
+ labelExtractor={(pair) => pair.label}
+ keyExtractor={(pair) => pair.label}
+ onSelect={(pair) => {
+ if (pair.period === PERIOD_PAIRS_COMPARE.DISABLE) {
+ compareDisable()
+ return
+ }
+
+ if (pair.period === PERIOD_PAIRS_COMPARE.CUSTOM) {
+ setTimeout(() => {
+ // @ts-ignore
+ refCalendarCompare.current.openCalendar()
+ }, 100)
+ } else {
+ setPeriodPairsCompare(tbPeriodPairsCompare(t))
+ setDateRangeCompare(null)
+ setActivePeriodCompare(pair.period)
+ }
+ }}
+ />
+ </>
+ )}
+ <FlatPicker
+ ref={refCalendar}
+ onChange={setDateRange}
+ value={dateRange || []}
+ maxDateMonths={MAX_MONTHS_IN_PAST}
+ maxRange={0}
+ />
+ <FlatPicker
+ ref={refCalendarCompare}
+ onChange={(date) => {
+ setDateRangeCompare(date)
+ setActivePeriodCompare(PERIOD_PAIRS_COMPARE.CUSTOM)
+ setPeriodPairsCompare(tbPeriodPairsCompare(t, date))
+ }}
+ value={dateRangeCompare || []}
+ maxDateMonths={MAX_MONTHS_IN_PAST}
+ maxRange={maxRangeCompare}
+ />
+ </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 gap-y-1'>
+ {activeTab === PROJECT_TABS.traffic ? (
+ !isPanelsDataEmpty && (
+ <Dropdown
+ items={isActiveCompare ? _filter(chartMetrics, (el) => {
+ return !_includes(FILTER_CHART_METRICS_MAPPING_FOR_COMPARE, el.id)
+ }) : chartMetrics}
+ title={t('project.metricVis')}
+ labelExtractor={(pair) => {
+ const {
+ label, id: pairID, active, conflicts,
+ } = pair
+
+ const conflicted = isConflicted(conflicts)
+
+ if (pairID === CHART_METRICS_MAPPING.customEvents) {
+ if (_isEmpty(panelsData.customs)) {
+ return (
+ <span className='px-4 py-2 flex items-center cursor-not-allowed'>
+ <NoSymbolIcon className='w-5 h-5 mr-1' />
+ {label}
+ </span>
+ )
+ }
+
+ return (
+ <Dropdown
+ menuItemsClassName='max-w-[300px] max-h-[300px] overflow-auto'
+ items={chartMetricsCustomEvents}
+ title={label}
+ labelExtractor={(event) => (
+ <Checkbox
+ className={cx({ hidden: isPanelsDataEmpty || analyticsLoading })}
+ label={_size(event.label) > CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH ? (
+ <span title={event.label}>
+ {_truncate(event.label, { length: CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH })}
+ </span>
+ ) : event.label}
+ id={event.id}
+ onChange={() => { }}
+ checked={event.active}
+ />
+ )}
+ buttonClassName='group-hover:bg-gray-200 dark:group-hover:bg-slate-700 px-4 py-2 inline-flex w-full bg-white text-sm font-medium text-gray-700 dark:text-gray-50 dark:border-gray-800 dark:bg-slate-800'
+ keyExtractor={(event) => event.id}
+ onSelect={(event, e) => {
+ e?.stopPropagation()
+ e?.preventDefault()
+
+ setActiveChartMetricsCustomEvents((prev) => {
+ const newActiveChartMetricsCustomEvents = [...prev]
+ const index = _findIndex(prev, (item) => item === event.id)
+ if (index === -1) {
+ newActiveChartMetricsCustomEvents.push(event.id)
+ } else {
+ newActiveChartMetricsCustomEvents.splice(index, 1)
+ }
+ return newActiveChartMetricsCustomEvents
+ })
+ }}
+ />
+ )
+ }
+
+ return (
+ <Checkbox
+ className={cx('px-4 py-2', { hidden: isPanelsDataEmpty || analyticsLoading })}
+ label={label}
+ disabled={conflicted}
+ id={pairID}
+ checked={active}
+ />
+ )
+ }}
+ selectItemClassName='group text-gray-700 dark:text-gray-50 dark:border-gray-800 dark:bg-slate-800 block text-sm cursor-pointer hover:bg-gray-200 dark:hover:bg-slate-700'
+ keyExtractor={(pair) => pair.id}
+ onSelect={({ id: pairID, conflicts }) => {
+ if (isConflicted(conflicts)) {
+ generateAlert(t('project.conflictMetric'), 'error')
+ return
+ }
+
+ if (pairID === CHART_METRICS_MAPPING.customEvents) {
+ return
+ }
+
+ switchActiveChartMetric(pairID)
+ }}
+ />
+ )) : (
+ !isPanelsDataEmptyPerf && (
+ <Dropdown
+ items={chartMetricsPerf}
+ className='min-w-[170px] xs:min-w-0'
+ title={(
+ <p>
+ {_find(chartMetricsPerf, ({ id: chartId }) => chartId === activeChartMetricsPerf)?.label}
+ </p>
+ )}
+ labelExtractor={(pair) => pair.label}
+ keyExtractor={(pair) => pair.id}
+ onSelect={({ id: pairID }) => {
+ switchActiveChartMetric(pairID)
+ }}
+ />
+ )
+ )}
+ <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 !pr-3 pl-2 py-2 md:pr-4 ml-3 text-sm dark:text-gray-50 dark:border-gray-800 dark:bg-slate-800 dark:hover:bg-slate-700'
+ secondary
+ >
+ <>
+ <Cog8ToothIcon className='w-5 h-5 mr-1' />
+ {t('common.settings')}
+ </>
+ </Button>
+ )}
+ </div>
+ </div>
+ <div
+ className={cx({
+ hidden: isPanelsDataEmpty || analyticsLoading,
+ })}
+ >
+ <div className={cx('xs:mt-0', {
+ 'mt-14': project.public || (isSharedProject && project?.role === roleAdmin.role) || project.isOwner,
+ })}
+ />
+ <div className={cx('relative', {
+ hidden: checkIfAllMetricsAreDisabled,
+ })}
+ >
+ <div className={cx('absolute right-0 z-10 -top-2 max-sm:top-6 space-x-2', {
+ 'right-[90px]': activeChartMetrics[CHART_METRICS_MAPPING.sessionDuration],
+ 'right-[60px]': activeChartMetrics[CHART_METRICS_MAPPING.bounce],
+ })}
+ >
+ <button
+ type='button'
+ title={t('project.barChart')}
+ 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-slate-800 dark:hover:bg-slate-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'
+ title={t('project.lineChart')}
+ 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-slate-800 dark:hover:bg-slate-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} />
+ )}
+ {(isPanelsDataEmptyPerf && activeTab === PROJECT_TABS.performance) && (
+ <NoEvents filters={filters} resetFilters={resetFilters} />
+ )}
+ {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 mt-8' 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}
+ sessionDurationAVGCompare={sessionDurationAVGCompare}
+ isActiveCompare={isActiveCompare}
+ activeDropdownLabelCompare={activeDropdownLabelCompare}
+ dataChartCompare={dataChartCompare}
+ live={liveStats[id]}
+ projectId={id}
+ projectPassword={projectPassword}
+ />
+ )}
+ {!_isEmpty(panelsData.types) && _map(TRAFFIC_PANELS_ORDER, (type: keyof typeof tnMapping) => {
+ const panelName = tnMapping[type]
+ // @ts-ignore
+ 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}
+ activeTab={activeTab}
+ name={panelName}
+ data={panelsData.data[type]}
+ customTabs={customTabs}
+ rowMapper={(rowName) => (
+ <CCRow rowName={rowName} language={language} />
+ )}
+ />
+ )
+ }
+
+ if (type === 'dv') {
+ return (
+ <Panel
+ t={t}
+ key={type}
+ activeTab={activeTab}
+ 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}
+ activeTab={activeTab}
+ data={panelsData.data[type]}
+ customTabs={customTabs}
+ rowMapper={(rowName) => (
+ <RefRow rowName={rowName} showIcons={showIcons} />
+ )}
+ />
+ )
+ }
+
+ if (type === 'so' || type === 'me' || type === 'ca') {
+ return (
+ <Panel
+ t={t}
+ key={type}
+ icon={panelIcon}
+ id={type}
+ activeTab={activeTab}
+ onFilter={filterHandler}
+ name={panelName}
+ data={panelsData.data[type]}
+ customTabs={customTabs}
+ rowMapper={(row) => decodeURIComponent(row)}
+ />
+ )
+ }
+
+ if (type === 'pg') {
+ return (
+ <Panel
+ t={t}
+ key={type}
+ icon={panelIcon}
+ id={type}
+ onFilter={filterHandler}
+ onFragmentChange={setPgActiveFragment}
+ name={pgPanelNameMapping[pgActiveFragment]}
+ data={panelsData.data[type]}
+ customTabs={customTabs}
+ period={period}
+ activeTab={activeTab}
+ pid={id}
+ timeBucket={timeBucket}
+ filters={filters}
+ from={dateRange ? getFormatDate(dateRange[0]) : null}
+ to={dateRange ? getFormatDate(dateRange[1]) : null}
+ timezone={timezone}
+ />
+ )
+ }
+
+ return (
+ <Panel
+ t={t}
+ key={type}
+ icon={panelIcon}
+ id={type}
+ activeTab={activeTab}
+ 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-8 md:pt-4', { 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'>
+ {!_isEmpty(panelsDataPerf.types) && _map(PERFORMANCE_PANELS_ORDER, (type: keyof typeof tnMapping) => {
+ const panelName = tnMapping[type]
+ // @ts-ignore
+ 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}
+ activeTab={activeTab}
+ 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}
+ activeTab={activeTab}
+ data={panelsDataPerf.data[type]}
+ customTabs={customTabs}
+ valueMapper={(value) => getStringFromTime(getTimeFromSeconds(value), true)}
+ capitalize
+ />
+ )
+ }
+
+ return (
+ <Panel
+ t={t}
+ key={type}
+ icon={panelIcon}
+ id={type}
+ activeTab={activeTab}
+ 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>
+ )}
+ <Forecast
+ isOpened={isForecastOpened}
+ onClose={() => setIsForecastOpened(false)}
+ onSubmit={onForecastSubmit}
+ activeTB={t(`project.${timeBucket}`)}
+ tb={timeBucket}
+ />
+ </div>
+ )
+ }
+
+ return (
+ <div>
+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
+ <Loader />
+ </div>
+ </div>
+ )
+}
+
+ViewProject.propTypes = {
+ projects: PropTypes.arrayOf(PropTypes.object).isRequired,
+ sharedProjects: PropTypes.arrayOf(PropTypes.object).isRequired,
+ cache: 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,
+ timezone: PropTypes.string,
+}
+
+ViewProject.defaultProps = {
+ timezone: DEFAULT_TIMEZONE,
+}
+
+export default memo(withProjectProtected(ViewProject))
diff --git a/app/routes/project/view/components/CCRow.tsx b/app/routes/project/view/components/CCRow.tsx
new file mode 100644
index 000000000..bed9f85f1
--- /dev/null
+++ b/app/routes/project/view/components/CCRow.tsx
@@ -0,0 +1,35 @@
+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 }: {
+ rowName: string
+ language: string
+}): JSX.Element => (
+ <>
+ <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/app/routes/project/view/components/Filters.tsx b/app/routes/project/view/components/Filters.tsx
new file mode 100644
index 000000000..30299d6f0
--- /dev/null
+++ b/app/routes/project/view/components/Filters.tsx
@@ -0,0 +1,115 @@
+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,
+}: {
+ column: string
+ filter: string
+ isExclusive: boolean
+ // eslint-disable-next-line no-shadow
+ onRemoveFilter: (column: string, filter: string) => void
+ // eslint-disable-next-line no-shadow
+ onChangeExclusive: (column: string, filter: string, isExclusive: boolean) => void
+ tnMapping: Record<string, string>
+ language: string
+ t: (key: string) => string
+}): JSX.Element => {
+ 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-slate-800'>
+ {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-slate-800 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,
+}: {
+ filters: {
+ column: string
+ filter: string
+ isExclusive: boolean
+ }[]
+ // eslint-disable-next-line no-shadow
+ onRemoveFilter: (column: string, filter: string) => void
+ // eslint-disable-next-line no-shadow
+ onChangeExclusive: (column: string, filter: string, isExclusive: boolean) => void
+ tnMapping: Record<string, string>
+}) => {
+ 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/app/routes/project/view/components/InteractiveMap.tsx b/app/routes/project/view/components/InteractiveMap.tsx
new file mode 100644
index 000000000..f865bea10
--- /dev/null
+++ b/app/routes/project/view/components/InteractiveMap.tsx
@@ -0,0 +1,139 @@
+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 { StateType } from 'redux/store'
+import { getTimeFromSeconds, getStringFromTime, nFormatter } from 'utils/generic'
+
+import countriesList from 'utils/countries'
+import { useSelector } from 'react-redux'
+
+const InteractiveMap = ({ data, onClickCountry, total }: {
+ data: Record<string, number>
+ onClickCountry: (country: string) => void
+ total: number
+}) => {
+ const { t, i18n: { language } } = useTranslation('common')
+ const [hoverShow, setHoverShow] = useState<boolean>(false)
+ const [dataHover, setDataHover] = useState<{
+ countries: string
+ data: number
+ }>({} as {
+ countries: string
+ data: number
+ })
+ const [cursorPosition, setCursorPosition] = useState<{
+ pageX: number
+ pageY: number
+ }>({} as {
+ pageX: number
+ pageY: number
+ })
+
+ const projectTab = useSelector((state: StateType) => state.ui.projects.projectTab)
+ const isTrafficTab = projectTab === PROJECT_TABS.traffic
+
+ const onMouseMove = (e: React.MouseEvent<SVGSVGElement, MouseEvent>) => {
+ 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-slate-900 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 ? nFormatter(dataHover.data, 1) : 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/app/routes/project/view/components/LiveVisitorsDropdown.tsx b/app/routes/project/view/components/LiveVisitorsDropdown.tsx
new file mode 100644
index 000000000..9c48b80e4
--- /dev/null
+++ b/app/routes/project/view/components/LiveVisitorsDropdown.tsx
@@ -0,0 +1,96 @@
+import React, { useState, useEffect } from 'react'
+import _map from 'lodash/map'
+import { useTranslation } from 'react-i18next'
+// @ts-ignore
+import OutsideClickHandler from 'react-outside-click-handler'
+import {
+ ChevronDownIcon, ChevronUpIcon, XMarkIcon,
+} from '@heroicons/react/24/outline'
+import Flag from 'react-flagkit'
+
+import { getLiveVisitorsInfo, IGetLiveVisitorsInfo } from 'api'
+
+const LiveVisitorsDropdown = ({ live, projectId, projectPassword }: {
+ live: number | string,
+ projectId: string,
+ projectPassword?: string,
+}): JSX.Element => {
+ const { t } = useTranslation()
+ const [show, setShow] = useState<boolean>(false)
+ const [liveInfo, setLiveInfo] = useState<IGetLiveVisitorsInfo[]>([])
+ const [loading, setLoading] = useState<boolean>(true)
+
+ const getLiveVisitors = async () => {
+ await getLiveVisitorsInfo(projectId, projectPassword)
+ .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}` || 'N/A'}
+ {' '}
+ {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-slate-900 dark:border-slate-700/50 min-w-[250px] max-h-[200px] overflow-auto'>
+ <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-slate-800'>
+ <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>
+ )
+}
+
+LiveVisitorsDropdown.defaultProps = {
+ projectPassword: '',
+}
+
+export default LiveVisitorsDropdown
diff --git a/app/routes/project/view/components/NoEvents.tsx b/app/routes/project/view/components/NoEvents.tsx
new file mode 100644
index 000000000..9ff75e1d5
--- /dev/null
+++ b/app/routes/project/view/components/NoEvents.tsx
@@ -0,0 +1,80 @@
+import React, {
+ memo,
+} from 'react'
+import { useTranslation, Trans } from 'react-i18next'
+import _isEmpty from 'lodash/isEmpty'
+import PropTypes from 'prop-types'
+
+import Button from 'ui/Button'
+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,
+}: {
+ filters: {
+ column: string
+ filter: string
+ isExclusive: boolean
+ }[]
+ resetFilters: () => void
+}): JSX.Element => {
+ const { t }: {
+ t: (key: string) => string
+ } = useTranslation('common')
+
+ 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
+ // @ts-ignore
+ t={t}
+ i18nKey='project.noEvContent'
+ components={{
+ // eslint-disable-next-line jsx-a11y/anchor-has-content
+ url: <a title={`${t('titles.docs')} (opens in a new tab)`} 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>
+ )}
+ </div>
+ </div>
+ )
+}
+
+NoEvents.propTypes = {
+ filters: PropTypes.arrayOf(PropTypes.shape({
+ column: PropTypes.string,
+ filter: PropTypes.string,
+ isExclusive: PropTypes.bool,
+ })),
+ resetFilters: PropTypes.func.isRequired,
+}
+
+NoEvents.defaultProps = {
+ filters: [],
+}
+
+export default memo(NoEvents)
diff --git a/app/routes/project/view/components/RefRow.tsx b/app/routes/project/view/components/RefRow.tsx
new file mode 100644
index 000000000..bee34ee08
--- /dev/null
+++ b/app/routes/project/view/components/RefRow.tsx
@@ -0,0 +1,60 @@
+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 }: {
+ rowName: string
+ showIcons: boolean
+}): JSX.Element => {
+ let isUrl: boolean = true
+ let url: URL | null = null
+
+ try {
+ url = new URL(rowName) as URL
+ } 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/app/routes/project/view/components/UserFlow.tsx b/app/routes/project/view/components/UserFlow.tsx
new file mode 100644
index 000000000..8c5d080e1
--- /dev/null
+++ b/app/routes/project/view/components/UserFlow.tsx
@@ -0,0 +1,216 @@
+import React, { useEffect, useState, useMemo } from 'react'
+import { ResponsiveSankey } from '@nivo/sankey'
+import { connect } from 'react-redux'
+import { StateType, AppDispatch } from 'redux/store'
+import UIActions from 'redux/reducers/ui'
+import { errorsActions } from 'redux/reducers/errors'
+import { IUserFlow } from 'redux/models/IUserFlow'
+import _isEmpty from 'lodash/isEmpty'
+import { getUserFlowCacheKey, PROJECTS_PROTECTED } from 'redux/constants'
+import { getUserFlow } from 'api'
+import { getItem } from 'utils/localstorage'
+import Loader from 'ui/Loader'
+
+const mapStateToProps = (state: StateType) => ({
+ userFlowAscendingCache: state.ui.cache.userFlowAscending,
+ userFlowDescendingCache: state.ui.cache.userFlowDescending,
+ password: state.ui.projects.password,
+})
+
+const mapDispatchToProps = (dispatch: AppDispatch) => ({
+ setUserFlowAscending: (data: IUserFlow, pid: string, period: string) => {
+ dispatch(UIActions.setUserFlowAscending({
+ data,
+ pid,
+ period,
+ }))
+ },
+ setUserFlowDescending: (data: IUserFlow, pid: string, period: string) => {
+ dispatch(UIActions.setUserFlowDescending({
+ data,
+ pid,
+ period,
+ }))
+ },
+ generateError: (message: string) => {
+ dispatch(errorsActions.genericError({
+ message,
+ }))
+ },
+})
+
+const UserFlow = ({
+ disableLegend, pid, period, timeBucket, from, to, timezone, userFlowAscendingCache,
+ userFlowDescendingCache, filters, setReversed,
+ isReversed, setUserFlowAscending, setUserFlowDescending, generateError, t,
+ password,
+}: {
+ disableLegend?: boolean
+ pid: string
+ userFlowAscendingCache: {
+ [key: string]: IUserFlow
+ }
+ userFlowDescendingCache: {
+ [key: string]: IUserFlow
+ }
+ period: string
+ timezone: string
+ timeBucket: string
+ from: string
+ to: string
+ isReversed?: boolean
+ setUserFlowAscending: (data: IUserFlow, id: string, pd: string) => void
+ setUserFlowDescending: (data: IUserFlow, id: string, pd: string) => void
+ generateError: (message: string) => void
+ t: (key: string) => string
+ filters: string[]
+ setReversed: () => void
+ password: {
+ [key: string]: string
+ }
+}) => {
+ const key = getUserFlowCacheKey(pid, period)
+ const userFlowAscending = userFlowAscendingCache[key]
+ const userFlowDescending = userFlowDescendingCache[key]
+ const [isLoading, setIsLoading] = useState<boolean>(true)
+ const projectPassword: string = useMemo(() => password[pid] || getItem(PROJECTS_PROTECTED)?.[pid] || '', [pid, password])
+
+ const fetchUserFlow = async () => {
+ setIsLoading(true)
+ await getUserFlow(pid, timeBucket, period, filters, from, to, timezone, projectPassword)
+ .then((res: {
+ ascending: IUserFlow
+ descending: IUserFlow
+ }) => {
+ const { ascending, descending } = res
+
+ setUserFlowAscending(ascending, pid, period)
+ setUserFlowDescending(descending, pid, period)
+ })
+ .catch((err: Error) => {
+ generateError(err.message)
+ })
+ .finally(() => {
+ setIsLoading(false)
+ })
+ }
+
+ useEffect(() => {
+ if (_isEmpty(userFlowAscending) && _isEmpty(userFlowDescending)) {
+ fetchUserFlow()
+ } else if (isLoading) {
+ setIsLoading(false)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [period, timeBucket, from, to, timezone, pid])
+
+ useEffect(() => {
+ fetchUserFlow()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [filters])
+
+ if (isLoading) {
+ return <Loader />
+ }
+
+ if (!isReversed ? (_isEmpty(userFlowAscending) || _isEmpty(userFlowAscending?.nodes) || _isEmpty(userFlowAscending?.links)) : (_isEmpty(userFlowDescending) || _isEmpty(userFlowDescending?.links) || _isEmpty(userFlowDescending?.nodes))) {
+ return (
+ <>
+ <p className='flex mt-4 items-center justify-center text-md text-gray-900 dark:text-gray-50'>
+ {t('project.userFlow.noData')}
+ </p>
+ <button
+ type='button'
+ onClick={() => {
+ setReversed()
+ }}
+ className='mt-2 w-full inline-flex justify-center rounded-md dark:border-none border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:text-gray-50 dark:border-gray-600 dark:bg-slate-700 dark:hover:border-gray-600 dark:hover:bg-gray-700 sm:w-auto sm:text-sm'
+ >
+ {t('project.reverse')}
+ </button>
+
+ </>
+ )
+ }
+
+ return (
+ <ResponsiveSankey
+ // @ts-ignore
+ data={isReversed ? userFlowDescending : userFlowAscending}
+ margin={{
+ top: 0,
+ // right: disableLegend ? 0 : 120,
+ right: 0,
+ bottom: 0,
+ left: 20,
+ }}
+ align='justify'
+ colors={{ scheme: 'nivo' }}
+ nodeOpacity={1}
+ nodeHoverOthersOpacity={0.35}
+ nodeThickness={18}
+ nodeSpacing={24}
+ nodeBorderWidth={0}
+ nodeBorderColor={{
+ from: 'color',
+ modifiers: [
+ [
+ 'darker',
+ 0.8,
+ ],
+ ],
+ }}
+ nodeBorderRadius={3}
+ linkOpacity={0.5}
+ linkHoverOthersOpacity={0.1}
+ linkContract={3}
+ enableLinkGradient
+ labelPosition='outside'
+ labelOrientation='vertical'
+ labelPadding={16}
+ labelTextColor={{
+ from: 'color',
+ modifiers: [
+ [
+ 'darker',
+ 1,
+ ],
+ ],
+ }}
+ // legends={!disableLegend ? [
+ // {
+ // anchor: 'bottom-right',
+ // direction: 'column',
+ // translateX: 100,
+ // itemWidth: 100,
+ // itemHeight: 14,
+ // itemDirection: 'right-to-left',
+ // itemsSpacing: 2,
+ // itemTextColor: '#999',
+ // symbolSize: 14,
+ // effects: [
+ // {
+ // on: 'hover',
+ // style: {
+ // itemTextColor: '#000',
+ // },
+ // },
+ // ],
+ // },
+ // ] : []}
+ />
+ )
+}
+
+UserFlow.defaultProps = {
+ disableLegend: false,
+ isReversed: false,
+}
+
+const mergeProps = (stateProps: ReturnType<typeof mapStateToProps>, dispatchProps: ReturnType<typeof mapDispatchToProps>, ownProps: ReturnType<typeof UserFlow>) => ({
+ ...ownProps,
+ ...stateProps,
+ ...dispatchProps,
+})
+
+export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(UserFlow)
diff --git a/app/routesPath/index.ts b/app/routesPath/index.ts
index 6666ce850..61125c30d 100644
--- a/app/routesPath/index.ts
+++ b/app/routesPath/index.ts
@@ -3,7 +3,7 @@ const routes = Object.freeze({
signup: '/signup',
reset_password: '/recovery',
new_password_form: '/password-reset/:id',
- confirm_share: '/share/:id',
+ confirm_share: 'project/confirm_share/:id',
confirm_subcription: '/projects/:id/subscribers/invite',
main: '/',
dashboard: '/dashboard',
diff --git a/app/styles/ProjectViewStyle.css b/app/styles/ProjectViewStyle.css
new file mode 100644
index 000000000..4033bbaf4
--- /dev/null
+++ b/app/styles/ProjectViewStyle.css
@@ -0,0 +1,15 @@
+html.dark .bb-legend-item text {
+ fill: #f9fafb;
+}
+
+html.dark .bb-axis {
+ fill: #f9fafb;
+}
+
+@media (max-width: 640px) {
+ .custom-space-x-style > :not([hidden]) ~ :not([hidden]) {
+ --tw-space-x-reverse: 0 !important;
+ margin-right: calc(0.5rem * var(--tw-space-x-reverse)) !important;
+ margin-left: calc(0.5rem * calc(1 - var(--tw-space-x-reverse))) !important;
+ }
+}
diff --git a/app/utils/compareConvertDate.ts b/app/utils/compareConvertDate.ts
index a38691e96..ad7600a4c 100644
--- a/app/utils/compareConvertDate.ts
+++ b/app/utils/compareConvertDate.ts
@@ -1,7 +1,7 @@
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
-import { getFormatDate } from '../pages/Project/View/ViewProject.helpers'
+import { getFormatDate } from 'routes/project/view/__ViewProject.helpers'
dayjs.extend(utc)
diff --git a/package-lock.json b/package-lock.json
index 0c16e7d19..465126ba5 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -22,7 +22,7 @@
"billboard.js": "^3.8.0",
"clsx": "^1.2.1",
"d3": "^7.8.4",
- "dayjs": "^1.11.7",
+ "dayjs": "^1.11.8",
"debug": "^4.3.4",
"dom-to-image": "^2.6.0",
"file-saver": "^2.0.5",
diff --git a/package.json b/package.json
index daf22de39..229f60d70 100644
--- a/package.json
+++ b/package.json
@@ -29,7 +29,7 @@
"billboard.js": "^3.8.0",
"clsx": "^1.2.1",
"d3": "^7.8.4",
- "dayjs": "^1.11.7",
+ "dayjs": "^1.11.8",
"debug": "^4.3.4",
"dom-to-image": "^2.6.0",
"file-saver": "^2.0.5",