:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(charts): click a legend row to isolate that series (#82652)
Sam Pennington904cd2116580
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsxindex ebafa81fe384..4ba79d8a4d6b 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx@@ -304,7 +304,10 @@ describe('SqlLineGraph', () => {expect(container.querySelector('[data-attr="hog-chart-timeseries-line-legend"]')).not.toBeInTheDocument()})- it('hides a series from the chart and tooltip when its legend item is toggled off', async () => {+ it.each([+ { name: 'clicking a legend item isolates that series', additive: false, expectedRows: ['b'] },+ { name: 'meta-clicking a legend item hides just that series', additive: true, expectedRows: ['a'] },+ ])('$name', async ({ additive, expectedRows }) => {const { container } = renderLine({ yAxis: [{ column: 'a' }, { column: 'b' }], showLegend: true },twoSeries()@@ -314,11 +317,11 @@ describe('SqlLineGraph', () => {const bButton = [...getLegend(container).querySelectorAll('button')].find((b) =>b.textContent?.includes('b'))!- fireEvent.click(bButton)+ fireEvent.click(bButton, { metaKey: additive })await waitFor(() => expect(getHogChart().seriesCount).toBe(1))const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)- expect(tooltip.rows()).toEqual(['a'])+ expect(tooltip.rows()).toEqual(expectedRows)})})diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 57373c32f8a0..b8c6d638c1f4 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -91,8 +91,8 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin). A numeric line reveals its value on hover of the line itself (via a wider invisible hit area) or its label — appended as `label: value` when it has a label, shown alone when it doesn't — matching the legacy chart.js goal-line behavior.- `TrendLineOverlay` renders linear/exponential regression lines as SVG polylines on vertical bar and combo charts. Use via `trendLines?: TrendLineConfig[]` in `TimeSeriesBarChartConfig` or `TimeSeriesComboChartConfig` — the chart computes the derived series via `buildTrendLineSeries` and passes them to the overlay as a child. Only works for `axisOrientation: 'vertical'`; returns null on horizontal charts. Legend-toggled-off series are filtered automatically.- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original. `context.bandValues` is the stack's values at this index and `context.previousBandValues` the same for the preceding index (empty at the first), so a formatter can compute a segment's share of the current or the previous band (e.g. period-over-period). Collision avoidance is a single greedy pass over the full 2D label box (`minGap` on every side): a label is dropped only when it actually overlaps a higher-priority one, so on bar charts neighbours at different heights both keep their labels instead of the axis dropping every other bar. Ties resolve toward earlier series and left-to-right / top-to-bottom.-- Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `SlopeChart`, `PieChart`) takes a `config.legend: ChartLegendConfig` (`{ show, position, align, gap, interactive, hiddenKeys, onToggleSeries, renderItem }`). 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. `config.legend.renderItem(defaultNode, item)` wraps each rendered row, so consumers can augment it (e.g. attach a right-click context menu) while keeping the default swatch/label/toggle rendering — return `defaultNode` to leave a row untouched. 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). Long labels clip with an ellipsis only when they run out of the space actually available — there is no fixed max width. A vertical legend bounds each row to its column and truncates at the column edge; a horizontal legend caps each row at an equal share of the line floored at 180px (flexbox wraps before it shrinks, so without a cap one long label would take a whole line instead of clipping) — many series pack into tidy 180px columns while a few series with room to spare, or a lone series, show unclipped whenever they fit. The full text is always exposed via a native `title` tooltip on hover. The legend slot in `ChartLegendLayout` is bounded and scrolls (a top/bottom legend caps at ~40% of the chart height so the plot keeps the majority; a left/right legend stretches to full chart height and caps at 45% width but never more than 240px), so a many-series legend scrolls instead of squeezing or stretching the chart. A left/right legend uses `align-self: stretch` (resolves against the container's used height, so it works even when no ancestor sets an explicit `height`). The top/bottom `max-height: 40%` cap is a percentage, so it only resolves when the chart container has an **explicit** `height` — a flex-derived used size (e.g. `flex: 1` with only `min-height`/`max-height`) does **not** count and the cap silently no-ops; pin a real `height` on the container.+- Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `SlopeChart`, `PieChart`) takes a `config.legend: ChartLegendConfig` (`{ show, position, align, gap, interactive, hiddenKeys, onToggleSeries, onSetHiddenSeries, visibilityGroupKey, renderItem }`). With `show: true` the chart renders a built-in legend that, by default (`interactive`), follows Grafana's click model: **a plain click isolates that series** — every other row is hidden (no draw, no scale contribution, no tooltip, so the axes rescale into the freed space) while staying listed but dimmed — and clicking the isolated row again restores all. **⌘/Ctrl-click (or Shift-click) toggles one series** in or out of the visible set, so a selection is built up a row at a time. Picking one series out of twenty is the common case, and it costs one click rather than nineteen. A legend with one visibility group has nothing to isolate, so a plain click toggles instead. `visibilityGroupKey(rowKey)` maps a row onto the identity its visibility is actually stored against: rows sharing a group share one visibility bit, so isolating keeps the whole group visible, "only this one is visible" is judged per group, and the group count — not the row count — is what decides `canIsolate`. It defaults to the row's own key, so a legend whose rows are independent needs nothing. Trends needs it because comparing to the previous period puts a series' current and previous rows on one `resultCustomizations` key: without the hint the library would isolate a row, correctly leave its twin visible, and then never recognise the result as isolated — so the second click could not restore. The chart owns the toggled-off state (uncontrolled); set `interactive: false` for a static legend, or pass `hiddenKeys` + `onToggleSeries` to control it yourself. A controlled legend must also pass `onSetHiddenSeries(nextHiddenKeys)` for isolating and hide-all to work — they replace the whole hidden set at once, which the per-key `onToggleSeries` can't express in one update; without it a controlled legend degrades to plain toggling, and an uncontrolled one needs nothing extra. Hidden by default. `config.legend.renderItem(defaultNode, item, controls)` wraps each rendered row, so consumers can augment it (e.g. attach a right-click context menu) while keeping the default swatch/label/toggle rendering — return `defaultNode` to leave a row untouched. `controls` is that row's `LegendItemControls`: state (`isHidden`, `isOnlyVisible`, `areAllVisible`, `canIsolate`) plus the actions (`toggle`, `isolate`, `toggleAll`) running the same paths as the clicks, so a row menu never re-derives visibility or duplicates the isolate logic. "All" and "the others" mean the legend's _rows_, not `series` — derived overlays (CI bands, trend lines) have no row and are never isolated against. 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. `onItemClick(key, { additive })` reports whether the click carried ⌘/Ctrl/Shift; deciding what each gesture means is the caller's job (`useChartLegend` is what turns it into isolate vs toggle). 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). Long labels clip with an ellipsis only when they run out of the space actually available — there is no fixed max width. A vertical legend bounds each row to its column and truncates at the column edge; a horizontal legend caps each row at an equal share of the line floored at 180px (flexbox wraps before it shrinks, so without a cap one long label would take a whole line instead of clipping) — many series pack into tidy 180px columns while a few series with room to spare, or a lone series, show unclipped whenever they fit. The full text is always exposed via a native `title` tooltip on hover. The legend slot in `ChartLegendLayout` is bounded and scrolls (a top/bottom legend caps at ~40% of the chart height so the plot keeps the majority; a left/right legend stretches to full chart height and caps at 45% width but never more than 240px), so a many-series legend scrolls instead of squeezing or stretching the chart. A left/right legend uses `align-self: stretch` (resolves against the container's used height, so it works even when no ancestor sets an explicit `height`). The top/bottom `max-height: 40%` cap is a percentage, so it only resolves when the chart container has an **explicit** `height` — a flex-derived used size (e.g. `flex: 1` with only `min-height`/`max-height`) does **not** count and the cap silently no-ops; pin a real `height` on the container.- `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.- `FunnelChart` is a thin wrapper over grouped `BarChart` that owns the funnel look (hatched `track`, rounded + shadowed bars, percent value axis). `steps` is a `string[]` of display labels — duplicates are fine, bands are keyed by step index internally. Each `Series.data[stepIndex]` is the conversion from the first step as a percent (0–100); `funnelFromCounts` builds the single-series case from raw `{ label, count }` steps (zero basis yields 0, not NaN). `onStepClick` replaces `onPointClick` and reports `{ stepIndex, converted }` — `converted: false` means the hatched drop-off track above the bar was clicked. `stepFooter(stepIndex)` renders per-step content in a row below the plot, pixel-aligned under each step's bars (and hides the built-in step labels); use it for step legends richer than an axis label. Config: `hideStepLabels`, `hideValueAxis`, `barCornerRadius`, `bandPadding`, `maxBandRange` (cluster a 2–3 step funnel instead of stretching it), `chartMinHeight` (floor the plot region's px height when `stepFooter` is set, so a tall footer can't starve the `flex-1` canvas to zero height in a height-constrained column), plus the usual `tooltip`/`legend`/`margins`.- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`; `sparklineDashedFromIndex` dashes the sparkline from that index onward (e.g. an in-progress trailing period). `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point). `changeTooltip` shows a styled hover tooltip (floating-ui, using the host's tooltip surface tokens with chart-surface fallbacks) on the change pill (e.g. to spell out what the resting comparison is).diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsxindex d63bbbb630bf..454961273c2c 100644--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx@@ -657,7 +657,7 @@ describe('BarChart', () => {expect(container.querySelector('[data-attr="hog-chart-bar-legend"]')).toBeNull()})- it('toggles a series off and on when its legend row is clicked', () => {+ it('isolates a series when its legend row is clicked, and restores all on the next click', () => {const { container, chart } = renderHogChart(<BarChart series={SERIES} labels={LABELS} theme={THEME} config={{ legend: { show: true } }} />)@@ -667,11 +667,28 @@ describe('BarChart', () => {fireEvent.click(buttons()[1])expect(getHogChart(container).seriesCount).toBe(1)- expect(buttons()[1].className).toContain('opacity-40')+ expect(buttons()[0].className).toContain('opacity-40')+ expect(buttons()[1].className).not.toContain('opacity-40')fireEvent.click(buttons()[1])expect(getHogChart(container).seriesCount).toBe(2)})++ it('toggles just one series off and on when its legend row is meta-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], { metaKey: true })+ expect(getHogChart(container).seriesCount).toBe(1)+ expect(buttons()[1].className).toContain('opacity-40')++ fireEvent.click(buttons()[1], { metaKey: true })+ expect(getHogChart(container).seriesCount).toBe(2)+ })})describe('drag-to-zoom', () => {diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsxindex 2e879533132b..579d2b656bd3 100644--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx@@ -547,7 +547,7 @@ describe('LineChart', () => {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', () => {+ it('isolates a series on legend click and shows them all again on a second click', () => {const { container, chart } = renderHogChart(<LineChart series={SERIES} labels={LABELS} theme={THEME} config={{ legend: { show: true } }} />)@@ -555,14 +555,29 @@ describe('LineChart', () => {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.+ // The isolated-away 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'])+ expect(dimmed.map((b) => b.textContent)).toEqual(['A'])fireEvent.click(legendButtons(container)[1])expect(getHogChart(container).seriesCount).toBe(2)})+ it('hides just one series on a meta-click and shows it again on a second one', () => {+ 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], { metaKey: true })+ expect(getHogChart(container).seriesCount).toBe(1)+ const dimmed = legendButtons(container).filter((b) => b.className.includes('opacity-40'))+ expect(dimmed.map((b) => b.textContent)).toEqual(['B'])++ fireEvent.click(legendButtons(container)[1], { metaKey: true })+ expect(getHogChart(container).seriesCount).toBe(2)+ })+it('renders a static (non-clickable) legend when interactive is false', () => {const { container } = renderHogChart(<LineChartdiff --git a/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx b/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsxindex 7b1a11b3f321..34aeba306b63 100644--- a/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx@@ -183,7 +183,7 @@ describe('PieChart', () => {expect(container.querySelector('[data-attr="hog-chart-pie-legend"]')).toBeNull()})- it('removes a slice on legend click and restores it on a second click', () => {+ it('isolates a slice on legend click and restores them all on a second click', () => {const { container } = renderHogChart(<PieChart series={SERIES} theme={THEME} config={{ legend: { show: true } }} />)@@ -196,9 +196,9 @@ describe('PieChart', () => {expect(container.querySelector('canvas[aria-label]')?.getAttribute('aria-label')).toBe('Pie chart with 1 slices')- // The toggled-off row stays in the legend (dimmed) so it can be restored.+ // The isolated-away 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(['Firefox'])+ expect(dimmed.map((b) => b.textContent)).toEqual(['Chrome'])fireEvent.click(legendButtons(container)[1])expect(container.querySelector('canvas[aria-label]')?.getAttribute('aria-label')).toBe(diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsxindex 232936af4902..e16c5071b268 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx@@ -514,7 +514,7 @@ describe('TimeSeriesLineChart', () => {})describe('interactive legend', () => {- it('lists the raw series (not derived trend lines) and toggles one off on click', () => {+ it('lists the raw series (not derived trend lines) and isolates one on click', () => {const { container, chart } = renderHogChart(<TimeSeriesLineChartseries={MULTI_SERIES}@@ -533,8 +533,13 @@ describe('TimeSeriesLineChart', () => {// A + B + trend-of-A are all drawn before any toggle.expect(chart.seriesCount).toBe(3)+ // Isolating A keeps its derived trend line, and drops B.fireEvent.click(buttons()[0])- // Hiding A also suppresses its trend line, leaving only B.+ expect(getHogChart(container).seriesCount).toBe(2)++ // Meta-clicking A instead hides it, and its trend line with it, leaving only B.+ fireEvent.click(buttons()[0])+ fireEvent.click(buttons()[0], { metaKey: true })expect(getHogChart(container).seriesCount).toBe(1)})})diff --git a/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsx b/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsxindex 4ca097d0143e..f9ae0873c9ce 100644--- a/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsx+++ b/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsx@@ -1,7 +1,7 @@import React from 'react'import { ChartLegendLayout } from './ChartLegendLayout'-import { Legend, type LegendItem } from './Legend'+import { Legend, type LegendItem, type LegendProps } from './Legend'export interface ChartLegendProps {/** When false, renders children with no wrapper and no legend. Defaults to true. */@@ -10,7 +10,7 @@ export interface ChartLegendProps {position?: 'top' | 'bottom' | 'left' | 'right'align?: 'start' | 'center' | 'end'gap?: number- onItemClick?: (key: string) => void+ onItemClick?: LegendProps['onItemClick']hiddenKeys?: string[]className?: string/** Wrap each legend row — forwarded to {@link Legend}'s `renderItem`. */diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.test.tsxindex 22a68d709dfe..e1d6f0e27626 100644--- a/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx+++ b/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx@@ -46,7 +46,18 @@ describe('Legend', () => {const buttons = clickable.querySelectorAll('button')expect(buttons).toHaveLength(ITEMS.length)fireEvent.click(buttons[1])- expect(onClick).toHaveBeenCalledWith('returning')+ expect(onClick).toHaveBeenCalledWith('returning', { additive: false })+ })++ it.each([+ { name: 'meta', event: { metaKey: true } },+ { name: 'ctrl', event: { ctrlKey: true } },+ { name: 'shift', event: { shiftKey: true } },+ ])('reports a $name-click as additive so the handler can add to the selection', ({ event }) => {+ const onClick = jest.fn()+ const { container } = render(<Legend items={ITEMS} onItemClick={onClick} />)+ fireEvent.click(container.querySelectorAll('button')[0], event)+ expect(onClick).toHaveBeenCalledWith('new', { additive: true })})it('wraps each row via renderItem while preserving the default node', () => {@@ -61,7 +72,7 @@ describe('Legend', () => {expect(container.querySelectorAll('[data-attr^="wrap-"]')).toHaveLength(ITEMS.length)const wrapped = container.querySelector('[data-attr="wrap-returning"] button')!fireEvent.click(wrapped)- expect(onClick).toHaveBeenCalledWith('returning')+ expect(onClick).toHaveBeenCalledWith('returning', { additive: false })})it('keeps the full label text and exposes it via a native title tooltip', () => {diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.tsxindex 266f239967dc..3d75461b4021 100644--- a/packages/quill/packages/charts/src/components/Legend/Legend.tsx+++ b/packages/quill/packages/charts/src/components/Legend/Legend.tsx@@ -9,11 +9,19 @@ export interface LegendItem {secondaryLabel?: string}+/** Which gesture a legend row click was: a plain click means "isolate this series", a modified one+ * means "add/remove this series from the visible set". The legend only reports the intent — what+ * each one does is the click handler's business. */+export interface LegendItemClickModifiers {+ /** The user held ⌘/Ctrl (or Shift) while clicking. */+ additive: boolean+}+export interface LegendProps {items: LegendItem[]orientation?: 'horizontal' | 'vertical'align?: 'start' | 'center' | 'end'- onItemClick?: (key: string) => void+ onItemClick?: (key: string, modifiers: LegendItemClickModifiers) => voidhiddenKeys?: string[]className?: stringdataAttr?: string@@ -90,8 +98,13 @@ export function Legend({const node = onItemClick ? (<buttontype="button"- className={`${rowClass} cursor-pointer bg-transparent border-0 p-0 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent`}- onClick={() => onItemClick(item.key)}+ // select-none: clicking rows in quick succession would otherwise select their labels.+ className={`${rowClass} cursor-pointer select-none bg-transparent border-0 p-0 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>diff --git a/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx b/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsxindex f432e8b1627d..2ab7ce55c22a 100644--- a/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx+++ b/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx@@ -2,10 +2,20 @@ import { act, renderHook } from '@testing-library/react'import type { ReactNode } from 'react'import type { ChartTheme, Series } from '../../core/types'-import { applyHiddenSeries, useChartLegend } from './useChartLegend'+import type { LegendItem } from './Legend'+import { applyHiddenSeries, useChartLegend, type LegendItemControls } from './useChartLegend'const THEME: ChartTheme = { colors: ['#1f77b4', '#ff7f0e', '#2ca02c'] }+const PLAIN = { additive: false }+const ADDITIVE = { additive: true }++let captured: LegendItemControls | null = null+const captureOne = (node: ReactNode, _item: LegendItem, controls: LegendItemControls): ReactNode => {+ captured = controls+ return node+}+const SERIES: Series[] = [{ key: 'a', label: 'A', data: [1, 2, 3] },{ key: 'b', label: 'B', data: [4, 5, 6] },@@ -43,27 +53,171 @@ describe('useChartLegend', () => {expect(result.current.legendProps.show).toBe(true)})- it('forwards config.renderItem onto legendProps', () => {- const renderItem = (node: ReactNode): ReactNode => node- const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true, renderItem }))- expect(result.current.legendProps.renderItem).toBe(renderItem)+ it('hands each row its own controls through config.renderItem', () => {+ const seen: Record<string, LegendItemControls> = {}+ const renderItem = (node: ReactNode, item: LegendItem, controls: LegendItemControls): ReactNode => {+ seen[item.key] = controls+ return node+ }+ const { result } = renderHook(() =>+ useChartLegend(SERIES, THEME, { show: true, defaultHiddenKeys: ['a', 'c'], renderItem })+ )++ result.current.legendProps.items.forEach((item) => result.current.legendProps.renderItem!(null, item))++ expect(seen.a.isHidden).toBe(true)+ expect(seen.b.isHidden).toBe(false)+ expect(seen.b.isOnlyVisible).toBe(true)+ expect(seen.a.isOnlyVisible).toBe(false)+ expect(seen.b.areAllVisible).toBe(false)+ expect(seen.b.canIsolate).toBe(true)++ act(() => seen.b.toggleAll())+ expect(result.current.legendProps.hiddenKeys).toEqual([])+ })++ it('hides every series through toggleAll, then restores them all', () => {+ const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true, renderItem: captureOne }))+ const controls = (): LegendItemControls => {+ result.current.legendProps.renderItem!(null, result.current.legendProps.items[0])+ return captured!+ }++ act(() => controls().toggleAll())+ expect(result.current.legendProps.hiddenKeys).toEqual(['a', 'b', 'c'])++ act(() => controls().toggleAll())+ expect(result.current.legendProps.hiddenKeys).toEqual([])})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'))+ act(() => result.current.legendProps.onItemClick!('b', ADDITIVE))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'))+ act(() => result.current.legendProps.onItemClick!('b', ADDITIVE))expect(result.current.legendProps.hiddenKeys).toEqual([])expect(result.current.visibleSeries.find((s) => s.key === 'b')?.visibility?.excluded).toBeUndefined()})+ it('isolates a series on a plain click, and restores every series on the next one', () => {+ const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true }))++ act(() => result.current.legendProps.onItemClick!('b', PLAIN))+ expect(result.current.legendProps.hiddenKeys).toEqual(['a', 'c'])+ // The isolated series still renders; the rest are excluded so the axes rescale to it.+ expect(result.current.visibleSeries.filter((s) => !s.visibility?.excluded).map((s) => s.key)).toEqual(['b'])++ act(() => result.current.legendProps.onItemClick!('b', PLAIN))+ expect(result.current.legendProps.hiddenKeys).toEqual([])+ })++ it('adds to an isolated selection on an additive click without dropping it', () => {+ const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true }))++ act(() => result.current.legendProps.onItemClick!('b', PLAIN))+ act(() => result.current.legendProps.onItemClick!('c', ADDITIVE))+ expect(result.current.legendProps.hiddenKeys).toEqual(['a'])+ })++ it('isolates a different series when one is already isolated', () => {+ const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true }))++ act(() => result.current.legendProps.onItemClick!('b', PLAIN))+ act(() => result.current.legendProps.onItemClick!('c', PLAIN))+ expect(result.current.legendProps.hiddenKeys).toEqual(['a', 'b'])+ })++ it('falls back to toggling when there is only one row to isolate', () => {+ const single = [SERIES[0]]+ const { result } = renderHook(() => useChartLegend(single, THEME, { show: true }))++ act(() => result.current.legendProps.onItemClick!('a', PLAIN))+ expect(result.current.legendProps.hiddenKeys).toEqual(['a'])+ })++ describe('rows that share a visibility group', () => {+ // Trends' compare mode: 'a' and 'b' are one series' current and previous rows, so they share+ // one stored visibility bit and must count as one series to isolate against. The group key is+ // deliberately not also a row key, so hiding "the other rows" and hiding "the other groups"+ // can be told apart.+ const GROUP_BY_ROW: Record<string, string> = { a: 'ab', b: 'ab', c: 'c' }+ const visibilityGroupKey = (key: string): string => GROUP_BY_ROW[key]++ it('keeps the whole group visible when one of its rows is isolated', () => {+ const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true, visibilityGroupKey }))++ act(() => result.current.legendProps.onItemClick!('a', PLAIN))+ expect(result.current.legendProps.hiddenKeys).toEqual(['c'])+ })++ it('restores every series when the isolated group is clicked again', () => {+ const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true, visibilityGroupKey }))++ act(() => result.current.legendProps.onItemClick!('a', PLAIN))+ act(() => result.current.legendProps.onItemClick!('a', PLAIN))+ expect(result.current.legendProps.hiddenKeys).toEqual([])+ })++ it('hides every row of a group when a row outside it is isolated', () => {+ const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true, visibilityGroupKey }))++ act(() => result.current.legendProps.onItemClick!('c', PLAIN))+ expect(result.current.legendProps.hiddenKeys).toEqual(['a', 'b'])+ })++ it('reads the isolated group as the only visible one', () => {+ const seen: Record<string, LegendItemControls> = {}+ const renderItem = (node: ReactNode, item: LegendItem, controls: LegendItemControls): ReactNode => {+ seen[item.key] = controls+ return node+ }+ const { result } = renderHook(() =>+ useChartLegend(SERIES, THEME, { show: true, visibilityGroupKey, defaultHiddenKeys: ['c'], renderItem })+ )++ result.current.legendProps.items.forEach((item) => result.current.legendProps.renderItem!(null, item))++ expect([seen.a.isOnlyVisible, seen.b.isOnlyVisible, seen.c.isOnlyVisible]).toEqual([true, true, false])+ })++ it('falls back to toggling when every row is in one group', () => {+ const { result } = renderHook(() =>+ useChartLegend(SERIES, THEME, { show: true, visibilityGroupKey: () => 'only' })+ )++ act(() => result.current.legendProps.onItemClick!('a', PLAIN))+ expect(result.current.legendProps.hiddenKeys).toEqual(['a'])+ })+ })++ it('reports the whole next hidden set through onSetHiddenSeries when controlled', () => {+ const onSetHiddenSeries = jest.fn()+ const { result } = renderHook(() =>+ useChartLegend(SERIES, THEME, { show: true, hiddenKeys: [], onSetHiddenSeries })+ )++ act(() => result.current.legendProps.onItemClick!('b', PLAIN))+ expect(onSetHiddenSeries).toHaveBeenCalledWith(['a', 'c'])+ // Controlled: nothing moves until the parent feeds the new keys back in.+ expect(result.current.legendProps.hiddenKeys).toEqual([])+ })++ it('degrades a controlled legend without onSetHiddenSeries to plain toggling', () => {+ const onToggleSeries = jest.fn()+ const { result } = renderHook(() =>+ useChartLegend(SERIES, THEME, { show: true, hiddenKeys: [], onToggleSeries })+ )++ act(() => result.current.legendProps.onItemClick!('b', PLAIN))+ expect(onToggleSeries).toHaveBeenCalledWith('b', true)+ })+it('honors defaultHiddenKeys for the initial uncontrolled state', () => {const { result } = renderHook(() =>useChartLegend(SERIES, THEME, {@@ -86,12 +240,12 @@ describe('useChartLegend', () => {)expect(result.current.legendProps.hiddenKeys).toEqual(['a'])- act(() => result.current.legendProps.onItemClick!('a'))+ act(() => result.current.legendProps.onItemClick!('a', ADDITIVE))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'))+ act(() => result.current.legendProps.onItemClick!('b', ADDITIVE))expect(onToggleSeries).toHaveBeenCalledWith('b', true)})diff --git a/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts b/packages/quill/packages/charts/src/components/Legend/useChartLegend.tsindex 2c5b719f45c6..42c6f3218888 100644--- a/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts+++ b/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts@@ -1,7 +1,7 @@import { useCallback, useMemo, useState, type ReactNode } from 'react'import type { ChartLegendConfig, ChartTheme, Series } from '../../core/types'-import type { LegendItem } from './Legend'+import type { LegendItem, LegendItemClickModifiers } from './Legend'import { legendItemsFromSeries } from './legendItemsFromSeries'/** Mark each `hiddenKeys` series as `visibility.excluded` so the chart drops it from rendering,@@ -14,6 +14,29 @@ export function applyHiddenSeries<Meta>(series: Series<Meta>[], hiddenKeys: Readreturn series.map((s) => (hiddenKeys.has(s.key) ? { ...s, visibility: { ...s.visibility, excluded: true } } : s))}+/** One legend row's visibility state plus the actions that can change it, handed to+ * {@link ChartLegendConfig.renderItem} so a consumer's row menu doesn't re-derive any of it. The+ * actions run the same paths as clicking (`isolate`) and ⌘/Ctrl-clicking (`toggle`) the row. */+export interface LegendItemControls {+ /** This row's series is toggled off. */+ isHidden: boolean+ /** This row's group is the only visible one — i.e. it is currently isolated. */+ isOnlyVisible: boolean+ /** No row is toggled off. */+ areAllVisible: boolean+ /** Whether isolating does anything: it needs more than one visibility group, an interactive+ * legend, and — when the legend is controlled — an `onSetHiddenSeries` to write through. When+ * false, a plain click falls back to toggling this one series. */+ canIsolate: boolean+ /** Add or remove just this series, as a ⌘/Ctrl-click does. */+ toggle: () => void+ /** Show only this series — or show all of them when this one is already the only visible one.+ * What a plain click does. */+ isolate: () => void+ /** Hide every series, or show all when any is hidden. */+ toggleAll: () => void+}+/** Props to spread onto `<ChartLegend>` (everything except `children` and `legendDataAttr`). */export interface ChartLegendRenderProps {show: boolean@@ -21,7 +44,7 @@ export interface ChartLegendRenderProps {position: NonNullable<ChartLegendConfig['position']>align: ChartLegendConfig['align']gap: ChartLegendConfig['gap']- onItemClick?: (key: string) => void+ onItemClick?: (key: string, modifiers: LegendItemClickModifiers) => voidhiddenKeys: string[]renderItem?: (defaultNode: ReactNode, item: LegendItem) => ReactNode}@@ -65,6 +88,85 @@ export function useChartLegend<Meta>(const interactive = config?.interactive ?? true+ // The rows the user can see, which is what "all" and "the others" mean to them — narrower than+ // `series`, which also carries derived overlays (CI bands, trend lines) that get no legend row.+ const rowKeys = useMemo(() => derivedItems.map((item) => item.key), [derivedItems])++ // "The others" is a question about visibility, not about rows, and a consumer can store one+ // visibility bit for several rows (see `visibilityGroupKey`). Resolve every row to its group+ // once so isolating, `canIsolate`, and `isOnlyVisible` all agree on what a distinct series is.+ const visibilityGroupKey = config?.visibilityGroupKey+ const groupByRow = useMemo(() => {+ const groups = new Map<string, string>()+ rowKeys.forEach((key) => groups.set(key, visibilityGroupKey?.(key) ?? key))+ return groups+ }, [rowKeys, visibilityGroupKey])+ const groupCount = useMemo(() => new Set(groupByRow.values()).size, [groupByRow])++ // Isolating and hiding-all replace the whole hidden set in one go, so a controlled legend needs+ // `onSetHiddenSeries`: the per-series `onToggleSeries` can't express it as a single update.+ const onSetHiddenSeries = config?.onSetHiddenSeries+ const setHidden = useCallback(+ (next: string[]) => {+ onSetHiddenSeries?.(next)+ if (controlledKeys === undefined) {+ setInternalKeys(next)+ }+ },+ [controlledKeys, onSetHiddenSeries]+ )++ const canSetBulk = controlledKeys === undefined || onSetHiddenSeries !== undefined+ const canIsolate = interactive && canSetBulk && groupCount > 1++ const isolate = useCallback(+ (key: string) => {+ const group = groupByRow.get(key)+ const others = rowKeys.filter((k) => groupByRow.get(k) !== group)+ const alreadyIsolated = others.length > 0 && !hiddenSet.has(key) && others.every((k) => hiddenSet.has(k))+ setHidden(alreadyIsolated ? [] : others)+ },+ [rowKeys, groupByRow, hiddenSet, setHidden]+ )++ const toggleAll = useCallback(() => {+ const allVisible = rowKeys.every((k) => !hiddenSet.has(k))+ setHidden(allVisible ? [...rowKeys] : [])+ }, [rowKeys, hiddenSet, setHidden])++ // Grafana's legend model: a plain click isolates (and clicking the isolated row restores all),+ // ⌘/Ctrl-click builds a selection one series at a time. Picking one series out of twenty is the+ // common case, and it costs one click here instead of nineteen.+ const handleItemClick = useCallback(+ (key: string, { additive }: LegendItemClickModifiers) => {+ if (additive || !canIsolate) {+ toggle(key)+ return+ }+ isolate(key)+ },+ [canIsolate, toggle, isolate]+ )++ const consumerRenderItem = config?.renderItem+ const renderItem = useMemo(() => {+ if (!consumerRenderItem) {+ return undefined+ }+ const visibleRows = rowKeys.filter((k) => !hiddenSet.has(k))+ const visibleGroups = new Set(visibleRows.map((k) => groupByRow.get(k)))+ return (defaultNode: ReactNode, item: LegendItem): ReactNode =>+ consumerRenderItem(defaultNode, item, {+ isHidden: hiddenSet.has(item.key),+ isOnlyVisible: groupCount > 1 && visibleGroups.size === 1 && !hiddenSet.has(item.key),+ areAllVisible: visibleRows.length === rowKeys.length,+ canIsolate,+ toggle: () => toggle(item.key),+ isolate: () => isolate(item.key),+ toggleAll,+ })+ }, [consumerRenderItem, rowKeys, groupByRow, groupCount, hiddenSet, canIsolate, toggle, isolate, toggleAll])+return {visibleSeries,legendProps: {@@ -73,9 +175,9 @@ export function useChartLegend<Meta>(position: config?.position ?? 'bottom',align: config?.align,gap: config?.gap,- onItemClick: interactive ? toggle : undefined,+ onItemClick: interactive ? handleItemClick : undefined,hiddenKeys,- renderItem: config?.renderItem,+ renderItem,},}}diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex 0086473629d6..1c89f3d62c5f 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -1,6 +1,7 @@import type { ReactNode } from 'react'import type { LegendItem } from '../components/Legend/Legend'+import type { LegendItemControls } from '../components/Legend/useChartLegend'/** Visual theme colours consumed by chart rendering. */export interface ChartTheme {@@ -317,9 +318,11 @@ export interface YAxis {}/** 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. */+ * when interactive, owns the toggled-off state. A plain click isolates the clicked series — every+ * other row is hidden (no draw, no scale contribution, no tooltip) and the axes rescale into the+ * freed space — and clicking the isolated row again restores all; ⌘/Ctrl-click (or Shift-click)+ * toggles one series in or out. Pass `hiddenKeys` + `onToggleSeries` to control the state+ * yourself instead, and `onSetHiddenSeries` alongside them to keep isolating. */export interface ChartLegendConfig {/** Render the legend. Default false. */show?: boolean@@ -329,21 +332,36 @@ export interface ChartLegendConfig {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. */+ /** Legend rows respond to clicks — isolate, or toggle with ⌘/Ctrl. 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. */+ /** Controlled hidden-series keys. Provide together with `onToggleSeries` to own the state, plus+ * `onSetHiddenSeries` for the bulk actions — without it a controlled legend can't isolate and a+ * plain click falls back to toggling. Omit all three for chart-managed (uncontrolled) state. */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- /** Wrap each rendered legend row — receives the default row node and its item, returns the- * node to render. Lets consumers augment rows (e.g. a right-click context menu) while keeping- * the default swatch/label/toggle rendering. Return `defaultNode` to leave a row untouched. */- renderItem?: (defaultNode: ReactNode, item: LegendItem) => ReactNode+ /** Called with the whole next hidden set when a bulk action runs — a plain click isolating a+ * series, or a row menu's isolate / hide-all. A controlled legend must handle this for those+ * actions to work at all; `onToggleSeries` fires one key at a time and can't express them as a+ * single update. Uncontrolled legends update their own state and don't need it. */+ onSetHiddenSeries?: (hiddenKeys: string[]) => void+ /** Groups legend rows that a consumer stores one visibility bit for, so the chart counts them as+ * one series: isolating keeps the whole group visible, "only this one is visible" is judged per+ * group, and a legend with one group has nothing to isolate. A chart comparing two periods needs+ * this when a series' current and previous rows share one stored bit. `hiddenKeys` stays in row+ * space either way — this only answers which rows are the same series, never where the consumer+ * keeps the state. Defaults to the row's own key. */+ visibilityGroupKey?: (rowKey: string) => string+ /** Wrap each rendered legend row — receives the default row node, its item, and that row's+ * {@link LegendItemControls} (visibility state plus toggle/isolate/hide-all actions), and+ * returns the node to render. Lets consumers augment rows (e.g. a right-click context menu)+ * while keeping the default swatch/label/toggle rendering. Return `defaultNode` to leave a row+ * untouched. */+ renderItem?: (defaultNode: ReactNode, item: LegendItem, controls: LegendItemControls) => ReactNode}export interface TooltipConfig {diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.tsindex 63896303bbbb..8971af9122a9 100644--- a/packages/quill/packages/charts/src/index.ts+++ b/packages/quill/packages/charts/src/index.ts@@ -201,9 +201,13 @@ export { ciRanges, linearRegression, movingAverage, trendLine } from './utils/st// Generic UI primitives (no canvas) — composed alongside charts by adaptersexport { Legend } from './components/Legend/Legend'-export type { LegendItem, LegendProps } from './components/Legend/Legend'+export type { LegendItem, LegendItemClickModifiers, 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'+export type {+ ChartLegendRenderProps,+ ChartLegendState,+ LegendItemControls,+} from './components/Legend/useChartLegend'