:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(insights): decouple annotations overlay from the chart.js Chart type (#76924)
Sam Pennington9df11504142a
diff --git a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsxindex 47ba97064dbc..f6f1f511663d 100644--- a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx+++ b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx@@ -6,7 +6,6 @@ import React, { useEffect, useRef, useState } from 'react'import { IconPencil, IconPlusSmall, IconTrash } from '@posthog/icons'-import { Chart } from 'lib/Chart'import { TextContent } from 'lib/components/Cards/TextCard/TextCard'import { dayjs } from 'lib/dayjs'import { LemonBadge } from 'lib/lemon-ui/LemonBadge/LemonBadge'@@ -25,7 +24,7 @@ import { annotationsModel } from '~/models/annotationsModel'import { AnnotationType, DatedAnnotationType, IntervalType } from '~/types'import { AnnotationsOverlayLogicProps, annotationsOverlayLogic } from './annotationsOverlayLogic'-import { useAnnotationsPositioning } from './useAnnotationsPositioning'+import { AnnotationsChartGeometry, useAnnotationsPositioning } from './useAnnotationsPositioning'const MIN_BADGE_SPACING_PX = 24/** Clusters anchor on their starting badge (leftPx) so a chain of near-adjacent badges@@ -69,10 +68,8 @@ function getInterpolatedDataPointX(dataIndex: number, getDataPointX: (index: numexport interface AnnotationsOverlayProps {insightNumericId: AnnotationsOverlayLogicProps['insightNumericId']dates: string[]- chart: Chart+ geometry: AnnotationsChartGeometrychartWidth: number- chartHeight: number- datasetIndex?: number/** Forwarded to the kea logic key so multiple overlays on the same insight don't* collide. Used by compare-against-previous bar charts to show one overlay per period. */kind?: string@@ -85,29 +82,22 @@ interface AnnotationsOverlayCSSProperties extends React.CSSProperties {}export const AnnotationsOverlay = React.memo(function AnnotationsOverlay({- chart,+ geometry,chartWidth,- chartHeight,dates,insightNumericId,- datasetIndex = 0,kind,}: AnnotationsOverlayProps): JSX.Element {const { insightProps } = useValues(insightLogic)- const { tickIntervalPx, firstTickLeftPx, getDataPointX } = useAnnotationsPositioning(- chart,- chartWidth,- chartHeight,- datasetIndex- )+ const { tickIntervalPx, firstTickLeftPx, getDataPointX } = useAnnotationsPositioning(geometry)// Memoize ticks by value to prevent unnecessary kea selector cascades.- // chart.scales.x.ticks is a Chart.js internal array that is the same object between renders- // when the chart hasn't changed, but .map() would create new references every render,- // causing all downstream selectors (tickDates → dateRange → relevantAnnotations →- // groupedAnnotations) to recompute unnecessarily.+ // The tick array is the same object between renders while the chart's layout is unchanged,+ // but .map() would create new references every render, causing all downstream selectors+ // (tickDates → dateRange → relevantAnnotations → groupedAnnotations) to recompute+ // unnecessarily.const prevTicksRef = useRef<{ value: number }[]>([])- const currentChartTicks = chart.scales.x.ticks+ const currentChartTicks = geometry.xTicksif (prevTicksRef.current.length !== currentChartTicks.length ||prevTicksRef.current.some((t, i) => t.value !== currentChartTicks[i]?.value)@@ -139,7 +129,7 @@ export const AnnotationsOverlay = React.memo(function AnnotationsOverlay({const modalContentRef = useRef<HTMLDivElement | null>(null)const modalOverlayRef = useRef<HTMLDivElement | null>(null)const badgeRefs = useRef<Map<string, HTMLButtonElement>>(new Map())- const chartAreaLeft = chart ? chart.scales.x.left : 0+ const chartAreaLeft = geometry.plotLeftconst clusters = React.useMemo<AnnotationBadgeCluster[]>(() => {const positioned = annotationBadgeDataIndices@@ -194,7 +184,7 @@ export const AnnotationsOverlay = React.memo(function AnnotationsOverlay({style={{'--annotations-overlay-chart-area-left': `${chartAreaLeft}px`,- '--annotations-overlay-chart-area-height': `${chart ? chart.scales.x.top : 0}px`,+ '--annotations-overlay-chart-area-height': `${geometry.plotBottom}px`,'--annotations-overlay-chart-width': `${chartWidth}px`,} as AnnotationsOverlayCSSProperties}diff --git a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.test.ts b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.test.tsindex 330c6518e7b4..19951e79f0a0 100644--- a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.test.ts+++ b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.test.ts@@ -710,8 +710,8 @@ describe('annotationsOverlayLogic', () => {}}- it(`does not merge day groups even when Chart.js renders only one tick per N days (UTC)`, async () => {- // On a daily chart where Chart.js decides to render sparse ticks (e.g. one tick every 2 days),+ it(`does not merge day groups even when the chart renders only one tick per N days (UTC)`, async () => {+ // On a daily chart where the chart decides to render sparse ticks (e.g. one tick every 2 days),// annotation grouping should still be per-day — not bucketed by tick spacing.useInsightMocks()@@ -746,7 +746,7 @@ describe('annotationsOverlayLogic', () => {})})- it(`does not merge hour groups even when Chart.js renders only one tick per N hours (UTC)`, async () => {+ it(`does not merge hour groups even when the chart renders only one tick per N hours (UTC)`, async () => {useInsightMocks('hour')logic = annotationsOverlayLogic({diff --git a/frontend/src/lib/components/AnnotationsOverlay/index.ts b/frontend/src/lib/components/AnnotationsOverlay/index.tsindex 260367f26c41..2213462444c1 100644--- a/frontend/src/lib/components/AnnotationsOverlay/index.ts+++ b/frontend/src/lib/components/AnnotationsOverlay/index.ts@@ -1,2 +1,3 @@export * from './AnnotationsOverlay'export * from './annotationsOverlayLogic'+export * from './useAnnotationsPositioning'diff --git a/frontend/src/lib/components/AnnotationsOverlay/useAnnotationsPositioning.ts b/frontend/src/lib/components/AnnotationsOverlay/useAnnotationsPositioning.tsindex 5c207802219b..f8e546f12062 100644--- a/frontend/src/lib/components/AnnotationsOverlay/useAnnotationsPositioning.ts+++ b/frontend/src/lib/components/AnnotationsOverlay/useAnnotationsPositioning.ts@@ -1,6 +1,17 @@import { useMemo } from 'react'-import { Chart } from 'lib/Chart'+/** The chart geometry annotations are positioned against. Charts derive it from their own layout+ * (the trends charts read quill's `useChartLayout()`), so the overlay stays library-agnostic. */+export interface AnnotationsChartGeometry {+ /** Visible x-axis ticks, as indices into `pointsX`. */+ xTicks: { value: number }[]+ /** Pixel x of every data point, index-aligned with the chart's labels. */+ pointsX: number[]+ /** Pixel x of the plot area's left edge. */+ plotLeft: number+ /** Pixel y of the plot area's bottom edge. */+ plotBottom: number+}export interface AnnotationsPositioning {tickIntervalPx: number@@ -9,36 +20,24 @@ export interface AnnotationsPositioning {getDataPointX: (dataIndex: number) => number | null}-export function useAnnotationsPositioning(- chart: Chart | undefined,- chartWidth: number,- chartHeight: number,- datasetIndex = 0-): AnnotationsPositioning {+export function useAnnotationsPositioning(geometry: AnnotationsChartGeometry): AnnotationsPositioning {// Calculate chart content coordinates for annotations overlay positioningreturn useMemo<AnnotationsPositioning>(() => {- // @ts-expect-error - _metasets is not officially exposed- const metasets = chart?._metasets as PointMetaset[] | undefined- const points = metasets?.[datasetIndex]?.data ?? metasets?.[0]?.data ?? null-- if (chart && chart.scales.x.ticks.length > 1 && points && points.length > 0) {- const tickCount = chart.scales.x.ticks.length- // NOTE: If there are lots of points on the X axis, Chart.js only renders a tick once n data points- // so that the axis is readable. We use that mechanism to aggregate annotations for readability too.- // We use the internal _metasets instead just taking graph area width, because it's NOT guaranteed that the- // last tick is positioned at the right edge of the graph area. We need to find out where it is.- const firstTickPointIndex = chart.scales.x.ticks[0].value- const lastTickPointIndex = chart.scales.x.ticks[tickCount - 1].value+ const { xTicks, pointsX } = geometry+ // NOTE: If there are lots of points on the X axis, only one tick is rendered per n data points+ // so that the axis is readable. We use that mechanism to aggregate annotations for readability+ // too. We use the data points' own pixel positions instead of just taking the graph area width,+ // because it's NOT guaranteed that the last tick is positioned at the right edge of the graph+ // area. We need to find out where it is.+ if (xTicks.length > 1 && pointsX.length > 0) {+ const tickCount = xTicks.length// Fall back to zero for resiliency against temporary chart inconsistencies during loading- const firstTickLeftPx = points[firstTickPointIndex]?.x ?? 0- const lastTickLeftPx = points[lastTickPointIndex]?.x ?? 0+ const firstTickLeftPx = pointsX[xTicks[0].value] ?? 0+ const lastTickLeftPx = pointsX[xTicks[tickCount - 1].value] ?? 0return {tickIntervalPx: (lastTickLeftPx - firstTickLeftPx) / (tickCount - 1),firstTickLeftPx,- getDataPointX: (dataIndex: number) => {- const point = points[dataIndex]- return point ? point.x : null- },+ getDataPointX: (dataIndex: number) => pointsX[dataIndex] ?? null,}}return {@@ -46,5 +45,5 @@ export function useAnnotationsPositioning(firstTickLeftPx: 0,getDataPointX: () => null,}- }, [chart, chartWidth, chartHeight, datasetIndex])+ }, [geometry])}diff --git a/products/product_analytics/frontend/insights/trends/shared/AnnotationsLayer.tsx b/products/product_analytics/frontend/insights/trends/shared/AnnotationsLayer.tsxindex 178a6852717f..39f194fcc945 100644--- a/products/product_analytics/frontend/insights/trends/shared/AnnotationsLayer.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/AnnotationsLayer.tsx@@ -2,8 +2,7 @@ import React, { useMemo } from 'react'import { computeVisibleXLabels, useChartLayout } from '@posthog/quill-charts'-import { Chart } from 'lib/Chart'-import { AnnotationsOverlay } from 'lib/components/AnnotationsOverlay'+import { AnnotationsOverlay, type AnnotationsChartGeometry } from 'lib/components/AnnotationsOverlay'interface AnnotationsLayerProps {/** Numeric insight id used by the annotations logic. Pass `'new'` for unsaved insights. */@@ -24,7 +23,7 @@ interface AnnotationsLayerProps {}const WRAPPER_STYLE: React.CSSProperties = {- // Re-enable pointer-events here because Chart's overlay layer disables them+ // Re-enable pointer-events here because the chart's overlay layer disables them// for non-interactive overlays (axis labels, crosshair, reference lines).pointerEvents: 'auto',}@@ -44,41 +43,29 @@ export function AnnotationsLayer({const { scales, dimensions, labels, axis } = useChartLayout()const xTickFormatter = axis.xTickFormatter- const currentChartLike = useMemo(() => {+ const currentGeometry = useMemo<AnnotationsChartGeometry>(() => {const visibleXLabels = computeVisibleXLabels(labels, scales.x, xTickFormatter)- const points = labels.map((label) => ({ x: scales.x(label, seriesKey) ?? 0, y: 0 }))- const ticks = visibleXLabels.map((v) => ({ value: v.index }))return {- scales: {- x: {- ticks,- left: dimensions.plotLeft,- top: dimensions.plotTop + dimensions.plotHeight,- },- },- _metasets: [{ data: points }],+ xTicks: visibleXLabels.map((v) => ({ value: v.index })),+ pointsX: labels.map((label) => scales.x(label, seriesKey) ?? 0),+ plotLeft: dimensions.plotLeft,+ plotBottom: dimensions.plotTop + dimensions.plotHeight,}// eslint-disable-next-line react-hooks/exhaustive-deps -- only `scales.x` is read; `scales` itself is unused.}, [labels, scales.x, seriesKey, dimensions.plotLeft, dimensions.plotTop, dimensions.plotHeight, xTickFormatter])- const previousChartLike = useMemo(() => {+ const previousGeometry = useMemo<AnnotationsChartGeometry | null>(() => {if (!previousDates || !previousSeriesKey) {return null}const visibleXLabels = computeVisibleXLabels(labels, scales.x, xTickFormatter)- // Anchor on the previous-period bar (left bar in each band) but reuse the current- // labels — only the x positions matter, not the labels themselves.- const points = labels.map((label) => ({ x: scales.x(label, previousSeriesKey) ?? 0, y: 0 }))- const ticks = visibleXLabels.map((v) => ({ value: v.index }))return {- scales: {- x: {- ticks,- left: dimensions.plotLeft,- top: dimensions.plotTop + dimensions.plotHeight,- },- },- _metasets: [{ data: points }],+ xTicks: visibleXLabels.map((v) => ({ value: v.index })),+ // Anchor on the previous-period bar (left bar in each band) but reuse the current+ // labels — only the x positions matter, not the labels themselves.+ pointsX: labels.map((label) => scales.x(label, previousSeriesKey) ?? 0),+ plotLeft: dimensions.plotLeft,+ plotBottom: dimensions.plotTop + dimensions.plotHeight,}// eslint-disable-next-line react-hooks/exhaustive-deps -- only `scales.x` is read; `scales` itself is unused.}, [@@ -92,7 +79,7 @@ export function AnnotationsLayer({xTickFormatter,])- if (currentChartLike.scales.x.ticks.length < 2) {+ if (currentGeometry.xTicks.length < 2) {return null}@@ -105,18 +92,16 @@ export function AnnotationsLayer({onMouseDown={stopPointerPropagation}><AnnotationsOverlay- chart={currentChartLike as unknown as Chart}+ geometry={currentGeometry}dates={dates}chartWidth={dimensions.width}- chartHeight={dimensions.height}insightNumericId={insightNumericId}/>- {previousChartLike && previousDates && (+ {previousGeometry && previousDates && (<AnnotationsOverlay- chart={previousChartLike as unknown as Chart}+ geometry={previousGeometry}dates={previousDates}chartWidth={dimensions.width}- chartHeight={dimensions.height}insightNumericId={insightNumericId}kind="previous"/>