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!

10.1 KB
Raw Blame
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useRef,
  useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import {
  useNavigate,
  useSearchParams,
  useFetcher,
  useLoaderData,
  useRevalidator,
} from 'react-router'
import { toast } from 'sonner'

import { getLiveVisitors } from '~/api/v2/endpoints'
import {
  LIVE_VISITORS_UPDATE_INTERVAL,
  LS_PROJECTS_PROTECTED_KEY,
  Period,
  TimeBucket,
  isBrowser,
} from '~/lib/constants'
import { type Project } from '~/lib/models/Project'
import type {
  ProjectLoaderData,
  ProjectViewActionData,
} from '~/routes/projects.$id'
import { getItemJSON } from '~/utils/localstorage'
import routes from '~/utils/routes'

import {
  PROJECT_PASSWORD_UPDATED_EVENT,
  setProjectPassword,
} from '../pages/Project/View/utils/cache'
import { CHART_METRICS_MAPPING } from '../pages/Project/View/ViewProject.helpers'

interface CurrentProjectContextType {
  id: string
  projectPath: string
  projectSettingsPath: string
  project: Project | null
  preferences: ProjectPreferences
  allowedToManage: boolean
  updatePreferences: (prefs: ProjectPreferences) => void
  mergeProject: (project: Partial<Project>) => void
  liveVisitors: number
  updateLiveVisitors: () => Promise<void>
  isPasswordRequired: boolean
  isCheckingStoredPassword: boolean
  submitPassword: (
    password: string,
  ) => Promise<{ success: boolean; error?: string }>
}

const CurrentProjectContext = createContext<
  CurrentProjectContextType | undefined
>(undefined)

interface CurrentProjectProviderProps {
  id: string
  projectPath?: string
  children: React.ReactNode
}

export const useProjectPassword = (id?: string) => {
  const [searchParams] = useSearchParams()
  const [cachedPassword, setCachedPassword] = useState(
    () => getItemJSON(LS_PROJECTS_PROTECTED_KEY)?.[id || ''] || '',
  )

  useEffect(() => {
    setCachedPassword(getItemJSON(LS_PROJECTS_PROTECTED_KEY)?.[id || ''] || '')
  }, [id])

  useEffect(() => {
    if (!isBrowser) {
      return
    }

    const handlePasswordUpdated = (
      event: CustomEvent<{ id: string; password: string }>,
    ) => {
      if (event.detail.id === id) {
        setCachedPassword(event.detail.password || '')
      }
    }

    const handleStorage = (event: StorageEvent) => {
      if (event.key === LS_PROJECTS_PROTECTED_KEY) {
        setCachedPassword(
          getItemJSON(LS_PROJECTS_PROTECTED_KEY)?.[id || ''] || '',
        )
      }
    }

    window.addEventListener(
      PROJECT_PASSWORD_UPDATED_EVENT,
      handlePasswordUpdated as EventListener,
    )
    window.addEventListener('storage', handleStorage)

    return () => {
      window.removeEventListener(
        PROJECT_PASSWORD_UPDATED_EVENT,
        handlePasswordUpdated as EventListener,
      )
      window.removeEventListener('storage', handleStorage)
    }
  }, [id])

  return searchParams.get('password') || cachedPassword
}

