:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(quill-charts): extract click routing into resolve-clicked-bar-series (#61972)
Sam Pennington7b0ba1236f7d
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsxindex c83c04383cc5..c9690d6cd3ba 100644--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx@@ -26,7 +26,6 @@ import { useLatest } from '../../core/hooks/useLatest'import {buildSegmentResolveValue,buildStackedPositionValue,- type BarScaleSet,computeDivergingStackData,computePercentStackData,computeStackData,@@ -52,7 +51,6 @@ import { computeVisibleXLabels } from '../../overlays/AxisLabels'import { BarTooltip } from './BarTooltip'import { computeWrapperMinHeight, HORIZONTAL_MIN_BAND_SIZE_DEFAULT, resolveBarShadow } from './utils/bar-config'import {- type BarLayout,barContainsPointOnBandAxis,cursorOutsideBarFillExtent,findVisibleStackedSegment,@@ -60,6 +58,7 @@ import {isStackedLayout,iterBarsAtCursor,} from './utils/bars-under-cursor'+import { resolveClickedBarSeries } from './utils/resolve-clicked-bar-series'export interface BarChartProps<Meta = unknown> {series: Series<Meta>[]@@ -575,7 +574,7 @@ function BarChartInner<Meta = unknown>({return (resolveClickedBarSeries({clickData,- d3Scales,+ scales: d3Scales,barLayout,isHorizontal,stackedData,@@ -626,90 +625,3 @@ function BarChartInner<Meta = unknown>({</div>)}--/** Rewrites the click payload to the bar series actually under the cursor. The base payload- * always points at the first series in the band; this picks the right one per layout:- * - grouped: the series whose sub-band column the cursor is over — band axis only, so a- * click above a short bar (or on its track) still resolves to that column.- * - stacked/percent: the segment whose rect contains the cursor on the value axis, walking- * every dataIndex in the band so sparse-overlap segments route correctly, and re-reading- * the value at that segment's own dataIndex.- * Pure so the routing is unit-testable; returns `null` to pass `clickData` through unchanged. */-export function resolveClickedBarSeries<Meta>({- clickData,- d3Scales,- barLayout,- isHorizontal,- stackedData,- topStackedKeyByAxis,- series,- labels,-}: {- clickData: PointClickData<Meta>- d3Scales: BarScaleSet- barLayout: BarLayout- isHorizontal: boolean- stackedData: Map<string, StackedBand> | undefined- topStackedKeyByAxis: Map<string, string>- series: Series<Meta>[]- labels: readonly string[]-}): PointClickData<Meta> | null {- const { cursor, label, dataIndex, crossSeriesData } = clickData- if (!cursor) {- return null- }- const rewrite = (hitSeries: Series<Meta>, value: number, hitDataIndex: number): PointClickData<Meta> => ({- ...clickData,- dataIndex: hitDataIndex,- series: hitSeries,- value,- seriesIndex: series.findIndex((s) => s.key === hitSeries.key),- })-- if (barLayout === 'grouped') {- for (const { series: s, bar } of iterBarsAtCursor({- series: crossSeriesData.map((d) => d.series),- label,- dataIndex,- scales: d3Scales,- layout: barLayout,- isHorizontal,- topStackedKeyByAxis,- })) {- if (!barContainsPointOnBandAxis(bar, cursor, isHorizontal)) {- continue- }- const hit = crossSeriesData.find((d) => d.series.key === s.key)- if (!hit) {- return null- }- const inTrackArea = cursorOutsideBarFillExtent(bar, cursor, isHorizontal)- return { ...rewrite(hit.series, hit.value, dataIndex), inTrackArea }- }- return null- }-- const visible = findVisibleStackedSegment({- series: crossSeriesData.map((d) => d.series),- labels,- hoveredLabel: label,- cursor,- scales: d3Scales,- layout: barLayout,- isHorizontal,- stackedData,- topStackedKeyByAxis,- })- if (!visible) {- return null- }- const hit = crossSeriesData.find((d) => d.series.key === visible.series.key)- if (!hit) {- return null- }- // Re-read value at the visible segment's own dataIndex — `hit.value` was resolved at the- // band's dataIndex, which is a sparse-zero cell for the visible series.- const raw = hit.series.data[visible.dataIndex]- const resolvedValue = typeof raw === 'number' && Number.isFinite(raw) ? raw : hit.value- return rewrite(hit.series, resolvedValue, visible.dataIndex)-}diff --git a/packages/quill/packages/charts/src/charts/BarChart/utils/resolve-clicked-bar-series.test.ts b/packages/quill/packages/charts/src/charts/BarChart/utils/resolve-clicked-bar-series.test.tsnew file mode 100644index 000000000000..435378a22a01--- /dev/null+++ b/packages/quill/packages/charts/src/charts/BarChart/utils/resolve-clicked-bar-series.test.ts@@ -0,0 +1,170 @@+import { computeStackData, createBarScales } from '../../../core/scales'+import type { PointClickData, Series } from '../../../core/types'+import { dimensions } from '../../../testing/jsdom'+import type { BarLayout } from './bars-under-cursor'+import { resolveClickedBarSeries } from './resolve-clicked-bar-series'++describe('resolveClickedBarSeries', () => {+ const crossSeriesAt = <Meta>(series: Series<Meta>[], dataIndex: number): PointClickData<Meta>['crossSeriesData'] =>+ series.map((s) => ({ series: s, value: s.data[dataIndex] ?? 0 }))++ const baseClickData = <Meta>(+ series: Series<Meta>[],+ dataIndex: number,+ label: string,+ cursor: { x: number; y: number } | null+ ): PointClickData<Meta> => ({+ seriesIndex: 0,+ dataIndex,+ series: series[0],+ value: series[0].data[dataIndex] ?? 0,+ label,+ crossSeriesData: crossSeriesAt(series, dataIndex),+ cursor,+ })++ it('returns null (passthrough) when the cursor is unavailable', () => {+ const series: Series[] = [{ key: 'a', label: 'A', data: [10] }]+ const scales = createBarScales(series, ['x'], dimensions, { barLayout: 'grouped', axisOrientation: 'vertical' })+ const result = resolveClickedBarSeries({+ clickData: baseClickData(series, 0, 'x', null),+ scales,+ barLayout: 'grouped',+ isHorizontal: false,+ stackedData: undefined,+ topStackedKeyByAxis: new Map(),+ series,+ labels: ['x'],+ })+ expect(result).toBeNull()+ })++ describe('grouped layout', () => {+ const labels = ['x', 'y']+ // `a` is the tallest at x (domain max), `b` is short so the track region above it is testable.+ const series: Series[] = [+ { key: 'a', label: 'A', data: [100, 50] },+ { key: 'b', label: 'B', data: [20, 30] },+ { key: 'c', label: 'C', data: [60, 40] },+ ]+ const scales = createBarScales(series, labels, dimensions, {+ barLayout: 'grouped',+ axisOrientation: 'vertical',+ })+ const subBandCenterX = (key: string): number =>+ scales.band('x')! + scales.group!(key)! + scales.group!.bandwidth() / 2+ const fillCenterY = (value: number): number => (scales.value(value) + scales.value(0)) / 2++ const resolve = (cursor: { x: number; y: number }): PointClickData | null =>+ resolveClickedBarSeries({+ clickData: baseClickData(series, 0, 'x', cursor),+ scales,+ barLayout: 'grouped',+ isHorizontal: false,+ stackedData: undefined,+ topStackedKeyByAxis: new Map(),+ series,+ labels,+ })++ it.each([+ { key: 'a', seriesIndex: 0, value: 100 },+ { key: 'b', seriesIndex: 1, value: 20 },+ { key: 'c', seriesIndex: 2, value: 60 },+ ])('routes a click on the $key sub-band column to that series', ({ key, seriesIndex, value }) => {+ const result = resolve({ x: subBandCenterX(key), y: fillCenterY(value) })+ expect(result?.series.key).toBe(key)+ expect(result?.seriesIndex).toBe(seriesIndex)+ expect(result?.value).toBe(value)+ expect(result?.inTrackArea).toBe(false)+ })++ it('flags inTrackArea when the cursor is in the column but above the short bar', () => {+ const result = resolve({ x: subBandCenterX('b'), y: 0 })+ expect(result?.series.key).toBe('b')+ expect(result?.inTrackArea).toBe(true)+ })++ it('returns null when the cursor is outside every sub-band column', () => {+ expect(resolve({ x: scales.band('x')! - 100, y: fillCenterY(20) })).toBeNull()+ })+ })++ describe('stacked layout', () => {+ const labels = ['Mon']+ const series: Series[] = [+ { key: 'bottom', label: 'Bottom', data: [30] },+ { key: 'top', label: 'Top', data: [10] },+ ]+ const scales = createBarScales(series, labels, dimensions, {+ barLayout: 'stacked',+ axisOrientation: 'vertical',+ })+ const stackedData = computeStackData(series, labels)+ const bandCenterX = scales.band('Mon')! + scales.band.bandwidth() / 2++ const resolve = (layout: BarLayout, valueAtCursor: number): PointClickData | null =>+ resolveClickedBarSeries({+ clickData: baseClickData(series, 0, 'Mon', { x: bandCenterX, y: scales.value(valueAtCursor) }),+ scales,+ barLayout: layout,+ isHorizontal: false,+ stackedData,+ topStackedKeyByAxis: new Map(),+ series,+ labels,+ })++ it('routes to the bottom segment when the cursor is on the value axis below the split', () => {+ const result = resolve('stacked', 15)+ expect(result?.series.key).toBe('bottom')+ expect(result?.seriesIndex).toBe(0)+ expect(result?.value).toBe(30)+ })++ it('routes to the top segment when the cursor is above the split', () => {+ const result = resolve('stacked', 35)+ expect(result?.series.key).toBe('top')+ expect(result?.seriesIndex).toBe(1)+ expect(result?.value).toBe(10)+ })++ it('treats percent layout like stacked for routing', () => {+ expect(resolve('percent', 35)?.series.key).toBe('top')+ })+ })++ describe('sparse-overlap layout', () => {+ // Two bars sharing a band drawn from a common baseline (smallest on top). The hovered band's+ // dataIndex holds a zero for `small`; routing must re-read `small`'s value at its own column.+ const labels = ['band', 'band']+ const series: Series[] = [+ { key: 'big', label: 'Big', data: [100, 0] },+ { key: 'small', label: 'Small', data: [0, 20] },+ ]+ const scales = createBarScales(series, labels, dimensions, {+ barLayout: 'stacked',+ axisOrientation: 'horizontal',+ })+ const stackedData = computeStackData(series, labels)+ const bandCenterY = scales.band('band')! + scales.band.bandwidth() / 2++ it('re-reads the value at the visible segment own dataIndex (not the band sparse-zero cell)', () => {+ const result = resolveClickedBarSeries({+ // Clicked at the band's dataIndex 0, where `small` is a sparse zero.+ clickData: baseClickData(series, 0, 'band', { x: scales.value(10), y: bandCenterY }),+ scales,+ barLayout: 'stacked',+ isHorizontal: true,+ stackedData,+ topStackedKeyByAxis: new Map(),+ series,+ labels,+ })+ expect(result?.series.key).toBe('small')+ expect(result?.dataIndex).toBe(1)+ expect(result?.value).toBe(20)+ expect(result?.seriesIndex).toBe(1)+ })+ })+})diff --git a/packages/quill/packages/charts/src/charts/BarChart/utils/resolve-clicked-bar-series.ts b/packages/quill/packages/charts/src/charts/BarChart/utils/resolve-clicked-bar-series.tsnew file mode 100644index 000000000000..a31234ff2d31--- /dev/null+++ b/packages/quill/packages/charts/src/charts/BarChart/utils/resolve-clicked-bar-series.ts@@ -0,0 +1,101 @@+import type { BarScaleSet, StackedBand } from '../../../core/scales'+import type { PointClickData, Series } from '../../../core/types'+import {+ type BarLayout,+ barContainsPointOnBandAxis,+ cursorOutsideBarFillExtent,+ findVisibleStackedSegment,+ iterBarsAtCursor,+} from './bars-under-cursor'++export interface ResolveClickedBarSeriesArgs<Meta> {+ clickData: PointClickData<Meta>+ scales: BarScaleSet+ barLayout: BarLayout+ isHorizontal: boolean+ stackedData: Map<string, StackedBand> | undefined+ topStackedKeyByAxis: Map<string, string>+ series: Series<Meta>[]+ labels: readonly string[]+}++/** Rewrites the click payload to the bar series actually under the cursor. The base payload+ * always points at the first series in the band; this picks the right one per layout:+ * - grouped: the series whose sub-band column the cursor is over — band axis only, so a+ * click above a short bar (or on its track) still resolves to that column.+ * - stacked/percent: the segment whose rect contains the cursor on the value axis, walking+ * every dataIndex in the band so sparse-overlap segments route correctly, and re-reading+ * the value at that segment's own dataIndex.+ * Pure so the routing is unit-testable; returns `null` to pass `clickData` through unchanged. */+export function resolveClickedBarSeries<Meta>({+ clickData,+ scales,+ barLayout,+ isHorizontal,+ stackedData,+ topStackedKeyByAxis,+ series,+ labels,+}: ResolveClickedBarSeriesArgs<Meta>): PointClickData<Meta> | null {+ const { cursor, label, dataIndex, crossSeriesData } = clickData+ if (!cursor) {+ return null+ }+ // Resolve once per click: O(bars × series) lookups otherwise on the grouped path below.+ const seriesIndexByKey = new Map(series.map((s, i) => [s.key, i]))+ const crossByKey = new Map(crossSeriesData.map((d) => [d.series.key, d]))+ const rewrite = (hitSeries: Series<Meta>, value: number, hitDataIndex: number): PointClickData<Meta> => ({+ ...clickData,+ dataIndex: hitDataIndex,+ series: hitSeries,+ value,+ seriesIndex: seriesIndexByKey.get(hitSeries.key) ?? -1,+ })++ if (barLayout === 'grouped') {+ for (const { series: s, bar } of iterBarsAtCursor({+ series: crossSeriesData.map((d) => d.series),+ label,+ dataIndex,+ scales,+ layout: barLayout,+ isHorizontal,+ topStackedKeyByAxis,+ })) {+ if (!barContainsPointOnBandAxis(bar, cursor, isHorizontal)) {+ continue+ }+ const hit = crossByKey.get(s.key)+ if (!hit) {+ return null+ }+ const inTrackArea = cursorOutsideBarFillExtent(bar, cursor, isHorizontal)+ return { ...rewrite(hit.series, hit.value, dataIndex), inTrackArea }+ }+ return null+ }++ const visible = findVisibleStackedSegment({+ series: crossSeriesData.map((d) => d.series),+ labels,+ hoveredLabel: label,+ cursor,+ scales,+ layout: barLayout,+ isHorizontal,+ stackedData,+ topStackedKeyByAxis,+ })+ if (!visible) {+ return null+ }+ const hit = crossByKey.get(visible.series.key)+ if (!hit) {+ return null+ }+ // Re-read value at the visible segment's own dataIndex — `hit.value` was resolved at the+ // band's dataIndex, which is a sparse-zero cell for the visible series.+ const raw = hit.series.data[visible.dataIndex]+ const resolvedValue = typeof raw === 'number' && Number.isFinite(raw) ? raw : hit.value+ return rewrite(hit.series, resolvedValue, visible.dataIndex)+}