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(charts): add click-to-toggle series visibility to chart legends (#64467)

Sam Penningtond60d2d3dc32f
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index c035ee2eb756..5a3f6c319deb 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -67,7 +67,8 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`) compose as children.
- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).
- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original.
-- `Legend` is presentational: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change).
+- Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `SlopeChart`) takes a `config.legend: ChartLegendConfig` (`{ show, position, align, gap, interactive, hiddenKeys, defaultHiddenKeys, onToggleSeries }`). With `show: true` the chart renders a built-in legend that, by default (`interactive`), is click-to-toggle: clicking a row hides that series (no draw, no scale contribution, no tooltip — the axes rescale into the freed space) while the row stays listed but dimmed so it can be restored. The chart owns the toggled-off state (uncontrolled); set `interactive: false` for a static legend, or pass `hiddenKeys` + `onToggleSeries` to control it yourself. Hidden by default. Toggling on time-series charts lists the user's series only (not derived trend lines / CI bands) — and hiding a series also hides everything derived from it (its CI band, moving average, and trend line), so no orphaned overlay floats over the gap.
+- `Legend` (and `ChartLegend` for layout) is the lower-level presentational primitive: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. Use it directly when the built-in `config.legend` can't express what you need (custom item order/labels). `useChartLegend(series, theme, config, items?)` is the shared hook the charts use — returns `visibleSeries` (hidden applied as `visibility.excluded`) plus `legendProps` to spread onto `<ChartLegend>`; `applyHiddenSeries` is the underlying helper. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change).
- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order) and formats values with `valueFormatter` so they match the on-chart labels' units; pass your own `tooltip` to override. (`DefaultTooltip` itself takes an optional `valueFormatter` for the same reason — without it values fall back to `toLocaleString`.) Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.
- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis.
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
index 6386a0275d06..5a0aa91f6bea 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
@@ -2,7 +2,7 @@ import { fireEvent, waitFor } from '@testing-library/react'
import type { BarChartConfig, ChartTheme, PointClickData, Series } from '../../core/types'
import { ReferenceLine } from '../../overlays/ReferenceLine'
-import { getHogChartTooltip, renderHogChart } from '../../testing'
+import { getHogChart, getHogChartTooltip, renderHogChart } from '../../testing'
import { dimensions } from '../../testing/jsdom'
import { BarChart } from './BarChart'
@@ -104,7 +104,13 @@ describe('BarChart', () => {
})
it('tolerates NaN data values without throwing', () => {
- const broken: Series[] = [{ key: 'a', label: 'A', data: [Number.NaN, Number.NaN, Number.NaN] }]
+ const broken: Series[] = [
+ {
+ key: 'a',
+ label: 'A',
+ data: [Number.NaN, Number.NaN, Number.NaN],
+ },
+ ]
const { chart } = renderHogChart(<BarChart series={broken} labels={LABELS} theme={THEME} />)
expect(chart.seriesCount).toBe(1)
})
@@ -115,7 +121,12 @@ describe('BarChart', () => {
(barLayout) => {
const series: Series[] = [
{ key: 'a', label: 'A', data: [10, 20, 30] },
- { key: 'b', label: 'B', data: [5, 15, 25], visibility: { excluded: true } },
+ {
+ key: 'b',
+ label: 'B',
+ data: [5, 15, 25],
+ visibility: { excluded: true },
+ },
{ key: 'c', label: 'C', data: [3, 6, 9] },
]
const { chart } = renderHogChart(
@@ -316,7 +327,12 @@ describe('BarChart', () => {
)
await chart.clickAtIndex(1)
const clickData: PointClickData = onPointClick.mock.calls[0][0]
- expect(clickData.crossSeriesData.map((d) => ({ key: d.series.key, value: d.value }))).toEqual([
+ expect(
+ clickData.crossSeriesData.map((d) => ({
+ key: d.series.key,
+ value: d.value,
+ }))
+ ).toEqual([
{ key: 'a', value: 20 },
{ key: 'b', value: 15 },
])
@@ -346,7 +362,10 @@ describe('BarChart', () => {
series={SERIES}
labels={LABELS}
theme={THEME}
- config={{ barLayout: 'stacked', axisOrientation: 'horizontal' }}
+ config={{
+ barLayout: 'stacked',
+ axisOrientation: 'horizontal',
+ }}
/>
)
// plotHeight/2 lands in the middle row (Tue), which stacks to 35 while the value axis
@@ -379,7 +398,10 @@ describe('BarChart', () => {
{ key: 'mid', label: 'Mid', data: [0, 50, 0] },
{ key: 'small', label: 'Small', data: [0, 0, 20] },
]
- const HORIZONTAL_STACKED: BarChartConfig = { barLayout: 'stacked', axisOrientation: 'horizontal' }
+ const HORIZONTAL_STACKED: BarChartConfig = {
+ barLayout: 'stacked',
+ axisOrientation: 'horizontal',
+ }
// Value scale `[0, 100]` (already nice).
const xForValue = (value: number): number => dimensions.plotLeft + (value / 100) * dimensions.plotWidth
const yMidBand = dimensions.plotTop + dimensions.plotHeight / 2
@@ -536,7 +558,12 @@ describe('BarChart', () => {
it('omits a series from tooltip when visibility.tooltip is false', async () => {
const series: Series[] = [
{ key: 'a', label: 'A', data: [10, 20, 30] },
- { key: 'b', label: 'B', data: [5, 15, 25], visibility: { tooltip: false } },
+ {
+ key: 'b',
+ label: 'B',
+ data: [5, 15, 25],
+ visibility: { tooltip: false },
+ },
]
const { chart } = renderHogChart(<BarChart series={series} labels={LABELS} theme={THEME} />)
chart.hoverAtIndex(1)
@@ -585,4 +612,27 @@ describe('BarChart', () => {
}
})
})
+
+ describe('interactive legend', () => {
+ it('renders no legend by default', () => {
+ const { container } = renderHogChart(<BarChart series={SERIES} labels={LABELS} theme={THEME} />)
+ expect(container.querySelector('[data-attr="hog-chart-bar-legend"]')).toBeNull()
+ })
+
+ it('toggles a series off and on when its legend row is clicked', () => {
+ const { container, chart } = renderHogChart(
+ <BarChart series={SERIES} labels={LABELS} theme={THEME} config={{ legend: { show: true } }} />
+ )
+ expect(chart.seriesCount).toBe(2)
+ const buttons = (): HTMLButtonElement[] =>
+ Array.from(container.querySelectorAll('[data-attr="hog-chart-bar-legend"] button'))
+
+ fireEvent.click(buttons()[1])
+ expect(getHogChart(container).seriesCount).toBe(1)
+ expect(buttons()[1].className).toContain('opacity-40')
+
+ fireEvent.click(buttons()[1])
+ expect(getHogChart(container).seriesCount).toBe(2)
+ })
+ })
})
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
index 2329f3e427b5..6884bf723e87 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
@@ -1,5 +1,7 @@
import React, { useCallback, useMemo, useRef } from 'react'
+import { ChartLegend } from '../../components/Legend/ChartLegend'
+import { useChartLegend } from '../../components/Legend/useChartLegend'
import { bandCenter, type BarChartPrivate, groupedBarCenter } from '../../core/bar-layout'
import { Chart } from '../../core/Chart'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
@@ -95,28 +97,38 @@ function BarChartInner<Meta = unknown>({
const barTrack = trackConfig !== false
const barTrackHover = trackConfig === true || (typeof trackConfig === 'object' && trackConfig.hover !== false)
+ const { visibleSeries, legendProps } = useChartLegend(series, theme, config?.legend)
+
const resolvedMinBandSize = minBandSize ?? (isHorizontal ? HORIZONTAL_MIN_BAND_SIZE_DEFAULT : 0)
const wrapperMinHeight = useMemo(
- () => computeWrapperMinHeight({ isHorizontal, fitToHeight, resolvedMinBandSize, labels }),
+ () =>
+ computeWrapperMinHeight({
+ isHorizontal,
+ fitToHeight,
+ resolvedMinBandSize,
+ labels,
+ }),
[isHorizontal, fitToHeight, resolvedMinBandSize, labels]
)
const stackedData = useMemo((): Map<string, StackedBand> | undefined => {
if (barLayout === 'percent') {
- return computePercentStackData(series, labels)
+ return computePercentStackData(visibleSeries, labels)
}
if (barLayout === 'stacked') {
- return divergingStack ? computeDivergingStackData(series, labels) : computeStackData(series, labels)
+ return divergingStack
+ ? computeDivergingStackData(visibleSeries, labels)
+ : computeStackData(visibleSeries, labels)
}
return undefined
- }, [barLayout, series, labels, divergingStack])
+ }, [barLayout, visibleSeries, labels, divergingStack])
// Cap rounding is per-axis: buildStackData stacks each yAxisId independently, so each
// axis has its own topmost visible series. Iteration order matches d3.stack's key order,
// so the last write per axis is that axis's top layer.
const topStackedKeyByAxis = useMemo<Map<string, string>>(
- () => (barLayout === 'grouped' ? new Map() : computeTopStackedKeyByAxis(series)),
- [barLayout, series]
+ () => (barLayout === 'grouped' ? new Map() : computeTopStackedKeyByAxis(visibleSeries)),
+ [barLayout, visibleSeries]
)
const chartConfig = useMemo<BarChartConfig>(() => {
@@ -147,7 +159,11 @@ function BarChartInner<Meta = unknown>({
if (divergingStack) {
return [
{ ...s, data: band.top },
- { ...s, key: `${s.key}__bottom`, data: band.bottom },
+ {
+ ...s,
+ key: `${s.key}__bottom`,
+ data: band.bottom,
+ },
]
}
return [{ ...s, data: band.top }]
@@ -304,7 +320,12 @@ function BarChartInner<Meta = unknown>({
alpha = resetHoverFade()
lastHoverKeyRef.current = currentKey
}
- drawBarHoverItems(ctx, d3Scales, resolved, { alpha, barCornerRadius, barTrack, isHorizontal })
+ drawBarHoverItems(ctx, d3Scales, resolved, {
+ alpha,
+ barCornerRadius,
+ barTrack,
+ isHorizontal,
+ })
return true
},
[
@@ -324,7 +345,7 @@ function BarChartInner<Meta = unknown>({
const resolveValue = useMemo(() => buildSegmentResolveValue(stackedData), [stackedData])
const resolvePositionValue = useMemo(() => buildStackedPositionValue(stackedData), [stackedData])
- const seriesRef = useLatest(series)
+ const seriesRef = useLatest(visibleSeries)
const labelsRef = useLatest(labels)
// Bars sharing a band slot — rewrite the click payload to the series actually under the
@@ -353,7 +374,7 @@ function BarChartInner<Meta = unknown>({
const chart = (
<Chart
- series={series}
+ series={visibleSeries}
labels={labels}
config={chartConfig}
theme={theme}
@@ -364,7 +385,7 @@ function BarChartInner<Meta = unknown>({
<BarTooltip<Meta>
ctx={ctx}
userTooltip={tooltip}
- allSeries={series}
+ allSeries={visibleSeries}
stackedData={stackedData}
topStackedKeyByAxis={topStackedKeyByAxis}
layout={barLayout}
@@ -384,8 +405,10 @@ function BarChartInner<Meta = unknown>({
// Always wrap — switching shape (axisOrientation, empty labels) would otherwise remount Chart.
return (
- <div className="flex flex-col flex-1" style={{ minHeight: wrapperMinHeight }}>
- {chart}
- </div>
+ <ChartLegend {...legendProps} legendDataAttr="hog-chart-bar-legend">
+ <div className="flex flex-col flex-1" style={{ minHeight: wrapperMinHeight }}>
+ {chart}
+ </div>
+ </ChartLegend>
)
}
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx
index ab1fe8827b60..2e879533132b 100644
--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx
@@ -1,8 +1,15 @@
+import { fireEvent } from '@testing-library/react'
+
import type { ChartTheme, Series } from '../../core/types'
import { ReferenceLine } from '../../overlays/ReferenceLine'
-import { dimensions as testDimensions, rawDrag, renderHogChart } from '../../testing'
+import { dimensions as testDimensions, getHogChart, rawDrag, renderHogChart } from '../../testing'
import { LineChart } from './LineChart'
+function legendButtons(container: HTMLElement): HTMLButtonElement[] {
+ const legend = container.querySelector('[data-attr="hog-chart-line-legend"]')
+ return legend ? Array.from(legend.querySelectorAll('button')) : []
+}
+
const THEME: ChartTheme = {
colors: ['#1f77b4', '#ff7f0e', '#2ca02c'],
backgroundColor: '#ffffff',
@@ -35,7 +42,12 @@ describe('LineChart', () => {
it('skips excluded series', () => {
const series: Series[] = [
{ key: 'a', label: 'A', data: [10, 20, 30] },
- { key: 'b', label: 'B', data: [5, 15, 25], visibility: { excluded: true } },
+ {
+ key: 'b',
+ label: 'B',
+ data: [5, 15, 25],
+ visibility: { excluded: true },
+ },
{ key: 'c', label: 'C', data: [3, 6, 9] },
]
const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)
@@ -71,7 +83,13 @@ describe('LineChart', () => {
})
it('tolerates NaN data values without throwing', () => {
- const broken: Series[] = [{ key: 'a', label: 'A', data: [Number.NaN, Number.NaN, Number.NaN] }]
+ const broken: Series[] = [
+ {
+ key: 'a',
+ label: 'A',
+ data: [Number.NaN, Number.NaN, Number.NaN],
+ },
+ ]
const { chart } = renderHogChart(<LineChart series={broken} labels={LABELS} theme={THEME} />)
expect(chart.seriesCount).toBe(1)
})
@@ -105,7 +123,10 @@ describe('LineChart', () => {
series={SERIES}
labels={LABELS}
theme={THEME}
- config={{ xAxisLabel: 'Signup date', yAxisLabel: 'Unique users' }}
+ config={{
+ xAxisLabel: 'Signup date',
+ yAxisLabel: 'Unique users',
+ }}
/>
)
expect(chart.xAxisLabel()).toBe('Signup date')
@@ -118,7 +139,10 @@ describe('LineChart', () => {
series={SERIES}
labels={LABELS}
theme={THEME}
- config={{ xAxisLabel: 'Signup date', yAxisLabel: 'Unique users' }}
+ config={{
+ xAxisLabel: 'Signup date',
+ yAxisLabel: 'Unique users',
+ }}
/>
)
expect(getByRole('img').getAttribute('aria-label')).toBe(
@@ -165,7 +189,11 @@ describe('LineChart', () => {
series={SERIES}
labels={LABELS}
theme={THEME}
- config={{ xAxisLabel: 'Signup date', yAxisLabel: 'Unique users', hideXAxis: true }}
+ config={{
+ xAxisLabel: 'Signup date',
+ yAxisLabel: 'Unique users',
+ hideXAxis: true,
+ }}
/>
)
expect(chart.xAxisLabel()).toBeNull()
@@ -175,7 +203,12 @@ describe('LineChart', () => {
it('renders a right axis when a series sets yAxisId: right', () => {
const series: Series[] = [
{ key: 'a', label: 'A', data: [10, 20, 30] },
- { key: 'b', label: 'B', data: [1000, 2000, 3000], yAxisId: 'right' },
+ {
+ key: 'b',
+ label: 'B',
+ data: [1000, 2000, 3000],
+ yAxisId: 'right',
+ },
]
const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)
expect(chart.hasRightAxis).toBe(true)
@@ -186,7 +219,12 @@ describe('LineChart', () => {
const series: Series[] = [
{ key: 'a', label: 'A', data: [10, 20, 30] },
{ key: 'b', label: 'B', data: [100, 200, 300], yAxisId: 'y1' },
- { key: 'c', label: 'C', data: [3000, 4000, 5000], yAxisId: 'y2' },
+ {
+ key: 'c',
+ label: 'C',
+ data: [3000, 4000, 5000],
+ yAxisId: 'y2',
+ },
]
const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)
expect(chart.hasRightAxis).toBe(true)
@@ -224,7 +262,11 @@ describe('LineChart', () => {
)
await chart.clickAtIndex(1)
expect(onPointClick).toHaveBeenCalledWith(
- expect.objectContaining({ dataIndex: 1, label: 'Tue', value: 20 })
+ expect.objectContaining({
+ dataIndex: 1,
+ label: 'Tue',
+ value: 20,
+ })
)
})
@@ -258,7 +300,12 @@ describe('LineChart', () => {
it('omits a series from tooltip when visibility.tooltip is false', async () => {
const series: Series[] = [
{ key: 'a', label: 'A', data: [10, 20, 30] },
- { key: 'b', label: 'B', data: [5, 15, 25], visibility: { tooltip: false } },
+ {
+ key: 'b',
+ label: 'B',
+ data: [5, 15, 25],
+ visibility: { tooltip: false },
+ },
]
const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)
chart.hoverAtIndex(1)
@@ -486,4 +533,48 @@ describe('LineChart', () => {
}
})
})
+
+ describe('interactive legend', () => {
+ it('renders no legend by default', () => {
+ const { container } = renderHogChart(<LineChart series={SERIES} labels={LABELS} theme={THEME} />)
+ expect(container.querySelector('[data-attr="hog-chart-line-legend"]')).toBeNull()
+ })
+
+ it('renders a clickable legend item per series when legend.show is set', () => {
+ const { container } = renderHogChart(
+ <LineChart series={SERIES} labels={LABELS} theme={THEME} config={{ legend: { show: true } }} />
+ )
+ expect(legendButtons(container).map((b) => b.textContent)).toEqual(['A', 'B'])
+ })
+
+ it('hides a series on legend click and shows it again on a second click', () => {
+ const { container, chart } = renderHogChart(
+ <LineChart series={SERIES} labels={LABELS} theme={THEME} config={{ legend: { show: true } }} />
+ )
+ expect(chart.seriesCount).toBe(2)
+
+ fireEvent.click(legendButtons(container)[1])
+ expect(getHogChart(container).seriesCount).toBe(1)
+ // The toggled-off row stays in the legend (dimmed) so it can be restored.
+ const dimmed = legendButtons(container).filter((b) => b.className.includes('opacity-40'))
+ expect(dimmed.map((b) => b.textContent)).toEqual(['B'])
+
+ fireEvent.click(legendButtons(container)[1])
+ expect(getHogChart(container).seriesCount).toBe(2)
+ })
+
+ it('renders a static (non-clickable) legend when interactive is false', () => {
+ const { container } = renderHogChart(
+ <LineChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ legend: { show: true, interactive: false } }}
+ />
+ )
+ const legend = container.querySelector('[data-attr="hog-chart-line-legend"]')!
+ expect(legend.querySelectorAll('button')).toHaveLength(0)
+ expect(legend.textContent).toBe('AB')
+ })
+ })
})
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
index 4ad7cdee796c..378d8b17609b 100644
--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
@@ -1,5 +1,7 @@
import React, { useCallback, useMemo } from 'react'
+import { ChartLegend } from '../../components/Legend/ChartLegend'
+import { useChartLegend } from '../../components/Legend/useChartLegend'
import { drawArea, drawAxes, drawGrid, drawLine, drawLineHoverPoints, drawPoints } from '../../core/canvas-renderer'
import type { DrawContext } from '../../core/canvas-renderer'
import { withVerticalClip } from '../../core/canvas-renderer'
@@ -80,23 +82,25 @@ function LineChartInner<Meta = unknown>({
valueDomain,
} = config ?? {}
+ const { visibleSeries, legendProps } = useChartLegend(series, theme, config?.legend)
+
const hasMultipleFilledSeries = useMemo(() => {
- const filledSeries = series.filter((s) => s.fill && !s.fill.lowerData)
+ const filledSeries = visibleSeries.filter((s) => s.fill && !s.fill.lowerData)
return filledSeries.length >= 2
- }, [series])
+ }, [visibleSeries])
const stackedData = useMemo((): Map<string, StackedBand> | undefined => {
if (percentStackView) {
- return computePercentStackData(series, labels)
+ return computePercentStackData(visibleSeries, labels)
}
// Only stack when there are 2+ fillable series — a single area series has nothing to stack
// against, and forcing a stacked band would feed a `bottomValues` array into the canvas
// renderer, which disables the gradient fill path.
if (hasMultipleFilledSeries) {
- return computeStackData(series, labels)
+ return computeStackData(visibleSeries, labels)
}
return undefined
- }, [percentStackView, hasMultipleFilledSeries, series, labels])
+ }, [percentStackView, hasMultipleFilledSeries, visibleSeries, labels])
const chartConfig = useMemo(() => {
const base = { ...config, isPercent: percentStackView }
@@ -134,7 +138,9 @@ function LineChartInner<Meta = unknown>({
// a side-channel ref — every render gets a self-contained ChartScales object,
// which avoids strict-mode / concurrent-rendering races between the createScales
// pass and the static-draw effect.
- const lineChartPrivate: LineChartPrivate = { __lineChart: d3Scales }
+ const lineChartPrivate: LineChartPrivate = {
+ __lineChart: d3Scales,
+ }
return {
x: (label: string) => d3Scales.x(label),
@@ -181,7 +187,10 @@ function LineChartInner<Meta = unknown>({
continue
}
- const drawCtx: DrawContext = { ...baseDrawCtx, yScale: resolveYScale(s) }
+ const drawCtx: DrawContext = {
+ ...baseDrawCtx,
+ yScale: resolveYScale(s),
+ }
const band = stackedData?.get(s.key)
const yValues = band?.top
@@ -212,7 +221,10 @@ function LineChartInner<Meta = unknown>({
if (x == null) {
return null
}
- return { x, y: resolveYScaleForSeries(scales, s)(data[hoverIndex]) }
+ return {
+ x,
+ y: resolveYScaleForSeries(scales, s)(data[hoverIndex]),
+ }
})
},
[stackedData]
@@ -224,23 +236,25 @@ function LineChartInner<Meta = unknown>({
const resolvePositionValue = useMemo(() => buildStackedPositionValue(stackedData), [stackedData])
return (
- <Chart
- series={series}
- labels={labels}
- config={chartConfig}
- theme={theme}
- createScales={createScales}
- drawStatic={drawStatic}
- drawHover={drawHover}
- tooltip={tooltip}
- onPointClick={onPointClick}
- onDateRangeZoom={onDateRangeZoom}
- className={className}
- dataAttr={dataAttr}
- resolveValue={resolveValue}
- resolvePositionValue={resolvePositionValue}
- >
- {children}
- </Chart>
+ <ChartLegend {...legendProps} legendDataAttr="hog-chart-line-legend">
+ <Chart
+ series={visibleSeries}
+ labels={labels}
+ config={chartConfig}
+ theme={theme}
+ createScales={createScales}
+ drawStatic={drawStatic}
+ drawHover={drawHover}
+ tooltip={tooltip}
+ onPointClick={onPointClick}
+ onDateRangeZoom={onDateRangeZoom}
+ className={className}
+ dataAttr={dataAttr}
+ resolveValue={resolveValue}
+ resolvePositionValue={resolvePositionValue}
+ >
+ {children}
+ </Chart>
+ </ChartLegend>
)
}
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 8500af389f2e..2357b4fd4678 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
@@ -1,5 +1,7 @@
+import { fireEvent } from '@testing-library/react'
+
import type { ChartTheme, Series, TooltipContext } from '../../core/types'
-import { renderHogChart } from '../../testing'
+import { getHogChart, renderHogChart } from '../../testing'
import { sortSlopeTooltipRows, type SlopeSeriesMeta } from './slope-data'
import { SlopeChart } from './SlopeChart'
@@ -34,7 +36,12 @@ describe('SlopeChart', () => {
it('skips excluded series everywhere', () => {
const series: Series<SlopeSeriesMeta>[] = [
...SERIES,
- { key: 'c', label: 'C', data: [5, 9], visibility: { excluded: true } },
+ {
+ key: 'c',
+ label: 'C',
+ data: [5, 9],
+ visibility: { excluded: true },
+ },
]
const { chart } = renderHogChart(
<SlopeChart series={series} labels={LABELS} config={{ legend: { show: true } }} theme={THEME} />
@@ -67,7 +74,12 @@ describe('SlopeChart', () => {
['showEndLabels: false', { showEndLabels: true } as const, { showEndLabel: false }, 'end'],
])('honors per-series %s via meta', (_label, config, metaOverride, side) => {
const series: Series<SlopeSeriesMeta>[] = [
- { key: 'a', label: 'A', data: [10, 90], meta: metaOverride },
+ {
+ key: 'a',
+ label: 'A',
+ data: [10, 90],
+ meta: metaOverride,
+ },
{ key: 'b', label: 'B', data: [80, 20] },
]
const { chart } = renderHogChart(
@@ -82,7 +94,12 @@ describe('SlopeChart', () => {
it('drops all value labels for a series with visibility.valueLabel false', () => {
const series: Series<SlopeSeriesMeta>[] = [
- { key: 'a', label: 'A', data: [10, 90], visibility: { valueLabel: false } },
+ {
+ key: 'a',
+ label: 'A',
+ data: [10, 90],
+ visibility: { valueLabel: false },
+ },
{ key: 'b', label: 'B', data: [80, 20] },
]
const { chart } = renderHogChart(<SlopeChart series={series} labels={LABELS} theme={THEME} />)
@@ -145,7 +162,10 @@ describe('SlopeChart', () => {
<SlopeChart
series={SERIES}
labels={LABELS}
- config={{ legend: { show: true }, deltaFormatter: (d) => `${d > 0 ? '↑' : '↓'}${Math.abs(d)}` }}
+ config={{
+ legend: { show: true },
+ deltaFormatter: (d) => `${d > 0 ? '↑' : '↓'}${Math.abs(d)}`,
+ }}
theme={THEME}
/>
)
@@ -164,18 +184,52 @@ describe('SlopeChart', () => {
)
expect(chart.slopeLegendItems().map((i) => i.label)).toEqual(['B', 'C', 'A'])
})
+
+ it('toggles a series off and on when its legend row is clicked', () => {
+ const { container, chart } = renderHogChart(
+ <SlopeChart series={SERIES} labels={LABELS} config={{ legend: { show: true } }} theme={THEME} />
+ )
+ expect(chart.seriesCount).toBe(2)
+ const legend = container.querySelector('[data-attr="hog-chart-slope-legend"]')!
+ const buttonFor = (label: string): HTMLButtonElement =>
+ Array.from(legend.querySelectorAll('button')).find((b) => b.textContent?.startsWith(label))!
+
+ fireEvent.click(buttonFor('A'))
+ expect(getHogChart(container).seriesCount).toBe(1)
+ // The toggled-off series stays listed (so it can be restored).
+ expect(
+ getHogChart(container)
+ .slopeLegendItems()
+ .map((i) => i.label)
+ ).toEqual(['A', 'B'])
+
+ fireEvent.click(buttonFor('A'))
+ expect(getHogChart(container).seriesCount).toBe(2)
+ })
})
describe('incompleteEnd', () => {
it.each([
[
'one series with incompleteEnd',
- [{ key: 'a', label: 'A', data: [10, 90], meta: { incompleteEnd: true } }] as Series<SlopeSeriesMeta>[],
+ [
+ {
+ key: 'a',
+ label: 'A',
+ data: [10, 90],
+ meta: { incompleteEnd: true },
+ },
+ ] as Series<SlopeSeriesMeta>[],
],
[
'multiple series, one with incompleteEnd',
[
- { key: 'a', label: 'A', data: [10, 90], meta: { incompleteEnd: true } },
+ {
+ key: 'a',
+ label: 'A',
+ data: [10, 90],
+ meta: { incompleteEnd: true },
+ },
{ key: 'b', label: 'B', data: [80, 20] },
] as Series<SlopeSeriesMeta>[],
],
@@ -187,7 +241,14 @@ describe('SlopeChart', () => {
it.each([
[
'one series with incompleteEnd',
- [{ key: 'a', label: 'A', data: [10, 90], meta: { incompleteEnd: true } }] as Series<SlopeSeriesMeta>[],
+ [
+ {
+ key: 'a',
+ label: 'A',
+ data: [10, 90],
+ meta: { incompleteEnd: true },
+ },
+ ] as Series<SlopeSeriesMeta>[],
[
{ side: 'start', text: '10' },
{ side: 'end', text: '90' },
@@ -196,7 +257,12 @@ describe('SlopeChart', () => {
[
'multiple series, one with incompleteEnd',
[
- { key: 'a', label: 'A', data: [10, 90], meta: { incompleteEnd: true } },
+ {
+ key: 'a',
+ label: 'A',
+ data: [10, 90],
+ meta: { incompleteEnd: true },
+ },
{ key: 'b', label: 'B', data: [80, 20] },
] as Series<SlopeSeriesMeta>[],
[
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
index 87061f651d00..c067188fa54f 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
@@ -1,9 +1,11 @@
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 {
ChartConfig,
+ ChartLegendConfig,
ChartMargins,
ChartTheme,
LineChartConfig,
@@ -36,13 +38,9 @@ const NAME_GAP = 8
const EDGE_PAD = 8
const DEFAULT_POINT_RADIUS = 4
-export interface SlopeChartLegendConfig {
- /** Show the legend. Default false. */
- show?: boolean
- position?: 'top' | 'bottom' | 'left' | 'right'
- align?: 'start' | 'center' | 'end'
- gap?: number
-}
+/** Slope-chart legend config. Same shape as every chart's {@link ChartLegendConfig} — clicking a
+ * row toggles that series (interactive by default). Rows carry the per-series change. */
+export type SlopeChartLegendConfig = ChartLegendConfig
export interface SlopeChartConfig extends ChartConfig {
/** Show the series name labels beside each series' last point. Default true. */
@@ -120,6 +118,11 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
[showEndLabels]
)
+ // Legend rows come from the full series (so toggled-off ones stay listed and restorable);
+ // `visibleSeries` carries the toggled-off entries as excluded for everything the chart draws.
+ const legendItems = useMemo(() => slopeLegendItems(series, theme, deltaFormatter), [series, theme, deltaFormatter])
+ const { visibleSeries, legendProps } = useChartLegend(series, theme, legend, legendItems)
+
// A slope plots only its two ends, so reduce any-length labels to [first, last] to match — this
// lets a caller hand over a full time-series (data + labels) and have the chart slope it, so the
// first/last reduction lives here once rather than in every caller.
@@ -127,11 +130,11 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
// Reserve left/right gutters for the value/name labels, which sit in the margins beyond the plot.
const { margins, nameOffsetX } = useMemo(() => {
- const startWidth = maxLabelWidth(series.filter(showsStart).map((s) => valueFormatter(slopeStart(s))))
- const endWidth = maxLabelWidth(series.filter(showsEnd).map((s) => valueFormatter(slopeEnd(s))))
+ const startWidth = maxLabelWidth(visibleSeries.filter(showsStart).map((s) => valueFormatter(slopeStart(s))))
+ const endWidth = maxLabelWidth(visibleSeries.filter(showsEnd).map((s) => valueFormatter(slopeEnd(s))))
const nameWidth = showSeriesLabels
? maxLabelWidth(
- series
+ visibleSeries
.filter((s) => !s.visibility?.excluded && s.visibility?.valueLabel !== false)
.map((s) => s.label)
)
@@ -155,29 +158,48 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
const offset = (endWidth > 0 ? VALUE_GAP + endWidth : 0) + NAME_GAP
const base: Partial<ChartMargins> = { left, right }
- return { margins: { ...base, ...config?.margins }, nameOffsetX: offset }
- }, [series, slopeLabels, showsStart, showsEnd, showSeriesLabels, valueFormatter, config?.margins])
+ return {
+ margins: { ...base, ...config?.margins },
+ nameOffsetX: offset,
+ }
+ }, [visibleSeries, slopeLabels, showsStart, showsEnd, showSeriesLabels, valueFormatter, config?.margins])
// When the last point is the current incomplete period, dash only the *second half* of the
// connector so it reads as "the end is provisional", not the whole comparison.
- const dashEnd = useMemo(() => series.some((s) => (s.meta as SlopeSeriesMeta | undefined)?.incompleteEnd), [series])
+ const dashEnd = useMemo(
+ () => visibleSeries.some((s) => (s.meta as SlopeSeriesMeta | undefined)?.incompleteEnd),
+ [visibleSeries]
+ )
// A slope is a two-point line — collapse each series to its two points, with a dot at each. A
// dashed end splits the single segment at its midpoint (renderer-side, no phantom point).
const slopeSeries = useMemo<Series<Meta>[]>(
() =>
- series.map((s) => ({
+ visibleSeries.map((s) => ({
...s,
data: [slopeStart(s), slopeEnd(s)],
points: { ...s.points, radius: pointRadius },
- ...(dashEnd ? { stroke: { ...s.stroke, partial: { ...s.stroke?.partial, fromFraction: 0.5 } } } : {}),
+ ...(dashEnd
+ ? {
+ stroke: {
+ ...s.stroke,
+ partial: {
+ ...s.stroke?.partial,
+ fromFraction: 0.5,
+ },
+ },
+ }
+ : {}),
})),
- [series, pointRadius, dashEnd]
+ [visibleSeries, pointRadius, dashEnd]
)
+ // SlopeChart owns the legend (wrapper below); strip it from the inner LineChart's config so the
+ // line chart's own built-in legend stays off and we don't render two.
const lineConfig = useMemo<LineChartConfig>(
() => ({
...config,
+ legend: undefined,
hideYAxis: config?.hideYAxis ?? true,
showGrid: false,
margins,
@@ -186,26 +208,21 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
[config, margins, valueDomain]
)
- const legendItems = useMemo(() => slopeLegendItems(series, theme, deltaFormatter), [series, theme, deltaFormatter])
-
// A caller-supplied tooltip takes precedence; otherwise sort the default rows (see helper) and
// format values with the chart's valueFormatter so the tooltip matches the on-chart labels' units.
const sortedTooltip = useCallback(
(ctx: TooltipContext<Meta>): React.ReactNode => (
- <DefaultTooltip {...ctx} seriesData={sortSlopeTooltipRows(ctx.seriesData)} valueFormatter={valueFormatter} />
+ <DefaultTooltip
+ {...ctx}
+ seriesData={sortSlopeTooltipRows(ctx.seriesData)}
+ valueFormatter={valueFormatter}
+ />
),
[valueFormatter]
)
return (
- <ChartLegend
- show={legend?.show ?? false}
- items={legendItems}
- position={legend?.position ?? 'bottom'}
- align={legend?.align}
- gap={legend?.gap}
- legendDataAttr="hog-chart-slope-legend"
- >
+ <ChartLegend {...legendProps} legendDataAttr="hog-chart-slope-legend">
<LineChart<Meta>
series={slopeSeries}
labels={slopeLabels}
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
index 600c92207600..cffe7c751ea6 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
@@ -1,11 +1,20 @@
+import { fireEvent } from '@testing-library/react'
+
import { useChartLayout } from '../../core/chart-context'
import type { ChartTheme, Series } from '../../core/types'
-import { renderHogChart } from '../../testing'
+import { getHogChart, renderHogChart } from '../../testing'
import { TimeSeriesBarChart } from './TimeSeriesBarChart'
-const THEME: ChartTheme = { colors: ['#111', '#222', '#333'], backgroundColor: '#ffffff' }
+const THEME: ChartTheme = {
+ colors: ['#111', '#222', '#333'],
+ backgroundColor: '#ffffff',
+}
const LABELS = ['Mon', 'Tue', 'Wed']
const SERIES: Series[] = [{ key: 'a', label: 'A', data: [1, 2, 3] }]
+const MULTI_SERIES: Series[] = [
+ { key: 'a', label: 'A', data: [1, 2, 3] },
+ { key: 'b', label: 'B', data: [3, 2, 1] },
+]
describe('TimeSeriesBarChart', () => {
describe('config.xAxis', () => {
@@ -52,7 +61,11 @@ describe('TimeSeriesBarChart', () => {
labels={['2024-06-10', '2024-06-11', '2024-06-12']}
theme={THEME}
config={{
- xAxis: { tickFormatter: explicit, timezone: 'UTC', interval: 'day' },
+ xAxis: {
+ tickFormatter: explicit,
+ timezone: 'UTC',
+ interval: 'day',
+ },
}}
/>
)
@@ -105,7 +118,12 @@ describe('TimeSeriesBarChart', () => {
series={SERIES}
labels={LABELS}
theme={THEME}
- config={{ yAxis: { tickFormatter: explicit, format: 'percentage' } }}
+ config={{
+ yAxis: {
+ tickFormatter: explicit,
+ format: 'percentage',
+ },
+ }}
/>
)
expect(chart.yTicks().every((t) => t.startsWith('y:'))).toBe(true)
@@ -154,7 +172,10 @@ describe('TimeSeriesBarChart', () => {
series={[{ key: 'a', label: 'A', data: [50] }]}
labels={['Mon']}
theme={THEME}
- config={{ yAxis: { format: 'percentage' }, valueLabels: true }}
+ config={{
+ yAxis: { format: 'percentage' },
+ valueLabels: true,
+ }}
/>
)
expect(chart.valueLabels().map((l) => l.text)).toEqual(['50%'])
@@ -167,7 +188,10 @@ describe('TimeSeriesBarChart', () => {
series={SERIES}
labels={LABELS}
theme={THEME}
- config={{ yAxis: { tickFormatter: explicit }, valueLabels: true }}
+ config={{
+ yAxis: { tickFormatter: explicit },
+ valueLabels: true,
+ }}
/>
)
expect(chart.valueLabels().map((l) => l.text)).toEqual(['y:1', 'y:2', 'y:3'])
@@ -308,4 +332,26 @@ describe('TimeSeriesBarChart', () => {
)
expect(container.querySelector('[data-attr="custom-overlay"]')).not.toBeNull()
})
+
+ describe('interactive legend', () => {
+ it('toggles a series off and on when its legend row is clicked', () => {
+ const { container, chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={MULTI_SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ legend: { show: true } }}
+ />
+ )
+ expect(chart.seriesCount).toBe(2)
+ const buttons = (): HTMLButtonElement[] =>
+ Array.from(container.querySelectorAll('[data-attr="hog-chart-timeseries-bar-legend"] button'))
+
+ fireEvent.click(buttons()[1])
+ expect(getHogChart(container).seriesCount).toBe(1)
+
+ fireEvent.click(buttons()[1])
+ expect(getHogChart(container).seriesCount).toBe(2)
+ })
+ })
})
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index 9ffad50a5da9..70e37d4a3acf 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -1,8 +1,11 @@
import React, { useMemo } from 'react'
+import { ChartLegend } from '../../components/Legend/ChartLegend'
+import { useChartLegend } from '../../components/Legend/useChartLegend'
import type {
BarChartConfig,
BarFillStyle,
+ ChartLegendConfig,
ChartTheme,
PointClickData,
Series,
@@ -48,6 +51,8 @@ export interface TimeSeriesBarChartConfig {
fillStyle?: BarFillStyle
/** Ease the hover highlight in over this many ms (`true` = default duration). Omit to snap. */
animateHover?: boolean | number
+ /** Built-in legend with click-to-toggle series visibility. Hidden by default. */
+ legend?: ChartLegendConfig
}
export interface TimeSeriesBarChartProps<Meta = unknown> {
@@ -89,12 +94,15 @@ export function TimeSeriesBarChart<Meta = unknown>({
divergingStack,
fillStyle,
animateHover,
+ legend,
} = config ?? {}
const xTickFormatter = useXTickFormatter(xAxis, labels)
const yTickFormatter = useYTickFormatter(yAxis)
+ const { visibleSeries, legendProps } = useChartLegend(series, theme, legend)
+
const valueLabelsConfig = resolveValueLabelsConfig(valueLabels)
- const seriesAfterValueLabels = useSeriesWithValueLabelAllowlist(series, valueLabelsConfig?.seriesKeys)
+ const seriesAfterValueLabels = useSeriesWithValueLabelAllowlist(visibleSeries, valueLabelsConfig?.seriesKeys)
const valueLabelFormatter = valueLabelsConfig ? (valueLabelsConfig.formatter ?? yTickFormatter) : undefined
@@ -134,20 +142,22 @@ export function TimeSeriesBarChart<Meta = unknown>({
}
return (
- <BarChart
- series={seriesAfterValueLabels}
- labels={labels}
- config={barChartConfig}
- theme={theme}
- tooltip={tooltip}
- onPointClick={onPointClick}
- className={className}
- dataAttr={dataAttr}
- onError={onError}
- >
- {referenceLines.length > 0 && <ReferenceLines lines={referenceLines} />}
- {valueLabelsConfig && <ValueLabels valueFormatter={valueLabelFormatter} />}
- {children}
- </BarChart>
+ <ChartLegend {...legendProps} legendDataAttr="hog-chart-timeseries-bar-legend">
+ <BarChart
+ series={seriesAfterValueLabels}
+ labels={labels}
+ config={barChartConfig}
+ theme={theme}
+ tooltip={tooltip}
+ onPointClick={onPointClick}
+ className={className}
+ dataAttr={dataAttr}
+ onError={onError}
+ >
+ {referenceLines.length > 0 && <ReferenceLines lines={referenceLines} />}
+ {valueLabelsConfig && <ValueLabels valueFormatter={valueLabelFormatter} />}
+ {children}
+ </BarChart>
+ </ChartLegend>
)
}
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 0d097609c05b..16229e1053ee 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
@@ -1,13 +1,20 @@
-import { cleanup } from '@testing-library/react'
+import { cleanup, fireEvent } from '@testing-library/react'
import { useChartLayout } from '../../core/chart-context'
import type { ChartTheme, Series } from '../../core/types'
-import { renderHogChart, setupJsdom, setupSyncRaf } from '../../testing'
+import { getHogChart, renderHogChart, setupJsdom, setupSyncRaf } from '../../testing'
import { TimeSeriesLineChart } from './TimeSeriesLineChart'
-const THEME: ChartTheme = { colors: ['#111', '#222', '#333'], backgroundColor: '#ffffff' }
+const THEME: ChartTheme = {
+ colors: ['#111', '#222', '#333'],
+ backgroundColor: '#ffffff',
+}
const LABELS = ['Mon', 'Tue', 'Wed']
const SERIES: Series[] = [{ key: 'a', label: 'A', data: [1, 2, 3] }]
+const MULTI_SERIES: Series[] = [
+ { key: 'a', label: 'A', data: [1, 2, 3] },
+ { key: 'b', label: 'B', data: [3, 2, 1] },
+]
describe('TimeSeriesLineChart', () => {
let teardownJsdom: () => void
@@ -69,7 +76,11 @@ describe('TimeSeriesLineChart', () => {
labels={['2024-06-10', '2024-06-11', '2024-06-12']}
theme={THEME}
config={{
- xAxis: { tickFormatter: explicit, timezone: 'UTC', interval: 'day' },
+ xAxis: {
+ tickFormatter: explicit,
+ timezone: 'UTC',
+ interval: 'day',
+ },
}}
/>
)
@@ -122,7 +133,12 @@ describe('TimeSeriesLineChart', () => {
series={SERIES}
labels={LABELS}
theme={THEME}
- config={{ yAxis: { tickFormatter: explicit, format: 'percentage' } }}
+ config={{
+ yAxis: {
+ tickFormatter: explicit,
+ format: 'percentage',
+ },
+ }}
/>
)
expect(chart.yTicks().every((t) => t.startsWith('y:'))).toBe(true)
@@ -171,7 +187,10 @@ describe('TimeSeriesLineChart', () => {
series={[{ key: 'a', label: 'A', data: [50] }]}
labels={['Mon']}
theme={THEME}
- config={{ yAxis: { format: 'percentage' }, valueLabels: true }}
+ config={{
+ yAxis: { format: 'percentage' },
+ valueLabels: true,
+ }}
/>
)
expect(chart.valueLabels().map((l) => l.text)).toEqual(['50%'])
@@ -184,7 +203,10 @@ describe('TimeSeriesLineChart', () => {
series={SERIES}
labels={LABELS}
theme={THEME}
- config={{ yAxis: { tickFormatter: explicit }, valueLabels: true }}
+ config={{
+ yAxis: { tickFormatter: explicit },
+ valueLabels: true,
+ }}
/>
)
expect(chart.valueLabels().map((l) => l.text)).toEqual(['y:1', 'y:2', 'y:3'])
@@ -253,7 +275,12 @@ describe('TimeSeriesLineChart', () => {
describe('derived-series wiring', () => {
it.each([
- ['confidenceIntervals', { confidenceIntervals: [{ seriesKey: 'a', lower: [0, 1, 2], upper: [2, 3, 4] }] }],
+ [
+ 'confidenceIntervals',
+ {
+ confidenceIntervals: [{ seriesKey: 'a', lower: [0, 1, 2], upper: [2, 3, 4] }],
+ },
+ ],
['movingAverage', { movingAverage: [{ seriesKey: 'a', window: 2 }] }],
['trendLines', { trendLines: [{ seriesKey: 'a', kind: 'linear' as const }] }],
])('plumbs config.%s through to the rendered series count', (_, derivedConfig) => {
@@ -267,7 +294,12 @@ describe('TimeSeriesLineChart', () => {
it('skips comparison-period series count change while still rendering them', () => {
const series: Series[] = [
{ key: 'a', label: 'A', data: [1, 2, 3], color: '#112233' },
- { key: 'a-prev', label: 'A (prev)', data: [1, 2, 3], color: '#112233' },
+ {
+ key: 'a-prev',
+ label: 'A (prev)',
+ data: [1, 2, 3],
+ color: '#112233',
+ },
]
const { chart } = renderHogChart(
<TimeSeriesLineChart
@@ -289,4 +321,30 @@ describe('TimeSeriesLineChart', () => {
)
expect(container.querySelector('[data-attr="custom-overlay"]')).not.toBeNull()
})
+
+ describe('interactive legend', () => {
+ it('lists the raw series (not derived trend lines) and toggles one off on click', () => {
+ const { container, chart } = renderHogChart(
+ <TimeSeriesLineChart
+ series={MULTI_SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{
+ legend: { show: true },
+ trendLines: [{ seriesKey: 'a' }],
+ }}
+ />
+ )
+ const buttons = (): HTMLButtonElement[] =>
+ Array.from(container.querySelectorAll('[data-attr="hog-chart-timeseries-line-legend"] button'))
+ // The legend lists only the user's series, not the derived trend line.
+ expect(buttons().map((b) => b.textContent)).toEqual(['A', 'B'])
+
+ // A + B + trend-of-A are all drawn before any toggle.
+ expect(chart.seriesCount).toBe(3)
+ fireEvent.click(buttons()[0])
+ // Hiding A also suppresses its trend line, leaving only B.
+ expect(getHogChart(container).seriesCount).toBe(1)
+ })
+ })
})
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index d2dafad07aed..48f7e4b40204 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -1,6 +1,9 @@
import React, { useMemo } from 'react'
+import { ChartLegend } from '../../components/Legend/ChartLegend'
+import { useChartLegend } from '../../components/Legend/useChartLegend'
import type {
+ ChartLegendConfig,
ChartTheme,
DateRangeZoomData,
LineChartConfig,
@@ -51,6 +54,8 @@ export interface TimeSeriesLineChartConfig {
showAxisLines?: boolean
/** Tooltip behaviour (pinning, placement). Tooltip *content* is the `tooltip` render prop. */
tooltip?: TooltipConfig
+ /** Built-in legend with click-to-toggle series visibility. Hidden by default. */
+ legend?: ChartLegendConfig
}
export interface TimeSeriesLineChartProps<Meta = unknown> {
@@ -93,12 +98,17 @@ export function TimeSeriesLineChart<Meta = unknown>({
showCrosshair,
showAxisLines,
tooltip: tooltipConfig,
+ legend,
} = config ?? {}
const xTickFormatter = useXTickFormatter(xAxis, labels)
const yTickFormatter = useYTickFormatter(yAxis)
+ // Toggling works off the raw series so the legend lists the user's series (not derived trend
+ // lines / CI bands); hidden ones flow through the derived pipeline already excluded.
+ const { visibleSeries, legendProps } = useChartLegend(series, theme, legend)
+
const valueLabelsConfig = resolveValueLabelsConfig(valueLabels)
- const seriesAfterValueLabels = useSeriesWithValueLabelAllowlist(series, valueLabelsConfig?.seriesKeys)
+ const seriesAfterValueLabels = useSeriesWithValueLabelAllowlist(visibleSeries, valueLabelsConfig?.seriesKeys)
const finalSeries = useDerivedSeries(seriesAfterValueLabels, {
confidenceIntervals,
@@ -133,21 +143,23 @@ export function TimeSeriesLineChart<Meta = unknown>({
}
return (
- <LineChart
- series={finalSeries}
- labels={labels}
- config={lineChartConfig}
- theme={theme}
- tooltip={tooltip}
- onPointClick={onPointClick}
- onDateRangeZoom={onDateRangeZoom}
- className={className}
- dataAttr={dataAttr}
- onError={onError}
- >
- {referenceLines.length > 0 && <ReferenceLines lines={referenceLines} />}
- {valueLabelsConfig && <ValueLabels valueFormatter={valueLabelFormatter} />}
- {children}
- </LineChart>
+ <ChartLegend {...legendProps} legendDataAttr="hog-chart-timeseries-line-legend">
+ <LineChart
+ series={finalSeries}
+ labels={labels}
+ config={lineChartConfig}
+ theme={theme}
+ tooltip={tooltip}
+ onPointClick={onPointClick}
+ onDateRangeZoom={onDateRangeZoom}
+ className={className}
+ dataAttr={dataAttr}
+ onError={onError}
+ >
+ {referenceLines.length > 0 && <ReferenceLines lines={referenceLines} />}
+ {valueLabelsConfig && <ValueLabels valueFormatter={valueLabelFormatter} />}
+ {children}
+ </LineChart>
+ </ChartLegend>
)
}
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.test.ts b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.test.ts
index da8a535626d8..2fb315fb4581 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.test.ts
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.test.ts
@@ -63,6 +63,11 @@ describe('buildMovingAverageSeries', () => {
const ma = buildMovingAverageSeries({ sourceSeries: SOURCE, window: 3, label: 'Smoothed' })
expect(ma.label).toBe('Smoothed')
})
+
+ it('forwards the excluded flag so it hides alongside a hidden source', () => {
+ const ma = buildMovingAverageSeries({ sourceSeries: SOURCE, window: 3, excluded: true })
+ expect(ma.visibility?.excluded).toBe(true)
+ })
})
describe('buildTrendLineSeries', () => {
@@ -87,4 +92,9 @@ describe('buildTrendLineSeries', () => {
expect(tl.data[0]).toBeCloseTo(expectedFirst, 2)
expect(tl.data[data.length - 1]).toBeCloseTo(expectedLast, 2)
})
+
+ it('forwards the excluded flag so it hides alongside a hidden source', () => {
+ const tl = buildTrendLineSeries({ sourceSeries: SOURCE, kind: 'linear', excluded: true })
+ expect(tl.visibility?.excluded).toBe(true)
+ })
})
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.ts b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.ts
index 96fadc01d577..8905279a8ac2 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.ts
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.ts
@@ -37,6 +37,7 @@ export interface BuildMovingAverageSeriesInput<Meta = unknown> {
sourceSeries: Series<Meta>
window: number
label?: string
+ excluded?: boolean
}
export function movingAverageKey(sourceKey: string): string {
@@ -54,7 +55,7 @@ export function buildMovingAverageSeries<Meta = unknown>(input: BuildMovingAvera
meta: sourceSeries.meta,
stroke: { pattern: MA_DASH_PATTERN },
overlay: true,
- visibility: { tooltip: false },
+ visibility: { excluded: input.excluded, tooltip: false },
}
}
@@ -66,6 +67,7 @@ export interface BuildTrendLineSeriesInput<Meta = unknown> {
* trend is extrapolated across the full data range. Useful for excluding an
* in-progress tail so the partial bucket doesn't drag the slope. */
fitUpTo?: number
+ excluded?: boolean
}
/** Linear or exponential regression rendered as a dimmed dotted line. Exponential is
@@ -87,7 +89,7 @@ export function buildTrendLineSeries<Meta = unknown>(input: BuildTrendLineSeries
meta: sourceSeries.meta,
stroke: { pattern: TREND_LINE_DASH_PATTERN },
overlay: true,
- visibility: { tooltip: false, valueLabel: false },
+ visibility: { excluded: input.excluded, tooltip: false, valueLabel: false },
}
}
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/use-derived-series.test.ts b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/use-derived-series.test.ts
index eb3823e0aa34..568679bc9ac5 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/use-derived-series.test.ts
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/use-derived-series.test.ts
@@ -42,6 +42,22 @@ describe('useDerivedSeries', () => {
expect(result.current[1].color).toMatch(/^rgba\([^)]*,\s*0\.5\)$/)
})
+ it('propagates a hidden source excluded flag into its derived MA and trend line', () => {
+ const source: Series[] = [
+ { key: 'a', label: 'A', data: [1, 2, 3, 4], color: '#112233', visibility: { excluded: true } },
+ { key: 'b', label: 'B', data: [5, 6, 7, 8], color: '#445566' },
+ ]
+ const { result } = renderHook(() =>
+ useDerivedSeries(source, {
+ movingAverage: [{ seriesKey: 'a', window: 2 }],
+ trendLines: [{ seriesKey: 'a', kind: 'linear' }],
+ })
+ )
+ const byKey = new Map(result.current.map((s) => [s.key, s]))
+ expect(byKey.get('a-ma')?.visibility?.excluded).toBe(true)
+ expect(byKey.get('a__trendline')?.visibility?.excluded).toBe(true)
+ })
+
it('resolves a trendline whose seriesKey targets a moving-average series', () => {
const { result } = renderHook(() =>
useDerivedSeries(SOURCE, {
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/use-derived-series.ts b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/use-derived-series.ts
index 8a8995e7e27d..6d460fb385da 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/use-derived-series.ts
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/use-derived-series.ts
@@ -88,7 +88,14 @@ export function useDerivedSeries<Meta>(source: Series<Meta>[], options: DerivedS
if (!found) {
continue
}
- maSeries.push(buildMovingAverageSeries<Meta>({ sourceSeries: found, window: ma.window, label: ma.label }))
+ maSeries.push(
+ buildMovingAverageSeries<Meta>({
+ sourceSeries: found,
+ window: ma.window,
+ label: ma.label,
+ excluded: found.visibility?.excluded,
+ })
+ )
}
// Trend lines may reference moving-average series too (e.g. trends renders both a
@@ -113,6 +120,7 @@ export function useDerivedSeries<Meta>(source: Series<Meta>[], options: DerivedS
kind: tl.kind,
label: tl.label,
fitUpTo: tl.fitUpTo,
+ excluded: found.visibility?.excluded,
})
)
}
diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsx
index 9d9aad4f750c..986c10e2f267 100644
--- a/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsx
+++ b/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsx
@@ -21,7 +21,10 @@ const MANY: LegendItem[] = Array.from({ length: 12 }, (_, i) => ({
color: `hsl(${(i * 36) % 360} 70% 55%)`,
}))
-const meta: Meta = { title: 'Components/HogCharts/Legend', parameters: { layout: 'centered' } }
+const meta: Meta = {
+ title: 'Components/HogCharts/Legend',
+ parameters: { layout: 'centered' },
+}
export default meta
type Story = StoryObj
@@ -89,8 +92,39 @@ function ChartLegendStory({
)
}
-export const LayoutTop: Story = { render: () => <ChartLegendStory position="top" /> }
-export const LayoutBottom: Story = { render: () => <ChartLegendStory position="bottom" /> }
-export const LayoutLeft: Story = { render: () => <ChartLegendStory position="left" /> }
-export const LayoutRight: Story = { render: () => <ChartLegendStory position="right" /> }
-export const LegendHidden: Story = { render: () => <ChartLegendStory show={false} position="top" /> }
+export const LayoutTop: Story = {
+ render: () => <ChartLegendStory position="top" />,
+}
+export const LayoutBottom: Story = {
+ render: () => <ChartLegendStory position="bottom" />,
+}
+export const LayoutLeft: Story = {
+ render: () => <ChartLegendStory position="left" />,
+}
+export const LayoutRight: Story = {
+ render: () => <ChartLegendStory position="right" />,
+}
+export const LegendHidden: Story = {
+ render: () => <ChartLegendStory show={false} position="top" />,
+}
+
+// The chart owns the toggle state — `config.legend.show` is all that's needed; clicking a row
+// hides that series (dimmed in the legend) and the axes rescale into the freed space.
+function BuiltInToggleStory(): JSX.Element {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={520} height={320}>
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={DAYS}
+ theme={theme}
+ config={{
+ yAxis: { showGrid: true },
+ legend: { show: true, position: 'bottom' },
+ }}
+ />
+ </Stage>
+ )
+}
+
+export const BuiltInToggle: Story = { render: () => <BuiltInToggleStory /> }
diff --git a/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx b/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx
new file mode 100644
index 000000000000..35a7287c2e94
--- /dev/null
+++ b/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx
@@ -0,0 +1,101 @@
+import { act, renderHook } from '@testing-library/react'
+
+import type { ChartTheme, Series } from '../../core/types'
+import { applyHiddenSeries, useChartLegend } from './useChartLegend'
+
+const THEME: ChartTheme = { colors: ['#1f77b4', '#ff7f0e', '#2ca02c'] }
+
+const SERIES: Series[] = [
+ { key: 'a', label: 'A', data: [1, 2, 3] },
+ { key: 'b', label: 'B', data: [4, 5, 6] },
+ { key: 'c', label: 'C', data: [7, 8, 9] },
+]
+
+describe('useChartLegend', () => {
+ describe('applyHiddenSeries', () => {
+ it('returns the same array reference when nothing is hidden', () => {
+ expect(applyHiddenSeries(SERIES, new Set())).toBe(SERIES)
+ })
+
+ it('marks only hidden keys excluded and preserves other visibility flags', () => {
+ const series: Series[] = [
+ {
+ key: 'a',
+ label: 'A',
+ data: [1],
+ visibility: { tooltip: false },
+ },
+ { key: 'b', label: 'B', data: [2] },
+ ]
+ const result = applyHiddenSeries(series, new Set(['a']))
+ expect(result[0].visibility).toEqual({
+ tooltip: false,
+ excluded: true,
+ })
+ expect(result[1].visibility).toBeUndefined()
+ })
+ })
+
+ it('derives a legend item per series, listing every series', () => {
+ const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true }))
+ expect(result.current.legendProps.items.map((i) => i.key)).toEqual(['a', 'b', 'c'])
+ expect(result.current.legendProps.show).toBe(true)
+ })
+
+ it('toggles a series off then back on in uncontrolled mode, keeping it in the legend', () => {
+ const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true }))
+
+ act(() => result.current.legendProps.onItemClick!('b'))
+ expect(result.current.legendProps.hiddenKeys).toEqual(['b'])
+ // Hidden series is excluded for rendering...
+ expect(result.current.visibleSeries.find((s) => s.key === 'b')?.visibility?.excluded).toBe(true)
+ // ...but still listed in the legend so it can be restored.
+ expect(result.current.legendProps.items.map((i) => i.key)).toContain('b')
+
+ act(() => result.current.legendProps.onItemClick!('b'))
+ expect(result.current.legendProps.hiddenKeys).toEqual([])
+ expect(result.current.visibleSeries.find((s) => s.key === 'b')?.visibility?.excluded).toBeUndefined()
+ })
+
+ it('honors defaultHiddenKeys for the initial uncontrolled state', () => {
+ const { result } = renderHook(() =>
+ useChartLegend(SERIES, THEME, {
+ show: true,
+ defaultHiddenKeys: ['c'],
+ })
+ )
+ expect(result.current.legendProps.hiddenKeys).toEqual(['c'])
+ expect(result.current.visibleSeries.find((s) => s.key === 'c')?.visibility?.excluded).toBe(true)
+ })
+
+ it('does not mutate its own state in controlled mode — only notifies onToggleSeries', () => {
+ const onToggleSeries = jest.fn()
+ const { result } = renderHook(() =>
+ useChartLegend(SERIES, THEME, {
+ show: true,
+ hiddenKeys: ['a'],
+ onToggleSeries,
+ })
+ )
+ expect(result.current.legendProps.hiddenKeys).toEqual(['a'])
+
+ act(() => result.current.legendProps.onItemClick!('a'))
+ expect(onToggleSeries).toHaveBeenCalledWith('a', false)
+ // Controlled: hiddenKeys is unchanged until the parent updates the prop.
+ expect(result.current.legendProps.hiddenKeys).toEqual(['a'])
+
+ act(() => result.current.legendProps.onItemClick!('b'))
+ expect(onToggleSeries).toHaveBeenCalledWith('b', true)
+ })
+
+ it('omits onItemClick when interactive is false (static legend)', () => {
+ const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true, interactive: false }))
+ expect(result.current.legendProps.onItemClick).toBeUndefined()
+ })
+
+ it('uses caller-supplied items verbatim when provided', () => {
+ const items = [{ key: 'a', label: 'Custom A', color: '#000' }]
+ const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true }, items))
+ expect(result.current.legendProps.items).toBe(items)
+ })
+})
diff --git a/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts b/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts
new file mode 100644
index 000000000000..c9dfd937517c
--- /dev/null
+++ b/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts
@@ -0,0 +1,79 @@
+import { useCallback, useMemo, useState } from 'react'
+
+import type { ChartLegendConfig, ChartTheme, Series } from '../../core/types'
+import type { LegendItem } from './Legend'
+import { legendItemsFromSeries } from './legendItemsFromSeries'
+
+/** Mark each `hiddenKeys` series as `visibility.excluded` so the chart drops it from rendering,
+ * scales, tooltips, and hit-testing — leaving the visible series to rescale into the freed space.
+ * Other `visibility` flags are preserved. Returns the input untouched when nothing is hidden. */
+export function applyHiddenSeries<Meta>(series: Series<Meta>[], hiddenKeys: ReadonlySet<string>): Series<Meta>[] {
+ if (hiddenKeys.size === 0) {
+ return series
+ }
+ return series.map((s) => (hiddenKeys.has(s.key) ? { ...s, visibility: { ...s.visibility, excluded: true } } : s))
+}
+
+/** Props to spread onto `<ChartLegend>` (everything except `children` and `legendDataAttr`). */
+export interface ChartLegendRenderProps {
+ show: boolean
+ items: LegendItem[]
+ position: NonNullable<ChartLegendConfig['position']>
+ align: ChartLegendConfig['align']
+ gap: ChartLegendConfig['gap']
+ onItemClick?: (key: string) => void
+ hiddenKeys: string[]
+}
+
+export interface ChartLegendState<Meta> {
+ /** Series with toggled-off entries marked excluded — feed this into the chart's renderer. */
+ visibleSeries: Series<Meta>[]
+ /** Spread onto `<ChartLegend>`; the legend still lists hidden series (dimmed) so they restore. */
+ legendProps: ChartLegendRenderProps
+}
+
+/** Shared plumbing for the multi-series charts' built-in legend. Manages the toggled-off keys
+ * (uncontrolled by default, controlled when `config.hiddenKeys` is set), derives the dimmed
+ * legend items from the *original* series (so hidden ones stay clickable), and returns the
+ * series to actually render with hidden entries excluded. Pass `items` to override the derived
+ * legend rows (e.g. a slope chart's per-series change labels). */
+export function useChartLegend<Meta>(
+ series: Series<Meta>[],
+ theme: ChartTheme,
+ config: ChartLegendConfig | undefined,
+ items?: LegendItem[]
+): ChartLegendState<Meta> {
+ const controlledKeys = config?.hiddenKeys
+ const [internalKeys, setInternalKeys] = useState<string[]>(() => config?.defaultHiddenKeys ?? [])
+ const hiddenKeys = controlledKeys ?? internalKeys
+
+ const onToggleSeries = config?.onToggleSeries
+ const toggle = useCallback(
+ (key: string) => {
+ onToggleSeries?.(key, !hiddenKeys.includes(key))
+ if (controlledKeys === undefined) {
+ setInternalKeys((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]))
+ }
+ },
+ [controlledKeys, hiddenKeys, onToggleSeries]
+ )
+
+ const hiddenSet = useMemo(() => new Set(hiddenKeys), [hiddenKeys])
+ const visibleSeries = useMemo(() => applyHiddenSeries(series, hiddenSet), [series, hiddenSet])
+ const derivedItems = useMemo(() => items ?? legendItemsFromSeries(series, theme), [items, series, theme])
+
+ const interactive = config?.interactive ?? true
+
+ return {
+ visibleSeries,
+ legendProps: {
+ show: config?.show ?? false,
+ items: derivedItems,
+ position: config?.position ?? 'bottom',
+ align: config?.align,
+ gap: config?.gap,
+ onItemClick: interactive ? toggle : undefined,
+ hiddenKeys,
+ },
+ }
+}
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index f6b17201f6ba..cc3454b8cfa8 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -129,7 +129,12 @@ export interface TooltipContext<Meta = unknown> {
label: string
/** One entry per visible series with its value and color at this index. `fraction` is set
* for radial charts (share of total) so renderers don't need to look the slice back up. */
- seriesData: { series: Series<Meta>; value: number; color: string; fraction?: number }[]
+ seriesData: {
+ series: Series<Meta>
+ value: number
+ color: string
+ fraction?: number
+ }[]
/** Pixel position (relative to the chart container) for anchoring the tooltip.
* `width` (optional) is the horizontal data-extent centered on `x` — bar charts
* populate it with the band width so {@link Tooltip} can anchor at the band edge
@@ -217,6 +222,32 @@ export interface ChartConfig {
maxCategoryLabelWidth?: number
}
+/** Built-in legend config for the multi-series charts. The chart renders a {@link Legend} and,
+ * when interactive, owns the toggled-off state — clicking a row hides that series (no draw, no
+ * scale contribution, no tooltip) and the axes rescale, matching the classic insight legend.
+ * Pass `hiddenKeys` + `onToggleSeries` to control the state yourself instead. */
+export interface ChartLegendConfig {
+ /** Render the legend. Default false. */
+ show?: boolean
+ /** Where the legend sits relative to the plot. Default 'bottom'. */
+ position?: 'top' | 'bottom' | 'left' | 'right'
+ /** Legend alignment along its axis. Default 'center'. */
+ align?: 'start' | 'center' | 'end'
+ /** Gap in px between the legend and the plot. */
+ gap?: number
+ /** Clicking a legend item hides/shows its series. Default true when the legend is shown;
+ * set false for a static, read-only legend. */
+ interactive?: boolean
+ /** Controlled hidden-series keys. Provide together with `onToggleSeries` to own the state;
+ * omit for chart-managed (uncontrolled) toggling. */
+ hiddenKeys?: string[]
+ /** Initial hidden keys for the chart-managed (uncontrolled) state. Ignored when `hiddenKeys`
+ * is set (controlled). */
+ defaultHiddenKeys?: string[]
+ /** Called whenever a series is toggled, with its key and resulting hidden state. */
+ onToggleSeries?: (key: string, hidden: boolean) => void
+}
+
export interface TooltipConfig {
/** Show a tooltip on hover. Defaults to true. Use the `tooltip` render prop on Chart to customize content. */
enabled?: boolean
@@ -301,12 +332,16 @@ export interface BarChartConfig extends ChartConfig {
barLayout?: 'stacked' | 'grouped' | 'percent'
/** Bar appearance + band-layout details (corner rounding, track, shadow, padding…). */
bars?: BarsConfig
+ /** Built-in legend with click-to-toggle series visibility. Hidden by default. */
+ legend?: ChartLegendConfig
}
export interface LineChartConfig extends ChartConfig {
percentStackView?: boolean
/** Value-axis domain control — omit for data-derived auto-scaling. See {@link ValueDomain}. */
valueDomain?: ValueDomain
+ /** Built-in legend with click-to-toggle series visibility. Hidden by default. */
+ legend?: ChartLegendConfig
}
/** Arguments passed to a chart type's canvas draw function. */
diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.ts
index 162fcff3ffe6..c4c0fe3005b0 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -77,6 +77,7 @@ export type {
BarChartConfig,
BarsConfig,
ChartConfig,
+ ChartLegendConfig,
ChartDimensions,
ChartDrawArgs,
ChartMargins,
@@ -150,3 +151,5 @@ export type { LegendItem, LegendProps } from './components/Legend/Legend'
export { ChartLegend } from './components/Legend/ChartLegend'
export type { ChartLegendProps } from './components/Legend/ChartLegend'
export { legendItemsFromSeries } from './components/Legend/legendItemsFromSeries'
+export { useChartLegend, applyHiddenSeries } from './components/Legend/useChartLegend'
+export type { ChartLegendRenderProps, ChartLegendState } from './components/Legend/useChartLegend'