Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Annotations: FE (#6481)

Artur Pataa3a2f3126fc8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 52c4cc1be2..e31fb5ddb6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file.
### Added
+- Annotations feature
- Pages report can now be broken down by URL (hostname + path) in addition to path only
- New "AI Assistants" acquisition channel + improved recognized sources database
- Allow querying revenue metrics (`total_revenue`, `average_revenue`) with visit dimensions in Stats API v2
diff --git a/assets/css/app.css b/assets/css/app.css
index 33a1f4faa0..4e3cc348a8 100644
--- a/assets/css/app.css
+++ b/assets/css/app.css
@@ -63,6 +63,10 @@
disabled:cursor-not-allowed;
}
+ .btn-xs {
+ @apply px-2 py-1;
+ }
+
.btn-sm {
@apply px-3 py-2;
}
diff --git a/assets/js/dashboard/annotations/annotation-list-items.tsx b/assets/js/dashboard/annotations/annotation-list-items.tsx
new file mode 100644
index 0000000000..03ebe3feb8
--- /dev/null
+++ b/assets/js/dashboard/annotations/annotation-list-items.tsx
@@ -0,0 +1,60 @@
+import React, { ReactNode } from 'react'
+import classNames from 'classnames'
+import {
+ Annotation,
+ getAnnotationAuthorship,
+ getAttributionDateLabel
+} from './annotations'
+
+export const AnnotationsListContainer = ({
+ children
+}: {
+ children: ReactNode
+}) => (
+ <div className="text-sm font-normal text-gray-100 flex flex-col gap-2">
+ {children}
+ </div>
+)
+
+const VerticalBar = () => (
+ <div className="rounded-xs w-[3px] bg-green-500 shrink-0" />
+)
+
+export const AnnotationItemRow = ({ children }: { children: ReactNode }) => (
+ <div className="group flex flex-row gap-x-2">
+ <VerticalBar />
+ {children}
+ </div>
+)
+
+export const AnnotationAuthorshipLine = ({
+ annotation
+}: {
+ annotation: Annotation
+}) => (
+ <div className="flex items-baseline text-xs text-gray-300 pr-8">
+ <span className="truncate min-w-0">
+ {getAnnotationAuthorship(annotation)}
+ </span>
+ <span className="whitespace-nowrap shrink-0">
+ {` • ${getAttributionDateLabel(annotation)}`}
+ </span>
+ </div>
+)
+
+export const AnnotationNote = ({
+ note,
+ clamp
+}: {
+ note: string
+ clamp?: boolean
+}) => (
+ <div
+ className={classNames(
+ 'text-left whitespace-pre-wrap [overflow-wrap:anywhere] [word-break:normal]',
+ { 'line-clamp-2': clamp }
+ )}
+ >
+ {note}
+ </div>
+)
diff --git a/assets/js/dashboard/annotations/annotations-modals.tsx b/assets/js/dashboard/annotations/annotations-modals.tsx
new file mode 100644
index 0000000000..bfac7ebaec
--- /dev/null
+++ b/assets/js/dashboard/annotations/annotations-modals.tsx
@@ -0,0 +1,380 @@
+import React, { ReactNode, useState } from 'react'
+import {
+ Annotation,
+ ANNOTATION_TYPE_LABELS,
+ AnnotationGranularity,
+ AnnotationPayload,
+ AnnotationType,
+ canEditAnnotation,
+ NOTE_MAX_LENGTH
+} from './annotations'
+import { MutationStatus } from '@tanstack/react-query'
+import { ApiError } from '../api'
+import { ErrorPanel } from '../components/error-panel'
+import {
+ ModalLayout,
+ ModalFooter,
+ SaveButton
+} from '../components/modal-layout'
+import {
+ LabeledTextarea,
+ TypeSelector,
+ getOptionDisabledMessage,
+ isOverMaxLength,
+ OptionDisabledMessageType
+} from '../components/form-elements'
+import { Button } from '../components/button'
+import { UpgradePill } from '../components/pill'
+import { Role, UserContextValue } from '../user-context'
+import {
+ formatDay,
+ formatTime,
+ is12HourClock,
+ parseUTCDate
+} from '../util/date'
+
+const formatAnnotationDatetime = (
+ datetime: string,
+ granularity: AnnotationGranularity
+): string => {
+ const date = parseUTCDate(datetime)
+ if (granularity === AnnotationGranularity.minute) {
+ const time = formatTime(date, {
+ use12HourClock: is12HourClock(),
+ includeMinutes: true
+ })
+ return `${formatDay(date)} at ${time}`
+ }
+ return formatDay(date)
+}
+
+interface ApiRequestProps {
+ status: MutationStatus
+ error?: unknown
+ reset: () => void
+}
+
+interface AnnotationModalProps {
+ user: UserContextValue
+ siteAnnotationsAvailable: boolean
+ onClose: () => void
+ notePlaceholder: string
+}
+
+export const CreateAnnotationModal = ({
+ onClose,
+ onSave,
+ user,
+ siteAnnotationsAvailable,
+ notePlaceholder,
+ initialDatetime,
+ initialGranularity,
+ initialType,
+ error,
+ reset,
+ status
+}: AnnotationModalProps &
+ ApiRequestProps & {
+ initialDatetime: AnnotationPayload['datetime']
+ initialGranularity: AnnotationPayload['granularity']
+ initialType: AnnotationPayload['type']
+ } & {
+ onSave: (input: AnnotationPayload) => void
+ }) => {
+ const [note, setNote] = useState('')
+ const [type, setType] = useState(initialType)
+ const trimmedNote = note.trim()
+ const granularity = initialGranularity
+ const datetime = initialDatetime
+
+ const siteOptionDisabledMessage = getAnnotationTypeDisabledMessage({
+ siteAnnotationsAvailable,
+ user
+ })
+
+ const disabledMessage =
+ type === AnnotationType.site ? siteOptionDisabledMessage : null
+
+ return (
+ <ModalLayout
+ title={`Add note for ${formatAnnotationDatetime(datetime, granularity)}`}
+ onClose={onClose}
+ >
+ <LabeledTextarea
+ label="Note"
+ id="note"
+ value={note}
+ onChange={setNote}
+ placeholder={notePlaceholder}
+ maxLength={NOTE_MAX_LENGTH}
+ />
+ <AnnotationTypeSelector
+ value={type}
+ onChange={setType}
+ siteOptionDisabledMessage={siteOptionDisabledMessage}
+ />
+ <ModalFooter>
+ <Button theme="secondary" size="sm" onClick={onClose}>
+ Cancel
+ </Button>
+ <SaveButton
+ disabled={isSaveButtonDisabled({
+ requestStatus: status,
+ disabledMessage,
+ trimmedNote
+ })}
+ onSave={() =>
+ onSave({
+ note: trimmedNote,
+ type,
+ datetime,
+ granularity
+ })
+ }
+ />
+ </ModalFooter>
+ {error !== null && (
+ <ErrorPanel
+ className="mt-4"
+ errorMessage={
+ error instanceof ApiError
+ ? error.message
+ : 'Something went wrong adding the note'
+ }
+ onClose={reset}
+ />
+ )}
+ </ModalLayout>
+ )
+}
+
+const AnnotationTypeSelector = ({
+ value,
+ onChange,
+ siteOptionDisabledMessage
+}: {
+ value: AnnotationType
+ onChange: (value: AnnotationType) => void
+ siteOptionDisabledMessage: OptionDisabledMessageType | null
+}) => (
+ <TypeSelector<AnnotationType>
+ idPrefix="annotation-type"
+ value={value}
+ onChange={onChange}
+ options={[
+ {
+ type: AnnotationType.personal,
+ name: ANNOTATION_TYPE_LABELS[AnnotationType.personal],
+ description: 'Visible only to you'
+ },
+ {
+ type: AnnotationType.site,
+ name: ANNOTATION_TYPE_LABELS[AnnotationType.site],
+ description: 'Visible to others on the site',
+ disabled: siteOptionDisabledMessage !== null,
+ pill:
+ siteOptionDisabledMessage === 'upgrade-subscription-yourself' ||
+ siteOptionDisabledMessage === 'upgrade-subscription-reach-out' ? (
+ <UpgradePill
+ plan="Growth"
+ linked={
+ siteOptionDisabledMessage === 'upgrade-subscription-yourself'
+ }
+ />
+ ) : null,
+ tooltipContent:
+ siteOptionDisabledMessage !== null ? (
+ <AnnotationTypeDisabledMessage
+ messageType={siteOptionDisabledMessage}
+ />
+ ) : null
+ }
+ ]}
+ />
+)
+
+const AnnotationTypeDisabledMessage = ({
+ messageType
+}: {
+ messageType: OptionDisabledMessageType
+}): Exclude<ReactNode, undefined> => {
+ switch (messageType) {
+ case 'no-permissions':
+ return "You don't have enough permissions to change note to this type"
+ case 'upgrade-subscription-yourself':
+ return 'Upgrade to Growth to make notes visible to others.'
+ case 'upgrade-subscription-reach-out':
+ return 'Ask a team owner to upgrade to Growth to make notes visible to others.'
+ }
+}
+
+const getAnnotationTypeDisabledMessage = ({
+ siteAnnotationsAvailable,
+ user
+}: {
+ siteAnnotationsAvailable: boolean
+ user: UserContextValue
+}): OptionDisabledMessageType | null =>
+ getOptionDisabledMessage({
+ optionAvailable: siteAnnotationsAvailable,
+ userHasOptionPermissions: canEditAnnotation({
+ type: AnnotationType.site,
+ user
+ }),
+ userCanUpgradeSubscription: user.role === Role.owner
+ })
+
+export const DeleteAnnotationModal = ({
+ annotation,
+ onClose,
+ onSave,
+ status,
+ error,
+ reset
+}: {
+ onClose: () => void
+ onSave: (input: Pick<Annotation, 'id'>) => void
+ annotation: Annotation
+} & ApiRequestProps) => {
+ const deleteDisabled = status === 'pending'
+
+ return (
+ <ModalLayout
+ title={
+ <>
+ Delete {ANNOTATION_TYPE_LABELS[annotation.type].toLowerCase()}
+ <span className="break-all">{` "${annotation.note}"?`}</span>
+ </>
+ }
+ onClose={onClose}
+ >
+ <ModalFooter>
+ <Button theme="secondary" size="sm" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button
+ theme="danger"
+ size="sm"
+ disabled={deleteDisabled}
+ onClick={
+ deleteDisabled
+ ? () => {}
+ : () => {
+ onSave({ id: annotation.id })
+ }
+ }
+ >
+ Delete
+ </Button>
+ </ModalFooter>
+ {error !== null && (
+ <ErrorPanel
+ className="mt-4"
+ errorMessage={
+ error instanceof ApiError
+ ? error.message
+ : 'Something went wrong deleting annotation'
+ }
+ onClose={reset}
+ />
+ )}
+ </ModalLayout>
+ )
+}
+
+export const UpdateAnnotationModal = ({
+ onClose,
+ onSave,
+ onDelete,
+ annotation,
+ siteAnnotationsAvailable,
+ user,
+ notePlaceholder,
+ status,
+ error,
+ reset
+}: AnnotationModalProps &
+ ApiRequestProps & {
+ onSave: (input: Pick<Annotation, 'id' | 'note' | 'type'>) => void
+ onDelete: (annotation: Annotation) => void
+ annotation: Annotation
+ }) => {
+ const [note, setNote] = useState(annotation.note)
+ const [type, setType] = useState<AnnotationType>(annotation.type)
+ const trimmedNote = note.trim()
+
+ const siteOptionDisabledMessage = getAnnotationTypeDisabledMessage({
+ siteAnnotationsAvailable,
+ user
+ })
+
+ const disabledMessage =
+ type === AnnotationType.site ? siteOptionDisabledMessage : null
+
+ return (
+ <ModalLayout
+ title={`Update note for ${formatAnnotationDatetime(annotation.datetime, annotation.granularity)}`}
+ onClose={onClose}
+ >
+ <LabeledTextarea
+ label="Note"
+ id="note"
+ value={note}
+ onChange={setNote}
+ placeholder={notePlaceholder}
+ maxLength={NOTE_MAX_LENGTH}
+ />
+ <AnnotationTypeSelector
+ value={type}
+ onChange={setType}
+ siteOptionDisabledMessage={siteOptionDisabledMessage}
+ />
+ <ModalFooter>
+ <Button
+ theme="danger"
+ size="sm"
+ className="mr-auto"
+ onClick={() => onDelete(annotation)}
+ >
+ Delete note
+ </Button>
+ <Button theme="secondary" size="sm" onClick={onClose}>
+ Cancel
+ </Button>
+ <SaveButton
+ disabled={isSaveButtonDisabled({
+ requestStatus: status,
+ disabledMessage,
+ trimmedNote
+ })}
+ onSave={() => onSave({ id: annotation.id, note: trimmedNote, type })}
+ />
+ </ModalFooter>
+ {error !== null && (
+ <ErrorPanel
+ className="mt-4"
+ errorMessage={
+ error instanceof ApiError
+ ? error.message
+ : 'Something went wrong updating note'
+ }
+ onClose={reset}
+ />
+ )}
+ </ModalLayout>
+ )
+}
+
+const isSaveButtonDisabled = ({
+ requestStatus,
+ disabledMessage,
+ trimmedNote
+}: {
+ requestStatus: MutationStatus
+ trimmedNote: string
+ disabledMessage: string | null
+}) =>
+ requestStatus === 'pending' ||
+ isOverMaxLength(trimmedNote, NOTE_MAX_LENGTH) ||
+ disabledMessage !== null ||
+ !trimmedNote.length
diff --git a/assets/js/dashboard/annotations/annotations.test.ts b/assets/js/dashboard/annotations/annotations.test.ts
new file mode 100644
index 0000000000..0b36eb0b2a
--- /dev/null
+++ b/assets/js/dashboard/annotations/annotations.test.ts
@@ -0,0 +1,297 @@
+import {
+ AnnotationGranularity,
+ AnnotationType,
+ canAddAnnotation,
+ canEditAnnotation,
+ getAnnotationAuthorship,
+ getAnnotationGranularity,
+ getAnnotationTimeLabel,
+ groupAnnotationsByTimeLabel
+} from './annotations'
+import { Interval } from '../stats/graph/intervals'
+import { Role, UserContextValue } from '../user-context'
+
+const loggedInUser = (role: Role, id: number = 42): UserContextValue => ({
+ loggedIn: true,
+ id,
+ role,
+ team: { identifier: null, hasConsolidatedView: false }
+})
+
+const publicUser: UserContextValue = {
+ loggedIn: false,
+ id: null,
+ role: Role.public,
+ team: { identifier: null, hasConsolidatedView: false }
+}
+
+describe(`${getAnnotationAuthorship.name}`, () => {
+ it('returns the owner name for a site annotation with an owner', () => {
+ expect(
+ getAnnotationAuthorship({
+ type: AnnotationType.site,
+ owner_name: 'Alice'
+ })
+ ).toBe('Alice')
+ })
+
+ it('returns "Site note" for a site annotation with a dangling owner', () => {
+ expect(
+ getAnnotationAuthorship({
+ type: AnnotationType.site,
+ owner_name: null
+ })
+ ).toBe('Site note')
+ })
+
+ it('returns "Personal note" for a personal annotation regardless of owner (we assume personal notes are served only to the author)', () => {
+ expect(
+ getAnnotationAuthorship({
+ type: AnnotationType.personal,
+ owner_name: 'Alice'
+ })
+ ).toBe('Personal note')
+ })
+})
+
+describe(`${canAddAnnotation.name}`, () => {
+ it.each([[Role.admin], [Role.editor], [Role.owner]])(
+ 'allows adding a site annotation if the user is logged in, in role %p, and the site-annotations feature is available',
+ (role) => {
+ expect(
+ canAddAnnotation({
+ type: AnnotationType.site,
+ user: loggedInUser(role),
+ siteAnnotationsAvailable: true
+ })
+ ).toBe(true)
+ }
+ )
+
+ it.each([[Role.admin], [Role.editor], [Role.owner]])(
+ 'forbids adding a site annotation in role %p when the feature is unavailable (billing gate)',
+ (role) => {
+ expect(
+ canAddAnnotation({
+ type: AnnotationType.site,
+ user: loggedInUser(role),
+ siteAnnotationsAvailable: false
+ })
+ ).toBe(false)
+ }
+ )
+
+ it.each([[Role.viewer], [Role.billing]])(
+ 'forbids adding a site annotation in role %p even when the feature is available',
+ (role) => {
+ expect(
+ canAddAnnotation({
+ type: AnnotationType.site,
+ user: loggedInUser(role),
+ siteAnnotationsAvailable: true
+ })
+ ).toBe(false)
+ }
+ )
+
+ it.each([
+ [Role.viewer],
+ [Role.billing],
+ [Role.editor],
+ [Role.admin],
+ [Role.owner]
+ ])(
+ 'allows adding a personal annotation in role %p regardless of site-annotations availability',
+ (role) => {
+ expect(
+ canAddAnnotation({
+ type: AnnotationType.personal,
+ user: loggedInUser(role),
+ siteAnnotationsAvailable: true
+ })
+ ).toBe(true)
+ expect(
+ canAddAnnotation({
+ type: AnnotationType.personal,
+ user: loggedInUser(role),
+ siteAnnotationsAvailable: false
+ })
+ ).toBe(true)
+ }
+ )
+
+ it.each([[AnnotationType.personal], [AnnotationType.site]])(
+ 'forbids the public role from adding %s annotations',
+ (type) => {
+ expect(
+ canAddAnnotation({
+ type,
+ user: publicUser,
+ siteAnnotationsAvailable: true
+ })
+ ).toBe(false)
+ }
+ )
+})
+
+describe(`${canEditAnnotation.name}`, () => {
+ it.each([[Role.admin], [Role.editor], [Role.owner]])(
+ 'allows editing a site annotation if the user is logged in and in role %p',
+ (role) => {
+ expect(
+ canEditAnnotation({
+ type: AnnotationType.site,
+ user: loggedInUser(role)
+ })
+ ).toBe(true)
+ }
+ )
+
+ it.each([[Role.viewer], [Role.billing]])(
+ 'forbids editing site annotations in role %p',
+ (role) => {
+ expect(
+ canEditAnnotation({
+ type: AnnotationType.site,
+ user: loggedInUser(role)
+ })
+ ).toBe(false)
+ }
+ )
+
+ it.each([
+ [Role.viewer],
+ [Role.billing],
+ [Role.editor],
+ [Role.admin],
+ [Role.owner]
+ ])('allows editing a personal annotation when in role %p', (role) => {
+ expect(
+ canEditAnnotation({
+ type: AnnotationType.personal,
+ user: loggedInUser(role)
+ })
+ ).toBe(true)
+ })
+
+ it.each([[AnnotationType.personal], [AnnotationType.site]])(
+ 'forbids the public role from editing %s annotations',
+ (type) => {
+ expect(
+ canEditAnnotation({
+ type,
+ user: publicUser
+ })
+ ).toBe(false)
+ }
+ )
+})
+
+describe(`${getAnnotationGranularity.name}`, () => {
+ it.each<[Interval, AnnotationGranularity]>([
+ [Interval.minute, AnnotationGranularity.minute],
+ [Interval.hour, AnnotationGranularity.minute],
+ [Interval.day, AnnotationGranularity.date],
+ [Interval.week, AnnotationGranularity.date],
+ [Interval.month, AnnotationGranularity.date]
+ ])('maps interval %s to granularity %s', (interval, granularity) => {
+ expect(getAnnotationGranularity(interval)).toBe(granularity)
+ })
+})
+
+describe(`${getAnnotationTimeLabel.name}`, () => {
+ // 2025-02-26 is a Wednesday
+ const dateAnnotation = {
+ datetime: '2025-02-26',
+ granularity: AnnotationGranularity.date
+ }
+
+ it.each<[Interval, string]>([
+ [Interval.minute, '2025-02-26'],
+ [Interval.hour, '2025-02-26'],
+ [Interval.day, '2025-02-26'],
+ [Interval.week, '2025-02-24'],
+ [Interval.month, '2025-02-01']
+ ])(
+ `date-granularity annotation on ${dateAnnotation.datetime} bucketed to %s yields %s`,
+ (interval, expected) => {
+ expect(getAnnotationTimeLabel(dateAnnotation, interval)).toBe(expected)
+ }
+ )
+
+ const minuteAnnotation = {
+ datetime: '2025-02-26T10:30:00',
+ granularity: AnnotationGranularity.minute
+ }
+ it.each<[Interval, string]>([
+ [Interval.month, '2025-02-01'],
+ [Interval.week, '2025-02-24'],
+ [Interval.day, '2025-02-26'],
+ [Interval.hour, '2025-02-26 10:00:00'],
+ [Interval.minute, '2025-02-26 10:30:00']
+ ])(
+ `minute granularity annotation with datetime ${minuteAnnotation.datetime} bucketed to %s yields %s`,
+ (interval, expected) => {
+ expect(getAnnotationTimeLabel(minuteAnnotation, interval)).toBe(expected)
+ }
+ )
+})
+
+describe(`${groupAnnotationsByTimeLabel.name}`, () => {
+ const dateGranularity = AnnotationGranularity.date
+ const annotations = [
+ { id: 1, datetime: '2025-02-24 00:00:00', granularity: dateGranularity }, // Mon
+ { id: 2, datetime: '2025-02-26 00:00:00', granularity: dateGranularity }, // Wed (same week)
+ { id: 3, datetime: '2025-03-05 00:00:00', granularity: dateGranularity } // following month
+ ]
+
+ it('groups annotations by day when the interval is day', () => {
+ const grouped = groupAnnotationsByTimeLabel(annotations, Interval.day)
+
+ expect(Object.keys(grouped).sort()).toEqual([
+ '2025-02-24',
+ '2025-02-26',
+ '2025-03-05'
+ ])
+ expect(grouped['2025-02-24']!.map((a) => a.id)).toEqual([1])
+ expect(grouped['2025-02-26']!.map((a) => a.id)).toEqual([2])
+ expect(grouped['2025-03-05']!.map((a) => a.id)).toEqual([3])
+ })
+
+ it('collapses annotations from the same week into one bucket', () => {
+ const grouped = groupAnnotationsByTimeLabel(annotations, Interval.week)
+
+ expect(Object.keys(grouped).sort()).toEqual(['2025-02-24', '2025-03-03'])
+ expect(grouped['2025-02-24']!.map((a) => a.id)).toEqual([1, 2])
+ expect(grouped['2025-03-03']!.map((a) => a.id)).toEqual([3])
+ })
+
+ it('collapses annotations from the same month into one bucket', () => {
+ const grouped = groupAnnotationsByTimeLabel(annotations, Interval.month)
+
+ expect(Object.keys(grouped).sort()).toEqual(['2025-02-01', '2025-03-01'])
+ expect(grouped['2025-02-01']!.map((a) => a.id)).toEqual([1, 2])
+ expect(grouped['2025-03-01']!.map((a) => a.id)).toEqual([3])
+ })
+
+ it('preserves insertion order within a bucket', () => {
+ const sameDay = [
+ { id: 10, datetime: '2025-02-26 08:00:00', granularity: dateGranularity },
+ { id: 11, datetime: '2025-02-26 09:00:00', granularity: dateGranularity },
+ { id: 12, datetime: '2025-02-26 10:00:00', granularity: dateGranularity }
+ ]
+
+ const grouped = groupAnnotationsByTimeLabel(sameDay, Interval.day)
+
+ expect(grouped['2025-02-26']!.map((a) => a.id)).toEqual([10, 11, 12])
+ })
+
+ it('returns an empty object when there are no annotations', () => {
+ expect(
+ groupAnnotationsByTimeLabel(
+ [] as { datetime: string; granularity: AnnotationGranularity }[],
+ Interval.day
+ )
+ ).toEqual({})
+ })
+})
diff --git a/assets/js/dashboard/annotations/annotations.ts b/assets/js/dashboard/annotations/annotations.ts
new file mode 100644
index 0000000000..4ba1faf966
--- /dev/null
+++ b/assets/js/dashboard/annotations/annotations.ts
@@ -0,0 +1,224 @@
+import { Interval } from '../stats/graph/intervals'
+import { Role, UserContextValue } from '../user-context'
+import {
+ formatDayShort,
+ formatTime,
+ is12HourClock,
+ parseUTCDate
+} from '../util/date'
+
+export enum AnnotationType {
+ personal = 'personal',
+ site = 'site'
+}
+
+/** This type signifies that the owner can't be shown. */
+// type AnnotationOwnershipHidden = { owner_id: null; owner_name: null }
+
+/** This type signifies that the original owner has been removed from the site. */
+type AnnotationOwnershipDangling = { owner_id: null; owner_name: null }
+
+type AnnotationOwnership =
+ | AnnotationOwnershipDangling
+ | { owner_id: number; owner_name: string }
+
+export enum AnnotationGranularity {
+ date = 'date',
+ minute = 'minute'
+}
+
+// the DB side limit is 255, but this looks better in the UI
+export const NOTE_MAX_LENGTH = 250
+
+export type Annotation = {
+ datetime: string
+ granularity: AnnotationGranularity
+ type: AnnotationType
+ note: string
+
+ id: number
+ /** datetime in site timezone, example 2025-02-26 10:00:00 */
+ inserted_at: string
+ /** datetime in site timezone, example 2025-02-26 10:00:00 */
+ updated_at: string
+} & AnnotationOwnership
+
+export type AnnotationPayload = Pick<
+ Annotation,
+ 'note' | 'datetime' | 'granularity' | 'type'
+>
+
+export const ANNOTATION_TYPE_LABELS = {
+ [AnnotationType.personal]: 'Personal note',
+ [AnnotationType.site]: 'Site note'
+}
+
+export const getAnnotationAuthorship = (
+ annotation: Pick<Annotation, 'type' | 'owner_name'>
+): string => {
+ if (annotation.type === AnnotationType.site && annotation.owner_name) {
+ return annotation.owner_name
+ }
+ return ANNOTATION_TYPE_LABELS[annotation.type]
+}
+
+export const getAttributionDateLabel = (
+ annotation: Pick<Annotation, 'datetime' | 'granularity'>
+): string => {
+ const date = parseUTCDate(annotation.datetime)
+ const dayLabel = formatDayShort(date)
+ if (annotation.granularity === AnnotationGranularity.minute) {
+ const time = formatTime(date, {
+ use12HourClock: is12HourClock(),
+ includeMinutes: true
+ })
+ return `${dayLabel} ${time}`
+ }
+ return dayLabel
+}
+
+/** keep in sync with Plausible.Annotations */
+const ROLES_WITH_MAYBE_SITE_ANNOTATIONS = [Role.admin, Role.editor, Role.owner]
+const ROLES_WITH_PERSONAL_ANNOTATIONS = [
+ Role.billing,
+ Role.viewer,
+ Role.admin,
+ Role.editor,
+ Role.owner
+]
+
+export function canEditAnnotation({
+ type,
+ user
+}: {
+ type: AnnotationType
+ user: UserContextValue
+}) {
+ if (!user.loggedIn) {
+ return false
+ }
+ switch (type) {
+ case AnnotationType.site:
+ // we don't check whether site annotations are available here:
+ // even when site annotations aren't available,
+ // the user should be able to downgrade them to personal, or delete them
+ return ROLES_WITH_MAYBE_SITE_ANNOTATIONS.includes(user.role)
+ case AnnotationType.personal:
+ return ROLES_WITH_PERSONAL_ANNOTATIONS.includes(user.role)
+ default:
+ return false
+ }
+}
+
+export function canShowAddAnnotationButton(props: {
+ user: UserContextValue
+ siteAnnotationsAvailable: boolean
+}) {
+ return (
+ canAddAnnotation({ type: AnnotationType.personal, ...props }) ||
+ canAddAnnotation({ type: AnnotationType.site, ...props })
+ )
+}
+
+export function canAddAnnotation({
+ type,
+ user,
+ siteAnnotationsAvailable
+}: {
+ type: AnnotationType
+ user: UserContextValue
+ siteAnnotationsAvailable: boolean
+}) {
+ switch (type) {
+ case AnnotationType.site:
+ return siteAnnotationsAvailable && canEditAnnotation({ type, user })
+ case AnnotationType.personal:
+ return canEditAnnotation({ type, user })
+ default:
+ return false
+ }
+}
+
+export const getAnnotationTimeLabel = (
+ annotation: Pick<Annotation, 'datetime' | 'granularity'>,
+ interval: Interval
+): string => {
+ const dateString = annotation.datetime.substring(0, 'YYYY-MM-DD'.length)
+ switch (annotation.granularity) {
+ case AnnotationGranularity.date: {
+ switch (interval) {
+ case Interval.month:
+ // floors to closest start of month for the date
+ return parseUTCDate(dateString).startOf('month').format('YYYY-MM-DD')
+ case Interval.week:
+ // floors to closest start of week for the date
+ return parseUTCDate(dateString).startOf('week').format('YYYY-MM-DD')
+ case Interval.day:
+ case Interval.hour:
+ case Interval.minute:
+ // floors to date
+ return dateString
+ }
+ break
+ }
+ case AnnotationGranularity.minute: {
+ switch (interval) {
+ case Interval.month:
+ // floors to closest start of month for the date
+ return parseUTCDate(dateString).startOf('month').format('YYYY-MM-DD')
+ case Interval.week:
+ // floors to closest start of week for the date
+ return parseUTCDate(dateString).startOf('week').format('YYYY-MM-DD')
+ case Interval.day:
+ // floors to date
+ return dateString
+ case Interval.hour: {
+ const [dateYYYYMMDD, timeHHMMSS] = annotation.datetime.split('T')
+ // floors time to hour
+ return `${dateYYYYMMDD} ${timeHHMMSS.substring(0, 'HH'.length)}:00:00`
+ }
+ case Interval.minute:
+ return annotation.datetime.split('T').join(' ')
+ }
+ }
+ }
+}
+
+export const groupAnnotationsByTimeLabel = <
+ T extends Pick<Annotation, 'datetime' | 'granularity'>
+>(
+ annotations: T[],
+ interval: Interval
+): Record<string, T[] | undefined> => {
+ return annotations.reduce<Record<string, T[]>>((acc, annotation) => {
+ const timeLabel = getAnnotationTimeLabel(annotation, interval)
+ return { ...acc, [timeLabel]: [...(acc[timeLabel] ?? []), annotation] }
+ }, {})
+}
+
+export const getAnnotationGranularity = (
+ interval: Interval
+): AnnotationGranularity => {
+ switch (interval) {
+ case Interval.minute:
+ case Interval.hour:
+ return AnnotationGranularity.minute
+ case Interval.day:
+ case Interval.week:
+ case Interval.month:
+ return AnnotationGranularity.date
+ }
+}
+
+export const getApiFormattedPayload = ({
+ granularity,
+ datetime,
+ ...payload
+}: AnnotationPayload) => {
+ switch (granularity) {
+ case AnnotationGranularity.date:
+ return { date: datetime, granularity, ...payload }
+ case AnnotationGranularity.minute:
+ return { datetime, granularity, ...payload }
+ }
+}
diff --git a/assets/js/dashboard/annotations/hover-annotations-list.tsx b/assets/js/dashboard/annotations/hover-annotations-list.tsx
new file mode 100644
index 0000000000..2acc232c61
--- /dev/null
+++ b/assets/js/dashboard/annotations/hover-annotations-list.tsx
@@ -0,0 +1,36 @@
+import React from 'react'
+import { Annotation } from './annotations'
+import {
+ AnnotationAuthorshipLine,
+ AnnotationItemRow,
+ AnnotationNote,
+ AnnotationsListContainer
+} from './annotation-list-items'
+
+const MAX_PREVIEW = 2
+
+export const HoverAnnotationsList = ({
+ annotations
+}: {
+ annotations: Annotation[]
+}) => {
+ const preview = annotations.slice(0, MAX_PREVIEW)
+ const extra = annotations.length - MAX_PREVIEW
+
+ return (
+ <>
+ <AnnotationsListContainer>
+ {preview.map((annotation) => (
+ <AnnotationItemRow key={annotation.id}>
+ <div className="relative flex flex-col gap-y-px w-full max-w-64">
+ <AnnotationAuthorshipLine annotation={annotation} />
+ <AnnotationNote note={annotation.note} clamp />
+ </div>
+ </AnnotationItemRow>
+ ))}
+ </AnnotationsListContainer>
+ {extra === 1 && `and 1 more note`}
+ {extra > 1 && `and ${extra} more notes`}
+ </>
+ )
+}
diff --git a/assets/js/dashboard/annotations/interactive-annotations-list.tsx b/assets/js/dashboard/annotations/interactive-annotations-list.tsx
new file mode 100644
index 0000000000..987007df4d
--- /dev/null
+++ b/assets/js/dashboard/annotations/interactive-annotations-list.tsx
@@ -0,0 +1,75 @@
+import React, { ReactNode } from 'react'
+import { Annotation, canEditAnnotation } from './annotations'
+import {
+ AnnotationAuthorshipLine,
+ AnnotationItemRow,
+ AnnotationNote,
+ AnnotationsListContainer
+} from './annotation-list-items'
+import { useRoutelessModalsContext } from '../navigation/routeless-modals-context'
+import { useUserContext } from '../user-context'
+import { PencilIcon } from '../components/icons'
+
+const ScrollableArea = (props: { children: ReactNode }) => (
+ <div className="max-h-25 sm:max-h-40 overflow-y-auto overflow-x-hidden -mr-2.5 pr-2.5 [scrollbar-width:thin] [scrollbar-color:theme(colors.gray.600)_transparent]">
+ {props.children}
+ </div>
+)
+
+export const InteractiveAnnotationsList = ({
+ annotations,
+ isTouchDevice,
+ closeTooltip
+}: {
+ annotations: Annotation[]
+ isTouchDevice: boolean
+ closeTooltip: () => void
+}) => {
+ const { setModal } = useRoutelessModalsContext()
+ const user = useUserContext()
+ const openEdit = (annotation: Annotation) => {
+ closeTooltip()
+ setModal({ type: 'update-annotation', annotation })
+ }
+
+ return (
+ <ScrollableArea>
+ <AnnotationsListContainer>
+ {annotations.map((annotation) => {
+ const editable = canEditAnnotation({ type: annotation.type, user })
+ const content = (
+ <>
+ <AnnotationAuthorshipLine annotation={annotation} />
+ <AnnotationNote note={annotation.note} />
+ {editable && !isTouchDevice && (
+ <button
+ aria-label="Edit note"
+ className="absolute top-px right-0 opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity text-gray-300 hover:text-gray-100 focus:outline-none"
+ onClick={() => openEdit(annotation)}
+ >
+ <PencilIcon className="size-4" />
+ </button>
+ )}
+ </>
+ )
+ return (
+ <AnnotationItemRow key={annotation.id}>
+ {editable && isTouchDevice ? (
+ <button
+ className="relative flex flex-col gap-y-px w-full max-w-64 text-left focus:outline-none"
+ onClick={() => openEdit(annotation)}
+ >
+ {content}
+ </button>
+ ) : (
+ <div className="relative flex flex-col gap-y-px w-full max-w-64">
+ {content}
+ </div>
+ )}
+ </AnnotationItemRow>
+ )
+ })}
+ </AnnotationsListContainer>
+ </ScrollableArea>
+ )
+}
diff --git a/assets/js/dashboard/annotations/routeless-annotations-modals.tsx b/assets/js/dashboard/annotations/routeless-annotations-modals.tsx
new file mode 100644
index 0000000000..ce7aff3a60
--- /dev/null
+++ b/assets/js/dashboard/annotations/routeless-annotations-modals.tsx
@@ -0,0 +1,190 @@
+import React from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useSiteContext } from '../site-context'
+import { useUserContext } from '../user-context'
+import { get, mutation } from '../api'
+import { useRoutelessModalsContext } from '../navigation/routeless-modals-context'
+import {
+ CreateAnnotationModal,
+ DeleteAnnotationModal,
+ UpdateAnnotationModal
+} from './annotations-modals'
+import {
+ Annotation,
+ AnnotationPayload,
+ getApiFormattedPayload
+} from './annotations'
+import { useDashboardStateContext } from '../dashboard-state-context'
+import { createDateRange } from '../stats-query'
+import { formatISO } from '../util/date'
+import { DashboardState } from '../dashboard-state'
+
+export const useGetAnnotations = () => {
+ const site = useSiteContext()
+ const { dashboardState } = useDashboardStateContext()
+ const date_range = createDateRange(dashboardState)
+ const relative_date = dashboardState.date
+ ? formatISO(dashboardState.date)
+ : null
+
+ const dateRangeParams: Record<string, string> = Array.isArray(date_range)
+ ? { date_range_start: date_range[0], date_range_end: date_range[1] }
+ : { date_range }
+
+ const annotationsIndexQuery = useQuery({
+ queryKey: ['annotations', { date_range, relative_date }],
+ queryFn: async () => {
+ const response: Annotation[] = await get(
+ `/api/${encodeURIComponent(site.domain)}/annotations`,
+ // workaround to allow custom params to be defined
+ // without passing the whole dashboard state
+ {} as unknown as DashboardState,
+ {
+ ...dateRangeParams,
+ ...(relative_date ? { relative_date } : {})
+ }
+ )
+ return response
+ }
+ })
+ return annotationsIndexQuery
+}
+
+export type RoutelessAnnotationModal =
+ | {
+ type: 'create-annotation'
+ annotation: Pick<Annotation, 'datetime' | 'granularity' | 'type'>
+ }
+ | { type: 'update-annotation'; annotation: Annotation }
+ | { type: 'delete-annotation'; annotation: Annotation }
+
+export const RoutelessAnnotationModals = () => {
+ const queryClient = useQueryClient()
+ const site = useSiteContext()
+ const { modal, setModal } = useRoutelessModalsContext()
+ const user = useUserContext()
+
+ const patchAnnotation = useMutation({
+ mutationFn: async ({
+ id,
+ note,
+ type
+ }: Pick<Annotation, 'id'> & Partial<Pick<Annotation, 'note' | 'type'>>) => {
+ const response: Annotation = await mutation(
+ `/api/${encodeURIComponent(site.domain)}/annotations/${id}`,
+ {
+ method: 'PATCH',
+ body: {
+ note,
+ type
+ }
+ }
+ )
+
+ return response
+ },
+ onSuccess: async () => {
+ queryClient.invalidateQueries({ queryKey: ['annotations'] })
+ setModal(null)
+ }
+ })
+
+ const createAnnotation = useMutation({
+ mutationFn: async (payload: AnnotationPayload) => {
+ const response: Annotation = await mutation(
+ `/api/${encodeURIComponent(site.domain)}/annotations`,
+ {
+ method: 'POST',
+ body: getApiFormattedPayload(payload)
+ }
+ )
+ return response
+ },
+ onSuccess: async () => {
+ queryClient.invalidateQueries({ queryKey: ['annotations'] })
+ setModal(null)
+ }
+ })
+
+ const deleteAnnotation = useMutation({
+ mutationFn: async (data: Pick<Annotation, 'id'>) => {
+ const response: Annotation = await mutation(
+ `/api/${encodeURIComponent(site.domain)}/annotations/${data.id}`,
+ {
+ method: 'DELETE'
+ }
+ )
+ return response
+ },
+ onSuccess: (): void => {
+ queryClient.invalidateQueries({ queryKey: ['annotations'] })
+ setModal(null)
+ }
+ })
+
+ if (!user.loggedIn) {
+ return null
+ }
+
+ return (
+ <>
+ {modal?.type === 'delete-annotation' && (
+ <DeleteAnnotationModal
+ annotation={modal.annotation}
+ onClose={() => {
+ setModal(null)
+ deleteAnnotation.reset()
+ }}
+ onSave={({ id }) => deleteAnnotation.mutate({ id })}
+ status={deleteAnnotation.status}
+ error={deleteAnnotation.error}
+ reset={deleteAnnotation.reset}
+ />
+ )}
+
+ {modal?.type === 'update-annotation' && (
+ <UpdateAnnotationModal
+ user={user}
+ siteAnnotationsAvailable={site.siteAnnotationsAvailable}
+ annotation={modal.annotation}
+ notePlaceholder={''}
+ onClose={() => {
+ setModal(null)
+ patchAnnotation.reset()
+ }}
+ onSave={({ id, note, type }) =>
+ patchAnnotation.mutate({
+ id,
+ note,
+ type
+ })
+ }
+ onDelete={(annotation) =>
+ setModal({ type: 'delete-annotation', annotation })
+ }
+ status={patchAnnotation.status}
+ error={patchAnnotation.error}
+ reset={patchAnnotation.reset}
+ />
+ )}
+ {modal?.type === 'create-annotation' && (
+ <CreateAnnotationModal
+ user={user}
+ siteAnnotationsAvailable={site.siteAnnotationsAvailable}
+ notePlaceholder={`E.g. 'Campaign started' or 'Feature released'`}
+ initialType={modal.annotation.type}
+ initialDatetime={modal.annotation.datetime}
+ initialGranularity={modal.annotation.granularity}
+ onClose={() => {
+ setModal(null)
+ createAnnotation.reset()
+ }}
+ onSave={(payload) => createAnnotation.mutate(payload)}
+ status={createAnnotation.status}
+ error={createAnnotation.error}
+ reset={createAnnotation.reset}
+ />
+ )}
+ </>
+ )
+}
diff --git a/assets/js/dashboard/components/button.tsx b/assets/js/dashboard/components/button.tsx
index a4d746c69f..56d9fb7add 100644
--- a/assets/js/dashboard/components/button.tsx
+++ b/assets/js/dashboard/components/button.tsx
@@ -4,7 +4,7 @@ import classNames from 'classnames'
/**
* Themes and sizes are kept in sync with the Phoenix `button` component in
* `lib/plausible_web/components/generic.ex`. The actual Tailwind classes live
- * in `assets/css/app.css` (.btn-base, .btn-{sm,md}, .btn-theme-*).
+ * in `assets/css/app.css` (.btn-base, .btn-{xs,sm,md}, .btn-theme-*).
*/
export type ButtonTheme =
@@ -15,11 +15,12 @@ export type ButtonTheme =
| 'ghost'
| 'icon'
-export type ButtonSize = 'sm' | 'md'
+export type ButtonSize = 'xs' | 'sm' | 'md'
const buttonBaseClass = 'btn-base'
const buttonSizes: Record<ButtonSize, string> = {
+ xs: 'btn-xs',
sm: 'btn-sm',
md: 'btn-md'
}
diff --git a/assets/js/dashboard/components/feature-setup-notice.tsx b/assets/js/dashboard/components/feature-setup-notice.tsx
index 7fd9a349a8..fa06308bee 100644
--- a/assets/js/dashboard/components/feature-setup-notice.tsx
+++ b/assets/js/dashboard/components/feature-setup-notice.tsx
@@ -3,19 +3,9 @@ import classNames from 'classnames'
import { MODES } from '../stats/behaviours/modes-context'
import * as api from '../api'
import { useSiteContext } from '../site-context'
-import { Pill } from './pill'
-import { DiamondIcon } from './icons'
+import { UpgradePill } from './pill'
import { buttonClassName } from './button'
-function BusinessPill() {
- return (
- <Pill color="yellow">
- <DiamondIcon className="size-3.5 [&_path]:stroke-2" />
- Business
- </Pill>
- )
-}
-
export function FeatureSetupNotice({
feature,
title,
@@ -121,7 +111,7 @@ export function FeatureSetupNotice({
>
{previewMock && (
<div className="flex justify-center mb-3">
- <BusinessPill />
+ <UpgradePill plan="Business" color="yellow" />
</div>
)}
<div className="text-center mt-2 text-gray-800 dark:text-gray-200 font-medium text-pretty">
diff --git a/assets/js/dashboard/components/form-elements.tsx b/assets/js/dashboard/components/form-elements.tsx
index b916f26750..db1ec30948 100644
--- a/assets/js/dashboard/components/form-elements.tsx
+++ b/assets/js/dashboard/components/form-elements.tsx
@@ -1,36 +1,131 @@
import React, { ReactNode } from 'react'
-import { ExclamationTriangleIcon } from '@heroicons/react/24/outline'
+import classNames from 'classnames'
+import { Tooltip } from '../util/tooltip'
+
+export const getCharacterCount = (value: string): number => [...value].length
+
+export const isOverMaxLength = (value: string, maxLength: number): boolean =>
+ getCharacterCount(value) > maxLength
+
+const fieldClassName =
+ 'block px-3.5 py-2.5 w-full text-sm dark:text-gray-300 rounded-md border border-gray-300 dark:border-gray-750 dark:bg-gray-750 focus:outline-none focus:ring-3 focus:ring-indigo-500/20 dark:focus:ring-indigo-500/25 focus:border-indigo-500'
+
+interface LabeledFieldProps {
+ label: string
+ id: string
+ value: string
+ onChange: (value: string) => void
+ placeholder: string
+ maxLength?: number
+}
+
+const LabeledField = ({
+ label,
+ id,
+ value,
+ maxLength,
+ children
+}: Pick<LabeledFieldProps, 'label' | 'id' | 'value' | 'maxLength'> & {
+ children: ReactNode
+}) => (
+ <div className="flex flex-col">
+ <label
+ htmlFor={id}
+ className="block mb-1.5 text-sm font-medium dark:text-gray-100 text-gray-700 dark:text-gray-300"
+ >
+ {label}
+ </label>
+ {children}
+ {maxLength !== undefined && (
+ <CharacterCounter
+ id={`${id}-counter`}
+ length={getCharacterCount(value)}
+ maxLength={maxLength}
+ />
+ )}
+ </div>
+)
export const LabeledTextInput = ({
label,
id,
value,
onChange,
- placeholder
+ placeholder,
+ maxLength
+}: LabeledFieldProps) => (
+ <LabeledField label={label} id={id} value={value} maxLength={maxLength}>
+ <input
+ autoComplete="off"
+ id={id}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ aria-describedby={maxLength !== undefined ? `${id}-counter` : undefined}
+ className={fieldClassName}
+ />
+ </LabeledField>
+)
+
+export const LabeledTextarea = ({
+ label,
+ id,
+ value,
+ onChange,
+ placeholder,
+ maxLength,
+ rows = 3
+}: LabeledFieldProps & {
+ rows?: number
+}) => (
+ <LabeledField label={label} id={id} value={value} maxLength={maxLength}>
+ <textarea
+ autoComplete="off"
+ id={id}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ rows={rows}
+ aria-describedby={maxLength !== undefined ? `${id}-counter` : undefined}
+ className={classNames(fieldClassName, 'resize-y leading-5')}
+ />
+ </LabeledField>
+)
+
+const CharacterCounter = ({
+ id,
+ length,
+ maxLength
}: {
- label: string
id: string
- value: string
- onChange: (value: string) => void
- placeholder: string
+ length: number
+ maxLength: number
}) => {
+ const closeToLimit = length > maxLength * 0.8
+ const visible = closeToLimit
+ const overLimit = length > maxLength
return (
- <div className="flex flex-col">
- <label
- htmlFor={id}
- className="block mb-1.5 text-sm font-medium dark:text-gray-100 text-gray-700 dark:text-gray-300"
- >
- {label}
- </label>
- <input
- autoComplete="off"
- value={value}
- onChange={(e) => onChange(e.target.value)}
- placeholder={placeholder}
- id={id}
- className="block px-3.5 py-2.5 w-full text-sm dark:text-gray-300 rounded-md border border-gray-300 dark:border-gray-750 dark:bg-gray-750 focus:outline-none focus:ring-3 focus:ring-indigo-500/20 dark:focus:ring-indigo-500/25 focus:border-indigo-500"
- />
- </div>
+ <p
+ id={id}
+ className="mt-1.5 text-xs text-gray-500 dark:text-gray-400"
+ aria-live="polite"
+ >
+ {visible ? (
+ <span>
+ {`Max: ${maxLength} characters. You've used `}
+ <span
+ className={classNames('font-semibold', {
+ 'text-red-500 dark:text-red-400': overLimit
+ })}
+ >
+ {length}
+ </span>
+ </span>
+ ) : (
+ // reserve 1 line worth of room to avoid layout jumps when the count appears
+ <span className="opacity-0 select-none">&nbsp</span>
+ )}
+ </p>
)
}
@@ -42,34 +137,72 @@ export const TypeSelector = <T extends string>({
}: {
value: T
onChange: (value: T) => void
- options: { type: T; name: string; description: string }[]
+ options: {
+ type: T
+ name: string
+ description: string
+ disabled?: boolean
+ pill?: ReactNode
+ tooltipContent?: ReactNode
+ }[]
idPrefix: string
}) => {
return (
<div className="flex flex-col gap-y-2">
- {options.map(({ type, name, description }) => (
- <div key={type}>
- <div className="flex">
- <input
- checked={value === type}
- id={`${idPrefix}-${type}`}
- type="radio"
- value=""
- onChange={() => onChange(type)}
- className="mt-px size-4.5 cursor-pointer text-indigo-600 dark:bg-transparent border-gray-400 dark:border-gray-600 checked:border-indigo-600 dark:checked:border-white"
- />
+ {options.map(
+ ({ type, name, description, disabled, pill, tooltipContent }) => {
+ const row = (
<label
htmlFor={`${idPrefix}-${type}`}
- className="block ml-3 text-sm font-medium dark:text-gray-100 flex flex-col flex-inline"
+ className={classNames(
+ 'flex flex-col text-sm font-medium dark:text-gray-100',
+ disabled && 'cursor-not-allowed'
+ )}
>
- <div>{name}</div>
- <div className="text-gray-500 dark:text-gray-400 text-sm font-normal">
+ <div className="flex items-center gap-x-3">
+ <input
+ checked={value === type}
+ id={`${idPrefix}-${type}`}
+ type="radio"
+ value=""
+ onChange={() => onChange(type)}
+ disabled={disabled}
+ className={classNames(
+ 'size-4.5 text-indigo-600 dark:bg-transparent border-gray-400 dark:border-gray-600 checked:border-indigo-600 dark:checked:border-white',
+ disabled
+ ? 'cursor-not-allowed opacity-50'
+ : 'cursor-pointer'
+ )}
+ />
+ <div className="flex items-center gap-x-2">
+ <span className={classNames(disabled && 'opacity-50')}>
+ {name}
+ </span>
+ {pill}
+ </div>
+ </div>
+ <div
+ className={classNames(
+ 'ml-[1.875rem] text-gray-500 dark:text-gray-400 text-sm font-normal',
+ disabled && 'opacity-50'
+ )}
+ >
{description}
</div>
</label>
- </div>
- </div>
- ))}
+ )
+
+ return (
+ <div key={type}>
+ {tooltipContent ? (
+ <Tooltip info={tooltipContent}>{row}</Tooltip>
+ ) : (
+ row
+ )}
+ </div>
+ )
+ }
+ )}
</div>
)
}
@@ -100,21 +233,6 @@ export const getOptionDisabledMessage = ({
return null
}
-export const TypeDisabledMessage = ({
- message
-}: {
- message: ReactNode | null
-}) => {
- if (!message) return null
-
- return (
- <div className="mt-2 flex gap-x-2 text-sm">
- <ExclamationTriangleIcon className="mt-1 block w-4 h-4 shrink-0" />
- <div>{message}</div>
- </div>
- )
-}
-
/** Keep this component styled the same as checkboxes in PlausibleWeb.Live.Installation.Instructions */
export const Checkbox = ({
id,
diff --git a/assets/js/dashboard/components/graph-tooltip.tsx b/assets/js/dashboard/components/graph-tooltip.tsx
index 94524ac9dc..792098dbfd 100644
--- a/assets/js/dashboard/components/graph-tooltip.tsx
+++ b/assets/js/dashboard/components/graph-tooltip.tsx
@@ -1,19 +1,13 @@
-import React, { ReactNode, useLayoutEffect, useRef, useState } from 'react'
+import React, { ReactNode, RefObject, useLayoutEffect, useState } from 'react'
import {
Transition,
TransitionClasses,
TransitionEvents
} from '@headlessui/react'
-export const GraphTooltipWrapper = ({
- x,
- y,
- maxX,
- minWidth,
- children,
- className,
- transition
-}: {
+type GraphTooltipWrapperProps = {
+ verticalAnchor: 'topEdge' | 'bottomEdge'
+ horizontalAnchor: 'start' | 'middle'
x: number
y: number
maxX: number
@@ -21,21 +15,52 @@ export const GraphTooltipWrapper = ({
children: ReactNode
className?: string
transition?: TransitionClasses & TransitionEvents
-}) => {
- const ref = useRef<HTMLDivElement>(null)
+ wrapperRef: RefObject<HTMLDivElement>
+}
- const xOffset = 12
+export const GraphTooltipWrapper = ({
+ verticalAnchor,
+ horizontalAnchor,
+ x,
+ y,
+ maxX,
+ minWidth,
+ children,
+ className,
+ transition,
+ wrapperRef
+}: GraphTooltipWrapperProps) => {
+ const minX = 0
+ const xOffsetFromStart = 12
const [measuredWidth, setMeasuredWidth] = useState(minWidth)
const leftByAlignment = {
- alignedRight: x + xOffset,
- alignedLeft: x - xOffset - measuredWidth,
- alignedRightClamped: Math.max(0, Math.min(x, maxX - measuredWidth))
- }
+ start: {
+ alignedRight: x + xOffsetFromStart,
+ alignedLeft: x - xOffsetFromStart - measuredWidth,
+ alignedRightClamped: Math.max(0, Math.min(x, maxX - measuredWidth))
+ },
+ middle: {
+ alignedRight: x - measuredWidth / 2,
+ alignedLeft: x - measuredWidth / 2,
+ alignedRightClamped: Math.max(
+ minX,
+ Math.min(x - measuredWidth / 2, maxX - measuredWidth)
+ )
+ }
+ }[horizontalAnchor]
+
+ const canFitRight = {
+ start: leftByAlignment.alignedRight + measuredWidth <= maxX,
+ middle: x - measuredWidth / 2 >= minX && x + measuredWidth / 2 <= maxX
+ }[horizontalAnchor]
+
+ const canFitLeft = {
+ start: leftByAlignment.alignedLeft >= minX,
+ middle: false
+ }[horizontalAnchor]
- const canFitRight = leftByAlignment.alignedRight + measuredWidth <= maxX
- const canFitLeft = leftByAlignment.alignedLeft >= 0
const position = canFitRight
? 'alignedRight'
: canFitLeft
@@ -43,21 +68,29 @@ export const GraphTooltipWrapper = ({
: 'alignedRightClamped'
useLayoutEffect(() => {
- if (!ref.current) {
+ if (!wrapperRef?.current) {
return
}
- setMeasuredWidth(ref.current.offsetWidth)
- }, [children, className, minWidth])
+ const el = wrapperRef.current
+ const w = el.getBoundingClientRect().width
+ setMeasuredWidth(w)
+ }, [x, maxX, minWidth, className, children, wrapperRef])
+
+ const extraStyleByVerticalAnchor = {
+ topEdge: {},
+ bottomEdge: { transform: 'translateY(-100%)' }
+ }
return (
<Transition as={React.Fragment} appear show {...transition}>
<div
- ref={ref}
+ ref={wrapperRef}
className={className}
style={{
minWidth,
left: leftByAlignment[position],
- top: y
+ top: y,
+ ...extraStyleByVerticalAnchor[verticalAnchor]
}}
>
{children}
diff --git a/assets/js/dashboard/components/graph.tsx b/assets/js/dashboard/components/graph.tsx
index 85fa237437..b7c3831cc8 100644
--- a/assets/js/dashboard/components/graph.tsx
+++ b/assets/js/dashboard/components/graph.tsx
@@ -8,6 +8,7 @@ import React, {
import * as d3 from 'd3'
import classNames from 'classnames'
+const ANNOTATION_DIAMOND_SIZE_PX = 3
const IDEAL_Y_TICK_COUNT = 5
const MAX_X_TICK_COUNT = 8
const X_TICK_LENGTH_PX = 4
@@ -35,12 +36,14 @@ type GraphProps<
/** initial guess for left margin, automatically enlarged to fit y tick texts */
defaultMarginLeft: number
data: Datum<T>[]
+ annotationsByIndex: { count: number }[]
yMax: number
onPointerEnter: (event: unknown) => void
onPointerMove: PointerHandler<T>
onPointerLeave: (event: unknown) => void
onGotPointerCapture: (event: unknown) => void
onClick?: PointerHandler<T>
+ onContextMenu?: PointerHandler<T>
yFormat: (domainValue: d3.NumberValue, index: number) => string
/**
* Things are drawn in the order of settings,
@@ -79,6 +82,7 @@ export function Graph<T extends GraphYValues>({
}
const highlightIndicatorGroupId = 'highlight-indicator'
+const annotationsGroupId = 'annotations'
function InnerGraph<T extends GraphYValues>({
className,
@@ -96,10 +100,12 @@ function InnerGraph<T extends GraphYValues>({
onGotPointerCapture,
onPointerEnter,
onClick,
+ onContextMenu,
yFormat,
settings,
gradients,
- highlightedIndex
+ highlightedIndex,
+ annotationsByIndex
}: GraphProps<T>) {
const [extraMarginLeft, setExtraMarginLeft] = useState(0)
const [points, setPoints] = useState<Point<T>[]>([])
@@ -281,6 +287,7 @@ function InnerGraph<T extends GraphYValues>({
series,
x: point.x,
y: point.values[seriesIndex],
+ seriesIndex,
bucketIndex: i
})
points[i] = {
@@ -292,6 +299,8 @@ function InnerGraph<T extends GraphYValues>({
}
}
+ svg.append('g').attr('id', annotationsGroupId)
+
setPoints(points)
// Unhide chart
@@ -468,6 +477,44 @@ function InnerGraph<T extends GraphYValues>({
}
}, [onClick, isInHoverableArea, points])
+ useEffect(() => {
+ const currentSvg = svgRef.current
+ if (currentSvg && points.length) {
+ const svg = d3.select(currentSvg)
+ if (typeof onContextMenu !== 'function') {
+ svg.on('contextmenu', null)
+ } else {
+ svg.on('contextmenu', (event) => {
+ const { xPointer, yPointer } = getPosition(event)
+ const inHoverableArea = isInHoverableArea(xPointer, yPointer)
+ const closestIndexToPointer = inHoverableArea
+ ? getClosestIndexToPointer(xPointer, points)
+ : null
+ onContextMenu({
+ inHoverableArea,
+ closestPoint:
+ closestIndexToPointer !== null
+ ? {
+ index: closestIndexToPointer,
+ x: points[closestIndexToPointer].x,
+ values: points[closestIndexToPointer].values
+ }
+ : null,
+ xPointer,
+ yPointer,
+ event
+ })
+ })
+ }
+ }
+ return () => {
+ if (currentSvg) {
+ const svg = d3.select(currentSvg)
+ svg.on('contextmenu', null)
+ }
+ }
+ }, [onContextMenu, isInHoverableArea, points])
+
useEffect(() => {
points.forEach(({ dots }, index) =>
dots.forEach((g) =>
@@ -504,6 +551,43 @@ function InnerGraph<T extends GraphYValues>({
}
}, [height, highlightedIndex, marginBottom, marginTop, points])
+ useEffect(() => {
+ if (!svgRef.current) {
+ return
+ }
+ const svg = d3.select(svgRef.current)
+ const cleanup = () => {
+ svg.selectAll(`#${annotationsGroupId} g`).remove()
+ }
+ if (!points.length || points.length !== annotationsByIndex.length) {
+ return cleanup()
+ }
+
+ const pointsWithAnnotations = points.map((point, index) => {
+ return { ...point, index, annotations: annotationsByIndex[index] }
+ })
+
+ for (const point of pointsWithAnnotations) {
+ if (point.annotations.count > 0) {
+ svg
+ .select(`#${annotationsGroupId}`)
+ .append('g')
+ .call((g) =>
+ g
+ .append('polygon')
+ .attr(
+ 'points',
+ `${-ANNOTATION_DIAMOND_SIZE_PX},0 0,${ANNOTATION_DIAMOND_SIZE_PX} ${ANNOTATION_DIAMOND_SIZE_PX},0 0,${-ANNOTATION_DIAMOND_SIZE_PX}`
+ )
+ .attr('transform', `translate(${point.x}, ${yBottomEdge})`)
+ .attr('class', annotationDiamondClass)
+ .attr('data-testid', `annotation-marker-on-bucket-${point.index}`)
+ )
+ }
+ }
+ return cleanup
+ }, [points, annotationsByIndex, yBottomEdge])
+
return (
<svg
ref={svgRef}
@@ -519,6 +603,7 @@ const yTickLineClass =
'stroke-gray-150 dark:stroke-gray-800/75 group-first:stroke-gray-300 dark:group-first:stroke-gray-700'
const tickTextClass = 'fill-gray-500 dark:fill-gray-400 text-xs select-none'
const xTickLineClass = 'stroke-gray-300 dark:stroke-gray-700'
+const annotationDiamondClass = 'fill-indigo-500 stroke-indigo-500'
export const getXDomain = (bucketCount: number): [number, number] => {
const xMin = 0
@@ -811,12 +896,14 @@ function drawDot({
series,
x,
y,
+ seriesIndex,
bucketIndex
}: {
svg: SelectedSVG
series: SeriesConfig
x: number
y: number | null
+ seriesIndex: number
bucketIndex: number
}): SelectedGroup {
const group = svg.append('g').attr('class', 'group')
@@ -826,7 +913,10 @@ function drawDot({
.attr('r', 2.5)
.attr('class', series.dot.dotClassName)
.attr('transform', `translate(${x},${y})`)
- .attr('data-testid', `graph-dot-group-${bucketIndex}`)
+ .attr(
+ 'data-testid',
+ `graph-dot-series-${seriesIndex}-bucket-${bucketIndex}`
+ )
}
return group
}
diff --git a/assets/js/dashboard/components/icons.tsx b/assets/js/dashboard/components/icons.tsx
index 0439666850..e9a28e4b8d 100644
--- a/assets/js/dashboard/components/icons.tsx
+++ b/assets/js/dashboard/components/icons.tsx
@@ -79,6 +79,23 @@ export const RefreshIcon = ({ className }: { className?: string }) => (
</svg>
)
+export const PencilIcon = ({ className }: { className?: string }) => (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 18 18"
+ fill="none"
+ className={className}
+ >
+ <path
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ d="m10.547 4.422 3.031 3.031M2.75 15.25s3.599-.568 4.546-1.515l7.327-7.327a2.142 2.142 0 1 0-3.03-3.03l-7.327 7.327c-.947.947-1.515 4.546-1.515 4.546h0Z"
+ />
+ </svg>
+)
+
export const CursorIcon = ({ className }: { className?: string }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
diff --git a/assets/js/dashboard/components/pill.tsx b/assets/js/dashboard/components/pill.tsx
index cb7e726b0a..7d9d173f36 100644
--- a/assets/js/dashboard/components/pill.tsx
+++ b/assets/js/dashboard/components/pill.tsx
@@ -1,12 +1,15 @@
import React, { ReactNode } from 'react'
import classNames from 'classnames'
+import { DiamondIcon } from './icons'
-export type PillColor = 'green' | 'yellow'
+export type PillColor = 'green' | 'yellow' | 'indigo'
const colorClasses: Record<PillColor, string> = {
green: 'bg-green-50 dark:bg-green-900/60 text-green-700 dark:text-green-300',
yellow:
- 'bg-yellow-100 dark:bg-yellow-900/40 text-yellow-600 dark:text-yellow-400'
+ 'bg-yellow-100 dark:bg-yellow-900/40 text-yellow-600 dark:text-yellow-400',
+ indigo:
+ 'bg-indigo-100/60 text-indigo-600 dark:bg-indigo-900/50 dark:text-indigo-300'
}
export type PillProps = {
@@ -19,7 +22,7 @@ export function Pill({ className, color = 'green', children }: PillProps) {
return (
<div
className={classNames(
- 'flex items-center gap-x-1 shrink-0 h-fit rounded-md text-xs font-medium px-2.5 py-1',
+ 'flex items-center gap-x-1 shrink-0 h-fit rounded-md text-xs font-medium px-2 py-1',
colorClasses[color],
className
)}
@@ -28,3 +31,28 @@ export function Pill({ className, color = 'green', children }: PillProps) {
</div>
)
}
+
+export function UpgradePill({
+ plan,
+ color = 'indigo',
+ linked = false
+}: {
+ plan: string
+ color?: PillColor
+ linked?: boolean
+}) {
+ const pill = (
+ <Pill color={color}>
+ <DiamondIcon className="size-3.5 [&_path]:stroke-2" />
+ {plan}
+ </Pill>
+ )
+ if (!linked) {
+ return pill
+ }
+ return (
+ <a href="/billing/choose-plan" className="inline-block">
+ {pill}
+ </a>
+ )
+}
diff --git a/assets/js/dashboard/nav-menu/filters-bar.tsx b/assets/js/dashboard/nav-menu/filters-bar.tsx
index 79bf8c5f0e..7f090282f1 100644
--- a/assets/js/dashboard/nav-menu/filters-bar.tsx
+++ b/assets/js/dashboard/nav-menu/filters-bar.tsx
@@ -359,7 +359,7 @@ const SaveAsSegmentAction = ({ className }: { className?: string }) => {
<AppNavigationLink
className={className}
search={(s) => s}
- onClick={() => setModal('create')}
+ onClick={() => setModal({ type: 'create-segment' })}
state={{ expandedSegment: null }}
>
Save as segment
diff --git a/assets/js/dashboard/nav-menu/segments/segment-menu.tsx b/assets/js/dashboard/nav-menu/segments/segment-menu.tsx
index 9ceed0b911..8d8404c4f7 100644
--- a/assets/js/dashboard/nav-menu/segments/segment-menu.tsx
+++ b/assets/js/dashboard/nav-menu/segments/segment-menu.tsx
@@ -68,7 +68,7 @@ export const SegmentMenu = () => {
search={(s) => s}
state={{ expandedSegment }}
onClick={() => {
- setModal('update')
+ setModal({ type: 'update-segment' })
}}
>
<span className="px-2 whitespace-nowrap">Update segment</span>
@@ -106,7 +106,7 @@ export const SegmentMenu = () => {
state={{ expandedSegment }}
onClick={() => {
closeDropdown()
- setModal('create')
+ setModal({ type: 'create-segment' })
}}
>
<div className="flex items-center gap-x-2">
@@ -122,7 +122,7 @@ export const SegmentMenu = () => {
state={{ expandedSegment }}
onClick={() => {
closeDropdown()
- setModal('delete')
+ setModal({ type: 'delete-segment' })
}}
>
<div className="flex items-center gap-x-2">
diff --git a/assets/js/dashboard/navigation/routeless-modals-context.tsx b/assets/js/dashboard/navigation/routeless-modals-context.tsx
index a88d5a0449..d3a9035793 100644
--- a/assets/js/dashboard/navigation/routeless-modals-context.tsx
+++ b/assets/js/dashboard/navigation/routeless-modals-context.tsx
@@ -1,7 +1,8 @@
import React, { createContext, ReactNode, useContext, useState } from 'react'
import { RoutelessSegmentModal } from '../segments/routeless-segment-modals'
+import { RoutelessAnnotationModal } from '../annotations/routeless-annotations-modals'
-type ActiveModal = null | RoutelessSegmentModal
+type ActiveModal = null | RoutelessSegmentModal | RoutelessAnnotationModal
const routelessModalsContextDefaultValue: {
modal: ActiveModal
diff --git a/assets/js/dashboard/router.tsx b/assets/js/dashboard/router.tsx
index 9b9f71ed6b..54d3a0d598 100644
--- a/assets/js/dashboard/router.tsx
+++ b/assets/js/dashboard/router.tsx
@@ -26,6 +26,7 @@ import { RoutelessModalsContextProvider } from './navigation/routeless-modals-co
import { RoutelessSegmentModals } from './segments/routeless-segment-modals'
import { GOOGLE_SEARCH_TERMS_DETAILS_PATH } from './stats/sources/fetch-search-terms'
import { SourcesDetails } from './stats/sources/details'
+import { RoutelessAnnotationModals } from './annotations/routeless-annotations-modals'
const queryClient = new QueryClient({
defaultOptions: {
@@ -46,6 +47,7 @@ function DashboardElement() {
</LastLoadContextProvider>
<Outlet />
<RoutelessSegmentModals />
+ <RoutelessAnnotationModals />
</DashboardStateContextProvider>
</RoutelessModalsContextProvider>
</QueryClientProvider>
diff --git a/assets/js/dashboard/segments/routeless-segment-modals.tsx b/assets/js/dashboard/segments/routeless-segment-modals.tsx
index 3f8f2dc9a4..f0a6a8d528 100644
--- a/assets/js/dashboard/segments/routeless-segment-modals.tsx
+++ b/assets/js/dashboard/segments/routeless-segment-modals.tsx
@@ -22,7 +22,10 @@ import { mutation } from '../api'
import { useRoutelessModalsContext } from '../navigation/routeless-modals-context'
import { useSegmentsContext } from '../filtering/segments-context'
-export type RoutelessSegmentModal = 'create' | 'update' | 'delete'
+export type RoutelessSegmentModal =
+ | { type: 'create-segment' }
+ | { type: 'update-segment' }
+ | { type: 'delete-segment' }
export const RoutelessSegmentModals = () => {
const { updateOne, addOne, removeOne } = useSegmentsContext()
@@ -153,7 +156,7 @@ export const RoutelessSegmentModals = () => {
return (
<>
- {modal === 'update' && expandedSegment && (
+ {modal?.type === 'update-segment' && expandedSegment && (
<UpdateSegmentModal
user={user}
siteSegmentsAvailable={site.siteSegmentsAvailable}
@@ -179,7 +182,7 @@ export const RoutelessSegmentModals = () => {
reset={patchSegment.reset}
/>
)}
- {modal === 'create' && (
+ {modal?.type === 'create-segment' && (
<CreateSegmentModal
user={user}
siteSegmentsAvailable={site.siteSegmentsAvailable}
@@ -204,7 +207,7 @@ export const RoutelessSegmentModals = () => {
reset={createSegment.reset}
/>
)}
- {modal === 'delete' && expandedSegment && (
+ {modal?.type === 'delete-segment' && expandedSegment && (
<DeleteSegmentModal
segment={expandedSegment}
onClose={() => {
diff --git a/assets/js/dashboard/segments/segment-modals.tsx b/assets/js/dashboard/segments/segment-modals.tsx
index 30e9175dc8..18be91b6e1 100644
--- a/assets/js/dashboard/segments/segment-modals.tsx
+++ b/assets/js/dashboard/segments/segment-modals.tsx
@@ -34,10 +34,10 @@ import {
getOptionDisabledMessage,
LabeledTextInput,
OptionDisabledMessageType,
- TypeDisabledMessage,
TypeSelector
} from '../components/form-elements'
import { Placeholder } from '../components/placeholder'
+import { UpgradePill } from '../components/pill'
const inModalSectionLabelClassName = 'text-sm font-semibold dark:text-gray-100'
@@ -84,13 +84,13 @@ export const CreateSegmentModal = ({
const [type, setType] = useState<SegmentType>(defaultType)
+ const siteOptionDisabledMessage = getSiteSegmentDisabledMessage({
+ siteSegmentsAvailable,
+ user
+ })
+
const disabledMessage =
- type === SegmentType.site
- ? getSiteSegmentDisabledMessage({
- siteSegmentsAvailable,
- user
- })
- : null
+ type === SegmentType.site ? siteOptionDisabledMessage : null
return (
<ModalLayout title="Create segment" onClose={onClose}>
@@ -103,7 +103,7 @@ export const CreateSegmentModal = ({
<SegmentTypeSelector
type={type}
setType={setType}
- optionDisabledMessage={disabledMessage}
+ siteOptionDisabledMessage={siteOptionDisabledMessage}
/>
<ModalFooter>
<Button theme="secondary" size="sm" onClick={onClose}>
@@ -289,38 +289,46 @@ const getSiteSegmentDisabledMessage = ({
const SegmentTypeSelector = ({
type,
setType,
- optionDisabledMessage
+ siteOptionDisabledMessage
}: {
type: SegmentType
setType: (type: SegmentType) => void
- optionDisabledMessage: OptionDisabledMessageType | null
+ siteOptionDisabledMessage: OptionDisabledMessageType | null
}) => (
- <>
- <TypeSelector<SegmentType>
- idPrefix="segment-type"
- options={[
- {
- type: SegmentType.personal,
- name: SEGMENT_TYPE_LABELS[SegmentType.personal],
- description: 'Visible only to you'
- },
- {
- type: SegmentType.site,
- name: SEGMENT_TYPE_LABELS[SegmentType.site],
- description: 'Visible to others on the site'
- }
- ]}
- value={type}
- onChange={setType}
- />
- {optionDisabledMessage !== null && (
- <TypeDisabledMessage
- message={
- <SegmentTypeDisabledMessage messageType={optionDisabledMessage} />
- }
- />
- )}
- </>
+ <TypeSelector<SegmentType>
+ idPrefix="segment-type"
+ options={[
+ {
+ type: SegmentType.personal,
+ name: SEGMENT_TYPE_LABELS[SegmentType.personal],
+ description: 'Visible only to you'
+ },
+ {
+ type: SegmentType.site,
+ name: SEGMENT_TYPE_LABELS[SegmentType.site],
+ description: 'Visible to others on the site',
+ disabled: siteOptionDisabledMessage !== null,
+ pill:
+ siteOptionDisabledMessage === 'upgrade-subscription-yourself' ||
+ siteOptionDisabledMessage === 'upgrade-subscription-reach-out' ? (
+ <UpgradePill
+ plan="Growth"
+ linked={
+ siteOptionDisabledMessage === 'upgrade-subscription-yourself'
+ }
+ />
+ ) : null,
+ tooltipContent:
+ siteOptionDisabledMessage !== null ? (
+ <SegmentTypeDisabledMessage
+ messageType={siteOptionDisabledMessage}
+ />
+ ) : null
+ }
+ ]}
+ value={type}
+ onChange={setType}
+ />
)
const SegmentTypeDisabledMessage = ({
@@ -333,22 +341,10 @@ const SegmentTypeDisabledMessage = ({
return "You don't have enough permissions to change segment to this type"
}
case 'upgrade-subscription-yourself': {
- return (
- <>
- To use this segment type,{' '}
- <a href="/billing/choose-plan" className="underline">
- please upgrade your subscription
- </a>
- </>
- )
+ return 'Upgrade to Growth to share segments with others.'
}
case 'upgrade-subscription-reach-out': {
- return (
- <>
- To use this segment type, please reach out to a team owner to upgrade
- their subscription
- </>
- )
+ return 'Ask a team owner to upgrade to Growth to share segments with others.'
}
}
}
@@ -371,13 +367,13 @@ export const UpdateSegmentModal = ({
const [name, setName] = useState(segment.name)
const [type, setType] = useState<SegmentType>(segment.type)
+ const siteOptionDisabledMessage = getSiteSegmentDisabledMessage({
+ siteSegmentsAvailable,
+ user
+ })
+
const disabledMessage =
- type === SegmentType.site
- ? getSiteSegmentDisabledMessage({
- siteSegmentsAvailable,
- user
- })
- : null
+ type === SegmentType.site ? siteOptionDisabledMessage : null
return (
<ModalLayout title="Update segment" onClose={onClose}>
@@ -390,7 +386,7 @@ export const UpdateSegmentModal = ({
<SegmentTypeSelector
type={type}
setType={setType}
- optionDisabledMessage={disabledMessage}
+ siteOptionDisabledMessage={siteOptionDisabledMessage}
/>
<ModalFooter>
<Button theme="secondary" size="sm" onClick={onClose}>
diff --git a/assets/js/dashboard/site-context.test.tsx b/assets/js/dashboard/site-context.test.tsx
index 13ddfea577..44f67dc1ff 100644
--- a/assets/js/dashboard/site-context.test.tsx
+++ b/assets/js/dashboard/site-context.test.tsx
@@ -19,6 +19,7 @@ describe('parseSiteFromDataset', () => {
data-exploration-journey-end-event="__journey_end__"
data-exploration-max-journey-steps="20"
data-site-segments-available="true"
+ data-site-annotations-available="true"
data-props-available="true"
data-revenue-goals='[{"currency":"USD","display_name":"Purchase"}]'
data-funnels='[{"id":1,"name":"From homepage to login","steps_count":3}]'
@@ -50,6 +51,7 @@ describe('parseSiteFromDataset', () => {
explorationJourneyEndEvent: '__journey_end__',
explorationMaxJourneySteps: 20,
siteSegmentsAvailable: true,
+ siteAnnotationsAvailable: true,
revenueGoals: [{ currency: 'USD', display_name: 'Purchase' }],
funnels: [{ id: 1, name: 'From homepage to login', steps_count: 3 }],
hasProps: true,
diff --git a/assets/js/dashboard/site-context.tsx b/assets/js/dashboard/site-context.tsx
index a7ea4d3fc8..c812686a0a 100644
--- a/assets/js/dashboard/site-context.tsx
+++ b/assets/js/dashboard/site-context.tsx
@@ -15,6 +15,7 @@ export function parseSiteFromDataset(dataset: DOMStringMap): PlausibleSite {
10
),
siteSegmentsAvailable: dataset.siteSegmentsAvailable === 'true',
+ siteAnnotationsAvailable: dataset.siteAnnotationsAvailable === 'true',
conversionsOptedOut: dataset.conversionsOptedOut === 'true',
funnelsOptedOut: dataset.funnelsOptedOut === 'true',
propsOptedOut: dataset.propsOptedOut === 'true',
@@ -46,6 +47,7 @@ export const siteContextDefaultValue = {
explorationMaxJourneySteps: 0,
propsAvailable: false,
siteSegmentsAvailable: false,
+ siteAnnotationsAvailable: false,
conversionsOptedOut: false,
funnelsOptedOut: false,
propsOptedOut: false,
diff --git a/assets/js/dashboard/stats/graph/main-graph.tsx b/assets/js/dashboard/stats/graph/main-graph.tsx
index 185716925a..bf8708ca32 100644
--- a/assets/js/dashboard/stats/graph/main-graph.tsx
+++ b/assets/js/dashboard/stats/graph/main-graph.tsx
@@ -1,5 +1,6 @@
import React, {
ReactNode,
+ RefObject,
useCallback,
useEffect,
useMemo,
@@ -38,8 +39,19 @@ import {
MainGraphSeriesName
} from './main-graph-data'
import { Metric, getMetricLabel } from '../metrics'
-
import { extractIntervalFromDimensions, Interval } from './intervals'
+import { useRoutelessModalsContext } from '../../navigation/routeless-modals-context'
+import {
+ Annotation,
+ AnnotationType,
+ canShowAddAnnotationButton,
+ getAnnotationGranularity,
+ groupAnnotationsByTimeLabel
+} from '../../annotations/annotations'
+import { useUserContext } from '../../user-context'
+import { Button } from '../../components/button'
+import { HoverAnnotationsList } from '../../annotations/hover-annotations-list'
+import { InteractiveAnnotationsList } from '../../annotations/interactive-annotations-list'
const height = 368
const marginTop = 16
@@ -63,6 +75,7 @@ type TooltipState = {
selectedIndex: number | null
persistent: boolean
}
+
const initialTooltipState: TooltipState = {
x: 0,
selectedIndex: null,
@@ -71,31 +84,70 @@ const initialTooltipState: TooltipState = {
export const MainGraph = ({
width,
- data
+ data,
+ annotations
}: {
width: number
data: MainGraphResponse
+ annotations: Annotation[]
}) => {
const site = useSiteContext()
+ const user = useUserContext()
const { mode } = useTheme()
const navigate = useAppNavigate()
const { primaryGradient, secondaryGradient } = paletteByTheme[mode]
const [isTouchDevice, setIsTouchDevice] = useState<null | boolean>(null)
const [tooltip, setTooltip] = useState<TooltipState>(initialTooltipState)
+ const canAddAnnotation = canShowAddAnnotationButton({
+ user,
+ siteAnnotationsAvailable: site.siteAnnotationsAvailable
+ })
+
+ const closeTooltip = useCallback(() => {
+ setTooltip(initialTooltipState)
+ }, [])
+
+ useEffect(() => {
+ setTooltip(initialTooltipState)
+ }, [width])
+
+ const tooltipRef = useRef<HTMLDivElement>(null)
const { selectedIndex } = tooltip
const panGestureStartTimeRef = useRef<number | null>(null)
const metric = data.query.metrics[0] as Metric
const interval = extractIntervalFromDimensions(data.query.dimensions)
const isRealtime = data.extraContext.isRealtime
+ const annotationsByTimeLabel = useMemo(
+ () => groupAnnotationsByTimeLabel(annotations, interval),
+ [annotations, interval]
+ )
+
useEffect(() => {
setTooltip(initialTooltipState)
}, [data])
useEffect(() => {
- const onPointerCancel = (e: PointerEvent) => {
- if (e.pointerType === 'touch') {
+ const onClickOutside = (event: MouseEvent) => {
+ if (!tooltipRef.current?.contains(event.target as Node)) {
+ setTooltip(initialTooltipState)
+ }
+ }
+ if (tooltip.persistent && isTouchDevice === false) {
+ document.addEventListener('click', onClickOutside)
+ }
+ return () => {
+ document.removeEventListener('click', onClickOutside)
+ }
+ }, [tooltip.persistent, isTouchDevice])
+
+ useEffect(() => {
+ const onPointerCancel = (event: PointerEvent) => {
+ if (event.pointerType === 'touch') {
panGestureStartTimeRef.current = null
+ if (tooltipRef.current?.contains(event.target as Node)) {
+ return
+ }
setTooltip(initialTooltipState)
}
}
@@ -248,6 +300,19 @@ export const MainGraph = ({
metric
])
+ const annotationsByIndex = useMemo(
+ () =>
+ remappedData.map((datum) => {
+ const annotationsOnDatum = datum.main.isDefined
+ ? (annotationsByTimeLabel[datum.main.timeLabel] ?? [])
+ : []
+ return {
+ count: annotationsOnDatum.length
+ }
+ }),
+ [remappedData, annotationsByTimeLabel]
+ )
+
const getFormattedValue = useCallback(
(value: MetricValue) => MetricFormatterShort[metric](value),
[metric]
@@ -264,7 +329,7 @@ export const MainGraph = ({
setIsTouchDevice(true)
if (tooltip.persistent && inHoverableArea && closestPoint) {
const now = Date.now()
- // move the tooltip only when it is certain it's a y-pan
+ // move the tooltip only when it is certain it's not a y-pan
if (panGestureStartTimeRef.current === null) {
panGestureStartTimeRef.current = now
} else if (
@@ -281,26 +346,32 @@ export const MainGraph = ({
return
}
setIsTouchDevice(false)
- if (!inHoverableArea || !closestPoint) {
- return setTooltip(initialTooltipState)
- }
- return setTooltip({
- selectedIndex: closestPoint.index,
- x: closestPoint.x,
- persistent: false
+ setTooltip((currentState): TooltipState => {
+ const currentlyPersistent = currentState.persistent
+ if (currentlyPersistent) {
+ return currentState
+ }
+ if (!inHoverableArea || !closestPoint) {
+ return initialTooltipState
+ }
+ return {
+ persistent: false,
+ selectedIndex: closestPoint.index,
+ x: closestPoint.x
+ }
})
},
[tooltip.persistent]
)
const onGotPointerCapture = useCallback((event: unknown) => {
- if (event instanceof PointerEvent && event.pointerType === 'touch') {
+ if (isTouchEvent(event)) {
return setIsTouchDevice(true)
}
}, [])
const onPointerEnter = useCallback((event: unknown) => {
- if (event instanceof PointerEvent && event.pointerType === 'touch') {
+ if (isTouchEvent(event)) {
return setIsTouchDevice(true)
}
}, [])
@@ -325,6 +396,11 @@ export const MainGraph = ({
? selectedDatum.main.timeLabel
: null
+ const annotationDatetime =
+ selectedDatum && selectedDatum.main.isDefined
+ ? selectedDatum.main.timeLabel
+ : null
+
const zoomToPeriod = useCallback(
(date: string) => {
setTooltip(initialTooltipState)
@@ -342,9 +418,16 @@ export const MainGraph = ({
[navigate, interval]
)
- const onClick = useCallback<PointerHandler<MainGraphYValues>>(
- ({ inHoverableArea, closestPoint }) => {
- if (isTouchDevice) {
+ const onChartClick = useCallback<PointerHandler<MainGraphYValues>>(
+ ({ inHoverableArea, closestPoint, event }) => {
+ // the first tap / click can happen when
+ // isTouchDevice isn't determined yet
+ // (no preceding pointerenter, gotpointercapture, pointermove)
+ const shouldHandleAsTouch = isTouchDevice ?? isTouchEvent(event)
+ if (isTouchDevice === null) {
+ setIsTouchDevice(shouldHandleAsTouch)
+ }
+ if (shouldHandleAsTouch) {
if (inHoverableArea && closestPoint) {
return setTooltip({
selectedIndex: closestPoint.index,
@@ -354,19 +437,33 @@ export const MainGraph = ({
}
return setTooltip(initialTooltipState)
}
+
+ if (tooltip.persistent) {
+ return
+ }
if (typeof zoomDate === 'string') {
return zoomToPeriod(zoomDate)
}
},
- [zoomDate, zoomToPeriod, isTouchDevice]
+ [isTouchDevice, zoomDate, zoomToPeriod, tooltip.persistent]
+ )
+
+ const onContextMenu = useCallback<PointerHandler<MainGraphYValues>>(
+ ({ event }) => {
+ if (selectedDatum) {
+ ;(event as Event).preventDefault()
+ return setTooltip((current) => ({ ...current, persistent: true }))
+ }
+ },
+ [selectedDatum]
)
return (
<Graph<MainGraphYValues>
- className={classNames(
- showZoomToPeriod && selectedDatum ? 'cursor-pointer' : '',
- tooltip.persistent ? 'touch-pan-y' : ''
- )}
+ className={classNames({
+ 'cursor-pointer': selectedDatum && showZoomToPeriod,
+ 'touch-pan-y': tooltip.persistent
+ })}
highlightedIndex={selectedIndex}
width={width}
height={height}
@@ -382,9 +479,11 @@ export const MainGraph = ({
onGotPointerCapture={onGotPointerCapture}
onPointerMove={onPointerMove}
onPointerLeave={onPointerLeave}
- onClick={onClick}
+ onClick={onChartClick}
+ onContextMenu={onContextMenu}
yFormat={yFormat}
gradients={gradients}
+ annotationsByIndex={annotationsByIndex}
>
{!!selectedDatum && isTouchDevice !== null && (
<MainGraphTooltip
@@ -398,41 +497,149 @@ export const MainGraph = ({
interval={interval}
metric={metric}
x={tooltip.x}
- // aligned to top of graph
- y={0}
datum={selectedDatum}
bucketIndex={selectedIndex}
totalBuckets={remappedData.length}
persistent={tooltip.persistent}
- onClick={
- tooltip.persistent && typeof zoomDate === 'string'
- ? () => zoomToPeriod(zoomDate)
- : undefined
- }
- />
+ tooltipRef={tooltipRef}
+ isTouchDevice={isTouchDevice}
+ >
+ {tooltip.persistent ? (
+ <PersistentTooltipContents
+ annotationDatetime={annotationDatetime}
+ annotations={
+ annotationDatetime
+ ? annotationsByTimeLabel[annotationDatetime]
+ : undefined
+ }
+ isTouchDevice={isTouchDevice}
+ interval={interval}
+ zoomDate={zoomDate}
+ onZoomToPeriod={zoomToPeriod}
+ canAddAnnotation={canAddAnnotation}
+ closeTooltip={closeTooltip}
+ />
+ ) : (
+ <HoveredTooltipContents
+ annotations={
+ annotationDatetime
+ ? annotationsByTimeLabel[annotationDatetime]
+ : undefined
+ }
+ interval={interval}
+ zoomDate={zoomDate}
+ canAddAnnotation={canAddAnnotation}
+ />
+ )}
+ </MainGraphTooltip>
)}
</Graph>
)
}
-const MainGraphTooltip = ({
- metric,
- getFormattedValue,
+type TooltipContentsProps = {
+ annotations: Annotation[] | undefined
+ interval: Interval
+ zoomDate: string | null
+ canAddAnnotation: boolean
+}
+
+const PersistentTooltipContents = ({
+ annotationDatetime,
+ annotations,
+ isTouchDevice,
interval,
- isRealtime,
- hasConversionGoalFilter,
- shouldShowDate,
- shouldShowYear,
- maxX,
- x,
- y,
- datum,
- showZoomToPeriod,
- bucketIndex,
- totalBuckets,
- persistent,
- onClick
+ zoomDate,
+ onZoomToPeriod,
+ canAddAnnotation,
+ closeTooltip
}: {
+ annotationDatetime: string | null
+ isTouchDevice: boolean
+ onZoomToPeriod: (date: string) => void
+ closeTooltip: () => void
+} & TooltipContentsProps) => {
+ const { setModal } = useRoutelessModalsContext()
+
+ const hasActions = !!zoomDate || (!!annotationDatetime && canAddAnnotation)
+ return (
+ <>
+ {!!annotations?.length && (
+ <InteractiveAnnotationsList
+ annotations={annotations}
+ isTouchDevice={isTouchDevice}
+ closeTooltip={closeTooltip}
+ />
+ )}
+ {hasActions && (
+ <div className="flex flex-row gap-x-2 mt-2">
+ {!!annotationDatetime && canAddAnnotation && (
+ <Button
+ size="xs"
+ className="flex-auto bg-gray-600/70 border-gray-600/70 border-transparent hover:bg-gray-600"
+ onClick={() => {
+ closeTooltip()
+ setModal({
+ type: 'create-annotation',
+ annotation: {
+ type: AnnotationType.personal,
+ datetime: annotationDatetime,
+ granularity: getAnnotationGranularity(interval)
+ }
+ })
+ }}
+ >
+ Add note
+ </Button>
+ )}
+ {!!zoomDate && (
+ <Button
+ size="xs"
+ className="flex-auto bg-gray-600/70 border-gray-600/70 border-transparent hover:bg-gray-600"
+ onClick={() => onZoomToPeriod(zoomDate)}
+ >{`View ${interval}`}</Button>
+ )}
+ </div>
+ )}
+ </>
+ )
+}
+
+const HoveredTooltipContents = ({
+ annotations,
+ interval,
+ zoomDate,
+ canAddAnnotation
+}: TooltipContentsProps) => {
+ return (
+ <>
+ {!!annotations?.length && (
+ <HoverAnnotationsList annotations={annotations} />
+ )}
+ <hr className="border-gray-600 dark:border-gray-800 my-1" />
+ <div className="flex flex-col gap-y-0.5">
+ {!!zoomDate && (
+ <div className="text-gray-300 dark:text-gray-400 text-xs">
+ {`Click to view ${interval}`}
+ </div>
+ )}
+ <div className="text-gray-300 dark:text-gray-400 text-xs">
+ {canAddAnnotation
+ ? 'Right click for more actions'
+ : 'Right click to pin tooltip'}
+ </div>
+ </div>
+ </>
+ )
+}
+
+const isTouchEvent = (event: unknown) =>
+ event instanceof PointerEvent && event.pointerType === 'touch'
+
+const mainGraphTooltipClassName =
+ 'absolute bg-gray-800 dark:bg-gray-950 py-3 px-4 rounded-md shadow shadow-gray-200 dark:shadow-gray-850 w-max max-w-[220px] sm:max-w-[300px]'
+
+type MainGraphTooltipProps = {
metric: Metric
getFormattedValue: (value: MetricValue) => string
interval: Interval
@@ -441,7 +648,6 @@ const MainGraphTooltip = ({
shouldShowYear: boolean
shouldShowDate: boolean
x: number
- y: number
datum: GraphDatum
showZoomToPeriod?: boolean
bucketIndex: number
@@ -449,23 +655,50 @@ const MainGraphTooltip = ({
maxX: number
persistent: boolean
onClick?: () => void
-}) => {
- const metricLabel = getMetricLabel(metric, { hasConversionGoalFilter })
+ children?: ReactNode
+ tooltipRef: RefObject<HTMLDivElement>
+ isTouchDevice: boolean
+}
+
+const MainGraphTooltip = ({
+ metric,
+ getFormattedValue,
+ interval,
+ hasConversionGoalFilter,
+ isRealtime,
+ shouldShowDate,
+ shouldShowYear,
+ maxX,
+ x,
+ datum,
+ bucketIndex,
+ totalBuckets,
+ persistent,
+ children,
+ tooltipRef,
+ isTouchDevice
+}: MainGraphTooltipProps) => {
+ const metricLabel = getMetricLabel(metric, {
+ hasConversionGoalFilter
+ })
const { main, comparison, change } = datum
return (
<GraphTooltipWrapper
+ wrapperRef={tooltipRef}
+ horizontalAnchor="start"
+ verticalAnchor="topEdge"
x={x}
- y={y}
+ y={0}
minWidth={200}
maxX={maxX}
- className={classNames(
- 'absolute select-none bg-gray-800 dark:bg-gray-950 py-3 px-4 rounded-md shadow shadow-gray-200 dark:shadow-gray-850',
- typeof onClick !== 'function' && 'pointer-events-none'
- )}
+ className={classNames(mainGraphTooltipClassName, {
+ 'select-none': !persistent || isTouchDevice,
+ 'pointer-events-none': !persistent
+ })}
>
<aside
+ className="text-sm font-normal text-gray-100 flex flex-col gap-2"
data-testid="graph-tooltip"
- className="text-sm font-normal text-gray-100 flex flex-col gap-1.5"
>
<div className="flex justify-between items-center rounded-sm">
<div
@@ -537,23 +770,7 @@ const MainGraphTooltip = ({
</div>
)}
</div>
-
- {!!showZoomToPeriod && (
- <>
- <hr className="border-gray-600 dark:border-gray-800 my-1" />
- {!persistent && (
- <span className="text-gray-300 dark:text-gray-400 text-xs">
- {`Click to view ${interval}`}
- </span>
- )}
- {persistent && (
- <button
- className="button"
- onClick={onClick}
- >{`View ${interval}`}</button>
- )}
- </>
- )}
+ {children}
</aside>
</GraphTooltipWrapper>
)
diff --git a/assets/js/dashboard/stats/graph/visitor-graph.tsx b/assets/js/dashboard/stats/graph/visitor-graph.tsx
index da6957ce1f..e16a9d955e 100644
--- a/assets/js/dashboard/stats/graph/visitor-graph.tsx
+++ b/assets/js/dashboard/stats/graph/visitor-graph.tsx
@@ -8,6 +8,7 @@ import { Metric } from '../metrics'
import { MainGraph, MainGraphContainer, useMainGraphWidth } from './main-graph'
import { useGraphIntervalContext } from './graph-interval-context'
import { useSetImportsIncluded } from './imports-included-context'
+import { useGetAnnotations } from '../../annotations/routeless-annotations-modals'
// height of at least one row of top stats
const DEFAULT_TOP_STATS_LOADING_HEIGHT_PX = 85
@@ -22,6 +23,7 @@ export default function VisitorGraph({
const mainGraphContainer = useRef<HTMLDivElement>(null)
const { width } = useMainGraphWidth(mainGraphContainer)
const site = useSiteContext()
+ const getAnnotationsQuery = useGetAnnotations()
const { selectedInterval } = useGraphIntervalContext()
@@ -139,7 +141,11 @@ export default function VisitorGraph({
{!!mainGraphApiState.data && !!width && (
<>
{!showGraphLoader && (
- <MainGraph width={width} data={mainGraphApiState.data} />
+ <MainGraph
+ width={width}
+ data={mainGraphApiState.data}
+ annotations={getAnnotationsQuery.data ?? []}
+ />
)}
{showGraphLoader && <Loader />}
</>
diff --git a/assets/js/dashboard/util/date.js b/assets/js/dashboard/util/date.js
index 474c862bbf..30bde2ea52 100644
--- a/assets/js/dashboard/util/date.js
+++ b/assets/js/dashboard/util/date.js
@@ -1,7 +1,17 @@
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
+import updateLocale from 'dayjs/plugin/updateLocale'
dayjs.extend(utc)
+dayjs.extend(updateLocale)
+// The locale 'en' is the default (and the only one currently),
+// but its start of week is Sunday.
+// This change that the week starts on Monday unifies behavior
+// between start of week according to the backend
+// and start of week according to the frontend.
+dayjs.updateLocale('en', {
+ weekStart: 1
+})
const browserDateFormat = Intl.DateTimeFormat(navigator.language, {
hour: 'numeric'
diff --git a/assets/js/dashboard/util/date.test.ts b/assets/js/dashboard/util/date.test.ts
index 95698ea702..e0e185161b 100644
--- a/assets/js/dashboard/util/date.test.ts
+++ b/assets/js/dashboard/util/date.test.ts
@@ -5,6 +5,7 @@ import {
formatISO,
now,
parseNaiveDate,
+ parseUTCDate,
shiftMonths,
yesterday
} from './date'
@@ -110,6 +111,12 @@ for (const [timezone, suite] of sets) {
})
}
+it('startOf("week") returns a Monday', () => {
+ expect(formatISO(parseUTCDate('2026-07-02').startOf('week'))).toEqual(
+ '2026-06-29' // Monday
+ )
+})
+
describe('formatting site-timezoned datetimes from database works flawlessly', () => {
it('is able to enrich UTC date string with site timezone, formatting the value correctly', () => {
expect(formatDayShort(parseNaiveDate('2025-01-01 14:00:00'))).toEqual(
diff --git a/assets/test-utils/app-context-providers.tsx b/assets/test-utils/app-context-providers.tsx
index e0fcd5588b..062aac19f3 100644
--- a/assets/test-utils/app-context-providers.tsx
+++ b/assets/test-utils/app-context-providers.tsx
@@ -37,6 +37,7 @@ export const DEFAULT_SITE: PlausibleSite = {
explorationMaxJourneySteps: 0,
propsAvailable: false,
siteSegmentsAvailable: false,
+ siteAnnotationsAvailable: false,
conversionsOptedOut: false,
funnelsOptedOut: false,
propsOptedOut: false,
diff --git a/e2e/tests/dashboard/annotations.spec.ts b/e2e/tests/dashboard/annotations.spec.ts
new file mode 100644
index 0000000000..aa15273f25
--- /dev/null
+++ b/e2e/tests/dashboard/annotations.spec.ts
@@ -0,0 +1,265 @@
+import { test, expect } from '@playwright/test'
+import { setupSite, populateStats, register } from '../fixtures'
+import { randomID } from '../test-utils'
+
+test.use({ locale: 'en-GB' })
+
+test('user can create annotations across granularities, edit, and delete them', async ({
+ page,
+ request
+}) => {
+ const user = {
+ email: `site-owner-for-annotations-${randomID()}@example.com`,
+ // name matters in this test
+ name: 'J R.R. Smith',
+ password: 'VeryStrongVerySecret'
+ }
+ await register({
+ page,
+ request,
+ user
+ })
+ const { domain } = await setupSite({ page, request, user })
+
+ await populateStats({
+ request,
+ domain,
+ events: [
+ {
+ user_id: 0,
+ name: 'pageview',
+ pathname: '/',
+ timestamp: '2026-04-01 00:00:00'
+ },
+ {
+ user_id: 1,
+ name: 'pageview',
+ pathname: '/',
+ timestamp: '2026-06-29 05:00:00'
+ },
+ {
+ user_id: 2,
+ name: 'pageview',
+ pathname: '/',
+ timestamp: '2026-06-29 10:00:00'
+ }
+ ]
+ })
+
+ await page.goto(`/${domain}?period=7d&date=2026-07-06&comparison=off`, {
+ waitUntil: 'commit'
+ })
+
+ const mondayIn7d = page.getByTestId('graph-dot-series-1-bucket-0')
+ const mondayMarker7d = page.getByTestId('annotation-marker-on-bucket-0')
+
+ const tooltip = page.getByTestId('graph-tooltip')
+
+ // inputs in create / edit modals
+ const noteField = page.getByRole('textbox', { name: 'Note' })
+ const saveButton = page.getByRole('button', { name: 'Save' })
+
+ const siteNoteText = 'Company-wide: launch day'
+ const personalNoteText = 'Feature available for 50% of customers'
+ const updatedNoteText = 'Feature fully released (correction)'
+
+ const personalNoteAttribution = 'Personal note • 29 Jun 10:00'
+ const siteNoteAttribution = `${user.name} • 29 Jun`
+
+ // Asserts the tooltip's annotation list matches provided list exactly
+ const expectTooltipAnnotations = async (
+ expected: Array<{ note: string; attribution: string }>
+ ) => {
+ const rows = tooltip.locator('div.group')
+ await expect(rows).toHaveCount(expected.length)
+ for (const [i, { note, attribution }] of expected.entries()) {
+ const row = rows.nth(i)
+ await expect(row).toContainText(note)
+ await expect(row.getByText(attribution, { exact: true })).toBeVisible()
+ }
+ }
+
+ // Needed because the tests expect a particular graph interval
+ const setGraphInterval = async (label: 'Hours' | 'Days' | 'Months') => {
+ await page.getByTestId('dashboard-options-menu').click()
+ await page.getByRole('button', { name: label, exact: true }).click()
+ await page.keyboard.press('Escape')
+ }
+
+ await test.step('in 7d view, create date-granularity site annotation on Monday', async () => {
+ await setGraphInterval('Days')
+
+ // hovered tooltip
+ await mondayIn7d.hover()
+ await expect(tooltip).toBeVisible()
+ await expectTooltipAnnotations([])
+
+ await expect(tooltip).toContainText('Click to view day')
+ await expect(tooltip).toContainText('Right click for more actions')
+
+ // persisted tooltip
+ await mondayIn7d.click({ button: 'right' })
+ await expect(tooltip).toBeVisible()
+
+ await expect(tooltip.locator('button')).toContainText([
+ 'Add note',
+ 'View day'
+ ])
+ await tooltip.getByRole('button', { name: 'Add note' }).click()
+
+ const createModalHeading = page.getByRole('heading', {
+ name: 'Add note for Mon, 29 Jun',
+ exact: true
+ })
+ await expect(createModalHeading).toBeVisible()
+
+ await noteField.fill(siteNoteText)
+ await page.getByRole('radio', { name: /Site note/ }).check()
+ await saveButton.click()
+
+ await expect(createModalHeading).toBeHidden()
+ await expect(mondayMarker7d).toBeVisible()
+ })
+
+ await test.step('right-click Monday and zoom in via "View day"', async () => {
+ await mondayIn7d.hover()
+ await expectTooltipAnnotations([
+ { note: siteNoteText, attribution: siteNoteAttribution }
+ ])
+
+ await mondayIn7d.click({ button: 'right' })
+
+ await tooltip.getByRole('button', { name: 'View day' }).click()
+ await expect(page).toHaveURL(/period=day&date=2026-06-29/)
+
+ // Date-granularity annotations don't map to hour buckets — no marker in day view.
+ await expect(page.getByTestId(/^annotation-marker-on-bucket-/)).toHaveCount(
+ 0
+ )
+ })
+
+ await test.step('in day view, create minute-granularity personal annotation at 10:00', async () => {
+ await setGraphInterval('Hours')
+
+ const hour10InDay = page.getByTestId('graph-dot-series-1-bucket-10')
+ await hour10InDay.hover()
+ await hour10InDay.click({ button: 'right' })
+ await expect(tooltip).toBeVisible()
+
+ await tooltip.getByRole('button', { name: 'Add note' }).click()
+
+ const createModalHeading = page.getByRole('heading', {
+ name: 'Add note for Mon, 29 Jun at 10:00',
+ exact: true
+ })
+ await expect(createModalHeading).toBeVisible()
+ await expect(tooltip).toBeHidden()
+
+ await noteField.fill(personalNoteText)
+ await saveButton.click()
+
+ await expect(createModalHeading).toBeHidden()
+ await expect(
+ page.getByTestId('annotation-marker-on-bucket-10')
+ ).toBeVisible()
+ })
+
+ await test.step('zoom back out to 7d, both annotations are visible on Monday', async () => {
+ await page.goBack({ waitUntil: 'commit' })
+ await setGraphInterval('Days')
+
+ await expect(mondayMarker7d).toBeVisible()
+
+ const expectedOnMonday = [
+ { note: siteNoteText, attribution: siteNoteAttribution },
+ { note: personalNoteText, attribution: personalNoteAttribution }
+ ]
+
+ await mondayIn7d.hover()
+ await expect(tooltip).toBeVisible()
+ await expectTooltipAnnotations(expectedOnMonday)
+
+ await mondayIn7d.click({ button: 'right' })
+ await expect(tooltip).toBeVisible()
+ await expectTooltipAnnotations(expectedOnMonday)
+ })
+
+ await test.step('edit personal annotation', async () => {
+ const personalRow = tooltip.locator('div.group', {
+ hasText: personalNoteText
+ })
+ await personalRow.hover()
+ await personalRow.getByRole('button', { name: 'Edit note' }).click()
+
+ const updateModalHeading = page.getByRole('heading', {
+ name: 'Update note for Mon, 29 Jun at 10:00',
+ exact: true
+ })
+ await expect(updateModalHeading).toBeVisible()
+ await expect(tooltip).toBeHidden()
+ await expect(noteField).toHaveValue(personalNoteText)
+
+ await noteField.fill(updatedNoteText)
+ await saveButton.click()
+
+ await expect(updateModalHeading).toBeHidden()
+
+ await mondayIn7d.hover()
+ await mondayIn7d.click({ button: 'right' })
+ await expectTooltipAnnotations([
+ { note: siteNoteText, attribution: siteNoteAttribution },
+ { note: updatedNoteText, attribution: personalNoteAttribution }
+ ])
+ })
+
+ await test.step('delete personal annotation', async () => {
+ const personalNote = tooltip.locator('div.group', {
+ hasText: updatedNoteText
+ })
+ await personalNote.hover()
+ await personalNote.getByRole('button', { name: 'Edit note' }).click()
+
+ const updateModalHeading = page.getByRole('heading', {
+ name: 'Update note for Mon, 29 Jun at 10:00',
+ exact: true
+ })
+ await expect(updateModalHeading).toBeVisible()
+
+ await page.getByRole('button', { name: 'Delete note' }).click()
+
+ const deleteModalHeading = page.getByRole('heading', {
+ name: `Delete personal note "${updatedNoteText}"?`,
+ exact: true
+ })
+ await expect(deleteModalHeading).toBeVisible()
+ await expect(updateModalHeading).toBeHidden()
+
+ await page.getByRole('button', { name: 'Delete', exact: true }).click()
+
+ await expect(deleteModalHeading).toBeHidden()
+ await mondayIn7d.hover()
+ await expectTooltipAnnotations([
+ { note: siteNoteText, attribution: siteNoteAttribution }
+ ])
+ await expect(mondayMarker7d).toBeVisible()
+ })
+
+ await test.step('date annotations are shown for All period', async () => {
+ await page.getByTestId('current-query-period').click()
+ await page
+ .getByTestId('query-period-picker')
+ .getByRole('link', { name: 'All time' })
+ .click()
+ await expect(page).toHaveURL(/period=all/)
+
+ const marker = page.getByTestId(/^annotation-marker-on-bucket-/)
+ await expect(marker).toHaveCount(1)
+ await expect(marker).toBeVisible()
+
+ await setGraphInterval('Months')
+ await page.getByText('June 2026', { exact: true }).hover()
+ await expectTooltipAnnotations([
+ { note: siteNoteText, attribution: siteNoteAttribution }
+ ])
+ })
+})
diff --git a/e2e/tests/dashboard/main-graph.spec.ts b/e2e/tests/dashboard/main-graph.spec.ts
index 06888b002c..2910961a3e 100644
--- a/e2e/tests/dashboard/main-graph.spec.ts
+++ b/e2e/tests/dashboard/main-graph.spec.ts
@@ -15,20 +15,13 @@ type BucketExpectation = [
const MAIN_LINE = 'path.stroke-indigo-500[data-testid="graph-line"]'
async function hoverAndReadTooltip(page: Page, bucketIndex: number) {
- await page
- .locator(`[data-testid="graph-dot-group-${bucketIndex}"]`)
- .first()
- .hover()
- const tooltip = page.locator('[data-testid="graph-tooltip"]')
+ await page.getByTestId(`graph-dot-series-1-bucket-${bucketIndex}`).hover()
+ const tooltip = page.getByTestId('graph-tooltip')
await expect(tooltip).toBeVisible()
return {
- metricLabel: await tooltip
- .locator('[data-testid="metric-label"]')
- .innerText(),
- mainTimeLabel: await tooltip
- .locator('[data-testid="main-time-label"]')
- .innerText(),
- mainValue: await tooltip.locator('[data-testid="main-value"]').innerText()
+ metricLabel: await tooltip.getByTestId('metric-label').innerText(),
+ mainTimeLabel: await tooltip.getByTestId('main-time-label').innerText(),
+ mainValue: await tooltip.getByTestId('main-value').innerText()
}
}
diff --git a/lib/plausible/annotations/annotations.ex b/lib/plausible/annotations/annotations.ex
index 64d38b0387..625587cdb9 100644
--- a/lib/plausible/annotations/annotations.ex
+++ b/lib/plausible/annotations/annotations.ex
@@ -43,7 +43,7 @@ defmodule Plausible.Annotations do
select: ^fields,
where: annotation.site_id == ^site.id,
where: annotation.type == :site,
- order_by: [desc: annotation.updated_at, desc: annotation.id],
+ order_by: [asc: annotation.datetime, desc: annotation.id],
preload: [site: site]
)
|> filter_by_range(range_in_site_tz)
@@ -65,7 +65,7 @@ defmodule Plausible.Annotations do
where:
annotation.type == :site or
(annotation.type == :personal and annotation.owner_id == ^user.id),
- order_by: [desc: annotation.updated_at, desc: annotation.id],
+ order_by: [asc: annotation.datetime, desc: annotation.id],
preload: [site: site, owner: owner]
)
|> filter_by_range(range_in_site_tz)
@@ -297,6 +297,7 @@ defmodule Plausible.Annotations do
defp can_update_one?(site, site_role, new_annotation_type, existing_annotation_type) do
updating_to_site_annotation? = new_annotation_type == :site
+ updating_to_personal_annotation? = new_annotation_type == :personal
cond do
(existing_annotation_type == :site or
@@ -304,7 +305,14 @@ defmodule Plausible.Annotations do
site_annotations_available?(site) ->
:ok
- existing_annotation_type == :personal and not updating_to_site_annotation? and
+ # Allow demoting a site annotation to personal even when
+ # site_annotations is no longer available on the plan — gives users a
+ # way to keep their annotations usable after a downgrade.
+ existing_annotation_type == :site and updating_to_personal_annotation? and
+ site_role in roles_with_maybe_site_annotations() ->
+ :ok
+
+ existing_annotation_type == :personal and updating_to_personal_annotation? and
site_role in roles_with_personal_annotations() ->
:ok
diff --git a/lib/plausible/billing/feature.ex b/lib/plausible/billing/feature.ex
index 5c455b2922..1ce71268aa 100644
--- a/lib/plausible/billing/feature.ex
+++ b/lib/plausible/billing/feature.ex
@@ -72,6 +72,7 @@ defmodule Plausible.Billing.Feature do
Plausible.Billing.Feature.Goals,
Plausible.Billing.Feature.RevenueGoals,
Plausible.Billing.Feature.SiteSegments,
+ Plausible.Billing.Feature.SiteAnnotations,
Plausible.Billing.Feature.SitesAPI,
Plausible.Billing.Feature.StatsAPI,
Plausible.Billing.Feature.SSO,
@@ -211,6 +212,13 @@ defmodule Plausible.Billing.Feature.SiteSegments do
display_name: "Shared Segments"
end
+defmodule Plausible.Billing.Feature.SiteAnnotations do
+ @moduledoc false
+ use Plausible.Billing.Feature,
+ name: :site_annotations,
+ display_name: "Shared Annotations"
+end
+
defmodule Plausible.Billing.Feature.StatsAPI do
use Plausible
diff --git a/lib/plausible/billing/plan_benefits.ex b/lib/plausible/billing/plan_benefits.ex
index 9817e2e101..9ea43ecb89 100644
--- a/lib/plausible/billing/plan_benefits.ex
+++ b/lib/plausible/billing/plan_benefits.ex
@@ -16,7 +16,7 @@ defmodule Plausible.Billing.PlanBenefits do
"Google Analytics import"
]
|> Kernel.++(feature_benefits(starter_plan))
- |> Kernel.++(["Saved Segments"])
+ |> Kernel.++(benefits_available_on_lowest_plan())
end
@doc """
@@ -27,13 +27,15 @@ defmodule Plausible.Billing.PlanBenefits do
and Growth. Everything in Starter is also included in Growth.
"""
def for_growth(growth_plan, starter_benefits) do
- [
- if(Enum.empty?(starter_benefits), do: nil, else: "Everything in Starter"),
+ lowest_plan? = Enum.empty?(starter_benefits)
+
+ if(not lowest_plan?, do: ["Everything in Starter"], else: [])
+ |> Kernel.++([
site_limit_benefit(growth_plan),
team_member_limit_benefit(growth_plan),
- "Team Management",
- if(Enum.empty?(starter_benefits), do: "Saved Segments", else: nil)
- ]
+ "Team Management"
+ ])
+ |> Kernel.++(if(lowest_plan?, do: benefits_available_on_lowest_plan(), else: []))
|> Kernel.++(feature_benefits(growth_plan))
|> Kernel.--(starter_benefits)
|> Enum.filter(& &1)
@@ -105,6 +107,10 @@ defmodule Plausible.Billing.PlanBenefits do
|> Enum.filter(& &1)
end
+ defp benefits_available_on_lowest_plan do
+ ["Saved Segments", "Annotations"]
+ end
+
defp data_retention_benefit(%Plan{} = plan) do
if plan.data_retention_in_years, do: "#{plan.data_retention_in_years} years of data retention"
end
diff --git a/lib/plausible/teams/billing.ex b/lib/plausible/teams/billing.ex
index 0e815f0d7d..2074403fde 100644
--- a/lib/plausible/teams/billing.ex
+++ b/lib/plausible/teams/billing.ex
@@ -606,12 +606,17 @@ defmodule Plausible.Teams.Billing do
site_segments_usage_q =
from s in Plausible.Segments.Segment, where: s.site_id in ^site_ids and s.type == :site
+ site_annotations_usage_q =
+ from a in Plausible.Annotations.Annotation,
+ where: a.site_id in ^site_ids and a.type == :site
+
[
{Feature.SharedLinks, shared_links_usage_q},
{Feature.Props, props_usage_q},
{Feature.Funnels, funnels_usage_q},
{Feature.RevenueGoals, revenue_goals_usage_q},
- {Feature.SiteSegments, site_segments_usage_q}
+ {Feature.SiteSegments, site_segments_usage_q},
+ {Feature.SiteAnnotations, site_annotations_usage_q}
]
|> Enum.reduce([], fn {feature, query}, acc ->
if Repo.exists?(query), do: acc ++ [feature], else: acc
diff --git a/lib/plausible_web/components/generic.ex b/lib/plausible_web/components/generic.ex
index 7485c47ca0..f02bfdf080 100644
--- a/lib/plausible_web/components/generic.ex
+++ b/lib/plausible_web/components/generic.ex
@@ -6,6 +6,8 @@ defmodule PlausibleWeb.Components.Generic do
import PlausibleWeb.Components.Icons
+ alias PlausibleWeb.Router.Helpers, as: Routes
+
@notice_themes %{
gray: %{
bg: "bg-gray-100 dark:bg-gray-800",
@@ -1304,7 +1306,7 @@ defmodule PlausibleWeb.Components.Generic do
~H"""
<span
class={[
- "inline-flex items-center text-xs font-medium py-[3px] px-[7px] rounded-md",
+ "inline-flex items-center text-xs font-medium py-1 px-2 rounded-md",
@color_classes,
@class
]}
@@ -1315,6 +1317,25 @@ defmodule PlausibleWeb.Components.Generic do
"""
end
+ attr(:plan, :string, required: true)
+ attr(:color, :atom, default: :indigo, values: [:gray, :indigo, :yellow, :green, :red])
+ attr(:rest, :global)
+
+ def upgrade_pill(assigns) do
+ ~H"""
+ <.link
+ href={Routes.billing_path(PlausibleWeb.Endpoint, :choose_plan)}
+ class="inline-block"
+ {@rest}
+ >
+ <.pill color={@color} class="gap-x-1">
+ <.diamond_icon class="size-3.5 [&_path]:stroke-2" />
+ {@plan}
+ </.pill>
+ </.link>
+ """
+ end
+
defp get_pill_color_classes(:gray) do
"bg-gray-100 text-gray-800 dark:bg-gray-750 dark:text-gray-200"
end
diff --git a/lib/plausible_web/components/icons.ex b/lib/plausible_web/components/icons.ex
index 2ce11f0581..51bca1baaf 100644
--- a/lib/plausible_web/components/icons.ex
+++ b/lib/plausible_web/components/icons.ex
@@ -65,6 +65,22 @@ defmodule PlausibleWeb.Components.Icons do
attr :class, :any, default: []
+ def diamond_icon(assigns) do
+ ~H"""
+ <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class={@class}>
+ <path
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1.5"
+ d="M2.734 9h18.531M3.023 8.164l3.205-3.408c.255-.27.61-.424.984-.424h9.57c.374 0 .73.153.985.424l3.205 3.408c.44.468.48 1.18.093 1.693l-7.99 10.608a1.352 1.352 0 0 1-2.155 0L2.93 9.857a1.31 1.31 0 0 1 .093-1.693"
+ />
+ </svg>
+ """
+ end
+
+ attr :class, :any, default: []
+
def subscription_icon(assigns) do
~H"""
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class={@class}>
diff --git a/lib/plausible_web/controllers/api/internal/annotations_controller.ex b/lib/plausible_web/controllers/api/internal/annotations_controller.ex
index bbd1dac6fd..e161589252 100644
--- a/lib/plausible_web/controllers/api/internal/annotations_controller.ex
+++ b/lib/plausible_web/controllers/api/internal/annotations_controller.ex
@@ -10,10 +10,8 @@ defmodule PlausibleWeb.Api.Internal.AnnotationsController do
alias Plausible.Stats.{ApiQueryParser, QueryPeriod}
alias PlausibleWeb.Api.Helpers, as: H
- plug(PlausibleWeb.Plugs.FeatureFlagCheckPlug, [:annotations])
-
def index(conn, params) do
- user = conn.assigns.current_user
+ user = conn.assigns[:current_user]
site = conn.assigns.site
site_role = conn.assigns.site_role
@@ -69,7 +67,7 @@ defmodule PlausibleWeb.Api.Internal.AnnotationsController do
defp parse_relative_date(_), do: {:ok, nil}
def create(conn, params) do
- user = conn.assigns.current_user
+ user = conn.assigns[:current_user]
site = conn.assigns.site
site_role = conn.assigns.site_role
@@ -93,7 +91,7 @@ defmodule PlausibleWeb.Api.Internal.AnnotationsController do
end
def update(conn, params) do
- user = conn.assigns.current_user
+ user = conn.assigns[:current_user]
site = conn.assigns.site
site_role = conn.assigns.site_role
annotation_id = normalize_annotation_id_param(params["annotation_id"])
@@ -118,7 +116,7 @@ defmodule PlausibleWeb.Api.Internal.AnnotationsController do
end
def delete(conn, params) do
- user = conn.assigns.current_user
+ user = conn.assigns[:current_user]
site = conn.assigns.site
site_role = conn.assigns.site_role
annotation_id = normalize_annotation_id_param(params["annotation_id"])
diff --git a/lib/plausible_web/live/goal_settings/form.ex b/lib/plausible_web/live/goal_settings/form.ex
index 3d521537df..ead9c153b9 100644
--- a/lib/plausible_web/live/goal_settings/form.ex
+++ b/lib/plausible_web/live/goal_settings/form.ex
@@ -531,15 +531,10 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
<span class="text-sm/6 font-medium text-gray-900 dark:text-gray-100">
{if @use_custom_props, do: "Custom properties", else: "Add custom property"}
</span>
- <.link
+ <.upgrade_pill
:if={not @has_access_to_props? and not @use_custom_props}
- href={Routes.billing_path(PlausibleWeb.Endpoint, :choose_plan)}
- class="inline-block"
- >
- <.pill color={:indigo}>
- Business
- </.pill>
- </.link>
+ plan="Business"
+ />
</div>
<.tooltip enabled?={not @has_access_to_props?} centered?={true}>
<:tooltip_content>
@@ -720,15 +715,7 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
<span class="text-sm/6 font-medium text-gray-900 dark:text-gray-100">
Enable revenue tracking
</span>
- <.link
- :if={not @has_access_to_revenue_goals?}
- href={Routes.billing_path(PlausibleWeb.Endpoint, :choose_plan)}
- class="inline-block"
- >
- <.pill color={:indigo}>
- Business
- </.pill>
- </.link>
+ <.upgrade_pill :if={not @has_access_to_revenue_goals?} plan="Business" />
</div>
<.tooltip enabled?={not @has_access_to_revenue_goals?} centered?={true}>
<:tooltip_content>
diff --git a/lib/plausible_web/plugins/api/schemas/capabilities.ex b/lib/plausible_web/plugins/api/schemas/capabilities.ex
index f98daee979..76a9a0aba5 100644
--- a/lib/plausible_web/plugins/api/schemas/capabilities.ex
+++ b/lib/plausible_web/plugins/api/schemas/capabilities.ex
@@ -35,6 +35,7 @@ defmodule PlausibleWeb.Plugins.API.Schemas.Capabilities do
StatsAPI: false,
SitesAPI: false,
SiteSegments: false,
+ SiteAnnotations: false,
Teams: false,
SharedLinks: false,
SSO: false,
diff --git a/priv/plans_v3.json b/priv/plans_v3.json
index 37aa5f0d42..0d4310a3f9 100644
--- a/priv/plans_v3.json
+++ b/priv/plans_v3.json
@@ -134,6 +134,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
]
@@ -153,6 +154,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
]
@@ -172,6 +174,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
]
@@ -191,6 +194,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
]
@@ -210,6 +214,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
]
@@ -229,6 +234,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
]
@@ -248,6 +254,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
]
@@ -267,6 +274,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
]
diff --git a/priv/plans_v4.json b/priv/plans_v4.json
index de39f7ac36..29ed585e95 100644
--- a/priv/plans_v4.json
+++ b/priv/plans_v4.json
@@ -126,6 +126,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
],
@@ -146,6 +147,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
],
@@ -166,6 +168,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
],
@@ -186,6 +189,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
],
@@ -206,6 +210,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
],
@@ -226,6 +231,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
],
@@ -246,6 +252,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
],
@@ -266,6 +273,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links",
"consolidated_view"
],
diff --git a/priv/plans_v5.json b/priv/plans_v5.json
index 69c3641a23..ede05fec99 100644
--- a/priv/plans_v5.json
+++ b/priv/plans_v5.json
@@ -114,7 +114,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -129,7 +130,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -144,7 +146,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -159,7 +162,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -174,7 +178,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -189,7 +194,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -204,7 +210,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -219,7 +226,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -235,6 +243,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -255,6 +264,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -275,6 +285,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -295,6 +306,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -315,6 +327,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -335,6 +348,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -355,6 +369,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -375,6 +390,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
diff --git a/priv/sandbox_plans_v3.json b/priv/sandbox_plans_v3.json
index 295e159cb0..bf031da630 100644
--- a/priv/sandbox_plans_v3.json
+++ b/priv/sandbox_plans_v3.json
@@ -134,6 +134,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
]
},
@@ -152,6 +153,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
]
},
@@ -170,6 +172,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
]
},
@@ -188,6 +191,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
]
},
@@ -206,6 +210,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
]
},
@@ -224,6 +229,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
]
},
@@ -242,6 +248,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
]
},
@@ -260,6 +267,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
]
}
diff --git a/priv/sandbox_plans_v4.json b/priv/sandbox_plans_v4.json
index 4d82acb7f2..c2e48f53c9 100644
--- a/priv/sandbox_plans_v4.json
+++ b/priv/sandbox_plans_v4.json
@@ -126,6 +126,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
],
"data_retention_in_years": 5
@@ -145,6 +146,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
],
"data_retention_in_years": 5
@@ -164,6 +166,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
],
"data_retention_in_years": 5
@@ -183,6 +186,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
],
"data_retention_in_years": 5
@@ -202,6 +206,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
],
"data_retention_in_years": 5
@@ -221,6 +226,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
],
"data_retention_in_years": 5
@@ -240,6 +246,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
],
"data_retention_in_years": 5
@@ -259,6 +266,7 @@
"funnels",
"stats_api",
"site_segments",
+ "site_annotations",
"shared_links"
],
"data_retention_in_years": 5
diff --git a/priv/sandbox_plans_v5.json b/priv/sandbox_plans_v5.json
index d3d104cc80..a54bbeda0c 100644
--- a/priv/sandbox_plans_v5.json
+++ b/priv/sandbox_plans_v5.json
@@ -114,7 +114,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -129,7 +130,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -144,7 +146,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -159,7 +162,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -174,7 +178,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -189,7 +194,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -204,7 +210,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -219,7 +226,8 @@
"features": [
"goals",
"shared_links",
- "site_segments"
+ "site_segments",
+ "site_annotations"
],
"data_retention_in_years": 3
},
@@ -235,6 +243,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -254,6 +263,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -273,6 +283,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -292,6 +303,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -311,6 +323,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -330,6 +343,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -349,6 +363,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
@@ -368,6 +383,7 @@
"goals",
"shared_links",
"site_segments",
+ "site_annotations",
"props",
"stats_api",
"revenue_goals",
diff --git a/test/plausible/billing/feature_test.exs b/test/plausible/billing/feature_test.exs
index c74e0e4cfa..859fb29f67 100644
--- a/test/plausible/billing/feature_test.exs
+++ b/test/plausible/billing/feature_test.exs
@@ -4,6 +4,7 @@ defmodule Plausible.Billing.FeatureTest do
alias Plausible.Billing.Feature.{
Goals,
SiteSegments,
+ SiteAnnotations,
SharedLinks,
Funnels,
RevenueGoals,
@@ -100,7 +101,7 @@ defmodule Plausible.Billing.FeatureTest do
end
describe "growth features" do
- for mod <- [SharedLinks, SiteSegments] do
+ for mod <- [SharedLinks, SiteSegments, SiteAnnotations] do
test "#{mod}.check_availability/1 returns :ok when site owner is on a enterprise plan that supports #{mod}" do
team =
new_user()
diff --git a/test/plausible/billing/plan_benefits_test.exs b/test/plausible/billing/plan_benefits_test.exs
index 917737ea02..258548760c 100644
--- a/test/plausible/billing/plan_benefits_test.exs
+++ b/test/plausible/billing/plan_benefits_test.exs
@@ -12,7 +12,8 @@ defmodule Plausible.Billing.PlanBenefitsTest do
"Email/Slack reports",
"Google Analytics import",
"Goals and custom events",
- "Saved Segments"
+ "Saved Segments",
+ "Annotations"
]
end
end
@@ -28,7 +29,8 @@ defmodule Plausible.Billing.PlanBenefitsTest do
"Team Management",
"Shared Links",
"Embedded Dashboards",
- "Shared Segments"
+ "Shared Segments",
+ "Shared Annotations"
]
end
@@ -54,6 +56,7 @@ defmodule Plausible.Billing.PlanBenefitsTest do
"Unlimited team members",
"Team Management",
"Saved Segments",
+ "Annotations",
"Goals and custom events",
"Custom Properties",
"Stats API (600 requests per hour)",
@@ -101,6 +104,7 @@ defmodule Plausible.Billing.PlanBenefitsTest do
"Stats API (600 requests per hour)",
"Looker Studio Connector",
"Shared Segments",
+ "Shared Annotations",
"Consolidated View"
]
end
@@ -123,6 +127,7 @@ defmodule Plausible.Billing.PlanBenefitsTest do
"Ecommerce revenue attribution",
"Funnels and user journeys",
"Shared Segments",
+ "Shared Annotations",
"Consolidated View"
]
end
diff --git a/test/plausible_web/controllers/api/internal_controller/annotations_controller_test.exs b/test/plausible_web/controllers/api/internal_controller/annotations_controller_test.exs
index 4821624af3..0f383668d4 100644
--- a/test/plausible_web/controllers/api/internal_controller/annotations_controller_test.exs
+++ b/test/plausible_web/controllers/api/internal_controller/annotations_controller_test.exs
@@ -61,58 +61,74 @@ defmodule PlausibleWeb.Api.Internal.AnnotationsControllerTest do
] = json_response(conn, 200)
end
- test "personal annotations of the user and all site annotations are shown with annotation owner info when viewing their site, sorted by updated_at, ascending",
+ test "personal annotations of the user and all site annotations are shown with annotation owner info when viewing their site, ordered by datetime ascending then id descending",
%{conn: conn, user: user} do
site = new_site()
other_user = new_user()
add_guest(site, user: user, role: :viewer)
+ insert(:annotation,
+ site: site,
+ owner: other_user,
+ type: :site,
+ note: "site note from other user",
+ granularity: :date,
+ datetime: ~U[2026-06-29 00:00:00Z],
+ updated_at: ~U[2026-07-01 12:00:00Z]
+ )
+
insert(:annotation,
site: site,
owner: user,
- type: :personal,
- note: "mine",
- inserted_at: ~U[2026-07-01 10:00:00Z],
- updated_at: ~U[2026-07-01 10:00:00Z]
+ type: :site,
+ note: "site note from this user",
+ granularity: :date,
+ datetime: ~U[2026-06-29 00:00:00Z],
+ updated_at: ~U[2026-07-01 12:00:00Z]
)
insert(:annotation,
site: site,
- owner: other_user,
- type: :personal,
- note: "not mine",
- inserted_at: ~U[2026-07-01 10:00:00Z],
- updated_at: ~U[2026-07-01 11:00:00Z]
+ owner: nil,
+ type: :site,
+ note: "site note without owner",
+ granularity: :date,
+ datetime: ~U[2026-06-01 00:00:00Z]
)
insert(:annotation,
site: site,
owner: other_user,
- type: :site,
- note: "shared",
- inserted_at: ~U[2026-07-01 10:00:00Z],
- updated_at: ~U[2026-07-01 12:00:00Z]
+ type: :personal,
+ note: "other user's personal note",
+ granularity: :date,
+ datetime: ~U[2026-06-29 00:00:00Z]
)
insert(:annotation,
site: site,
- owner: nil,
- type: :site,
- note: "dangling",
- inserted_at: ~U[2026-07-01 10:00:00Z],
- updated_at: ~U[2026-07-01 13:00:00Z]
+ owner: user,
+ type: :personal,
+ note: "my note",
+ granularity: :minute,
+ datetime: ~U[2026-06-29 00:01:00Z],
+ updated_at: ~U[2026-07-01 10:00:00Z]
)
- conn = get(conn, "/api/#{site.domain}/annotations?date_range=day&relative_date=2026-01-04")
+ conn =
+ get(
+ conn,
+ "/api/#{site.domain}/annotations?date_range_start=2026-06-01&date_range_end=2026-06-30"
+ )
results = json_response(conn, 200)
assert_matches [
^strict_map(%{
"id" => ^any(:pos_integer),
- "note" => "dangling",
+ "note" => "site note without owner",
"type" => "site",
- "datetime" => "2026-01-04",
+ "datetime" => "2026-06-01",
"granularity" => "date",
"owner_id" => nil,
"owner_name" => nil,
@@ -121,9 +137,20 @@ defmodule PlausibleWeb.Api.Internal.AnnotationsControllerTest do
}),
^strict_map(%{
"id" => ^any(:pos_integer),
- "note" => "shared",
+ "note" => "site note from this user",
"type" => "site",
- "datetime" => "2026-01-04",
+ "datetime" => "2026-06-29",
+ "granularity" => "date",
+ "owner_id" => ^user.id,
+ "owner_name" => ^user.name,
+ "inserted_at" => ^any(:iso8601_naive_datetime),
+ "updated_at" => ^any(:iso8601_naive_datetime)
+ }),
+ ^strict_map(%{
+ "id" => ^any(:pos_integer),
+ "note" => "site note from other user",
+ "type" => "site",
+ "datetime" => "2026-06-29",
"granularity" => "date",
"owner_id" => ^other_user.id,
"owner_name" => ^other_user.name,
@@ -132,10 +159,10 @@ defmodule PlausibleWeb.Api.Internal.AnnotationsControllerTest do
}),
^strict_map(%{
"id" => ^any(:pos_integer),
- "note" => "mine",
+ "note" => "my note",
"type" => "personal",
- "datetime" => "2026-01-04",
- "granularity" => "date",
+ "datetime" => "2026-06-29T00:01:00",
+ "granularity" => "minute",
"owner_id" => ^user.id,
"owner_name" => ^user.name,
"inserted_at" => ^any(:iso8601_naive_datetime),
@@ -723,5 +750,35 @@ defmodule PlausibleWeb.Api.Internal.AnnotationsControllerTest do
}) = response
end
end
+
+ test "owner on a plan without site_annotations can demote a site annotation to personal",
+ %{conn: conn, user: user} do
+ subscribe_to_starter_plan(user)
+ site = new_site(owner: user)
+ refute Plausible.Annotations.site_annotations_available?(site)
+
+ annotation =
+ insert(:annotation,
+ site: site,
+ owner: user,
+ type: :site,
+ granularity: :date,
+ datetime: ~U[2026-06-15 00:00:00Z]
+ )
+
+ response =
+ patch(conn, "/api/#{site.domain}/annotations/#{annotation.id}", %{
+ "type" => "personal",
+ "note" => "converted after downgrade"
+ })
+ |> json_response(200)
+
+ assert response["type"] == "personal"
+ assert response["note"] == "converted after downgrade"
+
+ reloaded = Plausible.Repo.get!(Plausible.Annotations.Annotation, annotation.id)
+ assert reloaded.type == :personal
+ assert reloaded.note == "converted after downgrade"
+ end
end
end
diff --git a/test/plausible_web/live/choose_plan_test.exs b/test/plausible_web/live/choose_plan_test.exs
index 762d6fc8b4..098e276269 100644
--- a/test/plausible_web/live/choose_plan_test.exs
+++ b/test/plausible_web/live/choose_plan_test.exs
@@ -1163,6 +1163,7 @@ defmodule PlausibleWeb.Live.ChoosePlanTest do
assert growth_box =~ "Unlimited team members"
assert growth_box =~ "Team Management"
assert growth_box =~ "Saved Segments"
+ assert growth_box =~ "Annotations"
assert growth_box =~ "Goals and custom events"
assert growth_box =~ "Custom Properties"
assert growth_box =~ "Stats API (600 requests per hour)"
diff --git a/test/plausible_web/live/customer_support/teams_test.exs b/test/plausible_web/live/customer_support/teams_test.exs
index 196979266e..2ffe3743f7 100644
--- a/test/plausible_web/live/customer_support/teams_test.exs
+++ b/test/plausible_web/live/customer_support/teams_test.exs
@@ -431,6 +431,7 @@ defmodule PlausibleWeb.Live.CustomerSupport.TeamsTest do
"shared_segments" => "false",
"revenue_goals" => "false",
"site_segments" => "false",
+ "site_annotations" => "false",
"shared_links" => "true",
"sites_api" => "true"
}
@@ -464,6 +465,7 @@ defmodule PlausibleWeb.Live.CustomerSupport.TeamsTest do
"shared_segments" => "false",
"revenue_goals" => "false",
"site_segments" => "false",
+ "site_annotations" => "false",
"shared_links" => "true",
"sites_api" => "true",
"sso" => "false",
@@ -658,6 +660,7 @@ defmodule PlausibleWeb.Live.CustomerSupport.TeamsTest do
"props" => "false",
"revenue_goals" => "false",
"site_segments" => "false",
+ "site_annotations" => "false",
"shared_links" => "false",
"sites_api" => "false",
"sso" => "false"
diff --git a/test/plausible_web/plugins/api/controllers/capabilities_test.exs b/test/plausible_web/plugins/api/controllers/capabilities_test.exs
index de8b5077bd..75faa09a59 100644
--- a/test/plausible_web/plugins/api/controllers/capabilities_test.exs
+++ b/test/plausible_web/plugins/api/controllers/capabilities_test.exs
@@ -31,6 +31,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.CapabilitiesTest do
"StatsAPI" => false,
"SitesAPI" => false,
"SiteSegments" => false,
+ "SiteAnnotations" => false,
"SharedLinks" => false,
"SSO" => false,
"ConsolidatedView" => false
@@ -60,6 +61,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.CapabilitiesTest do
"StatsAPI" => false,
"SitesAPI" => false,
"SiteSegments" => false,
+ "SiteAnnotations" => false,
"SharedLinks" => false,
"SSO" => false,
"ConsolidatedView" => false
@@ -91,6 +93,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.CapabilitiesTest do
"StatsAPI" => true,
"SitesAPI" => false,
"SiteSegments" => true,
+ "SiteAnnotations" => true,
"SharedLinks" => true,
"SSO" => false,
"ConsolidatedView" => true
@@ -124,6 +127,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.CapabilitiesTest do
"StatsAPI" => false,
"SitesAPI" => false,
"SiteSegments" => false,
+ "SiteAnnotations" => false,
"SharedLinks" => true,
"SSO" => false,
"ConsolidatedView" => false
@@ -160,6 +164,7 @@ defmodule PlausibleWeb.Plugins.API.Controllers.CapabilitiesTest do
"StatsAPI" => true,
"SitesAPI" => true,
"SiteSegments" => false,
+ "SiteAnnotations" => false,
"SharedLinks" => false,
"SSO" => false,
"ConsolidatedView" => false