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.

refactor(charts): default reference-line orientation from context (#63488)

Sam Pennington26b2821dda3d
diff --git a/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx b/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx
new file mode 100644
index 000000000000..f224706bea52
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx
@@ -0,0 +1,186 @@
+import { fireEvent, waitFor } from '@testing-library/react'
+import React from 'react'
+
+import type { RadialSlicePayload } from '../../core/hooks/useRadialInteraction'
+import { RADIAL_MARGINS } from '../../core/RadialChart'
+import type { ResolvedSeries, ChartTheme, Series } from '../../core/types'
+import { getHogChartTooltip, renderHogChart } from '../../testing'
+import { mockRect } from '../../testing/jsdom'
+import { computePieLayout } from './computePieLayout'
+import type { PieLayout } from './computePieLayout'
+import { PieChart } from './PieChart'
+
+const THEME: ChartTheme = {
+ colors: ['#1f77b4', '#ff7f0e', '#2ca02c'],
+ backgroundColor: '#ffffff',
+}
+
+const SERIES: Series[] = [
+ { key: 'a', label: 'Chrome', data: [50] },
+ { key: 'b', label: 'Firefox', data: [50] },
+]
+
+// RadialChart computes its plot box from the full canvas rect minus RADIAL_MARGINS.
+const PLOT_BOX = {
+ plotLeft: RADIAL_MARGINS.left,
+ plotTop: RADIAL_MARGINS.top,
+ plotWidth: mockRect.width - RADIAL_MARGINS.left - RADIAL_MARGINS.right,
+ plotHeight: mockRect.height - RADIAL_MARGINS.top - RADIAL_MARGINS.bottom,
+}
+
+function layoutFor(series: Series[], innerRadiusRatio = 0): PieLayout {
+ return computePieLayout({ series: series as ResolvedSeries[], dimensions: PLOT_BOX, innerRadiusRatio })
+}
+
+// A cursor point on a slice's centroid bisector at mid-radius — guaranteed inside the slice.
+// The wrapper rect is mocked at origin (0,0), so client coords equal cursor offsets.
+function pointInSlice(layout: PieLayout, sliceIndex: number): { clientX: number; clientY: number } {
+ const slice = layout.slices[sliceIndex]
+ const midR = (layout.innerRadius + layout.outerRadius) / 2
+ return {
+ clientX: layout.cx + Math.sin(slice.centroidAngle) * midR,
+ clientY: layout.cy - Math.cos(slice.centroidAngle) * midR,
+ }
+}
+
+function sliceLabels(wrapper: HTMLElement): string[] {
+ return Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-pie-slice-label"]')).map(
+ (el) => el.textContent ?? ''
+ )
+}
+
+describe('PieChart', () => {
+ it('renders a canvas labeled as a pie chart with one slice per series', () => {
+ const { container } = renderHogChart(<PieChart series={SERIES} theme={THEME} />)
+ const canvas = container.querySelector('canvas[aria-label]')
+ expect(canvas?.getAttribute('aria-label')).toBe('Pie chart with 2 slices')
+ })
+
+ it('forwards dataAttr to the chart wrapper', () => {
+ const { chart } = renderHogChart(<PieChart series={SERIES} theme={THEME} dataAttr="pie-instance" />)
+ expect(chart.element.getAttribute('data-attr')).toBe('pie-instance')
+ })
+
+ it('renders one on-slice value label per slice by default', () => {
+ const { chart } = renderHogChart(<PieChart series={SERIES} theme={THEME} />)
+ const labels = sliceLabels(chart.element)
+ expect(labels).toHaveLength(2)
+ expect(labels.join('|')).toContain('50')
+ })
+
+ it('renders percentage labels when isPercent is set', () => {
+ const { chart } = renderHogChart(<PieChart series={SERIES} theme={THEME} config={{ isPercent: true }} />)
+ const text = sliceLabels(chart.element).join('|')
+ expect(text).toContain('50%')
+ })
+
+ it('suppresses on-slice value labels when showValueOnSlice is false', () => {
+ const { chart } = renderHogChart(
+ <PieChart series={SERIES} theme={THEME} config={{ showValueOnSlice: false }} />
+ )
+ expect(sliceLabels(chart.element)).toHaveLength(0)
+ })
+
+ it('renders a center label for a donut', () => {
+ const { chart } = renderHogChart(
+ <PieChart series={SERIES} theme={THEME} config={{ innerRadiusRatio: 0.5 }} centerLabel="Total: 100" />
+ )
+ expect(chart.element.textContent).toContain('Total: 100')
+ })
+
+ it('renders custom overlay children', () => {
+ const { chart } = renderHogChart(
+ <PieChart series={SERIES} theme={THEME}>
+ <div data-attr="custom-child" />
+ </PieChart>
+ )
+ expect(chart.element.querySelector('[data-attr="custom-child"]')).not.toBeNull()
+ })
+
+ it('renders an empty pie (zero total) without crashing and with no slice labels', () => {
+ const { chart } = renderHogChart(<PieChart series={[{ key: 'a', label: 'A', data: [0] }]} theme={THEME} />)
+ expect(sliceLabels(chart.element)).toHaveLength(0)
+ })
+
+ describe('hover & tooltip', () => {
+ it('shows a tooltip for the slice under the cursor', async () => {
+ const { chart } = renderHogChart(<PieChart series={SERIES} theme={THEME} />)
+ const layout = layoutFor(SERIES)
+ fireEvent.mouseMove(chart.element, pointInSlice(layout, 0))
+ const tooltip = await chart.waitForTooltip()
+ expect(tooltip.seriesData[0].series.label).toBe('Chrome')
+ expect(tooltip.seriesData[0].value).toBe(50)
+ })
+
+ it('switches the tooltip to the other slice when the cursor moves', async () => {
+ const { chart } = renderHogChart(<PieChart series={SERIES} theme={THEME} />)
+ const layout = layoutFor(SERIES)
+ fireEvent.mouseMove(chart.element, pointInSlice(layout, 1))
+ const tooltip = await chart.waitForTooltip()
+ expect(tooltip.seriesData[0].series.label).toBe('Firefox')
+ })
+
+ it('shows no tooltip when hovering the donut hole', async () => {
+ const { chart } = renderHogChart(
+ <PieChart series={SERIES} theme={THEME} config={{ innerRadiusRatio: 0.5 }} />
+ )
+ const layout = layoutFor(SERIES, 0.5)
+ // Dead center is inside the inner radius — a hit-test miss.
+ fireEvent.mouseMove(chart.element, { clientX: layout.cx, clientY: layout.cy })
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(getHogChartTooltip()?.textContent ?? '').toBe('')
+ })
+ })
+
+ describe('slice click', () => {
+ it('invokes onSliceClick with the clicked slice payload', async () => {
+ const onSliceClick = jest.fn<void, [RadialSlicePayload]>()
+ const { chart } = renderHogChart(<PieChart series={SERIES} theme={THEME} onSliceClick={onSliceClick} />)
+ const layout = layoutFor(SERIES)
+ fireEvent.mouseMove(chart.element, pointInSlice(layout, 1))
+ await waitFor(() => expect(getHogChartTooltip()).not.toBeNull())
+ fireEvent.click(chart.element)
+ expect(onSliceClick).toHaveBeenCalledWith(
+ expect.objectContaining({ sliceIndex: 1, value: 50, fraction: 0.5 })
+ )
+ expect(onSliceClick.mock.calls[0][0].series.key).toBe('b')
+ })
+
+ it('does not invoke onSliceClick when the click misses every slice', () => {
+ const onSliceClick = jest.fn()
+ const { chart } = renderHogChart(
+ <PieChart
+ series={SERIES}
+ theme={THEME}
+ config={{ innerRadiusRatio: 0.5 }}
+ onSliceClick={onSliceClick}
+ />
+ )
+ const layout = layoutFor(SERIES, 0.5)
+ // Hover the hole (miss), then click — nothing should fire.
+ fireEvent.mouseMove(chart.element, { clientX: layout.cx, clientY: layout.cy })
+ fireEvent.click(chart.element)
+ expect(onSliceClick).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('error boundary', () => {
+ it('reports render errors through onError', async () => {
+ const onError = jest.fn()
+ const tooltip = (): React.ReactNode => {
+ throw new Error('boom')
+ }
+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
+ try {
+ const { chart } = renderHogChart(
+ <PieChart series={SERIES} theme={THEME} tooltip={tooltip} onError={onError} />
+ )
+ const layout = layoutFor(SERIES)
+ fireEvent.mouseMove(chart.element, pointInSlice(layout, 0))
+ await waitFor(() => expect(onError).toHaveBeenCalled())
+ } finally {
+ consoleErrorSpy.mockRestore()
+ }
+ })
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index d74cb1749e35..9ffad50a5da9 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -98,19 +98,13 @@ export function TimeSeriesBarChart<Meta = unknown>({
const valueLabelFormatter = valueLabelsConfig ? (valueLabelsConfig.formatter ?? yTickFormatter) : undefined
+ // `axisOrientation` flows through `barChartConfig` into chart context, so `ReferenceLine`
+ // reads it automatically — no need to stamp each line here.
const referenceLines = useMemo(
() => buildGoalLineReferenceLines(goalLines, seriesAfterValueLabels),
[goalLines, seriesAfterValueLabels]
)
- const orientedReferenceLines = useMemo(
- () =>
- axisOrientation === 'horizontal'
- ? referenceLines.map((line) => ({ ...line, axisOrientation: 'horizontal' as const }))
- : referenceLines,
- [referenceLines, axisOrientation]
- )
-
// Extend the value axis to cover goal lines that sit above (or below) the data, so a goal
// line off the data's natural scale still renders inside the plot. Memoized so the `{ include }`
// object stays referentially stable and doesn't re-trigger scale recomputation each render.
@@ -151,7 +145,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
dataAttr={dataAttr}
onError={onError}
>
- {orientedReferenceLines.length > 0 && <ReferenceLines lines={orientedReferenceLines} />}
+ {referenceLines.length > 0 && <ReferenceLines lines={referenceLines} />}
{valueLabelsConfig && <ValueLabels valueFormatter={valueLabelFormatter} />}
{children}
</BarChart>
diff --git a/packages/quill/packages/charts/src/overlays/AnomalyPointsLayer.test.tsx b/packages/quill/packages/charts/src/overlays/AnomalyPointsLayer.test.tsx
new file mode 100644
index 000000000000..78e2e2c16d04
--- /dev/null
+++ b/packages/quill/packages/charts/src/overlays/AnomalyPointsLayer.test.tsx
@@ -0,0 +1,134 @@
+import { cleanup, type RenderResult } from '@testing-library/react'
+import React from 'react'
+
+import type { BaseChartContext } from '../core/chart-context'
+import { makeOverlayContext, renderOverlayInChart } from '../testing'
+import { AnomalyPointsLayer, type AnomalyMarker } from './AnomalyPointsLayer'
+
+const DIMENSIONS = {
+ width: 800,
+ height: 400,
+ plotLeft: 48,
+ plotTop: 16,
+ plotWidth: 720,
+ plotHeight: 352,
+}
+
+// Simple linear y-scale: 0 -> plotBottom (368), 100 -> plotTop (16).
+const yScale = (v: number): number => 368 - (v / 100) * 352
+
+const CONTEXT: BaseChartContext = makeOverlayContext(
+ {
+ x: (label: string) => (({ Mon: 100, Tue: 400, Wed: 700 }) as Record<string, number | undefined>)[label],
+ y: yScale,
+ yTicks: () => [0, 50, 100],
+ },
+ {
+ dimensions: DIMENSIONS,
+ labels: ['Mon', 'Tue', 'Wed'],
+ }
+)
+
+function renderInChart(node: React.ReactNode, ctx: BaseChartContext = CONTEXT): RenderResult {
+ return renderOverlayInChart(node, ctx)
+}
+
+function dots(container: HTMLElement): NodeListOf<HTMLDivElement> {
+ return container.querySelectorAll<HTMLDivElement>('div[data-attr="hog-chart-anomaly-point"]')
+}
+
+function marker(overrides: Partial<AnomalyMarker> = {}): AnomalyMarker {
+ return { dataIndex: 1, value: 50, color: '#ff0000', yAxisId: 'left', ...overrides }
+}
+
+describe('AnomalyPointsLayer', () => {
+ afterEach(() => cleanup())
+
+ it('renders null when there are no markers', () => {
+ const { container } = renderInChart(<AnomalyPointsLayer markers={[]} />)
+ expect(container.firstChild).toBeNull()
+ })
+
+ it('renders a dot at the pixel computed from the scales', () => {
+ const { container } = renderInChart(<AnomalyPointsLayer markers={[marker({ dataIndex: 1, value: 50 })]} />)
+ const dot = dots(container)[0]
+ expect(dot).toBeTruthy()
+ // xScale('Tue') = 400, yScale(50) = 192; default radius 3 → left/top offset by 3.
+ expect(dot.style.left).toBe('397px')
+ expect(dot.style.top).toBe('189px')
+ expect(dot.style.width).toBe('6px')
+ expect(dot.style.height).toBe('6px')
+ })
+
+ it('fills the dot with the marker color', () => {
+ const { container } = renderInChart(<AnomalyPointsLayer markers={[marker({ color: 'rgb(1, 2, 3)' })]} />)
+ expect(dots(container)[0].style.backgroundColor).toBe('rgb(1, 2, 3)')
+ })
+
+ it('honors a custom radius', () => {
+ const { container } = renderInChart(<AnomalyPointsLayer markers={[marker({ value: 50 })]} radius={5} />)
+ const dot = dots(container)[0]
+ expect(dot.style.width).toBe('10px')
+ expect(dot.style.height).toBe('10px')
+ // left = xScale('Tue') 400 - radius 5 = 395
+ expect(dot.style.left).toBe('395px')
+ })
+
+ it('skips a marker whose label is unknown to the x-scale', () => {
+ // dataIndex 9 is out of the labels array → no x pixel.
+ const { container } = renderInChart(<AnomalyPointsLayer markers={[marker({ dataIndex: 9 })]} />)
+ expect(dots(container)).toHaveLength(0)
+ })
+
+ it('skips a marker whose y value falls outside the plot bounds', () => {
+ // value 500 → yScale(500) = 368 - 1760 = well above plotTop, out of bounds.
+ const { container } = renderInChart(<AnomalyPointsLayer markers={[marker({ value: 500 })]} />)
+ expect(dots(container)).toHaveLength(0)
+ })
+
+ it('positions a marker against its own yAxes scale when yAxisId matches', () => {
+ const rightScale = (v: number): number => 368 - (v / 1000) * 352
+ const multiAxisContext: BaseChartContext = {
+ ...CONTEXT,
+ scales: {
+ ...CONTEXT.scales,
+ yAxes: {
+ left: { scale: yScale, ticks: () => [0, 50, 100], position: 'left' },
+ y1: { scale: rightScale, ticks: () => [0, 500, 1000], position: 'right' },
+ },
+ },
+ }
+ // value 500 is out of bounds on the left axis but lands mid-plot on the right axis.
+ const { container } = renderInChart(
+ <AnomalyPointsLayer markers={[marker({ value: 500, yAxisId: 'y1' })]} />,
+ multiAxisContext
+ )
+ const dot = dots(container)[0]
+ expect(dot).toBeTruthy()
+ // rightScale(500) = 192; radius 3 → top = 189.
+ expect(dot.style.top).toBe('189px')
+ })
+
+ it('renders every in-bounds marker and skips only the out-of-bounds ones', () => {
+ const { container } = renderInChart(
+ <AnomalyPointsLayer
+ markers={[
+ marker({ dataIndex: 0, value: 25 }),
+ marker({ dataIndex: 2, value: 75 }),
+ marker({ dataIndex: 1, value: 9999 }), // out of bounds
+ ]}
+ />
+ )
+ expect(dots(container)).toHaveLength(2)
+ })
+
+ it('renders a stable data-attr on each dot', () => {
+ const { container } = renderInChart(<AnomalyPointsLayer markers={[marker(), marker({ dataIndex: 2 })]} />)
+ const rendered = dots(container)
+ expect(rendered).toHaveLength(2)
+ expect(Array.from(rendered).map((dot) => dot.getAttribute('data-attr'))).toEqual([
+ 'hog-chart-anomaly-point',
+ 'hog-chart-anomaly-point',
+ ])
+ })
+})
diff --git a/packages/quill/packages/charts/src/overlays/ReferenceLine.test.tsx b/packages/quill/packages/charts/src/overlays/ReferenceLine.test.tsx
index 3e7aee65ef79..817c3256ecab 100644
--- a/packages/quill/packages/charts/src/overlays/ReferenceLine.test.tsx
+++ b/packages/quill/packages/charts/src/overlays/ReferenceLine.test.tsx
@@ -186,6 +186,42 @@ describe('ReferenceLine', () => {
})
})
+ describe('axisOrientation from chart context', () => {
+ // In a horizontal-axis chart, scales.y is the value scale producing x-pixels, so a
+ // numeric horizontal reference line is drawn as a vertical stripe at scales.y(value).
+ const horizontalAxisContext: BaseChartContext = makeOverlayContext(
+ { ...CONTEXT.scales },
+ { dimensions: DIMENSIONS, labels: ['Mon', 'Tue', 'Wed'], axisOrientation: 'horizontal' }
+ )
+
+ it('defaults to the chart axis orientation (horizontal) without an explicit prop', () => {
+ const { container } = renderInChart(<ReferenceLine value={50} />, horizontalAxisContext)
+ // Drawn as a vertical stripe (left border) at scales.y(50) = 192; width 2 → left = 191.
+ const line = lineDiv(container, 'left')
+ expect(line).not.toBeNull()
+ expect(line!.style.left).toBe('191px')
+ // ...and NOT as a horizontal (top border) line.
+ expect(lineDiv(container, 'top')).toBeNull()
+ })
+
+ it('renders a horizontal line in a vertical-axis chart by default', () => {
+ // CONTEXT defaults axis.orientation to 'vertical'.
+ const { container } = renderInChart(<ReferenceLine value={50} />)
+ expect(lineDiv(container, 'top')).not.toBeNull()
+ expect(lineDiv(container, 'left')).toBeNull()
+ })
+
+ it('lets an explicit axisOrientation prop override the context', () => {
+ const { container } = renderInChart(
+ <ReferenceLine value={50} axisOrientation="vertical" />,
+ horizontalAxisContext
+ )
+ // Forced back to a horizontal (top border) line despite the horizontal-axis context.
+ expect(lineDiv(container, 'top')).not.toBeNull()
+ expect(lineDiv(container, 'left')).toBeNull()
+ })
+ })
+
describe('variants and style overrides', () => {
it.each([
['goal (default)', undefined, 'dashed', '2px'],
diff --git a/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx b/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx
index a2e746cac467..ff6bb69dc8bf 100644
--- a/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx
+++ b/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx
@@ -44,7 +44,8 @@ export interface ReferenceLineProps {
yAxisId?: string
/** Chart axis orientation. When `'horizontal'`, a `'horizontal'`-orientation reference
* line at a numeric value is drawn as a vertical stripe at `scales.y(value)` — matching
- * the value axis of horizontal bar charts. Defaults to `'vertical'`. */
+ * the value axis of horizontal bar charts. Defaults to the chart's own axis orientation
+ * (from context), so it's correct without the caller having to thread it through. */
axisOrientation?: ReferenceLineOrientation
}
@@ -90,7 +91,8 @@ export function ReferenceLines({ lines }: { lines: ReferenceLineProps[] }): Reac
* type narrowing, scale lookup, and bounds check, then hands pre-computed styles to
* {@link ReferenceLineView}. */
export function ReferenceLine(props: ReferenceLineProps): React.ReactElement | null {
- const { orientation = 'horizontal', variant = 'goal', style, axisOrientation = 'vertical' } = props
+ const { axis } = useChartLayout()
+ const { orientation = 'horizontal', variant = 'goal', style, axisOrientation = axis.orientation } = props
const resolved = useMemo(
() => resolveStyle(variant, style),
// eslint-disable-next-line react-hooks/exhaustive-deps