📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Add chart annotations
Blue Mouse00b4d9409bcc
diff --git a/backend/apps/cloud/src/project/dto/annotation-create.dto.ts b/backend/apps/cloud/src/project/dto/annotation-create.dto.tsnew file mode 100644index 000000000..5f680a396--- /dev/null+++ b/backend/apps/cloud/src/project/dto/annotation-create.dto.ts@@ -0,0 +1,30 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty, IsDateString, Length } from 'class-validator'++export class AnnotationCreateDTO {+ @ApiProperty({+ example: 'aUn1quEid-3',+ required: true,+ description: 'Project ID',+ })+ @IsNotEmpty()+ pid: string++ @ApiProperty({+ example: '2025-01-15',+ required: true,+ description: 'Date of the annotation (YYYY-MM-DD)',+ })+ @IsNotEmpty()+ @IsDateString()+ date: string++ @ApiProperty({+ example: 'Started Facebook ad campaign',+ required: true,+ description: 'Annotation text (max 120 characters)',+ })+ @IsNotEmpty()+ @Length(1, 120)+ text: string+}diff --git a/backend/apps/cloud/src/project/dto/annotation-update.dto.ts b/backend/apps/cloud/src/project/dto/annotation-update.dto.tsnew file mode 100644index 000000000..e68aa0050--- /dev/null+++ b/backend/apps/cloud/src/project/dto/annotation-update.dto.ts@@ -0,0 +1,38 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty, IsDateString, Length, IsOptional } from 'class-validator'++export class AnnotationUpdateDTO {+ @ApiProperty({+ example: 'uuid-annotation-id',+ required: true,+ description: 'Annotation ID',+ })+ @IsNotEmpty()+ id: string++ @ApiProperty({+ example: 'aUn1quEid-3',+ required: true,+ description: 'Project ID',+ })+ @IsNotEmpty()+ pid: string++ @ApiProperty({+ example: '2025-01-15',+ required: false,+ description: 'Date of the annotation (YYYY-MM-DD)',+ })+ @IsOptional()+ @IsDateString()+ date?: string++ @ApiProperty({+ example: 'Updated annotation text',+ required: false,+ description: 'Annotation text (max 120 characters)',+ })+ @IsOptional()+ @Length(1, 120)+ text?: string+}diff --git a/backend/apps/cloud/src/project/dto/index.ts b/backend/apps/cloud/src/project/dto/index.tsindex 9141d4c67..1c2a8ba0b 100644--- a/backend/apps/cloud/src/project/dto/index.ts+++ b/backend/apps/cloud/src/project/dto/index.ts@@ -14,3 +14,5 @@ export * from './share.dto'export * from './share-update.dto'export * from './funnel-create.dto'export * from './funnel-update.dto'+export * from './annotation-create.dto'+export * from './annotation-update.dto'diff --git a/backend/apps/cloud/src/project/entity/annotation.entity.ts b/backend/apps/cloud/src/project/entity/annotation.entity.tsnew file mode 100644index 000000000..af71311b4--- /dev/null+++ b/backend/apps/cloud/src/project/entity/annotation.entity.ts@@ -0,0 +1,28 @@+import {+ Column,+ CreateDateColumn,+ Entity,+ JoinColumn,+ ManyToOne,+ PrimaryGeneratedColumn,+} from 'typeorm'+import { Project } from './project.entity'++@Entity()+export class Annotation {+ @PrimaryGeneratedColumn('uuid')+ id: string++ @Column('date')+ date: Date++ @Column('varchar', { length: 120 })+ text: string++ @CreateDateColumn()+ created: Date++ @ManyToOne(() => Project, project => project.annotations)+ @JoinColumn()+ project: Project+}diff --git a/backend/apps/cloud/src/project/entity/index.ts b/backend/apps/cloud/src/project/entity/index.tsindex 32e7cd311..2f08fc0be 100644--- a/backend/apps/cloud/src/project/entity/index.ts+++ b/backend/apps/cloud/src/project/entity/index.ts@@ -2,3 +2,4 @@ export * from './project-subscriber.entity'export * from './funnel.entity'export * from './project.entity'export * from './project-share.entity'+export * from './annotation.entity'diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.tsindex 598633865..fd9cbe807 100644--- a/backend/apps/cloud/src/project/entity/project.entity.ts+++ b/backend/apps/cloud/src/project/entity/project.entity.ts@@ -14,6 +14,7 @@ import { ProjectShare } from './project-share.entity'import { ExtensionToProject } from '../../marketplace/extensions/entities/extension-to-project.entity'import { ProjectSubscriber } from './project-subscriber.entity'import { Funnel } from './funnel.entity'+import { Annotation } from './annotation.entity'import { CAPTCHA_SECRET_KEY_LENGTH } from '../../common/constants'import { ProjectViewEntity } from './project-view.entity'import { Organisation } from '../../organisation/entity/organisation.entity'@@ -116,6 +117,10 @@ export class Project {@OneToMany(() => Funnel, funnel => funnel.project)funnels: Funnel[]+ @ApiProperty({ type: () => Annotation })+ @OneToMany(() => Annotation, annotation => annotation.project)+ annotations: Annotation[]+@Column('varchar', {default: null,length: 60,diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.tsindex 81c5c4733..f091b2dd2 100644--- a/backend/apps/cloud/src/project/project.controller.ts+++ b/backend/apps/cloud/src/project/project.controller.ts@@ -102,6 +102,8 @@ import {ShareUpdateDTO,FunnelCreateDTO,FunnelUpdateDTO,+ AnnotationCreateDTO,+ AnnotationUpdateDTO,} from './dto'import { ProjectsViewsRepository } from './repositories/projects-views.repository'import { ProjectViewEntity } from './entity/project-view.entity'@@ -582,6 +584,146 @@ export class ProjectController {return this.projectService.getFunnels(project.id)}+ @Post('/annotation')+ @ApiResponse({ status: 201 })+ @Auth(true)+ async createAnnotation(+ @Body() annotationDTO: AnnotationCreateDTO,+ @CurrentUserId() userId: string,+ ): Promise<any> {+ this.logger.log({ annotationDTO, userId }, 'POST /project/annotation')++ if (!userId) {+ throw new UnauthorizedException('Please auth first')+ }++ const user = await this.userService.findOne({+ where: { id: userId },+ relations: ['projects'],+ })++ if (!user.isActive) {+ throw new ForbiddenException('Please, verify your email address first')+ }++ const project = await this.projectService.getFullProject(+ annotationDTO.pid,+ userId,+ )++ if (!project) {+ throw new NotFoundException('Project not found.')+ }++ this.projectService.allowedToManage(project, userId)++ return this.projectService.createAnnotation(project.id, annotationDTO)+ }++ @Patch('/annotation')+ @ApiResponse({ status: 200 })+ @Auth(true)+ async updateAnnotation(+ @Body() annotationDTO: AnnotationUpdateDTO,+ @CurrentUserId() userId: string,+ ): Promise<void> {+ this.logger.log({ annotationDTO, userId }, 'PATCH /project/annotation')++ if (!userId) {+ throw new UnauthorizedException('Please auth first')+ }++ const user = await this.userService.findOne({+ where: { id: userId },+ relations: ['projects'],+ })++ if (!user.isActive) {+ throw new ForbiddenException('Please, verify your email address first')+ }++ const project = await this.projectService.getFullProject(+ annotationDTO.pid,+ userId,+ )++ if (!project) {+ throw new NotFoundException('Project not found.')+ }++ this.projectService.allowedToManage(project, userId)++ const oldAnnotation = await this.projectService.getAnnotation(+ annotationDTO.id,+ project.id,+ )++ if (!oldAnnotation) {+ throw new NotFoundException('Annotation not found.')+ }++ await this.projectService.updateAnnotation(annotationDTO)+ }++ @Delete('/annotation/:id/:pid')+ @ApiResponse({ status: 200 })+ @Auth(true)+ async deleteAnnotation(+ @Param('id') id: string,+ @Param('pid') pid: string,+ @CurrentUserId() userId: string,+ ): Promise<void> {+ this.logger.log({ id, userId }, 'DELETE /project/annotation')++ if (!userId) {+ throw new UnauthorizedException('Please auth first')+ }++ const project = await this.projectService.getFullProject(pid, userId)++ if (!project) {+ throw new NotFoundException('Project not found')+ }++ this.projectService.allowedToManage(project, userId)++ const oldAnnotation = await this.projectService.getAnnotation(+ id,+ project.id,+ )++ if (!oldAnnotation) {+ throw new NotFoundException('Annotation not found.')+ }++ await this.projectService.deleteAnnotation(id)+ }++ @Get('/annotations/:pid')+ @ApiResponse({ status: 200 })+ @Auth(true)+ async getAnnotations(+ @Param('pid') pid: string,+ @CurrentUserId() userId: string,+ @Headers() headers: { 'x-password'?: string },+ ): Promise<any> {+ this.logger.log({ pid, userId }, 'GET /project/annotations')++ if (!userId) {+ throw new UnauthorizedException('Please auth first')+ }++ const project = await this.projectService.getFullProject(pid, userId)++ if (!project) {+ throw new NotFoundException('Project not found.')+ }++ this.projectService.allowedToView(project, userId, headers['x-password'])++ return this.projectService.getAnnotations(project.id)+ }+@ApiBearerAuth()@Delete('/reset/:id')@HttpCode(204)diff --git a/backend/apps/cloud/src/project/project.module.ts b/backend/apps/cloud/src/project/project.module.tsindex 8b2495359..c850ce176 100644--- a/backend/apps/cloud/src/project/project.module.ts+++ b/backend/apps/cloud/src/project/project.module.ts@@ -9,7 +9,13 @@ import { UserModule } from '../user/user.module'import { ActionTokensModule } from '../action-tokens/action-tokens.module'import { MailerModule } from '../mailer/mailer.module'import { AppLoggerModule } from '../logger/logger.module'-import { Project, ProjectSubscriber, Funnel, ProjectShare } from './entity'+import {+ Project,+ ProjectSubscriber,+ Funnel,+ ProjectShare,+ Annotation,+} from './entity'import { ProjectsViewsRepository } from './repositories/projects-views.repository'import { ProjectViewEntity } from './entity/project-view.entity'import { ProjectViewCustomEventEntity } from './entity/project-view-custom-event.entity'@@ -23,6 +29,7 @@ import { ProjectExtraService } from './project-extra.service'ProjectShare,ProjectSubscriber,Funnel,+ Annotation,ProjectViewEntity,ProjectViewCustomEventEntity,]),diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.tsindex 300adfede..3a9cc7d1e 100644--- a/backend/apps/cloud/src/project/project.service.ts+++ b/backend/apps/cloud/src/project/project.service.ts@@ -64,7 +64,7 @@ import {} from '../common/constants'import { clickhouse } from '../common/integrations/clickhouse'import { IUsageInfoRedis } from '../user/interfaces'-import { ProjectSubscriber, Funnel } from './entity'+import { ProjectSubscriber, Funnel, Annotation } from './entity'import { AddSubscriberType } from './types'import {CreateProjectDTO,@@ -73,6 +73,8 @@ import {UpdateSubscriberBodyDto,FunnelCreateDTO,FunnelUpdateDTO,+ AnnotationCreateDTO,+ AnnotationUpdateDTO,} from './dto'import { ReportFrequency } from './enums'import { nFormatter } from '../common/utils'@@ -288,6 +290,8 @@ export class ProjectService {private readonly projectSubscriberRepository: Repository<ProjectSubscriber>,@InjectRepository(Funnel)private readonly funnelRepository: Repository<Funnel>,+ @InjectRepository(Annotation)+ private readonly annotationRepository: Repository<Annotation>,private readonly actionTokens: ActionTokensService,private readonly mailerService: MailerService,private readonly userService: UserService,@@ -1249,6 +1253,43 @@ export class ProjectService {return this.funnelRepository.delete({ id })}+ async createAnnotation(projectId: string, data: AnnotationCreateDTO) {+ const annotation = await this.annotationRepository.save({+ date: data.date,+ text: data.text,+ project: { id: projectId },+ })+ return annotation+ }++ async getAnnotations(projectId: string) {+ return this.annotationRepository.find({+ where: { project: { id: projectId } },+ order: { date: 'ASC' },+ })+ }++ async getAnnotation(annotationId: string, projectId: string) {+ return this.annotationRepository.findOne({+ where: { id: annotationId, project: { id: projectId } },+ })+ }++ async updateAnnotation(data: AnnotationUpdateDTO) {+ const updateData: Partial<Annotation> = {}+ if (data.date !== undefined) {+ updateData.date = new Date(data.date)+ }+ if (data.text !== undefined) {+ updateData.text = data.text+ }+ return this.annotationRepository.update({ id: data.id }, updateData)+ }++ async deleteAnnotation(id: string) {+ return this.annotationRepository.delete({ id })+ }+async updateSubscriber(projectId: string,subscriberId: string,diff --git a/backend/migrations/mysql/2025_11_30.sql b/backend/migrations/mysql/2025_11_30.sqlnew file mode 100644index 000000000..81ecb3cc6--- /dev/null+++ b/backend/migrations/mysql/2025_11_30.sql@@ -0,0 +1,10 @@+CREATE TABLE `annotation` (+ `id` varchar(36) NOT NULL,+ `date` date NOT NULL,+ `text` varchar(120) NOT NULL,+ `created` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),+ `projectId` varchar(12) DEFAULT NULL,+ PRIMARY KEY (`id`),+ FOREIGN KEY (`projectId`) REFERENCES `project` (`id`) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;+diff --git a/web/app/api/index.ts b/web/app/api/index.tsindex ec6737de6..d76f8e2ec 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -1118,6 +1118,42 @@ export const deleteFunnel = (id: string, pid: string) =>throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})+export const getAnnotations = (pid: string, password: string | undefined = '') =>+ api+ .get(`project/annotations/${pid}`, {+ headers: {+ 'x-password': password,+ },+ })+ .then((response): any[] => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const createAnnotation = (pid: string, date: string, text: string) =>+ api+ .post('project/annotation', { pid, date, text })+ .then((response): any => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const updateAnnotation = (id: string, pid: string, date: string, text: string) =>+ api+ .patch('project/annotation', { id, pid, date, text })+ .then((response): any => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const deleteAnnotation = (id: string, pid: string) =>+ api+ .delete(`project/annotation/${id}/${pid}`)+ .then((response): any => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })+export const getSubscribers = (id: string, offset: number, limit: number) =>api.get(`project/${id}/subscribers?offset=${offset}&limit=${limit}`)diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.tsindex 7a1b9a004..70838763a 100644--- a/web/app/lib/models/Project.ts+++ b/web/app/lib/models/Project.ts@@ -58,6 +58,13 @@ export interface Funnel {created: string}+export interface Annotation {+ id: string+ date: string+ text: string+ created: string+}+export interface SwetrixError {eid: stringname: stringdiff --git a/web/app/modals/AnnotationModal.tsx b/web/app/modals/AnnotationModal.tsxnew file mode 100644index 000000000..4048a4363--- /dev/null+++ b/web/app/modals/AnnotationModal.tsx@@ -0,0 +1,139 @@+import { InfoIcon } from 'lucide-react'+import { useState, useEffect } from 'react'+import { useTranslation } from 'react-i18next'++import { Annotation } from '~/lib/models/Project'+import Input from '~/ui/Input'+import Modal from '~/ui/Modal'+import Textarea from '~/ui/Textarea'++const MAX_ANNOTATION_LENGTH = 120++interface AnnotationModalProps {+ onClose: () => void+ onSubmit: (date: string, text: string) => Promise<void>+ onDelete?: () => Promise<void>+ isOpened: boolean+ loading: boolean+ annotation?: Annotation+ defaultDate?: string+ allowedToManage?: boolean+}++const AnnotationModal = ({+ onClose,+ onSubmit,+ onDelete,+ isOpened,+ annotation,+ loading,+ defaultDate,+ allowedToManage = true,+}: AnnotationModalProps) => {+ const { t } = useTranslation('common')+ const [date, setDate] = useState(annotation?.date || defaultDate || '')+ const [text, setText] = useState(annotation?.text || '')++ useEffect(() => {+ if (!isOpened) {+ return+ }++ setDate(annotation?.date || defaultDate || '')+ setText(annotation?.text || '')+ }, [isOpened, annotation, defaultDate])++ const _onClose = () => {+ setTimeout(() => {+ setDate('')+ setText('')+ }, 300)+ onClose()+ }++ const _onSubmit = async () => {+ if (!date || !text.trim() || !allowedToManage) {+ return+ }++ await onSubmit(date, text.trim())+ _onClose()+ }++ const _onDelete = async () => {+ if (!onDelete || !allowedToManage) {+ return+ }++ await onDelete()+ _onClose()+ }++ const isEditMode = !!annotation++ return (+ <Modal+ isLoading={loading}+ onClose={_onClose}+ onSubmit={_onSubmit}+ submitText={isEditMode ? t('common.save') : t('common.add')}+ closeText={t('common.cancel')}+ customButtons={+ isEditMode && onDelete && allowedToManage ? (+ <button+ type='button'+ onClick={_onDelete}+ disabled={loading}+ className='mt-3 inline-flex w-full justify-center rounded-md border border-red-300 bg-white px-4 py-2 text-base font-medium text-red-700 transition-colors hover:bg-red-50 sm:mt-0 sm:w-auto sm:text-sm dark:border-red-600 dark:bg-slate-800 dark:text-red-400 dark:hover:bg-red-900/20'+ >+ {t('common.delete')}+ </button>+ ) : null+ }+ message={+ <div className='space-y-4'>+ <Input+ name='annotation-date-input'+ label={+ <>+ {t('modals.annotation.date')}+ <span className='text-red-600'>*</span>+ </>+ }+ type='date'+ value={date}+ onChange={(e) => setDate(e.target.value)}+ disabled={!allowedToManage}+ />+ <div>+ <Textarea+ name='annotation-text-input'+ label={t('modals.annotation.text')}+ value={text}+ onChange={(e) => {+ if (e.target.value.length <= MAX_ANNOTATION_LENGTH) {+ setText(e.target.value)+ }+ }}+ disabled={!allowedToManage}+ rows={3}+ />+ <p className='mt-1 text-right text-xs text-gray-500 dark:text-gray-400'>+ {text.length}/{MAX_ANNOTATION_LENGTH}+ </p>+ </div>+ <div className='flex items-start gap-2 rounded-md bg-blue-50 p-3 dark:bg-blue-900/20'>+ <InfoIcon className='mt-0.5 h-4 w-4 shrink-0 text-blue-600 dark:text-blue-400' />+ <p className='text-xs text-blue-700 dark:text-blue-300'>{t('modals.annotation.warning')}</p>+ </div>+ </div>+ }+ title={isEditMode ? t('modals.annotation.editTitle') : t('modals.annotation.addTitle')}+ isOpened={isOpened}+ submitDisabled={!date || !text.trim() || !allowedToManage}+ overflowVisible+ />+ )+}++export default AnnotationModaldiff --git a/web/app/pages/Project/Settings/Annotations.tsx b/web/app/pages/Project/Settings/Annotations.tsxnew file mode 100644index 000000000..8197c2713--- /dev/null+++ b/web/app/pages/Project/Settings/Annotations.tsx@@ -0,0 +1,274 @@+import { PencilIcon, Trash2Icon, PlusIcon } from 'lucide-react'+import _isEmpty from 'lodash/isEmpty'+import _map from 'lodash/map'+import _size from 'lodash/size'+import { useCallback, useEffect, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'++import {+ getAnnotations,+ createAnnotation,+ updateAnnotation as updateAnnotationApi,+ deleteAnnotation as deleteAnnotationApi,+} from '~/api'+import { Annotation } from '~/lib/models/Project'+import AnnotationModal from '~/modals/AnnotationModal'+import Button from '~/ui/Button'+import Loader from '~/ui/Loader'+import Modal from '~/ui/Modal'+import Pagination from '~/ui/Pagination'++const ANNOTATIONS_PER_PAGE = 10++interface AnnotationsProps {+ projectId: string+ allowedToManage: boolean+}++const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {+ const { t } = useTranslation('common')++ const [annotations, setAnnotations] = useState<Annotation[]>([])+ const [isLoading, setIsLoading] = useState(true)+ const [page, setPage] = useState(1)++ // Modal states+ const [isModalOpen, setIsModalOpen] = useState(false)+ const [editingAnnotation, setEditingAnnotation] = useState<Annotation | undefined>()+ const [actionLoading, setActionLoading] = useState(false)++ // Delete confirmation+ const [deleteAnnotation, setDeleteAnnotation] = useState<Annotation | null>(null)++ const loadAnnotations = useCallback(async () => {+ setIsLoading(true)+ try {+ const result = await getAnnotations(projectId)+ // Sort by date descending (newest first)+ const sorted = result.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())+ setAnnotations(sorted)+ } catch (reason: any) {+ console.error('[ERROR] Failed to load annotations:', reason)+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))+ } finally {+ setIsLoading(false)+ }+ }, [projectId, t])++ useEffect(() => {+ loadAnnotations()+ }, [loadAnnotations])++ const totalPages = Math.ceil(_size(annotations) / ANNOTATIONS_PER_PAGE)+ const paginatedAnnotations = annotations.slice((page - 1) * ANNOTATIONS_PER_PAGE, page * ANNOTATIONS_PER_PAGE)++ const openCreateModal = () => {+ setEditingAnnotation(undefined)+ setIsModalOpen(true)+ }++ const openEditModal = (annotation: Annotation) => {+ setEditingAnnotation(annotation)+ setIsModalOpen(true)+ }++ const closeModal = () => {+ setIsModalOpen(false)+ setEditingAnnotation(undefined)+ }++ const handleSubmit = async (date: string, text: string) => {+ setActionLoading(true)+ try {+ if (editingAnnotation) {+ await updateAnnotationApi(editingAnnotation.id, projectId, date, text)+ toast.success(t('apiNotifications.annotationUpdated'))+ } else {+ await createAnnotation(projectId, date, text)+ toast.success(t('apiNotifications.annotationCreated'))+ }+ await loadAnnotations()+ } catch (reason: any) {+ console.error('[ERROR] Failed to save annotation:', reason)+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))+ } finally {+ setActionLoading(false)+ }+ }++ const handleDelete = async () => {+ if (!deleteAnnotation) return++ setActionLoading(true)+ try {+ await deleteAnnotationApi(deleteAnnotation.id, projectId)+ toast.success(t('apiNotifications.annotationDeleted'))+ setDeleteAnnotation(null)+ await loadAnnotations()+ // Reset to first page if current page becomes empty+ if (paginatedAnnotations.length === 1 && page > 1) {+ setPage(page - 1)+ }+ } catch (reason: any) {+ console.error('[ERROR] Failed to delete annotation:', reason)+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))+ } finally {+ setActionLoading(false)+ }+ }++ const handleDeleteFromModal = async () => {+ if (!editingAnnotation) return++ setActionLoading(true)+ try {+ await deleteAnnotationApi(editingAnnotation.id, projectId)+ toast.success(t('apiNotifications.annotationDeleted'))+ closeModal()+ await loadAnnotations()+ } catch (reason: any) {+ console.error('[ERROR] Failed to delete annotation:', reason)+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))+ } finally {+ setActionLoading(false)+ }+ }++ if (isLoading) {+ return (+ <div className='flex justify-center py-8'>+ <Loader />+ </div>+ )+ }++ return (+ <div>+ <div className='mb-4 flex items-center justify-between'>+ <div>+ <h3 className='text-lg font-medium text-gray-900 dark:text-gray-50'>+ {t('project.settings.annotations.title')}+ </h3>+ <p className='mt-1 text-sm text-gray-500 dark:text-gray-400'>+ {t('project.settings.annotations.description')}+ </p>+ </div>+ {allowedToManage && (+ <Button type='button' onClick={openCreateModal} primary regular>+ <PlusIcon className='mr-1 h-4 w-4' />+ {t('project.settings.annotations.add')}+ </Button>+ )}+ </div>++ {_isEmpty(annotations) ? (+ <div className='rounded-lg border border-dashed border-gray-300 p-8 text-center dark:border-slate-700'>+ <p className='text-gray-500 dark:text-gray-400'>{t('project.settings.annotations.empty')}</p>+ {allowedToManage && (+ <Button type='button' onClick={openCreateModal} className='mt-4' primary regular>+ <PlusIcon className='mr-1 h-4 w-4' />+ {t('project.settings.annotations.addFirst')}+ </Button>+ )}+ </div>+ ) : (+ <>+ <div className='overflow-hidden rounded-lg border border-gray-200 dark:border-slate-700'>+ <table className='min-w-full divide-y divide-gray-200 dark:divide-slate-700'>+ <thead className='bg-gray-50 dark:bg-slate-800'>+ <tr>+ <th+ scope='col'+ className='px-4 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase dark:text-gray-400'+ >+ {t('project.settings.annotations.date')}+ </th>+ <th+ scope='col'+ className='px-4 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase dark:text-gray-400'+ >+ {t('project.settings.annotations.text')}+ </th>+ {allowedToManage && (+ <th+ scope='col'+ className='px-4 py-3 text-right text-xs font-medium tracking-wider text-gray-500 uppercase dark:text-gray-400'+ >+ {t('common.actions')}+ </th>+ )}+ </tr>+ </thead>+ <tbody className='divide-y divide-gray-200 bg-white dark:divide-slate-700 dark:bg-slate-900'>+ {_map(paginatedAnnotations, (annotation) => (+ <tr key={annotation.id} className='hover:bg-gray-50 dark:hover:bg-slate-800/50'>+ <td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>+ {new Date(annotation.date).toLocaleDateString()}+ </td>+ <td className='px-4 py-3 text-sm text-gray-700 dark:text-gray-300'>+ <span className='line-clamp-2'>{annotation.text}</span>+ </td>+ {allowedToManage && (+ <td className='px-4 py-3 text-right text-sm whitespace-nowrap'>+ <div className='flex items-center justify-end gap-2'>+ <button+ type='button'+ onClick={() => openEditModal(annotation)}+ className='rounded p-1.5 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-slate-700 dark:hover:text-gray-200'+ title={t('common.edit')}+ >+ <PencilIcon className='h-4 w-4' />+ </button>+ <button+ type='button'+ onClick={() => setDeleteAnnotation(annotation)}+ className='rounded p-1.5 text-red-500 transition-colors hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-900/20 dark:hover:text-red-300'+ title={t('common.delete')}+ >+ <Trash2Icon className='h-4 w-4' />+ </button>+ </div>+ </td>+ )}+ </tr>+ ))}+ </tbody>+ </table>+ </div>++ {totalPages > 1 && (+ <div className='mt-4 flex justify-center'>+ <Pagination page={page} setPage={setPage} pageAmount={totalPages} total={_size(annotations)} />+ </div>+ )}+ </>+ )}++ <AnnotationModal+ isOpened={isModalOpen}+ onClose={closeModal}+ onSubmit={handleSubmit}+ onDelete={editingAnnotation ? handleDeleteFromModal : undefined}+ loading={actionLoading}+ annotation={editingAnnotation}+ allowedToManage={allowedToManage}+ />++ <Modal+ isOpened={!!deleteAnnotation}+ onClose={() => setDeleteAnnotation(null)}+ onSubmit={handleDelete}+ title={t('project.settings.annotations.deleteTitle')}+ message={t('project.settings.annotations.deleteConfirm')}+ submitText={t('common.delete')}+ closeText={t('common.cancel')}+ submitType='danger'+ type='error'+ isLoading={actionLoading}+ />+ </div>+ )+}++export default Annotationsdiff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsxindex 383791dee..e278c6ef7 100644--- a/web/app/pages/Project/Settings/ProjectSettings.tsx+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx@@ -20,6 +20,7 @@ import {TriangleAlertIcon,ChevronLeftIcon,PuzzleIcon,+ StickyNoteIcon,} from 'lucide-react'import React, { useState, useEffect, useMemo, useCallback } from 'react'import { Trans, useTranslation } from 'react-i18next'@@ -64,6 +65,7 @@ import routes from '~/utils/routes'import CCRow from '../View/components/CCRow'import { getFormatDate } from '../View/ViewProject.helpers'+import Annotations from './Annotations'import Emails from './Emails'import People from './People'import AccessSettings from './tabs/AccessSettings'@@ -313,7 +315,7 @@ const ProjectSettings = () => {const [error, setError] = useState<string | null>(null)const [searchParams, setSearchParams] = useSearchParams()- type SettingsTab = 'general' | 'shields' | 'access' | 'integrations' | 'emails' | 'people' | 'danger'+ type SettingsTab = 'general' | 'shields' | 'access' | 'integrations' | 'emails' | 'people' | 'annotations' | 'danger'const tabs = useMemo(() =>@@ -329,6 +331,7 @@ const ProjectSettings = () => {},{ id: 'emails', label: t('project.settings.tabs.emails'), icon: MailIcon, visible: !isSelfhosted },{ id: 'people', label: t('project.settings.tabs.people'), icon: UserRoundIcon, visible: true },+ { id: 'annotations', label: t('project.settings.tabs.annotations'), icon: StickyNoteIcon, visible: true },{id: 'danger',label: t('project.settings.tabs.danger'),@@ -813,6 +816,9 @@ const ProjectSettings = () => {{activeTab === 'emails' && !isSelfhosted ? <Emails projectId={id} /> : null}{activeTab === 'people' ? <People project={project} reloadProject={reloadProject} /> : null}+ {activeTab === 'annotations' ? (+ <Annotations projectId={id} allowedToManage={project?.role === 'owner' || project?.role === 'admin'} />+ ) : null}{activeTab === 'integrations' ? (<div>diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsxindex 934c3efd6..778386bfe 100644--- a/web/app/pages/Project/View/ViewProject.helpers.tsx+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx@@ -52,7 +52,7 @@ import {OS_LOGO_MAP_DARK,} from '~/lib/constants'import { Entry } from '~/lib/models/Entry'-import { AnalyticsFunnel } from '~/lib/models/Project'+import { AnalyticsFunnel, Annotation } from '~/lib/models/Project'import { getTimeFromSeconds, getStringFromTime, sumArrays, nFormatter } from '~/utils/generic'import countries from '~/utils/isoCountries'@@ -501,9 +501,17 @@ const getSettings = (compareChart?: TrafficLogResponse['chart'] & { [key: string]: number[] },onZoom?: (domain: [Date, Date] | null) => void,enableZoom?: boolean,+ annotations?: Annotation[],): ChartOptions => {const xAxisSize = _size(chart.x)- const lines: GridLineOptions[] = []++ // Convert annotations to grid lines+ const lines: GridLineOptions[] = _map(annotations || [], (annotation) => ({+ value: dayjs(annotation.date).toDate(),+ text: annotation.text.length > 20 ? `${annotation.text.substring(0, 20)}...` : annotation.text,+ class: 'annotation-line',+ position: 'start',+ }))const modifiedChart = { ...chart }let regionsconst customEventsToArray = customEvents@@ -1004,9 +1012,18 @@ const getSettingsError = (timeFormat: string,rotateXAxis: boolean,chartType: string,+ annotations?: Annotation[],): ChartOptions => {const xAxisSize = _size(chart.x)+ // Convert annotations to grid lines+ const annotationLines: GridLineOptions[] = _map(annotations || [], (annotation) => ({+ value: dayjs(annotation.date).toDate(),+ text: annotation.text.length > 20 ? `${annotation.text.substring(0, 20)}...` : annotation.text,+ class: 'annotation-line',+ position: 'start',+ }))+const columns = getColumns(chart, { occurrences: true })const allYValues: number[] = []@@ -1048,6 +1065,9 @@ const getSettingsError = (},},grid: {+ x: {+ lines: annotationLines,+ },y: {show: true,},@@ -1325,9 +1345,18 @@ const getSettingsPerf = (compareChart?: Record<string, string[]>,onZoom?: (domain: [Date, Date] | null) => void,enableZoom?: boolean,+ annotations?: Annotation[],): ChartOptions => {const xAxisSize = _size(chart.x)+ // Convert annotations to grid lines+ const annotationLines: GridLineOptions[] = _map(annotations || [], (annotation) => ({+ value: dayjs(annotation.date).toDate(),+ text: annotation.text.length > 20 ? `${annotation.text.substring(0, 20)}...` : annotation.text,+ class: 'annotation-line',+ position: 'start',+ }))+return {data: {x: 'x',@@ -1406,6 +1435,9 @@ const getSettingsPerf = (],},grid: {+ x: {+ lines: annotationLines,+ },y: {show: true,},diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex ff21c5c3b..aa43ab888 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -78,6 +78,10 @@ import {deleteProjectView,getFunnels,getGSCKeywords,+ getAnnotations,+ createAnnotation,+ updateAnnotation,+ deleteAnnotation,} from '~/api'import EventsRunningOutBanner from '~/components/EventsRunningOutBanner'import Footer from '~/components/Footer'@@ -125,7 +129,9 @@ import {SwetrixErrorDetails,SessionDetails as SessionDetailsModel,Session,+ Annotation,} from '~/lib/models/Project'+import AnnotationModal from '~/modals/AnnotationModal'import NewFunnel from '~/modals/NewFunnel'import ViewProjectHotkeys from '~/modals/ViewProjectHotkeys'import { useAuth } from '~/providers/AuthProvider'@@ -155,6 +161,7 @@ import ProjectAlertsView from '../Alerts/View'import AddAViewModal from './components/AddAViewModal'import CCRow from './components/CCRow'+import { ChartContextMenu } from './components/ChartContextMenu'import { ChartManagerProvider } from './components/ChartManager'import CustomEventsSubmenu from './components/CustomEventsSubmenu'import CustomMetrics from './components/CustomMetrics'@@ -561,6 +568,29 @@ 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,+ })+// Reset sessions and errors when filters change so lists reload with correct paginationuseEffect(() => {sessionsRequestIdRef.current += 1@@ -690,6 +720,203 @@ const ViewProjectContent = () => {setFunnelActionLoading(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 () => {+ if (annotationActionLoading || !annotationToEdit) {+ return+ }++ setAnnotationActionLoading(true)++ try {+ await deleteAnnotation(annotationToEdit.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) => {+ // Always prevent default - we'll show our own menu (even if empty for non-managers)+ event.preventDefault()++ let existingAnnotation: Annotation | null = null+ let date: string | null = null++ // Check if user clicked directly on an annotation line (traverse up DOM tree for SVG compatibility)+ let element: Element | null = event.target as Element+ let annotationLineElement: Element | null = null++ while (element && element !== event.currentTarget) {+ if (element.classList?.contains('annotation-line')) {+ annotationLineElement = element+ break+ }+ element = element.parentElement+ }++ if (annotationLineElement) {+ // User clicked on an annotation line - find the annotation by its text+ const textElement = annotationLineElement.querySelector('text')+ if (textElement) {+ const lineText = textElement.textContent || ''+ // Find annotation that matches this text (could be truncated)+ existingAnnotation =+ annotations.find(+ (a) => a.text === lineText || (a.text.length > 20 && `${a.text.substring(0, 20)}...` === lineText),+ ) || null+ if (existingAnnotation) {+ date = dayjs(existingAnnotation.date).format('YYYY-MM-DD')+ }+ }+ }++ // If not clicking on annotation line, calculate date from position+ if (!existingAnnotation && xAxisData && xAxisData.length > 0) {+ const chartContainer = (event.currentTarget as HTMLElement).querySelector('.bb') as HTMLElement+ if (chartContainer) {+ const rect = chartContainer.getBoundingClientRect()+ const clickX = event.clientX - rect.left++ // Get the chart area (excluding y-axis labels) - approximate 50px for y-axis+ const chartAreaStart = 50+ const chartAreaWidth = rect.width - chartAreaStart - 20 // 20px padding on right++ // Calculate the relative position within the chart area+ const relativeX = Math.max(0, clickX - chartAreaStart)+ const percentage = Math.min(1, relativeX / chartAreaWidth)++ // Calculate the index+ const index = Math.round(percentage * (xAxisData.length - 1))+ const clampedIndex = Math.max(0, Math.min(xAxisData.length - 1, index))++ // Format date as YYYY-MM-DD for the date input+ date = dayjs(xAxisData[clampedIndex]).format('YYYY-MM-DD')++ // Check if there's an annotation for this calculated date (normalize both to YYYY-MM-DD)+ existingAnnotation =+ annotations.find((a) => {+ const annotationDate = dayjs(a.date).format('YYYY-MM-DD')+ return annotationDate === date+ }) || null++ // If no exact match, find the closest annotation within a pixel threshold+ if (!existingAnnotation && annotations.length > 0) {+ const pixelThreshold = 30 // pixels+ 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 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+ 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+ }+ }+ }++ 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 [panelsActiveTabs, setPanelsActiveTabs] = useState<{location: 'cc' | 'rg' | 'ct' | 'lc' | 'map'page: 'pg' | 'host' | 'userFlow' | 'entryPage' | 'exitPage'@@ -2100,6 +2327,16 @@ const ViewProjectContent = () => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [mode, activeTab, customMetrics, filters, authLoading, project, isActiveCompare, dateRange, period, timeBucket])+ // Load annotations when project loads+ useEffect(() => {+ if (authLoading || !project) {+ return+ }++ loadAnnotations()+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [authLoading, project])+useEffect(() => {if (activeTab !== PROJECT_TABS.traffic || authLoading || !project) {return@@ -3374,14 +3611,20 @@ const ViewProjectContent = () => {</div>{activeError?.details ? <ErrorDetails details={activeError.details} /> : null}{activeError?.chart ? (- <ErrorChart- chart={activeError?.chart}- timeBucket={activeError?.timeBucket}- timeFormat={timeFormat}- rotateXAxis={rotateXAxis}- chartType={chartType}- dataNames={dataNames}- />+ <div+ onContextMenu={(e) => handleChartContextMenu(e, activeError?.chart?.x)}+ className='relative'+ >+ <ErrorChart+ chart={activeError?.chart}+ timeBucket={activeError?.timeBucket}+ timeFormat={timeFormat}+ rotateXAxis={rotateXAxis}+ chartType={chartType}+ dataNames={dataNames}+ annotations={annotations}+ />+ </div>) : null}<Filters tnMapping={tnMapping} /><div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>@@ -3695,21 +3938,24 @@ const ViewProjectContent = () => {</div>) : null}{!checkIfAllMetricsAreDisabled && !_isEmpty(chartData) ? (- <TrafficChart- chartData={chartData}- timeBucket={timeBucket}- activeChartMetrics={activeChartMetrics}- applyRegions={!_includes(noRegionPeriods, activePeriod?.period)}- timeFormat={timeFormat}- rotateXAxis={rotateXAxis}- chartType={chartType}- customEventsChartData={customEventsChartData}- dataChartCompare={dataChartCompare}- onZoom={onMainChartZoom}- enableZoom={shouldEnableZoom}- dataNames={dataNames}- className='mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible'- />+ <div onContextMenu={(e) => handleChartContextMenu(e, chartData.x)} className='relative'>+ <TrafficChart+ chartData={chartData}+ timeBucket={timeBucket}+ activeChartMetrics={activeChartMetrics}+ applyRegions={!_includes(noRegionPeriods, activePeriod?.period)}+ timeFormat={timeFormat}+ rotateXAxis={rotateXAxis}+ chartType={chartType}+ customEventsChartData={customEventsChartData}+ dataChartCompare={dataChartCompare}+ onZoom={onMainChartZoom}+ enableZoom={shouldEnableZoom}+ dataNames={dataNames}+ className='mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible'+ annotations={annotations}+ />+ </div>) : null}</div>{!isPanelsDataEmpty ? <Filters tnMapping={tnMapping} /> : null}@@ -4098,19 +4344,25 @@ const ViewProjectContent = () => {/>) : null}{!checkIfAllMetricsAreDisabled && !_isEmpty(chartDataPerf) ? (- <PerformanceChart- chart={chartDataPerf}- timeBucket={timeBucket}- activeChartMetrics={activeChartMetricsPerf}- rotateXAxis={rotateXAxis}- chartType={chartType}- timeFormat={timeFormat}- compareChart={dataChartPerfCompare}- onZoom={onMainChartZoom}- enableZoom={shouldEnableZoom}- dataNames={dataNamesPerf}- className='mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible'- />+ <div+ onContextMenu={(e) => handleChartContextMenu(e, chartDataPerf?.x)}+ className='relative'+ >+ <PerformanceChart+ chart={chartDataPerf}+ timeBucket={timeBucket}+ activeChartMetrics={activeChartMetricsPerf}+ rotateXAxis={rotateXAxis}+ chartType={chartType}+ timeFormat={timeFormat}+ compareChart={dataChartPerfCompare}+ onZoom={onMainChartZoom}+ enableZoom={shouldEnableZoom}+ dataNames={dataNamesPerf}+ className='mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible'+ annotations={annotations}+ />+ </div>) : null}</div>{!isPanelsDataEmptyPerf ? <Filters tnMapping={tnMapping} /> : null}@@ -4458,6 +4710,40 @@ 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+ ? () => {+ setAnnotationToEdit(contextMenu.annotation!)+ onAnnotationDelete()+ }+ : undefined+ }+ existingAnnotation={contextMenu.annotation}+ allowedToManage={allowedToManage}+ />{!isEmbedded ? <Footer showDBIPMessage /> : null}</></ViewProjectContext.Provider>diff --git a/web/app/pages/Project/View/components/ChartContextMenu.tsx b/web/app/pages/Project/View/components/ChartContextMenu.tsxnew file mode 100644index 000000000..68f7d9745--- /dev/null+++ b/web/app/pages/Project/View/components/ChartContextMenu.tsx@@ -0,0 +1,138 @@+import cx from 'clsx'+import { PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react'+import { useEffect, useRef } from 'react'+import { useTranslation } from 'react-i18next'++import { Annotation } from '~/lib/models/Project'++interface ChartContextMenuProps {+ x: number+ y: number+ isOpen: boolean+ onClose: () => void+ onAddAnnotation: () => void+ onEditAnnotation?: () => void+ onDeleteAnnotation?: () => void+ existingAnnotation?: Annotation | null+ allowedToManage: boolean+}++export const ChartContextMenu = ({+ x,+ y,+ isOpen,+ onClose,+ onAddAnnotation,+ onEditAnnotation,+ onDeleteAnnotation,+ existingAnnotation,+ allowedToManage,+}: ChartContextMenuProps) => {+ const { t } = useTranslation('common')+ const menuRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (!isOpen) {+ return+ }++ const handleClickOutside = (event: MouseEvent) => {+ if (menuRef.current && !menuRef.current.contains(event.target as Node)) {+ onClose()+ }+ }++ const handleEscape = (event: KeyboardEvent) => {+ if (event.key === 'Escape') {+ onClose()+ }+ }++ // Add a small delay to avoid the event that opened the menu from immediately closing it+ const timeoutId = setTimeout(() => {+ document.addEventListener('click', handleClickOutside)+ document.addEventListener('contextmenu', handleClickOutside)+ document.addEventListener('keydown', handleEscape)+ }, 10)++ return () => {+ clearTimeout(timeoutId)+ document.removeEventListener('click', handleClickOutside)+ document.removeEventListener('contextmenu', handleClickOutside)+ document.removeEventListener('keydown', handleEscape)+ }+ }, [isOpen, onClose])++ if (!isOpen) {+ return null+ }++ // If not allowed to manage, show a message+ if (!allowedToManage) {+ return (+ <div+ ref={menuRef}+ className='fixed z-[9999] min-w-[160px] rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-800'+ style={{+ left: x,+ top: y,+ }}+ >+ <div className='px-3 py-2 text-sm text-gray-500 dark:text-gray-400'>{t('project.annotationsViewOnly')}</div>+ </div>+ )+ }++ const menuItems = existingAnnotation+ ? [+ {+ label: t('project.editAnnotation'),+ icon: PencilIcon,+ onClick: onEditAnnotation,+ },+ {+ label: t('project.deleteAnnotation'),+ icon: Trash2Icon,+ onClick: onDeleteAnnotation,+ danger: true,+ },+ ]+ : [+ {+ label: t('project.addAnnotation'),+ icon: PlusIcon,+ onClick: onAddAnnotation,+ },+ ]++ return (+ <div+ ref={menuRef}+ className='fixed z-[9999] min-w-[160px] rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-800'+ style={{+ left: x,+ top: y,+ }}+ >+ {menuItems.map((item) => (+ <button+ key={item.label}+ type='button'+ onClick={() => {+ item.onClick?.()+ onClose()+ }}+ className={cx(+ 'flex w-full items-center gap-2 px-3 py-2 text-left text-sm transition-colors',+ item.danger+ ? 'text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20'+ : 'text-gray-700 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-slate-700',+ )}+ >+ <item.icon className='h-4 w-4' />+ {item.label}+ </button>+ ))}+ </div>+ )+}diff --git a/web/app/pages/Project/View/components/ErrorChart.tsx b/web/app/pages/Project/View/components/ErrorChart.tsxindex 2aed3a2fe..fb35aa8fa 100644--- a/web/app/pages/Project/View/components/ErrorChart.tsx+++ b/web/app/pages/Project/View/components/ErrorChart.tsx@@ -1,6 +1,8 @@import { ChartOptions } from 'billboard.js'import React, { useMemo } from 'react'+import { Annotation } from '~/lib/models/Project'+import { getSettingsError } from '../ViewProject.helpers'import { MainChart } from './MainChart'@@ -16,6 +18,7 @@ interface ErrorChartProps {chartType: stringdataNames: anyclassName?: string+ annotations?: Annotation[]}export const ErrorChart = ({@@ -26,14 +29,15 @@ export const ErrorChart = ({chartType,dataNames,className,+ annotations,}: ErrorChartProps) => {const options: ChartOptions = useMemo(() => {- return getSettingsError(chart, timeBucket as string, timeFormat, rotateXAxis, chartType)- }, [chart, timeBucket, timeFormat, rotateXAxis, chartType])+ return getSettingsError(chart, timeBucket as string, timeFormat, rotateXAxis, chartType, annotations)+ }, [chart, timeBucket, timeFormat, rotateXAxis, chartType, annotations])const deps = useMemo(- () => [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames],- [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames],+ () => [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames, annotations],+ [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames, annotations],)return (diff --git a/web/app/pages/Project/View/components/PerformanceChart.tsx b/web/app/pages/Project/View/components/PerformanceChart.tsxindex 9e7ef5348..f5ea7beeb 100644--- a/web/app/pages/Project/View/components/PerformanceChart.tsx+++ b/web/app/pages/Project/View/components/PerformanceChart.tsx@@ -1,6 +1,8 @@import { ChartOptions } from 'billboard.js'import React, { useMemo } from 'react'+import { Annotation } from '~/lib/models/Project'+import { getSettingsPerf } from '../ViewProject.helpers'import { MainChart } from './MainChart'@@ -17,6 +19,7 @@ interface PerformanceChartProps {enableZoom?: booleandataNames: Record<string, string>className?: string+ annotations?: Annotation[]}export const PerformanceChart = ({@@ -31,6 +34,7 @@ export const PerformanceChart = ({enableZoom,dataNames,className,+ annotations,}: PerformanceChartProps) => {const options: ChartOptions = useMemo(() => {return getSettingsPerf(@@ -43,12 +47,46 @@ export const PerformanceChart = ({compareChart,onZoom,enableZoom,+ annotations,)- }, [chart, timeBucket, activeChartMetrics, rotateXAxis, chartType, timeFormat, compareChart, onZoom, enableZoom])+ }, [+ chart,+ timeBucket,+ activeChartMetrics,+ rotateXAxis,+ chartType,+ timeFormat,+ compareChart,+ onZoom,+ enableZoom,+ annotations,+ ])const deps = useMemo(- () => [chart, timeBucket, activeChartMetrics, rotateXAxis, chartType, timeFormat, compareChart, onZoom, enableZoom],- [chart, timeBucket, activeChartMetrics, rotateXAxis, chartType, timeFormat, compareChart, onZoom, enableZoom],+ () => [+ chart,+ timeBucket,+ activeChartMetrics,+ rotateXAxis,+ chartType,+ timeFormat,+ compareChart,+ onZoom,+ enableZoom,+ annotations,+ ],+ [+ chart,+ timeBucket,+ activeChartMetrics,+ rotateXAxis,+ chartType,+ timeFormat,+ compareChart,+ onZoom,+ enableZoom,+ annotations,+ ],)return (diff --git a/web/app/pages/Project/View/components/TrafficChart.tsx b/web/app/pages/Project/View/components/TrafficChart.tsxindex e4abe0514..e41d5e479 100644--- a/web/app/pages/Project/View/components/TrafficChart.tsx+++ b/web/app/pages/Project/View/components/TrafficChart.tsx@@ -1,6 +1,8 @@import { ChartOptions } from 'billboard.js'import React, { useMemo } from 'react'+import { Annotation } from '~/lib/models/Project'+import { getSettings } from '../ViewProject.helpers'import { MainChart } from './MainChart'@@ -19,6 +21,7 @@ interface TrafficChartProps {enableZoom?: booleandataNames: Record<string, string>className?: string+ annotations?: Annotation[]}export const TrafficChart = ({@@ -35,6 +38,7 @@ export const TrafficChart = ({enableZoom,dataNames,className,+ annotations,}: TrafficChartProps) => {const options: ChartOptions = useMemo(() => {return getSettings(@@ -49,6 +53,7 @@ export const TrafficChart = ({dataChartCompare,onZoom,enableZoom,+ annotations,)}, [chartData,@@ -62,6 +67,7 @@ export const TrafficChart = ({dataChartCompare,onZoom,enableZoom,+ annotations,])const deps = useMemo(@@ -77,6 +83,7 @@ export const TrafficChart = ({dataChartCompare,onZoom,enableZoom,+ annotations,],[chartData,@@ -90,6 +97,7 @@ export const TrafficChart = ({dataChartCompare,onZoom,enableZoom,+ annotations,],)diff --git a/web/app/styles/ProjectViewStyle.css b/web/app/styles/ProjectViewStyle.cssindex bba669080..0c61c3726 100644--- a/web/app/styles/ProjectViewStyle.css+++ b/web/app/styles/ProjectViewStyle.css@@ -191,3 +191,39 @@ body.dark .bb-ygrid {margin-left: calc(0.5rem * calc(1 - var(--tw-space-x-reverse))) !important;}}++/* Annotation lines */+.bb-xgrid-line.annotation-line {+ pointer-events: all;+ cursor: pointer;+}++.bb-xgrid-line.annotation-line line {+ stroke: var(--color-purple-500);+ stroke-width: 2;+ stroke-dasharray: 4 2;+ pointer-events: stroke;+}++.bb-xgrid-line.annotation-line text {+ font-size: 10px;+ font-weight: 600;+ fill: var(--color-purple-700);+ dominant-baseline: middle;+ text-anchor: start;+ paint-order: stroke fill;+ stroke: white;+ stroke-width: 3px;+ stroke-linecap: round;+ stroke-linejoin: round;+ pointer-events: all;+}++body.dark .bb-xgrid-line.annotation-line line {+ stroke: var(--color-purple-400);+}++body.dark .bb-xgrid-line.annotation-line text {+ fill: var(--color-purple-300);+ stroke: var(--color-slate-900);+}diff --git a/web/app/styles/tailwind.css b/web/app/styles/tailwind.cssindex 529840bf3..009beb8cc 100644--- a/web/app/styles/tailwind.css+++ b/web/app/styles/tailwind.css@@ -1,7 +1,7 @@@import 'tailwindcss';-@plugin "@tailwindcss/forms";-@plugin "@tailwindcss/typography";+@plugin '@tailwindcss/forms';+@plugin '@tailwindcss/typography';@theme {/* Fonts */diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 60bcdc788..42862c28f 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -44,6 +44,9 @@"funnelCreated": "The funnel has been created","funnelUpdated": "The funnel has been updated","funnelDeleted": "The funnel has been deleted",+ "annotationCreated": "The annotation has been created",+ "annotationUpdated": "The annotation has been updated",+ "annotationDeleted": "The annotation has been deleted","errorCode": "Error code: {{error}}","updateErrorStatusFailed": "Error occured while updating error status","errorStatusUpdated": "Error status has been updated",@@ -908,6 +911,10 @@"support": "Contact support"},"project": {+ "addAnnotation": "Add annotation",+ "editAnnotation": "Edit annotation",+ "deleteAnnotation": "Delete annotation",+ "annotationsViewOnly": "Only project managers can add annotations","impressions": "Impressions","position": "Position","ctr": "CTR",@@ -1153,9 +1160,21 @@"shields": "Shields","emails": "Emails","people": "People",+ "annotations": "Annotations","danger": "Danger zone","integrations": "Integrations"},+ "annotations": {+ "title": "Annotations",+ "description": "Mark important events on your charts to remember why traffic patterns changed.",+ "add": "Add annotation",+ "addFirst": "Add your first annotation",+ "empty": "No annotations yet. Add annotations to mark important events on your charts.",+ "date": "Date",+ "text": "Note",+ "deleteTitle": "Delete annotation",+ "deleteConfirm": "Are you sure you want to delete this annotation? This action cannot be undone."+ },"botsProtectionLevel": {"title": "Bots protection level","levels": {@@ -1331,6 +1350,13 @@"steps": "Funnel steps","addStep": "Add one more step"},+ "annotation": {+ "addTitle": "Add annotation",+ "editTitle": "Edit annotation",+ "date": "Date",+ "text": "Annotation",+ "warning": "Caution: Don't include sensitive information. All users with access to this property can see annotation content."+ },"shortcuts": {"title": "Keyboard shortcuts","timebuckets": "Timebuckets selection",