: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
feat(insights): add BoxPlot chart primitive to hog-charts library (#59880)
Sam Pennington6b1d4126d41a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex ee111857e948..d6dd348587f9 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -512,6 +512,22 @@ snapshots:hash: v1.k794b7964.d3b234d49784932eb4030d36ed1d1f8f74a00ee33921a4b7829a9b5b1acdc1a1.TNkfQrhR3kG9pKFnfFR1jIwuHvcQPeFprQM0nT9bEXscomponents-hogcharts-barchart--with-value-labels--light:hash: v1.k794b7964.9c31987f15bf48811309dab07e083a8c48ca7c87810ed55fb5fb1ee5b425d229.eF7z7jVC4P7Sa-vwW7C_jRc36GsRJcUlDz_Z-frOCec+ components-hogcharts-boxplot--multi-series-grouped--dark:+ hash: v1.k794b7964.e15fda1aa538cf716cbdc777ea0c7c0f8a1c2dce2bfc6a0ffcbcf51057cd61c0.ULzfhkAtxomnx0InVbOJ5SsEtSP60_OGSdFo-hZyWzo+ components-hogcharts-boxplot--multi-series-grouped--light:+ hash: v1.k794b7964.7358dc09fe05525935f428d91a0973969ce92d86d053495a90f35e6819f76bcc.hxbEezqVNPS4bEq0hk1AXkArYMwPGvGkd7QClId_oBI+ components-hogcharts-boxplot--no-grid--dark:+ hash: v1.k794b7964.21933874669d2ae068b7ba4761b8c9199cee0a4b0c5bb2817c3f0e4012eda95e.2WPXXDZS_nlRzv972uyaO42g143kCV38MBOEyfuh1Ws+ components-hogcharts-boxplot--no-grid--light:+ hash: v1.k794b7964.d101cb0578900466a42b5d30227d74aee0fbe74eed1855b97a4afa618683a372.gy8uCGLXWo3NJtNbZ0j-o6jrTsPoH0yFxigjaVauDy8+ components-hogcharts-boxplot--single-series--dark:+ hash: v1.k794b7964.67261ae28707a7b6cfba91d5ec7881d4eab4f9a39590001188c0b66e18cbc094.8YX-szCqzEDiMipHC1kMpT5SQ4vpAbT_-EJCYp_zysk+ components-hogcharts-boxplot--single-series--light:+ hash: v1.k794b7964.50c41defb191aef562b3bc55bd6bc3fef5eebd5af4fee1e8e87f24372fb748c5.c4ahYor0nJBNlF6tC7YMGUxx0XjcUptSRht6JATzTc0+ components-hogcharts-boxplot--with-gaps--dark:+ hash: v1.k794b7964.c154af270a078cbbb060543de422c6f2f2a2ae2134ffb797be0fb07f4e9c77bf.0gi1GO81ELv-U16NxXdiJF3VbtVBZaYK81G92hf8g_k+ components-hogcharts-boxplot--with-gaps--light:+ hash: v1.k794b7964.17739e468a4911b2bdfe16f13059a9b832e87386e3339ffb3a51c1c38ecfe821.9zttDtobDMs7E45HWOOxGwbEKOCRWDa2BqtMW8GSXcQcomponents-hogcharts-linechart--combined-overlays--dark:hash: v1.k794b7964.38753d5c6bab2f9d1be492d0e191aca21265953e220c0f37714913c89d7caf42.0wzgqeeUqe_bxIfIbS861HknzpuGVzxC664U1GTe9S8components-hogcharts-linechart--combined-overlays--light:@@ -4807,7 +4823,7 @@ snapshots:scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--superwide--light:hash: v1.k794b7964.c95c5a49f7a20b7fcb1041dd26c73ee87c9a906cb229247a44fd4633bbdc9173.StrJ2VBA5acLqvnsiO2CS_o6qadxeaeO6ST8lxf5UdIscenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--dark:- hash: v1.k794b7964.293297b83994468984576e5c15fa2cbbb2c4c0a7a8234959b9deba539efa383b.O7SwG4Drfr3z02hcLNC1LsLsGWddouhybBp4xZaUE-A+ hash: v1.k794b7964.c47bdb853ef9b6becfb675e2ca0bdbdb0c1b4385cf2442d50dd92752d90f7906.URrKOLP9uUjbKWcui2yOA7hm_JsXsbkAlOcWJshoQrIscenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--light:hash: v1.k794b7964.6c391cbc05b64230fbd8defdbb960b131fd433409817497873fb9ffc705cd360.EIwByuofuT77yP259A9ffqfjSFwW9MrUDOvsZNA_aZMscenes-app-insights-funnels--funnel-time-to-convert--dark:diff --git a/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlot.stories.tsx b/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlot.stories.tsxnew file mode 100644index 000000000000..0bdc4fad75c1--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlot.stories.tsx@@ -0,0 +1,137 @@+import { Meta, StoryObj } from '@storybook/react'++import { Stage, useReactiveTheme } from '../../story-helpers'+import { BoxPlot } from './BoxPlot'+import type { BoxPlotSeries } from './computeBoxLayout'++const DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']++function d(+ min: number,+ p25: number,+ median: number,+ mean: number,+ p75: number,+ max: number,+ day?: string+): { min: number; p25: number; median: number; mean: number; p75: number; max: number; day?: string } {+ return { min, p25, median, mean, p75, max, day }+}++const SESSION_DURATION: BoxPlotSeries[] = [+ {+ key: 'sessions',+ label: 'Session duration (s)',+ color: '',+ data: [+ d(2, 18, 42, 53, 84, 220, '2025-01-01'),+ d(3, 22, 48, 58, 90, 240, '2025-01-02'),+ d(1, 15, 38, 49, 78, 200, '2025-01-03'),+ d(4, 25, 55, 65, 100, 280, '2025-01-04'),+ d(2, 20, 50, 60, 95, 260, '2025-01-05'),+ d(3, 24, 52, 62, 98, 270, '2025-01-06'),+ d(2, 19, 45, 55, 88, 230, '2025-01-07'),+ ],+ },+]++const TWO_SERIES: BoxPlotSeries[] = [+ {+ key: 'desktop',+ label: 'Desktop',+ color: '',+ data: [+ d(2, 18, 42, 53, 84, 220),+ d(3, 22, 48, 58, 90, 240),+ d(1, 15, 38, 49, 78, 200),+ d(4, 25, 55, 65, 100, 280),+ d(2, 20, 50, 60, 95, 260),+ d(3, 24, 52, 62, 98, 270),+ d(2, 19, 45, 55, 88, 230),+ ],+ },+ {+ key: 'mobile',+ label: 'Mobile',+ color: '',+ data: [+ d(1, 10, 25, 32, 55, 140),+ d(2, 12, 28, 36, 60, 150),+ d(1, 11, 27, 33, 58, 145),+ d(3, 16, 35, 42, 70, 175),+ d(2, 14, 32, 40, 66, 160),+ d(2, 13, 30, 38, 64, 158),+ d(1, 10, 26, 33, 56, 148),+ ],+ },+]++const meta: Meta = { title: 'Components/HogCharts/BoxPlot', parameters: { layout: 'centered' } }+export default meta++type Story = StoryObj<{}>++export const SingleSeries: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage>+ <BoxPlot+ series={SESSION_DURATION}+ labels={SESSION_DURATION[0].data.map((datum, i) => datum?.day ?? `Day ${i}`)}+ theme={theme}+ config={{ showGrid: true }}+ />+ </Stage>+ )+ },+}++export const MultiSeriesGrouped: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage>+ <BoxPlot series={TWO_SERIES} labels={DAYS} theme={theme} config={{ showGrid: true }} />+ </Stage>+ )+ },+}++export const NoGrid: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage>+ <BoxPlot series={TWO_SERIES} labels={DAYS} theme={theme} />+ </Stage>+ )+ },+}++export const WithGaps: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: BoxPlotSeries[] = [+ {+ key: 'a',+ label: 'With gaps',+ color: '',+ data: [+ d(2, 18, 42, 53, 84, 220),+ null,+ d(1, 15, 38, 49, 78, 200),+ null,+ d(2, 20, 50, 60, 95, 260),+ d(3, 24, 52, 62, 98, 270),+ d(2, 19, 45, 55, 88, 230),+ ],+ },+ ]+ return (+ <Stage>+ <BoxPlot series={series} labels={DAYS} theme={theme} config={{ showGrid: true }} />+ </Stage>+ )+ },+}diff --git a/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlot.test.tsx b/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlot.test.tsxnew file mode 100644index 000000000000..f33eadf1bd39--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlot.test.tsx@@ -0,0 +1,276 @@+import { waitFor } from '@testing-library/react'++import type { ChartTheme } from '../../core/types'+import { renderHogChart, waitForHogChartTooltip } from '../../testing'+import { BoxPlot, type BoxPlotClickData } from './BoxPlot'+import type { BoxPlotDatum, BoxPlotSeries } from './computeBoxLayout'++const THEME: ChartTheme = {+ colors: ['#1f77b4', '#ff7f0e', '#2ca02c'],+ backgroundColor: '#ffffff',+ gridColor: '#eeeeee',+ crosshairColor: '#888888',+}++const LABELS = ['Mon', 'Tue', 'Wed']++function datum(overrides: Partial<BoxPlotDatum> = {}): BoxPlotDatum {+ return { min: 0, p25: 25, median: 50, mean: 55, p75: 75, max: 100, ...overrides }+}++const TWO_SERIES: BoxPlotSeries[] = [+ {+ key: 'a',+ label: 'A',+ data: [datum({ median: 40 }), datum({ median: 50 }), datum({ median: 60 })],+ },+ {+ key: 'b',+ label: 'B',+ data: [datum({ median: 30 }), datum({ median: 45 }), datum({ median: 55 })],+ },+]++describe('BoxPlot', () => {+ it('renders the canvas and reports series count via aria-label', () => {+ const { chart } = renderHogChart(<BoxPlot series={TWO_SERIES} labels={LABELS} theme={THEME} />)+ expect(chart.seriesCount).toBe(2)+ })++ it('renders y-axis ticks for the value range that spans whiskers', () => {+ const series: BoxPlotSeries[] = [+ {+ key: 'a',+ label: 'A',+ data: [datum({ min: 0, max: 200 }), datum({ min: 10, max: 220 })],+ },+ ]+ const { chart } = renderHogChart(<BoxPlot series={series} labels={['Mon', 'Tue']} theme={THEME} />)+ const ticks = chart.yTicks()+ expect(ticks.length).toBeGreaterThan(0)+ const nums = ticks.map((t) => parseFloat(t.replace(/[^\d.-]/g, '')))+ const maxTick = Math.max(...nums.filter((n) => Number.isFinite(n)))+ // The y-domain must span the largest whisker max (220), not just the median values.+ expect(maxTick).toBeGreaterThanOrEqual(200)+ })++ it('allocates left margin wide enough for the whisker-derived y ticks (not just medians)', () => {+ // Regression: clipping of the y-tick column. `useChartMargins` reads+ // `seriesValueRange(adaptedSeries)` to size the left margin, so the adapted series'+ // `data` must include the whisker extremes (not just medians) — `valueRangeSeries`+ // alone only reaches the d3 y-domain. Tick set covers the whisker range here, with+ // visual margin sizing left to Storybook snapshots (jsdom stubs `measureText`).+ const series: BoxPlotSeries[] = [+ {+ key: 'a',+ label: 'A',+ data: [+ datum({ min: 0, p25: 25, median: 30, mean: 35, p75: 50, max: 280 }),+ datum({ min: 0, p25: 28, median: 35, mean: 40, p75: 55, max: 270 }),+ ],+ },+ ]+ const { chart } = renderHogChart(<BoxPlot series={series} labels={['Mon', 'Tue']} theme={THEME} />)+ const ticks = chart.yTicks()+ const maxTickNumeric = Math.max(+ ...ticks.map((t) => parseFloat(t.replace(/[^\d.-]/g, ''))).filter((n) => Number.isFinite(n))+ )+ expect(maxTickNumeric).toBeGreaterThanOrEqual(250)+ })++ it('forwards `dataAttr` to the chart wrapper', () => {+ const { chart } = renderHogChart(+ <BoxPlot series={TWO_SERIES} labels={LABELS} theme={THEME} dataAttr="boxplot-instance" />+ )+ expect(chart.element.getAttribute('data-attr')).toBe('boxplot-instance')+ })++ it('renders empty state without crashing', () => {+ const { chart } = renderHogChart(<BoxPlot series={[]} labels={[]} theme={THEME} />)+ expect(chart.seriesCount).toBe(0)+ })++ it('tolerates null entries in series data', () => {+ const series: BoxPlotSeries[] = [{ key: 'a', label: 'A', data: [datum(), null, datum()] }]+ const { chart } = renderHogChart(<BoxPlot series={series} labels={LABELS} theme={THEME} />)+ expect(chart.seriesCount).toBe(1)+ })++ it('skips excluded series in seriesCount', () => {+ const series: BoxPlotSeries[] = [+ { key: 'a', label: 'A', data: [datum(), datum(), datum()] },+ {+ key: 'b',+ label: 'B',+ data: [datum(), datum(), datum()],+ visibility: { excluded: true },+ },+ ]+ const { chart } = renderHogChart(<BoxPlot series={series} labels={LABELS} theme={THEME} />)+ expect(chart.seriesCount).toBe(1)+ })++ describe('tooltip context', () => {+ it('exposes the original BoxPlotDatum on each series via meta.datums (six stats reachable)', async () => {+ const { chart } = renderHogChart(<BoxPlot series={TWO_SERIES} labels={LABELS} theme={THEME} />)+ chart.hoverAtIndex(1)+ const tooltip = await chart.waitForTooltip()+ const aMeta = tooltip.series.a!.series.meta as { datums: (BoxPlotDatum | null)[] }+ expect(aMeta.datums[1]).toEqual(+ expect.objectContaining({+ min: expect.any(Number),+ p25: expect.any(Number),+ median: 50,+ mean: expect.any(Number),+ p75: expect.any(Number),+ max: expect.any(Number),+ })+ )+ })++ it('includes the x-axis label in the tooltip context', async () => {+ const { chart } = renderHogChart(<BoxPlot series={TWO_SERIES} labels={LABELS} theme={THEME} />)+ chart.hoverAtIndex(1)+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.label).toBe('Tue')+ })+ })++ describe('tooltip rendering', () => {+ // `nativeTooltip: true` lets BoxPlotTooltip render its own DOM — the default mode+ // replaces the tooltip prop and short-circuits past it.++ const SINGLE_SERIES: BoxPlotSeries[] = [+ {+ key: 'a',+ label: 'A-label',+ data: [datum({ min: 1, p25: 2, median: 3, mean: 4, p75: 5, max: 6 }), datum(), datum()],+ },+ ]++ it('renders the six stats in the canonical order (Max → p75 → Median → Mean → p25 → Min)', async () => {+ const { chart } = renderHogChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />, {+ nativeTooltip: true,+ })+ chart.hoverAtIndex(0)+ const tooltipEl = await waitForHogChartTooltip()+ const rowLabels = Array.from(tooltipEl.querySelectorAll('tr')).map((tr) =>+ (tr.firstElementChild as HTMLElement).textContent!.trim()+ )+ expect(rowLabels).toEqual(['Max', '75th percentile', 'Median', 'Mean', '25th percentile', 'Min'])+ })++ it('renders the values in the canonical row order', async () => {+ const { chart } = renderHogChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />, {+ nativeTooltip: true,+ })+ chart.hoverAtIndex(0)+ const tooltipEl = await waitForHogChartTooltip()+ const values = Array.from(tooltipEl.querySelectorAll('tr')).map((tr) =>+ (tr.lastElementChild as HTMLElement).textContent!.trim()+ )+ expect(values).toEqual(['6', '5', '3', '4', '2', '1'])+ })++ it('shows the x label in the header', async () => {+ const { chart } = renderHogChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />, {+ nativeTooltip: true,+ })+ chart.hoverAtIndex(0)+ const tooltipEl = await waitForHogChartTooltip()+ expect(tooltipEl.textContent).toContain('Mon')+ })++ it('renders one stat table per visible series when grouped (multi-series)', async () => {+ const { chart } = renderHogChart(<BoxPlot series={TWO_SERIES} labels={LABELS} theme={THEME} />, {+ nativeTooltip: true,+ })+ chart.hoverAtIndex(0)+ const tooltipEl = await waitForHogChartTooltip()+ // Per-series header labels show in grouped mode.+ expect(tooltipEl.textContent).toContain('A')+ expect(tooltipEl.textContent).toContain('B')+ expect(tooltipEl.querySelectorAll('table')).toHaveLength(2)+ })++ it('hides the per-series label when not grouped (single series)', async () => {+ const { chart } = renderHogChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />, {+ nativeTooltip: true,+ })+ chart.hoverAtIndex(0)+ const tooltipEl = await waitForHogChartTooltip()+ const headers = Array.from(tooltipEl.querySelectorAll('.font-semibold')).map((el) => el.textContent)+ // The single "Mon" header is the only font-semibold heading in single-series mode.+ expect(headers).toContain('Mon')+ expect(headers).not.toContain('A-label')+ })++ it('passes through to a user-supplied tooltip when provided', async () => {+ const userTooltip = jest.fn(+ (): React.ReactElement => <div data-attr="custom-boxplot-user-tooltip">custom</div>+ )+ const { chart } = renderHogChart(+ <BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} tooltip={userTooltip} />,+ { nativeTooltip: true }+ )+ chart.hoverAtIndex(0)+ const tooltipEl = await waitForHogChartTooltip()+ expect(tooltipEl.querySelector('[data-attr="custom-boxplot-user-tooltip"]')).not.toBeNull()+ expect(userTooltip).toHaveBeenCalled()+ })+ })++ describe('click', () => {+ it('invokes onBoxClick with the clicked datum and cross-series data', async () => {+ const onBoxClick = jest.fn()+ const { chart } = renderHogChart(+ <BoxPlot series={TWO_SERIES} labels={LABELS} theme={THEME} onBoxClick={onBoxClick} />+ )+ await chart.clickAtIndex(1)+ await waitFor(() => expect(onBoxClick).toHaveBeenCalled())+ const arg = onBoxClick.mock.calls[0][0] as BoxPlotClickData+ expect(arg.dataIndex).toBe(1)+ expect(arg.label).toBe('Tue')+ // `series` is the primary (first visible) series — matches BarChart's onPointClick contract.+ expect(arg.series.key).toBe('a')+ expect(arg.datum.median).toBe(50)+ // crossSeriesData carries every visible series's datum at this column.+ expect(arg.crossSeriesData).toHaveLength(2)+ expect(arg.crossSeriesData.map((c) => c.series.key)).toEqual(['a', 'b'])+ expect(arg.crossSeriesData.map((c) => c.datum.median)).toEqual([50, 45])+ })+ })++ describe('error handling', () => {+ let consoleErrorSpy: jest.SpyInstance+ beforeEach(() => {+ consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})+ })+ afterEach(() => {+ consoleErrorSpy.mockRestore()+ })++ it('reports render errors through onError', async () => {+ const onError = jest.fn()+ const tooltip = (): React.ReactNode => {+ throw new Error('boom')+ }+ const { chart } = renderHogChart(+ <BoxPlot series={TWO_SERIES} labels={LABELS} theme={THEME} tooltip={tooltip} onError={onError} />+ )+ chart.hoverAtIndex(1)+ await waitFor(() => expect(onError).toHaveBeenCalled())+ })+ })++ describe('children', () => {+ it('renders custom overlay children', () => {+ const { chart } = renderHogChart(+ <BoxPlot series={TWO_SERIES} labels={LABELS} theme={THEME}>+ <div data-attr="custom-box-child" />+ </BoxPlot>+ )+ expect(chart.element.querySelector('[data-attr="custom-box-child"]')).not.toBeNull()+ })+ })+})diff --git a/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlot.tsx b/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlot.tsxnew file mode 100644index 000000000000..1bcfcff6902f--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlot.tsx@@ -0,0 +1,386 @@+import React, { useCallback, useMemo } from 'react'++import { drawBoxes, drawBoxHighlight, drawGrid, type DrawContext } from '../../core/canvas-renderer'+import { Chart } from '../../core/Chart'+import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'+import { dimColor } from '../../core/color-utils'+import { createBarScales, type BarScaleSet, yTickCountForHeight } from '../../core/scales'+import type {+ ChartConfig,+ ChartDimensions,+ ChartDrawArgs,+ ChartScales,+ ChartTheme,+ CreateScalesFn,+ PointClickData,+ ResolvedSeries,+ Series,+ TooltipContext,+} from '../../core/types'+import { BoxPlotTooltip } from './BoxPlotTooltip'+import { computeBoxRect, computeSeriesBoxes, type BoxPlotDatum, type BoxPlotSeries } from './computeBoxLayout'+import { seriesKeysAtCursor } from './utils/boxes-under-cursor'++/** Stash slot — survives a render via `ChartScales._private` so drawStatic/drawHover+ * can read the d3 scales and the per-series datums lookup without recomputing them. */+interface BoxPlotPrivate {+ __boxPlot: {+ scales: BarScaleSet+ datumsByKey: Map<string, (BoxPlotDatum | null)[]>+ grouped: boolean+ }+}++/** Meta attached to the inner adapter `Series` we hand to the `Chart` base — carries the+ * original six-number summaries indexed by x-position, plus any user-supplied meta. Exported+ * so consumers with a custom `tooltip` can read the original datum back out of+ * `entry.series.meta?.datums?.[ctx.dataIndex]`. */+export interface BoxPlotAdaptedMeta<Meta = unknown> {+ datums: (BoxPlotDatum | null)[]+ user?: Meta+}++/** Tooltip context handed to consumer-supplied `tooltip` callbacks. Same shape as+ * `TooltipContext` but with the `BoxPlotAdaptedMeta` `Meta` parameter baked in so consumers+ * don't have to redeclare it. */+export type BoxPlotTooltipContext<Meta = unknown> = TooltipContext<BoxPlotAdaptedMeta<Meta>>++/** Chart-level config. `axisOrientation` is always vertical for BoxPlot — there's no+ * horizontal mode — so it's omitted from the consumer-visible config to avoid silently+ * ignored values. */+export interface BoxPlotConfig extends Omit<ChartConfig, 'axisOrientation'> {+ /** Mean marker radius in CSS pixels. Defaults to 3. */+ meanRadius?: number+ /** Whisker cap width as a fraction of the box width. Defaults to 0.6. */+ whiskerCapRatio?: number+ /** Box outline / whisker stroke width. Defaults to 1.5. */+ boxStrokeWidth?: number+}++export interface BoxPlotClickData<Meta = unknown> {+ /** The *first visible series* at the clicked column — matches BarChart's `onPointClick`+ * contract. In grouped mode this is **not necessarily the series under the cursor**: when+ * the user clicks series B's sub-band, `series` is still A. The product layer should+ * narrow via `crossSeriesData` + the cursor x if it needs the precise box. */+ series: BoxPlotSeries<Meta>+ /** Index of `series` in the input `series` array (first-visible, not under-cursor). */+ seriesIndex: number+ /** Index along the x-axis (into `labels`). */+ dataIndex: number+ /** The x-axis label at this index. */+ label: string+ /** The six-number summary on `series` at this column. */+ datum: BoxPlotDatum+ /** All visible boxes at this column, in render order, for cross-series comparisons. */+ crossSeriesData: { series: BoxPlotSeries<Meta>; datum: BoxPlotDatum }[]+}++export interface BoxPlotProps<Meta = unknown> {+ series: BoxPlotSeries<Meta>[]+ labels: string[]+ theme: ChartTheme+ config?: BoxPlotConfig+ /** Optional custom tooltip. Receives the adapter `TooltipContext`; consumers can read+ * the original datum back out via `entry.series.meta?.datums?.[ctx.dataIndex]`. */+ tooltip?: (ctx: BoxPlotTooltipContext<Meta>) => React.ReactNode+ /** Click callback — fired when the user clicks a box. The product layer wires this to+ * the persons modal in the BoxPlot insight. */+ onBoxClick?: (data: BoxPlotClickData<Meta>) => void+ className?: string+ dataAttr?: string+ children?: React.ReactNode+ onError?: (error: Error, info: React.ErrorInfo) => void+}++export function BoxPlot<Meta = unknown>({ onError, ...rest }: BoxPlotProps<Meta>): React.ReactElement {+ return (+ <ChartErrorBoundary onError={onError}>+ <BoxPlotInner {...rest} />+ </ChartErrorBoundary>+ )+}++function BoxPlotInner<Meta = unknown>({+ series,+ labels,+ theme,+ config,+ tooltip,+ onBoxClick,+ className,+ dataAttr,+ children,+}: Omit<BoxPlotProps<Meta>, 'onError'>): React.ReactElement {+ const {+ yScaleType = 'linear',+ showGrid = false,+ meanRadius = 3,+ whiskerCapRatio = 0.6,+ boxStrokeWidth = 1.5,+ } = config ?? {}++ const grouped = series.filter((s) => !s.visibility?.excluded).length > 1++ const adaptedSeries = useMemo<Series<BoxPlotAdaptedMeta<Meta>>[]>(+ () =>+ series.map((s) => ({+ key: s.key,+ label: s.label,+ color: s.color,+ data: Array.from({ length: labels.length }, (_, i) => {+ const datum = s.data[i]+ return datum && Number.isFinite(datum.median) ? datum.median : Number.NaN+ }),+ meta: { datums: s.data, user: s.meta },+ visibility: s.visibility,+ })),+ [series, labels.length]+ )++ /** Synthetic series carrying min/max samples so the y-domain spans every whisker, not just+ * the medians on `adaptedSeries.data`. Fed to `createBarScales` (as `stackedSeries`) for+ * the d3 scale and to `Chart` (as `valueRangeSeries`) for `useChartMargins` tick sizing —+ * one source, two call sites. */+ const valueRangeSeries = useMemo<Series[]>(() => {+ const out: Series[] = []+ for (const s of series) {+ if (s.visibility?.excluded) {+ continue+ }+ const mins: number[] = []+ const maxs: number[] = []+ for (const datum of s.data) {+ if (!datum) {+ continue+ }+ if (Number.isFinite(datum.min)) {+ mins.push(datum.min)+ }+ if (Number.isFinite(datum.max)) {+ maxs.push(datum.max)+ }+ }+ if (mins.length > 0) {+ out.push({ key: `${s.key}__min`, label: s.label, data: mins })+ }+ if (maxs.length > 0) {+ out.push({ key: `${s.key}__max`, label: s.label, data: maxs })+ }+ }+ return out+ }, [series])++ const { datumsByKey, seriesByKey } = useMemo(() => {+ const datums = new Map<string, (BoxPlotDatum | null)[]>()+ const seriesMap = new Map<string, BoxPlotSeries<Meta>>()+ for (const s of series) {+ datums.set(s.key, s.data)+ seriesMap.set(s.key, s)+ }+ return { datumsByKey: datums, seriesByKey: seriesMap }+ }, [series])++ const createScales: CreateScalesFn = useCallback(+ (coloredSeries: ResolvedSeries[], scaleLabels: string[], dimensions: ChartDimensions): ChartScales => {+ const barLayout = grouped ? 'grouped' : 'stacked'+ const d3Scales = createBarScales(coloredSeries, scaleLabels, dimensions, {+ scaleType: yScaleType,+ barLayout,+ axisOrientation: 'vertical',+ stackedSeries: valueRangeSeries.length > 0 ? valueRangeSeries : undefined,+ })++ const yTickCount = yTickCountForHeight(dimensions.plotHeight)+ const priv: BoxPlotPrivate = {+ __boxPlot: { scales: d3Scales, datumsByKey, grouped },+ }++ return {+ x: (label: string, seriesKey?: string) => {+ const start = d3Scales.band(label)+ if (start == null) {+ return undefined+ }+ if (grouped && seriesKey != null) {+ const groupOffset = d3Scales.group?.(seriesKey)+ const groupBandwidth = d3Scales.group?.bandwidth()+ if (groupOffset != null && groupBandwidth != null) {+ return start + groupOffset + groupBandwidth / 2+ }+ }+ return start + d3Scales.band.bandwidth() / 2+ },+ y: (value: number) => d3Scales.value(value),+ yTicks: () => d3Scales.value.ticks?.(yTickCount) ?? [],+ _private: priv,+ }+ },+ [grouped, yScaleType, valueRangeSeries, datumsByKey]+ )++ const drawStatic = useCallback(+ ({ ctx, dimensions, scales, series: coloredSeries, labels: drawLabels, theme }: ChartDrawArgs) => {+ const priv = (scales._private as BoxPlotPrivate | undefined)?.__boxPlot+ if (!priv) {+ return+ }++ const baseDrawCtx: DrawContext = {+ ctx,+ dimensions,+ xScale: (label: string) => {+ const start = priv.scales.band(label)+ return start == null ? undefined : start + priv.scales.band.bandwidth() / 2+ },+ yScale: priv.scales.value,+ labels: drawLabels,+ }++ if (showGrid) {+ drawGrid(baseDrawCtx, { gridColor: theme.gridColor, orientation: 'vertical' })+ }++ for (const s of coloredSeries) {+ if (s.visibility?.excluded) {+ continue+ }+ const datums = priv.datumsByKey.get(s.key)+ if (!datums) {+ continue+ }+ const boxes = computeSeriesBoxes({+ seriesKey: s.key,+ data: datums,+ labels: drawLabels,+ scales: priv.scales,+ grouped: priv.grouped,+ })+ drawBoxes(ctx, boxes, {+ color: s.color,+ fillColor: dimColor(s.color, 0.25),+ meanFillColor: dimColor(s.color, 0.5),+ meanRadius,+ whiskerCapRatio,+ lineWidth: boxStrokeWidth,+ })+ }+ },+ [showGrid, meanRadius, whiskerCapRatio, boxStrokeWidth]+ )++ const drawHover = useCallback(+ ({+ ctx,+ scales,+ series: coloredSeries,+ labels: drawLabels,+ hoverIndex,+ hoverPosition,+ }: ChartDrawArgs): boolean => {+ const priv = (scales._private as BoxPlotPrivate | undefined)?.__boxPlot+ if (!priv || hoverIndex < 0 || !hoverPosition) {+ return false+ }+ const hoveredLabel = drawLabels[hoverIndex]++ // Same band-axis hit-test as BarChart's hover layer — anchors the highlight to+ // whichever group slot the cursor lines up with. `seriesKeysAtCursor` is now+ // band-only, so we only materialise the full `BoxRect` for hit series in the loop.+ const hits = seriesKeysAtCursor<Meta>({+ series,+ label: hoveredLabel,+ dataIndex: hoverIndex,+ cursor: hoverPosition,+ scales: priv.scales,+ grouped: priv.grouped,+ })+ if (hits.size === 0) {+ return false+ }+ let drewAny = false+ for (const s of coloredSeries) {+ if (s.visibility?.excluded || !hits.has(s.key)) {+ continue+ }+ const datums = priv.datumsByKey.get(s.key)+ const datum = datums?.[hoverIndex]+ if (!datum) {+ continue+ }+ const box = computeBoxRect({+ seriesKey: s.key,+ label: hoveredLabel,+ dataIndex: hoverIndex,+ datum,+ scales: priv.scales,+ grouped: priv.grouped,+ })+ if (!box) {+ continue+ }+ drawBoxHighlight(ctx, box, dimColor(s.color, 0.25))+ drewAny = true+ }+ return drewAny+ },+ [series]+ )++ const renderTooltip = useCallback(+ (ctx: TooltipContext<BoxPlotAdaptedMeta<Meta>>) => (+ <BoxPlotTooltip<Meta> ctx={ctx} userTooltip={tooltip} grouped={grouped} />+ ),+ [tooltip, grouped]+ )++ const onPointClick = useCallback(+ (data: PointClickData<BoxPlotAdaptedMeta<Meta>>): void => {+ if (!onBoxClick) {+ return+ }+ const primaryDatums = data.series.meta?.datums+ const datum = primaryDatums?.[data.dataIndex]+ const primarySeries = seriesByKey.get(data.series.key)+ if (!datum || !primarySeries) {+ return+ }+ const crossSeriesData: BoxPlotClickData<Meta>['crossSeriesData'] = []+ for (const entry of data.crossSeriesData) {+ const ds = entry.series.meta?.datums?.[data.dataIndex]+ const origin = seriesByKey.get(entry.series.key)+ if (!ds || !origin) {+ continue+ }+ crossSeriesData.push({ series: origin, datum: ds })+ }+ onBoxClick({+ series: primarySeries,+ seriesIndex: data.seriesIndex,+ dataIndex: data.dataIndex,+ label: data.label,+ datum,+ crossSeriesData,+ })+ },+ [onBoxClick, seriesByKey]+ )++ return (+ <Chart<BoxPlotAdaptedMeta<Meta>>+ series={adaptedSeries}+ labels={labels}+ config={{ ...config, axisOrientation: 'vertical' }}+ theme={theme}+ createScales={createScales}+ drawStatic={drawStatic}+ drawHover={drawHover}+ tooltip={renderTooltip}+ onPointClick={onPointClick}+ valueRangeSeries={valueRangeSeries.length > 0 ? valueRangeSeries : undefined}+ className={className}+ dataAttr={dataAttr}+ >+ {children}+ </Chart>+ )+}diff --git a/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlotTooltip.tsx b/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlotTooltip.tsxnew file mode 100644index 000000000000..a46a9422d1c4--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/BoxPlot/BoxPlotTooltip.tsx@@ -0,0 +1,106 @@+import React from 'react'++import { useChartLayout } from '../../core/chart-context'+import type { TooltipContext } from '../../core/types'+import type { BoxPlotAdaptedMeta } from './BoxPlot'+import type { BoxPlotDatum } from './computeBoxLayout'++const DEFAULT_TOOLTIP_BG = '#1d2330'+const DEFAULT_TOOLTIP_COLOR = '#ffffff'++/** Rows shown per box, in the same order the legacy BoxPlotChart used. */+const ROWS: { label: string; key: keyof BoxPlotDatum }[] = [+ { label: 'Max', key: 'max' },+ { label: '75th percentile', key: 'p75' },+ { label: 'Median', key: 'median' },+ { label: 'Mean', key: 'mean' },+ { label: '25th percentile', key: 'p25' },+ { label: 'Min', key: 'min' },+]++export interface BoxPlotTooltipProps<Meta = unknown> {+ ctx: TooltipContext<BoxPlotAdaptedMeta<Meta>>+ /** Optional consumer override — passes the original TooltipContext through so the consumer+ * can render their own template while still reading the original BoxPlotDatum from the+ * adapter meta on each series. */+ userTooltip?: (ctx: TooltipContext<BoxPlotAdaptedMeta<Meta>>) => React.ReactNode+ /** Whether multiple series are being shown — drives whether each box's series label is+ * printed in the header above its stats. */+ grouped: boolean+}++function defaultFormatValue(v: number): string {+ return Number.isFinite(v) ? v.toLocaleString() : '—'+}++export function BoxPlotTooltip<Meta = unknown>({+ ctx,+ userTooltip,+ grouped,+}: BoxPlotTooltipProps<Meta>): React.ReactElement | null {+ const { theme } = useChartLayout()++ if (userTooltip) {+ return <>{userTooltip(ctx)}</>+ }++ const entries: { key: string; color: string; label: string; datum: BoxPlotDatum }[] = []+ for (const seriesEntry of ctx.seriesData) {+ if (seriesEntry.series.visibility?.tooltip === false) {+ continue+ }+ const datum = seriesEntry.series.meta?.datums?.[ctx.dataIndex]+ if (!datum) {+ continue+ }+ entries.push({+ key: seriesEntry.series.key,+ color: seriesEntry.color,+ label: seriesEntry.series.label,+ datum,+ })+ }+ if (entries.length === 0) {+ return null+ }++ return (+ <div+ className="px-3 py-2 rounded-lg shadow-lg text-[13px]"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ backgroundColor: theme.tooltipBackground ?? DEFAULT_TOOLTIP_BG,+ color: theme.tooltipColor ?? DEFAULT_TOOLTIP_COLOR,+ }}+ data-attr="hog-chart-boxplot-tooltip"+ >+ <div className="font-semibold mb-1">{ctx.label}</div>+ {entries.map((entry, i) => (+ <div key={entry.key} className={i > 0 ? 'mt-2' : undefined}>+ {grouped && (+ <div className="flex items-center gap-2 mb-1">+ <span+ className="inline-block size-2 rounded-full"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ backgroundColor: entry.color }}+ />+ <span className="font-semibold">{entry.label}</span>+ </div>+ )}+ <table className="border-collapse">+ <tbody>+ {ROWS.map((row) => (+ <tr key={row.key}>+ <td className="pr-3 opacity-70">{row.label}</td>+ <td className="font-medium">+ {defaultFormatValue(entry.datum[row.key] as number)}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ ))}+ </div>+ )+}diff --git a/frontend/src/lib/hog-charts/charts/BoxPlot/computeBoxLayout.test.ts b/frontend/src/lib/hog-charts/charts/BoxPlot/computeBoxLayout.test.tsnew file mode 100644index 000000000000..2842c525f7aa--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/BoxPlot/computeBoxLayout.test.ts@@ -0,0 +1,273 @@+import { createBarScales } from '../../core/scales'+import type { ChartDimensions } from '../../core/types'+import { makeSeries } from '../../testing'+import { computeBoxRect, computeSeriesBoxes, type BoxPlotDatum } from './computeBoxLayout'++const PIXEL_TEST_DIMENSIONS: ChartDimensions = {+ width: 400,+ height: 200,+ plotLeft: 0,+ plotTop: 0,+ plotWidth: 400,+ plotHeight: 200,+}++function datum(overrides: Partial<BoxPlotDatum> = {}): BoxPlotDatum {+ return { min: 0, p25: 25, median: 50, mean: 55, p75: 75, max: 100, ...overrides }+}++// Synthetic min/max samples flow into `seriesValueRange` via the `stackedSeries` option+// so the y-domain spans whiskers, not just medians — exactly the same trick the BoxPlot+// component uses at the component layer.+function makeScales(+ labels: string[],+ seriesSpec: { key: string; data: BoxPlotDatum[] }[],+ barLayout: 'grouped' | 'stacked',+ dims = PIXEL_TEST_DIMENSIONS+): ReturnType<typeof createBarScales> {+ const coloredSeries = seriesSpec.map((s) => makeSeries({ key: s.key, data: [0] }))+ const valueRange = seriesSpec.flatMap((s) => [+ { key: `${s.key}__min`, label: s.key, data: s.data.map((d) => d.min) },+ { key: `${s.key}__max`, label: s.key, data: s.data.map((d) => d.max) },+ ])+ return createBarScales(coloredSeries, labels, dims, {+ barLayout,+ axisOrientation: 'vertical',+ stackedSeries: valueRange,+ })+}++describe('computeBoxRect', () => {+ it('puts the box top at p75 and bottom at p25 (y-axis inverted)', () => {+ const data = [datum({ min: 0, p25: 20, median: 50, mean: 55, p75: 80, max: 100 })]+ const scales = makeScales(['Mon'], [{ key: 'a', data }], 'stacked')+ const box = computeBoxRect({+ seriesKey: 'a',+ label: 'Mon',+ dataIndex: 0,+ datum: data[0]!,+ scales,+ grouped: false,+ })!+ expect(box).not.toBeNull()+ // y-axis is inverted, so the p75 pixel is *smaller* than the p25 pixel+ expect(box.top).toBe(scales.value(80))+ expect(box.bottom).toBe(scales.value(20))+ expect(box.top).toBeLessThan(box.bottom)+ })++ it('positions the median line and mean marker at their values', () => {+ const data = [datum({ p25: 20, median: 50, mean: 60, p75: 80 })]+ const scales = makeScales(['Mon'], [{ key: 'a', data }], 'stacked')+ const box = computeBoxRect({+ seriesKey: 'a',+ label: 'Mon',+ dataIndex: 0,+ datum: data[0]!,+ scales,+ grouped: false,+ })!+ expect(box.medianY).toBeCloseTo(scales.value(50), 5)+ expect(box.mean.y).toBeCloseTo(scales.value(60), 5)+ expect(box.mean.x).toBeCloseTo(box.x + box.width / 2, 5)+ })++ it('extends whiskers to min and max', () => {+ const data = [datum({ min: 5, p25: 20, median: 50, mean: 55, p75: 80, max: 95 })]+ const scales = makeScales(['Mon'], [{ key: 'a', data }], 'stacked')+ const box = computeBoxRect({+ seriesKey: 'a',+ label: 'Mon',+ dataIndex: 0,+ datum: data[0]!,+ scales,+ grouped: false,+ })!+ expect(box.whiskerTop).toBeCloseTo(scales.value(95), 5)+ expect(box.whiskerBottom).toBeCloseTo(scales.value(5), 5)+ expect(box.whiskerTop).toBeLessThan(box.top)+ expect(box.whiskerBottom).toBeGreaterThan(box.bottom)+ })++ it('uses the full band width when not grouped', () => {+ const data = [datum()]+ const scales = makeScales(['Mon'], [{ key: 'a', data }], 'stacked')+ const box = computeBoxRect({+ seriesKey: 'a',+ label: 'Mon',+ dataIndex: 0,+ datum: data[0]!,+ scales,+ grouped: false,+ })!+ expect(box.width).toBeCloseTo(scales.band.bandwidth(), 5)+ expect(box.x).toBeCloseTo(scales.band('Mon')!, 5)+ })++ it('uses the group sub-band when grouped', () => {+ const aData = [datum()]+ const bData = [datum()]+ const scales = makeScales(+ ['Mon'],+ [+ { key: 'a', data: aData },+ { key: 'b', data: bData },+ ],+ 'grouped'+ )+ const boxA = computeBoxRect({+ seriesKey: 'a',+ label: 'Mon',+ dataIndex: 0,+ datum: aData[0]!,+ scales,+ grouped: true,+ })!+ const boxB = computeBoxRect({+ seriesKey: 'b',+ label: 'Mon',+ dataIndex: 0,+ datum: bData[0]!,+ scales,+ grouped: true,+ })!+ expect(boxA.width).toBeCloseTo(scales.group!.bandwidth(), 5)+ expect(boxB.width).toBeCloseTo(scales.group!.bandwidth(), 5)+ // Two grouped boxes within a single band must not overlap on the band axis.+ expect(boxA.x + boxA.width).toBeLessThanOrEqual(boxB.x + 0.0001)+ })++ it('returns null for unknown labels (band scale miss)', () => {+ const data = [datum()]+ const scales = makeScales(['Mon'], [{ key: 'a', data }], 'stacked')+ const box = computeBoxRect({+ seriesKey: 'a',+ label: 'Friday',+ dataIndex: 0,+ datum: data[0]!,+ scales,+ grouped: false,+ })+ expect(box).toBeNull()+ })++ it('returns null when grouped but the series is missing from the group scale', () => {+ const data = [datum()]+ const scales = makeScales(['Mon'], [{ key: 'a', data }], 'stacked')+ // Stacked layout has no group scale — caller asking for grouped should miss cleanly.+ const box = computeBoxRect({+ seriesKey: 'a',+ label: 'Mon',+ dataIndex: 0,+ datum: data[0]!,+ scales,+ grouped: true,+ })+ expect(box).toBeNull()+ })++ it('returns null when any of the six numbers is non-finite', () => {+ const data = [datum({ p25: Number.NaN })]+ const scales = makeScales(['Mon'], [{ key: 'a', data: [datum()] }], 'stacked')+ const box = computeBoxRect({+ seriesKey: 'a',+ label: 'Mon',+ dataIndex: 0,+ datum: data[0]!,+ scales,+ grouped: false,+ })+ expect(box).toBeNull()+ })++ it('collapses to a flat box when all-equal values', () => {+ const data = [{ min: 50, p25: 50, median: 50, mean: 50, p75: 50, max: 50 }]+ const scales = makeScales(['Mon'], [{ key: 'a', data }], 'stacked')+ const box = computeBoxRect({+ seriesKey: 'a',+ label: 'Mon',+ dataIndex: 0,+ datum: data[0]!,+ scales,+ grouped: false,+ })!+ expect(box.top).toBeCloseTo(box.bottom, 5)+ expect(box.whiskerTop).toBeCloseTo(box.top, 5)+ expect(box.whiskerBottom).toBeCloseTo(box.bottom, 5)+ expect(box.medianY).toBeCloseTo(box.top, 5)+ })++ it('handles degenerate inverted p25 > p75 by always reporting top < bottom', () => {+ const data = [{ min: 0, p25: 80, median: 50, mean: 50, p75: 20, max: 100 }]+ const scales = makeScales(['Mon'], [{ key: 'a', data: [datum()] }], 'stacked')+ const box = computeBoxRect({+ seriesKey: 'a',+ label: 'Mon',+ dataIndex: 0,+ datum: data[0]!,+ scales,+ grouped: false,+ })!+ expect(box.top).toBeLessThanOrEqual(box.bottom)+ })++ it('preserves dataIndex on the result', () => {+ const data: BoxPlotDatum[] = [datum(), datum(), datum()]+ const scales = makeScales(['Mon', 'Tue', 'Wed'], [{ key: 'a', data }], 'stacked')+ const box = computeBoxRect({+ seriesKey: 'a',+ label: 'Wed',+ dataIndex: 2,+ datum: data[2],+ scales,+ grouped: false,+ })!+ expect(box.dataIndex).toBe(2)+ })+})++describe('computeSeriesBoxes', () => {+ it('drops null and unrenderable indices', () => {+ const labels = ['Mon', 'Tue', 'Wed']+ const data: (BoxPlotDatum | null)[] = [datum(), null, datum()]+ // makeScales only needs the value-range samples — pass the non-null entries.+ const scales = makeScales(labels, [{ key: 'a', data: [datum(), datum()] }], 'stacked')+ const boxes = computeSeriesBoxes({+ seriesKey: 'a',+ data,+ labels,+ scales,+ grouped: false,+ })+ expect(boxes.map((b) => b.dataIndex)).toEqual([0, 2])+ })++ it('emits one box per non-null index', () => {+ const labels = ['Mon', 'Tue', 'Wed']+ const data: BoxPlotDatum[] = [datum(), datum(), datum()]+ const scales = makeScales(labels, [{ key: 'a', data }], 'stacked')+ const boxes = computeSeriesBoxes({+ seriesKey: 'a',+ data,+ labels,+ scales,+ grouped: false,+ })+ expect(boxes).toHaveLength(3)+ })++ it('handles a single-point series (one label)', () => {+ const labels = ['only']+ const data: BoxPlotDatum[] = [datum()]+ const scales = makeScales(labels, [{ key: 'a', data }], 'stacked')+ const boxes = computeSeriesBoxes({+ seriesKey: 'a',+ data,+ labels,+ scales,+ grouped: false,+ })+ expect(boxes).toHaveLength(1)+ expect(boxes[0].dataIndex).toBe(0)+ })+})diff --git a/frontend/src/lib/hog-charts/charts/BoxPlot/computeBoxLayout.ts b/frontend/src/lib/hog-charts/charts/BoxPlot/computeBoxLayout.tsnew file mode 100644index 000000000000..784296783606--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/BoxPlot/computeBoxLayout.ts@@ -0,0 +1,168 @@+import type { BoxPlotDatum as SchemaBoxPlotDatum } from '~/queries/schema/schema-general'++import type { BoxRect } from '../../core/canvas-renderer'+import type { BarScaleSet } from '../../core/scales'++export type { BoxRect }++/** Six-number summary plus an opaque `day` identifier. Structurally compatible with the+ * canonical `BoxPlotDatum` in `queries/schema-general.ts` (we only care about the six+ * numbers; `day` is the consumer-side key for click handlers / persons-modal labels). */+export type BoxPlotDatum = Pick<SchemaBoxPlotDatum, 'min' | 'p25' | 'median' | 'mean' | 'p75' | 'max'> & {+ /** Optional identifier for this x position (e.g. ISO date). The chart treats it as opaque. */+ day?: string+}++/** Series shape for the BoxPlot chart. Unlike the generic `Series` (whose `data` is+ * `number[]`), each entry is a six-number summary. `data.length` must match the chart's+ * `labels.length`; entries may be `null` for missing x positions. */+export interface BoxPlotSeries<Meta = unknown> {+ /** Unique identifier — used for React keys, scale group keys, and tooltip joins. */+ key: string+ /** Human-readable label used in legends/tooltips. */+ label: string+ /** Optional CSS color. When omitted (or empty), the chart picks one from `theme.colors`. */+ color?: string+ /** One six-number summary per x label, or `null` for missing data at that index. */+ data: (BoxPlotDatum | null)[]+ /** Free-form metadata flowed through to tooltip / click handlers. */+ meta?: Meta+ /** Visibility controls. Mirrors `Series.visibility` but with only the flags BoxPlot honors. */+ visibility?: {+ excluded?: boolean+ tooltip?: boolean+ }+}++interface BandSlot {+ x: number+ width: number+}++/** Resolve only the band-axis extent of a (series, x) slot. Cheap — touches the band/group+ * scales and nothing on the value axis — so callers like band-only hit-testing don't pay+ * for six value-axis lookups they'd immediately throw away. */+export function computeBoxBand(+ seriesKey: string,+ label: string,+ scales: BarScaleSet,+ grouped: boolean+): BandSlot | null {+ const bandStart = scales.band(label)+ if (bandStart == null) {+ return null+ }+ if (grouped) {+ const groupOffset = scales.group?.(seriesKey)+ const groupBandwidth = scales.group?.bandwidth()+ if (groupOffset == null || groupBandwidth == null) {+ return null+ }+ return { x: bandStart + groupOffset, width: groupBandwidth }+ }+ return { x: bandStart, width: scales.band.bandwidth() }+}++export interface ComputeBoxRectOptions {+ seriesKey: string+ label: string+ dataIndex: number+ datum: BoxPlotDatum+ scales: BarScaleSet+ /** Whether the chart is in grouped mode (multiple series → side-by-side boxes within a band). */+ grouped: boolean+}++/** Single-box geometry. Pure: takes already-built scales and returns pixel coordinates only.+ * Returns `null` when any of (band, group offset, value pixel) can't be resolved — usually+ * the series isn't in the group scale, or one of the six numbers is non-finite. */+export function computeBoxRect({+ seriesKey,+ label,+ dataIndex,+ datum,+ scales,+ grouped,+}: ComputeBoxRectOptions): BoxRect | null {+ if (+ !Number.isFinite(datum.min) ||+ !Number.isFinite(datum.max) ||+ !Number.isFinite(datum.p25) ||+ !Number.isFinite(datum.p75)+ ) {+ return null+ }+ if (!Number.isFinite(datum.median) || !Number.isFinite(datum.mean)) {+ return null+ }+ const slot = computeBoxBand(seriesKey, label, scales, grouped)+ if (!slot) {+ return null+ }++ const p25Y = scales.value(datum.p25)+ const p75Y = scales.value(datum.p75)+ const medianY = scales.value(datum.median)+ const meanY = scales.value(datum.mean)+ const maxY = scales.value(datum.max)+ const minY = scales.value(datum.min)+ if (!Number.isFinite(p25Y) || !Number.isFinite(p75Y) || !Number.isFinite(medianY) || !Number.isFinite(meanY)) {+ return null+ }+ if (!Number.isFinite(maxY) || !Number.isFinite(minY)) {+ return null+ }++ // y-axis is inverted (larger value = smaller pixel) — `top` is the p75 pixel+ // when p75 >= p25 (the normal case), but be defensive against degenerate input.+ const top = Math.min(p25Y, p75Y)+ const bottom = Math.max(p25Y, p75Y)+ const whiskerTop = Math.min(minY, maxY)+ const whiskerBottom = Math.max(minY, maxY)++ return {+ x: slot.x,+ width: slot.width,+ top,+ bottom,+ medianY,+ mean: { x: slot.x + slot.width / 2, y: meanY },+ whiskerTop,+ whiskerBottom,+ dataIndex,+ }+}++export interface ComputeSeriesBoxesOptions {+ seriesKey: string+ data: (BoxPlotDatum | null)[]+ labels: string[]+ scales: BarScaleSet+ grouped: boolean+}++/** Lays out every renderable box for one series. Skipped indices (`null` datum or+ * unresolvable scales) are dropped from the result — the caller can join back to the+ * original `data` via `BoxRect.dataIndex`. */+export function computeSeriesBoxes({ seriesKey, data, labels, scales, grouped }: ComputeSeriesBoxesOptions): BoxRect[] {+ const out: BoxRect[] = []+ const len = Math.min(data.length, labels.length)+ for (let i = 0; i < len; i++) {+ const datum = data[i]+ if (!datum) {+ continue+ }+ const rect = computeBoxRect({+ seriesKey,+ label: labels[i],+ dataIndex: i,+ datum,+ scales,+ grouped,+ })+ if (rect) {+ out.push(rect)+ }+ }+ return out+}diff --git a/frontend/src/lib/hog-charts/charts/BoxPlot/utils/boxes-under-cursor.test.ts b/frontend/src/lib/hog-charts/charts/BoxPlot/utils/boxes-under-cursor.test.tsnew file mode 100644index 000000000000..64925c524af2--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/BoxPlot/utils/boxes-under-cursor.test.ts@@ -0,0 +1,146 @@+import { createBarScales } from '../../../core/scales'+import type { ChartDimensions } from '../../../core/types'+import { makeSeries } from '../../../testing'+import type { BoxPlotDatum, BoxPlotSeries } from '../computeBoxLayout'+import { cursorInsideBoxBand, seriesKeysAtCursor } from './boxes-under-cursor'++const DIMS: ChartDimensions = {+ width: 400,+ height: 200,+ plotLeft: 0,+ plotTop: 0,+ plotWidth: 400,+ plotHeight: 200,+}++function datum(overrides: Partial<BoxPlotDatum> = {}): BoxPlotDatum {+ return { min: 0, p25: 25, median: 50, mean: 55, p75: 75, max: 100, ...overrides }+}++function makeScales(+ labels: string[],+ seriesSpec: { key: string; data: (BoxPlotDatum | null)[] }[],+ barLayout: 'grouped' | 'stacked' = seriesSpec.length > 1 ? 'grouped' : 'stacked'+): ReturnType<typeof createBarScales> {+ const coloredSeries = seriesSpec.map((s) => makeSeries({ key: s.key, data: [0] }))+ const valueRange: { key: string; label: string; data: number[] }[] = []+ for (const s of seriesSpec) {+ for (const d of s.data) {+ if (d) {+ valueRange.push({ key: `${s.key}_${valueRange.length}`, label: s.key, data: [d.min, d.max] })+ }+ }+ }+ return createBarScales(coloredSeries, labels, DIMS, {+ barLayout,+ axisOrientation: 'vertical',+ stackedSeries: valueRange,+ })+}++describe('cursorInsideBoxBand', () => {+ const box = { x: 10, width: 40 }+ it.each([+ ['cursor left of box', { x: 5 }, false],+ ['cursor on left edge', { x: 10 }, true],+ ['cursor inside box', { x: 30 }, true],+ ['cursor on right edge', { x: 50 }, true],+ ['cursor right of box', { x: 60 }, false],+ ])('%s', (_name, cursor, expected) => {+ expect(cursorInsideBoxBand(box, cursor)).toBe(expected)+ })+})++describe('seriesKeysAtCursor', () => {+ const LABELS = ['Mon', 'Tue']++ it('finds the box under the cursor in a grouped layout', () => {+ const series: BoxPlotSeries[] = [+ { key: 'a', label: 'A', data: [datum(), datum()] },+ { key: 'b', label: 'B', data: [datum(), datum()] },+ ]+ const scales = makeScales(LABELS, series)++ // Sub-band centers for series a and b in label "Mon".+ const bandStart = scales.band('Mon')!+ const groupBandwidth = scales.group!.bandwidth()+ const aCenter = bandStart + scales.group!('a')! + groupBandwidth / 2+ const bCenter = bandStart + scales.group!('b')! + groupBandwidth / 2++ const aHits = seriesKeysAtCursor({+ series,+ label: 'Mon',+ dataIndex: 0,+ cursor: { x: aCenter, y: 100 },+ scales,+ grouped: true,+ })+ const bHits = seriesKeysAtCursor({+ series,+ label: 'Mon',+ dataIndex: 0,+ cursor: { x: bCenter, y: 100 },+ scales,+ grouped: true,+ })+ expect(Array.from(aHits)).toEqual(['a'])+ expect(Array.from(bHits)).toEqual(['b'])+ })++ it('returns empty when the cursor is in a between-group gap', () => {+ const series: BoxPlotSeries[] = [+ { key: 'a', label: 'A', data: [datum(), datum()] },+ { key: 'b', label: 'B', data: [datum(), datum()] },+ ]+ const scales = makeScales(LABELS, series)+ const bandStart = scales.band('Mon')!+ // x just before the band starts — in the outer-padding gap.+ const gapX = bandStart - 5+ const hits = seriesKeysAtCursor({+ series,+ label: 'Mon',+ dataIndex: 0,+ cursor: { x: gapX, y: 100 },+ scales,+ grouped: true,+ })+ expect(hits.size).toBe(0)+ })++ it('skips excluded series', () => {+ const series: BoxPlotSeries[] = [+ { key: 'a', label: 'A', data: [datum(), datum()] },+ { key: 'b', label: 'B', data: [datum(), datum()], visibility: { excluded: true } },+ ]+ const scales = makeScales(LABELS, series, 'grouped')+ const bandStart = scales.band('Mon')!+ const groupBandwidth = scales.group!.bandwidth()+ // even at b's would-be center, b is excluded so it can't be a hit+ const bCenter = bandStart + (scales.group!('b') ?? 0) + groupBandwidth / 2+ const hits = seriesKeysAtCursor({+ series,+ label: 'Mon',+ dataIndex: 0,+ cursor: { x: bCenter, y: 100 },+ scales,+ grouped: true,+ })+ expect(hits.has('b')).toBe(false)+ })++ it('skips indices with null data', () => {+ const series: BoxPlotSeries[] = [{ key: 'a', label: 'A', data: [datum(), null] }]+ const scales = makeScales(LABELS, series, 'stacked')+ const bandStart = scales.band('Tue')!+ const cursorX = bandStart + scales.band.bandwidth() / 2+ const hits = seriesKeysAtCursor({+ series,+ label: 'Tue',+ dataIndex: 1,+ cursor: { x: cursorX, y: 100 },+ scales,+ grouped: false,+ })+ expect(hits.size).toBe(0)+ })+})diff --git a/frontend/src/lib/hog-charts/charts/BoxPlot/utils/boxes-under-cursor.ts b/frontend/src/lib/hog-charts/charts/BoxPlot/utils/boxes-under-cursor.tsnew file mode 100644index 000000000000..34deebbe41ad--- /dev/null+++ b/frontend/src/lib/hog-charts/charts/BoxPlot/utils/boxes-under-cursor.ts@@ -0,0 +1,44 @@+import type { BarScaleSet } from '../../../core/scales'+import { computeBoxBand } from '../computeBoxLayout'+import type { BoxPlotSeries } from '../computeBoxLayout'++/** Whether the cursor lies inside the band-axis extent of a box. Mirrors the+ * bar-chart pattern of resolving "which sub-band is under the cursor" with a+ * value-axis-agnostic check, so hovering above (or below) a tall whisker still+ * selects the right box. */+export function cursorInsideBoxBand(box: { x: number; width: number }, cursor: { x: number }): boolean {+ return cursor.x >= box.x && cursor.x <= box.x + box.width+}++export interface SeriesKeysAtCursorArgs<Meta> {+ series: BoxPlotSeries<Meta>[]+ label: string+ dataIndex: number+ cursor: { x: number; y: number }+ scales: BarScaleSet+ grouped: boolean+}++/** Returns the set of series keys whose box (at the given x-label) contains the cursor+ * on the band axis. Empty set means the cursor sits in a gap between groups — the+ * tooltip wrapper uses that to hide the tooltip rather than highlight all neighbouring+ * series. Uses `computeBoxBand` (band-axis only) — value-axis math is for the highlight+ * pass, not the hit-test. */+export function seriesKeysAtCursor<Meta>(args: SeriesKeysAtCursorArgs<Meta>): Set<string> {+ const { series, label, dataIndex, cursor, scales, grouped } = args+ const hits = new Set<string>()+ for (const s of series) {+ if (s.visibility?.excluded) {+ continue+ }+ const datum = s.data[dataIndex]+ if (!datum) {+ continue+ }+ const band = computeBoxBand(s.key, label, scales, grouped)+ if (band && cursorInsideBoxBand(band, cursor)) {+ hits.add(s.key)+ }+ }+ return hits+}diff --git a/frontend/src/lib/hog-charts/core/Chart.tsx b/frontend/src/lib/hog-charts/core/Chart.tsxindex d128faadfa4b..1ffe962c5915 100644--- a/frontend/src/lib/hog-charts/core/Chart.tsx+++ b/frontend/src/lib/hog-charts/core/Chart.tsx@@ -104,6 +104,11 @@ export interface ChartProps<Meta = unknown> {* axis (y in horizontal mode). Should be referentially stable; non-stable identities* invalidate the interaction memo on every render. */labelToCoord?: (label: string) => number | undefined+ /** Override the series fed into value-axis tick sizing (`useChartMargins`). Use when the+ * visible series's `data[i]` doesn't span the y-domain — e.g. BoxPlot passes synthetic+ * whisker min/max samples so the y-tick column fits the real value range, not just the+ * medians it draws on `series.data`. */+ valueRangeSeries?: Series[]}export function Chart<Meta = unknown>({@@ -122,6 +127,7 @@ export function Chart<Meta = unknown>({resolveValue,resolvePositionValue,labelToCoord,+ valueRangeSeries,}: ChartProps<Meta>): React.ReactElement {const {xTickFormatter,@@ -156,6 +162,7 @@ export function Chart<Meta = unknown>({yTickFormatter,axisOrientation,override: marginsOverride,+ valueRangeSeries,})const { canvasRef, overlayCanvasRef, wrapperRef, dimensions, ctx, overlayCtx } = useChartCanvas({ margins })diff --git a/frontend/src/lib/hog-charts/core/canvas-renderer.ts b/frontend/src/lib/hog-charts/core/canvas-renderer.tsindex 553104e7cee3..e9f0f5e23615 100644--- a/frontend/src/lib/hog-charts/core/canvas-renderer.ts+++ b/frontend/src/lib/hog-charts/core/canvas-renderer.ts@@ -594,6 +594,136 @@ export function drawHighlightPoint(ctx.fill()}+export interface DrawBoxOptions {+ /** Series base color — used for the box outline, whisker, median, and mean stroke. */+ color: string+ /** Box fill — typically the series color at reduced alpha. */+ fillColor: string+ /** Optional explicit median stroke color. Defaults to `color`. */+ medianColor?: string+ /** Optional mean marker fill. Defaults to `fillColor`. */+ meanFillColor?: string+ /** Mean marker radius in CSS pixels. Defaults to 3. */+ meanRadius?: number+ /** Line width for the box outline, whiskers, and median. Defaults to 1.5. */+ lineWidth?: number+ /** Width of the whisker caps (as a fraction of the box width). Defaults to 0.6. */+ whiskerCapRatio?: number+}++/** A laid-out box-and-whisker for a single (series, x) slot. Same shape contract as+ * {@link BarRect} — pre-computed pixel coordinates so the draw primitives don't touch scales. */+export interface BoxRect {+ x: number+ width: number+ top: number+ bottom: number+ medianY: number+ mean: { x: number; y: number }+ whiskerTop: number+ whiskerBottom: number+ dataIndex: number+}++/** Paint a whole series of box-and-whiskers, batching path operations so the number of+ * `beginPath`/`stroke` pairs is `4 + N` instead of `5N` (whisker stems, caps, box outlines,+ * and medians are each one shared path; mean markers stay per-box since each needs both+ * fill and stroke). Pure: takes pre-laid-out {@link BoxRect}s; no scale access. */+export function drawBoxes(ctx: CanvasRenderingContext2D, boxes: BoxRect[], options: DrawBoxOptions): void {+ if (boxes.length === 0) {+ return+ }+ const {+ color,+ fillColor,+ medianColor = color,+ meanFillColor = fillColor,+ meanRadius = 3,+ lineWidth = 1.5,+ whiskerCapRatio = 0.6,+ } = options++ ctx.lineWidth = lineWidth+ ctx.strokeStyle = color+ ctx.setLineDash([])++ // 1. Whisker stems — only emit a stem when the whisker extends past the box edge.+ ctx.beginPath()+ for (const box of boxes) {+ const centerX = box.x + box.width / 2+ if (box.whiskerTop < box.top) {+ ctx.moveTo(centerX, box.whiskerTop)+ ctx.lineTo(centerX, box.top)+ }+ if (box.whiskerBottom > box.bottom) {+ ctx.moveTo(centerX, box.bottom)+ ctx.lineTo(centerX, box.whiskerBottom)+ }+ }+ ctx.stroke()++ // 2. Whisker caps — skip the cap whenever the corresponding stem was skipped, otherwise+ // a cross-bar would paint on top of the box outline for collapsed distributions+ // (`min == p25` / `max == p75`).+ ctx.beginPath()+ for (const box of boxes) {+ const centerX = box.x + box.width / 2+ const capHalfWidth = (box.width * whiskerCapRatio) / 2+ if (box.whiskerTop < box.top) {+ ctx.moveTo(centerX - capHalfWidth, box.whiskerTop)+ ctx.lineTo(centerX + capHalfWidth, box.whiskerTop)+ }+ if (box.whiskerBottom > box.bottom) {+ ctx.moveTo(centerX - capHalfWidth, box.whiskerBottom)+ ctx.lineTo(centerX + capHalfWidth, box.whiskerBottom)+ }+ }+ ctx.stroke()++ // 3. Box rectangles (p25 → p75) — fill then outline. `fillRect` / `strokeRect` are+ // already optimal — no `beginPath` accumulation needed.+ ctx.fillStyle = fillColor+ for (const box of boxes) {+ const boxHeight = Math.max(0, box.bottom - box.top)+ if (boxHeight > 0 && box.width > 0) {+ ctx.fillRect(box.x, box.top, box.width, boxHeight)+ ctx.strokeRect(box.x, box.top, box.width, boxHeight)+ }+ }++ // 4. Median lines.+ ctx.strokeStyle = medianColor+ ctx.beginPath()+ for (const box of boxes) {+ const medianClamped = Math.max(box.top, Math.min(box.bottom, box.medianY))+ ctx.moveTo(box.x, medianClamped)+ ctx.lineTo(box.x + box.width, medianClamped)+ }+ ctx.stroke()++ // 5. Mean markers — filled circle outlined in the series color. Stays per-box because+ // each marker requires both a fill and a stroke pass.+ ctx.fillStyle = meanFillColor+ ctx.strokeStyle = color+ for (const box of boxes) {+ ctx.beginPath()+ ctx.arc(box.mean.x, box.mean.y, meanRadius, 0, Math.PI * 2)+ ctx.fill()+ ctx.stroke()+ }+}++/** Translucent highlight overlay for a hovered box. Drawn on the overlay canvas so it+ * composites over the static box without disturbing it — mirrors {@link drawBarHighlight}. */+export function drawBoxHighlight(ctx: CanvasRenderingContext2D, box: BoxRect, overlayColor: string): void {+ const boxHeight = Math.max(0, box.bottom - box.top)+ if (box.width <= 0 || boxHeight <= 0) {+ return+ }+ ctx.fillStyle = overlayColor+ ctx.fillRect(box.x, box.top, box.width, boxHeight)+}+type DrawHoverFn = (args: ChartDrawArgs) => DrawHoverResultinterface ComposeDrawHoverOptions {diff --git a/frontend/src/lib/hog-charts/core/color-utils.ts b/frontend/src/lib/hog-charts/core/color-utils.tsnew file mode 100644index 000000000000..37496df597bc--- /dev/null+++ b/frontend/src/lib/hog-charts/core/color-utils.ts@@ -0,0 +1,7 @@+import * as d3 from 'd3'++/** Translucent variant of a series colour (any CSS color form d3 can parse — hex 3/6 digit,+ * rgb/rgba, named, HSL). Falls back to the raw string when `d3.color` returns `null`. */+export function dimColor(color: string, alpha: number): string {+ return d3.color(color)?.copy({ opacity: alpha }).toString() ?? color+}diff --git a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.tsindex 6ae30e5a6aa9..ecc34f27ec1c 100644--- a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts+++ b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts@@ -29,6 +29,11 @@ interface UseChartMarginsOptions {axisOrientation?: 'vertical' | 'horizontal'/** Per-side overrides applied on top of the computed margins. */override?: Partial<ChartMargins>+ /** Override the value-range source for value-axis tick sizing. Defaults to `series`. Use+ * this when the visible series's `data[i]` doesn't span the full y-domain — e.g. BoxPlot+ * passes the whisker min/max samples so the y-tick column fits the actual range, not just+ * the medians it draws on `series.data`. yAxis-id discovery still reads from `series`. */+ valueRangeSeries?: Series[]}function widestCategoryLabelWidth(@@ -76,8 +81,10 @@ export function useChartMargins({yTickFormatter,axisOrientation = 'vertical',override,+ valueRangeSeries,}: UseChartMarginsOptions): ChartMargins {const isHorizontal = axisOrientation === 'horizontal'+ const valueSeries = valueRangeSeries ?? seriesconst normalizedXAxisLabel = normalizeAxisLabel(xAxisLabel)const normalizedYAxisLabel = normalizeAxisLabel(yAxisLabel)@@ -95,22 +102,22 @@ export function useChartMargins({if (isHorizontal) {return widestCategoryLabelWidth(labels, xTickFormatter)}- return widestValueLabelWidth(series, yTickFormatter)- }, [series, yTickFormatter, hideYAxis, isHorizontal, labels, xTickFormatter])+ return widestValueLabelWidth(valueSeries, yTickFormatter)+ }, [valueSeries, yTickFormatter, hideYAxis, isHorizontal, labels, xTickFormatter])const xLabelHalfWidth = useMemo<number>(() => {if (hideXAxis) {return 0}if (isHorizontal) {- const widest = widestValueLabelWidth(series, yTickFormatter)+ const widest = widestValueLabelWidth(valueSeries, yTickFormatter)return Math.ceil(widest / 2)}if (labels.length === 0) {return 0}return Math.ceil(widestCategoryLabelWidth(labels, xTickFormatter) / 2)- }, [labels, xTickFormatter, hideXAxis, isHorizontal, series, yTickFormatter])+ }, [labels, xTickFormatter, hideXAxis, isHorizontal, valueSeries, yTickFormatter])return useMemo<ChartMargins>(() => {const bottom = hideXAxisdiff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.tsindex 80837d49f3ee..cf6b81d66c2d 100644--- a/frontend/src/lib/hog-charts/index.ts+++ b/frontend/src/lib/hog-charts/index.ts@@ -24,6 +24,20 @@ export { RadialChart, RADIAL_MARGINS } from './core/RadialChart'export type { RadialChartProps, RadialLayoutBuilder } from './core/RadialChart'export { DEFAULT_MARGINS } from './core/hooks/useChartMargins'+// Box plot+export { BoxPlot } from './charts/BoxPlot/BoxPlot'+export type {+ BoxPlotAdaptedMeta,+ BoxPlotClickData,+ BoxPlotConfig,+ BoxPlotProps,+ BoxPlotTooltipContext,+} from './charts/BoxPlot/BoxPlot'+export { computeBoxBand, computeBoxRect, computeSeriesBoxes } from './charts/BoxPlot/computeBoxLayout'+export type { BoxPlotDatum, BoxPlotSeries, BoxRect } from './charts/BoxPlot/computeBoxLayout'+export { BoxPlotTooltip } from './charts/BoxPlot/BoxPlotTooltip'+export type { BoxPlotTooltipProps } from './charts/BoxPlot/BoxPlotTooltip'+// Pie / donutexport { PieChart } from './charts/PieChart/PieChart'export type { PieChartConfig, PieChartProps } from './charts/PieChart/PieChart'diff --git a/frontend/src/lib/hog-charts/testing/index.ts b/frontend/src/lib/hog-charts/testing/index.tsindex 3f893cce015b..9922d3f3ea3a 100644--- a/frontend/src/lib/hog-charts/testing/index.ts+++ b/frontend/src/lib/hog-charts/testing/index.ts@@ -3,6 +3,7 @@ export { clickAtIndex, hoverAtIndex } from './interactions'export { getHogChart } from './accessor'export type { GetHogChartOptions, HogChart, TooltipSnapshot } from './accessor'export { renderHogChart } from './render'+export type { RenderHogChartOptions } from './render'export { makeOverlayContext, renderOverlayInChart } from './overlay'export type { OverlayContextOverrides } from './overlay'export {diff --git a/frontend/src/lib/hog-charts/testing/render.ts b/frontend/src/lib/hog-charts/testing/render.tsindex 30eee680edae..344e0897e324 100644--- a/frontend/src/lib/hog-charts/testing/render.ts+++ b/frontend/src/lib/hog-charts/testing/render.ts@@ -7,30 +7,42 @@ import { getHogChart, type HogChart } from './accessor'import { ensureJsdom } from './jsdom'import { HOG_CHARTS_TOOLTIP_SELECTOR } from './tooltip'+export interface RenderHogChartOptions {+ /** Skip the tooltip-prop override so the chart renders its own tooltip. Context capture+ * via `chart.waitForTooltip()` is unavailable in this mode. */+ nativeTooltip?: boolean+}+/** Render a hog-charts component and return Testing Library's `RenderResult` with a `chart`* accessor attached. Throws if the rendered tree doesn't contain a hog-charts canvas.** Sets up the jsdom mocks + sync RAF on first call (idempotent), so tests don't need a* beforeEach for those. Also calls `cleanup()` and removes any leftover tooltip portal* before each render — RTL's auto-cleanup doesn't always reach `FloatingPortal` children. */-export function renderHogChart<Meta = unknown>(ui: ReactElement): RenderResult & { chart: HogChart<Meta> } {+export function renderHogChart<Meta = unknown>(+ ui: ReactElement,+ options: RenderHogChartOptions = {}+): RenderResult & { chart: HogChart<Meta> } {ensureJsdom()cleanup()document.querySelectorAll(HOG_CHARTS_TOOLTIP_SELECTOR).forEach((el) => el.remove())- // Intercept the (optional) `tooltip` render prop so `chart.waitForTooltip()` can return- // the structured `TooltipContext` the chart computed. When the consumer passes a tooltip- // we still call it for the rendered DOM; otherwise we fall through to DefaultTooltip,- // matching the chart's natural default.- let lastTooltipContext: TooltipContext<Meta> | null = nullconst props = ui.props as { tooltip?: (ctx: TooltipContext<Meta>) => ReactNode; labels?: string[] }- const userTooltip = props.tooltip- const captureTooltip = (ctx: TooltipContext<Meta>): ReactNode => {- lastTooltipContext = ctx- return userTooltip ? userTooltip(ctx) : DefaultTooltip(ctx as TooltipContext)++ // Intercept the `tooltip` render prop so `chart.waitForTooltip()` exposes the structured+ // `TooltipContext` the chart computed. Falls through to DefaultTooltip when no consumer+ // tooltip is supplied, matching the chart's natural default.+ let lastTooltipContext: TooltipContext<Meta> | null = null+ let toRender: ReactElement = ui+ if (!options.nativeTooltip) {+ const userTooltip = props.tooltip+ const captureTooltip = (ctx: TooltipContext<Meta>): ReactNode => {+ lastTooltipContext = ctx+ return userTooltip ? userTooltip(ctx) : DefaultTooltip(ctx as TooltipContext)+ }+ toRender = React.cloneElement(ui, { tooltip: captureTooltip })}- const wrapped = React.cloneElement(ui, { tooltip: captureTooltip })- const result = render(wrapped)+ const result = render(toRender)return {...result,chart: getHogChart<Meta>(result.container, {