Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

move new project creation to a modal window

Blue Mouse1ced297a3e93
diff --git a/web/app/pages/Dashboard/AddProject.tsx b/web/app/pages/Dashboard/AddProject.tsx
index 0a85d27e7..c55b83972 100644
--- a/web/app/pages/Dashboard/AddProject.tsx
+++ b/web/app/pages/Dashboard/AddProject.tsx
@@ -2,12 +2,9 @@ import { FolderPlusIcon } from '@heroicons/react/24/outline'
import cx from 'clsx'
import React from 'react'
import { useTranslation } from 'react-i18next'
-import { Link } from 'react-router'
-
-import routes from '~/utils/routes'
interface AddProjectProps {
- onClick: (e: React.MouseEvent<HTMLAnchorElement>) => void
+ onClick: () => void
sitesCount: number
viewMode: 'grid' | 'list'
}
@@ -16,15 +13,15 @@ export const AddProject = ({ onClick, sitesCount, viewMode }: AddProjectProps) =
const { t } = useTranslation('common')
return (
- <Link
- to={routes.new_project}
+ <button
+ type='button'
onClick={onClick}
className={cx(
'group cursor-pointer border-2 border-dashed border-gray-300 hover:border-gray-400',
viewMode === 'list'
? 'flex h-[72px] items-center justify-center rounded-lg'
: cx('flex h-auto min-h-[153.1px] items-center justify-center rounded-lg', {
- 'lg:min-h-[auto]': sitesCount % 3 !== 0,
+ 'lg:min-h-auto': sitesCount % 3 !== 0,
}),
)}
>
@@ -39,6 +36,6 @@ export const AddProject = ({ onClick, sitesCount, viewMode }: AddProjectProps) =
{t('dashboard.newProject')}
</span>
</div>
- </Link>
+ </button>
)
}
diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsx
index 9b11cfdaa..c217f8b1d 100644
--- a/web/app/pages/Dashboard/Dashboard.tsx
+++ b/web/app/pages/Dashboard/Dashboard.tsx
@@ -1,5 +1,6 @@
import cx from 'clsx'
import _isEmpty from 'lodash/isEmpty'
+import _keys from 'lodash/keys'
import _map from 'lodash/map'
import _size from 'lodash/size'
import { StretchHorizontalIcon, LayoutGridIcon, SearchIcon, XIcon, FolderPlusIcon, CircleXIcon } from 'lucide-react'
@@ -7,8 +8,9 @@ import React, { useState, useEffect, useRef, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useLoaderData, useNavigate, useSearchParams } from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
+import { toast } from 'sonner'
-import { getProjects, getLiveVisitors, getOverallStats, getOverallStatsCaptcha } from '~/api'
+import { getProjects, getLiveVisitors, getOverallStats, getOverallStatsCaptcha, createProject } from '~/api'
import DashboardLockedBanner from '~/components/DashboardLockedBanner'
import EventsRunningOutBanner from '~/components/EventsRunningOutBanner'
import { withAuthentication, auth } from '~/hoc/protected'
@@ -19,9 +21,12 @@ import { isSelfhosted, LIVE_VISITORS_UPDATE_INTERVAL, tbPeriodPairs } from '~/li
import { Overall, Project } from '~/lib/models/Project'
import { FeatureFlag } from '~/lib/models/User'
import { useAuth } from '~/providers/AuthProvider'
+import Input from '~/ui/Input'
import Modal from '~/ui/Modal'
import Pagination from '~/ui/Pagination'
+import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
+import { trackCustom } from '~/utils/analytics'
import { setCookie } from '~/utils/cookie'
import routes from '~/utils/routes'
@@ -39,6 +44,9 @@ const DASHBOARD_VIEW = {
LIST: 'list',
} as const
+const MAX_PROJECT_NAME_LENGTH = 50
+const DEFAULT_PROJECT_NAME = 'Untitled Project'
+
const Dashboard = () => {
const { viewMode: defaultViewMode } = useLoaderData<any>()
const { user, isLoading: authLoading } = useAuth()
@@ -100,6 +108,27 @@ const Dashboard = () => {
return sortParam && Object.values(SORT_OPTIONS).includes(sortParam as any) ? sortParam : SORT_OPTIONS.ALPHA_ASC
})
+ // New project modal state
+ const [newProjectModalOpen, setNewProjectModalOpen] = useState(false)
+ const [newProjectName, setNewProjectName] = useState('')
+ const [newProjectOrganisationId, setNewProjectOrganisationId] = useState<string | undefined>(undefined)
+ const [isNewProjectLoading, setIsNewProjectLoading] = useState(false)
+ const [newProjectError, setNewProjectError] = useState<string | null>(null)
+ const [newProjectBeenSubmitted, setNewProjectBeenSubmitted] = useState(false)
+
+ const organisations = useMemo(
+ () => [
+ {
+ id: undefined as string | undefined,
+ name: t('common.notSet'),
+ },
+ ...(user?.organisationMemberships || [])
+ .filter((om) => om.confirmed && (om.role === 'admin' || om.role === 'owner'))
+ .map((om) => om.organisation),
+ ],
+ [user?.organisationMemberships, t],
+ )
+
const pageAmount = Math.ceil(paginationTotal / pageSize)
// This search represents what's inside the search input
@@ -157,13 +186,75 @@ const Dashboard = () => {
const _viewMode = isAboveLgBreakpoint ? viewMode : 'grid'
- const onNewProject = (e: React.MouseEvent<HTMLAnchorElement>) => {
- if (user?.isActive || isSelfhosted) {
+ const onNewProject = () => {
+ if (!user?.isActive && !isSelfhosted) {
+ setShowActivateEmailModal(true)
return
}
- e.preventDefault()
- setShowActivateEmailModal(true)
+ setNewProjectModalOpen(true)
+ }
+
+ const validateProjectName = () => {
+ const errors: { name?: string } = {}
+
+ if (_isEmpty(newProjectName)) {
+ errors.name = t('project.settings.noNameError')
+ }
+
+ if (_size(newProjectName) > MAX_PROJECT_NAME_LENGTH) {
+ errors.name = t('project.settings.pxCharsError', { amount: MAX_PROJECT_NAME_LENGTH })
+ }
+
+ return { errors, valid: _isEmpty(_keys(errors)) }
+ }
+
+ const onCreateProject = async () => {
+ if (isNewProjectLoading) {
+ return
+ }
+
+ setNewProjectBeenSubmitted(true)
+ const { errors, valid } = validateProjectName()
+
+ if (!valid) {
+ setNewProjectError(errors.name || null)
+ return
+ }
+
+ setIsNewProjectLoading(true)
+
+ try {
+ await createProject({
+ name: newProjectName || DEFAULT_PROJECT_NAME,
+ organisationId: newProjectOrganisationId,
+ })
+ trackCustom('PROJECT_CREATED', {
+ from: 'dashboard-modal',
+ })
+
+ await refetchProjects()
+
+ toast.success(t('project.settings.created'))
+ closeNewProjectModal()
+ } catch (reason: any) {
+ setNewProjectError(reason)
+ toast.error(reason)
+ } finally {
+ setIsNewProjectLoading(false)
+ }
+ }
+
+ const closeNewProjectModal = () => {
+ if (isNewProjectLoading) {
+ return
+ }
+
+ setNewProjectModalOpen(false)
+ setNewProjectError(null)
+ setNewProjectName('')
+ setNewProjectOrganisationId(undefined)
+ setNewProjectBeenSubmitted(false)
}
const refetchProjects = async () => {
@@ -432,14 +523,14 @@ const Dashboard = () => {
</button>
) : null}
</div>
- <Link
- to={routes.new_project}
+ <button
+ type='button'
onClick={onNewProject}
className='ml-3 inline-flex cursor-pointer items-center justify-center rounded-md border border-transparent bg-slate-900 p-2 text-center text-sm font-medium text-white transition-colors hover:bg-slate-700 dark:border-gray-800 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
>
<FolderPlusIcon className='mr-1 h-5 w-5' strokeWidth={1.5} />
{t('dashboard.newProject')}
- </Link>
+ </button>
</div>
</div>
{isSearchActive ? (
@@ -548,6 +639,50 @@ const Dashboard = () => {
message={t('dashboard.verifyEmailDesc')}
isOpened={showActivateEmailModal}
/>
+ <Modal
+ isLoading={isNewProjectLoading}
+ onClose={closeNewProjectModal}
+ onSubmit={onCreateProject}
+ submitText={t('common.continue')}
+ overflowVisible
+ message={
+ <div>
+ <Input
+ name='project-name-input'
+ label={t('project.settings.name')}
+ value={newProjectName}
+ placeholder='My awesome website'
+ onChange={(e) => setNewProjectName(e.target.value)}
+ error={newProjectBeenSubmitted ? newProjectError : null}
+ />
+ {organisations.length > 1 ? (
+ <div className='mt-4'>
+ <Select
+ items={organisations}
+ keyExtractor={(item) => item.id || 'not-set'}
+ labelExtractor={(item) => {
+ if (item.id === undefined) {
+ return <span className='italic'>{t('common.notSet')}</span>
+ }
+
+ return item.name
+ }}
+ onSelect={(item) => {
+ setNewProjectOrganisationId(item.id)
+ }}
+ label={t('project.settings.organisation')}
+ title={organisations.find((org) => org.id === newProjectOrganisationId)?.name}
+ selectedItem={organisations.find((org) => org.id === newProjectOrganisationId)}
+ />
+ </div>
+ ) : null}
+ <p className='mt-2 text-sm text-gray-500 italic dark:text-gray-300'>{t('project.settings.createHint')}</p>
+ </div>
+ }
+ title={t('project.settings.create')}
+ isOpened={newProjectModalOpen}
+ submitDisabled={!newProjectName}
+ />
</>
)
}
diff --git a/web/app/pages/Dashboard/NoProjects.tsx b/web/app/pages/Dashboard/NoProjects.tsx
index 7ecf40950..1bc98790a 100644
--- a/web/app/pages/Dashboard/NoProjects.tsx
+++ b/web/app/pages/Dashboard/NoProjects.tsx
@@ -2,15 +2,13 @@ import { FolderPlusIcon } from '@heroicons/react/24/outline'
import { FolderInputIcon } from 'lucide-react'
import React from 'react'
import { useTranslation } from 'react-i18next'
-import { Link } from 'react-router'
import { Text } from '~/ui/Text'
-import routes from '~/utils/routes'
import { DASHBOARD_TABS } from './Tabs'
interface NoProjectsProps {
- onClick: (e: React.MouseEvent<HTMLAnchorElement>) => void
+ onClick: () => void
activeTab: (typeof DASHBOARD_TABS)[number]['id']
search: string
}
@@ -42,14 +40,14 @@ export const NoProjects = ({ onClick, activeTab, search }: NoProjectsProps) => {
{t('dashboard.createProject')}
</Text>
<div className='mt-6'>
- <Link
- to={routes.new_project}
+ <button
+ type='button'
onClick={onClick}
className='inline-flex items-center justify-center rounded-md border border-transparent bg-slate-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-slate-700 dark:border-gray-800 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
>
<FolderPlusIcon className='mr-2 h-5 w-5' />
{t('dashboard.newProject')}
- </Link>
+ </button>
</div>
</div>
)
diff --git a/web/app/pages/Project/New/index.tsx b/web/app/pages/Project/New/index.tsx
deleted file mode 100644
index ad561c41b..000000000
--- a/web/app/pages/Project/New/index.tsx
+++ /dev/null
@@ -1,207 +0,0 @@
-import _isEmpty from 'lodash/isEmpty'
-import _keys from 'lodash/keys'
-import _size from 'lodash/size'
-import React, { useState, useEffect, useMemo } from 'react'
-import { useTranslation } from 'react-i18next'
-import { Link, useNavigate } from 'react-router'
-import { toast } from 'sonner'
-
-import { createProject } from '~/api'
-import { withAuthentication, auth } from '~/hoc/protected'
-import { isSelfhosted, TITLE_SUFFIX } from '~/lib/constants'
-import { Project } from '~/lib/models/Project'
-import { useAuth } from '~/providers/AuthProvider'
-import Button from '~/ui/Button'
-import Input from '~/ui/Input'
-import Loader from '~/ui/Loader'
-import Select from '~/ui/Select'
-import { Text } from '~/ui/Text'
-import { trackCustom } from '~/utils/analytics'
-import routes from '~/utils/routes'
-
-export const MAX_PROJECT_NAME_LENGTH = 50
-
-const DEFAULT_PROJECT_NAME = 'Untitled Project'
-
-const NewProject = () => {
- const { user, isLoading } = useAuth()
- const { t } = useTranslation('common')
- const navigate = useNavigate()
-
- const [form, setForm] = useState<Partial<Project>>({
- name: '',
- organisationId: undefined,
- })
- const [validated, setValidated] = useState(false)
- const [errors, setErrors] = useState<{
- name?: string
- }>({})
- const [beenSubmitted, setBeenSubmitted] = useState(false)
- const [projectSaving, setProjectSaving] = useState(false)
-
- const organisations = useMemo(
- () => [
- {
- id: undefined,
- name: t('common.notSet'),
- },
- ...(user?.organisationMemberships || [])
- .filter((om) => om.confirmed && (om.role === 'admin' || om.role === 'owner'))
- .map((om) => om.organisation),
- ],
- [user?.organisationMemberships, t],
- )
-
- useEffect(() => {
- if (isLoading || !user) {
- return
- }
-
- if (!user.isActive && !isSelfhosted) {
- toast.error(t('project.settings.verify'))
- navigate(routes.dashboard)
- }
- }, [user, navigate, t, isLoading])
-
- const onSubmit = async (data: Partial<Project>) => {
- if (!projectSaving) {
- setProjectSaving(true)
- try {
- await createProject({
- name: data.name || DEFAULT_PROJECT_NAME,
- organisationId: data.organisationId,
- })
- trackCustom('PROJECT_CREATED', {
- from: 'new-project',
- })
- navigate(routes.dashboard)
- toast.success(t('project.settings.created'))
- } catch (reason: any) {
- toast.error(reason)
- } finally {
- setProjectSaving(false)
- }
- }
- }
-
- const validate = () => {
- const allErrors: {
- name?: string
- } = {}
-
- if (_isEmpty(form.name)) {
- allErrors.name = t('project.settings.noNameError')
- }
-
- if (_size(form.name) > MAX_PROJECT_NAME_LENGTH) {
- allErrors.name = t('project.settings.pxCharsError', { amount: MAX_PROJECT_NAME_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)
- }
- }
-
- useEffect(() => {
- document.title = `${t('project.settings.create')} ${TITLE_SUFFIX}`
- }, [t])
-
- if (isLoading) {
- return (
- <div className='flex min-h-min-footer flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900'>
- <Loader />
- </div>
- )
- }
-
- return (
- <div className='flex min-h-min-footer flex-col bg-gray-50 dark:bg-slate-900'>
- <form className='mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8' onSubmit={handleSubmit}>
- <Text as='h2' size='3xl' weight='bold' className='mt-2'>
- {t('project.settings.create')}
- </Text>
- <Input
- name='name'
- label={t('project.settings.name')}
- value={form.name}
- placeholder='My awesome website'
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.name : null}
- />
-
- {organisations.length > 1 ? (
- <div className='mt-4'>
- <Select
- items={organisations}
- keyExtractor={(item) => item.id || 'not-set'}
- labelExtractor={(item) => {
- if (item.id === undefined) {
- return <span className='italic'>{t('common.notSet')}</span>
- }
-
- return item.name
- }}
- onSelect={(item) => {
- setForm((oldForm) => ({
- ...oldForm,
- organisationId: item.id,
- }))
- }}
- label={t('project.settings.organisation')}
- title={organisations.find((org) => org.id === form.organisationId)?.name}
- selectedItem={organisations.find((org) => org.id === form.organisationId)}
- />
- </div>
- ) : null}
-
- <Text as='p' size='sm' colour='muted' className='mt-1 mb-4 italic'>
- {t('project.settings.createHint')}
- </Text>
-
- <div>
- <Button
- className='mr-2 border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
- as={Link}
- // @ts-expect-error
- to={routes.dashboard}
- secondary
- regular
- >
- {t('common.cancel')}
- </Button>
- <Button type='submit' loading={projectSaving} primary regular>
- {t('common.save')}
- </Button>
- </div>
- </form>
- </div>
- )
-}
-
-export default withAuthentication(NewProject, auth.authenticated)
diff --git a/web/app/routes/projects.new.tsx b/web/app/routes/projects.new.tsx
deleted file mode 100644
index 15d5429a6..000000000
--- a/web/app/routes/projects.new.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import type { SitemapFunction } from 'remix-sitemap'
-
-import NewProject from '~/pages/Project/New'
-
-export const sitemap: SitemapFunction = () => ({
- exclude: true,
-})
-
-export default function Index() {
- return <NewProject />
-}
diff --git a/web/app/utils/routes.ts b/web/app/utils/routes.ts
index 0af556433..4de9e9c4a 100644
--- a/web/app/utils/routes.ts
+++ b/web/app/utils/routes.ts
@@ -13,7 +13,6 @@ const routes = Object.freeze({
user_settings: '/user-settings',
verify: '/verify/:id',
change_email: '/change-email/:id',
- new_project: '/projects/new',
new_captcha: '/captchas/new',
project_settings: '/projects/settings/:id',
captcha_settings: '/captchas/settings/:id',
diff --git a/web/app/utils/server.ts b/web/app/utils/server.ts
index 706e21f91..d4e8d653a 100644
--- a/web/app/utils/server.ts
+++ b/web/app/utils/server.ts
@@ -120,7 +120,6 @@ export const getPageMeta = (t: typeof i18next.t, url?: string, _pathname?: strin
}
break
- case routes.new_project:
case routes.new_captcha:
result = {
title: t('project.settings.create'),