const useProject = (id: string, projectPath: string) => {
  const { t } = useTranslation('common')
  const navigate = useNavigate()
  const revalidator = useRevalidator()
  const loaderData = useLoaderData<ProjectLoaderData>()
  const storedPassword = useProjectPassword(id)

  // Use loader data only for initial state (SSR hydration)
  const [project, setProject] = useState<Project | null>(
    () => loaderData?.project || null,
  )
  const [isPasswordRequired, setIsPasswordRequired] = useState(
    () => loaderData?.isPasswordRequired || false,
  )
  const [isCheckingStoredPassword, setIsCheckingStoredPassword] = useState(() =>
    Boolean(loaderData?.isPasswordRequired && storedPassword),
  )

  const passwordFetcher = useFetcher<ProjectViewActionData>()
  const lastHandledFetcherData = useRef<ProjectViewActionData | null>(null)
  const hasTriedStoredPassword = useRef(false)
  const passwordResolverRef = useRef<
    ((value: { success: boolean; error?: string }) => void) | null
  >(null)
  const lastSubmittedPasswordRef = useRef<string | null>(null)

  useEffect(() => {
    if (
      loaderData?.error &&
      !loaderData.project &&
      !loaderData.isPasswordRequired
    ) {
      console.error('[ERROR] (getProject)', loaderData.error)
      toast.error(t('project.noExist'))
      navigate(routes.dashboard)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // Auto-submit stored password if loader says password is required but we have it in localStorage
  useEffect(() => {
    if (
      loaderData?.isPasswordRequired &&
      isPasswordRequired &&
      storedPassword &&
      !hasTriedStoredPassword.current &&
      passwordFetcher.state === 'idle'
    ) {
      hasTriedStoredPassword.current = true
      setIsCheckingStoredPassword(true)
      passwordFetcher.submit(
        { intent: 'get-project', password: storedPassword },
        { method: 'POST', action: projectPath },
      )
    }
  }, [
    loaderData?.isPasswordRequired,
    isPasswordRequired,
    storedPassword,
    id,
    projectPath,
    passwordFetcher,
  ])

  // Handle password fetcher response
  useEffect(() => {
    if (passwordFetcher.state !== 'idle' || !passwordFetcher.data) return

    // Prevent handling the same response twice
    if (lastHandledFetcherData.current === passwordFetcher.data) return
    lastHandledFetcherData.current = passwordFetcher.data

    if (passwordFetcher.data.success && passwordFetcher.data.data) {
      const result = passwordFetcher.data.data as Project
      setProject(result)
      setIsPasswordRequired(false)
      setIsCheckingStoredPassword(false)

      if (lastSubmittedPasswordRef.current) {
        setProjectPassword(id, lastSubmittedPasswordRef.current)
        lastSubmittedPasswordRef.current = null
      }

      revalidator.revalidate()

      if (passwordResolverRef.current) {
        passwordResolverRef.current({ success: true })
        passwordResolverRef.current = null
      }
    } else if (passwordFetcher.data.error) {
      toast.error(t('apiNotifications.incorrectPassword'))

      setIsPasswordRequired(true)
      setIsCheckingStoredPassword(false)
      lastSubmittedPasswordRef.current = null
      if (passwordResolverRef.current) {
        passwordResolverRef.current({
          success: false,
          error: passwordFetcher.data.error,
        })
        passwordResolverRef.current = null
      }
    }
  }, [passwordFetcher.state, passwordFetcher.data, t, id, revalidator])

  const submitPassword = useCallback(
    async (password: string): Promise<{ success: boolean; error?: string }> => {
      return new Promise((resolve) => {
        passwordResolverRef.current = resolve
        lastSubmittedPasswordRef.current = password
        passwordFetcher.submit(
          { intent: 'get-project', password },
          { method: 'POST', action: projectPath },
        )
      })
    },
    [passwordFetcher, projectPath],
  )

  const mergeProject = useCallback((updates: Partial<Project>) => {
    setProject((prev) => {
      if (!prev) {
        return null
      }

      return { ...prev, ...updates }
    })
  }, [])

  return {
    project,
    mergeProject,
    isPasswordRequired,
    isCheckingStoredPassword,
    submitPassword,
  }
}

type ProjectPreferences = {
  period?: Period
  timeBucket?: TimeBucket
  rangeDate?: Date[]
  customEvents?: any
  metricsVisualisation?: Record<keyof typeof CHART_METRICS_MAPPING, boolean>
}

const useProjectPreferences = () => {
  const [preferences, setPreferences] = useState<ProjectPreferences>({})

  const updatePreferences = useCallback((prefs: ProjectPreferences) => {
    setPreferences((prev) => ({ ...prev, ...prefs }))
  }, [])

  return { preferences, updatePreferences }
}

const useLiveVisitors = (project: Project | null) => {
  const projectId = project?.id
  const isLocked = project?.isLocked
  const [liveVisitors, setLiveVisitors] = useState(0)

  const updateLiveVisitors = useCallback(async () => {
    if (!projectId || isLocked) {
      return
    }

    try {
      const { data } = await getLiveVisitors(projectId)
      setLiveVisitors(data.count || 0)
    } catch (reason) {
      console.error('Failed to update live visitors:', reason)
    }
  }, [projectId, isLocked])

  useEffect(() => {
    if (!projectId || isLocked) {
      return
    }

    // Initial fetch on mount - eslint-disable needed as this is intentional
    // eslint-disable-next-line react-hooks/set-state-in-effect
    updateLiveVisitors()

    const interval = setInterval(() => {
      updateLiveVisitors()
    }, LIVE_VISITORS_UPDATE_INTERVAL)

    return () => clearInterval(interval)
  }, [projectId, isLocked, updateLiveVisitors])

  return { liveVisitors, updateLiveVisitors }
}

export const CurrentProjectProvider = ({
  children,
  id,
  projectPath,
}: CurrentProjectProviderProps) => {
  const resolvedProjectPath = projectPath || routes.project.replace(':id', id)
  const projectSettingsPath = routes.project_settings.replace(':id', id)
  const {
    project,
    mergeProject,
    isPasswordRequired,
    isCheckingStoredPassword,
    submitPassword,
  } = useProject(id, resolvedProjectPath)
  const { preferences, updatePreferences } = useProjectPreferences()
  const { liveVisitors, updateLiveVisitors } = useLiveVisitors(project)

  return (
    <CurrentProjectContext.Provider
      value={{
        id,
        projectPath: resolvedProjectPath,
        projectSettingsPath,
        project,
        preferences,
        updatePreferences,
        mergeProject,
        allowedToManage: project?.role === 'owner' || project?.role === 'admin',
        liveVisitors,
        updateLiveVisitors,
        isPasswordRequired,
        isCheckingStoredPassword,
        submitPassword,
      }}
    >
      {children}
    </CurrentProjectContext.Provider>
  )
}

export const useCurrentProject = () => {
  const context = useContext(CurrentProjectContext)

  if (context === undefined) {
    throw new Error(
      'useCurrentProject must be used within a CurrentProjectProvider',
    )
  }

  return context
}

// Non-throwing variant for components that may render outside the provider
// (e.g. reused inside the project Settings page). Returns undefined when there
// is no surrounding CurrentProjectProvider.
export const useOptionalCurrentProject = () => useContext(CurrentProjectContext)