: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
fix(insights): toggle chart legend series on tap on touch devices (#89081)
Sam Pennington861b97a2b7f2
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 14e33f1bc553..cc377af56ab9 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -91,7 +91,7 @@ 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, 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.+- 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. On a coarse pointer (touch screen) there is no ⌘/Ctrl/Shift, so a plain tap toggles instead of isolating, letting taps build any subset the way the checkbox legend table does (isolate stays reachable through the row menu). `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`.diff --git a/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx b/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsxindex 2ab7ce55c22a..d7afb95654bf 100644--- a/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx+++ b/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx@@ -117,6 +117,22 @@ describe('useChartLegend', () => {expect(result.current.legendProps.hiddenKeys).toEqual([])})+ it('toggles instead of isolating on a coarse pointer, where the additive gesture is unreachable', () => {+ const original = window.matchMedia+ window.matchMedia = jest.fn().mockImplementation((query: string) => ({+ matches: query === '(pointer: coarse)',+ })) as unknown as typeof window.matchMedia+ try {+ 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(['b', 'c'])+ } finally {+ window.matchMedia = original+ }+ })+it('adds to an isolated selection on an additive click without dropping it', () => {const { result } = renderHook(() => useChartLegend(SERIES, THEME, { show: true }))diff --git a/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts b/packages/quill/packages/charts/src/components/Legend/useChartLegend.tsindex 42c6f3218888..ac8306a0bf73 100644--- a/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts+++ b/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts@@ -4,6 +4,17 @@ import type { ChartLegendConfig, ChartTheme, Series } from '../../core/types'import type { LegendItem, LegendItemClickModifiers } from './Legend'import { legendItemsFromSeries } from './legendItemsFromSeries'+/** True when the primary pointer is coarse (a touch screen), read live at click time. Guarded like+ * `prefersReducedMotion` because `matchMedia` is absent in jsdom test workers and other non-browser+ * hosts, where a bare access would throw mid-render. Missing support reads as a fine pointer. */+function isCoarsePointer(): boolean {+ return (+ typeof window !== 'undefined' &&+ typeof window.matchMedia === 'function' &&+ window.matchMedia('(pointer: coarse)').matches+ )+}+/** 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. */@@ -137,9 +148,12 @@ export function useChartLegend<Meta>(// 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.+ // A touch screen has no ⌘/Ctrl/Shift, so the additive gesture is unreachable and isolate-on-tap+ // would strand the user on one series with no way to add a second. Tap toggles there instead, so+ // taps build any subset the way the checkbox legend table does. Isolate stays on the row menu.const handleItemClick = useCallback((key: string, { additive }: LegendItemClickModifiers) => {- if (additive || !canIsolate) {+ if (additive || !canIsolate || isCoarsePointer()) {toggle(key)return}