: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(insights): quill in-chart legend for pie charts and exports (#71892)
Sam Penningtonaa4dd5cd7b4e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d1dfd928fd01..76f56a7b389c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -856,6 +856,10 @@ snapshots:hash: v1.k794b7964.8722c8fbf0ae21aaf5859792fd9d3290f7cb9d6b8454ef49efc40e9b70ea38a2.Itph8hW6UZ9BLa-NSu1QZwMufjgt5RrolGGoXBMUxgocomponents-hogcharts-piechart--with-breakdown-labels--light:hash: v1.k794b7964.bf784228da762a8863cac34da1233ba75792c32d7e11d42cbea859ebd1480367.RWfmnGln-i1Gxp-y0amq8goeKI5sEQxvWr0R10YyJHQ+ components-hogcharts-piechart--with-legend--dark:+ hash: v1.k794b7964.9fb9de3ef6ea3c41afefb2ef1f48bd8ea996498fd3178094becab4a8a99e6b53.7StTlix5q6M4Ywy06Z6zUB14yt-gXrgyo2qGEqyejBg+ components-hogcharts-piechart--with-legend--light:+ hash: v1.k794b7964.8bb46927c74f00a5579e78a238a28ae3b1c47017dd4d058c0ed3d46d66e95218.oR1c60kYOX2Uvf1l-aT1TcDUTpqAbQNFuJtRRPTQljIcomponents-hogcharts-referenceline--fill-sides--dark:hash: v1.k794b7964.acab36e04b2a92190ca4add4f71d9e99abcbac5f7a0dd296fabeb6e762e377fc.jQyBm-m9DF4DfHq2RGkaoyHq0v1J5Q_46M7kIcWv6Lgcomponents-hogcharts-referenceline--fill-sides--light:@@ -2281,9 +2285,9 @@ snapshots:exporter-trends--trends-pie-insight-detailed--light:hash: v1.k794b7964.95dcd4785917ad0e1f258f30d82e481656398599a75ed040623dc11fae0d0598.E4VYQa1Di0mNwKY2uMTaBDnXwFMmtGg5fRntgafPZcAexporter-trends--trends-pie-insight-legend--dark:- hash: v1.k794b7964.db9a3388825ec030c3da484a38d3e2faf57d279626dbccec83546cc3e16d9e06.3xhuY7XkY5k7zICENHWIbcauBzu6ngjQ0YgbiTw_HPE+ hash: v1.k794b7964.8d38d0a77274613f2b304d64ea0bb3ddabf44924304fa734ed152316ba00b8d4.FguklZx16pOjDtTI_lADxcKAAwD5gViligIlak9hhnIexporter-trends--trends-pie-insight-legend--light:- hash: v1.k794b7964.d57e08bf35b41c38b736d8712cf2cf68b70139cfe4f013e2f9103fc6d7729ac6.Oz3bw73AWu5BJ27LeGKzEktsAVp1d_NwxseczUx9FwM+ hash: v1.k794b7964.2eee29146a4cd703a88df5986742cf2bfe804374e9b46e04f3a065acb3bb0d8f.vDNDFJu83-A5zpZF5hhUW1uHl36Hd18AwHbnNLrLnOAexporter-trends--trends-table-insight--dark:hash: v1.k794b7964.92191f5d6ed09bce9843b2168a0ae277493e522cfb6bd52fd7a5b91397d91fa5.2VnfYOZnlJzHQtD34o5Rws-OY7mm8onFWP_ZIfiPj-8exporter-trends--trends-table-insight--light:diff --git a/frontend/src/exporter/ExportedInsight/ExportedInsight.test.tsx b/frontend/src/exporter/ExportedInsight/ExportedInsight.test.tsxnew file mode 100644index 000000000000..f77920ef6b6a--- /dev/null+++ b/frontend/src/exporter/ExportedInsight/ExportedInsight.test.tsx@@ -0,0 +1,61 @@+import { MOCK_DATA_COLOR_THEMES } from 'lib/api.mock'++import '@testing-library/jest-dom'++import { cleanup, waitFor } from '@testing-library/react'++import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'++import { renderWithInsights } from '~/test/insight-testing'+import { InsightModel } from '~/types'++import __trendsLineMulti from '../../mocks/fixtures/api/projects/team_id/insights/trendsLineMulti.json'+import { ExportedInsight } from './ExportedInsight'++let cleanupJsdom: () => void+let cleanupRaf: () => void++beforeEach(() => {+ cleanupJsdom = setupJsdom()+ cleanupRaf = setupSyncRaf()+})++afterEach(() => {+ cleanupRaf()+ cleanupJsdom()+ cleanup()+})++describe('ExportedInsight', () => {+ function renderExported(legend: boolean): { container: HTMLElement } {+ return renderWithInsights({+ component: (+ <ExportedInsight+ insight={__trendsLineMulti as unknown as InsightModel}+ themes={MOCK_DATA_COLOR_THEMES}+ exportOptions={{ legend }}+ />+ ),+ })+ }++ it('lets the chart draw the quill in-chart legend when the legend export option is on', async () => {+ const { container } = renderExported(true)++ await waitFor(() => {+ expect(container.querySelector('[data-attr="hog-chart-timeseries-line-legend"]')).toBeInTheDocument()+ })+ // Exactly one legend: the legacy horizontal legend below the chart must not render too.+ expect(container.querySelector('.InsightLegendMenu')).not.toBeInTheDocument()+ })++ it('renders no legend at all when the legend export option is off', async () => {+ const { container } = renderExported(false)++ await waitFor(() => {+ expect(container.querySelector('canvas[aria-label]')).toBeInTheDocument()+ })+ expect(container.querySelector('[data-attr="hog-chart-timeseries-line-legend"]')).not.toBeInTheDocument()+ expect(container.querySelector('.InsightLegendMenu')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/exporter/ExportedInsight/ExportedInsight.tsx b/frontend/src/exporter/ExportedInsight/ExportedInsight.tsxindex 1d1e9ccee657..a3792e3ba2d5 100644--- a/frontend/src/exporter/ExportedInsight/ExportedInsight.tsx+++ b/frontend/src/exporter/ExportedInsight/ExportedInsight.tsx@@ -13,6 +13,7 @@ import {import { SINGLE_SERIES_DISPLAY_TYPES } from 'lib/constants'import { dataThemeLogic } from 'scenes/dataThemeLogic'import { insightLogic } from 'scenes/insights/insightLogic'+import { DISPLAYS_WITH_IN_CHART_LEGEND } from 'scenes/insights/insightVizDataLogic'import { BoxPlotLegend } from 'scenes/insights/views/BoxPlot/BoxPlotLegend'import { InsightsTable } from 'scenes/insights/views/InsightsTable/InsightsTable'@@ -34,16 +35,9 @@ export function ExportedInsight({useMountedLogic(dataThemeLogic({ themes }))const insight = getQueryBasedInsightModel(legacyInsight)-- if (- isInsightVizNode(insight.query) &&- isTrendsQuery(insight.query.source) &&- insight.query.source.trendsFilter &&- insight.query.source.trendsFilter.showLegend == true- ) {- // legend is always shown so don't show it alongside the insight- insight.query.source.trendsFilter.showLegend = false- }+ // getQueryBasedInsightModel returns the caller's query object by reference — clone it so the+ // export-only tweaks below (legend settings, table editing controls) can't leak into a shared model.+ insight.query = insight.query ? structuredClone(insight.query) : insight.queryif (isDataTableNode(insight.query)) {// don't show editing controls when exporting/sharing@@ -72,6 +66,25 @@ export function ExportedInsight({!SINGLE_SERIES_DISPLAY_TYPES.includes(trendsDisplay as ChartDisplayType) &&!DISPLAY_TYPES_WITHOUT_LEGEND.includes(trendsDisplay as ChartDisplayType)+ // Displays covered by the quill in-chart legend draw the legend inside the chart itself.+ const usesQuillInChartLegend =+ !trendsDisplay || DISPLAYS_WITH_IN_CHART_LEGEND.includes(trendsDisplay as ChartDisplayType)++ if (isInsightVizNode(insight.query) && isTrendsQuery(insight.query.source)) {+ if (usesQuillInChartLegend) {+ // The export `legend` option decides whether the chart shows its in-chart quill legend,+ // pinned to the bottom to match the legacy exported layout (legend below the chart).+ insight.query.source.trendsFilter = {+ ...insight.query.source.trendsFilter,+ showLegend: !!showLegend,+ legendPosition: 'bottom',+ }+ } else if (insight.query.source.trendsFilter?.showLegend) {+ // legend is rendered separately below so don't show it alongside the insight too+ insight.query.source.trendsFilter.showLegend = false+ }+ }+const showDetailedResultsTable =detailedResults &&isInsightVizNode(query) &&@@ -115,7 +128,7 @@ export function ExportedInsight({embeddedinSharedMode/>- {showLegend && (+ {showLegend && !usesQuillInChartLegend && (<div className="p-4">{isBoxPlot ? <BoxPlotLegend horizontal /> : <InsightLegend horizontal readOnly />}</div>diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsxindex ceb76e5b4cc6..4a508b87e54a 100644--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx@@ -187,8 +187,9 @@ describe('InsightDisplayConfig', () => {displayItems: ['Show values on series','Show as % of total',- 'Show legend','Show total below chart',+ // In-chart legend toggle + position select ("Bottom" is the prospective default)+ 'Show legendBottom',],},],@@ -378,6 +379,7 @@ describe('InsightDisplayConfig', () => {it.each([['trends bar', () => makeTrendsQuery(ChartDisplayType.ActionsBar)],['trends unstacked bar', () => makeTrendsQuery(ChartDisplayType.ActionsUnstackedBar)],+ ['trends pie', () => makeTrendsQuery(ChartDisplayType.ActionsPie)],['stickiness line', () => makeStickinessQuery(ChartDisplayType.ActionsLineGraph)],['stickiness bar', () => makeStickinessQuery(ChartDisplayType.ActionsBar)],['lifecycle', () => makeLifecycleQuery()],diff --git a/frontend/src/queries/nodes/InsightViz/InsightViz.scss b/frontend/src/queries/nodes/InsightViz/InsightViz.scssindex f90d4bad9465..af4a16222ec7 100644--- a/frontend/src/queries/nodes/InsightViz/InsightViz.scss+++ b/frontend/src/queries/nodes/InsightViz/InsightViz.scss@@ -245,6 +245,23 @@}}+// In the exporter the trends wrapper is `.InsightCard__viz` (embedded), which is flex-sized with no+// definite height — so a bottom in-chart legend's `max-height: 40%` cap can't resolve and the plot+// stretches the card taller and taller. Pin a viewport height on the displays that draw the in-chart+// legend so the exported chart stays a bounded, page-filling card (mirrors `.TrendsInsight`'s explicit+// height in the app). Table/world map/number/metric are excluded — they size to content or are their+// own card. `8rem` leaves room for the export header and padding above the chart.+.ExportedInsight {+ .InsightCard__viz--ActionsLineGraph,+ .InsightCard__viz--ActionsLineGraphCumulative,+ .InsightCard__viz--ActionsAreaGraph,+ .InsightCard__viz--ActionsBar,+ .InsightCard__viz--ActionsUnstackedBar,+ .InsightCard__viz--ActionsPie {+ height: calc(100vh - 8rem);+ }+}+// Drop the viz padding so the Metric sparkline can bleed to the card edges..InsightVizDisplay__content:has(.Metric) {padding: 0;diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsxindex 87b1388952fd..ad2645c51a8c 100644--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx@@ -323,8 +323,8 @@ export function InsightVizDisplay({})()// A chart that draws its own legend inside the plot opts out of the side-legend column, so we- // don't render two legends. The slope graph always does; trends/stickiness/lifecycle charts do- // when the quill in-chart legend is on (`usesInChartLegend`).+ // don't render two legends. The slope graph always does; trends/stickiness/lifecycle charts+ // (including pie) do when the quill in-chart legend is on (`usesInChartLegend`).const chartDrawsOwnLegend = display === ChartDisplayType.SlopeGraph || usesInChartLegendconst showSideLegend = supportsDisplay && showLegend && !chartDrawsOwnLegenddiff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.tsindex 9accb2dd6472..19ddb6aede69 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts@@ -150,14 +150,15 @@ import type { AnyPropertyFilter, GroupTypeIndex, PropertyGroupFilter } from '../const SHOW_TIMEOUT_MESSAGE_AFTER = 5000-// Trends/stickiness displays whose chart renders the in-chart quill legend (line/area/cumulative-// and bar layouts). Lifecycle always renders it regardless of display.-const DISPLAYS_WITH_IN_CHART_LEGEND = [+// Trends/stickiness displays whose chart renders the in-chart quill legend (line/area/cumulative,+// bar layouts, and pie). Lifecycle always renders it regardless of display.+export const DISPLAYS_WITH_IN_CHART_LEGEND = [ChartDisplayType.ActionsLineGraph,ChartDisplayType.ActionsLineGraphCumulative,ChartDisplayType.ActionsAreaGraph,ChartDisplayType.ActionsBar,ChartDisplayType.ActionsUnstackedBar,+ ChartDisplayType.ActionsPie,]export type QuerySourceUpdate = Omit<Partial<InsightQueryNode>, 'kind'>diff --git a/frontend/src/scenes/trends/Trends.tsx b/frontend/src/scenes/trends/Trends.tsxindex c64f412227e5..fb117ddcd140 100644--- a/frontend/src/scenes/trends/Trends.tsx+++ b/frontend/src/scenes/trends/Trends.tsx@@ -165,7 +165,13 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode }return (<>{series && (- <div className={embedded ? 'InsightCard__viz' : `TrendsInsight TrendsInsight--${display}`}>+ <div+ className={+ embedded+ ? `InsightCard__viz InsightCard__viz--${display}`+ : `TrendsInsight TrendsInsight--${display}`+ }+ ><Suspensefallback={<WrappingLoadingSkeleton fullWidth>diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex ee05666483a2..e334846bcf21 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -4,21 +4,21 @@ Quick-reference for AI agents using `@posthog/quill-charts`. Canvas-rendered cha## Choosing a chart-| Chart | Use when |-| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| LineChart | Categorical x-axis trends; area fills, fill-between (confidence ribbons) |-| BarChart | Categorical comparisons — `barLayout: 'stacked' \| 'grouped' \| 'percent'`, `axisOrientation: 'horizontal'` for horizontal bars; end-cap rounding via top-level `barCornerRadius` (the same key across the time-series/combo configs) |-| FunnelChart | Funnel steps as grouped vertical bars over a hatched drop-off track — one band per step, one bar per variant, valued as percent-of-first-step (0–100) |-| ComboChart | Mixed bar/line/area series on one band x-axis — set `Series.type`; vertical-only, `barLayout: 'stacked' \| 'grouped' \| 'percent'` (percent stacks bar series to 100%; a line/area series needs its own `yAxisId: 'right'` axis — one sharing the bars' axis can't plot raw values against their [0,1] scale) |-| TimeSeriesLineChart | Time-indexed labels (ISO strings) with timezone/interval-aware x-axis |-| TimeSeriesBarChart | Same x-axis handling, bar rendering; supports per-series `yAxisId` axes |-| TimeSeriesComboChart | Mixed bar + line/area on a time x-axis — `ComboChart` plus the time-series chrome (date x-axis, goal lines, legend, value labels) |-| PieChart | Part-of-whole, one value per series; `innerRadiusRatio` for donut + `centerLabel`; on-slice labels via `showLabelOnSlice`/`showValueOnSlice`, positioned with `labelRadiusRatio` (0=center, 1=rim) and gated by `minSlicePercentForLabel` |-| BoxPlot | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label |-| Heatmap | 2D density grid (e.g. latency over time) — `xLabels` × `yLabels` (row 0 at the bottom), `cells[row][col]` counts → color intensity on one accent (log ramp by default, `colorScale: 'linear'` to opt out); single-cell tooltip resolved from the cursor, `onCellClick` reports `{ xIndex, yIndex, value }` |-| Sparkline | Tiny inline trend, no axes — a gradient-filled line (default) or stacked bars via `type: 'bar'`; a flat `number[]` + `color`, or full `series` for multi-series; tooltip off by default, opt in with a `tooltip` render prop |-| MetricCard | Headline number + sparkline + change pill (dashboard stat tiles) |-| SlopeChart | Change between two points (slopegraph) — one line per series, left "before" → right "after"; `data: [start, end]` |+| Chart | Use when |+| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| LineChart | Categorical x-axis trends; area fills, fill-between (confidence ribbons) |+| BarChart | Categorical comparisons — `barLayout: 'stacked' \| 'grouped' \| 'percent'`, `axisOrientation: 'horizontal'` for horizontal bars; end-cap rounding via top-level `barCornerRadius` (the same key across the time-series/combo configs) |+| FunnelChart | Funnel steps as grouped vertical bars over a hatched drop-off track — one band per step, one bar per variant, valued as percent-of-first-step (0–100) |+| ComboChart | Mixed bar/line/area series on one band x-axis — set `Series.type`; vertical-only, `barLayout: 'stacked' \| 'grouped' \| 'percent'` (percent stacks bar series to 100%; a line/area series needs its own `yAxisId: 'right'` axis — one sharing the bars' axis can't plot raw values against their [0,1] scale) |+| TimeSeriesLineChart | Time-indexed labels (ISO strings) with timezone/interval-aware x-axis |+| TimeSeriesBarChart | Same x-axis handling, bar rendering; supports per-series `yAxisId` axes |+| TimeSeriesComboChart | Mixed bar + line/area on a time x-axis — `ComboChart` plus the time-series chrome (date x-axis, goal lines, legend, value labels) |+| PieChart | Part-of-whole, one value per series; `innerRadiusRatio` for donut + `centerLabel`; on-slice labels via `showLabelOnSlice`/`showValueOnSlice`, positioned with `labelRadiusRatio` (0=center, 1=rim) and gated by `minSlicePercentForLabel`; `config.legend` for the built-in legend (a toggled-off slice is removed and the rest rescale to the full circle) |+| BoxPlot | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label |+| Heatmap | 2D density grid (e.g. latency over time) — `xLabels` × `yLabels` (row 0 at the bottom), `cells[row][col]` counts → color intensity on one accent (log ramp by default, `colorScale: 'linear'` to opt out); single-cell tooltip resolved from the cursor, `onCellClick` reports `{ xIndex, yIndex, value }` |+| Sparkline | Tiny inline trend, no axes — a gradient-filled line (default) or stacked bars via `type: 'bar'`; a flat `number[]` + `color`, or full `series` for multi-series; tooltip off by default, opt in with a `tooltip` render prop |+| MetricCard | Headline number + sparkline + change pill (dashboard stat tiles) |+| SlopeChart | Change between two points (slopegraph) — one line per series, left "before" → right "after"; `data: [start, end]` |## Theme wiring@@ -78,7 +78,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).- `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`) 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.+- 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.- `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/charts/PieChart/PieChart.stories.tsx b/packages/quill/packages/charts/src/charts/PieChart/PieChart.stories.tsxindex 77e00699bbc0..ebf04e8300b5 100644--- a/packages/quill/packages/charts/src/charts/PieChart/PieChart.stories.tsx+++ b/packages/quill/packages/charts/src/charts/PieChart/PieChart.stories.tsx@@ -58,6 +58,18 @@ export const Donut: Story = {},}+export const WithLegend: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const config: PieChartConfig = { legend: { show: true, position: 'right' } }+ return (+ <Stage>+ <PieChart series={BROWSERS} theme={theme} config={config} />+ </Stage>+ )+ },+}+export const Percent: Story = {render: () => {const theme = useReactiveTheme()diff --git a/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx b/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsxindex f224706bea52..ec6634012714 100644--- a/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx@@ -164,6 +164,42 @@ describe('PieChart', () => {})})+ describe('interactive legend', () => {+ function legendButtons(container: HTMLElement): HTMLButtonElement[] {+ return Array.from(+ container.querySelectorAll<HTMLButtonElement>('[data-attr="hog-chart-pie-legend"] button')+ )+ }++ it('renders no legend by default', () => {+ const { container } = renderHogChart(<PieChart series={SERIES} theme={THEME} />)+ expect(container.querySelector('[data-attr="hog-chart-pie-legend"]')).toBeNull()+ })++ it('removes a slice on legend click and restores it on a second click', () => {+ const { container } = renderHogChart(+ <PieChart series={SERIES} theme={THEME} config={{ legend: { show: true } }} />+ )+ expect(legendButtons(container).map((b) => b.textContent)).toEqual(['Chrome', 'Firefox'])+ expect(container.querySelector('canvas[aria-label]')?.getAttribute('aria-label')).toBe(+ 'Pie chart with 2 slices'+ )++ fireEvent.click(legendButtons(container)[1])+ 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.+ const dimmed = legendButtons(container).filter((b) => b.className.includes('opacity-40'))+ expect(dimmed.map((b) => b.textContent)).toEqual(['Firefox'])++ fireEvent.click(legendButtons(container)[1])+ expect(container.querySelector('canvas[aria-label]')?.getAttribute('aria-label')).toBe(+ 'Pie chart with 2 slices'+ )+ })+ })+describe('error boundary', () => {it('reports render errors through onError', async () => {const onError = jest.fn()diff --git a/packages/quill/packages/charts/src/charts/PieChart/PieChart.tsx b/packages/quill/packages/charts/src/charts/PieChart/PieChart.tsxindex 65b5e6accdf9..65f0094be7be 100644--- a/packages/quill/packages/charts/src/charts/PieChart/PieChart.tsx+++ b/packages/quill/packages/charts/src/charts/PieChart/PieChart.tsx@@ -1,12 +1,21 @@import React, { useCallback, useMemo, useRef } from 'react'+import { ChartLegend } from '../../components/Legend/ChartLegend'+import { useChartLegend } from '../../components/Legend/useChartLegend'import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'import { mixColors } from '../../core/color-utils'import type { RadialSlicePayload } from '../../core/hooks/useRadialInteraction'import { useRadialLayout } from '../../core/radial-context'import { RadialChart } from '../../core/RadialChart'import type { RadialLayoutBuilder } from '../../core/RadialChart'-import type { ChartDrawArgs, ChartTheme, ResolvedSeries, Series, TooltipContext } from '../../core/types'+import type {+ ChartDrawArgs,+ ChartLegendConfig,+ ChartTheme,+ ResolvedSeries,+ Series,+ TooltipContext,+} from '../../core/types'import { computePieLayout } from './computePieLayout'import type { PieLayout } from './computePieLayout'import { PieTooltip } from './PieTooltip'@@ -46,6 +55,9 @@ export interface PieChartConfig<Meta = unknown> {tooltip?: {enabled?: boolean}+ /** Built-in legend, one row per slice. Hidden by default; toggling a row off removes the+ * slice and the rest rescale to the full circle. Same semantics as the other charts. */+ legend?: ChartLegendConfig}export interface PieChartProps<Meta = unknown> {@@ -143,10 +155,13 @@ function PieChartInner<Meta = unknown>({sort = null,sliceValue,tooltip: tooltipConfig,+ legend,} = config ?? {}const showTooltip = tooltipConfig?.enabled !== false+ const { visibleSeries, legendProps } = useChartLegend(series, theme, legend)+const buildLayout = useCallback<RadialLayoutBuilder<Meta>>((resolvedSeries, dimensions) =>computePieLayout<Meta>({@@ -226,31 +241,33 @@ function PieChartInner<Meta = unknown>({)return (- <RadialChart<Meta>- series={series}- theme={theme}- buildLayout={buildLayout}- drawStatic={drawStatic}- drawHover={drawHover}- tooltip={renderTooltip}- showTooltip={showTooltip}- onSliceClick={onSliceClick}- hitOuterSlack={effectiveHoverGrowth}- hoverAnimationMs={effectiveHoverAnimationMs}- className={className}- dataAttr={dataAttr}- >- <SliceLabels- valueFormatter={valueFormatter}- showValueOnSlice={showValueOnSlice}- showLabelOnSlice={showLabelOnSlice}- minSlicePercentForLabel={minSlicePercentForLabel}- labelRadiusRatio={labelRadiusRatio}- isPercent={isPercent}- />- <PieCenterLabel>{centerLabel}</PieCenterLabel>- {children}- </RadialChart>+ <ChartLegend {...legendProps} legendDataAttr="hog-chart-pie-legend">+ <RadialChart<Meta>+ series={visibleSeries}+ theme={theme}+ buildLayout={buildLayout}+ drawStatic={drawStatic}+ drawHover={drawHover}+ tooltip={renderTooltip}+ showTooltip={showTooltip}+ onSliceClick={onSliceClick}+ hitOuterSlack={effectiveHoverGrowth}+ hoverAnimationMs={effectiveHoverAnimationMs}+ className={className}+ dataAttr={dataAttr}+ >+ <SliceLabels+ valueFormatter={valueFormatter}+ showValueOnSlice={showValueOnSlice}+ showLabelOnSlice={showLabelOnSlice}+ minSlicePercentForLabel={minSlicePercentForLabel}+ labelRadiusRatio={labelRadiusRatio}+ isPercent={isPercent}+ />+ <PieCenterLabel>{centerLabel}</PieCenterLabel>+ {children}+ </RadialChart>+ </ChartLegend>)}diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsxindex d019b29c8095..267be9979bec 100644--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx@@ -5,7 +5,7 @@ import { cleanup, screen, waitFor } from '@testing-library/react'import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'import { NodeKind } from '~/queries/schema/schema-general'-import { buildTrendsQuery, personsModal, renderInsight } from '~/test/insight-testing'+import { buildTrendsQuery, legend, personsModal, renderInsight } from '~/test/insight-testing'import { ChartDisplayType } from '~/types'let cleanupJsdom: () => void@@ -63,4 +63,49 @@ describe('TrendsPieChart (ActionsPie)', () => {)expect([...sliceLabels()].sort()).toEqual([...expectedLabels].sort())})++ describe('quill in-chart legend', () => {+ const getInChartLegend = (container: HTMLElement): HTMLElement | null =>+ container.querySelector<HTMLElement>('[data-attr="hog-chart-pie-legend"]')++ it('renders the in-chart legend and suppresses the legacy side legend', async () => {+ const { container } = renderInsight({ query: pieByHedgehog({ showLegend: true }) })+ await screen.findByLabelText(/pie chart with/i, undefined, { timeout: 5000 })++ const legendEl = getInChartLegend(container)+ expect(legendEl).not.toBeNull()+ expect(legendEl!.textContent).toContain('Spike')+ expect(container.querySelector('.InsightLegendMenu')).not.toBeInTheDocument()+ })++ it('humanizes built-in event names in the legend (no breakdown)', async () => {+ const { container } = renderInsight({+ query: buildTrendsQuery({+ series: [{ kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' }],+ trendsFilter: { display: ChartDisplayType.ActionsPie, showLegend: true },+ }),+ })+ await screen.findByLabelText(/pie chart with/i, undefined, { timeout: 5000 })++ const legendEl = getInChartLegend(container)+ expect(legendEl).not.toBeNull()+ expect(legendEl!.textContent).toContain('Pageview')+ expect(legendEl!.textContent).not.toContain('$pageview')+ })++ it('removes a toggled-off slice but keeps it listed (dimmed) so it can be restored', async () => {+ const { container } = renderInsight({ query: pieByHedgehog({ showLegend: true }) })+ await screen.findByLabelText(/pie chart with 5 slices/i, undefined, { timeout: 5000 })++ await legend.toggle('Spike')++ await waitFor(() => {+ expect(screen.getByLabelText(/pie chart with 4 slices/i)).toBeInTheDocument()+ })+ const dimmed = [...getInChartLegend(container)!.querySelectorAll<HTMLElement>('button')].filter((b) =>+ b.className.includes('opacity-40')+ )+ expect(dimmed.map((b) => b.textContent)).toEqual(['Spike'])+ })+ })})diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsxindex 4db4fc9e9d5e..c94dfddf1692 100644--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx@@ -1,3 +1,4 @@+import clsx from 'clsx'import { useValues } from 'kea'import posthog from 'posthog-js'import { useCallback, useMemo, type ErrorInfo } from 'react'@@ -13,7 +14,6 @@ import {import { InsightEmptyState } from 'scenes/insights/EmptyStates'import { insightLogic } from 'scenes/insights/insightLogic'import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'-import { formatBreakdownLabel } from 'scenes/insights/utils'import { teamLogic } from 'scenes/teamLogic'import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'@@ -27,7 +27,9 @@ import { InsightVizNode } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'import { InsightSeriesTooltip } from '../../shared/InsightSeriesTooltip'+import { getTrendsSeriesDisplayLabel } from '../shared/getTrendsSeriesDisplayLabel'import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'+import { useInsightsLegendConfig } from '../shared/useInsightsLegendConfig'import { buildTrendsPieSeries } from './trendsPieTransforms'interface TrendsPieChartProps {@@ -43,10 +45,15 @@ const handleChartError = (error: Error, info: ErrorInfo): void => {})}-export function TrendsPieChart({ context, showPersonsModal = true }: TrendsPieChartProps): JSX.Element | null {+export function TrendsPieChart({+ context,+ inSharedMode,+ showPersonsModal = true,+}: TrendsPieChartProps): JSX.Element | null {const theme = useChartTheme()const { insightProps } = useValues(insightLogic)+ const legendConfig = useInsightsLegendConfig({ insightProps, inSharedMode })const { baseCurrency } = useValues(teamLogic)const { allCohorts } = useValues(cohortsModel)const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)@@ -82,16 +89,15 @@ export function TrendsPieChart({ context, showPersonsModal = true }: TrendsPieChconst onDataPointClick = context?.onDataPointClickconst showAggregation = !pieChartVizOptions?.hideAggregation+ // Share the line/bar label resolver so the legend humanizes event names ($pageview → Pageview)+ // and honors series renames, instead of showing the raw event key.const getLabel = useCallback((r: IndexedTrendResult): string =>- breakdownFilter- ? formatBreakdownLabel(- r.breakdown_value,- breakdownFilter,- allCohorts.results,- formatPropertyValueForDisplay- )- : (r.label ?? ''),+ getTrendsSeriesDisplayLabel(r, {+ breakdownFilter,+ cohorts: allCohorts.results,+ formatPropertyValueForDisplay,+ }),[breakdownFilter, allCohorts.results, formatPropertyValueForDisplay])@@ -99,10 +105,12 @@ export function TrendsPieChart({ context, showPersonsModal = true }: TrendsPieCh() =>buildTrendsPieSeries(indexedResults ?? [], {getColor: getTrendsColor,- getHidden: getTrendsHidden,+ // Hidden series are listed (dimmed) and excluded via config.legend.hiddenKeys instead+ // of being dropped here, so the legend can restore them.+ getHidden: undefined,getLabel,}),- [indexedResults, getTrendsColor, getTrendsHidden, getLabel]+ [indexedResults, getTrendsColor, getLabel])const visibleResults = useMemo(@@ -126,8 +134,15 @@ export function TrendsPieChart({ context, showPersonsModal = true }: TrendsPieChshowLabelOnSlice: !!showLabelOnSeries,isPercent: isPercentStackView,disableHoverOffset: !!pieChartVizOptions?.disableHoverOffset,+ legend: legendConfig,}),- [showValuesOnSeries, showLabelOnSeries, isPercentStackView, pieChartVizOptions?.disableHoverOffset]+ [+ showValuesOnSeries,+ showLabelOnSeries,+ isPercentStackView,+ pieChartVizOptions?.disableHoverOffset,+ legendConfig,+ ])// ActionsPie disables clicks entirely when the insight has data-warehouse series (see@@ -226,7 +241,9 @@ export function TrendsPieChart({ context, showPersonsModal = true }: TrendsPieCh])- if (!visibleResults.length) {+ // An all-hidden pie must keep rendering the legend (dimmed rows) so the hidden slices can be+ // restored — only a truly empty result set gets the empty state.+ if (!(indexedResults ?? []).length) {return (<InsightEmptyStateheading={context?.emptyStateHeading}@@ -236,23 +253,33 @@ export function TrendsPieChart({ context, showPersonsModal = true }: TrendsPieCh)}+ // A bottom legend (exports/shared images) hugs the bottom of the chart box. If the box fills a+ // tall card the round pie centers in it, stranding the legend far below the pie and up against+ // the total. Bound the box to a square around the pie so the legend sits right under it, and+ // center the whole group. In-app (right legend) the chart keeps filling the column.+ const legendAtBottom = !!legendConfig.show && legendConfig.position === 'bottom'++ const pie = (+ <PieChart<TrendsSeriesMeta>+ series={series}+ theme={theme}+ config={pieConfig}+ tooltip={renderTooltip}+ onSliceClick={canHandleClick ? onSliceClick : undefined}+ valueFormatter={valueFormatter}+ dataAttr="trend-pie-graph"+ onError={handleChartError}+ />+ )+return (// `flex-1 min-h-0` (not `h-full`) so the chart fills the flex column even when the// parent only sets `min-height`/`flex` — a percentage height would collapse to 0,// leaving `PieChart` with `outerRadius <= 0` and no slices. Mirrors the bar/line charts.- <div className="flex flex-col w-full flex-1 min-h-0">- <PieChart<TrendsSeriesMeta>- series={series}- theme={theme}- config={pieConfig}- tooltip={renderTooltip}- onSliceClick={canHandleClick ? onSliceClick : undefined}- valueFormatter={valueFormatter}- dataAttr="trend-pie-graph"- onError={handleChartError}- />+ <div className={clsx('flex flex-col w-full flex-1 min-h-0', legendAtBottom && 'justify-center')}>+ {legendAtBottom ? <div className="flex flex-col w-full min-h-0 max-h-full aspect-square">{pie}</div> : pie}{showAggregation && (- <div className="text-7xl text-center font-bold m-0">+ <div className={clsx('text-7xl text-center font-bold m-0', legendAtBottom && 'mt-6')}>{formatAggregationAxisValue(trendsFilter, total, baseCurrency)}</div>)}