π 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
add pages
Maksim Mrugf7b48515bdc7
diff --git a/app/pages/About/index.tsx b/app/pages/About/index.tsxnew file mode 100644index 000000000..5b03ef995--- /dev/null+++ b/app/pages/About/index.tsx@@ -0,0 +1,169 @@+/* eslint-disable */+import React from 'react'+import _map from 'lodash/map'++import { CONTACT_EMAIL, GITHUB_URL } from 'redux/constants'+import Title from 'components/Title'++const socialIcons: {+ [key: string]: JSX.Element+} = {+ LinkedIn: (+ <img className='h-6 w-6 opacity-75 hover:opacity-90 bg-white rounded' aria-hidden='true' src='/assets/linkedin.svg' alt='LinkedIn' />+ ),+ Github: (+ <svg className='h-6 w-6' fill='currentColor' viewBox='0 0 24 24'>+ <path+ d='M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z'+ fillRule='evenodd'+ clipRule='evenodd'+ />+ </svg>+ ),+ Twitter: (+ <svg className='h-6 w-6' fill='currentColor' viewBox='0 0 24 24'>+ <path+ d='M8.29 20.251c7.547 0 11.675-6.253 11.675-11.675 0-.178 0-.355-.012-.53A8.348 8.348 0 0022 5.92a8.19 8.19 0 01-2.357.646 4.118 4.118 0 001.804-2.27 8.224 8.224 0 01-2.605.996 4.107 4.107 0 00-6.993 3.743 11.65 11.65 0 01-8.457-4.287 4.106 4.106 0 001.27 5.477A4.072 4.072 0 012.8 9.713v.052a4.105 4.105 0 003.292 4.022 4.095 4.095 0 01-1.853.07 4.108 4.108 0 003.834 2.85A8.233 8.233 0 012 18.407a11.616 11.616 0 006.29 1.84'+ fillRule='evenodd'+ clipRule='evenodd'+ />+ </svg>+ ),+}++const Teammate = ({+ photo, name, role, socials, desc,+}: {+ photo: string+ name: string+ role: string+ socials: {+ [key: string]: string+ }+ desc: string+}): JSX.Element => (+ <div className='flex flex-col lg:flex-row mt-6'>+ <img alt={name} src={photo} className='rounded-xl shadow-lg w-80' />+ <div className='ml-0 lg:ml-2'>+ <p className='text-3xl mt-2 lg:mt-0 font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ {name}+ </p>+ <p className='text-xl text-gray-900 dark:text-gray-50 tracking-tight'>+ {role}+ </p>+ <div className='flex space-x-4 mt-2'>+ {_map(socials, (value, key) => (+ <a key={value} href={value} title={key} target='_blank' rel='noopener noreferrer' className='text-gray-400 hover:text-gray-300' aria-label={`${key} (opens in a new tab)`}>+ <span className='sr-only'>{key}</span>+ {socialIcons[key]}+ </a>+ ))}+ </div>+ <p className='mt-2 lg:mt-5 text-lg whitespace-pre-line text-gray-900 dark:text-gray-50 tracking-tight'>+ {desc}+ </p>+ </div>+ </div>+)++const team: {+ name: string+ role: string+ photo: string+ desc: string+ socials: {+ [key: string]: string+ }+}[] = [+ {+ name: 'πΊπ¦ Andrii Romasiun',+ role: 'Founder; Product Developer.',+ photo: '/assets/andrii.jpg',+ desc: 'Works on Swetrix frontend and backend side.\nPartially marketing and product management.',+ socials: {+ LinkedIn: 'https://www.linkedin.com/in/andriir/',+ Twitter: 'https://twitter.com/blaumaus_',+ Github: 'https://github.com/Blaumaus',+ },+ },+ {+ name: 'πΊπ¦ Yehor Dremliuha',+ role: 'Co-Founder; Software Engineer.',+ photo: '/assets/yehor.jpg',+ desc: 'A great person.\nEnglish tutor, Python developer.\nWorks on Swetrix Python integrations, blog and anything related to the backend.',+ socials: {+ LinkedIn: 'https://www.linkedin.com/in/yehor-dremliuha-0b6161212/',+ Github: 'https://github.com/pro1code1hack',+ },+ },+ {+ name: 'πΊπ¦ Maxim Mrug',+ role: 'Co-Founder; Frontend Engineer.',+ photo: '/assets/maxim.jpg',+ desc: 'A great frontend developer.\nKnows JavaScript and TypeScript like his native language.',+ socials: {+ LinkedIn: 'https://www.linkedin.com/in/maksim-mrug-047b52235/',+ Github: 'https://github.com/kruzhambus',+ },+ },+ {+ name: 'πΊπ¦ Ivan Kolesov',+ role: 'Software Engineer; Data Scientist.',+ photo: '/assets/ivan.jpg',+ desc: 'Works on Swetrix Telegram integrations and Analytics logic.',+ socials: {+ Github: 'https://github.com/ivan1kolesov',+ },+ },+ {+ name: 'πΊπ¦ Yevhenii Kulisidi',+ role: 'Lead Backend Developer.',+ photo: '/assets/yevhenii.jpg',+ desc: 'An amazing backend engineer. Works on Swetrix API, Swetrix Marketplace and integrations.',+ socials: {+ Github: 'https://github.com/yevheniikulisidi',+ },+ },+]++const About = (): JSX.Element => (+ <Title title='About us'>+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>+ <div className='max-w-prose md:max-w-none md:w-8/12 mx-auto pb-16 pt-12 px-4 sm:px-6 lg:px-8 whitespace-pre-line'>+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ About us+ </h1>+ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ Swetrix was launched in August 2021 as a project that focuses on user privacy and transparency, while at the same time offering the same functionality as competitors like Google Analytics.+ <br />+ Swetrix is completely + <a href={GITHUB_URL} className='text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' target='_blank' rel='noopener noreferrer' aria-label='Source code (opens in a new tab)'>+ open source+ </a>+ , we don't use cookies to track users so you can forget about cookie banners using our service.+ <br />+ We will not and will never sell, abuse, share or otherwise negatively manipulate your data. Our priority is simplicity and transparency.+ </p>++ <h2 className='text-3xl mt-4 font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ Meet our team+ </h2>++ {_map(team, (el) => (+ <Teammate key={el.name} {...el} />+ ))}++ <hr className='mt-10 border-gray-200 dark:border-gray-600' />+ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ If you have read this far, why not + <a href={`mailto:${CONTACT_EMAIL}`} className='text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'>+ reach out to us?+ </a>+ We would be happy to hear feedback, criticism or suggestions from you!+ </p>+ </div>+ </div>+ </Title>+)++export default Aboutdiff --git a/app/pages/Auth/CreateNewPassword/CreateNewPassword.container.tsx b/app/pages/Auth/CreateNewPassword/CreateNewPassword.container.tsxnew file mode 100644index 000000000..6bec5f3f2--- /dev/null+++ b/app/pages/Auth/CreateNewPassword/CreateNewPassword.container.tsx@@ -0,0 +1,20 @@+import { connect } from 'react-redux'+import { errorsActions } from 'redux/reducers/errors'+import { alertsActions } from 'redux/reducers/alerts'+import { AppDispatch } from 'redux/store'+import CreateNewPassword from './CreateNewPassword'++const mapDispatchToProps = (dispatch: AppDispatch) => ({+ createNewPasswordFailed: (e: string) => {+ dispatch(errorsActions.createNewPasswordFailed({+ message: e,+ }))+ },+ newPassword: (message: string) => {+ dispatch(alertsActions.newPassword({+ message,+ }))+ },+})++export default connect(null, mapDispatchToProps)(CreateNewPassword)diff --git a/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx b/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsxnew file mode 100644index 000000000..b80d84559--- /dev/null+++ b/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx@@ -0,0 +1,156 @@+import React, { useState, useEffect, memo } from 'react'+import { Link, useHistory, useParams } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import _size from 'lodash/size'+import _keys from 'lodash/keys'+import _isEmpty from 'lodash/isEmpty'++import { createNewPassword } from 'api'+import { withAuthentication, auth } from 'hoc/protected'+import Title from 'components/Title'+import routes from 'routes'+import Input from 'ui/Input'+import Button from 'ui/Button'+import { isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS } from 'utils/validator'++interface FormSubmitData {+ password: string,+ repeat: string,+}++const CreateNewPassword = ({+ createNewPasswordFailed, newPassword,+}: {+ createNewPasswordFailed: (e: string) => void,+ newPassword: (message: string) => void,+}): JSX.Element => {+ const { t }: {+ t: (key: string, options?: { [key: string]: string | number }) => string,+ } = useTranslation('common')+ const history = useHistory()+ const { id }: {+ id: string,+ } = useParams()+ const [form, setForm] = useState<FormSubmitData>({+ password: '',+ repeat: '',+ })+ const [validated, setValidated] = useState<boolean>(false)+ const [errors, setErrors] = useState<{+ password?: string,+ repeat?: string,+ }>({})+ const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)+ const [isLoading, setIsLoading] = useState<boolean>(false)++ const validate = () => {+ const allErrors = {} as {+ password?: string,+ repeat?: string,+ }++ if (!isValidPassword(form.password)) {+ allErrors.password = t('auth.common.xCharsError', { amount: MIN_PASSWORD_CHARS })+ }++ if (form.password !== form.repeat || form.repeat === '') {+ allErrors.repeat = t('auth.common.noMatchError')+ }++ if (_size(form.password) > 50) {+ allErrors.password = t('auth.common.passwordTooLong', { amount: MAX_PASSWORD_CHARS })+ }++ const valid = _isEmpty(_keys(allErrors))++ setErrors(allErrors)+ setValidated(valid)+ }++ useEffect(() => {+ validate()+ }, [form]) // eslint-disable-line++ const onSubmit = async (data: FormSubmitData) => {+ if (!isLoading) {+ setIsLoading(true)+ try {+ const { password } = data+ await createNewPassword(id, password)++ newPassword(t('auth.recovery.updated'))+ history.push(routes.signin)+ } catch (e: any) {+ createNewPasswordFailed(e.toString())+ } 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)+ }+ }++ return (+ <Title title={t('titles.recovery')}>+ <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('auth.recovery.title')}+ </h2>+ <Input+ name='password'+ id='password'+ type='password'+ label={t('auth.recovery.newPassword')}+ hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}+ value={form.password}+ placeholder={t('auth.common.password')}+ className='mt-4'+ onChange={handleInput}+ error={beenSubmitted && errors.password}+ />+ <Input+ name='repeat'+ id='repeat'+ type='password'+ label={t('auth.common.repeat')}+ value={form.repeat}+ placeholder={t('auth.common.password')}+ className='mt-4'+ onChange={handleInput}+ error={beenSubmitted && errors.repeat}+ />+ <div className='flex justify-between mt-3'>+ <Link to={routes.signin} className='underline text-blue-600 hover:text-indigo-800 dark:text-blue-400 dark:hover:text-blue-500'>+ {t('auth.common.signinInstead')}+ </Link>+ <Button type='submit' loading={isLoading} primary large>+ {t('auth.recovery.save')}+ </Button>+ </div>+ </form>+ </div>+ </Title>+ )+}++export default memo(withAuthentication(CreateNewPassword, auth.notAuthenticated))diff --git a/app/pages/Auth/CreateNewPassword/index.tsx b/app/pages/Auth/CreateNewPassword/index.tsxnew file mode 100644index 000000000..2d019ca50--- /dev/null+++ b/app/pages/Auth/CreateNewPassword/index.tsx@@ -0,0 +1,3 @@+import CreateNewPassword from './CreateNewPassword.container'++export default CreateNewPassworddiff --git a/app/pages/Auth/ForgotPassword/ForgotPassword.container.tsx b/app/pages/Auth/ForgotPassword/ForgotPassword.container.tsxnew file mode 100644index 000000000..3f81d9023--- /dev/null+++ b/app/pages/Auth/ForgotPassword/ForgotPassword.container.tsx@@ -0,0 +1,20 @@+import { connect } from 'react-redux'+import { errorsActions } from 'redux/reducers/errors'+import { alertsActions } from 'redux/reducers/alerts'+import { AppDispatch } from 'redux/store'+import ForgotPassword from './ForgotPassword'++const mapDispatchToProps = (dispatch: AppDispatch) => ({+ createNewPasswordFailed: (e: string) => {+ dispatch(errorsActions.createNewPasswordFailed({+ message: e,+ }))+ },+ newPassword: (message: string) => {+ dispatch(alertsActions.newPassword({+ message,+ }))+ },+})++export default connect(null, mapDispatchToProps)(ForgotPassword)diff --git a/app/pages/Auth/ForgotPassword/ForgotPassword.tsx b/app/pages/Auth/ForgotPassword/ForgotPassword.tsxnew file mode 100644index 000000000..3eb6813d1--- /dev/null+++ b/app/pages/Auth/ForgotPassword/ForgotPassword.tsx@@ -0,0 +1,128 @@+import React, { useState, useEffect, memo } from 'react'+import { Link, useHistory } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import _keys from 'lodash/keys'+import _isEmpty from 'lodash/isEmpty'++import { forgotPassword } from 'api'+import Title from 'components/Title'+import { withAuthentication, auth } from 'hoc/protected'+import routes from 'routes'+import Input from 'ui/Input'+import Button from 'ui/Button'+import { isValidEmail } from 'utils/validator'++const ForgotPassword = ({+ createNewPasswordFailed, newPassword,+}: {+ createNewPasswordFailed: (e: string) => void,+ newPassword: (message: string) => void,+}): JSX.Element => {+ const { t }: {+ t: (key: string) => string,+ } = useTranslation('common')+ const history = useHistory()+ const [form, setForm] = useState<{+ email: string,+ }>({+ email: '',+ })+ const [validated, setValidated] = useState<boolean>(false)+ const [errors, setErrors] = useState<{+ email?: string,+ }>({})+ const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)+ const [isLoading, setIsLoading] = useState<boolean>(false)++ const validate = () => {+ const allErrors = {} as {+ email?: string,+ }++ if (!isValidEmail(form.email)) {+ allErrors.email = t('auth.common.badEmailError')+ }++ const valid = _isEmpty(_keys(allErrors))++ setErrors(allErrors)+ setValidated(valid)+ }++ useEffect(() => {+ validate()+ }, [form]) // eslint-disable-line++ const onSubmit = async (data: {+ email: string,+ }) => {+ if (!isLoading) {+ setIsLoading(true)++ try {+ await forgotPassword(data)++ newPassword(t('auth.forgot.sent'))+ history.push(routes.main)+ } catch (e: any) {+ createNewPasswordFailed(e.toString())+ } 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)+ }+ }++ return (+ <Title title={t('titles.recovery')}>+ <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.recovery')}+ </h2>+ <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}+ />+ <div className='flex justify-between mt-3'>+ <Link to={routes.signin} className='mt-1 underline text-blue-600 hover:text-indigo-800 dark:text-blue-400 dark:hover:text-blue-500'>+ {t('auth.common.signin')}+ </Link>+ <Button type='submit' loading={isLoading} primary large>+ {t('auth.forgot.reset')}+ </Button>+ </div>+ </form>+ </div>+ </Title>+ )+}++export default memo(withAuthentication(ForgotPassword, auth.notAuthenticated))diff --git a/app/pages/Auth/ForgotPassword/index.tsx b/app/pages/Auth/ForgotPassword/index.tsxnew file mode 100644index 000000000..657a2f2a9--- /dev/null+++ b/app/pages/Auth/ForgotPassword/index.tsx@@ -0,0 +1,3 @@+import ForgotPassword from './ForgotPassword.container'++export default ForgotPassworddiff --git a/app/pages/Auth/Signin/Signin.container.tsx b/app/pages/Auth/Signin/Signin.container.tsxnew file mode 100644index 000000000..16034accf--- /dev/null+++ b/app/pages/Auth/Signin/Signin.container.tsx@@ -0,0 +1,33 @@+import { connect } from 'react-redux'++import sagaActions from 'redux/sagas/actions'+import { authActions } from 'redux/reducers/auth'+import { errorsActions } from 'redux/reducers/errors'+import { AppDispatch } from 'redux/store'+import { IUser } from 'redux/models/IUser'+import Signin from './Signin'++const mapDispatchToProps = (dispatch: AppDispatch) => ({+ login: (data: {+ email: string,+ password: string,+ dontRemember: boolean+ }, callback: () => void) => {+ dispatch(sagaActions.loginAsync(data, callback))+ },+ loginSuccess: (user: IUser) => {+ dispatch(authActions.loginSuccessful(user))+ dispatch(sagaActions.loadProjects())+ dispatch(sagaActions.loadSharedProjects())+ },+ loginFailed: (error: string) => {+ dispatch(errorsActions.loginFailed({+ message: error,+ }))+ },+ authSSO: (provider: string, dontRemember: boolean, t: (key: string) => string, callback: (res: any) => void) => {+ dispatch(sagaActions.authSSO(provider, dontRemember, t, callback))+ },+})++export default connect(null, mapDispatchToProps)(Signin)diff --git a/app/pages/Auth/Signin/Signin.tsx b/app/pages/Auth/Signin/Signin.tsxnew file mode 100644index 000000000..e9e9e73d4--- /dev/null+++ b/app/pages/Auth/Signin/Signin.tsx@@ -0,0 +1,291 @@+import React, { useState, useEffect, memo } from 'react'+import { Link } from 'react-router-dom'+import PropTypes from 'prop-types'+import { useTranslation, Trans } from 'react-i18next'+import _keys from 'lodash/keys'+import _isEmpty from 'lodash/isEmpty'+import _isString from 'lodash/isString'++import Title from 'components/Title'+import GoogleAuth from 'components/GoogleAuth'+import GithubAuth from 'components/GithubAuth'+import { withAuthentication, auth } from 'hoc/protected'+import routes from 'routes'+import Input from 'ui/Input'+import Button from 'ui/Button'+import Checkbox from 'ui/Checkbox'+import {+ isValidEmail, isValidPassword, MIN_PASSWORD_CHARS,+} from 'utils/validator'+import { isSelfhosted } from 'redux/constants'+import { IUser } from 'redux/models/IUser'+import { submit2FA } from 'api'+import { setAccessToken, removeAccessToken } from 'utils/accessToken'+import { setRefreshToken, removeRefreshToken } from 'utils/refreshToken'++interface ISigninForm {+ email: string,+ password: string,+ dontRemember: boolean,+}++interface ISignin {+ login: (data: {+ email: string,+ password: string,+ dontRemember: boolean+ },+ callback: (result: boolean, twoFARequired: boolean) => void) => void,+ loginSuccess: (user: IUser) => void,+ loginFailed: (error: string) => void,+ authSSO: (provider: string, dontRemember: boolean, t: (key: string) => string, callback: (res: any) => void) => void+}++const Signin = ({+ login, loginSuccess, loginFailed, authSSO,+}: ISignin): JSX.Element => {+ const { t }: {+ t: (key: string, optinions?: {+ [key: string]: string | number,+ }) => string,+ } = useTranslation('common')+ const [form, setForm] = useState<ISigninForm>({+ email: '',+ password: '',+ dontRemember: false,+ })+ const [validated, setValidated] = useState<boolean>(false)+ const [errors, setErrors] = useState<{+ email?: string,+ password?: string,+ }>({})+ const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)+ const [isLoading, setIsLoading] = useState<boolean>(false)+ const [isTwoFARequired, setIsTwoFARequired] = useState<boolean>(false)+ const [twoFACode, setTwoFACode] = useState<string>('')+ const [twoFACodeError, setTwoFACodeError] = useState<string | null>(null)++ const validate = () => {+ const allErrors = {} as {+ email?: string,+ password?: string,+ }++ if (!isValidEmail(form.email)) {+ allErrors.email = t('auth.common.badEmailError')+ }++ if (!isValidPassword(form.password)) {+ allErrors.password = t('auth.common.xCharsError', { amount: MIN_PASSWORD_CHARS })+ }++ const valid = _isEmpty(_keys(allErrors))++ setErrors(allErrors)+ setValidated(valid)+ }++ useEffect(() => {+ validate()+ }, [form]) // eslint-disable-line++ const handle2FAInput = (event: React.ChangeEvent<HTMLInputElement>) => {+ const { target: { value } } = event+ setTwoFACode(value)+ setTwoFACodeError(null)+ }++ const loginCallback = (result: boolean, twoFARequired: boolean) => {+ if (!result) {+ setIsLoading(false)+ setIsTwoFARequired(twoFARequired)+ }+ }++ const onSubmit = (data: ISigninForm) => {+ if (!isLoading) {+ setIsLoading(true)+ login(data, loginCallback)+ }+ }++ const _submit2FA = async (e: React.FormEvent<HTMLFormElement>) => {+ e.preventDefault()+ e.stopPropagation()++ if (!isLoading) {+ setIsLoading(true)++ try {+ const { accessToken, refreshToken, user } = await submit2FA(twoFACode)+ removeAccessToken()+ removeRefreshToken()+ setAccessToken(accessToken)+ setRefreshToken(refreshToken)+ loginSuccess(user)+ } catch (err) {+ if (_isString(err)) {+ loginFailed(err)+ }+ console.error(`[ERROR] Failed to authenticate with 2FA: ${err}`)+ setTwoFACodeError(t('profileSettings.invalid2fa'))+ }++ setTwoFACode('')+ 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)+ }+ }++ if (isTwoFARequired) {+ return (+ <Title title={t('titles.signin')}>+ <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-prose mx-auto' onSubmit={_submit2FA}>+ <h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>+ {t('auth.signin.2fa')}+ </h2>+ <p className='mt-4 text-base whitespace-pre-line text-gray-900 dark:text-gray-50'>+ {t('auth.signin.2faDesc')}+ </p>+ <Input+ type='text'+ label={t('profileSettings.enter2faToDisable')}+ value={twoFACode}+ placeholder={t('auth.signin.6digitCode')}+ className='mt-4'+ onChange={handle2FAInput}+ disabled={isLoading}+ error={twoFACodeError}+ />+ <div className='flex justify-between mt-3'>+ <div className='whitespace-pre-line text-sm text-gray-600 dark:text-gray-400'>+ {!isSelfhosted && (+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='auth.signin.2faUnavailable'+ components={{+ ctl: <Link to={routes.contact} className='underline hover:text-gray-900 dark:hover:text-gray-200' />,+ }}+ />+ )}+ </div>+ <Button type='submit' loading={isLoading} primary large>+ {t('common.continue')}+ </Button>+ </div>+ </form>+ </div>+ </Title>+ )+ }++ return (+ <Title title={t('titles.signin')}>+ <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('auth.signin.title')}+ </h2>+ <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}+ />+ <Input+ name='password'+ id='password'+ type='password'+ label={t('auth.common.password')}+ hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}+ value={form.password}+ placeholder={t('auth.common.password')}+ className='mt-4'+ onChange={handleInput}+ error={beenSubmitted && errors.password}+ />+ <Checkbox+ checked={form.dontRemember}+ onChange={handleInput}+ name='dontRemember'+ id='dontRemember'+ className='mt-4'+ label={t('auth.common.noRemember')}+ />+ <div className='flex justify-between mt-3'>+ <div className='pt-1'>+ {!isSelfhosted && (+ <>+ <Link to={routes.reset_password} className='underline text-blue-600 hover:text-indigo-800 dark:text-blue-400 dark:hover:text-blue-500'>+ {t('auth.signin.forgot')}+ </Link>+ <span className='text-gray-900 dark:text-gray-50'> | </span>+ <Link to={routes.signup} className='underline text-blue-600 hover:text-indigo-800 dark:text-blue-400 dark:hover:text-blue-500' aria-label={t('titles.signup')}>+ {t('auth.common.signupInstead')}+ </Link>+ </>+ )}+ </div>+ <Button type='submit' loading={isLoading} primary large>+ {t('auth.signin.button')}+ </Button>+ </div>+ {!isSelfhosted && (+ <div className='flex flex-wrap'>+ <GoogleAuth+ className='mt-4 mr-5'+ setIsLoading={setIsLoading}+ authSSO={authSSO}+ callback={loginCallback}+ dontRemember={form.dontRemember}+ />+ <GithubAuth+ className='mt-4'+ setIsLoading={setIsLoading}+ authSSO={authSSO}+ callback={loginCallback}+ dontRemember={form.dontRemember}+ />+ </div>+ )}+ </form>+ </div>+ </Title>+ )+}++Signin.propTypes = {+ login: PropTypes.func.isRequired,+ loginSuccess: PropTypes.func.isRequired,+ loginFailed: PropTypes.func.isRequired,+ authSSO: PropTypes.func.isRequired,+}++export default memo(withAuthentication(Signin, auth.notAuthenticated))diff --git a/app/pages/Auth/Signin/index.tsx b/app/pages/Auth/Signin/index.tsxnew file mode 100644index 000000000..32520e958--- /dev/null+++ b/app/pages/Auth/Signin/index.tsx@@ -0,0 +1,3 @@+import Signin from './Signin.container'++export default Signindiff --git a/app/pages/Auth/Signup/BasicSignup.tsx b/app/pages/Auth/Signup/BasicSignup.tsxnew file mode 100644index 000000000..9f393569f--- /dev/null+++ b/app/pages/Auth/Signup/BasicSignup.tsx@@ -0,0 +1,217 @@+import React, { memo, useState, useEffect } from 'react'+import sagaActions from 'redux/sagas/actions'+import { useTranslation, Trans } from 'react-i18next'+import { useHistory } from 'react-router-dom'+import _size from 'lodash/size'+import _keys from 'lodash/keys'+import _isEmpty from 'lodash/isEmpty'+import _omit from 'lodash/omit'++import Input from 'ui/Input'+import Button from 'ui/Button'+import Checkbox from 'ui/Checkbox'+import Tooltip from 'ui/Tooltip'+import {+ isValidEmail, isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS,+} from 'utils/validator'+import { HAVE_I_BEEN_PWNED_URL } from 'redux/constants'+import { trackCustom } from 'utils/analytics'+import { useAppDispatch } from 'redux/store'+import GoogleAuth from 'components/GoogleAuth'+import GithubAuth from 'components/GithubAuth'+import routes from 'routes'++interface ISignUpForm {+ email: string,+ password: string,+ repeat: string,+ tos: boolean,+ dontRemember: boolean,+ checkIfLeaked: boolean,+}++const BasicSignup = (): JSX.Element => {+ const { t }: {+ t: (key: string, optinions?: {+ [key: string]: string | number,+ }) => string,+ } = useTranslation('common')+ const history = useHistory()+ const dispatch = useAppDispatch()+ const [form, setForm] = useState<ISignUpForm>({+ email: '',+ password: '',+ repeat: '',+ tos: true,+ dontRemember: false,+ checkIfLeaked: true,+ })+ const [validated, setValidated] = useState<boolean>(false)+ const [errors, setErrors] = useState<{+ email?: string,+ password?: string,+ repeat?: string,+ tos?: string,+ }>({})+ const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)+ const [isLoading, setIsLoading] = useState<boolean>(false)++ const signUpCallback = (result: boolean) => {+ if (result) {+ trackCustom('SIGNUP_BASIC')+ history.push(routes.dashboard)+ } else {+ setIsLoading(false)+ }+ }++ const authSSO = (provider: string) => {+ dispatch(sagaActions.authSSO(provider, form.dontRemember, t, signUpCallback))+ }++ const onSubmit = (data: ISignUpForm) => {+ if (!isLoading) {+ setIsLoading(true)+ dispatch(sagaActions.signupAsync(_omit(data, 'tos'), t, signUpCallback))+ }+ }++ const validate = () => {+ const allErrors = {} as {+ email?: string,+ password?: string,+ repeat?: string,+ }++ if (!isValidEmail(form.email)) {+ allErrors.email = t('auth.common.badEmailError')+ }++ if (!isValidPassword(form.password)) {+ allErrors.password = t('auth.common.xCharsError', { amount: MIN_PASSWORD_CHARS })+ }++ if (form.password !== form.repeat || form.repeat === '') {+ allErrors.repeat = t('auth.common.noMatchError')+ }++ if (_size(form.password) > 50) {+ allErrors.password = t('auth.common.passwordTooLong', { amount: MAX_PASSWORD_CHARS })+ }++ 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)+ }+ }++ return (+ <form className='space-y-6' onSubmit={handleSubmit}>+ <Input+ name='email'+ id='email'+ type='email'+ value={form.email}+ placeholder={t('auth.signup.email')}+ onChange={handleInput}+ error={beenSubmitted && errors.email}+ />+ <Input+ name='password'+ id='password'+ type='password'+ value={form.password}+ placeholder={t('auth.common.password')}+ className='mt-4'+ onChange={handleInput}+ error={beenSubmitted && errors.password}+ />+ <Input+ name='repeat'+ id='repeat'+ type='password'+ value={form.repeat}+ placeholder={t('auth.common.repeat')}+ className='mt-4'+ onChange={handleInput}+ error={beenSubmitted && errors.repeat}+ />+ <div className='flex mt-4'>+ <Checkbox+ checked={form.checkIfLeaked}+ onChange={handleInput}+ name='checkIfLeaked'+ id='checkIfLeaked'+ label={t('auth.common.checkLeakedPassword')}+ />+ <Tooltip+ className='ml-2'+ text={(+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='auth.common.checkLeakedPasswordDesc'+ components={{+ // eslint-disable-next-line jsx-a11y/anchor-has-content+ db: <a href={HAVE_I_BEEN_PWNED_URL} className='font-medium text-indigo-400 hover:underline hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' target='_blank' rel='noreferrer noopener' />,+ }}+ values={{+ database: 'haveibeenpwned.com',+ }}+ />+ )}+ />+ </div>+ <Button className='w-full flex justify-center' type='submit' loading={isLoading} primary giant>+ {t('auth.signup.create')}+ </Button>+ {/* SSO options */}+ <div>+ <hr className='mt-8 xs:mt-2 sm:mt-5 border-gray-200 dark:border-slate-700' />+ <p className='text-sm mt-2 mb-2 text-center text-gray-500 dark:text-gray-100'>+ {t('auth.socialisation.orSingUpWith')}+ </p>+ <div className='flex justify-around space-x-5'>+ <GoogleAuth+ className='w-full flex justify-center'+ setIsLoading={setIsLoading}+ authSSO={authSSO}+ isMiniButton+ />+ <GithubAuth+ className='w-full flex justify-center'+ setIsLoading={setIsLoading}+ authSSO={authSSO}+ isMiniButton+ />+ </div>+ </div>+ </form>+ )+}++export default memo(BasicSignup)diff --git a/app/pages/Auth/Signup/Signup.container.tsx b/app/pages/Auth/Signup/Signup.container.tsxnew file mode 100644index 000000000..6eebdce45--- /dev/null+++ b/app/pages/Auth/Signup/Signup.container.tsx@@ -0,0 +1,23 @@+import { connect } from 'react-redux'+import { AppDispatch } from 'redux/store'+import sagaActions from 'redux/sagas/actions'+import Signup from './Signup'++const mapDispatchToProps = (dispatch: AppDispatch) => ({+ signup: (data: {+ email: string,+ password: string,+ repeat: string,+ dontRemember: boolean,+ checkIfLeaked: boolean,+ }, t: (key: string, optinions?: {+ [key: string]: string | number,+ }) => string, callback: (res: any) => void) => {+ dispatch(sagaActions.signupAsync(data, t, callback))+ },+ authSSO: (provider: string, dontRemember: boolean, t: (key: string) => string, callback: (res: any) => void) => {+ dispatch(sagaActions.authSSO(provider, dontRemember, t, callback))+ },+})++export default connect(null, mapDispatchToProps)(Signup)diff --git a/app/pages/Auth/Signup/Signup.tsx b/app/pages/Auth/Signup/Signup.tsxnew file mode 100644index 000000000..c2da709c9--- /dev/null+++ b/app/pages/Auth/Signup/Signup.tsx@@ -0,0 +1,282 @@+import React, { useState, useEffect, memo } from 'react'+import { Link } from 'react-router-dom'+import PropTypes from 'prop-types'+import { useTranslation, Trans } from 'react-i18next'+import _size from 'lodash/size'+import _keys from 'lodash/keys'+import _omit from 'lodash/omit'+import _isEmpty from 'lodash/isEmpty'++import Title from 'components/Title'+import GoogleAuth from 'components/GoogleAuth'+import GithubAuth from 'components/GithubAuth'+import { withAuthentication, auth } from 'hoc/protected'+import routes from 'routes'+import Input from 'ui/Input'+import Checkbox from 'ui/Checkbox'+import Tooltip from 'ui/Tooltip'+import Button from 'ui/Button'+import {+ isValidEmail, isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS,+} from 'utils/validator'+import { HAVE_I_BEEN_PWNED_URL, TRIAL_DAYS } from 'redux/constants'+import { trackCustom } from 'utils/analytics'++interface ISignupForm {+ email: string,+ password: string,+ repeat: string,+ tos: boolean,+ dontRemember: boolean,+ checkIfLeaked: boolean,+}++interface ISignup {+ signup: (data: {+ email: string,+ password: string,+ repeat: string,+ dontRemember: boolean,+ checkIfLeaked: boolean,+ },+ t: (key: string, options?: {+ [key: string]: string | number,+ }) => string, callback: (res: any) => void) => void,+ authSSO: (provider: string, dontRemember: boolean, t: (key: string) => string, callback: (res: any) => void) => void+}++const Signup = ({ signup, authSSO }: ISignup): JSX.Element => {+ const { t }: {+ t: (key: string, options?: {+ [key: string]: string | number,+ }) => string,+ } = useTranslation('common')+ const [form, setForm] = useState<ISignupForm>({+ email: '',+ password: '',+ repeat: '',+ tos: false,+ dontRemember: false,+ checkIfLeaked: true,+ })+ const [validated, setValidated] = useState<boolean>(false)+ const [errors, setErrors] = useState<{+ email?: string,+ password?: string,+ repeat?: string,+ tos?: string,+ }>({})+ const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)+ const [isLoading, setIsLoading] = useState<boolean>(false)++ const validate = () => {+ const allErrors = {} as {+ email?: string,+ password?: string,+ repeat?: string,+ tos?: string,+ }++ if (!isValidEmail(form.email)) {+ allErrors.email = t('auth.common.badEmailError')+ }++ if (!isValidPassword(form.password)) {+ allErrors.password = t('auth.common.xCharsError', { amount: MIN_PASSWORD_CHARS })+ }++ if (form.password !== form.repeat || form.repeat === '') {+ allErrors.repeat = t('auth.common.noMatchError')+ }++ if (_size(form.password) > 50) {+ allErrors.password = t('auth.common.passwordTooLong', { amount: MAX_PASSWORD_CHARS })+ }++ if (!form.tos) {+ allErrors.tos = t('auth.common.tosError')+ }++ const valid = _isEmpty(_keys(allErrors))++ setErrors(allErrors)+ setValidated(valid)+ }++ useEffect(() => {+ validate()+ }, [form]) // eslint-disable-line++ const signUpCallback = (result: any) => {+ if (result) {+ trackCustom('SIGNUP')+ } else {+ setIsLoading(false)+ }+ }++ const onSubmit = (data: ISignupForm) => {+ if (!isLoading) {+ setIsLoading(true)+ signup(_omit(data, 'tos'), t, signUpCallback)+ }+ }++ 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)+ }+ }++ return (+ <Title title={t('titles.signup')}>+ <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('auth.signup.trial', {+ amount: TRIAL_DAYS,+ })}+ </h2>+ <p className='text-lg text-gray-900 dark:text-gray-50'>+ {t('auth.signup.noCC')}+ </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 : ''}+ />+ <Input+ name='password'+ id='password'+ type='password'+ label={t('auth.common.password')}+ hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}+ value={form.password}+ placeholder={t('auth.common.password')}+ className='mt-4'+ onChange={handleInput}+ error={beenSubmitted ? errors.password : ''}+ />+ <Input+ name='repeat'+ id='repeat'+ type='password'+ label={t('auth.common.repeat')}+ value={form.repeat}+ placeholder={t('auth.common.repeat')}+ className='mt-4'+ onChange={handleInput}+ error={beenSubmitted ? errors.repeat : ''}+ />+ <Checkbox+ checked={form.tos}+ onChange={handleInput}+ name='tos'+ id='tos'+ className='mt-4'+ label={(+ <span>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='auth.signup.tos'+ components={{+ tos: <Link to={routes.terms} className='font-medium text-gray-900 dark:text-gray-300 hover:underline' aria-label={t('footer.tos')} />,+ pp: <Link to={routes.privacy} className='font-medium text-gray-900 dark:text-gray-300 hover:underline' aria-label={t('footer.pp')} />,+ }}+ />+ </span>+ )}+ hintClassName='!text-red-600 dark:!text-red-500'+ hint={beenSubmitted ? errors.tos : ''}+ />+ <div className='flex mt-4'>+ <Checkbox+ checked={form.checkIfLeaked}+ onChange={handleInput}+ name='checkIfLeaked'+ id='checkIfLeaked'+ label={t('auth.common.checkLeakedPassword')}+ />+ <Tooltip+ className='ml-2'+ text={(+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='auth.common.checkLeakedPasswordDesc'+ components={{+ // eslint-disable-next-line jsx-a11y/anchor-has-content+ db: <a href={HAVE_I_BEEN_PWNED_URL} className='font-medium text-indigo-400 hover:underline hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' target='_blank' rel='noreferrer noopener' />,+ }}+ values={{+ database: 'haveibeenpwned.com',+ }}+ />+ )}+ />+ </div>+ <Checkbox+ checked={form.dontRemember}+ onChange={handleInput}+ name='dontRemember'+ id='dontRemember'+ className='mt-4'+ label={t('auth.common.noRemember')}+ />+ <div className='pt-1 flex justify-between mt-3'>+ <Link to={routes.signin} className='underline text-blue-600 hover:text-indigo-800 dark:text-blue-400 dark:hover:text-blue-500'>+ {t('auth.common.signinInstead')}+ </Link>+ <Button type='submit' loading={isLoading} primary large>+ {t('auth.signup.button')}+ </Button>+ </div>+ <div className='flex flex-wrap'>+ <GoogleAuth+ className='mt-4 mr-5'+ setIsLoading={setIsLoading}+ authSSO={authSSO}+ callback={signUpCallback}+ dontRemember={form.dontRemember}+ />+ <GithubAuth+ className='mt-4'+ setIsLoading={setIsLoading}+ authSSO={authSSO}+ callback={signUpCallback}+ dontRemember={form.dontRemember}+ />+ </div>+ </form>+ </div>+ </Title>+ )+}++Signup.propTypes = {+ signup: PropTypes.func.isRequired,+ authSSO: PropTypes.func.isRequired,+}++export default memo(withAuthentication(Signup, auth.notAuthenticated))diff --git a/app/pages/Auth/Signup/index.tsx b/app/pages/Auth/Signup/index.tsxnew file mode 100644index 000000000..9144b1fd7--- /dev/null+++ b/app/pages/Auth/Signup/index.tsx@@ -0,0 +1,3 @@+import Signup from './Signup.container'++export default Signupdiff --git a/app/pages/Auth/Socialised/index.tsx b/app/pages/Auth/Socialised/index.tsxnew file mode 100644index 000000000..2e0c91f16--- /dev/null+++ b/app/pages/Auth/Socialised/index.tsx@@ -0,0 +1,129 @@+import React, {+ useEffect, useState, memo,+} from 'react'+import { Link } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'+import _split from 'lodash/split'+import _replace from 'lodash/replace'++import { processSSOToken } from 'api'+import { SSO_PROVIDERS } from 'redux/constants'+import Title from 'components/Title'+import Loader from 'ui/Loader'+import routes from 'routes'++const Socialised = (): JSX.Element => {+ const { t }: {+ t: (key: string, optinions?: {+ [key: string]: string | number,+ }) => string,+ } = useTranslation('common')+ const [loading, setLoading] = useState<boolean>(true)+ const [isError, setIsError] = useState<boolean>(false)++ // For some reason, Google redirects to a hash URL, let's fix it+ const _location = _replace(window.location.href, `${routes.socialised}#`, `${routes.socialised}?`)++ const { searchParams } = new URL(_location)+ const hash = searchParams.get('state')+ const accessToken = searchParams.get('access_token')+ const code = searchParams.get('code')+ const provider = _split(hash, ':')[0]++ useEffect(() => {+ const processCode = async () => {+ if (!hash || !provider) {+ setIsError(true)+ return+ }++ let _token++ if (provider === SSO_PROVIDERS.GOOGLE) {+ _token = accessToken+ }++ if (provider === SSO_PROVIDERS.GITHUB) {+ _token = code+ }++ if (!_token) {+ setIsError(true)+ return+ }++ try {+ await processSSOToken(_token, hash)+ } catch (reason) {+ setIsError(true)+ console.error(`[ERROR] Error while processing Google code: ${reason}`)+ } finally {+ setLoading(false)+ }+ }++ setLoading(true)+ processCode()+ }, []) // eslint-disable-line++ if (loading) {+ return (+ <Title title={t('titles.socialisation')}>+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>+ <Loader />+ </div>+ </Title>+ )+ }++ if (isError) {+ return (+ <Title title={t('titles.socialisation')}>+ <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'>+ {t('apiNotifications.socialisationGenericError')}+ </h1>+ </div>+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>+ <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>+ </Title>+ )+ }++ return (+ <Title title={t('titles.socialisation')}>+ <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('auth.socialisation.success')}+ </h1>+ </div>+ </div>+ </main>+ </div>+ </div>+ </Title>+ )+}++export default memo(Socialised)diff --git a/app/pages/Auth/VerifyEmail/index.tsx b/app/pages/Auth/VerifyEmail/index.tsxnew file mode 100644index 000000000..467578c0f--- /dev/null+++ b/app/pages/Auth/VerifyEmail/index.tsx@@ -0,0 +1,118 @@+import React, { useState, useEffect, memo } from 'react'+import { useDispatch } from 'react-redux'+import { useParams, Link } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'+import _isString from 'lodash/isString'++import Title from 'components/Title'+import sagaActions from 'redux/sagas/actions'+import Loader from 'ui/Loader'+import routes from 'routes'++const VerifyEmail = (): JSX.Element => {+ const { t }: {+ t: (key: string, optinions?: {+ [key: string]: string | number,+ }) => string,+ } = useTranslation('common')+ const dispatch = useDispatch()+ const { id }: {+ id: string,+ } = useParams()+ const [loading, setLoading] = useState<boolean>(true)+ const [error, setError] = useState<string>('')++ useEffect(() => {+ setLoading(true)++ dispatch(+ sagaActions.emailVerifyAsync(+ {+ id,+ },+ () => {+ setLoading(false)+ },+ (verifyError: string | { message: string }) => {+ setError(_isString(verifyError) ? verifyError : verifyError.message)+ setLoading(false)+ },+ ),+ )+ }, [id]) // eslint-disable-line++ if (loading) {+ return (+ <Title title={t('titles.verification')}>+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>+ <Loader />+ </div>+ </Title>+ )+ }++ if (error) {+ return (+ <Title title={t('titles.verification')}>+ <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>+ </Title>+ )+ }++ return (+ <Title title={t('titles.verification')}>+ <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('auth.verification.success')}+ </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>+ </Title>+ )+}++export default memo(VerifyEmail)diff --git a/app/pages/Billing/index.tsx b/app/pages/Billing/index.tsxnew file mode 100644index 000000000..6926c0bef--- /dev/null+++ b/app/pages/Billing/index.tsx@@ -0,0 +1,290 @@+/* eslint-disable jsx-a11y/anchor-has-content, lodash/prefer-lodash-method */+import React, {+ memo, useMemo, useState, useEffect,+} from 'react'+import { useTranslation, Trans } from 'react-i18next'+import { useSelector, useDispatch } from 'react-redux'+import { HashLink } from 'react-router-hash-link'+import dayjs from 'dayjs'+import utc from 'dayjs/plugin/utc'+import duration from 'dayjs/plugin/duration'+import { ExclamationTriangleIcon, InformationCircleIcon } from '@heroicons/react/24/outline'+import _round from 'lodash/round'++import { CONTACT_EMAIL, paddleLanguageMapping } from 'redux/constants'+import routes from 'routes'+import sagaActions from 'redux/sagas/actions'+import { withAuthentication, auth } from 'hoc/protected'+import Title from 'components/Title'+import Modal from 'ui/Modal'+import { IUser } from 'redux/models/IUser'+import { StateType } from 'redux/store/index'+import Pricing from '../MainPage/Pricing'++dayjs.extend(utc)+dayjs.extend(duration)++const Billing = (): JSX.Element => {+ const [isCancelSubModalOpened, setIsCancelSubModalOpened] = useState<boolean>(false)+ const { metainfo, usageinfo } = useSelector((state: StateType) => state.ui.misc)+ const { user }: {+ user: IUser+ } = useSelector((state: StateType) => state.auth)+ const { theme } = useSelector((state: StateType) => state.ui.theme)+ const dispatch = useDispatch()+ const { t, i18n: { language } }: {+ t: (key: string, optinions?: {+ [key: string]: string | number,+ }) => string,+ i18n: {+ language: string,+ },+ } = useTranslation('common')+ const {+ nextBillDate, planCode, subUpdateURL, trialEndDate, timeFormat, cancellationEffectiveDate, subCancelURL, maxEventsCount,+ } = user++ const isTrial: boolean = planCode === 'trial'+ const isNoSub: boolean = planCode === 'none'+ const totalUsage = _round((usageinfo.total / maxEventsCount) * 100, 2)++ useEffect(() => {+ dispatch(sagaActions.loadUsageinfo())+ }, [dispatch])++ const isTrialEnded = useMemo(() => {+ if (!trialEndDate) {+ return false+ }++ const now = dayjs.utc()+ const future = dayjs.utc(trialEndDate)+ const diff = future.diff(now)++ return diff < 0+ }, [trialEndDate])++ const trialMessage = useMemo(() => {+ if (!trialEndDate || !isTrial) {+ return null+ }++ if (isTrialEnded) {+ return t('pricing.trialEnded')+ }++ let date++ if (language === 'en') {+ if (timeFormat === '12-hour') {+ date = dayjs(trialEndDate).locale(language).format('MMMM D, h:mm A')+ } else {+ date = dayjs(trialEndDate).locale(language).format('MMMM D, HH:mm')+ }+ } else if (timeFormat === '12-hour') {+ date = dayjs(trialEndDate).locale(language).format('D MMMM, h:mm A')+ } else {+ date = dayjs(trialEndDate).locale(language).format('D MMMM, HH:mm')+ }++ return t('billing.trialEnds', {+ date,+ })+ }, [language, trialEndDate, isTrial, timeFormat, isTrialEnded, t])++ const onSubscriptionCancel = () => {+ // @ts-ignore+ if (!window.Paddle) {+ if (subCancelURL) window.location.replace(subCancelURL)+ return+ }++ // @ts-ignore+ window.Paddle.Checkout.open({+ override: subCancelURL,+ method: 'inline',+ frameTarget: 'checkout-container',+ frameInitialHeight: 416,+ frameStyle: 'width:100%; min-width:312px; background-color: #f9fafb; border: none; border-radius: 10px; margin-top: 10px;',+ locale: paddleLanguageMapping[language] || language,+ displayModeTheme: theme,+ country: metainfo.country,+ })+ setTimeout(() => {+ // @ts-ignore+ document.querySelector('#checkout-container').scrollIntoView()+ }, 500)+ }++ const onUpdatePaymentDetails = () => {+ // @ts-ignore+ if (!window.Paddle) {+ if (subUpdateURL) window.location.replace(subUpdateURL)+ return+ }++ // @ts-ignore+ window.Paddle.Checkout.open({+ override: subUpdateURL,+ method: 'inline',+ frameTarget: 'checkout-container',+ frameInitialHeight: 416,+ frameStyle: 'width:100%; min-width:312px; background-color: #f9fafb; border: none; border-radius: 10px; margin-top: 10px;',+ locale: paddleLanguageMapping[language] || language,+ displayModeTheme: theme,+ country: metainfo.country,+ })+ setTimeout(() => {+ // @ts-ignore+ document.querySelector('#checkout-container').scrollIntoView()+ }, 500)+ }++ return (+ <Title title={t('titles.billing')}>+ <div className='bg-gray-50 dark:bg-slate-900'>+ <div className='w-11/12 md:w-4/5 mx-auto pb-16 pt-12 px-4 sm:px-6 lg:px-8 whitespace-pre-line'>+ <div className='flex justify-between flex-wrap gap-y-2 mb-4'>+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight mr-2'>+ {t('billing.title')}+ </h1>+ <div>+ {subUpdateURL && (+ <span onClick={onUpdatePaymentDetails} className='inline-flex select-none cursor-pointer mr-2 items-center border border-transparent leading-4 font-medium rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 px-4 py-2 text-sm'>+ {t('billing.update')}+ </span>+ )}+ {subCancelURL && (+ <span onClick={() => setIsCancelSubModalOpened(true)} className='inline-flex select-none cursor-pointer items-center border border-transparent leading-4 font-medium rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 shadow-sm text-white bg-red-500 dark:bg-red-600 hover:bg-red-600 dark:hover:bg-red-700 px-4 py-2 text-sm'>+ {t('billing.cancelSub')}+ </span>+ )}+ </div>+ </div>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('billing.desc')}+ <br />+ <HashLink to={`${routes.billing}#usage`} className='text-indigo-600 dark:text-indigo-400 hover:text-indigo-500 dark:hover:text-indigo-500'>+ {t('billing.gotoUsage')}+ </HashLink>+ </p>+ <hr className='mt-3 mb-2 border-gray-200 dark:border-gray-600' />+ {cancellationEffectiveDate && (+ <div className='flex items-center text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <InformationCircleIcon className='h-10 w-10 mr-2 text-blue-600' aria-hidden='true' />+ <span className='font-bold max-w-prose'>+ {t('billing.cancelledSubMessage', {+ date: language === 'en'+ ? dayjs(cancellationEffectiveDate).locale(language).format('MMMM D, YYYY')+ : dayjs(cancellationEffectiveDate).locale(language).format('D MMMM, YYYY'),+ })}+ </span>+ </div>+ )}+ {nextBillDate && (+ <div className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <span className='font-bold'>+ {t('billing.nextBillDate')}+ </span>+ + <span>+ {language === 'en'+ ? dayjs(nextBillDate).locale(language).format('MMMM D, YYYY')+ : dayjs(nextBillDate).locale(language).format('D MMMM, YYYY')}+ </span>+ </div>+ )}+ {isTrial && trialMessage && (+ <div className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <span className='font-bold'>+ {trialMessage}+ </span>+ </div>+ )}+ {isNoSub && (+ <div className='flex items-center text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <ExclamationTriangleIcon className='h-10 w-10 mr-2 text-red-600' aria-hidden='true' />+ <span className='font-bold max-w-prose'>+ {t('billing.noSubWarning')}+ </span>+ </div>+ )}+ <Pricing t={t} language={language} />+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight mt-10'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='billing.contact'+ values={{ email: CONTACT_EMAIL }}+ // @ts-ignore+ components={{+ mail: <a title={`Email us at ${CONTACT_EMAIL}`} href={`mailto:${CONTACT_EMAIL}`} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400' />,+ amount: 5,+ }}+ />+ </p>+ <h2 id='usage' className='mt-5 text-3xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mr-2'>+ {t('billing.planUsage')}+ </h2>+ <p className='mt-1 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('billing.usageOverview', {+ tracked: usageinfo.total,+ trackedPerc: totalUsage,+ maxEvents: maxEventsCount,+ })}+ </p>+ <div className='mt-2 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('billing.breakdown')}+ <ul className='list-disc list-inside'>+ <li>+ {t('billing.pageviews', {+ quantity: usageinfo.traffic,+ percentage: usageinfo.trafficPerc,+ })}+ </li>+ <li>+ {t('billing.customEvents', {+ quantity: usageinfo.customEvents,+ percentage: usageinfo.customEventsPerc,+ })}+ </li>+ <li>+ {t('billing.captcha', {+ quantity: usageinfo.captcha,+ percentage: usageinfo.captchaPerc,+ })}+ </li>+ </ul>+ </div>+ </div>+ <Modal+ onClose={() => {+ setIsCancelSubModalOpened(false)+ }}+ onSubmit={() => {+ setIsCancelSubModalOpened(false)+ onSubscriptionCancel()+ }}+ submitText={t('common.yes')}+ closeText={t('common.no')}+ title={t('pricing.cancelTitle')}+ submitType='danger'+ type='error'+ message={(+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='pricing.cancelDesc'+ values={{+ email: CONTACT_EMAIL,+ }}+ />+ )}+ isOpened={isCancelSubModalOpened}+ />+ </div>+ </Title>+ )+}++export default memo(withAuthentication(Billing, auth.authenticated))diff --git a/app/pages/Captcha/Settings/CaptchaSettings.container.tsx b/app/pages/Captcha/Settings/CaptchaSettings.container.tsxnew file mode 100644index 000000000..ee292e355--- /dev/null+++ b/app/pages/Captcha/Settings/CaptchaSettings.container.tsx@@ -0,0 +1,62 @@+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 CaptchaSettings from './CaptchaSettings'++const mapStateToProps = (state: StateType) => ({+ projects: state.ui.projects.captchaProjects,+ analyticsProjects: state.ui.projects.projects,+ isLoading: state.ui.projects.isLoadingCaptcha,+ user: state.auth.user,+})++const mapDispatchToProps = (dispatch: AppDispatch) => ({+ updateProjectFailed: (message: string) => {+ dispatch(errorsActions.updateProjectFailed({+ message,+ }))+ },+ createNewProjectFailed: (message: string) => {+ dispatch(errorsActions.createNewProjectFailed({+ message,+ }))+ },+ newProject: (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: () => {+ sagaActions.loadProjectsCaptcha()+ },+ removeProject: (pid: string) => {+ dispatch(UIActions.removeCaptchaProject(pid))+ },+ deleteProjectCache: (pid: string, filters: any) => {+ dispatch(UIActions.deleteCaptchaProjectCache({+ pid,+ }))+ },+ showError: (message: string) => {+ dispatch(errorsActions.genericError({+ message,+ }))+ },+})++export default connect(mapStateToProps, mapDispatchToProps)(CaptchaSettings)diff --git a/app/pages/Captcha/Settings/CaptchaSettings.tsx b/app/pages/Captcha/Settings/CaptchaSettings.tsxnew file mode 100644index 000000000..716f440a9--- /dev/null+++ b/app/pages/Captcha/Settings/CaptchaSettings.tsx@@ -0,0 +1,604 @@+/* eslint-disable react/forbid-prop-types */+import React, {+ useState, useEffect, useMemo, memo, useRef,+} from 'react'+import { useLocation, useHistory, useParams } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import cx from 'clsx'+import _isEmpty from 'lodash/isEmpty'+import _size from 'lodash/size'+import _replace from 'lodash/replace'+import _find from 'lodash/find'+import _join from 'lodash/join'+import _isString from 'lodash/isString'+import _split from 'lodash/split'+import _keys from 'lodash/keys'+import _map from 'lodash/map'+import _filter from 'lodash/filter'+import _includes from 'lodash/includes'+import PropTypes from 'prop-types'+import { ExclamationTriangleIcon, TrashIcon, ClipboardDocumentIcon } from '@heroicons/react/24/outline'++import Title from 'components/Title'+import { withAuthentication, auth } from 'hoc/protected'+import { isSelfhosted } from 'redux/constants'+import {+ createProject, updateProject, deleteCaptchaProject, resetCaptchaProject, reGenerateCaptchaSecretKey, getProjectsNames, createCaptchaInherited,+} from 'api'+import Input from 'ui/Input'+import Button from 'ui/Button'+import Checkbox from 'ui/Checkbox'+import Modal from 'ui/Modal'+import Select from 'ui/Select'+import { nanoid } from 'utils/random'+import { trackCustom } from 'utils/analytics'+import routes from 'routes'+import { ICaptchaProject, IProject, IProjectNames } from 'redux/models/IProject'+import { IUser } from 'redux/models/IUser'++const MAX_NAME_LENGTH = 50+const MAX_ORIGINS_LENGTH = 300+const MAX_IPBLACKLIST_LENGTH = 300++const tabForCreateCaptcha = [{+ name: 'new',+ label: 'project.captcha.settings.general',+}, {+ name: 'inheritance',+ label: 'project.captcha.settings.inheritance',+}]++const tabForNew = 'new'+const tabForInheritance = 'inheritance'++// add to interface IProject new fields isCaptcha+interface IForm extends Partial<ICaptchaProject> {+ isCaptcha?: boolean+ id: string+ name: string+ origins?: string | null | string[]+ ipBlacklist?: string | null | string[]+}++const CaptchaSettings = ({+ updateProjectFailed, createNewProjectFailed, newProject, projectDeleted, deleteProjectFailed,+ loadProjects, isLoading, projects, showError, removeProject, user,+ deleteProjectCache, analyticsProjects,+}: {+ updateProjectFailed: (error: string) => void,+ createNewProjectFailed: (error: string) => void,+ newProject: (message: string) => void,+ projectDeleted: (message: string) => void,+ deleteProjectFailed: (error: string) => void,+ loadProjects: () => void,+ isLoading: boolean,+ projects: ICaptchaProject[],+ showError: (error: string) => void,+ removeProject: (pid: string) => void,+ user: IUser,+ deleteProjectCache: (pid: string) => void,+ analyticsProjects: IProject[],+}): JSX.Element => {+ const { t }: {+ t: (key: string, options?: {+ [key: string]: string | number | boolean | undefined+ }) => string,+ } = useTranslation('common')+ const { pathname } = useLocation()+ const { id }: {+ id: string,+ } = useParams()+ const project: ICaptchaProject | IProject = useMemo(() => _find([...projects, ...analyticsProjects], p => p.id === id) || {} as IProject | ICaptchaProject, [projects, analyticsProjects, id])+ const isSettings: boolean = !_isEmpty(id) && (_replace(routes.captcha_settings, ':id', id) === pathname)+ const history = useHistory()+ const [form, setForm] = useState<IForm>({+ name: '',+ id: id || nanoid(),+ public: false,+ isCaptcha: true,+ })+ const [validated, setValidated] = useState<boolean>(false)+ const [errors, setErrors] = useState<{+ name?: string,+ id?: string,+ origins?: string,+ ipBlacklist?: 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 [tab, setTab] = useState<string>(tabForCreateCaptcha[0].name)+ const [reuseProjectId, setReuseProjectId] = useState()+ const [allProjectsNames, setAllProjectsNames] = useState<IProjectNames[]>([])+ const [copied, setCopied] = useState(false)+ const [captchaSecretKey, setCaptchaSecretKey] = useState(project?.captchaSecretKey)+ const [showRegenerateSecret, setShowRegenerateSecret] = useState(false)+ const copyTimerRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (!user.isActive && !isSelfhosted) {+ showError(t('project.captcha.settings.verify'))+ history.push(routes.dashboard)+ }++ if (!isLoading && isSettings && !projectDeleting) {+ if (_isEmpty(project) || project?.uiHidden) {+ showError(t('project.captcha.noExist'))+ history.push(routes.dashboard)+ } else {+ setForm({+ ...project,+ ipBlacklist: _isString(project.ipBlacklist) ? project.ipBlacklist : _join(project.ipBlacklist, ', '),+ origins: _isString(project.origins) ? project.origins : _join(project.origins, ', '),+ })+ }+ }+ }, [user, project, isLoading, isSettings, history, showError, projectDeleting, t])++ const onSubmit = async (data: IForm) => {+ if (!projectSaving) {+ setProjectSaving(true)+ try {+ const formalisedData: IForm = {+ ...data,+ origins: _isEmpty(data.origins) ? null : _map(_split(data.origins as string, ','), (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 as string, ','),+ }+ if (isSettings) {+ await updateProject(id, formalisedData as ICaptchaProject)+ newProject(t('project.settings.updated'))+ } else {+ if (tab === tabForInheritance) {+ if (_isEmpty(reuseProjectId)) {+ showError('Select projects')+ return+ }+ await createCaptchaInherited(formalisedData.id)+ } else {+ await createProject({+ id: formalisedData.id,+ name: formalisedData.name,+ isCaptcha: true,+ })+ }+ trackCustom('CAPTCHA_CREATED')+ newProject(t('project.settings.created'))+ }++ loadProjects()+ history.push(routes.dashboard)+ } 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 deleteCaptchaProject(id)+ removeProject(id)+ projectDeleted(t('project.settings.deleted'))+ history.push(routes.dashboard)+ } catch (e) {+ deleteProjectFailed(e as string)+ } finally {+ setProjectDeleting(false)+ }+ }+ }++ const onReset = async () => {+ setShowReset(false)+ if (!projectResetting) {+ setProjectResetting(true)+ try {+ await resetCaptchaProject(id)+ deleteProjectCache(id)+ projectDeleted(t('project.settings.resetted'))+ history.push(routes.dashboard)+ } catch (e) {+ deleteProjectFailed(e as string)+ } finally {+ setProjectResetting(false)+ }+ }+ }++ const validate = () => {+ const allErrors = {} as {+ name?: string,+ origins?: string,+ ipBlacklist?: string+ }++ if (_isEmpty(form.name) && tabForInheritance !== tab) {+ allErrors.name = t('project.settings.noNameError')+ }++ if (_size(form.name) > MAX_NAME_LENGTH && tabForInheritance !== tab) {+ 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 (tab === tabForInheritance) {+ const data = _find(allProjectsNames || analyticsProjects, (item) => `${item.name} | ${item.id}` === reuseProjectId)++ if (_isEmpty(data)) {+ showError('Select project or select corect project')+ }++ onSubmit({ ...data as IForm, isCaptcha: true })+ return+ }++ if (validated) {+ onSubmit(form)+ }+ }++ const onCancel = () => {+ history.push(isSettings ? _replace(routes.captcha, ':id', id) : routes.dashboard)+ }++ const title = isSettings ? `${t('project.settings.settings')} ${form.name}` : t('project.settings.create')++ const onRegenerateSecretKey = async () => {+ try {+ const res = await reGenerateCaptchaSecretKey(id)+ setCaptchaSecretKey(res)+ } catch (e) {+ showError(e as string)+ }+ }++ const setToClipboard = (value: string) => {+ if (!copied) {+ navigator.clipboard.writeText(value)+ setCopied(true)+ // @ts-ignore+ copyTimerRef.current = setTimeout(() => {+ setCopied(false)+ }, 2000)+ }+ }++ const getAllProjectsNames = async () => {+ await getProjectsNames()+ .then((res) => {+ setAllProjectsNames(res)+ }).catch((e) => {+ console.log(e)+ })+ }++ useEffect(() => {+ if (_isEmpty(allProjectsNames)) {+ getAllProjectsNames()+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [tab])++ return (+ <Title title={title}>+ <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>+ <div className='mt-6'>+ {(!isSettings && _filter(allProjectsNames || analyticsProjects, (item) => !item?.isCaptchaProject).length > 0) && (+ <nav className='-mb-px flex space-x-8'>+ {_map(tabForCreateCaptcha, (tabCaptcha) => (+ <button+ key={tabCaptcha.name}+ type='button'+ onClick={() => setTab(tabCaptcha.name)}+ className={cx('whitespace-nowrap pb-4 px-1 border-b-2 font-medium text-md', {+ 'border-indigo-500 text-indigo-600 dark:text-indigo-500': tab === tabCaptcha.name,+ 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300 dark:hover:border-gray-300': tab !== tabCaptcha.name,+ })}+ >+ {t(tabCaptcha.label)}+ </button>+ ))}+ </nav>+ )}+ </div>+ {tab === tabForNew && (+ <>+ <Input+ name='name'+ id='name'+ type='text'+ label={t('project.captcha.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.captcha.settings.pid')}+ value={form.id}+ className='mt-4'+ onChange={handleInput}+ error={beenSubmitted ? errors.id : null}+ disabled+ />+ </>+ )}+ {tab === tabForInheritance && (+ <Select+ title={_isEmpty(reuseProjectId) ? 'select project' : reuseProjectId}+ label={t('profileSettings.selectProject')}+ className='w-full'+ items={_filter(allProjectsNames || analyticsProjects, (item) => !item.isCaptchaProject)}+ labelExtractor={(item) => `${item.name} | ${item.id}`}+ keyExtractor={(item) => item.id}+ onSelect={(item) => setReuseProjectId(item)}+ />+ )}+ {isSettings ? (+ <>+ <Input+ name='origins'+ id='origins'+ type='text'+ label={t('project.settings.origins')}+ hint={t('project.settings.originsHint')}+ value={form.origins as string || ''}+ 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 as string || ''}+ className='mt-4'+ onChange={handleInput}+ error={beenSubmitted ? errors.ipBlacklist : null}+ isBeta+ />+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.captchaSecretKey')}+ </h3>+ {captchaSecretKey ? (+ <>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.captchaSecretKeyHint')}+ </p>+ <p className='mt-4 max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.captchaSecretKey')}+ </p>+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2'>+ <div className='relative group'>+ <Input+ name='sercretKey'+ id='sercretKey'+ type='text'+ className='pr-9'+ value={captchaSecretKey}+ onChange={handleInput}+ disabled+ />+ <div className='absolute right-2 top-3'>+ <div className='group relative'>+ <Button+ type='button'+ onClick={() => setToClipboard(captchaSecretKey)}+ className='opacity-70 hover:opacity-100'+ noBorder+ >+ <>+ <ClipboardDocumentIcon className='w-6 h-6' />+ {copied && (+ <div className='animate-appear bg-white dark:bg-slate-800 cursor-auto rounded p-1 absolute sm:top-0 top-0.5 right-8 text-xs text-green-600'>+ {t('common.copied')}+ </div>+ )}+ </>+ </Button>+ </div>+ </div>+ </div>+ </div>+ </>+ ) : (+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.noApiKey')}+ </p>+ )}+ {captchaSecretKey ? (+ <Button className='mt-4' onClick={() => setShowRegenerateSecret(true)} danger large>+ {t('profileSettings.regenerateSecretKey')}+ </Button>+ ) : (+ <Button className='mt-4' onClick={onRegenerateSecretKey} primary large>+ {t('profileSettings.generateSecretKey')}+ </Button>+ )}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <Checkbox+ checked={Boolean(form.active)}+ onChange={handleInput}+ name='active'+ id='active'+ className='mt-4'+ label={t('project.captcha.settings.enabled')}+ hint={t('project.captcha.settings.enabledHint')}+ />+ <Checkbox+ checked={Boolean(form.public)}+ onChange={handleInput}+ name='public'+ id='public'+ className='mt-4'+ label={t('project.settings.public')}+ hint={t('project.settings.publicHint')}+ />+ <div className='flex justify-between mt-8 h-20 sm:h-min'>+ <div className='flex flex-wrap items-center'>+ <Button className='mr-2 border-indigo-100 dark:text-gray-50 dark:border-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>+ <div className='flex flex-wrap items-center justify-end'>+ <Button onClick={() => !projectResetting && setShowReset(true)} loading={projectDeleting} semiDanger semiSmall>+ <>+ <TrashIcon className='w-5 h-5 mr-1' />+ {t('project.settings.reset')}+ </>+ </Button>+ <Button className='ml-2' onClick={() => !projectDeleting && setShowDelete(true)} loading={projectDeleting} danger semiSmall>+ <>+ <ExclamationTriangleIcon className='w-5 h-5 mr-1' />+ {t('project.settings.delete')}+ </>+ </Button>+ </div>+ </div>+ <hr className='mt-2 sm:mt-5 border-gray-200 dark:border-gray-600' />+ </>+ ) : (+ <p className='text-gray-500 dark:text-gray-300 italic mt-1 mb-4 text-sm'>+ {t('project.settings.createHint')}+ </p>+ )}++ {!isSettings && (+ <div>+ <Button className='mr-2 border-indigo-100 dark:text-gray-50 dark:border-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={t('project.settings.resetHint')}+ submitType='danger'+ type='error'+ isOpened={showReset}+ />+ <Modal+ onClose={() => setShowRegenerateSecret(false)}+ onSubmit={() => {+ setShowRegenerateSecret(false)+ onRegenerateSecretKey()+ }}+ submitText={t('profileSettings.regenerateSecretKey')}+ closeText={t('common.close')}+ title={t('profileSettings.regenerateSecretKeyTitle')}+ submitType='danger'+ type='error'+ message={t('profileSettings.regenerateSecretKeyMessage')}+ isOpened={showRegenerateSecret}+ />+ </div>+ </Title>+ )+}++CaptchaSettings.propTypes = {+ updateProjectFailed: PropTypes.func.isRequired,+ createNewProjectFailed: PropTypes.func.isRequired,+ newProject: PropTypes.func.isRequired,+ projectDeleted: PropTypes.func.isRequired,+ deleteProjectFailed: PropTypes.func.isRequired,+ loadProjects: PropTypes.func.isRequired,+ projects: PropTypes.arrayOf(PropTypes.object).isRequired,+ showError: PropTypes.func.isRequired,+ isLoading: PropTypes.bool.isRequired,+ user: PropTypes.object.isRequired,+ deleteProjectCache: PropTypes.func.isRequired,+}++export default memo(withAuthentication(CaptchaSettings, auth.authenticated))diff --git a/app/pages/Captcha/Settings/index.tsx b/app/pages/Captcha/Settings/index.tsxnew file mode 100644index 000000000..1ce8f6fd4--- /dev/null+++ b/app/pages/Captcha/Settings/index.tsx@@ -0,0 +1,3 @@+import ProjectSettings from './CaptchaSettings.container'++export default ProjectSettingsdiff --git a/app/pages/Captcha/View/Panels.tsx b/app/pages/Captcha/View/Panels.tsxnew file mode 100644index 000000000..750501938--- /dev/null+++ b/app/pages/Captcha/View/Panels.tsx@@ -0,0 +1,702 @@+import React, {+ memo, useState, useEffect, useMemo, Fragment,+} from 'react'+import { ArrowSmallUpIcon, ArrowSmallDownIcon } from '@heroicons/react/24/solid'+import {+ FunnelIcon, MapIcon, Bars4Icon, ArrowsPointingOutIcon, ChartPieIcon,+} 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 _includes from 'lodash/includes'+import _floor from 'lodash/floor'+import _size from 'lodash/size'+import _slice from 'lodash/slice'+import _sum from 'lodash/sum'++import Progress from 'ui/Progress'+import PulsatingCircle from 'ui/icons/PulsatingCircle'+import Modal from 'ui/Modal'+import Chart from 'ui/Chart'+import LiveVisitorsDropdown from './components/LiveVisitorsDropdown'+import InteractiveMap from './components/InteractiveMap'+import { iconClassName } from './ViewCaptcha.helpers'++const ENTRIES_PER_PANEL = 5++const panelsWithBars = ['cc', 'ce', 'os', 'br', 'dv']++const checkIfBarsNeeded = (panelID: string) => {+ return _includes(panelsWithBars, panelID)+}++// noSwitch - 'previous' and 'next' buttons+const PanelContainer = ({+ name, children, noSwitch, icon, type, openModal, activeFragment, setActiveFragment,+}: {+ name: string,+ children?: React.ReactNode,+ noSwitch?: boolean,+ icon?: React.ReactNode,+ type: string,+ openModal?: () => void,+ activeFragment: number | string,+ setActiveFragment: (arg: number) => void,+}): JSX.Element => (+ <div+ className={cx('relative bg-white dark:bg-slate-800/25 pt-5 px-4 min-h-72 sm:pt-6 sm:px-6 shadow rounded-lg overflow-hidden', {+ 'pb-12': !noSwitch,+ 'pb-5': noSwitch,+ })}+ >+ <div className='flex items-center justify-between mb-2'>+ <h3 className='flex items-center text-lg leading-6 font-semibold text-gray-900 dark:text-gray-50'>+ {icon && (+ <>+ {icon}+ + </>+ )}+ {name}+ </h3>+ <div className='flex'>+ {(checkIfBarsNeeded(type)) && (+ <Bars4Icon+ className={cx(iconClassName, 'cursor-pointer', {+ 'text-blue-500': activeFragment === 0,+ 'text-gray-900 dark:text-gray-50': activeFragment === 1,+ })}+ onClick={() => setActiveFragment(0)}+ />+ )}++ {/* if it is a Country tab */}+ {type === 'cc' && (+ <>+ <MapIcon+ className={cx(iconClassName, 'ml-2 cursor-pointer', {+ 'text-blue-500': activeFragment === 1,+ 'text-gray-900 dark:text-gray-50': activeFragment === 0,+ })}+ onClick={() => setActiveFragment(1)}+ />+ <ArrowsPointingOutIcon+ className={cx(iconClassName, 'ml-2 cursor-pointer text-gray-900 dark:text-gray-50', {+ hidden: activeFragment === 0,+ })}+ onClick={openModal}+ />+ </>+ )}+ {/* if this tab using Circle showing stats panel */}+ {(type === 'ce' || type === 'os' || type === 'br' || type === 'dv') && (+ <ChartPieIcon+ className={cx(iconClassName, 'ml-2 cursor-pointer', {+ 'text-blue-500': activeFragment === 1,+ 'text-gray-900 dark:text-gray-50': activeFragment === 0,+ })}+ onClick={() => setActiveFragment(1)}+ />+ )}+ </div>+ </div>+ {/* for other tabs */}+ <div className='flex flex-col h-full scroll-auto overflow-auto'>+ {children}+ </div>+ </div>+)++PanelContainer.propTypes = {+ name: PropTypes.string.isRequired,+ children: PropTypes.node.isRequired,+ noSwitch: PropTypes.bool,+ activeFragment: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),+ setActiveFragment: PropTypes.func,+ icon: PropTypes.node,+ openModal: PropTypes.func,+}++PanelContainer.defaultProps = {+ icon: null,+ noSwitch: false,+ activeFragment: 0,+ setActiveFragment: () => { },+ openModal: () => { },+}++// First tab with stats+const Overview = ({+ overall, chartData, activePeriod, t, live, sessionDurationAVG, projectId,+}: {+ overall: any+ chartData: any+ activePeriod: any+ t: (arg: string) => string+ live: number | string+ sessionDurationAVG: number+ projectId: string+}) => {+ const pageviewsDidGrowUp = overall.percChange >= 0+ const uniqueDidGrowUp = overall.percChangeUnique >= 0+ const pageviews = _sum(chartData?.visits) || 0+ const uniques = _sum(chartData?.uniques) || 0+ let bounceRate = 0++ if (pageviews > 0) {+ bounceRate = _round((uniques * 100) / pageviews, 1)+ }++ return (+ <PanelContainer name={t('project.overview')} noSwitch 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} />+ </div>+ {!_isEmpty(chartData) && (+ <>+ <p className='text-lg font-semibold dark:text-gray-50'>+ {t('project.statsFor')}+ <span className='lowercase'>+ + {activePeriod.label}+ </span>+ </p>++ <div className='flex justify-between'>+ <p className='text-lg dark:text-gray-50'>+ {t('dashboard.pageviews')}+ :+ </p>+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl'>+ {pageviews}+ </p>+ </div>++ <div className='flex justify-between'>+ <p className='text-lg dark:text-gray-50'>+ {t('dashboard.unique')}+ :+ </p>+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl'>+ {uniques}+ </p>+ </div>++ <div className='flex justify-between'>+ <p className='text-lg dark:text-gray-50'>+ {t('dashboard.bounceRate')}+ :+ </p>+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl'>+ {bounceRate}+ %+ </p>+ </div>+ <div className='flex justify-between'>+ <p className='text-lg dark:text-gray-50'>+ {t('dashboard.sessionDuration')}+ :+ </p>+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl'>+ {sessionDurationAVG}+ </p>+ </div>+ <hr className='my-2 border-gray-200 dark:border-gray-600' />+ </>+ )}+ <p className='text-lg font-semibold dark:text-gray-50'>+ {t('project.weeklyStats')}+ </p>+ <div className='flex justify-between'>+ <p className='text-lg dark:text-gray-50'>+ {t('dashboard.pageviews')}+ :+ </p>+ <dd className='flex items-baseline'>+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-lg'>+ {overall.thisWeek}+ </p>+ <p+ className={cx('flex text-sm -ml-1 items-baseline', {+ 'text-green-600': pageviewsDidGrowUp,+ 'text-red-600': !pageviewsDidGrowUp,+ })}+ >+ {pageviewsDidGrowUp ? (+ <>+ <ArrowSmallUpIcon className='self-center flex-shrink-0 h-4 w-4 text-green-500' />+ <span className='sr-only'>+ {t('dashboard.inc')}+ </span>+ </>+ ) : (+ <>+ <ArrowSmallDownIcon className='self-center flex-shrink-0 h-4 w-4 text-red-500' />+ <span className='sr-only'>+ {t('dashboard.dec')}+ </span>+ </>+ )}+ {overall.percChange}+ %+ </p>+ </dd>+ </div>+ <div className='flex justify-between'>+ <p className='text-lg dark:text-gray-50'>+ {t('dashboard.unique')}+ :+ </p>+ <dd className='flex items-baseline'>+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-lg'>+ {overall.thisWeekUnique}+ </p>+ <p+ className={cx('flex text-sm -ml-1 items-baseline', {+ 'text-green-600': uniqueDidGrowUp,+ 'text-red-600': !uniqueDidGrowUp,+ })}+ >+ {uniqueDidGrowUp ? (+ <>+ <ArrowSmallUpIcon className='self-center flex-shrink-0 h-4 w-4 text-green-500' />+ <span className='sr-only'>+ {t('dashboard.inc')}+ </span>+ </>+ ) : (+ <>+ <ArrowSmallDownIcon className='self-center flex-shrink-0 h-4 w-4 text-red-500' />+ <span className='sr-only'>+ {t('dashboard.dec')}+ </span>+ </>+ )}+ {overall.percChangeUnique}+ %+ </p>+ </dd>+ </div>+ </PanelContainer>+ )+}++// Options for circle chart showing the stats of data+const getPieOptions = (customs: 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-800 rounded-md shadow-md px-3 py-1'>+ {{+ <li class='flex'>+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:{=COLOR}></div>+ <span>{=NAME}</span>+ </li>+ <hr class='border-gray-200 dark:border-gray-600' />+ <li class='flex justify-between'>+ <span>${tQuantity}</span>+ <span class='pl-4'>{=QUANTITY}</span>+ </li>+ <li class='flex justify-between'>+ <span>${tConversion}</span>+ <span class='pl-4'>{=CONVERSION}%</span>+ </li>+ <li class='flex justify-between'>+ <span>${tRatio}</span>+ <span class='pl-4'>{=VALUE}</span>+ </li>+ }}+ </ul>`,+ },+ },+ }+}++// Tabs with custom events like submit form, press button, go to the link rate etc.+const CustomEvents = ({+ customs, chartData, onFilter, t,+}: {+ customs: any+ chartData: any+ onFilter: any+ t: (arg0: string) => string+}) => {+ const keys = _keys(customs)+ const uniques = _sum(chartData.uniques)+ const [chartOptions, setChartOptions] = useState<any>({})+ const [activeFragment, setActiveFragment] = useState<number>(0)++ useEffect(() => {+ if (!_isEmpty(chartData)) {+ const options = getPieOptions(customs, uniques, t)+ setChartOptions({+ data: {+ columns: _map(keys, (ev) => [ev, customs[ev]]),+ type: pie(),+ },+ ...options,+ })+ }+ }, [chartData, customs, t]) // eslint-disable-line react-hooks/exhaustive-deps++ // for showing chart circle of stats a data+ if (activeFragment === 1 && !_isEmpty(chartData)) {+ return (+ <PanelContainer+ name={t('project.customEv')}+ type='ce'+ setActiveFragment={setActiveFragment}+ activeFragment={activeFragment}+ >+ {_isEmpty(chartData) ? (+ <p className='mt-1 text-base text-gray-700 dark:text-gray-300'>+ {t('project.noParamData')}+ </p>+ ) : (+ <Chart+ options={chartOptions}+ current='panels-ce'+ />+ )}+ </PanelContainer>+ )+ }++ return (+ <PanelContainer name={t('project.customEv')} type='ce' setActiveFragment={setActiveFragment} activeFragment={activeFragment}>+ <table className='table-fixed'>+ <thead>+ <tr className='text-gray-900 dark:text-gray-50'>+ <th className='w-4/6 text-left'>{t('project.event')}</th>+ <th className='w-1/6 text-right'>+ {t('project.quantity')}+ + </th>+ <th className='w-1/6 text-right'>{t('project.conversion')}</th>+ </tr>+ </thead>+ <tbody>+ {_map(keys, (ev) => (+ <tr+ key={ev}+ className='text-gray-900 dark:text-gray-50 group hover:bg-gray-100 hover:dark:bg-slate-800 cursor-pointer'+ onClick={() => onFilter('ev', ev)}+ >+ <td className='text-left flex items-center'>+ {ev}+ <FunnelIcon className='ml-2 w-4 h-4 text-gray-500 hidden group-hover:block dark:text-gray-300' />+ </td>+ <td className='text-right'>+ {customs[ev]}+ + </td>+ <td className='text-right'>+ {_round((customs[ev] / uniques) * 100, 2)}+ %+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </PanelContainer>+ )+}++CustomEvents.propTypes = {+ customs: PropTypes.objectOf(PropTypes.number).isRequired,+ onFilter: PropTypes.func.isRequired,+ t: PropTypes.func.isRequired,+ // eslint-disable-next-line react/forbid-prop-types+ chartData: PropTypes.objectOf(PropTypes.any).isRequired,+}++const Panel = ({+ name, data, rowMapper, valueMapper, capitalize, linkContent, t, icon, id, hideFilters, onFilter,+}: {+ name: string+ data: any+ rowMapper: any+ valueMapper: any+ capitalize: boolean+ linkContent: boolean+ t: (arg0: string) => string+ icon: any+ id: string+ hideFilters: boolean+ onFilter: any+}): 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 + 5), [keys, currentIndex])+ const total = useMemo(() => _reduce(keys, (prev, curr) => prev + data[curr], 0), [keys]) // eslint-disable-line+ const [activeFragment, setActiveFragment] = useState(0)+ const [modal, setModal] = useState(false)+ const canGoPrev = () => page > 0+ const canGoNext = () => page < _floor((_size(keys) - 1) / ENTRIES_PER_PANEL)++ const _onFilter = hideFilters ? () => { } : onFilter++ useEffect(() => {+ const sizeKeys = _size(keys)++ if (currentIndex > sizeKeys) {+ setPage(_floor(sizeKeys / ENTRIES_PER_PANEL))+ }+ }, [currentIndex, keys])++ useEffect(() => {+ setPage(0)+ }, [data])++ const onPrevious = () => {+ if (canGoPrev()) {+ setPage(page - 1)+ }+ }++ const onNext = () => {+ if (canGoNext()) {+ setPage(page + 1)+ }+ }+ // Showing map of stats a data+ if (id === 'cc' && activeFragment === 1 && !_isEmpty(data)) {+ return (+ <PanelContainer+ name={name}+ icon={icon}+ type={id}+ activeFragment={activeFragment}+ setActiveFragment={setActiveFragment}+ openModal={() => setModal(true)}+ >+ <InteractiveMap+ data={data}+ total={total}+ onClickCountry={(key) => _onFilter(id, key)}+ />+ <Modal+ onClose={() => setModal(false)}+ closeText={t('common.close')}+ isOpened={modal}+ message={(+ <InteractiveMap+ data={data}+ total={total}+ onClickCountry={(key) => _onFilter(id, key)}+ />+ )}+ size='large'+ />+ </PanelContainer>+ )+ }++ // Showing chart of stats a data (start if)+ if ((id === 'os' || id === 'br' || id === 'dv') && activeFragment === 1 && !_isEmpty(data)) {+ const tQuantity = t('project.quantity')+ const tRatio = t('project.ratio')+ const mappedData = _map(data, valueMapper)++ const options = {+ data: {+ columns: _map(data, (e, index) => [index, e]),+ type: pie(),+ },+ tooltip: {+ contents: {+ text: {+ QUANTITY: _values(mappedData),+ },+ template: `+ <ul class='bg-gray-100 dark:text-gray-50 dark:bg-slate-800 rounded-md shadow-md px-3 py-1'>+ {{+ <li class='flex'>+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:{=COLOR}></div>+ <span>{=NAME}</span>+ </li>+ <hr class='border-gray-200 dark:border-gray-600' />+ <li class='flex justify-between'>+ <span>${tQuantity}</span>+ <span class='pl-4'>{=QUANTITY}</span>+ </li>+ <li class='flex justify-between'>+ <span>${tRatio}</span>+ <span class='pl-4'>{=VALUE}</span>+ </li>+ }}+ </ul>`,+ },+ },+ }++ return (+ <PanelContainer+ name={name}+ icon={icon}+ type={id}+ setActiveFragment={setActiveFragment}+ activeFragment={activeFragment}+ >+ {_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>+ )+ }++ return (+ <PanelContainer name={name} icon={icon} type={id} activeFragment={activeFragment} setActiveFragment={setActiveFragment}>+ {_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-800 cursor-pointer': !hideFilters,+ })}+ onClick={() => _onFilter(id, key)}+ >+ {linkContent ? (+ <a+ className={cx('flex items-center label hover:underline text-blue-600 dark:text-blue-500', { capitalize })}+ href={rowData}+ target='_blank'+ rel='noopener noreferrer nofollow'+ aria-label={`${rowData} (opens in a new tab)`}+ >+ {rowData}+ {!hideFilters && (+ <FunnelIcon className='ml-2 w-4 h-4 text-gray-500 hidden group-hover:block dark:text-gray-300' />+ )}+ </a>+ ) : (+ <span className={cx('flex items-center label', { capitalize })}>+ {rowData}+ {!hideFilters && (+ <FunnelIcon className='ml-2 w-4 h-4 text-gray-500 hidden group-hover:block dark:text-gray-300' />+ )}+ </span>+ )}+ <span className='ml-3 dark:text-gray-50'>+ {valueData}+ + <span className='text-gray-500 dark:text-gray-200 font-light'>+ (+ {perc}+ %)+ </span>+ </span>+ </div>+ <Progress now={perc} />+ </Fragment>+ )+ })}+ {/* for pagination in tabs */}+ {_size(keys) > 5 && (+ <div className='absolute bottom-0 w-card-toggle-sm sm:w-card-toggle'>+ <div className='flex justify-between select-none mb-2'>+ <span+ className={cx('text-gray-500 dark:text-gray-200 font-light', {+ hoverable: canGoPrev(),+ disabled: !canGoPrev(),+ })}+ role='button'+ onClick={onPrevious}+ tabIndex={0}+ >+ <+ + {t('project.prev')}+ </span>+ <span+ className={cx('text-gray-500 dark:text-gray-200 font-light', {+ hoverable: canGoNext(),+ disabled: !canGoNext(),+ })}+ role='button'+ onClick={onNext}+ tabIndex={0}+ >+ {t('project.next')}+ + >+ </span>+ </div>+ </div>+ )}+ </PanelContainer>+ )+}++Panel.propTypes = {+ name: PropTypes.string.isRequired,+ data: PropTypes.objectOf(PropTypes.number).isRequired,+ id: PropTypes.string,+ rowMapper: PropTypes.func,+ valueMapper: PropTypes.func,+ onFilter: PropTypes.func,+ capitalize: PropTypes.bool,+ linkContent: PropTypes.bool,+ hideFilters: PropTypes.bool,+ icon: PropTypes.node,+}++Panel.defaultProps = {+ id: null,+ rowMapper: null,+ valueMapper: null,+ capitalize: false,+ linkContent: false,+ onFilter: () => { },+ hideFilters: false,+ icon: null,+}++const PanelMemo = memo(Panel)+const OverviewMemo = memo(Overview)+const CustomEventsMemo = memo(CustomEvents)++export {+ PanelMemo as Panel,+ OverviewMemo as Overview,+ CustomEventsMemo as CustomEvents,+}diff --git a/app/pages/Captcha/View/ViewCaptcha.container.tsx b/app/pages/Captcha/View/ViewCaptcha.container.tsxnew file mode 100644index 000000000..390c2bd59--- /dev/null+++ b/app/pages/Captcha/View/ViewCaptcha.container.tsx@@ -0,0 +1,46 @@+import { connect } from 'react-redux'+import { errorsActions } from 'redux/reducers/errors'+import UIActions from 'redux/reducers/ui'+import { StateType, AppDispatch } from 'redux/store'++import { ICaptchaProject } from 'redux/models/IProject'+import ViewCaptcha from './ViewCaptcha'++const mapStateToProps = (state: StateType) => ({+ projects: state.ui.projects.captchaProjects,+ isLoading: state.ui.projects.isLoadingCaptcha,+ cache: state.ui.cache.captchaAnalytics,+ projectViewPrefs: state.ui.cache.captchaProjectsViewPrefs,+ authenticated: state.auth.authenticated,+ timezone: state.auth.user.timezone,+ user: state.auth.user,+ liveStats: state.ui.projects.liveStats,+})++const mapDispatchToProps = (dispatch: AppDispatch) => ({+ showError: (message: string) => {+ dispatch(errorsActions.genericError({+ message,+ }))+ },+ setProjectCache: (pid: string, data: any, key: string) => {+ dispatch(UIActions.setCaptchaProjectCache({+ pid,+ data,+ key,+ }))+ },+ setProjects: (project: ICaptchaProject[]) => {+ dispatch(UIActions.setCaptchaProjects(project))+ },+ setProjectViewPrefs: (pid: string, period: string, timeBucket: string, rangeDate?: Date[] | null) => {+ dispatch(UIActions.setCaptchaProjectViewPrefs({+ pid,+ period,+ timeBucket,+ rangeDate,+ }))+ },+})++export default connect(mapStateToProps, mapDispatchToProps)(ViewCaptcha)diff --git a/app/pages/Captcha/View/ViewCaptcha.helpers.tsx b/app/pages/Captcha/View/ViewCaptcha.helpers.tsxnew file mode 100644index 000000000..bcbdf7754--- /dev/null+++ b/app/pages/Captcha/View/ViewCaptcha.helpers.tsx@@ -0,0 +1,273 @@+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, bar,+} from 'billboard.js'+import _forEach from 'lodash/forEach'+import _map from 'lodash/map'+import _split from 'lodash/split'+import _replace from 'lodash/replace'+import _isEmpty from 'lodash/isEmpty'+import _keys from 'lodash/keys'+import _size from 'lodash/size'+import _round from 'lodash/round'+import JSZip from 'jszip'++import {+ TimeFormat, chartTypes, tbsFormatMapper, tbsFormatMapper24h,+} from 'redux/constants'+import countries from 'utils/isoCountries'++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 line = ''++ _forEach(array[i], (index) => {+ if (line !== '') line += ','+ line += index+ })++ str += `${line}\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 = {+ results: 'results',+}++// function to filter the data for the chart+const getColumns = (chart: {+ x: string[],+ results: string[],+}, activeChartMetrics: {+ [key: string]: boolean,+}) => {+ const {+ results,+ } = activeChartMetrics++ const columns = [+ ['x', ..._map(chart.x, el => dayjs(el).toDate())],+ ]++ if (results) {+ columns.push(['results', ...chart.results])+ }++ return columns+}++// setting the default values for the time period dropdown+const noRegionPeriods = ['custom', 'yesterday']++// function to get the settings and data for the chart(main diagram)+const getSettings = (chart: any, timeBucket: string, activeChartMetrics: {+ [key: string]: boolean,+}, applyRegions: boolean, timeFormat: string, rotateXAxias: boolean, chartType: string) => {+ const xAxisSize = _size(chart.x)+ const lines: any[] = []+ const modifiedChart = { ...chart }+ let regions++ if (applyRegions) {+ let regionStart++ if (xAxisSize > 1) {+ regionStart = dayjs(chart.x[xAxisSize - 2]).toDate()+ } else {+ regionStart = dayjs(chart.x[xAxisSize - 1]).toDate()+ }++ regions = {+ results: [+ {+ start: regionStart,+ style: {+ dasharray: '6 2',+ },+ },+ ],+ }+ }++ return {+ data: {+ x: 'x',+ columns: getColumns(modifiedChart, activeChartMetrics),+ types: {+ results: chartType === chartTypes.line ? area() : bar(),+ },+ colors: {+ results: '#2563EB',+ },+ regions,+ },+ grid: {+ x: {+ lines,+ },+ },+ axis: {+ x: {+ clipPath: false,+ tick: {+ fit: true,+ rotate: rotateXAxias ? 45 : 0,+ format: timeFormat === TimeFormat['24-hour'] ? (x: any) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x) : null,+ },+ localtime: timeFormat === TimeFormat['24-hour'],+ type: 'timeseries',+ },+ },+ tooltip: {+ format: {+ title: (x: any) => d3.timeFormat(tbsFormatMapper[timeBucket])(x),+ },+ contents: {+ template: `+ <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'>{=TITLE}</li>+ <hr class='border-gray-200 dark:border-gray-600' />+ {{+ <li class='flex justify-between'>+ <div class='flex justify-items-start'>+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:{=COLOR}></div>+ <span>{=NAME}</span>+ </div>+ <span class='pl-4'>{=VALUE}</span>+ </li>+ }}+ </ul>`,+ },+ },+ point: {+ focus: {+ only: xAxisSize > 1,+ },+ pattern: [+ 'circle',+ ],+ r: 3,+ },+ legend: {+ usePoint: true,+ item: {+ tile: {+ width: 10,+ },+ },+ },+ area: {+ linearGradient: true,+ },+ padding: {+ right: rotateXAxias && 35,+ left: 40,+ },+ 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: (key: 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'),+})++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,+}diff --git a/app/pages/Captcha/View/ViewCaptcha.tsx b/app/pages/Captcha/View/ViewCaptcha.tsxnew file mode 100644index 000000000..d96cae41f--- /dev/null+++ b/app/pages/Captcha/View/ViewCaptcha.tsx@@ -0,0 +1,965 @@+/* eslint-disable react/forbid-prop-types, react/no-unstable-nested-components, react/display-name */+import React, {+ useState, useEffect, useMemo, memo, useRef, Fragment,+} from 'react'+import useSize from 'hooks/useSize'+import { useHistory, useParams, Link } from 'react-router-dom'+// @ts-ignore+import domToImage from 'dom-to-image'+// @ts-ignore+import { saveAs } from 'file-saver'+import bb from 'billboard.js'+import {+ ArrowDownTrayIcon, Cog8ToothIcon, ArrowPathIcon, PresentationChartBarIcon, PresentationChartLineIcon,+} from '@heroicons/react/24/outline'+import cx from 'clsx'+import dayjs from 'dayjs'+import { useTranslation } from 'react-i18next'+import _keys from 'lodash/keys'+import _map from 'lodash/map'+import _includes from 'lodash/includes'+import _last from 'lodash/last'+import _isEmpty from 'lodash/isEmpty'+import _replace from 'lodash/replace'+import _find from 'lodash/find'+import _filter from 'lodash/filter'+import _startsWith from 'lodash/startsWith'+import _debounce from 'lodash/debounce'+import _some from 'lodash/some'+import PropTypes from 'prop-types'++import { getItem, setItem } from 'utils/localstorage'+import Title from 'components/Title'+import EventsRunningOutBanner from 'components/EventsRunningOutBanner'+import {+ tbPeriodPairs, getProjectCaptchaCacheKey, timeBucketToDays, getProjectCacheCustomKey, roleViewer,+ MAX_MONTHS_IN_PAST, TimeFormat, chartTypes,+} from 'redux/constants'+import { ICaptchaProject, IProject, ILiveStats } from 'redux/models/IProject'+import { IUser } from 'redux/models/IUser'+import Button from 'ui/Button'+import Loader from 'ui/Loader'+import Dropdown from 'ui/Dropdown'+import Checkbox from 'ui/Checkbox'+import FlatPicker from 'ui/Flatpicker'+import routes from 'routes'+import {+ getProject, getOverallStats, getLiveVisitors, getCaptchaData,+} from 'api'+import {+ Panel, CustomEvents, // Overview,+} from './Panels'+import {+ onCSVExportClick, getFormatDate, panelIconMapping, typeNameMapping, validFilters, validPeriods,+ validTimeBacket, noRegionPeriods, getSettings, CHART_METRICS_MAPPING,+} from './ViewCaptcha.helpers'+import CCRow from './components/CCRow'+import RefRow from './components/RefRow'+import NoEvents from './components/NoEvents'+import Filters from './components/Filters'+import './styles.css'++interface IProjectView extends ICaptchaProject {+ isPublicVisitors?: boolean,+}++const ViewProject = ({+ projects, isLoading: _isLoading, showError, cache, setProjectCache, projectViewPrefs, setProjectViewPrefs, authenticated, user, setProjects, liveStats,+}: {+ projects: IProjectView[],+ isLoading: boolean,+ showError: (message: string) => void,+ cache: any,+ setProjectCache: (pid: string, data: any, key: string) => void,+ projectViewPrefs: any,+ setProjectViewPrefs: (pid: string, period: string, timeBucket: string, rangeDate?: Date[] | null) => void,+ authenticated: boolean,+ user: IUser,+ // eslint-disable-next-line no-unused-vars, no-shadow+ setProjects: (projects: ICaptchaProject[]) => void,+ liveStats: ILiveStats,+}): JSX.Element => {+ const { t, i18n: { language } }: {+ t: (key: string, options?: {+ [key: string]: string | number | boolean | undefined | null,+ }) => string,+ i18n: { language: string },+ } = useTranslation('common')+ const [periodPairs, setPeriodPairs] = useState(tbPeriodPairs(t))+ const dashboardRef = useRef(null)+ const { id }: {+ id: string,+ } = useParams()+ const history = useHistory()+ const project: IProjectView = useMemo(() => _find(projects, p => p.id === id) || {} as IProjectView, [projects, id])+ const [areFiltersParsed, setAreFiltersParsed] = useState<boolean>(false)+ const [areTimeBucketParsed, setAreTimeBucketParsed] = useState<boolean>(false)+ const [arePeriodParsed, setArePeriodParsed] = useState<boolean>(false)+ const [panelsData, setPanelsData] = useState<any>({})+ const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState<boolean>(false)+ const [analyticsLoading, setAnalyticsLoading] = useState<boolean>(true)+ const [period, setPeriod] = useState<string>(projectViewPrefs ? projectViewPrefs[id]?.period || periodPairs[3].period : periodPairs[3].period)+ const [timeBucket, setTimebucket] = useState<string>(projectViewPrefs ? projectViewPrefs[id]?.timeBucket || periodPairs[3].tbs[1] : periodPairs[3].tbs[1])+ const activePeriod: {+ period: string,+ label: string,+ tbs: string[],+ } = useMemo(() => _find(periodPairs, p => p.period === period) || {+ period: periodPairs[3].period,+ tbs: periodPairs[3].tbs,+ label: periodPairs[3].label,+ }, [period, periodPairs])+ const [chartData, setChartData] = useState<any>({})+ const [dataLoading, setDataLoading] = useState<boolean>(false)+ const [activeChartMetrics, setActiveChartMetrics] = useState<{+ [key: string]: boolean,+ }>({+ [CHART_METRICS_MAPPING.results]: true,+ })+ const checkIfAllMetricsAreDisabled = useMemo(() => !_some(activeChartMetrics, (value) => value), [activeChartMetrics])+ const [filters, setFilters] = 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)+ const isLoading = authenticated ? _isLoading : false+ const tnMapping = typeNameMapping(t)+ const refCalendar = useRef(null)+ const localStorageDateRange = projectViewPrefs ? projectViewPrefs[id]?.rangeDate : null+ const [dateRange, setDateRange] = useState<Date[] | null>(localStorageDateRange ? [new Date(localStorageDateRange[0]), new Date(localStorageDateRange[1])] : null)++ const timeFormat = useMemo(() => user.timeFormat || TimeFormat['12-hour'], [user])+ const [ref, size] = useSize() as any+ const rotateXAxias = useMemo(() => (size.width > 0 && size.width < 500), [size])+ const [chartType, setChartType] = useState<string>(getItem('chartType') as string || chartTypes.line)++ const { name } = project as IProject++ // @ts-ignore+ const sharedRoles = useMemo(() => _find(user.sharedProjects, p => p.project.id === id)?.role || {}, [user, id])++ const chartMetrics = useMemo(() => {+ return [+ {+ id: CHART_METRICS_MAPPING.results,+ label: t('project.results'),+ active: activeChartMetrics[CHART_METRICS_MAPPING.results],+ },+ ]+ }, [t, activeChartMetrics])++ const dataNames = useMemo(() => {+ return {+ results: t('project.results'),+ }+ }, [t])++ // eslint-disable-next-line react-hooks/exhaustive-deps+ const switchActiveChartMetric = _debounce((pairID) => {+ setActiveChartMetrics(prev => ({ ...prev, [pairID]: !prev[pairID] }))+ })++ const onErrorLoading = () => {+ showError(t('project.noExist'))+ history.push(routes.dashboard)+ }++ // this function is used for requesting the data from the API+ const loadAnalytics = async (forced: boolean = false, newFilters: any = null) => {+ if (!forced && (isLoading || _isEmpty(project) || dataLoading)) {+ return+ }++ setDataLoading(true)+ try {+ let data+ let key+ let from+ let to++ if (dateRange) {+ from = getFormatDate(dateRange[0])+ to = getFormatDate(dateRange[1])+ key = getProjectCacheCustomKey(from, to, timeBucket, newFilters || filters)+ } else {+ key = getProjectCaptchaCacheKey(period, timeBucket, newFilters || filters)+ }++ if (!forced && !_isEmpty(cache[id]) && !_isEmpty(cache[id][key])) {+ data = cache[id][key]+ } else {+ if (period === 'custom' && dateRange) {+ data = await getCaptchaData(id, timeBucket, '', newFilters || filters, from, to)+ } else {+ data = await getCaptchaData(id, timeBucket, period, newFilters || filters, '', '')+ }++ setProjectCache(id, data || {}, key)+ }++ if (_isEmpty(data)) {+ setAnalyticsLoading(false)+ setDataLoading(false)+ setIsPanelsDataEmpty(true)+ return+ }++ const {+ chart, params, customs, appliedFilters,+ } = data++ if (!_isEmpty(appliedFilters)) {+ setFilters(appliedFilters)+ }++ if (_isEmpty(params)) {+ setIsPanelsDataEmpty(true)+ } else {+ const applyRegions = !_includes(noRegionPeriods, activePeriod.period)+ const bbSettings: any = getSettings(chart, timeBucket, activeChartMetrics, applyRegions, timeFormat, rotateXAxias, chartType)+ setChartData(chart)++ setPanelsData({+ types: _keys(params),+ data: params,+ customs,+ })++ const generete = bb.generate(bbSettings)+ generete.data.names(dataNames)++ 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)+ }+ }++ useEffect(() => {+ loadAnalytics()+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [chartType])++ // this funtion is used for requesting the data from the API when the filter is changed+ const filterHandler = (column: any, filter: any, isExclusive: boolean = false) => {+ let newFilters++ // 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+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ } else {+ // selected filter is not present in the filters array -> applying it+ // sroting filter in the state+ newFilters = [+ ...filters,+ { column, filter, isExclusive },+ ]+ setFilters(newFilters)++ // storing filter in the page URL+ // @ts-ignore+ const url = new URL(window.location)+ url.searchParams.append(column, filter)+ const { pathname, search } = url+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ }++ loadAnalytics(true, newFilters)+ }++ // this function is used for requesting the data from the API when the exclusive filter is changed+ const onChangeExclusive = (column: any, filter: any, isExclusive: boolean) => {+ const 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)++ url.searchParams.delete(column)+ url.searchParams.append(column, filter)++ const { pathname, search } = url+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ }++ const refreshStats = () => {+ if (!isLoading && !dataLoading) {+ loadAnalytics(true)+ }+ }++ // Parsing initial filters from the address bar+ useEffect(() => {+ // using try/catch because new URL is not supported by browsers like IE, so at least analytics would work without parsing filters+ 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)+ }+ }, [])++ useEffect(() => {+ if (arePeriodParsed) {+ try {+ // @ts-ignore+ const url = new URL(window.location)+ const { searchParams } = url+ const intialTimeBucket: string = searchParams.get('timeBucket') || ''+ // eslint-disable-next-line lodash/prefer-lodash-method+ if (!_includes(validTimeBacket, intialTimeBucket)) {+ return+ }+ const newPeriodFull = _find(periodPairs, (el) => el.period === period) || {+ period: '',+ tbs: [],+ label: '',+ }+ if (!_includes(newPeriodFull.tbs, intialTimeBucket)) {+ return+ }+ setTimebucket(intialTimeBucket)+ } finally {+ setAreTimeBucketParsed(true)+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [arePeriodParsed])++ const onRangeDateChange = (dates: Date[], onRender?: any) => {+ 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+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ setTimebucket(eventEmitTimeBucket)+ }++ url.searchParams.delete('period')+ url.searchParams.delete('from')+ url.searchParams.delete('to')+ url.searchParams.append('period', 'custom')+ url.searchParams.append('from', dates[0].toISOString())+ url.searchParams.append('to', dates[1].toISOString())++ const { pathname, search } = url+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })++ setPeriodPairs(tbPeriodPairs(t, timeBucketToDays[index].tb, dates))+ setPeriod('custom')+ setProjectViewPrefs(id, 'custom', timeBucketToDays[4].tb[0], dates)++ break+ }+ }+ }++ useEffect(() => {+ if (areFiltersParsed && areTimeBucketParsed && arePeriodParsed) {+ loadAnalytics()+ }+ }, [project, period, timeBucket, periodPairs, areFiltersParsed, areTimeBucketParsed, arePeriodParsed, t]) // eslint-disable-line++ useEffect(() => {+ if (dateRange && arePeriodParsed) {+ onRangeDateChange(dateRange)+ }+ }, [dateRange, t, arePeriodParsed]) // eslint-disable-line++ useEffect(() => {+ if (!isLoading && _isEmpty(project)) {+ getProject(id, true)+ .then(projectRes => {+ if (!_isEmpty(projectRes)) {+ getOverallStats([id])+ .then(res => {+ setProjects([...(projects as any[]), {+ ...projectRes,+ overall: res[id],+ live: 'N/A',+ }])+ })+ .then(() => {+ return getLiveVisitors([id])+ })+ .catch(e => {+ console.error(e)+ onErrorLoading()+ })+ } else {+ onErrorLoading()+ }+ })+ .catch(e => {+ console.error(e)+ onErrorLoading()+ })+ }+ }, [isLoading, project, id]) // eslint-disable-line++ const updatePeriod = (newPeriod: any) => {+ const newPeriodFull = _find(periodPairs, (el) => el.period === newPeriod.period)+ let tb: any = timeBucket+ // @ts-ignore+ const url = new URL(window.location)+ if (_isEmpty(newPeriodFull)) return++ if (!_includes(newPeriodFull.tbs, timeBucket)) {+ tb = _last(newPeriodFull.tbs)+ url.searchParams.delete('timeBucket')+ url.searchParams.append('timeBucket', tb)+ setTimebucket(tb)+ }++ if (newPeriod.period !== 'custom') {+ url.searchParams.delete('period')+ url.searchParams.delete('from')+ url.searchParams.delete('to')+ url.searchParams.append('period', newPeriod.period)+ setProjectViewPrefs(id, newPeriod.period, tb)+ setPeriod(newPeriod.period)+ setDateRange(null)+ }+ const { pathname, search } = url+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ }++ 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+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ setTimebucket(newTimebucket)+ setProjectViewPrefs(id, period, newTimebucket, dateRange)+ }++ const openSettingsHandler = () => {+ history.push(_replace(routes.captcha_settings, ':id', id))+ }++ const exportAsImageHandler = async () => {+ setShowIcons(false)+ try {+ const blob = await domToImage.toBlob(dashboardRef.current)+ saveAs(blob, `swetrix-${dayjs().format('YYYY-MM-DD-HH-mm-ss')}.png`)+ } catch (e) {+ showError(t('project.exportImgError'))+ console.error('[ERROR] Error while generating export image.')+ console.error(e)+ } finally {+ setShowIcons(true)+ }+ }++ useEffect(() => {+ try {+ // @ts-ignore+ const url = new URL(window.location)+ const { searchParams } = url+ const intialPeriod = projectViewPrefs ? searchParams.get('period') || projectViewPrefs[id]?.period : searchParams.get('period') || '7d'+ 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+ }, [])++ const resetFilters = () => {+ // @ts-ignore+ const url: URL = new URL(window.location)+ const { searchParams } = url+ // eslint-disable-next-line lodash/prefer-lodash-method+ searchParams.forEach((value, key) => {+ if (!_includes(validFilters, key)) {+ return+ }+ searchParams.delete(key)+ })+ const { pathname, search } = url+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ setFilters([])+ loadAnalytics(true, [])+ }++ const exportTypes = [+ { label: t('project.asImage'), onClick: exportAsImageHandler },+ {+ label: t('project.asCSV'),+ onClick: () => {+ return onCSVExportClick(panelsData, id, tnMapping, language)+ },+ },+ ]++ // function set chart type and save to local storage+ const setChartTypeOnClick = (type: string) => {+ setItem('chartType', type)+ setChartType(type)+ }++ // useEffect to change chart if we change chart type+ useEffect(() => {+ loadAnalytics()+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [chartType])++ if (!isLoading) {+ return (+ <Title title={name}>+ <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,+ 'min-h-min-footer-ad': !authenticated,+ },+ )}+ ref={dashboardRef}+ >+ <div className='flex flex-col md:flex-row items-center md:items-start justify-between mt-2'>+ <h2 className='text-3xl font-bold text-gray-900 dark:text-gray-50 break-words break-all'>+ {name}+ </h2>+ <div className='flex mt-3 md:mt-0 max-w-[420px] flex-wrap items-center sm:max-w-none justify-between w-full sm:w-auto mx-auto sm:mx-0'>+ <div className='md:border-r border-gray-200 dark:border-gray-600 md:pr-3 sm:mr-3'>+ <button+ type='button'+ 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>+ <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-gray-200 dark:text-gray-50': timeBucket === tb,+ 'text-gray-700 dark:text-gray-50 border-gray-300 dark:border-gray-800 ': timeBucket !== tb,+ },+ )}+ >+ {t(`project.${tb}`)}+ </button>+ ))}+ </span>+ </div>+ <Dropdown+ items={periodPairs}+ title={activePeriod.label}+ labelExtractor={(pair) => pair.dropdownLabel || pair.label}+ keyExtractor={(pair) => pair.label}+ onSelect={(pair) => {+ if (pair.isCustomDate) {+ setTimeout(() => {+ // @ts-ignore+ refCalendar.current.openCalendar()+ }, 100)+ } else {+ setPeriodPairs(tbPeriodPairs(t))+ setDateRange(null)+ updatePeriod(pair)+ }+ }}+ />+ <FlatPicker+ ref={refCalendar}+ onChange={(date) => setDateRange(date)}+ value={dateRange || []}+ maxDateMonths={MAX_MONTHS_IN_PAST}+ />+ </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'>+ {!isPanelsDataEmpty && (+ <Dropdown+ items={chartMetrics}+ title={t('project.metricVis')}+ labelExtractor={(pair) => {+ const {+ label, id: pairID, active,+ } = pair++ return (+ <Checkbox+ className={cx({ hidden: isPanelsDataEmpty || analyticsLoading })}+ label={label}+ id={pairID}+ checked={active}+ />+ )+ }}+ keyExtractor={(pair) => pair.id}+ onSelect={({ id: pairID }) => {+ switchActiveChartMetric(pairID)+ }}+ />+ )}+ <Dropdown+ items={exportTypes}+ 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='mt-14 xs:mt-0' />+ <div className='relative'>+ <div className='absolute right-0 z-10 -top-2'>+ <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-900 dark:hover:bg-gray-700 focus:outline-none focus:!ring-0 focus:!ring-offset-0 focus:!ring-transparent', {+ 'text-indigo-600 dark:text-indigo-500 shadow-md': chartType === chartTypes.bar,+ 'text-gray-400 dark:text-gray-500': chartType !== chartTypes.bar,+ })}+ >+ <PresentationChartBarIcon className='w-6 h-6' />+ </button>+ <button+ type='button'+ 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-900 dark:hover:bg-gray-700 focus:!outline-0 focus:!ring-0 focus:!ring-offset-0 focus:!ring-transparent', {+ 'text-indigo-600 dark:text-indigo-500 shadow-md': chartType === chartTypes.line,+ 'text-gray-400 dark:text-gray-500': chartType !== chartTypes.line,+ })}+ >+ <PresentationChartLineIcon className='w-6 h-6' />+ </button>+ </div>+ </div>+ </div>+ {(analyticsLoading) && (+ <Loader />+ )}+ {(isPanelsDataEmpty) && (+ <NoEvents filters={filters} resetFilters={resetFilters} />+ )}+ <div className={cx('pt-4 md:pt-0', { hidden: isPanelsDataEmpty || analyticsLoading })}>+ <div+ className={cx('h-80', {+ hidden: checkIfAllMetricsAreDisabled,+ })}+ >+ <div className='h-80' id='dataChart' />+ </div>+ <Filters+ filters={filters}+ onRemoveFilter={filterHandler}+ onChangeExclusive={onChangeExclusive}+ tnMapping={tnMapping}+ />+ {dataLoading && (+ <div className='loader bg-transparent static mt-4' id='loader'>+ <div className='loader-head dark:bg-slate-800'>+ <div className='first dark:bg-slate-600' />+ <div className='second dark:bg-slate-600' />+ </div>+ </div>+ )}+ <div className='mt-5 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3'>+ {/* {!_isEmpty(project.overall) && (+ <Overview+ t={t}+ overall={project.overall}+ chartData={chartData}+ activePeriod={activePeriod}+ sessionDurationAVG={sessionDurationAVG}+ live={liveStats[id] || 'N/A'}+ projectId={id}+ />+ )} */}+ {_map(panelsData.types, (type: keyof typeof tnMapping) => {+ const panelName = tnMapping[type]+ // @ts-ignore+ const panelIcon = panelIconMapping[type]++ if (type === 'cc') {+ return (+ <Panel+ t={t}+ key={type}+ icon={panelIcon}+ id={type}+ onFilter={filterHandler}+ name={panelName}+ data={panelsData.data[type]}+ rowMapper={(rowName) => (+ <CCRow rowName={rowName} language={language} />+ )}+ />+ )+ }++ if (type === 'dv') {+ return (+ <Panel+ t={t}+ key={type}+ icon={panelIcon}+ id={type}+ onFilter={filterHandler}+ name={panelName}+ data={panelsData.data[type]}+ capitalize+ />+ )+ }++ if (type === 'ref') {+ return (+ <Panel+ t={t}+ key={type}+ icon={panelIcon}+ id={type}+ onFilter={filterHandler}+ name={panelName}+ data={panelsData.data[type]}+ rowMapper={(rowName) => (+ <RefRow rowName={rowName} showIcons={showIcons} />+ )}+ />+ )+ }++ return (+ <Panel+ t={t}+ key={type}+ icon={panelIcon}+ id={type}+ onFilter={filterHandler}+ name={panelName}+ data={panelsData.data[type]}+ />+ )+ })}+ {!_isEmpty(panelsData.customs) && (+ <CustomEvents+ t={t}+ customs={panelsData.customs}+ onFilter={filterHandler}+ chartData={chartData}+ />+ )}+ </div>+ </div>+ </div>+ </div>+ {!authenticated && (+ <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>+ )}+ </Title>+ )+ }++ return (+ <Title title={name}>+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>+ <Loader />+ </div>+ </Title>+ )+}++ViewProject.propTypes = {+ projects: PropTypes.arrayOf(PropTypes.object).isRequired,+ cache: PropTypes.objectOf(PropTypes.object).isRequired,+ projectViewPrefs: PropTypes.objectOf(PropTypes.object).isRequired,+ showError: PropTypes.func.isRequired,+ setProjectCache: PropTypes.func.isRequired,+ setProjectViewPrefs: PropTypes.func.isRequired,+ isLoading: PropTypes.bool.isRequired,+ authenticated: PropTypes.bool.isRequired,+}++export default memo(ViewProject)diff --git a/app/pages/Captcha/View/components/CCRow.tsx b/app/pages/Captcha/View/components/CCRow.tsxnew file mode 100644index 000000000..bed9f85f1--- /dev/null+++ b/app/pages/Captcha/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'+ />+ + {countries.getName(rowName, language)}+ </>+)++CCRow.propTypes = {+ rowName: PropTypes.string.isRequired,+ language: PropTypes.string.isRequired,+}++export default memo(CCRow)diff --git a/app/pages/Captcha/View/components/Filters.tsx b/app/pages/Captcha/View/components/Filters.tsxnew file mode 100644index 000000000..30299d6f0--- /dev/null+++ b/app/pages/Captcha/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}+ + <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>+ + "+ {displayFilter}+ "+ <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/pages/Captcha/View/components/InteractiveMap.tsx b/app/pages/Captcha/View/components/InteractiveMap.tsxnew file mode 100644index 000000000..5493c9bc6--- /dev/null+++ b/app/pages/Captcha/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 } 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')}+ :+ + <strong+ className={cx({+ 'dark:text-indigo-400': isTrafficTab || dataHover.data < 5,+ 'dark:text-red-400': !isTrafficTab && dataHover.data >= 5,+ })}+ >+ {isTrafficTab ? dataHover.data : getStringFromTime(getTimeFromSeconds(dataHover.data), true)}+ </strong>+ </div>+ )}+ </div>+ </div>+ )+}++InteractiveMap.propTypes = {+ onClickCountry: PropTypes.func,+ data: PropTypes.objectOf(PropTypes.number),+ total: PropTypes.number,+}++InteractiveMap.defaultProps = {+ data: {},+ onClickCountry: () => { },+ total: 0,+}++export default memo(InteractiveMap)diff --git a/app/pages/Captcha/View/components/LiveVisitorsDropdown.tsx b/app/pages/Captcha/View/components/LiveVisitorsDropdown.tsxnew file mode 100644index 000000000..e48dabacb--- /dev/null+++ b/app/pages/Captcha/View/components/LiveVisitorsDropdown.tsx@@ -0,0 +1,91 @@+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 }: {+ live: number | string+ projectId: 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)+ .then((res) => {+ setLiveInfo(res)+ })+ .catch((err) => {+ console.log(err)+ })+ .finally(() => {+ setLoading(false)+ })+ }++ useEffect(() => {+ if (show) {+ getLiveVisitors()+ }+ }, [show]) // eslint-disable-line react-hooks/exhaustive-deps++ return (+ <OutsideClickHandler+ onOutsideClick={() => setShow(false)}+ >+ <p className='h-5 mr-2 text-gray-900 dark:text-gray-50 text-xl cursor-pointer' onClick={() => setShow(!show)}>+ {live}+ {' '}+ {show ? <ChevronUpIcon className='inline w-5 h-5' /> : <ChevronDownIcon className='inline w-5 h-5' />}+ </p>+ {show && (+ <div className='absolute z-10 mt-2 right-0 top-20 text-gray-900 bg-white border border-gray-200 rounded-md shadow-lg dark:bg-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 rounded-md top-2 right-2 w-5 h-5 text-gray-900 cursor-pointer dark:text-gray-50 hover:bg-gray-200 hover:dark:bg-slate-800 ' onClick={() => setShow(!show)} />+ </div>+ )}+ </OutsideClickHandler>+ )+}++export default LiveVisitorsDropdowndiff --git a/app/pages/Captcha/View/components/NoEvents.tsx b/app/pages/Captcha/View/components/NoEvents.tsxnew file mode 100644index 000000000..ddc5ac585--- /dev/null+++ b/app/pages/Captcha/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_CAPTCHA_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.noCaptchaEv'+ components={{+ // eslint-disable-next-line jsx-a11y/anchor-has-content+ url: <a href={DOCS_CAPTCHA_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/pages/Captcha/View/components/RefRow.tsx b/app/pages/Captcha/View/components/RefRow.tsxnew file mode 100644index 000000000..bee34ee08--- /dev/null+++ b/app/pages/Captcha/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/pages/Captcha/View/index.jsx b/app/pages/Captcha/View/index.jsxnew file mode 100644index 000000000..0c9f97005--- /dev/null+++ b/app/pages/Captcha/View/index.jsx@@ -0,0 +1,3 @@+import ViewProject from './ViewCaptcha.container'++export default ViewProjectdiff --git a/app/pages/Captcha/View/styles.css b/app/pages/Captcha/View/styles.cssnew file mode 100644index 000000000..f8a7a141b--- /dev/null+++ b/app/pages/Captcha/View/styles.css@@ -0,0 +1,7 @@+html.dark .bb-legend-item text {+ fill: #f9fafb;+}++html.dark .bb-axis {+ fill: #f9fafb;+}diff --git a/app/pages/Changelog/index.tsx b/app/pages/Changelog/index.tsxnew file mode 100644index 000000000..82a64998c--- /dev/null+++ b/app/pages/Changelog/index.tsx@@ -0,0 +1,344 @@+/* eslint-disable jsx-a11y/anchor-has-content */+import React from 'react'+import _map from 'lodash/map'+import { useTranslation } from 'react-i18next'+import dayjs from 'dayjs'+import { HashLink } from 'react-router-hash-link'+import { Link } from 'react-router-dom'++import {+ SWETRIX_VS_GOOGLE, DOCS_URL, CAPTCHA_URL, DOCS_CAPTCHA_URL,+} from 'redux/constants'+import Title from 'components/Title'+import routes from 'routes'++const INTEGRATIONS_LINK = `${routes.user_settings}#integrations`++// Date format: YYYY-MM-DD+const changelog = [+ {+ date: '2023-05-29',+ changes: [+ 'Added password protected Projects functionality: now you can set a password on your Dashboard and share it with other people, only those who know the password will be able to access it.',+ ],+ },+ {+ date: '2023-05-28',+ changes: [+ 'Added an indicator that shows how many live visitors your Project has at the moment on the browser tab.',+ 'Updated Swetrix logo.',+ 'Hidden the "Hi! How can we help?" chat widget on all pages except the Contact page (yeah, it was a terrible idea to display it on ALL of the pages).',+ ],+ },+ {+ date: '2023-05-27',+ changes: [+ 'Added Plan usage section to the Billing page.',+ 'Added currency localisation: now you can pay for your plan with GBP (if you\'re located in the UK) or EUR (if you\'re located in Eurozone), for all other countries the default currency is still the US Dollar.',+ ],+ },+ {+ date: '2023-05-15',+ changes: [+ 'Fixed timezone related issues.',+ 'Dropped support for weekly timebucket - it\'s a pain to support it across multiple timezones, but we may add it back in the future.',+ 'Fix a bug when filters might not be applied to the chart when reloading the page.',+ ],+ },+ {+ date: '2023-05-08',+ changes: [+ 'Added an ability to compare statistics over time periods - now you can compare the current period with the previous one, or select a custom date range to compare.',+ <>+ Swetrix is now an Open Startup, we+ {' '}+ <Link to={routes.open} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'>+ publish+ </Link>+ our finance and technical metrics.+ </>,+ 'Refactored the statistics API: now the Dashboard loads at least 2 times faster and can easily handle dozens of millions of events.',+ ],+ },+ {+ date: '2023-04-27',+ changes: [+ 'Added user flow feature. By using this functionality you can track user interactions and navigation patterns throughout your application, providing valuable insights for optimising user experience and engagement. To track user flow, you have to upgrade Swetrix NPM library to the version v2.2.1 or higher.',+ 'Fully redesigned the Dashboard page, now your projects are listed as cards with a preview of the most important metrics.',+ 'Updated the Project View screen to be more optimised for larger screens.',+ 'Slightly improved the Dark theme throughout the application.',+ ],+ },+ {+ date: '2023-04-22',+ changes: [+ 'Added an ability to partially delete project related analytics data.',+ ],+ },+ {+ date: '2023-04-20',+ changes: [+ 'Added sorting functinoality to the Custom events panel.',+ ],+ },+ {+ date: '2023-04-18',+ changes: [+ 'Added pagination for Custom events panel in Dashboard.',+ ],+ },+ {+ date: '2023-04-17',+ changes: [+ 'Added Github SSO support.',+ ],+ },+ {+ date: '2023-04-16',+ changes: [+ 'Added OAuth SSO: now you can sign in or register to Swetrix using your Google account or link a Google account to your existing Swetrix account to ease the sign in process. We will add other SSO providers soon :)',+ ],+ },+ {+ date: '2023-04-13',+ changes: [+ 'Added an ability to view custom events on chart.',+ ],+ },+ {+ date: '2023-04-12',+ changes: [+ 'Fixed an issue when the selected time bucket or period was not remembered and used after page reload.',+ ],+ },+ {+ date: '2023-04-09',+ changes: [+ 'Added an ability to transfer a project from one account to another.',+ 'Fixed a bug when the app was crashing due to \'ChunkLoadError: Loading chunk N failed\' error. Now in case of such error the app will reload the page automatically for one time.',+ 'Fixed broken alignment of the action buttons in the dashboard.',+ ],+ },+ {+ date: '2023-04-06',+ changes: [+ 'utm_* parameters in the dashboard are now displayed as decoded URL values (i.e. %20 is replaced with a space, %3D is replaced with an equal sign, etc.).',+ 'Fully rewritten the frontend part of Swetrix to TypeScript to improve stability and code quality.',+ 'Fixed some minor bugs related to live visitors counter and the CAPTCHA configuration page.',+ 'Fixed spacing between action buttons on Dashboard on mobile layouts.',+ ],+ },+ {+ date: '2023-03-20',+ changes: [+ <>+ Introducing a new service:+ {' '}+ <a+ href={CAPTCHA_URL}+ className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'+ target='_blank'+ rel='noopener noreferrer'+ >+ Swetrix CAPTCHA+ </a>+ .+ This is a privacy-focused and fully opensource CAPTCHA service that you can use on your website to protect it from bots.+ {' '}+ Read more about it in our+ {' '}+ <a+ href={DOCS_CAPTCHA_URL}+ className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'+ target='_blank'+ rel='noopener noreferrer'+ >+ documentation page+ </a>+ .+ </>,+ ],+ },+ {+ date: '2023-03-18',+ changes: [+ 'Added new email report frequency: quarterly.',+ 'Added project email reports subscription to multiple email addresses.',+ ],+ },+ {+ date: '2023-03-11',+ changes: [+ 'Redesigned Dashboard page panel pages layout (now it\'s more user friendly, the total count of items and pages are displayed as well).',+ ],+ },+ {+ date: '2023-02-26',+ changes: [+ 'Added a switch between line and bar chart on the dashboard page.',+ ],+ },+ {+ date: '2023-02-18',+ changes: [+ 'Added AI forecasting functionality.',+ 'Migrated to a paid-only model with a free trial. Everyone who had signed up on Swetrix before that change can continue to use their free tier.',+ ],+ },+ {+ date: '2023-02-09',+ changes: [+ 'Added an ability to filter data by custom events.',+ <>+ Released a public+ {' '}+ <a href={`${DOCS_URL}/statistics-api`} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' target='_blank' rel='noopener noreferrer'>+ API Documentation+ </a>+ {' '}+ related to data aggregation.+ </>,+ 'Fully refactored the authentication system.',+ 'Added support for API keys.',+ ],+ },+ {+ date: '2023-02-04',+ changes: [+ 'Added a Polish translation.',+ <>+ Added a+ {' '}+ <Link to={routes.cookiePolicy} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'>+ Cookie policy+ </Link>+ .+ </>,+ ],+ },+ {+ date: '2023-01-28',+ changes: [+ 'Added time notation setting: now you can display chart hours in 12-hour or 24-hour format.',+ 'Fixed live visitors dropdown overlap for non-English languages.',+ ],+ },+ {+ date: '2023-01-17',+ changes: [+ <>+ Got rid of our custom documentation page and migrated to Docusaurus insted. Check it out at+ {' '}+ <a href={DOCS_URL} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' target='_blank' rel='noopener noreferrer'>+ {DOCS_URL}+ </a>+ .+ </>,+ ],+ },+ {+ date: '2023-01-05',+ changes: [+ <>+ Added notification channels integrations. Now you can connect your Telegram account to our official bot and receive notifications (e.g. when someone logins into your account), set up custom project alerts and much more! You can set up the integration in your+ {' '}+ <HashLink to={INTEGRATIONS_LINK} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'>+ account settings+ </HashLink>+ .+ </>,+ 'Added new tab in Dashboard: Alerts.\nAutomated alerts are a powerful tool that allow you to run automated tasks when specific events occur.\nWe can automatically monitor your project for traffic spikes and notify you via Telegram.',+ ],+ },+ {+ date: '2023-01-03',+ changes: [+ 'Added new tab in Dashboard: Performance. By switching to it you\'ll be able to see the performance of your website, page loading by country, some detailed statistics like TTFB, DOM Content Load, DNS response time and so on.\nTo collect the performance data you need to upgrade swetrix.js tracking script to v2.0.0 or higher.\nIf you\'re using the UMD build - the latest version is pulled automatically.\nIf you\'re using the NPM package - make sure to update it manually.',+ ],+ },+ {+ date: '2022-12-30',+ changes: [+ 'Added an ability to see live visitors on your website. Now you\'re able to not only see how many visitors you have, but actually see some information about them.',+ 'Added new metric: session duration. Now you\'re able to see how long your users are staying on your website.',+ 'Added new chart metrics: bounce rate, views per session, trendlines and session duration.',+ <>+ Added the comparisons column to the footer. There's only+ {' '}+ <a href={SWETRIX_VS_GOOGLE} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' target='_blank' rel='noopener noreferrer' aria-label='Swetrix to Google Analytics comparison (opens in a new tab)'>+ Google Analytics comparison+ </a>+ {' '}+ for now, but more will be added soon.+ </>,+ 'Improved chart colours.',+ 'Launched the changelog page! π',+ ],+ },+]++const Changelog = (): JSX.Element => {+ const { t }: {+ t: (key: string) => string+ } = useTranslation('common')++ return (+ <Title title={t('titles.changelog')}>+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>+ <div className='w-11/12 md:w-4/5 mx-auto pb-16 pt-12 px-4 sm:px-6 lg:px-8 whitespace-pre-line'>+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('titles.changelog')}+ </h1>++ <div className='relative sm:ml-[calc(2rem+1px)] md:ml-[calc(3.5rem+1px)] lg:ml-[calc(11rem)] sm:pb-12 mt-10'>+ <div className='hidden absolute top-3 bottom-0 right-full mr-7 md:mr-[3.25rem] w-px bg-slate-200 dark:bg-slate-700 sm:block' />+ <div className='space-y-16'>+ {_map(changelog, (item) => {+ const date = dayjs(item.date).format('YYYY-MM-DDT00:00:00.000Z')+ const displayDate = dayjs(item.date).locale('en').format('MMM DD, YYYY')++ return (+ <div key={item.date} className='relative group'>+ <div className='absolute -inset-y-2.5 -inset-x-4 md:-inset-y-4 md:-inset-x-6 sm:rounded-2xl group-hover:bg-slate-50/70 dark:group-hover:bg-slate-800/50' />+ <svg+ viewBox='0 0 9 9'+ className='hidden absolute right-full mr-6 top-2 text-slate-200 dark:text-slate-600 md:mr-12 w-[calc(0.5rem+1px)] h-[calc(0.5rem+1px)] overflow-visible sm:block'+ >+ <circle+ cx='4.5'+ cy='4.5'+ r='4.5'+ stroke='currentColor'+ className='fill-white dark:fill-slate-800'+ strokeWidth={2}+ />+ </svg>+ <div className='relative'>+ <ul className='list-disc text-gray-900 dark:text-gray-50 relative top-7 lg:top-0 lg:block text-base mt-2 mb-4 prose prose-slate prose-a:relative prose-a:z-10 dark:prose-dark line-clamp-2'>+ {_map(item.changes, (change) => (+ // @ts-ignore+ <li key={change} className='whitespace-pre-line'>{change}</li>+ ))}+ </ul>+ <dl className='absolute left-1.5 top-0 lg:left-auto lg:right-full lg:mr-[calc(5rem+1px)]'>+ <dt className='sr-only'>Date</dt>+ <dd className='whitespace-nowrap text-sm leading-6 text-slate-700 dark:text-slate-300'>+ <time dateTime={date}>+ {displayDate}+ </time>+ </dd>+ </dl>+ </div>+ </div>+ )+ })}+ </div>+ </div>++ </div>+ </div>+ </Title>+ )+}++export default Changelogdiff --git a/app/pages/Contact/index.tsx b/app/pages/Contact/index.tsxnew file mode 100644index 000000000..2592e7f13--- /dev/null+++ b/app/pages/Contact/index.tsx@@ -0,0 +1,85 @@+/* eslint-disable jsx-a11y/anchor-has-content */+import React, { useEffect } from 'react'+import { useTranslation, Trans } from 'react-i18next'++import {+ CONTACT_EMAIL, TWITTER_URL, TWITTER_USERNAME, DISCORD_URL,+} from 'redux/constants'+import Title from 'components/Title'++const Contact = (): JSX.Element => {+ const { t }: {+ t: (key: string) => string+ } = useTranslation('common')++ useEffect(() => {+ const intergram = document.querySelector('#intergramPlaceholder')++ if (!intergram) {+ return () => {}+ }++ intergram.classList.remove('hidden')+ intergram.classList.add('flex')++ return () => {+ intergram.classList.remove('flex')+ intergram.classList.add('hidden')+ }+ }, [])++ return (+ <Title title={t('titles.contact')}>+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>+ <div className='w-11/12 md:w-4/5 mx-auto pb-16 pt-12 px-4 sm:px-6 lg:px-8 whitespace-pre-line'>+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('titles.contact')}+ </h1>+ <div className='mt-2 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('contact.howTo')}++ <ol className='list-decimal ml-5 sm:ml-10'>+ <li className='mt-1'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='contact.ways.email'+ values={{ email: CONTACT_EMAIL }}+ components={{+ mail: <a href={`mailto:${CONTACT_EMAIL}`} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' />,+ }}+ />+ </li>+ <li className='mt-1'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='contact.ways.twitter'+ values={{ twitter: TWITTER_USERNAME }}+ components={{+ url: <a href={TWITTER_URL} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' />,+ }}+ />+ </li>+ <li className='mt-1'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='contact.ways.discord'+ components={{+ url: <a href={DISCORD_URL} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' />,+ }}+ />+ </li>+ <li className='mt-1'>+ {t('contact.ways.chat')}+ </li>+ </ol>+ </div>+ </div>+ </div>+ </Title>+ )+}++export default Contactdiff --git a/app/pages/CookiePolicy/index.tsx b/app/pages/CookiePolicy/index.tsxnew file mode 100644index 000000000..773acd379--- /dev/null+++ b/app/pages/CookiePolicy/index.tsx@@ -0,0 +1,96 @@+/* eslint-disable react/no-unescaped-entities */+import React from 'react'+import _map from 'lodash/map'++import Title from 'components/Title'++const typesOfCookies = [+ {+ cookie: 'Essential cookies',+ description: 'These cookies are strictly necessary to provide you with our website and use its functionalities. If you choose to disable these cookies via your internet browser, access and/or use of our website may be altered.',+ },+]++const CookiePolicy = () => {+ return (+ <Title title='Cookie Policy'>+ <div className='bg-gray-50 dark:bg-slate-900'>+ <div className='w-11/12 md:w-4/5 mx-auto pb-16 pt-12 px-4 sm:px-6 lg:px-8'>+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ Cookie Policy+ </h1>+ <p className='mt-4 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ Part of the provision of our service and this website relies on the collection of cookies. Depending on their use, they may be considered essential or subject to your explicit consent.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>+ What is a cookie?+ </h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ A cookie is a small text file that may be deposited and saved on the hard drive of your device (computer, tablet, smartphone, etc.) when you visit our website. It allows us or third parties to identify the device on which it has been saved and to keep record of certain information relating to your journey in order, for instance, to simplify your visit on our website, to secure your connection or to adapt the content of a page to your interests.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>+ What types of cookies are collected?+ </h3>+ <div className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <div className='mt-2 flex flex-col'>+ <div className='-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8'>+ <div className='inline-block min-w-full py-2 align-middle md:px-6 lg:px-8'>+ <div className='overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg'>+ <table className='w-full min-w-full divide-y divide-gray-300 200 dark:divide-gray-500'>+ <thead className='bg-gray-50 dark:bg-slate-800'>+ <tr>+ <th+ scope='col'+ className='w-1/5 py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 dark:text-gray-50 sm:pl-6'+ >+ Cookie+ </th>+ <th+ scope='col'+ className='w-4/5 px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'+ >+ Description+ </th>+ </tr>+ </thead>+ <tbody className='divide-y divide-gray-200 dark:divide-gray-600 bg-white dark:bg-slate-800'>+ {_map(typesOfCookies, ({+ cookie, description,+ }) => (+ <tr key={cookie}>+ <td className='w-1/5 px-3 py-4 text-sm text-gray-900 dark:text-gray-50 sm:pl-6'>+ {cookie}+ </td>+ <td className='break-words w-4/5 px-3 py-4 text-sm text-gray-900 dark:text-gray-50'>+ {description}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ </div>+ </div>+ </div>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>+ How to manage cookies?+ </h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ Your internet browser may allow you to manage your cookie preferences by removing or rejecting them via your browser settings (usually located in "help", βtoolsβ or βeditβ sections). Remember that if you choose to disable our cookies, you may experience some inconvenience when using our website.+ </p>++ <hr className='mt-10 mb-4 border-gray-200 dark:border-gray-600' />+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <i>Last updated: February 4, 2023.</i>+ </p>+ </div>+ </div>+ </Title>+ )+}++export default CookiePolicydiff --git a/app/pages/CrashHandler/index.tsx b/app/pages/CrashHandler/index.tsxnew file mode 100644index 000000000..d47760b17--- /dev/null+++ b/app/pages/CrashHandler/index.tsx@@ -0,0 +1,114 @@+import React from 'react'+import _toString from 'lodash/toString'+import { ExclamationTriangleIcon, ChevronDownIcon, ChevronUpIcon } from '@heroicons/react/24/outline'+import { CONTACT_EMAIL, PAGE_FORCE_REFRESHED } from 'redux/constants'++interface CrashHandlerProps {+ children: JSX.Element+}++interface CrashHandlerState {+ appCrashed: boolean+ crashStack: string+ errorMessage: string+ crashStackShown: boolean+}++const retryPageLoading = () => {+ const wasPageForceRefreshed = sessionStorage.getItem(PAGE_FORCE_REFRESHED) === 'true'++ if (!wasPageForceRefreshed) {+ sessionStorage.setItem(PAGE_FORCE_REFRESHED, 'true')+ return window.location.reload()+ }++ return null+}++class CrashHandler extends React.Component<CrashHandlerProps, CrashHandlerState> {+ constructor(props: CrashHandlerProps) {+ super(props)+ this.state = {+ appCrashed: false,+ crashStack: '',+ errorMessage: '',+ crashStackShown: false,+ }+ }++ componentDidCatch() {+ retryPageLoading()+ }++ static getDerivedStateFromError(error: Error) {+ return {+ errorMessage: _toString(error),+ crashStack: error?.stack,+ appCrashed: true,+ }+ }++ onCrashStackClick = () => {+ this.setState((prevState) => ({+ crashStackShown: !prevState.crashStackShown,+ }))+ }++ render() {+ const {+ appCrashed, crashStack, errorMessage, crashStackShown,+ } = this.state+ const { children } = this.props++ if (appCrashed) {+ return (+ // Using style because for some reason min-h-screen doesn't work+ <div style={{ minHeight: '100vh' }} className='pt-16 pb-12 flex flex-col bg-gray-50 dark:bg-slate-900'>+ <div className='flex-grow flex flex-col justify-center max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8'>+ <div className='flex-shrink-0 flex justify-center'>+ <ExclamationTriangleIcon className='h-24 w-auto text-yellow-400 dark:text-yellow-600' />+ </div>+ <div className='py-8'>+ <div className='text-center'>+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight sm:text-5xl'>Uh-oh..</h1>+ <p className='mt-2 text-base font-medium text-gray-800 dark:text-gray-300'>+ The app has crashed. We are sorry about that :(+ <br />+ Please, tell us about it at+ {' '}+ {CONTACT_EMAIL}+ </p>+ <p className='mt-6 text-base font-medium text-gray-800 dark:text-gray-300'>+ {errorMessage}+ <br />+ <span onClick={this.onCrashStackClick} className='flex justify-center items-center text-base text-gray-800 dark:text-gray-300 cursor-pointer hover:underline'>+ {crashStackShown ? (+ <>+ Hide crash stack+ <ChevronUpIcon className='w-4 h-4 ml-2' />+ </>+ ) : (+ <>+ Show crash stack+ <ChevronDownIcon className='w-4 h-4 ml-2' />+ </>+ )}+ </span>+ {crashStackShown && (+ <span className='text-sm text-gray-600 dark:text-gray-400 whitespace-pre-line'>+ {crashStack}+ </span>+ )}+ </p>+ </div>+ </div>+ </div>+ </div>+ )+ }++ return children+ }+}++export default CrashHandlerdiff --git a/app/pages/Dashboard/Dashboard.container.tsx b/app/pages/Dashboard/Dashboard.container.tsxnew file mode 100644index 000000000..6edbb07d4--- /dev/null+++ b/app/pages/Dashboard/Dashboard.container.tsx@@ -0,0 +1,81 @@+import { connect } from 'react-redux'+import { errorsActions } from 'redux/reducers/errors'+import UIActions from 'redux/reducers/ui'+import sagaActions from 'redux/sagas/actions'+import { authActions } from 'redux/reducers/auth'+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 Dashboard from './Dashboard'++const mapStateToProps = (state: StateType) => ({+ projects: state.ui.projects.projects,+ sharedProjects: state.ui.projects.sharedProjects,+ captchaProjects: state.ui.projects.captchaProjects,+ user: state.auth.user,+ isLoading: state.ui.projects.isLoading,+ total: state.ui.projects.total,+ sharedTotal: state.ui.projects.sharedTotal,+ captchaTotal: state.ui.projects.captchaTotal,+ error: state.ui.projects.error,+ dashboardPaginationPage: state.ui.projects.dashboardPaginationPage,+ dashboardPaginationPageShared: state.ui.projects.dashboardPaginationPageShared,+ dashboardPaginationPageCaptcha: state.ui.projects.dashboardPaginationPageCaptcha,+ dashboardTabs: state.ui.projects.dashboardTabs,+ liveStats: state.ui.projects.liveStats,+})++const mapDispatchToProps = (dispatch: AppDispatch) => ({+ deleteProjectFailed: (message: string) => {+ dispatch(errorsActions.deleteProjectFailed({+ message,+ }))+ },+ setProjectsShareData: (data: IProject | ISharedProject, id: string, shared?: boolean) => {+ dispatch(UIActions.setProjectsShareData({+ data,+ id,+ shared,+ }))+ },+ setUserShareData: (data: ISharedProject, id: string) => {+ dispatch(authActions.setUserShareData({+ data,+ id,+ }))+ },+ userSharedUpdate: (message: string) => {+ dispatch(alertsActions.userSharedUpdate({+ message,+ }))+ },+ sharedProjectError: (message: string) => {+ dispatch(errorsActions.sharedProjectFailed({+ message,+ }))+ },+ loadProjects: (take: number, skip: number) => {+ dispatch(sagaActions.loadProjects(take, skip))+ },+ loadSharedProjects: (take: number, skip: number) => {+ dispatch(sagaActions.loadSharedProjects(take, skip))+ },+ setDashboardPaginationPage: (page: number) => {+ dispatch(UIActions.setDashboardPaginationPage(page))+ },+ setDashboardPaginationPageShared: (page: number) => {+ dispatch(UIActions.setDashboardPaginationPageShared(page))+ },+ setDashboardTabs: (tab: string) => {+ dispatch(UIActions.setDashboardTabs(tab))+ },+ loadProjectsCaptcha: (take: number, skip: number) => {+ dispatch(sagaActions.loadProjectsCaptcha(take, skip))+ },+ setDashboardPaginationPageCaptcha: (page: number) => {+ dispatch(UIActions.setDashboardPaginationPageCaptcha(page))+ },+})++export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)diff --git a/app/pages/Dashboard/Dashboard.tsx b/app/pages/Dashboard/Dashboard.tsxnew file mode 100644index 000000000..0a45d6dc9--- /dev/null+++ b/app/pages/Dashboard/Dashboard.tsx@@ -0,0 +1,689 @@+/* eslint-disable react/forbid-prop-types */+import React, {+ memo, useState, useEffect, useMemo,+} from 'react'+import { Link, useHistory } from 'react-router-dom'+import cx from 'clsx'+import PropTypes from 'prop-types'+import _isEmpty from 'lodash/isEmpty'+import _isNumber from 'lodash/isNumber'+import _replace from 'lodash/replace'+import _map from 'lodash/map'+import _isUndefined from 'lodash/isUndefined'+import _filter from 'lodash/filter'+import _find from 'lodash/find'+import { useTranslation } from 'react-i18next'+import {+ FolderPlusIcon, AdjustmentsVerticalIcon, ArrowTopRightOnSquareIcon,+} from '@heroicons/react/24/outline'+import { XCircleIcon } from '@heroicons/react/24/solid'+import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/20/solid'++import Modal from 'ui/Modal'+import Select from 'ui/Select'+import { withAuthentication, auth } from 'hoc/protected'+import Title from 'components/Title'+import Loader from 'ui/Loader'+import {+ ActivePin, InactivePin, WarningPin, CustomPin,+} from 'ui/Pin'+import routes from 'routes'+import { nFormatter } from 'utils/generic'+import {+ isSelfhosted, ENTRIES_PER_PAGE_DASHBOARD, tabForOwnedProject, tabForSharedProject,+ tabForCaptchaProject, DASHBOARD_TABS, tabsForDashboard, roleViewer,+} from 'redux/constants'+import EventsRunningOutBanner from 'components/EventsRunningOutBanner'++import { acceptShareProject } from 'api'++import Pagination from 'ui/Pagination'+import { ISharedProject } from 'redux/models/ISharedProject'+import {+ IProject, IOvervallObject, ICaptchaProject, ILiveStats,+} from 'redux/models/IProject'+import { IUser } from 'redux/models/IUser'++interface IProjectCard {+ name?: string+ active?: boolean+ overall?: IOvervallObject+ type: 'analytics' | 'captcha'+ t: (key: string, options?: {+ [key: string]: string | number | null | undefined+ }) => string+ live?: string | number+ isPublic?: boolean+ confirmed?: boolean+ id: string+ deleteProjectFailed: (message: string) => void+ sharedProjects: ISharedProject[]+ setProjectsShareData: (data: Partial<ISharedProject>, id: string, shared?: boolean) => void+ setUserShareData: (data: Partial<ISharedProject>, id: string) => void+ shared?: boolean+ userSharedUpdate: (message: string) => void+ sharedProjectError: (message: string) => void+ captcha?: boolean+ isTransferring?: boolean+ getRole?: (id: string) => string | null+}++interface IMiniCard {+ labelTKey: string+ t: (key: string, options?: {+ [key: string]: string | number | null | undefined+ }) => string+ total?: number | string+ percChange?: number+}++const MiniCard = ({+ labelTKey, t, total, percChange,+}: IMiniCard): JSX.Element => {+ const statsDidGrowUp = percChange ? percChange >= 0 : false++ return (+ <div>+ <p className='text-sm text-gray-500 dark:text-gray-300'>+ {t(labelTKey)}+ </p>++ <div className='flex font-bold'>+ <p className='text-xl text-gray-700 dark:text-gray-100'>+ {_isNumber(total) ? nFormatter(total) : total}+ </p>+ {_isNumber(percChange) && (+ <p+ className={cx('flex text-xs items-center', {+ 'text-green-600': statsDidGrowUp,+ 'text-red-600': !statsDidGrowUp,+ })}+ >+ {statsDidGrowUp ? (+ <>+ <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>+ </>+ )}+ {nFormatter(percChange)}+ %+ </p>+ )}+ </div>+ </div>+ )+}++MiniCard.defaultProps = {+ total: 0,+ percChange: null,+}++const ProjectCard = ({+ name, active, overall, t, live, isPublic, confirmed, id, deleteProjectFailed,+ sharedProjects, setProjectsShareData, setUserShareData, shared, userSharedUpdate, sharedProjectError,+ captcha, isTransferring, type, getRole,+}: IProjectCard): JSX.Element => {+ const [showInviteModal, setShowInviteModal] = useState(false)+ const role = useMemo(() => getRole && getRole(id), [getRole, id])+ const history = useHistory()++ const onAccept = async () => {+ // @ts-ignore+ const pid: string = _find(sharedProjects, (item: ISharedProject) => item.project && item.project.id === id)?.id++ try {+ if (!pid || !id) {+ throw new Error('Project not found')+ }+ await acceptShareProject(pid)+ setProjectsShareData({ confirmed: true }, id, true)+ setUserShareData({ confirmed: true }, pid)+ userSharedUpdate(t('apiNotifications.acceptInvitation'))+ } catch (e) {+ sharedProjectError(t('apiNotifications.acceptInvitationError'))+ // @ts-ignore+ deleteProjectFailed(e)+ }+ }++ const onElementClick = (e: React.MouseEvent<HTMLLIElement>) => {+ if (confirmed) {+ return+ }++ e.stopPropagation()+ e.preventDefault()+ setShowInviteModal(true)+ }++ return (+ <div onClick={() => {+ history.push(_replace(type === 'analytics' ? routes.project : routes.captcha, ':id', id))+ }}+ >+ <li+ onClick={onElementClick}+ className='overflow-hidden rounded-xl border border-gray-200 cursor-pointer bg-gray-50 hover:bg-gray-100 dark:bg-slate-800 dark:hover:bg-slate-700 dark:border-slate-800/25'+ >+ <div className='py-4 px-4'>+ <div className='flex justify-between items-center'>+ <p className='text-lg font-semibold text-slate-900 dark:text-gray-50 truncate'>+ {name}+ </p>++ <div+ className='flex items-center gap-2'+ onClick={(e) => e.stopPropagation()}+ >+ {role !== roleViewer.role && (+ <Link+ to={_replace(type === 'analytics' ? routes.project_settings : routes.captcha_settings, ':id', id)}+ aria-label={`${t('project.settings.settings')} ${name}`}+ >+ <AdjustmentsVerticalIcon className='w-6 h-6 text-gray-800 dark:text-slate-400 hover:text-gray-900 dark:hover:text-slate-500' />+ </Link>+ )}+ <a+ href={_replace(type === 'analytics' ? routes.project : routes.captcha, ':id', id)}+ aria-label='name (opens in a new tab)'+ target='_blank'+ rel='noopener noreferrer'+ >+ <ArrowTopRightOnSquareIcon className='w-6 h-6 text-gray-800 dark:text-slate-400 hover:text-gray-900 dark:hover:text-slate-500' />+ </a>+ </div>+ </div>+ <div className='mt-1 flex-shrink-0 flex gap-2'>+ {shared && (+ confirmed ? (+ <ActivePin className='dark:!text-gray-300 dark:!bg-slate-600' label={t('dashboard.shared')} />+ ) : (+ <WarningPin className='dark:!text-gray-300 dark:!bg-slate-600' label={t('common.pending')} />+ )+ )}+ {isTransferring && (+ <CustomPin className='!bg-indigo-500 dark:!bg-indigo-600 !text-gray-300 dark:!text-gray-300' label={t('common.transferring')} />+ )}+ {active ? (+ <ActivePin className='dark:!text-gray-300 dark:!bg-slate-600' label={t('dashboard.active')} />+ ) : (+ <InactivePin className='dark:!text-gray-300 dark:!bg-slate-600' label={t('dashboard.disabled')} />+ )}+ {isPublic && (+ <ActivePin className='dark:!text-gray-300 dark:!bg-slate-600' label={t('dashboard.public')} />+ )}+ </div>+ <div className='mt-4 flex-shrink-0 flex gap-5'>+ {overall && (+ <MiniCard+ labelTKey='dashboard.pageviews'+ t={t}+ total={overall?.thisWeek}+ percChange={overall?.percChange}+ />+ )}+ {!captcha && (+ <MiniCard+ labelTKey='dashboard.liveVisitors'+ t={t}+ total={live}+ />+ )}+ </div>+ </div>+ {!confirmed && (+ <Modal+ onClose={() => { setShowInviteModal(false) }}+ onSubmit={() => { setShowInviteModal(false); onAccept() }}+ submitText={t('common.accept')}+ type='confirmed'+ closeText={t('common.cancel')}+ title={t('dashboard.invitationFor', { project: name })}+ message={t('dashboard.invitationDesc', { project: name })}+ isOpened={showInviteModal}+ />+ )}+ </li>+ </div>+ )+}++ProjectCard.defaultProps = {+ isPublic: false,+ overall: {+ percChange: 0,+ total: 0,+ thisWeek: 0,+ },+ active: false,+ shared: false,+ captcha: false,+ confirmed: false,+ name: '',+ live: 'N/A',+ isTransferring: false,+ getRole: () => '',+}++interface INoProjects {+ t: (key: string) => string+ onClick: () => void+}++const NoProjects = ({ t, onClick }: INoProjects): JSX.Element => (+ <button+ type='button'+ onClick={onClick}+ className='mx-auto relative block max-w-lg rounded-lg border-2 border-dashed border-gray-300 p-12 text-center hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2'+ >+ <FolderPlusIcon className='mx-auto h-12 w-12 text-gray-400 dark:text-gray-200' />+ <span className='mt-2 block text-sm font-semibold text-gray-900 dark:text-gray-50'>+ {t('dashboard.createProject')}+ </span>+ </button>+)++const AddProject = ({ t, onClick }: INoProjects): JSX.Element => (+ <li onClick={onClick} className='flex cursor-pointer justify-center items-center rounded-lg border-2 border-dashed h-auto min-h-[149.1px] group border-gray-300 hover:border-gray-400'>+ <div>+ <FolderPlusIcon className='mx-auto h-12 w-12 text-gray-400 dark:text-gray-200 group-hover:text-gray-500 group-hover:dark:text-gray-400' />+ <span className='mt-2 block text-sm font-semibold text-gray-900 dark:text-gray-50 group-hover:dark:text-gray-400'>+ {t('dashboard.newProject')}+ </span>+ </div>+ </li>+)++interface DashboardProps {+ projects: IProject[]+ isLoading: boolean+ error: string+ user: IUser+ deleteProjectFailed: (error: string) => void+ setProjectsShareData: (data: Partial<ISharedProject>) => void+ setUserShareData: (data: Partial<ISharedProject>) => void+ userSharedUpdate: (message: string) => void+ sharedProjectError: (error: string) => void+ loadProjects: (take: number, skip: number) => void+ loadSharedProjects: (take: number, skip: number) => void+ total: number+ setDashboardPaginationPage: (page: number) => void+ dashboardPaginationPage: number+ sharedProjects: ISharedProject[]+ dashboardTabs: string+ setDashboardTabs: (tab: string) => void+ sharedTotal: number+ setDashboardPaginationPageShared: (page: number) => void+ dashboardPaginationPageShared: number+ captchaProjects: ICaptchaProject[]+ captchaTotal: number+ dashboardPaginationPageCaptcha: number+ setDashboardPaginationPageCaptcha: (page: number) => void+ loadProjectsCaptcha: (take: number, skip: number) => void+ projectTab: string+ liveStats: ILiveStats+}++const Dashboard = ({+ projects, isLoading, error, user, deleteProjectFailed, setProjectsShareData,+ setUserShareData, userSharedUpdate, sharedProjectError, loadProjects, loadSharedProjects,+ total, setDashboardPaginationPage, dashboardPaginationPage, sharedProjects, dashboardTabs,+ setDashboardTabs, sharedTotal, setDashboardPaginationPageShared, dashboardPaginationPageShared, captchaProjects, captchaTotal, dashboardPaginationPageCaptcha, setDashboardPaginationPageCaptcha,+ loadProjectsCaptcha, projectTab, liveStats,+}: DashboardProps): JSX.Element => {+ const { t }: {+ t: (key: string, options?: {+ [key: string]: string | number | null | undefined+ }) => string+ } = useTranslation('common')+ const [showActivateEmailModal, setShowActivateEmailModal] = useState<boolean>(false)+ const history = useHistory()+ const [tabProjects, setTabProjects] = useState<string>(dashboardTabs)+ const pageAmountShared: number = Math.ceil(sharedTotal / ENTRIES_PER_PAGE_DASHBOARD)+ const pageAmount: number = Math.ceil(total / ENTRIES_PER_PAGE_DASHBOARD)+ const pageAmountCaptcha: number = Math.ceil(captchaTotal / ENTRIES_PER_PAGE_DASHBOARD)+ const getRole = (pid: string): string | null => (_find([..._map(sharedProjects, (item) => ({ ...item.project, role: item.role }))], p => p.id === pid)?.role || null)++ const onNewProject = () => {+ if (user.isActive || isSelfhosted) {+ if (dashboardTabs === tabForCaptchaProject) {+ history.push(routes.new_captcha)+ } else {+ history.push(routes.new_project)+ }+ } else {+ setShowActivateEmailModal(true)+ }+ }++ useEffect(() => {+ if (sharedTotal <= 0 && tabProjects === tabForSharedProject) {+ setDashboardTabs(tabForOwnedProject)+ setTabProjects(tabForOwnedProject)+ }++ setDashboardTabs(tabProjects)+ }, [tabProjects, setDashboardTabs, sharedTotal])++ useEffect(() => {+ if (tabProjects === tabForOwnedProject) {+ loadProjects(ENTRIES_PER_PAGE_DASHBOARD, (dashboardPaginationPage - 1) * ENTRIES_PER_PAGE_DASHBOARD)+ }+ if (tabProjects === tabForSharedProject) {+ loadSharedProjects(ENTRIES_PER_PAGE_DASHBOARD, (dashboardPaginationPageShared - 1) * ENTRIES_PER_PAGE_DASHBOARD)+ }+ if (tabProjects === tabForCaptchaProject) {+ loadProjectsCaptcha(ENTRIES_PER_PAGE_DASHBOARD, (dashboardPaginationPageCaptcha - 1) * ENTRIES_PER_PAGE_DASHBOARD)+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [dashboardPaginationPage, dashboardPaginationPageShared])++ const dashboardLocTabs = useMemo(() => {+ return [+ {+ id: DASHBOARD_TABS.owned,+ name: tabForOwnedProject,+ label: t('profileSettings.owned'),+ },+ {+ id: DASHBOARD_TABS.shared,+ name: tabForSharedProject,+ label: t('profileSettings.shared'),+ },+ {+ id: DASHBOARD_TABS.captcha,+ name: tabForCaptchaProject,+ label: t('profileSettings.captcha'),+ },+ ]+ }, [t])++ const activeTabLabel = useMemo(() => {+ return _find(dashboardLocTabs, (tab) => tab.name === tabProjects)?.label+ }, [dashboardLocTabs, tabProjects])++ if (error && !isLoading) {+ return (+ <Title title={t('titles.dashboard')}>+ <div className='flex justify-center pt-10'>+ <div className='rounded-md bg-red-50 p-4 w-11/12 lg:w-4/6'>+ <div className='flex'>+ <div className='flex-shrink-0'>+ <XCircleIcon className='h-5 w-5 text-red-400' aria-hidden='true' />+ </div>+ <div className='ml-3'>+ <h3 className='text-sm font-medium text-red-800'>{error}</h3>+ </div>+ </div>+ </div>+ </div>+ </Title>+ )+ }++ return (+ <Title title={t('titles.dashboard')}>+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>+ <EventsRunningOutBanner />+ <div className='flex flex-col py-6 px-4 sm:px-6 lg:px-8'>+ <div className='max-w-7xl w-full mx-auto'>+ <div className='flex justify-between mb-6'>+ <h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>+ {t('titles.dashboard')}+ </h2>+ <span+ onClick={onNewProject}+ className='!pl-2 inline-flex justify-center items-center cursor-pointer text-center border border-transparent leading-4 font-medium rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-500 shadow-sm text-white bg-slate-900 hover:bg-slate-700 dark:text-gray-50 dark:border-gray-800 dark:bg-slate-800 dark:hover:bg-slate-700 px-3 py-2 text-sm'+ >+ <FolderPlusIcon className='w-5 h-5 mr-1' />+ {tabProjects === tabForCaptchaProject ? t('dashboard.newCaptchaProject') : t('dashboard.newProject')}+ </span>+ </div>+ {!isSelfhosted && (+ <div className='mb-2'>+ {/* Dashboard tabs selector */}+ <div>+ <div className='sm:hidden mb-2'>+ <Select+ items={dashboardLocTabs}+ keyExtractor={(item) => item.id}+ labelExtractor={(item) => item.label}+ onSelect={(label) => {+ const nameTab = _find(dashboardLocTabs, (tab) => t(tab.label) === label)?.name+ if (nameTab) {+ setTabProjects(nameTab)+ }+ }}+ title={activeTabLabel}+ />+ </div>+ <div className='hidden sm:block'>+ <nav className='-mb-px flex space-x-8'>+ {_map(tabsForDashboard, (tab) => {+ if (tab.name === tabForSharedProject && sharedTotal <= 0) {+ return null+ }++ return (+ <button+ key={tab.name}+ type='button'+ onClick={() => setTabProjects(tab.name)}+ className={cx('whitespace-nowrap pb-4 px-1 border-b-2 font-medium text-md', {+ 'border-slate-900 text-slate-900 dark:text-gray-50 dark:border-gray-50': tabProjects === tab.name,+ 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300 dark:hover:border-gray-300': tabProjects !== tab.name,+ })}+ aria-current={tab.name === tabProjects ? 'page' : undefined}+ >+ {t(tab.label)}+ </button>+ )+ })}+ </nav>+ </div>+ </div>+ </div>+ )}+ {isLoading ? (+ <Title title={t('titles.dashboard')}>+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>+ <Loader />+ </div>+ </Title>+ ) : (+ <>+ {tabProjects === tabForOwnedProject && (+ <div>+ {_isEmpty(_filter(projects, ({ uiHidden }) => !uiHidden)) ? (+ <NoProjects t={t} onClick={onNewProject} />+ ) : (+ <ul className='grid grid-cols-1 gap-x-6 gap-y-3 lg:gap-y-6 lg:grid-cols-3'>+ {_map(_filter(projects, ({ uiHidden }) => !uiHidden), ({+ name, id, active, overall, public: isPublic, isTransferring,+ }) => (+ <ProjectCard+ key={id}+ id={id}+ type='analytics'+ t={t}+ name={name}+ active={active}+ isPublic={isPublic}+ overall={overall}+ live={_isNumber(liveStats[id]) ? liveStats[id] : 'N/A'}+ setUserShareData={() => { }}+ deleteProjectFailed={() => { }}+ userSharedUpdate={() => { }}+ sharedProjects={[]}+ setProjectsShareData={() => { }}+ sharedProjectError={() => { }}+ isTransferring={isTransferring}+ confirmed+ />+ ))}+ <AddProject t={t} onClick={onNewProject} />+ </ul>+ )}+ </div>+ )}++ {tabProjects === tabForCaptchaProject && (+ <div>+ {_isEmpty(_filter(captchaProjects, ({ uiHidden }) => !uiHidden)) ? (+ <NoProjects t={t} onClick={onNewProject} />+ ) : (+ <ul className='grid grid-cols-1 gap-x-6 gap-y-3 lg:gap-y-6 lg:grid-cols-3'>+ {_map(_filter(captchaProjects, ({ uiHidden }) => !uiHidden), ({+ name, id, active, overall, public: isPublic,+ }) => (+ <ProjectCard+ t={t}+ key={id}+ id={id}+ type='captcha'+ name={name}+ captcha+ active={active}+ isPublic={isPublic}+ overall={overall}+ live={_isNumber(liveStats[id]) ? liveStats[id] : 'N/A'}+ deleteProjectFailed={() => { }}+ sharedProjects={[]}+ setProjectsShareData={() => { }}+ setUserShareData={() => { }}+ userSharedUpdate={() => { }}+ sharedProjectError={() => { }}+ confirmed+ />+ ))}+ <AddProject t={t} onClick={onNewProject} />+ </ul>+ )}+ </div>+ )}++ {tabProjects === tabForSharedProject && (+ <div>+ {_isEmpty(_filter(sharedProjects, ({ uiHidden }) => !uiHidden)) ? (+ <NoProjects t={t} onClick={onNewProject} />+ ) : (+ <ul className='grid grid-cols-1 gap-x-6 gap-y-3 lg:gap-y-6 lg:grid-cols-3'>+ {_map(_filter(sharedProjects, ({ uiHidden }) => !uiHidden), ({+ project, confirmed,+ }) => {+ if (_isUndefined(confirmed) || confirmed) {+ return (+ <ProjectCard+ t={t}+ key={confirmed ? `${project?.id}-confirmed` : project?.id}+ type='analytics'+ id={project?.id}+ name={project?.name}+ shared+ getRole={getRole}+ active={project?.active}+ isPublic={project?.public}+ confirmed={confirmed}+ overall={project?.overall}+ live={_isNumber(liveStats[project.id]) ? liveStats[project.id] : 'N/A'}+ setUserShareData={() => { }}+ deleteProjectFailed={() => { }}+ sharedProjects={[]}+ setProjectsShareData={() => { }}+ userSharedUpdate={() => { }}+ sharedProjectError={() => { }}+ />+ )+ }++ return (+ <ProjectCard+ t={t}+ key={confirmed ? `${project?.id}-confirmed` : project?.id}+ id={project?.id}+ type='analytics'+ name={project?.name}+ shared+ getRole={getRole}+ active={project?.active}+ isPublic={project?.public}+ overall={project?.overall}+ confirmed={confirmed}+ sharedProjects={user.sharedProjects}+ setProjectsShareData={setProjectsShareData}+ setUserShareData={setUserShareData}+ live={_isNumber(liveStats[project.id]) ? liveStats[project.id] : 'N/A'}+ userSharedUpdate={userSharedUpdate}+ sharedProjectError={sharedProjectError}+ deleteProjectFailed={deleteProjectFailed}+ />+ )+ })}+ </ul>+ )}+ </div>+ )}+ </>+ )}+ {(tabProjects === tabForOwnedProject && pageAmount > 1) && (+ <Pagination className='mt-2' page={dashboardPaginationPage} pageAmount={pageAmount} setPage={setDashboardPaginationPage} total={total} />+ )}+ {(tabProjects === tabForSharedProject && pageAmountShared > 1) && (+ <Pagination className='mt-2' page={dashboardPaginationPageShared} pageAmount={pageAmountShared} setPage={setDashboardPaginationPageShared} total={sharedTotal} />+ )}+ {(tabProjects === tabForCaptchaProject && pageAmountCaptcha > 1) && (+ <Pagination className='mt-2' page={dashboardPaginationPageCaptcha} pageAmount={pageAmountCaptcha} setPage={setDashboardPaginationPageCaptcha} total={captchaTotal} />+ )}+ </div>+ </div>+ </div>+ <Modal+ onClose={() => setShowActivateEmailModal(false)}+ onSubmit={() => setShowActivateEmailModal(false)}+ submitText={t('common.gotIt')}+ title={t('dashboard.verifyEmailTitle')}+ type='info'+ message={t('dashboard.verifyEmailDesc')}+ isOpened={showActivateEmailModal}+ />+ </Title>+ )+}++Dashboard.propTypes = {+ projects: PropTypes.arrayOf(PropTypes.object).isRequired,+ sharedProjects: PropTypes.arrayOf(PropTypes.object).isRequired,+ user: PropTypes.object.isRequired,+ isLoading: PropTypes.bool.isRequired,+ error: PropTypes.string,+ deleteProjectFailed: PropTypes.func.isRequired,+ setProjectsShareData: PropTypes.func.isRequired,+ setUserShareData: PropTypes.func.isRequired,+ sharedProjectError: PropTypes.func.isRequired,+ userSharedUpdate: PropTypes.func.isRequired,+ loadProjects: PropTypes.func.isRequired,+ total: PropTypes.number.isRequired,+ setDashboardPaginationPage: PropTypes.func.isRequired,+ setDashboardPaginationPageShared: PropTypes.func.isRequired,+ dashboardPaginationPage: PropTypes.number.isRequired,+ dashboardPaginationPageShared: PropTypes.number.isRequired,+ dashboardTabs: PropTypes.string.isRequired,+ setDashboardTabs: PropTypes.func.isRequired,+ sharedTotal: PropTypes.number.isRequired,+}++Dashboard.defaultProps = {+ error: '',+}++export default memo(withAuthentication(Dashboard, auth.authenticated))diff --git a/app/pages/Dashboard/index.tsx b/app/pages/Dashboard/index.tsxnew file mode 100644index 000000000..52cf8f17a--- /dev/null+++ b/app/pages/Dashboard/index.tsx@@ -0,0 +1,3 @@+import Dashboard from './Dashboard.container'++export default Dashboarddiff --git a/app/pages/Features/index.tsx b/app/pages/Features/index.tsxnew file mode 100644index 000000000..042e05502--- /dev/null+++ b/app/pages/Features/index.tsx@@ -0,0 +1,97 @@+/* eslint-disable jsx-a11y/anchor-has-content */+import React, { Fragment } from 'react'+import { Link } from 'react-router-dom'+import { useTranslation, Trans } from 'react-i18next'+import _map from 'lodash/map'++import Title from 'components/Title'+import {+ CHROME_EXTENSION_URL, FIREFOX_ADDON_URL, DOCS_URL,+} from 'redux/constants'+import routes from 'routes'++const Features = (): JSX.Element => {+ const { t }: {+ t: (key: string, options?: {+ [key: string]: string | number | boolean | undefined+ }) => string+ } = useTranslation('common')++ return (+ <Title title={t('titles.features')}>+ <div className='bg-gray-50 dark:bg-slate-900'>+ <div className='w-11/12 md:w-4/5 mx-auto pb-16 pt-12 px-4 sm:px-6 lg:px-8 whitespace-pre-line'>+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('titles.features')}+ </h1>++ <h3 className='text-2xl font-normal text-gray-900 dark:text-gray-50 tracking-tight mt-4'>+ {t('features.feature1Name')}+ </h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='features.feature1Content'+ components={{+ docs: <a className='text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' href={`${DOCS_URL}/swetrix-js-reference#trackviews`} target='_blank' rel='noreferrer noopener' />,+ gh: <a className='text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' href='https://github.com/Swetrix' target='_blank' rel='noopener noreferrer' />,+ }}+ />+ </p>++ <h3 className='text-2xl font-normal text-gray-900 dark:text-gray-50 tracking-tight mt-4'>+ {t('features.feature2Name')}+ </h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='features.feature2Content'+ components={{+ firefox: <a className='text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' href={FIREFOX_ADDON_URL} target='_blank' rel='noopener noreferrer' aria-label='Firefox Addon (opens in a new tab)' />,+ chrome: <a className='text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' href={CHROME_EXTENSION_URL} target='_blank' rel='noopener noreferrer' aria-label='Chrome Extension (opens in a new tab)' />,+ }}+ />+ </p>+ {_map(t('features.list', { returnObjects: true }), (feature: {+ name: string+ content: string+ }) => (+ <Fragment key={feature.name}>+ <h3 className='text-2xl font-normal text-gray-900 dark:text-gray-50 tracking-tight mt-4'>+ {feature.name}+ </h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ {feature.content}+ </p>+ </Fragment>+ ))}+ </div>+ </div>+ <div className='bg-indigo-600 dark:bg-slate-800'>+ <div className='w-4/5 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 dark:text-gray-50'>+ <span className='block text-white'>+ {t('features.ready')}+ </span>+ <span className='block text-gray-300'>+ {t('features.start')}+ </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 dark:text-slate-800'+ aria-label={t('titles.signup')}+ >+ {t('common.getStarted')}+ </Link>+ </div>+ </div>+ </div>+ </Title>+ )+}++export default Featuresdiff --git a/app/pages/MainPage/Pricing.tsx b/app/pages/MainPage/Pricing.tsxnew file mode 100644index 000000000..d48122cbc--- /dev/null+++ b/app/pages/MainPage/Pricing.tsx@@ -0,0 +1,490 @@+/* eslint-disable no-confusing-arrow */+import React, { memo, useState, useEffect } from 'react'+import { useSelector, useDispatch } from 'react-redux'+import { Link } from 'react-router-dom'+import { CheckIcon } from '@heroicons/react/24/solid'+import _map from 'lodash/map'+import _isNil from 'lodash/isNil'+import _findIndex from 'lodash/findIndex'+import _isEmpty from 'lodash/isEmpty'+import { Trans } from 'react-i18next'+import cx from 'clsx'++import Modal from 'ui/Modal'+import Spin from 'ui/icons/Spin'+import {+ CONTACT_EMAIL, paddleLanguageMapping, PLAN_LIMITS, CURRENCIES,+} from 'redux/constants'+import { errorsActions } from 'redux/reducers/errors'+import { alertsActions } from 'redux/reducers/alerts'+import { authActions } from 'redux/reducers/auth'+import sagaActions from 'redux/sagas/actions'+import { authMe } from 'api'+import routes from 'routes'+import { IUser } from 'redux/models/IUser'+import { AppDispatch, StateType } from 'redux/store'++type CurrencyCode = 'USD' | 'EUR' | 'GBP'++const getNonStandardTiers = (t: (key: string, options?: {+ [key: string]: any+}) => string, currencyCode: CurrencyCode) => ({+ free: {+ name: t('pricing.free'),+ planCode: 'free',+ priceMonthly: PLAN_LIMITS.free.price[currencyCode].monthly,+ priceYearly: PLAN_LIMITS.free.price[currencyCode].yearly,+ legacy: PLAN_LIMITS.free.legacy,+ includedFeatures: [+ t('pricing.tiers.upToXVMo', { amount: PLAN_LIMITS.free.monthlyUsageLimit.toLocaleString() }),+ t('pricing.tiers.upToXWebsites', { amount: PLAN_LIMITS.free.maxProjects }),+ // t('pricing.tiers.xMoDataRetention', { amount: 3 }),+ t('pricing.tiers.xAlertsSingular', { amount: PLAN_LIMITS.free.maxAlerts }),+ t('pricing.tiers.userFlowAnalysis'),+ t('pricing.tiers.dataExports'),+ t('pricing.tiers.dataOwnership'),+ t('main.competitiveFeatures.perf'),+ t('pricing.tiers.dashboards'),+ t('pricing.tiers.reports'),+ ],+ },+ trial: {+ name: t('pricing.tiers.trial'),+ planCode: 'trial',+ priceMonthly: PLAN_LIMITS.trial.price[currencyCode].monthly,+ priceYearly: PLAN_LIMITS.trial.price[currencyCode].yearly,+ legacy: PLAN_LIMITS.trial.legacy,+ includedFeatures: [+ t('pricing.tiers.evXPlanIncl', { plan: t('pricing.tiers.freelancer') }),+ ],+ },+})++const getTiers = (t: (key: string, options?: {+ [key: string]: any+}) => string, currencyCode: CurrencyCode) => [+ {+ name: t('pricing.tiers.hobby'),+ planCode: 'hobby',+ priceMonthly: PLAN_LIMITS.hobby.price[currencyCode].monthly,+ priceYearly: PLAN_LIMITS.hobby.price[currencyCode].yearly,+ includedFeatures: [+ t('pricing.tiers.upToXVMo', { amount: PLAN_LIMITS.hobby.monthlyUsageLimit.toLocaleString() }),+ t('pricing.tiers.upToXWebsites', { amount: PLAN_LIMITS.hobby.maxProjects }),+ // t('pricing.tiers.xMoDataRetention', { amount: 3 }),+ t('pricing.tiers.xAlertsPlural', { amount: PLAN_LIMITS.hobby.maxAlerts }),+ t('pricing.tiers.userFlowAnalysis'),+ t('pricing.tiers.dataExports'),+ t('pricing.tiers.dataOwnership'),+ t('main.competitiveFeatures.perf'),+ t('pricing.tiers.dashboards'),+ t('pricing.tiers.reports'),+ ],+ pid: '813694', // Plan ID+ ypid: '813695', // Plan ID - Yearly billing+ },+ {+ name: t('pricing.tiers.freelancer'),+ planCode: 'freelancer',+ priceMonthly: PLAN_LIMITS.freelancer.price[currencyCode].monthly,+ priceYearly: PLAN_LIMITS.freelancer.price[currencyCode].yearly,+ includedFeatures: [+ t('pricing.tiers.evXPlanIncl', { plan: t('pricing.tiers.hobby') }),+ t('pricing.tiers.xVMo', { amount: PLAN_LIMITS.freelancer.monthlyUsageLimit.toLocaleString() }),+ t('pricing.tiers.upToXWebsites', { amount: PLAN_LIMITS.freelancer.maxProjects }),+ t('pricing.tiers.xAlertsPlural', { amount: PLAN_LIMITS.freelancer.maxAlerts }),+ // t('pricing.tiers.xMoDataRetention', { amount: 12 }),+ // t('pricing.tiers.smallBusiSupport'),+ ],+ pid: 752316, // Plan ID+ ypid: 776469, // Plan ID - Yearly billing+ },+ {+ name: t('pricing.tiers.startup'),+ planCode: 'startup',+ priceMonthly: PLAN_LIMITS.startup.price[currencyCode].monthly,+ priceYearly: PLAN_LIMITS.startup.price[currencyCode].yearly,+ includedFeatures: [+ t('pricing.tiers.evXPlanIncl', { plan: t('pricing.tiers.freelancer') }),+ t('pricing.tiers.xVMo', { amount: PLAN_LIMITS.startup.monthlyUsageLimit.toLocaleString() }),+ t('pricing.tiers.xAlertsPlural', { amount: PLAN_LIMITS.startup.maxAlerts }),+ // t('pricing.tiers.xMoDataRetention', { amount: 12 }),+ ],+ pid: 752317,+ ypid: 776470,+ mostPopular: true,+ },+ {+ name: t('pricing.tiers.enterprise'),+ planCode: 'enterprise',+ priceMonthly: PLAN_LIMITS.enterprise.price[currencyCode].monthly,+ priceYearly: PLAN_LIMITS.enterprise.price[currencyCode].yearly,+ includedFeatures: [+ t('pricing.tiers.evXPlanIncl', { plan: t('pricing.tiers.startup') }),+ t('pricing.tiers.xVMo', { amount: PLAN_LIMITS.enterprise.monthlyUsageLimit.toLocaleString() }),+ t('pricing.tiers.upToXWebsites', { amount: PLAN_LIMITS.enterprise.maxProjects }),+ t('pricing.tiers.xAlertsPlural', { amount: PLAN_LIMITS.enterprise.maxAlerts }),+ // t('pricing.tiers.xMoDataRetention', { amount: 24 }),+ ],+ pid: 752318,+ ypid: 776471,+ },+]++const BillingFrequency = {+ monthly: 'monthly',+ yearly: 'yearly',+}++interface IPricingItem {+ tier: any+ user: IUser+ t: (key: string, options?: {+ [key: string]: any+ }) => string+ authenticated: boolean+ billingFrequency: string+ onPlanChange: (planCode: {+ planCode: string,+ name: string,+ pid: string,+ ypid: string,+ }) => void+ downgradeHandler: (item: any) => void+ downgrade: boolean+ planCodeLoading: boolean | string | null+ planCodeID: string | number+ userPlancodeID: string | number+ currencyCode: CurrencyCode+}++const PricingItem = ({+ tier, user, t, authenticated, billingFrequency, onPlanChange, downgradeHandler, downgrade,+ planCodeLoading, planCodeID, userPlancodeID, currencyCode,+}: IPricingItem) => {+ let action++ const currency = CURRENCIES[currencyCode]++ if (planCodeID > userPlancodeID) {+ action = t('pricing.upgrade')+ } else if (downgrade) {+ action = t('pricing.downgrade')+ } else if (user.billingFrequency === billingFrequency || user.planCode === 'free' || user.planCode === 'trial') {+ action = t('pricing.yourPlan')+ } else if (billingFrequency === BillingFrequency.monthly) {+ action = t('pricing.switchToMonthly')+ } else {+ action = t('pricing.switchToYearly')+ }++ return (+ <div+ key={tier.name}+ className={cx('relative border rounded-2xl shadow-sm divide-y bg-[#F5F5F5] dark:bg-slate-800/20 dark:border dark:border-slate-800 divide-gray-200 dark:divide-slate-700', {+ 'border-indigo-400': user.planCode === tier.planCode,+ 'border-gray-200 dark:border-gray-500': user.planCode !== tier.planCode,+ })}+ >+ {user.planCode === tier.planCode && (+ <div className='absolute inset-x-0 top-0 transform translate-y-px'>+ <div className='flex justify-center transform -translate-y-1/2'>+ <span className='inline-flex rounded-full bg-indigo-600 px-4 py-1 text-sm font-semibold tracking-wider uppercase text-white'>+ {t('pricing.currentPlan')}+ </span>+ </div>+ </div>+ )}+ <div className='p-6 border-none'>+ <h2 className='text-lg leading-6 font-semibold text-[#4D4D4D] dark:text-gray-50 text-center'>{tier.name}</h2>+ {tier.mostPopular && !authenticated && (+ <p className='absolute top-0 py-1.5 px-4 bg-indigo-600 dark:bg-indigo-700 rounded-full text-xs font-semibold uppercase tracking-wide text-white transform -translate-y-1/2'>+ {t('pricing.mostPopular')}+ </p>+ )}+ {tier.legacy && (+ <p className='absolute top-0 left-2 py-1 px-2 bg-yellow-500 rounded-full text-xs font-semibold uppercase tracking-wide text-white transform translate-y-4'>+ {t('pricing.legacy')}+ </p>+ )}+ <p className='mt-4 text-center'>+ <span className='text-4xl font-bold text-[#4D4D4D] dark:text-gray-50'>+ {currency.symbol}+ {billingFrequency === BillingFrequency.monthly ? tier.priceMonthly : tier.priceYearly}+ </span>+ + <span className='text-base font-medium text-gray-500 dark:text-gray-400'>+ /+ {t(billingFrequency === BillingFrequency.monthly ? 'pricing.perMonth' : 'pricing.perYear')}+ </span>+ </p>+ {authenticated ? (+ <span+ onClick={() => downgrade ? downgradeHandler(tier) : onPlanChange(tier)}+ className={cx('inline-flex items-center justify-center mt-8 w-full rounded-md py-2 text-sm font-semibold text-white text-center select-none', {+ 'bg-indigo-600 hover:bg-indigo-700 dark:bg-indigo-700 hover:dark:bg-indigo-800 cursor-pointer': planCodeLoading === null && (tier.planCode !== user.planCode || (user.billingFrequency !== billingFrequency && user.planCode !== 'free')),+ 'bg-indigo-400 cursor-default': planCodeLoading !== null || (tier.planCode === user.planCode && (user.billingFrequency === billingFrequency || user.planCode === 'free' || user.planCode === 'trial')),+ })}+ >+ {planCodeLoading === tier.planCode && (+ <Spin />+ )}+ {action}+ </span>+ ) : (+ <Link+ className='mt-8 block w-full bg-indigo-600 dark:bg-indigo-700 hover:dark:bg-indigo-800 rounded-md py-2 text-sm font-semibold text-white text-center hover:bg-indigo-700'+ to={routes.signup}+ aria-label={t('titles.signup')}+ >+ {t('common.getStarted')}+ </Link>+ )}+ </div>+ <div className='px-6 border-none'>+ <hr className='w-full mx-auto border border-gray-300 dark:border-slate-800' />+ </div>+ <div className='pt-6 pb-8 px-6 border-none'>+ <h3 className='text-xs font-medium text-gray-900 dark:text-gray-50 tracking-wide uppercase'>+ {t('pricing.whatIncl')}+ </h3>+ <ul className='mt-6 space-y-4'>+ {_map(tier.includedFeatures, (feature) => (+ <li key={feature} className='flex space-x-3'>+ <CheckIcon className='flex-shrink-0 h-5 w-5 text-green-500' aria-hidden='true' />+ <span className='text-sm text-gray-500 dark:text-gray-200'>{feature}</span>+ </li>+ ))}+ </ul>+ </div>+ </div>+ )+}++interface IPricing {+ t: (key: string) => string,+ language: string,+}++const Pricing = ({ t, language }: IPricing) => {+ const dispatch: AppDispatch = useDispatch()+ const { authenticated, user } = useSelector((state: StateType) => state.auth)+ const { theme } = useSelector((state: StateType) => state.ui.theme)+ const { paddle, metainfo } = useSelector((state: StateType) => state.ui.misc)+ const { lastEvent } = paddle+ const currencyCode = user?.tierCurrency || metainfo.code++ const [planCodeLoading, setPlanCodeLoading] = useState<string | null>(null)+ const [downgradeTo, setDowngradeTo] = useState<{+ planCode: string,+ name: string,+ pid: string,+ ypid: string,+ } | null>(null)+ const [showDowngradeModal, setShowDowngradeModal] = useState<boolean>(false)+ const [billingFrequency, setBillingFrequency] = useState(user?.billingFrequency || BillingFrequency.monthly)+ const tiers = getTiers(t, currencyCode)+ const nonStandardTiers: {+ [key: string]: {+ [key: string]: any,+ },+ } = getNonStandardTiers(t, currencyCode)+ const isNonStandardTier = authenticated && !_isEmpty(nonStandardTiers[user.planCode])++ useEffect(() => {+ const lastEventHandler = async (data: {+ event: string,+ }) => {+ if (_isNil(data)) {+ return+ }++ if (data.event === 'Checkout.Complete') {+ // giving some time to the API to process tier upgrate via Paddle webhook+ setTimeout(async () => {+ try {+ const me = await authMe()++ dispatch(authActions.loginSuccessful(me))+ dispatch(authActions.finishLoading())+ } catch (e) {+ dispatch(authActions.logout())+ dispatch(sagaActions.logout(false))+ }++ dispatch(alertsActions.accountUpdated({+ message: t('apiNotifications.subscriptionUpdated'),+ }))+ }, 3000)+ setPlanCodeLoading(null)+ setDowngradeTo(null)+ } else if (data.event === 'Checkout.Close') {+ setPlanCodeLoading(null)+ setDowngradeTo(null)+ }+ }++ lastEventHandler(lastEvent)+ }, [lastEvent, dispatch, t])++ const onPlanChange = (tier: {+ planCode: string,+ name: string,+ pid: string,+ ypid: string,+ }) => {+ if (planCodeLoading === null && (user.planCode !== tier.planCode || (user.billingFrequency !== billingFrequency && user.planCode !== 'free' && user.planCode !== 'trial'))) {+ setPlanCodeLoading(tier.planCode)++ // @ts-ignore+ if (!window.Paddle) {+ dispatch(errorsActions.genericError({+ message: 'Payment script has not yet loaded! Please, try again.',+ }))+ setPlanCodeLoading(null)+ return+ }++ // @ts-ignore+ window.Paddle.Checkout.open({+ product: billingFrequency === BillingFrequency.monthly ? tier.pid : tier.ypid,+ email: user.email,+ passthrough: JSON.stringify({+ uid: user.id,+ }),+ locale: paddleLanguageMapping[language] || language,+ title: tier.name,+ displayModeTheme: theme,+ country: metainfo.country,+ })+ }+ }++ const downgradeHandler = (tier: {+ planCode: string,+ name: string,+ pid: string,+ ypid: string,+ }) => {+ if (planCodeLoading === null && user.planCode !== tier.planCode) {+ setDowngradeTo(tier)+ setShowDowngradeModal(true)+ }+ }++ const userPlancodeID = _findIndex(tiers, (el) => el.planCode === user.planCode)++ return (+ <>+ <div id='pricing' className={cx({ 'bg-white dark:bg-slate-900/75': !authenticated })}>+ <div className={cx('w-11/12 max-w-7xl mx-auto whitespace-pre-line', { 'px-4 sm:px-6 lg:px-8 py-24': !authenticated })}>+ <div className='sm:flex sm:flex-col sm:align-center'>+ {!authenticated && (+ <>+ <h1 className='text-3xl font-extrabold text-gray-900 dark:text-gray-50 sm:text-center'>+ {t('pricing.title')}+ </h1>+ <p className='mt-5 text-xl text-gray-500 dark:text-gray-200 sm:text-center'>+ {t('pricing.adv')}+ </p>+ </>+ )}+ <div className='relative self-center mt-6 bg-gray-100 dark:bg-slate-800 rounded-lg p-0.5 flex sm:mt-8 xs:flex-row flex-col'>+ <button+ type='button'+ onClick={() => setBillingFrequency(BillingFrequency.monthly)}+ className={cx('relative xs:w-1/2 rounded-md shadow-sm py-2 text-sm font-medium whitespace-nowrap sm:w-auto sm:px-8', {+ 'bg-white border-gray-200 text-gray-900 dark:bg-slate-900 dark:border-gray-800 dark:text-gray-50': billingFrequency === BillingFrequency.monthly,+ 'text-gray-700 dark:text-gray-100': billingFrequency === BillingFrequency.yearly,+ })}+ >+ {t('pricing.monthlyBilling')}+ </button>+ <button+ type='button'+ onClick={() => setBillingFrequency(BillingFrequency.yearly)}+ className={cx('ml-0.5 relative xs:w-1/2 border border-transparent rounded-md py-2 text-sm font-medium whitespace-nowrap sm:w-auto sm:px-8', {+ 'text-gray-700 dark:text-gray-100': billingFrequency === BillingFrequency.monthly,+ 'bg-white border-gray-200 text-gray-900 dark:bg-slate-900 dark:border-gray-800 dark:text-gray-50': billingFrequency === BillingFrequency.yearly,+ })}+ >+ {t('pricing.yearlyBilling')}+ </button>+ </div>+ </div>+ <div className='mt-6 space-y-4 sm:mt-10 sm:space-y-0 sm:grid sm:grid-cols-2 sm:gap-6 lg:max-w-4xl lg:mx-auto xl:max-w-none xl:mx-0 xl:grid-cols-4'>+ {isNonStandardTier && (+ <PricingItem+ key={user.planCode}+ tier={nonStandardTiers[user.planCode]}+ user={user}+ t={t}+ billingFrequency={billingFrequency}+ onPlanChange={onPlanChange}+ downgrade={false}+ downgradeHandler={downgradeHandler}+ planCodeLoading={planCodeLoading}+ authenticated={authenticated}+ planCodeID={user.planCode}+ userPlancodeID={user.planCode}+ currencyCode={currencyCode}+ />+ )}+ {_map(tiers, (tier) => {+ const planCodeID = _findIndex(tiers, (el) => el.planCode === tier.planCode)+ const downgrade = planCodeID < userPlancodeID++ return (+ <PricingItem+ key={tier.planCode}+ tier={tier}+ user={user}+ t={t}+ billingFrequency={billingFrequency}+ onPlanChange={onPlanChange}+ downgrade={downgrade}+ downgradeHandler={downgradeHandler}+ planCodeLoading={planCodeLoading}+ authenticated={authenticated}+ planCodeID={planCodeID}+ userPlancodeID={userPlancodeID}+ currencyCode={currencyCode}+ />+ )+ })}+ </div>+ </div>+ <div className='checkout-container' id='checkout-container' />+ </div>+ <Modal+ onClose={() => {+ setDowngradeTo(null)+ setShowDowngradeModal(false)+ }}+ onSubmit={() => {+ setShowDowngradeModal(false)+ if (downgradeTo) {+ onPlanChange(downgradeTo)+ }+ }}+ submitText={t('common.yes')}+ closeText={t('common.no')}+ title={t('pricing.downgradeTitle')}+ type='warning'+ message={(+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='pricing.downgradeDesc'+ values={{+ email: CONTACT_EMAIL,+ }}+ />+ )}+ isOpened={showDowngradeModal}+ />+ </>+ )+}++export default memo(Pricing)diff --git a/app/pages/MainPage/index.tsx b/app/pages/MainPage/index.tsxnew file mode 100644index 000000000..e3e35cfd0--- /dev/null+++ b/app/pages/MainPage/index.tsx@@ -0,0 +1,858 @@+/* eslint-disable react/jsx-no-target-blank */+import React, { memo } from 'react'+import { Link } from 'react-router-dom'+import { useTranslation, Trans } from 'react-i18next'+import cx from 'clsx'+import { useSelector } from 'react-redux'+import {+ ArrowTopRightOnSquareIcon, ArrowSmallRightIcon, CheckCircleIcon, CheckIcon, XMarkIcon, ChevronRightIcon,+} from '@heroicons/react/24/solid'+import {+ CodeBracketIcon, PuzzlePieceIcon, ShareIcon, ArrowsPointingOutIcon, LightBulbIcon, ArrowTrendingUpIcon,+} from '@heroicons/react/20/solid'+import { TypeAnimation } from 'react-type-animation'+import _map from 'lodash/map'+import _reduce from 'lodash/reduce'+import _isEmpty from 'lodash/isEmpty'++import routes from 'routes'+import { nFormatterSeparated } from 'utils/generic'+import Title from 'components/Title'+import { GITHUB_URL, MARKETPLACE_URL, LIVE_DEMO_URL } from 'redux/constants'+import { StateType } from 'redux/store/index'+import BackgroundSvg from 'ui/icons/BackgroundSvg'+import Webflow from 'ui/icons/Webflow'+import NextJS from 'ui/icons/NextJS'+import NuxtJS from 'ui/icons/NuxtJS'+import Angular from 'ui/icons/Angular'+import ReactSVG from 'ui/icons/ReactSVG'+import Quote from 'ui/icons/Quote'+import Telegram from 'ui/icons/Telegram'+import Wordpress from 'ui/icons/Wordpress'+import Cloudflare from 'ui/icons/Cloudflare'+import Notion from 'ui/icons/Notion'+import Ghost from 'ui/icons/Ghost'+import Gatsby from 'ui/icons/Gatsby'+import Wix from 'ui/icons/Wix'++import Header from 'components/Header'+import SignUp from '../Auth/Signup/BasicSignup'+import Pricing from './Pricing'++import './styles.css'++const COMPETITORS_LIST = ['Google Analytics', 'Fathom', 'Plausible', 'Simple Analytics']+const SWETRIX_AND_COMPETITORS_LIST = ['Swetrix', ...COMPETITORS_LIST]+const COMPETITOR_SEQUENCE_DELAY = 5000 // in milliseconds+const processedList = _reduce(COMPETITORS_LIST, (acc: any[], curr: any) => {+ acc.push(curr)+ acc.push(COMPETITOR_SEQUENCE_DELAY)+ return acc+}, [])++// The order in the table is defined by the Swetrix object+const COMPETITOR_FEATURE_TABLE: {+ [key: string]: {+ [key: string]: boolean | null+ }+} = {+ Swetrix: {+ 'main.competitiveFeatures.gdpr': true, // GDPR-compatible+ 'main.competitiveFeatures.open': true, // Open-source+ 'main.competitiveFeatures.perf': true, // Performance+ 'main.competitiveFeatures.usfl': true, // User Flow+ 'main.competitiveFeatures.ext': true, // Custom extensions+ 'main.competitiveFeatures.alrt': true, // Custom alerts+ 'main.competitiveFeatures.pbld': true, // Public dashboards+ 'main.competitiveFeatures.shad': true, // Dashboard sharing+ 'main.competitiveFeatures.ckfree': true, // Has a free plan+ 'main.competitiveFeatures.api': true, // Has a free plan+ 'main.competitiveFeatures.2fa': true, // 2FA+ },+ 'Google Analytics': {+ 'main.competitiveFeatures.gdpr': false,+ 'main.competitiveFeatures.open': false,+ 'main.competitiveFeatures.perf': false,+ 'main.competitiveFeatures.usfl': true,+ 'main.competitiveFeatures.ext': false,+ 'main.competitiveFeatures.alrt': false,+ 'main.competitiveFeatures.pbld': false,+ 'main.competitiveFeatures.shad': false,+ 'main.competitiveFeatures.ckfree': false,+ 'main.competitiveFeatures.api': true,+ 'main.competitiveFeatures.2fa': true,+ },+ Fathom: {+ 'main.competitiveFeatures.gdpr': true,+ 'main.competitiveFeatures.open': null,+ 'main.competitiveFeatures.perf': false,+ 'main.competitiveFeatures.usfl': false,+ 'main.competitiveFeatures.ext': false,+ 'main.competitiveFeatures.alrt': true,+ 'main.competitiveFeatures.pbld': true,+ 'main.competitiveFeatures.shad': true,+ 'main.competitiveFeatures.ckfree': true,+ 'main.competitiveFeatures.api': true,+ 'main.competitiveFeatures.2fa': true,+ },+ Plausible: {+ 'main.competitiveFeatures.gdpr': true,+ 'main.competitiveFeatures.open': true,+ 'main.competitiveFeatures.perf': false,+ 'main.competitiveFeatures.usfl': false,+ 'main.competitiveFeatures.ext': false,+ 'main.competitiveFeatures.alrt': false,+ 'main.competitiveFeatures.pbld': true,+ 'main.competitiveFeatures.shad': true,+ 'main.competitiveFeatures.ckfree': true,+ 'main.competitiveFeatures.api': true,+ 'main.competitiveFeatures.2fa': false,+ },+ 'Simple Analytics': {+ 'main.competitiveFeatures.gdpr': true,+ 'main.competitiveFeatures.open': false,+ 'main.competitiveFeatures.perf': false,+ 'main.competitiveFeatures.usfl': false,+ 'main.competitiveFeatures.ext': false,+ 'main.competitiveFeatures.alrt': false,+ 'main.competitiveFeatures.pbld': true,+ 'main.competitiveFeatures.shad': false,+ 'main.competitiveFeatures.ckfree': true,+ 'main.competitiveFeatures.api': true,+ 'main.competitiveFeatures.2fa': false,+ },+}++const Lines = (): JSX.Element => (+ <div className='relative pointer-events-none'>+ <div className='absolute rotate-6 right-[-48rem] top-[32rem] h-px w-[800%] bg-gradient-to-l from-slate-600 dark:from-slate-400 opacity-10' />+ <div className='absolute rotate-[96deg] top-[22.26rem] xl:top-[23.5rem] -left-60 ml-[-0.5px] h-96 w-[2px] rounded-full bg-gradient-to-t from-emerald-600 dark:from-emerald-700 opacity-50' />+ </div>+)++const M_FEATURES_ICONS = [+ <ArrowsPointingOutIcon className='w-5 h-5' key='ArrowsPointingOutIcon' />,+ <CodeBracketIcon className='w-5 h-5' key='CodeBracketIcon' />,+ <PuzzlePieceIcon className='w-5 h-5' key='PuzzlePieceIcon' />,+ <ArrowTrendingUpIcon className='w-5 h-5' key='ArrowTrendingUpIcon' />,+ <LightBulbIcon className='w-5 h-5' key='LightBulbIcon' />,+ <ShareIcon className='w-5 h-5' key='ShareIcon' />,+]++const Main = (): JSX.Element => {+ const { t, i18n: { language } }: {+ t: (key: string, options?: {+ [key: string]: any+ }) => string,+ i18n: {+ language: string+ },+ } = useTranslation('common')+ const { theme } = useSelector((state: StateType) => state.ui.theme)+ const { authenticated } = useSelector((state: StateType) => state.auth)+ const { stats, lastBlogPost } = useSelector((state: StateType) => state.ui.misc)++ const events = nFormatterSeparated(Number(stats.events))+ const users = nFormatterSeparated(Number(stats.users))+ const websites = nFormatterSeparated(Number(stats.projects))++ return (+ <Title title={t('titles.main')}>+ <div className='overflow-hidden'>+ <main className='bg-white dark:bg-slate-900'>+ {/* first block with live demo */}+ <div className='relative overflow-x-clip isolate'>+ <svg+ className='absolute inset-0 -z-10 h-full w-full stroke-gray-200 dark:stroke-white/10 [mask-image:radial-gradient(100%_100%_at_top_right,white,transparent)]'+ aria-hidden='true'+ >+ <defs>+ <pattern+ id='rect-pattern'+ width={200}+ height={200}+ x='50%'+ y={-1}+ patternUnits='userSpaceOnUse'+ >+ <path d='M.5 200V.5H200' fill='none' />+ </pattern>+ </defs>+ <svg x='50%' y={-1} className='overflow-visible fill-white dark:fill-gray-800/20'>+ <path+ d='M-200 0h201v201h-201Z M600 0h201v201h-201Z M-400 600h201v201h-201Z M200 800h201v201h-201Z'+ strokeWidth={0}+ />+ </svg>+ <rect width='100%' height='100%' strokeWidth={0} fill='url(#rect-pattern)' />+ </svg>+ <div+ className='absolute left-[calc(50%-4rem)] top-10 -z-10 transform-gpu blur-3xl sm:left-[calc(50%-18rem)] lg:left-48 lg:top-[calc(50%-30rem)] xl:left-[calc(50%-24rem)]'+ aria-hidden='true'+ >+ <div+ className='aspect-[1108/632] w-[69.25rem] bg-gradient-to-r from-[#80caff] to-[#4f46e5] opacity-20'+ style={{+ clipPath:+ 'polygon(73.6% 51.7%, 91.7% 11.8%, 100% 46.4%, 97.4% 82.2%, 92.5% 84.9%, 75.7% 64%, 55.3% 47.5%, 46.5% 49.4%, 45% 62.9%, 50.3% 87.2%, 21.3% 64.1%, 0.1% 100%, 5.4% 51.1%, 21.4% 63.9%, 58.9% 0.2%, 73.6% 51.7%)',+ }}+ />+ </div>+ <Header />+ <div className='flex justify-center items-center py-2 px-2'>+ <a+ href='https://bank.gov.ua/en/news/all/natsionalniy-bank-vidkriv-spetsrahunok-dlya-zboru-koshtiv-na-potrebi-armiyi'+ target='_blank'+ rel='noreferrer noopener'+ className='text-slate-900 dark:text-white border-transparent border-b-2 hover:border-slate-900 dark:hover:border-white text-center'+ >+ {t('main.ukrSupport')}+ </a>+ <ArrowTopRightOnSquareIcon className='h-4 w-4 text-slate-800 dark:text-white ml-1 hidden md:block' />+ </div>+ <div+ className='relative pt-10 lg:pt-24 pb-5 xl:px-8 lg:px-6 sm:px-3 mx-auto min-h-[740px]'+ >+ <div className='relative z-20 flex flex-row content-between 2xl:mr-[14vw] 2xl:justify-center justify-center lg:justify-start'>+ <div className='lg:mt-0 text-left relative lg:mr-14 px-4'>+ <h1 className='max-w-2xl text-3xl sm:text-5xl md:text-5xl font-extrabold text-slate-900 dark:text-white sm:leading-none lg:text-5xl xl:text-6xl xl:leading-[110%]'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='main.slogan'+ components={{+ span: <span className='from-indigo-700 to-indigo-700 dark:from-indigo-600 dark:to-indigo-400 text-transparent bg-clip-text bg-gradient-to-r' />,+ }}+ />+ </h1>+ <div className='flex items-center overflow-hidden mt-2 mb-2 sm:text-xl lg:text-lg xl:text-lg'>+ <p className='rounded-full bg-indigo-500/10 px-3 py-1 text-sm text-center font-semibold leading-6 text-indigo-600 dark:text-indigo-400 ring-1 ring-inset ring-indigo-500/20'>+ Latest news+ </p>+ {_isEmpty(lastBlogPost) ? (+ <div className='h-6 ml-1 bg-slate-300 dark:bg-slate-700 w-80 rounded-md animate-pulse' />+ ) : (+ <a+ className='inline-flex ml-1 items-center space-x-1 text-sm font-semibold leading-6 text-slate-700 dark:text-slate-300 hover:underline'+ href={`${process.env.REACT_APP_BLOG_URL}post/${lastBlogPost.url_path}`}+ target='_blank'+ rel='noopener'+ >+ <span>+ {lastBlogPost.title}+ </span>+ <ChevronRightIcon className='h-4 w-4 text-slate-500' aria-hidden='true' />+ </a>+ )}+ </div>+ <p className='text-base text-slate-700 dark:text-slate-300 sm:text-xl lg:text-lg xl:text-lg'>+ {t('main.description')}+ <br />+ {t('main.trackEveryMetric')}+ </p>+ <div className='mt-10 flex flex-col items-center sm:flex-row'>+ <Link+ to={routes.signup}+ className='rounded-md !duration-300 transition-all w-full sm:max-w-[210px] h-12 flex items-center justify-center sm:mr-6 shadow-sm ring-1 text-white bg-slate-900 ring-slate-900 hover:bg-slate-700 dark:bg-indigo-700 dark:ring-indigo-700 dark:hover:bg-indigo-600'+ aria-label={t('titles.signup')}+ >+ <span className='text-base font-semibold mr-1'>+ {t('common.getStarted')}+ </span>+ <ArrowSmallRightIcon className='h-4 w-5 mt-[1px]' />+ </Link>+ <a+ href={LIVE_DEMO_URL}+ className='rounded-md !duration-300 transition-all sm:mt-0 mt-2 ring-1 ring-slate-900 dark:ring-white/20 w-full sm:max-w-[210px] h-12 flex items-center justify-center shadow-sm text-slate-900 dark:text-white bg-transparent hover:bg-slate-200 dark:hover:bg-gray-800'+ target='_blank'+ rel='noopener noreferrer'+ aria-label={`${t('common.liveDemo')} (opens in a new tab)`}+ >+ <span className='text-base font-semibold'>{t('common.liveDemo')}</span>+ </a>+ </div>+ </div>+ <div className='max-w-md xl:max-w-lg hidden lg:block'>+ <Lines />+ <picture>+ <source srcSet={theme === 'dark' ? '/assets/screenshot_dark.webp' : '/assets/screenshot_light.webp'} type='image/webp' />+ <img+ src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}+ className='h-full min-w-[880px] rounded-xl relative shadow-2xl ring-1 ring-gray-900/10 dark:ring-white/10'+ width='100%'+ height='auto'+ alt='Swetrix Analytics dashboard'+ />+ </picture>+ </div>+ </div>+ <div className='my-10 block lg:hidden relative z-20 px-4 md:px-0'>+ <picture>+ <source srcSet={theme === 'dark' ? '/assets/screenshot_dark.webp' : '/assets/screenshot_light.webp'} type='image/webp' />+ <img+ src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}+ className='rounded-xl relative shadow-2xl w-full ring-1 ring-gray-900/10 dark:ring-white/10'+ width='100%'+ height='auto'+ alt='Swetrix Analytics dashboard'+ />+ </picture>+ </div>+ </div>+ </div>+ {/* end first block with live demo */}+ {/* section Core Analytics Features */}+ <div className='dark:bg-slate-900 bg-white px-4 pb-24'>+ <section className='flex pt-16 md:pt-48 flex-col-reverse md:flex-row items-center md:items-start md:justify-between max-w-7xl m-auto'>+ <picture>+ <source srcSet='/assets/CoreFeaturesLight.webp' type='image/webp' />+ <img src='/assets/CoreFeaturesLight.png' className='md:max-w-md md:mr-3 mt-3 md:mt-0 lg:max-w-full md:relative md:-top-10' alt='Core Analytics Features' />+ </picture>+ <div className='max-w-lg'>+ <h2 className='font-extrabold text-4xl dark:text-white text-slate-900'>+ {t('main.coreFeatures.title')}+ </h2>+ <p className='mt-6 dark:text-gray-400 text-gray-600 mb-11'>+ {t('main.coreFeatures.desc')}+ </p>+ <a+ href={LIVE_DEMO_URL}+ className='dark:text-indigo-400 text-indigo-700 hover:underline font-bold border-0 flex items-center'+ target='_blank'+ rel='noopener noreferrer'+ aria-label={`${t('common.liveDemo')} (opens in a new tab)`}+ >+ {t('common.liveDemo')}+ <ArrowSmallRightIcon className='w-5 h-4 mt-[1px]' />+ </a>+ </div>+ </section>+ {/* end section Core Analytics Features */}+ {/* section Marketplace & build-in Extensions */}+ <section className='flex flex-col md:flex-row items-center md:justify-between max-w-7xl m-auto'>+ <div className='max-w-[516px]'>+ <h2 className='font-extrabold text-4xl text-slate-900 dark:text-white'>+ {t('main.marketplace.title')}+ </h2>+ <p className='mt-6 text-gray-600 dark:text-gray-400 mb-3'>+ {t('main.marketplace.desc1')}+ </p>+ <p className='text-gray-600 dark:text-gray-400 mb-11'>+ {t('main.marketplace.desc2')}+ </p>+ <a+ href={MARKETPLACE_URL}+ className='dark:text-indigo-400 text-indigo-700 hover:underline font-bold border-0 flex items-center'+ target='_blank'+ rel='noopener noreferrer'+ aria-label='Swetrix Marketplace (opens in a new tab)'+ >+ {t('main.visitAddons')}+ <ArrowSmallRightIcon className='w-5 h-4 mt-[1px]' />+ </a>+ </div>+ <img className='md:max-w-[450px] lg:max-w-lg md:ml-5 mt-8 md:mt-0' src='/assets/teardown.svg' alt='Marketplace' />+ </section>+ {/* end section Marketplace & build-in Extensions */}+ {/* section Privacy compliance. */}+ <section className='flex pt-20 md:pt-28 flex-col-reverse md:flex-row items-center md:items-start md:justify-between max-w-7xl m-auto'>+ <img className='md:max-w-[360px] md:mr-3 mt-3 md:mt-0 lg:max-w-lg' src='/assets/gdpr.svg' alt='GDPR compliant' />+ <div className='max-w-[516px] w-full md:min-w-[370px] pb-16 md:pb-0 md:pt-8'>+ <h2 className='font-extrabold mb-6 text-4xl text-slate-900 dark:text-white'>+ {t('main.privacy.title')}+ </h2>+ {_map(t('main.privacy.list', { returnObjects: true }), (item: {+ label: string+ desc: string+ }) => (+ <div key={item.label} className='mb-4 flex items-center'>+ <div className='mr-3'>+ <CheckCircleIcon className='fill-indigo-500 w-[24px] h-[24px]' />+ </div>+ <p>+ <span className='dark:text-white'>{item.label}</span>+ <span className='mr-1 ml-1 dark:text-white'>-</span>+ <span className='text-gray-600 dark:text-gray-400'>{item.desc}</span>+ </p>+ </div>+ ))}+ {/* mt-7 because mb-4 in upper component + mt-7 = 11. mb-11 is used for spacing the links in other sections. */}+ <Link to={routes.privacy} className='mt-7 dark:text-indigo-400 text-indigo-700 hover:underline font-bold border-0 flex items-center' aria-label={t('footer.pp')}>+ {t('main.dataProtection')}+ <ArrowSmallRightIcon className='w-5 h-4 mt-[1px]' />+ </Link>+ </div>+ </section>+ {/* end section Privacy compliance. */}+ </div>+ {/* block singup */}+ {!authenticated && (+ <div className='overflow-x-clip'>+ <div className='py-20 max-w-7xl w-full flex justify-center md:justify-between items-center mx-auto px-5 relative isolate'>+ <div+ className='absolute inset-x-0 -top-3 -z-10 transform-gpu overflow-hidden px-36 blur-3xl'+ aria-hidden='true'+ >+ <div+ className='mx-auto aspect-[1155/678] w-[72.1875rem] bg-gradient-to-tr from-[#ff80b5] to-[#9089fc] opacity-30'+ style={{+ clipPath:+ 'polygon(74.1% 44.1%, 100% 61.6%, 97.5% 26.9%, 85.5% 0.1%, 80.7% 2%, 72.5% 32.5%, 60.2% 62.4%, 52.4% 68.1%, 47.5% 58.3%, 45.2% 34.5%, 27.5% 76.7%, 0.1% 64.9%, 17.9% 100%, 27.6% 76.8%, 76.1% 97.7%, 74.1% 44.1%)',+ }}+ />+ </div>+ <div className='relative z-50 lg:col-span-6 rounded-xl'>+ <div className='bg-white dark:bg-slate-800/20 ring-1 ring-slate-200 dark:ring-slate-800 sm:max-w-md sm:w-full sm:mx-auto sm:rounded-lg sm:overflow-hidden'>+ <div className='px-4 py-8 sm:px-10'>+ <p className='text-lg text-gray-900 dark:text-white text-center md:text-xl font-semibold'>+ {t('main.signup')}+ </p>+ <div className='mt-6'>+ <SignUp />+ </div>+ </div>+ <div className='px-4 sm:px-10'>+ <div className='py-6 bg-transparent border-t border-gray-200 dark:border-slate-700'>+ <p className='text-xs leading-5 text-gray-500 dark:text-gray-100'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='main.signupTerms'+ components={{+ tos: <Link to={routes.terms} className='font-medium text-gray-900 dark:text-gray-300 hover:underline' aria-label={t('footer.tos')} />,+ pp: <Link to={routes.privacy} className='font-medium text-gray-900 dark:text-gray-300 hover:underline' aria-label={t('footer.pp')} />,+ }}+ />+ </p>+ </div>+ </div>+ </div>+ </div>+ <div className='relative'>+ <picture>+ <source srcSet={theme === 'dark' ? '/assets/section-signup-dark.webp' : '/assets/section-signup-light.webp'} type='image/webp' />+ <img+ src={theme === 'dark' ? '/assets/section-signup-dark.png' : '/assets/section-signup-light.png'}+ className='relative z-50 hidden md:block'+ alt='Swetrix Dashboard overview'+ />+ </picture>+ </div>+ </div>+ </div>+ )}+ {/* end block singup */}+ {/* Core features section */}+ <section className='bg-white dark:bg-slate-900 pt-14 relative pb-14'>+ <BackgroundSvg className='absolute -left-8' type='shapes' />+ <div className='mx-auto text-slate-900 font-extrabold text-3xl sm:text-5xl w-fit relative'>+ <h2 className='relative z-20 dark:text-white'>+ {t('main.coreFeaturesBlock')}+ </h2>+ <BackgroundSvg className='absolute right-0 sm:-right-16 top-9 z-10 opacity-30' type='semicircle' />+ </div>+ <div className='mt-[60px] flex items-center max-w-7xl w-full mx-auto flex-wrap justify-center xl:justify-between'>+ {_map(t('main.features', { returnObjects: true }), (item: {+ name: string+ desc: string+ }, index: number) => (+ <div key={item.name} className='w-[416px] h-64 px-7 py-11 text-center'>+ <span className='text-indigo-500 text-3xl font-semibold'>{1 + index}</span>+ <div className='mt-2'>+ <h2 className='text-slate-900 dark:text-white text-xl font-semibold max-w-[300px] mx-auto mb-3 whitespace-pre-line'>{item.name}</h2>+ <p className='text-gray-500 max-w-xs mx-auto dark:text-gray-400'>{item.desc}</p>+ </div>+ </div>+ ))}+ </div>+ <BackgroundSvg className='absolute right-0 bottom-0 z-10' type='twolinecircle' />+ </section>+ {/* end Core features section */}+ {/* section supports */}+ <section className='bg-white dark:bg-slate-900 pt-24 sm:px-5 px-3 relative'>+ <h2 className='mx-auto text-slate-900 dark:text-white font-bold text-3xl sm:ext-5xl w-fit text-center'>+ {t('main.supports')}+ </h2>+ <div className='mt-20 grid sm:grid-cols-4 md:grid-cols-6 grid-cols-3 gap-x-4 gap-y-10 justify-items-center items-center lg:gap-x-10 lg:gap-y-16 max-w-7xl w-full mx-auto justify-between'>+ <Telegram className='max-w-[64px] sm:max-w-[150px] max-h-16' />+ <NuxtJS theme={theme} className='max-w-[106px] sm:max-w-[150px] max-h-12' />+ <Webflow theme={theme} className='max-w-[106px] sm:max-w-[150px] max-h-12' />+ <NextJS theme={theme} className='max-w-[78px] sm:max-w-[80px] max-h-12' />+ <Notion theme={theme} className='max-w-[106px] sm:max-w-[130px] max-h-12' />+ <ReactSVG className='max-w-[71px] sm:max-w-[150px] max-h-16' />+ <Angular className='max-w-[60px] sm:max-w-[160px] max-h-20' />+ <Wordpress theme={theme} className='max-w-[100px] sm:max-w-[160px] max-h-16' />+ <Wix theme={theme} className='max-w-[105px] sm:max-w-[120px] max-h-12' />+ <Ghost theme={theme} className='max-w-[105px] sm:max-w-[150px] max-h-20' />+ <Gatsby theme={theme} className='max-w-[105px] sm:max-w-[150px] max-h-12' />+ <Cloudflare theme={theme} className='max-w-[105px] sm:max-w-[140px] max-h-12' />+ </div>+ </section>+ {/* end section supports */}+ {/* Marketplace and extension features */}+ <div className='overflow-hidden'>+ <div className='relative w-full mx-auto pt-10 mt-10 isolate'>+ <svg+ className='absolute w-full inset-0 -z-10 hidden h-full stroke-gray-200 dark:stroke-white/10 [mask-image:radial-gradient(64rem_64rem_at_top,white,transparent)] sm:block'+ aria-hidden='true'+ >+ <defs>+ <pattern+ id='rect-pattern-2'+ width={200}+ height={200}+ x='50%'+ y={0}+ patternUnits='userSpaceOnUse'+ >+ <path d='M.5 200V.5H200' fill='none' />+ </pattern>+ </defs>+ <svg x='50%' y={0} className='overflow-visible fill-gray-50 dark:fill-slate-800/30'>+ <path+ d='M-200.5 0h201v201h-201Z M599.5 0h201v201h-201Z M399.5 400h201v201h-201Z M-400.5 600h201v201h-201Z'+ strokeWidth={0}+ />+ </svg>+ <rect width='100%' height='100%' strokeWidth={0} fill='url(#rect-pattern-2)' />+ </svg>+ <section className='relative z-20 px-3 max-w-7xl mx-auto'>+ <h2 className='mt-20 text-center text-3xl sm:text-5xl text-slate-900 dark:text-white font-extrabold max-w-lg w-full mx-auto'>+ {t('main.marketplaceBlock')}+ </h2>+ <div className='grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-y-10 sm:gap-y-24 justify-between justify-items-center text-slate-900 dark:text-white pt-20 pb-36'>+ {_map(t('main.mFeatures', { returnObjects: true }), (item: {+ name: string+ desc: string+ }, index: number) => (+ <div key={item.name} className='max-w-[310px] w-full'>+ <div className='flex items-center'>+ <span className='text-slate-900 dark:text-gray-200 text-xl mr-4'>+ {M_FEATURES_ICONS[index]}+ </span>+ <h2 className='font-semibold text-xl'>+ {item.name}+ </h2>+ </div>+ <p className='pl-9 text-slate-700 dark:text-gray-300'>{item.desc}</p>+ </div>+ ))}+ </div>+ </section>+ </div>+ </div>+ {/* end Marketplace and extension features */}+ <Pricing t={t} language={language} />++ {/* section: Why use Swetrix when there is .... */}+ <div className='overflow-hidden'>+ <div className='relative max-w-7xl w-full mx-auto isolate'>+ <div+ className='absolute inset-x-0 top-1/2 -z-10 -translate-y-1/2 transform-gpu overflow-hidden opacity-30 blur-3xl'+ aria-hidden='true'+ >+ <div+ className='ml-[max(50%,38rem)] aspect-[1313/771] w-[82.0625rem] bg-gradient-to-tr from-[#ff80b5] to-[#9089fc]'+ style={{+ clipPath:+ 'polygon(74.1% 44.1%, 100% 61.6%, 97.5% 26.9%, 85.5% 0.1%, 80.7% 2%, 72.5% 32.5%, 60.2% 62.4%, 52.4% 68.1%, 47.5% 58.3%, 45.2% 34.5%, 27.5% 76.7%, 0.1% 64.9%, 17.9% 100%, 27.6% 76.8%, 76.1% 97.7%, 74.1% 44.1%)',+ }}+ />+ </div>+ <div+ className='absolute inset-x-0 top-0 -z-10 flex transform-gpu overflow-hidden pt-8 opacity-25 blur-3xl xl:justify-end'+ aria-hidden='true'+ >+ <div+ className='ml-[-22rem] aspect-[1313/771] w-[82.0625rem] flex-none origin-top-right rotate-[30deg] bg-gradient-to-tr from-[#ff80b5] to-[#9089fc] xl:ml-0 xl:mr-[calc(50%-12rem)]'+ style={{+ clipPath:+ 'polygon(74.1% 44.1%, 100% 61.6%, 97.5% 26.9%, 85.5% 0.1%, 80.7% 2%, 72.5% 32.5%, 60.2% 62.4%, 52.4% 68.1%, 47.5% 58.3%, 45.2% 34.5%, 27.5% 76.7%, 0.1% 64.9%, 17.9% 100%, 27.6% 76.8%, 76.1% 97.7%, 74.1% 44.1%)',+ }}+ />+ </div>+ <section className='relative z-20 px-3'>+ <h1 className='mt-20 text-center h-8 mb-5 text-3xl sm:text-5xl text-slate-900 dark:text-white font-extrabold max-w-prose w-full mx-auto'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='main.whyUseSwetrix'+ components={{+ // eslint-disable-next-line jsx-a11y/anchor-has-content+ competitor: (+ <TypeAnimation+ sequence={processedList}+ className='text-slate-500 dark:text-gray-400'+ wrapper='span'+ speed={10}+ repeat={Infinity}+ cursor+ />+ ),+ swetrix: <span className='text-indigo-600 dark:text-indigo-500'>Swetrix</span>,+ }}+ />+ </h1>+ <div className='py-20 text-lg text-gray-50 tracking-tight'>+ <div className='mt-2 flex flex-col'>+ <div className='-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8'>+ <div className='inline-block min-w-full py-2 align-middle md:px-6 lg:px-8'>+ <div className='overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg'>+ <table className='w-full min-w-full divide-y divide-slate-500'>+ <thead className='bg-gray-100 dark:bg-slate-800'>+ <tr>+ <th />+ {_map(SWETRIX_AND_COMPETITORS_LIST, (item, key) => (+ <th+ scope='col'+ key={key}+ className='w-1/6 py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-slate-800 dark:text-gray-50 sm:pl-6'+ >+ {item}+ </th>+ ))}+ </tr>+ </thead>+ <tbody className='divide-y divide-slate-300 dark:divide-slate-700 bg-gray-50 dark:bg-slate-800'>+ {_map(COMPETITOR_FEATURE_TABLE.Swetrix, (_, key) => (+ <tr key={key}>+ <td className='w-1/6 px-3 py-4 text-sm text-slate-700 dark:text-gray-50 sm:pl-6'>+ {t(key)}+ </td>+ {_map(SWETRIX_AND_COMPETITORS_LIST, (service) => (+ <td+ key={`${key}-${service}`}+ className='w-1/6 px-3 py-4 text-sm text-gray-50 sm:pl-6'+ >+ {COMPETITOR_FEATURE_TABLE[service][key] && (+ <CheckIcon className='flex-shrink-0 h-5 w-5 text-green-600 dark:text-green-500' aria-label={t('common.yes')} />+ )}+ {COMPETITOR_FEATURE_TABLE[service][key] === false && (+ <XMarkIcon className='flex-shrink-0 h-5 w-5 text-red-600 dark:text-red-500' aria-label={t('common.no')} />+ )}+ {COMPETITOR_FEATURE_TABLE[service][key] === null && (+ <p className='text-slate-700 dark:text-gray-50 h-5 w-5 text-center'>+ -+ </p>+ )}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ </div>+ </div>+ </div>+ </section>+ </div>+ </div>++ {/* section Testimonials */}+ <section className='bg-white dark:bg-slate-900 pt-20 pb-20 relative'>+ <div className='absolute right-0 top-0'>+ <BackgroundSvg type='twolinecircle2' />+ </div>+ <div className='absolute rotate-[135deg] left-0 z-0'>+ <BackgroundSvg type='shapes' />+ </div>+ <div className='max-w-[1000px] w-full mx-auto'>+ <h2 className='text-slate-900 text-center font-extrabold text-5xl relative z-20 dark:text-white'>+ {t('main.testimonials')}+ </h2>+ <div className='flex items-center flex-col md:flex-row justify-between mt-16'>+ {_map(t('main.lTestimonials', { returnObjects: true }), (item: {+ name: string;+ role: string;+ desc: string;+ }, index: number) => (+ <div+ key={item.name}+ className={cx('max-w-xs w-full dark:bg-slate-900', {+ 'mt-5 md:mt-0': index > 0,+ })}+ style={{+ boxShadow: '-22px -11px 40px rgba(0, 0, 0, 0.02), 3px -5px 16px rgba(0, 0, 0, 0.02), 17px 24px 20px rgba(0, 0, 0, 0.02)',+ borderRadius: '100px 30px 30px 30px',+ }}+ >+ <Quote theme={theme} color={index === 1 ? 'indigo' : 'black'} className='mx-auto relative -top-4' />+ <div className='px-10 mb-10 max-h-80 overflow-auto'>+ <p className='text-gray-500 text-sm mt-8 dark:text-gray-400'>+ {item.name}+ <br />+ {item.role}+ </p>+ <p className='text-slate-900 dark:text-white text-md text mt-2 leading-9 whitespace-pre-line'>+ {item.desc}+ </p>+ </div>+ </div>+ ))}+ </div>+ </div>+ </section>+ {/* end section Testimonials */}++ <div className='bg-white dark:bg-slate-900 px-4 md:px-8 pb-12'>+ <section className='relative isolate max-w-7xl w-full mx-auto bg-slate-800 overflow-hidden lg:h-[450px]' style={{ borderRadius: '100px 30px 30px 30px' }}>+ <div className='absolute -z-10 inset-0 overflow-hidden' aria-hidden='true'>+ <div className='absolute left-[calc(20%-19rem)] top-[calc(50%-36rem)] transform-gpu blur-3xl'>+ <div+ className='aspect-[1097/1023] w-[68.5625rem] bg-gradient-to-r from-[#ff4694] to-[#776fff] opacity-25 dark:opacity-10'+ style={{+ clipPath:+ 'polygon(74.1% 44.1%, 100% 61.6%, 97.5% 26.9%, 85.5% 0.1%, 80.7% 2%, 72.5% 32.5%, 60.2% 62.4%, 52.4% 68.1%, 47.5% 58.3%, 45.2% 34.5%, 27.5% 76.7%, 0.1% 64.9%, 17.9% 100%, 27.6% 76.8%, 76.1% 97.7%, 74.1% 44.1%)',+ }}+ />+ </div>+ </div>+ <div className='flex items-start justify-between pt-8 pl-8 sm:pl-14 lg:pl-28 md:flex-row flex-col'>+ <div className='max-w-[430px] w-full pt-14 pr-3 mb-16 md:mb-0'>+ <h2 className='font-bold text-2xl leading-9 sm:text-4xl sm:leading-[48px] md:text-[28px] md:leading-10 lg:text-[33px] lg:leading-[48px] text-white mb-3'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='main.os'+ components={{+ // eslint-disable-next-line jsx-a11y/anchor-has-content+ gradi: <span className='text-transparent !bg-clip-text' style={{ background: 'linear-gradient(91.37deg, #4E46DD 10%, #5C3CDA 55%, #A274EF 100%)' }} />,+ }}+ />+ </h2>+ <p className='text-gray-300 mb-9 font-medium text-base sm:text-lg'>+ {t('main.demoGeoReports')}+ </p>+ <Link to={routes.signup} className='rounded-md border !duration-300 transition-all w-full max-w-[210px] h-[50px] flex items-center justify-center sm:mr-6 shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 border-transparent' aria-label={t('titles.signup')}>+ <span className='text-base font-semibold mr-1'>{t('main.start')}</span>+ <ArrowSmallRightIcon className='w-5 h-4 mt-[1px]' />+ </Link>+ </div>+ <div className='max-w-md xl:max-w-lg block h-[450px] md:shadow-[8px_8px_10px_3px] md:rounded-md '>+ <img+ className='rounded-xl ring-1 ring-gray-900/10'+ style={{ minHeight: '600px', minWidth: '880px' }}+ src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}+ width='100%'+ height='auto'+ alt='Swetrix Analytics dashboard'+ />+ </div>+ </div>+ </section>+ </div>++ {/* Advantages of using open source */}+ <section className='flex items-center lg:flex-row flex-col-reverse justify-between max-w-7xl w-full mx-auto py-20 lg:py-32 px-5'>+ <picture>+ <source srcSet={theme === 'dark' ? '/assets/opensource_dark.webp' : '/assets/opensource_light.webp'} type='image/webp' />+ <img+ className='ring-1 ring-gray-900/10 dark:ring-white/10 rounded-xl'+ src={theme === 'dark' ? '/assets/opensource_dark.png' : '/assets/opensource_light.png'}+ loading='lazy'+ alt='Swetrix open source'+ />+ </picture>+ <div className='max-w-lg w-full lg:ml-5'>+ <h2 className='text-3xl md:text-4xl text-slate-900 dark:text-white font-extrabold'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='main.opensourceAdv'+ components={{+ // eslint-disable-next-line jsx-a11y/anchor-has-content+ url: <a href={GITHUB_URL} className='hover:underline' target='_blank' rel='noopener noreferrer' aria-label='Source code (opens in a new tab)' />,+ }}+ />+ </h2>+ <hr className='border-slate-300 dark:border-slate-700 border-1 max-w-[346px] my-6' />+ <div className='max-w-md w-full lg:mb-0 mb-9'>+ {_map(t('main.opensource', { returnObjects: true }), (item: {+ desc: string+ }) => (+ <p key={item.desc} className='text-slate-700 dark:text-gray-300 text-sm leading-6 flex items-center mb-3'>+ <span>+ <CheckCircleIcon className='w-6 h-6 text-indigo-500 mr-4' />+ </span>+ {item.desc}+ </p>+ ))}+ </div>+ </div>+ </section>+ {/* end Advantages of using open source */}+ {/* Become a developer */}+ <section className='bg-white dark:bg-slate-900 pt-20 pb-44 relative'>+ <div className='absolute right-0 top-16 z-0'>+ <BackgroundSvg type='threecircle' />+ </div>+ <div className='absolute -left-9 top-52 rotate-90'>+ <BackgroundSvg type='shapes' />+ </div>+ <div className='max-w-5xl w-full mx-auto px-3'>+ <div className='max-w-sm w-full mx-auto'>+ <h2 className='text-gray-900 dark:text-white text-3xl md:text-4xl font-extrabold text-center'>+ {t('main.becomeDev')}+ </h2>+ <p className='text-gray-600 dark:text-gray-400 text-base font-medium text-center mt-2'>+ {t('main.becomeDevDesc')}+ </p>+ </div>+ <div className='flex items-center justify-between mt-20 md:mt-32 md:flex-row flex-col'>+ <div className='text-center'>+ <p className='text-indigo-700 text-5xl font-extrabold text-center'>+ {users[0]}+ {users[1] && (+ <span className='text-gray-900 dark:text-indigo-200'>+ {users[1]}+ ++ </span>+ )}+ </p>+ <p className='text-gray-600 text-lg dark:text-gray-200'>+ {t('main.users')}+ </p>+ </div>+ <div className='bg-gray-800 dark:bg-gray-200 w-2 h-2 rounded-full mx-5 mb-14 mt-16 md:mb-0 md:mt-0' />+ <div className='text-center'>+ <p className='text-indigo-700 text-5xl font-extrabold text-center'>+ {websites[0]}+ {websites[1] && (+ <span className='text-gray-900 dark:text-indigo-200'>+ {websites[1]}+ ++ </span>+ )}+ </p>+ <p className='text-gray-600 text-lg dark:text-gray-200'>+ {t('main.websites')}+ </p>+ </div>+ <div className='bg-gray-800 dark:bg-gray-200 w-2 h-2 rounded-full mx-5 mb-14 mt-16 md:mb-0 md:mt-0' />+ <div className='text-center'>+ <p className='text-indigo-700 text-5xl font-extrabold text-center'>+ {events[0]}+ {events[1] && (+ <span className='text-gray-900 dark:text-indigo-200'>+ {events[1]}+ ++ </span>+ )}+ </p>+ <p className='text-gray-600 text-lg dark:text-gray-200'>+ {t('main.pageviews')}+ </p>+ </div>+ </div>+ </div>+ </section>+ {/* end Become a developer */}+ </main>+ </div>+ </Title>+ )+}++export default memo(Main)diff --git a/app/pages/MainPage/styles.css b/app/pages/MainPage/styles.cssnew file mode 100644index 000000000..ff00c8145--- /dev/null+++ b/app/pages/MainPage/styles.css@@ -0,0 +1,14 @@+.filter_blur {+ -ms-filter: blur(150px);+ -o-filter: blur(150px);+ -webkit-filter: blur(150px);+ filter: blur(150px);+}++@-moz-document url-prefix() {+ .filter_blur {+ width: 300px !important;+ height: 500px !important;+ opacity: 0.3 !important;+ }+}\ No newline at end of filediff --git a/app/pages/NotFound/index.tsx b/app/pages/NotFound/index.tsxnew file mode 100644index 000000000..7e648c898--- /dev/null+++ b/app/pages/NotFound/index.tsx@@ -0,0 +1,52 @@+import React from 'react'+import { Link } from 'react-router-dom'+import { useTranslation } from 'react-i18next'++import routes from 'routes'+import Title from 'components/Title'++const NotFound = (): JSX.Element => {+ const { t }: {+ t: (key: string) => string+ } = useTranslation('common')++ return (+ <Title title={t('notFoundPage.title')}>+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900 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'>+ <p className='text-4xl font-bold text-indigo-600 dark:text-indigo-500 sm:text-5xl'>+ 404+ </p>+ <div className='sm:ml-6'>+ <div className='sm:border-l 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('notFoundPage.title')}+ </h1>+ <p className='mt-1 whitespace-pre-line text-base text-gray-500 dark:text-gray-300'>+ {t('notFoundPage.description')}+ </p>+ </div>+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>+ <Link+ to={routes.main}+ 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('notFoundPage.goHome')}+ </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>+ </Title>+ )+}++export default NotFounddiff --git a/app/pages/OpenStartup/index.tsx b/app/pages/OpenStartup/index.tsxnew file mode 100644index 000000000..da35c2f6b--- /dev/null+++ b/app/pages/OpenStartup/index.tsx@@ -0,0 +1,375 @@+/* eslint-disable */+import React, { useEffect } from 'react'+import _map from 'lodash/map'+import bb, {+ bar, line,+} from 'billboard.js'+import { useTranslation, Trans } from 'react-i18next'+import { Link } from 'react-router-dom'+import { useSelector } from 'react-redux'++import { nFormatterSeparated } from 'utils/generic'+import { StateType } from 'redux/store/index'+import Title from 'components/Title'+import { LIVE_DEMO_URL } from 'redux/constants'+import '../Project/View/styles.css'++// This should be generated on the API side, will be done later.+const financeData = {+ '2021-08-01': {+ 'Technical Expences': -32,+ 'Business Expences': 0,+ 'MRR': 0,+ 'Revenue': 0,+ },+ '2021-09-01': {+ 'Technical Expences': -32,+ 'Business Expences': 0,+ 'MRR': 0,+ 'Revenue': 0,+ },+ '2021-10-01': {+ 'Technical Expences': -32,+ 'Business Expences': 0,+ 'MRR': 0,+ 'Revenue': 0,+ },+ '2021-11-01': {+ 'Technical Expences': -32,+ 'Business Expences': 0,+ 'MRR': 0,+ 'Revenue': 0,+ },+ '2021-12-01': {+ 'Technical Expences': -32,+ 'Business Expences': 0,+ 'MRR': 0,+ 'Revenue': 0,+ },+ '2022-01-01': {+ 'Technical Expences': -32,+ 'Business Expences': 0,+ 'MRR': 0,+ 'Revenue': 0,+ },+ '2022-02-01': {+ 'Technical Expences': -32,+ 'Business Expences': 0,+ 'MRR': 2,+ 'Revenue': 2,+ },+ '2022-03-01': {+ 'Technical Expences': -32,+ 'Business Expences': 0,+ 'MRR': 15,+ 'Revenue': 14,+ },+ '2022-04-01': {+ 'Technical Expences': -32,+ 'Business Expences': -300,+ 'MRR': 15,+ 'Revenue': 14,+ },+ '2022-05-01': {+ 'Technical Expences': -32,+ 'Business Expences': -300,+ 'MRR': 15,+ 'Revenue': 14,+ },+ '2022-06-01': {+ 'Technical Expences': -32,+ 'Business Expences': -300,+ 'MRR': 15,+ 'Revenue': 14,+ },+ '2022-07-01': {+ 'Technical Expences': -32,+ 'Business Expences': -300,+ 'MRR': 15,+ 'Revenue': 14,+ },+ '2022-08-01': {+ 'Technical Expences': -42,+ 'Business Expences': -300,+ 'MRR': 15,+ 'Revenue': 14,+ },+ '2022-09-01': {+ 'Technical Expences': -42,+ 'Business Expences': -350,+ 'MRR': 15,+ 'Revenue': 14,+ },+ '2022-10-01': {+ 'Technical Expences': -48,+ 'Business Expences': -300,+ 'MRR': 15,+ 'Revenue': 14,+ },+ '2022-11-01': {+ 'Technical Expences': -48,+ 'Business Expences': -300,+ 'MRR': 15,+ 'Revenue': 14,+ },+ '2022-12-01': {+ 'Technical Expences': -48,+ 'Business Expences': -400,+ 'MRR': 15,+ 'Revenue': 14,+ },+ '2023-01-01': {+ 'Technical Expences': -48,+ 'Business Expences': -375,+ 'MRR': 15,+ 'Revenue': 14,+ },+ '2023-02-01': {+ 'Technical Expences': -48,+ 'Business Expences': -300,+ 'MRR': 35,+ 'Revenue': 31,+ },+ '2023-03-01': {+ 'Technical Expences': -48,+ 'Business Expences': -370,+ 'MRR': 30,+ 'Revenue': 26,+ },+ '2023-04-01': {+ 'Technical Expences': -48,+ 'Business Expences': -50,+ 'MRR': 34,+ 'Revenue': 73,+ },+ '2023-05-01': {+ 'Technical Expences': -48,+ 'Business Expences': -650,+ 'MRR': 38,+ 'Revenue': 73,+ },+}++const financeDataToColumns = (financeData: any) => {+ const dates = Object.keys(financeData)+ const columns = [+ ['Technical Expences'],+ ['Business Expences'],+ ['MRR'],+ ['Profit'],+ ['Revenue'],+ ['x']+ ]++ dates.forEach((date) => {+ columns[0].push(financeData[date]['Technical Expences'])+ columns[1].push(financeData[date]['Business Expences'])+ columns[2].push(financeData[date]['MRR'])+ columns[3].push(+ financeData[date]['Revenue'] + financeData[date]['Technical Expences'] + financeData[date]['Business Expences']+ )+ columns[4].push(financeData[date]['Revenue'])+ columns[5].push(date)+ })++ return columns+}++const columns = financeDataToColumns(financeData)++const groups = ['Revenue', 'MRR', 'Profit', 'Technical Expences', 'Business Expences']++const getSettings = () => {+ return {+ data: {+ x: 'x',+ xFormat: '%b %Y',+ columns,+ types: {+ 'Technical Expences': bar(),+ 'Business Expences': bar(),+ MRR: bar(),+ Profit: line(),+ Revenue: line(),+ },+ colors: {+ 'Technical Expences': '#EC4319',+ 'Business Expences': '#F27059',+ MRR: '#709775',+ Profit: '#A5E6AB',+ Revenue: '#12731E'+ },+ groups: [+ groups,+ ],+ },+ axis: {+ x: {+ type: 'timeseries',+ tick: {+ format: '%b %Y',+ },+ },+ y: {+ tick: {+ // format: (d: string) => getStringFromTime(getTimeFromSeconds(d), true),+ },+ },+ },+ tooltip: {+ // format: {+ // title: (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x),+ // },+ order: (a: any, b: any) => {+ const aIndex = groups.indexOf(a.name)+ const bIndex = groups.indexOf(b.name)++ // ascending order+ return aIndex - bIndex+ },+ contents: {+ template: `+ <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'>{=TITLE}</li>+ <hr class='border-gray-200 dark:border-gray-600' />+ {{+ <li class='flex justify-between'>+ <div class='flex justify-items-start'>+ <div class='w-3 h-3 rounded-sm mt-1.5 mr-2' style=background-color:{=COLOR}></div>+ <span>{=NAME}</span>+ </div>+ <span class='pl-4'>{=VALUE} US\$</span>+ </li>+ }}+ </ul>+ `,+ },+ },+ point: {+ // focus: {+ // only: xAxisSize > 1,+ // },+ pattern: [+ 'circle',+ ],+ r: 3,+ },+ legend: {+ usePoint: true,+ item: {+ tile: {+ width: 10,+ },+ },+ },+ // area: {+ // linearGradient: true,+ // },+ // padding: {+ // right: rotateXAxias && 35,+ // },+ bindto: '#open-startup',+ }+}++const OpenStartup = (): JSX.Element => {+ const { t }: any = useTranslation('common')+ const { stats } = useSelector((state: StateType) => state.ui.misc)++ const events = nFormatterSeparated(Number(stats.events), 1)+ const users = nFormatterSeparated(Number(stats.users), 1)+ const websites = nFormatterSeparated(Number(stats.projects), 1)++ useEffect(() => {+ const bbSettings = getSettings()++ // @ts-ignore+ bb.generate(bbSettings)+ }, [])++ return (+ <Title title={t('titles.open')}>+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>+ <div className='w-11/12 md:w-4/5 mx-auto pb-16 pt-12 px-4 sm:px-6 lg:px-8 whitespace-pre-line'>+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('titles.open')}+ </h1>++ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('open.desc')}+ </p>++ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('open.updated')}+ </p>++ <h2 className='mt-8 text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('open.finance.title')}+ </h2>++ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('open.finance.desc')}+ </p>++ <div className='h-80 mt-4' id='open-startup' />++ <h2 className='mt-8 text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('open.usage.title')}+ </h2>++ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('open.usage.desc')}+ </p>++ <p className='mt-2 text-md text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('main.users')}+ {': '}+ {users[0]}+ {users[1] && (+ <span className='text-gray-900 dark:text-indigo-200'>+ {users[1]}+ ++ </span>+ )}+ </p>++ <p className='mt-2 text-md text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('main.websites')}+ {': '}+ {websites[0]}+ {websites[1] && (+ <span className='text-gray-900 dark:text-indigo-200'>+ {websites[1]}+ ++ </span>+ )}+ </p>++ <p className='mt-2 text-md text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('main.pageviews')}+ {': '}+ {events[0]}+ {events[1] && (+ <span className='text-gray-900 dark:text-indigo-200'>+ {events[1]}+ ++ </span>+ )}+ </p>++ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <Trans+ t={t}+ i18nKey='open.usage.live'+ components={{+ livedemo: <Link to={LIVE_DEMO_URL} className='font-medium hover:underline text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' />,+ }}+ />+ </p>+ </div>+ </div>+ </Title>+ )+}++export default OpenStartupdiff --git a/app/pages/Press/index.tsx b/app/pages/Press/index.tsxnew file mode 100644index 000000000..5db47eaed--- /dev/null+++ b/app/pages/Press/index.tsx@@ -0,0 +1,127 @@+/* eslint-disable jsx-a11y/anchor-has-content */+import React from 'react'+import { Link } from 'react-router-dom'+import { useTranslation, Trans } from 'react-i18next'++import Title from 'components/Title'+import routes from 'routes'++const FONT_INTER_URL = 'https://rsms.me/inter/'+const FONT_NAME = 'Inter'++interface ILogoComponent {+ description: string+ logoPNG: string+ logoSVG?: string+}++const LogoComponent = ({ description, logoSVG, logoPNG }: ILogoComponent): JSX.Element => (+ <p>+ <b className='font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ {description}+ </b>+ <img+ className='h-20 mt-5 mb-2'+ src={logoSVG || logoPNG}+ alt={description}+ />+ {logoSVG && (+ <a+ href={logoSVG}+ target='_blank'+ rel='noopener noreferrer'+ className='hover:underline text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'+ >+ SVG+ </a>+ )}+ {logoSVG && logoPNG && (+ <span className='text-gray-900 dark:text-gray-50'> | </span>+ )}+ {logoPNG && (+ <a+ href={logoPNG}+ target='_blank'+ rel='noopener noreferrer'+ className='hover:underline text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'+ >+ PNG+ </a>+ )}+ </p>+)++LogoComponent.defaultProps = {+ logoSVG: null,+}++const Press = (): JSX.Element => {+ const { t }: {+ t: (key: string) => string+ } = useTranslation('common')++ return (+ <Title title={t('titles.press')}>+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>+ <div className='w-11/12 md:w-4/5 mx-auto pb-16 pt-12 px-4 sm:px-6 lg:px-8 whitespace-pre-line'>+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('titles.press')}+ </h1>+ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <Trans+ i18nKey='press.description'+ components={{+ url: <Link to={routes.contact} className='font-medium hover:underline text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' />,+ }}+ />+ </p>++ {/* Logos */}+ <h2 className='text-2xl mt-2 font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('press.logos')}+ </h2>+ <div className='grid grid-cols-2 gap-4 mt-2'>+ <LogoComponent+ description={t('press.logo')}+ logoPNG='/assets/logo_blue.png'+ />+ <LogoComponent+ description={t('press.logoWhiteText')}+ logoPNG='/assets/logo_white.png'+ />+ </div>+ <div className='grid grid-cols-2 gap-4 mt-8'>+ <LogoComponent+ description={t('press.logoNoText')}+ logoPNG='/logo512.png'+ />+ </div>++ {/* Font */}+ <h2 className='text-2xl mt-8 font-bold text-gray-900 dark:text-gray-50 tracking-tight'>+ {t('press.font.title')}+ </h2>+ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <Trans+ i18nKey='press.font.description'+ components={{+ url: <a+ aria-label='Inter font website (opens in a new tab)'+ href={FONT_INTER_URL}+ className='font-medium hover:underline text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'+ target='_blank'+ rel='noopener noreferrer'+ />,+ }}+ values={{+ font: FONT_NAME,+ }}+ />+ </p>+ </div>+ </div>+ </Title>+ )+}++export default Pressdiff --git a/app/pages/Privacy/index.tsx b/app/pages/Privacy/index.tsxnew file mode 100644index 000000000..ec889ba5d--- /dev/null+++ b/app/pages/Privacy/index.tsx@@ -0,0 +1,346 @@+/* eslint-disable react/no-unescaped-entities */+import React from 'react'+import _map from 'lodash/map'++import Title from 'components/Title'+import {+ CONTACT_EMAIL, SECURITY_EMAIL, DOCS_URL,+} from 'redux/constants'++const serviceProviders: {+ company: string+ purpose: string+ dataSubjects: string+ location: string+}[] = [+ {+ company: 'Paddle.com Market Limited',+ purpose: 'Payment and subscriptions',+ dataSubjects: 'Customers',+ location: 'United Kingdom',+ },+ {+ company: 'Fastmail Pty Ltd',+ purpose: 'Business emails',+ dataSubjects: 'Customers',+ location: 'Australia',+ },+ {+ company: 'Cloudflare, Inc.',+ purpose: 'Cloud services',+ dataSubjects: 'Website Visitors, Customers, End Users',+ location: 'United States',+ },+ {+ company: 'Wildbit, LLC (Postmark)',+ purpose: 'Transactional and marketing emails',+ dataSubjects: 'Customers',+ location: 'United States',+ },+ {+ company: 'New Relic, Inc.',+ purpose: 'Error tracking',+ dataSubjects: 'Website Visitors, Customers, End Users',+ location: 'United States',+ },+]++const Features = (): JSX.Element => {+ return (+ <Title title='Privacy Policy'>+ <div className='bg-gray-50 dark:bg-slate-900'>+ <div className='w-11/12 md:w-4/5 mx-auto pb-16 pt-12 px-4 sm:px-6 lg:px-8'>+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50 tracking-tight'>Privacy Policy</h1>+ <p className='mt-4 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ This Swetrix Privacy Policy (βPolicyβ, "Privacy Policy") outlines the personal information that we gather, how we use that personal information, and the options you have to access, correct, or delete such personal information.+ <br />+ By visiting swetrix.com and using the Services provided here, you agree to the terms outlined in this Privacy Policy. Unless otherwise defined in this document, the terms used in this Privacy Policy have the same meanings as in our Terms and Conditions.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>1. Policy application</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ This Privacy Policy applies to the following data subjects:+ <br />++ {'- '}+ <b>Customers:</b>+ {' '}+ Those who register for an account on Swetrix and to whom Swetrix provides its Services. For purposes of this Policy, βServicesβ refers to all of the solutions offered, marketed, or sold by us.+ <br />+ {'- '}+ <b>Website Visitors:</b>+ {' '}+ Those who visit our Websites, which may optionally provide an email address or other information to receive communications from us, or give us feedback. For the purposes of this Policy, βWebsitesβ refer to swetrix.com as well as any other websites we operate on our own behalf and that link to this Policy. For clarity, βWebsitesβ does not include any sites owned or operated by our Customers.+ <br />+ {'- '}+ <b>End Users:</b>+ {' '}+ Those who access or use our Customers websites, networks, APIs, and applications.+ <br />++ This Privacy Policy does not apply to our Customers websites, networks, APIs, and applications, which may have their own terms and privacy policies. Our Customers are solely responsible for establishing policies for and ensuring compliance with all applicable laws and regulations.+ <br />++ Swetrixβs Websites and Services are not intended for, nor designed to attract, individuals under the age of eighteen. Swetrix does not knowingly collect personal information from any person under the age of eighteen. You represent that you are at least 18 or that you are the parent or guardian of such a minor and consent to such minor dependentβs use of the Websites and Services.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>2. Information we collect</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We may collect the following types of data in order to provide and improve our Services:+ <br />+ {'- '}+ <b>Personal Data:</b>+ {' '}+ While using our Services, we may ask you to provide us with certain personally identifiable information that can be used to contact or identify you. Personally identifiable information may include, but is not limited to your name, email address and billing addresses necessary to process payment and delivery of Services.+ <br />+ {'- '}+ <b>Payment Information:</b>+ {' '}+ We do not require our Customers to have payment information on file with us unless they have a paid subscription to our Services.+ <br />+ When you sign up for one of our paid Subscriptions, you must provide payment and billing information. The information you will need to submit depends on which payment method you choose. For clarity, we do not store full credit card numbers or personal account numbers.+ <br />+ {'- '}+ <b>Usage Data:</b>+ {' '}+ When you visit our Websites, we gather certain information and store it in log files to be able to provide you with our Services. This information may include but is not limited to Internet Protocol (IP) addresses, device or system information, URLs of referrer pages, browser information and language preferences.+ <br />+ For clarity, the purpose of these log files is to enable us to operate and provide you with our Services, and to monitor for overall trends on our Websites and for security. These log files are not shared with third parties.+ <br />+ {'- '}+ <b>Cookie Data:</b>+ {' '}+ We use essential cookies on our Websites to provide our Services. Without these cookies, the services that you have asked for cannot be provided, and we only use these cookies to provide you those services.+ <br />+ These cookies are essential for the functioning of our Websites. For example, they help to authenticate you and to prevent fraudulent use of your account.+ <br />+ You can instruct your browser to refuse all cookies or to indicate when a cookie is being sent. However, if you do not accept cookies, you may not be able to use some parts of our Websites and Services.+ <br />+ At this time, our Websites do not respond to Do Not Track beacons sent by browser plugins.+ <br />+ {'- '}+ <b>Log Data:</b>+ {' '}+ We process End Users information on behalf of our Customers. This information is processed when End Users access or use our Customers domains, websites, APIs, applications, devices, endpoints, and networks that use our Services.+ <br />+ The information processed may include but is not limited to IP addresses, device or system information, and other information about the traffic on our Customers websites, devices, applications, and/or networks (collectively, βLog Dataβ). You can find more information on the data collected and how we process it+ {' '}+ <a className='text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500' href={`${DOCS_URL}/swetrix-js-reference#trackviews`} target='_blank' rel='noreferrer noopener'>here</a>+ .+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>3. How we use information we collect</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We only processes personal information in a way that is relevant for the purpose for which it was collected or authorized:+ <br />+ - To enable you to access and use the Websites and Services.+ <br />+ - To operate and improve the Websites and Services.+ <br />+ - To send transactional messages, provide customer support, updates, security alerts, and account related messages.+ <br />+ - To process and complete transactions, and send you related information, including purchase confirmations and invoices.+ <br />+ - To monitor and analyze overall trends, usage, and activities in connection with the Websites and Services.+ <br />+ - To create, publish or send marketing emails, news or advertising material. For clarity, we do not send marketing emails without your explicit consent.+ <br />+ - To comply with legal obligations to investigate and prevent fraudulent transactions, unauthorized access, and other illegal activities.+ <br />+ - To personalize the Websites and Services.+ <br />+ - To process your data for other purposes for which we obtain your consent.+ <br />+ We use and process the Log Data from End Users to fulfill our obligations under our Customer agreements and as may be required by law. We act as a data processor and service provider pursuant to data processing instructions by our Customers.+ <br />+ We may use the Usage and Log Data to assemble non-personally identifiable web traffic reports and statistics. These reports and statistics may be shared with third parties.+ </p>+ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>4. UK and EU residents</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ Please note that the βpersonal informationβ referenced in this Privacy Policy means βpersonal dataβ as that term is defined under the European Union (βEUβ) General Data Protection Regulations (βGDPRβ) and its United Kingdom (βUKβ) GDPR counterpart. Swetrix is the data controller for the Personal Data of Customers and Website Visitors, but not for the Personal Data of End Users. We process the Personal Data of End Users on behalf of our Customers.+ <br />+ If you are an individual from the European Economic Area (the βEEAβ), the UK or Switzerland, please note that our legal basis for collecting and using your personal information will depend on the personal information collected and the specific context in which we collect it.+ <br />+ However, we will normally collect personal data from you only (i) where the processing is in our legitimate interests and not overridden by your rights; (ii) where we need the personal data to perform a contract with you or (iii) where we have your consent to do so. In some cases, we may also have a legal obligation to collect personal data from you.+ <br />+ Please note that in most cases, if you do not provide the requested information, we will not be able to provide the requested service to you. In some cases, we may also have a legal obligation to collect personal information from you, or may need the personal information to protect your vital interests or those of another person.+ <br />+ Where we rely on your consent to process your personal data, you have the right to withdraw or decline consent at any time. Where we rely on our legitimate interests to process your personal data, you have the right to object.+ <br />+ If you have any questions about or need further information concerning the legal basis on which we collect and use your personal information, please contact us at + <a href={`mailto:${CONTACT_EMAIL}`} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'>+ {CONTACT_EMAIL}+ </a>+ .+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>5. California Residents</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We do not sell, rent, or share personal information with third parties as defined under the California Consumer Privacy Act of 2018 (California Civil Code Sec. 1798.100 et seq.), nor do we sell, rent, or share personal information with third parties for their direct marketing purposes as defined under California Civil Code Sec. 1798.83.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>6. Retention of data</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We may retain your information for as long as your account is active or as needed to provide you services, comply with our legal obligations, resolve disputes and enforce our agreements. In certain circumstances we may be required by law to retain your personal information, or may need to retain your personal information in order to continue providing a service.+ <br />+ Even if you delete your account, keep in mind that the deletion by our third party providers may not be immediate and that the deleted information may persist in backup copies for a reasonable period of time.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>7. Transfer of data</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ Your information, including Personal Data, may be transferred to β and maintained on β computers located outside of your state, province, country or other governmental jurisdiction where the data protection laws may differ from those in your jurisdiction. If you are located outside Germany and choose to provide information to us, please note that we transfer the data, including Personal Data, to Germany and process it there.+ <br />+ Your consent to this Privacy Policy followed by your submission of such information represents your agreement to that transfer. We will take all steps reasonably necessary to ensure that your data is treated securely and in accordance with this Privacy Policy and no transfer of your Personal Data will take place to an organization or a country unless there are adequate controls in place including the security of your data and other personal information.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>8. Information sharing</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We do not sell or rent personal information.+ <br />+ We may disclose personal information to service providers who help us run the Services and our business (βService Providersβ). These Service Providers may only process personal information pursuant to our instructions and in compliance both with this Privacy Policy and other applicable security measures and regulations.+ <br />+ {/* Before engaging any Service Provider, we perform due diligence, including a security assessment. Our Service Providers are subject to strict contract terms designed to ensure that these Service Providers process personal data only for the purposes of providing services to Swetrix and in accordance with our commitments to applicable data protection laws.+ <br /> */}+ The following Service Providers may be considered our "sub-processors" under GDPR. We only share what's required for their purpose.+ <br />+ <div className='mt-8 flex flex-col'>+ <div className='-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8'>+ <div className='inline-block min-w-full py-2 align-middle md:px-6 lg:px-8'>+ <div className='overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg'>+ <table className='min-w-full divide-y divide-gray-300 200 dark:divide-gray-500'>+ <thead className='bg-gray-50 dark:bg-slate-800'>+ <tr>+ <th scope='col' className='py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 dark:text-gray-50 sm:pl-6'>+ Company+ </th>+ <th scope='col' className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'>+ Purpose+ </th>+ <th scope='col' className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'>+ Data subjects+ </th>+ <th scope='col' className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'>+ Corporate location+ </th>+ </tr>+ </thead>+ <tbody className='divide-y divide-gray-200 dark:divide-gray-600 bg-white dark:bg-slate-800'>+ {_map(serviceProviders, ({+ company, purpose, dataSubjects, location,+ }) => (+ <tr key={company}>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-gray-50 sm:pl-6'>{company}</td>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-gray-50'>{purpose}</td>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-gray-50'>{dataSubjects}</td>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-gray-50'>{location}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ </div>+ </div>+ <br />+ In addition to sharing with Service Providers as described above, we also may share your information with others in the following circumstances:+ <br />+ - In the event of a merger, sale, change in control, or reorganization of all or part of our business.+ <br />+ - When we are required to disclose personal information to respond to subpoenas, court orders, or legal process, or to establish or exercise our legal rights or defend against legal claims.+ <br />+ - Where we have a good-faith belief sharing is necessary to investigate, prevent or take action regarding illegal activities, suspected fraud, situations involving potential threats to the physical safety of any person, or violations of our Terms and Conditions, or as otherwise required to comply with our legal obligations.+ <br />+ - Other purposes for which we obtain your consent.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>9. Data subject rights</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We would like to make sure you are fully aware of all of your data protection rights. In certain circumstances, you have the following data protection rights:+ <br />+ {'- '}+ <b>The right to access:</b>+ {' '}+ You have the right to request our Company for copies of your personal data.+ <br />+ {'- '}+ <b>The right to rectification:</b>+ {' '}+ You have the right to request that our Company corrects any information you believe is inaccurate. You also have the right to request our Company to complete the information you believe is incomplete.+ <br />+ {'- '}+ <b>The right to erasure:</b>+ {' '}+ You have the right to request that our Company erases your personal data, under certain conditions.+ <br />+ {'- '}+ <b>The right to restrict processing:</b>+ {' '}+ You have the right to request that our Company restricts the processing of your personal data, under certain conditions.+ <br />+ {'- '}+ <b>The right to object to processing:</b>+ {' '}+ You have the right to object to our Company's processing of your personal data, under certain conditions.+ <br />+ {'- '}+ <b>The right to data portability:</b>+ {' '}+ You have the right to request that our Company transfers the data that we have collected to another organization, or directly to you, under certain conditions.+ <br />+ If you make a request, we have one month to respond to you. If you would like to exercise any of these rights, please contact us via email at + <a href={`mailto:${CONTACT_EMAIL}`} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'>+ {CONTACT_EMAIL}+ </a>+ . Please note that we may ask you to verify your identity before responding to such requests.+ <br />+ We have no direct relationship with the End Users. Our Customers are solely responsible for ensuring compliance with all applicable laws and regulations with respect to their website users.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>10. Communication preferences</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ Swetrix will send you commercial communications based on the communication preferences in your account settings. Swetrix also will send you service-related communications. You may manage your receipt of commercial communications by clicking on the βunsubscribeβ link located on the bottom of such emails, through your account settings if you have a Swetrix account, or you may send a request to + <a href={`mailto:${CONTACT_EMAIL}`} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'>+ {CONTACT_EMAIL}+ </a>+ .+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>11. Data security</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We take all reasonable steps to protect information we receive from you from loss, misuse or unauthorized access, disclosure, alteration and/or destruction. We have put in place appropriate physical, technical and administrative measures to safeguard and secure your information, and we make use of privacy-enhancing technologies such as encryption. If you have any questions about the security of your personal information, you can contact us at + <a href={`mailto:${CONTACT_EMAIL}`} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'>+ {SECURITY_EMAIL}+ </a>+ .+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>12. Notification of changes</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ If we make changes to this Policy that we believe materially impact the privacy of your personal information, we will promptly provide notice of any such changes (and, where necessary, obtain consent), as well as post the updated Policy on this website noting the date of any changes via the "Last updated" date at the bottom of this Privacy Policy. We encourage you to periodically review this page for the latest information on our privacy practices.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>13. Business transactions</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We may assign or transfer this Policy, as well as information covered by this Policy, in the event of a merger, sale, change in control, or reorganization of all or part of our business.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>14. Contact</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ If you have any questions about this Privacy Policy, you can contact us by email at + <a href={`mailto:${CONTACT_EMAIL}`} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'>+ {CONTACT_EMAIL}+ </a>+ .+ </p>++ <hr className='mt-10 mb-4 border-gray-200 dark:border-gray-600' />+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <i>Last updated: August 14, 2022.</i>+ </p>+ </div>+ </div>+ </Title>+ )+}++export default Featuresdiff --git a/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.container.tsx b/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.container.tsxnew file mode 100644index 000000000..f8cc6322e--- /dev/null+++ b/app/pages/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/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx b/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsxnew file mode 100644index 000000000..c2eb66516--- /dev/null+++ b/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx@@ -0,0 +1,384 @@+/* eslint-disable react/forbid-prop-types */+import React, { useEffect, useMemo, useState } from 'react'+import { useHistory, useParams, useLocation } from 'react-router-dom'+import { useTranslation, Trans } from 'react-i18next'+import { ExclamationTriangleIcon } from '@heroicons/react/24/outline'+import { HashLink } from 'react-router-hash-link'+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 Title from 'components/Title'+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 'routes'+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 history = useHistory()+ 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) => {+ history.push(`/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) => {+ history.push(`/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)+ history.push(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)+ generateAlerts(t('alertsSettings.alertDeleted'))+ })+ .catch((err) => {+ showError(err.message || err || 'Something went wrong')+ })+ }++ const onCancel = () => {+ history.push(`/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 (+ <Title title={title}>+ <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: <HashLink 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>+ </Title>+ )+}++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/pages/Project/Alerts/Settings/index.tsx b/app/pages/Project/Alerts/Settings/index.tsxnew file mode 100644index 000000000..6a9cc75cf--- /dev/null+++ b/app/pages/Project/Alerts/Settings/index.tsx@@ -0,0 +1,3 @@+import ProjectAlertsSettings from './ProjectAlertsSettings.container'++export default ProjectAlertsSettingsdiff --git a/app/pages/Project/Alerts/View/ProjectAlertsView.container.tsx b/app/pages/Project/Alerts/View/ProjectAlertsView.container.tsxnew file mode 100644index 000000000..892c5b14f--- /dev/null+++ b/app/pages/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/pages/Project/Alerts/View/ProjectAlertsView.tsx b/app/pages/Project/Alerts/View/ProjectAlertsView.tsxnew file mode 100644index 000000000..a07da9e43--- /dev/null+++ b/app/pages/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 { useHistory } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import PropTypes from 'prop-types'+import {+ BellIcon, CurrencyDollarIcon, PencilSquareIcon, FolderPlusIcon,+} from '@heroicons/react/24/outline'++import routes from 'routes'+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 history = useHistory()++ // @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+ }++ history.push(_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={() => {+ history.push(_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/pages/Project/Alerts/View/index.tsx b/app/pages/Project/Alerts/View/index.tsxnew file mode 100644index 000000000..1f8582931--- /dev/null+++ b/app/pages/Project/Alerts/View/index.tsx@@ -0,0 +1,3 @@+import ProjectAlertsView from './ProjectAlertsView.container'++export default ProjectAlertsViewdiff --git a/app/pages/Project/ConfirmShare/index.tsx b/app/pages/Project/ConfirmShare/index.tsxnew file mode 100644index 000000000..7ace398dc--- /dev/null+++ b/app/pages/Project/ConfirmShare/index.tsx@@ -0,0 +1,114 @@+import React, { useState, useEffect, memo } from 'react'+import { useDispatch } from 'react-redux'+import { useParams, Link } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'+import _split from 'lodash/split'++import Title from 'components/Title'+import sagaActions from 'redux/sagas/actions'+import Loader from 'ui/Loader'+import routes from 'routes'+import { AppDispatch } from 'redux/store'++const ConfirmShare = () => {+ 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 (+ <Title title={t('titles.invitation')}>+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>+ <Loader />+ </div>+ </Title>+ )+ }++ if (error) {+ return (+ <Title title={t('titles.invitation')}>+ <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>+ </Title>+ )+ }++ return (+ <Title title={t('titles.invitation')}>+ <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>+ </Title>+ )+}++export default memo(ConfirmShare)diff --git a/app/pages/Project/ProjectProtectedPassword/index.tsx b/app/pages/Project/ProjectProtectedPassword/index.tsxnew file mode 100644index 000000000..e747e3d56--- /dev/null+++ b/app/pages/Project/ProjectProtectedPassword/index.tsx@@ -0,0 +1,149 @@+import React, { useState, useEffect, memo } from 'react'+import { useHistory, useParams } from 'react-router-dom'+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 Title from 'components/Title'+import routes from 'routes'+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 history = useHistory()+ 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,+ }))+ history.push(_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 = () => {+ history.push(routes.main)+ }++ return (+ <Title title={t('titles.passwordProtected')}>+ <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>+ </Title>+ )+}++export default memo(ProjectProtectedPassword)diff --git a/app/pages/Project/Settings/Emails/ConfirmReportsShare/index.tsx b/app/pages/Project/Settings/Emails/ConfirmReportsShare/index.tsxnew file mode 100644index 000000000..42655524b--- /dev/null+++ b/app/pages/Project/Settings/Emails/ConfirmReportsShare/index.tsx@@ -0,0 +1,119 @@+import React, { useState, useEffect, memo } from 'react'+import { useParams, Link } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'++import Title from 'components/Title'+import Loader from 'ui/Loader'++import { confirmSubscriberInvite } from 'api'+import routes from 'routes'++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 (+ <Title title={t('titles.invitation')}>+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>+ <Loader />+ </div>+ </Title>+ )+ }++ if (error) {+ return (+ <Title title={t('titles.invitation')}>+ <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>+ </Title>+ )+ }++ return (+ <Title title={t('titles.invitation')}>+ <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>+ </Title>+ )+}++export default memo(ConfirmReportsShare)diff --git a/app/pages/Project/Settings/Emails/Emails.container.tsx b/app/pages/Project/Settings/Emails/Emails.container.tsxnew file mode 100644index 000000000..0eb84826b--- /dev/null+++ b/app/pages/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/pages/Project/Settings/Emails/Emails.tsx b/app/pages/Project/Settings/Emails/Emails.tsxnew file mode 100644index 000000000..728a1cb13--- /dev/null+++ b/app/pages/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 Emailsdiff --git a/app/pages/Project/Settings/Emails/index.tsx b/app/pages/Project/Settings/Emails/index.tsxnew file mode 100644index 000000000..df0c540c1--- /dev/null+++ b/app/pages/Project/Settings/Emails/index.tsx@@ -0,0 +1,3 @@+import Emails from './Emails.container'++export default Emailsdiff --git a/app/pages/Project/Settings/People/People.container.tsx b/app/pages/Project/Settings/People/People.container.tsxnew file mode 100644index 000000000..d39372375--- /dev/null+++ b/app/pages/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/pages/Project/Settings/People/People.tsx b/app/pages/Project/Settings/People/People.tsxnew file mode 100644index 000000000..63c689242--- /dev/null+++ b/app/pages/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 Peoplediff --git a/app/pages/Project/Settings/People/index.tsx b/app/pages/Project/Settings/People/index.tsxnew file mode 100644index 000000000..e1573d0ef--- /dev/null+++ b/app/pages/Project/Settings/People/index.tsx@@ -0,0 +1,3 @@+import People from './People.container'++export default Peoplediff --git a/app/pages/Project/Settings/ProjectSettings.container.tsx b/app/pages/Project/Settings/ProjectSettings.container.tsxnew file mode 100644index 000000000..330ffd3a1--- /dev/null+++ b/app/pages/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/pages/Project/Settings/ProjectSettings.tsx b/app/pages/Project/Settings/ProjectSettings.tsxnew file mode 100644index 000000000..0862b5092--- /dev/null+++ b/app/pages/Project/Settings/ProjectSettings.tsx@@ -0,0 +1,654 @@+/* eslint-disable react/forbid-prop-types */+import React, {+ useState, useEffect, useMemo, memo,+} from 'react'+import { useLocation, useHistory, useParams } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import cx from 'clsx'+import _isEmpty from 'lodash/isEmpty'+import _size from 'lodash/size'+import _replace from 'lodash/replace'+import _find from 'lodash/find'+import _join from 'lodash/join'+import _isString from 'lodash/isString'+import _split from 'lodash/split'+import _keys from 'lodash/keys'+import _map from 'lodash/map'+import _includes from 'lodash/includes'+import PropTypes from 'prop-types'+import { ExclamationTriangleIcon, TrashIcon, RocketLaunchIcon } from '@heroicons/react/24/outline'++import Title from 'components/Title'+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 'routes'+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 history = useHistory()++ 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'))+ history.push(routes.dashboard)+ }++ if (!isLoading && isSettings && !projectDeleting) {+ if (_isEmpty(project) || project?.uiHidden) {+ showError(t('project.noExist'))+ history.push(routes.dashboard)+ } else {+ setForm({+ ...project,+ ipBlacklist: _isString(project.ipBlacklist) ? project.ipBlacklist : _join(project.ipBlacklist, ', '),+ origins: _isString(project.origins) ? project.origins : _join(project.origins, ', '),+ })+ }+ }+ }, [user, project, isLoading, isSettings, history, showError, projectDeleting, t])++ const onSubmit = async (data: 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'))+ history.push(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'))+ history.push(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 = () => {+ history.push(isSettings ? _replace(routes.project, ':id', id) : routes.dashboard)+ }++ const onTransfer = async () => {+ await transferProject(id, transferEmail)+ .then(() => {+ generateAlerts(t('apiNotifications.transferRequestSent'))+ history.push(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 (+ <Title title={title}>+ <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>+ </Title>+ )+}++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/pages/Project/Settings/TransferProject/TransferProjectConfirm.tsx b/app/pages/Project/Settings/TransferProject/TransferProjectConfirm.tsxnew file mode 100644index 000000000..f10c41d6e--- /dev/null+++ b/app/pages/Project/Settings/TransferProject/TransferProjectConfirm.tsx@@ -0,0 +1,116 @@+import React, { useState, useEffect, memo } from 'react'+import { Link } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'++import Title from 'components/Title'+import Loader from 'ui/Loader'++import { confirmTransferProject } from 'api'+import routes from 'routes'++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 (+ <Title title={t('titles.invitation')}>+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>+ <Loader />+ </div>+ </Title>+ )+ }++ if (error) {+ return (+ <Title title={t('titles.invitation')}>+ <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>+ </Title>+ )+ }++ return (+ <Title title={t('titles.invitation')}>+ <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>+ </Title>+ )+}++export default memo(TransferProjectConfirm)diff --git a/app/pages/Project/Settings/TransferProject/TransferProjectReject.tsx b/app/pages/Project/Settings/TransferProject/TransferProjectReject.tsxnew file mode 100644index 000000000..8c38240d2--- /dev/null+++ b/app/pages/Project/Settings/TransferProject/TransferProjectReject.tsx@@ -0,0 +1,116 @@+import React, { useState, useEffect, memo } from 'react'+import { Link } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { XCircleIcon, InformationCircleIcon } from '@heroicons/react/24/solid'++import Title from 'components/Title'+import Loader from 'ui/Loader'++import { rejectTransferProject } from 'api'+import routes from 'routes'++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 (+ <Title title={t('titles.invitation')}>+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>+ <Loader />+ </div>+ </Title>+ )+ }++ if (error) {+ return (+ <Title title={t('titles.invitation')}>+ <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>+ </Title>+ )+ }++ return (+ <Title title={t('titles.invitation')}>+ <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>+ </Title>+ )+}++export default memo(TransferProjectReject)diff --git a/app/pages/Project/Settings/index.tsx b/app/pages/Project/Settings/index.tsxnew file mode 100644index 000000000..91c7f9508--- /dev/null+++ b/app/pages/Project/Settings/index.tsx@@ -0,0 +1,3 @@+import ProjectSettings from './ProjectSettings.container'++export default ProjectSettingsdiff --git a/app/pages/Project/View/Panels.tsx b/app/pages/Project/View/Panels.tsxnew file mode 100644index 000000000..6a0f9b580--- /dev/null+++ b/app/pages/Project/View/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}+ + </>+ )}+ {name}+ </h3>+ <div className='flex'>+ {(checkIfBarsNeeded(type) || checkCustomTabs(type, customTabs)) && (+ <Bars4Icon+ className={cx(iconClassName, 'cursor-pointer', {+ 'text-slate-900 dark:text-gray-50': activeFragment === 0,+ 'text-slate-400 dark:text-slate-500': activeFragment === 1,+ })}+ onClick={() => setActiveFragment(0)}+ />+ )}++ {/* if it is a Country tab */}+ {type === 'cc' && (+ <>+ <MapIcon+ className={cx(iconClassName, 'ml-2 cursor-pointer', {+ 'text-slate-900 dark:text-gray-50': activeFragment === 1,+ 'text-slate-400 dark:text-slate-500': activeFragment === 0,+ })}+ onClick={() => setActiveFragment(1)}+ />+ <ArrowsPointingOutIcon+ className={cx(iconClassName, 'ml-2 cursor-pointer text-slate-400 dark:text-slate-500', {+ hidden: activeFragment === 0,+ })}+ onClick={openModal}+ />+ </>+ )}++ {(type === 'pg' && activeTab !== PROJECT_TABS.performance) && (+ <>+ <RectangleGroupIcon+ className={cx(iconClassName, 'ml-2 cursor-pointer', {+ 'text-slate-900 dark:text-gray-50': activeFragment === 1,+ 'text-slate-400 dark:text-slate-500': 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-slate-900 dark:text-gray-50': activeFragment === 1,+ 'text-slate-400 dark:text-slate-500': activeFragment === 0,+ })}+ onClick={() => setActiveFragment(1)}+ />+ )}+ {checkCustomTabs(type, customTabs) && (+ <>+ {_map(customTabs, ({ extensionID, panelID }) => (+ <PuzzlePieceIcon+ key={`${extensionID}-${panelID}`}+ className={cx(iconClassName, 'ml-2 cursor-pointer', {+ 'text-slate-900 dark:text-gray-50': activeFragment === extensionID,+ 'text-slate-400 dark:text-slate-500': 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'>+ + {activePeriod.label}+ </span>+ {isActiveCompare && (+ // return vs activeDropdownLabelCompare+ <span className='text-sm text-gray-500 dark:text-gray-400'>+ (+ {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'>+ (+ {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}+ />+ + </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]}+ + </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}+ + <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/pages/Project/View/ViewProject.container.tsx b/app/pages/Project/View/ViewProject.container.tsxnew file mode 100644index 000000000..77881d5e4--- /dev/null+++ b/app/pages/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/pages/Project/View/ViewProject.helpers.tsx b/app/pages/Project/View/ViewProject.helpers.tsxnew file mode 100644index 000000000..d3d7ed4ce--- /dev/null+++ b/app/pages/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/pages/Project/View/ViewProject.tsx b/app/pages/Project/View/ViewProject.tsxnew file mode 100644index 000000000..32b18f140--- /dev/null+++ b/app/pages/Project/View/ViewProject.tsx@@ -0,0 +1,2487 @@+/* eslint-disable react/forbid-prop-types, react/no-unstable-nested-components, react/display-name */+import React, {+ useState, useEffect, useMemo, memo, useRef, Fragment, useCallback,+} from 'react'+import useSize from 'hooks/useSize'+import { useHistory, useParams, Link } from 'react-router-dom'+// @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 Title from 'components/Title'+import EventsRunningOutBanner from 'components/EventsRunningOutBanner'+import {+ tbPeriodPairs, getProjectCacheKey, LIVE_VISITORS_UPDATE_INTERVAL, DEFAULT_TIMEZONE, CDN_URL, isDevelopment,+ timeBucketToDays, getProjectCacheCustomKey, roleViewer, MAX_MONTHS_IN_PAST, 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 'routes'+import {+ getProjectData, getProject, getOverallStats, getLiveVisitors, getPerfData, getProjectDataCustomEvents, getProjectCompareData, checkPassword,+} from 'api'+import { getChartPrediction } from 'api/ai'+import {+ Panel, Overview, CustomEvents,+} from './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.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()+ // history is a history from react-router-dom+ const history = useHistory()++ // 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) {+ history.push(_replace(routes.project, ':id', id))+ return+ }++ showError(t('apiNotifications.incorrectPassword'))+ history.push(_replace(routes.project_protected_password, ':id', id))+ removeItem(PROJECTS_PROTECTED)+ })+ return+ }++ showError(t('project.noExist'))+ history.push(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, newFilters || filters)+ } 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, newFilters || filters)+ }+ }++ if (!_isEmpty(fromCompare) && !_isEmpty(toCompare)) {+ if (!_isEmpty(cache[id]) && !_isEmpty(cache[id][keyCompare])) {+ 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, newFilters || filters)+ } else {+ key = getProjectCacheKey(period, timeBucket, newFilters || filters)+ }++ // check if we need to load new date or we have data in redux/localstorage+ if ((!forced && !_isEmpty(cache[id]) && !_isEmpty(cache[id][key]))) {+ data = cache[id][key]+ } else {+ if (period === 'custom' && dateRange) {+ data = await getProjectData(id, timeBucket, '', newFilters || filters, from, to, timezone, 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, newFilters || filtersPerf)+ } 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, newFilters || filtersPerf)+ }+ }++ if (!_isEmpty(fromCompare) && !_isEmpty(toCompare)) {+ if (!_isEmpty(cache[id]) && !_isEmpty(cache[id][keyCompare])) {+ 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, newFilters || filtersPerf)+ } else {+ key = getProjectCacheKey(period, timeBucket, newFilters || filtersPerf)+ }++ 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+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ 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+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ setFiltersPerf(newFiltersPerf)+ }+ } else {+ // eslint-disable-next-line no-lonely-if+ if (_find(filters, (f) => f.column === column) /* && f.filter === filter) */) {+ // selected filter is already included into the filters array -> removing it+ // removing filter from the state+ newFilters = _filter(filters, (f) => f.column !== column)+ setFilters(newFilters)++ // removing filter from the page URL++ // @ts-ignore+ const url = new URL(window.location)+ url.searchParams.delete(column)+ const { pathname, search } = url+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ } else {+ // selected filter is not present in the filters array -> applying it+ // sroting filter in the state+ newFilters = [+ ...filters,+ { column, filter, isExclusive },+ ]+ setFilters(newFilters)++ // storing filter in the page URL++ // @ts-ignore+ const url = new URL(window.location)+ url.searchParams.append(column, filter)+ const { pathname, search } = url+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ }+ }++ sdkInstance?._emitEvent('filtersupdate', newFilters)+ if (activeTab === PROJECT_TABS.performance) {+ loadAnalyticsPerf(true, newFiltersPerf)+ } else {+ loadAnalytics(true, newFilters)+ }+ }++ // this function is used for requesting the data from the API when the exclusive filter is changed+ const onChangeExclusive = (column: 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+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ 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, filters)+ 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+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ // 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+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ setTimebucket(eventEmitTimeBucket)+ }++ url.searchParams.delete('period')+ url.searchParams.delete('from')+ url.searchParams.delete('to')+ url.searchParams.append('period', 'custom')+ url.searchParams.append('from', dates[0].toISOString())+ url.searchParams.append('to', dates[1].toISOString())++ const { pathname, search } = url+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })++ setPeriodPairs(tbPeriodPairs(t, timeBucketToDays[index].tb, dates))+ setPeriod('custom')+ setProjectViewPrefs(id, 'custom', timeBucketToDays[index].tb[0], dates)++ sdkInstance?._emitEvent('timeupdate', {+ period: 'custom',+ timeBucket: eventEmitTimeBucket,+ dateRange: dates,+ })++ break+ }+ }+ }++ // useEffect 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)) {+ history.push(_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+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ 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+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ setTimebucket(newTimebucket)+ setProjectViewPrefs(id, period, newTimebucket, dateRange as Date[])+ sdkInstance?._emitEvent('timeupdate', {+ period,+ timeBucket: newTimebucket,+ dateRange,+ })+ setForecasedChartData({})+ }++ const openSettingsHandler = () => {+ history.push(_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+ history.push({+ pathname,+ search,+ state: {+ scrollToTopDisable: true,+ },+ })+ setFilters([])+ setFiltersPerf([])+ if (activeTab === PROJECT_TABS.performance) {+ loadAnalyticsPerf(true, [])+ } else {+ loadAnalytics(true, [])+ }+ }++ const exportTypes = [+ { label: t('project.asImage'), onClick: exportAsImageHandler },+ {+ label: t('project.asCSV'),+ onClick: () => {+ if (activeTab === PROJECT_TABS.performance) {+ return onCSVExportClick(panelsDataPerf, id, tnMapping, language)+ }+ return onCSVExportClick(panelsData, id, tnMapping, language)+ },+ },+ ]++ // function set chart type and save to local storage+ const setChartTypeOnClick = (type: 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 (+ <Title title={pageTitle}>+ <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-slate-900 text-slate-900 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-slate-900 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-slate-900 dark:text-gray-50 shadow-md': chartType === chartTypes.bar,+ 'text-slate-500 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-slate-900 dark:text-gray-50 shadow-md': chartType === chartTypes.line,+ 'text-slate-500 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 dark:bg-slate-800'>+ <div className='first dark:bg-slate-600' />+ <div className='second dark:bg-slate-600' />+ </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 dark:bg-slate-800'>+ <div className='first dark:bg-slate-600' />+ <div className='second dark:bg-slate-600' />+ </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}+ />+ </Title>+ )+ }++ return (+ <Title title={name}>+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>+ <Loader />+ </div>+ </Title>+ )+}++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/pages/Project/View/components/CCRow.tsx b/app/pages/Project/View/components/CCRow.tsxnew file mode 100644index 000000000..bed9f85f1--- /dev/null+++ b/app/pages/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'+ />+ + {countries.getName(rowName, language)}+ </>+)++CCRow.propTypes = {+ rowName: PropTypes.string.isRequired,+ language: PropTypes.string.isRequired,+}++export default memo(CCRow)diff --git a/app/pages/Project/View/components/Filters.tsx b/app/pages/Project/View/components/Filters.tsxnew file mode 100644index 000000000..30299d6f0--- /dev/null+++ b/app/pages/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}+ + <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>+ + "+ {displayFilter}+ "+ <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/pages/Project/View/components/InteractiveMap.tsx b/app/pages/Project/View/components/InteractiveMap.tsxnew file mode 100644index 000000000..f865bea10--- /dev/null+++ b/app/pages/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')}+ :+ + <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/pages/Project/View/components/LiveVisitorsDropdown.tsx b/app/pages/Project/View/components/LiveVisitorsDropdown.tsxnew file mode 100644index 000000000..9c48b80e4--- /dev/null+++ b/app/pages/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 LiveVisitorsDropdowndiff --git a/app/pages/Project/View/components/NoEvents.tsx b/app/pages/Project/View/components/NoEvents.tsxnew file mode 100644index 000000000..9ff75e1d5--- /dev/null+++ b/app/pages/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/pages/Project/View/components/RefRow.tsx b/app/pages/Project/View/components/RefRow.tsxnew file mode 100644index 000000000..bee34ee08--- /dev/null+++ b/app/pages/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/pages/Project/View/components/UserFlow.tsx b/app/pages/Project/View/components/UserFlow.tsxnew file mode 100644index 000000000..d3aa1bbc7--- /dev/null+++ b/app/pages/Project/View/components/UserFlow.tsx@@ -0,0 +1,218 @@+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, filters: any) => {+ dispatch(UIActions.setUserFlowAscending({+ data,+ pid,+ period,+ filters,+ }))+ },+ setUserFlowDescending: (data: IUserFlow, pid: string, period: string, filters: any) => {+ dispatch(UIActions.setUserFlowDescending({+ data,+ pid,+ period,+ filters,+ }))+ },+ 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, fltr: any) => void+ setUserFlowDescending: (data: IUserFlow, id: string, pd: string, fltr: any) => void+ generateError: (message: string) => void+ t: (key: string) => string+ filters: string[]+ setReversed: () => void+ password: {+ [key: string]: string+ }+}) => {+ const key = getUserFlowCacheKey(pid, period, filters)+ 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, filters)+ setUserFlowDescending(descending, pid, period, filters)+ })+ .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/pages/Project/View/index.tsx b/app/pages/Project/View/index.tsxnew file mode 100644index 000000000..9bb6ff2df--- /dev/null+++ b/app/pages/Project/View/index.tsx@@ -0,0 +1,3 @@+import ViewProject from './ViewProject.container'++export default ViewProjectdiff --git a/app/pages/Project/View/styles.css b/app/pages/Project/View/styles.cssnew file mode 100644index 000000000..4033bbaf4--- /dev/null+++ b/app/pages/Project/View/styles.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/pages/Terms/index.tsx b/app/pages/Terms/index.tsxnew file mode 100644index 000000000..589b34390--- /dev/null+++ b/app/pages/Terms/index.tsx@@ -0,0 +1,199 @@+/* eslint-disable react/no-unescaped-entities */+import React from 'react'++import Title from 'components/Title'+import { CONTACT_EMAIL } from 'redux/constants'++const Features = (): JSX.Element => {+ return (+ <Title title='Terms and Conditions'>+ <div className='bg-gray-50 dark:bg-slate-900'>+ <div className='w-11/12 md:w-4/5 mx-auto pb-16 pt-12 px-4 sm:px-6 lg:px-8'>+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50 tracking-tight'>Swetrix Terms and Conditions</h1>+ <p className='mt-4 text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ These Swetrix Terms and Conditions ("Terms", "Terms and Conditions") govern your relationship with swetrix.com ("Service") operated by Andrii Romasiun ("Swetrix", "Swetrix Analytics", "Company", "us", "we", or "our").+ <br />+ Please read these Terms and Conditions carefully before using the Service.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Acknowledgment</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ These are the Terms and Conditions governing the use of this Service and the agreement that operates between you and us. These Terms and Conditions set out the rights and obligations of all users regarding the use of the Service.+ <br />+ Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms and Conditions. These Terms and Conditions apply to all visitors, users and others who access or use the Service.+ <br />+ By accessing or using the Service you agree to be bound by these Terms and Conditions. If you disagree with any part of these Terms and Conditions then you may not access the Service.+ <br />+ Your access to and use of the Service is also conditioned on your acceptance of and compliance with our Privacy Policy. Our Privacy Policy describes our policies and procedures on the collection, use and disclosure of your personal information when you access our websites or use our Service and tells you about your privacy rights and how the law protects you. Please read Our Privacy Policy carefully before using our Service.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Eligibility</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ By agreeing to these Terms, you represent and warrant to us: (i) that you are at least eighteen (18) years of age; (ii) that you have not previously been suspended or removed from our Service and (iii) that your use of our Service is in compliance with any and all applicable laws and regulations.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Indemnity</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ You agree that you will be responsible for your use of the Service, and you agree to defend, indemnify, and us hold harmless and our officers, directors, employees, consultants, affiliates, subsidiaries and agents (collectively, the "Company Entities") from and against any and all claims, liabilities, damages, losses, and expenses, including reasonable attorneys' fees and costs, arising out of or in any way connected with (i) your access to, use of, or alleged use of the Service; (ii) your violation of these Terms or any representation, warranty, or agreements referenced herein, or any applicable law or regulation; (iii) your violation of any third-party right, including without limitation any intellectual property right, publicity, confidentiality, property or privacy right; or (iv) any disputes or issues between you and any third party. We reserve the right, at our own expense, to assume the exclusive defense and control of any matter otherwise subject to indemnification by you (and without limiting your indemnification obligations with respect to such matter), and in such case, you agree to cooperate with our defense of such claim.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Termination</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We may at our sole discretion suspend or terminate your access to our Service at any time, with or without notice for any reason or no reason at all. We also reserve the right to modify or discontinue the Service at any time (including, without limitation, by limiting or discontinuing certain features of the Service) without notice to you. We will have no liability whatsoever on account of any change to the Service or any suspension or termination of your access to or use of the Service.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Fair use</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We will use commercially reasonable efforts to provide all plan levels with sufficient capacity for the analytics data, number of websites, and other plan features that we determine are typical of accounts at that plan level. We may notify you if your usage is unreasonable, and we may at our sole discretion and at any time shut down and terminate our Service if your usage is creating an unreasonable burden on our infrastructure and/or business operations.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Third-party websites</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ The Service may contain links to third-party websites or services that are not owned or controlled by us.+ <br />+ We have no control over, and assume no responsibility for, the content, privacy policies, or practices of any third party websites or services. You further acknowledge and agree that the Company shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with the use of or reliance on any such content, goods or services available on or through any such websites or services.+ <br />+ We strongly advise you to read the terms and conditions and privacy policies of any third-party websites or services that you visit.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>License grant to us</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ By submitting, posting, or publishing your content, suggestions, enhancement requests, recommendations, feedback, information, data, or comments (βContentβ) to our Service, you are granting us a perpetual, irrevocable, worldwide, non-exclusive, royalty-free right and license (with the right to sublicense) to use, incorporate, exploit, display, perform, reproduce, distribute, and prepare derivative works of your Content. You will retain ownership of your Content, however, any use of your Content by us may be without any compensation paid to you. By submitting, posting, and publishing your Content, you represent and warrant that your Content, does not: (i) infringe, violate, or misappropriate any third-party right, including any copyright, trademark, patent, trade secret, moral right, privacy right, right of publicity, or any other intellectual property or proprietary right; or (ii) slander, defame, or libel any third-party.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Prohibited uses</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ As a condition of your use of the Service, you will not use the Service for any purpose that is unlawful or prohibited by these Terms. You may not use the Service in any manner that could damage, disable, overburden, disrupt or impair any of our servers or APIs, or any networks connected to any of our server or APIs, or that could interfere with any other party's use and enjoyment of any Service. You may not transmit any viruses, worms, defects, Trojan horses, or any items of a destructive nature through your use of Service. You may not exceed or circumvent, or try to exceed or circumvent, limitations on the Service, including on any API calls, or otherwise use the Service in a manner that violates any Swetrix documentation or user manuals. You may not attempt to gain unauthorized access to any Service, other accounts, computer systems, or networks connected to any Swetrix server or to any of the Service through hacking, password mining, or any other means. You may not obtain or attempt to obtain any materials or information through any means not intentionally made available through the Service. You may not use the Service in any way that violates any applicable federal, state, local, or international law or regulation (including, without limitation, any laws regarding the export of data or software to and from the US or other countries).+ <br />+ Our Service is not intended for providing alerts on disaster scenarios or any other situations related to health or safety in any way. This includes but is not limited to natural disasters, acts of terrorism, or emergency responses, and you shall not use our Service for any such purposes.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Limitation of liability</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ IN NO EVENT WILL THE COMPANY ENTITIES BE LIABLE TO YOU OR ANY THIRD PARTY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES ARISING OUT OF OR RELATING TO YOUR ACCESS TO OR USE OF, OR YOUR INABILITY TO ACCESS OR USE, THE SERVICE OR ANY MATERIALS OR CONTENT ON THE SERVICE, WHETHER BASED ON WARRANTY, CONTRACT, TORT (INCLUDING NEGLIGENCE), STATUTE, OR ANY OTHER LEGAL THEORY, WHETHER OR NOT THE COMPANY ENTITIES HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGE.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Disclaimers; no warranties</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ THE SERVICE ARE MADE AVAILABLE TO YOU ON AN "AS IS" AND "AS AVAILABLE" BASIS, WITH THE EXPRESS UNDERSTANDING THAT THE COMPANY ENTITIES HAVE NO OBLIGATION TO MONITOR, CONTROL, OR VET THE CONTENT OR DATA APPEARING ON THE SERVICE. AS SUCH, YOUR USE OF THE SERVICE IS AT YOUR OWN DISCRETION AND RISK. THE COMPANY ENTITIES MAKE NO CLAIMS OR PROMISES ABOUT THE QUALITY, ACCURACY, OR RELIABILITY OF THE SERVICE AND EXPRESSLY DISCLAIM ALL WARRANTIES, WHETHER EXPRESS OR IMPLIED, INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Accounts</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ When you create an account with us, you must provide us information that is accurate, complete, and current at all times. Failure to do so constitutes a breach of the Terms, which may result in immediate termination of your account on our Service.+ <br />+ You are responsible for safeguarding the password that you use to access the Service and for any activities or actions under your password, whether your password is with our Service or a third-party service.+ <br />+ You agree not to disclose your password to any third party. You must notify us immediately upon becoming aware of any breach of security or unauthorized use of your account.+ <br />+ You may not use as a username the name of another person or entity or that is not lawfully available for use, a name or trademark that is subject to any rights of another person or entity other than you without appropriate authorization, or a name that is otherwise offensive, vulgar or obscene.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Subscriptions</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ Some parts of the Service are billed on a subscription basis ("Subscription(s)"). You will be billed in advance on a recurring and periodic basis ("Billing Cycle"). Billing cycles are set either on a monthly or annual basis, depending on the type of subscription plan you select when purchasing a Subscription.+ <br />+ At the end of each Billing Cycle, your Subscription will automatically renew under the exact same conditions unless you cancel it or we cancel it. You may cancel your Subscription renewal either through your online account management page or by contacting our customer support team.+ <br />+ A valid payment method, including credit card, is required to process the payment for your Subscription. You shall provide us with accurate and complete billing information including full name, address, state, zip code, telephone number, and a valid payment method information. By submitting such payment information, you automatically authorize us to charge all Subscription fees incurred through your account to any such payment instruments.+ <br />+ Should automatic billing fail to occur for any reason, we may issue an electronic invoice indicating that you must proceed manually, within a certain deadline date, with the full payment corresponding to the billing period as indicated on the invoice.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Fee changes</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We may, at our sole discretion and at any time, modify the Subscription fees for the Subscriptions. Any Subscription fee change will become effective at the end of the then-current Billing Cycle.+ <br />+ We will provide you with a reasonable prior notice of any change in Subscription fees to give you an opportunity to terminate your Subscription before such change becomes effective.+ <br />+ Your continued use of the Service after the Subscription fee change comes into effect constitutes your agreement to pay the modified Subscription fee amount.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Refunds</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ To avoid being charged for your Subscription, you must cancel the Subscription before your renewal date. Otherwise, youβll be charged and will retain access to the Service through the end of the Billing Cycle.+ <br />+ Except when required by law, paid Subscription fees are non-refundable. However, you may contact our support team and at our sole discretion we may issue a refund on a case-by-case basis.+ </p>++ {/* <h3 className='text-2xl font-bold text-gray-900 tracking-tight mt-4'>Service Level Agreement (SLA)</h3>+ <p className='text-lg text-gray-900 tracking-tight'>+ If you purchased a Subscription with a SLA, we aim to provide Service availability of 99.5% or better. If downtime in any one month exceeds 0.5% of that month, we will credit your account. Service credits are applied at your request and will apply toward the balance due at the end of the next Billing Cycle (either monthly or yearly).<br />+ We will apply any service credits only against future payments for the services otherwise due from you. Service credits will not entitle you to any refund or other payment from us. A service credit will be applicable and issued only if the credit amount for the applicable billing cycle is greater than one euro (β¬1). Service credits may not be transferred or applied to any other account.<br />+ Service credits are calculated as a percentage of the total charges paid by you (excluding one-time payments such as upfront payments) for the month in which the downtime occurred in accordance with the schedule below. For yearly billing, the total charge paid by the user is divided into 12 equal parts, each corresponding to a month unit for the purpose of the service credits calculation.<br />+ We calculate service credits the following way:<br />+ - If the monthly uptime is less than 99.5% but equal to or greater than 98.5%, the service credit is equal to 10% of the Serviceβs monthly cost.<br />+ - If the monthly uptime is less than 98.5%, the service credit is equal to 30% of the Serviceβs monthly cost.<br />++ Some performance issues are excluded from downtime calculations, such as:<br />+ - Issues caused by factors outside of our reasonable control.<br />+ - Issues that resulted from any actions or inaction by a user or a third-party.<br />+ - Issues that resulted from the userβs equipment and/or third-party equipment (not within our primary control). For the avoidance of any doubt, we do not provide any Internet or network services and any performance issues related to that type of services shall be deemed not in the primary control of the Company.<br />+ - Issues that arise from the Companyβs suspension or termination of rights to use the Service in accordance with these Terms.<br />+ - Downtime caused by reasonable scheduled maintenance that is announced in advance.+ </p> */}++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Governing Law</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ These Terms shall be governed and construed in accordance with the laws of Ukraine, without regard to its conflict of law provisions.+ <br />+ Our failure to enforce any right or provision of these Terms will not be considered a waiver of those rights. If any provision of these Terms is held to be invalid or unenforceable by a court, the remaining provisions of these Terms will remain in effect. These Terms constitute the entire agreement between us regarding our Service, and supersede and replace any prior agreements we might have between us regarding the Service.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Disputes resolution</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ If you have any concern or dispute about the Service, you agree to first try to resolve the dispute informally by contacting the Company.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>For European Union (EU) users</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ If You are a European Union consumer, you will benefit from any mandatory provisions of the law of the country in which you are resident in.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>United States Legal Compliance</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ You represent and warrant that (i) you are not located in a country that is subject to the United States government embargo, or that has been designated by the United States government as a "terrorist supporting" country, and (ii) You are not listed on any United States government list of prohibited or restricted parties.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Severability</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ If any provision of these Terms is held to be unenforceable or invalid, such provision will be changed and interpreted to accomplish the objectives of such provision to the greatest extent possible under applicable law and the remaining provisions will continue in full force and effect.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Waiver</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ Except as provided herein, the failure to exercise a right or to require performance of an obligation under this Agreement shall not affect a partyβs ability to exercise such right or require such performance at any time thereafter, nor shall the waiver of a breach constitute the waiver of any subsequent breach.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Translation interpretation</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ These Terms and Conditions may have been translated if we have made them available to you on our Service. You agree that the original English text shall prevail in the case of a dispute.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Changes to these Terms and Conditions</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ We reserve the right, at our sole discretion, to modify or replace these Terms and Conditions at any time. If a revision is material we will make reasonable efforts to provide at least 30 days' notice prior to any new terms taking effect. What constitutes a material change will be determined at our sole discretion.+ <br />+ By continuing to access or use our Service after those revisions become effective, you agree to be bound by the revised terms. If you do not agree to the new terms, in whole or in part, please stop using the website and the Service.+ </p>++ <h3 className='text-2xl font-bold text-gray-900 dark:text-gray-50 tracking-tight mt-4'>Contact us</h3>+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ If you have any questions you can contact us by sending us an email at + <a href={`mailto:${CONTACT_EMAIL}`} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'>+ {CONTACT_EMAIL}+ </a>+ .+ </p>++ <hr className='mt-10 mb-4 border-gray-200 dark:border-gray-600' />+ <p className='text-lg text-gray-900 dark:text-gray-50 tracking-tight'>+ <i>Last updated: August 14, 2022.</i>+ </p>+ </div>+ </div>+ </Title>+ )+}++export default Featuresdiff --git a/app/pages/UserSettings/UserSettings.container.tsx b/app/pages/UserSettings/UserSettings.container.tsxnew file mode 100644index 000000000..8ddf26374--- /dev/null+++ b/app/pages/UserSettings/UserSettings.container.tsx@@ -0,0 +1,149 @@+import { connect } from 'react-redux'+import UIActions from 'redux/reducers/ui'+import { errorsActions } from 'redux/reducers/errors'+import { authActions } from 'redux/reducers/auth'+import { alertsActions } from 'redux/reducers/alerts'+import { trackCustom } from 'utils/analytics'+import { StateType, AppDispatch } from 'redux/store'+import sagaActions from 'redux/sagas/actions'+import { IUser } from 'redux/models/IUser'+import { ISharedProject } from 'redux/models/ISharedProject'++import UserSettings from './UserSettings'++const mapStateToProps = (state: StateType) => {+ return {+ user: state.auth.user,+ dontRemember: state.auth.dontRemember,+ isPaidTierUsed: state.auth.isPaidTierUsed,+ theme: state.ui.theme.theme,+ }+}++const mapDispatchToProps = (dispatch: AppDispatch) => ({+ onGDPRExportFailed: (message: string) => {+ dispatch(errorsActions.genericError({+ message,+ }))+ },+ onDelete: (t: (key: string) => string, onSuccess: {+ (): void,+ }) => {+ dispatch(+ sagaActions.deleteAccountAsync(+ (error: string) => dispatch(+ errorsActions.deleteAccountFailed({+ message: error,+ }),+ ),+ () => {+ trackCustom('ACCOUNT_DELETED')+ onSuccess()+ },+ t,+ ),+ )+ },+ updateUserData: (data: IUser) => {+ dispatch(authActions.updateUserData(data))+ },+ onDeleteProjectCache: () => {+ dispatch(UIActions.deleteProjectCache({}))+ },+ userSharedUpdate: (message: string) => {+ dispatch(alertsActions.userSharedUpdate({+ message,+ type: 'success',+ }))+ },+ sharedProjectError: (message: string) => {+ dispatch(errorsActions.sharedProjectFailed({+ message,+ }))+ },+ genericError: (message: string) => {+ dispatch(errorsActions.genericError({+ message,+ }))+ },+ removeProject: (projectId: string) => {+ dispatch(UIActions.removeProject({+ pid: projectId,+ shared: true,+ }))+ },+ removeShareProject: (id: string) => {+ dispatch(authActions.deleteShareProject(id))+ },+ setProjectsShareData: (data: Partial<ISharedProject>, id: string) => {+ dispatch(UIActions.setProjectsShareData({+ data,+ id,+ shared: true,+ }))+ },+ setUserShareData: (data: Partial<ISharedProject>, id: string) => {+ dispatch(authActions.setUserShareData({+ data,+ id,+ }))+ },+ updateProfileFailed: (message: string) => {+ dispatch(errorsActions.updateUserProfileFailed({+ message,+ }))+ },+ accountUpdated: (message: string) => {+ dispatch(alertsActions.accountUpdated({+ message,+ type: 'success',+ }))+ },+ updateUserProfileAsync: (data: Partial<IUser>, successMessage: string, callback = (e: any) => {}) => {+ dispatch(+ sagaActions.updateUserProfileAsync(+ data,+ (res: any) => {+ if (res) {+ dispatch(+ alertsActions.accountUpdated({+ message: successMessage,+ type: 'success',+ }),+ )+ }+ callback(res)+ },+ ),+ )+ },+ setAPIKey: (apiKey: string) => {+ dispatch(authActions.setApiKey(apiKey))+ },+ // setThemeType: (theme) => {+ // dispatch(UIActions.setThemeType(theme))+ // },+ linkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => {+ dispatch(+ sagaActions.linkSSO(+ t,+ callback,+ provider,+ ),+ )+ },+ unlinkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => {+ dispatch(+ sagaActions.unlinkSSO(+ t,+ callback,+ provider,+ ),+ )+ },+ updateShowLiveVisitorsInTitle: (show: boolean, callback: (isSuccess: boolean) => void) => {+ dispatch(sagaActions.updateShowLiveVisitorsInTitle(show, callback))+ },+})++export default connect(mapStateToProps, mapDispatchToProps)(UserSettings)diff --git a/app/pages/UserSettings/UserSettings.tsx b/app/pages/UserSettings/UserSettings.tsxnew file mode 100644index 000000000..03b6b83fb--- /dev/null+++ b/app/pages/UserSettings/UserSettings.tsx@@ -0,0 +1,804 @@+/* eslint-disable no-param-reassign, react/forbid-prop-types */+import React, {+ useState, useEffect, memo, useRef,+} from 'react'+import { useHistory } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import _size from 'lodash/size'+import _isEmpty from 'lodash/isEmpty'+import _isNull from 'lodash/isNull'+import _findIndex from 'lodash/findIndex'+import _map from 'lodash/map'+import _keys from 'lodash/keys'+import {+ EnvelopeIcon, ExclamationTriangleIcon, ArrowDownTrayIcon, CurrencyDollarIcon, ClipboardDocumentIcon, ChevronDownIcon,+} from '@heroicons/react/24/outline'+import PropTypes from 'prop-types'+import dayjs from 'dayjs'+import utc from 'dayjs/plugin/utc'+import cx from 'clsx'++import {+ reportFrequencies, DEFAULT_TIMEZONE, WEEKLY_REPORT_FREQUENCY, CONFIRMATION_TIMEOUT,+ GDPR_REQUEST, GDPR_EXPORT_TIMEFRAME, TimeFormat, isSelfhosted,+} from 'redux/constants'+import { IUser } from 'redux/models/IUser'+import { ISharedProject } from 'redux/models/ISharedProject'+import Title from 'components/Title'+import { withAuthentication, auth } from 'hoc/protected'+import Input from 'ui/Input'+import Button from 'ui/Button'+import Modal from 'ui/Modal'+import Beta from 'ui/Beta'+import Select from 'ui/Select'+import Checkbox from 'ui/Checkbox'+import PaidFeature from 'modals/PaidFeature'+import TimezonePicker from 'ui/TimezonePicker'+import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS } from 'utils/validator'+import routes from 'routes'+import { trackCustom } from 'utils/analytics'+import { getCookie, setCookie } from 'utils/cookie'+import {+ confirmEmail, exportUserData, generateApiKey, deleteApiKey, // setTheme,+} from 'api'+import ProjectList from './components/ProjectList'+import TwoFA from './components/TwoFA'+import Integrations from './components/Integrations'+import Socialisations from './components/Socialisations'+import NoSharedProjects from './components/NoSharedProjects'++dayjs.extend(utc)++const timeFormatArray = _map(TimeFormat, (key) => key)++interface IProps {+ onDelete: (t: (key: string) => string, callback: () => void) => void,+ onDeleteProjectCache: () => void,+ removeProject: (id: string) => void,+ removeShareProject: (id: string) => void,+ setUserShareData: (data: Partial<ISharedProject>, id: string) => void,+ setProjectsShareData: (data: Partial<ISharedProject>, id: string) => void,+ userSharedUpdate: (message: string) => void,+ sharedProjectError: (message: string) => void,+ updateUserData: (data: Partial<IUser>) => void,+ genericError: (message: string) => void,+ onGDPRExportFailed: (message: string) => void,+ updateProfileFailed: (message: string) => void,+ updateUserProfileAsync: (data: IUser, successMessage: string, callback?: (e: any) => {}) => void,+ accountUpdated: (t: string) => void,+ setAPIKey: (key: string | null) => void,+ user: IUser,+ dontRemember: boolean,+ isPaidTierUsed: boolean,+ linkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => void,+ unlinkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => void,+ theme: string,+ updateShowLiveVisitorsInTitle: (show: boolean, callback: (isSuccess: boolean) => void) => void,+}++interface IForm extends Partial<IUser> {+ repeat: string,+ password: string,+ email: string+}++const UserSettings = ({+ onDelete, onDeleteProjectCache, removeProject, removeShareProject, setUserShareData,+ setProjectsShareData, userSharedUpdate, sharedProjectError, updateUserData,+ genericError, onGDPRExportFailed, updateProfileFailed, updateUserProfileAsync,+ accountUpdated, setAPIKey, user, dontRemember, isPaidTierUsed, // setThemeType, themeType,+ linkSSO, unlinkSSO, theme, updateShowLiveVisitorsInTitle,+}: IProps): JSX.Element => {+ const history = useHistory()+ const { t }: {+ t: (key: string, options?: {+ [key: string]: string | number | null,+ }) => string,+ } = useTranslation('common')++ const [form, setForm] = useState<IForm>({+ email: user.email || '',+ password: '',+ repeat: '',+ timeFormat: user.timeFormat || TimeFormat['12-hour'],+ })+ const [showPasswordFields, setShowPasswordFields] = useState<boolean>(false)+ const [timezone, setTimezone] = useState<string>(user.timezone || DEFAULT_TIMEZONE)+ const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState<boolean>(false)+ const [timezoneChanged, setTimezoneChanged] = useState<boolean>(false)+ const [reportFrequency, setReportFrequency] = useState<string>(user.reportFrequency)+ 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 [showAPIDeleteModal, setShowAPIDeleteModal] = useState<boolean>(false)+ const [showExportModal, setShowExportModal] = useState<boolean>(false)+ const [error, setError] = useState<null | string>(null)+ const [copied, setCopied] = useState<boolean>(false)+ const translatedFrequencies: string[] = _map(reportFrequencies, (key) => t(`profileSettings.${key}`)) // useMemo(_map(reportFrequencies, (key) => t(`profileSettings.${key}`)), [t])+ const translatedTimeFormat: string[] = _map(TimeFormat, (key) => t(`profileSettings.${key}`)) // useMemo(_map(TimeFormat, (key) => t(`profileSettings.${key}`)), [t])+ const [settingUpdating, setSettingUpdating] = useState<boolean>(false)++ const copyTimerRef = useRef(null)++ const validate = () => {+ const allErrors = {} as {+ [key: string]: string,+ }++ if (!isValidEmail(form.email)) {+ allErrors.email = t('auth.common.badEmailError')+ }++ if (_size(form.password) > 0 && !isValidPassword(form.password)) {+ allErrors.password = t('auth.common.xCharsError', { amount: MIN_PASSWORD_CHARS })+ }++ if (form.password !== form.repeat) {+ allErrors.repeat = t('auth.common.noMatchError')+ }++ const valid = _isEmpty(_keys(allErrors))++ setErrors(allErrors)+ setValidated(valid)+ }++ const onSubmit = (data: any, callback = () => { }) => {+ delete data.repeat+ // eslint-disable-next-line no-restricted-syntax+ for (const key in data) {+ if (data[key] === '') {+ delete data[key]+ }+ }++ updateUserProfileAsync(data, t('profileSettings.updated'))+ }++ useEffect(() => {+ validate()+ }, [form]) // eslint-disable-line++ useEffect(() => {+ return () => {+ // @ts-ignore+ clearTimeout(copyTimerRef.current)+ }+ }, [])++ const _setTimezone = (value: string) => {+ setTimezoneChanged(true)+ setTimezone(value)+ }++ 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 handleTimezoneSave = () => {+ setBeenSubmitted(true)++ if (validated) {+ // if the timezone updates, we need to delete all project cache to refetch it with the new timezone setting afterwards+ if (timezoneChanged) {+ onDeleteProjectCache()+ }++ onSubmit({+ ...form,+ timezone,+ })+ }+ }++ const handleShowLiveVisitorsSave = (e: React.ChangeEvent<HTMLInputElement>) => {+ if (settingUpdating) {+ return+ }++ const { checked } = e.target++ setSettingUpdating(true)+ updateShowLiveVisitorsInTitle(checked, (isSuccess: boolean) => {+ setSettingUpdating(false)++ if (isSuccess) {+ accountUpdated(t('profileSettings.updated'))+ return+ }++ genericError(t('apiNotifications.somethingWentWrong'))+ })+ }++ const handleIntegrationSave = (data: any, callback = () => { }) => {+ setBeenSubmitted(true)++ if (validated) {+ onSubmit({+ ...form,+ ...data,+ }, callback)+ }+ }++ const handleReportSave = () => {+ setBeenSubmitted(true)++ if (validated) {+ onSubmit({+ ...form,+ reportFrequency,+ })+ }+ }++ const _setReportFrequency = (value: string) => {+ if (!isPaidTierUsed && value === WEEKLY_REPORT_FREQUENCY) {+ setIsPaidFeatureOpened(true)+ return+ }++ setReportFrequency(value)+ }++ const reportIconExtractor = (_: any, index: number) => {+ if (!isPaidTierUsed && reportFrequencies[index] === WEEKLY_REPORT_FREQUENCY) {+ return (+ <CurrencyDollarIcon className='w-5 h-5 mr-1' />+ )+ }++ return null+ }++ const setToClipboard = (value: string) => {+ if (!copied) {+ navigator.clipboard.writeText(value)+ setCopied(true)+ // @ts-ignore+ copyTimerRef.current = setTimeout(() => {+ setCopied(false)+ }, 2000)+ }+ }++ const _onDelete = () => {+ onDelete(t, () => {+ history.push(routes.main)+ })+ }++ const onExport = async (exportedAt: string) => {+ try {+ if (getCookie(GDPR_REQUEST) || (!_isNull(exportedAt) && !dayjs().isAfter(dayjs.utc(exportedAt).add(GDPR_EXPORT_TIMEFRAME, 'day'), 'day'))) {+ onGDPRExportFailed(t('profileSettings.tryAgainInXDays', { amount: GDPR_EXPORT_TIMEFRAME }))+ return+ }+ await exportUserData()++ trackCustom('GDPR_EXPORT')+ accountUpdated(t('profileSettings.reportSent'))+ setCookie(GDPR_REQUEST, true, 1209600) // setting cookie for 14 days+ } catch (e) {+ updateProfileFailed(e as string)+ }+ }++ const onEmailConfirm = async (errorCallback: any) => {+ if (getCookie(CONFIRMATION_TIMEOUT)) {+ updateProfileFailed(t('profileSettings.confTimeout'))+ return+ }++ try {+ const res = await confirmEmail()++ if (res) {+ setCookie(CONFIRMATION_TIMEOUT, true, 600)+ accountUpdated(t('profileSettings.confSent'))+ } else {+ errorCallback(t('profileSettings.noConfLeft'))+ }+ } catch (e) {+ updateProfileFailed(e as string)+ }+ }++ const onApiKeyGenerate = async () => {+ try {+ const res = await generateApiKey()+ setAPIKey(res.apiKey)+ } catch (e) {+ updateProfileFailed(e as string)+ }+ }++ const onApiKeyDelete = async () => {+ try {+ await deleteApiKey()+ setAPIKey(null)+ } catch (e) {+ updateProfileFailed(e as string)+ }+ }++ // const setAsyncThemeType = async (theme) => {+ // try {+ // await setTheme(theme)+ // setThemeType(theme)+ // } catch (e) {+ // updateProfileFailed(e)+ // }+ // }++ const setAsyncTimeFormat = async () => {+ setBeenSubmitted(true)++ if (validated) {+ onSubmit({+ ...form,+ })+ }+ }++ const toggleShowPasswordFields = () => {+ setForm((prev) => ({+ ...prev,+ password: '',+ repeat: '',+ }))+ setShowPasswordFields((prev) => !prev)+ }++ return (+ <Title title={t('titles.profileSettings')}>+ <div className='min-h-min-footer 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.profileSettings')}+ </h2>+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.general')}+ </h3>+ <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 : null}+ disabled={isSelfhosted}+ />+ {!isSelfhosted && (+ <>+ <span+ onClick={toggleShowPasswordFields}+ className='flex items-center cursor-pointer max-w-max text-gray-900 dark:text-gray-50 hover:underline'+ >+ {t('auth.common.changePassword')}+ <ChevronDownIcon+ className={cx('w-4 h-4 ml-2', {+ 'rotate-180': showPasswordFields,+ })}+ />+ </span>+ {showPasswordFields && (+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6 mt-4'>+ <Input+ name='password'+ id='password'+ type='password'+ label={t('auth.common.password')}+ hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}+ value={form.password}+ placeholder={t('auth.common.password')}+ className='sm:col-span-3'+ onChange={handleInput}+ error={beenSubmitted ? errors.password : null}+ />+ <Input+ name='repeat'+ id='repeat'+ type='password'+ label={t('auth.common.repeat')}+ value={form.repeat}+ placeholder={t('auth.common.repeat')}+ className='sm:col-span-3'+ onChange={handleInput}+ error={beenSubmitted ? errors.repeat : null}+ />+ </div>+ )}+ <Button className='mt-4' type='submit' primary large>+ {t('profileSettings.update')}+ </Button>+ </>+ )}+ {/* Theme type switch */}+ {/* <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.theme')}+ </h3>+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-2 mb-4'>+ <div>+ <Select+ title={themeType}+ label={t('profileSettings.selectTheme')}+ className='w-full'+ items={[THEME_TYPE.classic, THEME_TYPE.christmas]}+ onSelect={(f) => setAsyncThemeType(f)}+ />+ </div>+ </div> */}+ {/* Timezone selector */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50 flex items-center'>+ {t('profileSettings.timezone')}+ <div className='ml-5'>+ <Beta />+ </div>+ </h3>+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-4'>+ <div>+ <TimezonePicker value={timezone} onChange={_setTimezone} />+ </div>+ </div>+ <Button className='mt-4' onClick={handleTimezoneSave} primary large>+ {t('common.save')}+ </Button>+ {/* Timeformat selector (12 / 24 hour format) */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.timeFormat')}+ </h3>+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-4'>+ <div>+ <Select+ title={t(`profileSettings.${form.timeFormat}`)}+ label={t('profileSettings.selectTimeFormat')}+ className='w-full'+ items={translatedTimeFormat}+ onSelect={(f) => setForm((prev) => ({ ...prev, timeFormat: timeFormatArray[_findIndex(translatedTimeFormat, (freq) => freq === f)] }))}+ />+ </div>+ </div>+ <Button className='mt-4' onClick={setAsyncTimeFormat} primary large>+ {t('common.save')}+ </Button>++ {!isSelfhosted && (+ <>+ {/* Email reports frequency selector (e.g. monthly, weekly, etc.) */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.email')}+ </h3>+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-4'>+ <div>+ <Select+ title={t(`profileSettings.${reportFrequency}`)}+ label={t('profileSettings.frequency')}+ className='w-full'+ items={translatedFrequencies}+ iconExtractor={reportIconExtractor}+ onSelect={(f) => _setReportFrequency(+ reportFrequencies[_findIndex(translatedFrequencies, (freq) => freq === f)],+ )}+ />+ </div>+ </div>+ <Button className='mt-4' onClick={handleReportSave} primary large>+ {t('common.save')}+ </Button>+ </>+ )}++ {/* UI Settings */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.uiSettings')}+ </h3>+ <Checkbox+ checked={user.showLiveVisitorsInTitle}+ onChange={handleShowLiveVisitorsSave}+ disabled={settingUpdating}+ name='active'+ id='active'+ className='mt-4'+ label={t('profileSettings.showVisitorsInTitle')}+ />++ {!isSelfhosted && (+ <>+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ {/* Integrations setup */}+ <h3 id='integrations' className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.integrations')}+ </h3>+ <Integrations+ user={user}+ updateUserData={updateUserData}+ handleIntegrationSave={handleIntegrationSave}+ genericError={genericError}+ />+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />++ {/* API access setup */}+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.apiKey')}+ <div className='ml-5'>+ <Beta />+ </div>+ </h3>+ {user.apiKey ? (+ <>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.apiKeyWarning')}+ </p>+ <p className='mt-4 max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.apiKey')}+ </p>+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2'>+ <div className='relative group'>+ <Input+ name='apiKey'+ id='apiKey'+ type='text'+ className='pr-9'+ value={user.apiKey}+ onChange={handleInput}+ disabled+ />+ <div className='absolute right-2 top-3'>+ <div className='group relative'>+ <Button+ type='button'+ onClick={() => setToClipboard(user.apiKey || '')}+ className='opacity-70 hover:opacity-100'+ noBorder+ >+ <>+ <ClipboardDocumentIcon className='w-6 h-6' />+ {copied && (+ <div className='animate-appear bg-white dark:bg-slate-800 cursor-auto rounded p-1 absolute sm:top-0 top-0.5 right-8 text-xs text-green-600'>+ {t('common.copied')}+ </div>+ )}+ </>+ </Button>+ </div>+ </div>+ </div>+ </div>+ </>+ ) : (+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.noApiKey')}+ </p>+ )}+ {user.apiKey ? (+ <Button className='mt-4' onClick={() => setShowAPIDeleteModal(true)} danger large>+ {t('profileSettings.deleteApiKeyBtn')}+ </Button>+ ) : (+ <Button className='mt-4' onClick={onApiKeyGenerate} primary large>+ {t('profileSettings.addApiKeyBtn')}+ </Button>+ )}++ {/* 2FA setting */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2fa')}+ </h3>+ <TwoFA+ user={user}+ dontRemember={dontRemember}+ updateUserData={updateUserData}+ genericError={genericError}+ />++ {/* Socialisations setup */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 id='socialisations' className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.socialisations')}+ </h3>+ <Socialisations+ user={user}+ genericError={genericError}+ linkSSO={linkSSO}+ unlinkSSO={unlinkSSO}+ theme={theme}+ />++ {/* Shared projects setting */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.shared')}+ </h3>+ <div>+ {!_isEmpty(user.sharedProjects) ? (+ <div className='mt-3 flex flex-col'>+ <div className='-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8'>+ <div className='inline-block min-w-full py-2 align-middle md:px-6 lg:px-8'>+ <div className='overflow-hidden 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('profileSettings.sharedTable.project')}+ </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.role')}+ </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' className='relative py-3.5 pl-3 pr-4 sm:pr-6' />+ </tr>+ </thead>+ <tbody className='divide-y divide-gray-300 dark:divide-gray-600'>+ {_map(user.sharedProjects, (item) => (+ <ProjectList+ key={item.id}+ item={item}+ removeProject={removeProject}+ removeShareProject={removeShareProject}+ setUserShareData={setUserShareData}+ setProjectsShareData={setProjectsShareData}+ userSharedUpdate={userSharedUpdate}+ sharedProjectError={sharedProjectError}+ />+ ))}+ </tbody>+ </table>+ </div>+ </div>+ </div>+ </div>+ ) : (+ <NoSharedProjects t={t} />+ )}+ </div>+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ {!user.isActive && (+ <div+ className='flex cursor-pointer mt-4 pl-0 underline text-blue-600 hover:text-indigo-800 dark:hover:text-indigo-600'+ onClick={() => onEmailConfirm(setError)}+ >+ <EnvelopeIcon className='mt-0.5 mr-2 w-6 h-6 text-blue-500' />+ {t('profileSettings.noLink')}+ </div>+ )}+ <div className='flex justify-between mt-4'>+ <Button onClick={() => setShowExportModal(true)} semiSmall primary>+ <>+ <ArrowDownTrayIcon className='w-5 h-5 mr-1' />+ {t('profileSettings.requestExport')}+ </>+ </Button>+ <Button className='ml-3' onClick={() => setShowModal(true)} semiSmall danger>+ <>+ <ExclamationTriangleIcon className='w-5 h-5 mr-1' />+ {t('profileSettings.delete')}+ </>+ </Button>+ </div>+ </>+ )}+ </form>++ <PaidFeature isOpened={isPaidFeatureOpened} onClose={() => setIsPaidFeatureOpened(false)} />+ <Modal+ onClose={() => setShowExportModal(false)}+ onSubmit={() => {+ setShowExportModal(false)+ onExport(user.exportedAt)+ }}+ submitText={t('common.continue')}+ closeText={t('common.close')}+ title={t('profileSettings.dataExport')}+ type='info'+ message={t('profileSettings.exportConfirmation')}+ isOpened={showExportModal}+ />+ <Modal+ onClose={() => setShowModal(false)}+ onSubmit={() => {+ setShowModal(false)+ _onDelete()+ }}+ submitText={t('profileSettings.aDelete')}+ closeText={t('common.close')}+ title={t('profileSettings.qDelete')}+ submitType='danger'+ type='error'+ message={t('profileSettings.deactivateConfirmation')}+ isOpened={showModal}+ />+ <Modal+ onClose={() => setShowAPIDeleteModal(false)}+ onSubmit={() => {+ setShowAPIDeleteModal(false)+ onApiKeyDelete()+ }}+ submitText={t('profileSettings.deleteApiKeyBtn')}+ closeText={t('common.close')}+ title={t('profileSettings.apiKeyDelete')}+ submitType='danger'+ type='error'+ message={t('profileSettings.apiKeyDeleteConf')}+ isOpened={showAPIDeleteModal}+ />+ <Modal+ onClose={() => {+ setError(null)+ }}+ closeText={t('common.gotIt')}+ type='error'+ title={t('common.error')}+ message={error}+ isOpened={Boolean(error)}+ />+ </div>+ </Title>+ )+}++UserSettings.propTypes = {+ onDelete: PropTypes.func.isRequired,+ onGDPRExportFailed: PropTypes.func.isRequired,+ onDeleteProjectCache: PropTypes.func.isRequired,+ removeProject: PropTypes.func.isRequired,+ removeShareProject: PropTypes.func.isRequired,+ setUserShareData: PropTypes.func.isRequired,+ setProjectsShareData: PropTypes.func.isRequired,+ userSharedUpdate: PropTypes.func.isRequired,+ sharedProjectError: PropTypes.func.isRequired,+ updateUserData: PropTypes.func.isRequired,+ genericError: PropTypes.func.isRequired,+ updateProfileFailed: PropTypes.func.isRequired,+ updateUserProfileAsync: PropTypes.func.isRequired,+ accountUpdated: PropTypes.func.isRequired,+ setAPIKey: PropTypes.func.isRequired,+ user: PropTypes.object.isRequired,+ dontRemember: PropTypes.bool.isRequired,+ isPaidTierUsed: PropTypes.bool.isRequired,+ linkSSO: PropTypes.func.isRequired,+ unlinkSSO: PropTypes.func.isRequired,+ theme: PropTypes.string.isRequired,+}++export default memo(withAuthentication(UserSettings, auth.authenticated))diff --git a/app/pages/UserSettings/components/Integrations.tsx b/app/pages/UserSettings/components/Integrations.tsxnew file mode 100644index 000000000..3bb0eac84--- /dev/null+++ b/app/pages/UserSettings/components/Integrations.tsx@@ -0,0 +1,230 @@+import React, { useState, memo } from 'react'+import { useTranslation, Trans } from 'react-i18next'+import _map from 'lodash/map'+import _isString from 'lodash/isString'+import {+ CheckCircleIcon, XCircleIcon, ClockIcon,+} from '@heroicons/react/24/solid'++import Input from 'ui/Input'+import Button from 'ui/Button'+import Telegram from 'ui/icons/Telegram'+import { removeTgIntegration } from 'api'+import { IUser } from 'redux/models/IUser'++const getAvailableIntegrations = (t: (key: string) => string): {+ name: string,+ key: string,+ description: string,+ Icon: React.FC<React.SVGProps<SVGSVGElement>>,+}[] => ([+ {+ name: 'Telegram',+ key: 'telegram',+ description: t('profileSettings.integrationsList.telegram'),+ Icon: Telegram,+ },+])++const TG_BOT_URL: string = 'https://t.me/swetrixbot'+const TG_BOT_USERNAME: string = '@swetrixbot'++const Integrations = ({+ user, updateUserData, handleIntegrationSave, genericError,+}: {+ user: IUser,+ updateUserData: (data: Partial<IUser>) => void,+ handleIntegrationSave: (data: Partial<IUser>, cb: () => void) => void,+ genericError: (message: string) => void,+}) => {+ const { t }: {+ t: (key: string) => string,+ } = useTranslation('common')+ const available = getAvailableIntegrations(t)+ const [integrationConfigurating, setIntegrationConfigurating] = useState<string | null>(null)+ const [tgChatId, setTgChatId] = useState<string | null>(null)+ const [isIntegrationLoading, setIsIntegrationLoading] = useState<boolean>(false)+ const [isRemovalLoading, setIsRemovalLoading] = useState<boolean>(false)++ const setupIntegration = (key: string) => () => {+ setIntegrationConfigurating(key)+ }++ const addIntegration = (key: string) => () => {+ if (isIntegrationLoading) {+ return+ }++ if (key === 'telegram' && tgChatId) {+ setIsIntegrationLoading(true)+ handleIntegrationSave({+ telegramChatId: tgChatId,+ }, () => {+ setIsIntegrationLoading(false)+ setIntegrationConfigurating(null)+ })+ }+ }++ const getIntegrationStatus = (key: string) => {+ if (key === 'telegram') {+ return {+ connected: user.telegramChatId,+ confirmed: user.isTelegramChatIdConfirmed,+ id: user.telegramChatId,+ }+ }++ return {}+ }++ const removeIntegration = async (key: string) => {+ if (isRemovalLoading) {+ return+ }++ if (key === 'telegram') {+ setIsRemovalLoading(true)++ try {+ if (user.telegramChatId) {+ await removeTgIntegration(user.telegramChatId)+ } else {+ throw new Error('No chat ID')+ }+ updateUserData({+ isTelegramChatIdConfirmed: false,+ telegramChatId: null,+ })+ } catch (e) {+ if (_isString(e)) {+ genericError(e)+ } else {+ genericError(t('apiNotifications.integrationRemovalError'))+ }+ console.error(`[ERROR] Failed to remove TG integration: ${e}`)+ }+ setIsRemovalLoading(false)+ }+ }++ if (integrationConfigurating) {+ if (integrationConfigurating === 'telegram') {+ return (+ <>+ <Button+ className='mb-2 mt-2'+ onClick={() => setIntegrationConfigurating(null)}+ primary+ small+ >+ {t('common.goBack')}+ </Button>+ <p className='text-base max-w-prose text-gray-900 dark:text-gray-50'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='profileSettings.integrationsList.tgHint'+ components={{+ // eslint-disable-next-line jsx-a11y/anchor-has-content+ url: <a href={TG_BOT_URL} className='hover:underline text-blue-600' target='_blank' rel='noreferrer noopener' />,+ }}+ values={{+ username: TG_BOT_USERNAME,+ }}+ />+ </p>+ <div className='flex items-center mt-4'>+ <Input+ type='text'+ label={t('profileSettings.chatID')}+ value={tgChatId || ''}+ placeholder={t('profileSettings.chatID')}+ className='sm:col-span-3'+ onChange={(e) => setTgChatId(e.target.value)}+ disabled={isIntegrationLoading}+ />+ <Button+ className='ml-2 mt-4'+ onClick={addIntegration(integrationConfigurating)}+ loading={isIntegrationLoading}+ primary+ large+ >+ {t('common.enable')}+ </Button>+ </div>+ </>+ )+ }++ return null+ }++ return (+ <>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.integrationsDesc')}+ </p>+ <div className='overflow-hidden bg-white dark:bg-slate-800 mt-2 shadow sm:rounded-md'>+ <ul className='divide-y divide-gray-200 dark:divide-slate-700'>+ {+ _map(available, ({+ name, key, description, Icon,+ }) => {+ const { connected, confirmed, id } = getIntegrationStatus(key)+ const status = connected ? (confirmed ? 'connected' : 'pending') : 'notConnected'++ return (+ <li key={key}>+ <div className='sm:flex items-center px-1 py-4 sm:px-6'>+ <div className='flex min-w-0 flex-1 items-center'>+ <div className='flex-shrink-0 hidden sm:block'>+ <Icon className='max-h-12 max-w-12 h-12 w-12 rounded-full' />+ </div>+ <div className='min-w-0 flex-1 px-2 sm:px-4 md:grid md:grid-cols-2 md:gap-4'>+ <div>+ <p className='text-md font-medium text-gray-800 dark:text-gray-50'>{name}</p>+ <p className='mt-2 flex items-center text-sm text-gray-500 dark:text-gray-100'>+ <span>{description}</span>+ </p>+ </div>+ <div>+ {id && (+ <p className='text-sm text-gray-900 dark:text-gray-50'>+ {t('profileSettings.chatID')}+ {`: ${id}`}+ </p>+ )}+ <p className='mt-2 flex items-center text-sm text-gray-500 dark:text-gray-100'>+ {status === 'notConnected' && <XCircleIcon className='mr-1.5 h-5 w-5 flex-shrink-0 text-red-400' aria-hidden='true' />}+ {status === 'pending' && <ClockIcon className='mr-1.5 h-5 w-5 flex-shrink-0 text-yellow-400' aria-hidden='true' />}+ {status === 'connected' && <CheckCircleIcon className='mr-1.5 h-5 w-5 flex-shrink-0 text-green-400' aria-hidden='true' />}+ {t(`common.${status}`)}+ </p>+ </div>+ </div>+ </div>+ <div className='flex justify-center mt-2 sm:block sm:mt-0'>+ {connected ? (+ <Button onClick={() => removeIntegration(key)} small danger>+ {t('profileSettings.removeIntegration')}+ </Button>+ ) : (+ <Button onClick={setupIntegration(key)} small primary>+ {t('profileSettings.addIntegration')}+ </Button>+ )}+ </div>+ </div>+ </li>+ )+ })+ }+ </ul>+ </div>+ </>+ )+}++export default memo(Integrations)diff --git a/app/pages/UserSettings/components/NoSharedProjects.tsx b/app/pages/UserSettings/components/NoSharedProjects.tsxnew file mode 100644index 000000000..f04daf5ef--- /dev/null+++ b/app/pages/UserSettings/components/NoSharedProjects.tsx@@ -0,0 +1,15 @@+import React from 'react'++const NoSharedProjects = ({ 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-4 text-center leading-snug'>+ {t('profileSettings.noSharedProjects')}+ </h2>+ </div>+ </div>+)++export default NoSharedProjectsdiff --git a/app/pages/UserSettings/components/ProjectList.tsx b/app/pages/UserSettings/components/ProjectList.tsxnew file mode 100644index 000000000..0992598d4--- /dev/null+++ b/app/pages/UserSettings/components/ProjectList.tsx@@ -0,0 +1,119 @@+import React, { memo, useState } from 'react'+import dayjs from 'dayjs'+import PropTypes from 'prop-types'+import { useTranslation } from 'react-i18next'++import Button from 'ui/Button'+import Modal from 'ui/Modal'+import {+ deleteShareProject, acceptShareProject,+} from 'api'+import { ISharedProject } from 'redux/models/ISharedProject'++const ProjectList = ({+ item, removeShareProject, removeProject, setProjectsShareData, setUserShareData,+ userSharedUpdate, sharedProjectError,+}: {+ item: ISharedProject,+ removeShareProject: (id: string) => void,+ removeProject: (id: string) => void,+ setProjectsShareData: (data: Partial<ISharedProject>, id: string, shared?: boolean) => void,+ setUserShareData: (data: Partial<ISharedProject>, id: string) => void,+ userSharedUpdate: (message: string) => void,+ sharedProjectError: (message: string) => void,+}): JSX.Element => {+ const { t, i18n: { language } }: {+ t: (key: string, options?: {+ [key: string]: string | number,+ }) => string,+ i18n: {+ language: string,+ },+ } = useTranslation('common')++ const [showDeleteModal, setShowDeleteModal] = useState<boolean>(false)+ const {+ created, confirmed, id, role, project,+ } = item++ const deleteProject = async (pid: string) => {+ try {+ await deleteShareProject(pid)+ removeShareProject(pid)+ removeProject(project.id)+ userSharedUpdate(t('apiNotifications.quitProject'))+ } catch (e) {+ console.error(`[ERROR] Error while quitting project: ${e}`)+ sharedProjectError(t('apiNotifications.quitProjectError'))+ }+ }++ const onAccept = async () => {+ try {+ await acceptShareProject(id)+ setProjectsShareData({ confirmed: true }, project.id)+ setUserShareData({ confirmed: true }, id)+ userSharedUpdate(t('apiNotifications.acceptInvitation'))+ } catch (e) {+ console.error(`[ERROR] Error while accepting project invitation: ${e}`)+ sharedProjectError(t('apiNotifications.acceptInvitationError'))+ }+ }++ 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'>+ {project.name}+ </td>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-white'>+ {t(`project.settings.roles.${role}.name`)}+ </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 pl-3 pr-4 text-right text-sm font-medium sm:pr-6'>+ {confirmed ? (+ <Button onClick={() => setShowDeleteModal(true)} danger small>+ {t('common.quit')}+ </Button>+ ) : (+ <>+ <Button className='mr-2' onClick={() => setShowDeleteModal(true)} primary small>+ {t('common.reject')}+ </Button>+ <Button onClick={() => onAccept()} primary small>+ {t('common.accept')}+ </Button>+ </>+ )}+ <Modal+ onClose={() => {+ setShowDeleteModal(false)+ }}+ onSubmit={() => {+ setShowDeleteModal(false)+ deleteProject(id)+ }}+ submitText={t('common.yes')}+ type='confirmed'+ closeText={t('common.no')}+ title={t('profileSettings.quitProjectTitle', { project: project.name })}+ message={t('profileSettings.quitProject')}+ isOpened={showDeleteModal}+ />+ </td>+ </tr>+ )+}++ProjectList.propTypes = {+ item: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types+ sharedProjectError: PropTypes.func.isRequired,+ removeProject: PropTypes.func.isRequired,+ removeShareProject: PropTypes.func.isRequired,+ userSharedUpdate: PropTypes.func.isRequired,+}++export default memo(ProjectList)diff --git a/app/pages/UserSettings/components/Socialisations.tsx b/app/pages/UserSettings/components/Socialisations.tsxnew file mode 100644index 000000000..327d293f4--- /dev/null+++ b/app/pages/UserSettings/components/Socialisations.tsx@@ -0,0 +1,172 @@+import React, { useState, memo } from 'react'+import { useTranslation } from 'react-i18next'+import _map from 'lodash/map'+import {+ CheckCircleIcon, XCircleIcon,+} from '@heroicons/react/24/solid'++import Button from 'ui/Button'+import Google from 'ui/icons/GoogleG'+import GithubDark from 'ui/icons/GithubDark'+import GithubLight from 'ui/icons/GithubLight'+import { IUser } from 'redux/models/IUser'+import { SSO_PROVIDERS } from 'redux/constants'++const AVAILABLE_SSO_PROVIDERS = [+ {+ name: 'Google',+ key: SSO_PROVIDERS.GOOGLE,+ Icon: Google,+ icons: {+ Dark: Google,+ Light: Google,+ },+ },+ {+ name: 'Github',+ key: SSO_PROVIDERS.GITHUB,+ icons: {+ Dark: GithubDark,+ Light: GithubLight,+ },+ },+]++/**+ * @param {IUser} user - user object+ * @param {string} socialisation - key from SOCIALISATIONS+ * @returns {[boolean, boolean]} - [isConnected, isUnlinkable]+*/+const getStatusByUser = (user: IUser, socialisation: string) => {+ if (socialisation === SSO_PROVIDERS.GOOGLE) {+ const connected = user.googleId+ const unlinkable = !user.registeredWithGoogle+ return [connected, unlinkable]+ }++ if (socialisation === SSO_PROVIDERS.GITHUB) {+ const connected = user.githubId+ const unlinkable = !user.registeredWithGithub+ return [connected, unlinkable]+ }++ return [false, false]+}++interface ISocialisations {+ user: IUser,+ linkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => void,+ unlinkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => void,+ genericError: (message: string) => void,+ theme: string+}++const Socialisations = ({+ user, linkSSO, unlinkSSO, genericError, theme,+}: ISocialisations) => {+ const { t }: {+ t: (key: string) => string,+ } = useTranslation('common')+ const [isLoading, setIsLoading] = useState(false)++ const _linkSSO = (provider: string) => {+ setIsLoading(true)++ linkSSO(t, () => {+ setIsLoading(false)+ }, provider)+ }++ const _unlinkSSO = (provider: string) => {+ setIsLoading(true)++ unlinkSSO(t, () => {+ setIsLoading(false)+ }, provider)+ }++ return (+ <>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.socialisationsDesc')}+ </p>+ <div className='overflow-hidden bg-white dark:bg-slate-800 mt-2 shadow sm:rounded-md'>+ <ul className='divide-y divide-gray-200 dark:divide-slate-700'>+ {+ _map(AVAILABLE_SSO_PROVIDERS, ({+ name, key, icons,+ }) => {+ const [connected, unlinkable] = getStatusByUser(user, key)+ const { Light, Dark } = icons++ const status = connected ? 'connected' : 'notConnected'++ return (+ <li key={key}>+ <div className='sm:flex items-center px-1 py-4 sm:px-6'>+ <div className='flex min-w-0 flex-1 items-center'>+ <div className='flex-shrink-0 hidden sm:block'>+ {theme === 'dark' ? (+ <Light className='max-h-12 max-w-12 h-12 w-12 rounded-full' />+ ) : (+ <Dark className='max-h-12 max-w-12 h-12 w-12 rounded-full' />+ )}+ </div>+ <div className='min-w-0 flex-1 px-2 sm:px-4 md:grid md:grid-cols-2 md:gap-4'>+ <div>+ <p className='text-md font-medium text-gray-800 dark:text-gray-50'>+ {name}+ </p>+ <p className='mt-2 flex items-center text-sm text-gray-500 dark:text-gray-100'>+ {status === 'notConnected' && <XCircleIcon className='mr-1.5 h-5 w-5 flex-shrink-0 text-red-400' aria-hidden='true' />}+ {status === 'connected' && <CheckCircleIcon className='mr-1.5 h-5 w-5 flex-shrink-0 text-green-400' aria-hidden='true' />}+ {t(`common.${status}`)}+ </p>+ </div>+ </div>+ </div>+ <div className='flex justify-center mt-2 sm:block sm:mt-0'>+ {connected && !unlinkable && (+ <Button+ onClick={() => genericError(t('profileSettings.cantUnlinkSocialisation'))}+ small+ danger+ >+ {t('common.unlink')}+ </Button>+ )}++ {connected && unlinkable && (+ <Button+ onClick={() => _unlinkSSO(key)}+ loading={isLoading}+ small+ danger+ >+ {t('common.unlink')}+ </Button>+ )}++ {!connected && (+ <Button+ onClick={() => _linkSSO(key)}+ loading={isLoading}+ small+ primary+ >+ {t('common.link')}+ </Button>+ )}+ </div>+ </div>+ </li>+ )+ })+ }+ </ul>+ </div>+ </>+ )+}++export default memo(Socialisations)diff --git a/app/pages/UserSettings/components/TwoFA.tsx b/app/pages/UserSettings/components/TwoFA.tsxnew file mode 100644index 000000000..77b75d9e0--- /dev/null+++ b/app/pages/UserSettings/components/TwoFA.tsx@@ -0,0 +1,239 @@+import React, { useState, memo } from 'react'+import QRCode from 'react-qr-code'+import { useTranslation } from 'react-i18next'+import cx from 'clsx'+import _isNull from 'lodash/isNull'+import _isString from 'lodash/isString'++import Input from 'ui/Input'+import Button from 'ui/Button'+import {+ generate2FA, enable2FA, disable2FA,+} from 'api'+import { setAccessToken } from 'utils/accessToken'+import { setRefreshToken } from 'utils/refreshToken'+import { IUser } from 'redux/models/IUser'++const TwoFA = ({+ user, dontRemember, updateUserData, genericError,+}: {+ user: IUser,+ dontRemember: boolean,+ updateUserData: (data: Partial<IUser>) => void,+ genericError: (message: string) => void,+}): JSX.Element => {+ const { t }: {+ t: (key: string, options?: {+ [key: string]: string | number,+ }) => string,+ } = useTranslation('common')+ const [twoFAConfigurating, setTwoFAConfigurating] = useState<boolean>(false)+ const [twoFADisabling, setTwoFADisabling] = useState<boolean>(false)+ const [twoFAConfigData, setTwoFAConfigData] = useState<{+ secret?: string,+ otpauthUrl?: string,+ }>({}) // { secret, otpauthUrl }+ const [isTwoFaLoading, setIsTwoFaLoading] = useState<boolean>(false)+ const [twoFACode, setTwoFACode] = useState('')+ const [twoFACodeError, setTwoFACodeError] = useState<string | null>(null)+ const [twoFARecovery, setTwoFARecovery] = useState<string | null>(null)+ const { isTwoFactorAuthenticationEnabled } = user++ const handle2FAInput = (event: React.ChangeEvent<HTMLInputElement>) => {+ const { target: { value } } = event+ setTwoFACode(value)+ setTwoFACodeError(null)+ }++ const _generate2FA = async () => {+ if (!isTwoFaLoading) {+ setIsTwoFaLoading(true)++ try {+ const result = await generate2FA()+ setTwoFAConfigurating(true)+ setTwoFAConfigData(result)+ } catch (e) {+ if (_isString(e)) {+ genericError(e)+ } else {+ genericError(t('apiNotifications.generate2FAError'))+ }+ console.error(`[ERROR] Failed to generate 2FA: ${e}`)+ setTwoFAConfigurating(false)+ setTwoFAConfigData({})+ }++ setIsTwoFaLoading(false)+ }+ }++ const _enable2FA = async () => {+ if (!isTwoFaLoading) {+ setIsTwoFaLoading(true)++ try {+ const { twoFactorRecoveryCode, accessToken, refreshToken } = await enable2FA(twoFACode)+ setRefreshToken(refreshToken)+ setAccessToken(accessToken, dontRemember)+ updateUserData({ isTwoFactorAuthenticationEnabled: true })+ setTwoFARecovery(twoFactorRecoveryCode)+ } catch (e) {+ if (_isString(e)) {+ genericError(e)+ }+ setTwoFACodeError(t('profileSettings.invalid2fa'))+ }++ setTwoFACode('')+ setIsTwoFaLoading(false)+ }+ }++ const _disable2FA = async () => {+ if (!isTwoFaLoading) {+ setIsTwoFaLoading(true)++ try {+ await disable2FA(twoFACode)+ updateUserData({ isTwoFactorAuthenticationEnabled: false })+ } catch (e) {+ if (_isString(e)) {+ genericError(e)+ }+ setTwoFACodeError(t('profileSettings.invalid2fa'))+ }++ setTwoFACode('')+ setIsTwoFaLoading(false)+ }+ }++ const callFnOnKeyPress = (fn: (e: any) => void, key = 'Enter') => (e: any) => {+ e.stopPropagation()+ if (e.key === key) {+ fn(e)+ }+ }++ const recoverySaved = () => {+ setTwoFARecovery(null)+ setTwoFAConfigurating(false)+ }++ if (twoFARecovery) {+ return (+ <div className='max-w-prose'>+ <p className='text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faRecoveryNote')}+ </p>+ <Input type='text' className='mt-4' value={twoFARecovery} />+ <Button onClick={recoverySaved} primary large>+ {t('profileSettings.2faRecoverySaved')}+ </Button>+ </div>+ )+ }++ if (isTwoFactorAuthenticationEnabled) {+ if (twoFADisabling) {+ return (+ <>+ <p className='text-base max-w-prose text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faDisableHint')}+ </p>+ <div className='flex items-center mt-4'>+ <Input+ type='text'+ label={t('profileSettings.enter2faToDisable')}+ value={twoFACode}+ placeholder={t('profileSettings.yourOneTimeCode')}+ className='sm:col-span-3'+ onChange={handle2FAInput}+ onKeyDown={callFnOnKeyPress(_disable2FA)}+ error={twoFACodeError}+ disabled={isTwoFaLoading}+ />+ <Button+ className={cx('ml-2', {+ 'mt-4': _isNull(twoFACodeError),+ 'mb-1': !_isNull(twoFACodeError),+ })}+ onClick={_disable2FA}+ loading={isTwoFaLoading}+ danger+ large+ >+ {t('common.disable')}+ </Button>+ </div>+ </>+ )+ }++ return (+ <>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faEnabled')}+ </p>+ <Button className='mt-4' onClick={() => setTwoFADisabling(true)} danger large>+ {t('profileSettings.2faDisableBtn')}+ </Button>+ </>+ )+ }++ if (twoFAConfigurating) {+ return (+ <>+ <p className='text-base max-w-prose text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faDesc')}+ </p>+ <div className='mt-4 p-4 bg-white w-max'>+ <QRCode value={twoFAConfigData?.otpauthUrl || ''} />+ </div>+ <p className='text-base whitespace-pre-line mt-2 text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faQRAlt', { key: twoFAConfigData?.secret || '' })}+ </p>+ <div className='flex items-center mt-4'>+ <Input+ type='text'+ label={t('profileSettings.enter2faToEnable')}+ value={twoFACode}+ placeholder={t('profileSettings.yourOneTimeCode')}+ className='sm:col-span-3'+ onChange={handle2FAInput}+ onKeyDown={callFnOnKeyPress(_enable2FA)}+ error={twoFACodeError}+ disabled={isTwoFaLoading}+ />+ <Button+ className={cx('ml-2', {+ 'mt-8 xs:mt-4': _isNull(twoFACodeError),+ 'mb-1': !_isNull(twoFACodeError),+ })}+ onClick={_enable2FA}+ loading={isTwoFaLoading}+ primary+ large+ >+ {t('common.enable')}+ </Button>+ </div>+ </>+ )+ }++ return (+ <>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faEnable')}+ </p>+ <Button className='mt-4' onClick={_generate2FA} loading={isTwoFaLoading} primary large>+ {t('profileSettings.2faEnableBtn')}+ </Button>+ </>+ )+}++export default memo(TwoFA)diff --git a/app/pages/UserSettings/index.tsx b/app/pages/UserSettings/index.tsxnew file mode 100644index 000000000..f15e496b0--- /dev/null+++ b/app/pages/UserSettings/index.tsx@@ -0,0 +1,3 @@+import UserSettings from './UserSettings.container'++export default UserSettings