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!

a little bit of refactoring

Blue Mousee6907b0e3428
diff --git a/web/app/hooks/useAnnotations.ts b/web/app/hooks/useAnnotations.ts
new file mode 100644
index 000000000..47a6a4b23
--- /dev/null
+++ b/web/app/hooks/useAnnotations.ts
@@ -0,0 +1,391 @@
+import dayjs from 'dayjs'
+import { useState, useCallback, useEffect } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+
+import { getAnnotations, createAnnotation, updateAnnotation, deleteAnnotation } from '~/api'
+import { Annotation } from '~/lib/models/Project'
+import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+
+/**
+ * Pixel distance threshold for snapping to nearby annotations when clicking on the chart.
+ * If a click is within this many pixels of an annotation line, that annotation will be selected.
+ */
+const ANNOTATION_CLICK_THRESHOLD_PX = 30
+
+/** Chart metrics derived from SVG/DOM layout */
+interface ChartMetrics {
+ /** X coordinate where the chart plotting area begins (left edge of x-axis) */
+ chartAreaStart: number
+ /** Width of the chart plotting area */
+ chartAreaWidth: number
+}
+
+/**
+ * Traverses up the DOM tree from a target element to find an annotation line element.
+ */
+const findAnnotationLineElement = (target: Element, boundary: Element): Element | null => {
+ let element: Element | null = target
+
+ while (element && element !== boundary) {
+ if (element.classList?.contains('annotation-line')) {
+ return element
+ }
+ element = element.parentElement
+ }
+
+ return null
+}
+
+/**
+ * Extracts the annotation ID from an annotation line element's class list.
+ */
+const getAnnotationIdFromElement = (element: Element): string | null => {
+ const classes = element.classList
+ for (const className of classes) {
+ if (className.startsWith('annotation-id-')) {
+ return className.replace('annotation-id-', '')
+ }
+ }
+ return null
+}
+
+/**
+ * Calculates the chart area metrics by examining the SVG's x-axis domain path.
+ */
+const calculateChartMetrics = (svg: SVGSVGElement, chartContainer: HTMLElement): ChartMetrics => {
+ const svgRect = svg.getBoundingClientRect()
+
+ // Default fallbacks based on typical billboard.js chart layout
+ let chartAreaStart = 50
+ let chartAreaWidth = svgRect.width - 70
+
+ // Try to get exact boundaries from the x-axis domain path (the axis line)
+ const xAxisPath = chartContainer.querySelector('.bb-axis-x path.domain') as SVGPathElement | null
+ if (xAxisPath) {
+ const pathBBox = xAxisPath.getBBox()
+ chartAreaStart = pathBBox.x
+ chartAreaWidth = pathBBox.width
+ }
+
+ return { chartAreaStart, chartAreaWidth }
+}
+
+/**
+ * Calculates the date corresponding to a click position on the chart.
+ */
+const calculateDateFromPosition = (
+ clientX: number,
+ svgRect: DOMRect,
+ xAxisData: string[],
+ chartMetrics: ChartMetrics,
+): string => {
+ const clickX = clientX - svgRect.left
+ const { chartAreaStart, chartAreaWidth } = chartMetrics
+
+ // Calculate relative position within the chart area (clamped to [0, 1])
+ const relativeX = Math.max(0, clickX - chartAreaStart)
+ const percentage = Math.min(1, relativeX / chartAreaWidth)
+
+ // Map percentage to index in xAxisData
+ const index = Math.round(percentage * (xAxisData.length - 1))
+ const clampedIndex = Math.max(0, Math.min(xAxisData.length - 1, index))
+
+ return dayjs(xAxisData[clampedIndex]).format('YYYY-MM-DD')
+}
+
+/**
+ * Finds the closest annotation to a click position within the pixel threshold.
+ */
+const findClosestAnnotation = (
+ clickX: number,
+ annotations: Annotation[],
+ xAxisData: string[],
+ chartMetrics: ChartMetrics,
+ pixelThreshold: number,
+): Annotation | null => {
+ const { chartAreaStart, chartAreaWidth } = chartMetrics
+
+ let closestAnnotation: Annotation | null = null
+ let closestDistance = Infinity
+
+ for (const annotation of annotations) {
+ const annotationDate = dayjs(annotation.date).format('YYYY-MM-DD')
+
+ // Find the index of this annotation's date in xAxisData
+ const annotationIndex = xAxisData.findIndex((xDate) => dayjs(xDate).format('YYYY-MM-DD') === annotationDate)
+
+ if (annotationIndex !== -1) {
+ // Calculate the x position of this annotation on the chart
+ const annotationPercentage = annotationIndex / (xAxisData.length - 1)
+ const annotationX = chartAreaStart + annotationPercentage * chartAreaWidth
+ const distance = Math.abs(clickX - annotationX)
+
+ if (distance < pixelThreshold && distance < closestDistance) {
+ closestDistance = distance
+ closestAnnotation = annotation
+ }
+ }
+ }
+
+ return closestAnnotation
+}
+
+interface UseAnnotationsReturn {
+ // State
+ annotations: Annotation[]
+ annotationsLoading: boolean
+ isAnnotationModalOpen: boolean
+ annotationToEdit: Annotation | undefined
+ annotationModalDate: string | undefined
+ annotationActionLoading: boolean
+ contextMenu: {
+ isOpen: boolean
+ x: number
+ y: number
+ date: string | null
+ annotation: Annotation | null
+ }
+
+ // Actions
+ loadAnnotations: () => Promise<void>
+ onAnnotationCreate: (date: string, text: string) => Promise<void>
+ onAnnotationUpdate: (date: string, text: string) => Promise<void>
+ onAnnotationDelete: (annotation?: Annotation) => Promise<void>
+ openAnnotationModal: (date?: string, annotation?: Annotation) => void
+ closeAnnotationModal: () => void
+ handleChartContextMenu: (event: React.MouseEvent, xAxisData: string[] | undefined) => void
+ closeContextMenu: () => void
+}
+
+interface UseAnnotationsOptions {
+ allowedToManage?: boolean
+}
+
+export const useAnnotations = (options: UseAnnotationsOptions = {}): UseAnnotationsReturn => {
+ const { allowedToManage = true } = options
+ const { id, project } = useCurrentProject()
+ const projectPassword = useProjectPassword(id)
+ const { t } = useTranslation('common')
+
+ // Annotations state
+ const [annotations, setAnnotations] = useState<Annotation[]>([])
+ const [annotationsLoading, setAnnotationsLoading] = useState(false)
+ const [isAnnotationModalOpen, setIsAnnotationModalOpen] = useState(false)
+ const [annotationToEdit, setAnnotationToEdit] = useState<Annotation | undefined>()
+ const [annotationModalDate, setAnnotationModalDate] = useState<string | undefined>()
+ const [annotationActionLoading, setAnnotationActionLoading] = useState(false)
+
+ // Chart context menu state
+ const [contextMenu, setContextMenu] = useState<{
+ isOpen: boolean
+ x: number
+ y: number
+ date: string | null
+ annotation: Annotation | null
+ }>({
+ isOpen: false,
+ x: 0,
+ y: 0,
+ date: null,
+ annotation: null,
+ })
+
+ const loadAnnotations = useCallback(async () => {
+ if (annotationsLoading) {
+ return
+ }
+
+ setAnnotationsLoading(true)
+
+ try {
+ const data = await getAnnotations(id, projectPassword)
+ setAnnotations(data || [])
+ } catch (reason: any) {
+ console.error('[ERROR] (loadAnnotations)', reason)
+ }
+
+ setAnnotationsLoading(false)
+ }, [id, projectPassword, annotationsLoading])
+
+ const onAnnotationCreate = useCallback(
+ async (date: string, text: string) => {
+ if (annotationActionLoading) {
+ return
+ }
+
+ setAnnotationActionLoading(true)
+
+ try {
+ await createAnnotation(id, date, text)
+ await loadAnnotations()
+ toast.success(t('apiNotifications.annotationCreated'))
+ } catch (reason: any) {
+ console.error('[ERROR] (onAnnotationCreate)', reason)
+ toast.error(reason)
+ }
+
+ setAnnotationActionLoading(false)
+ },
+ [id, annotationActionLoading, loadAnnotations, t],
+ )
+
+ const onAnnotationUpdate = useCallback(
+ async (date: string, text: string) => {
+ if (annotationActionLoading || !annotationToEdit) {
+ return
+ }
+
+ setAnnotationActionLoading(true)
+
+ try {
+ await updateAnnotation(annotationToEdit.id, id, date, text)
+ await loadAnnotations()
+ toast.success(t('apiNotifications.annotationUpdated'))
+ } catch (reason: any) {
+ console.error('[ERROR] (onAnnotationUpdate)', reason)
+ toast.error(reason)
+ }
+
+ setAnnotationActionLoading(false)
+ },
+ [id, annotationActionLoading, annotationToEdit, loadAnnotations, t],
+ )
+
+ const onAnnotationDelete = useCallback(
+ async (annotation?: Annotation) => {
+ const targetAnnotation = annotation || annotationToEdit
+
+ if (annotationActionLoading || !targetAnnotation) {
+ return
+ }
+
+ setAnnotationActionLoading(true)
+
+ try {
+ await deleteAnnotation(targetAnnotation.id, id)
+ await loadAnnotations()
+ toast.success(t('apiNotifications.annotationDeleted'))
+ } catch (reason: any) {
+ console.error('[ERROR] (onAnnotationDelete)', reason)
+ toast.error(reason)
+ }
+
+ setAnnotationActionLoading(false)
+ setAnnotationToEdit(undefined)
+ },
+ [id, annotationActionLoading, annotationToEdit, loadAnnotations, t],
+ )
+
+ const openAnnotationModal = useCallback((date?: string, annotation?: Annotation) => {
+ setAnnotationModalDate(date)
+ setAnnotationToEdit(annotation)
+ setIsAnnotationModalOpen(true)
+ }, [])
+
+ const closeAnnotationModal = useCallback(() => {
+ setIsAnnotationModalOpen(false)
+ setAnnotationToEdit(undefined)
+ setAnnotationModalDate(undefined)
+ }, [])
+
+ const handleChartContextMenu = useCallback(
+ (event: React.MouseEvent, xAxisData: string[] | undefined) => {
+ event.preventDefault()
+
+ let existingAnnotation: Annotation | null = null
+ let date: string | null = null
+
+ // Check if user clicked directly on an annotation line
+ const annotationLineElement = findAnnotationLineElement(event.target as Element, event.currentTarget as Element)
+
+ if (annotationLineElement) {
+ // User clicked on an annotation line - find it by ID from the element's class
+ const annotationId = getAnnotationIdFromElement(annotationLineElement)
+ if (annotationId) {
+ existingAnnotation = annotations.find((a) => a.id === annotationId) || null
+ if (existingAnnotation) {
+ date = dayjs(existingAnnotation.date).format('YYYY-MM-DD')
+ }
+ }
+ }
+
+ // If not clicking on an annotation line, calculate date from click position
+ if (!existingAnnotation && xAxisData && xAxisData.length > 0) {
+ const chartContainer = (event.currentTarget as HTMLElement).querySelector('.bb') as HTMLElement
+ const svg = chartContainer?.querySelector('svg') as SVGSVGElement | null
+
+ if (svg) {
+ const svgRect = svg.getBoundingClientRect()
+ const chartMetrics = calculateChartMetrics(svg, chartContainer)
+ const clickX = event.clientX - svgRect.left
+
+ date = calculateDateFromPosition(event.clientX, svgRect, xAxisData, chartMetrics)
+
+ // Check for exact date match first
+ existingAnnotation = annotations.find((a) => dayjs(a.date).format('YYYY-MM-DD') === date) || null
+
+ // If no exact match, try to find the closest annotation within threshold
+ if (!existingAnnotation && annotations.length > 0) {
+ const closestAnnotation = findClosestAnnotation(
+ clickX,
+ annotations,
+ xAxisData,
+ chartMetrics,
+ ANNOTATION_CLICK_THRESHOLD_PX,
+ )
+
+ if (closestAnnotation) {
+ existingAnnotation = closestAnnotation
+ date = dayjs(closestAnnotation.date).format('YYYY-MM-DD')
+ }
+ }
+ }
+ }
+
+ setContextMenu({
+ isOpen: true,
+ x: event.clientX,
+ y: event.clientY,
+ date,
+ annotation: existingAnnotation,
+ })
+ },
+ [annotations],
+ )
+
+ const closeContextMenu = useCallback(() => {
+ setContextMenu((prev) => ({ ...prev, isOpen: false }))
+ }, [])
+
+ // Load annotations when project loads
+ useEffect(() => {
+ if (!project) {
+ return
+ }
+
+ loadAnnotations()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [project])
+
+ return {
+ // State
+ annotations,
+ annotationsLoading,
+ isAnnotationModalOpen,
+ annotationToEdit,
+ annotationModalDate,
+ annotationActionLoading,
+ contextMenu,
+
+ // Actions
+ loadAnnotations,
+ onAnnotationCreate,
+ onAnnotationUpdate,
+ onAnnotationDelete,
+ openAnnotationModal,
+ closeAnnotationModal,
+ handleChartContextMenu,
+ closeContextMenu,
+ }
+}
diff --git a/web/app/pages/Project/Performance/View/PerformanceView.tsx b/web/app/pages/Project/Performance/View/PerformanceView.tsx
index 03e64b68d..8a2f95f2f 100644
--- a/web/app/pages/Project/Performance/View/PerformanceView.tsx
+++ b/web/app/pages/Project/Performance/View/PerformanceView.tsx
@@ -12,14 +12,17 @@ import { useNavigate, useSearchParams } from 'react-router'
import { toast } from 'sonner'
import { getPerfData, getPerformanceCompareData, getPerformanceOverallStats, getOverallStats } from '~/api'
+import { useAnnotations } from '~/hooks/useAnnotations'
import { PERFORMANCE_PANELS_ORDER, chartTypes, PERIOD_PAIRS_COMPARE, type TimeBucket } from '~/lib/constants'
import { CountryEntry } from '~/lib/models/Entry'
-import { Annotation, OverallPerformanceObject } from '~/lib/models/Project'
+import { OverallPerformanceObject } from '~/lib/models/Project'
+import AnnotationModal from '~/modals/AnnotationModal'
+import CCRow from '~/pages/Project/View/components/CCRow'
+import { ChartContextMenu } from '~/pages/Project/View/components/ChartContextMenu'
import Filters from '~/pages/Project/View/components/Filters'
-import NoEvents from '~/pages/Project/View/components/NoEvents'
import { PerformanceMetricCards } from '~/pages/Project/View/components/MetricCards'
+import NoEvents from '~/pages/Project/View/components/NoEvents'
import { PerformanceChart } from '~/pages/Project/View/components/PerformanceChart'
-import CCRow from '~/pages/Project/View/components/CCRow'
import { Panel } from '~/pages/Project/View/Panels'
import {
getFormatDate,
@@ -126,41 +129,52 @@ const getDeviceRowMapper = (activeTabId: string, theme: string, t: any) => {
interface PerformanceViewProps {
tnMapping: Record<string, string>
- chartType: string
- rotateXAxis: boolean
- isActiveCompare: boolean
- dateRangeCompare: Date[] | null
- activePeriodCompare: string | null
- compareDisable: () => void
- annotations: Annotation[]
- onChartContextMenu: (e: React.MouseEvent, xAxisData: string[]) => void
- getFilterLink: (column: string, value: string | null) => any
- getVersionFilterLink: (parent: string | null, version: string | null, panelType: 'br' | 'os') => string
- onMainChartZoom: (domain: [Date, Date] | null) => void
- shouldEnableZoom: boolean
- setChartTypeOnClick: (type: 'line' | 'bar') => void
}
-const PerformanceView = ({
- tnMapping,
- chartType,
- rotateXAxis,
- isActiveCompare,
- dateRangeCompare,
- activePeriodCompare,
- compareDisable,
- annotations,
- onChartContextMenu,
- getFilterLink,
- getVersionFilterLink,
- onMainChartZoom,
- shouldEnableZoom,
- setChartTypeOnClick,
-}: PerformanceViewProps) => {
- const { id, project } = useCurrentProject()
+const PerformanceView = ({ tnMapping }: PerformanceViewProps) => {
+ const { id, project, allowedToManage } = useCurrentProject()
const projectPassword = useProjectPassword(id)
- const { performanceRefreshTrigger, timezone, period, dateRange, filters, timeFormat, timeBucket, activePeriod } =
- useViewProjectContext()
+ const {
+ performanceRefreshTrigger,
+ timezone,
+ period,
+ dateRange,
+ filters,
+ timeFormat,
+ timeBucket,
+ activePeriod,
+ // Comparison state from context
+ isActiveCompare,
+ dateRangeCompare,
+ activePeriodCompare,
+ compareDisable,
+ // Chart state from context
+ chartType,
+ setChartTypeOnClick,
+ rotateXAxis,
+ // Zoom state from context
+ onMainChartZoom,
+ shouldEnableZoom,
+ // Filter functions from context
+ getFilterLink,
+ } = useViewProjectContext()
+
+ // Annotations hook
+ const {
+ annotations,
+ isAnnotationModalOpen,
+ annotationToEdit,
+ annotationModalDate,
+ annotationActionLoading,
+ contextMenu,
+ onAnnotationCreate,
+ onAnnotationUpdate,
+ onAnnotationDelete,
+ openAnnotationModal,
+ closeAnnotationModal,
+ handleChartContextMenu,
+ closeContextMenu,
+ } = useAnnotations({ allowedToManage })
const {
t,
i18n: { language },
@@ -572,7 +586,7 @@ const PerformanceView = ({
/>
) : null}
{!checkIfAllMetricsAreDisabled && !_isEmpty(chartData) ? (
- <div onContextMenu={(e) => onChartContextMenu(e, chartData?.x)} className='relative'>
+ <div onContextMenu={(e) => handleChartContextMenu(e, chartData?.x)} className='relative'>
<PerformanceChart
chart={chartData}
timeBucket={timeBucket}
@@ -760,6 +774,39 @@ const PerformanceView = ({
})
: null}
</div>
+ <AnnotationModal
+ isOpened={isAnnotationModalOpen}
+ onClose={closeAnnotationModal}
+ onSubmit={annotationToEdit ? onAnnotationUpdate : onAnnotationCreate}
+ onDelete={annotationToEdit ? onAnnotationDelete : undefined}
+ loading={annotationActionLoading}
+ annotation={annotationToEdit}
+ defaultDate={annotationModalDate}
+ allowedToManage={allowedToManage}
+ />
+ <ChartContextMenu
+ isOpen={contextMenu.isOpen}
+ x={contextMenu.x}
+ y={contextMenu.y}
+ onClose={closeContextMenu}
+ onAddAnnotation={() => {
+ openAnnotationModal(contextMenu.date || undefined)
+ }}
+ onEditAnnotation={
+ contextMenu.annotation
+ ? () => openAnnotationModal(contextMenu.annotation?.date, contextMenu.annotation!)
+ : undefined
+ }
+ onDeleteAnnotation={
+ contextMenu.annotation
+ ? () => {
+ onAnnotationDelete(contextMenu.annotation!)
+ }
+ : undefined
+ }
+ existingAnnotation={contextMenu.annotation}
+ allowedToManage={allowedToManage}
+ />
</div>
)
}
diff --git a/web/app/pages/Project/Traffic/View/TrafficView.tsx b/web/app/pages/Project/Traffic/View/TrafficView.tsx
index 33adf6771..1d2889833 100644
--- a/web/app/pages/Project/Traffic/View/TrafficView.tsx
+++ b/web/app/pages/Project/Traffic/View/TrafficView.tsx
@@ -22,10 +22,13 @@ import {
getPropertyMetadata,
getGSCKeywords,
} from '~/api'
+import { useAnnotations } from '~/hooks/useAnnotations'
import { TRAFFIC_PANELS_ORDER, chartTypes, PERIOD_PAIRS_COMPARE, isSelfhosted, type TimeBucket } from '~/lib/constants'
import { CountryEntry, Entry } from '~/lib/models/Entry'
-import { Annotation, OverallObject } from '~/lib/models/Project'
+import { OverallObject } from '~/lib/models/Project'
+import AnnotationModal from '~/modals/AnnotationModal'
import CCRow from '~/pages/Project/View/components/CCRow'
+import { ChartContextMenu } from '~/pages/Project/View/components/ChartContextMenu'
import CustomMetrics from '~/pages/Project/View/components/CustomMetrics'
import Filters from '~/pages/Project/View/components/Filters'
import { MetricCard, MetricCards } from '~/pages/Project/View/components/MetricCards'
@@ -77,19 +80,6 @@ type KeywordEntry = Entry & { impressions: number; position: number; ctr: number
interface TrafficViewProps {
tnMapping: Record<string, string>
- chartType: string
- rotateXAxis: boolean
- isActiveCompare: boolean
- dateRangeCompare: Date[] | null
- activePeriodCompare: string | null
- compareDisable: () => void
- annotations: Annotation[]
- onChartContextMenu: (e: React.MouseEvent, xAxisData: string[]) => void
- getFilterLink: (column: string, value: string | null) => any
- getVersionFilterLink: (parent: string | null, version: string | null, panelType: 'br' | 'os') => string
- onMainChartZoom: (domain: [Date, Date] | null) => void
- shouldEnableZoom: boolean
- setChartTypeOnClick: (type: 'line' | 'bar') => void
customMetrics: ProjectViewCustomEvent[]
onCustomMetric: (metrics: ProjectViewCustomEvent[]) => void
onRemoveCustomMetric: (metricId: string) => void
@@ -100,19 +90,6 @@ interface TrafficViewProps {
const TrafficView = ({
tnMapping,
- chartType,
- rotateXAxis,
- isActiveCompare,
- dateRangeCompare,
- activePeriodCompare,
- compareDisable,
- annotations,
- onChartContextMenu,
- getFilterLink,
- getVersionFilterLink,
- onMainChartZoom,
- shouldEnableZoom,
- setChartTypeOnClick,
customMetrics,
onCustomMetric,
onRemoveCustomMetric,
@@ -120,10 +97,33 @@ const TrafficView = ({
mode,
sdkInstance,
}: TrafficViewProps) => {
- const { id, project } = useCurrentProject()
+ const { id, project, allowedToManage } = useCurrentProject()
const projectPassword = useProjectPassword(id)
- const { trafficRefreshTrigger, timezone, period, dateRange, filters, timeFormat, timeBucket, activePeriod } =
- useViewProjectContext()
+ const {
+ trafficRefreshTrigger,
+ timezone,
+ period,
+ dateRange,
+ filters,
+ timeFormat,
+ timeBucket,
+ activePeriod,
+ // Comparison state from context
+ isActiveCompare,
+ dateRangeCompare,
+ activePeriodCompare,
+ compareDisable,
+ // Chart state from context
+ chartType,
+ setChartTypeOnClick,
+ rotateXAxis,
+ // Zoom state from context
+ onMainChartZoom,
+ shouldEnableZoom,
+ // Filter functions from context
+ getFilterLink,
+ getVersionFilterLink,
+ } = useViewProjectContext()
const {
t,
i18n: { language },
@@ -132,6 +132,23 @@ const TrafficView = ({
const navigate = useNavigate()
const [searchParams, setSearchParams] = useSearchParams()
+ // Annotations hook
+ const {
+ annotations,
+ isAnnotationModalOpen,
+ annotationToEdit,
+ annotationModalDate,
+ annotationActionLoading,
+ contextMenu,
+ onAnnotationCreate,
+ onAnnotationUpdate,
+ onAnnotationDelete,
+ openAnnotationModal,
+ closeAnnotationModal,
+ handleChartContextMenu,
+ closeContextMenu,
+ } = useAnnotations({ allowedToManage })
+
// Traffic-specific state
const [dataLoading, setDataLoading] = useState(false)
const [analyticsLoading, setAnalyticsLoading] = useState(true)
@@ -823,7 +840,7 @@ const TrafficView = ({
</div>
) : null}
{!checkIfAllMetricsAreDisabled && !_isEmpty(chartData) ? (
- <div onContextMenu={(e) => onChartContextMenu(e, chartData.x)} className='relative'>
+ <div onContextMenu={(e) => handleChartContextMenu(e, chartData.x)} className='relative'>
<TrafficChart
chartData={chartData}
timeBucket={timeBucket}
@@ -1143,6 +1160,39 @@ const TrafficView = ({
/>
) : null}
</div>
+ <AnnotationModal
+ isOpened={isAnnotationModalOpen}
+ onClose={closeAnnotationModal}
+ onSubmit={annotationToEdit ? onAnnotationUpdate : onAnnotationCreate}
+ onDelete={annotationToEdit ? onAnnotationDelete : undefined}
+ loading={annotationActionLoading}
+ annotation={annotationToEdit}
+ defaultDate={annotationModalDate}
+ allowedToManage={allowedToManage}
+ />
+ <ChartContextMenu
+ isOpen={contextMenu.isOpen}
+ x={contextMenu.x}
+ y={contextMenu.y}
+ onClose={closeContextMenu}
+ onAddAnnotation={() => {
+ openAnnotationModal(contextMenu.date || undefined)
+ }}
+ onEditAnnotation={
+ contextMenu.annotation
+ ? () => openAnnotationModal(contextMenu.annotation?.date, contextMenu.annotation!)
+ : undefined
+ }
+ onDeleteAnnotation={
+ contextMenu.annotation
+ ? () => {
+ onAnnotationDelete(contextMenu.annotation!)
+ }
+ : undefined
+ }
+ existingAnnotation={contextMenu.annotation}
+ allowedToManage={allowedToManage}
+ />
</div>
)
}
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 0b3dcc6ac..09a9b4d14 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -34,14 +34,7 @@ import { useNavigate, Link, useSearchParams, LinkProps } from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
import { toast } from 'sonner'
-import {
- getProjectViews,
- deleteProjectView,
- getAnnotations,
- createAnnotation,
- updateAnnotation,
- deleteAnnotation,
-} from '~/api'
+import { getProjectViews, deleteProjectView } from '~/api'
import EventsRunningOutBanner from '~/components/EventsRunningOutBanner'
import Footer from '~/components/Footer'
import Header from '~/components/Header'
@@ -73,8 +66,6 @@ import {
languages,
languageFlag,
} from '~/lib/constants'
-import { Annotation } from '~/lib/models/Project'
-import AnnotationModal from '~/modals/AnnotationModal'
import ViewProjectHotkeys from '~/modals/ViewProjectHotkeys'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
@@ -100,7 +91,6 @@ import SessionsView from '../Sessions/View/SessionsView'
import TrafficView from '../Traffic/View/TrafficView'
import AddAViewModal from './components/AddAViewModal'
-import { ChartContextMenu } from './components/ChartContextMenu'
import { ChartManagerProvider } from './components/ChartManager'
const CaptchaView = lazy(() => import('./components/CaptchaView'))
import DashboardHeader from './components/DashboardHeader'
@@ -132,158 +122,6 @@ import {
SHORTCUTS_TIMEBUCKETS_LISTENERS,
} from './ViewProject.helpers'
-/**
- * Pixel distance threshold for snapping to nearby annotations when clicking on the chart.
- * If a click is within this many pixels of an annotation line, that annotation will be selected.
- */
-const ANNOTATION_CLICK_THRESHOLD_PX = 30
-
-/** Chart metrics derived from SVG/DOM layout */
-interface ChartMetrics {
- /** X coordinate where the chart plotting area begins (left edge of x-axis) */
- chartAreaStart: number
- /** Width of the chart plotting area */
- chartAreaWidth: number
-}
-
-/**
- * Traverses up the DOM tree from a target element to find an annotation line element.
- * @param target - The element where the click/event originated
- * @param boundary - The boundary element to stop traversal (usually event.currentTarget)
- * @returns The annotation line element if found, null otherwise
- */
-const findAnnotationLineElement = (target: Element, boundary: Element): Element | null => {
- let element: Element | null = target
-
- while (element && element !== boundary) {
- if (element.classList?.contains('annotation-line')) {
- return element
- }
- element = element.parentElement
- }
-
- return null
-}
-
-/**
- * Extracts the annotation ID from an annotation line element's class list.
- * Annotation elements have classes in the format "annotation-line annotation-id-{uuid}".
- * @param element - The annotation line DOM element
- * @returns The annotation ID if found, null otherwise
- */
-const getAnnotationIdFromElement = (element: Element): string | null => {
- const classes = element.classList
- for (const className of classes) {
- if (className.startsWith('annotation-id-')) {
- return className.replace('annotation-id-', '')
- }
- }
- return null
-}
-
-/**
- * Calculates the chart area metrics by examining the SVG's x-axis domain path.
- * Falls back to sensible defaults if the DOM elements cannot be queried.
- *
- * @param svg - The SVG element containing the chart
- * @param chartContainer - The billboard.js chart container element
- * @returns Chart metrics with start position and width of the plotting area
- *
- * Fallback rationale:
- * - chartAreaStart defaults to 50px (typical left margin for y-axis labels)
- * - chartAreaWidth defaults to svgWidth - 70px (accounts for left margin + right padding)
- */
-const calculateChartMetrics = (svg: SVGSVGElement, chartContainer: HTMLElement): ChartMetrics => {
- const svgRect = svg.getBoundingClientRect()
-
- // Default fallbacks based on typical billboard.js chart layout
- let chartAreaStart = 50
- let chartAreaWidth = svgRect.width - 70
-
- // Try to get exact boundaries from the x-axis domain path (the axis line)
- const xAxisPath = chartContainer.querySelector('.bb-axis-x path.domain') as SVGPathElement | null
- if (xAxisPath) {
- const pathBBox = xAxisPath.getBBox()
- chartAreaStart = pathBBox.x
- chartAreaWidth = pathBBox.width
- }
-
- return { chartAreaStart, chartAreaWidth }
-}
-
-/**
- * Calculates the date corresponding to a click position on the chart.
- *
- * @param clientX - The X coordinate of the click event (event.clientX)
- * @param svgRect - The bounding rectangle of the SVG element
- * @param xAxisData - Array of date strings representing x-axis values
- * @param chartMetrics - The computed chart area metrics
- * @returns The date string in YYYY-MM-DD format for the clicked position
- */
-const calculateDateFromPosition = (
- clientX: number,
- svgRect: DOMRect,
- xAxisData: string[],
- chartMetrics: ChartMetrics,
-): string => {
- const clickX = clientX - svgRect.left
- const { chartAreaStart, chartAreaWidth } = chartMetrics
-
- // Calculate relative position within the chart area (clamped to [0, 1])
- const relativeX = Math.max(0, clickX - chartAreaStart)
- const percentage = Math.min(1, relativeX / chartAreaWidth)
-
- // Map percentage to index in xAxisData
- const index = Math.round(percentage * (xAxisData.length - 1))
- const clampedIndex = Math.max(0, Math.min(xAxisData.length - 1, index))
-
- return dayjs(xAxisData[clampedIndex]).format('YYYY-MM-DD')
-}
-
-/**
- * Finds the closest annotation to a click position within the pixel threshold.
- *
- * @param clickX - The X coordinate of the click relative to the SVG's left edge
- * @param annotations - Array of all annotations
- * @param xAxisData - Array of date strings representing x-axis values
- * @param chartMetrics - The computed chart area metrics
- * @param pixelThreshold - Maximum distance in pixels to consider an annotation as "close"
- * @returns The closest annotation if within threshold, null otherwise
- */
-const findClosestAnnotation = (
- clickX: number,
- annotations: Annotation[],
- xAxisData: string[],
- chartMetrics: ChartMetrics,
- pixelThreshold: number,
-): Annotation | null => {
- const { chartAreaStart, chartAreaWidth } = chartMetrics
-
- let closestAnnotation: Annotation | null = null
- let closestDistance = Infinity
-
- for (const annotation of annotations) {
- const annotationDate = dayjs(annotation.date).format('YYYY-MM-DD')
-
- // Find the index of this annotation's date in xAxisData
- const annotationIndex = xAxisData.findIndex((xDate) => dayjs(xDate).format('YYYY-MM-DD') === annotationDate)
-
- if (annotationIndex !== -1) {
- // Calculate the x position of this annotation on the chart
- const annotationPercentage = annotationIndex / (xAxisData.length - 1)
- const annotationX = chartAreaStart + annotationPercentage * chartAreaWidth
- const distance = Math.abs(clickX - annotationX)
-
- if (distance < pixelThreshold && distance < closestDistance) {
- closestDistance = distance
- closestAnnotation = annotation
- }
- }
- }
-
- return closestAnnotation
-}
-
interface ViewProjectContextType {
// States
timezone: string
@@ -308,6 +146,28 @@ interface ViewProjectContextType {
funnelsRefreshTrigger: number
profilesRefreshTrigger: number
+ // Comparison state
+ isActiveCompare: boolean
+ dateRangeCompare: Date[] | null
+ activePeriodCompare: string
+ setIsActiveCompare: (value: boolean) => void
+ setDateRangeCompare: (value: Date[] | null) => void
+ setActivePeriodCompare: (value: string) => void
+ compareDisable: () => void
+
+ // Chart state
+ chartType: keyof typeof chartTypes
+ setChartTypeOnClick: (type: keyof typeof chartTypes) => void
+ rotateXAxis: boolean
+
+ // Zoom state
+ onMainChartZoom: (domain: [Date, Date] | null) => void
+ shouldEnableZoom: boolean
+
+ // Filter functions
+ getFilterLink: (column: string, value: string | null) => LinkProps['to']
+ getVersionFilterLink: (parent: string | null, version: string | null, panelType: 'br' | 'os') => string
+
// Functions
updatePeriod: (newPeriod: { period: Period; label?: string }) => void
updateTimebucket: (newTimebucket: TimeBucket) => void
@@ -338,6 +198,29 @@ const defaultViewProjectContext: ViewProjectContextType = {
trafficRefreshTrigger: 0,
funnelsRefreshTrigger: 0,
profilesRefreshTrigger: 0,
+
+ // Comparison state defaults
+ isActiveCompare: false,
+ dateRangeCompare: null,
+ activePeriodCompare: '',
+ setIsActiveCompare: () => {},
+ setDateRangeCompare: () => {},
+ setActivePeriodCompare: () => {},
+ compareDisable: () => {},
+
+ // Chart state defaults
+ chartType: chartTypes.line,
+ setChartTypeOnClick: () => {},
+ rotateXAxis: false,
+
+ // Zoom state defaults
+ onMainChartZoom: () => {},
+ shouldEnableZoom: true,
+
+ // Filter functions defaults
+ getFilterLink: () => ({ search: '' }) as LinkProps['to'],
+ getVersionFilterLink: () => '',
+
updatePeriod: () => {},
updateTimebucket: (_newTimebucket) => {},
refCalendar: { current: null } as any,
@@ -541,29 +424,6 @@ const ViewProjectContent = () => {
const [projectViewDeleting, setProjectViewDeleting] = useState(false)
const [projectViewToUpdate, setProjectViewToUpdate] = useState<ProjectView | undefined>()
- // Annotations state
- const [annotations, setAnnotations] = useState<Annotation[]>([])
- const [annotationsLoading, setAnnotationsLoading] = useState(false)
- const [isAnnotationModalOpen, setIsAnnotationModalOpen] = useState(false)
- const [annotationToEdit, setAnnotationToEdit] = useState<Annotation | undefined>()
- const [annotationModalDate, setAnnotationModalDate] = useState<string | undefined>()
- const [annotationActionLoading, setAnnotationActionLoading] = useState(false)
-
- // Chart context menu state
- const [contextMenu, setContextMenu] = useState<{
- isOpen: boolean
- x: number
- y: number
- date: string | null
- annotation: Annotation | null
- }>({
- isOpen: false,
- x: 0,
- y: 0,
- date: null,
- annotation: null,
- })
-
const mode = activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode] ? 'cumulative' : 'periodical'
const loadProjectViews = async (forced?: boolean) => {
@@ -605,162 +465,6 @@ const ViewProjectContent = () => {
setProjectViewDeleting(false)
}
- // Annotation functions
- const loadAnnotations = async () => {
- if (annotationsLoading) {
- return
- }
-
- setAnnotationsLoading(true)
-
- try {
- const data = await getAnnotations(id, projectPassword)
- setAnnotations(data || [])
- } catch (reason: any) {
- console.error('[ERROR] (loadAnnotations)', reason)
- }
-
- setAnnotationsLoading(false)
- }
-
- const onAnnotationCreate = async (date: string, text: string) => {
- if (annotationActionLoading) {
- return
- }
-
- setAnnotationActionLoading(true)
-
- try {
- await createAnnotation(id, date, text)
- await loadAnnotations()
- toast.success(t('apiNotifications.annotationCreated'))
- } catch (reason: any) {
- console.error('[ERROR] (onAnnotationCreate)', reason)
- toast.error(reason)
- }
-
- setAnnotationActionLoading(false)
- }
-
- const onAnnotationUpdate = async (date: string, text: string) => {
- if (annotationActionLoading || !annotationToEdit) {
- return
- }
-
- setAnnotationActionLoading(true)
-
- try {
- await updateAnnotation(annotationToEdit.id, id, date, text)
- await loadAnnotations()
- toast.success(t('apiNotifications.annotationUpdated'))
- } catch (reason: any) {
- console.error('[ERROR] (onAnnotationUpdate)', reason)
- toast.error(reason)
- }
-
- setAnnotationActionLoading(false)
- }
-
- const onAnnotationDelete = async (annotation?: Annotation) => {
- const targetAnnotation = annotation || annotationToEdit
-
- if (annotationActionLoading || !targetAnnotation) {
- return
- }
-
- setAnnotationActionLoading(true)
-
- try {
- await deleteAnnotation(targetAnnotation.id, id)
- await loadAnnotations()
- toast.success(t('apiNotifications.annotationDeleted'))
- } catch (reason: any) {
- console.error('[ERROR] (onAnnotationDelete)', reason)
- toast.error(reason)
- }
-
- setAnnotationActionLoading(false)
- setAnnotationToEdit(undefined)
- }
-
- const openAnnotationModal = (date?: string, annotation?: Annotation) => {
- setAnnotationModalDate(date)
- setAnnotationToEdit(annotation)
- setIsAnnotationModalOpen(true)
- }
-
- const closeAnnotationModal = () => {
- setIsAnnotationModalOpen(false)
- setAnnotationToEdit(undefined)
- setAnnotationModalDate(undefined)
- }
-
- const handleChartContextMenu = (event: React.MouseEvent, xAxisData: string[] | undefined) => {
- event.preventDefault()
-
- let existingAnnotation: Annotation | null = null
- let date: string | null = null
-
- // Check if user clicked directly on an annotation line
- const annotationLineElement = findAnnotationLineElement(event.target as Element, event.currentTarget as Element)
-
- if (annotationLineElement) {
- // User clicked on an annotation line - find it by ID from the element's class
- const annotationId = getAnnotationIdFromElement(annotationLineElement)
- if (annotationId) {
- existingAnnotation = annotations.find((a) => a.id === annotationId) || null
- if (existingAnnotation) {
- date = dayjs(existingAnnotation.date).format('YYYY-MM-DD')
- }
- }
- }
-
- // If not clicking on an annotation line, calculate date from click position
- if (!existingAnnotation && xAxisData && xAxisData.length > 0) {
- const chartContainer = (event.currentTarget as HTMLElement).querySelector('.bb') as HTMLElement
- const svg = chartContainer?.querySelector('svg') as SVGSVGElement | null
-
- if (svg) {
- const svgRect = svg.getBoundingClientRect()
- const chartMetrics = calculateChartMetrics(svg, chartContainer)
- const clickX = event.clientX - svgRect.left
-
- date = calculateDateFromPosition(event.clientX, svgRect, xAxisData, chartMetrics)
-
- // Check for exact date match first
- existingAnnotation = annotations.find((a) => dayjs(a.date).format('YYYY-MM-DD') === date) || null
-
- // If no exact match, try to find the closest annotation within threshold
- if (!existingAnnotation && annotations.length > 0) {
- const closestAnnotation = findClosestAnnotation(
- clickX,
- annotations,
- xAxisData,
- chartMetrics,
- ANNOTATION_CLICK_THRESHOLD_PX,
- )
-
- if (closestAnnotation) {
- existingAnnotation = closestAnnotation
- date = dayjs(closestAnnotation.date).format('YYYY-MM-DD')
- }
- }
- }
- }
-
- setContextMenu({
- isOpen: true,
- x: event.clientX,
- y: event.clientY,
- date,
- annotation: existingAnnotation,
- })
- }
-
- const closeContextMenu = () => {
- setContextMenu((prev) => ({ ...prev, isOpen: false }))
- }
-
const getVersionFilterLink = (parent: string | null, version: string | null, panelType: 'br' | 'os') => {
const filterParams = new URLSearchParams(searchParams.toString())
@@ -1037,16 +741,6 @@ const ViewProjectContent = () => {
[authLoading, dataLoading, activeTab],
)
- // Load annotations when project loads
- useEffect(() => {
- if (authLoading || !project) {
- return
- }
-
- loadAnnotations()
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [authLoading, project])
-
useEffect(() => {
let sdk: SwetrixSDK | null = null
@@ -1547,6 +1241,28 @@ const ViewProjectContent = () => {
funnelsRefreshTrigger,
profilesRefreshTrigger,
+ // Comparison state
+ isActiveCompare,
+ dateRangeCompare,
+ activePeriodCompare,
+ setIsActiveCompare,
+ setDateRangeCompare,
+ setActivePeriodCompare,
+ compareDisable,
+
+ // Chart state
+ chartType,
+ setChartTypeOnClick,
+ rotateXAxis,
+
+ // Zoom state
+ onMainChartZoom,
+ shouldEnableZoom,
+
+ // Filter functions
+ getFilterLink,
+ getVersionFilterLink,
+
// Functions
updatePeriod,
updateTimebucket,
@@ -1686,19 +1402,6 @@ const ViewProjectContent = () => {
{activeTab === PROJECT_TABS.traffic ? (
<TrafficView
tnMapping={tnMapping}
- chartType={chartType}
- rotateXAxis={rotateXAxis}
- isActiveCompare={isActiveCompare}
- dateRangeCompare={dateRangeCompare}
- activePeriodCompare={activePeriodCompare}
- compareDisable={compareDisable}
- annotations={annotations}
- onChartContextMenu={handleChartContextMenu}
- getFilterLink={getFilterLink}
- getVersionFilterLink={getVersionFilterLink}
- onMainChartZoom={onMainChartZoom}
- shouldEnableZoom={shouldEnableZoom}
- setChartTypeOnClick={setChartTypeOnClick}
customMetrics={customMetrics}
onCustomMetric={onCustomMetric}
onRemoveCustomMetric={onRemoveCustomMetric}
@@ -1707,24 +1410,7 @@ const ViewProjectContent = () => {
sdkInstance={sdkInstance}
/>
) : null}
- {activeTab === PROJECT_TABS.performance ? (
- <PerformanceView
- tnMapping={tnMapping}
- chartType={chartType}
- rotateXAxis={rotateXAxis}
- isActiveCompare={isActiveCompare}
- dateRangeCompare={dateRangeCompare}
- activePeriodCompare={activePeriodCompare}
- compareDisable={compareDisable}
- annotations={annotations}
- onChartContextMenu={handleChartContextMenu}
- getFilterLink={getFilterLink}
- getVersionFilterLink={getVersionFilterLink}
- onMainChartZoom={onMainChartZoom}
- shouldEnableZoom={shouldEnableZoom}
- setChartTypeOnClick={setChartTypeOnClick}
- />
- ) : null}
+ {activeTab === PROJECT_TABS.performance ? <PerformanceView tnMapping={tnMapping} /> : null}
</motion.div>
</AnimatePresence>
@@ -1840,39 +1526,6 @@ const ViewProjectContent = () => {
defaultView={projectViewToUpdate}
tnMapping={tnMapping}
/>
- <AnnotationModal
- isOpened={isAnnotationModalOpen}
- onClose={closeAnnotationModal}
- onSubmit={annotationToEdit ? onAnnotationUpdate : onAnnotationCreate}
- onDelete={annotationToEdit ? onAnnotationDelete : undefined}
- loading={annotationActionLoading}
- annotation={annotationToEdit}
- defaultDate={annotationModalDate}
- allowedToManage={allowedToManage}
- />
- <ChartContextMenu
- isOpen={contextMenu.isOpen}
- x={contextMenu.x}
- y={contextMenu.y}
- onClose={closeContextMenu}
- onAddAnnotation={() => {
- openAnnotationModal(contextMenu.date || undefined)
- }}
- onEditAnnotation={
- contextMenu.annotation
- ? () => openAnnotationModal(contextMenu.annotation?.date, contextMenu.annotation!)
- : undefined
- }
- onDeleteAnnotation={
- contextMenu.annotation
- ? () => {
- onAnnotationDelete(contextMenu.annotation!)
- }
- : undefined
- }
- existingAnnotation={contextMenu.annotation}
- allowedToManage={allowedToManage}
- />
{!isEmbedded ? <Footer showDBIPMessage /> : null}
</>
</ViewProjectContext.Provider>