: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): render trends line legend in-chart via quill (#64639)
Sam Penningtonbea538a064a4
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c9bb8066ddc8..9b33cbbec862 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -588,10 +588,26 @@ snapshots:hash: v1.k794b7964.586cbc343561fe2ea416c4e8a15661d80f0dc0e6602c4c4505fb763a960e3fec.wnr2iqA9493GIdPtZgO3pqa1uiD9pZcM3L01W8_FZ-Qcomponents-hogcharts-defaulttooltip--total-excludes-overlay--light:hash: v1.k794b7964.cf566924008a871da770d7d0a0b7a2ac6748823639d3d60ca60344770f581a2a.7s92rB7AHoeq-uQd_tSJGFVCn3cU-LQeOQVJ2qyvLWo- components-hogcharts-legend--built-in-toggle--dark:- hash: v1.k794b7964.a44913b0e0cdf88b5d0d8960560fa4ce5a663f0b187cdcc5a723d1bb9b653fc6.pxcAORXTtyj4dK4h_9PUe9keV7tagKmaBvwS56KoeXI- components-hogcharts-legend--built-in-toggle--light:- hash: v1.k794b7964.dc8065b867dd309ca1c05935745e283b13d2fd7ebb7ddde80c9b5e8c24ee6cec.BzRyo-huuWL4HvNyXrykyXbCBuFTjeQKpECqODhn7AE+ components-hogcharts-legend--built-in-toggle-bottom--dark:+ hash: v1.k794b7964.a44913b0e0cdf88b5d0d8960560fa4ce5a663f0b187cdcc5a723d1bb9b653fc6.UksdQY23gh9zRrpzKMZvncH2EPYvXRVmC-_Uw9thCVY+ components-hogcharts-legend--built-in-toggle-bottom--light:+ hash: v1.k794b7964.dc8065b867dd309ca1c05935745e283b13d2fd7ebb7ddde80c9b5e8c24ee6cec.ClUoy56bHSDjNbDKl4gvk44LkC0RDQubZjS-kYkWsqo+ components-hogcharts-legend--built-in-toggle-left--dark:+ hash: v1.k794b7964.940d5343cb791764132973fe75d4643867612b490a05de0471154a27e1b70c87.7lo0qDOzQ_wG3eVp2Uu0HTOtR0dgaW0Ux-cCo8ae3pI+ components-hogcharts-legend--built-in-toggle-left--light:+ hash: v1.k794b7964.ba087b577f6ea3d9c113b8dab106a60e36af54609cf231ba73c2a4cad98b7925.8OaKUsuLXSK35PfyX0ftUMbKex3CjfepcPo_XhNQmG4+ components-hogcharts-legend--built-in-toggle-render-item--dark:+ hash: v1.k794b7964.5784ffd6dd3a0ed90d08b5657b91e40c39cdc023f1ac46ac43c2873b15b1cb26.a2QF9RGbobFD-dROwyEmtVHKN1QKWoE07Y1hlBKhIBU+ components-hogcharts-legend--built-in-toggle-render-item--light:+ hash: v1.k794b7964.c4c9efe186859eb6ded290545379f1abac92025bcbad98ae1217b23e0739d558.ZhlvMvfqXZLTg8y3VZV5nVSL1_ZYqYzxos1RhxfWT_o+ components-hogcharts-legend--built-in-toggle-right--dark:+ hash: v1.k794b7964.a2ff6fd5f9b3e268aad6da1c9b29d0cbc875da4db68658d4a1dc268f771efc22.tGBD8Q_321bUnlGoBoD3yb5o6x0PDh6iD9MQ3C92wlI+ components-hogcharts-legend--built-in-toggle-right--light:+ hash: v1.k794b7964.39c3abaa97521c612ecdc00fe7899bd3b6627fb856f0084d66da6a84894e9ed8.jqj0nRnNOYGjx0etBQ99ipKInhelJ6yxK2uO7gtthuk+ components-hogcharts-legend--built-in-toggle-top--dark:+ hash: v1.k794b7964.20d8a26ebcc186deed6a7b0d81853f68e1d33c3a6f7d3f91260cd9c7d040da25.xzQMN1RWIvqiBOyerFDCZ2fsKfMsIs5VZhg4PVryFS4+ components-hogcharts-legend--built-in-toggle-top--light:+ hash: v1.k794b7964.4757cdd97063190f0a41e9c11047e1497238ac337c2dd7b9f31ae4bf72d3cac1.JgRnzqTouBMjKm6jTI2cXtiU8F48PPmetq2arxl_Cvwcomponents-hogcharts-legend--horizontal--dark:hash: v1.k794b7964.748c8221979ca1984c3ef06b0a2d5016e683810a2530a2b7549ff2994484d32d.WlgOW_onzflesCUfetduXiySjbl4uF8oTLxdKf4xYsocomponents-hogcharts-legend--horizontal--light:@@ -6371,7 +6387,7 @@ snapshots:scenes-app-settings-project--settings-project-replay--dark:hash: v1.k794b7964.ba60bfbf98de5592216589808ad521f77a07d52ec4a2eed451ddfb83be74e3ce.dar84_LEwqHpOsgERR81YBLmbO611_mtZkkY0Pe23qYscenes-app-settings-project--settings-project-replay--light:- hash: v1.k794b7964.c9478fa31ea024f0f01038d33f41d359ad02c809d0a2eb3868e382c39f7dc91f.ZtIw0iZbRRa0-Q7jRSLBfSr8h220b0TcGA8bqRIAT-g+ hash: v1.k794b7964.366ec670cf6546bf1a1b3bc7b80248a428165b8deefbd5e8c4853928c169eae9.CVkkawDcnb3CGaczLMAoxrBZMECrScRqIWOwSC9JcFAscenes-app-settings-project--settings-project-surveys--dark:hash: v1.k794b7964.9de7aa543fc7e1921df96fc61c58ee45edcab684082c3b030a7fab17ca7d8188.KTsEcD3ill1gnaBMK9ftFDSVWv5qvgfy-fyMhjSPX0Iscenes-app-settings-project--settings-project-surveys--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex d7f8426d9f2c..8aea66ba3d2c 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -432,6 +432,7 @@ export const FEATURE_FLAGS = {PRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analyticsINSIGHT_ADD_TO_DASHBOARD_AAB: 'insight-add-to-dashboard-aab', // owner: @pauldambra #team-product-analytics multivariate=control,control_2,testPRODUCT_ANALYTICS_PATHS_V2: 'paths-v2', // owner: @thmsobrmlr #team-product-analytics+ PRODUCT_ANALYTICS_QUILL_LEGEND: 'product-analytics-quill-legend', // owner: #team-product-analytics, gates the in-chart quill legend replacing the legacy side InsightLegendPRODUCT_ANALYTICS_QUILL_SQL_CHARTS: 'product-analytics-quill-sql-charts', // owner: #team-data-tools, gates rendering DataVisualization line/area charts via @posthog/quill-chartsPRODUCT_ANALYTICS_RETENTION_AGGREGATION: 'retention-aggregation', // owner: @anirudhpillai #team-product-analyticsPRODUCT_ANALYTICS_RETENTION_DWH: 'retention-dwh', // owner: @thmsobrmlr #team-product-analyticsdiff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsxindex 763cfcb93132..facaa9c4492a 100644--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx@@ -5,7 +5,9 @@ import { LemonButton } from '@posthog/lemon-ui'import { ExportButton } from 'lib/components/ExportButton/ExportButton'import { InsightLegend } from 'lib/components/InsightLegend/InsightLegend'+import { FEATURE_FLAGS } from 'lib/constants'import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'import { Funnel } from 'scenes/funnels/Funnel'import { FunnelCanvasLabel } from 'scenes/funnels/FunnelCanvasLabel'@@ -131,6 +133,7 @@ export function InsightVizDisplay({useValues(insightLogic)const { activeView } = useValues(insightNavLogic(insightProps))+ const { featureFlags } = useValues(featureFlagLogic)const {isFunnels,@@ -279,8 +282,18 @@ export function InsightVizDisplay({return null})()- // The slope graph draws its own legend inside the chart, so it opts out of the side-legend column.- const showSideLegend = supportsDisplay && showLegend && display !== ChartDisplayType.SlopeGraph+ // 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 line/area/cumulative do when the+ // quill in-chart legend is on (an unset display is the line chart, matching Trends.tsx's renderer).+ const isQuillLegendTrendsChart =+ !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND] &&+ activeView === InsightType.TRENDS &&+ (!display ||+ display === ChartDisplayType.ActionsLineGraph ||+ display === ChartDisplayType.ActionsLineGraphCumulative ||+ display === ChartDisplayType.ActionsAreaGraph)+ const chartDrawsOwnLegend = display === ChartDisplayType.SlopeGraph || isQuillLegendTrendsChart+ const showSideLegend = supportsDisplay && showLegend && !chartDrawsOwnLegendfunction renderActiveView(): JSX.Element | null {switch (activeView) {diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 86dd44f07188..0855da47cdae 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -69,7 +69,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `showTotal`, `totalLabel`, `totalFormatter`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) from the sum and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. A formatter taking only `value` stays compatible — the extra arg is ignored.- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original.-- Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `SlopeChart`) takes a `config.legend: ChartLegendConfig` (`{ show, position, align, gap, interactive, hiddenKeys, defaultHiddenKeys, onToggleSeries }`). With `show: true` the chart renders a built-in legend that, by default (`interactive`), is click-to-toggle: clicking a row hides that series (no draw, no scale contribution, no tooltip — the axes rescale into the freed space) while the row stays listed but dimmed so it can be restored. The chart owns the toggled-off state (uncontrolled); set `interactive: false` for a static legend, or pass `hiddenKeys` + `onToggleSeries` to control it yourself. Hidden by default. Toggling on time-series charts lists the user's series only (not derived trend lines / CI bands) — and hiding a series also hides everything derived from it (its CI band, moving average, and trend line), so no orphaned overlay floats over the gap.+- 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.- `Legend` (and `ChartLegend` for layout) is the lower-level presentational primitive: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. Use it directly when the built-in `config.legend` can't express what you need (custom item order/labels). `useChartLegend(series, theme, config, items?)` is the shared hook the charts use — returns `visibleSeries` (hidden applied as `visibility.excluded`) plus `legendProps` to spread onto `<ChartLegend>`; `applyHiddenSeries` is the underlying helper. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change).- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order) and formats values with `valueFormatter` so they match the on-chart labels' units; pass your own `tooltip` to override. (`DefaultTooltip` itself takes an optional `valueFormatter` for the same reason — without it values fall back to `toLocaleString`.) Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.- `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`. `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).diff --git a/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsx b/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsxindex cc9f26dfefe6..4ca097d0143e 100644--- a/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsx+++ b/packages/quill/packages/charts/src/components/Legend/ChartLegend.tsx@@ -13,6 +13,8 @@ export interface ChartLegendProps {onItemClick?: (key: string) => voidhiddenKeys?: string[]className?: string+ /** Wrap each legend row — forwarded to {@link Legend}'s `renderItem`. */+ renderItem?: (defaultNode: React.ReactNode, item: LegendItem) => React.ReactNode/** data-attr on the inner `<Legend>`. The outer layout wrapper has no data-attr. */legendDataAttr?: stringchildren: React.ReactNode@@ -27,6 +29,7 @@ export function ChartLegend({onItemClick,hiddenKeys,className,+ renderItem,legendDataAttr,children,}: ChartLegendProps): React.ReactElement {@@ -45,6 +48,7 @@ export function ChartLegend({align={align}onItemClick={onItemClick}hiddenKeys={hiddenKeys}+ renderItem={renderItem}dataAttr={legendDataAttr}/>}diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsxindex 986c10e2f267..7167c0751386 100644--- a/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsx+++ b/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsx@@ -1,5 +1,5 @@import { Meta, StoryObj } from '@storybook/react'-import { useMemo, useState } from 'react'+import { useMemo, useState, type ReactNode } from 'react'import { DAYS, SERIES } from '../../charts/time-series-fixtures'import { TimeSeriesBarChart } from '../../charts/TimeSeriesBarChart/TimeSeriesBarChart'@@ -108,9 +108,16 @@ export const LegendHidden: Story = {render: () => <ChartLegendStory show={false} position="top" />,}-// The chart owns the toggle state — `config.legend.show` is all that's needed; clicking a row-// hides that series (dimmed in the legend) and the axes rescale into the freed space.-function BuiltInToggleStory(): JSX.Element {+// The chart owns the toggle state — `config.legend` is all that's needed; clicking a row hides+// that series (dimmed in the legend) and the axes rescale into the freed space. These stories+// snapshot the built-in legend at each position around the chart, not the legend in isolation.+function BuiltInToggleStory({+ position,+ renderItem,+}: {+ position: 'top' | 'bottom' | 'left' | 'right'+ renderItem?: (node: ReactNode, item: LegendItem) => ReactNode+}): JSX.Element {const theme = useReactiveTheme()return (<Stage width={520} height={320}>@@ -120,11 +127,25 @@ function BuiltInToggleStory(): JSX.Element {theme={theme}config={{yAxis: { showGrid: true },- legend: { show: true, position: 'bottom' },+ legend: { show: true, position, renderItem },}}/></Stage>)}-export const BuiltInToggle: Story = { render: () => <BuiltInToggleStory /> }+export const BuiltInToggleTop: Story = { render: () => <BuiltInToggleStory position="top" /> }+export const BuiltInToggleBottom: Story = { render: () => <BuiltInToggleStory position="bottom" /> }+export const BuiltInToggleLeft: Story = { render: () => <BuiltInToggleStory position="left" /> }+export const BuiltInToggleRight: Story = { render: () => <BuiltInToggleStory position="right" /> }++// `renderItem` wraps each row so a consumer can augment it (here a native-title tooltip standing in+// for a right-click context menu) while keeping the default swatch/label/toggle rendering.+export const BuiltInToggleRenderItem: Story = {+ render: () => (+ <BuiltInToggleStory+ position="bottom"+ renderItem={(node, item) => <span title={`Right-click ${item.label} for options`}>{node}</span>}+ />+ ),+}diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.test.tsxindex be005d640aaa..8901e64a6c37 100644--- a/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx+++ b/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx@@ -49,6 +49,21 @@ describe('Legend', () => {expect(onClick).toHaveBeenCalledWith('returning')})+ it('wraps each row via renderItem while preserving the default node', () => {+ const onClick = jest.fn()+ const { container } = render(+ <Legend+ items={ITEMS}+ onItemClick={onClick}+ renderItem={(node, item) => <div data-attr={`wrap-${item.key}`}>{node}</div>}+ />+ )+ 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')+ })+it('dims only rows whose key is in hiddenKeys', () => {const { container } = render(<Legend items={ITEMS} hiddenKeys={['returning']} />)const dimmedLabels = rowsOf(container)diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.tsxindex 037f1060d980..9b3761815bb0 100644--- a/packages/quill/packages/charts/src/components/Legend/Legend.tsx+++ b/packages/quill/packages/charts/src/components/Legend/Legend.tsx@@ -17,6 +17,9 @@ export interface LegendProps {hiddenKeys?: string[]className?: stringdataAttr?: string+ /** Wrap each row — receives the default row node and its item, returns the node to render.+ * Use to augment rows (e.g. a right-click context menu) while keeping the default rendering. */+ renderItem?: (defaultNode: React.ReactNode, item: LegendItem) => React.ReactNode}const ALIGN_CLASS = {@@ -33,6 +36,7 @@ export function Legend({hiddenKeys,className,dataAttr,+ renderItem,}: LegendProps): React.ReactElement | null {if (items.length === 0) {return null@@ -59,9 +63,8 @@ export function Legend({)}</>)- return onItemClick ? (+ const node = onItemClick ? (<button- key={item.key}type="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)}@@ -69,10 +72,9 @@ export function Legend({{inner}</button>) : (- <span key={item.key} className={rowClass}>- {inner}- </span>+ <span className={rowClass}>{inner}</span>)+ return <React.Fragment key={item.key}>{renderItem ? renderItem(node, item) : node}</React.Fragment>})}</div>)diff --git a/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx b/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsxindex 35a7287c2e94..f432e8b1627d 100644--- a/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx+++ b/packages/quill/packages/charts/src/components/Legend/useChartLegend.test.tsx@@ -1,4 +1,5 @@import { act, renderHook } from '@testing-library/react'+import type { ReactNode } from 'react'import type { ChartTheme, Series } from '../../core/types'import { applyHiddenSeries, useChartLegend } from './useChartLegend'@@ -42,6 +43,12 @@ 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('toggles a series off then back on in uncontrolled mode, keeping it in the legend', () => {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 c9dfd937517c..2c5b719f45c6 100644--- a/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts+++ b/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts@@ -1,4 +1,4 @@-import { useCallback, useMemo, useState } from 'react'+import { useCallback, useMemo, useState, type ReactNode } from 'react'import type { ChartLegendConfig, ChartTheme, Series } from '../../core/types'import type { LegendItem } from './Legend'@@ -23,6 +23,7 @@ export interface ChartLegendRenderProps {gap: ChartLegendConfig['gap']onItemClick?: (key: string) => voidhiddenKeys: string[]+ renderItem?: (defaultNode: ReactNode, item: LegendItem) => ReactNode}export interface ChartLegendState<Meta> {@@ -74,6 +75,7 @@ export function useChartLegend<Meta>(gap: config?.gap,onItemClick: interactive ? toggle : undefined,hiddenKeys,+ renderItem: config?.renderItem,},}}diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex 5229d90a2c73..bbf05deae673 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -1,3 +1,7 @@+import type { ReactNode } from 'react'++import type { LegendItem } from '../components/Legend/Legend'+/** Visual theme colours consumed by chart rendering. */export interface ChartTheme {colors: string[]@@ -256,6 +260,10 @@ export interface ChartLegendConfig {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}export interface TooltipConfig {diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsxindex 15f70861aef0..6d4e81b08dcb 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx@@ -4,6 +4,8 @@ import { cleanup, configure, fireEvent, screen, waitFor } from '@testing-libraryimport { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'+import { FEATURE_FLAGS } from 'lib/constants'+import { NodeKind } from '~/queries/schema/schema-general'import {buildTrendsQuery,@@ -808,4 +810,70 @@ describe('TrendsLineChart', () => {expect(personsModal.get()).not.toBeInTheDocument()})})++ describe('quill in-chart legend (PRODUCT_ANALYTICS_QUILL_LEGEND on)', () => {+ const quillLegendFlag = { [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND]: true }+ const twoSeriesQuery = buildTrendsQuery({+ series: [+ { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },+ { kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },+ ],+ trendsFilter: { showLegend: true },+ })++ const getInChartLegend = (container: HTMLElement): HTMLElement =>+ container.querySelector<HTMLElement>('[data-attr="hog-chart-timeseries-line-legend"]')!++ it('renders the in-chart legend and suppresses the legacy side legend', async () => {+ const { container } = renderInsight({ query: twoSeriesQuery, featureFlags: quillLegendFlag })++ await waitFor(() => {+ expect(screen.getByRole('img', { name: /chart with 2 data series/i })).toBeInTheDocument()+ })++ const legendEl = getInChartLegend(container)+ expect(legendEl.textContent).toContain('Napped')+ expect(container.querySelector('.InsightLegendMenu')).not.toBeInTheDocument()+ })++ it('keeps a toggled-off series listed and dimmed in the legend but out of the tooltip', async () => {+ const { container } = renderInsight({ query: twoSeriesQuery, featureFlags: quillLegendFlag })++ await waitFor(() => {+ expect(screen.getByRole('img', { name: /chart with 2 data series/i })).toBeInTheDocument()+ })+ const legendEl = getInChartLegend(container)++ await legend.toggle('Napped')++ // Hidden series stays listed (so it can be restored) but is rendered dimmed.+ const nappedRow = await waitFor(() => {+ const row = [...legendEl.querySelectorAll<HTMLElement>('button')].find((b) =>+ b.textContent?.includes('Napped')+ )+ expect(row?.className).toContain('opacity-40')+ return row+ })+ expect(nappedRow).toBeInTheDocument()++ const tooltip = await chart.hoverTooltip(2)+ expect(tooltip.element.textContent).not.toContain('Napped')+ })++ it('renders a static, non-interactive legend in shared mode', async () => {+ const { container } = renderInsight({+ query: twoSeriesQuery,+ featureFlags: quillLegendFlag,+ inSharedMode: true,+ })++ await waitFor(() => {+ expect(screen.getByRole('img', { name: /chart with 2 data series/i })).toBeInTheDocument()+ })+ const legendEl = getInChartLegend(container)++ expect(legendEl.textContent).toContain('Napped')+ expect(legendEl.querySelector('button')).not.toBeInTheDocument()+ })+ })})diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsxindex 4ec6def86629..7dd5bd93f8c9 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx@@ -28,6 +28,7 @@ import { handleTrendsChartClick } from '../shared/handleTrendsChartClick'import { TrendsAlertOverlays } from '../shared/TrendsAlertOverlays'import { buildTrendsSeriesMeta, resolveGroupTypeLabel, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'import { TrendsTooltip } from '../shared/TrendsTooltip'+import { useTrendsLegendConfig } from '../shared/useTrendsLegendConfig'import { buildTrendsLineTimeSeriesConfig, buildTrendsSeries } from './trendsChartTransforms'interface TrendsLineChartProps {@@ -44,6 +45,9 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChaconst theme = useMemo(() => buildTheme(), [isDarkModeOn])const { insightProps, insight } = useValues(insightLogic)+ const legendConfig = useTrendsLegendConfig({ insightProps, inSharedMode })+ const quillLegendEnabled = !!legendConfig+const {indexedResults,display,@@ -195,7 +199,9 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChaincompletenessOffsetFromEnd,isStickiness,getColor: getTrendsColor,- getHidden: getTrendsHidden,+ // With the quill legend on, hidden series are listed (dimmed) and excluded via+ // config.legend.hiddenKeys instead of being dropped here, so the legend can restore them.+ getHidden: quillLegendEnabled ? undefined : getTrendsHidden,buildMeta: buildTrendsSeriesMeta,}),[@@ -206,6 +212,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChaisStickiness,getTrendsColor,getTrendsHidden,+ quillLegendEnabled,])@@ -235,6 +242,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChavalueLabels: showValuesOnSeries && valueLabelFormatter ? { formatter: valueLabelFormatter } : false,showCrosshair: true,tooltip: TOOLTIP_CONFIG,+ legend: legendConfig,}),[indexedResults,@@ -256,6 +264,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChashowTrendLines,showValuesOnSeries,valueLabelFormatter,+ legendConfig,])diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.tsindex de746ba1ef11..393336ccebed 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts@@ -197,6 +197,7 @@ export interface BuildTrendsLineTimeSeriesConfigOpts<R extends TrendsResultLike>showCrosshair?: booleantooltip?: TooltipConfig+ legend?: TimeSeriesLineChartConfig['legend']}export function buildTrendsLineTimeSeriesConfig<R extends TrendsResultLike>(@@ -236,5 +237,6 @@ export function buildTrendsLineTimeSeriesConfig<R extends TrendsResultLike>(percentStackView: opts.isPercentStackView,showCrosshair: opts.showCrosshair,tooltip: opts.tooltip,+ legend: opts.legend,}}diff --git a/products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart.tsxindex 161b08957f99..61222940d469 100644--- a/products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart.tsx@@ -58,7 +58,7 @@ export function TrendsSlopeChart({ context }: TrendsSlopeChartProps): JSX.Elemen// The chart's own legend carries the series name + first-to-last change, gated on the// insight's "Show legend" toggle, so there's only ever one legend and no in-chart names.showSeriesLabels: false,- legend: { show: !!showLegend, position: 'bottom' },+ legend: { show: !!showLegend },xTickFormatter: createXAxisTickCallback({interval: interval ?? 'day',allDays: currentPeriodResult?.days ?? [],diff --git a/products/product_analytics/frontend/insights/trends/shared/TrendsLegendItemContextMenu.tsx b/products/product_analytics/frontend/insights/trends/shared/TrendsLegendItemContextMenu.tsxnew file mode 100644index 000000000000..0d2aa0a3a3d1--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/shared/TrendsLegendItemContextMenu.tsx@@ -0,0 +1,63 @@+import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'+import type { ReactNode } from 'react'++import { InsightLegendRowContextMenu } from 'lib/components/InsightLegend/InsightLegendRowContextMenu'+import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'+import type { IndexedTrendResult } from 'scenes/trends/types'++import { InsightLogicProps } from '~/types'++interface TrendsLegendItemContextMenuProps {+ insightProps: InsightLogicProps+ item: IndexedTrendResult+ children: ReactNode+}++/** Right-click isolate/show-all/hide-all menu for a quill legend row, mirroring the legacy+ * InsightLegendRow menu — shares trendsDataLogic's toggle actions so hidden state stays in+ * the query (resultCustomizations). */+export function TrendsLegendItemContextMenu({+ insightProps,+ item,+ children,+}: TrendsLegendItemContextMenuProps): JSX.Element {+ const {+ getTrendsHidden,+ indexedResults,+ areAllSeriesVisible,+ showLegendIsolateSeriesItem,+ getIsOnlyVisibleSeriesInLegend,+ } = useValues(trendsDataLogic(insightProps))+ const { toggleOtherSeriesHidden, toggleAllResultsHidden } = useActions(trendsDataLogic(insightProps))++ const isHidden = getTrendsHidden(item)+ const isOnlyThisVisible = getIsOnlyVisibleSeriesInLegend(item)++ return (+ <InsightLegendRowContextMenu+ areAllSeriesVisible={areAllSeriesVisible}+ showLegendIsolateSeriesItem={showLegendIsolateSeriesItem}+ isHidden={isHidden}+ isOnlyThisVisible={isOnlyThisVisible}+ onToggleOtherSeries={() => {+ posthog.capture('insight_legend_context_menu', {+ action: isOnlyThisVisible ? 'show_all_series' : 'hide_other_series',+ source: 'isolate_row',+ series_count: indexedResults.length,+ })+ toggleOtherSeriesHidden(item)+ }}+ onToggleAllSeries={() => {+ posthog.capture('insight_legend_context_menu', {+ action: areAllSeriesVisible ? 'hide_all_series' : 'show_all_series',+ source: 'toggle_all_row',+ series_count: indexedResults.length,+ })+ toggleAllResultsHidden(indexedResults, areAllSeriesVisible)+ }}+ >+ {children}+ </InsightLegendRowContextMenu>+ )+}diff --git a/products/product_analytics/frontend/insights/trends/shared/useTrendsLegendConfig.tsx b/products/product_analytics/frontend/insights/trends/shared/useTrendsLegendConfig.tsxnew file mode 100644index 000000000000..c49dcbfa4ce7--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/shared/useTrendsLegendConfig.tsx@@ -0,0 +1,86 @@+import { useActions, useValues } from 'kea'+import { useMemo, type ReactNode } from 'react'++import type { ChartLegendConfig, LegendItem } from '@posthog/quill-charts'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { insightLogic } from 'scenes/insights/insightLogic'+import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'+import type { IndexedTrendResult } from 'scenes/trends/types'++import { InsightLogicProps } from '~/types'++import { TrendsLegendItemContextMenu } from './TrendsLegendItemContextMenu'++interface UseTrendsLegendConfigOptions {+ insightProps: InsightLogicProps+ inSharedMode?: boolean+}++/** Builds the quill in-chart legend config shared by the trends-family charts (line/area/cumulative,+ * and bar next). Wires toggle persistence + the isolate/show-all context menu through trendsDataLogic+ * so every trends chart renders one consistent legend. Returns `undefined` when the quill-legend flag+ * is off, so callers fall back to the legacy side legend and skip pre-stripping hidden series. */+export function useTrendsLegendConfig({+ insightProps,+ inSharedMode = false,+}: UseTrendsLegendConfigOptions): ChartLegendConfig | undefined {+ const { featureFlags } = useValues(featureFlagLogic)+ const quillLegendEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND]+ const { canEditInsight } = useValues(insightLogic)+ const { indexedResults, getTrendsHidden, showLegend, legendSeriesIsolationMenuEligible } = useValues(+ trendsDataLogic(insightProps)+ )+ const { toggleResultHidden } = useActions(trendsDataLogic(insightProps))++ const resultById = useMemo(() => {+ const m = new Map<string, IndexedTrendResult>()+ ;(indexedResults ?? []).forEach((r) => m.set(String(r.id), r))+ return m+ }, [indexedResults])++ const legendInteractive = canEditInsight && !inSharedMode++ return useMemo<ChartLegendConfig | undefined>(() => {+ if (!quillLegendEnabled) {+ return undefined+ }+ const hiddenKeys = (indexedResults ?? []).filter((r) => getTrendsHidden(r)).map((r) => String(r.id))+ const showContextMenu = legendInteractive && legendSeriesIsolationMenuEligible+ return {+ show: !!showLegend,+ interactive: legendInteractive,+ hiddenKeys,+ onToggleSeries: (key: string) => {+ const result = resultById.get(key)+ if (result) {+ toggleResultHidden(result)+ }+ },+ renderItem: showContextMenu+ ? (node: ReactNode, item: LegendItem) => {+ const result = resultById.get(item.key)+ if (!result) {+ return node+ }+ return (+ <TrendsLegendItemContextMenu insightProps={insightProps} item={result}>+ {node}+ </TrendsLegendItemContextMenu>+ )+ }+ : undefined,+ }+ }, [+ quillLegendEnabled,+ indexedResults,+ getTrendsHidden,+ showLegend,+ legendInteractive,+ legendSeriesIsolationMenuEligible,+ resultById,+ toggleResultHidden,+ insightProps,+ ])+}