Skip to content

: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.

chore(hog-charts): extract anomaly points layer (stage 5) (#57438)

Sam Pennington0a063d5196ad
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a2799725bfb8..ea01e66b8162 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -572,6 +572,10 @@ snapshots:
hash: v1.k794b7964.8f27aa8ee4161d4041693a5549046f0e348aab5fdccc466ea461d6a0f5cf97e2.KEpUtlvBURMPzv1Vyq9Pvf8i_sDKoF3t7fZO8Ed1yPs
components-hogcharts-referenceline--vertical-reference-lines--light:
hash: v1.k794b7964.c5c09ab055b1b0fde7a5d73279e6a1adba9cc4165d0883ea8c641d4cd68ebf2b.hb7hZ9GBhWL6oRE5jtOZuUEer6xZ5dTyjpH0qB4Dfpk
+ components-hogcharts-timeserieslinechart--anomalies--dark:
+ hash: v1.k794b7964.fc7e9b233a0ff0847a5dcade2aaa7004f453c1af65a443adeecb526540ffa0a8.h18dCehQgzalv7JwGX-pqrA-zgiB0WsMqioFp0lX5EY
+ components-hogcharts-timeserieslinechart--anomalies--light:
+ hash: v1.k794b7964.ec037285360c27f8362e5476fbb5eb9c02eff034c83c40d91915b2456adafa85.Ls5QZuxtjPy-4OamK69F1DVapsxQ6sKdNf9dGJdzMCg
components-hogcharts-timeserieslinechart--basic--dark:
hash: v1.k794b7964.529535e435c93c8f004cdba8f2ba29681dd679eb9bfbaff745a5f00c3b424ffd.2Kq3-2B9F2VNlkrFY-dge3vntnfrudonJ-Lle1s8m5E
components-hogcharts-timeserieslinechart--basic--light:
@@ -5767,9 +5771,9 @@ snapshots:
scenes-other-toolbar--actions-dark--light:
hash: v1.k794b7964.5e201782c0e7cc4fb79a3a415957412f7289067d389fc843016d525b240f65c6.SSUCR9SF-qmJPo_ZYzLnD6sdBVd068TCfgxKtvXrBAk
scenes-other-toolbar--default--dark:
- hash: v1.k794b7964.b63b312c1025e77b9ad7cd341fc74269a4419e355816518dbf293eeba347d997.gp4k4wzoHhcIEtIsO-hLFejBICNa-Uv0YHjWLvh4nfA
+ hash: v1.k794b7964.60433d2f1ba31f04a2fbea8b13664ca00d3cb4d490f202b608c2fae125e75b42.BXy8KDjQPq8Rizc12C0FxmLb0XaVfT_TJMrCX_9ZDaQ
scenes-other-toolbar--default--light:
- hash: v1.k794b7964.caed317b8657db1d87f5f14939fca7b00dab779984fda6bdb655910858dad332.f2GrDHnkAPsSyl5DkvVSpWU81J52MQTVt-Dh_PxYNNA
+ hash: v1.k794b7964.d31d8fe47d002bc2250bba565f2762490fe83b850ef7a34794e5374d3a775ac0.yzuot7AtMFiAtCuajEkMcjt5a3B_UggDkgZWlScp8aY
scenes-other-toolbar--default-dark--dark:
hash: v1.k794b7964.2636ee97c76404f279b123eefea7039fb60d570cd9c000e97c202ee89b346ccf.GwjJqF1xvhLzXZNHu_-0VWnSDrq1PCDn2QhExrG6VeI
scenes-other-toolbar--default-dark--light:
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
index 06b96f9ae8b6..0b7a8483ebb3 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
@@ -1,7 +1,7 @@
import { Meta, StoryObj } from '@storybook/react'
-import { TimeSeriesLineChart } from 'lib/hog-charts'
-import type { Series, TimeInterval, YAxisConfig } from 'lib/hog-charts'
+import { DEFAULT_Y_AXIS_ID, TimeSeriesLineChart } from 'lib/hog-charts'
+import type { AnomalyMarker, Series, TimeInterval, YAxisConfig } from 'lib/hog-charts'
import { Stage, useReactiveTheme } from '../../story-helpers'
@@ -165,6 +165,29 @@ export const YAxisFormats: Story = {
),
}
+export const Anomalies: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const series: Series[] = [{ key: 'visits', label: 'Visits', data: [20, 35, 28, 60, 45, 70, 52] }]
+ // Severity drives color — low (amber), medium (orange), high (red).
+ const anomalies: AnomalyMarker[] = [
+ { dataIndex: 1, value: 35, color: '#f59e0b', yAxisId: DEFAULT_Y_AXIS_ID },
+ { dataIndex: 3, value: 60, color: '#f97316', yAxisId: DEFAULT_Y_AXIS_ID },
+ { dataIndex: 5, value: 70, color: '#ef4444', yAxisId: DEFAULT_Y_AXIS_ID },
+ ]
+ return (
+ <Stage>
+ <TimeSeriesLineChart
+ series={series}
+ labels={DAYS}
+ theme={theme}
+ config={{ yAxis: { showGrid: true }, anomalies }}
+ />
+ </Stage>
+ )
+ },
+}
+
export const DateAxis: Story = {
render: () => {
const cells: { interval: TimeInterval; labels: string[]; series: Series[]; title: string }[] = [
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
index fd819ac841af..7d4a155afb49 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
@@ -2,6 +2,7 @@ import { cleanup } from '@testing-library/react'
import type { ChartTheme, Series } from '../../core/types'
import { renderHogChart, setupJsdom, setupSyncRaf } from '../../testing'
+import type { AnomalyMarker } from './overlays/AnomalyPointsLayer'
import { TimeSeriesLineChart } from './TimeSeriesLineChart'
const THEME: ChartTheme = { colors: ['#111', '#222', '#333'], backgroundColor: '#ffffff' }
@@ -219,6 +220,37 @@ describe('TimeSeriesLineChart', () => {
})
})
+ describe('config.anomalies', () => {
+ it.each([
+ ['omitted', undefined],
+ ['empty', [] as AnomalyMarker[]],
+ ])('does not render anomaly points when anomalies is %s', (_, anomalies) => {
+ const { container } = renderHogChart(
+ <TimeSeriesLineChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={anomalies === undefined ? undefined : { anomalies }}
+ />
+ )
+ expect(container.querySelectorAll('[data-attr="hog-chart-anomaly-point"]')).toHaveLength(0)
+ })
+
+ it('renders one anomaly point per marker', () => {
+ const markers: AnomalyMarker[] = [
+ { dataIndex: 1, value: 2, color: '#f00', yAxisId: 'left' },
+ { dataIndex: 2, value: 3, color: '#0f0', yAxisId: 'left' },
+ ]
+ const { container } = renderHogChart(
+ <TimeSeriesLineChart series={SERIES} labels={LABELS} theme={THEME} config={{ anomalies: markers }} />
+ )
+ const dots = container.querySelectorAll<HTMLElement>('[data-attr="hog-chart-anomaly-point"]')
+ expect(dots).toHaveLength(2)
+ expect(dots[0].style.backgroundColor).toBe('rgb(255, 0, 0)')
+ expect(dots[1].style.backgroundColor).toBe('rgb(0, 255, 0)')
+ })
+ })
+
it('forwards children alongside built-in overlays', () => {
const { container } = renderHogChart(
<TimeSeriesLineChart series={SERIES} labels={LABELS} theme={THEME}>
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index 851e8efe5f6f..67fc0faa49dd 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -4,6 +4,7 @@ import type { ChartTheme, LineChartConfig, PointClickData, Series, TooltipContex
import { ReferenceLines } from '../../overlays/ReferenceLine'
import { ValueLabels } from '../../overlays/ValueLabels'
import { LineChart } from '../LineChart'
+import { AnomalyPointsLayer, type AnomalyMarker } from './overlays/AnomalyPointsLayer'
import { buildGoalLineReferenceLines, type GoalLineConfig } from './utils/goal-lines'
import { applyInProgressToSeries, type InProgressConfig } from './utils/in-progress'
import { useXTickFormatter, useYTickFormatter, type XAxisConfig, type YAxisConfig } from './utils/use-axis-formatters'
@@ -19,6 +20,8 @@ export interface TimeSeriesLineChartConfig {
inProgress?: InProgressConfig
valueLabels?: boolean | ValueLabelsConfig
goalLines?: GoalLineConfig[]
+ /** Anomaly markers rendered as filled circles on top of the chart. */
+ anomalies?: AnomalyMarker[]
}
export interface TimeSeriesLineChartProps<Meta = unknown> {
@@ -54,7 +57,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
className,
children,
}: TimeSeriesLineChartProps<Meta>): React.ReactElement {
- const { xAxis, yAxis, inProgress, valueLabels, goalLines } = config ?? {}
+ const { xAxis, yAxis, inProgress, valueLabels, goalLines, anomalies } = config ?? {}
const xTickFormatter = useXTickFormatter(xAxis, labels)
const yTickFormatter = useYTickFormatter(yAxis)
@@ -109,6 +112,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
>
{referenceLines.length > 0 && <ReferenceLines lines={referenceLines} />}
{valueLabelsConfig && <ValueLabels valueFormatter={valueLabelFormatter} />}
+ {anomalies && anomalies.length > 0 && <AnomalyPointsLayer markers={anomalies} />}
{children}
</LineChart>
)
diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/AnomalyPointsLayer.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/overlays/AnomalyPointsLayer.tsx
similarity index 81%
rename from frontend/src/scenes/trends/viz/trends-line-chart/AnomalyPointsLayer.tsx
rename to frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/overlays/AnomalyPointsLayer.tsx
index 4c66a04d5492..7601656dfa9c 100644
--- a/frontend/src/scenes/trends/viz/trends-line-chart/AnomalyPointsLayer.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/overlays/AnomalyPointsLayer.tsx
@@ -1,9 +1,18 @@
/* eslint-disable react/forbid-dom-props -- dynamic pixel positions from d3 scales */
import React from 'react'
-import { useChartLayout } from 'lib/hog-charts'
+import { useChartLayout } from '../../../core/chart-context'
-import type { AnomalyMarker } from './anomalyPointsAdapter'
+export interface AnomalyMarker {
+ /** Index along the x-axis (into the chart's `labels` array). */
+ dataIndex: number
+ /** y-value at the marker (used to position via the y-scale). */
+ value: number
+ /** Color to fill the marker (typically the source series's color). */
+ color: string
+ /** y-axis id the marker is positioned against. */
+ yAxisId: string
+}
interface AnomalyPointsLayerProps {
markers: AnomalyMarker[]
@@ -43,6 +52,7 @@ export function AnomalyPointsLayer({ markers, radius = 3 }: AnomalyPointsLayerPr
dots.push(
<div
key={`${marker.dataIndex}-${marker.yAxisId}`}
+ data-attr="hog-chart-anomaly-point"
className="absolute pointer-events-none rounded-full"
style={{
left: x - radius,
diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.ts
index f67ba531ea64..17ec4cda3c2d 100644
--- a/frontend/src/lib/hog-charts/index.ts
+++ b/frontend/src/lib/hog-charts/index.ts
@@ -60,6 +60,10 @@ export type { ValueLabelsProps } from './overlays/ValueLabels'
// Helper for adapters that need to align with the same x-axis tick selection the chart draws.
export { computeVisibleXLabels } from './overlays/AxisLabels'
+// Timeseries overlays
+export { AnomalyPointsLayer } from './charts/TimeSeriesLineChart/overlays/AnomalyPointsLayer'
+export type { AnomalyMarker } from './charts/TimeSeriesLineChart/overlays/AnomalyPointsLayer'
+
// Timeseries utils
export { createXAxisTickCallback, parseDateForAxis } from './charts/TimeSeriesLineChart/utils/dates'
export type { TimeInterval } from './charts/TimeSeriesLineChart/utils/dates'
diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/TrendsAlertOverlays.tsx b/frontend/src/scenes/trends/viz/trends-line-chart/TrendsAlertOverlays.tsx
index a6d9153f49fb..74de066813a8 100644
--- a/frontend/src/scenes/trends/viz/trends-line-chart/TrendsAlertOverlays.tsx
+++ b/frontend/src/scenes/trends/viz/trends-line-chart/TrendsAlertOverlays.tsx
@@ -2,13 +2,12 @@ import { useValues } from 'kea'
import React, { useMemo } from 'react'
import { insightAlertsLogic } from 'lib/components/Alerts/insightAlertsLogic'
-import { ReferenceLines } from 'lib/hog-charts'
+import { AnomalyPointsLayer, ReferenceLines } from 'lib/hog-charts'
import type { InsightLogicProps } from '~/types'
import type { IndexedTrendResult } from '../../types'
import { buildAnomalyMarkers } from './anomalyPointsAdapter'
-import { AnomalyPointsLayer } from './AnomalyPointsLayer'
import { alertThresholdsToReferenceLines } from './goalLinesAdapter'
interface TrendsAlertOverlaysProps {
diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/anomalyPointsAdapter.ts b/frontend/src/scenes/trends/viz/trends-line-chart/anomalyPointsAdapter.ts
index d99c8cd11ebb..7ad12e6efbd9 100644
--- a/frontend/src/scenes/trends/viz/trends-line-chart/anomalyPointsAdapter.ts
+++ b/frontend/src/scenes/trends/viz/trends-line-chart/anomalyPointsAdapter.ts
@@ -1,18 +1,11 @@
import type { AnomalyPoint } from 'lib/components/Alerts/types'
+import type { AnomalyMarker as BaseAnomalyMarker } from 'lib/hog-charts'
import type { IndexedTrendResult } from '../../types'
-export interface AnomalyMarker {
- /** Index along the x-axis (into the chart's `labels` array). */
- dataIndex: number
- /** y-value at the marker (used to position via the y-scale). */
- value: number
- /** Color to fill the marker (typically the source series's color). */
- color: string
+export interface AnomalyMarker extends BaseAnomalyMarker {
/** Originating alert anomaly score (0..1) if available. */
score: number | null
- /** y-axis id the marker is positioned against. */
- yAxisId: string
}
/** Build a flat list of {@link AnomalyMarker}s ready for rendering as DOM dots.