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!

15.9 KB
Raw Blame
import {
  InfoIcon,
  MagnifyingGlassIcon,
  FolderPlusIcon,
  XIcon,
} from '@phosphor-icons/react'
import _filter from 'lodash/filter'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import _replace from 'lodash/replace'
import { useState, useEffect, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from '~/ui/Link'
import { useFetcher } from 'react-router'
import { toast } from 'sonner'

import { useDeduplicateFetcherResponse } from '~/hooks/useDeduplicateFetcherResponse'
import useDebounce from '~/hooks/useDebounce'
import { DetailedOrganisation } from '~/lib/models/Organisation'
import { Project } from '~/lib/models/Project'
import { useAuth } from '~/providers/AuthProvider'
import type { OrganisationSettingsActionData } from '~/routes/organisations.$id'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
import Pagination from '~/ui/Pagination'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
import routes from '~/utils/routes'

interface SelectAProjectProps {
  onSelect: (project: Project) => void
}

const PROJECT_SELECT_PAGE_SIZE = 5
const PROJECT_LIST_PAGE_SIZE = 20
type SubmittedProject = Pick<Project, 'id' | 'name'> & {
  admin?: {
    email?: string
  }
}

const SelectAProject = ({ onSelect }: SelectAProjectProps) => {
  const { t } = useTranslation('common')
  const fetcher = useFetcher<OrganisationSettingsActionData>()

  const [currentPage, setCurrentPage] = useState(1)
  const [search, setSearch] = useState('')
  const [projects, setProjects] = useState<Project[]>([])
  const [total, setTotal] = useState(0)

  const debouncedSearch = useDebounce(search, 500)
  const pageAmount = Math.ceil(total / PROJECT_SELECT_PAGE_SIZE)
  const isLoading =
    fetcher.state === 'submitting' || fetcher.state === 'loading'

  // Fetch projects when page or search changes
  useEffect(() => {
    const formData = new FormData()
    formData.set('intent', 'get-available-projects')
    formData.set('take', String(PROJECT_SELECT_PAGE_SIZE))
    formData.set('skip', String((currentPage - 1) * PROJECT_SELECT_PAGE_SIZE))
    formData.set('search', debouncedSearch)
    fetcher.submit(formData, { method: 'post' })
  }, [currentPage, debouncedSearch]) // eslint-disable-line react-hooks/exhaustive-deps

  // Update local state when fetcher returns data
  useEffect(() => {
    if (
      fetcher.data?.intent === 'get-available-projects' &&
      fetcher.data?.availableProjects
    ) {
      setTimeout(() => {
        setProjects(fetcher.data!.availableProjects!.results as Project[])
        setTotal(fetcher.data!.availableProjects!.total)
      }, 0)
    }
  }, [fetcher.data])

  useEffect(() => {
    setTimeout(() => setCurrentPage(1), 0)
  }, [debouncedSearch])

  return (
    <div className='mt-4 flex flex-col'>
      <div className='mb-4'>
        <Input
          type='search'
          aria-label={t('project.search')}
          placeholder={t('project.search')}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          classes={{ input: 'py-1.5' }}
          leadingIcon={<MagnifyingGlassIcon className='size-4' />}
        />
      </div>

      {isLoading ? (
        <Loader />
      ) : (
        <div className='overflow-hidden rounded-lg border border-gray-200 dark:border-slate-600'>
          <ul className='divide-y divide-gray-200 dark:divide-slate-600'>
            {_map(
              _filter(projects, ({ uiHidden }) => !uiHidden),
              (project) => (
                <li
                  key={project.id}
                  className='hover:bg-gray-50 dark:hover:bg-slate-800'
                >
                  <button
                    type='button'
                    aria-label={project.name}
                    onClick={() => onSelect(project)}
                    className='flex w-full cursor-pointer items-center px-4 py-4 text-left sm:px-6'
                  >
                    <div className='min-w-0 flex-1'>
                      <Text
                        as='span'
                        size='sm'
                        weight='medium'
                        className='truncate'
                      >
                        {project.name}
                      </Text>
                    </div>
                  </button>
                </li>
              ),
            )}
          </ul>
        </div>
      )}

      {pageAmount > 1 ? (
        <Pagination
          className='mt-4'
          page={currentPage}
          pageAmount={pageAmount}
          setPage={setCurrentPage}
          total={total}
          pageSize={PROJECT_SELECT_PAGE_SIZE}
        />
      ) : null}
    </div>
  )
}

const NoProjects = () => {
  const { t } = useTranslation('common')

  return (
    <div className='flex flex-col py-6 sm:px-6 lg:px-8'>
      <div className='mx-auto w-full max-w-7xl'>
        <Text as='h2' size='xl' className='mb-8 px-4 text-center leading-snug'>
          {t('organisations.noProjectsFound')}
        </Text>
      </div>
    </div>
  )
}

interface ProjectListProps {
  projects: DetailedOrganisation['projects']
  onRemove: (project: DetailedOrganisation['projects'][number]) => void
}

const ProjectList = ({ projects, onRemove }: ProjectListProps) => {
  const { t } = useTranslation('common')
  const { user } = useAuth()

  return projects.map((project) => (
    <tr
      key={project.id}
      aria-label={project.name}
      className='bg-white hover:bg-gray-50 dark:bg-slate-950 dark:hover:bg-slate-900/50'
    >
      <td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>
        <Link
          to={_replace(routes.project, ':id', project.id)}
          className='hover:underline'
        >
          {project.name}
        </Link>
      </td>
      <td className='px-4 py-3 text-right text-sm whitespace-nowrap'>
        <div className='flex items-center justify-end'>
          {project.admin.email !== user?.email ? (
            <Tooltip
              className='mr-2'
              text={t('organisations.projectOwnedBy', {
                email: project.admin.email,
              })}
              tooltipNode={
                <InfoIcon className='size-5 text-gray-400' aria-hidden='true' />
              }
            />
          ) : null}

          <Button variant='danger' size='xs' onClick={() => onRemove(project)}>
            {t('common.remove')}
          </Button>
        </div>
      </td>
    </tr>
  ))
}

interface ProjectsProps {
  organisation: DetailedOrganisation
}

export const Projects = ({ organisation }: ProjectsProps) => {
  const { t } = useTranslation('common')
  const { user } = useAuth()
  const fetcher = useFetcher<OrganisationSettingsActionData>()

  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [showAddProjectModal, setShowAddProjectModal] = useState(false)
  const [projectToRemove, setProjectToRemove] = useState<
    DetailedOrganisation['projects'][number] | null
  >(null)
  const [selectedProject, setSelectedProject] = useState<any>(null)
  const submittedProjectRef = useRef<SubmittedProject | null>(null)
  const shouldHandleFetcherData =
    useDeduplicateFetcherResponse<OrganisationSettingsActionData>()

  const [currentPage, setCurrentPage] = useState(1)
  const [search, setSearch] = useState('')
  const [isSearchActive, setIsSearchActive] = useState(false)
  const { projects: organisationProjects } = organisation
  const [projects, setProjects] = useState<DetailedOrganisation['projects']>(
    () => organisationProjects,
  )

  const isSubmitting = fetcher.state === 'submitting'
  const isAddingProject =
    isSubmitting && fetcher.formData?.get('intent') === 'add-project'
  const isRemovingProject =
    isSubmitting && fetcher.formData?.get('intent') === 'remove-project'

  useEffect(() => {
    setProjects(organisationProjects)
  }, [organisationProjects])

  /* eslint-disable react-hooks/set-state-in-effect */
  useEffect(() => {
    if (!fetcher.data) return
    if (!shouldHandleFetcherData(fetcher.data)) return

    if (fetcher.data?.success) {
      const { intent } = fetcher.data
      if (intent === 'add-project') {
        const submittedProject = submittedProjectRef.current
        if (submittedProject) {
          setProjects((current) =>
            current.some((project) => project.id === submittedProject.id)
              ? current
              : [
                  ...current,
                  {
                    id: submittedProject.id,
                    name: submittedProject.name,
                    admin: {
                      email: submittedProject.admin?.email || user?.email || '',
                    },
                  },
                ],
          )
        }
        submittedProjectRef.current = null
        toast.success(t('apiNotifications.projectAddedToOrganisation'))
        setShowAddProjectModal(false)
        setSelectedProject(null)
      } else if (intent === 'remove-project') {
        const removedProjectId = fetcher.data.projectId || projectToRemove?.id
        if (removedProjectId) {
          setProjects((current) =>
            _filter(current, (project) => project.id !== removedProjectId),
          )
        }
        toast.success(t('apiNotifications.projectRemovedFromOrganisation'))
        setShowDeleteModal(false)
        setProjectToRemove(null)
      }
    } else if (fetcher.data?.error) {
      toast.error(fetcher.data.error)
    }
  }, [
    fetcher.data,
    projectToRemove?.id,
    t,
    user?.email,
    shouldHandleFetcherData,
  ])
  /* eslint-enable react-hooks/set-state-in-effect */

  const filteredProjects = useMemo(() => {
    if (!search) {
      return projects
    }

    return projects.filter((project) =>
      project.name.toLowerCase().includes(search),
    )
  }, [projects, search])

  const pageAmount = Math.ceil(filteredProjects.length / PROJECT_LIST_PAGE_SIZE)

  const removeProject = (projectId: string) => {
    const formData = new FormData()
    formData.set('intent', 'remove-project')
    formData.set('projectId', projectId)
    fetcher.submit(formData, { method: 'post' })
  }

  const onAddProject = () => {
    if (!selectedProject) return

    const submittedProject = selectedProject as SubmittedProject
    submittedProjectRef.current = submittedProject
    const formData = new FormData()
    formData.set('intent', 'add-project')
    formData.set('projectId', submittedProject.id)
    fetcher.submit(formData, { method: 'post' })
  }

  return (
    <div className='mt-6 mb-6'>
      <div className='mb-3 flex items-center justify-between'>
        <Text
          as='h3'
          size='lg'
          weight='bold'
          className='mt-2 flex items-center'
        >
          {t('organisations.projects')}
          {isSearchActive ? (
            <XIcon
              className='ml-2 size-5 cursor-pointer text-gray-900 hover:opacity-80 dark:text-gray-50'
              onClick={() => {
                setSearch('')
                setIsSearchActive(false)
              }}
            />
          ) : (
            <MagnifyingGlassIcon
              className='ml-2 size-5 cursor-pointer text-gray-900 hover:opacity-80 dark:text-gray-50'
              onClick={() => {
                setIsSearchActive(true)
              }}
            />
          )}
        </Text>
        <Button
          className='h-8 pl-2'
          type='button'
          onClick={() => {
            setShowAddProjectModal(true)
          }}
        >
          <>
            <FolderPlusIcon className='mr-1 h-5 w-5' />
            {t('organisations.addProject')}
          </>
        </Button>
      </div>
      {isSearchActive ? (
        <Input
          type='search'
          aria-label={t('project.search')}
          onChange={(e) => {
            setSearch(e.target.value.toLowerCase())
            setCurrentPage(1)
          }}
          value={search}
          className='mb-2'
          classes={{ input: 'h-8 py-1.5' }}
          leadingIcon={<MagnifyingGlassIcon className='size-4' />}
          placeholder={t('project.search')}
        />
      ) : null}
      <div>
        {_isEmpty(filteredProjects) ? (
          <NoProjects />
        ) : (
          <div className='overflow-hidden rounded-lg border border-gray-200 dark:border-slate-800'>
            <table className='min-w-full divide-y divide-gray-200 dark:divide-slate-800'>
              <thead className='bg-gray-50 dark:bg-slate-900'>
                <tr>
                  <th
                    scope='col'
                    className='px-4 py-3 text-left text-xs font-semibold tracking-wider text-gray-900 uppercase dark:text-white'
                  >
                    {t('common.name')}
                  </th>
                  <th scope='col' aria-label={t('ariaLabels.actions')} />
                </tr>
              </thead>
              <tbody className='divide-y divide-gray-200 bg-white dark:divide-slate-800 dark:bg-slate-950'>
                <ProjectList
                  projects={filteredProjects.slice(
                    (currentPage - 1) * PROJECT_LIST_PAGE_SIZE,
                    currentPage * PROJECT_LIST_PAGE_SIZE,
                  )}
                  onRemove={(project) => {
                    setProjectToRemove(project)
                    setShowDeleteModal(true)
                  }}
                />
              </tbody>
            </table>
            {pageAmount > 1 ? (
              <Pagination
                className='mt-4 px-2'
                page={currentPage}
                pageAmount={pageAmount}
                setPage={setCurrentPage}
                total={projects.length}
                pageSize={PROJECT_LIST_PAGE_SIZE}
              />
            ) : null}
          </div>
        )}
      </div>

      <Modal
        onClose={() => {
          setShowAddProjectModal(false)
          setSelectedProject(null)
        }}
        customButtons={
          <button
            type='button'
            className='inline-flex w-full justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-base font-medium text-white hover:bg-indigo-700 sm:ml-3 sm:w-auto sm:text-sm'
            onClick={onAddProject}
            disabled={!selectedProject || isAddingProject}
          >
            {t('organisations.addProject')}
          </button>
        }
        closeText={t('common.cancel')}
        title={t('organisations.modals.addProject.title', {
          organisation: organisation.name,
        })}
        message={
          <div>
            <Text as='p' size='base' colour='secondary' className='mt-2'>
              {t('organisations.modals.addProject.message')}
            </Text>

            {selectedProject ? (
              <div className='mt-4 flex items-center justify-between rounded-lg border border-gray-200 p-4 dark:border-slate-600'>
                <span className='text-sm font-medium text-gray-900 dark:text-white'>
                  {selectedProject.name}
                </span>
                <button
                  type='button'
                  onClick={() => setSelectedProject(null)}
                  className='text-sm text-red-600 hover:text-red-500'
                >
                  {t('common.remove')}
                </button>
              </div>
            ) : (
              <SelectAProject onSelect={setSelectedProject} />
            )}
          </div>
        }
        isOpened={showAddProjectModal}
        isLoading={isAddingProject}
      />

      <Modal
        onClose={() => {
          setShowDeleteModal(false)
          setProjectToRemove(null)
        }}
        onSubmit={() => {
          removeProject(projectToRemove!.id)
        }}
        submitText={t('common.yes')}
        closeText={t('common.no')}
        title={t('organisations.modals.remove.title', {
          project: projectToRemove?.name,
        })}
        message={t('organisations.modals.remove.message')}
        isOpened={showDeleteModal}
        type='warning'
        isLoading={isRemovingProject}
      />
    </div>
  )
}