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): show per-series values in the legend (#125547)

Ben Whitef1ab6c409d35
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 08085f45a96f..027abd35f848 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1616,6 +1616,10 @@ snapshots:
hash: v1.k794b7964.613e3b336b545f0411fccd60407a4f623c142f63f3dcd3ac0679f20c148e1f9e.21JBgOt2yEpUt7Cr6oeZI6UkEptAhiiWCb_xXzKyexs
components-hogcharts-timeserieslinechart--dual-y-axis-mixed-scales--light:
hash: v1.k794b7964.d58372cff8f8021d6554ea554704d63c24d4d2ae50ee474cb5e88f6be41f8dcd.pl5JmjbyxI6hDEEOyLiYNELEYCHBX7rNc49BRicLk8o
+ components-hogcharts-timeserieslinechart--legend-values--dark:
+ hash: v1.k794b7964.8fbd1fa63209b5ff2f20f71cfcd8cae465eb57a7fa939c275664192abe287671.a64ol5b8yxZd-X0EK2sr_pgDpn-eVWKhodOUb6YiLuU
+ components-hogcharts-timeserieslinechart--legend-values--light:
+ hash: v1.k794b7964.61393fa737e500dd2acae4da34412f53a6252becde093eef91d1ecfc11e1940d.DskrVGJHPyCqk6k38qXFMbymmM9dnTUz-Rd9DrV3Qks
components-hogcharts-timeserieslinechart--moving-average--dark:
hash: v1.k794b7964.3ceedb6cc4e7e7dc732c2781243e1dc1b05c72c682d62b9d017dcec77f6cd78f.sZVdza2_lkTWkS4oLl4BbOOlXlqNQJZn7YpCtGLVhzI
components-hogcharts-timeserieslinechart--moving-average--light:
diff --git a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsx b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsx
index f9e611b1fb6a..cf81c1ff55f7 100644
--- a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsx
+++ b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsx
@@ -62,7 +62,7 @@ export type BoxPlotTooltipContext<Meta = unknown> = TooltipContext<BoxPlotAdapte
/** Chart-level config. `axisOrientation: 'horizontal'` lists the labels down the y-axis and draws
* the value axis along x, which suits a few long boxes better than a row of narrow columns. */
export interface BoxPlotConfig extends ChartConfig {
- legend?: ChartLegendConfig
+ legend?: Omit<ChartLegendConfig, 'table'>
/** 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. */
diff --git a/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.test.tsx b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.test.tsx
index 269d99e9744f..7c6ebdb6901a 100644
--- a/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.test.tsx
+++ b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.test.tsx
@@ -94,6 +94,18 @@ describe('ProportionBar', () => {
}
)
+ it('fills legend value columns for its own legend rows and keeps their share text', () => {
+ const { chart } = renderChart(
+ <ProportionBar series={PARTS} theme={THEME} config={{ legend: { table: { values: ['sum'] } } }} />
+ )
+ expect(chart.legendItems()).toEqual([
+ { label: 'a', secondaryLabel: '75% · 600' },
+ { label: 'b', secondaryLabel: '12.5% · 100' },
+ { label: 'c', secondaryLabel: '12.5% · 100' },
+ ])
+ expect(chart.legendValues()).toEqual([['600'], ['100'], ['100']])
+ })
+
it('recomputes the legend shares over the parts left visible', () => {
const { chart } = renderChart(<ProportionBar series={PARTS} theme={THEME} />)
expect(chart.legendItems().map((item) => item.secondaryLabel)).toEqual([
diff --git a/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx
index 50e37624ff3c..ca5e82a454a7 100644
--- a/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx
+++ b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx
@@ -1,6 +1,7 @@
import React, { useMemo } from 'react'
import { ChartLegend } from '../../components/Legend/ChartLegend'
+import { withLegendValues } from '../../components/Legend/legendItemsFromSeries'
import { useChartLegend } from '../../components/Legend/useChartLegend'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
import type { RadialSlicePayload } from '../../core/hooks/useRadialInteraction'
@@ -91,8 +92,13 @@ function ProportionBarInner<Meta = unknown>({
const legendConfig: ChartLegendConfig = { show: true, position: 'bottom', align: 'start', ...legend }
const { visibleSeries, legendProps } = useChartLegend(series, theme, legendConfig)
const legendItems = useMemo(
- () => proportionLegendItems(series, theme, valueFormatter, legendProps.hiddenKeys),
- [series, theme, valueFormatter, legendProps.hiddenKeys]
+ () =>
+ withLegendValues(
+ proportionLegendItems(series, theme, valueFormatter, legendProps.hiddenKeys),
+ series,
+ legendProps.table?.values
+ ),
+ [series, theme, valueFormatter, legendProps.hiddenKeys, legendProps.table?.values]
)
const colorByKey = new Map(legendItems.map((item) => [item.key, item.color]))
// Tooltips and clicks hand back the consumer's own series, not the single-value copies the bar draws.
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/types.ts b/packages/quill/packages/charts/src/charts/ScatterChart/types.ts
index bd37810deda3..3b3fd8c18a70 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/types.ts
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/types.ts
@@ -71,7 +71,7 @@ export interface ScatterChartConfig<Meta = unknown> {
/** Draws a dashed least-squares fit line per series, spanning that series' own points. Fitted in
* the axes' own space, so a log axis fits the log values. */
showBestFit?: boolean
- legend?: ChartLegendConfig
+ legend?: Omit<ChartLegendConfig, 'table'>
tooltip?: ScatterTooltipConfig<Meta>
/** Applied over the computed margins. */
margins?: Partial<ChartMargins>
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 38c4cea3b186..967c11bc2f0b 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
@@ -27,6 +27,22 @@ describe('SlopeChart', () => {
expect(chart.yTicks()).toHaveLength(0)
})
+ it('fills legend value columns for its own legend rows and keeps their change text', () => {
+ const { chart } = renderChart(
+ <SlopeChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ legend: { show: true, table: { values: ['max'] } } }}
+ />
+ )
+ expect(chart.legendItems()).toEqual([
+ { label: 'A', secondaryLabel: '+80' },
+ { label: 'B', secondaryLabel: '-60' },
+ ])
+ expect(chart.legendValues()).toEqual([['90'], ['80']])
+ })
+
it('renders empty state without crashing', () => {
const { chart } = renderChart(<SlopeChart series={[]} labels={LABELS} theme={THEME} />)
expect(chart.seriesCount).toBe(0)
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index 0686cf330ea9..cd84455845ff 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -145,7 +145,13 @@ export function TimeSeriesBarChart<Meta = unknown>({
valueLabelFormatter,
primaryYAxis,
yAxes,
- } = useTimeSeries(series, labels, theme, { xAxis, yAxis, valueLabels, legend })
+ } = useTimeSeries(series, labels, theme, {
+ xAxis,
+ yAxis,
+ valueLabels,
+ legend,
+ isPercent: barLayout === 'percent',
+ })
const timeSeriesTooltipConfig = useTimeSeriesTooltipConfig(tooltipConfig, xAxis, labels)
// `axisOrientation` flows through `barChartConfig` into chart context, so `ReferenceLine`
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
index 68f6e773e8d3..052e68cf800e 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
@@ -124,7 +124,13 @@ export function TimeSeriesComboChart<Meta = unknown>({
valueLabelFormatter,
primaryYAxis,
yAxes,
- } = useTimeSeries(series, labels, theme, { xAxis, yAxis, valueLabels, legend })
+ } = useTimeSeries(series, labels, theme, {
+ xAxis,
+ yAxis,
+ valueLabels,
+ legend,
+ isPercent: barLayout === 'percent',
+ })
const timeSeriesTooltipConfig = useTimeSeriesTooltipConfig(tooltipConfig, xAxis, labels)
const { referenceLines, valueDomain: goalLineDomain } = useGoalLines(goalLines, chartSeries)
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
index 3a27e4012205..f57ace336ee7 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
@@ -260,6 +260,43 @@ export const YAxisRange: Story = {
),
}
+const LATENCY_SERIES: Series[] = [
+ { key: 'api', label: 'api', data: [120, 140, 130, 160, 150, 170, 155] },
+ { key: 'web', label: 'web', data: [220, 260, 240, 300, 280, 320, 290] },
+ { key: 'worker', label: 'worker', data: [400, 460, 430, NaN, 480, 560, 510] },
+ { key: 'cron', label: 'cron', data: [60, 65, 58, 72, 70, 66, 61] },
+]
+
+/** `legend.table` turns the legend into a table of per-series summaries, formatted like the axis.
+ * Click a header to sort by it; rows still isolate and toggle their series. */
+export const LegendValues: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ // eslint-disable-next-line react/forbid-dom-props
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, auto)', gap: 24 }}>
+ {(['bottom', 'right'] as const).map((position) => (
+ <Stage key={position} width={560} height={320}>
+ <TimeSeriesLineChart
+ series={LATENCY_SERIES}
+ labels={DAYS}
+ theme={theme}
+ config={{
+ yAxis: { showGrid: true, suffix: ' ms' },
+ legend: {
+ show: true,
+ position,
+ table: { values: ['mean', 'max', 'last'], defaultSort: { by: 'mean' } },
+ },
+ }}
+ />
+ </Stage>
+ ))}
+ </div>
+ )
+ },
+}
+
const DERIVED_SERIES: Series[] = [
{ key: 'visits', label: 'Visits', data: [20, 35, 28, 60, 45, 70, 52] },
{ key: 'signups', label: 'Sign-ups', data: [4, 8, 6, 14, 11, 19, 13] },
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
index a30918819f53..a59c7486664b 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
@@ -10,7 +10,7 @@ import {
setupSyncRaf,
waitForChartTooltip,
} from '../../testing'
-import { TimeSeriesLineChart } from './TimeSeriesLineChart'
+import { TimeSeriesLineChart, type TimeSeriesLineChartConfig } from './TimeSeriesLineChart'
const THEME: ChartTheme = {
colors: ['#111', '#222', '#333'],
@@ -658,6 +658,40 @@ describe('TimeSeriesLineChart', () => {
})
describe('interactive legend', () => {
+ // MULTI_SERIES peaks at 3 in both series.
+ it.each<[string, Partial<TimeSeriesLineChartConfig>, string[][]]>([
+ [
+ 'formats legend values with each series axis format',
+ {
+ yAxis: [
+ { id: 'left', suffix: ' ms' },
+ { id: 'right', prefix: '$' },
+ ],
+ },
+ [['3 ms'], ['$3']],
+ ],
+ [
+ 'keeps a secondary axis without a format plain',
+ { yAxis: [{ id: 'left', suffix: ' ms' }, { id: 'right' }] },
+ [['3 ms'], ['3']],
+ ],
+ [
+ 'keeps raw values plain on a percent chart',
+ { yAxis: { format: 'percentage_scaled' }, percentStackView: true },
+ [['3'], ['3']],
+ ],
+ ])('%s', (_, config, expectedValues) => {
+ const { chart } = renderChart(
+ <TimeSeriesLineChart
+ series={[MULTI_SERIES[0], { ...MULTI_SERIES[1], yAxisId: 'right' }]}
+ labels={LABELS}
+ theme={THEME}
+ config={{ ...config, legend: { show: true, table: { values: ['max'] } } }}
+ />
+ )
+ expect(chart.legendValues()).toEqual(expectedValues)
+ })
+
it('lists the raw series (not derived trend lines) and isolates one on click', () => {
const { container, chart } = renderChart(
<TimeSeriesLineChart
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index 6ca663649088..2c1b0b28b5e7 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -141,7 +141,13 @@ export function TimeSeriesLineChart<Meta = unknown>({
valueLabelFormatter,
primaryYAxis,
yAxes,
- } = useTimeSeries(series, labels, theme, { xAxis, yAxis, valueLabels, legend })
+ } = useTimeSeries(series, labels, theme, {
+ xAxis,
+ yAxis,
+ valueLabels,
+ legend,
+ isPercent: !!percentStackView,
+ })
const timeSeriesTooltipConfig = useTimeSeriesTooltipConfig(tooltipConfig, xAxis, labels)
const timeXs = useMemo(() => (timeScale ? labels.map(timeScale.parse) : undefined), [timeScale, labels])
diff --git a/packages/quill/packages/charts/src/charts/utils/use-time-series.ts b/packages/quill/packages/charts/src/charts/utils/use-time-series.ts
index 6c9b01097b2c..678170a42389 100644
--- a/packages/quill/packages/charts/src/charts/utils/use-time-series.ts
+++ b/packages/quill/packages/charts/src/charts/utils/use-time-series.ts
@@ -2,6 +2,7 @@ import { useMemo } from 'react'
import { useChartLegend, type ChartLegendRenderProps } from '../../components/Legend/useChartLegend'
import type { ChartLegendConfig, ChartTheme, Series, ValueDomain, YAxis } from '../../core/types'
+import { DEFAULT_Y_AXIS_ID } from '../../core/types'
import type { ReferenceLineProps } from '../../overlays/ReferenceLine'
import type { ValueLabelFormatter } from '../../overlays/ValueLabels'
import { buildGoalLineReferenceLines, goalLineValueDomain, type GoalLineConfig } from '../../utils/goal-lines'
@@ -14,6 +15,7 @@ import {
type XAxisConfig,
type YAxisConfig,
} from '../../utils/use-axis-formatters'
+import { buildYTickFormatter } from '../../utils/y-formatters'
import { resolveValueLabelsConfig, useSeriesWithValueLabelAllowlist, type ValueLabelsConfig } from './use-value-labels'
export interface UseTimeSeriesConfig {
@@ -24,6 +26,8 @@ export interface UseTimeSeriesConfig {
yAxis?: YAxisConfig | YAxisConfig[]
valueLabels?: boolean | ValueLabelsConfig
legend?: ChartLegendConfig
+ /** The chart plots shares (percent stack or percent bars), so its axis formats a 0..1 fraction. */
+ isPercent?: boolean
}
export interface UseTimeSeriesResult<Meta> {
@@ -60,13 +64,14 @@ export function useTimeSeries<Meta>(
theme: ChartTheme,
config: UseTimeSeriesConfig
): UseTimeSeriesResult<Meta> {
- const { xAxis, yAxis, valueLabels, legend } = config
+ const { xAxis, yAxis, valueLabels, legend, isPercent = false } = config
const axisList = useMemo(() => normalizeYAxisList(yAxis), [yAxis])
const primaryYAxis = useMemo(() => primaryYAxisConfig(axisList), [axisList])
const yAxes = useMemo(() => (Array.isArray(yAxis) ? buildYAxes(axisList) : undefined), [yAxis, axisList])
const xTickFormatter = useXTickFormatter(xAxis, labels)
const yTickFormatter = useYTickFormatter(primaryYAxis)
- const { visibleSeries, legendProps } = useChartLegend(series, theme, legend)
+ const legendConfig = useLegendAxisFormatter(series, legend, yTickFormatter, yAxes, isPercent)
+ const { visibleSeries, legendProps } = useChartLegend(series, theme, legendConfig)
const valueLabelsConfig = resolveValueLabelsConfig(valueLabels)
const chartSeries = useSeriesWithValueLabelAllowlist(visibleSeries, valueLabelsConfig?.seriesKeys)
const valueLabelFormatter = valueLabelsConfig ? (valueLabelsConfig.formatter ?? yTickFormatter) : undefined
@@ -104,3 +109,29 @@ export function useGoalLines<Meta>(
const valueDomain = useMemo(() => goalLineValueDomain(referenceLines), [referenceLines])
return { referenceLines, valueDomain }
}
+
+/** Defaults a value-column legend's formatter to each series' axis tick format, so a legend value
+ * reads the same as the axis it is plotted against. A percent axis formats a 0..1 fraction, but
+ * legend values are raw, so a percent chart keeps the plain number format. */
+function useLegendAxisFormatter(
+ series: Series<unknown>[],
+ legend: ChartLegendConfig | undefined,
+ primaryFormatter: ((value: number) => string) | undefined,
+ yAxes: YAxis[] | undefined,
+ isPercent: boolean
+): ChartLegendConfig | undefined {
+ return useMemo(() => {
+ const table = legend?.table
+ if (!table?.values.length || table.valueFormatter || isPercent || (!primaryFormatter && !yAxes)) {
+ return legend
+ }
+ const axisByKey = new Map(series.map((s) => [s.key, s.yAxisId ?? DEFAULT_Y_AXIS_ID]))
+ const formatterByAxis = new Map((yAxes ?? []).map((axis) => [axis.id, axis.tickFormatter]))
+ const plain = buildYTickFormatter({})
+ // With several axes, an axis without format fields auto-formats its own ticks, so its
+ // series stay plain rather than borrowing the primary format.
+ const formatterFor = (key: string): ((value: number) => string) =>
+ (yAxes ? formatterByAxis.get(axisByKey.get(key) ?? DEFAULT_Y_AXIS_ID) : primaryFormatter) ?? plain
+ return { ...legend, table: { ...table, valueFormatter: (value, item) => formatterFor(item.key)(value) } }
+ }, [series, legend, primaryFormatter, yAxes, isPercent])
+}
diff --git a/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsx b/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsx
index f9ae0873c9ce..bf2c0282175e 100644
--- a/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsx
+++ b/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsx
@@ -15,6 +15,7 @@ export interface ChartLegendProps {
className?: string
/** Wrap each legend row — forwarded to {@link Legend}'s `renderItem`. */
renderItem?: (defaultNode: React.ReactNode, item: LegendItem) => React.ReactNode
+ table?: LegendProps['table']
/** data-attr on the inner `<Legend>`. The outer layout wrapper has no data-attr. */
legendDataAttr?: string
children: React.ReactNode
@@ -30,6 +31,7 @@ export function ChartLegend({
hiddenKeys,
className,
renderItem,
+ table,
legendDataAttr,
children,
}: ChartLegendProps): React.ReactElement {
@@ -49,10 +51,12 @@ export function ChartLegend({
onItemClick={onItemClick}
hiddenKeys={hiddenKeys}
renderItem={renderItem}
+ table={table}
dataAttr={legendDataAttr}
/>
}
position={position}
+ wide={!!table?.values.length}
align={align}
gap={gap}
className={wrapperClassName}
diff --git a/packages/quill/packages/charts/src/components/Legend/ChartLegendLayout.tsx b/packages/quill/packages/charts/src/components/Legend/ChartLegendLayout.tsx
index c7cdabf035b4..aa76a72d3710 100644
--- a/packages/quill/packages/charts/src/components/Legend/ChartLegendLayout.tsx
+++ b/packages/quill/packages/charts/src/components/Legend/ChartLegendLayout.tsx
@@ -8,6 +8,8 @@ export interface ChartLegendLayoutProps {
gap?: number
className?: string
dataAttr?: string
+ /** Give a side legend more width, for a legend with value columns. */
+ wide?: boolean
children: React.ReactNode
}
@@ -24,6 +26,7 @@ export function ChartLegendLayout({
gap = 8,
className,
dataAttr,
+ wide = false,
children,
}: ChartLegendLayoutProps): React.ReactElement {
const isRow = position === 'left' || position === 'right'
@@ -32,8 +35,11 @@ export function ChartLegendLayout({
// which top/bottom's max-h-[40%] still needs. Their width caps at 45% of the chart but never more than
// 240px, so one long label can't squeeze the plot on a wide chart. `justify-center-safe` keeps short
// side legends centered yet scrollable (plain center would push the top rows past the scroll origin).
+ // A side table legend needs room for its value columns, so it moves below (or above) a chart
+ // narrower than 480px rather than squeezing the plot and the series names.
+ const stackWhenNarrow = isRow && wide
const legendClass = isRow
- ? 'flex flex-col self-stretch max-w-[min(45%,240px)] overflow-y-auto justify-center-safe'
+ ? `flex flex-col self-stretch ${wide ? 'max-w-[min(60%,480px)] @max-[480px]:max-w-none @max-[480px]:max-h-[40%]' : 'max-w-[min(45%,240px)]'} overflow-y-auto justify-center-safe`
: 'self-stretch max-h-[40%] overflow-y-auto'
const legendSlot = legend ? (
@@ -41,14 +47,22 @@ export function ChartLegendLayout({
) : null
// `flex flex-col` so the inner chart's `flex: 1` resolves; `self-stretch` so the chart fills the cross axis regardless of `align` (which then only affects the legend).
const chartSlot = <div className="flex flex-col flex-1 min-w-0 min-h-0 self-stretch">{children}</div>
- return (
+ const layout = (
<div
- className={`flex min-w-0 min-h-0 ${isRow ? 'flex-row' : 'flex-col'} ${ALIGN_CLASS[align]} ${className ?? ''}`}
+ className={`flex min-w-0 min-h-0 ${isRow ? 'flex-row' : 'flex-col'} ${stackWhenNarrow ? 'flex-1 @max-[480px]:flex-col' : ''} ${ALIGN_CLASS[align]} ${stackWhenNarrow ? '' : (className ?? '')}`}
style={{ gap }}
- data-attr={dataAttr}
+ data-attr={stackWhenNarrow ? undefined : dataAttr}
>
{legendFirst ? legendSlot : chartSlot}
{legendFirst ? chartSlot : legendSlot}
</div>
)
+ // The container query reads the width of a wrapper, since an element can't query its own size.
+ return stackWhenNarrow ? (
+ <div className={`@container flex min-w-0 min-h-0 ${className ?? ''}`} data-attr={dataAttr}>
+ {layout}
+ </div>
+ ) : (
+ layout
+ )
}
diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx
index e1d6f0e27626..157ef4c38168 100644
--- a/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx
+++ b/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx
@@ -91,4 +91,54 @@ describe('Legend', () => {
.map((row) => row.textContent)
expect(dimmedLabels).toEqual(['Returning'])
})
+
+ describe('value columns', () => {
+ const VALUE_ITEMS: LegendItem[] = [
+ { key: 'a', label: 'Alpha', color: '#000', values: { mean: 10, max: 30 } },
+ { key: 'b', label: 'Beta', color: '#111', values: { mean: 25, max: 5 } },
+ { key: 'c', label: 'Gamma', color: '#222', values: { mean: null, max: null } },
+ ]
+ const labelsOf = (container: HTMLElement): string[] =>
+ Array.from(container.querySelectorAll('[data-attr="hog-chart-legend-label"]')).map((l) => l.textContent!)
+
+ it('renders a formatted cell per value and series, empty for a series without values', () => {
+ const { container } = render(
+ <Legend items={VALUE_ITEMS} table={{ values: ['mean', 'max'], valueFormatter: (v) => `${v} ms` }} />
+ )
+ const cells = Array.from(container.querySelectorAll('[data-attr="hog-chart-legend-value"]'))
+ expect(cells.map((c) => c.textContent)).toEqual(['10 ms', '30 ms', '25 ms', '5 ms', '', ''])
+ })
+
+ it('sorts by the initial column, then by a clicked header, flipping on a second click', () => {
+ const { container } = render(
+ <Legend items={VALUE_ITEMS} table={{ values: ['mean', 'max'], defaultSort: { by: 'mean' } }} />
+ )
+ expect(labelsOf(container)).toEqual(['Beta', 'Alpha', 'Gamma'])
+ const maxHeader = container.querySelectorAll('[data-attr="hog-chart-legend-sort"]')[2]
+ fireEvent.click(maxHeader)
+ expect(labelsOf(container)).toEqual(['Alpha', 'Beta', 'Gamma'])
+ fireEvent.click(maxHeader)
+ expect(labelsOf(container)).toEqual(['Beta', 'Alpha', 'Gamma'])
+ })
+
+ it('starts an initial name sort A to Z, like a header click', () => {
+ const reversed = [...VALUE_ITEMS].reverse()
+ const { container } = render(
+ <Legend items={reversed} table={{ values: ['mean'], defaultSort: { by: 'label' } }} />
+ )
+ expect(labelsOf(container)).toEqual(['Alpha', 'Beta', 'Gamma'])
+ })
+
+ it('fires onItemClick from a table row', () => {
+ const onClick = jest.fn()
+ const { container } = render(
+ <Legend items={VALUE_ITEMS} table={{ values: ['mean'] }} onItemClick={onClick} />
+ )
+ const rows = Array.from(container.querySelectorAll('button')).filter(
+ (b) => b.dataset.attr !== 'hog-chart-legend-sort'
+ )
+ fireEvent.click(rows[1], { metaKey: true })
+ expect(onClick).toHaveBeenCalledWith('b', { additive: true })
+ })
+ })
})
diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.tsx
index abe33c6c9da9..a2f647ddf8db 100644
--- a/packages/quill/packages/charts/src/components/Legend/Legend.tsx
+++ b/packages/quill/packages/charts/src/components/Legend/Legend.tsx
@@ -1,12 +1,33 @@
/* eslint-disable react/forbid-dom-props -- swatch color and the per-count row cap are dynamic values */
import React from 'react'
+import { LegendTable } from './LegendTable'
+
+/** A per-series summary a legend table can show as a column, computed over the series' finite
+ * values. `delta` is the last value minus the first. */
+export type LegendValue = 'mean' | 'min' | 'max' | 'last' | 'sum' | 'delta'
+
+export interface LegendTableConfig {
+ values: LegendValue[]
+ /** Read on mount only. Omit to keep the series order. A header click changes the sort. */
+ defaultSort?: {
+ by: 'label' | LegendValue
+ /** Defaults to true for a value column and false for `'label'`, the order a header click starts with. */
+ descending?: boolean
+ }
+ /** Formats a value cell. The time-series charts default to the series' axis tick format; the
+ * others to a locale number with significant decimals. */
+ valueFormatter?: (value: number, item: LegendItem) => string
+}
+
export interface LegendItem {
key: string
label: string
color: string
/** Optional trailing text shown muted after the label — e.g. a slope chart's per-series change. */
secondaryLabel?: string
+ /** Per-series summaries for a value-column legend, `null` when the series has no finite value. */
+ values?: Partial<Record<LegendValue, number | null>>
}
/** Which gesture a legend row click was: a plain click means "isolate this series", a modified one
@@ -28,6 +49,7 @@ export interface LegendProps {
/** Wrap each row — receives the default row node and its item, returns the node to render.
* Use to augment rows (e.g. a right-click context menu) while keeping the default rendering. */
renderItem?: (defaultNode: React.ReactNode, item: LegendItem) => React.ReactNode
+ table?: LegendTableConfig
}
// Align a horizontal legend with `justify-content` so wrapped rows stay centered (or start/end) within the
@@ -48,10 +70,24 @@ export function Legend({
className,
dataAttr,
renderItem,
+ table,
}: LegendProps): React.ReactElement | null {
if (items.length === 0) {
return null
}
+ if (table?.values.length) {
+ return (
+ <LegendTable
+ items={items}
+ table={table}
+ onItemClick={onItemClick}
+ hiddenKeys={hiddenKeys}
+ className={className}
+ dataAttr={dataAttr}
+ renderItem={renderItem}
+ />
+ )
+ }
const hidden = hiddenKeys?.length ? new Set(hiddenKeys) : null
const isVertical = orientation === 'vertical'
// A vertical legend stacks from the start edge (justify-start) so it scrolls cleanly when it overflows
diff --git a/packages/quill/packages/charts/src/components/Legend/LegendTable.tsx b/packages/quill/packages/charts/src/components/Legend/LegendTable.tsx
new file mode 100644
index 000000000000..f6c71874eeb3
--- /dev/null
+++ b/packages/quill/packages/charts/src/components/Legend/LegendTable.tsx
@@ -0,0 +1,165 @@
+/* eslint-disable react/forbid-dom-props -- swatch color and the content-sized column widths are dynamic values */
+import React, { useMemo, useState } from 'react'
+
+import { buildYTickFormatter } from '../../utils/y-formatters'
+import type { LegendProps, LegendTableConfig, LegendValue } from './Legend'
+
+const HEADERS: Record<'label' | LegendValue, string> = {
+ label: 'Name',
+ mean: 'Mean',
+ min: 'Min',
+ max: 'Max',
+ last: 'Last',
+ sum: 'Total',
+ delta: 'Delta',
+}
+
+const defaultFormatValue = buildYTickFormatter({})
+
+type SortKey = 'label' | LegendValue
+
+/** The value-column form of {@link Legend}: one row per series with its summaries as columns,
+ * sortable by clicking a header. Rows click and dim exactly like the list legend. */
+export function LegendTable({
+ items,
+ table,
+ onItemClick,
+ hiddenKeys,
+ className,
+ dataAttr,
+ renderItem,
+}: Omit<LegendProps, 'orientation' | 'align' | 'table'> & { table: LegendTableConfig }): React.ReactElement {
+ const { values, valueFormatter: formatValue = defaultFormatValue, defaultSort } = table
+ const [sort, setSort] = useState<{ key: SortKey; descending: boolean } | null>(
+ defaultSort ? { key: defaultSort.by, descending: defaultSort.descending ?? defaultSort.by !== 'label' } : null
+ )
+
+ const cells = useMemo(
+ () =>
+ new Map(
+ items.map((item) => [
+ item.key,
+ values.map((v) => {
+ const value = item.values?.[v]
+ return value == null ? '' : formatValue(value, item)
+ }),
+ ])
+ ),
+ [items, values, formatValue]
+ )
+
+ // Size each column to its widest cell in `ch`, so rows stay aligned even when `renderItem`
+ // wraps them in its own element.
+ const widths = values.map((v, i) =>
+ Math.max(HEADERS[v].length + 2, ...items.map((item) => cells.get(item.key)?.[i].length ?? 0))
+ )
+
+ const rows = useMemo(() => {
+ if (!sort) {
+ return items
+ }
+ const direction = sort.descending ? -1 : 1
+ return [...items].sort((a, b) => {
+ if (sort.key === 'label') {
+ return a.label.localeCompare(b.label) * direction
+ }
+ const x = a.values?.[sort.key]
+ const y = b.values?.[sort.key]
+ // Series without a value sort last in either direction.
+ if (x == null || y == null) {
+ return x == null ? (y == null ? 0 : 1) : -1
+ }
+ return (x - y) * direction
+ })
+ }, [items, sort])
+
+ const hidden = hiddenKeys?.length ? new Set(hiddenKeys) : null
+ const header = (key: SortKey, label: string, width?: number): React.ReactElement => {
+ const active = sort?.key === key
+ return (
+ <button
+ type="button"
+ className={`${width == null ? 'flex-1 min-w-0 text-left' : 'shrink-0 text-right'} cursor-pointer select-none bg-transparent border-0 p-0 font-medium text-(--color-graph-axis-label) whitespace-nowrap`}
+ style={width == null ? undefined : { width: `${width}ch` }}
+ aria-label={
+ active ? `${label}, sorted ${sort.descending ? 'descending' : 'ascending'}` : `Sort by ${label}`
+ }
+ data-attr="hog-chart-legend-sort"
+ onClick={() =>
+ // Values start highest first and names A to Z, then each click flips the order.
+ setSort((prev) => ({
+ key,
+ descending: prev?.key === key ? !prev.descending : key !== 'label',
+ }))
+ }
+ >
+ {label}
+ {active ? (sort.descending ? ' ↓' : ' ↑') : ''}
+ </button>
+ )
+ }
+
+ return (
+ <div
+ className={`flex flex-col w-full text-xs leading-4 tabular-nums ${className ?? ''}`}
+ data-attr={dataAttr}
+ data-hog-charts-legend=""
+ >
+ <div className="flex items-center gap-3 px-1 pb-1">
+ {header('label', HEADERS.label)}
+ {values.map((v, i) => (
+ <React.Fragment key={v}>{header(v, HEADERS[v], widths[i])}</React.Fragment>
+ ))}
+ </div>
+ {rows.map((item) => {
+ const rowClass = `flex w-full min-w-0 items-center gap-3 px-1 py-0.5 rounded text-left${hidden?.has(item.key) ? ' opacity-40' : ''}`
+ const inner = (
+ <>
+ <span className="flex flex-1 min-w-0 items-center gap-1.5">
+ <span
+ aria-hidden="true"
+ 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} data-attr="hog-chart-legend-label">
+ {item.label}
+ </span>
+ {item.secondaryLabel != null && item.secondaryLabel !== '' && (
+ <span
+ className="shrink-0 text-(--color-graph-axis-label)"
+ data-attr="hog-chart-legend-secondary"
+ >
+ {item.secondaryLabel}
+ </span>
+ )}
+ </span>
+ {cells.get(item.key)?.map((text, i) => (
+ <span
+ key={values[i]}
+ className="shrink-0 text-right whitespace-nowrap"
+ style={{ width: `${widths[i]}ch` }}
+ data-attr="hog-chart-legend-value"
+ >
+ {text}
+ </span>
+ ))}
+ </>
+ )
+ const node = onItemClick ? (
+ <button
+ type="button"
+ className={`${rowClass} cursor-pointer select-none bg-transparent border-0 hover:bg-current/5 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent`}
+ onClick={(event) =>
+ onItemClick(item.key, { additive: event.metaKey || event.ctrlKey || event.shiftKey })
+ }
+ >
+ {inner}
+ </button>
+ ) : (
+ <div className={rowClass}>{inner}</div>
+ )
+ return <React.Fragment key={item.key}>{renderItem ? renderItem(node, item) : node}</React.Fragment>
+ })}
+ </div>
+ )
+}
diff --git a/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.test.ts b/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.test.ts
index a1a537e986e6..7ef1ef91e3f4 100644
--- a/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.test.ts
+++ b/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.test.ts
@@ -1,5 +1,5 @@
import type { ChartTheme, Series } from '../../core/types'
-import { legendItemsFromSeries } from './legendItemsFromSeries'
+import { computeLegendValues, legendItemsFromSeries } from './legendItemsFromSeries'
const THEME: ChartTheme = { colors: ['#aaa', '#bbb', '#ccc'], backgroundColor: '#fff' }
@@ -24,4 +24,15 @@ describe('legendItemsFromSeries', () => {
expect(items.map((i) => i.key)).toEqual(['a', 'c'])
expect(items.find((i) => i.key === 'c')!.color).toBe('#ccc')
})
+
+ it.each([
+ ['skips missing points', [3, NaN, 1, 5], { mean: 3, min: 1, max: 5, last: 5, sum: 9, delta: 2 }],
+ [
+ 'is null for a series without finite values',
+ [NaN],
+ { mean: null, min: null, max: null, last: null, sum: null, delta: null },
+ ],
+ ])('computeLegendValues %s', (_, data, expected) => {
+ expect(computeLegendValues(data, ['mean', 'min', 'max', 'last', 'sum', 'delta'])).toEqual(expected)
+ })
})
diff --git a/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.ts b/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.ts
index 30c376b6b50a..5ab6ec47734a 100644
--- a/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.ts
+++ b/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.ts
@@ -1,7 +1,11 @@
import type { ChartTheme, ResolvedSeries, Series } from '../../core/types'
-import type { LegendItem } from './Legend'
+import type { LegendItem, LegendValue } from './Legend'
-export function legendItemsFromSeries(series: ReadonlyArray<Series | ResolvedSeries>, theme: ChartTheme): LegendItem[] {
+export function legendItemsFromSeries(
+ series: ReadonlyArray<Series | ResolvedSeries>,
+ theme: ChartTheme,
+ values?: readonly LegendValue[]
+): LegendItem[] {
const palette = theme.colors
const items: LegendItem[] = []
for (let i = 0; i < series.length; i++) {
@@ -10,7 +14,56 @@ export function legendItemsFromSeries(series: ReadonlyArray<Series | ResolvedSer
continue
}
const fallback = palette.length > 0 ? palette[i % palette.length] : '#000'
- items.push({ key: s.key, label: s.label, color: s.color || fallback })
+ const item: LegendItem = { key: s.key, label: s.label, color: s.color || fallback }
+ if (values?.length) {
+ item.values = computeLegendValues(s.data, values)
+ }
+ items.push(item)
}
return items
}
+
+/** Fills value-column summaries into legend rows built elsewhere (a chart's own items), matching
+ * each row to its series by key. Rows that already carry values keep them. */
+export function withLegendValues(
+ items: LegendItem[],
+ series: ReadonlyArray<Series | ResolvedSeries>,
+ values: readonly LegendValue[] | undefined
+): LegendItem[] {
+ if (!values?.length) {
+ return items
+ }
+ const dataByKey = new Map(series.map((s) => [s.key, s.data]))
+ return items.map((item) =>
+ item.values ? item : { ...item, values: computeLegendValues(dataByKey.get(item.key), values) }
+ )
+}
+
+/** Summaries of a series' finite values, `null` for a series without any. */
+export function computeLegendValues(
+ data: readonly number[] | null | undefined,
+ values: readonly LegendValue[]
+): Partial<Record<LegendValue, number | null>> {
+ let count = 0
+ let sum = 0
+ let min = Infinity
+ let max = -Infinity
+ let first: number | null = null
+ let last: number | null = null
+ for (const v of data ?? []) {
+ if (v == null || !isFinite(v)) {
+ continue
+ }
+ count++
+ sum += v
+ min = Math.min(min, v)
+ max = Math.max(max, v)
+ first ??= v
+ last = v
+ }
+ const all: Record<LegendValue, number | null> =
+ first === null || last === null
+ ? { mean: null, min: null, max: null, last: null, sum: null, delta: null }
+ : { mean: sum / count, min, max, last, sum, delta: last - first }
+ return Object.fromEntries(values.map((v) => [v, all[v]]))
+}
diff --git a/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts b/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts
index d5ae1cdfac06..9023a433583b 100644
--- a/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts
+++ b/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts
@@ -1,8 +1,8 @@
import { useMemo, useState, type ReactNode } from 'react'
import type { ChartLegendConfig, ChartTheme, Series } from '../../core/types'
-import type { LegendItem, LegendItemClickModifiers } from './Legend'
-import { legendItemsFromSeries } from './legendItemsFromSeries'
+import type { LegendItem, LegendItemClickModifiers, LegendTableConfig, LegendValue } from './Legend'
+import { legendItemsFromSeries, withLegendValues } from './legendItemsFromSeries'
/** True when the primary pointer is coarse (a touch screen), read live at click time. Guarded like
* `prefersReducedMotion` because `matchMedia` is absent in jsdom test workers and other non-browser
@@ -58,6 +58,7 @@ export interface ChartLegendRenderProps {
onItemClick?: (key: string, modifiers: LegendItemClickModifiers) => void
hiddenKeys: string[]
renderItem?: (defaultNode: ReactNode, item: LegendItem) => ReactNode
+ table?: LegendTableConfig
}
export interface ChartLegendState<Meta> {
@@ -92,7 +93,14 @@ export function useChartLegend<Meta>(
const hiddenSet = useMemo(() => new Set(hiddenKeys), [hiddenKeys])
const visibleSeries = useMemo(() => applyHiddenSeries(series, hiddenSet), [series, hiddenSet])
- const derivedItems = items ?? legendItemsFromSeries(series, theme)
+ // Keyed on the column names, so an inline `values` array doesn't recompute every series' summaries.
+ const valuesKey = config?.show ? config.table?.values.join(',') : undefined
+ const legendValues = useMemo(() => (valuesKey ? (valuesKey.split(',') as LegendValue[]) : undefined), [valuesKey])
+ const derivedItems = useMemo(
+ () =>
+ items ? withLegendValues(items, series, legendValues) : legendItemsFromSeries(series, theme, legendValues),
+ [items, series, theme, legendValues]
+ )
const interactive = config?.interactive ?? true
@@ -174,6 +182,7 @@ export function useChartLegend<Meta>(
onItemClick: interactive ? handleItemClick : undefined,
hiddenKeys,
renderItem,
+ table: legendValues && config?.table ? { ...config.table, values: legendValues } : undefined,
},
}
}
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index 317fc3bf4be1..ccae6622eff5 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -1,6 +1,6 @@
import type { ReactNode } from 'react'
-import type { LegendItem } from '../components/Legend/Legend'
+import type { LegendItem, LegendTableConfig } from '../components/Legend/Legend'
import type { LegendItemControls } from '../components/Legend/useChartLegend'
import type { DefaultTooltipProps } from '../overlays/DefaultTooltip'
@@ -381,6 +381,9 @@ export interface ChartLegendConfig {
* while keeping the default swatch/label/toggle rendering. Return `defaultNode` to leave a row
* untouched. */
renderItem?: (defaultNode: ReactNode, item: LegendItem, controls: LegendItemControls) => ReactNode
+ /** Renders the legend as a table with one column per summary (`{ values: ['mean', 'max', 'last'] }`).
+ * Rows still isolate and toggle on click, and a header click sorts by that column. */
+ table?: LegendTableConfig
}
export interface TooltipConfig extends Pick<DefaultTooltipProps, 'labelRenderer' | 'showHeader' | 'hideZeroRows'> {
diff --git a/packages/quill/packages/charts/src/docs/TESTING.md b/packages/quill/packages/charts/src/docs/TESTING.md
index 4db9338245bf..f97592461429 100644
--- a/packages/quill/packages/charts/src/docs/TESTING.md
+++ b/packages/quill/packages/charts/src/docs/TESTING.md
@@ -55,6 +55,8 @@ chart.anomalyPoints() // [{ element, color }, …] (TimeSeriesLineChart)
chart.legend() // legend container in the render scope, null when hidden
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
+chart.legendValues() // [['12 ms', '40 ms'], …] value-table cells per legend row
+chart.sortLegendBy('Max') // click a value-table header to sort by that column
chart.slope.valueLabels() // [{ text, color, side }, …] slope value labels, start and end columns
chart.slope.seriesLabels() // slope series names, after collision avoidance
chart.sankey.nodeLabels() // ['/home', '/pricing', …] Sankey node labels in layout order, after overlap hiding
diff --git a/packages/quill/packages/charts/src/docs/legend.md b/packages/quill/packages/charts/src/docs/legend.md
index 4107a6ff80ed..c52594b2c1d7 100644
--- a/packages/quill/packages/charts/src/docs/legend.md
+++ b/packages/quill/packages/charts/src/docs/legend.md
@@ -54,6 +54,21 @@ On time-series charts the legend lists the user's series only, and hiding a seri
- Long labels clip with an ellipsis only when they run out of available space. A vertical legend truncates at the column edge. A horizontal legend caps each row at an equal share of the line floored at 180px, because flexbox wraps before it shrinks and one long label would otherwise take a whole line. The full text is always in a native `title` tooltip.
- `LegendItem.secondaryLabel` shows muted trailing text (a slope chart's per-series change).
+## Value table
+
+`table: { values: ['mean', 'max', 'last'] }` renders the legend as a table with one column per summary: `mean`, `min`, `max`, `last`, `sum`, `delta`.
+Each is computed over the series' finite values, so `last` skips missing points and `delta` is the last finite value minus the first.
+A series with no finite value shows empty cells.
+Rows click, dim, and take `renderItem` exactly like the list legend.
+A header click sorts by that column: values start highest first and names A to Z, and a second click flips the order.
+`table.defaultSort: { by, descending? }` sets the sort on mount, in the same direction a header click starts with unless `descending` says otherwise.
+`table.valueFormatter(value, item)` formats a cell; the time-series charts default it to the tick format of the series' own axis.
+A percent chart, and a secondary axis without a format, keep the plain number format, because legend values are raw.
+`BoxPlot` and `ScatterChart` take no `table`.
+The summaries are computed only while the legend is shown.
+A left or right table legend gets more width than a list legend, up to 60% of the chart or 480px.
+On a chart narrower than 480px it moves below the plot (above for `left`), so the plot and the series names keep their room.
+
## Lower-level primitives
`Legend` (and `ChartLegend` for layout) is the presentational primitive: pass `items`, `onItemClick`, `hiddenKeys`; filtering series is the caller's state.
@@ -62,4 +77,4 @@ Use it directly when `config.legend` cannot express what you need (custom item o
`useChartLegend(series, theme, config, items?)` is the shared hook the charts use.
It returns `visibleSeries` (hidden applied as `visibility.excluded`) plus `legendProps` to spread onto `<ChartLegend>`.
-`applyHiddenSeries` is the underlying helper, and `legendItemsFromSeries(series, theme)` builds the item list.
+`applyHiddenSeries` is the underlying helper, and `legendItemsFromSeries(series, theme, values?)` builds the item list.
diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.ts
index f4b8725eca93..bf1a9e5adad1 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -273,7 +273,13 @@ export { ciRanges, linearRegression, movingAverage, trendLine } from './utils/st
// Generic UI primitives (no canvas) — composed alongside charts by adapters
export { Legend } from './components/Legend/Legend'
-export type { LegendItem, LegendItemClickModifiers, LegendProps } from './components/Legend/Legend'
+export type {
+ LegendItem,
+ LegendItemClickModifiers,
+ LegendProps,
+ LegendTableConfig,
+ LegendValue,
+} from './components/Legend/Legend'
export { ChartLegend } from './components/Legend/ChartLegend'
export type { ChartLegendProps } from './components/Legend/ChartLegend'
export { legendItemsFromSeries } from './components/Legend/legendItemsFromSeries'
diff --git a/packages/quill/packages/charts/src/testing/accessor.ts b/packages/quill/packages/charts/src/testing/accessor.ts
index 3e8485c5287b..5e30caac579b 100644
--- a/packages/quill/packages/charts/src/testing/accessor.ts
+++ b/packages/quill/packages/charts/src/testing/accessor.ts
@@ -147,6 +147,12 @@ export interface ChartAccessor<Meta = unknown> {
/** 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
+ /** Click the value-table header with this text, which sorts the legend by that column. Throws
+ * when no header has the text. */
+ sortLegendBy(header: string): void
+ /** The value-table cells of each legend row as rendered, in row then column order. Empty for a
+ * list legend. */
+ legendValues(): string[][]
/** Fire one `mouseMove` over the label at `index`, without waiting for a tooltip. */
hoverAtIndex(index: number): void
/** Hover the label at `index` until the tooltip shows its content, then read it as a `DefaultTooltip`.
@@ -357,6 +363,26 @@ export function getChart<Meta = unknown>(
fireEvent.click(row, { metaKey: additive })
})
},
+ legendValues: () =>
+ Array.from(scope.querySelectorAll<HTMLElement>('[data-attr="hog-chart-legend-label"]'), (labelEl) =>
+ Array.from(
+ labelEl
+ .closest('button, div')
+ ?.querySelectorAll<HTMLElement>('[data-attr="hog-chart-legend-value"]') ?? [],
+ (cell) => cell.textContent ?? ''
+ )
+ ).filter((cells) => cells.length > 0),
+ sortLegendBy(header: string): void {
+ const button = Array.from(scope.querySelectorAll<HTMLElement>('[data-attr="hog-chart-legend-sort"]')).find(
+ (el) => el.textContent?.replace(/ [↑↓]$/, '') === header
+ )
+ if (!button) {
+ throw new Error(`No legend column headed "${header}"`)
+ }
+ act(() => {
+ fireEvent.click(button)
+ })
+ },
hoverAtIndex(index: number): void {
hoverAtIndex(wrapper, index, labelCount())
},