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.2 KB
Raw Blame
import NumberFlow from '@number-flow/react'
import cx from 'clsx'
import _find from 'lodash/find'
import _isNumber from 'lodash/isNumber'
import _replace from 'lodash/replace'
import _size from 'lodash/size'
import {
  SlidersHorizontalIcon,
  PushPinIcon,
  CaretUpIcon,
  CaretDownIcon,
} from '@phosphor-icons/react'
import React, { useState, useMemo, useCallback, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from '~/ui/Link'
import { useFetcher, useNavigate } from 'react-router'
import { toast } from 'sonner'

import {
  FLOW_TIMING,
  FLOW_VALUE_CLASS,
  useFlowValue,
} from '~/hooks/useFlowValue'
import { OverallObject, Project } from '~/lib/models/Project'
import { useAuth } from '~/providers/AuthProvider'
import type { DashboardActionData } from '~/routes/dashboard'
import { Badge, BadgeProps } from '~/ui/Badge'
import Spin from '~/ui/icons/Spin'
import Modal from '~/ui/Modal'
import { Text } from '~/ui/Text'
import {
  nFormatter,
  nFormatterSeparated,
  calculateRelativePercentage,
} from '~/utils/generic'
import { getFaviconHost, getFaviconUrl } from '~/utils/referrers'
import routes from '~/utils/routes'

import Sparkline from './Sparkline'

// Detect if device supports hover (i.e., not a touch-only device)
const useIsTouchDevice = () => {
  // Important for SSR hydration: first client render must match server output.
  const [isTouchDevice, setIsTouchDevice] = useState(false)

  useEffect(() => {
    if (typeof window === 'undefined') {
      return
    }

    const mediaQuery = window.matchMedia('(hover: none)')
    queueMicrotask(() => setIsTouchDevice(mediaQuery.matches))

    const handler = (e: MediaQueryListEvent) => setIsTouchDevice(e.matches)
    mediaQuery.addEventListener('change', handler)
    return () => mediaQuery.removeEventListener('change', handler)
  }, [])

  return isTouchDevice
}

interface ProjectCardProps {
  live?: string | number | null
  overallStats?: OverallObject
  project: Project
  activePeriod: string
  viewMode: 'grid' | 'list'
  refetchProjects: () => void
}

// Rolls the live visitor count in on load and on every live-stats refresh
const FlowingNumber = ({ value }: { value: number }) => {
  const flowValue = useFlowValue(value)
  const [num, symbol] = nFormatterSeparated(flowValue, 1) as [
    number,
    string | null,
  ]

  return (
    <NumberFlow
      className={FLOW_VALUE_CLASS}
      {...FLOW_TIMING}
      value={num}
      suffix={symbol ?? undefined}
      format={{ maximumFractionDigits: 1 }}
      willChange
    />
  )
}

interface MiniCardProps {
  labelTKey: string
  total?: number | string | null
  percChange?: number
  hasData?: boolean
  flow?: boolean
}

const MiniCard = ({
  labelTKey,
  total,
  percChange,
  hasData,
  flow,
}: MiniCardProps) => {
  const { t } = useTranslation('common')
  const statsDidGrowUp = percChange ? percChange >= 0 : false
  const isLoading = total === null

  return (
    <div>
      <Text as='p' size='sm' colour='muted'>
        {t(labelTKey)}
      </Text>

      <div className='flex font-bold'>
        {isLoading ? (
          <Spin className='mt-2 ml-0!' />
        ) : !hasData || total === 'N/A' ? (
          <div className='flex items-baseline gap-1'>
            <Text as='p' weight='bold' size='sm' colour='muted'>
              —
            </Text>
            <Text as='span' size='xs' colour='muted' className='font-normal'>
              {t('dashboard.noData')}
            </Text>
          </div>
        ) : (
          <>
            <Text as='p' weight='bold' size='base' colour='secondary'>
              {!_isNumber(total) ? (
                total
              ) : flow ? (
                <FlowingNumber value={total} />
              ) : (
                nFormatter(total)
              )}
            </Text>
            {_isNumber(percChange) && percChange !== 0 ? (
              <Text
                as='p'
                size='xs'
                weight='medium'
                colour={statsDidGrowUp ? 'success' : 'muted'}
                className='-mt-3 flex items-center'
              >
                {statsDidGrowUp ? (
                  <>
                    <CaretUpIcon className='size-3.5 shrink-0 text-green-500' />
                    <span className='sr-only'>{t('dashboard.inc')}</span>
                  </>
                ) : (
                  <>
                    <CaretDownIcon className='size-3.5 shrink-0 text-slate-500 dark:text-slate-400' />
                    <span className='sr-only'>{t('dashboard.dec')}</span>
                  </>
                )}
                {nFormatter(percChange)}%
              </Text>
            ) : null}
          </>
        )}
      </div>
    </div>
  )
}

export const ProjectCard = ({
  live,
  project,
  overallStats,
  activePeriod,
  viewMode,
  refetchProjects,
}: ProjectCardProps) => {
  const { t } = useTranslation('common')
  const [showInviteModal, setShowInviteModal] = useState(false)
  const fetcher = useFetcher<DashboardActionData>()
  const navigate = useNavigate()

  const { user, mergeUser } = useAuth()
  const isTouchDevice = useIsTouchDevice()

  const shareId = useMemo(
    () => _find(project.share, (item) => item.user?.id === user?.id)?.id,
    [project.share, user?.id],
  )

  const {
    id,
    name,
    public: isPublic,
    active,
    isTransferring,
    share,
    organisation,
    role,
    isPinned,
    websiteUrl,
  } = project

  const faviconHost = useMemo(
    () => getFaviconHost(websiteUrl || null),
    [websiteUrl],
  )
  const [localIsPinned, setLocalIsPinned] = useState(isPinned)

  const isPinning =
    (fetcher.state === 'submitting' || fetcher.state === 'loading') &&
    (fetcher.formData?.get('intent') === 'pin-project' ||
      fetcher.formData?.get('intent') === 'unpin-project')

  const isAccepting =
    (fetcher.state === 'submitting' || fetcher.state === 'loading') &&
    fetcher.formData?.get('intent') === 'accept-project-share'

  // Sync local state with prop
  useEffect(() => {
    setLocalIsPinned(isPinned)
  }, [isPinned])

  const processedFetcherDataRef = useRef<DashboardActionData | undefined>(
    undefined,
  )

  // Handle fetcher responses
  useEffect(() => {
    if (!fetcher.data || fetcher.data === processedFetcherDataRef.current)
      return
    processedFetcherDataRef.current = fetcher.data

    const submittedProjectId = fetcher.formData?.get('projectId')
    const submittedShareId = fetcher.formData?.get('shareId')
    const isForThisCard =
      submittedProjectId === id || submittedShareId === shareId
    if (!isForThisCard) return

    if (fetcher.data.success) {
      const { intent } = fetcher.data

      if (intent === 'pin-project') {
        toast.success(t('dashboard.pinned'))
        refetchProjects()
      } else if (intent === 'unpin-project') {
        toast.success(t('dashboard.unpinned'))
        refetchProjects()
      } else if (intent === 'accept-project-share') {
        mergeUser({
          sharedProjects: user?.sharedProjects?.map((item) => {
            if (item.id === shareId) {
              return { ...item, isAccessConfirmed: true }
            }
            return item
          }),
        })
        refetchProjects()
        toast.success(t('apiNotifications.acceptInvitation'))
      }
    } else if (fetcher.data.error) {
      // Revert optimistic update on error
      if (
        fetcher.data.intent === 'pin-project' ||
        fetcher.data.intent === 'unpin-project'
      ) {
        setLocalIsPinned(isPinned)
      }
      toast.error(fetcher.data.error)
    }
  }, [
    fetcher.data,
    fetcher.formData,
    isPinned,
    shareId,
    user,
    mergeUser,
    refetchProjects,
    t,
    id,
  ])

  const handlePinToggle = useCallback(
    (e: React.MouseEvent) => {
      e.preventDefault()
      e.stopPropagation()

      if (isPinning) return

      // Optimistically update local state
      const newPinnedState = !localIsPinned
      setLocalIsPinned(newPinnedState)

      const formData = new FormData()
      formData.set('intent', newPinnedState ? 'pin-project' : 'unpin-project')
      formData.set('projectId', id)
      fetcher.submit(formData, { method: 'post' })
    },
    [id, localIsPinned, isPinning, fetcher],
  )

  const badges = useMemo(() => {
    const list: BadgeProps[] = []

    if (!active) {
      list.push({ colour: 'red', label: t('dashboard.disabled') })
    }

    if (organisation) {
      list.push({ colour: 'sky', label: organisation.name })
    }

    if (project.role !== 'owner' && shareId) {
      list.push({ colour: 'indigo', label: t('dashboard.shared') })
    }

    if (project.role !== 'owner' && !project.isAccessConfirmed) {
      list.push({ colour: 'yellow', label: t('common.pending') })
    }

    if (isTransferring) {
      list.push({ colour: 'indigo', label: t('common.transferring') })
    }

    if (isPublic) {
      list.push({ colour: 'green', label: t('dashboard.public') })
    }

    const members = _size(share)

    if (members > 0) {
      list.push({
        colour: 'slate',
        label: t('common.xMembers', { number: members + 1 }),
      })
    }

    return list
  }, [
    t,
    active,
    isTransferring,
    isPublic,
    organisation,
    share,
    project.isAccessConfirmed,
    project.role,
    shareId,
  ])

  const onAccept = () => {
    if (fetcher.state !== 'idle') {
      return
    }

    if (!shareId) {
      toast.error(t('apiNotifications.acceptInvitationError'))
      return
    }

    const formData = new FormData()
    formData.set('intent', 'accept-project-share')
    formData.set('shareId', shareId)
    fetcher.submit(formData, { method: 'post' })
  }

  const onElementClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    if (project.role === 'owner' || project.isAccessConfirmed) {
      return
    }

    e.preventDefault()
    setShowInviteModal(true)
  }

  const searchParams = useMemo(() => {
    const params = new URLSearchParams()

    params.set('period', activePeriod)

    return params.toString()
  }, [activePeriod])

  // Determine if action buttons should always be visible
  // Show on touch devices, or when project is pinned
  const alwaysShowActions = isTouchDevice || localIsPinned

  return (
    <Link
      to={{
        pathname: _replace(routes.project, ':id', id),
        search: searchParams,
      }}
      onClick={onElementClick}
      className={cx(
        'group relative cursor-pointer overflow-hidden rounded-xl border border-gray-200 bg-gray-50 transition-colors hover:bg-gray-200/70 dark:border-slate-800/60 dark:bg-slate-900/25 dark:hover:bg-slate-900',
        viewMode === 'list'
          ? 'flex items-center justify-between px-6 py-4'
          : 'min-h-[153.1px]',
      )}
    >
      {/* Background sparkline chart */}
      {viewMode === 'grid' && overallStats?.chart ? (
        <div className='pointer-events-none absolute inset-x-0 bottom-0 z-0 opacity-50'>
          <Sparkline chart={overallStats.chart} className='w-full' />
        </div>
      ) : null}
      <div
        className={cx(
          'relative z-10 flex flex-col',
          viewMode === 'list' ? 'flex-1' : 'px-4 py-4',
        )}
      >
        <div
          className={cx(
            'flex items-center',
            viewMode === 'grid' ? 'justify-between' : 'justify-start gap-1',
          )}
        >
          <div className='flex min-w-0 items-center gap-1'>
            {faviconHost ? (
              <img
                className='size-6 shrink-0 rounded-sm'
                src={getFaviconUrl(faviconHost)}
                loading='lazy'
                alt=''
                aria-hidden='true'
              />
            ) : null}
            <Text as='p' size='lg' weight='semibold' truncate>
              {name}
            </Text>
          </div>

          <div
            className={cx(
              'flex shrink-0 items-center transition-opacity',
              alwaysShowActions
                ? 'opacity-100'
                : 'opacity-0 group-hover:opacity-100',
            )}
          >
            <button
              type='button'
              className='rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-300 dark:hover:border-slate-700/80 dark:hover:bg-slate-900 dark:hover:text-slate-300'
              onClick={handlePinToggle}
              disabled={isPinning}
              aria-label={
                localIsPinned ? t('dashboard.unpin') : t('dashboard.pin')
              }
            >
              <PushPinIcon
                className='size-5 transition-transform'
                weight={localIsPinned ? 'duotone' : 'regular'}
              />
            </button>
            {project.isAccessConfirmed && role !== 'viewer' ? (
              <button
                type='button'
                className='rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-300 dark:hover:border-slate-700/80 dark:hover:bg-slate-900 dark:hover:text-slate-300'
                onClick={(e) => {
                  e.preventDefault()
                  e.stopPropagation()
                  navigate(_replace(routes.project_settings, ':id', id))
                }}
                aria-label={`${t('project.settings.settings')} ${name}`}
              >
                <SlidersHorizontalIcon className='size-5' />
              </button>
            ) : null}
          </div>
        </div>
        <div className='mt-1 flex shrink-0 flex-wrap gap-2'>
          {badges.length > 0 ? (
            badges.map((badge) => (
              <Badge key={badge.label as string} {...badge} />
            ))
          ) : (
            <Badge label='I' colour='slate' className='invisible' />
          )}
        </div>
      </div>
      <div
        className={cx(
          'relative z-10 flex shrink-0 gap-5',
          viewMode === 'list' ? 'ml-4' : 'mt-4 px-4 pb-4',
        )}
      >
        <MiniCard
          labelTKey='dashboard.pageviews'
          total={live === 'N/A' ? 'N/A' : (overallStats?.current.all ?? null)}
          percChange={
            live === 'N/A'
              ? 0
              : calculateRelativePercentage(
                  overallStats?.previous.all ?? 0,
                  overallStats?.current.all ?? 0,
                )
          }
          hasData={
            project?.isDataExists ||
            project?.isErrorDataExists ||
            project?.isCaptchaDataExists
          }
        />
        <MiniCard
          labelTKey='dashboard.liveVisitors'
          total={live}
          flow
          hasData={
            project?.isDataExists ||
            project?.isErrorDataExists ||
            project?.isCaptchaDataExists
          }
        />
      </div>
      {project.role !== 'owner' && !project.isAccessConfirmed ? (
        <Modal
          onClose={() => {
            setShowInviteModal(false)
          }}
          onSubmit={() => {
            setShowInviteModal(false)
            onAccept()
          }}
          submitText={t('common.accept')}
          submitDisabled={isAccepting}
          type='confirmed'
          closeText={t('common.cancel')}
          title={t('dashboard.invitationFor', { project: name })}
          message={t('dashboard.invitationDesc', { project: name })}
          isOpened={showInviteModal}
        />
      ) : null}
    </Link>
  )
}