Add website annotations with chart markers and CRUD management

This commit is contained in:
Mike Cao committed 2026-08-27 00:09:03 -07:00
1 parent eea124bbf8
commit 64e4cc1c3b
24 files changed
+957 -3

No files matched your search

+74
View File
@@ -6,6 +6,11 @@ import ChartJS, {
type UpdateMode,
} from 'chart.js/auto';
import { useEffect, useMemo, useRef, useState } from 'react';
import {
type AnnotationMarker,
type ChartAnnotation,
ChartAnnotationMarkers,
} from '@/components/charts/ChartAnnotationMarkers';
import { Legend } from '@/components/metrics/Legend';
import { DEFAULT_ANIMATION_DURATION } from '@/lib/constants';
@@ -20,6 +25,21 @@ export interface ChartProps extends BoxProps {
onTooltip?: (model: any) => void;
hiddenLabels?: Set<string>;
onLegendClick?: (label: string, willBeHidden: boolean) => void;
annotations?: ChartAnnotation[];
onAnnotationClick?: (annotation: ChartAnnotation) => void;
}
function isSameMarkers(a: AnnotationMarker[], b: AnnotationMarker[]) {
return (
a.length === b.length &&
a.every(
(m, i) =>
m.x === b[i].x &&
m.y === b[i].y &&
m.annotations.length === b[i].annotations.length &&
m.annotations.every((annotation, j) => annotation === b[i].annotations[j]),
)
);
}
export function Chart({
@@ -31,11 +51,56 @@ export function Chart({
chartOptions,
hiddenLabels,
onLegendClick,
annotations,
onAnnotationClick,
...props
}: ChartProps) {
const canvas = useRef(null);
const chart = useRef(null);
const [legendItems, setLegendItems] = useState([]);
const [markers, setMarkers] = useState<AnnotationMarker[]>([]);
const annotationsRef = useRef<ChartAnnotation[]>(annotations);
annotationsRef.current = annotations;
// Computes pixel positions for annotation markers whenever the chart lays out (update / resize)
const annotationPlugin = useMemo(
() => ({
id: 'annotationMarkers',
afterLayout: (instance: any) => {
const list = annotationsRef.current;
const { chartArea, scales } = instance;
if (!list?.length || !chartArea || !scales?.x) {
setMarkers(prev => (prev.length ? [] : prev));
return;
}
// Group annotations that land on the same pixel column into a single marker
const groups = new Map<number, AnnotationMarker>();
for (const annotation of list) {
const x = Math.round(scales.x.getPixelForValue(annotation.date.getTime()));
if (!Number.isFinite(x) || x < chartArea.left || x > chartArea.right) {
continue;
}
const group = groups.get(x);
if (group) {
group.annotations.push(annotation);
} else {
groups.set(x, { annotations: [annotation], x, y: chartArea.bottom });
}
}
const next = [...groups.values()];
setMarkers(prev => (isSameMarkers(prev, next) ? prev : next));
},
}),
[],
);
const options = useMemo(() => {
return {
@@ -99,6 +164,7 @@ export function Chart({
type,
data: chartData,
options,
plugins: [annotationPlugin],
});
setLegendItems(chart.current.legend.legendItems);
@@ -140,11 +206,19 @@ export function Chart({
}
}, [chartData, options, updateMode, hiddenLabels]);
// Re-run layout when annotations change so marker positions are recalculated
useEffect(() => {
chart.current?.update('none');
}, [annotations]);
return (
<Column gap="6">
<Box {...props}>
<div style={{ position: 'relative', width: '100%', height: '100%', overflow: 'hidden' }}>
<canvas ref={canvas} style={{ position: 'absolute', top: 0, left: 0 }} />
{markers.length > 0 && (
<ChartAnnotationMarkers markers={markers} onClick={onAnnotationClick} />
)}
</div>
</Box>
<Legend items={legendItems} onClick={handleLegendClick} />
@@ -0,0 +1,42 @@
.marker {
position: absolute;
width: 14px;
height: 14px;
border-radius: 50%;
border: 2px solid var(--base-color-1, #fff);
padding: 0;
cursor: pointer;
transform: translate(-50%, -50%);
z-index: 1;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
transition: transform 0.1s ease-in-out;
}
.marker:hover,
.marker:focus-visible {
transform: translate(-50%, -50%) scale(1.3);
outline: none;
}
.count {
position: absolute;
top: -8px;
right: -8px;
min-width: 14px;
height: 14px;
padding: 0 3px;
border-radius: 7px;
font-size: 9px;
font-weight: 600;
line-height: 14px;
color: #fff;
background: inherit;
border: 1px solid var(--base-color-1, #fff);
pointer-events: none;
}
.note {
max-width: 300px;
white-space: pre-wrap;
word-break: break-word;
}
@@ -0,0 +1,69 @@
import { Column, Text, Tooltip, TooltipTrigger, useTheme } from '@umami/react-zen';
import { useMemo } from 'react';
import { useLocale } from '@/components/hooks';
import { getThemeColors } from '@/lib/colors';
import { formatDate } from '@/lib/date';
import styles from './ChartAnnotationMarkers.module.css';
export interface ChartAnnotation {
id: string;
date: Date;
label: string;
allDay?: boolean;
}
export interface AnnotationMarker {
annotations: ChartAnnotation[];
x: number;
y: number;
}
export function formatAnnotationDate(annotation: ChartAnnotation, locale: string) {
return formatDate(annotation.date, annotation.allDay === false ? 'PP p' : 'PP', locale);
}
export function ChartAnnotationMarkers({
markers,
onClick,
}: {
markers: AnnotationMarker[];
onClick?: (annotation: ChartAnnotation) => void;
}) {
const { theme } = useTheme();
const { locale } = useLocale();
const { colors } = useMemo(() => getThemeColors(theme), [theme]);
return (
<>
{markers.map(({ annotations, x, y }) => {
const [first] = annotations;
return (
<TooltipTrigger key={first.id} delay={0}>
<button
type="button"
className={styles.marker}
style={{ left: x, top: y, backgroundColor: colors.chart.views.hoverBorderColor }}
aria-label={annotations.map(({ label }) => label).join(', ')}
onClick={() => onClick?.(first)}
>
{annotations.length > 1 && <span className={styles.count}>{annotations.length}</span>}
</button>
<Tooltip placement="top">
<Column gap="3" className={styles.note}>
{annotations.map(annotation => (
<Column key={annotation.id} gap="1">
<Text size="sm" weight="bold">
{formatAnnotationDate(annotation, locale)}
</Text>
<Text size="sm">{annotation.label}</Text>
</Column>
))}
</Column>
</Tooltip>
</TooltipTrigger>
);
})}
</>
);
}
+1
View File
@@ -75,6 +75,7 @@ export * from './queries/useWebsiteMetricsQuery';
export * from './queries/useWebsitePageviewsQuery';
export * from './queries/useWebsiteListChartsQuery';
export * from './queries/useWebsiteQuery';
export * from './queries/useWebsiteAnnotationsQuery';
export * from './queries/useWebsiteSegmentQuery';
export * from './queries/useWebsiteSegmentsQuery';
export * from './queries/useWebsiteSessionQuery';
@@ -0,0 +1,21 @@
import { keepPreviousData } from '@tanstack/react-query';
import type { ReactQueryOptions } from '@/lib/types';
import { useApi } from '../useApi';
import { useModified } from '../useModified';
export function useWebsiteAnnotationsQuery(
websiteId: string,
params?: Record<string, string | number>,
options?: ReactQueryOptions,
) {
const { get, useQuery } = useApi();
const { modified } = useModified(`annotations`);
return useQuery({
queryKey: ['website:annotations', { websiteId, modified, ...params }],
queryFn: () => get(`/websites/${websiteId}/annotations`, params),
enabled: !!websiteId,
placeholderData: keepPreviousData,
...options,
});
}
+3
View File
@@ -336,6 +336,9 @@ export const labels: Record<string, string> = {
addBoard: 'label.add-board',
selectComponent: 'label.select-component',
addLink: 'label.add-link',
addNote: 'label.add-note',
notes: 'label.notes',
note: 'label.note',
addPixel: 'label.add-pixel',
maximize: 'label.maximize',
remaining: 'label.remaining',