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.

feat(quill-charts): add proportion bar chart (#112763)

Paul D'Ambrabde3058bf120
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 7bb8acf91767..54904098645d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1268,6 +1268,22 @@ snapshots:
hash: v1.k794b7964.9fb9de3ef6ea3c41afefb2ef1f48bd8ea996498fd3178094becab4a8a99e6b53.7StTlix5q6M4Ywy06Z6zUB14yt-gXrgyo2qGEqyejBg
components-hogcharts-piechart--with-legend--light:
hash: v1.k794b7964.8bb46927c74f00a5579e78a238a28ae3b1c47017dd4d058c0ed3d46d66e95218.oR1c60kYOX2Uvf1l-aT1TcDUTpqAbQNFuJtRRPTQljI
+ components-hogcharts-proportionbar--default--dark:
+ hash: v1.k794b7964.c7486be534f90f4d590b14f0150689f4d3752a6473a2929f6e4c58ff49adccf2.3Ca4csVlKfjdDzpA--mrdYaDzag1lUmksLCxy8rvKU8
+ components-hogcharts-proportionbar--default--light:
+ hash: v1.k794b7964.4005134e4f87877daf8a15d89d66c40ddf9ad40e7d2361f949df67d6b1968e90.wE0d-G06zrxdV4pD6FIYHe3G9eXYfKe58jqEAf8TbcQ
+ components-hogcharts-proportionbar--narrow--dark:
+ hash: v1.k794b7964.52d79c18a21bf3ced34e255e97c2038a864bd3aa884bc57576a85530c40f67e1.Jm1ctA9bdKuM_HLvBy7Y5dinq0abvC80wmhj02s_eCk
+ components-hogcharts-proportionbar--narrow--light:
+ hash: v1.k794b7964.c3155449e80acdaedf56a4adcdd2bb67696120db785456daa5da3e1f7eec5c06.W-XVGjc-H-vR906fAYvYfrw07ir-USuUCbcsjuQsOeQ
+ components-hogcharts-proportionbar--thin-with-currency--dark:
+ hash: v1.k794b7964.d08e6bbea9c82e6f0048c53dae699ce4f137449218e2adb012c70922e2d943ba.V97cm3tTqDauU196D-UsRqcyY31SgG3IyLsYOa7Px1Q
+ components-hogcharts-proportionbar--thin-with-currency--light:
+ hash: v1.k794b7964.9a98af30e608492246071eb8a8aa32c84f33132557fa7380c2edc6d764a59b3d.qkUHw6OYpYyzBFjFXZPLU4W8pXnxVHI9qAh7ydYkT5w
+ components-hogcharts-proportionbar--two-parts--dark:
+ hash: v1.k794b7964.9cf706da788d59039a7164f3258a028d4c64b2c00307b2a19a2bc2efcf58a252.9myoHWU04Yr48OJtosq5KCU_NsYa9KhAhJ-KOU4B8I8
+ components-hogcharts-proportionbar--two-parts--light:
+ hash: v1.k794b7964.a6b9696f53f3006e285d41ec84516640ebe05d5cbf0cfaf0df77868e93c3172e.MpvCPxDn1N6s0dTO0eLAuJzAyIMHnxcVJ_mJkPdhjlw
components-hogcharts-referenceline--fill-sides--dark:
hash: v1.k794b7964.b41b2cebf82f249680d02283fefc807d117ae54b38745e5fb46c7d14390f2353.bs-zM7MFAJsKbP_eQF4IWfMhJEqDNrQbqDfExi_wgwY
components-hogcharts-referenceline--fill-sides--light:
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 78ab064fdb48..f5b953e82e70 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -16,6 +16,7 @@ This file is the map. Prop-level semantics live in the JSDoc on the config and p
| `TimeSeriesComboChart` | `ComboChart` plus the time-series chrome (date x-axis, goal lines, legend, value labels) |
| `FunnelChart` | Funnel steps as grouped bars over a hatched drop-off track — one band per step, one bar per variant, valued as percent of first step |
| `PieChart` | Part of whole, one value per series; `innerRadiusRatio` for a donut |
+| `ProportionBar` | Part of whole as one flat 100% bar with no axes, legend rows show `share · value`; takes the same `series` as `PieChart` |
| `ScatterChart` | Two continuous numeric axes — one marker per `{ x, y }` point; takes `points`, not `labels` |
| `BoxPlot` | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label |
| `Heatmap` | 2D density grid (latency over time) — `xLabels` × `yLabels`, `cells[row][col]` |
@@ -105,7 +106,7 @@ Import helpers from `@posthog/quill-charts/testing` (jsdom only): `getHogChart`
| Doc | Covers |
| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| [src/README.md](./src/README.md) | Public surface, setup, theme, custom tooltip and overlay basics, sparkline |
-| [docs/chart-types.md](./src/docs/chart-types.md) | Per-chart behavior: scatter, funnel, slope, pie, box plot, heatmap, sparkline, metric card |
+| [docs/chart-types.md](./src/docs/chart-types.md) | Per-chart behavior: scatter, funnel, slope, pie, proportion bar, box plot, heatmap, sparkline, metric card |
| [docs/axes.md](./src/docs/axes.md) | Defaults, grid and axis chrome, x-axis labels, y format, baseline and range, multi-axis, margins, blank-plot diagnosis |
| [docs/bars.md](./src/docs/bars.md) | Layouts, per-bar overrides, `minBarSize`, `trackData`, hit-testing, trend lines, combo |
| [docs/tooltips.md](./src/docs/tooltips.md) | `config.tooltip`, `DefaultTooltip` props, custom pieces, context fields, touch |
diff --git a/packages/quill/packages/charts/src/README.md b/packages/quill/packages/charts/src/README.md
index 08b24c0d0ad7..3224591a3c86 100644
--- a/packages/quill/packages/charts/src/README.md
+++ b/packages/quill/packages/charts/src/README.md
@@ -133,7 +133,7 @@ import { Sparkline } from '@posthog/quill-charts'
## More
- Choosing a chart, the gotchas, and the docs index → [AGENTS.md](../AGENTS.md)
-- Per-chart behavior (scatter, funnel, slope, pie, metric card) → [docs/chart-types.md](./docs/chart-types.md)
+- Per-chart behavior (scatter, funnel, slope, pie, proportion bar, metric card) → [docs/chart-types.md](./docs/chart-types.md)
- Axes, ranges, multi-axis, chrome → [docs/axes.md](./docs/axes.md)
- Bars: layouts, per-bar overrides, `minBarSize`, `trackData` → [docs/bars.md](./docs/bars.md)
- Tooltips → [docs/tooltips.md](./docs/tooltips.md); legend → [docs/legend.md](./docs/legend.md)
diff --git a/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.stories.tsx b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.stories.tsx
new file mode 100644
index 000000000000..880e42486a8c
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.stories.tsx
@@ -0,0 +1,72 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import type { Series } from '../../core/types'
+import { Stage, useReactiveTheme } from '../../story-helpers'
+import { ProportionBar } from './ProportionBar'
+
+const CHECKOUT_OUTCOMES: Series[] = [
+ { key: 'paid', label: 'Paid', data: [1180] },
+ { key: 'retried', label: 'Paid after retry', data: [96] },
+ { key: 'abandoned', label: 'Abandoned at payment', data: [430] },
+ { key: 'declined', label: 'Card declined', data: [212] },
+ { key: 'error', label: 'Payment provider error', data: [57] },
+]
+
+const TWO_PARTS: Series[] = [
+ { key: 'new', label: 'New users', data: [3120] },
+ { key: 'returning', label: 'Returning users', data: [5480] },
+]
+
+const meta: Meta = { title: 'Components/HogCharts/ProportionBar', parameters: { layout: 'centered' } }
+export default meta
+
+type Story = StoryObj
+
+export const Default: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={640} height={120}>
+ <ProportionBar series={CHECKOUT_OUTCOMES} theme={theme} />
+ </Stage>
+ )
+ },
+}
+
+export const TwoParts: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={640} height={80}>
+ <ProportionBar series={TWO_PARTS} theme={theme} />
+ </Stage>
+ )
+ },
+}
+
+export const Narrow: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={360} height={160}>
+ <ProportionBar series={CHECKOUT_OUTCOMES} theme={theme} />
+ </Stage>
+ )
+ },
+}
+
+export const ThinWithCurrency: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={640} height={80}>
+ <ProportionBar
+ series={TWO_PARTS}
+ theme={theme}
+ config={{ barHeight: 8, barCornerRadius: 4 }}
+ valueFormatter={(value) => `$${value.toLocaleString()}`}
+ />
+ </Stage>
+ )
+ },
+}
diff --git a/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.test.tsx b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.test.tsx
new file mode 100644
index 000000000000..3890a85593d5
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.test.tsx
@@ -0,0 +1,109 @@
+import { fireEvent } from '@testing-library/react'
+
+import type { RadialSlicePayload } from '../../core/hooks/useRadialInteraction'
+import type { ChartTheme, Series } from '../../core/types'
+import { mockRect, renderHogChart, waitForHogChartTooltip } from '../../testing'
+import { ProportionBar } from './ProportionBar'
+
+const THEME: ChartTheme = { colors: ['#22d3ee', '#f14f58', '#a78bfa'], backgroundColor: '#ffffff' }
+
+// 600 + 100 + 100 over the 800px mock rect, so part `b` spans x 600..700. With `a` hidden, `b` and `c`
+// share the bar and `b` spans x 0..400.
+const PARTS: Series[] = [
+ { key: 'a', label: 'a', data: [600] },
+ { key: 'b', label: 'b', data: [100] },
+ { key: 'c', label: 'c', data: [100] },
+]
+const at = (clientX: number): { clientX: number; clientY: number } => ({ clientX, clientY: mockRect.height / 2 })
+const INSIDE_B = at(650)
+
+describe('ProportionBar', () => {
+ it('hands the tooltip the hovered part with its raw value, like a pie', async () => {
+ const { chart } = renderHogChart(<ProportionBar series={PARTS} theme={THEME} />)
+
+ await waitForHogChartTooltip(3000, () => fireEvent.mouseMove(chart.element, INSIDE_B))
+ const tooltip = await chart.waitForTooltip()
+
+ expect(tooltip).toMatchObject({ label: 'b', dataIndex: 1 })
+ expect(tooltip.seriesData).toHaveLength(1)
+ expect(tooltip.seriesData[0]).toMatchObject({
+ series: { key: 'b', color: THEME.colors[1] },
+ value: 100,
+ fraction: 0.125,
+ })
+ })
+
+ it.each([
+ { name: 'all parts drawn', hidden: [], cursor: INSIDE_B, sliceIndex: 1, fraction: 0.125 },
+ { name: 'a hidden part before it', hidden: ['a'], cursor: at(200), sliceIndex: 0, fraction: 0.5 },
+ ])('reports the clicked part like a pie slice, with $name', async ({ hidden, cursor, sliceIndex, fraction }) => {
+ const onSliceClick = jest.fn()
+ const { chart } = renderHogChart(
+ <ProportionBar
+ series={PARTS}
+ theme={THEME}
+ config={{ legend: { defaultHiddenKeys: hidden } }}
+ onSliceClick={onSliceClick}
+ />
+ )
+
+ await waitForHogChartTooltip(3000, () => fireEvent.mouseMove(chart.element, cursor))
+ fireEvent.click(chart.element)
+
+ const payload: RadialSlicePayload = onSliceClick.mock.calls[0][0]
+ expect(payload).toMatchObject({ sliceIndex, value: 100, fraction, series: { key: 'b', data: [100] } })
+ expect(payload.series.color).toBe(THEME.colors[1])
+ })
+
+ it.each([
+ {
+ name: 'every part is 0',
+ series: [
+ { key: 'a', label: 'a', data: [0] },
+ { key: 'b', label: 'b', data: [0] },
+ ],
+ hidden: [],
+ secondaryLabels: ['0% · 0', '0% · 0'],
+ },
+ {
+ name: 'the legend hides every part',
+ series: PARTS,
+ hidden: ['a', 'b', 'c'],
+ secondaryLabels: [null, null, null],
+ },
+ ])(
+ 'renders an empty bar with no click when $name, like a pie draws no slice',
+ ({ series, hidden, secondaryLabels }) => {
+ const onSliceClick = jest.fn()
+ const onError = jest.fn()
+ const { chart } = renderHogChart(
+ <ProportionBar
+ series={series}
+ theme={THEME}
+ config={{ legend: { defaultHiddenKeys: hidden } }}
+ onSliceClick={onSliceClick}
+ onError={onError}
+ />
+ )
+
+ fireEvent.click(chart.element)
+
+ expect(chart.legendItems().map((item) => item.secondaryLabel)).toEqual(secondaryLabels)
+ expect(onSliceClick).not.toHaveBeenCalled()
+ expect(onError).not.toHaveBeenCalled()
+ }
+ )
+
+ it('recomputes the legend shares over the parts left visible', () => {
+ const { chart } = renderHogChart(<ProportionBar series={PARTS} theme={THEME} />)
+ expect(chart.legendItems().map((item) => item.secondaryLabel)).toEqual([
+ '75% · 600',
+ '12.5% · 100',
+ '12.5% · 100',
+ ])
+
+ chart.clickLegendItem('a', { additive: true })
+
+ expect(chart.legendItems().map((item) => item.secondaryLabel)).toEqual([null, '50% · 100', '50% · 100'])
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx
new file mode 100644
index 000000000000..4694365663dc
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx
@@ -0,0 +1,212 @@
+import React, { useCallback, useMemo } from 'react'
+
+import { ChartLegend } from '../../components/Legend/ChartLegend'
+import { useChartLegend } from '../../components/Legend/useChartLegend'
+import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
+import type { RadialSlicePayload } from '../../core/hooks/useRadialInteraction'
+import type {
+ BarChartConfig,
+ ChartLegendConfig,
+ ChartTheme,
+ PointClickData,
+ Series,
+ TooltipContext,
+} from '../../core/types'
+import { BarChart } from '../BarChart/BarChart'
+import { PieTooltip } from '../PieChart/PieTooltip'
+import { partValue, proportionLegendItems } from './proportion-bar-data'
+
+export interface ProportionBarConfig {
+ /** Bar thickness in px. Default 24. */
+ barHeight?: number
+ /** Corner radius in px for both ends of the bar. Default 6. */
+ barCornerRadius?: number
+ /** Legend with one row per part and `share · value` on each row. Unlike the other charts it
+ * shows by default, at the bottom and start-aligned, because the bar has no axis to read a
+ * size from. Same click model as the other charts. */
+ legend?: ChartLegendConfig
+ tooltip?: {
+ enabled?: boolean
+ }
+}
+
+/** Shares `series`, `valueFormatter`, `tooltip`, `onSliceClick` and `config.legend` with `PieChart`.
+ * It has no `isPercent`, `sliceValueDisplay` or `config.sliceValue`: the bar always shows each
+ * part's share and value, and always values a part as the sum of its data. */
+export interface ProportionBarProps<Meta = unknown> {
+ /** One series per part, valued like a `PieChart` slice: the sum of `data`, floored at 0. */
+ series: Series<Meta>[]
+ theme: ChartTheme
+ config?: ProportionBarConfig
+ /** Formats a part's raw value in the legend and the default tooltip. */
+ valueFormatter?: (value: number) => string
+ /** Replaces the default tooltip. As on `PieChart`, `ctx.seriesData[0]` is the hovered part,
+ * with its raw `value` and its `fraction` of the visible parts. */
+ tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
+ onSliceClick?: (payload: RadialSlicePayload<Meta>) => void
+ className?: string
+ /** `data-attr` applied to the chart wrapper. */
+ dataAttr?: string
+ onError?: (error: Error, info: React.ErrorInfo) => void
+}
+
+const DEFAULT_BAR_HEIGHT = 24
+const DEFAULT_CORNER_RADIUS = 6
+const BAND_LABELS = ['total']
+
+export function ProportionBar<Meta = unknown>({ onError, ...rest }: ProportionBarProps<Meta>): React.ReactElement {
+ return (
+ <ChartErrorBoundary onError={onError}>
+ <ProportionBarInner {...rest} onError={onError} />
+ </ChartErrorBoundary>
+ )
+}
+
+function defaultValueFormatter(value: number): string {
+ return value.toLocaleString()
+}
+
+function ProportionBarInner<Meta = unknown>({
+ series,
+ theme,
+ config,
+ valueFormatter = defaultValueFormatter,
+ tooltip,
+ onSliceClick,
+ className,
+ dataAttr,
+ onError,
+}: ProportionBarProps<Meta>): React.ReactElement {
+ const {
+ barHeight = DEFAULT_BAR_HEIGHT,
+ barCornerRadius = DEFAULT_CORNER_RADIUS,
+ legend,
+ tooltip: tooltipConfig,
+ } = config ?? {}
+
+ const legendConfig = useMemo<ChartLegendConfig>(
+ () => ({ show: true, position: 'bottom', align: 'start', ...legend }),
+ [legend]
+ )
+ const { visibleSeries, legendProps } = useChartLegend(series, theme, legendConfig)
+ const legendItems = useMemo(
+ () => proportionLegendItems(series, theme, valueFormatter, legendProps.hiddenKeys),
+ [series, theme, valueFormatter, legendProps.hiddenKeys]
+ )
+ const colorByKey = useMemo(() => new Map(legendItems.map((item) => [item.key, item.color])), [legendItems])
+ // Tooltips and clicks hand back the consumer's own series, not the single-value copies the bar draws.
+ const seriesByKey = useMemo(() => new Map(series.map((s) => [s.key, s])), [series])
+
+ // Only the fields the bar needs to draw and identify a part. Carrying the rest of `s` through
+ // (yAxisId, overlay, fill.lowerData, per-bar `bars` overrides) would let it change how the part
+ // is drawn or stacked, which `PieChart` has no equivalent for.
+ const barSeries = useMemo<Series<Meta>[]>(
+ () =>
+ visibleSeries.map((s) => ({
+ key: s.key,
+ label: s.label,
+ color: s.color,
+ visibility: s.visibility,
+ meta: s.meta,
+ data: [partValue(s)],
+ })),
+ [visibleSeries]
+ )
+ const valueByKey = useMemo(() => new Map(barSeries.map((s) => [s.key, s.data[0]])), [barSeries])
+ const visibleTotal = useMemo(
+ () => barSeries.reduce((acc, s) => (s.visibility?.excluded ? acc : acc + s.data[0]), 0),
+ [barSeries]
+ )
+ // As on PieChart, a slice index counts only the drawn parts, so a hidden part does not shift it.
+ const drawnKeys = useMemo(() => barSeries.filter((s) => !s.visibility?.excluded).map((s) => s.key), [barSeries])
+ const fractionOf = useCallback(
+ (value: number): number => (visibleTotal > 0 ? value / visibleTotal : 0),
+ [visibleTotal]
+ )
+
+ // BarChart layers the library's default axes, grid and margins under any config, so opt out of
+ // each one to leave only the bar.
+ const barConfig = useMemo<BarChartConfig>(
+ () => ({
+ barLayout: 'percent',
+ axisOrientation: 'horizontal',
+ hideXAxis: true,
+ hideYAxis: true,
+ showGrid: false,
+ showAxisLines: false,
+ showTickMarks: false,
+ showCrosshair: false,
+ margins: { top: 0, right: 0, bottom: 0, left: 0 },
+ barCornerRadius,
+ bars: { bandPadding: 0, minBandSize: 0, roundStackEnds: true },
+ tooltip: { enabled: tooltipConfig?.enabled !== false },
+ }),
+ [barCornerRadius, tooltipConfig?.enabled]
+ )
+
+ // A percent layout hands the tooltip every segment as a 0..1 fraction. Narrow it to the hovered
+ // part with its raw value, which is the context a PieChart tooltip receives. Reads the value
+ // already computed for `barSeries` instead of rescanning the part's data on every hover.
+ const renderTooltip = useCallback(
+ (ctx: TooltipContext<Meta>): React.ReactNode => {
+ const entry = ctx.seriesData.find((d) => d.series.key === ctx.hoveredSeriesKey)
+ if (!entry) {
+ return null
+ }
+ const original = seriesByKey.get(entry.series.key) ?? entry.series
+ const part = { ...original, color: colorByKey.get(original.key) ?? entry.color }
+ const value = valueByKey.get(entry.series.key) ?? 0
+ const partCtx = {
+ ...ctx,
+ label: part.label,
+ dataIndex: series.indexOf(original),
+ seriesData: [{ ...entry, series: part, value, fraction: fractionOf(value) }],
+ }
+ return tooltip ? tooltip(partCtx) : <PieTooltip ctx={partCtx} valueFormatter={valueFormatter} />
+ },
+ [tooltip, series, seriesByKey, colorByKey, valueByKey, fractionOf, valueFormatter]
+ )
+
+ const handlePointClick = useCallback(
+ ({ series: clicked }: PointClickData<Meta>): void => {
+ const part = seriesByKey.get(clicked.key)
+ const sliceIndex = drawnKeys.indexOf(clicked.key)
+ const value = valueByKey.get(clicked.key) ?? 0
+ // A part with no visible width (value 0, or the whole bar empty) draws nothing. `PieChart`
+ // draws no slice and fires no click for it, so match that here.
+ if (!onSliceClick || !part || sliceIndex < 0 || visibleTotal <= 0 || value <= 0) {
+ return
+ }
+ onSliceClick({
+ sliceIndex,
+ series: { ...part, color: colorByKey.get(part.key) ?? '' },
+ value,
+ fraction: fractionOf(value),
+ })
+ },
+ [seriesByKey, drawnKeys, valueByKey, visibleTotal, onSliceClick, colorByKey, fractionOf]
+ )
+
+ // `ChartLegend` grows to fill a flex parent. Holding it in a box sized to its content keeps the
+ // legend right next to the bar, and lets the consumer place the pair, for example centered.
+ return (
+ <div className="flex flex-col min-w-0">
+ <ChartLegend {...legendProps} items={legendItems} legendDataAttr="hog-chart-proportion-legend">
+ {/* eslint-disable-next-line react/forbid-dom-props -- dynamic pixel height from config */}
+ <div className="relative flex flex-col" style={{ height: barHeight }}>
+ <BarChart
+ series={barSeries}
+ labels={BAND_LABELS}
+ theme={theme}
+ config={barConfig}
+ tooltip={renderTooltip}
+ onPointClick={onSliceClick ? handlePointClick : undefined}
+ className={className}
+ dataAttr={dataAttr}
+ onError={onError}
+ />
+ </div>
+ </ChartLegend>
+ </div>
+ )
+}
diff --git a/packages/quill/packages/charts/src/charts/ProportionBar/proportion-bar-data.test.ts b/packages/quill/packages/charts/src/charts/ProportionBar/proportion-bar-data.test.ts
new file mode 100644
index 000000000000..c726da3c9314
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ProportionBar/proportion-bar-data.test.ts
@@ -0,0 +1,47 @@
+import type { ChartTheme, Series } from '../../core/types'
+import { proportionLegendItems } from './proportion-bar-data'
+
+const THEME: ChartTheme = { colors: ['#22d3ee', '#f14f58', '#a78bfa'], backgroundColor: '#ffffff' }
+
+function part(key: string, data: number[], extra: Partial<Series> = {}): Series {
+ return { key, label: key, data, ...extra }
+}
+
+describe('proportionLegendItems', () => {
+ it.each([
+ {
+ name: 'shows each share of the total and the raw value',
+ series: [part('matched', [244]), part('partial', [25]), part('missed', [731])],
+ expected: ['24.4% · 244', '2.5% · 25', '73.1% · 731'],
+ },
+ {
+ name: 'counts negative and non-finite values as nothing',
+ series: [part('a', [30, Number.NaN]), part('b', [-10]), part('c', [10])],
+ expected: ['75% · 30', '0% · 0', '25% · 10'],
+ },
+ {
+ name: 'shows 0% instead of NaN when the total is zero',
+ series: [part('a', [0]), part('b', [0])],
+ expected: ['0% · 0', '0% · 0'],
+ },
+ {
+ name: 'leaves excluded series out of the rows and the total',
+ series: [part('a', [50]), part('excluded', [50], { visibility: { excluded: true } }), part('b', [50])],
+ expected: ['50% · 50', '50% · 50'],
+ },
+ {
+ name: 'keeps a legend-hidden row without a share, and leaves it out of the total',
+ series: [part('a', [50]), part('hidden', [100]), part('b', [150])],
+ hiddenKeys: ['hidden'],
+ expected: ['25% · 50', undefined, '75% · 150'],
+ },
+ ])('$name', ({ series, hiddenKeys, expected }) => {
+ const items = proportionLegendItems(series, THEME, (value) => value.toLocaleString(), hiddenKeys)
+ expect(items.map((item) => item.secondaryLabel)).toEqual(expected)
+ })
+
+ it('formats the value with the given formatter', () => {
+ const items = proportionLegendItems([part('a', [1200])], THEME, (value) => `$${value}`)
+ expect(items[0]).toMatchObject({ key: 'a', label: 'a', secondaryLabel: '100% · $1200' })
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/ProportionBar/proportion-bar-data.ts b/packages/quill/packages/charts/src/charts/ProportionBar/proportion-bar-data.ts
new file mode 100644
index 000000000000..931c6ffa0923
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ProportionBar/proportion-bar-data.ts
@@ -0,0 +1,41 @@
+import type { LegendItem } from '../../components/Legend/Legend'
+import { legendItemsFromSeries } from '../../components/Legend/legendItemsFromSeries'
+import type { ChartTheme, Series } from '../../core/types'
+import { percentage } from '../../utils/format'
+
+/** The size of one part: the sum of its finite values, floored at 0. This matches how `PieChart`
+ * sizes a slice, so the same `series` gives the same shares in both charts. */
+export function partValue(series: Series): number {
+ let sum = 0
+ for (const value of series.data) {
+ if (Number.isFinite(value)) {
+ sum += value
+ }
+ }
+ return Math.max(0, sum)
+}
+
+/** Legend rows for a proportion bar. Each row carries `share · value` as its `secondaryLabel`,
+ * because the bar has no axis to read a size from. A row hidden through the legend keeps its
+ * place but shows no share, and its value leaves the total, so the rows agree with the bar. */
+export function proportionLegendItems(
+ series: Series[],
+ theme: ChartTheme,
+ valueFormatter: (value: number) => string,
+ hiddenKeys: readonly string[] = []
+): LegendItem[] {
+ const hidden = new Set(hiddenKeys)
+ const valueByKey = new Map(series.map((s) => [s.key, partValue(s)]))
+ const total = series.reduce(
+ (acc, s) => (s.visibility?.excluded || hidden.has(s.key) ? acc : acc + (valueByKey.get(s.key) ?? 0)),
+ 0
+ )
+ return legendItemsFromSeries(series, theme).map((item) => {
+ if (hidden.has(item.key)) {
+ return item
+ }
+ const value = valueByKey.get(item.key) ?? 0
+ const share = total > 0 ? value / total : 0
+ return { ...item, secondaryLabel: `${percentage(share, 1)} · ${valueFormatter(value)}` }
+ })
+}
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
index f3b35ce63a15..04b12a1a108b 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
@@ -48,7 +48,7 @@ describe('SlopeChart', () => {
)
expect(chart.seriesCount).toBe(2)
expect(chart.slopeSeriesLabels()).not.toContain('C')
- expect(chart.slopeLegendItems().map((i) => i.label)).not.toContain('C')
+ expect(chart.legendItems().map((i) => i.label)).not.toContain('C')
})
describe('value labels', () => {
@@ -159,14 +159,14 @@ describe('SlopeChart', () => {
describe('legend', () => {
it('is hidden unless enabled', () => {
const { chart } = renderHogChart(<SlopeChart series={SERIES} labels={LABELS} theme={THEME} />)
- expect(chart.slopeLegendItems()).toHaveLength(0)
+ expect(chart.legendItems()).toHaveLength(0)
})
it('shows the label and signed change for each series', () => {
const { chart } = renderHogChart(
<SlopeChart series={SERIES} labels={LABELS} config={{ legend: { show: true } }} theme={THEME} />
)
- expect(chart.slopeLegendItems()).toEqual([
+ expect(chart.legendItems()).toEqual([
{ label: 'A', secondaryLabel: '+80' },
{ label: 'B', secondaryLabel: '-60' },
])
@@ -184,7 +184,7 @@ describe('SlopeChart', () => {
theme={THEME}
/>
)
- expect(chart.slopeLegendItems().map((i) => i.secondaryLabel)).toEqual(['↑80', '↓60'])
+ expect(chart.legendItems().map((i) => i.secondaryLabel)).toEqual(['↑80', '↓60'])
})
it('orders rows biggest-to-smallest by end value', () => {
@@ -197,7 +197,7 @@ describe('SlopeChart', () => {
const { chart } = renderHogChart(
<SlopeChart series={series} labels={LABELS} config={{ legend: { show: true } }} theme={THEME} />
)
- expect(chart.slopeLegendItems().map((i) => i.label)).toEqual(['B', 'C', 'A'])
+ expect(chart.legendItems().map((i) => i.label)).toEqual(['B', 'C', 'A'])
})
it('toggles a series off and on when its legend row is clicked', () => {
@@ -214,7 +214,7 @@ describe('SlopeChart', () => {
// The toggled-off series stays listed (so it can be restored).
expect(
getHogChart(container)
- .slopeLegendItems()
+ .legendItems()
.map((i) => i.label)
).toEqual(['A', 'B'])
diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.tsx
index 3d75461b4021..63840f993c57 100644
--- a/packages/quill/packages/charts/src/components/Legend/Legend.tsx
+++ b/packages/quill/packages/charts/src/components/Legend/Legend.tsx
@@ -85,7 +85,7 @@ export function Legend({
className="inline-block w-2.5 h-2.5 rounded-sm shrink-0"
style={{ backgroundColor: item.color }}
/>
- <span className="truncate min-w-0" title={item.label}>
+ <span className="truncate min-w-0" title={item.label} data-attr="hog-chart-legend-label">
{item.label}
</span>
{item.secondaryLabel != null && item.secondaryLabel !== '' && (
diff --git a/packages/quill/packages/charts/src/docs/TESTING.md b/packages/quill/packages/charts/src/docs/TESTING.md
index 9e1dd3576b89..8d544337af93 100644
--- a/packages/quill/packages/charts/src/docs/TESTING.md
+++ b/packages/quill/packages/charts/src/docs/TESTING.md
@@ -50,6 +50,8 @@ chart.referenceLines() // [{ label, position, color, orientation }, …]
chart.valueLabels() // [{ text, color }, …]
chart.anomalyPoints() // [{ element, color }, …] (TimeSeriesLineChart)
chart.annotationBadges() // HTMLElement[]
+chart.legendItems() // [{ label, secondaryLabel }, …] legend rows in the render scope, empty when hidden
+chart.clickLegendItem('A', { additive: true }) // click a legend row, additive toggles instead of isolating
```
For interactions, use the module-level helpers:
diff --git a/packages/quill/packages/charts/src/docs/chart-types.md b/packages/quill/packages/charts/src/docs/chart-types.md
index ee084ba0d28a..08393f5611f4 100644
--- a/packages/quill/packages/charts/src/docs/chart-types.md
+++ b/packages/quill/packages/charts/src/docs/chart-types.md
@@ -61,6 +61,19 @@ Part of whole, one value per series (`data[0]`).
- `theme.backgroundColor` is required for the hover pop-out mask; without it the pop-out is skipped. `disableHoverOffset` turns the pop-out off.
- Children read `useRadialLayout()` for `layout.slices`, `innerRadius`, `outerRadius`, `cx`, `cy`, and `centroidAngle`.
+## ProportionBar
+
+Part of whole as one horizontal bar that fills 100% of its width, with no axes.
+It takes the same `series` as `PieChart` and sizes each part the same way as a pie with the default slice value.
+
+- It is a preset over `BarChart` with `barLayout: 'percent'` and `axisOrientation: 'horizontal'`, like `Sparkline` is a preset over `BarChart` and `LineChart`.
+- It shares these props with `PieChart`: `series`, `valueFormatter`, `tooltip`, `onSliceClick`, and `config.legend`.
+- It has no `isPercent`, `sliceValueDisplay` or `config.sliceValue`. The bar always shows each part's share and value, and always values a part as the sum of its data. A pie that sets any of these does not swap to a bar unchanged.
+- A part thinner than about a pixel cannot be hovered or clicked. Its legend row still shows its share, and the legend can isolate it.
+- The legend shows below the bar by default. Each row shows `share · value` as its `secondaryLabel`, because the bar has no axis to read a size from. A part hidden through the legend leaves the total, and its row shows no share.
+- A `tooltip` render prop receives the hovered part as `seriesData[0]`, with its raw `value` and its `fraction` of the visible parts, as on `PieChart`.
+- `barHeight` sets the bar thickness. The chart takes its height from the bar and the legend, so it does not need a parent with a fixed height. It does not grow to fill a flex parent either, so the legend stays next to the bar; center the pair in the parent if you want it in the middle.
+
## BoxPlot
Distribution summaries: `{ min, p25, median, mean, p75, max }` per label.
diff --git a/packages/quill/packages/charts/src/docs/legend.md b/packages/quill/packages/charts/src/docs/legend.md
index 625878c39e3c..4107a6ff80ed 100644
--- a/packages/quill/packages/charts/src/docs/legend.md
+++ b/packages/quill/packages/charts/src/docs/legend.md
@@ -1,7 +1,8 @@
# Legend
-Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `TimeSeriesComboChart`, `SlopeChart`, `PieChart`) takes `config.legend: ChartLegendConfig`.
+Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `TimeSeriesComboChart`, `SlopeChart`, `PieChart`, `ProportionBar`) takes `config.legend: ChartLegendConfig`.
Hidden by default; `show: true` renders the built-in legend.
+`ProportionBar` is the exception: its legend shows by default, below the bar, because the bar has no axis to read a size from.
The fields are documented on `ChartLegendConfig` in `core/types.ts`.
## Click model
diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.ts
index a4284473a1a2..eca71fa81035 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -113,6 +113,10 @@ export { useRadialLayout } from './core/radial-context'
export type { RadialLayoutContextValue } from './core/radial-context'
export type { RadialSlicePayload } from './core/hooks/useRadialInteraction'
+// Proportion bar
+export { ProportionBar } from './charts/ProportionBar/ProportionBar'
+export type { ProportionBarConfig, ProportionBarProps } from './charts/ProportionBar/ProportionBar'
+
// Chart context (for custom overlay children)
export { useChart, useChartHover, useChartLayout } from './core/chart-context'
export type { BaseChartContext, ChartHoverContextValue, ChartLayoutContextValue } from './core/chart-context'
diff --git a/packages/quill/packages/charts/src/testing/accessor.ts b/packages/quill/packages/charts/src/testing/accessor.ts
index 59692924e6ec..3e3436290f5d 100644
--- a/packages/quill/packages/charts/src/testing/accessor.ts
+++ b/packages/quill/packages/charts/src/testing/accessor.ts
@@ -6,7 +6,7 @@
// contract — renaming them breaks consumers' tests. Keep in sync with the
// overlay components that emit them.
-import { fireEvent } from '@testing-library/react'
+import { act, fireEvent } from '@testing-library/react'
import type { TooltipContext } from '../core/types'
import { dragSelection } from './interactions'
@@ -54,9 +54,10 @@ interface SlopeValueLabelSummary {
side: 'start' | 'end'
}
-interface SlopeLegendItemSummary {
+interface LegendItemSummary {
label: string
- /** The per-series change text, or null when absent. */
+ /** The row's secondary text (a slope chart's change, a proportion bar's `share · value`), or null
+ * when absent. */
secondaryLabel: string | null
}
@@ -89,8 +90,15 @@ export interface HogChart<Meta = unknown> {
slopeValueLabels(): SlopeValueLabelSummary[]
/** Series name labels currently rendered by a slope chart (post-collision-avoidance). */
slopeSeriesLabels(): string[]
- /** Slope-chart legend rows — label plus the per-series change. Empty when the legend is hidden. */
- slopeLegendItems(): SlopeLegendItemSummary[]
+ /** Legend rows in this chart's render scope — label plus the row's secondary text (a slope
+ * chart's change, a proportion bar's `share · value`), or null when the row has none. Empty when
+ * the legend is hidden. */
+ legendItems(): LegendItemSummary[]
+ /** @deprecated Use `legendItems()`, which reads any chart's legend. */
+ slopeLegendItems(): LegendItemSummary[]
+ /** Click the legend row with this label. `additive` holds ⌘/Ctrl, which toggles that one series
+ * instead of isolating it. Throws when no legend row has the label. */
+ clickLegendItem(label: string, options?: { additive?: boolean }): void
/** Annotation badges currently rendered. */
annotationBadges(): HTMLElement[]
/** Fire a `mouseMove` over the data point at `index`. Only available when the chart was
@@ -226,20 +234,18 @@ export function getHogChart<Meta = unknown>(
Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-slope-series-label"]')).map(
(el) => el.textContent ?? ''
),
- slopeLegendItems: () => {
- // The legend renders as a sibling of the chart wrapper (inside ChartLegendLayout), so it
- // lives in the broader render scope rather than under `wrapper`.
- const legend = scope.querySelector<HTMLElement>('[data-attr="hog-chart-slope-legend"]')
- if (!legend) {
- return []
+ legendItems: () => readLegendItems(scope),
+ slopeLegendItems: () => readLegendItems(scope),
+ clickLegendItem(label: string, { additive = false }: { additive?: boolean } = {}): void {
+ const labelEl = Array.from(
+ scope.querySelectorAll<HTMLElement>('[data-attr="hog-chart-legend-label"]')
+ ).find((el) => el.textContent === label)
+ const row = labelEl?.closest('button')
+ if (!row) {
+ throw new Error(`No clickable legend row labelled "${label}"`)
}
- return Array.from(legend.querySelectorAll<HTMLElement>('.truncate')).map((labelEl) => {
- const secondary = labelEl.nextElementSibling
- const isSecondary = secondary?.getAttribute('data-attr') === 'hog-chart-legend-secondary'
- return {
- label: labelEl.textContent ?? '',
- secondaryLabel: isSecondary ? (secondary as HTMLElement).textContent : null,
- }
+ act(() => {
+ fireEvent.click(row, { metaKey: additive })
})
},
annotationBadges: () => Array.from(wrapper.querySelectorAll<HTMLElement>('.AnnotationsBadge')),
@@ -282,3 +288,16 @@ export function getHogChart<Meta = unknown>(
},
}
}
+
+// The legend renders as a sibling of the chart wrapper (inside ChartLegendLayout), so it lives in the
+// broader render scope rather than under the chart wrapper.
+function readLegendItems(scope: ParentNode): LegendItemSummary[] {
+ return Array.from(scope.querySelectorAll<HTMLElement>('[data-attr="hog-chart-legend-label"]')).map((labelEl) => {
+ const secondary = labelEl.nextElementSibling
+ const isSecondary = secondary?.getAttribute('data-attr') === 'hog-chart-legend-secondary'
+ return {
+ label: labelEl.textContent ?? '',
+ secondaryLabel: isSecondary ? (secondary as HTMLElement).textContent : null,
+ }
+ })
+}